MCPcopy
hub / github.com/micro-editor/micro / TryBindKey

Function TryBindKey

internal/action/bindings.go:275–330  ·  view source on GitHub ↗

TryBindKey tries to bind a key by writing to config.ConfigDir/bindings.json Returns true if the keybinding already existed or is binded successfully and a possible error

(k, v string, overwrite bool, writeToFile bool)

Source from the content-addressed store, hash-verified

273// TryBindKey tries to bind a key by writing to config.ConfigDir/bindings.json
274// Returns true if the keybinding already existed or is binded successfully and a possible error
275func TryBindKey(k, v string, overwrite bool, writeToFile bool) (bool, error) {
276 var e error
277 var parsed map[string]any
278
279 filename := filepath.Join(config.ConfigDir, "bindings.json")
280 createBindingsIfNotExist(filename)
281 if _, e = os.Stat(filename); e == nil {
282 input, err := os.ReadFile(filename)
283 if err != nil {
284 return false, errors.New("Error reading bindings.json file: " + err.Error())
285 }
286
287 err = json5.Unmarshal(input, &parsed)
288 if err != nil {
289 return false, errors.New("Error reading bindings.json: " + err.Error())
290 }
291
292 key, err := findEvent(k)
293 if err != nil {
294 return false, err
295 }
296
297 found := false
298 var ev string
299 for ev = range parsed {
300 if e, err := findEvent(ev); err == nil {
301 if eventsEqual(e, key) {
302 found = true
303 break
304 }
305 }
306 }
307
308 if found {
309 if overwrite {
310 parsed[ev] = v
311 } else {
312 return true, nil
313 }
314 } else {
315 parsed[k] = v
316 }
317
318 BindKey(k, v, Binder["buffer"])
319
320 txt, _ := json.MarshalIndent(parsed, "", " ")
321 txt = append(txt, '\n')
322
323 if writeToFile {
324 return true, writeFile(filename, txt)
325 } else {
326 return true, nil
327 }
328 }
329 return false, e
330}
331
332// UnbindKey removes the binding for a key from the bindings.json file

Callers 2

TryBindKeyPlugFunction · 0.85
BindCmdMethod · 0.85

Calls 7

createBindingsIfNotExistFunction · 0.85
findEventFunction · 0.85
eventsEqualFunction · 0.85
BindKeyFunction · 0.85
JoinMethod · 0.80
writeFileFunction · 0.70
ErrorMethod · 0.45

Tested by

no test coverage detected