Skip to content

Commit

Permalink
Fix meta-left and meta-right word navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
Verseth committed Jul 7, 2023
1 parent 194a198 commit 049ed01
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
31 changes: 31 additions & 0 deletions document.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/elk-language/go-prompt/internal/bisect"
istrings "github.com/elk-language/go-prompt/internal/strings"
runewidth "github.com/mattn/go-runewidth"
"golang.org/x/exp/utf8string"
)

Expand Down Expand Up @@ -132,6 +133,13 @@ func (d *Document) FindStartOfPreviousWord() int {
return 0
}

// Returns the string width (as visible in the terminal)
// of the text before the cursor until the start of the previous word.
func (d *Document) FindStringWidthUntilStartOfPreviousWord() int {
x := d.TextBeforeCursor()
return runewidth.StringWidth(x[d.FindStartOfPreviousWordWithSpace():])
}

// FindStartOfPreviousWordWithSpace is almost the same as FindStartOfPreviousWord.
// The only difference is to ignore contiguous spaces.
func (d *Document) FindStartOfPreviousWordWithSpace() int {
Expand Down Expand Up @@ -211,6 +219,29 @@ func (d *Document) FindEndOfCurrentWordWithSpace() int {
return start + end
}

// Returns the string width (as visible in the terminal)
// of the text after the cursor until the end of the current word.
func (d *Document) FindStringWidthUntilEndOfCurrentWord() int {
t := d.TextAfterCursor()
width := 0
nonSpaceCharSeen := false
for _, char := range t {
if !nonSpaceCharSeen && char == ' ' {
width += 1
continue
}

if nonSpaceCharSeen && char == ' ' {
break
}

nonSpaceCharSeen = true
width += runewidth.RuneWidth(char)
}

return width
}

// FindEndOfCurrentWordUntilSeparator is almost the same as FindEndOfCurrentWord.
// But this can specify Separator. Return 0 if nothing was found.
func (d *Document) FindEndOfCurrentWordUntilSeparator(sep string) int {
Expand Down
4 changes: 2 additions & 2 deletions emacs.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ var emacsKeyBindings = []KeyBind{
{
Key: AltRight,
Fn: func(buf *Buffer) {
buf.CursorRight(buf.Document().FindEndOfCurrentWordWithSpace())
buf.CursorRight(buf.Document().FindStringWidthUntilEndOfCurrentWord())
},
},
// Left allow: Backward one character
Expand All @@ -112,7 +112,7 @@ var emacsKeyBindings = []KeyBind{
{
Key: AltLeft,
Fn: func(buf *Buffer) {
buf.CursorLeft(len([]rune(buf.Document().TextBeforeCursor())) - buf.Document().FindStartOfPreviousWordWithSpace())
buf.CursorLeft(buf.Document().FindStringWidthUntilStartOfPreviousWord())
},
},
// Cut the Word before the cursor.
Expand Down

0 comments on commit 049ed01

Please sign in to comment.