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: /
schedule:
interval: daily
commit-message:
prefix: chore
include: scope
- package-ecosystem: gomod
directory: /
schedule:
interval: daily
commit-message:
prefix: chore
include: scope
+2 -2
View File
@@ -70,7 +70,7 @@ jobs:
GOARCH: ${{ matrix.arch }}
- name: Upload artifact
uses: actions/upload-artifact@v5
uses: actions/upload-artifact@v6
with:
name: lf-${{ matrix.os }}-${{ matrix.arch }}
path: dist/*
@@ -80,7 +80,7 @@ jobs:
needs: build
steps:
- name: Download artifacts
uses: actions/download-artifact@v6
uses: actions/download-artifact@v7
with:
path: dist
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`
- `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)
### Changed
+40 -60
View File
@@ -19,24 +19,24 @@ import (
)
type app struct {
ui *ui
nav *nav
ticker *time.Ticker
quitChan chan struct{}
cmd *exec.Cmd
cmdIn io.WriteCloser
cmdOutBuf []byte
cmdHistory []string
cmdHistoryBeg int
cmdHistoryInd int
cmdHistoryInput *string
menuCompActive bool
menuCompTmp []string
menuComps []compMatch
menuCompInd int
selectionOut []string
watch *watch
quitting bool
ui *ui // ui state (screen, windows, input)
nav *nav // navigation state (dirs, cursor, selections, preview, caches)
ticker *time.Ticker // refresh ticker if `period` > 0
quitChan chan struct{} // signals main loop to exit
cmd *exec.Cmd // currently running % (shell-pipe) command
cmdIn io.WriteCloser // stdin writer for running % command
cmdOutBuf []byte // output of running % command
cmdHistory []string // command history entries
cmdHistoryBeg int // index where commands from this session start in cmdHistory
cmdHistoryInd int // history navigation offset from most recent
cmdHistoryInput *string // initial input used as prefix filter while browsing history
menuCompActive bool // whether completion cycling is active
menuCompTmp []string // token snapshot taken when completion cycling starts, used for `cmd-menu-discard`
menuComps []compMatch // completion candidates for active prompt
menuCompInd int // index of selected completion candidate (-1: none selected)
selectionOut []string // paths to output on exit, used for `-print-selection` and `-selection-path`
watch *watch // fs watcher if `watch` is enabled
quitting bool // guard to prevent re-entering quit logic
}
func newApp(ui *ui, nav *nav) *app {
@@ -84,11 +84,11 @@ func (app *app) quit() {
}
}
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)
}
if gOpts.autoquit {
if err := remote("quit"); err != nil {
if _, err := remote("quit"); err != nil {
log.Printf("auto quitting server: %s", err)
}
}
@@ -255,7 +255,7 @@ func (app *app) writeHistory() error {
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
// for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update.
@@ -296,14 +296,8 @@ func (app *app) loop() {
}
}
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
app.nav.updateDirs(wd)
app.nav.loadDirs()
app.nav.addJumpList()
app.nav.init = true
if gSelect != "" {
go func() {
@@ -393,6 +387,11 @@ func (app *app) loop() {
}
app.ui.draw(app.nav)
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]
if ok {
d.ind = prev.ind
@@ -405,27 +404,12 @@ func (app *app) loop() {
}
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()
curr, err := app.nav.currFile()
if err == nil {
if curr := app.nav.currFile(); curr != nil {
if curr.path != oldCurrPath {
app.ui.loadFile(app, true)
}
if d.path == curr.path {
app.ui.dirPrev = d
}
}
app.watchDir(d)
@@ -444,10 +428,8 @@ func (app *app) loop() {
case r := <-app.nav.regChan:
app.nav.regCache[r.path] = r
curr, err := app.nav.currFile()
if err == nil {
if curr := app.nav.currFile(); curr != nil {
if r.path == curr.path {
app.ui.regPrev = r
app.ui.sxScreen.forceClear = true
if gOpts.preload && r.volatile {
app.ui.loadFile(app, true)
@@ -489,9 +471,7 @@ func (app *app) loop() {
deletePathRecursive(app.nav.dirCache, path)
currPath := app.nav.currDir().path
if currPath == path || strings.HasPrefix(currPath, path+string(filepath.Separator)) {
if wd, err := os.Getwd(); err == nil {
app.nav.updateDirs(wd)
}
app.nav.loadDirs()
}
case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev, app.nav)
@@ -555,7 +535,7 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
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
// $ No No Yes Yes Yes Pause and then resume
@@ -608,10 +588,10 @@ func (app *app) runShell(s string, args []string, prefix string) {
return
}
// 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
// only wait for the command to finish executing regardless of whether
// the output has been fully read or not.
// [exec.Cmd.StdoutPipe] cannot be used as it requires the output to be fully
// read before calling [exec.Cmd.Wait], however in this case Cmd.Wait should
// only wait for the command to finish executing regardless of whether the
// output has been fully read or not.
inReader, inWriter, err := os.Pipe()
if err != nil {
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) {
var result string
var longest string
switch app.ui.cmdPrefix {
case ":":
matches, result = completeCmd(app.ui.cmdAccLeft)
matches, longest = completeCmd(app.ui.cmdAccLeft)
case "$", "%", "!", "&":
matches, result = completeShell(app.ui.cmdAccLeft)
matches, longest = completeShell(app.ui.cmdAccLeft)
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)
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)
if err != nil {
log.Printf("opening last dir file: %s", err)
@@ -168,14 +168,15 @@ func readExpr() <-chan expr {
return ch
}
func remote(cmd string) error {
func remote(req string) (string, error) {
c, err := net.Dial(gSocketProt, gSocketPath)
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 {
return fmt.Errorf("sending command to server: %w", err)
if _, err := fmt.Fprintln(c, req); err != nil {
return "", fmt.Errorf("sending command to server: %w", err)
}
// XXX: Standard net.Conn interface does not include a CloseWrite method
@@ -190,17 +191,10 @@ func remote(cmd string) error {
c.CloseWrite()
}
// The most straightforward way to write the response to stdout would be
// 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)
resp, err := io.ReadAll(c)
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) {
for entry := range strings.SplitSeq(env, ":") {
if entry == "" {
@@ -179,7 +179,7 @@ func (sm *styleMap) parsePair(pair []string) {
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) {
if len(env) != 22 {
log.Printf("invalid $LSCOLORS variable: %s", env)
+74 -71
View File
@@ -161,7 +161,7 @@ func getLocalOptWords(localOpts any) (localOptWords []string) {
return
}
func commonPrefix(s1, s2 string) string {
func getLongest(s1, s2 string) string {
r1 := []rune(s1)
r2 := []rune(s2)
@@ -180,7 +180,7 @@ type compMatch struct {
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 {
if !strings.HasPrefix(w, s) {
continue
@@ -188,22 +188,22 @@ func matchWord(s string, words []string) (matches []compMatch, result string) {
matches = append(matches, compMatch{w, w})
if len(matches) == 1 {
result = w
longest = w
} else {
result = commonPrefix(result, w)
longest = getLongest(longest, w)
}
}
switch len(matches) {
case 0:
result = s
longest = s
case 1:
result += " "
longest += " "
}
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, ":")
for _, w := range words {
@@ -215,31 +215,31 @@ func matchList(s string, words []string) (matches []compMatch, result string) {
matches = append(matches, compMatch{w, matchResult})
if len(matches) == 1 {
result = matchResult
longest = matchResult
} else {
result = commonPrefix(result, matchResult)
longest = getLongest(longest, matchResult)
}
}
switch len(matches) {
case 0:
result = s
longest = s
case 1:
if result == s {
result += " "
if longest == s {
longest += " "
}
}
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)))
slices.Sort(words)
matches, result = matchWord(s, slices.Compact(words))
matches, longest = matchWord(s, slices.Compact(words))
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)))
d := dir
@@ -249,11 +249,11 @@ func matchFile(s string, dirOnly bool, escape func(string) string, unescape func
files, err := os.ReadDir(d)
if err != nil {
log.Printf("reading directory: %s", err)
result = s
longest = s
return
}
var commonName string
var longestName string
for _, f := range files {
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)})
if len(matches) == 1 {
commonName = name
longestName = name
} 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) {
case 0:
result = s
longest = s
case 1:
result = escape(dir + commonName)
if !strings.HasSuffix(commonName, string(filepath.Separator)) {
result += " "
longest = escape(dir + longestName)
if !strings.HasSuffix(longestName, string(filepath.Separator)) {
longest += " "
}
default:
result = escape(dir + commonName)
longest = escape(dir + longestName)
}
return
}
func matchCmdFile(s string, dirOnly bool) (matches []compMatch, result string) {
matches, result = matchFile(s, dirOnly, cmdEscape, cmdUnescape)
func matchCmdFile(s string, dirOnly bool) (matches []compMatch, longest string) {
matches, longest = matchFile(s, dirOnly, cmdEscape, cmdUnescape)
return
}
func matchShellFile(s string) (matches []compMatch, result string) {
matches, result = matchFile(s, false, shellEscape, shellUnescape)
func matchShellFile(s string) (matches []compMatch, longest string) {
matches, longest = matchFile(s, false, shellEscape, shellUnescape)
return
}
func matchSetlocalDir(s string) (matches []compMatch, result string) {
matches, result = matchFile(s, true, cmdEscape, cmdUnescape)
func matchSetlocalDir(s string) (matches []compMatch, longest string) {
matches, longest = matchFile(s, true, cmdEscape, cmdUnescape)
if len(matches) == 0 {
return
}
@@ -332,13 +334,13 @@ func matchSetlocalDir(s string) (matches []compMatch, result string) {
}
matches = tmp
if result != s {
result = trimSepEsc(result)
if longest != s {
longest = trimSepEsc(longest)
}
return
}
func matchExec(s string) (matches []compMatch, result string) {
func matchExec(s string) (matches []compMatch, longest string) {
var words []string
for p := range strings.SplitSeq(envPath, string(filepath.ListSeparator)) {
files, err := os.ReadDir(p)
@@ -367,15 +369,15 @@ func matchExec(s string) (matches []compMatch, result string) {
}
slices.Sort(words)
matches, result = matchWord(s, slices.Compact(words))
matches, longest = matchWord(s, slices.Compact(words))
return
}
func matchSearch(s string) (matches []compMatch, result string) {
func matchSearch(s string) (matches []compMatch, longest string) {
files, err := os.ReadDir(".")
if err != nil {
log.Printf("reading directory: %s", err)
result = s
longest = s
return
}
@@ -386,65 +388,66 @@ func matchSearch(s string) (matches []compMatch, result string) {
matches = append(matches, compMatch{f.Name(), f.Name()})
if len(matches) == 1 {
result = f.Name()
longest = f.Name()
} 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 {
result = s
longest = s
}
return
}
func completeCmd(acc []rune) (matches []compMatch, result string) {
func completeCmd(acc []rune) (matches []compMatch, longest string) {
s := string(acc)
f := tokenize(s)
if len(f) == 1 {
matches, result = matchCmd(s)
matches, longest = matchCmd(s)
return
}
result = f[len(f)-1]
longest = f[len(f)-1]
switch f[0] {
case "set":
if len(f) == 2 {
matches, result = matchWord(f[1], gOptWords)
matches, longest = matchWord(f[1], gOptWords)
break
}
if len(f) != 3 {
break
}
switch f[1] {
case "cleaner", "previewer":
matches, result = matchCmdFile(f[2], false)
case "cleaner", "previewer", "rulerfile":
matches, longest = matchCmdFile(f[2], false)
case "filtermethod", "searchmethod":
matches, result = matchWord(f[2], []string{"glob", "regex", "text"})
matches, longest = matchWord(f[2], []string{"glob", "regex", "text"})
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":
matches, result = matchList(f[2], []string{"mode", "timestamps"})
matches, longest = matchList(f[2], []string{"mode", "timestamps"})
case "selmode":
matches, result = matchWord(f[2], []string{"all", "dir"})
matches, longest = matchWord(f[2], []string{"all", "dir"})
case "sizeunits":
matches, result = matchWord(f[2], []string{"binary", "decimal"})
matches, longest = matchWord(f[2], []string{"binary", "decimal"})
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:
if slices.Contains(gOptWords, f[1]+"!") {
matches, result = matchWord(f[2], []string{"false", "true"})
matches, longest = matchWord(f[2], []string{"false", "true"})
}
}
case "setlocal":
if len(f) == 2 {
matches, result = matchSetlocalDir(f[1])
matches, longest = matchSetlocalDir(f[1])
break
}
if len(f) == 3 {
matches, result = matchWord(f[2], gLocalOptWords)
matches, longest = matchWord(f[2], gLocalOptWords)
break
}
if len(f) != 4 {
@@ -452,56 +455,56 @@ func completeCmd(acc []rune) (matches []compMatch, result string) {
}
switch f[2] {
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":
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:
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":
if len(f) == 3 {
matches, result = matchCmd(f[2])
matches, longest = matchCmd(f[2])
}
case "cmd":
case "cd":
if len(f) == 2 {
matches, result = matchCmdFile(f[1], true)
matches, longest = matchCmdFile(f[1], true)
}
case "addcustominfo", "select", "source":
if len(f) == 2 {
matches, result = matchCmdFile(f[1], false)
matches, longest = matchCmdFile(f[1], false)
}
case "toggle":
matches, result = matchCmdFile(f[len(f)-1], false)
matches, longest = matchCmdFile(f[len(f)-1], false)
default:
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
result = strings.Join(f, " ")
f[len(f)-1] = longest
longest = strings.Join(f, " ")
return
}
func completeShell(acc []rune) (matches []compMatch, result string) {
func completeShell(acc []rune) (matches []compMatch, longest string) {
f := tokenize(string(acc))
switch len(f) {
case 1:
matches, result = matchExec(f[0])
matches, longest = matchExec(f[0])
default:
matches, result = matchShellFile(f[len(f)-1])
matches, longest = matchShellFile(f[len(f)-1])
}
f[len(f)-1] = result
result = strings.Join(f, " ")
f[len(f)-1] = longest
longest = strings.Join(f, " ")
return
}
func completeSearch(acc []rune) (matches []compMatch, result string) {
matches, result = matchSearch(string(acc))
func completeSearch(acc []rune) (matches []compMatch, longest string) {
matches, longest = matchSearch(string(acc))
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 {
s1 string
s2 string
@@ -60,7 +60,7 @@ func TestCommonPrefix(t *testing.T) {
}
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)
}
}
@@ -71,24 +71,26 @@ func TestMatchWord(t *testing.T) {
s string
words []string
matches []compMatch
result string
longest string
}{
{"", nil, nil, ""},
{"", []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 "},
{"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"},
{"fo", []string{"bar", "baz"}, nil, "fo"},
}
for _, test := range tests {
matches, result := matchWord(test.s, test.words)
matches, longest := matchWord(test.s, test.words)
if !reflect.DeepEqual(matches, test.matches) {
t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches)
}
if result != test.result {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result)
if longest != test.longest {
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
words []string
matches []compMatch
result string
longest string
}{
{"", nil, nil, ""},
{"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""},
@@ -117,14 +119,14 @@ func TestMatchList(t *testing.T) {
}
for _, test := range tests {
matches, result := matchList(test.s, test.words)
matches, longest := matchList(test.s, test.words)
if !reflect.DeepEqual(matches, test.matches) {
t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches)
}
if result != test.result {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result)
if longest != test.longest {
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)
}
func checkRemoveDiacritics(testStr string, expStr string, t *testing.T) {
func checkRemoveDiacritics(testStr, expStr string, t *testing.T) {
resultStr := removeDiacritics(testStr)
if resultStr != expStr {
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*
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**
@@ -287,6 +287,7 @@ The following options can be used to customize the behavior of lf:
menufmt string (default "\033[0m")
menuheaderfmt string (default "\033[1m")
menuselectfmt string (default "\033[7m")
mergeindicators bool (default false)
mouse bool (default false)
number bool (default false)
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)
reverse bool (default false)
roundbox bool (default false)
rulerfile bool (default false)
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")
rulerfile string (default "")
rulerfmt string (default "")
scrolloff int (default 0)
searchmethod string (default 'text')
selectfmt string (default "\033[7;35m")
@@ -449,12 +450,6 @@ The icons file should be located at:
Unix /etc/lf/icons ~/.config/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:
Unix ~/.local/share/lf/files
@@ -690,7 +685,7 @@ Simulate key pushes given in the argument.
## 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.
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.
## 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)
Send mouse events as input.
@@ -1103,14 +1103,17 @@ Reverse the direction of sort.
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.
## 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.
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:
@@ -1203,6 +1206,8 @@ The following sort types are supported:
## 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.
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:
@@ -1777,6 +1782,10 @@ For example, to select a previous command using fzf and execute it:
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:
lf -remote 'quit'
@@ -2204,9 +2213,8 @@ https://github.com/gokcehan/lf/blob/master/etc/icons_colored.example
# 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).
This feature is currently experimental and must be enabled via the `rulerfile` option.
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}}`)
.Stat.Path string Path 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.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.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.User string User 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.CustomInfo string Custom property if defined via `addcustominfo`, otherwise a blank string
The following functions are exported:
+41 -24
View File
@@ -91,8 +91,8 @@ SERVER
-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
@@ -299,6 +299,7 @@ The following options can be used to customize the behavior of lf:
menufmt string (default "\033[0m")
menuheaderfmt string (default "\033[1m")
menuselectfmt string (default "\033[7m")
mergeindicators bool (default false)
mouse bool (default false)
number bool (default false)
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)
reverse bool (default false)
roundbox bool (default false)
rulerfile bool (default false)
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")
rulerfile string (default "")
rulerfmt string (default "")
scrolloff int (default 0)
searchmethod string (default 'text')
selectfmt string (default "\033[7;35m")
@@ -463,12 +464,6 @@ The icons file should be located at:
Unix /etc/lf/icons ~/.config/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:
Unix ~/.local/share/lf/files
@@ -724,9 +719,10 @@ Simulate key pushes given in the argument.
addcustominfo
Update the custom info field of the given file with the given string.
The info string may contain ANSI escape codes to further customize its
appearance. If no info is provided, clear the file's info instead.
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. If no info is provided, clear the
file's info instead.
calcdirsize
@@ -1098,6 +1094,13 @@ menuselectfmt (string) (default \033[7m)
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)
Send mouse events as input.
@@ -1197,15 +1200,18 @@ roundbox (bool) (default false)
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. Refer to the RULER section for more
information about how the ruler file works.
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 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:
@@ -1305,7 +1311,9 @@ The following sort types are supported:
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:
@@ -1960,6 +1968,10 @@ For example, to select a previous command using fzf and execute it:
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:
@@ -2473,12 +2485,10 @@ https://github.com/gokcehan/lf/blob/master/etc/icons_colored.example
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
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.
https://pkg.go.dev/text/template for more details on the syntax).
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}}`)
.Stat.Path string Path 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.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.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.User string User 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.CustomInfo string Custom property if defined via `addcustominfo`, otherwise a blank string
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)
if err == nil {
app.nav.sort()
app.ui.sort()
}
case "dironly", "nodironly", "dironly!":
err = applyBoolOpt(&gOpts.dironly, e)
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "dirpreviews", "nodirpreviews", "dirpreviews!":
@@ -98,7 +96,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "history", "nohistory", "history!":
@@ -110,7 +107,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "ignoredia", "noignoredia", "ignoredia!":
@@ -118,13 +114,14 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "incfilter", "noincfilter", "incfilter!":
err = applyBoolOpt(&gOpts.incfilter, e)
case "incsearch", "noincsearch", "incsearch!":
err = applyBoolOpt(&gOpts.incsearch, e)
case "mergeindicators", "nomergeindicators", "mergeindicators!":
err = applyBoolOpt(&gOpts.mergeindicators, e)
case "mouse", "nomouse", "mouse!":
err = applyBoolOpt(&gOpts.mouse, e)
if err == nil {
@@ -155,12 +152,9 @@ func (e *setExpr) eval(app *app, _ []string) {
err = applyBoolOpt(&gOpts.reverse, e)
if err == nil {
app.nav.sort()
app.ui.sort()
}
case "roundbox", "noroundbox", "roundbox!":
err = applyBoolOpt(&gOpts.roundbox, e)
case "rulerfile", "norulerfile", "rulerfile!":
err = applyBoolOpt(&gOpts.rulerfile, e)
case "showbinds", "noshowbinds", "showbinds!":
err = applyBoolOpt(&gOpts.showbinds, e)
case "smartcase", "nosmartcase", "smartcase!":
@@ -168,7 +162,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "smartdia", "nosmartdia", "smartdia!":
@@ -176,7 +169,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "watch", "nowatch", "watch!":
@@ -225,7 +217,6 @@ func (e *setExpr) eval(app *app, _ []string) {
}
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
case "findlen":
n, err := strconv.Atoi(e.val)
@@ -254,7 +245,6 @@ func (e *setExpr) eval(app *app, _ []string) {
gOpts.hiddenfiles = toks
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
case "ifs":
gOpts.ifs = e.val
@@ -344,6 +334,9 @@ func (e *setExpr) eval(app *app, _ []string) {
app.ui.wins = getWins(app.ui.screen)
app.nav.resize(app.ui)
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":
gOpts.rulerfmt = e.val
case "scrolloff":
@@ -401,7 +394,6 @@ func (e *setExpr) eval(app *app, _ []string) {
}
gOpts.sortby = method
app.nav.sort()
app.ui.sort()
case "statfmt":
gOpts.statfmt = e.val
case "tabstop":
@@ -485,14 +477,12 @@ func (e *setLocalExpr) eval(app *app, _ []string) {
err = applyLocalBoolOpt(gLocalOpts.dirfirst, gOpts.dirfirst, e)
if err == nil {
app.nav.sort()
app.ui.sort()
}
case "dironly", "nodironly", "dironly!":
err = applyLocalBoolOpt(gLocalOpts.dironly, gOpts.dironly, e)
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "hidden", "nohidden", "hidden!":
@@ -500,14 +490,12 @@ func (e *setLocalExpr) eval(app *app, _ []string) {
if err == nil {
app.nav.sort()
app.nav.position()
app.ui.sort()
app.ui.loadFile(app, true)
}
case "reverse", "noreverse", "reverse!":
err = applyLocalBoolOpt(gLocalOpts.reverse, gOpts.reverse, e)
if err == nil {
app.nav.sort()
app.ui.sort()
}
case "info":
if e.val == "" {
@@ -532,7 +520,6 @@ func (e *setLocalExpr) eval(app *app, _ []string) {
}
gLocalOpts.sortby[e.path] = method
app.nav.sort()
app.ui.sort()
default:
err = fmt.Errorf("unknown option: %s", e.opt)
}
@@ -849,7 +836,7 @@ func insert(app *app, arg string) {
app.nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
@@ -872,7 +859,7 @@ func insert(app *app, arg string) {
app.nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
@@ -893,7 +880,7 @@ func insert(app *app, arg string) {
return
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("mark-save: %s", err)
return
}
@@ -901,32 +888,14 @@ func insert(app *app, arg string) {
case app.ui.cmdPrefix == "mark-load: ":
normal(app)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
path, ok := app.nav.marks[arg]
if !ok {
app.ui.echoerr("mark-load: no such mark")
return
}
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)
if err := cd(app, path); err != nil {
app.ui.echoerrf("mark-load: %s", err)
}
case app.ui.cmdPrefix == "mark-remove: ":
normal(app)
@@ -944,7 +913,7 @@ func insert(app *app, arg string) {
return
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("mark-remove: %s", err)
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) {
app.ui.menu = ""
app.ui.menuSelect = nil
@@ -974,6 +974,7 @@ func exitCompMenu(app *app) {
func (e *callExpr) eval(app *app, _ []string) {
os.Setenv("lf_count", strconv.Itoa(e.count))
// commands that shouldn't clear the message line
silentCmds := []string{
"addcustominfo",
"clearmaps",
@@ -996,65 +997,38 @@ func (e *callExpr) eval(app *app, _ []string) {
case "quit":
app.quitChan <- struct{}{}
case "up":
if !app.nav.init {
return
}
if app.nav.up(e.count) {
app.ui.loadFile(app, true)
}
case "half-up":
if !app.nav.init {
return
}
if app.nav.up(e.count * app.nav.height / 2) {
app.ui.loadFile(app, true)
}
case "page-up":
if !app.nav.init {
return
}
if app.nav.up(e.count * app.nav.height) {
app.ui.loadFile(app, true)
}
case "scroll-up":
if !app.nav.init {
return
}
if app.nav.scrollUp(e.count) {
app.ui.loadFile(app, true)
}
case "down":
if !app.nav.init {
return
}
if app.nav.down(e.count) {
app.ui.loadFile(app, true)
}
case "half-down":
if !app.nav.init {
return
}
if app.nav.down(e.count * app.nav.height / 2) {
app.ui.loadFile(app, true)
}
case "page-down":
if !app.nav.init {
return
}
if app.nav.down(e.count * app.nav.height) {
app.ui.loadFile(app, true)
}
case "scroll-down":
if !app.nav.init {
return
}
if app.nav.scrollDown(e.count) {
app.ui.loadFile(app, true)
}
case "updir":
if !app.nav.init {
return
}
resetIncCmd(app)
preChdir(app)
for range e.count {
@@ -1067,12 +1041,8 @@ func (e *callExpr) eval(app *app, _ []string) {
restartIncCmd(app)
onChdir(app)
case "open":
if !app.nav.init {
return
}
curr, err := app.nav.currFile()
if err != nil {
app.ui.echoerrf("opening: %s", err)
curr := app.nav.currFile()
if curr == nil {
return
}
@@ -1117,9 +1087,6 @@ func (e *callExpr) eval(app *app, _ []string) {
restartIncCmd(app)
onChdir(app)
case "top":
if !app.nav.init {
return
}
var moved bool
if e.count == 1 {
moved = app.nav.top()
@@ -1130,9 +1097,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true)
}
case "bottom":
if !app.nav.init {
return
}
var moved bool
if e.count == 1 {
// 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)
}
case "high":
if !app.nav.init {
return
}
if app.nav.high() {
app.ui.loadFile(app, true)
}
case "middle":
if !app.nav.init {
return
}
if app.nav.middle() {
app.ui.loadFile(app, true)
}
case "low":
if !app.nav.init {
return
}
if app.nav.low() {
app.ui.loadFile(app, true)
}
case "toggle":
if !app.nav.init {
return
}
if len(e.args) == 0 {
app.nav.toggle()
} else {
dir := app.nav.currDir()
for _, path := range e.args {
path = replaceTilde(path)
if !filepath.IsAbs(path) {
path = filepath.Join(dir.path, path)
}
if _, err := os.Lstat(path); !os.IsNotExist(err) {
app.nav.toggleSelection(path)
} else {
path, err := filepath.Abs(replaceTilde(path))
if err != nil {
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":
if !app.nav.init {
return
}
app.nav.invert()
case "unselect":
app.nav.unselect()
case "glob-select":
if !app.nav.init {
return
}
if len(e.args) != 1 {
app.ui.echoerr("glob-select: requires a pattern to match")
return
@@ -1205,9 +1153,6 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
case "glob-unselect":
if !app.nav.init {
return
}
if len(e.args) != 1 {
app.ui.echoerr("glob-unselect: requires a pattern to match")
return
@@ -1217,10 +1162,6 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
case "copy":
if !app.nav.init {
return
}
if err := app.nav.save(clipboardCopy); err != nil {
app.ui.echoerrf("copy: %s", err)
return
@@ -1232,16 +1173,12 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("copy: %s", err)
return
}
}
case "cut":
if !app.nav.init {
return
}
if err := app.nav.save(clipboardCut); err != nil {
app.ui.echoerrf("cut: %s", err)
return
@@ -1253,16 +1190,12 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("cut: %s", err)
return
}
}
case "paste":
if !app.nav.init {
return
}
if cmd, ok := gOpts.cmds["paste"]; ok {
cmd.eval(app, e.args)
} 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)
case "clear":
if !app.nav.init {
return
}
if err := saveFiles(clipboard{nil, clipboardCut}); err != nil {
app.ui.echoerrf("clear: %s", err)
return
@@ -1284,7 +1214,7 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("clear: %s", err)
return
}
@@ -1295,9 +1225,6 @@ func (e *callExpr) eval(app *app, _ []string) {
}
case "draw":
case "redraw":
if !app.nav.init {
return
}
app.ui.screen.Sync()
app.ui.renew()
app.nav.resize(app.ui)
@@ -1305,22 +1232,15 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true)
onRedraw(app)
case "load":
if !app.nav.init || gOpts.watch {
if gOpts.watch {
return
}
app.nav.renew()
app.ui.loadFile(app, false)
case "reload":
if !app.nav.init {
return
}
app.nav.reload()
app.ui.loadFile(app, true)
case "delete":
if !app.nav.init {
return
}
if cmd, ok := gOpts.cmds["delete"]; ok {
cmd.eval(app, e.args)
app.nav.unselect()
@@ -1328,7 +1248,7 @@ func (e *callExpr) eval(app *app, _ []string) {
app.nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
app.ui.echoerrf("delete: %s", err)
return
}
@@ -1351,24 +1271,21 @@ func (e *callExpr) eval(app *app, _ []string) {
}
}
case "rename":
if !app.nav.init {
return
}
if cmd, ok := gOpts.cmds["rename"]; ok {
cmd.eval(app, e.args)
if gSingleMode {
app.nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
}
} else {
curr, err := app.nav.currFile()
if err != nil {
app.ui.echoerrf("rename: %s:", err)
curr := app.nav.currFile()
if curr == nil {
app.ui.echoerr("rename: empty directory")
return
}
if app.ui.cmdPrefix == ">" {
@@ -1430,9 +1347,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.cmdPrefix = "find-back: "
app.nav.findBack = true
case "find-next":
if !app.nav.init {
return
}
dir := app.nav.currDir()
old := dir.ind
for range e.count {
@@ -1446,9 +1360,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true)
}
case "find-prev":
if !app.nav.init {
return
}
dir := app.nav.currDir()
old := dir.ind
for range e.count {
@@ -1462,9 +1373,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.loadFile(app, true)
}
case "search":
if !app.nav.init {
return
}
if app.ui.cmdPrefix == ">" {
return
}
@@ -1475,9 +1383,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.nav.searchPos = dir.pos
app.nav.searchBack = false
case "search-back":
if !app.nav.init {
return
}
if app.ui.cmdPrefix == ">" {
return
}
@@ -1488,9 +1393,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.nav.searchPos = dir.pos
app.nav.searchBack = true
case "search-next":
if !app.nav.init {
return
}
for range e.count {
if app.nav.searchBack {
if moved, err := app.nav.searchPrev(); err != nil {
@@ -1507,9 +1409,6 @@ func (e *callExpr) eval(app *app, _ []string) {
}
}
case "search-prev":
if !app.nav.init {
return
}
for range e.count {
if app.nav.searchBack {
if moved, err := app.nav.searchNext(); err != nil {
@@ -1526,9 +1425,6 @@ func (e *callExpr) eval(app *app, _ []string) {
}
}
case "filter":
if !app.nav.init {
return
}
if app.ui.cmdPrefix == ">" {
return
}
@@ -1542,9 +1438,6 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.cmdAccLeft = []rune(strings.Join(e.args, " "))
}
case "setfilter":
if !app.nav.init {
return
}
log.Printf("filter: %s", e.args)
if err := app.nav.setFilter(e.args); err != nil {
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.cmdPrefix = "mark-remove: "
case "tag":
if !app.nav.init {
return
}
tag := "*"
if len(e.args) != 0 {
tag = e.args[0]
@@ -1591,15 +1480,11 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerrf("tag: %s", err)
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("tag: %s", err)
}
}
case "tag-toggle":
if !app.nav.init {
return
}
tag := "*"
if len(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)
}
} else {
if err := remote("send sync"); err != nil {
if _, err := remote("send sync"); err != nil {
app.ui.echoerrf("tag-toggle: %s", err)
}
}
@@ -1632,73 +1517,38 @@ func (e *callExpr) eval(app *app, _ []string) {
path = e.args[0]
}
wd, err := os.Getwd()
if err != nil {
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)
if err := cd(app, path); err != nil {
app.ui.echoerrf("cd: %s", err)
}
case "select":
if !app.nav.init {
return
}
if len(e.args) != 1 {
app.ui.echoerr("select: requires an argument")
return
}
wd, err := os.Getwd()
path, err := filepath.Abs(replaceTilde(e.args[0]))
if err != nil {
log.Printf("getting current directory: %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)
app.ui.echoerrf("select: %s", err)
return
}
app.ui.loadFile(app, true)
lstat, err := os.Lstat(path)
if err != nil {
app.ui.echoerrf("select: %s", err)
return
}
if wd != path {
app.nav.marks["'"] = wd
restartIncCmd(app)
onChdir(app)
if err := cd(app, filepath.Dir(path)); err != nil {
app.ui.echoerrf("select: %s", err)
return
}
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":
if len(e.args) != 1 {
@@ -1721,7 +1571,7 @@ func (e *callExpr) eval(app *app, _ []string) {
case 1:
k, v = e.args[0], ""
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:
app.ui.echoerr("addcustominfo: requires either 1 or 2 arguments")
return
@@ -1733,12 +1583,7 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
dir := filepath.Dir(path)
d, ok := app.nav.dirCache[dir]
if !ok {
app.ui.echoerrf("addcustominfo: dir not loaded: %s", dir)
return
}
d := app.nav.getDir(filepath.Dir(path))
var f *file
for _, file := range d.allFiles {
@@ -1752,27 +1597,20 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
if len(strings.Trim(v, " ")) == 0 {
v = ""
}
if f.customInfo != v {
f.customInfo = v
// only sort when order changes
if getSortBy(dir) == customSort {
if getSortBy(d.path) == customSort {
d.sort()
}
}
case "calcdirsize":
if !app.nav.init {
return
}
err := app.nav.calcDirSize()
if err != nil {
app.ui.echoerrf("calcdirsize: %s", err)
return
}
app.nav.sort()
app.ui.sort()
case "clearmaps":
// leave `:` and cmaps bound so the user can still exit using `:quit`
clear(gOpts.nkeys)
@@ -1793,16 +1631,10 @@ func (e *callExpr) eval(app *app, _ []string) {
tty.Write([]byte(e.args[0]))
case "visual":
if !app.nav.init {
return
}
dir := app.nav.currDir()
dir.visualAnchor = dir.ind
dir.visualWrap = 0
case "visual-accept":
if !app.nav.init {
return
}
dir := app.nav.currDir()
for _, path := range dir.visualSelections() {
if _, ok := app.nav.selections[path]; !ok {
@@ -1815,9 +1647,6 @@ func (e *callExpr) eval(app *app, _ []string) {
dir.visualAnchor = -1
normal(app)
case "visual-unselect":
if !app.nav.init {
return
}
dir := app.nav.currDir()
for _, path := range dir.visualSelections() {
delete(app.nav.selections, path)
@@ -1828,9 +1657,6 @@ func (e *callExpr) eval(app *app, _ []string) {
dir.visualAnchor = -1
normal(app)
case "visual-discard":
if !app.nav.init {
return
}
dir := app.nav.currDir()
dir.visualAnchor = -1
normal(app)
@@ -1966,9 +1792,9 @@ func (e *callExpr) eval(app *app, _ []string) {
case "rename: ":
app.ui.cmdPrefix = ""
curr, err := app.nav.currFile()
if err != nil {
app.ui.echoerrf("rename: %s", err)
curr := app.nav.currFile()
if curr == nil {
app.ui.echoerr("rename: empty directory")
return
}
wd, err := os.Getwd()
@@ -2012,7 +1838,7 @@ func (e *callExpr) eval(app *app, _ []string) {
if gSingleMode {
app.nav.renew()
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
@@ -2231,7 +2057,8 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
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) {
return
+2 -2
View File
@@ -7,8 +7,8 @@ require (
github.com/fsnotify/fsnotify v1.9.0
github.com/gdamore/tcell/v2 v2.9.0
github.com/mattn/go-runewidth v0.0.19
golang.org/x/sys v0.38.0
golang.org/x/term v0.37.0
golang.org/x/sys v0.40.0
golang.org/x/term v0.39.0
)
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-20220722155257-8c9f86f7a55f/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.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
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-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.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/term v0.39.0 h1:RclSuaJf32jOqZz74CkPA9qFuVTX7vhLlpfj/IGWlqY=
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.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
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
.\"
.TH "LF" "1" "2025\-12\-02" "r39" "DOCUMENTATION"
.TH "LF" "1" "2026\-02\-04" "r41" "DOCUMENTATION"
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
@@ -88,8 +88,9 @@ list to \f[I]path\f[R] instead of stdout.
.SS SERVER
.TP
\f[B]\-remote\f[R] \f[I]command\f[R]
Send \f[I]command\f[R] to the running server (e.g.
\f[CR]send\f[R], \f[CR]query\f[R] or \f[CR]quit\f[R]).
Send \f[I]command\f[R] to the running server (i.e.
\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.
.TP
\f[B]\-server\f[R]
@@ -310,6 +311,7 @@ infotimefmtold string (default \(aqJan _2 2006\(aq)
menufmt string (default \(dq\(rs033[0m\(dq)
menuheaderfmt string (default \(dq\(rs033[1m\(dq)
menuselectfmt string (default \(dq\(rs033[7m\(dq)
mergeindicators bool (default false)
mouse bool (default false)
number bool (default false)
numberfmt string (default \(dq\(rs033[33m\(dq)
@@ -323,8 +325,8 @@ ratios []int (default \(aq1:2:3\(aq)
relativenumber bool (default false)
reverse bool (default false)
roundbox bool (default false)
rulerfile bool (default false)
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)
rulerfile string (default \(dq\(dq)
rulerfmt string (default \(dq\(dq)
scrolloff int (default 0)
searchmethod string (default \(aqtext\(aq)
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
.EE
.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:
.IP
.EX
@@ -686,8 +680,8 @@ Read the configuration file given in the argument.
.SS push
Simulate key pushes given in the argument.
.SS addcustominfo
Update the \f[CR]custom\f[R] info field of the given file with the given
string.
Update the \f[CR]custom\f[R] info and \f[CR].Stat.CustomInfo\f[R] field
of the given file with the given string.
The info string may contain ANSI escape codes to further customize its
appearance.
If no info is provided, clear the file\(aqs info instead.
@@ -971,6 +965,12 @@ Format string of the menu.
Format string of the header row in the menu.
.SS menuselectfmt (string) (default \f[CR]\(rs033[7m\f[R])
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)
Send mouse events as input.
.SS number (bool) (default false)
@@ -1060,16 +1060,20 @@ Reverse the direction of sort.
.SS roundbox (bool) (default false)
Draw rounded outer corners when the \f[CR]drawbox\f[R] option is
enabled.
.SS rulerfile (bool) (default false)
Use the ruler file instead of the \f[CR]rulerfmt\f[R] and
\f[CR]statfmt\f[R] options when drawing the ruler at the bottom.
.SS rulerfile (string) (default \(ga\(ga)
Set the path of the ruler file.
If not set, then a default template will be used for the ruler.
Refer to the \c
.UR https://github.com/gokcehan/lf/blob/master/doc.md#ruler
RULER section
.UE \c
\ 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.
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
The following special expansions are supported:
.IP
@@ -1160,6 +1164,9 @@ custom property defined via \(gaaddcustominfo\(ga (empty by default)
.EE
.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.
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
The following special expansions are supported:
.IP
@@ -1849,6 +1856,13 @@ map <a\-h> ${{
}}
.EE
.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
are no connected clients left, and a \f[CR]quit!\f[R] command to force
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
.UE \c
.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
CONFIGURATION section
.UE \c
@@ -2509,8 +2524,6 @@ rendered to create the actual output (refer to \c
.UR https://pkg.go.dev/text/template
.UE \c
\ for more details on the syntax).
This feature is currently experimental and must be enabled via the
\f[CR]rulerfile\f[R] option.
.PP
The following data fields are exported:
.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)
\&.Stat.Path string Path 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.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.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.User string User 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.CustomInfo string Custom property if defined via \(gaaddcustominfo\(ga, otherwise a blank string
.EE
.PP
The following functions are exported:
+4 -1
View File
@@ -342,9 +342,12 @@ func main() {
case *showVersion:
printVersion()
case *remoteCmd != "":
if err := remote(*remoteCmd); err != nil {
resp, err := remote(*remoteCmd)
if err != nil {
log.Fatalf("remote command: %s", err)
return
}
fmt.Print(resp)
case *serverMode:
if err := os.Chdir(gUser.HomeDir); err != nil {
log.Print(err)
+56 -33
View File
@@ -70,7 +70,8 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune {
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 {
lastWidth := 0
for i := len(rs) - 1; i >= 0; i-- {
@@ -83,7 +84,7 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
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.
func cmdEscape(s string) string {
buf := make([]rune, 0, len(s))
@@ -96,8 +97,8 @@ func cmdEscape(s string) string {
return string(buf)
}
// This function is used to remove backslashes that are used to escape
// whitespaces and special characters in a given string.
// cmdUnescape is used to remove backslashes that are used to escape
// whitespace and special characters in a given string.
func cmdUnescape(s string) string {
esc := false
buf := make([]rune, 0, len(s))
@@ -123,8 +124,8 @@ func cmdUnescape(s string) string {
return string(buf)
}
// This function splits the given string by whitespaces. It is aware of escaped
// and quoted whitespaces so that they are not split unintentionally.
// tokenize splits the given string by whitespace. It is aware of escaped
// and quoted whitespace so that they are not split unintentionally.
func tokenize(s string) []string {
esc := false
quote := false
@@ -151,7 +152,7 @@ func tokenize(s string) []string {
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
// rest. Whitespace on the left side of both the word and the rest are trimmed.
func splitWord(s string) (word, rest string) {
@@ -168,8 +169,8 @@ func splitWord(s string) (word, rest string) {
return
}
// This function reads whitespace separated string arrays at each line. Single
// or double quotes can be used to escape whitespaces. Hash characters can be
// readArrays reads whitespace-separated string arrays on each line. Single
// 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
// trimmed. Empty lines are skipped.
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)
}
// 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)
// multiples. The output should be no more than 5 characters long.
func humanize(size uint64) string {
@@ -255,9 +256,8 @@ func humanize(size uint64) string {
return fmt.Sprintf("%dB", size)
}
// *Note*: due to [`FileSize.Size()`](https://pkg.go.dev/io/fs#FileInfo)
// being `int64`, the maximum possible representable value would be 8 EiB or
// 9.2 EB.
// Note: due to [fs.FileInfo.Size] being `int64`, the maximum
// possible representable value would be 8 EiB or 9.2 EB.
prefixes := []string{
"K", // kibi (2^10) or kilo (10^3)
"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])
}
// This function returns an ls(1)-style string representation of the given file
// mode, to avoid using Go's implementation, which slightly differs.
// permString returns an ls(1)-style string representation of the given file
// mode, to avoid using [fs.FileMode.String], which differs slightly.
func permString(m os.FileMode) string {
// re-use Perm()'s "-rwxrwxrwx" output and write type into b[0]
b := []byte(m.Perm().String())
@@ -337,7 +337,7 @@ func permString(m os.FileMode) string {
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
// '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing
// 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
// it returns an empty string if extension could not be determined
// getFileExtension returns the extension of a file with a leading dot.
// It returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
func getFileExtension(file fs.FileInfo) string {
if file.IsDir() {
@@ -403,12 +403,12 @@ func getFileExtension(file fs.FileInfo) string {
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
// 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
// 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()
if runeSliceWidth([]rune(filename)) <= maxWidth {
return filename
@@ -433,8 +433,8 @@ func truncateFilename(file fs.FileInfo, maxWidth int, truncatePct int, truncateC
return string(result)
}
// This function deletes entries from a map if the key is either the given path
// or a subpath of it.
// deletePathRecursive deletes entries from a map if the key is either the given
// path or a subpath of it.
// This is useful for clearing cached data when a directory is moved or deleted.
func deletePathRecursive[T any](m map[string]T, path string) {
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
// 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.
// readLines 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.
// Lines are split on `\n` characters, and `\r` characters are discarded.
// 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 type control
// 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) {
tests := []struct {
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) {
tests := []struct {
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 (
"bufio"
"bytes"
"cmp"
"errors"
"fmt"
@@ -22,27 +23,28 @@ import (
"github.com/djherbis/times"
)
// A linkState describes whether a file is a symlink and whether its target exists.
type linkState byte
const (
notLink linkState = iota
working
broken
notLink linkState = iota // Not a symbolic link.
working // Symbolic link with an existing target.
broken // Symbolic link with a missing target.
)
type file struct {
os.FileInfo
linkState linkState
linkTarget string
path string
dirCount int
dirSize int64
accessTime time.Time
birthTime time.Time
changeTime time.Time
customInfo string
ext string
err error
os.FileInfo // stat information
linkState linkState // symlink state
linkTarget string // path a symlink points to
path string // full path including the name
dirCount *uint64 // number of items inside the directory
dirSize *uint64 // total directory size (needs to be calculated via `calcdirsize`)
accessTime time.Time // time of last access
birthTime time.Time // time of file birth
changeTime time.Time // time of last status (inode) change
customInfo string // property defined via `addcustominfo`
ext string // file extension (including the dot)
err error // potential error returned by [os.Lstat]
}
func newFile(path string) *file {
@@ -52,15 +54,10 @@ func newFile(path string) *file {
return &file{
FileInfo: &fakeStat{name: filepath.Base(path)},
linkState: notLink,
linkTarget: "",
path: path,
dirCount: -1,
dirSize: -1,
accessTime: time.Unix(0, 0),
birthTime: time.Unix(0, 0),
changeTime: time.Unix(0, 0),
customInfo: "",
ext: "",
err: err,
}
}
@@ -84,7 +81,7 @@ func newFile(path string) *file {
ts := times.Get(lstat)
at := ts.AccessTime()
// from times docs:
// from [times.Timespec] docs:
// ChangeTime() panics unless HasChangeTime() is true and
// BirthTime() panics unless HasBirthTime() is true.
@@ -99,19 +96,20 @@ func newFile(path string) *file {
ct = ts.ChangeTime()
}
dirCount := -1
var dirCount *uint64
if lstat.IsDir() && getDirCounts(filepath.Dir(path)) {
d, err := os.Open(path)
if err != nil {
dirCount = -2
log.Printf("opening file: %s", err)
} else {
names, err := d.Readdirnames(10000)
d.Close()
if names == nil && err != io.EOF {
dirCount = -2
log.Printf("reading directory: %s", err)
} else {
dirCount = len(names)
v := uint64(len(names))
dirCount = &v
}
}
}
@@ -122,36 +120,15 @@ func newFile(path string) *file {
linkTarget: linkTarget,
path: path,
dirCount: dirCount,
dirSize: -1,
accessTime: at,
birthTime: bt,
changeTime: ct,
customInfo: "",
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 {
if file.Mode().IsRegular() {
return true
}
if file.IsDir() && gOpts.dirpreviews {
return true
}
return false
return !file.IsDir() || gOpts.dirpreviews
}
type fakeStat struct {
@@ -175,17 +152,20 @@ func readdir(path string) ([]*file, error) {
files := make([]*file, 0, len(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
}
type dir struct {
loading bool // directory is loading from disk
loading bool // whether directory is loading from disk
loadTime time.Time // last load time
ind int // index of current entry in files
pos int // position of current entry in ui
ind int // 0-based index of current entry in dir.files
pos int // 0-based cursor row in directory window
path string // full path of directory
files []*file // displayed files in directory including or excluding hidden ones
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
reverse bool // reverse value from last sort
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
filter []string // last filter for this directory
ignorecase bool // ignorecase value from last sort
@@ -295,14 +275,29 @@ func (dir *dir) sort() {
return cmp.Compare(normalize(f1.Name()), normalize(f2.Name()))
})
case sizeSort:
sizeVal := func(f *file) int64 {
sizeVal := func(f *file) *uint64 {
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 {
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:
applySort(func(f1, f2 *file) int {
@@ -365,7 +360,7 @@ func (dir *dir) name() string {
}
func (nav *nav) isVisualMode() bool {
return nav.init && nav.currDir().visualAnchor != -1
return nav.currDir().visualAnchor != -1
}
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))
}
// clipboardMode controls the clipboard's behavior when pasting.
type clipboardMode byte
const (
clipboardCopy = iota
clipboardCut
clipboardCopy clipboardMode = iota // Copy on paste.
clipboardCut // Move on paste.
)
type clipboard struct {
@@ -448,8 +444,7 @@ type clipboard struct {
}
type nav struct {
init bool
dirs []*dir
dirPaths []string
copyJobs int
copyBytes int64
copyTotal int64
@@ -499,32 +494,30 @@ type nav struct {
jumpListInd int
}
func (nav *nav) loadDir(path string) *dir {
d, ok := nav.dirCache[path]
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
func (nav *nav) getDir(path string) *dir {
if d, ok := nav.dirCache[path]; ok {
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
}
@@ -577,24 +570,26 @@ func (nav *nav) checkDir(dir *dir) {
}
}
func (nav *nav) updateDirs(wd string) {
var dirs []*dir
func (nav *nav) loadDirs() {
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) {
dir := nav.loadDir(curr)
dirPaths = append(dirPaths, curr)
dir := nav.getDir(curr)
if base != "" {
dir.sel(base, nav.height)
}
dirs = append(dirs, dir)
}
for i, j := 0, len(dirs)-1; i < j; i, j = i+1, j-1 {
dirs[i], dirs[j] = dirs[j], dirs[i]
}
nav.dirs = dirs
slices.Reverse(dirPaths)
nav.dirPaths = dirPaths
}
func newNav(ui *ui) *nav {
@@ -662,8 +657,9 @@ func (nav *nav) cdJumpListNext() {
}
func (nav *nav) renew() {
for _, d := range nav.dirs {
nav.checkDir(d)
for _, path := range nav.dirPaths {
dir := nav.getDir(path)
nav.checkDir(dir)
}
for m := range nav.selections {
@@ -678,14 +674,16 @@ func (nav *nav) renew() {
}
func (nav *nav) reload() {
curr := nav.currFile()
clear(nav.dirCache)
clear(nav.regCache)
curr, err := nav.currFile()
nav.updateDirs(nav.currDir().path)
if err == nil {
last := nav.dirs[len(nav.dirs)-1]
last.files = append(last.files, curr)
nav.loadDirs()
if curr != nil {
dir := nav.currDir()
dir.files = append(dir.files, curr)
}
}
@@ -698,8 +696,8 @@ func (nav *nav) resize(ui *ui) {
nav.height = previewWin.h
nav.previewWidth = previewWin.w
for _, dir := range nav.dirs {
dir.boundPos(nav.height)
for _, path := range nav.dirPaths {
nav.getDir(path).boundPos(nav.height)
}
clear(nav.regCache)
@@ -707,24 +705,22 @@ func (nav *nav) resize(ui *ui) {
}
func (nav *nav) position() {
if !nav.init {
return
}
var path string
var base string
path := nav.currDir().path
for i := len(nav.dirs) - 2; i >= 0; i-- {
nav.dirs[i].sel(filepath.Base(path), nav.height)
path = filepath.Dir(path)
for i := len(nav.dirPaths) - 1; i >= 0; i-- {
path = nav.dirPaths[i]
if i < len(nav.dirPaths)-1 {
nav.getDir(path).sel(base, nav.height)
}
base = filepath.Base(path)
}
}
func (nav *nav) exportFiles() {
if !nav.init {
return
}
var currFile string
if curr, err := nav.currFile(); err == nil {
if curr := nav.currFile(); curr != nil {
currFile = quoteString(curr.path)
}
@@ -753,24 +749,29 @@ func (nav *nav) exportFiles() {
}
func (nav *nav) preloadLoop(ui *ui) {
processed := make(map[string]struct{})
process := func(path string) {
if _, ok := processed[path]; !ok {
nav.preview(path, ui.wins[len(ui.wins)-1], "preload")
processed[path] = struct{}{}
}
stack := []string{}
push := func(path string) {
stack = slices.DeleteFunc(stack, func(s string) bool { return s == path })
stack = append(stack, path)
}
for path := range nav.preloadChan {
clear(processed)
process(path)
loop:
for {
pop := func() string {
path := stack[len(stack)-1]
stack = stack[:len(stack)-1]
return path
}
for {
if len(stack) == 0 {
push(<-nav.preloadChan)
} else {
select {
case path = <-nav.preloadChan:
process(path)
case path := <-nav.preloadChan:
push(path)
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]
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.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y),
path)
path,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
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
}
@@ -825,7 +839,7 @@ func matchPattern(pattern, name, path string) bool {
}
func (nav *nav) preload() {
if !nav.init || !gOpts.preview || !gOpts.preload {
if !gOpts.preview || !gOpts.preload {
return
}
@@ -852,12 +866,11 @@ func (nav *nav) preload() {
}
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)
}
for i := 1; i <= nav.height/2; i++ {
doPreload(dir.ind - i)
}
doPreload(dir.ind)
}
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),
mode,
)
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.StdoutPipe()
if err != nil {
@@ -906,10 +921,24 @@ func (nav *nav) preview(path string, win *win, mode string) {
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()
reader = bufio.NewReader(out)
} 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)
if err != nil {
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 {
r, ok := nav.regCache[path]
if !ok {
if !ok || (!gOpts.preload && r.loading) {
r = &reg{loading: true, loadTime: time.Now(), path: path}
nav.regCache[path] = r
nav.startPreview()
@@ -982,10 +1011,18 @@ func (nav *nav) startPreview() {
}
func (nav *nav) sort() {
for _, d := range nav.dirs {
name := d.name()
d.sort()
d.sel(name, nav.height)
for _, path := range nav.dirPaths {
dir := nav.getDir(path)
name := dir.name()
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 {
dir := nav.currDir()
// when reached top do nothing
if istop := dir.ind == dir.pos; istop {
return false
}
old := dir.ind
minedge := min(nav.height/2, gOpts.scrolloff)
oldPos := dir.pos
dir.pos += dist
dir.boundPos(nav.height)
// jump to ensure minedge when edge < minedge
edge := nav.height - 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)
dir.ind -= dist - (dir.pos - oldPos)
dir.ind = max(dir.ind, dir.pos)
return old != dir.ind
}
func (nav *nav) scrollDown(dist int) bool {
dir := nav.currDir()
maxind := len(dir.files) - 1
// reached bottom
if dir.ind-dir.pos > maxind-nav.height {
return false
}
old := dir.ind
minedge := min(nav.height/2, gOpts.scrolloff)
oldPos := dir.pos
dir.pos -= dist
dir.boundPos(nav.height)
// jump to ensure minedge when edge < minedge
delta := min(0, dir.pos-minedge)
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)
dir.ind += dist - (oldPos - dir.pos)
dir.ind = min(dir.ind, dir.pos+max(len(dir.files)-nav.height, 0))
return old != dir.ind
}
func (nav *nav) updir() error {
if len(nav.dirs) <= 1 {
if len(nav.dirPaths) < 2 {
return nil
}
dir := nav.currDir()
nav.dirs = nav.dirs[:len(nav.dirs)-1]
if err := os.Chdir(filepath.Dir(dir.path)); err != nil {
if err := os.Chdir(nav.dirPaths[len(nav.dirPaths)-2]); err != nil {
return fmt.Errorf("updir: %w", err)
}
nav.dirPaths = nav.dirPaths[:len(nav.dirPaths)-1]
return nil
}
func (nav *nav) open() error {
curr, err := nav.currFile()
if err != nil {
return fmt.Errorf("open: %w", err)
}
path := curr.path
dir := nav.loadDir(path)
nav.dirs = append(nav.dirs, dir)
if err := os.Chdir(path); err != nil {
curr := nav.currFile()
if curr == nil {
return nil
}
if err := os.Chdir(curr.path); err != nil {
return fmt.Errorf("open: %w", err)
}
nav.dirPaths = append(nav.dirPaths, curr.path)
return nil
}
@@ -1255,15 +1256,12 @@ func (nav *nav) toggleSelection(path string) {
}
func (nav *nav) toggle() {
curr, err := nav.currFile()
if err != nil {
return
if curr := nav.currFile(); curr != nil {
nav.toggleSelection(curr.path)
}
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 {
delete(nav.tags, path)
} else {
@@ -1306,10 +1304,8 @@ func (nav *nav) tag(tag string) error {
}
func (nav *nav) invert() {
dir := nav.currDir()
for _, f := range dir.files {
path := filepath.Join(dir.path, f.Name())
nav.toggleSelection(path)
for _, file := range nav.currDir().files {
nav.toggleSelection(file.path)
}
}
@@ -1383,7 +1379,7 @@ loop:
nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
sendErr("%v", err)
}
}
@@ -1489,7 +1485,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
sendErr("%v", err)
}
}
@@ -1549,7 +1545,7 @@ func (nav *nav) del(app *app) error {
nav.renew()
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
if _, err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
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.
deletePathRecursive(nav.regCache, newPath)
deletePathRecursive(nav.dirCache, newPath)
dir := nav.loadDir(filepath.Dir(newPath))
dir := nav.getDir(filepath.Dir(newPath))
nav.checkDir(dir)
if dir.loading {
for i := range dir.allFiles {
@@ -1622,56 +1619,16 @@ func (nav *nav) sync() error {
return err
}
func (nav *nav) cd(wd string) error {
wd = replaceTilde(wd)
wd = filepath.Clean(wd)
if !filepath.IsAbs(wd) {
wd = filepath.Join(nav.currDir().path, wd)
func (nav *nav) cd(path string) error {
if err := os.Chdir(path); err != nil {
return err
}
if err := os.Chdir(wd); err != nil {
return fmt.Errorf("cd: %w", err)
}
nav.updateDirs(wd)
nav.loadDirs()
nav.addJumpList()
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 {
dir := nav.currDir()
anyMatched := false
@@ -1992,17 +1949,22 @@ func (nav *nav) writeTags() error {
}
func (nav *nav) currDir() *dir {
return nav.dirs[len(nav.dirs)-1]
}
func (nav *nav) currFile() (*file, error) {
dir := nav.dirs[len(nav.dirs)-1]
if len(dir.files) == 0 {
return nil, errors.New("empty directory")
if len(nav.dirPaths) == 0 {
nav.loadDirs()
}
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 {
@@ -2040,16 +2002,15 @@ func (nav *nav) currSelections() []string {
}
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 {
curr, err := nav.currFile()
if err != nil {
return nil, errors.New("no file selected")
}
if curr := nav.currFile(); curr != nil {
return []string{curr.path}, nil
}
return sel, nil
return nil, errors.New("no file selected")
}
func (nav *nav) calcDirSize() error {
@@ -2059,14 +2020,15 @@ func (nav *nav) calcDirSize() error {
if err != nil {
return err
}
f.dirSize = total
v := uint64(total)
f.dirSize = &v
}
return nil
}
if len(nav.selections) == 0 {
curr, err := nav.currFile()
if err != nil {
curr := nav.currFile()
if curr == nil {
return errors.New("no file selected")
}
return calc(curr)
@@ -2078,7 +2040,7 @@ func (nav *nav) calcDirSize() error {
continue
}
path, name := filepath.Dir(sel), filepath.Base(sel)
dir := nav.loadDir(path)
dir := nav.getDir(path)
for _, f := range dir.files {
if f.Name() == name {
+5 -3
View File
@@ -78,6 +78,7 @@ var gOpts struct {
menufmt string
menuheaderfmt string
menuselectfmt string
mergeindicators bool
mouse bool
number bool
numberfmt string
@@ -91,7 +92,7 @@ var gOpts struct {
relativenumber bool
reverse bool
roundbox bool
rulerfile bool
rulerfile string
rulerfmt string
scrolloff int
searchmethod searchMethod
@@ -240,6 +241,7 @@ func init() {
gOpts.menufmt = "\033[0m"
gOpts.menuheaderfmt = "\033[1m"
gOpts.menuselectfmt = "\033[7m"
gOpts.mergeindicators = false
gOpts.mouse = false
gOpts.number = false
gOpts.numberfmt = "\033[33m"
@@ -253,8 +255,8 @@ func init() {
gOpts.relativenumber = false
gOpts.reverse = false
gOpts.roundbox = false
gOpts.rulerfile = false
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.rulerfile = ""
gOpts.rulerfmt = ""
gOpts.scrolloff = 0
gOpts.searchmethod = textSearch
gOpts.selectfmt = "\033[7;35m"
-6
View File
@@ -38,7 +38,6 @@ var (
gConfigPaths []string
gColorsPaths []string
gIconsPaths []string
gRulerPaths []string
gFilesPath string
gMarksPath string
gTagsPath string
@@ -106,11 +105,6 @@ func init() {
filepath.Join(config, "lf", "icons"),
}
gRulerPaths = []string{
filepath.Join("/etc", "lf", "ruler"),
filepath.Join(config, "lf", "ruler"),
}
data := cmp.Or(
os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"),
-6
View File
@@ -36,7 +36,6 @@ var (
gConfigPaths []string
gColorsPaths []string
gIconsPaths []string
gRulerPaths []string
gFilesPath string
gTagsPath string
gMarksPath string
@@ -96,11 +95,6 @@ func init() {
filepath.Join(config, "lf", "icons"),
}
gRulerPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "ruler"),
filepath.Join(config, "lf", "ruler"),
}
data := cmp.Or(
os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"),
+13 -13
View File
@@ -2,8 +2,8 @@ package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"text/template"
@@ -16,13 +16,20 @@ var gDefaultRuler string
type statData struct {
Path string
Name string
Extension string
Size uint64
DirSize *uint64
DirCount *uint64
Permissions string
ModTime string
AccessTime string
BirthTime string
ChangeTime string
LinkCount string
User string
Group string
Target string
CustomInfo string
}
type rulerData struct {
@@ -46,7 +53,7 @@ type rulerData struct {
Stat *statData
}
func parseRuler() (*template.Template, error) {
func parseRuler(path string) (*template.Template, error) {
funcs := template.FuncMap{
"df": func() string { return diskFree(".") },
"env": os.Getenv,
@@ -57,17 +64,11 @@ func parseRuler() (*template.Template, error) {
"upper": strings.ToUpper,
}
for i := len(gRulerPaths) - 1; i >= 0; i-- {
path := gRulerPaths[i]
if _, err := os.Stat(path); os.IsNotExist(err) {
continue
}
log.Printf("reading file: %s", path)
return template.New("ruler").Funcs(funcs).ParseFiles(path)
if path == "" {
return template.New("ruler").Funcs(funcs).Parse(gDefaultRuler)
}
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) {
@@ -76,8 +77,7 @@ func renderRuler(ruler *template.Template, data rulerData, width int) (string, s
return "", "", err
}
s := strings.TrimSuffix(b.String(), "\n")
s = strings.ReplaceAll(s, "\n", "\033[0;7m\\n\033[0m")
s := strings.ReplaceAll(b.String(), "\n", "")
sections := strings.Split(s, "\x1f")
if len(sections) == 1 {
+10
View File
@@ -6,6 +6,7 @@ import (
"log"
"net"
"os"
"sort"
"strconv"
)
@@ -106,6 +107,15 @@ Loop:
} else {
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":
if rest != "" {
word2, rest2 := splitWord(rest)
-5
View File
@@ -28,11 +28,6 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return
}
if !reg.sixel {
sxs.lastFile = ""
return
}
cw, ch, err := cellSize(screen)
if err != nil {
log.Printf("sixel: %s", err)
+36 -17
View File
@@ -11,14 +11,17 @@ import (
"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.
//
// *Note*: this function is based entirely on `printLength()` and strips only
// style-related sequences, `erase in line` and `OSC 8` sequences. Other codes
// (e.g., cursor moves), as well as broken escape sequences, aren't removed.
// This prevents mismatches between the two functions and avoids misalignment
// when rendering the UI.
// Note: this function is based on [printLength] and only strips style-related
// sequences, `erase in line`, and `OSC 8` sequences. Other codes (e.g. cursor
// moves), as well as broken escape sequences, are not removed. This prevents
// mismatches between the two functions and avoids misalignment when rendering
// the UI.
func stripTermSequence(s string) string {
var b strings.Builder
slen := len(s)
@@ -37,8 +40,9 @@ func stripTermSequence(s string) string {
return b.String()
}
// This function is used to extract and return a terminal sequence from a given
// string. If no supported sequence could be found, an empty string is returned.
// readTermSequence is used to extract and return a terminal sequence from a
// given string. If no supported sequence could be found, an empty string is
// returned.
//
// CSI (Control Sequence Introducer):
// - SGR (Select Graphic Rendition) `m`, used for text styling
@@ -49,7 +53,7 @@ func stripTermSequence(s string) string {
func readTermSequence(s string) string {
slen := len(s)
// must start with ESC
if slen < 2 || s[0] != byte(gEscapeCode) {
if slen < 2 || s[0] != gEscapeCode {
return ""
}
@@ -72,7 +76,7 @@ func readTermSequence(s string) string {
return s[:i+1]
}
// 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]
}
}
@@ -83,8 +87,18 @@ func readTermSequence(s string) string {
}
}
// This function takes an escape sequence option (e.g. `\033[1m`) and converts
// it to a `tcell.Style` object.
// optionToFmtstr takes an escape sequence option (e.g. `\033[1m`) and outputs
// 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.
func parseEscapeSequence(s string) tcell.Style {
s = strings.TrimPrefix(s, "\033[")
@@ -94,12 +108,12 @@ func parseEscapeSequence(s string) tcell.Style {
return applySGR(s, tcell.StyleDefault)
}
// This function takes an escape sequence (e.g. `\033[1m`) and applies it
// to the given `tcell.Style` object.
// applyTermSequence takes an escape sequence (e.g. `\033[1m`) and applies it
// to the given [tcell.Style] object.
// Accepts SGR and OSC sequences.
func applyTermSequence(s string, st tcell.Style) tcell.Style {
slen := len(s)
if slen < 2 || s[0] != byte(gEscapeCode) {
if slen < 2 || s[0] != gEscapeCode {
return st
}
switch s[1] {
@@ -112,7 +126,7 @@ func applyTermSequence(s string, st tcell.Style) tcell.Style {
// trim terminator (BEL or ESC\), then parse body
if s[slen-1] == 0x07 {
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 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 {
toks := strings.Split(s, ";")
@@ -216,7 +232,10 @@ loop:
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 {
genAutoID := func(url string) string {
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) {
tests := []struct {
s string
+147 -155
View File
@@ -22,8 +22,6 @@ import (
"golang.org/x/term"
)
const gEscapeCode = 27
var gKeyVal = map[tcell.Key]string{
tcell.KeyEnter: "<enter>",
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
}
// 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 {
ind := 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) {
if reg == nil {
return
}
st := tcell.StyleDefault
if reg.loading {
switch {
case reg.loading:
if previewLoading {
st = st.Reverse(true)
st := tcell.StyleDefault.Reverse(true)
win.print(screen, 2, 0, st, "loading...")
}
return
}
if !reg.sixel {
case reg.sixel:
sxs.printSixel(win, screen, reg)
default:
st := tcell.StyleDefault
for i, l := range reg.lines {
if i > win.h-1 {
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()
@@ -282,7 +281,7 @@ func infotimefmt(t time.Time) string {
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 custom string
var off int
@@ -292,25 +291,23 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
case "size":
if f.IsDir() && getDirCounts(d.path) {
switch {
case f.dirCount < -1:
info.WriteString(" !")
case f.dirCount < 0:
case f.dirCount == nil:
info.WriteString(" ?")
case f.dirCount < 10000:
fmt.Fprintf(&info, " %5d", f.dirCount)
case *f.dirCount < 10000:
fmt.Fprintf(&info, " %5d", *f.dirCount)
default:
info.WriteString(" 9999+")
}
continue
}
var sz string
if f.IsDir() && f.dirSize < 0 {
sz = "-"
} 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":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
case "atime":
@@ -349,12 +346,13 @@ type dirContext struct {
tags map[string]string
}
// dirRole describes what kind of directory pane is being drawn.
type dirRole byte
const (
Active dirRole = iota
Parent
Preview
Active dirRole = iota // Current directory pane.
Parent // Parent or ancestor directory pane.
Preview // Preview pane when it shows a directory listing.
)
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) {
lnwidth = 1
if gOpts.number && gOpts.relativenumber {
lnwidth++
}
for j := 10; j <= fileslen; j *= 10 {
lnwidth++
}
if gOpts.number && gOpts.relativenumber {
lnwidth = max(lnwidth, 2)
}
}
var userWidth int
var groupWidth int
var customWidth int
var userWidth, groupWidth, customWidth int
var fetchedCustom bool
// 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()
for i, f := range dir.files[beg:end] {
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:
ln = fmt.Sprintf("%*d", lnwidth, i-dir.pos)
case gOpts.number:
ln = fmt.Sprintf("%*d ", lnwidth-1, i+1+beg)
ln = fmt.Sprintf("%-*d", lnwidth, i+1+beg)
default:
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
}
}
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 := " "
if val, ok := context.tags[path]; ok && len(val) > 0 {
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 iconDef iconDef
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{' '})
}
// subtract space for tag and icon
maxFilenameWidth := maxWidth - 1 - runeSliceWidth(icon)
// subtract space for 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)
showInfo := infolen > 0 && 2*infolen < maxWidth
if showInfo {
@@ -505,7 +512,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if showInfo {
filename = append(filename, []rune(info)...)
off += lnwidth + 2 + runeSliceWidth(icon) + maxFilenameWidth
customOff += nameOff + runeSliceWidth(icon) + maxFilenameWidth
}
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
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{' '})
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
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 {
if tag == " " {
win.print(ui.screen, lnwidth+1, i, st, " ")
} else {
tagStr := fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag)
win.print(ui.screen, lnwidth+1, i, tcell.StyleDefault, tagStr)
if !gOpts.mergeindicators || fmtStr == "" {
if tag == " " {
win.print(ui.screen, tagOff, i, st, " ")
} else {
tagStr := fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag)
win.print(ui.screen, tagOff, i, tcell.StyleDefault, tagStr)
}
}
if len(icon) > 0 {
@@ -542,21 +553,21 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if iconDef.hasStyle {
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{' '})
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
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
for _, f := range dir.files[beg:end] {
@@ -566,7 +577,7 @@ func getUserWidth(dir *dir, beg int, end int) int {
return maxw
}
func getGroupWidth(dir *dir, beg int, end int) int {
func getGroupWidth(dir *dir, beg, end int) int {
maxw := 0
for _, f := range dir.files[beg:end] {
@@ -576,7 +587,7 @@ func getGroupWidth(dir *dir, beg int, end int) int {
return maxw
}
func getCustomWidth(dir *dir, beg int, end int) int {
func getCustomWidth(dir *dir, beg, end int) int {
maxw := 0
for _, f := range dir.files[beg:end] {
@@ -586,45 +597,23 @@ func getCustomWidth(dir *dir, beg int, end int) int {
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 {
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
wlen := len(widths)
wins := make([]*win, 0, wlen)
for i := range wlen {
if gOpts.drawbox {
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]
widths := getWidths(wtot, gOpts.ratios, gOpts.drawbox)
wins := make([]*win, 0, len(widths))
for _, w := range widths {
wins = append(wins, newWin(w, h, x, y))
x += w + 1
}
return wins
@@ -644,8 +633,6 @@ type ui struct {
msgWin *win
menuWin *win
msg string
regPrev *reg
dirPrev *dir
exprChan chan expr
keyChan chan string
tevChan chan tcell.Event
@@ -685,7 +672,7 @@ func newUI(screen tcell.Screen) *ui {
currentFile: "",
sxScreen: sixelScreen{},
}
ui.ruler, ui.rulerErr = parseRuler()
ui.ruler, ui.rulerErr = parseRuler(gOpts.rulerfile)
go ui.pollEvents()
@@ -723,15 +710,6 @@ func (ui *ui) renew() {
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) {
ui.msg = msg
}
@@ -750,9 +728,12 @@ func (ui *ui) echoerrf(format string, a ...any) {
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
// `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 {
loading bool
volatile bool
@@ -763,12 +744,8 @@ type reg struct {
}
func (ui *ui) loadFile(app *app, volatile bool) {
if !app.nav.init {
return
}
curr, err := app.nav.currFile()
if err != nil {
curr := app.nav.currFile()
if curr == nil {
return
}
@@ -786,9 +763,10 @@ func (ui *ui) loadFile(app *app, volatile bool) {
}
if curr.isPreviewable() {
ui.regPrev = app.nav.loadReg(curr.path, volatile)
app.nav.loadReg(curr.path, volatile)
} 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)
var fname string
curr, err := nav.currFile()
if err == nil {
if curr := nav.currFile(); curr != nil {
fname = filepath.Base(curr.path)
}
@@ -853,7 +830,7 @@ func (ui *ui) drawPromptLine(nav *nav) {
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
val = strings.ReplaceAll(val, "\033", "\033[7m\\033\033[0m")
@@ -871,8 +848,8 @@ func (ui *ui) drawStat(nav *nav) {
return
}
curr, err := nav.currFile()
if err != nil {
curr := nav.currFile()
if curr == nil {
return
}
@@ -883,7 +860,7 @@ func (ui *ui) drawStat(nav *nav) {
}
statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f")
replace := func(s string, val string) {
replace := func(s, val string) {
if val == "" {
val = "\x00"
}
@@ -1025,19 +1002,26 @@ func (ui *ui) drawRulerFile(nav *nav) {
}
var stat *statData
curr, err := nav.currFile()
if err == nil {
curr := nav.currFile()
if curr != nil {
if curr.err == nil {
stat = &statData{
Path: curr.path,
Name: curr.Name(),
Extension: curr.ext,
Size: uint64(curr.Size()),
DirSize: curr.dirSize,
DirCount: curr.dirCount,
Permissions: permString(curr.Mode()),
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),
User: userName(curr),
Group: groupName(curr),
Target: curr.linkTarget,
CustomInfo: curr.customInfo,
}
} else {
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)
}
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() {
st := parseEscapeSequence(gOpts.borderfmt)
@@ -1223,11 +1230,11 @@ func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
if gOpts.preview {
wins--
}
ind := len(nav.dirs) - wins + wind
ind := len(nav.dirPaths) - wins + wind
if ind < 0 {
return nil
}
return nav.dirs[ind]
return nav.getDir(nav.dirPaths[ind])
}
func (ui *ui) draw(nav *nav) {
@@ -1255,7 +1262,7 @@ func (ui *ui) draw(nav *nav) {
switch ui.cmdPrefix {
case "":
if gOpts.rulerfile {
if gOpts.rulerfmt == "" {
ui.drawRulerFile(nav)
} else {
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)
}
curr, err := nav.currFile()
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})
}
}
}
ui.drawPreview(nav, &context)
if gOpts.drawbox {
ui.drawBox()
@@ -1463,9 +1457,6 @@ func listMarks(marks map[string]string) string {
}
func listFilesInCurrDir(nav *nav) string {
if !nav.init {
return ""
}
dir := nav.currDir()
if dir.loading {
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
// preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k").
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
if gOpts.preview && wind == len(ui.wins)-1 {
curr, err := nav.currFile()
if err != nil {
curr := nav.currFile()
if curr == nil {
return nil
} else if !curr.IsDir() || gOpts.dirpreviews {
if tev.Buttons() != tcell.Button2 {
@@ -1701,7 +1692,8 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
}
return &callExpr{"open", nil, 1}
}
dir = ui.dirPrev
dir = nav.getDir(curr.path)
} else {
dir = ui.dirOfWin(nav, wind)
if dir == nil {
+56 -52
View File
@@ -10,29 +10,27 @@ import (
)
type watch struct {
watcher *fsnotify.Watcher
events <-chan fsnotify.Event
quit chan struct{}
loads map[string]bool
loadTimer *time.Timer
updates map[string]bool
updateTimer *time.Timer
dirChan chan<- *dir
fileChan chan<- *file
delChan chan<- string
watcher *fsnotify.Watcher
events <-chan fsnotify.Event
quit chan struct{}
pending map[watchUpdate]bool
timeout chan watchUpdate
dirChan chan<- *dir
fileChan chan<- *file
delChan chan<- string
}
func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) *watch {
return &watch{
quit: make(chan struct{}),
loads: make(map[string]bool),
loadTimer: time.NewTimer(0),
updates: make(map[string]bool),
updateTimer: time.NewTimer(0),
dirChan: dirChan,
fileChan: fileChan,
delChan: delChan,
watch := &watch{
quit: make(chan struct{}),
pending: make(map[watchUpdate]bool),
timeout: make(chan watchUpdate, 1024),
dirChan: dirChan,
fileChan: fileChan,
delChan: delChan,
}
return watch
}
func (watch *watch) start() {
@@ -83,8 +81,8 @@ func (watch *watch) loop() {
case ev := <-watch.events:
if ev.Has(fsnotify.Create) {
for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) {
watch.addLoad(path)
watch.addUpdate(path)
watch.addUpdate(watchUpdate{"dir", path})
watch.addUpdate(watchUpdate{"file", path})
}
}
@@ -92,8 +90,8 @@ func (watch *watch) loop() {
dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) {
watch.delChan <- filepath.Join(path, file)
watch.addLoad(path)
watch.addUpdate(path)
watch.addUpdate(watchUpdate{"dir", path})
watch.addUpdate(watchUpdate{"file", path})
}
}
@@ -108,47 +106,53 @@ func (watch *watch) loop() {
dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) {
watch.addUpdate(filepath.Join(path, file))
watch.addUpdate(watchUpdate{"file", filepath.Join(path, file)})
}
}
case <-watch.loadTimer.C:
for path := range watch.loads {
if _, err := os.Lstat(path); err != nil {
continue
}
dir := newDir(path)
dir.sort()
watch.dirChan <- dir
case update := <-watch.timeout:
if watch.pending[update] {
watch.processUpdate(update)
time.AfterFunc(100*time.Millisecond, func() { watch.timeout <- update })
watch.pending[update] = false
} else {
delete(watch.pending, update)
}
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:
return
}
}
}
func (watch *watch) addLoad(path string) {
if len(watch.loads) == 0 {
watch.loadTimer.Stop()
watch.loadTimer.Reset(10 * time.Millisecond)
}
watch.loads[path] = true
type watchUpdate struct {
kind string
path string
}
func (watch *watch) addUpdate(path string) {
if len(watch.updates) == 0 {
watch.updateTimer.Stop()
watch.updateTimer.Reset(10 * time.Millisecond)
func (watch *watch) addUpdate(update watchUpdate) {
// process an update immediately if is the first time, otherwise store it
// and process only after a timeout to reduce the number of actual loads
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