Fix a few completion bugs and add a few small features (#934)

* Fix some multibyte character completion bugs

- matchLongest now operates on runes instead of bytes so we don't
  complete part of a multibyte character.
- Fix some places that mixed string and rune slice indices.

* Fix wrong menu completion for subdirectories

When selecting a menu completion for a file in a subdirectory, the
entire filename would be appended to the command line, even if you had
already typed part of it.

* Escape file completions in menu completion

* Minor refactors and typo fixes

* Fix cmd-menu-complete-back bug

The first use of cmd-menu-complete-back after opening the completion
menu was incorrectly selecting the before-last completion instead of the
last completion.

* Allow completing broken symlinks

Also skip files with stat errors instead of returning.

* Add command to accept current menu selection

This is useful when completing filenames. For example

    cmap <c-y> :cmd-menu-accept; cmd-menu-complete

can be used to accept the selected directory completion, then complete
files in the directory.

* Complete command names for map and cmap
This commit is contained in:
Paul Ouellette authored and GitHub committed 2022-10-01 16:31:58 +03:00
1 parent 5ba70d0f61
commit cb7aa13218
8 files changed
+128 -91

No files matched your search

+83 -52
View File
@@ -77,6 +77,33 @@ var (
"mark-remove", "mark-remove",
"tag", "tag",
"tag-toggle", "tag-toggle",
"cmd-escape",
"cmd-complete",
"cmd-menu-complete",
"cmd-menu-complete-back",
"cmd-menu-accept",
"cmd-enter",
"cmd-interrupt",
"cmd-history-next",
"cmd-history-prev",
"cmd-left",
"cmd-right",
"cmd-home",
"cmd-end",
"cmd-delete",
"cmd-delete-back",
"cmd-delete-home",
"cmd-delete-end",
"cmd-delete-unix-word",
"cmd-yank",
"cmd-transpose",
"cmd-transpose-word",
"cmd-word",
"cmd-word-back",
"cmd-delete-word",
"cmd-capitalize-word",
"cmd-uppercase-word",
"cmd-lowercase-word",
} }
gOptWords = []string{ gOptWords = []string{
@@ -177,7 +204,7 @@ var (
} }
) )
func matchLongest(s1, s2 string) string { func matchLongest(s1, s2 []rune) []rune {
i := 0 i := 0
for ; i < len(s1) && i < len(s2); i++ { for ; i < len(s1) && i < len(s2); i++ {
if s1[i] != s2[i] { if s1[i] != s2[i] {
@@ -187,28 +214,28 @@ func matchLongest(s1, s2 string) string {
return s1[:i] return s1[:i]
} }
func matchWord(s string, words []string) (matches []string, longest string) { func matchWord(s string, words []string) (matches []string, longest []rune) {
for _, w := range words { for _, w := range words {
if !strings.HasPrefix(w, s) { if !strings.HasPrefix(w, s) {
continue continue
} }
matches = append(matches, w) matches = append(matches, w)
if longest != "" { if len(longest) != 0 {
longest = matchLongest(longest, w) longest = matchLongest(longest, []rune(w))
} else if s != "" { } else if s != "" {
longest = w + " " longest = []rune(w + " ")
} }
} }
if longest == "" { if len(longest) == 0 {
longest = s longest = []rune(s)
} }
return return
} }
func matchExec(s string) (matches []string, longest string) { func matchExec(s string) (matches []string, longest []rune) {
var words []string var words []string
paths := strings.Split(envPath, string(filepath.ListSeparator)) paths := strings.Split(envPath, string(filepath.ListSeparator))
@@ -258,7 +285,8 @@ func matchExec(s string) (matches []string, longest string) {
return matchWord(s, words) return matchWord(s, words)
} }
func matchFile(s string) (matches []string, longest string) { func matchFile(s string) (matches []string, longest []rune) {
s = unescape(s)
dir := replaceTilde(s) dir := replaceTilde(s)
if !filepath.IsAbs(dir) { if !filepath.IsAbs(dir) {
@@ -270,7 +298,7 @@ func matchFile(s string) (matches []string, longest string) {
} }
} }
dir = unescape(filepath.Dir(dir)) dir = filepath.Dir(dir)
files, err := ioutil.ReadDir(dir) files, err := ioutil.ReadDir(dir)
if err != nil { if err != nil {
@@ -279,25 +307,20 @@ func matchFile(s string) (matches []string, longest string) {
for _, f := range files { for _, f := range files {
name := filepath.Join(dir, f.Name()) name := filepath.Join(dir, f.Name())
f, err := os.Stat(name) f, err := os.Lstat(name)
if err != nil { if err != nil {
fl, err := os.Lstat(name)
if err == nil && fl.Mode()&os.ModeSymlink != 0 {
continue
} else {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
return continue
}
} }
_, last := filepath.Split(s) _, last := filepath.Split(s)
if !strings.HasPrefix(escape(f.Name()), last) { if !strings.HasPrefix(f.Name(), last) {
continue continue
} }
name = f.Name() name = f.Name()
if isRoot(s) || filepath.Base(s) != s { if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(unescape(s)), f.Name()) name = filepath.Join(filepath.Dir(s), f.Name())
} }
name = escape(name) name = escape(name)
@@ -307,32 +330,25 @@ func matchFile(s string) (matches []string, longest string) {
} }
matches = append(matches, item) matches = append(matches, item)
if longest != "" { if len(longest) != 0 {
longest = matchLongest(longest, name) longest = matchLongest(longest, []rune(name))
} else if s != "" { } else if s != "" {
if f.Mode().IsRegular() { if f.Mode().IsRegular() {
longest = name + " " longest = []rune(name + " ")
} else { } else {
longest = name + escape(string(filepath.Separator)) longest = []rune(name + escape(string(filepath.Separator)))
} }
} }
} }
if longest == "" { if len(longest) == 0 {
longest = s longest = []rune(s)
} }
return return
} }
func completeCmd(acc []rune) (matches []string, longestAcc []rune) { func matchCmd(s string) (matches []string, longest []rune) {
s := string(acc)
f := tokenize(s)
var longest string
switch len(f) {
case 1:
words := gCmdWords words := gCmdWords
for c := range gOpts.cmds { for c := range gOpts.cmds {
words = append(words, c) words = append(words, c)
@@ -348,25 +364,45 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
} }
words = words[:j+1] words = words[:j+1]
matches, longest = matchWord(s, words) matches, longest = matchWord(s, words)
longestAcc = []rune(longest) return
}
func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
var longest []rune
switch len(f) {
case 1:
matches, longestAcc = matchCmd(s)
case 2: case 2:
switch f[0] { switch f[0] {
case "set": case "set":
matches, longest = matchWord(f[1], gOptWords) matches, longest = matchWord(f[1], gOptWords)
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
case "map", "cmd": case "map", "cmap", "cmd":
longestAcc = acc longestAcc = acc
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
}
case 3:
switch f[0] {
case "map", "cmap":
matches, longest = matchCmd(f[2])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
default: default:
switch f[0] { switch f[0] {
case "set", "map", "cmd": case "set", "map", "cmap", "cmd":
longestAcc = acc longestAcc = acc
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
} }
@@ -386,8 +422,6 @@ func completeFile(acc []rune) (matches []string, longestAcc []rune) {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} }
var longest string
for _, f := range files { for _, f := range files {
if !strings.HasPrefix(f.Name(), s) { if !strings.HasPrefix(f.Name(), s) {
continue continue
@@ -395,19 +429,17 @@ func completeFile(acc []rune) (matches []string, longestAcc []rune) {
matches = append(matches, f.Name()) matches = append(matches, f.Name())
if longest != "" { if len(longestAcc) != 0 {
longest = matchLongest(longest, f.Name()) longestAcc = matchLongest(longestAcc, []rune(f.Name()))
} else if s != "" { } else if s != "" {
longest = f.Name() longestAcc = []rune(f.Name())
} }
} }
if longest == "" { if len(longestAcc) == 0 {
longest = s longestAcc = acc
} }
longestAcc = []rune(longest)
return return
} }
@@ -415,15 +447,14 @@ func completeShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
var longest string var longest []rune
switch len(f) { switch len(f) {
case 1: case 1:
matches, longest = matchExec(s) matches, longestAcc = matchExec(s)
longestAcc = []rune(longest)
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
return return
+4 -3
View File
@@ -18,10 +18,11 @@ func TestMatchLongest(t *testing.T) {
{"foo", "foobar", "foo"}, {"foo", "foobar", "foo"},
{"foo", "barfoo", ""}, {"foo", "barfoo", ""},
{"foobar", "foobaz", "fooba"}, {"foobar", "foobaz", "fooba"},
{"год", "гол", "го"},
} }
for _, test := range tests { for _, test := range tests {
if got := matchLongest(test.s1, test.s2); got != test.exp { if got := string(matchLongest([]rune(test.s1), []rune(test.s2))); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got) t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got)
} }
} }
@@ -48,8 +49,8 @@ func TestMatchWord(t *testing.T) {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m) t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m)
} }
if l != test.longest { if ls := string(l); ls != test.longest {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, l) t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, ls)
} }
} }
} }
+5
View File
@@ -85,6 +85,7 @@ The following command line commands are provided by lf:
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-menu-complete cmd-menu-complete
cmd-menu-complete-back cmd-menu-complete-back
cmd-menu-accept
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
@@ -492,6 +493,10 @@ Autocomplete the current word with menu selection.
You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back'). You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back').
You can use the assigned keys assigned to display the menu and then cycle through completion options. You can use the assigned keys assigned to display the menu and then cycle through completion options.
cmd-menu-accept
Accept the currently selected match in menu completion and close the menu.
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
Execute the current line. Execute the current line.
+5
View File
@@ -89,6 +89,7 @@ The following command line commands are provided by lf:
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-menu-complete cmd-menu-complete
cmd-menu-complete-back cmd-menu-complete-back
cmd-menu-accept
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
@@ -520,6 +521,10 @@ to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab>
cmd-menu-complete-back'). You can use the assigned keys assigned to display cmd-menu-complete-back'). You can use the assigned keys assigned to display
the menu and then cycle through completion options. the menu and then cycle through completion options.
cmd-menu-accept
Accept the currently selected match in menu completion and close the menu.
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
Execute the current line. Execute the current line.
+18 -27
View File
@@ -1587,7 +1587,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
// Reset the completition menu as in bash/vim // Reset the completion menu as in bash/vim
// and update the pertinent variables // and update the pertinent variables
if app.ui.menuBuf != nil { if app.ui.menuBuf != nil {
app.ui.menuBuf = nil app.ui.menuBuf = nil
@@ -1628,27 +1628,21 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.menuBuf = b app.ui.menuBuf = b
} }
case "cmd-menu-complete": case "cmd-menu-complete":
var target []rune
// target will store the current menu query
// note that, as we will store the current selected value // note that, as we will store the current selected value
// in cmdAccLeft, we can not call the complete function with its // in cmdAccLeft, we can not call the complete function with its
// value, as it is already a final completition result // value, as it is already a final completion result
if app.ui.menuBuf == nil { if app.ui.menuBuf == nil {
target = app.ui.cmdAccLeft
app.ui.cmdTmp = app.ui.cmdAccLeft app.ui.cmdTmp = app.ui.cmdAccLeft
} else {
target = app.ui.cmdTmp
} }
var matches []string var matches []string
switch app.ui.cmdPrefix { switch app.ui.cmdPrefix {
case ":": case ":":
matches, app.ui.cmdAccLeft = completeCmd(target) matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdTmp)
case "/", "?": case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(target) matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdTmp)
case "$", "%", "!", "&": case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(target) matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdTmp)
default: default:
return return
} }
@@ -1656,13 +1650,12 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.draw(app.nav) app.ui.draw(app.nav)
if len(matches) > 1 { if len(matches) > 1 {
step := 1 // Check if the tab-selection was inited
// Check if the tab-selecttion was inited
if app.ui.menuSelected == -2 { if app.ui.menuSelected == -2 {
app.ui.menuSelected = -1 app.ui.menuSelected = -1
} else { } else {
app.ui.menuSelected = mod(app.ui.menuSelected+step, len(matches)) app.ui.menuSelected++
app.ui.menuSelected %= len(matches)
} }
if err := listMatchesMenu(app.ui, matches); err != nil { if err := listMatchesMenu(app.ui, matches); err != nil {
@@ -1673,23 +1666,18 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.menuSelected = -2 app.ui.menuSelected = -2
} }
case "cmd-menu-complete-back": case "cmd-menu-complete-back":
var target []rune
if app.ui.menuBuf == nil { if app.ui.menuBuf == nil {
target = app.ui.cmdAccLeft
app.ui.cmdTmp = app.ui.cmdAccLeft app.ui.cmdTmp = app.ui.cmdAccLeft
} else {
target = app.ui.cmdTmp
} }
var matches []string var matches []string
switch app.ui.cmdPrefix { switch app.ui.cmdPrefix {
case ":": case ":":
matches, app.ui.cmdAccLeft = completeCmd(target) matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdTmp)
case "/", "?": case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(target) matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdTmp)
case "$", "%", "!", "&": case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(target) matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdTmp)
default: default:
return return
} }
@@ -1697,13 +1685,13 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.draw(app.nav) app.ui.draw(app.nav)
if len(matches) > 1 { if len(matches) > 1 {
step := -1 // Check if the tab-selection was inited
// Check if the tab-selecttion was inited
if app.ui.menuSelected == -2 { if app.ui.menuSelected == -2 {
app.ui.menuSelected = -1 app.ui.menuSelected = -1
} else if app.ui.menuSelected <= 0 {
app.ui.menuSelected = len(matches) - 1
} else { } else {
app.ui.menuSelected = mod(app.ui.menuSelected+step, len(matches)) app.ui.menuSelected--
} }
if err := listMatchesMenu(app.ui, matches); err != nil { if err := listMatchesMenu(app.ui, matches); err != nil {
@@ -1713,6 +1701,9 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.menuBuf = nil app.ui.menuBuf = nil
app.ui.menuSelected = -2 app.ui.menuSelected = -2
} }
case "cmd-menu-accept":
app.ui.menuBuf = nil
app.ui.menuSelected = -2
case "cmd-enter": case "cmd-enter":
s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...)) s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...))
if len(s) == 0 && app.ui.cmdPrefix != "filter: " { if len(s) == 0 && app.ui.cmdPrefix != "filter: " {
+7
View File
@@ -102,6 +102,7 @@ The following command line commands are provided by lf:
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-menu-complete cmd-menu-complete
cmd-menu-complete-back cmd-menu-complete-back
cmd-menu-accept
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
@@ -600,6 +601,12 @@ Autocomplete the current word.
.PP .PP
Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options. Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options.
.PP .PP
.EX
cmd-menu-accept
.EE
.PP
Accept the currently selected match in menu completion and close the menu.
.PP
.EX .EX
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
.EE .EE
+1 -5
View File
@@ -91,7 +91,7 @@ func unescape(s string) string {
} }
// This function splits the given string by whitespaces. It is aware of escaped // This function splits the given string by whitespaces. It is aware of escaped
// whitespaces so that they are not splitted unintentionally. // whitespaces so that they are not split unintentionally.
func tokenize(s string) []string { func tokenize(s string) []string {
esc := false esc := false
var buf []rune var buf []rune
@@ -295,10 +295,6 @@ func max(a, b int) int {
return b return b
} }
func mod(a, b int) int {
return (a%b + b) % b
}
// We don't need no generic code // We don't need no generic code
// We don't need no type control // We don't need no type control
// No dark templates in compiler // No dark templates in compiler
+5 -4
View File
@@ -1265,13 +1265,14 @@ func listMatchesMenu(ui *ui, matches []string) error {
// Handle menu tab match only if wanted // Handle menu tab match only if wanted
if ui.menuSelected == i { if ui.menuSelected == i {
comp := []rune(escape(target))
toks := tokenize(string(ui.cmdAccLeft)) toks := tokenize(string(ui.cmdAccLeft))
last := toks[len(toks)-1] _, last := filepath.Split(toks[len(toks)-1])
if strings.Contains(target, last) { if last == "" {
ui.cmdAccLeft = append(ui.cmdAccLeft[:len(ui.cmdAccLeft)-len(last)], []rune(target)...) ui.cmdAccLeft = append(ui.cmdAccLeft, comp...)
} else { } else {
ui.cmdAccLeft = append(ui.cmdAccLeft, []rune(target)...) ui.cmdAccLeft = append(ui.cmdAccLeft[:len(ui.cmdAccLeft)-len([]rune(last))], comp...)
} }
target = fmt.Sprintf("\033[7m%s\033[0m%*s", target, wcol-len(target), "") target = fmt.Sprintf("\033[7m%s\033[0m%*s", target, wcol-len(target), "")