diff --git a/app.go b/app.go index 62e351f1..191f26fa 100644 --- a/app.go +++ b/app.go @@ -31,7 +31,8 @@ type app struct { cmdHistoryBeg int cmdHistoryInd int menuCompActive bool - menuComps []string + menuCompTmp []string + menuComps []compMatch menuCompInd int selectionOut []string watch *watch @@ -670,6 +671,45 @@ func (app *app) runShell(s string, args []string, prefix string) { } } +func (app *app) doComplete() (matches []compMatch) { + var result string + + switch app.ui.cmdPrefix { + case ":": + matches, result = completeCmd(app.ui.cmdAccLeft) + case "$", "%", "!", "&": + matches, result = completeShell(app.ui.cmdAccLeft) + case "/", "?": + matches, result = completeSearch(app.ui.cmdAccLeft) + } + + app.ui.cmdAccLeft = []rune(result) + app.ui.menu = listMatches(app.ui.screen, matches, -1) + return +} + +func (app *app) menuComplete(direction int) { + if !app.menuCompActive { + app.menuCompTmp = tokenize(string(app.ui.cmdAccLeft)) + app.menuComps = app.doComplete() + if len(app.menuComps) > 1 { + app.menuCompInd = -1 + app.menuCompActive = true + } + } else { + app.menuCompInd += direction + if app.menuCompInd == len(app.menuComps) { + app.menuCompInd = 0 + } else if app.menuCompInd < 0 { + app.menuCompInd = len(app.menuComps) - 1 + } + + app.menuCompTmp[len(app.menuCompTmp)-1] = app.menuComps[app.menuCompInd].result + app.ui.cmdAccLeft = []rune(strings.Join(app.menuCompTmp, " ")) + } + app.ui.menu = listMatches(app.ui.screen, app.menuComps, app.menuCompInd) +} + func (app *app) watchDir(dir *dir) { if !gOpts.watch { return diff --git a/complete.go b/complete.go index 3e90ef9f..12b901a7 100644 --- a/complete.go +++ b/complete.go @@ -2,6 +2,7 @@ package main import ( "log" + "maps" "os" "path/filepath" "reflect" @@ -159,50 +160,164 @@ func getLocalOptWords(localOpts any) (localOptWords []string) { return } -func matchLongest(s1, s2 []rune) []rune { +func commonPrefix(s1, s2 string) string { + r1 := []rune(s1) + r2 := []rune(s2) + i := 0 - for ; i < len(s1) && i < len(s2); i++ { - if s1[i] != s2[i] { + for ; i < len(r1) && i < len(r2); i++ { + if r1[i] != r2[i] { break } } - return s1[:i] + + return string(r1[:i]) } -func matchWord(s string, words []string) (matches []string, longest []rune) { +type compMatch struct { + name string // display name in completion menu + result string // result when cycling through completion menu +} + +func matchWord(s string, words []string) (matches []compMatch, result string) { for _, w := range words { if !strings.HasPrefix(w, s) { continue } - matches = append(matches, w) - if len(longest) != 0 { - longest = matchLongest(longest, []rune(w)) - } else if s != "" { - longest = []rune(w + " ") + matches = append(matches, compMatch{w, w}) + if len(matches) == 1 { + result = w + } else { + result = commonPrefix(result, w) } } - if len(longest) == 0 { - longest = []rune(s) + switch len(matches) { + case 0: + result = s + case 1: + result += " " } - return } -func matchExec(s string) (matches []string, longest []rune) { - var words []string +func matchList(s string, words []string) (matches []compMatch, result string) { + toks := strings.Split(s, ":") - paths := strings.Split(envPath, string(filepath.ListSeparator)) - - for _, p := range paths { - if _, err := os.Stat(p); os.IsNotExist(err) { + for _, w := range words { + if slices.Contains(toks[:len(toks)-1], w) || !strings.HasPrefix(w, toks[len(toks)-1]) { continue } + matchResult := strings.Join(append(slices.Clone(toks[:len(toks)-1]), w), ":") + matches = append(matches, compMatch{w, matchResult}) + + if len(matches) == 1 { + result = matchResult + } else { + result = commonPrefix(result, matchResult) + } + } + + switch len(matches) { + case 0: + result = s + case 1: + if result == s { + result += " " + } + } + return +} + +func matchCmd(s string) (matches []compMatch, result string) { + words := append(gCmdWords, slices.Collect(maps.Keys(gOpts.cmds))...) + slices.Sort(words) + matches, result = matchWord(s, slices.Compact(words)) + return +} + +func matchFile(s string, dirOnly bool, escape func(string) string, unescape func(string) string) (matches []compMatch, result string) { + dir, file := filepath.Split(unescape(replaceTilde(s))) + + d := dir + if dir == "" { + d = "." + } + files, err := os.ReadDir(d) + if err != nil { + log.Printf("reading directory: %s", err) + result = s + return + } + + var commonName string + + for _, f := range files { + isDir := false + if f.IsDir() { + isDir = true + } else if f.Type()&os.ModeSymlink != 0 { + if stat, err := os.Stat(filepath.Join(d, f.Name())); err == nil && stat.IsDir() { + isDir = true + } + } + + if !isDir && dirOnly { + continue + } + + if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(file)) { + continue + } + + name := f.Name() + if isDir { + name += string(filepath.Separator) + } + matches = append(matches, compMatch{name, escape(dir + name)}) + + if len(matches) == 1 { + commonName = name + } else { + commonName = commonPrefix(strings.ToLower(commonName), strings.ToLower(name)) + } + } + + switch len(matches) { + case 0: + result = s + case 1: + result = escape(dir + commonName) + if !strings.HasSuffix(commonName, string(filepath.Separator)) { + result += " " + } + default: + result = escape(dir + commonName) + } + return +} + +func matchCmdFile(s string, dirOnly bool) (matches []compMatch, result string) { + matches, result = matchFile(s, dirOnly, cmdEscape, cmdUnescape) + return +} + +func matchShellFile(s string) (matches []compMatch, result string) { + matches, result = matchFile(s, false, shellEscape, shellUnescape) + return +} + +func matchExec(s string) (matches []compMatch, result string) { + var words []string + for _, p := range strings.Split(envPath, string(filepath.ListSeparator)) { files, err := os.ReadDir(p) if err != nil { - log.Printf("reading path: %s", err) + if !os.IsNotExist(err) { + log.Printf("reading path: %s", err) + } + continue } for _, f := range files { @@ -216,232 +331,140 @@ func matchExec(s string) (matches []string, longest []rune) { continue } - if !finfo.Mode().IsRegular() || !isExecutable(finfo) { - continue + if finfo.Mode().IsRegular() && isExecutable(finfo) { + words = append(words, f.Name()) } - - words = append(words, finfo.Name()) } } - if len(words) > 0 { - sort.Strings(words) - - uniq := words[:1] - for i := 1; i < len(words); i++ { - if words[i] != words[i-1] { - uniq = append(uniq, words[i]) - } - } - words = uniq - } - - return matchWord(s, words) + slices.Sort(words) + matches, result = matchWord(s, slices.Compact(words)) + return } -func matchFile(s string) (matches []string, longest []rune) { - dir := replaceTilde(s) - - if !filepath.IsAbs(dir) { - wd, err := os.Getwd() - if err != nil { - log.Printf("getting current directory: %s", err) - } else { - dir = wd + string(filepath.Separator) + dir - } - } - - dir = filepath.Dir(unescape(dir)) - - files, err := os.ReadDir(dir) +func matchSearch(s string) (matches []compMatch, result string) { + files, err := os.ReadDir(".") if err != nil { log.Printf("reading directory: %s", err) - } - - for _, f := range files { - name := filepath.Join(dir, f.Name()) - f, err := os.Lstat(name) - if err != nil { - log.Printf("getting file information: %s", err) - continue - } - - name = strings.ToLower(escape(f.Name())) - _, last := filepath.Split(s) - if !strings.HasPrefix(name, strings.ToLower(last)) { - continue - } - - name = f.Name() - if isRoot(s) || filepath.Base(s) != s { - name = filepath.Join(filepath.Dir(unescape(s)), f.Name()) - } - name = escape(replaceTilde(name)) - - item := f.Name() - if f.Mode().IsDir() { - item += escape(string(filepath.Separator)) - } - matches = append(matches, item) - - if longest == nil { - if f.Mode().IsRegular() { - longest = []rune(name + " ") - } else { - longest = []rune(name + escape(string(filepath.Separator))) - } - } else { - longest = matchLongest(longest, []rune(name)) - } - } - - if len(longest) < len([]rune(s)) { - longest = []rune(s) - } - - return -} - -func matchCmd(s string) (matches []string, longest []rune) { - words := make([]string, 0, len(gCmdWords)+len(gOpts.cmds)) - words = append(words, gCmdWords...) - for c := range gOpts.cmds { - words = append(words, c) - } - sort.Strings(words) - j := 0 - for i := 1; i < len(words); i++ { - if words[j] == words[i] { - continue - } - j++ - words[i], words[j] = words[j], words[i] - } - words = words[:j+1] - matches, longest = matchWord(s, words) - return -} - -func completeCmd(acc []rune) (matches []string, longestAcc []rune) { - s := string(acc) - f := tokenize(s) - - if len(f) == 1 { - matches, longestAcc = matchCmd(s) + result = s return } - longest := []rune(f[len(f)-1]) - - switch f[0] { - case "set": - if len(f) == 2 { - matches, longest = matchWord(f[1], gOptWords) - break - } - if len(f) != 3 { - break - } - switch f[1] { - case "filtermethod", "searchmethod": - matches, longest = matchWord(f[2], []string{"glob", "regex", "text"}) - case "selmode": - matches, longest = matchWord(f[2], []string{"all", "dir"}) - case "sortby": - matches, longest = matchWord(f[2], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"}) - default: - if slices.Contains(gOptWords, f[1]+"!") { - matches, longest = matchWord(f[2], []string{"false", "true"}) - } - } - case "setlocal": - if len(f) == 2 { - matches, longest = matchFile(f[1]) - break - } - if len(f) == 3 { - matches, longest = matchWord(f[2], gLocalOptWords) - break - } - if len(f) != 4 { - break - } - switch f[2] { - case "sortby": - matches, longest = matchWord(f[3], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"}) - default: - if slices.Contains(gLocalOptWords, f[2]+"!") { - matches, longest = matchWord(f[3], []string{"false", "true"}) - } - } - case "map", "nmap", "vmap", "cmap": - if len(f) == 3 { - matches, longest = matchCmd(f[2]) - } - case "cmd": - case "toggle": - matches, longest = matchFile(f[len(f)-1]) - case "cd", "select", "source": - if len(f) == 2 { - matches, longest = matchFile(f[1]) - } - default: - if !slices.Contains(gCmdWords, f[0]) { - matches, longest = matchFile(f[len(f)-1]) - } - } - - longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) - return -} - -func completeFile(acc []rune) (matches []string, longestAcc []rune) { - s := string(acc) - - wd, err := os.Getwd() - if err != nil { - log.Printf("getting current directory: %s", err) - } - - files, err := os.ReadDir(wd) - if err != nil { - log.Printf("reading directory: %s", err) - } - for _, f := range files { if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(s)) { continue } - matches = append(matches, f.Name()) - - if longestAcc == nil { - longestAcc = []rune(f.Name()) + matches = append(matches, compMatch{f.Name(), f.Name()}) + if len(matches) == 1 { + result = f.Name() } else { - longestAcc = matchLongest(longestAcc, []rune(f.Name())) + result = commonPrefix(strings.ToLower(result), strings.ToLower(f.Name())) } } - if len(longestAcc) < len(acc) { - longestAcc = acc + if len(matches) == 0 { + result = s } - return } -func completeShell(acc []rune) (matches []string, longestAcc []rune) { +func completeCmd(acc []rune) (matches []compMatch, result string) { s := string(acc) f := tokenize(s) - var longest []rune + if len(f) == 1 { + matches, result = matchCmd(s) + return + } + + result = f[len(f)-1] + + switch f[0] { + case "set": + if len(f) == 2 { + matches, result = matchWord(f[1], gOptWords) + break + } + if len(f) != 3 { + break + } + switch f[1] { + case "filtermethod", "searchmethod": + matches, result = matchWord(f[2], []string{"glob", "regex", "text"}) + case "info": + matches, result = matchList(f[2], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"}) + case "preserve": + matches, result = matchList(f[2], []string{"mode", "timestamps"}) + case "selmode": + matches, result = matchWord(f[2], []string{"all", "dir"}) + case "sortby": + matches, result = matchWord(f[2], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"}) + default: + if slices.Contains(gOptWords, f[1]+"!") { + matches, result = matchWord(f[2], []string{"false", "true"}) + } + } + case "setlocal": + if len(f) == 3 { + matches, result = matchWord(f[2], gLocalOptWords) + break + } + if len(f) != 4 { + break + } + switch f[2] { + case "info": + matches, result = matchList(f[3], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"}) + case "sortby": + matches, result = matchWord(f[3], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"}) + default: + if slices.Contains(gLocalOptWords, f[2]+"!") { + matches, result = matchWord(f[3], []string{"false", "true"}) + } + } + case "map", "nmap", "vmap", "cmap": + if len(f) == 3 { + matches, result = matchCmd(f[2]) + } + case "cmd": + case "cd": + if len(f) == 2 { + matches, result = matchCmdFile(f[1], true) + } + case "select", "source": + if len(f) == 2 { + matches, result = matchCmdFile(f[1], false) + } + case "toggle": + matches, result = matchCmdFile(f[len(f)-1], false) + default: + if !slices.Contains(gCmdWords, f[0]) { + matches, result = matchCmdFile(f[len(f)-1], false) + } + } + + f[len(f)-1] = result + result = strings.Join(f, " ") + return +} + +func completeShell(acc []rune) (matches []compMatch, result string) { + f := tokenize(string(acc)) switch len(f) { case 1: - matches, longestAcc = matchExec(s) + matches, result = matchExec(f[0]) default: - matches, longest = matchFile(f[len(f)-1]) - longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) + matches, result = matchShellFile(f[len(f)-1]) } + f[len(f)-1] = result + result = strings.Join(f, " ") + return +} + +func completeSearch(acc []rune) (matches []compMatch, result string) { + matches, result = matchSearch(string(acc)) return } diff --git a/complete_test.go b/complete_test.go index 58f45327..03509879 100644 --- a/complete_test.go +++ b/complete_test.go @@ -5,56 +5,6 @@ import ( "testing" ) -func TestMatchLongest(t *testing.T) { - tests := []struct { - s1 string - s2 string - exp string - }{ - {"", "", ""}, - {"", "foo", ""}, - {"foo", "", ""}, - {"foo", "bar", ""}, - {"foo", "foobar", "foo"}, - {"foo", "barfoo", ""}, - {"foobar", "foobaz", "fooba"}, - {"год", "гол", "го"}, - } - - for _, test := range tests { - 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) - } - } -} - -func TestMatchWord(t *testing.T) { - tests := []struct { - s string - words []string - matches []string - longest string - }{ - {"", nil, nil, ""}, - {"", []string{"foo", "bar", "baz"}, []string{"foo", "bar", "baz"}, ""}, - {"fo", []string{"foo", "bar", "baz"}, []string{"foo"}, "foo "}, - {"ba", []string{"foo", "bar", "baz"}, []string{"bar", "baz"}, "ba"}, - {"fo", []string{"bar", "baz"}, nil, "fo"}, - } - - for _, test := range tests { - m, l := matchWord(test.s, test.words) - - if !reflect.DeepEqual(m, test.matches) { - t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m) - } - - 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, ls) - } - } -} - func TestGetOptWords(t *testing.T) { tests := []struct { opts any @@ -92,3 +42,89 @@ func TestGetLocalOptWords(t *testing.T) { } } } + +func TestCommonPrefix(t *testing.T) { + tests := []struct { + s1 string + s2 string + exp string + }{ + {"", "", ""}, + {"", "foo", ""}, + {"foo", "", ""}, + {"foo", "bar", ""}, + {"foo", "foobar", "foo"}, + {"foo", "barfoo", ""}, + {"foobar", "foobaz", "fooba"}, + {"год", "гол", "го"}, + } + + for _, test := range tests { + if got := commonPrefix(test.s1, test.s2); got != test.exp { + t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got) + } + } +} + +func TestMatchWord(t *testing.T) { + tests := []struct { + s string + words []string + matches []compMatch + result string + }{ + {"", nil, nil, ""}, + {"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""}, + {"fo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "}, + {"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"}, + {"fo", []string{"bar", "baz"}, nil, "fo"}, + } + + for _, test := range tests { + matches, result := matchWord(test.s, test.words) + + if !reflect.DeepEqual(matches, test.matches) { + t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches) + } + + if result != test.result { + t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result) + } + } +} + +func TestMatchList(t *testing.T) { + tests := []struct { + s string + words []string + matches []compMatch + result string + }{ + {"", nil, nil, ""}, + {"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""}, + {"f", []string{"bar", "baz"}, nil, "f"}, + {"f", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo"}, + {"b", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"}, + {"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"}, + {"foo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "}, + {"foo:", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "foo:bar"}, {"baz", "foo:baz"}}, "foo:ba"}, + {"foo:f", []string{"foo", "bar", "baz"}, nil, "foo:f"}, + {"foo:b", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "foo:bar"}, {"baz", "foo:baz"}}, "foo:ba"}, + {"foo:ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "foo:bar"}, {"baz", "foo:baz"}}, "foo:ba"}, + {"bar:b", []string{"foo", "bar", "baz"}, []compMatch{{"baz", "bar:baz"}}, "bar:baz"}, + {"bar:f", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "bar:foo"}}, "bar:foo"}, + {"bar:foo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "bar:foo"}}, "bar:foo "}, + } + + for _, test := range tests { + matches, result := matchList(test.s, test.words) + + if !reflect.DeepEqual(matches, test.matches) { + t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches) + } + + if result != test.result { + t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result) + } + } +} diff --git a/eval.go b/eval.go index 0ff84c7d..7165c253 100644 --- a/eval.go +++ b/eval.go @@ -701,54 +701,6 @@ func splitKeys(s string) (keys []string) { return } -func doComplete(app *app) (matches []string) { - switch app.ui.cmdPrefix { - case ":": - matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdAccLeft) - case "/", "?": - matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdAccLeft) - case "$", "%", "!", "&": - matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdAccLeft) - } - return -} - -func menuComplete(app *app, dir int) { - if !app.menuCompActive { - toks := tokenize(string(app.ui.cmdAccLeft)) - for i, tok := range toks { - toks[i] = replaceTilde(tok) - } - app.ui.cmdAccLeft = []rune(strings.Join(toks, " ")) - app.ui.cmdTmp = app.ui.cmdAccLeft - app.menuComps = doComplete(app) - if len(app.menuComps) > 1 { - app.menuCompInd = -1 - app.menuCompActive = true - } - } else { - app.menuCompInd += dir - if app.menuCompInd == len(app.menuComps) { - app.menuCompInd = 0 - } else if app.menuCompInd < 0 { - app.menuCompInd = len(app.menuComps) - 1 - } - - comp := app.menuComps[app.menuCompInd] - toks := tokenize(string(app.ui.cmdTmp)) - last := toks[len(toks)-1] - - if app.ui.cmdPrefix != "/" && app.ui.cmdPrefix != "?" { - comp = escape(comp) - _, last = filepath.Split(last) - } - - ind := len(app.ui.cmdTmp) - len([]rune(last)) - app.ui.cmdAccLeft = append(app.ui.cmdTmp[:ind], []rune(comp)...) - } - app.ui.menu = listMatches(app.ui.screen, app.menuComps, app.menuCompInd) -} - func update(app *app) { app.ui.menu = "" app.menuCompActive = false @@ -1990,12 +1942,11 @@ func (e *callExpr) eval(app *app, args []string) { } normal(app) case "cmd-complete": - matches := doComplete(app) - app.ui.menu = listMatches(app.ui.screen, matches, -1) + app.doComplete() case "cmd-menu-complete": - menuComplete(app, 1) + app.menuComplete(1) case "cmd-menu-complete-back": - menuComplete(app, -1) + app.menuComplete(-1) case "cmd-menu-accept": app.ui.menu = "" app.menuCompActive = false diff --git a/lfrc b/lfrc new file mode 100644 index 00000000..b4416938 --- /dev/null +++ b/lfrc @@ -0,0 +1,2 @@ +cmap cmd-menu-complete +cmap cmd-menu-complete-back diff --git a/misc.go b/misc.go index 6c362daf..c7515b35 100644 --- a/misc.go +++ b/misc.go @@ -78,7 +78,7 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune { // This function is used to escape whitespaces and special characters with // backslashes in a given string. -func escape(s string) string { +func cmdEscape(s string) string { buf := make([]rune, 0, len(s)) for _, r := range s { if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' { @@ -91,7 +91,7 @@ func escape(s string) string { // This function is used to remove backslashes that are used to escape // whitespaces and special characters in a given string. -func unescape(s string) string { +func cmdUnescape(s string) string { esc := false buf := make([]rune, 0, len(s)) for _, r := range s { @@ -117,27 +117,28 @@ func unescape(s string) string { } // This function splits the given string by whitespaces. It is aware of escaped -// whitespaces so that they are not split unintentionally. +// and quoted whitespaces so that they are not split unintentionally. func tokenize(s string) []string { esc := false + quote := false var buf []rune var toks []string for _, r := range s { - if r == '\\' { - esc = true - buf = append(buf, r) - continue - } - if esc { + switch { + case esc: esc = false buf = append(buf, r) - continue - } - if !unicode.IsSpace(r) { + case r == '\\': + esc = true buf = append(buf, r) - } else { + case r == '"': + quote = !quote + buf = append(buf, r) + case unicode.IsSpace(r) && !quote: toks = append(toks, string(buf)) buf = nil + default: + buf = append(buf, r) } } return append(toks, string(buf)) diff --git a/misc_test.go b/misc_test.go index ddf89412..c338535c 100644 --- a/misc_test.go +++ b/misc_test.go @@ -128,7 +128,7 @@ func TestRuneSliceWidthLastRange(t *testing.T) { } } -func TestEscape(t *testing.T) { +func TestCmdEscape(t *testing.T) { tests := []struct { s string exp string @@ -147,13 +147,13 @@ func TestEscape(t *testing.T) { } for _, test := range tests { - if got := escape(test.s); !reflect.DeepEqual(got, test.exp) { + if got := cmdEscape(test.s); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) } } } -func TestUnescape(t *testing.T) { +func TestCmdUnescape(t *testing.T) { tests := []struct { s string exp string @@ -172,7 +172,7 @@ func TestUnescape(t *testing.T) { } for _, test := range tests { - if got := unescape(test.s); !reflect.DeepEqual(got, test.exp) { + if got := cmdUnescape(test.s); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) } } @@ -185,8 +185,17 @@ func TestTokenize(t *testing.T) { }{ {"", []string{""}}, {"foo", []string{"foo"}}, + {`foo\`, []string{`foo\`}}, + {`foo"`, []string{`foo"`}}, {"foo bar", []string{"foo", "bar"}}, + {`foo\ bar`, []string{`foo\ bar`}}, + {`"foo bar"`, []string{`"foo bar"`}}, + {`"foo" "bar"`, []string{`"foo"`, `"bar"`}}, + {`"foo "bar"`, []string{`"foo "bar"`}}, + {`"foo\" bar"`, []string{`"foo\" bar"`}}, + {`\"foo bar\"`, []string{`\"foo`, `bar\"`}}, {`:rename foo\ bar`, []string{":rename", `foo\ bar`}}, + {`!dir "C:\Program Files"`, []string{"!dir", `"C:\Program Files"`}}, } for _, test := range tests { diff --git a/os.go b/os.go index 31899e34..7685e18b 100644 --- a/os.go +++ b/os.go @@ -229,3 +229,31 @@ func errCrossDevice(err error) bool { func quoteString(s string) string { return s } + +func shellEscape(s string) string { + buf := make([]rune, 0, len(s)) + for _, r := range s { + if strings.ContainsRune(" !\"$&'()*,:;<=>?@[\\]^`{|}", r) { + buf = append(buf, '\\') + } + buf = append(buf, r) + } + return string(buf) +} + +func shellUnescape(s string) string { + esc := false + buf := make([]rune, 0, len(s)) + for _, r := range s { + if r == '\\' && !esc { + esc = true + continue + } + esc = false + buf = append(buf, r) + } + if esc { + buf = append(buf, '\\') + } + return string(buf) +} diff --git a/os_windows.go b/os_windows.go index ecf14a49..ab25267a 100644 --- a/os_windows.go +++ b/os_windows.go @@ -223,3 +223,16 @@ func quoteString(s string) string { } return s } + +func shellEscape(s string) string { + for _, r := range s { + if strings.ContainsRune(" !%&'()+,;=[]^`{}~", r) { + return fmt.Sprintf(`"%s"`, s) + } + } + return s +} + +func shellUnescape(s string) string { + return strings.ReplaceAll(s, `"`, "") +} diff --git a/ui.go b/ui.go index 0f29daa4..d677cb6a 100644 --- a/ui.go +++ b/ui.go @@ -658,7 +658,6 @@ type ui struct { cmdAccLeft []rune cmdAccRight []rune cmdYankBuf []rune - cmdTmp []rune keyAcc []rune keyCount []rune styles styleMap @@ -1668,7 +1667,7 @@ func anyKey() { os.Stdin.Read(b) } -func listMatches(screen tcell.Screen, matches []string, selectedInd int) string { +func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) string { mlen := len(matches) if mlen < 2 { return "" @@ -1679,7 +1678,7 @@ func listMatches(screen tcell.Screen, matches []string, selectedInd int) string wtot, _ := screen.Size() wcol := 0 for _, m := range matches { - wcol = max(wcol, len(m)) + wcol = max(wcol, runeSliceWidth([]rune(m.name))) } wcol += gOpts.tabstop - wcol%gOpts.tabstop ncol := max(wtot/wcol, 1) @@ -1688,12 +1687,13 @@ func listMatches(screen tcell.Screen, matches []string, selectedInd int) string for i := 0; i < mlen; { for j := 0; j < ncol && i < mlen; i, j = i+1, j+1 { - target := matches[i] + name := matches[i].name + w := runeSliceWidth([]rune(name)) - if selectedInd == i { - fmt.Fprintf(&b, "\033[7m%s\033[0m%*s", target, wcol-len(target), "") + if i == selectedInd { + fmt.Fprintf(&b, "\033[7m%s\033[0m%*s", name, wcol-w, "") } else { - fmt.Fprintf(&b, "%s%*s", target, wcol-len(target), "") + fmt.Fprintf(&b, "%s%*s", name, wcol-w, "") } } b.WriteByte('\n')