forked from u-root/u-root
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hooks.go
52 lines (44 loc) · 1.58 KB
/
hooks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package edit
import (
"github.com/u-root/u-root/cmds/elvish/eval"
"github.com/u-root/u-root/cmds/elvish/eval/vals"
"github.com/u-root/u-root/cmds/elvish/eval/vars"
"github.com/u-root/u-root/cmds/elvish/vector"
)
// The $edit:{before,after}-readline lists that contain hooks. We might have more
// hooks in future.
// editorHooks contain hooks for the editor. They are just slices of functions;
// each of them is initialized with a function that calls all Elvish functions
// contained in the eponymous variable under edit:.
type editorHooks struct {
beforeReadline []func()
afterReadline []func(string)
}
func init() {
atEditorInit(func(ed *editor, ns eval.Ns) {
beforeReadline := vals.EmptyList
ns["before-readline"] = vars.FromPtr(&beforeReadline)
ed.AddBeforeReadline(func() { callHooks(ed, beforeReadline) })
afterReadline := vals.EmptyList
ns["after-readline"] = vars.FromPtr(&afterReadline)
ed.AddAfterReadline(func(s string) { callHooks(ed, afterReadline, s) })
})
}
// AddBeforeReadline adds a function to the before-readline hook.
func (h *editorHooks) AddBeforeReadline(f func()) {
h.beforeReadline = append(h.beforeReadline, f)
}
// AddAfterReadline adds a function to the after-readline hook.
func (h *editorHooks) AddAfterReadline(f func(string)) {
h.afterReadline = append(h.afterReadline, f)
}
func callHooks(ed *editor, li vector.Vector, args ...interface{}) {
for it := li.Iterator(); it.HasElem(); it.Next() {
fn, ok := it.Elem().(eval.Callable)
if !ok {
// TODO More detailed error message.
ed.Notify("hook not a function")
}
ed.CallFn(fn, args...)
}
}