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