github.com/jmigpin/editor@v1.6.0/core/findshortcut.go (about)

     1  package core
     2  
     3  import (
     4  	"bytes"
     5  	"strconv"
     6  
     7  	"github.com/jmigpin/editor/core/toolbarparser"
     8  )
     9  
    10  func FindShortcut(erow *ERow) {
    11  	updateToolbarPartCmd(erow, "Find")
    12  }
    13  func ReplaceShortcut(erow *ERow) {
    14  	updateToolbarPartCmd(erow, "Replace")
    15  }
    16  func NewFileShortcut(erow *ERow) {
    17  	updateToolbarPartCmd(erow, "NewFile")
    18  }
    19  
    20  //----------
    21  
    22  // Search/add toolbar command and warps the pointer to it. Also inserts selected text as argument if available.
    23  func updateToolbarPartCmd(erow *ERow, cmd string) {
    24  	if err := updateToolbarPartCmd2(erow, cmd); err != nil {
    25  		erow.Ed.Error(err)
    26  	}
    27  }
    28  func updateToolbarPartCmd2(erow *ERow, cmd string) error {
    29  	// modify toolbar text
    30  	arg := erowTextSelection(erow)
    31  	res := toolbarparser.UpdateOrInsertPartCmd(&erow.TbData, cmd, arg)
    32  
    33  	// update toolbar text
    34  	tb := erow.Row.Toolbar
    35  	if err := tb.SetStr(res.S); err != nil {
    36  		return err
    37  	}
    38  
    39  	// update cursor position
    40  	c := tb.Cursor()
    41  	c.SetIndex(res.Pos)
    42  	c.UpdateSelection(true, res.End)
    43  
    44  	// warp pointer to toolbar close to added text
    45  	p := tb.GetPoint(tb.CursorIndex())
    46  	p.Y += tb.LineHeight() * 3 / 4 // center of rune
    47  	erow.Ed.UI.WarpPointer(p)
    48  
    49  	return nil
    50  }
    51  func erowTextSelection(erow *ERow) string {
    52  	ta := erow.Row.TextArea
    53  	text := []byte{}
    54  	// check if there is a selection in the textarea
    55  	if sel, ok := ta.EditCtx().Selection(); ok {
    56  		// don't use if selection has more then one line
    57  		if !bytes.ContainsRune(sel, '\n') {
    58  			text = sel
    59  			// quote if it has spaces
    60  			if bytes.ContainsRune(text, ' ') {
    61  				text = []byte(strconv.Quote(string(text)))
    62  			}
    63  		}
    64  	}
    65  	return string(text)
    66  }