diff --git a/complete.go b/complete.go index 44da95e2..494d050f 100644 --- a/complete.go +++ b/complete.go @@ -80,6 +80,7 @@ var ( "mark-remove", "tag", "tag-toggle", + "addcustominfo", "tty-write", "cmd-escape", "cmd-complete", @@ -342,6 +343,8 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) { case "map", "cmap": matches, longest = matchCmd(f[2]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) + case "addcustominfo": + longestAcc = acc default: matches, longest = matchFile(f[len(f)-1]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) diff --git a/doc.md b/doc.md index 3bd1b1db..bab6fcb2 100644 --- a/doc.md +++ b/doc.md @@ -102,6 +102,7 @@ The following commands are provided by lf: mark-remove (modal) (default '"') tag tag-toggle (default 't') + addcustominfo tty-write The following command line commands are provided by lf: @@ -571,6 +572,12 @@ You can define a new tag-clearing command by combining `tag` with `tag-toggle` ( Tag a file with `*` or a single width character given in the argument if the file is untagged, otherwise remove the tag. +## addcustominfo + +Update the `custom` info field of the given file with the given string. +The info string may contain ANSI escape codes to further customize its appearance. +If no info is provided, clear the file's info instead. + ## tty-write Write the given string to the tty. @@ -822,7 +829,8 @@ Apply filter pattern after each keystroke during filtering. ## info ([]string) (default ``) A list of information that is shown for directory items at the right side of the pane. -Currently supported information types are `size`, `time`, `atime`, `ctime`, `perm`, `user` and `group`. +Currently supported information types are `size`, `time`, `atime`, `ctime`, `perm`, `user`, `group` and `custom`. +The `custom` type is empty by default and can be updated using the `addcustominfo` command. Information is only shown when the pane width is more than twice the width of information. ## infotimefmtnew (string) (default `Jan _2 15:04`) @@ -1712,6 +1720,32 @@ Note that all shell commands are possible but `%` and `&` are usually more appro There is also a `pre-cd` command, that works like `on-cd`, but is run before the directory is actually changed. Another related command is `on-load` which gets executed when loading a directory. +# LOADING DIRECTORY + +Similar to `on-cd` there also is `on-load` that when defined runs a shell command after loading a directory. +It works well when combined with `addcustominfo`. + +The following example can be used to display git indicators in the info column: + + cmd on-load &{{ + cd "$(dirname "$1")" || exit 1 + git rev-parse >/dev/null 2>&1 || exit 0 + + cmds="" + + for file in "$@"; do + status=$(git status --porcelain --ignored -- "$file" | cut -c1-2 | head -n1) + + if [ -n "$status" ]; then + cmds="${cmds}addcustominfo ${file} \"$status\"; " + else + cmds="${cmds}addcustominfo ${file} ''; " + fi + done + + lf -remote "send $id :$cmds" + }} + # COLORS lf tries to automatically adapt its colors to the environment. diff --git a/doc.txt b/doc.txt index 424b3ca8..7a2a8478 100644 --- a/doc.txt +++ b/doc.txt @@ -92,6 +92,7 @@ The following commands are provided by lf: mark-remove (modal) (default '"') tag tag-toggle (default 't') + addcustominfo tty-write The following command line commands are provided by lf: @@ -590,6 +591,12 @@ tag-toggle (default t) Tag a file with * or a single width character given in the argument if the file is untagged, otherwise remove the tag. +addcustominfo + +Update the custom info field of the given file with the given string. +The info string may contain ANSI escape codes to further customize its +appearance. If no info is provided, clear the file's info instead. + tty-write Write the given string to the tty. This is useful for sending escape @@ -877,8 +884,10 @@ info ([]string) (default ``) A list of information that is shown for directory items at the right side of the pane. Currently supported information types are size, time, -atime, ctime, perm, user and group. Information is only shown when the -pane width is more than twice the width of information. +atime, ctime, perm, user, group and custom. The custom type is empty by +default and can be updated using the addcustominfo command. Information +is only shown when the pane width is more than twice the width of +information. infotimefmtnew (string) (default Jan _2 15:04) @@ -1929,6 +1938,34 @@ There is also a pre-cd command, that works like on-cd, but is run before the directory is actually changed. Another related command is on-load which gets executed when loading a directory. +LOADING DIRECTORY + +Similar to on-cd there also is on-load that when defined runs a shell +command after loading a directory. It works well when combined with +addcustominfo. + +The following example can be used to display git indicators in the info +column: + + cmd on-load &{{ + cd "$(dirname "$1")" || exit 1 + git rev-parse >/dev/null 2>&1 || exit 0 + + cmds="" + + for file in "$@"; do + status=$(git status --porcelain --ignored -- "$file" | cut -c1-2 | head -n1) + + if [ -n "$status" ]; then + cmds="${cmds}addcustominfo ${file} \"$status\"; " + else + cmds="${cmds}addcustominfo ${file} ''; " + fi + done + + lf -remote "send $id :$cmds" + }} + COLORS lf tries to automatically adapt its colors to the environment. It starts diff --git a/eval.go b/eval.go index 16b9db03..398400d3 100644 --- a/eval.go +++ b/eval.go @@ -268,9 +268,9 @@ func (e *setExpr) eval(app *app, args []string) { toks := strings.Split(e.val, ":") for _, s := range toks { switch s { - case "size", "time", "atime", "ctime", "perm", "user", "group": + case "size", "time", "atime", "ctime", "perm", "user", "group", "custom": default: - app.ui.echoerr("info: should consist of 'size', 'time', 'atime', 'ctime', 'perm', 'user' or 'group' separated with colon") + app.ui.echoerr("info: should consist of 'size', 'time', 'atime', 'ctime', 'perm', 'user', 'group' or 'custom' separated with colon") return } } @@ -502,9 +502,9 @@ func (e *setLocalExpr) eval(app *app, args []string) { toks := strings.Split(e.val, ":") for _, s := range toks { switch s { - case "size", "time", "atime", "ctime", "perm", "user", "group": + case "size", "time", "atime", "ctime", "perm", "user", "group", "custom": default: - app.ui.echoerr("info: should consist of 'size', 'time', 'atime', 'ctime', 'perm', 'user' or 'group' separated with colon") + app.ui.echoerr("info: should consist of 'size', 'time', 'atime', 'ctime', 'perm', 'user', 'group' or 'custom' separated with colon") return } } @@ -2250,6 +2250,48 @@ func (e *callExpr) eval(app *app, args []string) { []rune(string(app.ui.cmdAccLeft)[end2:]), ) update(app) + case "addcustominfo": + var k, v string + switch len(e.args) { + case 1: + k, v = e.args[0], "" + case 2: + k, v = e.args[0], e.args[1] + default: + app.ui.echoerr("addcustominfo: requires either 1 or 2 arguments") + return + } + + path, err := filepath.Abs(replaceTilde(k)) + if err != nil { + app.ui.echoerrf("addcustominfo: %s", err) + return + } + + dir := filepath.Dir(path) + d, ok := app.nav.dirCache[dir] + if !ok { + app.ui.echoerrf("addcustominfo: dir not loaded: %s", dir) + return + } + + var f *file + for _, file := range d.files { + if file.path == path { + f = file + break + } + } + if f == nil { + app.ui.echoerrf("addcustominfo: file not found: %s", path) + return + } + + if len(strings.Trim(v, " ")) == 0 { + f.customInfo = "" + } else { + f.customInfo = v + } default: cmd, ok := gOpts.cmds[e.name] if !ok { diff --git a/lf.1 b/lf.1 index 80059712..6171f150 100644 --- a/lf.1 +++ b/lf.1 @@ -1,6 +1,6 @@ .\" Automatically generated by Pandoc 2.11.4 .\" -.TH "LF" "1" "2025-06-19" "r35-23-gef2fb79" "DOCUMENTATION" +.TH "LF" "1" "2025-06-19" "r35-22-gb76d254" "DOCUMENTATION" .hy .SH NAME .PP @@ -102,6 +102,7 @@ mark-load (modal) (default \[dq]\[aq]\[dq]) mark-remove (modal) (default \[aq]\[dq]\[aq]) tag tag-toggle (default \[aq]t\[aq]) +addcustominfo tty-write \f[R] .fi @@ -629,6 +630,13 @@ with \f[C]tag-toggle\f[R] (i.e. .PP Tag a file with \f[C]*\f[R] or a single width character given in the argument if the file is untagged, otherwise remove the tag. +.SS addcustominfo +.PP +Update the \f[C]custom\f[R] info field of the given file with the given +string. +The info string may contain ANSI escape codes to further customize its +appearance. +If no info is provided, clear the file\[aq]s info instead. .SS tty-write .PP Write the given string to the tty. @@ -897,7 +905,9 @@ A list of information that is shown for directory items at the right side of the pane. Currently supported information types are \f[C]size\f[R], \f[C]time\f[R], \f[C]atime\f[R], \f[C]ctime\f[R], \f[C]perm\f[R], -\f[C]user\f[R] and \f[C]group\f[R]. +\f[C]user\f[R], \f[C]group\f[R] and \f[C]custom\f[R]. +The \f[C]custom\f[R] type is empty by default and can be updated using +the \f[C]addcustominfo\f[R] command. Information is only shown when the pane width is more than twice the width of information. .SS infotimefmtnew (string) (default \f[C]Jan _2 15:04\f[R]) @@ -2202,6 +2212,37 @@ There is also a \f[C]pre-cd\f[R] command, that works like \f[C]on-cd\f[R], but is run before the directory is actually changed. Another related command is \f[C]on-load\f[R] which gets executed when loading a directory. +.SH LOADING DIRECTORY +.PP +Similar to \f[C]on-cd\f[R] there also is \f[C]on-load\f[R] that when +defined runs a shell command after loading a directory. +It works well when combined with \f[C]addcustominfo\f[R]. +.PP +The following example can be used to display git indicators in the info +column: +.IP +.nf +\f[C] +cmd on-load &{{ + cd \[dq]$(dirname \[dq]$1\[dq])\[dq] || exit 1 + git rev-parse >/dev/null 2>&1 || exit 0 + + cmds=\[dq]\[dq] + + for file in \[dq]$\[at]\[dq]; do + status=$(git status --porcelain --ignored -- \[dq]$file\[dq] | cut -c1-2 | head -n1) + + if [ -n \[dq]$status\[dq] ]; then + cmds=\[dq]${cmds}addcustominfo ${file} \[rs]\[dq]$status\[rs]\[dq]; \[dq] + else + cmds=\[dq]${cmds}addcustominfo ${file} \[aq]\[aq]; \[dq] + fi + done + + lf -remote \[dq]send $id :$cmds\[dq] +}} +\f[R] +.fi .SH COLORS .PP lf tries to automatically adapt its colors to the environment. diff --git a/misc.go b/misc.go index 11263dce..b1c2cfdb 100644 --- a/misc.go +++ b/misc.go @@ -10,6 +10,7 @@ import ( "strconv" "strings" "unicode" + "unicode/utf8" "github.com/Xuanwo/go-locale" "github.com/mattn/go-runewidth" @@ -391,6 +392,37 @@ func deletePathRecursive[T any](m map[string]T, path string) { } } +// This function is used to remove style-related ANSI escape sequences from +// a given string. +// +// *Note*: this function is based entirely on `printLength()` and strips only +// style-related escape sequences and the `erase in line` sequence. Other codes +// (e.g., cursor moves), as well as broken escape sequences, aren't removed. +// This prevents mismatches between the two functions and avoids misalignment +// when rendering the UI. +func stripAnsi(s string) string { + var b strings.Builder + slen := len(s) + for i := 0; i < slen; i++ { + r, w := utf8.DecodeRuneInString(s[i:]) + + if r == gEscapeCode && i+1 < slen && s[i+1] == '[' { + j := strings.IndexAny(s[i:min(slen, i+64)], "mK") + if j == -1 { + continue + } + + i += j + continue + } + + i += w - 1 + b.WriteRune(r) + } + + return b.String() +} + // We don't need no generic code // We don't need no type control // No dark templates in compiler diff --git a/misc_test.go b/misc_test.go index 41d6eb96..a1e78759 100644 --- a/misc_test.go +++ b/misc_test.go @@ -386,3 +386,35 @@ func TestLocaleNaturalLess(t *testing.T) { } } } + +func TestStripAnsi(t *testing.T) { + tests := []struct { + s string + exp string + }{ + {"", ""}, // empty + {"foo bar", "foo bar"}, // plain text + {"\033[31mRed\033[0m", "Red"}, // octal syntax + {"\x1b[31mRed\x1b[0m", "Red"}, // hexadecimal syntax + {"foo\x1b[31mRed", "fooRed"}, // no reset parameter + { + "foo\x1b[1;31;102mBoldRedGreen\x1b[0mbar", + "fooBoldRedGreenbar", + }, // multiple attributes + { + "misc.go:func \x1b[01;31m\x1b[KstripAnsi\x1b[m\x1b[K(s string) string {", + "misc.go:func stripAnsi(s string) string {", + }, // `grep` output containing `erase in line` sequence + } + + for _, test := range tests { + if got := stripAnsi(test.s); got != test.exp { + t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got) + } + // we rely on both functions extracting the same runes + // to avoid misalignment + if printLength(test.s) != len(stripAnsi(test.s)) { + t.Errorf("at input %q expected '%d' but got '%d'", test.s, printLength(test.s), len(stripAnsi(test.s))) + } + } +} diff --git a/nav.go b/nav.go index 4615c67f..861b83ec 100644 --- a/nav.go +++ b/nav.go @@ -37,6 +37,7 @@ type file struct { dirSize int64 accessTime time.Time changeTime time.Time + customInfo string ext string err error } @@ -54,6 +55,7 @@ func newFile(path string) *file { dirSize: -1, accessTime: time.Unix(0, 0), changeTime: time.Unix(0, 0), + customInfo: "", ext: "", err: err, } @@ -113,6 +115,7 @@ func newFile(path string) *file { dirSize: -1, accessTime: at, changeTime: ct, + customInfo: "", ext: getFileExtension(lstat), err: nil, } diff --git a/ui.go b/ui.go index 60c77ff6..08e533fe 100644 --- a/ui.go +++ b/ui.go @@ -289,8 +289,10 @@ func infotimefmt(t time.Time) string { return t.Format(gOpts.infotimefmtold) } -func fileInfo(f *file, d *dir, userWidth int, groupWidth int) string { +func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (string, string, int) { var info strings.Builder + var custom string + var off int for _, s := range getInfo(d.path) { switch s { @@ -328,12 +330,18 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int) string { fmt.Fprintf(&info, " %-*s", userWidth, userName(f.FileInfo)) case "group": fmt.Fprintf(&info, " %-*s", groupWidth, groupName(f.FileInfo)) + case "custom": + // To allow for the usage of escape sequences, store `custom` + // separately and print it later using the offset. + off = info.Len() + fmt.Fprintf(&info, " %*s", customWidth, "") + custom = fmt.Sprintf(" %s%*s", f.customInfo, customWidth-printLength(f.customInfo), "") default: log.Printf("unknown info type: %s", s) } } - return info.String() + return info.String(), custom, off } type dirContext struct { @@ -399,17 +407,20 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty var userWidth int var groupWidth int + var customWidth int - // Only fetch user/group widths if configured to display them + // Only fetch user/group/custom widths if configured to display them for _, s := range getInfo(dir.path) { switch s { case "user": userWidth = getUserWidth(dir, beg, end) case "group": groupWidth = getGroupWidth(dir, beg, end) + case "custom": + customWidth = getCustomWidth(dir, beg, end) } - if userWidth > 0 && groupWidth > 0 { + if userWidth > 0 && groupWidth > 0 && customWidth > 0 { break } } @@ -473,7 +484,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty // subtract space for tag and icon maxFilenameWidth := maxWidth - 1 - runeSliceWidth(icon) - info := fileInfo(f, dir, userWidth, groupWidth) + info, custom, off := fileInfo(f, dir, userWidth, groupWidth, customWidth) infolen := len(info) showInfo := infolen > 0 && 2*infolen < maxWidth if showInfo { @@ -494,6 +505,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty if showInfo { filename = append(filename, []rune(info)...) + off += lnwidth + 2 + runeSliceWidth(icon) + maxFilenameWidth } if i == dir.pos { @@ -513,6 +525,11 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty line := append(icon, filename...) line = append(line, ' ') win.print(ui.screen, lnwidth+2, i, st, fmt.Sprintf(cursorFmt, string(line))) + + // print over the empty space we reserved for the custom info + if showInfo && custom != "" { + win.print(ui.screen, off, i, st, fmt.Sprintf(cursorFmt, stripAnsi(custom))) + } } else { if tag == " " { win.print(ui.screen, lnwidth+1, i, st, " ") @@ -531,6 +548,10 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty line := append(filename, ' ') win.print(ui.screen, lnwidth+2+runeSliceWidth(icon), i, st, string(line)) + + if showInfo && custom != "" { + win.print(ui.screen, off, i, st, custom) + } } } } @@ -555,6 +576,16 @@ func getGroupWidth(dir *dir, beg int, end int) int { return maxw } +func getCustomWidth(dir *dir, beg int, end int) int { + maxw := 0 + + for _, f := range dir.files[beg:end] { + maxw = max(printLength(f.customInfo), maxw) + } + + return maxw +} + func getWidths(wtot int) []int { rsum := 0 for _, r := range gOpts.ratios {