15 "github.com/flynn/json5"
16 "github.com/zyedidia/glob"
19 type optionValidator func(string, interface{}) error
21 // The options that the user can set
22 var globalSettings map[string]interface{}
24 var invalidSettings bool
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,
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{}
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") {
48 TermMessage("Error reading settings.json file: " + err.Error())
49 invalidSettings = true
53 err = json5.Unmarshal(input, &parsed)
55 TermMessage("Error reading settings.json:", err.Error())
56 invalidSettings = true
63 globalSettings = make(map[string]interface{})
64 for k, v := range defaults {
67 for k, v := range parsed {
68 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
73 if _, err := os.Stat(filename); os.IsNotExist(err) || writeSettings {
74 err := WriteSettings(filename)
76 TermMessage("Error writing settings.json file: " + err.Error())
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{}
87 filename := configDir + "/settings.json"
88 if _, e := os.Stat(filename); e == nil {
89 input, err := ioutil.ReadFile(filename)
91 TermMessage("Error reading settings.json file: " + err.Error())
92 invalidSettings = true
96 err = json5.Unmarshal(input, &parsed)
98 TermMessage("Error reading settings.json:", err.Error())
99 invalidSettings = true
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
112 g, err := glob.Compile(k)
114 TermMessage("Error with glob setting ", k, ": ", err)
118 if g.MatchString(buf.Path) {
119 for k1, v1 := range v.(map[string]interface{}) {
120 buf.Settings[k1] = v1
128 // WriteSettings writes the settings to the specified filename as JSON
129 func WriteSettings(filename string) error {
131 // Do not write the settings if there was an error when reading them
136 if _, e := os.Stat(configDir); e == nil {
137 parsed := make(map[string]interface{})
139 filename := configDir + "/settings.json"
140 for k, v := range globalSettings {
143 if _, e := os.Stat(filename); e == nil {
144 input, err := ioutil.ReadFile(filename)
145 if string(input) != "null" {
150 err = json5.Unmarshal(input, &parsed)
152 TermMessage("Error reading settings.json:", err.Error())
153 invalidSettings = true
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]
166 txt, _ := json.MarshalIndent(parsed, "", " ")
167 err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
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")
177 TermMessage("Error writing settings.json file: " + err.Error())
181 // GetGlobalOption returns the global value of the given option
182 func GetGlobalOption(name string) interface{} {
183 return globalSettings[name]
186 // GetLocalOption returns the local value of the given option
187 func GetLocalOption(name string, buf *Buffer) interface{} {
188 return buf.Settings[name]
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)
198 return GetGlobalOption(name)
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{}{
208 "colorcolumn": float64(0),
209 "colorscheme": "default",
213 "fileformat": "unix",
218 "keepautoindent": false,
221 "matchbraceleft": false,
223 "pluginchannels": []string{"https://raw.githubusercontent.com/micro-editor/plugin-channel/master/channel.json"},
224 "pluginrepos": []string{},
225 "rmtrailingws": false,
231 "scrollmargin": float64(3),
232 "scrollspeed": float64(2),
239 "tabmovement": false,
240 "tabsize": float64(4),
241 "tabstospaces": false,
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{}{
254 "colorcolumn": float64(0),
258 "fileformat": "unix",
259 "filetype": "Unknown",
263 "keepautoindent": false,
265 "matchbraceleft": false,
266 "rmtrailingws": false,
271 "scrollmargin": float64(3),
272 "scrollspeed": float64(2),
278 "tabmovement": false,
279 "tabsize": float64(4),
280 "tabstospaces": false,
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")
294 SetLocalOption(option, value, CurView())
298 var nativeValue interface{}
300 kind := reflect.TypeOf(globalSettings[option]).Kind()
301 if kind == reflect.Bool {
302 b, err := ParseBool(value)
304 return errors.New("Invalid value")
307 } else if kind == reflect.String {
309 } else if kind == reflect.Float64 {
310 i, err := strconv.Atoi(value)
312 return errors.New("Invalid value")
314 nativeValue = float64(i)
316 return errors.New("Option has unsupported value type")
319 if err := optionIsValid(option, nativeValue); err != nil {
323 globalSettings[option] = nativeValue
325 if option == "colorscheme" {
328 for _, tab := range tabs {
329 for _, view := range tab.Views {
330 view.Buf.UpdateRules()
335 if option == "infobar" || option == "keymenu" {
336 for _, tab := range tabs {
341 if option == "mouse" {
342 if !nativeValue.(bool) {
343 screen.DisableMouse()
350 if _, ok := CurView().Buf.Settings[option]; ok {
351 for _, tab := range tabs {
352 for _, view := range tab.Views {
353 SetLocalOption(option, value, view)
362 // SetLocalOption sets the local version of this option
363 func SetLocalOption(option, value string, view *View) error {
365 if _, ok := buf.Settings[option]; !ok {
366 return errors.New("Invalid option")
369 var nativeValue interface{}
371 kind := reflect.TypeOf(buf.Settings[option]).Kind()
372 if kind == reflect.Bool {
373 b, err := ParseBool(value)
375 return errors.New("Invalid value")
378 } else if kind == reflect.String {
380 } else if kind == reflect.Float64 {
381 i, err := strconv.Atoi(value)
383 return errors.New("Invalid value")
385 nativeValue = float64(i)
387 return errors.New("Option has unsupported value type")
390 if err := optionIsValid(option, nativeValue); err != nil {
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
399 for _, tab := range tabs {
400 for _, v := range tab.Views {
401 if !nativeValue.(bool) {
402 if v.Buf.origHash == empty {
405 go func(b *Buffer) { // calculate md5 hash of the file
408 if file, e := os.Open(b.AbsPath); e == nil {
413 if _, e = io.Copy(h, file); e == nil {
414 h.Sum(b.origHash[:0])
420 v.Buf.IsModified = v.Buf.Modified()
428 buf.Settings[option] = nativeValue
430 if option == "statusline" {
431 view.ToggleStatusLine()
434 if option == "filetype" {
440 if option == "fileformat" {
441 buf.IsModified = true
444 if option == "syntax" {
445 if !nativeValue.(bool) {
448 if buf.highlighter != nil {
449 buf.highlighter.HighlightStates(buf)
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"
461 err := SetOption(option, value)
464 messenger.Error(err.Error())
468 err = WriteSettings(filename)
470 messenger.Error("Error writing to settings.json: " + err.Error())
475 func optionIsValid(option string, value interface{}) error {
476 if validator, ok := optionValidators[option]; ok {
477 return validator(option, value)
485 func validatePositiveValue(option string, value interface{}) error {
486 tabsize, ok := value.(float64)
489 return errors.New("Expected numeric type for " + option)
493 return errors.New(option + " must be greater than 0")
499 func validateNonNegativeValue(option string, value interface{}) error {
500 nativeValue, ok := value.(float64)
503 return errors.New("Expected numeric type for " + option)
507 return errors.New(option + " must be non-negative")
513 func validateColorscheme(option string, value interface{}) error {
514 colorscheme, ok := value.(string)
517 return errors.New("Expected string type for colorscheme")
520 if !ColorschemeExists(colorscheme) {
521 return errors.New(colorscheme + " is not a valid colorscheme")
527 func validateLineEnding(option string, value interface{}) error {
528 endingType, ok := value.(string)
531 return errors.New("Expected string type for file format")
534 if endingType != "unix" && endingType != "dos" {
535 return errors.New("File format must be either 'unix' or 'dos'")