Debian Codegraph @

internal/config/settings.go

raw
1 package config
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "reflect"
10 "runtime"
11 "strconv"
12 "strings"
13
14 "github.com/micro-editor/json5"
15 "github.com/zyedidia/glob"
16 "github.com/zyedidia/micro/v2/internal/util"
17 "golang.org/x/text/encoding/htmlindex"
18 )
19
20 type optionValidator func(string, any) error
21
22 // a list of settings that need option validators
23 var optionValidators = map[string]optionValidator{
24 "autosave": validateNonNegativeValue,
25 "clipboard": validateChoice,
26 "colorcolumn": validateNonNegativeValue,
27 "colorscheme": validateColorscheme,
28 "detectlimit": validateNonNegativeValue,
29 "encoding": validateEncoding,
30 "fileformat": validateChoice,
31 "helpsplit": validateChoice,
32 "matchbracestyle": validateChoice,
33 "multiopen": validateChoice,
34 "pageoverlap": validateNonNegativeValue,
35 "reload": validateChoice,
36 "scrollmargin": validateNonNegativeValue,
37 "scrollspeed": validateNonNegativeValue,
38 "tabsize": validatePositiveValue,
39 "truecolor": validateChoice,
40 }
41
42 // a list of settings with pre-defined choices
43 var OptionChoices = map[string][]string{
44 "clipboard": {"internal", "external", "terminal"},
45 "fileformat": {"unix", "dos"},
46 "helpsplit": {"hsplit", "vsplit"},
47 "matchbracestyle": {"underline", "highlight"},
48 "multiopen": {"tab", "hsplit", "vsplit"},
49 "reload": {"prompt", "auto", "disabled"},
50 "truecolor": {"auto", "on", "off"},
51 }
52
53 // a list of settings that can be globally and locally modified and their
54 // default values
55 var defaultCommonSettings = map[string]any{
56 "autoindent": true,
57 "autosu": false,
58 "backup": true,
59 "backupdir": "",
60 "basename": false,
61 "colorcolumn": float64(0),
62 "cursorline": true,
63 "detectlimit": float64(100),
64 "diffgutter": false,
65 "encoding": "utf-8",
66 "eofnewline": true,
67 "fastdirty": false,
68 "fileformat": defaultFileFormat(),
69 "filetype": "unknown",
70 "hlsearch": false,
71 "hltaberrors": false,
72 "hltrailingws": false,
73 "ignorecase": true,
74 "incsearch": true,
75 "indentchar": " ", // Deprecated
76 "keepautoindent": false,
77 "matchbrace": true,
78 "matchbraceleft": true,
79 "matchbracestyle": "underline",
80 "mkparents": false,
81 "pageoverlap": float64(2),
82 "permbackup": false,
83 "readonly": false,
84 "relativeruler": false,
85 "reload": "prompt",
86 "rmtrailingws": false,
87 "ruler": true,
88 "savecursor": false,
89 "saveundo": false,
90 "scrollbar": false,
91 "scrollmargin": float64(3),
92 "scrollspeed": float64(2),
93 "showchars": "",
94 "smartpaste": true,
95 "softwrap": false,
96 "splitbottom": true,
97 "splitright": true,
98 "statusformatl": "$(filename) $(modified)$(overwrite)($(line),$(col)) $(status.paste)| ft:$(opt:filetype) | $(opt:fileformat) | $(opt:encoding)",
99 "statusformatr": "$(bind:ToggleKeyMenu): bindings, $(bind:ToggleHelp): help",
100 "statusline": true,
101 "syntax": true,
102 "tabmovement": false,
103 "tabsize": float64(4),
104 "tabstospaces": false,
105 "truecolor": "auto",
106 "useprimary": true,
107 "wordwrap": false,
108 }
109
110 // a list of settings that should only be globally modified and their
111 // default values
112 var DefaultGlobalOnlySettings = map[string]any{
113 "autosave": float64(0),
114 "clipboard": "external",
115 "colorscheme": "default",
116 "divchars": "|-",
117 "divreverse": true,
118 "fakecursor": false,
119 "helpsplit": "hsplit",
120 "infobar": true,
121 "keymenu": false,
122 "lockbindings": false,
123 "mouse": true,
124 "multiopen": "tab",
125 "parsecursor": false,
126 "paste": false,
127 "pluginchannels": []string{"https://raw.githubusercontent.com/micro-editor/plugin-channel/master/channel.json"},
128 "pluginrepos": []string{},
129 "savehistory": true,
130 "scrollbarchar": "|",
131 "sucmd": "sudo",
132 "tabhighlight": false,
133 "tabreverse": true,
134 "xterm": false,
135 }
136
137 // a list of settings that should never be globally modified
138 var LocalSettings = []string{
139 "filetype",
140 "readonly",
141 }
142
143 var (
144 ErrInvalidOption = errors.New("Invalid option")
145 ErrInvalidValue = errors.New("Invalid value")
146 ErrOptNotToggleable = errors.New("Option not toggleable")
147
148 // The options that the user can set
149 GlobalSettings map[string]any
150
151 // This is the raw parsed json
152 parsedSettings map[string]any
153 settingsParseError bool
154
155 // ModifiedSettings is a map of settings which should be written to disk
156 // because they have been modified by the user in this session
157 ModifiedSettings map[string]bool
158
159 // VolatileSettings is a map of settings which should not be written to disk
160 // because they have been temporarily set for this session only
161 VolatileSettings map[string]bool
162 )
163
164 func writeFile(name string, txt []byte) error {
165 return util.SafeWrite(name, txt, false)
166 }
167
168 func init() {
169 ModifiedSettings = make(map[string]bool)
170 VolatileSettings = make(map[string]bool)
171 }
172
173 func validateParsedSettings() error {
174 var err error
175 defaults := DefaultAllSettings()
176 for k, v := range parsedSettings {
177 if strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
178 if strings.HasPrefix(k, "ft:") {
179 for k1, v1 := range v.(map[string]any) {
180 if _, ok := defaults[k1]; ok {
181 if e := verifySetting(k1, v1, defaults[k1]); e != nil {
182 err = e
183 parsedSettings[k].(map[string]any)[k1] = defaults[k1]
184 continue
185 }
186 }
187 }
188 } else {
189 if _, e := glob.Compile(k); e != nil {
190 err = errors.New("Error with glob setting " + k + ": " + e.Error())
191 delete(parsedSettings, k)
192 continue
193 }
194 for k1, v1 := range v.(map[string]any) {
195 if _, ok := defaults[k1]; ok {
196 if e := verifySetting(k1, v1, defaults[k1]); e != nil {
197 err = e
198 parsedSettings[k].(map[string]any)[k1] = defaults[k1]
199 continue
200 }
201 }
202 }
203 }
204 continue
205 }
206
207 if k == "autosave" {
208 // if autosave is a boolean convert it to float
209 s, ok := v.(bool)
210 if ok {
211 if s {
212 parsedSettings["autosave"] = 8.0
213 } else {
214 parsedSettings["autosave"] = 0.0
215 }
216 }
217 continue
218 }
219
220 if _, ok := defaults[k]; ok {
221 if e := verifySetting(k, v, defaults[k]); e != nil {
222 err = e
223 parsedSettings[k] = defaults[k]
224 continue
225 }
226 }
227 }
228 return err
229 }
230
231 func ReadSettings() error {
232 parsedSettings = make(map[string]any)
233 filename := filepath.Join(ConfigDir, "settings.json")
234 if _, e := os.Stat(filename); e == nil {
235 input, err := os.ReadFile(filename)
236 if err != nil {
237 settingsParseError = true
238 return errors.New("Error reading settings.json file: " + err.Error())
239 }
240 if !strings.HasPrefix(string(input), "null") {
241 // Unmarshal the input into the parsed map
242 err = json5.Unmarshal(input, &parsedSettings)
243 if err != nil {
244 settingsParseError = true
245 return errors.New("Error reading settings.json: " + err.Error())
246 }
247 err = validateParsedSettings()
248 if err != nil {
249 return err
250 }
251 }
252 }
253 return nil
254 }
255
256 func ParsedSettings() map[string]any {
257 s := make(map[string]any)
258 for k, v := range parsedSettings {
259 s[k] = v
260 }
261 return s
262 }
263
264 func verifySetting(option string, value any, def any) error {
265 var interfaceArr []any
266 valType := reflect.TypeOf(value)
267 defType := reflect.TypeOf(def)
268 assignable := false
269
270 switch option {
271 case "pluginrepos", "pluginchannels":
272 assignable = valType.AssignableTo(reflect.TypeOf(interfaceArr))
273 default:
274 assignable = defType.AssignableTo(valType)
275 }
276 if !assignable {
277 return fmt.Errorf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", option, valType, def, defType)
278 }
279
280 if option == "colorscheme" {
281 // Plugins are not initialized yet, so do not verify if the colorscheme
282 // exists yet, since the colorscheme may be added by a plugin later.
283 return nil
284 }
285
286 if err := OptionIsValid(option, value); err != nil {
287 return err
288 }
289
290 return nil
291 }
292
293 // InitGlobalSettings initializes the options map and sets all options to their default values
294 // Must be called after ReadSettings
295 func InitGlobalSettings() error {
296 var err error
297 GlobalSettings = DefaultAllSettings()
298
299 for k, v := range parsedSettings {
300 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
301 GlobalSettings[k] = v
302 }
303 }
304 return err
305 }
306
307 // UpdatePathGlobLocals scans the already parsed settings and sets the options locally
308 // based on whether the path matches a glob
309 // Must be called after ReadSettings
310 func UpdatePathGlobLocals(settings map[string]any, path string) {
311 for k, v := range parsedSettings {
312 if strings.HasPrefix(reflect.TypeOf(v).String(), "map") && !strings.HasPrefix(k, "ft:") {
313 g, _ := glob.Compile(k)
314 if g.MatchString(path) {
315 for k1, v1 := range v.(map[string]any) {
316 settings[k1] = v1
317 }
318 }
319 }
320 }
321 }
322
323 // UpdateFileTypeLocals scans the already parsed settings and sets the options locally
324 // based on whether the filetype matches to "ft:"
325 // Must be called after ReadSettings
326 func UpdateFileTypeLocals(settings map[string]any, filetype string) {
327 for k, v := range parsedSettings {
328 if strings.HasPrefix(reflect.TypeOf(v).String(), "map") && strings.HasPrefix(k, "ft:") {
329 if filetype == k[3:] {
330 for k1, v1 := range v.(map[string]any) {
331 if k1 != "filetype" {
332 settings[k1] = v1
333 }
334 }
335 }
336 }
337 }
338 }
339
340 // WriteSettings writes the settings to the specified filename as JSON
341 func WriteSettings(filename string) error {
342 if settingsParseError {
343 // Don't write settings if there was a parse error
344 // because this will delete the settings.json if it
345 // is invalid. Instead we should allow the user to fix
346 // it manually.
347 return nil
348 }
349
350 var err error
351 if _, e := os.Stat(ConfigDir); e == nil {
352 defaults := DefaultAllSettings()
353
354 // remove any options froms parsedSettings that have since been marked as default
355 for k, v := range parsedSettings {
356 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
357 cur, okcur := GlobalSettings[k]
358 _, vol := VolatileSettings[k]
359 if def, ok := defaults[k]; ok && okcur && !vol && reflect.DeepEqual(cur, def) {
360 delete(parsedSettings, k)
361 }
362 }
363 }
364
365 // add any options to parsedSettings that have since been marked as non-default
366 for k, v := range GlobalSettings {
367 if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
368 if _, wr := ModifiedSettings[k]; wr {
369 parsedSettings[k] = v
370 }
371 }
372 }
373
374 txt, _ := json.MarshalIndent(parsedSettings, "", " ")
375 txt = append(txt, '\n')
376 err = writeFile(filename, txt)
377 }
378 return err
379 }
380
381 // OverwriteSettings writes the current settings to settings.json and
382 // resets any user configuration of local settings present in settings.json
383 func OverwriteSettings(filename string) error {
384 settings := make(map[string]any)
385
386 var err error
387 if _, e := os.Stat(ConfigDir); e == nil {
388 defaults := DefaultAllSettings()
389 for k, v := range GlobalSettings {
390 if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
391 if _, wr := ModifiedSettings[k]; wr {
392 settings[k] = v
393 }
394 }
395 }
396
397 txt, _ := json.MarshalIndent(parsedSettings, "", " ")
398 txt = append(txt, '\n')
399 err = writeFile(filename, txt)
400 }
401 return err
402 }
403
404 // RegisterCommonOptionPlug creates a new option (called pl.name). This is meant to be called by plugins to add options.
405 func RegisterCommonOptionPlug(pl string, name string, defaultvalue any) error {
406 return RegisterCommonOption(pl+"."+name, defaultvalue)
407 }
408
409 // RegisterGlobalOptionPlug creates a new global-only option (named pl.name)
410 func RegisterGlobalOptionPlug(pl string, name string, defaultvalue any) error {
411 return RegisterGlobalOption(pl+"."+name, defaultvalue)
412 }
413
414 // RegisterCommonOption creates a new option
415 func RegisterCommonOption(name string, defaultvalue any) error {
416 if _, ok := GlobalSettings[name]; !ok {
417 GlobalSettings[name] = defaultvalue
418 }
419 defaultCommonSettings[name] = defaultvalue
420 return nil
421 }
422
423 // RegisterGlobalOption creates a new global-only option
424 func RegisterGlobalOption(name string, defaultvalue any) error {
425 if _, ok := GlobalSettings[name]; !ok {
426 GlobalSettings[name] = defaultvalue
427 }
428 DefaultGlobalOnlySettings[name] = defaultvalue
429 return nil
430 }
431
432 // GetGlobalOption returns the global value of the given option
433 func GetGlobalOption(name string) any {
434 return GlobalSettings[name]
435 }
436
437 func defaultFileFormat() string {
438 if runtime.GOOS == "windows" {
439 return "dos"
440 }
441 return "unix"
442 }
443
444 func GetInfoBarOffset() int {
445 offset := 0
446 if GetGlobalOption("infobar").(bool) {
447 offset++
448 }
449 if GetGlobalOption("keymenu").(bool) {
450 offset += 2
451 }
452 return offset
453 }
454
455 // DefaultCommonSettings returns a map of all common buffer settings
456 // and their default values
457 func DefaultCommonSettings() map[string]any {
458 commonsettings := make(map[string]any)
459 for k, v := range defaultCommonSettings {
460 commonsettings[k] = v
461 }
462 return commonsettings
463 }
464
465 // DefaultAllSettings returns a map of all common buffer & global-only settings
466 // and their default values
467 func DefaultAllSettings() map[string]any {
468 allsettings := make(map[string]any)
469 for k, v := range defaultCommonSettings {
470 allsettings[k] = v
471 }
472 for k, v := range DefaultGlobalOnlySettings {
473 allsettings[k] = v
474 }
475 return allsettings
476 }
477
478 // GetNativeValue parses and validates a value for a given option
479 func GetNativeValue(option, value string) (any, error) {
480 curVal := GetGlobalOption(option)
481 if curVal == nil {
482 return nil, ErrInvalidOption
483 }
484
485 switch kind := reflect.TypeOf(curVal).Kind(); kind {
486 case reflect.Bool:
487 b, err := util.ParseBool(value)
488 if err != nil {
489 return nil, ErrInvalidValue
490 }
491 return b, nil
492 case reflect.String:
493 return value, nil
494 case reflect.Float64:
495 f, err := strconv.ParseFloat(value, 64)
496 if err != nil {
497 return nil, ErrInvalidValue
498 }
499 return f, nil
500 default:
501 return nil, ErrInvalidValue
502 }
503 }
504
505 // OptionIsValid checks if a value is valid for a certain option
506 func OptionIsValid(option string, value any) error {
507 if validator, ok := optionValidators[option]; ok {
508 return validator(option, value)
509 }
510
511 return nil
512 }
513
514 // Option validators
515
516 func validatePositiveValue(option string, value any) error {
517 nativeValue, ok := value.(float64)
518
519 if !ok {
520 return errors.New("Expected numeric type for " + option)
521 }
522
523 if nativeValue < 1 {
524 return errors.New(option + " must be greater than 0")
525 }
526
527 return nil
528 }
529
530 func validateNonNegativeValue(option string, value any) error {
531 nativeValue, ok := value.(float64)
532
533 if !ok {
534 return errors.New("Expected numeric type for " + option)
535 }
536
537 if nativeValue < 0 {
538 return errors.New(option + " must be non-negative")
539 }
540
541 return nil
542 }
543
544 func validateChoice(option string, value any) error {
545 if choices, ok := OptionChoices[option]; ok {
546 val, ok := value.(string)
547 if !ok {
548 return errors.New("Expected string type for " + option)
549 }
550
551 for _, v := range choices {
552 if val == v {
553 return nil
554 }
555 }
556
557 choicesStr := strings.Join(choices, ", ")
558 return errors.New(option + " must be one of: " + choicesStr)
559 }
560
561 return errors.New("Option has no pre-defined choices")
562 }
563
564 func validateColorscheme(option string, value any) error {
565 colorscheme, ok := value.(string)
566
567 if !ok {
568 return errors.New("Expected string type for colorscheme")
569 }
570
571 if !ColorschemeExists(colorscheme) {
572 return errors.New(colorscheme + " is not a valid colorscheme")
573 }
574
575 return nil
576 }
577
578 func validateEncoding(option string, value any) error {
579 _, err := htmlindex.Get(value.(string))
580 return err
581 }