github.com/kolbycrouch/elvish@v0.14.1-0.20210614162631-215b9ac1c423/pkg/edit/state_api.go (about) 1 package edit 2 3 import ( 4 "src.elv.sh/pkg/cli" 5 "src.elv.sh/pkg/cli/tk" 6 "src.elv.sh/pkg/eval" 7 "src.elv.sh/pkg/eval/vals" 8 "src.elv.sh/pkg/eval/vars" 9 ) 10 11 //elvdoc:fn insert-at-dot 12 // 13 // ```elvish 14 // edit:insert-at-dot $text 15 // ``` 16 // 17 // Inserts the given text at the dot, moving the dot after the newly 18 // inserted text. 19 20 func insertAtDot(app cli.App, text string) { 21 app.CodeArea().MutateState(func(s *tk.CodeAreaState) { 22 s.Buffer.InsertAtDot(text) 23 }) 24 } 25 26 //elvdoc:fn replace-input 27 // 28 // ```elvish 29 // edit:replace-input $text 30 // ``` 31 // 32 // Equivalent to assigning `$text` to `$edit:current-command`. 33 34 func replaceInput(app cli.App, text string) { 35 app.CodeArea().MutateState(func(s *tk.CodeAreaState) { 36 s.Buffer = tk.CodeBuffer{Content: text, Dot: len(text)} 37 }) 38 } 39 40 //elvdoc:var -dot 41 // 42 // Contains the current position of the cursor, as a byte position within 43 // `$edit:current-command`. 44 45 //elvdoc:var current-command 46 // 47 // Contains the content of the current input. Setting the variable will 48 // cause the cursor to move to the very end, as if `edit-dot = (count 49 // $edit:current-command)` has been invoked. 50 // 51 // This API is subject to change. 52 53 func initStateAPI(app cli.App, nb eval.NsBuilder) { 54 nb.AddGoFns("<edit>", map[string]interface{}{ 55 "insert-at-dot": func(s string) { insertAtDot(app, s) }, 56 "replace-input": func(s string) { replaceInput(app, s) }, 57 }) 58 59 setDot := func(v interface{}) error { 60 var dot int 61 err := vals.ScanToGo(v, &dot) 62 if err != nil { 63 return err 64 } 65 app.CodeArea().MutateState(func(s *tk.CodeAreaState) { 66 s.Buffer.Dot = dot 67 }) 68 return nil 69 } 70 getDot := func() interface{} { 71 return vals.FromGo(app.CodeArea().CopyState().Buffer.Dot) 72 } 73 nb.Add("-dot", vars.FromSetGet(setDot, getDot)) 74 75 setCurrentCommand := func(v interface{}) error { 76 var content string 77 err := vals.ScanToGo(v, &content) 78 if err != nil { 79 return err 80 } 81 replaceInput(app, content) 82 return nil 83 } 84 getCurrentCommand := func() interface{} { 85 return vals.FromGo(app.CodeArea().CopyState().Buffer.Content) 86 } 87 nb.Add("current-command", vars.FromSetGet(setCurrentCommand, getCurrentCommand)) 88 }