-
-
Notifications
You must be signed in to change notification settings - Fork 296
/
state_api.go
69 lines (62 loc) · 1.54 KB
/
state_api.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package edit
import (
"src.elv.sh/pkg/cli"
"src.elv.sh/pkg/cli/tk"
"src.elv.sh/pkg/eval"
"src.elv.sh/pkg/eval/vals"
"src.elv.sh/pkg/eval/vars"
)
func insertAtDot(app cli.App, text string) {
codeArea, ok := focusedCodeArea(app)
if !ok {
return
}
codeArea.MutateState(func(s *tk.CodeAreaState) {
s.Buffer.InsertAtDot(text)
})
}
func replaceInput(app cli.App, text string) {
codeArea, ok := focusedCodeArea(app)
if !ok {
return
}
codeArea.MutateState(func(s *tk.CodeAreaState) {
s.Buffer = tk.CodeBuffer{Content: text, Dot: len(text)}
})
}
func initStateAPI(app cli.App, nb eval.NsBuilder) {
// State API always operates on the root CodeArea widget
codeArea := app.ActiveWidget().(tk.CodeArea)
nb.AddGoFns(map[string]any{
"insert-at-dot": func(s string) { insertAtDot(app, s) },
"replace-input": func(s string) { replaceInput(app, s) },
})
setDot := func(v any) error {
var dot int
err := vals.ScanToGo(v, &dot)
if err != nil {
return err
}
codeArea.MutateState(func(s *tk.CodeAreaState) {
s.Buffer.Dot = dot
})
return nil
}
getDot := func() any {
return vals.FromGo(codeArea.CopyState().Buffer.Dot)
}
nb.AddVar("-dot", vars.FromSetGet(setDot, getDot))
setCurrentCommand := func(v any) error {
var content string
err := vals.ScanToGo(v, &content)
if err != nil {
return err
}
replaceInput(app, content)
return nil
}
getCurrentCommand := func() any {
return vals.FromGo(codeArea.CopyState().Buffer.Content)
}
nb.AddVar("current-command", vars.FromSetGet(setCurrentCommand, getCurrentCommand))
}