readline: Automatically do word completion based on history

This commit is contained in:
Kovid Goyal
2023-03-07 16:44:02 +05:30
parent 4cef83ffd0
commit 0e73c01093
5 changed files with 85 additions and 5 deletions

View File

@@ -156,6 +156,9 @@ func New(loop *loop.Loop, r RlInit) *Readline {
completions: completions{completer: r.Completer},
kill_ring: kill_ring{items: list.New().Init()},
}
if ans.completions.completer == nil && r.HistoryPath != "" {
ans.completions.completer = ans.HistoryCompleter
}
ans.prompt = ans.make_prompt(r.Prompt, false)
t := ""
if r.ContinuationPrompt != "" || !r.EmptyContinuationPrompt {
@@ -168,6 +171,10 @@ func New(loop *loop.Loop, r RlInit) *Readline {
return ans
}
func (self *Readline) HistoryCompleter(before_cursor, after_cursor string) *cli.Completions {
return self.history_completer(before_cursor, after_cursor)
}
func (self *Readline) SetPrompt(prompt string) {
self.prompt = self.make_prompt(prompt, false)
}

View File

@@ -7,6 +7,7 @@ import (
"strings"
"kitty/tools/cli"
"kitty/tools/tty"
"kitty/tools/utils"
"kitty/tools/wcswidth"
)
@@ -63,6 +64,8 @@ type completions struct {
current completion
}
var _ = tty.DebugPrintln
func (self *Readline) complete(forwards bool, repeat_count uint) bool {
c := &self.completions
if c.completer == nil {

View File

@@ -10,6 +10,8 @@ import (
"strings"
"time"
"kitty/tools/cli"
"kitty/tools/tty"
"kitty/tools/utils"
"kitty/tools/utils/shlex"
"kitty/tools/wcswidth"
@@ -396,3 +398,37 @@ func (self *Readline) history_search_prompt() string {
}
return fmt.Sprintf("history %s: ", ans)
}
var _ = tty.DebugPrintln
func (self *Readline) history_completer(before_cursor, after_cursor string) (ans *cli.Completions) {
ans = cli.NewCompletions()
if before_cursor != "" {
var words_before_cursor []string
words_before_cursor, ans.CurrentWordIdx = shlex.SplitForCompletion(before_cursor)
idx := len(words_before_cursor)
if idx > 0 {
idx--
}
seen := utils.NewSet[string](16)
mg := ans.AddMatchGroup("History")
for _, x := range self.history.items {
if strings.HasPrefix(x.Cmd, before_cursor) {
words, _ := shlex.SplitForCompletion(x.Cmd)
if idx < len(words) {
word := words[idx]
desc := ""
if !seen.Has(word) {
if word != x.Cmd {
desc = x.Cmd
}
mg.AddMatch(word, desc)
seen.Add(word)
}
}
}
}
}
return
}