14 "github.com/zyedidia/glob"
15 "github.com/zyedidia/json5"
16 "github.com/zyedidia/micro/v2/internal/util"
17 "golang.org/x/text/encoding/htmlindex"
20 type optionValidator func(string, interface{}) error
23 ErrInvalidOption = errors.New("Invalid option")
24 ErrInvalidValue = errors.New("Invalid value")
26 // The options that the user can set
27 GlobalSettings map[string]interface{}
29 // This is the raw parsed json
30 parsedSettings map[string]interface{}
31 settingsParseError bool
33 // ModifiedSettings is a map of settings which should be written to disk
34 // because they have been modified by the user in this session
35 ModifiedSettings map[string]bool
39 ModifiedSettings = make(map[string]bool)
40 parsedSettings = make(map[string]interface{})
43 // Options with validators
44 var optionValidators = map[string]optionValidator{
45 "autosave": validateNonNegativeValue,
46 "tabsize": validatePositiveValue,
47 "scrollmargin": validateNonNegativeValue,
48 "scrollspeed": validateNonNegativeValue,
49 "colorscheme": validateColorscheme,
50 "colorcolumn": validateNonNegativeValue,
51 "fileformat": validateLineEnding,
52 "encoding": validateEncoding,
55 func ReadSettings() error {
56 filename := filepath.Join(ConfigDir, "settings.json")
57 if _, e := os.Stat(filename); e == nil {
58 input, err := ioutil.ReadFile(filename)
60 settingsParseError = true
61 return errors.New("Error reading settings.json file: " + err.Error())
63 if !strings.HasPrefix(string(input), "null") {
64 // Unmarshal the input into the parsed map
65 err = json5.Unmarshal(input, &parsedSettings)
67 settingsParseError = true
68 return errors.New("Error reading settings.json: " + err.Error())
71 // check if autosave is a boolean and convert it to float if so
72 if v, ok := parsedSettings["autosave"]; ok {
76 parsedSettings["autosave"] = 8.0
78 parsedSettings["autosave"] = 0.0
87 func verifySetting(option string, value reflect.Type, def reflect.Type) bool {
88 var interfaceArr []interface{}
90 case "pluginrepos", "pluginchannels":
91 return value.AssignableTo(reflect.TypeOf(interfaceArr))
93 return def.AssignableTo(value)
97 // InitGlobalSettings initializes the options map and sets all options to their default values
98 // Must be called after ReadSettings
99 func InitGlobalSettings() error {
101 GlobalSettings = DefaultGlobalSettings()
103 for k, v := range parsedSettings {
104 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
105 if _, ok := GlobalSettings[k]; ok && !verifySetting(k, reflect.TypeOf(v), reflect.TypeOf(GlobalSettings[k])) {
106 err = errors.New(fmt.Sprintf("Global Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", k, reflect.TypeOf(v), GlobalSettings[k], reflect.TypeOf(GlobalSettings[k])))
110 GlobalSettings[k] = v
116 // InitLocalSettings scans the json in settings.json and sets the options locally based
117 // on whether the filetype or path matches ft or glob local settings
118 // Must be called after ReadSettings
119 func InitLocalSettings(settings map[string]interface{}, path string) error {
121 for k, v := range parsedSettings {
122 if strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
123 if strings.HasPrefix(k, "ft:") {
124 if settings["filetype"].(string) == k[3:] {
125 for k1, v1 := range v.(map[string]interface{}) {
126 if _, ok := settings[k1]; ok && !verifySetting(k1, reflect.TypeOf(v1), reflect.TypeOf(settings[k1])) {
127 parseError = errors.New(fmt.Sprintf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", k, reflect.TypeOf(v1), settings[k1], reflect.TypeOf(settings[k1])))
134 g, err := glob.Compile(k)
136 parseError = errors.New("Error with glob setting " + k + ": " + err.Error())
140 if g.MatchString(path) {
141 for k1, v1 := range v.(map[string]interface{}) {
142 if _, ok := settings[k1]; ok && !verifySetting(k1, reflect.TypeOf(v1), reflect.TypeOf(settings[k1])) {
143 parseError = errors.New(fmt.Sprintf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", k, reflect.TypeOf(v1), settings[k1], reflect.TypeOf(settings[k1])))
155 // WriteSettings writes the settings to the specified filename as JSON
156 func WriteSettings(filename string) error {
157 if settingsParseError {
158 // Don't write settings if there was a parse error
159 // because this will delete the settings.json if it
160 // is invalid. Instead we should allow the user to fix
166 if _, e := os.Stat(ConfigDir); e == nil {
167 defaults := DefaultGlobalSettings()
169 // remove any options froms parsedSettings that have since been marked as default
170 for k, v := range parsedSettings {
171 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
172 cur, okcur := GlobalSettings[k]
173 if def, ok := defaults[k]; ok && okcur && reflect.DeepEqual(cur, def) {
174 delete(parsedSettings, k)
179 // add any options to parsedSettings that have since been marked as non-default
180 for k, v := range GlobalSettings {
181 if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
182 if _, wr := ModifiedSettings[k]; wr {
183 parsedSettings[k] = v
188 txt, _ := json.MarshalIndent(parsedSettings, "", " ")
189 err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
194 // OverwriteSettings writes the current settings to settings.json and
195 // resets any user configuration of local settings present in settings.json
196 func OverwriteSettings(filename string) error {
197 settings := make(map[string]interface{})
200 if _, e := os.Stat(ConfigDir); e == nil {
201 defaults := DefaultGlobalSettings()
202 for k, v := range GlobalSettings {
203 if def, ok := defaults[k]; !ok || !reflect.DeepEqual(v, def) {
204 if _, wr := ModifiedSettings[k]; wr {
210 txt, _ := json.MarshalIndent(settings, "", " ")
211 err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
216 // RegisterCommonOptionPlug creates a new option (called pl.name). This is meant to be called by plugins to add options.
217 func RegisterCommonOptionPlug(pl string, name string, defaultvalue interface{}) error {
218 name = pl + "." + name
219 if _, ok := GlobalSettings[name]; !ok {
220 defaultCommonSettings[name] = defaultvalue
221 GlobalSettings[name] = defaultvalue
222 err := WriteSettings(filepath.Join(ConfigDir, "settings.json"))
224 return errors.New("Error writing settings.json file: " + err.Error())
227 defaultCommonSettings[name] = defaultvalue
232 // RegisterGlobalOptionPlug creates a new global-only option (named pl.name)
233 func RegisterGlobalOptionPlug(pl string, name string, defaultvalue interface{}) error {
234 return RegisterGlobalOption(pl+"."+name, defaultvalue)
237 // RegisterGlobalOption creates a new global-only option
238 func RegisterGlobalOption(name string, defaultvalue interface{}) error {
239 if v, ok := GlobalSettings[name]; !ok {
240 DefaultGlobalOnlySettings[name] = defaultvalue
241 GlobalSettings[name] = defaultvalue
242 err := WriteSettings(filepath.Join(ConfigDir, "settings.json"))
244 return errors.New("Error writing settings.json file: " + err.Error())
247 DefaultGlobalOnlySettings[name] = v
252 // GetGlobalOption returns the global value of the given option
253 func GetGlobalOption(name string) interface{} {
254 return GlobalSettings[name]
257 var defaultCommonSettings = map[string]interface{}{
263 "colorcolumn": float64(0),
269 "fileformat": "unix",
270 "filetype": "unknown",
273 "keepautoindent": false,
278 "rmtrailingws": false,
280 "relativeruler": false,
284 "scrollmargin": float64(3),
285 "scrollspeed": float64(2),
290 "statusformatl": "$(filename) $(modified)($(line),$(col)) $(status.paste)| ft:$(opt:filetype) | $(opt:fileformat) | $(opt:encoding)",
291 "statusformatr": "$(bind:ToggleKeyMenu): bindings, $(bind:ToggleHelp): help",
294 "tabmovement": false,
295 "tabsize": float64(4),
296 "tabstospaces": false,
300 func GetInfoBarOffset() int {
302 if GetGlobalOption("infobar").(bool) {
305 if GetGlobalOption("keymenu").(bool) {
311 // DefaultCommonSettings returns the default global settings for micro
312 // Note that colorscheme is a global only option
313 func DefaultCommonSettings() map[string]interface{} {
314 commonsettings := make(map[string]interface{})
315 for k, v := range defaultCommonSettings {
316 commonsettings[k] = v
318 return commonsettings
321 // a list of settings that should only be globally modified and their
323 var DefaultGlobalOnlySettings = map[string]interface{}{
324 "autosave": float64(0),
325 "colorscheme": "default",
331 "parsecursor": false,
335 "pluginchannels": []string{"https://raw.githubusercontent.com/micro-editor/plugin-channel/master/channel.json"},
336 "pluginrepos": []string{},
340 // a list of settings that should never be globally modified
341 var LocalSettings = []string{
346 // DefaultGlobalSettings returns the default global settings for micro
347 // Note that colorscheme is a global only option
348 func DefaultGlobalSettings() map[string]interface{} {
349 globalsettings := make(map[string]interface{})
350 for k, v := range defaultCommonSettings {
351 globalsettings[k] = v
353 for k, v := range DefaultGlobalOnlySettings {
354 globalsettings[k] = v
356 return globalsettings
359 // DefaultAllSettings returns a map of all settings and their
360 // default values (both common and global settings)
361 func DefaultAllSettings() map[string]interface{} {
362 allsettings := make(map[string]interface{})
363 for k, v := range defaultCommonSettings {
366 for k, v := range DefaultGlobalOnlySettings {
372 // GetNativeValue parses and validates a value for a given option
373 func GetNativeValue(option string, realValue interface{}, value string) (interface{}, error) {
374 var native interface{}
375 kind := reflect.TypeOf(realValue).Kind()
376 if kind == reflect.Bool {
377 b, err := util.ParseBool(value)
379 return nil, ErrInvalidValue
382 } else if kind == reflect.String {
384 } else if kind == reflect.Float64 {
385 i, err := strconv.Atoi(value)
387 return nil, ErrInvalidValue
391 return nil, ErrInvalidValue
394 if err := OptionIsValid(option, native); err != nil {
400 // OptionIsValid checks if a value is valid for a certain option
401 func OptionIsValid(option string, value interface{}) error {
402 if validator, ok := optionValidators[option]; ok {
403 return validator(option, value)
411 func validatePositiveValue(option string, value interface{}) error {
412 tabsize, ok := value.(float64)
415 return errors.New("Expected numeric type for " + option)
419 return errors.New(option + " must be greater than 0")
425 func validateNonNegativeValue(option string, value interface{}) error {
426 nativeValue, ok := value.(float64)
429 return errors.New("Expected numeric type for " + option)
433 return errors.New(option + " must be non-negative")
439 func validateColorscheme(option string, value interface{}) error {
440 colorscheme, ok := value.(string)
443 return errors.New("Expected string type for colorscheme")
446 if !ColorschemeExists(colorscheme) {
447 return errors.New(colorscheme + " is not a valid colorscheme")
453 func validateLineEnding(option string, value interface{}) error {
454 endingType, ok := value.(string)
457 return errors.New("Expected string type for file format")
460 if endingType != "unix" && endingType != "dos" {
461 return errors.New("File format must be either 'unix' or 'dos'")
467 func validateEncoding(option string, value interface{}) error {
468 _, err := htmlindex.Get(value.(string))