Compare commits

46 Commits
Author SHA1 Message Date
Joe Lim 18ab3cf650 chore: prepare for r41 release (#2366) 2026-02-04 16:30:52 +11:00
CatsDeservePets 60deb6e43b docs: normalize Go doc comments (#2359) 2026-01-25 01:14:27 +01:00
Joe Lim 8a01b4a15e refactor: refer to completion output as longest (#2358) 2026-01-23 17:57:46 +11:00
Joe Lim 5bfc8de207 docs: add unreleased section for CHANGELOG.md (#2356) 2026-01-22 14:43:14 +11:00
Joe Lim 46266df1c3 docs: fix order of entries in CHANGELOG.md (#2355) 2026-01-22 14:15:17 +11:00
Joe Lim a01195a4d2 fix: apply position to root directory (#2354) 2026-01-22 13:24:54 +11:00
Joe Lim c7be3c4434 refactor: use *uint64 for dir size and count (#2353)
* refactor: use `*uint64` for dir size and count

* no dircount should be ordered before dircount of 0
2026-01-22 13:11:18 +11:00
Joe Lim cc23e323ac docs: cleanup (#2352) 2026-01-20 13:12:01 +11:00
SPFab fa8e3788de Show directory size in ruler (#2343)
* Added dirSize to Size field and changed humanize function accordingly

* Seperated size into own fields and changed type to use pointers

* Added Documentation and Changelog
2026-01-20 13:01:23 +11:00
Joe Lim b5d981ad4a fix: improve width calculation for ratios option (#2347)
* fix: improve width calculation for `ratios` option

* Update `CHANGELOG.md`

* round window ends instead of floor

* grammar
2026-01-14 11:13:06 +11:00
CatsDeservePets 48689f9eab docs: improve code comments (#2349)
* docs: annotate `app` struct fields

* docs: annotate `file` struct fields

* docs: improve existing code comments

* docs: add new code comments
2026-01-14 00:16:23 +01:00
CatsDeservePets a96bdae71a docs: fix CHANGELOG.md (#2346) 2026-01-12 12:20:29 +01:00
Joe Lim 8ed089cc25 feat!: Load ruler file dynamically (#2338)
* feat!: Load ruler file dynamically

* Add documentation

* Fix bug with custom filename

* Update `CHANGELOG.md`

* Add docs for `statfmt`
2026-01-12 17:48:19 +11:00
dependabot[bot] d00fd5c752 chore(deps): bump golang.org/x/term from 0.38.0 to 0.39.0 (#2344) 2026-01-12 06:20:48 +01:00
SPFab 190f5369a2 feat: add new fields for the ruler file (#2329) 2026-01-11 18:58:37 +01:00
dependabot[bot] dd4be21e23 chore(deps): bump golang.org/x/sys from 0.39.0 to 0.40.0 (#2339)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.39.0 to 0.40.0.
- [Commits](https://github.com/golang/sys/compare/v0.39.0...v0.40.0)

---
updated-dependencies:
- dependency-name: golang.org/x/sys
  dependency-version: 0.40.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-01-10 00:05:02 +01:00
Joe Lim 733e8d6b55 refactor: remove init flag (#2313)
* refactor: remove init flag

* fix bugs

* cleanup of `addcustominfo`

* use `getDir` for accessing directories from cache

* Avoid trimming `addcustominfo` value
2026-01-05 13:15:09 +11:00
CatsDeservePets 57f6ade1b7 fix: avoid surprising case changes in completions (#2336) 2026-01-03 00:44:12 +01:00
CatsDeservePets e1016bbd74 refactor: adjust number column alignment (#2331) 2026-01-01 01:38:08 +01:00
CatsDeservePetsandJoe Lim 165c25b743 feat: add mergeindicators option (#2330)
* feat: add `mergeindicators` option

* docs: update `CHANGELOG.md`

* docs: add documentation

* style: fix typo

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>

---------

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>
2025-12-31 07:36:31 +01:00
CatsDeservePets c1b979371a feat: pass special files to previewer script (#2327) 2025-12-29 02:31:14 +01:00
CatsDeservePets 57d02dd01d refactor: move optionToFmtstr() to termseq.go (#2323) 2025-12-27 17:37:30 +01:00
CatsDeservePets eb01cb7c7b style: deduplicate types in function signatures (#2322) 2025-12-27 06:24:15 +01:00
CatsDeservePets d8b9026ef2 style: combine related var declarations (#2321) 2025-12-27 05:27:16 +01:00
Joe Lim 36cf932113 fix: prevent crash when scrolling (#2320)
* fix: prevent crash when scrolling

* Update `CHANGELOG.md`
2025-12-24 13:49:32 +11:00
Joe Lim d607bdc04e fix: ignore newlines when printing with ruler file (#2319)
* fix: ignore newlines when printing with ruler file

* Update `CHANGELOG.md`
2025-12-23 18:22:07 +11:00
CatsDeservePets 9dac520497 docs: update CHANGELOG.md (#2317) 2025-12-22 02:58:21 +01:00
CatsDeservePets 4a37c1e467 feat: log stderr from previewer and cleaner (#2316) 2025-12-22 02:25:05 +01:00
CatsDeservePets 59a27bbaed feat: add list server command (#2314) 2025-12-21 06:56:43 +01:00
Joe Lim f0f7cfbbed perf: throttle watch updates (#2311)
* perf: throttle watch updates

* Fix file not exist error in the UI

* Use separate timeout for each file
2025-12-19 19:08:55 +11:00
Joe Lim c3dbf0ab01 refactor: use stdlib for reversing slice (#2312) 2025-12-16 18:17:16 +11:00
dependabot[bot] 872783846c chore(deps): bump actions/download-artifact from 6 to 7 (#2306)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 6 to 7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-16 13:19:02 +11:00
dependabot[bot] 8853ac355e chore(deps): bump actions/upload-artifact from 5 to 6 (#2307)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v5...v6)

---
updated-dependencies:
- dependency-name: actions/upload-artifact
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-16 13:18:46 +11:00
Joe Limandveltza af62d1656f perf: change preload to use stack instead of queue (#2291)
* perf: change preload to use stack instead of queue

* Improve order of preloading

Co-authored-by: veltza <106755522+veltza@users.noreply.github.com>

---------

Co-authored-by: veltza <106755522+veltza@users.noreply.github.com>
2025-12-15 11:42:50 +11:00
Joe Lim cdbaa972a6 fix: reset sixel state if new file is loading (#2301)
* fix: reset sixel state if new file is loading

* Update `CHANGELOG.md`
2025-12-13 17:49:19 +11:00
Joe Lim 4575ed0cbf fix: add missing init check when sorting (#2303) 2025-12-13 17:31:20 +11:00
Joe Lim acb85d65c8 refactor: avoid storing current preview separately (#2300) 2025-12-12 16:59:32 +11:00
Joe Lim 0df05894ce chore: add commit prefixes to dependabot bumps (#2297) 2025-12-10 15:51:02 +11:00
Joe Lim e4395362e4 chore: prepare for r40 release (#2295) 2025-12-10 14:41:58 +11:00
Joe Lim 18b6077248 fix: write server response only for remote clients (#2290)
* fix: write server response only for remote clients

* Update `CHANGELOG.md`
2025-12-10 14:10:46 +11:00
Joe Lim 7727b28fbe fix: allow skipped previews to be reloaded (#2292)
* fix: allow skipped previews to be reloaded

* Update `CHANGELOG.md`
2025-12-10 13:49:54 +11:00
dependabot[bot] a9dbaa9dd1 Bump golang.org/x/term from 0.37.0 to 0.38.0 (#2293)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.37.0 to 0.38.0.
- [Commits](https://github.com/golang/term/compare/v0.37.0...v0.38.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  dependency-version: 0.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-09 23:58:35 +11:00
dependabot[bot] 6d82ea9ef8 Bump golang.org/x/sys from 0.38.0 to 0.39.0 (#2294) 2025-12-09 07:38:26 +01:00
Joe Lim 6402bafb9a refactor: Move gEscapeCode to where it is used (#2285) 2025-12-02 18:23:11 +11:00
Joe Lim 4ee121fb56 refactor: simplify for loop (#2283) 2025-12-02 01:38:46 +11:00
Joe Lim 6b92294a29 test: Add permString function (#2282) 2025-12-02 00:45:56 +11:00
29 changed files with 1034 additions and 1077 deletions

No files matched your search

+6
View File
@@ -4,7 +4,13 @@ updates:
directory: / directory: /
schedule: schedule:
interval: daily interval: daily
commit-message:
prefix: chore
include: scope
- package-ecosystem: gomod - package-ecosystem: gomod
directory: / directory: /
schedule: schedule:
interval: daily interval: daily
commit-message:
prefix: chore
include: scope
+2 -2
View File
@@ -70,7 +70,7 @@ jobs:
GOARCH: ${{ matrix.arch }} GOARCH: ${{ matrix.arch }}
- name: Upload artifact - name: Upload artifact
uses: actions/upload-artifact@v5 uses: actions/upload-artifact@v6
with: with:
name: lf-${{ matrix.os }}-${{ matrix.arch }} name: lf-${{ matrix.os }}-${{ matrix.arch }}
path: dist/* path: dist/*
@@ -80,7 +80,7 @@ jobs:
needs: build needs: build
steps: steps:
- name: Download artifacts - name: Download artifacts
uses: actions/download-artifact@v6 uses: actions/download-artifact@v7
with: with:
path: dist path: dist
merge-multiple: true merge-multiple: true
+35
View File
@@ -8,6 +8,41 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- `Added` - `Added`
- `Fixed` - `Fixed`
## Unreleased
## [r41](https://github.com/gokcehan/lf/releases/tag/r41)
### Changed
- The `previewer` script no longer skips non-regular files (#2327).
- Line numbers now take up less space when both `number` and `relativenumber` are enabled (#2331).
- Changes have been made to ruler configuration (#2338):
- The ruler file is no longer experimental.
- The ruler file will be used by default unless `rulerfmt` (now a blank string by default) is specified.
- The ruler file is no longer read from fixed locations like `~/.config/lf/ruler`, and instead the `rulerfile` option has been repurposed to specify the path of the ruler file.
### Added
- A new server command `list` is added to print the IDs of all currently connected clients (#2314).
- The `previewer` and `cleaner` scripts now have their `stderr` output logged (#2316).
- The `ruler` file now supports `.Stat.Extension`, `.Stat.AccessTime`, `.Stat.BirthTime`, `.Stat.ChangeTime` and `.Stat.CustomInfo` (#2329), as well as `.Stat.DirSize` and `.Stat.DirCount` (#2343).
- A new option `mergeindicators` is added to reduce the gap before filenames, by merging tag and selection indicators into a single column (#2330).
### Fixed
- A bug where sixel images fail to display when scrolling back and forth is now fixed (#2301).
- Newline characters are now ignored when drawing the ruler with the `ruler` file configured (#2319).
- A potential crash when using the `scroll-up`/`scroll-down` commands is now fixed (#2320).
- Case-insensitive command-line completions no longer cause user input to be displayed in lowercase (#2336).
- Calculation of window widths for the `ratios` option is now more accurate (#2347).
## [r40](https://github.com/gokcehan/lf/releases/tag/r40)
### Fixed
- Error messages from the server are no longer written to the terminal which causes the UI to break (#2290).
- A bug where file previews fail to load properly when scrolling quickly is now fixed (#2292).
## [r39](https://github.com/gokcehan/lf/releases/tag/r39) ## [r39](https://github.com/gokcehan/lf/releases/tag/r39)
### Changed ### Changed
+40 -60
View File
@@ -19,24 +19,24 @@ import (
) )
type app struct { type app struct {
ui *ui ui *ui // ui state (screen, windows, input)
nav *nav nav *nav // navigation state (dirs, cursor, selections, preview, caches)
ticker *time.Ticker ticker *time.Ticker // refresh ticker if `period` > 0
quitChan chan struct{} quitChan chan struct{} // signals main loop to exit
cmd *exec.Cmd cmd *exec.Cmd // currently running % (shell-pipe) command
cmdIn io.WriteCloser cmdIn io.WriteCloser // stdin writer for running % command
cmdOutBuf []byte cmdOutBuf []byte // output of running % command
cmdHistory []string cmdHistory []string // command history entries
cmdHistoryBeg int cmdHistoryBeg int // index where commands from this session start in cmdHistory
cmdHistoryInd int cmdHistoryInd int // history navigation offset from most recent
cmdHistoryInput *string cmdHistoryInput *string // initial input used as prefix filter while browsing history
menuCompActive bool menuCompActive bool // whether completion cycling is active
menuCompTmp []string menuCompTmp []string // token snapshot taken when completion cycling starts, used for `cmd-menu-discard`
menuComps []compMatch menuComps []compMatch // completion candidates for active prompt
menuCompInd int menuCompInd int // index of selected completion candidate (-1: none selected)
selectionOut []string selectionOut []string // paths to output on exit, used for `-print-selection` and `-selection-path`
watch *watch watch *watch // fs watcher if `watch` is enabled
quitting bool quitting bool // guard to prevent re-entering quit logic
} }
func newApp(ui *ui, nav *nav) *app { func newApp(ui *ui, nav *nav) *app {
@@ -84,11 +84,11 @@ func (app *app) quit() {
} }
} }
if !gSingleMode { if !gSingleMode {
if err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil { if _, err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil {
log.Printf("dropping connection: %s", err) log.Printf("dropping connection: %s", err)
} }
if gOpts.autoquit { if gOpts.autoquit {
if err := remote("quit"); err != nil { if _, err := remote("quit"); err != nil {
log.Printf("auto quitting server: %s", err) log.Printf("auto quitting server: %s", err)
} }
} }
@@ -255,7 +255,7 @@ func (app *app) writeHistory() error {
return nil return nil
} }
// This is the main event loop of the application. Expressions are read from // loop is the main event loop of the application. Expressions are read from
// the client and the server on separate goroutines and sent here over channels // the client and the server on separate goroutines and sent here over channels
// for evaluation. Similarly directories and regular files are also read in // for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update. // separate goroutines and sent here for update.
@@ -296,14 +296,8 @@ func (app *app) loop() {
} }
} }
wd, err := os.Getwd() app.nav.loadDirs()
if err != nil {
log.Printf("getting current directory: %s", err)
}
app.nav.updateDirs(wd)
app.nav.addJumpList() app.nav.addJumpList()
app.nav.init = true
if gSelect != "" { if gSelect != "" {
go func() { go func() {
@@ -393,6 +387,11 @@ func (app *app) loop() {
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
case d := <-app.nav.dirChan: case d := <-app.nav.dirChan:
var oldCurrPath string
if curr := app.nav.currFile(); curr != nil {
oldCurrPath = curr.path
}
prev, ok := app.nav.dirCache[d.path] prev, ok := app.nav.dirCache[d.path]
if ok { if ok {
d.ind = prev.ind d.ind = prev.ind
@@ -405,27 +404,12 @@ func (app *app) loop() {
} }
app.nav.dirCache[d.path] = d app.nav.dirCache[d.path] = d
var oldCurrPath string
if curr, err := app.nav.currFile(); err == nil {
oldCurrPath = curr.path
}
for i := range app.nav.dirs {
if app.nav.dirs[i].path == d.path {
app.nav.dirs[i] = d
}
}
app.nav.position() app.nav.position()
curr, err := app.nav.currFile() if curr := app.nav.currFile(); curr != nil {
if err == nil {
if curr.path != oldCurrPath { if curr.path != oldCurrPath {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
if d.path == curr.path {
app.ui.dirPrev = d
}
} }
app.watchDir(d) app.watchDir(d)
@@ -444,10 +428,8 @@ func (app *app) loop() {
case r := <-app.nav.regChan: case r := <-app.nav.regChan:
app.nav.regCache[r.path] = r app.nav.regCache[r.path] = r
curr, err := app.nav.currFile() if curr := app.nav.currFile(); curr != nil {
if err == nil {
if r.path == curr.path { if r.path == curr.path {
app.ui.regPrev = r
app.ui.sxScreen.forceClear = true app.ui.sxScreen.forceClear = true
if gOpts.preload && r.volatile { if gOpts.preload && r.volatile {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
@@ -489,9 +471,7 @@ func (app *app) loop() {
deletePathRecursive(app.nav.dirCache, path) deletePathRecursive(app.nav.dirCache, path)
currPath := app.nav.currDir().path currPath := app.nav.currDir().path
if currPath == path || strings.HasPrefix(currPath, path+string(filepath.Separator)) { if currPath == path || strings.HasPrefix(currPath, path+string(filepath.Separator)) {
if wd, err := os.Getwd(); err == nil { app.nav.loadDirs()
app.nav.updateDirs(wd)
}
} }
case ev := <-app.ui.evChan: case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev, app.nav) e := app.ui.readEvent(ev, app.nav)
@@ -555,7 +535,7 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
app.nav.renew() app.nav.renew()
} }
// This function is used to run a shell command. Modes are as follows: // runShell is used to run a shell command. Modes are as follows:
// //
// Prefix Wait Async Stdin Stdout Stderr UI action // Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume // $ No No Yes Yes Yes Pause and then resume
@@ -608,10 +588,10 @@ func (app *app) runShell(s string, args []string, prefix string) {
return return
} }
// Cmd.StdoutPipe cannot be used as it requires the output to be fully // [exec.Cmd.StdoutPipe] cannot be used as it requires the output to be fully
// read before calling Cmd.Wait, however in this case Cmd.Wait should // read before calling [exec.Cmd.Wait], however in this case Cmd.Wait should
// only wait for the command to finish executing regardless of whether // only wait for the command to finish executing regardless of whether the
// the output has been fully read or not. // output has been fully read or not.
inReader, inWriter, err := os.Pipe() inReader, inWriter, err := os.Pipe()
if err != nil { if err != nil {
log.Printf("creating input pipe: %s", err) log.Printf("creating input pipe: %s", err)
@@ -688,18 +668,18 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
func (app *app) doComplete() (matches []compMatch) { func (app *app) doComplete() (matches []compMatch) {
var result string var longest string
switch app.ui.cmdPrefix { switch app.ui.cmdPrefix {
case ":": case ":":
matches, result = completeCmd(app.ui.cmdAccLeft) matches, longest = completeCmd(app.ui.cmdAccLeft)
case "$", "%", "!", "&": case "$", "%", "!", "&":
matches, result = completeShell(app.ui.cmdAccLeft) matches, longest = completeShell(app.ui.cmdAccLeft)
case "/", "?": case "/", "?":
matches, result = completeSearch(app.ui.cmdAccLeft) matches, longest = completeSearch(app.ui.cmdAccLeft)
} }
app.ui.cmdAccLeft = []rune(result) app.ui.cmdAccLeft = []rune(longest)
app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, matches, -1) app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, matches, -1)
return return
} }
+9 -15
View File
@@ -86,7 +86,7 @@ func run() {
} }
} }
func writeLastDir(filename string, lastDir string) { func writeLastDir(filename, lastDir string) {
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
log.Printf("opening last dir file: %s", err) log.Printf("opening last dir file: %s", err)
@@ -168,14 +168,15 @@ func readExpr() <-chan expr {
return ch return ch
} }
func remote(cmd string) error { func remote(req string) (string, error) {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { if err != nil {
return fmt.Errorf("dialing to send server: %w", err) return "", fmt.Errorf("connecting to server: %w", err)
} }
defer c.Close()
if _, err := fmt.Fprintln(c, cmd); err != nil { if _, err := fmt.Fprintln(c, req); err != nil {
return fmt.Errorf("sending command to server: %w", err) return "", fmt.Errorf("sending command to server: %w", err)
} }
// XXX: Standard net.Conn interface does not include a CloseWrite method // XXX: Standard net.Conn interface does not include a CloseWrite method
@@ -190,17 +191,10 @@ func remote(cmd string) error {
c.CloseWrite() c.CloseWrite()
} }
// The most straightforward way to write the response to stdout would be resp, err := io.ReadAll(c)
// to do "io.Copy(os.Stdout, c)". However, on Linux, if stdout is connected to
// something like a pager that isn't immediately reading everything,
// this runs into Go bug https://github.com/golang/go/issues/75304 and
// busy-loops, eating a whole CPU.
response, err := io.ReadAll(c)
if err != nil { if err != nil {
return fmt.Errorf("reading response from server: %w", err) return "", fmt.Errorf("reading response from server: %w", err)
} }
c.Close()
os.Stdout.Write(response)
return nil return string(resp), nil
} }
+2 -2
View File
@@ -145,7 +145,7 @@ func (sm styleMap) parseFile(path string) {
} }
} }
// This function parses $LS_COLORS environment variable. // parseGNU parses the $LS_COLORS environment variable.
func (sm *styleMap) parseGNU(env string) { func (sm *styleMap) parseGNU(env string) {
for entry := range strings.SplitSeq(env, ":") { for entry := range strings.SplitSeq(env, ":") {
if entry == "" { if entry == "" {
@@ -179,7 +179,7 @@ func (sm *styleMap) parsePair(pair []string) {
sm.styles[key] = applySGR(val, tcell.StyleDefault) sm.styles[key] = applySGR(val, tcell.StyleDefault)
} }
// This function parses $LSCOLORS environment variable. // parseBSD parses the $LSCOLORS environment variable.
func (sm styleMap) parseBSD(env string) { func (sm styleMap) parseBSD(env string) {
if len(env) != 22 { if len(env) != 22 {
log.Printf("invalid $LSCOLORS variable: %s", env) log.Printf("invalid $LSCOLORS variable: %s", env)
+74 -71
View File
@@ -161,7 +161,7 @@ func getLocalOptWords(localOpts any) (localOptWords []string) {
return return
} }
func commonPrefix(s1, s2 string) string { func getLongest(s1, s2 string) string {
r1 := []rune(s1) r1 := []rune(s1)
r2 := []rune(s2) r2 := []rune(s2)
@@ -180,7 +180,7 @@ type compMatch struct {
result string // result when cycling through completion menu result string // result when cycling through completion menu
} }
func matchWord(s string, words []string) (matches []compMatch, result string) { func matchWord(s string, words []string) (matches []compMatch, longest string) {
for _, w := range words { for _, w := range words {
if !strings.HasPrefix(w, s) { if !strings.HasPrefix(w, s) {
continue continue
@@ -188,22 +188,22 @@ func matchWord(s string, words []string) (matches []compMatch, result string) {
matches = append(matches, compMatch{w, w}) matches = append(matches, compMatch{w, w})
if len(matches) == 1 { if len(matches) == 1 {
result = w longest = w
} else { } else {
result = commonPrefix(result, w) longest = getLongest(longest, w)
} }
} }
switch len(matches) { switch len(matches) {
case 0: case 0:
result = s longest = s
case 1: case 1:
result += " " longest += " "
} }
return return
} }
func matchList(s string, words []string) (matches []compMatch, result string) { func matchList(s string, words []string) (matches []compMatch, longest string) {
toks := strings.Split(s, ":") toks := strings.Split(s, ":")
for _, w := range words { for _, w := range words {
@@ -215,31 +215,31 @@ func matchList(s string, words []string) (matches []compMatch, result string) {
matches = append(matches, compMatch{w, matchResult}) matches = append(matches, compMatch{w, matchResult})
if len(matches) == 1 { if len(matches) == 1 {
result = matchResult longest = matchResult
} else { } else {
result = commonPrefix(result, matchResult) longest = getLongest(longest, matchResult)
} }
} }
switch len(matches) { switch len(matches) {
case 0: case 0:
result = s longest = s
case 1: case 1:
if result == s { if longest == s {
result += " " longest += " "
} }
} }
return return
} }
func matchCmd(s string) (matches []compMatch, result string) { func matchCmd(s string) (matches []compMatch, longest string) {
words := slices.Concat(gCmdWords, slices.Collect(maps.Keys(gOpts.cmds))) words := slices.Concat(gCmdWords, slices.Collect(maps.Keys(gOpts.cmds)))
slices.Sort(words) slices.Sort(words)
matches, result = matchWord(s, slices.Compact(words)) matches, longest = matchWord(s, slices.Compact(words))
return return
} }
func matchFile(s string, dirOnly bool, escape func(string) string, unescape func(string) string) (matches []compMatch, result string) { func matchFile(s string, dirOnly bool, escape, unescape func(string) string) (matches []compMatch, longest string) {
dir, file := filepath.Split(unescape(replaceTilde(s))) dir, file := filepath.Split(unescape(replaceTilde(s)))
d := dir d := dir
@@ -249,11 +249,11 @@ func matchFile(s string, dirOnly bool, escape func(string) string, unescape func
files, err := os.ReadDir(d) files, err := os.ReadDir(d)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
result = s longest = s
return return
} }
var commonName string var longestName string
for _, f := range files { for _, f := range files {
isDir := false isDir := false
@@ -280,38 +280,40 @@ func matchFile(s string, dirOnly bool, escape func(string) string, unescape func
matches = append(matches, compMatch{name, escape(dir + name)}) matches = append(matches, compMatch{name, escape(dir + name)})
if len(matches) == 1 { if len(matches) == 1 {
commonName = name longestName = name
} else { } else {
commonName = commonPrefix(strings.ToLower(commonName), strings.ToLower(name)) // Match case-insensitively without changing the prefix's case.
p := getLongest(strings.ToLower(longestName), strings.ToLower(name))
longestName = string([]rune(longestName)[:len([]rune(p))])
} }
} }
switch len(matches) { switch len(matches) {
case 0: case 0:
result = s longest = s
case 1: case 1:
result = escape(dir + commonName) longest = escape(dir + longestName)
if !strings.HasSuffix(commonName, string(filepath.Separator)) { if !strings.HasSuffix(longestName, string(filepath.Separator)) {
result += " " longest += " "
} }
default: default:
result = escape(dir + commonName) longest = escape(dir + longestName)
} }
return return
} }
func matchCmdFile(s string, dirOnly bool) (matches []compMatch, result string) { func matchCmdFile(s string, dirOnly bool) (matches []compMatch, longest string) {
matches, result = matchFile(s, dirOnly, cmdEscape, cmdUnescape) matches, longest = matchFile(s, dirOnly, cmdEscape, cmdUnescape)
return return
} }
func matchShellFile(s string) (matches []compMatch, result string) { func matchShellFile(s string) (matches []compMatch, longest string) {
matches, result = matchFile(s, false, shellEscape, shellUnescape) matches, longest = matchFile(s, false, shellEscape, shellUnescape)
return return
} }
func matchSetlocalDir(s string) (matches []compMatch, result string) { func matchSetlocalDir(s string) (matches []compMatch, longest string) {
matches, result = matchFile(s, true, cmdEscape, cmdUnescape) matches, longest = matchFile(s, true, cmdEscape, cmdUnescape)
if len(matches) == 0 { if len(matches) == 0 {
return return
} }
@@ -332,13 +334,13 @@ func matchSetlocalDir(s string) (matches []compMatch, result string) {
} }
matches = tmp matches = tmp
if result != s { if longest != s {
result = trimSepEsc(result) longest = trimSepEsc(longest)
} }
return return
} }
func matchExec(s string) (matches []compMatch, result string) { func matchExec(s string) (matches []compMatch, longest string) {
var words []string var words []string
for p := range strings.SplitSeq(envPath, string(filepath.ListSeparator)) { for p := range strings.SplitSeq(envPath, string(filepath.ListSeparator)) {
files, err := os.ReadDir(p) files, err := os.ReadDir(p)
@@ -367,15 +369,15 @@ func matchExec(s string) (matches []compMatch, result string) {
} }
slices.Sort(words) slices.Sort(words)
matches, result = matchWord(s, slices.Compact(words)) matches, longest = matchWord(s, slices.Compact(words))
return return
} }
func matchSearch(s string) (matches []compMatch, result string) { func matchSearch(s string) (matches []compMatch, longest string) {
files, err := os.ReadDir(".") files, err := os.ReadDir(".")
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
result = s longest = s
return return
} }
@@ -386,65 +388,66 @@ func matchSearch(s string) (matches []compMatch, result string) {
matches = append(matches, compMatch{f.Name(), f.Name()}) matches = append(matches, compMatch{f.Name(), f.Name()})
if len(matches) == 1 { if len(matches) == 1 {
result = f.Name() longest = f.Name()
} else { } else {
result = commonPrefix(strings.ToLower(result), strings.ToLower(f.Name())) p := getLongest(strings.ToLower(longest), strings.ToLower(f.Name()))
longest = string([]rune(longest)[:len([]rune(p))])
} }
} }
if len(matches) == 0 { if len(matches) == 0 {
result = s longest = s
} }
return return
} }
func completeCmd(acc []rune) (matches []compMatch, result string) { func completeCmd(acc []rune) (matches []compMatch, longest string) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
if len(f) == 1 { if len(f) == 1 {
matches, result = matchCmd(s) matches, longest = matchCmd(s)
return return
} }
result = f[len(f)-1] longest = f[len(f)-1]
switch f[0] { switch f[0] {
case "set": case "set":
if len(f) == 2 { if len(f) == 2 {
matches, result = matchWord(f[1], gOptWords) matches, longest = matchWord(f[1], gOptWords)
break break
} }
if len(f) != 3 { if len(f) != 3 {
break break
} }
switch f[1] { switch f[1] {
case "cleaner", "previewer": case "cleaner", "previewer", "rulerfile":
matches, result = matchCmdFile(f[2], false) matches, longest = matchCmdFile(f[2], false)
case "filtermethod", "searchmethod": case "filtermethod", "searchmethod":
matches, result = matchWord(f[2], []string{"glob", "regex", "text"}) matches, longest = matchWord(f[2], []string{"glob", "regex", "text"})
case "info": case "info":
matches, result = matchList(f[2], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"}) matches, longest = matchList(f[2], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"})
case "preserve": case "preserve":
matches, result = matchList(f[2], []string{"mode", "timestamps"}) matches, longest = matchList(f[2], []string{"mode", "timestamps"})
case "selmode": case "selmode":
matches, result = matchWord(f[2], []string{"all", "dir"}) matches, longest = matchWord(f[2], []string{"all", "dir"})
case "sizeunits": case "sizeunits":
matches, result = matchWord(f[2], []string{"binary", "decimal"}) matches, longest = matchWord(f[2], []string{"binary", "decimal"})
case "sortby": case "sortby":
matches, result = matchWord(f[2], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"}) matches, longest = matchWord(f[2], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"})
default: default:
if slices.Contains(gOptWords, f[1]+"!") { if slices.Contains(gOptWords, f[1]+"!") {
matches, result = matchWord(f[2], []string{"false", "true"}) matches, longest = matchWord(f[2], []string{"false", "true"})
} }
} }
case "setlocal": case "setlocal":
if len(f) == 2 { if len(f) == 2 {
matches, result = matchSetlocalDir(f[1]) matches, longest = matchSetlocalDir(f[1])
break break
} }
if len(f) == 3 { if len(f) == 3 {
matches, result = matchWord(f[2], gLocalOptWords) matches, longest = matchWord(f[2], gLocalOptWords)
break break
} }
if len(f) != 4 { if len(f) != 4 {
@@ -452,56 +455,56 @@ func completeCmd(acc []rune) (matches []compMatch, result string) {
} }
switch f[2] { switch f[2] {
case "info": case "info":
matches, result = matchList(f[3], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"}) matches, longest = matchList(f[3], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"})
case "sortby": case "sortby":
matches, result = matchWord(f[3], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"}) matches, longest = matchWord(f[3], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"})
default: default:
if slices.Contains(gLocalOptWords, f[2]+"!") { if slices.Contains(gLocalOptWords, f[2]+"!") {
matches, result = matchWord(f[3], []string{"false", "true"}) matches, longest = matchWord(f[3], []string{"false", "true"})
} }
} }
case "map", "nmap", "vmap", "cmap": case "map", "nmap", "vmap", "cmap":
if len(f) == 3 { if len(f) == 3 {
matches, result = matchCmd(f[2]) matches, longest = matchCmd(f[2])
} }
case "cmd": case "cmd":
case "cd": case "cd":
if len(f) == 2 { if len(f) == 2 {
matches, result = matchCmdFile(f[1], true) matches, longest = matchCmdFile(f[1], true)
} }
case "addcustominfo", "select", "source": case "addcustominfo", "select", "source":
if len(f) == 2 { if len(f) == 2 {
matches, result = matchCmdFile(f[1], false) matches, longest = matchCmdFile(f[1], false)
} }
case "toggle": case "toggle":
matches, result = matchCmdFile(f[len(f)-1], false) matches, longest = matchCmdFile(f[len(f)-1], false)
default: default:
if !slices.Contains(gCmdWords, f[0]) { if !slices.Contains(gCmdWords, f[0]) {
matches, result = matchCmdFile(f[len(f)-1], false) matches, longest = matchCmdFile(f[len(f)-1], false)
} }
} }
f[len(f)-1] = result f[len(f)-1] = longest
result = strings.Join(f, " ") longest = strings.Join(f, " ")
return return
} }
func completeShell(acc []rune) (matches []compMatch, result string) { func completeShell(acc []rune) (matches []compMatch, longest string) {
f := tokenize(string(acc)) f := tokenize(string(acc))
switch len(f) { switch len(f) {
case 1: case 1:
matches, result = matchExec(f[0]) matches, longest = matchExec(f[0])
default: default:
matches, result = matchShellFile(f[len(f)-1]) matches, longest = matchShellFile(f[len(f)-1])
} }
f[len(f)-1] = result f[len(f)-1] = longest
result = strings.Join(f, " ") longest = strings.Join(f, " ")
return return
} }
func completeSearch(acc []rune) (matches []compMatch, result string) { func completeSearch(acc []rune) (matches []compMatch, longest string) {
matches, result = matchSearch(string(acc)) matches, longest = matchSearch(string(acc))
return return
} }
+12 -10
View File
@@ -43,7 +43,7 @@ func TestGetLocalOptWords(t *testing.T) {
} }
} }
func TestCommonPrefix(t *testing.T) { func TestGetLongest(t *testing.T) {
tests := []struct { tests := []struct {
s1 string s1 string
s2 string s2 string
@@ -60,7 +60,7 @@ func TestCommonPrefix(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
if got := commonPrefix(test.s1, test.s2); got != test.exp { if got := getLongest(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) t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got)
} }
} }
@@ -71,24 +71,26 @@ func TestMatchWord(t *testing.T) {
s string s string
words []string words []string
matches []compMatch matches []compMatch
result string longest string
}{ }{
{"", nil, nil, ""}, {"", nil, nil, ""},
{"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""}, {"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""},
{"f", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "},
{"b", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"},
{"fo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "}, {"fo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "},
{"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"}, {"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"},
{"fo", []string{"bar", "baz"}, nil, "fo"}, {"fo", []string{"bar", "baz"}, nil, "fo"},
} }
for _, test := range tests { for _, test := range tests {
matches, result := matchWord(test.s, test.words) matches, longest := matchWord(test.s, test.words)
if !reflect.DeepEqual(matches, test.matches) { 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) t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches)
} }
if result != test.result { if longest != test.longest {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result) t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, longest)
} }
} }
} }
@@ -98,7 +100,7 @@ func TestMatchList(t *testing.T) {
s string s string
words []string words []string
matches []compMatch matches []compMatch
result string longest string
}{ }{
{"", nil, nil, ""}, {"", nil, nil, ""},
{"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""}, {"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""},
@@ -117,14 +119,14 @@ func TestMatchList(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
matches, result := matchList(test.s, test.words) matches, longest := matchList(test.s, test.words)
if !reflect.DeepEqual(matches, test.matches) { 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) t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches)
} }
if result != test.result { if longest != test.longest {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result) t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, longest)
} }
} }
} }
+1 -1
View File
@@ -30,7 +30,7 @@ func TestRemoveDiacritics(t *testing.T) {
checkRemoveDiacritics(testStr, expStr, t) checkRemoveDiacritics(testStr, expStr, t)
} }
func checkRemoveDiacritics(testStr string, expStr string, t *testing.T) { func checkRemoveDiacritics(testStr, expStr string, t *testing.T) {
resultStr := removeDiacritics(testStr) resultStr := removeDiacritics(testStr)
if resultStr != expStr { if resultStr != expStr {
t.Errorf("at input '%v' expected '%v' but got '%v'", testStr, expStr, resultStr) t.Errorf("at input '%v' expected '%v' but got '%v'", testStr, expStr, resultStr)
+30 -15
View File
@@ -86,7 +86,7 @@ Same as **-print-selection**, but write the newline-separated list to *path* ins
**-remote** *command* **-remote** *command*
Send *command* to the running server (e.g. `send`, `query` or `quit`). See `REMOTE COMMANDS` for more details. Send *command* to the running server (i.e. `send`, `query`, `list`, `quit`, or `quit!`). See `REMOTE COMMANDS` for more details.
**-server** **-server**
@@ -287,6 +287,7 @@ The following options can be used to customize the behavior of lf:
menufmt string (default "\033[0m") menufmt string (default "\033[0m")
menuheaderfmt string (default "\033[1m") menuheaderfmt string (default "\033[1m")
menuselectfmt string (default "\033[7m") menuselectfmt string (default "\033[7m")
mergeindicators bool (default false)
mouse bool (default false) mouse bool (default false)
number bool (default false) number bool (default false)
numberfmt string (default "\033[33m") numberfmt string (default "\033[33m")
@@ -300,8 +301,8 @@ The following options can be used to customize the behavior of lf:
relativenumber bool (default false) relativenumber bool (default false)
reverse bool (default false) reverse bool (default false)
roundbox bool (default false) roundbox bool (default false)
rulerfile bool (default false) rulerfile string (default "")
rulerfmt string (default " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t") rulerfmt string (default "")
scrolloff int (default 0) scrolloff int (default 0)
searchmethod string (default 'text') searchmethod string (default 'text')
selectfmt string (default "\033[7;35m") selectfmt string (default "\033[7;35m")
@@ -449,12 +450,6 @@ The icons file should be located at:
Unix /etc/lf/icons ~/.config/lf/icons Unix /etc/lf/icons ~/.config/lf/icons
Windows C:\ProgramData\lf\icons C:\Users\<user>\AppData\Roaming\lf\icons Windows C:\ProgramData\lf\icons C:\Users\<user>\AppData\Roaming\lf\icons
The ruler file should be located at:
OS system-wide user-specific
Unix /etc/lf/ruler ~/.config/lf/ruler
Windows C:\ProgramData\lf\ruler C:\Users\<user>\AppData\Roaming\lf\ruler
The selection file should be located at: The selection file should be located at:
Unix ~/.local/share/lf/files Unix ~/.local/share/lf/files
@@ -690,7 +685,7 @@ Simulate key pushes given in the argument.
## addcustominfo ## addcustominfo
Update the `custom` info field of the given file with the given string. Update the `custom` info and `.Stat.CustomInfo` field of the given file with the given string.
The info string may contain ANSI escape codes to further customize its appearance. The info string may contain ANSI escape codes to further customize its appearance.
If no info is provided, clear the file's info instead. If no info is provided, clear the file's info instead.
@@ -1018,6 +1013,11 @@ Format string of the header row in the menu.
Format string of the currently selected item in the menu. Format string of the currently selected item in the menu.
## mergeindicators (bool) (default false)
When `mergeindicators` is enabled, tag and selection indicators are drawn in a single column to reduce the gap before filenames.
If a file is both tagged and selected, the tag uses the selection format (e.g. `copyfmt`) instead of `tagfmt`.
## mouse (bool) (default false) ## mouse (bool) (default false)
Send mouse events as input. Send mouse events as input.
@@ -1103,14 +1103,17 @@ Reverse the direction of sort.
Draw rounded outer corners when the `drawbox` option is enabled. Draw rounded outer corners when the `drawbox` option is enabled.
## rulerfile (bool) (default false) ## rulerfile (string) (default ``)
Use the ruler file instead of the `rulerfmt` and `statfmt` options when drawing the ruler at the bottom. Set the path of the ruler file.
If not set, then a default template will be used for the ruler.
Refer to the [RULER section](https://github.com/gokcehan/lf/blob/master/doc.md#ruler) for more information about how the ruler file works. Refer to the [RULER section](https://github.com/gokcehan/lf/blob/master/doc.md#ruler) for more information about how the ruler file works.
## rulerfmt (string) (default ` %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t`) ## rulerfmt (string) (default ``)
Format string of the ruler shown in the bottom right corner. Format string of the ruler shown in the bottom right corner.
When set, it will be used along with `statfmt` to draw the ruler, and `rulerfile` will be ignored.
However, using `rulerfile` is preferred and this option is provided for backwards compatibility.
The following special expansions are supported: The following special expansions are supported:
@@ -1203,6 +1206,8 @@ The following sort types are supported:
## statfmt (string) (default `\033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l`) ## statfmt (string) (default `\033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l`)
Format string of the file info shown in the bottom left corner. Format string of the file info shown in the bottom left corner.
This option has no effect unless `rulerfmt` is also set.
Using `rulerfile` is preferred and this option is provided for backwards compatibility.
The following special expansions are supported: The following special expansions are supported:
@@ -1777,6 +1782,10 @@ For example, to select a previous command using fzf and execute it:
lf -remote "send $id $cmd" lf -remote "send $id $cmd"
}} }}
The `list` command prints the IDs of all currently connected clients:
lf -remote 'list'
There is also a `quit` command to quit the server when there are no connected clients left, and a `quit!` command to force quit the server by closing client connections first: There is also a `quit` command to quit the server when there are no connected clients left, and a `quit!` command to force quit the server by closing client connections first:
lf -remote 'quit' lf -remote 'quit'
@@ -2204,9 +2213,8 @@ https://github.com/gokcehan/lf/blob/master/etc/icons_colored.example
# RULER # RULER
The ruler can be configured using a ruler file (refer to the [CONFIGURATION section](https://github.com/gokcehan/lf/blob/master/doc.md#configuration)). The ruler can be configured using the `rulerfile` option (refer to the [CONFIGURATION section](https://github.com/gokcehan/lf/blob/master/doc.md#configuration)).
The contents of the ruler file should be a Go template which is then rendered to create the actual output (refer to https://pkg.go.dev/text/template for more details on the syntax). The contents of the ruler file should be a Go template which is then rendered to create the actual output (refer to https://pkg.go.dev/text/template for more details on the syntax).
This feature is currently experimental and must be enabled via the `rulerfile` option.
The following data fields are exported: The following data fields are exported:
@@ -2228,13 +2236,20 @@ The following data fields are exported:
.UserOptions map[string]string The value of user-defined options (e.g. `{{.UserOptions.foo}}`) .UserOptions map[string]string The value of user-defined options (e.g. `{{.UserOptions.foo}}`)
.Stat.Path string Path of the current file .Stat.Path string Path of the current file
.Stat.Name string Name of the current file .Stat.Name string Name of the current file
.Stat.Extension string Extension of the current file
.Stat.Size uint64 Size of the current file .Stat.Size uint64 Size of the current file
.Stat.DirSize *uint64 Total size of the current directory if calculated via `calcdirsize`
.Stat.DirCount *uint64 Number of items in the current directory if the `dircounts` option is enabled
.Stat.Permissions string Permissions of the current file .Stat.Permissions string Permissions of the current file
.Stat.ModTime string Last modified time of the current file (formatted based on the `timefmt` option) .Stat.ModTime string Last modified time of the current file (formatted based on the `timefmt` option)
.Stat.AccessTime string Last access time of the current file (formatted based on the `timefmt` option)
.Stat.BirthTime string Birth time of the current file (formatted based on the `timefmt` option)
.Stat.ChangeTime string Last status (inode) change time of the current file (formatted based on the `timefmt` option)
.Stat.LinkCount string Number of hard links for the current file .Stat.LinkCount string Number of hard links for the current file
.Stat.User string User of the current file .Stat.User string User of the current file
.Stat.Group string Group of the current file .Stat.Group string Group of the current file
.Stat.Target string Target if the current file is a symbolic link, otherwise a blank string .Stat.Target string Target if the current file is a symbolic link, otherwise a blank string
.Stat.CustomInfo string Custom property if defined via `addcustominfo`, otherwise a blank string
The following functions are exported: The following functions are exported:
+41 -24
View File
@@ -91,8 +91,8 @@ SERVER
-remote command -remote command
Send command to the running server (e.g. send, query or quit). See Send command to the running server (i.e. send, query, list, quit, or
REMOTE COMMANDS for more details. quit!). See REMOTE COMMANDS for more details.
-server -server
@@ -299,6 +299,7 @@ The following options can be used to customize the behavior of lf:
menufmt string (default "\033[0m") menufmt string (default "\033[0m")
menuheaderfmt string (default "\033[1m") menuheaderfmt string (default "\033[1m")
menuselectfmt string (default "\033[7m") menuselectfmt string (default "\033[7m")
mergeindicators bool (default false)
mouse bool (default false) mouse bool (default false)
number bool (default false) number bool (default false)
numberfmt string (default "\033[33m") numberfmt string (default "\033[33m")
@@ -312,8 +313,8 @@ The following options can be used to customize the behavior of lf:
relativenumber bool (default false) relativenumber bool (default false)
reverse bool (default false) reverse bool (default false)
roundbox bool (default false) roundbox bool (default false)
rulerfile bool (default false) rulerfile string (default "")
rulerfmt string (default " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t") rulerfmt string (default "")
scrolloff int (default 0) scrolloff int (default 0)
searchmethod string (default 'text') searchmethod string (default 'text')
selectfmt string (default "\033[7;35m") selectfmt string (default "\033[7;35m")
@@ -463,12 +464,6 @@ The icons file should be located at:
Unix /etc/lf/icons ~/.config/lf/icons Unix /etc/lf/icons ~/.config/lf/icons
Windows C:\ProgramData\lf\icons C:\Users\<user>\AppData\Roaming\lf\icons Windows C:\ProgramData\lf\icons C:\Users\<user>\AppData\Roaming\lf\icons
The ruler file should be located at:
OS system-wide user-specific
Unix /etc/lf/ruler ~/.config/lf/ruler
Windows C:\ProgramData\lf\ruler C:\Users\<user>\AppData\Roaming\lf\ruler
The selection file should be located at: The selection file should be located at:
Unix ~/.local/share/lf/files Unix ~/.local/share/lf/files
@@ -724,9 +719,10 @@ Simulate key pushes given in the argument.
addcustominfo addcustominfo
Update the custom info field of the given file with the given string. Update the custom info and .Stat.CustomInfo field of the given file with
The info string may contain ANSI escape codes to further customize its the given string. The info string may contain ANSI escape codes to
appearance. If no info is provided, clear the file's info instead. further customize its appearance. If no info is provided, clear the
file's info instead.
calcdirsize calcdirsize
@@ -1098,6 +1094,13 @@ menuselectfmt (string) (default \033[7m)
Format string of the currently selected item in the menu. Format string of the currently selected item in the menu.
mergeindicators (bool) (default false)
When mergeindicators is enabled, tag and selection indicators are drawn
in a single column to reduce the gap before filenames. If a file is both
tagged and selected, the tag uses the selection format (e.g. copyfmt)
instead of tagfmt.
mouse (bool) (default false) mouse (bool) (default false)
Send mouse events as input. Send mouse events as input.
@@ -1197,15 +1200,18 @@ roundbox (bool) (default false)
Draw rounded outer corners when the drawbox option is enabled. Draw rounded outer corners when the drawbox option is enabled.
rulerfile (bool) (default false) rulerfile (string) (default ``)
Use the ruler file instead of the rulerfmt and statfmt options when Set the path of the ruler file. If not set, then a default template will
drawing the ruler at the bottom. Refer to the RULER section for more be used for the ruler. Refer to the RULER section for more information
information about how the ruler file works. about how the ruler file works.
rulerfmt (string) (default %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t) rulerfmt (string) (default ``)
Format string of the ruler shown in the bottom right corner. Format string of the ruler shown in the bottom right corner. When set,
it will be used along with statfmt to draw the ruler, and rulerfile will
be ignored. However, using rulerfile is preferred and this option is
provided for backwards compatibility.
The following special expansions are supported: The following special expansions are supported:
@@ -1305,7 +1311,9 @@ The following sort types are supported:
statfmt (string) (default \033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l) statfmt (string) (default \033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l)
Format string of the file info shown in the bottom left corner. Format string of the file info shown in the bottom left corner. This
option has no effect unless rulerfmt is also set. Using rulerfile is
preferred and this option is provided for backwards compatibility.
The following special expansions are supported: The following special expansions are supported:
@@ -1960,6 +1968,10 @@ For example, to select a previous command using fzf and execute it:
lf -remote "send $id $cmd" lf -remote "send $id $cmd"
}} }}
The list command prints the IDs of all currently connected clients:
lf -remote 'list'
There is also a quit command to quit the server when there are no There is also a quit command to quit the server when there are no
connected clients left, and a quit! command to force quit the server by connected clients left, and a quit! command to force quit the server by
closing client connections first: closing client connections first:
@@ -2473,12 +2485,10 @@ https://github.com/gokcehan/lf/blob/master/etc/icons_colored.example
RULER RULER
The ruler can be configured using a ruler file (refer to the The ruler can be configured using the rulerfile option (refer to the
CONFIGURATION section). The contents of the ruler file should be a Go CONFIGURATION section). The contents of the ruler file should be a Go
template which is then rendered to create the actual output (refer to template which is then rendered to create the actual output (refer to
https://pkg.go.dev/text/template for more details on the syntax). This https://pkg.go.dev/text/template for more details on the syntax).
feature is currently experimental and must be enabled via the rulerfile
option.
The following data fields are exported: The following data fields are exported:
@@ -2500,13 +2510,20 @@ The following data fields are exported:
.UserOptions map[string]string The value of user-defined options (e.g. `{{.UserOptions.foo}}`) .UserOptions map[string]string The value of user-defined options (e.g. `{{.UserOptions.foo}}`)
.Stat.Path string Path of the current file .Stat.Path string Path of the current file
.Stat.Name string Name of the current file .Stat.Name string Name of the current file
.Stat.Extension string Extension of the current file
.Stat.Size uint64 Size of the current file .Stat.Size uint64 Size of the current file
.Stat.DirSize *uint64 Total size of the current directory if calculated via `calcdirsize`
.Stat.DirCount *uint64 Number of items in the current directory if the `dircounts` option is enabled
.Stat.Permissions string Permissions of the current file .Stat.Permissions string Permissions of the current file
.Stat.ModTime string Last modified time of the current file (formatted based on the `timefmt` option) .Stat.ModTime string Last modified time of the current file (formatted based on the `timefmt` option)
.Stat.AccessTime string Last access time of the current file (formatted based on the `timefmt` option)
.Stat.BirthTime string Birth time of the current file (formatted based on the `timefmt` option)
.Stat.ChangeTime string Last status (inode) change time of the current file (formatted based on the `timefmt` option)
.Stat.LinkCount string Number of hard links for the current file .Stat.LinkCount string Number of hard links for the current file
.Stat.User string User of the current file .Stat.User string User of the current file
.Stat.Group string Group of the current file .Stat.Group string Group of the current file
.Stat.Target string Target if the current file is a symbolic link, otherwise a blank string .Stat.Target string Target if the current file is a symbolic link, otherwise a blank string
.Stat.CustomInfo string Custom property if defined via `addcustominfo`, otherwise a blank string
The following functions are exported: The following functions are exported:
+95 -268
View File
@@ -74,14 +74,12 @@ func (e *setExpr) eval(app *app, _ []string) {
err = applyBoolOpt(&gOpts.dirfirst, e) err = applyBoolOpt(&gOpts.dirfirst, e)
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.ui.sort()
} }
case "dironly", "nodironly", "dironly!": case "dironly", "nodironly", "dironly!":
err = applyBoolOpt(&gOpts.dironly, e) err = applyBoolOpt(&gOpts.dironly, e)
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "dirpreviews", "nodirpreviews", "dirpreviews!": case "dirpreviews", "nodirpreviews", "dirpreviews!":
@@ -98,7 +96,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "history", "nohistory", "history!": case "history", "nohistory", "history!":
@@ -110,7 +107,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "ignoredia", "noignoredia", "ignoredia!": case "ignoredia", "noignoredia", "ignoredia!":
@@ -118,13 +114,14 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "incfilter", "noincfilter", "incfilter!": case "incfilter", "noincfilter", "incfilter!":
err = applyBoolOpt(&gOpts.incfilter, e) err = applyBoolOpt(&gOpts.incfilter, e)
case "incsearch", "noincsearch", "incsearch!": case "incsearch", "noincsearch", "incsearch!":
err = applyBoolOpt(&gOpts.incsearch, e) err = applyBoolOpt(&gOpts.incsearch, e)
case "mergeindicators", "nomergeindicators", "mergeindicators!":
err = applyBoolOpt(&gOpts.mergeindicators, e)
case "mouse", "nomouse", "mouse!": case "mouse", "nomouse", "mouse!":
err = applyBoolOpt(&gOpts.mouse, e) err = applyBoolOpt(&gOpts.mouse, e)
if err == nil { if err == nil {
@@ -155,12 +152,9 @@ func (e *setExpr) eval(app *app, _ []string) {
err = applyBoolOpt(&gOpts.reverse, e) err = applyBoolOpt(&gOpts.reverse, e)
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.ui.sort()
} }
case "roundbox", "noroundbox", "roundbox!": case "roundbox", "noroundbox", "roundbox!":
err = applyBoolOpt(&gOpts.roundbox, e) err = applyBoolOpt(&gOpts.roundbox, e)
case "rulerfile", "norulerfile", "rulerfile!":
err = applyBoolOpt(&gOpts.rulerfile, e)
case "showbinds", "noshowbinds", "showbinds!": case "showbinds", "noshowbinds", "showbinds!":
err = applyBoolOpt(&gOpts.showbinds, e) err = applyBoolOpt(&gOpts.showbinds, e)
case "smartcase", "nosmartcase", "smartcase!": case "smartcase", "nosmartcase", "smartcase!":
@@ -168,7 +162,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "smartdia", "nosmartdia", "smartdia!": case "smartdia", "nosmartdia", "smartdia!":
@@ -176,7 +169,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "watch", "nowatch", "watch!": case "watch", "nowatch", "watch!":
@@ -225,7 +217,6 @@ func (e *setExpr) eval(app *app, _ []string) {
} }
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "findlen": case "findlen":
n, err := strconv.Atoi(e.val) n, err := strconv.Atoi(e.val)
@@ -254,7 +245,6 @@ func (e *setExpr) eval(app *app, _ []string) {
gOpts.hiddenfiles = toks gOpts.hiddenfiles = toks
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "ifs": case "ifs":
gOpts.ifs = e.val gOpts.ifs = e.val
@@ -344,6 +334,9 @@ func (e *setExpr) eval(app *app, _ []string) {
app.ui.wins = getWins(app.ui.screen) app.ui.wins = getWins(app.ui.screen)
app.nav.resize(app.ui) app.nav.resize(app.ui)
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "rulerfile", "norulerfile", "rulerfile!":
gOpts.rulerfile = replaceTilde(e.val)
app.ui.ruler, app.ui.rulerErr = parseRuler(gOpts.rulerfile)
case "rulerfmt": case "rulerfmt":
gOpts.rulerfmt = e.val gOpts.rulerfmt = e.val
case "scrolloff": case "scrolloff":
@@ -401,7 +394,6 @@ func (e *setExpr) eval(app *app, _ []string) {
} }
gOpts.sortby = method gOpts.sortby = method
app.nav.sort() app.nav.sort()
app.ui.sort()
case "statfmt": case "statfmt":
gOpts.statfmt = e.val gOpts.statfmt = e.val
case "tabstop": case "tabstop":
@@ -485,14 +477,12 @@ func (e *setLocalExpr) eval(app *app, _ []string) {
err = applyLocalBoolOpt(gLocalOpts.dirfirst, gOpts.dirfirst, e) err = applyLocalBoolOpt(gLocalOpts.dirfirst, gOpts.dirfirst, e)
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.ui.sort()
} }
case "dironly", "nodironly", "dironly!": case "dironly", "nodironly", "dironly!":
err = applyLocalBoolOpt(gLocalOpts.dironly, gOpts.dironly, e) err = applyLocalBoolOpt(gLocalOpts.dironly, gOpts.dironly, e)
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "hidden", "nohidden", "hidden!": case "hidden", "nohidden", "hidden!":
@@ -500,14 +490,12 @@ func (e *setLocalExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "reverse", "noreverse", "reverse!": case "reverse", "noreverse", "reverse!":
err = applyLocalBoolOpt(gLocalOpts.reverse, gOpts.reverse, e) err = applyLocalBoolOpt(gLocalOpts.reverse, gOpts.reverse, e)
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
app.ui.sort()
} }
case "info": case "info":
if e.val == "" { if e.val == "" {
@@ -532,7 +520,6 @@ func (e *setLocalExpr) eval(app *app, _ []string) {
} }
gLocalOpts.sortby[e.path] = method gLocalOpts.sortby[e.path] = method
app.nav.sort() app.nav.sort()
app.ui.sort()
default: default:
err = fmt.Errorf("unknown option: %s", e.opt) err = fmt.Errorf("unknown option: %s", e.opt)
} }
@@ -849,7 +836,7 @@ func insert(app *app, arg string) {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
return return
} }
@@ -872,7 +859,7 @@ func insert(app *app, arg string) {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
return return
} }
@@ -893,7 +880,7 @@ func insert(app *app, arg string) {
return return
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("mark-save: %s", err) app.ui.echoerrf("mark-save: %s", err)
return return
} }
@@ -901,32 +888,14 @@ func insert(app *app, arg string) {
case app.ui.cmdPrefix == "mark-load: ": case app.ui.cmdPrefix == "mark-load: ":
normal(app) normal(app)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
path, ok := app.nav.marks[arg] path, ok := app.nav.marks[arg]
if !ok { if !ok {
app.ui.echoerr("mark-load: no such mark") app.ui.echoerr("mark-load: no such mark")
return return
} }
if wd != path { if err := cd(app, path); err != nil {
resetIncCmd(app) app.ui.echoerrf("mark-load: %s", err)
preChdir(app)
}
if err := app.nav.cd(path); err != nil {
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFile(app, true)
if wd != path {
app.nav.marks["'"] = wd
restartIncCmd(app)
onChdir(app)
} }
case app.ui.cmdPrefix == "mark-remove: ": case app.ui.cmdPrefix == "mark-remove: ":
normal(app) normal(app)
@@ -944,7 +913,7 @@ func insert(app *app, arg string) {
return return
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("mark-remove: %s", err) app.ui.echoerrf("mark-remove: %s", err)
return return
} }
@@ -965,6 +934,37 @@ func insert(app *app, arg string) {
} }
} }
func cd(app *app, path string) error {
wd, err := os.Getwd()
if err != nil {
return fmt.Errorf("getting current directory: %w", err)
}
path, err = filepath.Abs(replaceTilde(path))
if err != nil {
return fmt.Errorf("getting absolute path: %w", err)
}
if path == wd {
return nil
}
resetIncCmd(app)
preChdir(app)
if err := app.nav.cd(path); err != nil {
return fmt.Errorf("changing directory: %w", err)
}
app.ui.loadFile(app, true)
app.nav.marks["'"] = wd
restartIncCmd(app)
onChdir(app)
return nil
}
func exitCompMenu(app *app) { func exitCompMenu(app *app) {
app.ui.menu = "" app.ui.menu = ""
app.ui.menuSelect = nil app.ui.menuSelect = nil
@@ -974,6 +974,7 @@ func exitCompMenu(app *app) {
func (e *callExpr) eval(app *app, _ []string) { func (e *callExpr) eval(app *app, _ []string) {
os.Setenv("lf_count", strconv.Itoa(e.count)) os.Setenv("lf_count", strconv.Itoa(e.count))
// commands that shouldn't clear the message line
silentCmds := []string{ silentCmds := []string{
"addcustominfo", "addcustominfo",
"clearmaps", "clearmaps",
@@ -996,65 +997,38 @@ func (e *callExpr) eval(app *app, _ []string) {
case "quit": case "quit":
app.quitChan <- struct{}{} app.quitChan <- struct{}{}
case "up": case "up":
if !app.nav.init {
return
}
if app.nav.up(e.count) { if app.nav.up(e.count) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "half-up": case "half-up":
if !app.nav.init {
return
}
if app.nav.up(e.count * app.nav.height / 2) { if app.nav.up(e.count * app.nav.height / 2) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "page-up": case "page-up":
if !app.nav.init {
return
}
if app.nav.up(e.count * app.nav.height) { if app.nav.up(e.count * app.nav.height) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "scroll-up": case "scroll-up":
if !app.nav.init {
return
}
if app.nav.scrollUp(e.count) { if app.nav.scrollUp(e.count) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "down": case "down":
if !app.nav.init {
return
}
if app.nav.down(e.count) { if app.nav.down(e.count) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "half-down": case "half-down":
if !app.nav.init {
return
}
if app.nav.down(e.count * app.nav.height / 2) { if app.nav.down(e.count * app.nav.height / 2) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "page-down": case "page-down":
if !app.nav.init {
return
}
if app.nav.down(e.count * app.nav.height) { if app.nav.down(e.count * app.nav.height) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "scroll-down": case "scroll-down":
if !app.nav.init {
return
}
if app.nav.scrollDown(e.count) { if app.nav.scrollDown(e.count) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "updir": case "updir":
if !app.nav.init {
return
}
resetIncCmd(app) resetIncCmd(app)
preChdir(app) preChdir(app)
for range e.count { for range e.count {
@@ -1067,12 +1041,8 @@ func (e *callExpr) eval(app *app, _ []string) {
restartIncCmd(app) restartIncCmd(app)
onChdir(app) onChdir(app)
case "open": case "open":
if !app.nav.init { curr := app.nav.currFile()
return if curr == nil {
}
curr, err := app.nav.currFile()
if err != nil {
app.ui.echoerrf("opening: %s", err)
return return
} }
@@ -1117,9 +1087,6 @@ func (e *callExpr) eval(app *app, _ []string) {
restartIncCmd(app) restartIncCmd(app)
onChdir(app) onChdir(app)
case "top": case "top":
if !app.nav.init {
return
}
var moved bool var moved bool
if e.count == 1 { if e.count == 1 {
moved = app.nav.top() moved = app.nav.top()
@@ -1130,9 +1097,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "bottom": case "bottom":
if !app.nav.init {
return
}
var moved bool var moved bool
if e.count == 1 { if e.count == 1 {
// Different from Vim, which would treat a count of 1 as meaning to // Different from Vim, which would treat a count of 1 as meaning to
@@ -1145,57 +1109,41 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "high": case "high":
if !app.nav.init {
return
}
if app.nav.high() { if app.nav.high() {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "middle": case "middle":
if !app.nav.init {
return
}
if app.nav.middle() { if app.nav.middle() {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "low": case "low":
if !app.nav.init {
return
}
if app.nav.low() { if app.nav.low() {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "toggle": case "toggle":
if !app.nav.init {
return
}
if len(e.args) == 0 { if len(e.args) == 0 {
app.nav.toggle() app.nav.toggle()
} else { } else {
dir := app.nav.currDir()
for _, path := range e.args { for _, path := range e.args {
path = replaceTilde(path) path, err := filepath.Abs(replaceTilde(path))
if !filepath.IsAbs(path) { if err != nil {
path = filepath.Join(dir.path, path)
}
if _, err := os.Lstat(path); !os.IsNotExist(err) {
app.nav.toggleSelection(path)
} else {
app.ui.echoerrf("toggle: %s", err) app.ui.echoerrf("toggle: %s", err)
continue
} }
if _, err := os.Lstat(path); os.IsNotExist(err) {
app.ui.echoerrf("toggle: %s", err)
continue
}
app.nav.toggleSelection(path)
} }
} }
case "invert": case "invert":
if !app.nav.init {
return
}
app.nav.invert() app.nav.invert()
case "unselect": case "unselect":
app.nav.unselect() app.nav.unselect()
case "glob-select": case "glob-select":
if !app.nav.init {
return
}
if len(e.args) != 1 { if len(e.args) != 1 {
app.ui.echoerr("glob-select: requires a pattern to match") app.ui.echoerr("glob-select: requires a pattern to match")
return return
@@ -1205,9 +1153,6 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
case "glob-unselect": case "glob-unselect":
if !app.nav.init {
return
}
if len(e.args) != 1 { if len(e.args) != 1 {
app.ui.echoerr("glob-unselect: requires a pattern to match") app.ui.echoerr("glob-unselect: requires a pattern to match")
return return
@@ -1217,10 +1162,6 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
case "copy": case "copy":
if !app.nav.init {
return
}
if err := app.nav.save(clipboardCopy); err != nil { if err := app.nav.save(clipboardCopy); err != nil {
app.ui.echoerrf("copy: %s", err) app.ui.echoerrf("copy: %s", err)
return return
@@ -1232,16 +1173,12 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("copy: %s", err) app.ui.echoerrf("copy: %s", err)
return return
} }
} }
case "cut": case "cut":
if !app.nav.init {
return
}
if err := app.nav.save(clipboardCut); err != nil { if err := app.nav.save(clipboardCut); err != nil {
app.ui.echoerrf("cut: %s", err) app.ui.echoerrf("cut: %s", err)
return return
@@ -1253,16 +1190,12 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("cut: %s", err) app.ui.echoerrf("cut: %s", err)
return return
} }
} }
case "paste": case "paste":
if !app.nav.init {
return
}
if cmd, ok := gOpts.cmds["paste"]; ok { if cmd, ok := gOpts.cmds["paste"]; ok {
cmd.eval(app, e.args) cmd.eval(app, e.args)
} else if err := app.nav.paste(app); err != nil { } else if err := app.nav.paste(app); err != nil {
@@ -1271,9 +1204,6 @@ func (e *callExpr) eval(app *app, _ []string) {
} }
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "clear": case "clear":
if !app.nav.init {
return
}
if err := saveFiles(clipboard{nil, clipboardCut}); err != nil { if err := saveFiles(clipboard{nil, clipboardCut}); err != nil {
app.ui.echoerrf("clear: %s", err) app.ui.echoerrf("clear: %s", err)
return return
@@ -1284,7 +1214,7 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("clear: %s", err) app.ui.echoerrf("clear: %s", err)
return return
} }
@@ -1295,9 +1225,6 @@ func (e *callExpr) eval(app *app, _ []string) {
} }
case "draw": case "draw":
case "redraw": case "redraw":
if !app.nav.init {
return
}
app.ui.screen.Sync() app.ui.screen.Sync()
app.ui.renew() app.ui.renew()
app.nav.resize(app.ui) app.nav.resize(app.ui)
@@ -1305,22 +1232,15 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
onRedraw(app) onRedraw(app)
case "load": case "load":
if !app.nav.init || gOpts.watch { if gOpts.watch {
return return
} }
app.nav.renew() app.nav.renew()
app.ui.loadFile(app, false) app.ui.loadFile(app, false)
case "reload": case "reload":
if !app.nav.init {
return
}
app.nav.reload() app.nav.reload()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "delete": case "delete":
if !app.nav.init {
return
}
if cmd, ok := gOpts.cmds["delete"]; ok { if cmd, ok := gOpts.cmds["delete"]; ok {
cmd.eval(app, e.args) cmd.eval(app, e.args)
app.nav.unselect() app.nav.unselect()
@@ -1328,7 +1248,7 @@ func (e *callExpr) eval(app *app, _ []string) {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
app.ui.echoerrf("delete: %s", err) app.ui.echoerrf("delete: %s", err)
return return
} }
@@ -1351,24 +1271,21 @@ func (e *callExpr) eval(app *app, _ []string) {
} }
} }
case "rename": case "rename":
if !app.nav.init {
return
}
if cmd, ok := gOpts.cmds["rename"]; ok { if cmd, ok := gOpts.cmds["rename"]; ok {
cmd.eval(app, e.args) cmd.eval(app, e.args)
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
return return
} }
} }
} else { } else {
curr, err := app.nav.currFile() curr := app.nav.currFile()
if err != nil { if curr == nil {
app.ui.echoerrf("rename: %s:", err) app.ui.echoerr("rename: empty directory")
return return
} }
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
@@ -1430,9 +1347,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.cmdPrefix = "find-back: " app.ui.cmdPrefix = "find-back: "
app.nav.findBack = true app.nav.findBack = true
case "find-next": case "find-next":
if !app.nav.init {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
old := dir.ind old := dir.ind
for range e.count { for range e.count {
@@ -1446,9 +1360,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "find-prev": case "find-prev":
if !app.nav.init {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
old := dir.ind old := dir.ind
for range e.count { for range e.count {
@@ -1462,9 +1373,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
case "search": case "search":
if !app.nav.init {
return
}
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return
} }
@@ -1475,9 +1383,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.nav.searchPos = dir.pos app.nav.searchPos = dir.pos
app.nav.searchBack = false app.nav.searchBack = false
case "search-back": case "search-back":
if !app.nav.init {
return
}
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return
} }
@@ -1488,9 +1393,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.nav.searchPos = dir.pos app.nav.searchPos = dir.pos
app.nav.searchBack = true app.nav.searchBack = true
case "search-next": case "search-next":
if !app.nav.init {
return
}
for range e.count { for range e.count {
if app.nav.searchBack { if app.nav.searchBack {
if moved, err := app.nav.searchPrev(); err != nil { if moved, err := app.nav.searchPrev(); err != nil {
@@ -1507,9 +1409,6 @@ func (e *callExpr) eval(app *app, _ []string) {
} }
} }
case "search-prev": case "search-prev":
if !app.nav.init {
return
}
for range e.count { for range e.count {
if app.nav.searchBack { if app.nav.searchBack {
if moved, err := app.nav.searchNext(); err != nil { if moved, err := app.nav.searchNext(); err != nil {
@@ -1526,9 +1425,6 @@ func (e *callExpr) eval(app *app, _ []string) {
} }
} }
case "filter": case "filter":
if !app.nav.init {
return
}
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return
} }
@@ -1542,9 +1438,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.cmdAccLeft = []rune(strings.Join(e.args, " ")) app.ui.cmdAccLeft = []rune(strings.Join(e.args, " "))
} }
case "setfilter": case "setfilter":
if !app.nav.init {
return
}
log.Printf("filter: %s", e.args) log.Printf("filter: %s", e.args)
if err := app.nav.setFilter(e.args); err != nil { if err := app.nav.setFilter(e.args); err != nil {
app.ui.echoerrf("filter: %s", err) app.ui.echoerrf("filter: %s", err)
@@ -1571,10 +1464,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.menu = listMarks(app.nav.marks) app.ui.menu = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-remove: " app.ui.cmdPrefix = "mark-remove: "
case "tag": case "tag":
if !app.nav.init {
return
}
tag := "*" tag := "*"
if len(e.args) != 0 { if len(e.args) != 0 {
tag = e.args[0] tag = e.args[0]
@@ -1591,15 +1480,11 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerrf("tag: %s", err) app.ui.echoerrf("tag: %s", err)
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("tag: %s", err) app.ui.echoerrf("tag: %s", err)
} }
} }
case "tag-toggle": case "tag-toggle":
if !app.nav.init {
return
}
tag := "*" tag := "*"
if len(e.args) != 0 { if len(e.args) != 0 {
tag = e.args[0] tag = e.args[0]
@@ -1616,7 +1501,7 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerrf("tag-toggle: %s", err) app.ui.echoerrf("tag-toggle: %s", err)
} }
} else { } else {
if err := remote("send sync"); err != nil { if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("tag-toggle: %s", err) app.ui.echoerrf("tag-toggle: %s", err)
} }
} }
@@ -1632,73 +1517,38 @@ func (e *callExpr) eval(app *app, _ []string) {
path = e.args[0] path = e.args[0]
} }
wd, err := os.Getwd() if err := cd(app, path); err != nil {
if err != nil { app.ui.echoerrf("cd: %s", err)
log.Printf("getting current directory: %s", err)
}
path = replaceTilde(path)
if !filepath.IsAbs(path) {
path = filepath.Join(wd, path)
} else {
path = filepath.Clean(path)
}
if wd != path {
resetIncCmd(app)
preChdir(app)
}
if err := app.nav.cd(path); err != nil {
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFile(app, true)
if wd != path {
app.nav.marks["'"] = wd
restartIncCmd(app)
onChdir(app)
} }
case "select": case "select":
if !app.nav.init {
return
}
if len(e.args) != 1 { if len(e.args) != 1 {
app.ui.echoerr("select: requires an argument") app.ui.echoerr("select: requires an argument")
return return
} }
wd, err := os.Getwd() path, err := filepath.Abs(replaceTilde(e.args[0]))
if err != nil { if err != nil {
log.Printf("getting current directory: %s", err) app.ui.echoerrf("select: %s", err)
}
path := filepath.Dir(replaceTilde(e.args[0]))
if !filepath.IsAbs(path) {
path = filepath.Join(wd, path)
} else {
path = filepath.Clean(path)
}
if wd != path {
resetIncCmd(app)
preChdir(app)
}
if err := app.nav.sel(e.args[0]); err != nil {
app.ui.echoerrf("%s", err)
return return
} }
app.ui.loadFile(app, true) lstat, err := os.Lstat(path)
if err != nil {
app.ui.echoerrf("select: %s", err)
return
}
if wd != path { if err := cd(app, filepath.Dir(path)); err != nil {
app.nav.marks["'"] = wd app.ui.echoerrf("select: %s", err)
restartIncCmd(app) return
onChdir(app) }
dir := app.nav.currDir()
if dir.loading {
dir.files = append(dir.files, &file{FileInfo: lstat})
} else {
app.nav.currDir().sel(filepath.Base(path), app.nav.height)
app.ui.loadFile(app, true)
} }
case "source": case "source":
if len(e.args) != 1 { if len(e.args) != 1 {
@@ -1721,7 +1571,7 @@ func (e *callExpr) eval(app *app, _ []string) {
case 1: case 1:
k, v = e.args[0], "" k, v = e.args[0], ""
case 2: case 2:
k, v = e.args[0], e.args[1] k, v = e.args[0], e.args[1] // don't trim to allow for custom alignment
default: default:
app.ui.echoerr("addcustominfo: requires either 1 or 2 arguments") app.ui.echoerr("addcustominfo: requires either 1 or 2 arguments")
return return
@@ -1733,12 +1583,7 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
dir := filepath.Dir(path) d := app.nav.getDir(filepath.Dir(path))
d, ok := app.nav.dirCache[dir]
if !ok {
app.ui.echoerrf("addcustominfo: dir not loaded: %s", dir)
return
}
var f *file var f *file
for _, file := range d.allFiles { for _, file := range d.allFiles {
@@ -1752,27 +1597,20 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
if len(strings.Trim(v, " ")) == 0 {
v = ""
}
if f.customInfo != v { if f.customInfo != v {
f.customInfo = v f.customInfo = v
// only sort when order changes // only sort when order changes
if getSortBy(dir) == customSort { if getSortBy(d.path) == customSort {
d.sort() d.sort()
} }
} }
case "calcdirsize": case "calcdirsize":
if !app.nav.init {
return
}
err := app.nav.calcDirSize() err := app.nav.calcDirSize()
if err != nil { if err != nil {
app.ui.echoerrf("calcdirsize: %s", err) app.ui.echoerrf("calcdirsize: %s", err)
return return
} }
app.nav.sort() app.nav.sort()
app.ui.sort()
case "clearmaps": case "clearmaps":
// leave `:` and cmaps bound so the user can still exit using `:quit` // leave `:` and cmaps bound so the user can still exit using `:quit`
clear(gOpts.nkeys) clear(gOpts.nkeys)
@@ -1793,16 +1631,10 @@ func (e *callExpr) eval(app *app, _ []string) {
tty.Write([]byte(e.args[0])) tty.Write([]byte(e.args[0]))
case "visual": case "visual":
if !app.nav.init {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
dir.visualAnchor = dir.ind dir.visualAnchor = dir.ind
dir.visualWrap = 0 dir.visualWrap = 0
case "visual-accept": case "visual-accept":
if !app.nav.init {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
for _, path := range dir.visualSelections() { for _, path := range dir.visualSelections() {
if _, ok := app.nav.selections[path]; !ok { if _, ok := app.nav.selections[path]; !ok {
@@ -1815,9 +1647,6 @@ func (e *callExpr) eval(app *app, _ []string) {
dir.visualAnchor = -1 dir.visualAnchor = -1
normal(app) normal(app)
case "visual-unselect": case "visual-unselect":
if !app.nav.init {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
for _, path := range dir.visualSelections() { for _, path := range dir.visualSelections() {
delete(app.nav.selections, path) delete(app.nav.selections, path)
@@ -1828,9 +1657,6 @@ func (e *callExpr) eval(app *app, _ []string) {
dir.visualAnchor = -1 dir.visualAnchor = -1
normal(app) normal(app)
case "visual-discard": case "visual-discard":
if !app.nav.init {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
dir.visualAnchor = -1 dir.visualAnchor = -1
normal(app) normal(app)
@@ -1966,9 +1792,9 @@ func (e *callExpr) eval(app *app, _ []string) {
case "rename: ": case "rename: ":
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
curr, err := app.nav.currFile() curr := app.nav.currFile()
if err != nil { if curr == nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerr("rename: empty directory")
return return
} }
wd, err := os.Getwd() wd, err := os.Getwd()
@@ -2012,7 +1838,7 @@ func (e *callExpr) eval(app *app, _ []string) {
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
return return
} }
@@ -2231,7 +2057,8 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
ind := 0 ind := 0
for ; ind < len(app.ui.cmdAccRight) && unicode.IsSpace(app.ui.cmdAccRight[ind]); ind++ { for ind < len(app.ui.cmdAccRight) && unicode.IsSpace(app.ui.cmdAccRight[ind]) {
ind++
} }
if ind >= len(app.ui.cmdAccRight) { if ind >= len(app.ui.cmdAccRight) {
return return
+2 -2
View File
@@ -7,8 +7,8 @@ require (
github.com/fsnotify/fsnotify v1.9.0 github.com/fsnotify/fsnotify v1.9.0
github.com/gdamore/tcell/v2 v2.9.0 github.com/gdamore/tcell/v2 v2.9.0
github.com/mattn/go-runewidth v0.0.19 github.com/mattn/go-runewidth v0.0.19
golang.org/x/sys v0.38.0 golang.org/x/sys v0.40.0
golang.org/x/term v0.37.0 golang.org/x/term v0.39.0
) )
require ( require (
+4 -4
View File
@@ -31,13 +31,13 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= golang.org/x/term v0.39.0/go.mod h1:yxzUCTP/U+FzoxfdKmLaA0RV1WgE0VY7hXBwKtY/4ww=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
+42 -22
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\-12\-02" "r39" "DOCUMENTATION" .TH "LF" "1" "2026\-02\-04" "r41" "DOCUMENTATION"
.SH NAME .SH NAME
lf \- terminal file manager lf \- terminal file manager
.SH SYNOPSIS .SH SYNOPSIS
@@ -88,8 +88,9 @@ list to \f[I]path\f[R] instead of stdout.
.SS SERVER .SS SERVER
.TP .TP
\f[B]\-remote\f[R] \f[I]command\f[R] \f[B]\-remote\f[R] \f[I]command\f[R]
Send \f[I]command\f[R] to the running server (e.g. Send \f[I]command\f[R] to the running server (i.e.
\f[CR]send\f[R], \f[CR]query\f[R] or \f[CR]quit\f[R]). \f[CR]send\f[R], \f[CR]query\f[R], \f[CR]list\f[R], \f[CR]quit\f[R], or
\f[CR]quit!\f[R]).
See \f[CR]REMOTE COMMANDS\f[R] for more details. See \f[CR]REMOTE COMMANDS\f[R] for more details.
.TP .TP
\f[B]\-server\f[R] \f[B]\-server\f[R]
@@ -310,6 +311,7 @@ infotimefmtold string (default \(aqJan _2 2006\(aq)
menufmt string (default \(dq\(rs033[0m\(dq) menufmt string (default \(dq\(rs033[0m\(dq)
menuheaderfmt string (default \(dq\(rs033[1m\(dq) menuheaderfmt string (default \(dq\(rs033[1m\(dq)
menuselectfmt string (default \(dq\(rs033[7m\(dq) menuselectfmt string (default \(dq\(rs033[7m\(dq)
mergeindicators bool (default false)
mouse bool (default false) mouse bool (default false)
number bool (default false) number bool (default false)
numberfmt string (default \(dq\(rs033[33m\(dq) numberfmt string (default \(dq\(rs033[33m\(dq)
@@ -323,8 +325,8 @@ ratios []int (default \(aq1:2:3\(aq)
relativenumber bool (default false) relativenumber bool (default false)
reverse bool (default false) reverse bool (default false)
roundbox bool (default false) roundbox bool (default false)
rulerfile bool (default false) rulerfile string (default \(dq\(dq)
rulerfmt string (default \(dq %a| %p| \(rs033[7;31m %m \(rs033[0m| \(rs033[7;33m %c \(rs033[0m| \(rs033[7;35m %s \(rs033[0m| \(rs033[7;36m %v \(rs033[0m| \(rs033[7;34m %f \(rs033[0m| %i/%t\(dq) rulerfmt string (default \(dq\(dq)
scrolloff int (default 0) scrolloff int (default 0)
searchmethod string (default \(aqtext\(aq) searchmethod string (default \(aqtext\(aq)
selectfmt string (default \(dq\(rs033[7;35m\(dq) selectfmt string (default \(dq\(rs033[7;35m\(dq)
@@ -490,14 +492,6 @@ Unix /etc/lf/icons \(ti/.config/lf/icons
Windows C:\(rsProgramData\(rslf\(rsicons C:\(rsUsers\(rs<user>\(rsAppData\(rsRoaming\(rslf\(rsicons Windows C:\(rsProgramData\(rslf\(rsicons C:\(rsUsers\(rs<user>\(rsAppData\(rsRoaming\(rslf\(rsicons
.EE .EE
.PP .PP
The ruler file should be located at:
.IP
.EX
OS system\-wide user\-specific
Unix /etc/lf/ruler \(ti/.config/lf/ruler
Windows C:\(rsProgramData\(rslf\(rsruler C:\(rsUsers\(rs<user>\(rsAppData\(rsRoaming\(rslf\(rsruler
.EE
.PP
The selection file should be located at: The selection file should be located at:
.IP .IP
.EX .EX
@@ -686,8 +680,8 @@ Read the configuration file given in the argument.
.SS push .SS push
Simulate key pushes given in the argument. Simulate key pushes given in the argument.
.SS addcustominfo .SS addcustominfo
Update the \f[CR]custom\f[R] info field of the given file with the given Update the \f[CR]custom\f[R] info and \f[CR].Stat.CustomInfo\f[R] field
string. of the given file with the given string.
The info string may contain ANSI escape codes to further customize its The info string may contain ANSI escape codes to further customize its
appearance. appearance.
If no info is provided, clear the file\(aqs info instead. If no info is provided, clear the file\(aqs info instead.
@@ -971,6 +965,12 @@ Format string of the menu.
Format string of the header row in the menu. Format string of the header row in the menu.
.SS menuselectfmt (string) (default \f[CR]\(rs033[7m\f[R]) .SS menuselectfmt (string) (default \f[CR]\(rs033[7m\f[R])
Format string of the currently selected item in the menu. Format string of the currently selected item in the menu.
.SS mergeindicators (bool) (default false)
When \f[CR]mergeindicators\f[R] is enabled, tag and selection indicators
are drawn in a single column to reduce the gap before filenames.
If a file is both tagged and selected, the tag uses the selection format
(e.g.
\f[CR]copyfmt\f[R]) instead of \f[CR]tagfmt\f[R].
.SS mouse (bool) (default false) .SS mouse (bool) (default false)
Send mouse events as input. Send mouse events as input.
.SS number (bool) (default false) .SS number (bool) (default false)
@@ -1060,16 +1060,20 @@ Reverse the direction of sort.
.SS roundbox (bool) (default false) .SS roundbox (bool) (default false)
Draw rounded outer corners when the \f[CR]drawbox\f[R] option is Draw rounded outer corners when the \f[CR]drawbox\f[R] option is
enabled. enabled.
.SS rulerfile (bool) (default false) .SS rulerfile (string) (default \(ga\(ga)
Use the ruler file instead of the \f[CR]rulerfmt\f[R] and Set the path of the ruler file.
\f[CR]statfmt\f[R] options when drawing the ruler at the bottom. If not set, then a default template will be used for the ruler.
Refer to the \c Refer to the \c
.UR https://github.com/gokcehan/lf/blob/master/doc.md#ruler .UR https://github.com/gokcehan/lf/blob/master/doc.md#ruler
RULER section RULER section
.UE \c .UE \c
\ for more information about how the ruler file works. \ for more information about how the ruler file works.
.SS rulerfmt (string) (default \f[CR] %a| %p| \(rs033[7;31m %m \(rs033[0m| \(rs033[7;33m %c \(rs033[0m| \(rs033[7;35m %s \(rs033[0m| \(rs033[7;36m %v \(rs033[0m| \(rs033[7;34m %f \(rs033[0m| %i/%t\f[R]) .SS rulerfmt (string) (default \(ga\(ga)
Format string of the ruler shown in the bottom right corner. Format string of the ruler shown in the bottom right corner.
When set, it will be used along with \f[CR]statfmt\f[R] to draw the
ruler, and \f[CR]rulerfile\f[R] will be ignored.
However, using \f[CR]rulerfile\f[R] is preferred and this option is
provided for backwards compatibility.
.PP .PP
The following special expansions are supported: The following special expansions are supported:
.IP .IP
@@ -1160,6 +1164,9 @@ custom property defined via \(gaaddcustominfo\(ga (empty by default)
.EE .EE
.SS statfmt (string) (default \f[CR]\(rs033[36m%p\(rs033[0m| %c| %u| %g| %S| %t| \-> %l\f[R]) .SS statfmt (string) (default \f[CR]\(rs033[36m%p\(rs033[0m| %c| %u| %g| %S| %t| \-> %l\f[R])
Format string of the file info shown in the bottom left corner. Format string of the file info shown in the bottom left corner.
This option has no effect unless \f[CR]rulerfmt\f[R] is also set.
Using \f[CR]rulerfile\f[R] is preferred and this option is provided for
backwards compatibility.
.PP .PP
The following special expansions are supported: The following special expansions are supported:
.IP .IP
@@ -1849,6 +1856,13 @@ map <a\-h> ${{
}} }}
.EE .EE
.PP .PP
The \f[CR]list\f[R] command prints the IDs of all currently connected
clients:
.IP
.EX
lf \-remote \(aqlist\(aq
.EE
.PP
There is also a \f[CR]quit\f[R] command to quit the server when there There is also a \f[CR]quit\f[R] command to quit the server when there
are no connected clients left, and a \f[CR]quit!\f[R] command to force are no connected clients left, and a \f[CR]quit!\f[R] command to force
quit the server by closing client connections first: quit the server by closing client connections first:
@@ -2499,7 +2513,8 @@ A sample colored icons file can be found at \c
.UR https://github.com/gokcehan/lf/blob/master/etc/icons_colored.example .UR https://github.com/gokcehan/lf/blob/master/etc/icons_colored.example
.UE \c .UE \c
.SH RULER .SH RULER
The ruler can be configured using a ruler file (refer to the \c The ruler can be configured using the \f[CR]rulerfile\f[R] option (refer
to the \c
.UR https://github.com/gokcehan/lf/blob/master/doc.md#configuration .UR https://github.com/gokcehan/lf/blob/master/doc.md#configuration
CONFIGURATION section CONFIGURATION section
.UE \c .UE \c
@@ -2509,8 +2524,6 @@ rendered to create the actual output (refer to \c
.UR https://pkg.go.dev/text/template .UR https://pkg.go.dev/text/template
.UE \c .UE \c
\ for more details on the syntax). \ for more details on the syntax).
This feature is currently experimental and must be enabled via the
\f[CR]rulerfile\f[R] option.
.PP .PP
The following data fields are exported: The following data fields are exported:
.IP .IP
@@ -2533,13 +2546,20 @@ The following data fields are exported:
\&.UserOptions map[string]string The value of user\-defined options (e.g. \(ga{{.UserOptions.foo}}\(ga) \&.UserOptions map[string]string The value of user\-defined options (e.g. \(ga{{.UserOptions.foo}}\(ga)
\&.Stat.Path string Path of the current file \&.Stat.Path string Path of the current file
\&.Stat.Name string Name of the current file \&.Stat.Name string Name of the current file
\&.Stat.Extension string Extension of the current file
\&.Stat.Size uint64 Size of the current file \&.Stat.Size uint64 Size of the current file
\&.Stat.DirSize *uint64 Total size of the current directory if calculated via \(gacalcdirsize\(ga
\&.Stat.DirCount *uint64 Number of items in the current directory if the \(gadircounts\(ga option is enabled
\&.Stat.Permissions string Permissions of the current file \&.Stat.Permissions string Permissions of the current file
\&.Stat.ModTime string Last modified time of the current file (formatted based on the \(gatimefmt\(ga option) \&.Stat.ModTime string Last modified time of the current file (formatted based on the \(gatimefmt\(ga option)
\&.Stat.AccessTime string Last access time of the current file (formatted based on the \(gatimefmt\(ga option)
\&.Stat.BirthTime string Birth time of the current file (formatted based on the \(gatimefmt\(ga option)
\&.Stat.ChangeTime string Last status (inode) change time of the current file (formatted based on the \(gatimefmt\(ga option)
\&.Stat.LinkCount string Number of hard links for the current file \&.Stat.LinkCount string Number of hard links for the current file
\&.Stat.User string User of the current file \&.Stat.User string User of the current file
\&.Stat.Group string Group of the current file \&.Stat.Group string Group of the current file
\&.Stat.Target string Target if the current file is a symbolic link, otherwise a blank string \&.Stat.Target string Target if the current file is a symbolic link, otherwise a blank string
\&.Stat.CustomInfo string Custom property if defined via \(gaaddcustominfo\(ga, otherwise a blank string
.EE .EE
.PP .PP
The following functions are exported: The following functions are exported:
+4 -1
View File
@@ -342,9 +342,12 @@ func main() {
case *showVersion: case *showVersion:
printVersion() printVersion()
case *remoteCmd != "": case *remoteCmd != "":
if err := remote(*remoteCmd); err != nil { resp, err := remote(*remoteCmd)
if err != nil {
log.Fatalf("remote command: %s", err) log.Fatalf("remote command: %s", err)
return
} }
fmt.Print(resp)
case *serverMode: case *serverMode:
if err := os.Chdir(gUser.HomeDir); err != nil { if err := os.Chdir(gUser.HomeDir); err != nil {
log.Print(err) log.Print(err)
+56 -33
View File
@@ -70,7 +70,8 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune {
return rs[b:] return rs[b:]
} }
// Returns the last runes of `rs` that take up at most `maxWidth` space. // runeSliceWidthLastRange returns the last runes of `rs` that take up
// at most `maxWidth` space.
func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune { func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
lastWidth := 0 lastWidth := 0
for i := len(rs) - 1; i >= 0; i-- { for i := len(rs) - 1; i >= 0; i-- {
@@ -83,7 +84,7 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
return rs return rs
} }
// This function is used to escape whitespaces and special characters with // cmdEscape is used to escape whitespace and special characters with
// backslashes in a given string. // backslashes in a given string.
func cmdEscape(s string) string { func cmdEscape(s string) string {
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
@@ -96,8 +97,8 @@ func cmdEscape(s string) string {
return string(buf) return string(buf)
} }
// This function is used to remove backslashes that are used to escape // cmdUnescape is used to remove backslashes that are used to escape
// whitespaces and special characters in a given string. // whitespace and special characters in a given string.
func cmdUnescape(s string) string { func cmdUnescape(s string) string {
esc := false esc := false
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
@@ -123,8 +124,8 @@ func cmdUnescape(s string) string {
return string(buf) return string(buf)
} }
// This function splits the given string by whitespaces. It is aware of escaped // tokenize splits the given string by whitespace. It is aware of escaped
// and quoted whitespaces so that they are not split unintentionally. // and quoted whitespace so that they are not split unintentionally.
func tokenize(s string) []string { func tokenize(s string) []string {
esc := false esc := false
quote := false quote := false
@@ -151,7 +152,7 @@ func tokenize(s string) []string {
return append(toks, string(buf)) return append(toks, string(buf))
} }
// This function splits the first word of a string delimited by whitespace from // splitWord splits the first word of a string delimited by whitespace from
// the rest. This is used to tokenize a string one by one without touching the // the rest. This is used to tokenize a string one by one without touching the
// rest. Whitespace on the left side of both the word and the rest are trimmed. // rest. Whitespace on the left side of both the word and the rest are trimmed.
func splitWord(s string) (word, rest string) { func splitWord(s string) (word, rest string) {
@@ -168,8 +169,8 @@ func splitWord(s string) (word, rest string) {
return return
} }
// This function reads whitespace separated string arrays at each line. Single // readArrays reads whitespace-separated string arrays on each line. Single
// or double quotes can be used to escape whitespaces. Hash characters can be // or double quotes can be used to escape whitespace. Hash characters can be
// used to add a comment until the end of line. Leading and trailing space is // used to add a comment until the end of line. Leading and trailing space is
// trimmed. Empty lines are skipped. // trimmed. Empty lines are skipped.
func readArrays(r io.Reader, minCols, maxCols int) ([][]string, error) { func readArrays(r io.Reader, minCols, maxCols int) ([][]string, error) {
@@ -242,7 +243,7 @@ func readPairs(r io.Reader) ([][]string, error) {
return readArrays(r, 2, 2) return readArrays(r, 2, 2)
} }
// This function converts a size in bytes to a human readable form using // humanize converts a size in bytes to a human-readable form using
// prefixes for either binary (1 KiB = 1024 B) or decimal (1 KB = 1000 B) // prefixes for either binary (1 KiB = 1024 B) or decimal (1 KB = 1000 B)
// multiples. The output should be no more than 5 characters long. // multiples. The output should be no more than 5 characters long.
func humanize(size uint64) string { func humanize(size uint64) string {
@@ -255,9 +256,8 @@ func humanize(size uint64) string {
return fmt.Sprintf("%dB", size) return fmt.Sprintf("%dB", size)
} }
// *Note*: due to [`FileSize.Size()`](https://pkg.go.dev/io/fs#FileInfo) // Note: due to [fs.FileInfo.Size] being `int64`, the maximum
// being `int64`, the maximum possible representable value would be 8 EiB or // possible representable value would be 8 EiB or 9.2 EB.
// 9.2 EB.
prefixes := []string{ prefixes := []string{
"K", // kibi (2^10) or kilo (10^3) "K", // kibi (2^10) or kilo (10^3)
"M", // mebi (2^20) or mega (10^6) "M", // mebi (2^20) or mega (10^6)
@@ -290,8 +290,8 @@ func humanize(size uint64) string {
return fmt.Sprintf("+999%s", prefixes[len(prefixes)-1]) return fmt.Sprintf("+999%s", prefixes[len(prefixes)-1])
} }
// This function returns an ls(1)-style string representation of the given file // permString returns an ls(1)-style string representation of the given file
// mode, to avoid using Go's implementation, which slightly differs. // mode, to avoid using [fs.FileMode.String], which differs slightly.
func permString(m os.FileMode) string { func permString(m os.FileMode) string {
// re-use Perm()'s "-rwxrwxrwx" output and write type into b[0] // re-use Perm()'s "-rwxrwxrwx" output and write type into b[0]
b := []byte(m.Perm().String()) b := []byte(m.Perm().String())
@@ -337,7 +337,7 @@ func permString(m os.FileMode) string {
return string(b) return string(b)
} }
// This function compares two strings for natural sorting which takes into // naturalCmp compares two strings for natural sorting which takes into
// account the values of numbers in strings. For example, '2' is ordered before // account the values of numbers in strings. For example, '2' is ordered before
// '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing // '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing
// numbers, if they have the same value then the length of the string is also // numbers, if they have the same value then the length of the string is also
@@ -389,8 +389,8 @@ func naturalCmp(s1, s2 string) int {
} }
} }
// This function returns the extension of a file with a leading dot // getFileExtension returns the extension of a file with a leading dot.
// it returns an empty string if extension could not be determined // It returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions // i.e. directories, filenames without extensions
func getFileExtension(file fs.FileInfo) string { func getFileExtension(file fs.FileInfo) string {
if file.IsDir() { if file.IsDir() {
@@ -403,12 +403,12 @@ func getFileExtension(file fs.FileInfo) string {
return filepath.Ext(file.Name()) return filepath.Ext(file.Name())
} }
// This function truncates a filename at a given position. // truncateFilename truncates a filename at a given position.
// The position is specified as percentage indicating where the truncation // The position is specified as percentage indicating where the truncation
// character will appear (0 means left, 50 means middle, 100 means right). // character will appear (0 means left, 50 means middle, 100 means right).
// The file extension is not affected by truncation, however it will be clipped // The file extension is not affected by truncation, however it will be clipped
// if it exceeds the allowed width. // if it exceeds the allowed width.
func truncateFilename(file fs.FileInfo, maxWidth int, truncatePct int, truncateChar rune) string { func truncateFilename(file fs.FileInfo, maxWidth, truncatePct int, truncateChar rune) string {
filename := file.Name() filename := file.Name()
if runeSliceWidth([]rune(filename)) <= maxWidth { if runeSliceWidth([]rune(filename)) <= maxWidth {
return filename return filename
@@ -433,8 +433,8 @@ func truncateFilename(file fs.FileInfo, maxWidth int, truncatePct int, truncateC
return string(result) return string(result)
} }
// This function deletes entries from a map if the key is either the given path // deletePathRecursive deletes entries from a map if the key is either the given
// or a subpath of it. // path or a subpath of it.
// This is useful for clearing cached data when a directory is moved or deleted. // This is useful for clearing cached data when a directory is moved or deleted.
func deletePathRecursive[T any](m map[string]T, path string) { func deletePathRecursive[T any](m map[string]T, path string) {
delete(m, path) delete(m, path)
@@ -446,17 +446,7 @@ func deletePathRecursive[T any](m map[string]T, path string) {
} }
} }
// This function takes an escape sequence option (e.g. `\033[1m`) and outputs a // readLines reads lines from a file to be displayed as a preview.
// complete format string (e.g. `\033[1m%s\033[0m`).
func optionToFmtstr(optstr string) string {
if !strings.Contains(optstr, "%s") {
return optstr + "%s\033[0m"
} else {
return optstr
}
}
// This function reads lines from a file to be displayed as a preview.
// The number of lines to read is capped since files can be very large. // The number of lines to read is capped since files can be very large.
// Lines are split on `\n` characters, and `\r` characters are discarded. // Lines are split on `\n` characters, and `\r` characters are discarded.
// Sixel images are also detected and stored as separate lines. // Sixel images are also detected and stored as separate lines.
@@ -523,6 +513,39 @@ func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool,
} }
} }
// getWidths calculates the widths of windows as the result of applying the
// `ratios` option to the screen width. One column is allocated for each divider
// between windows. The `drawbox` option requires an additional two columns to
// draw the left and right borders.
func getWidths(wtot int, ratios []int, drawbox bool) []int {
rlen := len(ratios)
wtot -= rlen - 1
if drawbox {
wtot -= 2
}
wtot = max(wtot, 0)
rtot := 0
for _, r := range ratios {
rtot += r
}
divround := func(x, y int) int {
return (x + y/2) / y
}
widths := make([]int, rlen)
rsum := 0
wsum := 0
for i, r := range ratios {
rsum += r
widths[i] = divround(wtot*rsum, rtot) - wsum
wsum += widths[i]
}
return widths
}
// 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
+60 -16
View File
@@ -344,6 +344,39 @@ func TestHumanize(t *testing.T) {
} }
} }
func TestPermString(t *testing.T) {
tests := []struct {
name string
m os.FileMode
exp string
}{
{"none", 0, "----------"},
{"regular file", 0o644, "-rw-r--r--"},
{"executable", 0o755, "-rwxr-xr-x"},
{"directory", 0o755 | os.ModeDir, "drwxr-xr-x"},
{"symbolic link", 0o777 | os.ModeSymlink, "lrwxrwxrwx"},
{"named pipe", 0o644 | os.ModeNamedPipe, "prw-r--r--"},
{"socket", 0o777 | os.ModeSocket, "srwxrwxrwx"},
{"character device", 0o660 | os.ModeCharDevice, "crw-rw----"},
{"block device", 0o660 | os.ModeDevice, "brw-rw----"},
{"setuid", 0o644 | os.ModeSetuid, "-rwSr--r--"},
{"setuid executable", 0o755 | os.ModeSetuid, "-rwsr-xr-x"},
{"setgid", 0o644 | os.ModeSetgid, "-rw-r-Sr--"},
{"setgid executable", 0o755 | os.ModeSetgid, "-rwxr-sr-x"},
{"sticky", 0o644 | os.ModeSticky, "-rw-r--r-T"},
{"sticky executable", 0o755 | os.ModeSticky, "-rwxr-xr-t"},
{"sticky directory", 0o777 | os.ModeDir | os.ModeSticky, "drwxrwxrwt"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := permString(test.m); got != test.exp {
t.Errorf("at input '%#o' expected '%s' but got '%s'", test.m, test.exp, got)
}
})
}
}
func TestNaturalCmp(t *testing.T) { func TestNaturalCmp(t *testing.T) {
tests := []struct { tests := []struct {
s1 string s1 string
@@ -475,22 +508,6 @@ func TestTruncateFilename(t *testing.T) {
} }
} }
func TestOptionToFmtstr(t *testing.T) {
tests := []struct {
s string
exp string
}{
{"\033[1m", "\033[1m%s\033[0m"},
{"\033[1;7;31;42m", "\033[1;7;31;42m%s\033[0m"},
}
for _, test := range tests {
if got := optionToFmtstr(test.s); got != test.exp {
t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got)
}
}
}
func TestReadLines(t *testing.T) { func TestReadLines(t *testing.T) {
tests := []struct { tests := []struct {
s string s string
@@ -542,3 +559,30 @@ func TestReadLines(t *testing.T) {
} }
} }
} }
func TestGetWidths(t *testing.T) {
tests := []struct {
wtot int
ratios []int
drawbox bool
exp []int
}{
{0, []int{1}, false, []int{0}},
{0, []int{1}, true, []int{0}},
{0, []int{1, 3, 2}, false, []int{0, 0, 0}},
{0, []int{1, 3, 2}, true, []int{0, 0, 0}},
{14, []int{1, 3, 2}, false, []int{2, 6, 4}},
{16, []int{1, 3, 2}, true, []int{2, 6, 4}},
{23, []int{1, 3, 2, 4}, false, []int{2, 6, 4, 8}}, // windows end at 2.0, 8.0, 12.0, 20.0 respectively
{24, []int{1, 3, 2, 4}, false, []int{2, 6, 5, 8}}, // windows end at 2.1, 8.4, 12.6, 21.0 respectively
{25, []int{1, 3, 2, 4}, false, []int{2, 7, 4, 9}}, // windows end at 2.2, 8.8, 13.2, 22.0 respectively
{26, []int{1, 3, 2, 4}, false, []int{2, 7, 5, 9}}, // windows end at 2.3, 9.2, 13.8, 23.0 respectively
}
for _, test := range tests {
widths := getWidths(test.wtot, test.ratios, test.drawbox)
if !reflect.DeepEqual(widths, test.exp) {
t.Errorf("at input (%v, %v, %v) expected %v but got %v", test.wtot, test.ratios, test.drawbox, test.exp, widths)
}
}
}
+236 -274
View File
@@ -2,6 +2,7 @@ package main
import ( import (
"bufio" "bufio"
"bytes"
"cmp" "cmp"
"errors" "errors"
"fmt" "fmt"
@@ -22,27 +23,28 @@ import (
"github.com/djherbis/times" "github.com/djherbis/times"
) )
// A linkState describes whether a file is a symlink and whether its target exists.
type linkState byte type linkState byte
const ( const (
notLink linkState = iota notLink linkState = iota // Not a symbolic link.
working working // Symbolic link with an existing target.
broken broken // Symbolic link with a missing target.
) )
type file struct { type file struct {
os.FileInfo os.FileInfo // stat information
linkState linkState linkState linkState // symlink state
linkTarget string linkTarget string // path a symlink points to
path string path string // full path including the name
dirCount int dirCount *uint64 // number of items inside the directory
dirSize int64 dirSize *uint64 // total directory size (needs to be calculated via `calcdirsize`)
accessTime time.Time accessTime time.Time // time of last access
birthTime time.Time birthTime time.Time // time of file birth
changeTime time.Time changeTime time.Time // time of last status (inode) change
customInfo string customInfo string // property defined via `addcustominfo`
ext string ext string // file extension (including the dot)
err error err error // potential error returned by [os.Lstat]
} }
func newFile(path string) *file { func newFile(path string) *file {
@@ -52,15 +54,10 @@ func newFile(path string) *file {
return &file{ return &file{
FileInfo: &fakeStat{name: filepath.Base(path)}, FileInfo: &fakeStat{name: filepath.Base(path)},
linkState: notLink, linkState: notLink,
linkTarget: "",
path: path, path: path,
dirCount: -1,
dirSize: -1,
accessTime: time.Unix(0, 0), accessTime: time.Unix(0, 0),
birthTime: time.Unix(0, 0), birthTime: time.Unix(0, 0),
changeTime: time.Unix(0, 0), changeTime: time.Unix(0, 0),
customInfo: "",
ext: "",
err: err, err: err,
} }
} }
@@ -84,7 +81,7 @@ func newFile(path string) *file {
ts := times.Get(lstat) ts := times.Get(lstat)
at := ts.AccessTime() at := ts.AccessTime()
// from times docs: // from [times.Timespec] docs:
// ChangeTime() panics unless HasChangeTime() is true and // ChangeTime() panics unless HasChangeTime() is true and
// BirthTime() panics unless HasBirthTime() is true. // BirthTime() panics unless HasBirthTime() is true.
@@ -99,19 +96,20 @@ func newFile(path string) *file {
ct = ts.ChangeTime() ct = ts.ChangeTime()
} }
dirCount := -1 var dirCount *uint64
if lstat.IsDir() && getDirCounts(filepath.Dir(path)) { if lstat.IsDir() && getDirCounts(filepath.Dir(path)) {
d, err := os.Open(path) d, err := os.Open(path)
if err != nil { if err != nil {
dirCount = -2 log.Printf("opening file: %s", err)
} else { } else {
names, err := d.Readdirnames(10000) names, err := d.Readdirnames(10000)
d.Close() d.Close()
if names == nil && err != io.EOF { if names == nil && err != io.EOF {
dirCount = -2 log.Printf("reading directory: %s", err)
} else { } else {
dirCount = len(names) v := uint64(len(names))
dirCount = &v
} }
} }
} }
@@ -122,36 +120,15 @@ func newFile(path string) *file {
linkTarget: linkTarget, linkTarget: linkTarget,
path: path, path: path,
dirCount: dirCount, dirCount: dirCount,
dirSize: -1,
accessTime: at, accessTime: at,
birthTime: bt, birthTime: bt,
changeTime: ct, changeTime: ct,
customInfo: "",
ext: getFileExtension(lstat), ext: getFileExtension(lstat),
err: nil,
} }
} }
func (file *file) TotalSize() int64 {
if file.IsDir() {
if file.dirSize >= 0 {
return file.dirSize
}
return 0
}
return file.Size()
}
func (file *file) isPreviewable() bool { func (file *file) isPreviewable() bool {
if file.Mode().IsRegular() { return !file.IsDir() || gOpts.dirpreviews
return true
}
if file.IsDir() && gOpts.dirpreviews {
return true
}
return false
} }
type fakeStat struct { type fakeStat struct {
@@ -175,17 +152,20 @@ func readdir(path string) ([]*file, error) {
files := make([]*file, 0, len(names)) files := make([]*file, 0, len(names))
for _, fname := range names { for _, fname := range names {
files = append(files, newFile(filepath.Join(path, fname))) file := newFile(filepath.Join(path, fname))
if !os.IsNotExist(file.err) {
files = append(files, file)
}
} }
return files, err return files, err
} }
type dir struct { type dir struct {
loading bool // directory is loading from disk loading bool // whether directory is loading from disk
loadTime time.Time // last load time loadTime time.Time // last load time
ind int // index of current entry in files ind int // 0-based index of current entry in dir.files
pos int // position of current entry in ui pos int // 0-based cursor row in directory window
path string // full path of directory path string // full path of directory
files []*file // displayed files in directory including or excluding hidden ones files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files) allFiles []*file // all files in directory including hidden ones (same array as files)
@@ -196,7 +176,7 @@ type dir struct {
hidden bool // hidden value from last sort hidden bool // hidden value from last sort
reverse bool // reverse value from last sort reverse bool // reverse value from last sort
visualAnchor int // index where Visual mode was initiated visualAnchor int // index where Visual mode was initiated
visualWrap int // wrap direction in Visual mode visualWrap int // wrap direction in Visual mode (0: none, +: bottom->top, -: top->bottom)
hiddenfiles []string // hiddenfiles value from last sort hiddenfiles []string // hiddenfiles value from last sort
filter []string // last filter for this directory filter []string // last filter for this directory
ignorecase bool // ignorecase value from last sort ignorecase bool // ignorecase value from last sort
@@ -295,14 +275,29 @@ func (dir *dir) sort() {
return cmp.Compare(normalize(f1.Name()), normalize(f2.Name())) return cmp.Compare(normalize(f1.Name()), normalize(f2.Name()))
}) })
case sizeSort: case sizeSort:
sizeVal := func(f *file) int64 { sizeVal := func(f *file) *uint64 {
if f.IsDir() && dir.dircounts { if f.IsDir() && dir.dircounts {
return int64(f.dirCount) return f.dirCount
} }
return f.TotalSize() if f.dirSize != nil {
return f.dirSize
}
v := uint64(f.Size())
return &v
} }
applySort(func(f1, f2 *file) int { applySort(func(f1, f2 *file) int {
return cmp.Compare(sizeVal(f1), sizeVal(f2)) s1 := sizeVal(f1)
s2 := sizeVal(f2)
switch {
case s1 == nil && s2 == nil:
return 0
case s1 == nil && s2 != nil:
return -1
case s1 != nil && s2 == nil:
return 1
default:
return cmp.Compare(*s1, *s2)
}
}) })
case timeSort: case timeSort:
applySort(func(f1, f2 *file) int { applySort(func(f1, f2 *file) int {
@@ -365,7 +360,7 @@ func (dir *dir) name() string {
} }
func (nav *nav) isVisualMode() bool { func (nav *nav) isVisualMode() bool {
return nav.init && nav.currDir().visualAnchor != -1 return nav.currDir().visualAnchor != -1
} }
func (dir *dir) visualSelections() []string { func (dir *dir) visualSelections() []string {
@@ -435,11 +430,12 @@ func (dir *dir) boundPos(height int) {
dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind)) dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind))
} }
// clipboardMode controls the clipboard's behavior when pasting.
type clipboardMode byte type clipboardMode byte
const ( const (
clipboardCopy = iota clipboardCopy clipboardMode = iota // Copy on paste.
clipboardCut clipboardCut // Move on paste.
) )
type clipboard struct { type clipboard struct {
@@ -448,8 +444,7 @@ type clipboard struct {
} }
type nav struct { type nav struct {
init bool dirPaths []string
dirs []*dir
copyJobs int copyJobs int
copyBytes int64 copyBytes int64
copyTotal int64 copyTotal int64
@@ -499,32 +494,30 @@ type nav struct {
jumpListInd int jumpListInd int
} }
func (nav *nav) loadDir(path string) *dir { func (nav *nav) getDir(path string) *dir {
d, ok := nav.dirCache[path] if d, ok := nav.dirCache[path]; ok {
if !ok {
go func() {
nav.dirChan <- newDir(path)
}()
d := &dir{
loading: true,
path: path,
sortby: getSortBy(path),
dircounts: getDirCounts(path),
dirfirst: getDirFirst(path),
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
visualAnchor: -1,
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
}
nav.dirCache[path] = d
return d return d
} }
nav.checkDir(d) go func() {
nav.dirChan <- newDir(path)
}()
d := &dir{
loading: true,
path: path,
sortby: getSortBy(path),
dircounts: getDirCounts(path),
dirfirst: getDirFirst(path),
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
visualAnchor: -1,
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
}
nav.dirCache[path] = d
return d return d
} }
@@ -577,24 +570,26 @@ func (nav *nav) checkDir(dir *dir) {
} }
} }
func (nav *nav) updateDirs(wd string) { func (nav *nav) loadDirs() {
var dirs []*dir wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
return
}
wd = filepath.Clean(wd) var dirPaths []string
for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) { for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
dir := nav.loadDir(curr) dirPaths = append(dirPaths, curr)
dir := nav.getDir(curr)
if base != "" { if base != "" {
dir.sel(base, nav.height) dir.sel(base, nav.height)
} }
dirs = append(dirs, dir)
} }
for i, j := 0, len(dirs)-1; i < j; i, j = i+1, j-1 { slices.Reverse(dirPaths)
dirs[i], dirs[j] = dirs[j], dirs[i] nav.dirPaths = dirPaths
}
nav.dirs = dirs
} }
func newNav(ui *ui) *nav { func newNav(ui *ui) *nav {
@@ -662,8 +657,9 @@ func (nav *nav) cdJumpListNext() {
} }
func (nav *nav) renew() { func (nav *nav) renew() {
for _, d := range nav.dirs { for _, path := range nav.dirPaths {
nav.checkDir(d) dir := nav.getDir(path)
nav.checkDir(dir)
} }
for m := range nav.selections { for m := range nav.selections {
@@ -678,14 +674,16 @@ func (nav *nav) renew() {
} }
func (nav *nav) reload() { func (nav *nav) reload() {
curr := nav.currFile()
clear(nav.dirCache) clear(nav.dirCache)
clear(nav.regCache) clear(nav.regCache)
curr, err := nav.currFile() nav.loadDirs()
nav.updateDirs(nav.currDir().path)
if err == nil { if curr != nil {
last := nav.dirs[len(nav.dirs)-1] dir := nav.currDir()
last.files = append(last.files, curr) dir.files = append(dir.files, curr)
} }
} }
@@ -698,8 +696,8 @@ func (nav *nav) resize(ui *ui) {
nav.height = previewWin.h nav.height = previewWin.h
nav.previewWidth = previewWin.w nav.previewWidth = previewWin.w
for _, dir := range nav.dirs { for _, path := range nav.dirPaths {
dir.boundPos(nav.height) nav.getDir(path).boundPos(nav.height)
} }
clear(nav.regCache) clear(nav.regCache)
@@ -707,24 +705,22 @@ func (nav *nav) resize(ui *ui) {
} }
func (nav *nav) position() { func (nav *nav) position() {
if !nav.init { var path string
return var base string
}
path := nav.currDir().path for i := len(nav.dirPaths) - 1; i >= 0; i-- {
for i := len(nav.dirs) - 2; i >= 0; i-- { path = nav.dirPaths[i]
nav.dirs[i].sel(filepath.Base(path), nav.height) if i < len(nav.dirPaths)-1 {
path = filepath.Dir(path) nav.getDir(path).sel(base, nav.height)
}
base = filepath.Base(path)
} }
} }
func (nav *nav) exportFiles() { func (nav *nav) exportFiles() {
if !nav.init {
return
}
var currFile string var currFile string
if curr, err := nav.currFile(); err == nil { if curr := nav.currFile(); curr != nil {
currFile = quoteString(curr.path) currFile = quoteString(curr.path)
} }
@@ -753,24 +749,29 @@ func (nav *nav) exportFiles() {
} }
func (nav *nav) preloadLoop(ui *ui) { func (nav *nav) preloadLoop(ui *ui) {
processed := make(map[string]struct{}) stack := []string{}
process := func(path string) {
if _, ok := processed[path]; !ok { push := func(path string) {
nav.preview(path, ui.wins[len(ui.wins)-1], "preload") stack = slices.DeleteFunc(stack, func(s string) bool { return s == path })
processed[path] = struct{}{} stack = append(stack, path)
}
} }
for path := range nav.preloadChan { pop := func() string {
clear(processed) path := stack[len(stack)-1]
process(path) stack = stack[:len(stack)-1]
loop: return path
for { }
for {
if len(stack) == 0 {
push(<-nav.preloadChan)
} else {
select { select {
case path = <-nav.preloadChan: case path := <-nav.preloadChan:
process(path) push(path)
default: default:
break loop path := pop()
nav.preview(path, ui.wins[len(ui.wins)-1], "preload")
} }
} }
} }
@@ -791,14 +792,27 @@ func (nav *nav) previewLoop(ui *ui) {
} }
win := ui.wins[len(ui.wins)-1] win := ui.wins[len(ui.wins)-1]
if isClear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview { if isClear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
cmd := exec.Command(gOpts.cleaner, prev, cmd := exec.Command(
gOpts.cleaner,
prev,
strconv.Itoa(win.w), strconv.Itoa(win.w),
strconv.Itoa(win.h), strconv.Itoa(win.h),
strconv.Itoa(win.x), strconv.Itoa(win.x),
strconv.Itoa(win.y), strconv.Itoa(win.y),
path) path,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err) var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
log.Printf("cleaning preview: %s", err)
}
}
if s := strings.TrimSpace(stderr.String()); s != "" {
s = strings.Join(strings.Fields(s), " ")
log.Printf("cleaning preview (stderr): %s", s)
} }
nav.volatilePreview = false nav.volatilePreview = false
} }
@@ -825,7 +839,7 @@ func matchPattern(pattern, name, path string) bool {
} }
func (nav *nav) preload() { func (nav *nav) preload() {
if !nav.init || !gOpts.preview || !gOpts.preload { if !gOpts.preview || !gOpts.preload {
return return
} }
@@ -852,12 +866,11 @@ func (nav *nav) preload() {
} }
nav.startPreview() nav.startPreview()
for i := 0; i <= nav.height/2; i++ { for i := nav.height / 2; i >= 1; i-- {
doPreload(dir.ind - i)
doPreload(dir.ind + i) doPreload(dir.ind + i)
} }
for i := 1; i <= nav.height/2; i++ { doPreload(dir.ind)
doPreload(dir.ind - i)
}
} }
func (nav *nav) preview(path string, win *win, mode string) { func (nav *nav) preview(path string, win *win, mode string) {
@@ -884,6 +897,8 @@ func (nav *nav) preview(path string, win *win, mode string) {
strconv.Itoa(win.y), strconv.Itoa(win.y),
mode, mode,
) )
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.StdoutPipe() out, err := cmd.StdoutPipe()
if err != nil { if err != nil {
@@ -906,10 +921,24 @@ func (nav *nav) preview(path string, win *win, mode string) {
log.Printf("loading file: %s", err) log.Printf("loading file: %s", err)
} }
} }
if s := strings.TrimSpace(stderr.String()); s != "" {
s = strings.Join(strings.Fields(s), " ")
log.Printf("loading file (stderr): %s", s)
}
}() }()
defer out.Close() defer out.Close()
reader = bufio.NewReader(out) reader = bufio.NewReader(out)
} else { } else {
lstat, err := os.Lstat(path)
if err != nil {
log.Printf("lstat: %s", err)
return
}
if !lstat.Mode().IsRegular() {
return
}
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
log.Printf("opening file: %s", err) log.Printf("opening file: %s", err)
@@ -930,7 +959,7 @@ func (nav *nav) preview(path string, win *win, mode string) {
func (nav *nav) loadReg(path string, volatile bool) *reg { func (nav *nav) loadReg(path string, volatile bool) *reg {
r, ok := nav.regCache[path] r, ok := nav.regCache[path]
if !ok { if !ok || (!gOpts.preload && r.loading) {
r = &reg{loading: true, loadTime: time.Now(), path: path} r = &reg{loading: true, loadTime: time.Now(), path: path}
nav.regCache[path] = r nav.regCache[path] = r
nav.startPreview() nav.startPreview()
@@ -982,10 +1011,18 @@ func (nav *nav) startPreview() {
} }
func (nav *nav) sort() { func (nav *nav) sort() {
for _, d := range nav.dirs { for _, path := range nav.dirPaths {
name := d.name() dir := nav.getDir(path)
d.sort() name := dir.name()
d.sel(name, nav.height) dir.sort()
dir.sel(name, nav.height)
}
if curr := nav.currFile(); curr != nil && curr.IsDir() {
dir := nav.getDir(curr.path)
name := dir.name()
dir.sort()
dir.sel(name, nav.height)
} }
} }
@@ -1063,93 +1100,57 @@ func (nav *nav) down(dist int) bool {
func (nav *nav) scrollUp(dist int) bool { func (nav *nav) scrollUp(dist int) bool {
dir := nav.currDir() dir := nav.currDir()
// when reached top do nothing
if istop := dir.ind == dir.pos; istop {
return false
}
old := dir.ind old := dir.ind
minedge := min(nav.height/2, gOpts.scrolloff) oldPos := dir.pos
dir.pos += dist dir.pos += dist
dir.boundPos(nav.height)
// jump to ensure minedge when edge < minedge dir.ind -= dist - (dir.pos - oldPos)
edge := nav.height - dir.pos dir.ind = max(dir.ind, dir.pos)
delta := min(0, edge-minedge-1)
dir.pos = min(dir.pos, nav.height-minedge-1)
// update dir.ind accordingly
dir.ind += delta
dir.ind = min(dir.ind, dir.ind-(dir.pos-nav.height+1))
// prevent cursor disappearing downwards
dir.pos = min(dir.pos, nav.height-1)
return old != dir.ind return old != dir.ind
} }
func (nav *nav) scrollDown(dist int) bool { func (nav *nav) scrollDown(dist int) bool {
dir := nav.currDir() dir := nav.currDir()
maxind := len(dir.files) - 1
// reached bottom
if dir.ind-dir.pos > maxind-nav.height {
return false
}
old := dir.ind old := dir.ind
minedge := min(nav.height/2, gOpts.scrolloff) oldPos := dir.pos
dir.pos -= dist dir.pos -= dist
dir.boundPos(nav.height)
// jump to ensure minedge when edge < minedge dir.ind += dist - (oldPos - dir.pos)
delta := min(0, dir.pos-minedge) dir.ind = min(dir.ind, dir.pos+max(len(dir.files)-nav.height, 0))
dir.pos = max(dir.pos, minedge)
// update dir.ind accordingly
dir.ind -= delta
dir.ind = max(dir.ind, dir.ind-(dir.pos-minedge))
dir.ind = min(maxind, dir.ind)
// prevent disappearing
dir.pos = max(dir.pos, 0)
return old != dir.ind return old != dir.ind
} }
func (nav *nav) updir() error { func (nav *nav) updir() error {
if len(nav.dirs) <= 1 { if len(nav.dirPaths) < 2 {
return nil return nil
} }
dir := nav.currDir() if err := os.Chdir(nav.dirPaths[len(nav.dirPaths)-2]); err != nil {
nav.dirs = nav.dirs[:len(nav.dirs)-1]
if err := os.Chdir(filepath.Dir(dir.path)); err != nil {
return fmt.Errorf("updir: %w", err) return fmt.Errorf("updir: %w", err)
} }
nav.dirPaths = nav.dirPaths[:len(nav.dirPaths)-1]
return nil return nil
} }
func (nav *nav) open() error { func (nav *nav) open() error {
curr, err := nav.currFile() curr := nav.currFile()
if err != nil { if curr == nil {
return fmt.Errorf("open: %w", err) return nil
} }
path := curr.path if err := os.Chdir(curr.path); err != nil {
dir := nav.loadDir(path)
nav.dirs = append(nav.dirs, dir)
if err := os.Chdir(path); err != nil {
return fmt.Errorf("open: %w", err) return fmt.Errorf("open: %w", err)
} }
nav.dirPaths = append(nav.dirPaths, curr.path)
return nil return nil
} }
@@ -1255,15 +1256,12 @@ func (nav *nav) toggleSelection(path string) {
} }
func (nav *nav) toggle() { func (nav *nav) toggle() {
curr, err := nav.currFile() if curr := nav.currFile(); curr != nil {
if err != nil { nav.toggleSelection(curr.path)
return
} }
nav.toggleSelection(curr.path)
} }
func (nav *nav) tagToggleSelection(path string, tag string) { func (nav *nav) tagToggleSelection(path, tag string) {
if _, ok := nav.tags[path]; ok { if _, ok := nav.tags[path]; ok {
delete(nav.tags, path) delete(nav.tags, path)
} else { } else {
@@ -1306,10 +1304,8 @@ func (nav *nav) tag(tag string) error {
} }
func (nav *nav) invert() { func (nav *nav) invert() {
dir := nav.currDir() for _, file := range nav.currDir().files {
for _, f := range dir.files { nav.toggleSelection(file.path)
path := filepath.Join(dir.path, f.Name())
nav.toggleSelection(path)
} }
} }
@@ -1383,7 +1379,7 @@ loop:
nav.renew() nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
sendErr("%v", err) sendErr("%v", err)
} }
} }
@@ -1489,7 +1485,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
nav.renew() nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
sendErr("%v", err) sendErr("%v", err)
} }
} }
@@ -1549,7 +1545,7 @@ func (nav *nav) del(app *app) error {
nav.renew() nav.renew()
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if _, err := remote("send load"); err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo app.ui.exprChan <- echo
@@ -1579,7 +1575,8 @@ func (nav *nav) rename() error {
// this clears only the current instance of lf, and not any other instances. // this clears only the current instance of lf, and not any other instances.
deletePathRecursive(nav.regCache, newPath) deletePathRecursive(nav.regCache, newPath)
deletePathRecursive(nav.dirCache, newPath) deletePathRecursive(nav.dirCache, newPath)
dir := nav.loadDir(filepath.Dir(newPath)) dir := nav.getDir(filepath.Dir(newPath))
nav.checkDir(dir)
if dir.loading { if dir.loading {
for i := range dir.allFiles { for i := range dir.allFiles {
@@ -1622,56 +1619,16 @@ func (nav *nav) sync() error {
return err return err
} }
func (nav *nav) cd(wd string) error { func (nav *nav) cd(path string) error {
wd = replaceTilde(wd) if err := os.Chdir(path); err != nil {
wd = filepath.Clean(wd) return err
if !filepath.IsAbs(wd) {
wd = filepath.Join(nav.currDir().path, wd)
} }
if err := os.Chdir(wd); err != nil { nav.loadDirs()
return fmt.Errorf("cd: %w", err)
}
nav.updateDirs(wd)
nav.addJumpList() nav.addJumpList()
return nil return nil
} }
func (nav *nav) sel(path string) error {
path = replaceTilde(path)
path = filepath.Clean(path)
lstat, err := os.Lstat(path)
if err != nil {
return fmt.Errorf("select: %w", err)
}
dir := filepath.Dir(path)
if err := nav.cd(dir); err != nil {
return fmt.Errorf("select: %w", err)
}
base := filepath.Base(path)
last := nav.currDir()
if last.loading {
last.files = append(last.files, &file{FileInfo: lstat})
}
for i, f := range last.files {
if f.Name() == base {
nav.move(i)
break
}
}
return nil
}
func (nav *nav) globSel(pattern string, invert bool) error { func (nav *nav) globSel(pattern string, invert bool) error {
dir := nav.currDir() dir := nav.currDir()
anyMatched := false anyMatched := false
@@ -1992,17 +1949,22 @@ func (nav *nav) writeTags() error {
} }
func (nav *nav) currDir() *dir { func (nav *nav) currDir() *dir {
return nav.dirs[len(nav.dirs)-1] if len(nav.dirPaths) == 0 {
} nav.loadDirs()
func (nav *nav) currFile() (*file, error) {
dir := nav.dirs[len(nav.dirs)-1]
if len(dir.files) == 0 {
return nil, errors.New("empty directory")
} }
return dir.files[dir.ind], nil path := nav.dirPaths[len(nav.dirPaths)-1]
return nav.getDir(path)
}
func (nav *nav) currFile() *file {
dir := nav.currDir()
if len(dir.files) == 0 {
return nil
}
return dir.files[dir.ind]
} }
type indexedSelections struct { type indexedSelections struct {
@@ -2040,16 +2002,15 @@ func (nav *nav) currSelections() []string {
} }
func (nav *nav) currFileOrSelections() (list []string, err error) { func (nav *nav) currFileOrSelections() (list []string, err error) {
sel := nav.currSelections() if sel := nav.currSelections(); len(sel) > 0 {
return sel, nil
}
if len(sel) == 0 { if curr := nav.currFile(); curr != nil {
curr, err := nav.currFile()
if err != nil {
return nil, errors.New("no file selected")
}
return []string{curr.path}, nil return []string{curr.path}, nil
} }
return sel, nil
return nil, errors.New("no file selected")
} }
func (nav *nav) calcDirSize() error { func (nav *nav) calcDirSize() error {
@@ -2059,14 +2020,15 @@ func (nav *nav) calcDirSize() error {
if err != nil { if err != nil {
return err return err
} }
f.dirSize = total v := uint64(total)
f.dirSize = &v
} }
return nil return nil
} }
if len(nav.selections) == 0 { if len(nav.selections) == 0 {
curr, err := nav.currFile() curr := nav.currFile()
if err != nil { if curr == nil {
return errors.New("no file selected") return errors.New("no file selected")
} }
return calc(curr) return calc(curr)
@@ -2078,7 +2040,7 @@ func (nav *nav) calcDirSize() error {
continue continue
} }
path, name := filepath.Dir(sel), filepath.Base(sel) path, name := filepath.Dir(sel), filepath.Base(sel)
dir := nav.loadDir(path) dir := nav.getDir(path)
for _, f := range dir.files { for _, f := range dir.files {
if f.Name() == name { if f.Name() == name {
+5 -3
View File
@@ -78,6 +78,7 @@ var gOpts struct {
menufmt string menufmt string
menuheaderfmt string menuheaderfmt string
menuselectfmt string menuselectfmt string
mergeindicators bool
mouse bool mouse bool
number bool number bool
numberfmt string numberfmt string
@@ -91,7 +92,7 @@ var gOpts struct {
relativenumber bool relativenumber bool
reverse bool reverse bool
roundbox bool roundbox bool
rulerfile bool rulerfile string
rulerfmt string rulerfmt string
scrolloff int scrolloff int
searchmethod searchMethod searchmethod searchMethod
@@ -240,6 +241,7 @@ func init() {
gOpts.menufmt = "\033[0m" gOpts.menufmt = "\033[0m"
gOpts.menuheaderfmt = "\033[1m" gOpts.menuheaderfmt = "\033[1m"
gOpts.menuselectfmt = "\033[7m" gOpts.menuselectfmt = "\033[7m"
gOpts.mergeindicators = false
gOpts.mouse = false gOpts.mouse = false
gOpts.number = false gOpts.number = false
gOpts.numberfmt = "\033[33m" gOpts.numberfmt = "\033[33m"
@@ -253,8 +255,8 @@ func init() {
gOpts.relativenumber = false gOpts.relativenumber = false
gOpts.reverse = false gOpts.reverse = false
gOpts.roundbox = false gOpts.roundbox = false
gOpts.rulerfile = false gOpts.rulerfile = ""
gOpts.rulerfmt = " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t" gOpts.rulerfmt = ""
gOpts.scrolloff = 0 gOpts.scrolloff = 0
gOpts.searchmethod = textSearch gOpts.searchmethod = textSearch
gOpts.selectfmt = "\033[7;35m" gOpts.selectfmt = "\033[7;35m"
-6
View File
@@ -38,7 +38,6 @@ var (
gConfigPaths []string gConfigPaths []string
gColorsPaths []string gColorsPaths []string
gIconsPaths []string gIconsPaths []string
gRulerPaths []string
gFilesPath string gFilesPath string
gMarksPath string gMarksPath string
gTagsPath string gTagsPath string
@@ -106,11 +105,6 @@ func init() {
filepath.Join(config, "lf", "icons"), filepath.Join(config, "lf", "icons"),
} }
gRulerPaths = []string{
filepath.Join("/etc", "lf", "ruler"),
filepath.Join(config, "lf", "ruler"),
}
data := cmp.Or( data := cmp.Or(
os.Getenv("LF_DATA_HOME"), os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"), os.Getenv("XDG_DATA_HOME"),
-6
View File
@@ -36,7 +36,6 @@ var (
gConfigPaths []string gConfigPaths []string
gColorsPaths []string gColorsPaths []string
gIconsPaths []string gIconsPaths []string
gRulerPaths []string
gFilesPath string gFilesPath string
gTagsPath string gTagsPath string
gMarksPath string gMarksPath string
@@ -96,11 +95,6 @@ func init() {
filepath.Join(config, "lf", "icons"), filepath.Join(config, "lf", "icons"),
} }
gRulerPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "ruler"),
filepath.Join(config, "lf", "ruler"),
}
data := cmp.Or( data := cmp.Or(
os.Getenv("LF_DATA_HOME"), os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"), os.Getenv("XDG_DATA_HOME"),
+13 -13
View File
@@ -2,8 +2,8 @@ package main
import ( import (
"fmt" "fmt"
"log"
"os" "os"
"path/filepath"
"strings" "strings"
"text/template" "text/template"
@@ -16,13 +16,20 @@ var gDefaultRuler string
type statData struct { type statData struct {
Path string Path string
Name string Name string
Extension string
Size uint64 Size uint64
DirSize *uint64
DirCount *uint64
Permissions string Permissions string
ModTime string ModTime string
AccessTime string
BirthTime string
ChangeTime string
LinkCount string LinkCount string
User string User string
Group string Group string
Target string Target string
CustomInfo string
} }
type rulerData struct { type rulerData struct {
@@ -46,7 +53,7 @@ type rulerData struct {
Stat *statData Stat *statData
} }
func parseRuler() (*template.Template, error) { func parseRuler(path string) (*template.Template, error) {
funcs := template.FuncMap{ funcs := template.FuncMap{
"df": func() string { return diskFree(".") }, "df": func() string { return diskFree(".") },
"env": os.Getenv, "env": os.Getenv,
@@ -57,17 +64,11 @@ func parseRuler() (*template.Template, error) {
"upper": strings.ToUpper, "upper": strings.ToUpper,
} }
for i := len(gRulerPaths) - 1; i >= 0; i-- { if path == "" {
path := gRulerPaths[i] return template.New("ruler").Funcs(funcs).Parse(gDefaultRuler)
if _, err := os.Stat(path); os.IsNotExist(err) {
continue
}
log.Printf("reading file: %s", path)
return template.New("ruler").Funcs(funcs).ParseFiles(path)
} }
return template.New("ruler").Funcs(funcs).Parse(gDefaultRuler) return template.New(filepath.Base(path)).Funcs(funcs).ParseFiles(path)
} }
func renderRuler(ruler *template.Template, data rulerData, width int) (string, string, error) { func renderRuler(ruler *template.Template, data rulerData, width int) (string, string, error) {
@@ -76,8 +77,7 @@ func renderRuler(ruler *template.Template, data rulerData, width int) (string, s
return "", "", err return "", "", err
} }
s := strings.TrimSuffix(b.String(), "\n") s := strings.ReplaceAll(b.String(), "\n", "")
s = strings.ReplaceAll(s, "\n", "\033[0;7m\\n\033[0m")
sections := strings.Split(s, "\x1f") sections := strings.Split(s, "\x1f")
if len(sections) == 1 { if len(sections) == 1 {
+10
View File
@@ -6,6 +6,7 @@ import (
"log" "log"
"net" "net"
"os" "os"
"sort"
"strconv" "strconv"
) )
@@ -106,6 +107,15 @@ Loop:
} else { } else {
echoerr(c, "listen: drop: requires a client id") echoerr(c, "listen: drop: requires a client id")
} }
case "list":
ids := make([]int, 0, len(gConnList))
for id := range gConnList {
ids = append(ids, id)
}
sort.Ints(ids)
for _, id := range ids {
fmt.Fprintln(c, id)
}
case "send": case "send":
if rest != "" { if rest != "" {
word2, rest2 := splitWord(rest) word2, rest2 := splitWord(rest)
-5
View File
@@ -28,11 +28,6 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return return
} }
if !reg.sixel {
sxs.lastFile = ""
return
}
cw, ch, err := cellSize(screen) cw, ch, err := cellSize(screen)
if err != nil { if err != nil {
log.Printf("sixel: %s", err) log.Printf("sixel: %s", err)
+36 -17
View File
@@ -11,14 +11,17 @@ import (
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
) )
// This function is used to remove style-related ANSI escape sequences from // gEscapeCode is the byte that starts ANSI control sequences.
const gEscapeCode byte = '\x1b'
// stripTermSequence is used to remove style-related ANSI escape sequences from
// a given string. // a given string.
// //
// *Note*: this function is based entirely on `printLength()` and strips only // Note: this function is based on [printLength] and only strips style-related
// style-related sequences, `erase in line` and `OSC 8` sequences. Other codes // sequences, `erase in line`, and `OSC 8` sequences. Other codes (e.g. cursor
// (e.g., cursor moves), as well as broken escape sequences, aren't removed. // moves), as well as broken escape sequences, are not removed. This prevents
// This prevents mismatches between the two functions and avoids misalignment // mismatches between the two functions and avoids misalignment when rendering
// when rendering the UI. // the UI.
func stripTermSequence(s string) string { func stripTermSequence(s string) string {
var b strings.Builder var b strings.Builder
slen := len(s) slen := len(s)
@@ -37,8 +40,9 @@ func stripTermSequence(s string) string {
return b.String() return b.String()
} }
// This function is used to extract and return a terminal sequence from a given // readTermSequence is used to extract and return a terminal sequence from a
// string. If no supported sequence could be found, an empty string is returned. // given string. If no supported sequence could be found, an empty string is
// returned.
// //
// CSI (Control Sequence Introducer): // CSI (Control Sequence Introducer):
// - SGR (Select Graphic Rendition) `m`, used for text styling // - SGR (Select Graphic Rendition) `m`, used for text styling
@@ -49,7 +53,7 @@ func stripTermSequence(s string) string {
func readTermSequence(s string) string { func readTermSequence(s string) string {
slen := len(s) slen := len(s)
// must start with ESC // must start with ESC
if slen < 2 || s[0] != byte(gEscapeCode) { if slen < 2 || s[0] != gEscapeCode {
return "" return ""
} }
@@ -72,7 +76,7 @@ func readTermSequence(s string) string {
return s[:i+1] return s[:i+1]
} }
// ESC\ (ECMA-48) // ESC\ (ECMA-48)
if b == byte(gEscapeCode) && i+1 < slen && s[i+1] == '\\' { if b == gEscapeCode && i+1 < slen && s[i+1] == '\\' {
return s[:i+2] return s[:i+2]
} }
} }
@@ -83,8 +87,18 @@ func readTermSequence(s string) string {
} }
} }
// This function takes an escape sequence option (e.g. `\033[1m`) and converts // optionToFmtstr takes an escape sequence option (e.g. `\033[1m`) and outputs
// it to a `tcell.Style` object. // a complete format string (e.g. `\033[1m%s\033[0m`).
func optionToFmtstr(optstr string) string {
if !strings.Contains(optstr, "%s") {
return optstr + "%s\033[0m"
} else {
return optstr
}
}
// parseEscapeSequence takes an escape sequence option (e.g. `\033[1m`) and
// converts it to a [tcell.Style] object.
// Legacy function that only accepts SGR. Kept for convenience. // Legacy function that only accepts SGR. Kept for convenience.
func parseEscapeSequence(s string) tcell.Style { func parseEscapeSequence(s string) tcell.Style {
s = strings.TrimPrefix(s, "\033[") s = strings.TrimPrefix(s, "\033[")
@@ -94,12 +108,12 @@ func parseEscapeSequence(s string) tcell.Style {
return applySGR(s, tcell.StyleDefault) return applySGR(s, tcell.StyleDefault)
} }
// This function takes an escape sequence (e.g. `\033[1m`) and applies it // applyTermSequence takes an escape sequence (e.g. `\033[1m`) and applies it
// to the given `tcell.Style` object. // to the given [tcell.Style] object.
// Accepts SGR and OSC sequences. // Accepts SGR and OSC sequences.
func applyTermSequence(s string, st tcell.Style) tcell.Style { func applyTermSequence(s string, st tcell.Style) tcell.Style {
slen := len(s) slen := len(s)
if slen < 2 || s[0] != byte(gEscapeCode) { if slen < 2 || s[0] != gEscapeCode {
return st return st
} }
switch s[1] { switch s[1] {
@@ -112,7 +126,7 @@ func applyTermSequence(s string, st tcell.Style) tcell.Style {
// trim terminator (BEL or ESC\), then parse body // trim terminator (BEL or ESC\), then parse body
if s[slen-1] == 0x07 { if s[slen-1] == 0x07 {
return applyOSC(s[2:slen-1], st) return applyOSC(s[2:slen-1], st)
} else if slen >= 2 && s[slen-2] == byte(gEscapeCode) && s[slen-1] == '\\' { } else if slen >= 2 && s[slen-2] == gEscapeCode && s[slen-1] == '\\' {
return applyOSC(s[2:slen-2], st) return applyOSC(s[2:slen-2], st)
} }
return st return st
@@ -121,6 +135,8 @@ func applyTermSequence(s string, st tcell.Style) tcell.Style {
} }
} }
// applySGR takes an SGR sequence and applies it to the given [tcell.Style]
// object.
func applySGR(s string, st tcell.Style) tcell.Style { func applySGR(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";") toks := strings.Split(s, ";")
@@ -216,7 +232,10 @@ loop:
return st return st
} }
// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda // applyOSC takes an OSC sequence and applies it to the given [tcell.Style]
// object.
// It currently supports OSC 8 hyperlinks only, implemented as specified by
// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.
func applyOSC(body string, st tcell.Style) tcell.Style { func applyOSC(body string, st tcell.Style) tcell.Style {
genAutoID := func(url string) string { genAutoID := func(url string) string {
sum := sha256.Sum256([]byte(url)) sum := sha256.Sum256([]byte(url))
+16
View File
@@ -83,6 +83,22 @@ func TestReadTermSequence(t *testing.T) {
} }
} }
func TestOptionToFmtstr(t *testing.T) {
tests := []struct {
s string
exp string
}{
{"\033[1m", "\033[1m%s\033[0m"},
{"\033[1;7;31;42m", "\033[1;7;31;42m%s\033[0m"},
}
for _, test := range tests {
if got := optionToFmtstr(test.s); got != test.exp {
t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got)
}
}
}
func TestParseEscapeSequence(t *testing.T) { func TestParseEscapeSequence(t *testing.T) {
tests := []struct { tests := []struct {
s string s string
+147 -155
View File
@@ -22,8 +22,6 @@ import (
"golang.org/x/term" "golang.org/x/term"
) )
const gEscapeCode = 27
var gKeyVal = map[tcell.Key]string{ var gKeyVal = map[tcell.Key]string{
tcell.KeyEnter: "<enter>", tcell.KeyEnter: "<enter>",
tcell.KeyBackspace: "<backspace>", tcell.KeyBackspace: "<backspace>",
@@ -166,6 +164,10 @@ func (win *win) renew(w, h, x, y int) {
win.w, win.h, win.x, win.y = w, h, x, y win.w, win.h, win.x, win.y = w, h, x, y
} }
// printLength returns the display width of s in terminal cells.
//
// It ignores supported terminal control sequences (see [readTermSequence])
// and accounts for tab expansions using the `tabstop` option.
func printLength(s string) int { func printLength(s string) int {
ind := 0 ind := 0
off := 0 off := 0
@@ -246,21 +248,16 @@ func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string)
} }
func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs *sixelScreen) { func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs *sixelScreen) {
if reg == nil { switch {
return case reg.loading:
}
st := tcell.StyleDefault
if reg.loading {
if previewLoading { if previewLoading {
st = st.Reverse(true) st := tcell.StyleDefault.Reverse(true)
win.print(screen, 2, 0, st, "loading...") win.print(screen, 2, 0, st, "loading...")
} }
return case reg.sixel:
} sxs.printSixel(win, screen, reg)
default:
if !reg.sixel { st := tcell.StyleDefault
for i, l := range reg.lines { for i, l := range reg.lines {
if i > win.h-1 { if i > win.h-1 {
break break
@@ -270,7 +267,9 @@ func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs
} }
} }
sxs.printSixel(win, screen, reg) if !reg.sixel {
sxs.lastFile = ""
}
} }
var gThisYear = time.Now().Year() var gThisYear = time.Now().Year()
@@ -282,7 +281,7 @@ func infotimefmt(t time.Time) string {
return t.Format(gOpts.infotimefmtold) return t.Format(gOpts.infotimefmtold)
} }
func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (string, string, int) { func fileInfo(f *file, d *dir, userWidth, groupWidth, customWidth int) (string, string, int) {
var info strings.Builder var info strings.Builder
var custom string var custom string
var off int var off int
@@ -292,25 +291,23 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
case "size": case "size":
if f.IsDir() && getDirCounts(d.path) { if f.IsDir() && getDirCounts(d.path) {
switch { switch {
case f.dirCount < -1: case f.dirCount == nil:
info.WriteString(" !")
case f.dirCount < 0:
info.WriteString(" ?") info.WriteString(" ?")
case f.dirCount < 10000: case *f.dirCount < 10000:
fmt.Fprintf(&info, " %5d", f.dirCount) fmt.Fprintf(&info, " %5d", *f.dirCount)
default: default:
info.WriteString(" 9999+") info.WriteString(" 9999+")
} }
continue
}
var sz string
if f.IsDir() && f.dirSize < 0 {
sz = "-"
} else { } else {
sz = humanize(uint64(f.TotalSize())) switch {
case f.dirSize != nil:
fmt.Fprintf(&info, " %5s", humanize(*f.dirSize))
case f.IsDir():
info.WriteString(" -")
default:
fmt.Fprintf(&info, " %5s", humanize(uint64(f.Size())))
}
} }
fmt.Fprintf(&info, " %5s", sz)
case "time": case "time":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime())) fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
case "atime": case "atime":
@@ -349,12 +346,13 @@ type dirContext struct {
tags map[string]string tags map[string]string
} }
// dirRole describes what kind of directory pane is being drawn.
type dirRole byte type dirRole byte
const ( const (
Active dirRole = iota Active dirRole = iota // Current directory pane.
Parent Parent // Parent or ancestor directory pane.
Preview Preview // Preview pane when it shows a directory listing.
) )
type dirStyle struct { type dirStyle struct {
@@ -396,17 +394,15 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if dirStyle.role == Active && (gOpts.number || gOpts.relativenumber) { if dirStyle.role == Active && (gOpts.number || gOpts.relativenumber) {
lnwidth = 1 lnwidth = 1
if gOpts.number && gOpts.relativenumber {
lnwidth++
}
for j := 10; j <= fileslen; j *= 10 { for j := 10; j <= fileslen; j *= 10 {
lnwidth++ lnwidth++
} }
if gOpts.number && gOpts.relativenumber {
lnwidth = max(lnwidth, 2)
}
} }
var userWidth int var userWidth, groupWidth, customWidth int
var groupWidth int
var customWidth int
var fetchedCustom bool var fetchedCustom bool
// Only fetch user/group/custom widths if configured to display them // Only fetch user/group/custom widths if configured to display them
@@ -426,6 +422,12 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
} }
} }
indOff, tagOff, nameOff := lnwidth, lnwidth, lnwidth+1
if !gOpts.mergeindicators {
tagOff++
nameOff++
}
visualSelections := dir.visualSelections() visualSelections := dir.visualSelections()
for i, f := range dir.files[beg:end] { for i, f := range dir.files[beg:end] {
st := dirStyle.colors.get(f) st := dirStyle.colors.get(f)
@@ -442,7 +444,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
case i > dir.pos: case i > dir.pos:
ln = fmt.Sprintf("%*d", lnwidth, i-dir.pos) ln = fmt.Sprintf("%*d", lnwidth, i-dir.pos)
case gOpts.number: case gOpts.number:
ln = fmt.Sprintf("%*d ", lnwidth-1, i+1+beg) ln = fmt.Sprintf("%-*d", lnwidth, i+1+beg)
default: default:
ln = fmt.Sprintf("%*d", lnwidth, 0) ln = fmt.Sprintf("%*d", lnwidth, 0)
} }
@@ -465,22 +467,23 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
fmtStr = gOpts.cutfmt fmtStr = gOpts.cutfmt
} }
} }
if fmtStr != "" {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(fmtStr), " ")
}
// make space for select marker, and leave another space at the end
maxWidth := win.w - lnwidth - 2
// make extra space to separate windows if drawbox is not enabled
if !gOpts.drawbox {
maxWidth--
}
tag := " " tag := " "
if val, ok := context.tags[path]; ok && len(val) > 0 { if val, ok := context.tags[path]; ok && len(val) > 0 {
tag = val tag = val
} }
if fmtStr != "" {
ind := " "
if gOpts.mergeindicators {
ind = tag
}
win.print(ui.screen, indOff, i, parseEscapeSequence(fmtStr), ind)
}
// make space for select marker, and leave another space at the end
maxWidth := win.w - lnwidth - 2
var icon []rune var icon []rune
var iconDef iconDef var iconDef iconDef
if gOpts.icons { if gOpts.icons {
@@ -488,10 +491,14 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
icon = slices.Concat([]rune(iconDef.icon), []rune{' '}) icon = slices.Concat([]rune(iconDef.icon), []rune{' '})
} }
// subtract space for tag and icon // subtract space for icon
maxFilenameWidth := maxWidth - 1 - runeSliceWidth(icon) maxFilenameWidth := maxWidth - runeSliceWidth(icon)
// subtract space for tag if not merged with selection marker
if !gOpts.mergeindicators {
maxFilenameWidth--
}
info, custom, off := fileInfo(f, dir, userWidth, groupWidth, customWidth) info, custom, customOff := fileInfo(f, dir, userWidth, groupWidth, customWidth)
infolen := len(info) infolen := len(info)
showInfo := infolen > 0 && 2*infolen < maxWidth showInfo := infolen > 0 && 2*infolen < maxWidth
if showInfo { if showInfo {
@@ -505,7 +512,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if showInfo { if showInfo {
filename = append(filename, []rune(info)...) filename = append(filename, []rune(info)...)
off += lnwidth + 2 + runeSliceWidth(icon) + maxFilenameWidth customOff += nameOff + runeSliceWidth(icon) + maxFilenameWidth
} }
if i == dir.pos { if i == dir.pos {
@@ -520,21 +527,25 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
} }
// print tag separately as it can contain color escape sequences // print tag separately as it can contain color escape sequences
win.print(ui.screen, lnwidth+1, i, st, fmt.Sprintf(cursorFmt, tag)) if !gOpts.mergeindicators || fmtStr == "" {
win.print(ui.screen, tagOff, i, st, fmt.Sprintf(cursorFmt, tag))
}
line := slices.Concat(icon, filename, []rune{' '}) line := slices.Concat(icon, filename, []rune{' '})
win.print(ui.screen, lnwidth+2, i, st, fmt.Sprintf(cursorFmt, string(line))) win.print(ui.screen, nameOff, i, st, fmt.Sprintf(cursorFmt, string(line)))
// print over the empty space we reserved for the custom info // print over the empty space we reserved for the custom info
if showInfo && custom != "" { if showInfo && custom != "" {
win.print(ui.screen, off, i, st, fmt.Sprintf(cursorFmt, stripTermSequence(custom))) win.print(ui.screen, customOff, i, st, fmt.Sprintf(cursorFmt, stripTermSequence(custom)))
} }
} else { } else {
if tag == " " { if !gOpts.mergeindicators || fmtStr == "" {
win.print(ui.screen, lnwidth+1, i, st, " ") if tag == " " {
} else { win.print(ui.screen, tagOff, i, st, " ")
tagStr := fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag) } else {
win.print(ui.screen, lnwidth+1, i, tcell.StyleDefault, tagStr) tagStr := fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag)
win.print(ui.screen, tagOff, i, tcell.StyleDefault, tagStr)
}
} }
if len(icon) > 0 { if len(icon) > 0 {
@@ -542,21 +553,21 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if iconDef.hasStyle { if iconDef.hasStyle {
iconStyle = iconDef.style iconStyle = iconDef.style
} }
win.print(ui.screen, lnwidth+2, i, iconStyle, string(icon)) win.print(ui.screen, nameOff, i, iconStyle, string(icon))
} }
line := slices.Concat(filename, []rune{' '}) line := slices.Concat(filename, []rune{' '})
win.print(ui.screen, lnwidth+2+runeSliceWidth(icon), i, st, string(line)) win.print(ui.screen, nameOff+runeSliceWidth(icon), i, st, string(line))
// print over the empty space we reserved for the custom info // print over the empty space we reserved for the custom info
if showInfo && custom != "" { if showInfo && custom != "" {
win.print(ui.screen, off, i, st, custom) win.print(ui.screen, customOff, i, st, custom)
} }
} }
} }
} }
func getUserWidth(dir *dir, beg int, end int) int { func getUserWidth(dir *dir, beg, end int) int {
maxw := 0 maxw := 0
for _, f := range dir.files[beg:end] { for _, f := range dir.files[beg:end] {
@@ -566,7 +577,7 @@ func getUserWidth(dir *dir, beg int, end int) int {
return maxw return maxw
} }
func getGroupWidth(dir *dir, beg int, end int) int { func getGroupWidth(dir *dir, beg, end int) int {
maxw := 0 maxw := 0
for _, f := range dir.files[beg:end] { for _, f := range dir.files[beg:end] {
@@ -576,7 +587,7 @@ func getGroupWidth(dir *dir, beg int, end int) int {
return maxw return maxw
} }
func getCustomWidth(dir *dir, beg int, end int) int { func getCustomWidth(dir *dir, beg, end int) int {
maxw := 0 maxw := 0
for _, f := range dir.files[beg:end] { for _, f := range dir.files[beg:end] {
@@ -586,45 +597,23 @@ func getCustomWidth(dir *dir, beg int, end int) int {
return maxw return maxw
} }
func getWidths(wtot int) []int {
rsum := 0
for _, r := range gOpts.ratios {
rsum += r
}
wlen := len(gOpts.ratios)
widths := make([]int, wlen)
if gOpts.drawbox {
wtot -= (wlen + 1)
}
wsum := 0
for i := range wlen - 1 {
widths[i] = gOpts.ratios[i] * wtot / rsum
wsum += widths[i]
}
widths[wlen-1] = wtot - wsum
return widths
}
func getWins(screen tcell.Screen) []*win { func getWins(screen tcell.Screen) []*win {
wtot, htot := screen.Size() wtot, htot := screen.Size()
widths := getWidths(wtot) h := max(htot-2, 0)
x := 0
y := 1
if gOpts.drawbox {
h = max(htot-4, 0)
x = 1
y = 2
}
wacc := 0 widths := getWidths(wtot, gOpts.ratios, gOpts.drawbox)
wlen := len(widths) wins := make([]*win, 0, len(widths))
wins := make([]*win, 0, wlen) for _, w := range widths {
for i := range wlen { wins = append(wins, newWin(w, h, x, y))
if gOpts.drawbox { x += w + 1
wacc++
wins = append(wins, newWin(widths[i], max(htot-4, 0), wacc, 2))
} else {
wins = append(wins, newWin(widths[i], max(htot-2, 0), wacc, 1))
}
wacc += widths[i]
} }
return wins return wins
@@ -644,8 +633,6 @@ type ui struct {
msgWin *win msgWin *win
menuWin *win menuWin *win
msg string msg string
regPrev *reg
dirPrev *dir
exprChan chan expr exprChan chan expr
keyChan chan string keyChan chan string
tevChan chan tcell.Event tevChan chan tcell.Event
@@ -685,7 +672,7 @@ func newUI(screen tcell.Screen) *ui {
currentFile: "", currentFile: "",
sxScreen: sixelScreen{}, sxScreen: sixelScreen{},
} }
ui.ruler, ui.rulerErr = parseRuler() ui.ruler, ui.rulerErr = parseRuler(gOpts.rulerfile)
go ui.pollEvents() go ui.pollEvents()
@@ -723,15 +710,6 @@ func (ui *ui) renew() {
ui.menuWin.renew(wtot, 1, 0, htot-2) ui.menuWin.renew(wtot, 1, 0, htot-2)
} }
func (ui *ui) sort() {
if ui.dirPrev == nil {
return
}
name := ui.dirPrev.name()
ui.dirPrev.sort()
ui.dirPrev.sel(name, ui.wins[0].h)
}
func (ui *ui) echo(msg string) { func (ui *ui) echo(msg string) {
ui.msg = msg ui.msg = msg
} }
@@ -750,9 +728,12 @@ func (ui *ui) echoerrf(format string, a ...any) {
ui.echoerr(fmt.Sprintf(format, a...)) ui.echoerr(fmt.Sprintf(format, a...))
} }
// This represents the preview for a regular file. // reg represents the preview for a file.
// This can also be used to represent the preview of a directory if // This can also be used to represent the preview of a directory if
// `dirpreviews` is enabled. // `dirpreviews` is enabled.
//
// Note: the name `reg` is historical. It originally meant "regular"
// file preview, but `previewer` now also supports non-regular files.
type reg struct { type reg struct {
loading bool loading bool
volatile bool volatile bool
@@ -763,12 +744,8 @@ type reg struct {
} }
func (ui *ui) loadFile(app *app, volatile bool) { func (ui *ui) loadFile(app *app, volatile bool) {
if !app.nav.init { curr := app.nav.currFile()
return if curr == nil {
}
curr, err := app.nav.currFile()
if err != nil {
return return
} }
@@ -786,9 +763,10 @@ func (ui *ui) loadFile(app *app, volatile bool) {
} }
if curr.isPreviewable() { if curr.isPreviewable() {
ui.regPrev = app.nav.loadReg(curr.path, volatile) app.nav.loadReg(curr.path, volatile)
} else if curr.IsDir() { } else if curr.IsDir() {
ui.dirPrev = app.nav.loadDir(curr.path) dir := app.nav.getDir(curr.path)
app.nav.checkDir(dir)
} }
} }
@@ -805,8 +783,7 @@ func (ui *ui) drawPromptLine(nav *nav) {
sep := string(filepath.Separator) sep := string(filepath.Separator)
var fname string var fname string
curr, err := nav.currFile() if curr := nav.currFile(); curr != nil {
if err == nil {
fname = filepath.Base(curr.path) fname = filepath.Base(curr.path)
} }
@@ -853,7 +830,7 @@ func (ui *ui) drawPromptLine(nav *nav) {
ui.promptWin.print(ui.screen, 0, 0, st, prompt) ui.promptWin.print(ui.screen, 0, 0, st, prompt)
} }
func formatRulerOpt(name string, val string) string { func formatRulerOpt(name, val string) string {
// handle escape character so it doesn't mess up the ruler // handle escape character so it doesn't mess up the ruler
val = strings.ReplaceAll(val, "\033", "\033[7m\\033\033[0m") val = strings.ReplaceAll(val, "\033", "\033[7m\\033\033[0m")
@@ -871,8 +848,8 @@ func (ui *ui) drawStat(nav *nav) {
return return
} }
curr, err := nav.currFile() curr := nav.currFile()
if err != nil { if curr == nil {
return return
} }
@@ -883,7 +860,7 @@ func (ui *ui) drawStat(nav *nav) {
} }
statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f") statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f")
replace := func(s string, val string) { replace := func(s, val string) {
if val == "" { if val == "" {
val = "\x00" val = "\x00"
} }
@@ -1025,19 +1002,26 @@ func (ui *ui) drawRulerFile(nav *nav) {
} }
var stat *statData var stat *statData
curr, err := nav.currFile() curr := nav.currFile()
if err == nil { if curr != nil {
if curr.err == nil { if curr.err == nil {
stat = &statData{ stat = &statData{
Path: curr.path, Path: curr.path,
Name: curr.Name(), Name: curr.Name(),
Extension: curr.ext,
Size: uint64(curr.Size()), Size: uint64(curr.Size()),
DirSize: curr.dirSize,
DirCount: curr.dirCount,
Permissions: permString(curr.Mode()), Permissions: permString(curr.Mode()),
ModTime: curr.ModTime().Format(gOpts.timefmt), ModTime: curr.ModTime().Format(gOpts.timefmt),
AccessTime: curr.accessTime.Format(gOpts.timefmt),
BirthTime: curr.birthTime.Format(gOpts.timefmt),
ChangeTime: curr.changeTime.Format(gOpts.timefmt),
LinkCount: linkCount(curr), LinkCount: linkCount(curr),
User: userName(curr), User: userName(curr),
Group: groupName(curr), Group: groupName(curr),
Target: curr.linkTarget, Target: curr.linkTarget,
CustomInfo: curr.customInfo,
} }
} else { } else {
ui.echoerrf("stat: %s", curr.err) ui.echoerrf("stat: %s", curr.err)
@@ -1148,6 +1132,29 @@ func (ui *ui) drawRulerFile(nav *nav) {
ui.msgWin.printRight(ui.screen, 0, tcell.StyleDefault, right) ui.msgWin.printRight(ui.screen, 0, tcell.StyleDefault, right)
} }
func (ui *ui) drawPreview(nav *nav, context *dirContext) {
curr := nav.currFile()
if curr == nil {
return
}
win := ui.wins[len(ui.wins)-1]
ui.sxScreen.clearSixel(win, ui.screen, curr.path)
if gOpts.preview {
if curr.isPreviewable() {
if reg, ok := nav.regCache[curr.path]; ok {
win.printReg(ui.screen, reg, nav.previewLoading, &ui.sxScreen)
}
} else if curr.IsDir() {
ui.sxScreen.lastFile = ""
dir := nav.getDir(curr.path)
dirStyle := &dirStyle{colors: ui.styles, icons: ui.icons, role: Preview}
win.printDir(ui, dir, context, dirStyle)
}
}
}
func (ui *ui) drawBox() { func (ui *ui) drawBox() {
st := parseEscapeSequence(gOpts.borderfmt) st := parseEscapeSequence(gOpts.borderfmt)
@@ -1223,11 +1230,11 @@ func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
if gOpts.preview { if gOpts.preview {
wins-- wins--
} }
ind := len(nav.dirs) - wins + wind ind := len(nav.dirPaths) - wins + wind
if ind < 0 { if ind < 0 {
return nil return nil
} }
return nav.dirs[ind] return nav.getDir(nav.dirPaths[ind])
} }
func (ui *ui) draw(nav *nav) { func (ui *ui) draw(nav *nav) {
@@ -1255,7 +1262,7 @@ func (ui *ui) draw(nav *nav) {
switch ui.cmdPrefix { switch ui.cmdPrefix {
case "": case "":
if gOpts.rulerfile { if gOpts.rulerfmt == "" {
ui.drawRulerFile(nav) ui.drawRulerFile(nav)
} else { } else {
ui.drawStat(nav) ui.drawStat(nav)
@@ -1277,20 +1284,7 @@ func (ui *ui) draw(nav *nav) {
ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+runeSliceWidth(left), ui.msgWin.y) ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+runeSliceWidth(left), ui.msgWin.y)
} }
curr, err := nav.currFile() ui.drawPreview(nav, &context)
if err == nil {
preview := ui.wins[len(ui.wins)-1]
ui.sxScreen.clearSixel(preview, ui.screen, curr.path)
if gOpts.preview {
if curr.isPreviewable() {
preview.printReg(ui.screen, ui.regPrev, nav.previewLoading, &ui.sxScreen)
} else if curr.IsDir() {
ui.sxScreen.lastFile = ""
preview.printDir(ui, ui.dirPrev, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: Preview})
}
}
}
if gOpts.drawbox { if gOpts.drawbox {
ui.drawBox() ui.drawBox()
@@ -1463,9 +1457,6 @@ func listMarks(marks map[string]string) string {
} }
func listFilesInCurrDir(nav *nav) string { func listFilesInCurrDir(nav *nav) string {
if !nav.init {
return ""
}
dir := nav.currDir() dir := nav.currDir()
if dir.loading { if dir.loading {
log.Printf("listFilesInCurrDir(): %s is still loading, `files` isn't ready for remote query", dir.path) log.Printf("listFilesInCurrDir(): %s is still loading, `files` isn't ready for remote query", dir.path)
@@ -1545,7 +1536,7 @@ func addSpecialKeyModifier(val string, mod tcell.ModMask) string {
} }
} }
// This function is used to read a normal event on the client side. For keys, // readNormalEvent is used to read a normal event on the client side. For keys,
// digits are interpreted as command counts but this is only done for digits // digits are interpreted as command counts but this is only done for digits
// preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k"). // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k").
func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr { func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
@@ -1692,8 +1683,8 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
var dir *dir var dir *dir
if gOpts.preview && wind == len(ui.wins)-1 { if gOpts.preview && wind == len(ui.wins)-1 {
curr, err := nav.currFile() curr := nav.currFile()
if err != nil { if curr == nil {
return nil return nil
} else if !curr.IsDir() || gOpts.dirpreviews { } else if !curr.IsDir() || gOpts.dirpreviews {
if tev.Buttons() != tcell.Button2 { if tev.Buttons() != tcell.Button2 {
@@ -1701,7 +1692,8 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
} }
return &callExpr{"open", nil, 1} return &callExpr{"open", nil, 1}
} }
dir = ui.dirPrev
dir = nav.getDir(curr.path)
} else { } else {
dir = ui.dirOfWin(nav, wind) dir = ui.dirOfWin(nav, wind)
if dir == nil { if dir == nil {
+56 -52
View File
@@ -10,29 +10,27 @@ import (
) )
type watch struct { type watch struct {
watcher *fsnotify.Watcher watcher *fsnotify.Watcher
events <-chan fsnotify.Event events <-chan fsnotify.Event
quit chan struct{} quit chan struct{}
loads map[string]bool pending map[watchUpdate]bool
loadTimer *time.Timer timeout chan watchUpdate
updates map[string]bool dirChan chan<- *dir
updateTimer *time.Timer fileChan chan<- *file
dirChan chan<- *dir delChan chan<- string
fileChan chan<- *file
delChan chan<- string
} }
func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) *watch { func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) *watch {
return &watch{ watch := &watch{
quit: make(chan struct{}), quit: make(chan struct{}),
loads: make(map[string]bool), pending: make(map[watchUpdate]bool),
loadTimer: time.NewTimer(0), timeout: make(chan watchUpdate, 1024),
updates: make(map[string]bool), dirChan: dirChan,
updateTimer: time.NewTimer(0), fileChan: fileChan,
dirChan: dirChan, delChan: delChan,
fileChan: fileChan,
delChan: delChan,
} }
return watch
} }
func (watch *watch) start() { func (watch *watch) start() {
@@ -83,8 +81,8 @@ func (watch *watch) loop() {
case ev := <-watch.events: case ev := <-watch.events:
if ev.Has(fsnotify.Create) { if ev.Has(fsnotify.Create) {
for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) { for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) {
watch.addLoad(path) watch.addUpdate(watchUpdate{"dir", path})
watch.addUpdate(path) watch.addUpdate(watchUpdate{"file", path})
} }
} }
@@ -92,8 +90,8 @@ func (watch *watch) loop() {
dir, file := filepath.Split(ev.Name) dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) { for _, path := range watch.getSameDirs(dir) {
watch.delChan <- filepath.Join(path, file) watch.delChan <- filepath.Join(path, file)
watch.addLoad(path) watch.addUpdate(watchUpdate{"dir", path})
watch.addUpdate(path) watch.addUpdate(watchUpdate{"file", path})
} }
} }
@@ -108,47 +106,53 @@ func (watch *watch) loop() {
dir, file := filepath.Split(ev.Name) dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) { for _, path := range watch.getSameDirs(dir) {
watch.addUpdate(filepath.Join(path, file)) watch.addUpdate(watchUpdate{"file", filepath.Join(path, file)})
} }
} }
case <-watch.loadTimer.C: case update := <-watch.timeout:
for path := range watch.loads { if watch.pending[update] {
if _, err := os.Lstat(path); err != nil { watch.processUpdate(update)
continue time.AfterFunc(100*time.Millisecond, func() { watch.timeout <- update })
} watch.pending[update] = false
dir := newDir(path) } else {
dir.sort() delete(watch.pending, update)
watch.dirChan <- dir
} }
clear(watch.loads)
case <-watch.updateTimer.C:
for path := range watch.updates {
if _, err := os.Lstat(path); err != nil {
continue
}
watch.fileChan <- newFile(path)
}
clear(watch.updates)
case <-watch.quit: case <-watch.quit:
return return
} }
} }
} }
func (watch *watch) addLoad(path string) { type watchUpdate struct {
if len(watch.loads) == 0 { kind string
watch.loadTimer.Stop() path string
watch.loadTimer.Reset(10 * time.Millisecond)
}
watch.loads[path] = true
} }
func (watch *watch) addUpdate(path string) { func (watch *watch) addUpdate(update watchUpdate) {
if len(watch.updates) == 0 { // process an update immediately if is the first time, otherwise store it
watch.updateTimer.Stop() // and process only after a timeout to reduce the number of actual loads
watch.updateTimer.Reset(10 * time.Millisecond) if _, ok := watch.pending[update]; !ok {
watch.processUpdate(update)
time.AfterFunc(100*time.Millisecond, func() { watch.timeout <- update })
watch.pending[update] = false
} else {
watch.pending[update] = true
}
}
func (watch *watch) processUpdate(update watchUpdate) {
switch update.kind {
case "dir":
if _, err := os.Lstat(update.path); err == nil {
dir := newDir(update.path)
dir.sort()
watch.dirChan <- dir
}
case "file":
if _, err := os.Lstat(update.path); err == nil {
watch.fileChan <- newFile(update.path)
}
} }
watch.updates[path] = true
} }
// Hacky workaround since fsnotify reports changes for only one path if a // Hacky workaround since fsnotify reports changes for only one path if a