Implement smarter history navigation (#2161)

* Remove unnecessary space in history file

* Refactor history navigation

* Implement smarter history navigation

* Skip duplicate commands in history navigation

* Return to Normal mode if it started from there

* Reset history state when changing prompt

* Update documentation
This commit is contained in:
Joe Lim authored and GitHub committed 2025-09-19 19:44:43 +10:00
1 parent 5e15655539
commit 89ff7b0203
6 files changed
+96 -86

No files matched your search

+26 -36
View File
@@ -15,29 +15,25 @@ import (
"time" "time"
) )
type cmdItem struct {
prefix string
value string
}
type app struct { type app struct {
ui *ui ui *ui
nav *nav nav *nav
ticker *time.Ticker ticker *time.Ticker
quitChan chan struct{} quitChan chan struct{}
cmd *exec.Cmd cmd *exec.Cmd
cmdIn io.WriteCloser cmdIn io.WriteCloser
cmdOutBuf []byte cmdOutBuf []byte
cmdHistory []cmdItem cmdHistory []string
cmdHistoryBeg int cmdHistoryBeg int
cmdHistoryInd int cmdHistoryInd int
menuCompActive bool cmdHistoryInput *string
menuCompTmp []string menuCompActive bool
menuComps []compMatch menuCompTmp []string
menuCompInd int menuComps []compMatch
selectionOut []string menuCompInd int
watch *watch selectionOut []string
quitting bool watch *watch
quitting bool
} }
func newApp(ui *ui, nav *nav) *app { func newApp(ui *ui, nav *nav) *app {
@@ -196,14 +192,11 @@ func (app *app) readHistory() error {
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2) cmd := scanner.Text()
if toks[0] != ":" && toks[0] != "$" && toks[0] != "%" && toks[0] != "!" && toks[0] != "&" { if len(cmd) < 1 || !slices.Contains([]string{":", "$", "!", "%", "&"}, cmd[:1]) {
continue continue
} }
if len(toks) < 2 { app.cmdHistory = append(app.cmdHistory, cmd)
continue
}
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
} }
app.cmdHistoryBeg = len(app.cmdHistory) app.cmdHistoryBeg = len(app.cmdHistory)
@@ -220,8 +213,7 @@ func (app *app) writeHistory() error {
return nil return nil
} }
local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg) local := slices.Clone(app.cmdHistory[app.cmdHistoryBeg:])
copy(local, app.cmdHistory[app.cmdHistoryBeg:])
app.cmdHistory = nil app.cmdHistory = nil
if err := app.readHistory(); err != nil { if err := app.readHistory(); err != nil {
@@ -229,6 +221,9 @@ func (app *app) writeHistory() error {
} }
app.cmdHistory = append(app.cmdHistory, local...) app.cmdHistory = append(app.cmdHistory, local...)
if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
}
if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil { if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err) return fmt.Errorf("creating data directory: %s", err)
@@ -240,13 +235,8 @@ func (app *app) writeHistory() error {
} }
defer f.Close() defer f.Close()
if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
}
for _, cmd := range app.cmdHistory { for _, cmd := range app.cmdHistory {
_, err = fmt.Fprintf(f, "%s %s\n", cmd.prefix, cmd.value) if _, err = fmt.Fprintln(f, cmd); err != nil {
if err != nil {
return fmt.Errorf("writing history file: %s", err) return fmt.Errorf("writing history file: %s", err)
} }
} }
+2 -1
View File
@@ -669,7 +669,8 @@ Interrupt the current shell-pipe command and return to the Normal mode.
## cmd-history-next (default `<c-n>` and `<down>`), cmd-history-prev (default `<c-p>` and `<up>`) ## cmd-history-next (default `<c-n>` and `<down>`), cmd-history-prev (default `<c-p>` and `<up>`)
Go to the next/previous item in the history. Go to the next/previous entry in the command history.
If part of the command is already typed, then only matching entries will be considered, and consecutive duplicate entries are skipped.
## cmd-left (default `<c-b>` and `<left>`), cmd-right (default `<c-f>` and `<right>`) ## cmd-left (default `<c-b>` and `<left>`), cmd-right (default `<c-f>` and `<right>`)
+3 -1
View File
@@ -696,7 +696,9 @@ Interrupt the current shell-pipe command and return to the Normal mode.
cmd-history-next (default <c-n> and <down>), cmd-history-prev (default <c-p> and <up>) cmd-history-next (default <c-n> and <down>), cmd-history-prev (default <c-p> and <up>)
Go to the next/previous item in the history. Go to the next/previous entry in the command history. If part of the
command is already typed, then only matching entries will be considered,
and consecutive duplicate entries are skipped.
cmd-left (default <c-b> and <left>), cmd-right (default <c-f> and <right>) cmd-left (default <c-b> and <left>), cmd-right (default <c-f> and <right>)
+59 -44
View File
@@ -672,9 +672,8 @@ func splitKeys(s string) (keys []string) {
} }
func update(app *app) { func update(app *app) {
app.ui.menu = "" exitCompMenu(app)
app.ui.menuSelect = nil app.cmdHistoryInput = nil
app.menuCompActive = false
switch { switch {
case gOpts.incsearch && app.ui.cmdPrefix == "/": case gOpts.incsearch && app.ui.cmdPrefix == "/":
@@ -755,12 +754,10 @@ func resetIncCmd(app *app) {
func normal(app *app) { func normal(app *app) {
resetIncCmd(app) resetIncCmd(app)
exitCompMenu(app)
app.cmdHistoryInd = 0 app.cmdHistoryInd = 0
app.cmdHistoryInput = nil
app.ui.menu = ""
app.ui.menuSelect = nil
app.menuCompActive = false
app.ui.cmdAccLeft = nil app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
@@ -956,17 +953,24 @@ func insert(app *app, arg string) {
switch arg { switch arg {
case "!", "$", "%", "&": case "!", "$", "%", "&":
app.ui.cmdPrefix = arg app.ui.cmdPrefix = arg
app.cmdHistoryInd = 0
app.cmdHistoryInput = nil
return return
} }
fallthrough fallthrough
default: default:
app.ui.menu = "" exitCompMenu(app)
app.ui.menuSelect = nil app.cmdHistoryInput = nil
app.menuCompActive = false
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
} }
} }
func exitCompMenu(app *app) {
app.ui.menu = ""
app.ui.menuSelect = nil
app.menuCompActive = false
}
func (e *callExpr) eval(app *app, args []string) { func (e *callExpr) eval(app *app, args []string) {
os.Setenv("lf_count", strconv.Itoa(e.count)) os.Setenv("lf_count", strconv.Itoa(e.count))
@@ -1847,25 +1851,19 @@ func (e *callExpr) eval(app *app, args []string) {
case "cmd-menu-complete-back": case "cmd-menu-complete-back":
app.menuComplete(-1) app.menuComplete(-1)
case "cmd-menu-accept": case "cmd-menu-accept":
app.ui.menu = "" exitCompMenu(app)
app.ui.menuSelect = nil
app.menuCompActive = false
case "cmd-menu-discard": case "cmd-menu-discard":
if app.menuCompActive { if app.menuCompActive {
app.ui.cmdAccLeft = []rune(strings.Join(app.menuCompTmp, " ")) app.ui.cmdAccLeft = []rune(strings.Join(app.menuCompTmp, " "))
} }
app.ui.menu = "" exitCompMenu(app)
app.ui.menuSelect = nil
app.menuCompActive = false
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: " && app.ui.cmdPrefix != ">" { if len(s) == 0 && app.ui.cmdPrefix != "filter: " && app.ui.cmdPrefix != ">" {
return return
} }
app.ui.menu = "" exitCompMenu(app)
app.ui.menuSelect = nil
app.menuCompActive = false
app.ui.cmdAccLeft = nil app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
@@ -1873,8 +1871,8 @@ func (e *callExpr) eval(app *app, args []string) {
switch app.ui.cmdPrefix { switch app.ui.cmdPrefix {
case ":": case ":":
log.Printf("command: %s", s) log.Printf("command: %s", s)
app.cmdHistory = append(app.cmdHistory, app.ui.cmdPrefix+s)
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{":", s})
p := newParser(strings.NewReader(s)) p := newParser(strings.NewReader(s))
for p.parse() { for p.parse() {
p.expr.eval(app, nil) p.expr.eval(app, nil)
@@ -1884,25 +1882,25 @@ func (e *callExpr) eval(app *app, args []string) {
} }
case "$": case "$":
log.Printf("shell: %s", s) log.Printf("shell: %s", s)
app.cmdHistory = append(app.cmdHistory, app.ui.cmdPrefix+s)
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{"$", s})
app.runShell(s, nil, "$") app.runShell(s, nil, "$")
case "%": case "%":
log.Printf("shell-pipe: %s", s) log.Printf("shell-pipe: %s", s)
app.cmdHistory = append(app.cmdHistory, cmdItem{"%", s}) app.cmdHistory = append(app.cmdHistory, app.ui.cmdPrefix+s)
app.runShell(s, nil, "%") app.runShell(s, nil, "%")
case ">": case ">":
io.WriteString(app.cmdIn, s+"\n") io.WriteString(app.cmdIn, s+"\n")
app.cmdOutBuf = nil app.cmdOutBuf = nil
case "!": case "!":
log.Printf("shell-wait: %s", s) log.Printf("shell-wait: %s", s)
app.cmdHistory = append(app.cmdHistory, app.ui.cmdPrefix+s)
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{"!", s})
app.runShell(s, nil, "!") app.runShell(s, nil, "!")
case "&": case "&":
log.Printf("shell-async: %s", s) log.Printf("shell-async: %s", s)
app.cmdHistory = append(app.cmdHistory, app.ui.cmdPrefix+s)
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{"&", s})
app.runShell(s, nil, "&") app.runShell(s, nil, "&")
case "/": case "/":
dir := app.nav.currDir() dir := app.nav.currDir()
@@ -2027,33 +2025,48 @@ func (e *callExpr) eval(app *app, args []string) {
if !slices.Contains([]string{":", "$", "!", "%", "&"}, app.ui.cmdPrefix) { if !slices.Contains([]string{":", "$", "!", "%", "&"}, app.ui.cmdPrefix) {
return return
} }
if app.cmdHistoryInd > 0 { input := app.ui.cmdPrefix + string(app.ui.cmdAccLeft)
app.cmdHistoryInd-- if app.cmdHistoryInput == nil {
app.cmdHistoryInput = &input
} }
if app.cmdHistoryInd == 0 { for i := app.cmdHistoryInd - 1; i >= 0; i-- {
normal(app) if i == 0 {
app.ui.cmdPrefix = ":" if *app.cmdHistoryInput == "" {
return normal(app)
} else {
exitCompMenu(app)
app.ui.cmdAccLeft = nil
app.cmdHistoryInd = 0
}
break
}
cmd := app.cmdHistory[len(app.cmdHistory)-i]
if strings.HasPrefix(cmd, *app.cmdHistoryInput) && cmd != input {
exitCompMenu(app)
app.ui.cmdPrefix = cmd[:1]
app.ui.cmdAccLeft = []rune(cmd[1:])
app.cmdHistoryInd = i
break
}
} }
historyInd := app.cmdHistoryInd
cmd := app.cmdHistory[len(app.cmdHistory)-historyInd]
normal(app)
app.cmdHistoryInd = historyInd
app.ui.cmdPrefix = cmd.prefix
app.ui.cmdAccLeft = []rune(cmd.value)
case "cmd-history-prev": case "cmd-history-prev":
if !slices.Contains([]string{":", "$", "!", "%", "&", ""}, app.ui.cmdPrefix) { if !slices.Contains([]string{":", "$", "!", "%", "&", ""}, app.ui.cmdPrefix) {
return return
} }
if app.cmdHistoryInd == len(app.cmdHistory) { input := app.ui.cmdPrefix + string(app.ui.cmdAccLeft)
return if app.cmdHistoryInput == nil {
app.cmdHistoryInput = &input
}
for i := app.cmdHistoryInd + 1; i <= len(app.cmdHistory); i++ {
cmd := app.cmdHistory[len(app.cmdHistory)-i]
if strings.HasPrefix(cmd, *app.cmdHistoryInput) && cmd != input {
exitCompMenu(app)
app.ui.cmdPrefix = cmd[:1]
app.ui.cmdAccLeft = []rune(cmd[1:])
app.cmdHistoryInd = i
break
}
} }
historyInd := app.cmdHistoryInd + 1
cmd := app.cmdHistory[len(app.cmdHistory)-historyInd]
normal(app)
app.cmdHistoryInd = historyInd
app.ui.cmdPrefix = cmd.prefix
app.ui.cmdAccLeft = []rune(cmd.value)
case "cmd-left": case "cmd-left":
if len(app.ui.cmdAccLeft) == 0 { if len(app.ui.cmdAccLeft) == 0 {
return return
@@ -2083,6 +2096,8 @@ func (e *callExpr) eval(app *app, args []string) {
switch app.ui.cmdPrefix { switch app.ui.cmdPrefix {
case "!", "$", "%", "&": case "!", "$", "%", "&":
app.ui.cmdPrefix = ":" app.ui.cmdPrefix = ":"
app.cmdHistoryInd = 0
app.cmdHistoryInput = nil
case ">", "rename: ", "filter: ": case ">", "rename: ", "filter: ":
// Don't mess with programs waiting for input. // Don't mess with programs waiting for input.
// Exiting on backspace is also inconvenient for 'rename' and 'filter', // Exiting on backspace is also inconvenient for 'rename' and 'filter',
+4 -2
View File
@@ -1,6 +1,6 @@
.\" Automatically generated by Pandoc 3.7.0.2 .\" Automatically generated by Pandoc 3.7.0.2
.\" .\"
.TH "LF" "1" "2025\-09\-19" "r38" "DOCUMENTATION" .TH "LF" "1" "2025\-09\-19" "r39" "DOCUMENTATION"
.SH NAME .SH NAME
lf \- terminal file manager lf \- terminal file manager
.SH SYNOPSIS .SH SYNOPSIS
@@ -635,7 +635,9 @@ Execute the current line.
.SS cmd\-interrupt (default \f[CR]<c\-c>\f[R]) .SS cmd\-interrupt (default \f[CR]<c\-c>\f[R])
Interrupt the current shell\-pipe command and return to the Normal mode. Interrupt the current shell\-pipe command and return to the Normal mode.
.SS cmd\-history\-next (default \f[CR]<c\-n>\f[R] and \f[CR]<down>\f[R]), cmd\-history\-prev (default \f[CR]<c\-p>\f[R] and \f[CR]<up>\f[R]) .SS cmd\-history\-next (default \f[CR]<c\-n>\f[R] and \f[CR]<down>\f[R]), cmd\-history\-prev (default \f[CR]<c\-p>\f[R] and \f[CR]<up>\f[R])
Go to the next/previous item in the history. Go to the next/previous entry in the command history.
If part of the command is already typed, then only matching entries will
be considered, and consecutive duplicate entries are skipped.
.SS cmd\-left (default \f[CR]<c\-b>\f[R] and \f[CR]<left>\f[R]), cmd\-right (default \f[CR]<c\-f>\f[R] and \f[CR]<right>\f[R]) .SS cmd\-left (default \f[CR]<c\-b>\f[R] and \f[CR]<left>\f[R]), cmd\-right (default \f[CR]<c\-f>\f[R] and \f[CR]<right>\f[R])
Move the cursor to the left/right. Move the cursor to the left/right.
.SS cmd\-home (default \f[CR]<c\-a>\f[R] and \f[CR]<home>\f[R]), cmd\-end (default \f[CR]<c\-e>\f[R] and \f[CR]<end>\f[R]) .SS cmd\-home (default \f[CR]<c\-a>\f[R] and \f[CR]<home>\f[R]), cmd\-end (default \f[CR]<c\-e>\f[R] and \f[CR]<end>\f[R])
+2 -2
View File
@@ -1267,7 +1267,7 @@ func listJumps(jumps []string, ind int) string {
return b.String() return b.String()
} }
func listHistory(history []cmdItem) string { func listHistory(history []string) string {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
@@ -1276,7 +1276,7 @@ func listHistory(history []cmdItem) string {
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "number\tcommand") fmt.Fprintln(t, "number\tcommand")
for i, cmd := range history { for i, cmd := range history {
fmt.Fprintf(t, "%*d\t%s%s\n", maxlength, i+1, cmd.prefix, cmd.value) fmt.Fprintf(t, "%*d\t%s\n", maxlength, i+1, cmd)
} }
t.Flush() t.Flush()