12 "github.com/flynn/json5"
13 "github.com/zyedidia/glob"
14 "github.com/zyedidia/micro/internal/util"
15 "golang.org/x/text/encoding/htmlindex"
18 type optionValidator func(string, interface{}) error
21 ErrInvalidOption = errors.New("Invalid option")
22 ErrInvalidValue = errors.New("Invalid value")
24 // The options that the user can set
25 GlobalSettings map[string]interface{}
27 // This is the raw parsed json
28 parsedSettings map[string]interface{}
31 // Options with validators
32 var optionValidators = map[string]optionValidator{
33 "tabsize": validatePositiveValue,
34 "scrollmargin": validateNonNegativeValue,
35 "scrollspeed": validateNonNegativeValue,
36 "colorscheme": validateColorscheme,
37 "colorcolumn": validateNonNegativeValue,
38 "fileformat": validateLineEnding,
39 "encoding": validateEncoding,
42 func ReadSettings() error {
43 filename := ConfigDir + "/settings.json"
44 if _, e := os.Stat(filename); e == nil {
45 input, err := ioutil.ReadFile(filename)
47 return errors.New("Error reading settings.json file: " + err.Error())
49 if !strings.HasPrefix(string(input), "null") {
50 // Unmarshal the input into the parsed map
51 err = json5.Unmarshal(input, &parsedSettings)
53 return errors.New("Error reading settings.json: " + err.Error())
60 // InitGlobalSettings initializes the options map and sets all options to their default values
61 // Must be called after ReadSettings
62 func InitGlobalSettings() {
63 GlobalSettings = DefaultGlobalSettings()
65 for k, v := range parsedSettings {
66 if !strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
72 // InitLocalSettings scans the json in settings.json and sets the options locally based
73 // on whether the filetype or path matches ft or glob local settings
74 // Must be called after ReadSettings
75 func InitLocalSettings(settings map[string]interface{}, path string) error {
77 for k, v := range parsedSettings {
78 if strings.HasPrefix(reflect.TypeOf(v).String(), "map") {
79 if strings.HasPrefix(k, "ft:") {
80 if settings["filetype"].(string) == k[3:] {
81 for k1, v1 := range v.(map[string]interface{}) {
86 g, err := glob.Compile(k)
88 parseError = errors.New("Error with glob setting " + k + ": " + err.Error())
92 if g.MatchString(path) {
93 for k1, v1 := range v.(map[string]interface{}) {
103 // WriteSettings writes the settings to the specified filename as JSON
104 func WriteSettings(filename string) error {
106 if _, e := os.Stat(ConfigDir); e == nil {
107 for k, v := range GlobalSettings {
108 parsedSettings[k] = v
111 txt, _ := json.MarshalIndent(parsedSettings, "", " ")
112 err = ioutil.WriteFile(filename, append(txt, '\n'), 0644)
117 // AddOption creates a new option. This is meant to be called by plugins to add options.
118 func AddOption(name string, value interface{}) error {
119 GlobalSettings[name] = value
120 err := WriteSettings(ConfigDir + "/settings.json")
122 return errors.New("Error writing settings.json file: " + err.Error())
127 // GetGlobalOption returns the global value of the given option
128 func GetGlobalOption(name string) interface{} {
129 return GlobalSettings[name]
132 func DefaultCommonSettings() map[string]interface{} {
133 return map[string]interface{}{
137 "colorcolumn": float64(0),
142 "fileformat": "unix",
145 "keepautoindent": false,
147 "matchbraceleft": false,
148 "rmtrailingws": false,
153 "scrollmargin": float64(3),
154 "scrollspeed": float64(2),
159 "statusformatl": "$(filename) $(modified)($(line),$(col)) $(opt:filetype) $(opt:fileformat) $(opt:encoding)",
160 "statusformatr": "$(bind:ToggleKeyMenu): show bindings, $(bind:ToggleHelp): toggle help",
163 "tabmovement": false,
164 "tabsize": float64(4),
165 "tabstospaces": false,
170 func GetInfoBarOffset() int {
172 if GetGlobalOption("infobar").(bool) {
175 if GetGlobalOption("keymenu").(bool) {
181 // DefaultGlobalSettings returns the default global settings for micro
182 // Note that colorscheme is a global only option
183 func DefaultGlobalSettings() map[string]interface{} {
184 common := DefaultCommonSettings()
185 common["colorscheme"] = "default"
186 common["infobar"] = true
187 common["keymenu"] = false
188 common["mouse"] = true
189 common["pluginchannels"] = []string{"https://raw.githubusercontent.com/micro-editor/plugin-channel/master/channel.json"}
190 common["pluginrepos"] = []string{}
191 common["savehistory"] = true
192 common["sucmd"] = "sudo"
193 common["termtitle"] = false
197 // LocalSettings is a list of the local only settings
198 var LocalSettings = []string{"filetype", "readonly"}
200 // DefaultLocalSettings returns the default local settings
201 // Note that filetype is a local only option
202 func DefaultLocalSettings() map[string]interface{} {
203 common := DefaultCommonSettings()
204 common["filetype"] = "unknown"
205 common["readonly"] = false
209 func DefaultAllSettings() map[string]interface{} {
210 global := DefaultGlobalSettings()
211 local := DefaultLocalSettings()
212 for k, v := range global {
218 func GetNativeValue(option string, realValue interface{}, value string) (interface{}, error) {
219 var native interface{}
220 kind := reflect.TypeOf(realValue).Kind()
221 if kind == reflect.Bool {
222 b, err := util.ParseBool(value)
224 return nil, ErrInvalidValue
227 } else if kind == reflect.String {
229 } else if kind == reflect.Float64 {
230 i, err := strconv.Atoi(value)
232 return nil, ErrInvalidValue
236 return nil, ErrInvalidValue
239 if err := OptionIsValid(option, native); err != nil {
245 // OptionIsValid checks if a value is valid for a certain option
246 func OptionIsValid(option string, value interface{}) error {
247 if validator, ok := optionValidators[option]; ok {
248 return validator(option, value)
256 func validatePositiveValue(option string, value interface{}) error {
257 tabsize, ok := value.(float64)
260 return errors.New("Expected numeric type for " + option)
264 return errors.New(option + " must be greater than 0")
270 func validateNonNegativeValue(option string, value interface{}) error {
271 nativeValue, ok := value.(float64)
274 return errors.New("Expected numeric type for " + option)
278 return errors.New(option + " must be non-negative")
284 func validateColorscheme(option string, value interface{}) error {
285 colorscheme, ok := value.(string)
288 return errors.New("Expected string type for colorscheme")
291 if !ColorschemeExists(colorscheme) {
292 return errors.New(colorscheme + " is not a valid colorscheme")
298 func validateLineEnding(option string, value interface{}) error {
299 endingType, ok := value.(string)
302 return errors.New("Expected string type for file format")
305 if endingType != "unix" && endingType != "dos" {
306 return errors.New("File format must be either 'unix' or 'dos'")
312 func validateEncoding(option string, value interface{}) error {
313 _, err := htmlindex.Get(value.(string))