]> git.lizzy.rs Git - micro.git/blob - cmd/micro/settings.go
Make settings capitalization consistent
[micro.git] / cmd / micro / settings.go
1 package main
2
3 import (
4         "crypto/md5"
5         "encoding/json"
6         "errors"
7         "io/ioutil"
8         "os"
9         "reflect"
10         "strconv"
11         "strings"
12
13         "github.com/flynn/json5"
14         "github.com/zyedidia/glob"
15 )
16
17 type optionValidator func(string, interface{}) error
18
19 // The options that the user can set
20 var globalSettings map[string]interface{}
21
22 var invalidSettings bool
23
24 // Options with validators
25 var optionValidators = map[string]optionValidator{
26         "tabsize":      validatePositiveValue,
27         "scrollmargin": validateNonNegativeValue,
28         "scrollspeed":  validateNonNegativeValue,
29         "colorscheme":  validateColorscheme,
30         "colorcolumn":  validateNonNegativeValue,
31         "fileformat":   validateLineEnding,
32 }
33
34 // InitGlobalSettings initializes the options map and sets all options to their default values
35 func InitGlobalSettings() {
36         invalidSettings = false
37         defaults := DefaultGlobalSettings()
38         var parsed map[string]interface{}
39
40         filename := configDir + "/settings.json"
41         writeSettings := false
42         if _, e := os.Stat(filename); e == nil {
43                 input, err := ioutil.ReadFile(filename)
44                 if !strings.HasPrefix(string(input), "null") {
45                         if err != nil {
46                                 TermMessage("Error reading settings.json file: " + err.Error())
47                                 invalidSettings = true
48                                 return
49                         }
50
51                         err = json5.Unmarshal(input, &parsed)
52                         if err != nil {
53                                 TermMessage("Error reading settings.json:", err.Error())
54                                 invalidSettings = true
55                         }
56                 } else {
57                         writeSettings = true
58                 }
59         }
60
61         globalSettings = make(map[string]interface{})
62         for k, v := range defaults {
63                 globalSettings[k] = v
64         }
65         for k, v := range parsed {
66                 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
67                         globalSettings[k] = v
68                 }
69         }
70
71         if _, err := os.Stat(filename); os.IsNotExist(err) || writeSettings {
72                 err := WriteSettings(filename)
73                 if err != nil {
74                         TermMessage("Error writing settings.json file: " + err.Error())
75                 }
76         }
77 }
78
79 // InitLocalSettings scans the json in settings.json and sets the options locally based
80 // on whether the buffer matches the glob
81 func InitLocalSettings(buf *Buffer) {
82         invalidSettings = false
83         var parsed map[string]interface{}
84
85         filename := configDir + "/settings.json"
86         if _, e := os.Stat(filename); e == nil {
87                 input, err := ioutil.ReadFile(filename)
88                 if err != nil {
89                         TermMessage("Error reading settings.json file: " + err.Error())
90                         invalidSettings = true
91                         return
92                 }
93
94                 err = json5.Unmarshal(input, &parsed)
95                 if err != nil {
96                         TermMessage("Error reading settings.json:", err.Error())
97                         invalidSettings = true
98                 }
99         }
100
101         for k, v := range parsed {
102                 if strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
103                         g, err := glob.Compile(k)
104                         if err != nil {
105                                 TermMessage("Error with glob setting ", k, ": ", err)
106                                 continue
107                         }
108
109                         if g.MatchString(buf.Path) {
110                                 for k1, v1 := range v.(map[string]interface{}) {
111                                         buf.Settings[k1] = v1
112                                 }
113                         }
114                 }
115         }
116 }
117
118 // WriteSettings writes the settings to the specified filename as JSON
119 func WriteSettings(filename string) error {
120         if invalidSettings {
121                 // Do not write the settings if there was an error when reading them
122                 return nil
123         }
124
125         var err error
126         if _, e := os.Stat(configDir); e == nil {
127                 parsed := make(map[string]interface{})
128
129                 filename := configDir + "/settings.json"
130                 for k, v := range globalSettings {
131                         parsed[k] = v
132                 }
133                 if _, e := os.Stat(filename); e == nil {
134                         input, err := ioutil.ReadFile(filename)
135                         if string(input) != "null" {
136                                 if err != nil {
137                                         return err
138                                 }
139
140                                 err = json5.Unmarshal(input, &parsed)
141                                 if err != nil {
142                                         TermMessage("Error reading settings.json:", err.Error())
143                                         invalidSettings = true
144                                 }
145
146                                 for k, v := range parsed {
147                                         if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
148                                                 if _, ok := globalSettings[k]; ok {
149                                                         parsed[k] = globalSettings[k]
150                                                 }
151                                         }
152                                 }
153                         }
154                 }
155
156                 txt, _ := json.MarshalIndent(parsed, "", "    ")
157                 err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
158         }
159         return err
160 }
161
162 // AddOption creates a new option. This is meant to be called by plugins to add options.
163 func AddOption(name string, value interface{}) {
164         globalSettings[name] = value
165         err := WriteSettings(configDir + "/settings.json")
166         if err != nil {
167                 TermMessage("Error writing settings.json file: " + err.Error())
168         }
169 }
170
171 // GetGlobalOption returns the global value of the given option
172 func GetGlobalOption(name string) interface{} {
173         return globalSettings[name]
174 }
175
176 // GetLocalOption returns the local value of the given option
177 func GetLocalOption(name string, buf *Buffer) interface{} {
178         return buf.Settings[name]
179 }
180
181 // GetOption returns the value of the given option
182 // If there is a local version of the option, it returns that
183 // otherwise it will return the global version
184 func GetOption(name string) interface{} {
185         if GetLocalOption(name, CurView().Buf) != nil {
186                 return GetLocalOption(name, CurView().Buf)
187         }
188         return GetGlobalOption(name)
189 }
190
191 // DefaultGlobalSettings returns the default global settings for micro
192 // Note that colorscheme is a global only option
193 func DefaultGlobalSettings() map[string]interface{} {
194         return map[string]interface{}{
195                 "autoindent":     true,
196                 "keepautoindent": false,
197                 "autosave":       false,
198                 "colorcolumn":    float64(0),
199                 "colorscheme":    "default",
200                 "cursorline":     true,
201                 "eofnewline":     false,
202                 "fastdirty":      true,
203                 "fileformat":     "unix",
204                 "ignorecase":     false,
205                 "indentchar":     " ",
206                 "infobar":        true,
207                 "keymenu":        false,
208                 "mouse":          true,
209                 "rmtrailingws":   false,
210                 "ruler":          true,
211                 "savecursor":     false,
212                 "saveundo":       false,
213                 "scrollspeed":    float64(2),
214                 "scrollmargin":   float64(3),
215                 "softwrap":       false,
216                 "splitright":     true,
217                 "splitbottom":    true,
218                 "statusline":     true,
219                 "sucmd":          "sudo",
220                 "syntax":         true,
221                 "tabmovement":    false,
222                 "tabsize":        float64(4),
223                 "tabstospaces":   false,
224                 "termtitle":      false,
225                 "pluginchannels": []string{
226                         "https://raw.githubusercontent.com/micro-editor/plugin-channel/master/channel.json",
227                 },
228                 "pluginrepos": []string{},
229                 "useprimary":  true,
230         }
231 }
232
233 // DefaultLocalSettings returns the default local settings
234 // Note that filetype is a local only option
235 func DefaultLocalSettings() map[string]interface{} {
236         return map[string]interface{}{
237                 "autoindent":     true,
238                 "keepautoindent": false,
239                 "autosave":       false,
240                 "colorcolumn":    float64(0),
241                 "cursorline":     true,
242                 "eofnewline":     false,
243                 "fastdirty":      true,
244                 "fileformat":     "unix",
245                 "filetype":       "Unknown",
246                 "ignorecase":     false,
247                 "indentchar":     " ",
248                 "rmtrailingws":   false,
249                 "ruler":          true,
250                 "savecursor":     false,
251                 "saveundo":       false,
252                 "scrollspeed":    float64(2),
253                 "scrollmargin":   float64(3),
254                 "softwrap":       false,
255                 "splitright":     true,
256                 "splitbottom":    true,
257                 "statusline":     true,
258                 "syntax":         true,
259                 "tabmovement":    false,
260                 "tabsize":        float64(4),
261                 "tabstospaces":   false,
262                 "useprimary":     true,
263         }
264 }
265
266 // SetOption attempts to set the given option to the value
267 // By default it will set the option as global, but if the option
268 // is local only it will set the local version
269 // Use setlocal to force an option to be set locally
270 func SetOption(option, value string) error {
271         if _, ok := globalSettings[option]; !ok {
272                 if _, ok := CurView().Buf.Settings[option]; !ok {
273                         return errors.New("Invalid option")
274                 }
275                 SetLocalOption(option, value, CurView())
276                 return nil
277         }
278
279         var nativeValue interface{}
280
281         kind := reflect.TypeOf(globalSettings[option]).Kind()
282         if kind == reflect.Bool {
283                 b, err := ParseBool(value)
284                 if err != nil {
285                         return errors.New("Invalid value")
286                 }
287                 nativeValue = b
288         } else if kind == reflect.String {
289                 nativeValue = value
290         } else if kind == reflect.Float64 {
291                 i, err := strconv.Atoi(value)
292                 if err != nil {
293                         return errors.New("Invalid value")
294                 }
295                 nativeValue = float64(i)
296         } else {
297                 return errors.New("Option has unsupported value type")
298         }
299
300         if err := optionIsValid(option, nativeValue); err != nil {
301                 return err
302         }
303
304         globalSettings[option] = nativeValue
305
306         if option == "colorscheme" {
307                 // LoadSyntaxFiles()
308                 InitColorscheme()
309                 for _, tab := range tabs {
310                         for _, view := range tab.views {
311                                 view.Buf.UpdateRules()
312                         }
313                 }
314         }
315
316         if option == "infobar" || option == "keymenu" {
317                 for _, tab := range tabs {
318                         tab.Resize()
319                 }
320         }
321
322         if option == "mouse" {
323                 if !nativeValue.(bool) {
324                         screen.DisableMouse()
325                 } else {
326                         screen.EnableMouse()
327                 }
328         }
329
330         if _, ok := CurView().Buf.Settings[option]; ok {
331                 for _, tab := range tabs {
332                         for _, view := range tab.views {
333                                 SetLocalOption(option, value, view)
334                         }
335                 }
336         }
337
338         return nil
339 }
340
341 // SetLocalOption sets the local version of this option
342 func SetLocalOption(option, value string, view *View) error {
343         buf := view.Buf
344         if _, ok := buf.Settings[option]; !ok {
345                 return errors.New("Invalid option")
346         }
347
348         var nativeValue interface{}
349
350         kind := reflect.TypeOf(buf.Settings[option]).Kind()
351         if kind == reflect.Bool {
352                 b, err := ParseBool(value)
353                 if err != nil {
354                         return errors.New("Invalid value")
355                 }
356                 nativeValue = b
357         } else if kind == reflect.String {
358                 nativeValue = value
359         } else if kind == reflect.Float64 {
360                 i, err := strconv.Atoi(value)
361                 if err != nil {
362                         return errors.New("Invalid value")
363                 }
364                 nativeValue = float64(i)
365         } else {
366                 return errors.New("Option has unsupported value type")
367         }
368
369         if err := optionIsValid(option, nativeValue); err != nil {
370                 return err
371         }
372
373         if option == "fastdirty" {
374                 // If it is being turned off, we have to hash every open buffer
375                 var empty [16]byte
376                 for _, tab := range tabs {
377                         for _, v := range tab.views {
378                                 if !nativeValue.(bool) {
379                                         if v.Buf.origHash == empty {
380                                                 data, err := ioutil.ReadFile(v.Buf.AbsPath)
381                                                 if err != nil {
382                                                         data = []byte{}
383                                                 }
384                                                 v.Buf.origHash = md5.Sum(data)
385                                         }
386                                 } else {
387                                         v.Buf.IsModified = v.Buf.Modified()
388                                 }
389                         }
390                 }
391         }
392
393         buf.Settings[option] = nativeValue
394
395         if option == "statusline" {
396                 view.ToggleStatusLine()
397         }
398
399         if option == "filetype" {
400                 // LoadSyntaxFiles()
401                 InitColorscheme()
402                 buf.UpdateRules()
403         }
404
405         if option == "fileformat" {
406                 buf.IsModified = true
407         }
408
409         if option == "syntax" {
410                 if !nativeValue.(bool) {
411                         buf.ClearMatches()
412                 } else {
413                         buf.highlighter.HighlightStates(buf)
414                 }
415         }
416
417         return nil
418 }
419
420 // SetOptionAndSettings sets the given option and saves the option setting to the settings config file
421 func SetOptionAndSettings(option, value string) {
422         filename := configDir + "/settings.json"
423
424         err := SetOption(option, value)
425
426         if err != nil {
427                 messenger.Error(err.Error())
428                 return
429         }
430
431         err = WriteSettings(filename)
432         if err != nil {
433                 messenger.Error("Error writing to settings.json: " + err.Error())
434                 return
435         }
436 }
437
438 func optionIsValid(option string, value interface{}) error {
439         if validator, ok := optionValidators[option]; ok {
440                 return validator(option, value)
441         }
442
443         return nil
444 }
445
446 // Option validators
447
448 func validatePositiveValue(option string, value interface{}) error {
449         tabsize, ok := value.(float64)
450
451         if !ok {
452                 return errors.New("Expected numeric type for " + option)
453         }
454
455         if tabsize < 1 {
456                 return errors.New(option + " must be greater than 0")
457         }
458
459         return nil
460 }
461
462 func validateNonNegativeValue(option string, value interface{}) error {
463         nativeValue, ok := value.(float64)
464
465         if !ok {
466                 return errors.New("Expected numeric type for " + option)
467         }
468
469         if nativeValue < 0 {
470                 return errors.New(option + " must be non-negative")
471         }
472
473         return nil
474 }
475
476 func validateColorscheme(option string, value interface{}) error {
477         colorscheme, ok := value.(string)
478
479         if !ok {
480                 return errors.New("Expected string type for colorscheme")
481         }
482
483         if !ColorschemeExists(colorscheme) {
484                 return errors.New(colorscheme + " is not a valid colorscheme")
485         }
486
487         return nil
488 }
489
490 func validateLineEnding(option string, value interface{}) error {
491         endingType, ok := value.(string)
492
493         if !ok {
494                 return errors.New("Expected string type for file format")
495         }
496
497         if endingType != "unix" && endingType != "dos" {
498                 return errors.New("File format must be either 'unix' or 'dos'")
499         }
500
501         return nil
502 }