github.com/elves/elvish@v0.15.0/pkg/edit/state_api.go (about)

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