Compare commits

56 Commits
Author SHA1 Message Date
Joe Lim 3d205f05e3 Prepare for r35 release (#1967) 2025-04-25 11:23:45 +10:00
Joe Lim 1cb9e9d14a Add tty-write command (#1961)
This command offers a synchronized way to write to /dev/tty.
2025-04-13 11:14:00 +10:00
Joe Lim 0df0c0f5ff Simpler implementation of dirpreviews (#1958) 2025-04-10 15:34:13 +10:00
Joe Lim 3d5a418c6c Use Screen.Clear for clearing the screen (#1957) 2025-04-09 21:51:05 +10:00
Joe Lim 841cc3da06 Handle arrow keys when waiting for key press (#1956) 2025-04-09 19:03:19 +10:00
MahouShoujoMivutilde 1878faa942 Implement files query to export files in the current directory as (#1949)
presented in lf (including filter/sorting)

`lf -remote "query $id files"`

This version updates `files` list only before running shell commands.
2025-04-09 16:37:55 +10:00
dependabot[bot] 3fdd991040 Bump github.com/fsnotify/fsnotify from 1.8.0 to 1.9.0 (#1953)
Bumps [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify) from 1.8.0 to 1.9.0.
- [Release notes](https://github.com/fsnotify/fsnotify/releases)
- [Changelog](https://github.com/fsnotify/fsnotify/blob/main/CHANGELOG.md)
- [Commits](https://github.com/fsnotify/fsnotify/compare/v1.8.0...v1.9.0)

---
updated-dependencies:
- dependency-name: github.com/fsnotify/fsnotify
  dependency-version: 1.9.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-04-07 14:38:00 +10:00
dependabot[bot] 9cad75867d Bump golang.org/x/term from 0.30.0 to 0.31.0 (#1952)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.30.0 to 0.31.0.
- [Commits](https://github.com/golang/term/compare/v0.30.0...v0.31.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  dependency-version: 0.31.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-04-07 14:37:48 +10:00
dependabot[bot] 970b31852d Bump golang.org/x/text from 0.23.0 to 0.24.0 (#1951)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.23.0 to 0.24.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.23.0...v0.24.0)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-version: 0.24.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-04-07 14:32:19 +10:00
Joe Lim ffe4c97560 Change menu contents to be a string (#1954) 2025-04-07 14:23:25 +10:00
Joe Lim 6718a36334 Bump dependencies (#1941) 2025-03-30 16:37:32 +11:00
Joe Lim ad6fa3fa73 Fix crash if log file can't be opened (#1937) 2025-03-21 18:56:13 +11:00
Joe Lim 9b1f8386fa Add support for underline colors (#1933) 2025-03-15 13:01:17 +11:00
Joe Lim 26259f777f Add function for parsing SGR colors (#1932)
* Add function for parsing SGR colors

* Change error message

* Fix break out of loop

* Fix typo
2025-03-15 12:37:44 +11:00
Dusan Lesan 9dc4e6b431 Update screenshots (#1924)
cc #1919
2025-03-06 09:50:25 +11:00
Joe Lim 0e66d02746 Use clear for clearing maps (#1923) 2025-02-23 19:56:50 +11:00
Joe Lim 938e02e126 cleanup (#1922) 2025-02-23 17:14:19 +11:00
David Pedersen 2a3292560d Apply modernization fixes (#1921) 2025-02-23 17:05:20 +11:00
Joe Lim f9813744f7 Add dircounts to setlocal options (#1920)
* Remove plural from setlocal variable names

* Add `dircounts` for `setlocal`

* Update documentation

* Fix failing test
2025-02-19 10:43:15 +11:00
valoqandJoe Lim b087bf7d80 verify the Trash directory exists before moving files there (#1918)
* verify the Trash directory exists before moving files there

* Update etc/lfrc.example

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-02-19 10:38:33 +11:00
David Pedersen c42942d53e Remove redundant strconv in diacritics test (#1917) 2025-02-14 15:45:21 +11:00
Joe Lim 74b2954e6a Handle leading zeros in SGR escape sequences (#1912) 2025-02-10 17:13:34 +11:00
Penn Bauman 7797ad695f fix non-constant format string (#1910) 2025-02-10 12:04:49 +11:00
Joe Lim b3c652c4d4 Add support for underline styles (#1896) 2025-02-09 23:39:15 +11:00
dependabot[bot] 3b56a9fa64 Bump github.com/Xuanwo/go-locale from 1.1.2 to 1.1.3 (#1902)
Bumps [github.com/Xuanwo/go-locale](https://github.com/Xuanwo/go-locale) from 1.1.2 to 1.1.3.
- [Release notes](https://github.com/Xuanwo/go-locale/releases)
- [Changelog](https://github.com/Xuanwo/go-locale/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Xuanwo/go-locale/compare/v1.1.2...v1.1.3)

---
updated-dependencies:
- dependency-name: github.com/Xuanwo/go-locale
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-02-09 23:24:43 +11:00
dependabot[bot] 5b1ec5b6fc Bump golang.org/x/text from 0.21.0 to 0.22.0 (#1906)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.21.0 to 0.22.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.21.0...v0.22.0)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  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-02-09 23:17:03 +11:00
dependabot[bot] ec42237563 Bump golang.org/x/term from 0.28.0 to 0.29.0 (#1905)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.28.0 to 0.29.0.
- [Commits](https://github.com/golang/term/compare/v0.28.0...v0.29.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  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-02-09 23:09:23 +11:00
Joe Lim c25647d364 Prepare for r34 release (#1909) 2025-02-09 22:50:06 +11:00
Joe Lim 4f0a5d6211 Automatically unselect files after watch remove (#1901) 2025-02-03 10:45:53 +11:00
Joe Lim 7595e05957 Add workaround for equivalent paths for watch option (#1895)
* Add workaround for equivalent paths for watch option

* Add comment

* Simplify path watching
2025-01-30 09:53:50 +11:00
Joe Lim 2745c1ab22 Add link to ranger in README (#1891) 2025-01-15 21:57:30 +11:00
Joe Lim 2375b651ce Mark locale feature as experimental (#1892) 2025-01-15 21:48:17 +11:00
dependabot[bot] b34ca155ab Bump github.com/gdamore/tcell/v2 from 2.7.4 to 2.8.1 (#1888)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.7.4 to 2.8.1.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv2.md)
- [Commits](https://github.com/gdamore/tcell/compare/v2.7.4...v2.8.1)

---
updated-dependencies:
- dependency-name: github.com/gdamore/tcell/v2
  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-01-15 13:24:35 +11:00
dependabot[bot] df0b62af30 Bump golang.org/x/term from 0.27.0 to 0.28.0 (#1884)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.27.0 to 0.28.0.
- [Commits](https://github.com/golang/term/compare/v0.27.0...v0.28.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  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-01-15 13:16:06 +11:00
Joe Lim 2095efa661 Various fixes for updating dircounts with watch enabled (#1881)
* Fix file size bug when copying files

* Don't remove existing watches

* Bump fsnotify

* Ignore watching `/dev`
2025-01-15 13:06:00 +11:00
dependabot[bot] 8bfa3a6d34 Bump golang.org/x/term from 0.26.0 to 0.27.0 (#1868)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.26.0 to 0.27.0.
- [Commits](https://github.com/golang/term/compare/v0.26.0...v0.27.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  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>
2024-12-05 18:20:00 +11:00
dependabot[bot] 085717bc9f Bump golang.org/x/text from 0.20.0 to 0.21.0 (#1870)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.20.0 to 0.21.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.20.0...v0.21.0)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  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>
2024-12-05 18:13:57 +11:00
Joe Lim 68a29c9284 Prevent infinite loop when using on-quit (#1856) 2024-11-17 23:10:20 +11:00
Joe Lim f0dddccb04 Fix background color when rendering filenames (#1849) 2024-11-14 11:05:37 +11:00
valoq 23bef4dc0b Revert "Bump github.com/fsnotify/fsnotify from 1.7.0 to 1.8.0 (#1821)" (#1847)
This reverts commit 4079aead14.
2024-11-13 12:19:46 +11:00
zenyu 4fefcf7aac Create key event expr with non-zero count (#1846) 2024-11-11 10:35:32 +11:00
dependabot[bot] 0b5749f0ef Bump golang.org/x/text from 0.19.0 to 0.20.0 (#1842)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.19.0 to 0.20.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.19.0...v0.20.0)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  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>
2024-11-08 15:26:04 +11:00
dependabot[bot] dec026e2aa Bump golang.org/x/term from 0.25.0 to 0.26.0 (#1841)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.25.0 to 0.26.0.
- [Commits](https://github.com/golang/term/compare/v0.25.0...v0.26.0)

---
updated-dependencies:
- dependency-name: golang.org/x/term
  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>
2024-11-08 14:13:13 +11:00
Joe Lim ce3dbea2ae Enable autoquit by default (#1839) 2024-11-06 12:21:39 +11:00
Joe Lim 670343a23f Add on-init hook command (#1838) 2024-11-06 12:12:12 +11:00
David Pedersen 0b51987044 Use new slices/cmp standard lib (#1834) 2024-11-05 00:08:28 +11:00
dependabot[bot] d9a6ca5766 Bump golang.org/x/text from 0.18.0 to 0.19.0 (#1833)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.18.0 to 0.19.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.18.0...v0.19.0)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  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>
2024-11-04 18:02:56 +11:00
David Pedersen b5b7b84568 Bump Go to 1.23 (#1832) 2024-11-04 18:01:08 +11:00
David Pedersen fa2fa19ab0 Small optimizations for opts.go (#1831)
* Small optimizations for opts.go

* Add back all opts
2024-11-04 09:51:38 +11:00
David Pedersen 0f48f36b0f Small optimizations and cleanups (#1830) 2024-11-04 00:25:05 +11:00
David Pedersen f5a0e655a1 Small optimizations for os.go (#1829)
* Small optimizations for os.go

* Cleanup isHidden check further
2024-11-03 21:11:00 +11:00
David Pedersen 4408f37a9b Hardcode diacritics instead of generating during runtime (#1827)
* Hardcode diacritics instead of generating during runtime

* Remove redundant test
2024-11-03 18:21:33 +11:00
David Pedersen 1b1628c378 Small optimizations for ui.go (#1826) 2024-11-03 03:14:08 +11:00
Joe Lim dda8e88aaf Cleanup doc (#1823) 2024-11-02 00:28:54 +11:00
陆离 3f63bc980f Add option to sort base on certain locale. (#1818)
* Add support for localized sorting

* Switch go-locale module; Use collate option for natural sorting

* Doc and error message improvement

* Simplify predicated checking of localized sorting.

* Improve error handling of `set locale` command
2024-11-02 00:12:21 +11:00
dependabot[bot] 4079aead14 Bump github.com/fsnotify/fsnotify from 1.7.0 to 1.8.0 (#1821)
Bumps [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify) from 1.7.0 to 1.8.0.
- [Release notes](https://github.com/fsnotify/fsnotify/releases)
- [Changelog](https://github.com/fsnotify/fsnotify/blob/main/CHANGELOG.md)
- [Commits](https://github.com/fsnotify/fsnotify/compare/v1.7.0...v1.8.0)

---
updated-dependencies:
- dependency-name: github.com/fsnotify/fsnotify
  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>
2024-11-02 00:05:18 +11:00
31 changed files with 1024 additions and 744 deletions

No files matched your search

+4 -4
View File
@@ -21,7 +21,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.18"
go-version: "1.23"
- name: Build
run: go build -v ./...
@@ -31,7 +31,7 @@ jobs:
- uses: dominikh/staticcheck-action@v1.3.1
with:
version: "2022.1.3"
version: "2024.1.1"
install-go: false
cross-compile:
@@ -44,7 +44,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.18"
go-version: "1.23"
- name: Cross-compile on all supported platforms
run: gen/xbuild.sh
@@ -59,7 +59,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.18"
go-version: "1.23"
- name: Test `go fmt` creates no diffs
run: go fmt && git diff --exit-code
+1 -1
View File
@@ -15,7 +15,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.18"
go-version: "1.23"
- name: Build
run: gen/xbuild.sh
+3 -3
View File
@@ -9,11 +9,11 @@
[![Go Build](https://github.com/gokcehan/lf/actions/workflows/go.yml/badge.svg)](https://github.com/gokcehan/lf/actions/workflows/go.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf)
`lf` (as in "list files") is a terminal file manager written in Go with a heavy inspiration from ranger file manager.
`lf` (as in "list files") is a terminal file manager written in Go with a heavy inspiration from [`ranger`](https://github.com/ranger/ranger) file manager.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts.
![multicol-screenshot](http://i.imgur.com/DaTUenu.png)
![singlecol-screenshot](http://i.imgur.com/p95xzUj.png)
![icons-and-border](https://github.com/user-attachments/assets/d5623462-05ab-4921-aeb3-d377d4732f9e)
![image-preview](https://github.com/user-attachments/assets/9ff42a21-19dd-42fa-8407-5d055aa9d561)
## Features
+28 -25
View File
@@ -35,6 +35,7 @@ type app struct {
menuCompInd int
selectionOut []string
watch *watch
quitting bool
}
func newApp(ui *ui, nav *nav) *app {
@@ -66,6 +67,14 @@ func newApp(ui *ui, nav *nav) *app {
}
func (app *app) quit() {
// Using synchronous shell commands for `on-quit` can cause this to be
// called again, so a guard variable is introduced here to prevent an
// infinite loop.
if app.quitting {
return
}
app.quitting = true
onQuit(app)
if gOpts.history {
@@ -249,7 +258,6 @@ func (app *app) writeHistory() error {
// separate goroutines and sent here for update.
func (app *app) loop() {
go app.nav.previewLoop(app.ui)
go app.nav.dirPreviewLoop(app.ui)
var serverChan <-chan expr
if !gSingleMode {
@@ -327,7 +335,6 @@ func (app *app) loop() {
app.quit()
app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
log.Print("bye!")
@@ -418,7 +425,7 @@ func (app *app) loop() {
}
}
app.setWatchPaths()
app.watchDir(d)
app.ui.draw(app.nav)
case r := <-app.nav.regChan:
@@ -433,12 +440,7 @@ func (app *app) loop() {
app.ui.draw(app.nav)
case f := <-app.nav.fileChan:
dirs := app.nav.dirs
if app.ui.dirPrev != nil {
dirs = append(dirs, app.ui.dirPrev)
}
for _, dir := range dirs {
for _, dir := range app.nav.dirCache {
if dir.path != filepath.Dir(f.path) {
continue
}
@@ -463,6 +465,11 @@ func (app *app) loop() {
case path := <-app.nav.delChan:
delete(app.nav.dirCache, path)
delete(app.nav.regCache, path)
delete(app.nav.selections, path)
if len(app.nav.selections) == 0 {
app.nav.selectionInd = 0
}
case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev, app.nav)
if e == nil {
@@ -501,7 +508,6 @@ func (app *app) loop() {
func (app *app) runCmdSync(cmd *exec.Cmd, pause_after bool) {
app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err)
@@ -538,11 +544,12 @@ func (app *app) runShell(s string, args []string, prefix string) {
exportOpts()
gState.mutex.Lock()
gState.data["maps"] = listBinds(gOpts.keys).String()
gState.data["cmaps"] = listBinds(gOpts.cmdkeys).String()
gState.data["cmds"] = listCmds().String()
gState.data["jumps"] = listJumps(app.nav.jumpList, app.nav.jumpListInd).String()
gState.data["history"] = listHistory(app.cmdHistory).String()
gState.data["maps"] = listBinds(gOpts.keys)
gState.data["cmaps"] = listBinds(gOpts.cmdkeys)
gState.data["cmds"] = listCmds()
gState.data["jumps"] = listJumps(app.nav.jumpList, app.nav.jumpListInd)
gState.data["history"] = listHistory(app.cmdHistory)
gState.data["files"] = listFilesInCurrDir(app.nav)
gState.mutex.Unlock()
cmd := shellCommand(s, args)
@@ -629,21 +636,17 @@ func (app *app) runShell(s string, args []string, prefix string) {
}
}
func (app *app) setWatchPaths() {
if !gOpts.watch || len(app.nav.dirs) == 0 {
func (app *app) watchDir(dir *dir) {
if !gOpts.watch {
return
}
paths := make(map[string]bool)
for _, dir := range app.nav.dirs {
paths[dir.path] = true
}
app.watch.add(dir.path)
for _, file := range app.nav.currDir().allFiles {
// ensure dircounts are updated for child directories
for _, file := range dir.allFiles {
if file.IsDir() {
paths[file.path] = true
app.watch.add(file.path)
}
}
app.watch.set(paths)
}
+15 -14
View File
@@ -26,6 +26,19 @@ func init() {
}
func run() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
log.Fatalf("failed to open log file: %s", err)
}
defer f.Close()
log.SetOutput(f)
} else {
log.SetOutput(io.Discard)
}
log.Print("hi!")
var screen tcell.Screen
var err error
if screen, err = tcell.NewScreen(); err != nil {
@@ -37,19 +50,6 @@ func run() {
screen.EnableMouse()
}
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
panic(err)
}
defer f.Close()
log.SetOutput(f)
} else {
log.SetOutput(io.Discard)
}
log.Print("hi!")
ui := newUI(screen)
nav := newNav(ui.wins[0].h)
app := newApp(ui, nav)
@@ -117,7 +117,7 @@ func readExpr() <-chan expr {
ch := make(chan expr)
go func() {
duration := 1 * time.Second
duration := 100 * time.Millisecond
c, err := net.Dial(gSocketProt, gSocketPath)
for err != nil {
@@ -130,6 +130,7 @@ func readExpr() <-chan expr {
fmt.Fprintf(c, "conn %d\n", gClientID)
ch <- &callExpr{"sync", nil, 1}
ch <- &callExpr{"on-init", nil, 1}
s := bufio.NewScanner(c)
for s.Scan() {
+92 -55
View File
@@ -1,6 +1,7 @@
package main
import (
"fmt"
"log"
"os"
"path/filepath"
@@ -95,85 +96,121 @@ func parseEscapeSequence(s string) tcell.Style {
return applyAnsiCodes(s, tcell.StyleDefault)
}
func parseColor(toks []string) (tcell.Color, int, error) {
if len(toks) == 0 {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
}
if toks[0] == "5" && len(toks) >= 2 {
n, err := strconv.Atoi(toks[1])
if err != nil {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
}
return tcell.PaletteColor(n), 2, nil
}
if toks[0] == "2" && len(toks) >= 4 {
r, err := strconv.Atoi(toks[1])
if err != nil {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
}
g, err := strconv.Atoi(toks[2])
if err != nil {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
}
b, err := strconv.Atoi(toks[3])
if err != nil {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
}
return tcell.NewRGBColor(int32(r), int32(g), int32(b)), 4, nil
}
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
}
func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";")
var nums []int
for _, tok := range toks {
if tok == "" {
nums = append(nums, 0)
continue
}
n, err := strconv.Atoi(tok)
if err != nil {
log.Printf("converting escape code: %s", err)
continue
}
nums = append(nums, n)
}
// ECMA-48 details the standard
// TODO: should we support turning off attributes?
// Probably because this is used for previewers too
for i := 0; i < len(nums); i++ {
n := nums[i]
switch {
case n == 0:
tokslen := len(toks)
loop:
for i := 0; i < tokslen; i++ {
switch strings.TrimLeft(toks[i], "0") {
case "":
st = tcell.StyleDefault
case n == 1:
case "1":
st = st.Bold(true)
case n == 2:
case "2":
st = st.Dim(true)
case n == 3:
case "3":
st = st.Italic(true)
case n == 4:
case "4:0":
st = st.Underline(false)
case "4", "4:1":
st = st.Underline(true)
case n == 5 || n == 6:
case "4:2":
st = st.Underline(tcell.UnderlineStyleDouble)
case "4:3":
st = st.Underline(tcell.UnderlineStyleCurly)
case "4:4":
st = st.Underline(tcell.UnderlineStyleDotted)
case "4:5":
st = st.Underline(tcell.UnderlineStyleDashed)
case "5", "6":
st = st.Blink(true)
case n == 7:
case "7":
st = st.Reverse(true)
case n == 8:
case "8":
// TODO: tcell PR for proper conceal
_, bg, _ := st.Decompose()
st = st.Foreground(bg)
case n == 9:
case "9":
st = st.StrikeThrough(true)
case n >= 30 && n <= 37:
case "30", "31", "32", "33", "34", "35", "36", "37":
n, _ := strconv.Atoi(toks[i])
st = st.Foreground(tcell.PaletteColor(n - 30))
case n >= 90 && n <= 97:
case "90", "91", "92", "93", "94", "95", "96", "97":
n, _ := strconv.Atoi(toks[i])
st = st.Foreground(tcell.PaletteColor(n - 82))
case n == 38:
if i+3 <= len(nums) && nums[i+1] == 5 {
st = st.Foreground(tcell.PaletteColor(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
st = st.Foreground(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
int32(nums[i+4])))
i += 4
} else {
log.Printf("unknown ansi code or incorrect form: %d", n)
case "38":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 38: %s", err)
break loop
}
case n >= 40 && n <= 47:
st = st.Foreground(color)
i += offset
case "40", "41", "42", "43", "44", "45", "46", "47":
n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 40))
case n >= 100 && n <= 107:
case "100", "101", "102", "103", "104", "105", "106", "107":
n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 92))
case n == 48:
if i+3 <= len(nums) && nums[i+1] == 5 {
st = st.Background(tcell.PaletteColor(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
st = st.Background(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
int32(nums[i+4])))
i += 4
} else {
log.Printf("unknown ansi code or incorrect form: %d", n)
case "48":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 48: %s", err)
break loop
}
st = st.Background(color)
i += offset
case "58":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 58: %s", err)
break loop
}
st = st.Underline(color)
i += offset
default:
log.Printf("unknown ansi code: %d", n)
log.Printf("unknown ansi code: %s", toks[i])
}
}
+40
View File
@@ -6,6 +6,35 @@ import (
"github.com/gdamore/tcell/v2"
)
func TestParseColor(t *testing.T) {
tests := []struct {
toks []string
color tcell.Color
offset int
success bool
}{
{[]string{}, tcell.ColorDefault, 0, false},
{[]string{"foo"}, tcell.ColorDefault, 0, false},
{[]string{"5"}, tcell.ColorDefault, 0, false},
{[]string{"5", "foo"}, tcell.ColorDefault, 0, false},
{[]string{"5", "42"}, tcell.PaletteColor(42), 2, true},
{[]string{"2"}, tcell.ColorDefault, 0, false},
{[]string{"2", "foo"}, tcell.ColorDefault, 0, false},
{[]string{"2", "42", "foo"}, tcell.ColorDefault, 0, false},
{[]string{"2", "42", "43", "foo"}, tcell.ColorDefault, 0, false},
{[]string{"2", "42", "43", "44"}, tcell.NewRGBColor(42, 43, 44), 4, true},
}
for _, test := range tests {
color, offset, err := parseColor(test.toks)
success := err == nil
if color != test.color || offset != test.offset || success != test.success {
t.Errorf("at input %v expected (%v, %v, %v) but got (%v, %v, %v)",
test.toks, test.color, test.offset, test.success, color, offset, success)
}
}
}
func TestApplyAnsiCodes(t *testing.T) {
none := tcell.StyleDefault
@@ -35,6 +64,14 @@ func TestApplyAnsiCodes(t *testing.T) {
{"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"4:0", none, none},
{"4:0", none.Underline(true), none},
{"4:1", none, none.Underline(true)},
{"4:2", none, none.Underline(tcell.UnderlineStyleDouble)},
{"4:3", none, none.Underline(tcell.UnderlineStyleCurly)},
{"4:4", none, none.Underline(tcell.UnderlineStyleDotted)},
{"4:5", none, none.Underline(tcell.UnderlineStyleDashed)},
{"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
@@ -45,6 +82,9 @@ func TestApplyAnsiCodes(t *testing.T) {
{"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"01;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"01;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none.Foreground(tcell.ColorGray)},
+8 -6
View File
@@ -80,6 +80,7 @@ var (
"mark-remove",
"tag",
"tag-toggle",
"tty-write",
"cmd-escape",
"cmd-complete",
"cmd-menu-complete",
@@ -116,7 +117,7 @@ var (
func getOptWords(opts any) (optWords []string) {
t := reflect.TypeOf(opts)
for i := 0; i < t.NumField(); i++ {
for i := range t.NumField() {
field := t.Field(i)
switch field.Type.Kind() {
case reflect.Map:
@@ -134,9 +135,9 @@ func getOptWords(opts any) (optWords []string) {
func getLocalOptWords(localOpts any) (localOptWords []string) {
t := reflect.TypeOf(localOpts)
for i := 0; i < t.NumField(); i++ {
for i := range t.NumField() {
field := t.Field(i)
name := strings.TrimSuffix(field.Name, "s")
name := field.Name
if field.Type.Kind() != reflect.Map {
continue
}
@@ -215,9 +216,9 @@ func matchExec(s string) (matches []string, longest []rune) {
}
}
sort.Strings(words)
if len(words) > 0 {
sort.Strings(words)
uniq := words[:1]
for i := 1; i < len(words); i++ {
if words[i] != words[i-1] {
@@ -294,7 +295,8 @@ func matchFile(s string) (matches []string, longest []rune) {
}
func matchCmd(s string) (matches []string, longest []rune) {
words := gCmdWords
words := make([]string, 0, len(gCmdWords)+len(gOpts.cmds))
words = append(words, gCmdWords...)
for c := range gOpts.cmds {
words = append(words, c)
}
+4 -4
View File
@@ -79,10 +79,10 @@ func TestGetLocalOptWords(t *testing.T) {
localOpts any
exp []string
}{
{struct{ features map[string]bool }{}, []string{"feature", "feature!", "nofeature"}},
{struct{ features map[string]int }{}, []string{"feature"}},
{struct{ features map[string]string }{}, []string{"feature"}},
{struct{ features map[string][]string }{}, []string{"feature"}},
{struct{ feature map[string]bool }{}, []string{"feature", "feature!", "nofeature"}},
{struct{ feature map[string]int }{}, []string{"feature"}},
{struct{ feature map[string]string }{}, []string{"feature"}},
{struct{ feature map[string][]string }{}, []string{"feature"}},
}
for _, test := range tests {
+36 -42
View File
@@ -1,51 +1,45 @@
package main
import (
"strconv"
"unicode"
)
var normMap = map[rune]rune{
// lowercase (not only) european
'ě': 'e', 'ř': 'r', 'ů': 'u', 'ø': 'o', 'ĉ': 'c', 'ĝ': 'g', 'ĥ': 'h', 'ĵ': 'j', 'ŝ': 's',
'ŭ': 'u', 'è': 'e', 'ù': 'u', 'ÿ': 'y', 'ė': 'e', 'į': 'i', 'ų': 'u', 'ā': 'a', 'ē': 'e',
'ī': 'i', 'ū': 'u', 'ļ': 'l', 'ķ': 'k', 'ņ': 'n', 'ģ': 'g', 'ő': 'o', 'ű': 'u', 'ë': 'e',
'ï': 'i', 'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ś': 's', 'ź': 'z', 'ż': 'z',
'õ': 'o', 'ș': 's', 'ț': 't', 'č': 'c', 'ď': 'd', 'ĺ': 'l', 'ľ': 'l', 'ň': 'n', 'ŕ': 'r',
'š': 's', 'ť': 't', 'ý': 'y', 'ž': 'z', 'é': 'e', 'í': 'i', 'ñ': 'n', 'ó': 'o', 'ú': 'u',
'ü': 'u', 'å': 'a', 'ä': 'a', 'ö': 'o', 'ç': 'c', 'î': 'i', 'ş': 's', 'û': 'u', 'ğ': 'g',
'ă': 'a', 'â': 'a', 'đ': 'd', 'ê': 'e', 'ô': 'o', 'ơ': 'o', 'ư': 'u', 'á': 'a', 'à': 'a',
'ã': 'a', 'ả': 'a', 'ạ': 'a',
// uppercase (not only) european
'Ě': 'E', 'Ř': 'R', 'Ů': 'U', 'Ø': 'O', 'Ĉ': 'C', 'Ĝ': 'G', 'Ĥ': 'H', 'Ĵ': 'J', 'Ŝ': 'S',
'Ŭ': 'U', 'È': 'E', 'Ù': 'U', 'Ÿ': 'Y', 'Ė': 'E', 'Į': 'I', 'Ų': 'U', 'Ā': 'A', 'Ē': 'E',
'Ī': 'I', 'Ū': 'U', 'Ļ': 'L', 'Ķ': 'K', 'Ņ': 'N', 'Ģ': 'G', 'Ő': 'O', 'Ű': 'U', 'Ë': 'E',
'Ï': 'I', 'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z',
'Õ': 'O', 'Ș': 'S', 'Ț': 'T', 'Č': 'C', 'Ď': 'D', 'Ĺ': 'L', 'Ľ': 'L', 'Ň': 'N', 'Ŕ': 'R',
'Š': 'S', 'Ť': 'T', 'Ý': 'Y', 'Ž': 'Z', 'É': 'E', 'Í': 'I', 'Ñ': 'N', 'Ó': 'O', 'Ú': 'U',
'Ü': 'U', 'Å': 'A', 'Ä': 'A', 'Ö': 'O', 'Ç': 'C', 'Î': 'I', 'Ş': 'S', 'Û': 'U', 'Ğ': 'G',
'Ă': 'A', 'Â': 'A', 'Đ': 'D', 'Ê': 'E', 'Ô': 'O', 'Ơ': 'O', 'Ư': 'U', 'Á': 'A', 'À': 'A',
'Ã': 'A', 'Ả': 'A', 'Ạ': 'A',
var normMap map[rune]rune
func init() {
normMap = make(map[rune]rune)
// (not only) european
appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
)
// Vietnamese
appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
)
// lowercase Vietnamese
'ắ': 'a', 'ặ': 'a', 'ằ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ấ': 'a', 'ậ': 'a', 'ầ': 'a', 'ẩ': 'a',
'ẫ': 'a', 'ẹ': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ế': 'e', 'ệ': 'e', 'ề': 'e', 'ể': 'e', 'ễ': 'e',
'i': 'i', 'ị': 'i', 'ì': 'i', 'ỉ': 'i', 'ĩ': 'i', 'o': 'o', 'ọ': 'o', 'ò': 'o', 'ỏ': 'o',
'ố': 'o', 'ộ': 'o', 'ồ': 'o', 'ổ': 'o', 'ỗ': 'o', 'ớ': 'o', 'ợ': 'o', 'ờ': 'o', 'ở': 'o',
'ỡ': 'o', 'ụ': 'u', 'ủ': 'u', 'ũ': 'u', 'ứ': 'u', 'ự': 'u', 'ừ': 'u', 'ử': 'u', 'ữ': 'u',
'y': 'y', 'ỵ': 'y', 'ỳ': 'y', 'ỷ': 'y', 'ỹ': 'y',
// uppercase Vietnamese
'Ắ': 'A', 'Ặ': 'A', 'Ằ': 'A', 'Ẳ': 'A', 'Ẵ': 'A', 'Ấ': 'A', 'Ậ': 'A', 'Ầ': 'A', 'Ẩ': 'A',
'Ẫ': 'A', 'Ẹ': 'E', 'Ẻ': 'E', 'Ẽ': 'E', 'Ế': 'E', 'Ệ': 'E', 'Ề': 'E', 'Ể': 'E', 'Ễ': 'E',
'I': 'I', 'Ị': 'I', 'Ì': 'I', 'Ỉ': 'I', 'Ĩ': 'I', 'O': 'O', 'Ọ': 'O', 'Ò': 'O', 'Ỏ': 'O',
'Ố': 'O', 'Ộ': 'O', 'Ồ': 'O', 'Ổ': 'O', 'Ỗ': 'O', 'Ớ': 'O', 'Ợ': 'O', 'Ờ': 'O', 'Ở': 'O',
'Ỡ': 'O', 'Ụ': 'U', 'Ủ': 'U', 'Ũ': 'U', 'Ứ': 'U', 'Ự': 'U', 'Ừ': 'U', 'Ử': 'U', 'Ữ': 'U',
'Y': 'Y', 'Ỵ': 'Y', 'Ỳ': 'Y', 'Ỷ': 'Y', 'Ỹ': 'Y',
}
func appendTransliterate(base, norm string) {
normRunes := []rune(norm)
baseRunes := []rune(base)
lenNorm := len(normRunes)
lenBase := len(baseRunes)
if lenNorm != lenBase {
panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length
}
for i := 0; i < lenBase; i++ {
normMap[baseRunes[i]] = normRunes[i]
baseUpper := unicode.ToUpper(baseRunes[i])
normUpper := unicode.ToUpper(normRunes[i])
normMap[baseUpper] = normUpper
}
}
// Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string {
var normalizedRunes []rune
normalizedRunes := make([]rune, 0, len(baseString))
for _, baseRune := range baseString {
if normRune, ok := normMap[baseRune]; ok {
normalizedRunes = append(normalizedRunes, normRune)
+6 -7
View File
@@ -1,7 +1,6 @@
package main
import (
"strconv"
"testing"
)
@@ -13,7 +12,7 @@ func TestRemoveDiacritics(t *testing.T) {
expStr := "Prilis zlutoucky kun priserne upel dabelske ody"
checkRemoveDiacritics(testStr, expStr, t)
// other accents (non comlete, but all I founded)
// other accents (non complete, but all I found)
testStr = "áéíóúýčďěňřšťžůåøĉĝĥĵŝŭšžõäöüàâçéèêëîïôùûüÿžščćđáéíóúąęėįųūčšžāēīūčšžļķņģáéíóúöüőűäöüëïąćęłńóśźżáàãâçéêíóõôăâîșțáäčďéíĺľňóôŕšťúýžáéíñóúüåäöâçîşûğăâđêôơưáàãảạ"
expStr = "aeiouycdenrstzuaocghjsuszoaouaaceeeeiiouuuyzsccdaeiouaeeiuucszaeiucszlkngaeiouououaoueiacelnoszzaaaaceeioooaaistaacdeillnoorstuyzaeinouuaaoacisugaadeoouaaaaa"
checkRemoveDiacritics(testStr, expStr, t)
@@ -63,10 +62,10 @@ func runSearch(t *testing.T, ignorecase, smartcase, ignorediacritics, smartdiacr
gOpts.smartdia = smartdiacritics
matched, _ := searchMatch(base, pattern, false)
if matched != expected {
t.Errorf("False search for" +
" ignorecase = " + strconv.FormatBool(gOpts.ignorecase) + ", " +
" smartcase = " + strconv.FormatBool(gOpts.smartcase) + ", " +
" ignoredia = " + strconv.FormatBool(gOpts.ignoredia) + ", " +
" smartdia = " + strconv.FormatBool(gOpts.smartdia) + ", ")
t.Errorf("False search for ignorecase = %t, smartcase = %t, ignoredia = %t, smartdia = %t",
gOpts.ignorecase,
gOpts.smartcase,
gOpts.ignoredia,
gOpts.smartdia)
}
}
+25 -5
View File
@@ -102,6 +102,7 @@ The following commands are provided by lf:
mark-remove (modal) (default '"')
tag
tag-toggle (default 't')
tty-write
The following command line commands are provided by lf:
@@ -137,7 +138,7 @@ The following command line commands are provided by lf:
The following options can be used to customize the behavior of lf:
anchorfind bool (default true)
autoquit bool (default false)
autoquit bool (default true)
borderfmt string (default "\033[0m")
cleaner string (default '')
copyfmt string (default "\033[7;33m")
@@ -169,6 +170,7 @@ The following options can be used to customize the behavior of lf:
info []string (default '')
infotimefmtnew string (default 'Jan _2 15:04')
infotimefmtold string (default 'Jan _2 2006')
locale string (default '')
mouse bool (default false)
number bool (default false)
numberfmt string (default "\033[33m")
@@ -238,6 +240,7 @@ The following special shell commands are used to customize the behavior of lf wh
on-cd
on-focus-gained
on-focus-lost
on-init
on-select
on-redraw
on-quit
@@ -567,6 +570,12 @@ You can define a new tag-clearing command by combining `tag` with `tag-toggle` (
Tag a file with `*` or a single width character given in the argument if the file is untagged, otherwise remove the tag.
## tty-write
Write the given string to the tty.
This is useful for sending escape sequences to the terminal to control its behavior (e.g. OSC 0 to set the window title).
Using `tty-write` is preferred over directly writing to `/dev/tty` because the latter is not synchronized and can interfere with drawing the UI.
# COMMAND LINE COMMANDS
The prompt character specifies which of the several command-line modes you are in.
@@ -666,7 +675,7 @@ Character `:` is used as the separator for list options `[]int` and `[]string`.
When this option is enabled, the find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position.
## autoquit (bool) (default false)
## autoquit (bool) (default true)
Automatically quit the server when there are no clients left connected.
@@ -823,6 +832,12 @@ Format string of the file time shown in the info column when it matches this yea
Format string of the file time shown in the info column when it doesn't match this year.
## locale (string) (default ``)
An IETF BCP 47 language tag (e.g. `zh-CN`) for specifying the locale used when using sort type `natural` and `name`.
An empty string means disable locale ordering, and the special value `*` is used to indicate reading the locale setting from the system environment.
This feature is currently experimental.
## mouse (bool) (default false)
Send mouse events as input.
@@ -1136,6 +1151,10 @@ This shell command can be defined to be executed when the terminal gains focus.
This shell command can be defined to be executed when the terminal loses focus.
## on-init
This shell command can be defined to be executed after initializing and connecting to the server.
## on-select
This shell command can be defined to be executed after the selection changes.
@@ -1184,7 +1203,7 @@ Command `set` is used to set an option which can be a boolean, integer, or strin
set sortby "time" # string value with double quotes (backslash escapes)
Command `setlocal` is used to set a local option for a directory which can be a boolean or string.
Currently supported local options are `dirfirst`, `dironly`, `hidden`, `info`, `reverse`, and `sortby`.
Currently supported local options are `dircounts`, `dirfirst`, `dironly`, `hidden`, `info`, `reverse`, `sortby` and `locale`.
Adding a trailing path separator (i.e. `/` for Unix and `\` for Windows) sets the option for the given directory along with its subdirectories:
setlocal /foo/bar hidden # boolean enable
@@ -1458,6 +1477,7 @@ The following types of information are supported:
cmds list of commands created by the 'cmd' command
jumps contents of the jump list, showing previously visited locations
history list of previously executed commands on the command line
files list of files in the currently open directory as displayed by lf, empty if dir is still loading
This is useful for scripting actions based on the internal state of lf.
For example, to select a previous command using fzf and execute it:
@@ -1668,11 +1688,11 @@ You can define it just as you would define any other command:
'
}}
If you want to print escape sequences, you may redirect `printf` output to `/dev/tty`.
If you want to send escape sequences to the terminal, you can use the `tty-write` command to do so.
The following xterm-specific escape sequence sets the terminal title to the working directory:
cmd on-cd &{{
printf "\033]0; $PWD\007" > /dev/tty
lf -remote "send $id tty-write \"\033]0;$PWD\007\""
}}
This command runs whenever you change the directory but not on startup.
+35 -10
View File
@@ -92,6 +92,7 @@ The following commands are provided by lf:
mark-remove (modal) (default '"')
tag
tag-toggle (default 't')
tty-write
The following command line commands are provided by lf:
@@ -127,7 +128,7 @@ The following command line commands are provided by lf:
The following options can be used to customize the behavior of lf:
anchorfind bool (default true)
autoquit bool (default false)
autoquit bool (default true)
borderfmt string (default "\033[0m")
cleaner string (default '')
copyfmt string (default "\033[7;33m")
@@ -159,6 +160,7 @@ The following options can be used to customize the behavior of lf:
info []string (default '')
infotimefmtnew string (default 'Jan _2 15:04')
infotimefmtold string (default 'Jan _2 2006')
locale string (default '')
mouse bool (default false)
number bool (default false)
numberfmt string (default "\033[33m")
@@ -229,6 +231,7 @@ of lf when defined:
on-cd
on-focus-gained
on-focus-lost
on-init
on-select
on-redraw
on-quit
@@ -586,6 +589,14 @@ tag-toggle (default t)
Tag a file with * or a single width character given in the argument if
the file is untagged, otherwise remove the tag.
tty-write
Write the given string to the tty. This is useful for sending escape
sequences to the terminal to control its behavior (e.g. OSC 0 to set the
window title). Using tty-write is preferred over directly writing to
/dev/tty because the latter is not synchronized and can interfere with
drawing the UI.
COMMAND LINE COMMANDS
The prompt character specifies which of the several command-line modes
@@ -695,7 +706,7 @@ When this option is enabled, the find command starts matching patterns
from the beginning of file names, otherwise, it can match at an
arbitrary position.
autoquit (bool) (default false)
autoquit (bool) (default true)
Automatically quit the server when there are no clients left connected.
@@ -878,6 +889,14 @@ infotimefmtold (string) (default Jan _2 2006)
Format string of the file time shown in the info column when it doesn't
match this year.
locale (string) (default ``)
An IETF BCP 47 language tag (e.g. zh-CN) for specifying the locale used
when using sort type natural and name. An empty string means disable
locale ordering, and the special value * is used to indicate reading the
locale setting from the system environment. This feature is currently
experimental.
mouse (bool) (default false)
Send mouse events as input.
@@ -1252,6 +1271,11 @@ on-focus-lost
This shell command can be defined to be executed when the terminal loses
focus.
on-init
This shell command can be defined to be executed after initializing and
connecting to the server.
on-select
This shell command can be defined to be executed after the selection
@@ -1305,10 +1329,10 @@ string:
set sortby "time" # string value with double quotes (backslash escapes)
Command setlocal is used to set a local option for a directory which can
be a boolean or string. Currently supported local options are dirfirst,
dironly, hidden, info, reverse, and sortby. Adding a trailing path
separator (i.e. / for Unix and \ for Windows) sets the option for the
given directory along with its subdirectories:
be a boolean or string. Currently supported local options are dircounts,
dirfirst, dironly, hidden, info, reverse, sortby and locale. Adding a
trailing path separator (i.e. / for Unix and \ for Windows) sets the
option for the given directory along with its subdirectories:
setlocal /foo/bar hidden # boolean enable
setlocal /foo/bar hidden true # boolean enable
@@ -1619,6 +1643,7 @@ The following types of information are supported:
cmds list of commands created by the 'cmd' command
jumps contents of the jump list, showing previously visited locations
history list of previously executed commands on the command line
files list of files in the currently open directory as displayed by lf, empty if dir is still loading
This is useful for scripting actions based on the internal state of lf.
For example, to select a previous command using fzf and execute it:
@@ -1877,12 +1902,12 @@ would define any other command:
'
}}
If you want to print escape sequences, you may redirect printf output to
/dev/tty. The following xterm-specific escape sequence sets the terminal
title to the working directory:
If you want to send escape sequences to the terminal, you can use the
tty-write command to do so. The following xterm-specific escape sequence
sets the terminal title to the working directory:
cmd on-cd &{{
printf "\033]0; $PWD\007" > /dev/tty
lf -remote "send $id tty-write \"\033]0;$PWD\007\""
}}
This command runs whenever you change the directory but not on startup.
+1 -1
View File
@@ -60,7 +60,7 @@ map a :push %mkdir<space>
# move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options)
cmd trash %set -f; mv $fx ~/.trash
cmd trash %set -f; mv -t ~/.trash $fx
# define a custom 'delete' command
# cmd delete ${{
+87 -43
View File
@@ -7,6 +7,7 @@ import (
"log"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"time"
@@ -89,7 +90,7 @@ func (e *setExpr) eval(app *app, args []string) {
app.ui.renew()
if app.nav.height != app.ui.wins[0].h {
app.nav.height = app.ui.wins[0].h
app.nav.regCache = make(map[string]*reg)
clear(app.nav.regCache)
if gOpts.sixel {
app.ui.sxScreen.lastFile = ""
}
@@ -194,7 +195,9 @@ func (e *setExpr) eval(app *app, args []string) {
if err == nil {
if gOpts.watch {
app.watch.start()
app.setWatchPaths()
for _, dir := range app.nav.dirCache {
app.watchDir(dir)
}
} else {
app.watch.stop()
}
@@ -269,6 +272,17 @@ func (e *setExpr) eval(app *app, args []string) {
}
}
gOpts.info = toks
case "locale":
localeStr := e.val
if localeStr != localeStrDisable {
if _, err = getLocaleTag(localeStr); err != nil {
app.ui.echoerrf("locale: %s", err.Error())
return
}
}
gOpts.locale = localeStr
app.nav.sort()
app.ui.sort()
case "rulerfmt":
gOpts.rulerfmt = e.val
case "preserve":
@@ -315,7 +329,7 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.promptfmt = e.val
case "ratios":
toks := strings.Split(e.val, ":")
var rats []int
rats := make([]int, 0, len(toks))
for _, s := range toks {
n, err := strconv.Atoi(s)
if err != nil {
@@ -335,7 +349,7 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.ratios = rats
app.ui.wins = getWins(app.ui.screen)
if gOpts.sixel {
app.nav.regCache = make(map[string]*reg)
clear(app.nav.regCache)
app.ui.sxScreen.lastFile = ""
}
app.ui.loadFile(app, true)
@@ -448,14 +462,16 @@ func (e *setLocalExpr) eval(app *app, args []string) {
var err error
switch e.opt {
case "dircounts", "nodircounts", "dircounts!":
err = applyLocalBoolOpt(gLocalOpts.dircounts, gOpts.dircounts, e)
case "dirfirst", "nodirfirst", "dirfirst!":
err = applyLocalBoolOpt(gLocalOpts.dirfirsts, gOpts.dirfirst, e)
err = applyLocalBoolOpt(gLocalOpts.dirfirst, gOpts.dirfirst, e)
if err == nil {
app.nav.sort()
app.ui.sort()
}
case "dironly", "nodironly", "dironly!":
err = applyLocalBoolOpt(gLocalOpts.dironlys, gOpts.dironly, e)
err = applyLocalBoolOpt(gLocalOpts.dironly, gOpts.dironly, e)
if err == nil {
app.nav.sort()
app.nav.position()
@@ -463,7 +479,7 @@ func (e *setLocalExpr) eval(app *app, args []string) {
app.ui.loadFile(app, true)
}
case "hidden", "nohidden", "hidden!":
err = applyLocalBoolOpt(gLocalOpts.hiddens, gOpts.hidden, e)
err = applyLocalBoolOpt(gLocalOpts.hidden, gOpts.hidden, e)
if err == nil {
app.nav.sort()
app.nav.position()
@@ -471,14 +487,14 @@ func (e *setLocalExpr) eval(app *app, args []string) {
app.ui.loadFile(app, true)
}
case "reverse", "noreverse", "reverse!":
err = applyLocalBoolOpt(gLocalOpts.reverses, gOpts.reverse, e)
err = applyLocalBoolOpt(gLocalOpts.reverse, gOpts.reverse, e)
if err == nil {
app.nav.sort()
app.ui.sort()
}
case "info":
if e.val == "" {
gLocalOpts.infos[e.path] = nil
gLocalOpts.info[e.path] = nil
return
}
toks := strings.Split(e.val, ":")
@@ -490,14 +506,25 @@ func (e *setLocalExpr) eval(app *app, args []string) {
return
}
}
gLocalOpts.infos[e.path] = toks
gLocalOpts.info[e.path] = toks
case "sortby":
method := sortMethod(e.val)
if !isValidSortMethod(method) {
app.ui.echoerr(invalidSortErrorMessage)
return
}
gLocalOpts.sortbys[e.path] = method
gLocalOpts.sortby[e.path] = method
app.nav.sort()
app.ui.sort()
case "locale":
localeStr := e.val
if localeStr != localeStrDisable {
if _, err = getLocaleTag(localeStr); err != nil {
app.ui.echoerrf("locale: %s", err.Error())
return
}
}
gLocalOpts.locale[e.path] = localeStr
app.nav.sort()
app.ui.sort()
default:
@@ -559,7 +586,6 @@ func preChdir(app *app) {
func onChdir(app *app) {
app.nav.addJumpList()
app.setWatchPaths()
if cmd, ok := gOpts.cmds["on-cd"]; ok {
cmd.eval(app, nil)
}
@@ -577,6 +603,12 @@ func onFocusLost(app *app) {
}
}
func onInit(app *app) {
if cmd, ok := gOpts.cmds["on-init"]; ok {
cmd.eval(app, nil)
}
}
func onRedraw(app *app) {
if cmd, ok := gOpts.cmds["on-redraw"]; ok {
cmd.eval(app, nil)
@@ -659,11 +691,11 @@ func menuComplete(app *app, dir int) {
ind := len(app.ui.cmdTmp) - len([]rune(last))
app.ui.cmdAccLeft = append(app.ui.cmdTmp[:ind], []rune(comp)...)
}
app.ui.menuBuf = listMatches(app.ui.screen, app.menuComps, app.menuCompInd)
app.ui.menu = listMatches(app.ui.screen, app.menuComps, app.menuCompInd)
}
func update(app *app) {
app.ui.menuBuf = nil
app.ui.menu = ""
app.menuCompActive = false
switch {
@@ -754,7 +786,7 @@ func normal(app *app) {
app.cmdHistoryInd = 0
app.menuCompActive = false
app.ui.menuBuf = nil
app.ui.menu = ""
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
@@ -963,7 +995,7 @@ func insert(app *app, arg string) {
}
fallthrough
default:
app.ui.menuBuf = nil
app.ui.menu = ""
app.menuCompActive = false
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
}
@@ -1029,6 +1061,19 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav)
}
case "tty-write":
if len(e.args) != 1 {
app.ui.echoerr("tty-write: requires an argument")
return
}
tty, ok := app.ui.screen.Tty()
if !ok {
log.Printf("tty-write: failed to get tty")
return
}
tty.Write([]byte(e.args[0]))
case "scroll-down":
if !app.nav.init {
return
@@ -1043,7 +1088,7 @@ func (e *callExpr) eval(app *app, args []string) {
}
resetIncCmd(app)
preChdir(app)
for i := 0; i < e.count; i++ {
for range e.count {
if err := app.nav.updir(); err != nil {
app.ui.echoerrf("%s", err)
return
@@ -1092,7 +1137,7 @@ func (e *callExpr) eval(app *app, args []string) {
case "jump-prev":
resetIncCmd(app)
preChdir(app)
for i := 0; i < e.count; i++ {
for range e.count {
app.nav.cdJumpListPrev()
}
app.ui.loadFile(app, true)
@@ -1102,7 +1147,7 @@ func (e *callExpr) eval(app *app, args []string) {
case "jump-next":
resetIncCmd(app)
preChdir(app)
for i := 0; i < e.count; i++ {
for range e.count {
app.nav.cdJumpListNext()
}
app.ui.loadFile(app, true)
@@ -1261,7 +1306,7 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.sort()
case "clearmaps":
// leave `:` and cmaps bound so the user can still exit using `:quit`
gOpts.keys = make(map[string]expr)
clear(gOpts.keys)
gOpts.keys[":"] = &callExpr{"read", nil, 1}
case "copy":
if !app.nav.init {
@@ -1384,10 +1429,10 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.screen.Sync()
if app.nav.height != app.ui.wins[0].h {
app.nav.height = app.ui.wins[0].h
app.nav.regCache = make(map[string]*reg)
clear(app.nav.regCache)
}
if gOpts.sixel {
app.nav.regCache = make(map[string]*reg)
clear(app.nav.regCache)
app.ui.sxScreen.lastFile = ""
}
for _, dir := range app.nav.dirs {
@@ -1467,7 +1512,7 @@ func (e *callExpr) eval(app *app, args []string) {
}
dir := app.nav.currDir()
old := dir.ind
for i := 0; i < e.count; i++ {
for range e.count {
if app.nav.findBack {
app.nav.findPrev()
} else {
@@ -1484,7 +1529,7 @@ func (e *callExpr) eval(app *app, args []string) {
}
dir := app.nav.currDir()
old := dir.ind
for i := 0; i < e.count; i++ {
for range e.count {
if app.nav.findBack {
app.nav.findNext()
} else {
@@ -1527,7 +1572,7 @@ func (e *callExpr) eval(app *app, args []string) {
if !app.nav.init {
return
}
for i := 0; i < e.count; i++ {
for range e.count {
if app.nav.searchBack {
if moved, err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
@@ -1548,7 +1593,7 @@ func (e *callExpr) eval(app *app, args []string) {
if !app.nav.init {
return
}
for i := 0; i < e.count; i++ {
for range e.count {
if app.nav.searchBack {
if moved, err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
@@ -1603,14 +1648,14 @@ func (e *callExpr) eval(app *app, args []string) {
return
}
normal(app)
app.ui.menuBuf = listMarks(app.nav.marks)
app.ui.menu = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-load: "
case "mark-remove":
if app.ui.cmdPrefix == ">" {
return
}
normal(app)
app.ui.menuBuf = listMarks(app.nav.marks)
app.ui.menu = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-remove: "
case "rename":
if !app.nav.init {
@@ -1778,6 +1823,8 @@ func (e *callExpr) eval(app *app, args []string) {
onFocusGained(app)
case "on-focus-lost":
onFocusLost(app)
case "on-init":
onInit(app)
case "cmd-insert":
if len(e.args) == 0 {
return
@@ -1790,13 +1837,13 @@ func (e *callExpr) eval(app *app, args []string) {
normal(app)
case "cmd-complete":
matches := doComplete(app)
app.ui.menuBuf = listMatches(app.ui.screen, matches, -1)
app.ui.menu = listMatches(app.ui.screen, matches, -1)
case "cmd-menu-complete":
menuComplete(app, 1)
case "cmd-menu-complete-back":
menuComplete(app, -1)
case "cmd-menu-accept":
app.ui.menuBuf = nil
app.ui.menu = ""
app.menuCompActive = false
case "cmd-enter":
s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...))
@@ -1804,7 +1851,7 @@ func (e *callExpr) eval(app *app, args []string) {
return
}
app.ui.menuBuf = nil
app.ui.menu = ""
app.menuCompActive = false
app.ui.cmdAccLeft = nil
@@ -2089,8 +2136,7 @@ func (e *callExpr) eval(app *app, args []string) {
}
ind := locs[len(locs)-1][3]
old := app.ui.cmdAccRight
app.ui.cmdAccRight = append([]rune{}, []rune(string(app.ui.cmdAccLeft)[ind:])...)
app.ui.cmdAccRight = append(app.ui.cmdAccRight, old...)
app.ui.cmdAccRight = append([]rune(string(app.ui.cmdAccLeft)[ind:]), old...)
app.ui.cmdAccLeft = []rune(string(app.ui.cmdAccLeft)[:ind])
case "cmd-capitalize-word":
if len(app.ui.cmdAccRight) == 0 {
@@ -2183,15 +2229,13 @@ func (e *callExpr) eval(app *app, args []string) {
beg1, end1 := locs[len(locs)-2][0], locs[len(locs)-2][1]
beg2, end2 := locs[len(locs)-1][0], locs[len(locs)-1][1]
var acc []rune
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[:beg1])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[beg2:end2])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[end1:beg2])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[beg1:end1])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[end2:])...)
app.ui.cmdAccLeft = acc
app.ui.cmdAccLeft = slices.Concat(
[]rune(string(app.ui.cmdAccLeft)[:beg1]),
[]rune(string(app.ui.cmdAccLeft)[beg2:end2]),
[]rune(string(app.ui.cmdAccLeft)[end1:beg2]),
[]rune(string(app.ui.cmdAccLeft)[beg1:end1]),
[]rune(string(app.ui.cmdAccLeft)[end2:]),
)
update(app)
default:
cmd, ok := gOpts.cmds[e.name]
@@ -2223,7 +2267,7 @@ func (e *execExpr) eval(app *app, args []string) {
}
func (e *listExpr) eval(app *app, args []string) {
for i := 0; i < e.count; i++ {
for range e.count {
for _, expr := range e.exprs {
expr.eval(app, nil)
}
+9 -8
View File
@@ -1,19 +1,20 @@
module github.com/gokcehan/lf
go 1.18
go 1.23.0
require (
github.com/Xuanwo/go-locale v1.1.3
github.com/djherbis/times v1.6.0
github.com/fsnotify/fsnotify v1.7.0
github.com/gdamore/tcell/v2 v2.7.4
github.com/fsnotify/fsnotify v1.9.0
github.com/gdamore/tcell/v2 v2.8.1
github.com/mattn/go-runewidth v0.0.16
golang.org/x/sys v0.26.0
golang.org/x/term v0.25.0
golang.org/x/sys v0.32.0
golang.org/x/term v0.31.0
golang.org/x/text v0.24.0
)
require (
github.com/gdamore/encoding v1.0.0 // indirect
github.com/gdamore/encoding v1.0.1 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
golang.org/x/text v0.14.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
)
+46 -13
View File
@@ -1,31 +1,48 @@
github.com/Xuanwo/go-locale v1.1.3 h1:EWZZJJt5rqPHHbqPRH1zFCn5D7xHjjebODctA4aUO3A=
github.com/Xuanwo/go-locale v1.1.3/go.mod h1:REn+F/c+AtGSWYACBSYZgl23AP+0lfQC+SEFPN+hj30=
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/tcell/v2 v2.7.4 h1:sg6/UnTM9jGpZU+oFYAsDahfchWAFW8Xx2yFinNSAYU=
github.com/gdamore/tcell/v2 v2.7.4/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw=
github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo=
github.com/gdamore/tcell/v2 v2.8.1 h1:KPNxyqclpWpWQlPLx6Xui1pMk8S+7+R37h3g07997NU=
github.com/gdamore/tcell/v2 v2.8.1/go.mod h1:bj8ori1BG3OYMjmb3IklZVWfZUJ1UBQt9JXrOCOhGWw=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -33,23 +50,39 @@ 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.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
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.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.25.0 h1:WtHI/ltw4NvSUig5KARz9h521QvRC8RmF/cuYqifU24=
golang.org/x/term v0.25.0/go.mod h1:RPyXicDX+6vLxogjjRxjgD2TKtmAO6NZBsBRfrOLu7M=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
golang.org/x/term v0.31.0 h1:erwDkOK1Msy6offm1mOgvspSkslFnIGsFnxOKoufg3o=
golang.org/x/term v0.31.0/go.mod h1:R4BeIy7D95HzImkxGkTW1UQTtP54tio2RyHz7PwK0aw=
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=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+1 -3
View File
@@ -105,9 +105,7 @@ func (im *iconMap) parseEnv(env string) {
}
func (im *iconMap) parseArray(arr []string) {
key := arr[0]
key = replaceTilde(key)
key := replaceTilde(arr[0])
if filepath.IsAbs(key) {
key = filepath.Clean(key)
+35 -9
View File
@@ -1,6 +1,6 @@
.\" Automatically generated by Pandoc 2.11.4
.\"
.TH "LF" "1" "2024-11-01" "" "DOCUMENTATION"
.TH "LF" "1" "2025-04-25" "" "DOCUMENTATION"
.hy
.SH NAME
.PP
@@ -102,6 +102,7 @@ mark-load (modal) (default \[dq]\[aq]\[dq])
mark-remove (modal) (default \[aq]\[dq]\[aq])
tag
tag-toggle (default \[aq]t\[aq])
tty-write
\f[R]
.fi
.PP
@@ -145,7 +146,7 @@ The following options can be used to customize the behavior of lf:
.nf
\f[C]
anchorfind bool (default true)
autoquit bool (default false)
autoquit bool (default true)
borderfmt string (default \[dq]\[rs]033[0m\[dq])
cleaner string (default \[aq]\[aq])
copyfmt string (default \[dq]\[rs]033[7;33m\[dq])
@@ -177,6 +178,7 @@ incsearch bool (default false)
info []string (default \[aq]\[aq])
infotimefmtnew string (default \[aq]Jan _2 15:04\[aq])
infotimefmtold string (default \[aq]Jan _2 2006\[aq])
locale string (default \[aq]\[aq])
mouse bool (default false)
number bool (default false)
numberfmt string (default \[dq]\[rs]033[33m\[dq])
@@ -255,6 +257,7 @@ pre-cd
on-cd
on-focus-gained
on-focus-lost
on-init
on-select
on-redraw
on-quit
@@ -625,6 +628,15 @@ with \f[C]tag-toggle\f[R] (i.e.
.PP
Tag a file with \f[C]*\f[R] or a single width character given in the
argument if the file is untagged, otherwise remove the tag.
.SS tty-write
.PP
Write the given string to the tty.
This is useful for sending escape sequences to the terminal to control
its behavior (e.g.
OSC 0 to set the window title).
Using \f[C]tty-write\f[R] is preferred over directly writing to
\f[C]/dev/tty\f[R] because the latter is not synchronized and can
interfere with drawing the UI.
.SH COMMAND LINE COMMANDS
.PP
The prompt character specifies which of the several command-line modes
@@ -717,7 +729,7 @@ Character \f[C]:\f[R] is used as the separator for list options
When this option is enabled, the find command starts matching patterns
from the beginning of file names, otherwise, it can match at an
arbitrary position.
.SS autoquit (bool) (default false)
.SS autoquit (bool) (default true)
.PP
Automatically quit the server when there are no clients left connected.
.SS borderfmt (string) (default \f[C]\[rs]033[0m\f[R])
@@ -895,6 +907,15 @@ this year.
.PP
Format string of the file time shown in the info column when it
doesn\[aq]t match this year.
.SS locale (string) (default \[ga]\[ga])
.PP
An IETF BCP 47 language tag (e.g.
\f[C]zh-CN\f[R]) for specifying the locale used when using sort type
\f[C]natural\f[R] and \f[C]name\f[R].
An empty string means disable locale ordering, and the special value
\f[C]*\f[R] is used to indicate reading the locale setting from the
system environment.
This feature is currently experimental.
.SS mouse (bool) (default false)
.PP
Send mouse events as input.
@@ -1252,6 +1273,10 @@ focus.
.PP
This shell command can be defined to be executed when the terminal loses
focus.
.SS on-init
.PP
This shell command can be defined to be executed after initializing and
connecting to the server.
.SS on-select
.PP
This shell command can be defined to be executed after the selection
@@ -1314,9 +1339,9 @@ set sortby \[dq]time\[dq] # string value with double quotes (backslash escapes)
.PP
Command \f[C]setlocal\f[R] is used to set a local option for a directory
which can be a boolean or string.
Currently supported local options are \f[C]dirfirst\f[R],
\f[C]dironly\f[R], \f[C]hidden\f[R], \f[C]info\f[R], \f[C]reverse\f[R],
and \f[C]sortby\f[R].
Currently supported local options are \f[C]dircounts\f[R],
\f[C]dirfirst\f[R], \f[C]dironly\f[R], \f[C]hidden\f[R], \f[C]info\f[R],
\f[C]reverse\f[R], \f[C]sortby\f[R] and \f[C]locale\f[R].
Adding a trailing path separator (i.e.
\f[C]/\f[R] for Unix and \f[C]\[rs]\f[R] for Windows) sets the option
for the given directory along with its subdirectories:
@@ -1792,6 +1817,7 @@ cmaps list of mappings created by the \[aq]cmap\[aq] command
cmds list of commands created by the \[aq]cmd\[aq] command
jumps contents of the jump list, showing previously visited locations
history list of previously executed commands on the command line
files list of files in the currently open directory as displayed by lf, empty if dir is still loading
\f[R]
.fi
.PP
@@ -2138,15 +2164,15 @@ cmd on-cd &{{
\f[R]
.fi
.PP
If you want to print escape sequences, you may redirect \f[C]printf\f[R]
output to \f[C]/dev/tty\f[R].
If you want to send escape sequences to the terminal, you can use the
\f[C]tty-write\f[R] command to do so.
The following xterm-specific escape sequence sets the terminal title to
the working directory:
.IP
.nf
\f[C]
cmd on-cd &{{
printf \[dq]\[rs]033]0; $PWD\[rs]007\[dq] > /dev/tty
lf -remote \[dq]send $id tty-write \[rs]\[dq]\[rs]033]0;$PWD\[rs]007\[rs]\[dq]\[dq]
}}
\f[R]
.fi
+2 -2
View File
@@ -107,7 +107,7 @@ func fieldToString(field reflect.Value) string {
case reflect.Bool:
value = strconv.FormatBool(field.Bool())
case reflect.Slice:
for i := 0; i < field.Len(); i++ {
for i := range field.Len() {
element := field.Index(i)
if i == 0 {
@@ -128,7 +128,7 @@ func getOptsMap() map[string]string {
v := reflect.ValueOf(gOpts)
t := v.Type()
for i := 0; i < v.NumField(); i++ {
for i := range v.NumField() {
// Get field name and prefix it with lf_
name := "lf_" + t.Field(i).Name
+53 -22
View File
@@ -11,14 +11,22 @@ import (
"strings"
"unicode"
"github.com/Xuanwo/go-locale"
"github.com/mattn/go-runewidth"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
const (
localeStrDisable = "" // disable locale ordering for this locale value
localeStrSys = "*" // replace this locale value with locale value read from environment
)
func isRoot(name string) bool { return filepath.Dir(name) == name }
func replaceTilde(s string) string {
if strings.HasPrefix(s, "~") {
s = strings.Replace(s, "~", gUser.HomeDir, 1)
return gUser.HomeDir + s[1:]
}
return s
}
@@ -68,7 +76,7 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
}
// This function is used to escape whitespaces and special characters with
// backlashes in a given string.
// backslashes in a given string.
func escape(s string) string {
buf := make([]rune, 0, len(s))
for _, r := range s {
@@ -80,7 +88,7 @@ func escape(s string) string {
return string(buf)
}
// This function is used to remove backlashes that are used to escape
// This function is used to remove backslashes that are used to escape
// whitespaces and special characters in a given string.
func unescape(s string) string {
esc := false
@@ -131,8 +139,7 @@ func tokenize(s string) []string {
buf = nil
}
}
toks = append(toks, string(buf))
return toks
return append(toks, string(buf))
}
// This function splits the first word of a string delimited by whitespace from
@@ -163,7 +170,7 @@ func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) {
line := s.Text()
squote, dquote := false, false
for i := 0; i < len(line); i++ {
for i := range len(line) {
if line[i] == '\'' && !dquote {
squote = !squote
} else if line[i] == '"' && !squote {
@@ -190,15 +197,16 @@ func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) {
}
return !squote && !dquote && unicode.IsSpace(r)
})
arrlen := len(arr)
if len(arr) < min_cols || len(arr) > max_cols {
if arrlen < min_cols || arrlen > max_cols {
if min_cols == max_cols {
return nil, fmt.Errorf("expected %d columns but found: %s", min_cols, s.Text())
}
return nil, fmt.Errorf("expected %d~%d columns but found: %s", min_cols, max_cols, s.Text())
}
for i := 0; i < len(arr); i++ {
for i := range arrlen {
squote, dquote = false, false
buf := make([]rune, 0, len(arr[i]))
for _, r := range arr[i] {
@@ -249,7 +257,8 @@ func humanize(size int64) string {
for _, s := range suffix {
if curr < 10 {
return fmt.Sprintf("%.1f%s", curr-0.0499, s)
} else if curr < 1000 {
}
if curr < 1000 {
return fmt.Sprintf("%d%s", int(curr), s)
}
curr /= 1000
@@ -264,22 +273,24 @@ func humanize(size int64) string {
// than 'foo10bar'.
func naturalLess(s1, s2 string) bool {
lo1, lo2, hi1, hi2 := 0, 0, 0, 0
s1len := len(s1)
s2len := len(s2)
for {
if hi1 >= len(s1) {
return hi2 != len(s2)
if hi1 >= s1len {
return hi2 != s2len
}
if hi2 >= len(s2) {
if hi2 >= s2len {
return false
}
isDigit1 := isDigit(s1[hi1])
isDigit2 := isDigit(s2[hi2])
for lo1 = hi1; hi1 < len(s1) && isDigit(s1[hi1]) == isDigit1; hi1++ {
for lo1 = hi1; hi1 < s1len && isDigit(s1[hi1]) == isDigit1; hi1++ {
}
for lo2 = hi2; hi2 < len(s2) && isDigit(s2[hi2]) == isDigit2; hi2++ {
for lo2 = hi2; hi2 < s2len && isDigit(s2[hi2]) == isDigit2; hi2++ {
}
if s1[lo1:hi1] == s2[lo2:hi2] {
@@ -324,18 +335,38 @@ var (
reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
)
func min(a, b int) int {
if a < b {
return a
// This function parses given locale string into language tag value. Passing empty
// string as locale means reading locale value from environment.
func getLocaleTag(localeStr string) (language.Tag, error) {
if localeStr == localeStrSys {
// read environment locale
return locale.Detect()
}
return b
localeTag, err := language.Parse(localeStr)
if err != nil {
return localeTag, fmt.Errorf("invalid locale %q: %s", localeStr, err)
}
return localeTag, nil
}
func max(a, b int) int {
if a > b {
return a
// This function creates new collator for given locale. Passing empty string as
// as locale means reading locale value from environment.
//
// *Note*: this function returns error when given `localeStr` has value `localeStrDisable`
// or is an invalid locale tag.
func makeCollator(localeStr string, opts ...collate.Option) (*collate.Collator, error) {
if localeStr == localeStrDisable {
return nil, fmt.Errorf("locale is disabled")
}
return b
localeTag, err := getLocaleTag(localeStr)
if err != nil {
return nil, err
}
return collate.New(localeTag, opts...), nil
}
// We don't need no generic code
+51
View File
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"time"
"golang.org/x/text/collate"
)
func TestIsRoot(t *testing.T) {
@@ -335,3 +337,52 @@ func TestGetFileExtension(t *testing.T) {
})
}
}
func TestLocaleNaturalLess(t *testing.T) {
tests := []struct {
s1 string
s2 string
exp bool
}{
// preserving behavior of `naturalLess`
{"foo", "bar", false},
{"bar", "baz", true},
{"foo", "123", false},
{"foo1", "foobar", true},
{"foo1", "foo10", true},
{"foo2", "foo10", true},
{"foo1", "foo10bar", true},
{"foo2", "foo10bar", true},
{"foo1bar", "foo10bar", true},
{"foo2bar", "foo10bar", true},
{"foo1bar", "foo10", true},
{"foo2bar", "foo10", true},
// locale sort
{"你好", "他好", true}, // \u4F60\u597D, \u4ED6\u597D
{"到这", "到那", false}, // \u5230\u8FD9, \u5230\u90A3
{"你说", "什么", true}, // \u4f60\u8bf4, \u4ec0\u4e48
{"你好", "World", false}, // \u4F60\u597D, \u57\u6f\u72\u6c\u64
{"甲1", "甲乙", true},
{"甲1", "甲10", true},
{"甲2", "甲10", true},
{"甲1", "甲10乙", true},
{"甲2", "甲10乙", true},
{"甲1乙", "甲10乙", true},
{"甲2乙", "甲10乙", true},
{"甲1乙", "甲10", true},
{"甲2乙", "甲10", true},
}
localeStr := "zh-CN"
collator, err := makeCollator(localeStr, collate.Numeric)
if err != nil {
t.Fatalf("failed to create collator for %q: %s", localeStr, err)
}
for _, test := range tests {
if got := collator.CompareString(test.s1, test.s2) < 0; got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got)
}
}
}
+61 -121
View File
@@ -10,12 +10,14 @@ import (
"os/exec"
"path/filepath"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/djherbis/times"
"golang.org/x/text/collate"
)
type linkState byte
@@ -87,7 +89,7 @@ func newFile(path string) *file {
}
dirCount := -1
if lstat.IsDir() && gOpts.dircounts {
if lstat.IsDir() && getDirCounts(filepath.Dir(path)) {
d, err := os.Open(path)
if err != nil {
dirCount = -2
@@ -171,8 +173,8 @@ type dir struct {
filter []string // last filter for this directory
ignorecase bool // ignorecase value from last sort
ignoredia bool // ignoredia value from last sort
locale string // locale value from last sort
noPerm bool // whether lf has no permission to open the directory
lines []string // lines of text to display if directory previews are enabled
}
func newDir(path string) *dir {
@@ -184,7 +186,6 @@ func newDir(path string) *dir {
}
return &dir{
loading: gOpts.dirpreviews, // Directory is loaded after previewer function exits.
loadTime: time,
path: path,
files: files,
@@ -211,6 +212,7 @@ func (dir *dir) sort() {
dir.dironly = getDirOnly(dir.path)
dir.hidden = getHidden(dir.path)
dir.reverse = getReverse(dir.path)
dir.locale = getLocale(dir.path)
dir.hiddenfiles = gOpts.hiddenfiles
dir.ignorecase = gOpts.ignorecase
dir.ignoredia = gOpts.ignoredia
@@ -221,23 +223,47 @@ func (dir *dir) sort() {
// of equivalent elements will be reversed
switch dir.sortby {
case naturalSort:
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
})
if collator, err := makeCollator(dir.locale, collate.Numeric); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
})
}
case nameSort:
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return s1 < s2
} else {
return s2 < s1
}
})
if collator, err := makeCollator(dir.locale); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return s1 < s2
} else {
return s2 < s1
}
})
}
case sizeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
@@ -422,7 +448,6 @@ type nav struct {
deleteCountChan chan int
deleteTotalChan chan int
previewChan chan string
dirPreviewChan chan *dir
dirChan chan *dir
regChan chan *reg
fileChan chan *file
@@ -452,8 +477,6 @@ type nav struct {
}
func (nav *nav) loadDirInternal(path string) *dir {
nav.startPreview()
d := &dir{
loading: true,
loadTime: time.Now(),
@@ -463,6 +486,7 @@ func (nav *nav) loadDirInternal(path string) *dir {
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
locale: getLocale(path),
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
@@ -471,9 +495,6 @@ func (nav *nav) loadDirInternal(path string) *dir {
d := newDir(path)
d.sort()
d.ind, d.pos = 0, 0
if gOpts.dirpreviews {
nav.dirPreviewChan <- d
}
nav.dirChan <- d
}()
return d
@@ -512,14 +533,10 @@ func (nav *nav) checkDir(dir *dir) {
return
}
nav.startPreview()
dir.loading = true
dir.loadTime = now
go func() {
nd := newDir(dir.path)
if gOpts.dirpreviews {
nav.dirPreviewChan <- nd
}
nav.dirChan <- nd
}()
case dir.sortby != getSortBy(dir.path) ||
@@ -527,6 +544,7 @@ func (nav *nav) checkDir(dir *dir) {
dir.dironly != getDirOnly(dir.path) ||
dir.hidden != getHidden(dir.path) ||
dir.reverse != getReverse(dir.path) ||
dir.locale != getLocale(dir.path) ||
!reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles) ||
dir.ignorecase != gOpts.ignorecase ||
dir.ignoredia != gOpts.ignoredia:
@@ -569,7 +587,6 @@ func newNav(height int) *nav {
deleteCountChan: make(chan int, 1024),
deleteTotalChan: make(chan int, 1024),
previewChan: make(chan string, 1024),
dirPreviewChan: make(chan *dir, 1024),
dirChan: make(chan *dir),
regChan: make(chan *reg),
fileChan: make(chan *file),
@@ -636,8 +653,8 @@ func (nav *nav) renew() {
}
func (nav *nav) reload() error {
nav.dirCache = make(map[string]*dir)
nav.regCache = make(map[string]*reg)
clear(nav.dirCache)
clear(nav.regCache)
curr, err := nav.currFile()
nav.getDirs(nav.currDir().path)
@@ -688,23 +705,6 @@ func (nav *nav) exportFiles() {
}
}
func (nav *nav) dirPreviewLoop(ui *ui) {
var prevPath string
for dir := range nav.dirPreviewChan {
if dir == nil && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
cmd := exec.Command(gOpts.cleaner, prevPath)
if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err)
}
nav.volatilePreview = false
} else if dir != nil {
win := ui.wins[len(ui.wins)-1]
nav.previewDir(dir, win)
prevPath = dir.path
}
}
}
func (nav *nav) previewLoop(ui *ui) {
var prev string
for path := range nav.previewChan {
@@ -753,64 +753,6 @@ func matchPattern(pattern, name, path string) bool {
return matched
}
func (nav *nav) previewDir(dir *dir, win *win) {
defer func() {
dir.loading = false
nav.dirChan <- dir
}()
var reader io.Reader
if len(gOpts.previewer) != 0 {
cmd := exec.Command(gOpts.previewer, dir.path,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y))
out, err := cmd.StdoutPipe()
if err != nil {
log.Printf("previewing dir: %s", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("previewing dir: %s", err)
out.Close()
return
}
defer func() {
if err := cmd.Wait(); err != nil {
if e, ok := err.(*exec.ExitError); ok {
if e.ExitCode() != 0 {
nav.volatilePreview = true
}
} else {
log.Printf("loading dir: %s", err)
}
}
}()
defer out.Close()
reader = out
buf := bufio.NewScanner(reader)
for i := 0; i < win.h && buf.Scan(); i++ {
for _, r := range buf.Text() {
if r == 0 {
dir.lines = []string{"\033[7mbinary\033[0m"}
return
}
}
dir.lines = append(dir.lines, buf.Text())
}
if buf.Err() != nil {
log.Printf("loading dir: %s", buf.Err())
}
}
}
func (nav *nav) preview(path string, win *win) {
reg := &reg{loadTime: time.Now(), path: path}
defer func() { nav.regChan <- reg }()
@@ -886,11 +828,9 @@ func (nav *nav) preview(path string, win *win) {
break
}
for _, byte := range bytes {
if byte == 0 {
reg.lines = []string{"\033[7mbinary\033[0m"}
return
}
if slices.Contains(bytes, 0) {
reg.lines = []string{"\033[7mbinary\033[0m"}
return
}
line = append(line, bytes...)
@@ -1279,7 +1219,7 @@ func (nav *nav) invertBelow() {
}
func (nav *nav) unselect() {
nav.selections = make(map[string]int)
clear(nav.selections)
nav.selectionInd = 0
}
@@ -1293,7 +1233,7 @@ func (nav *nav) save(cp bool) error {
return err
}
nav.saves = make(map[string]bool)
clear(nav.saves)
for _, f := range list {
nav.saves[f] = cp
}
@@ -1571,7 +1511,7 @@ func (nav *nav) sync() error {
return err
}
nav.saves = make(map[string]bool)
clear(nav.saves)
for _, f := range list {
nav.saves[f] = cp
}
@@ -1645,7 +1585,7 @@ func (nav *nav) globSel(pattern string, invert bool) error {
dir := nav.currDir()
anyMatched := false
for i := 0; i < len(dir.files); i++ {
for i := range dir.files {
matched, err := filepath.Match(pattern, dir.files[i].Name())
if err != nil {
return fmt.Errorf("glob-select: %s", err)
@@ -1691,7 +1631,7 @@ func (nav *nav) findSingle() int {
count := 0
index := 0
dir := nav.currDir()
for i := 0; i < len(dir.files); i++ {
for i := range dir.files {
if findMatch(dir.files[i].Name(), nav.find) {
count++
if count > 1 {
@@ -1718,7 +1658,7 @@ func (nav *nav) findNext() (bool, bool) {
}
}
if gOpts.wrapscan {
for i := 0; i < dir.ind; i++ {
for i := range dir.ind {
if findMatch(dir.files[i].Name(), nav.find) {
return nav.up(dir.ind - i), true
}
@@ -1775,7 +1715,7 @@ func (nav *nav) searchNext() (bool, error) {
}
}
if gOpts.wrapscan {
for i := 0; i < dir.ind; i++ {
for i := range dir.ind {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
return false, err
} else if matched {
@@ -1832,7 +1772,7 @@ func (nav *nav) removeMark(mark string) error {
}
func (nav *nav) readMarks() error {
nav.marks = make(map[string]string)
clear(nav.marks)
f, err := os.Open(gMarksPath)
if os.IsNotExist(err) {
return nil
@@ -1890,7 +1830,7 @@ func (nav *nav) writeMarks() error {
}
func (nav *nav) readTags() error {
nav.tags = make(map[string]string)
clear(nav.tags)
f, err := os.Open(gTagsPath)
if os.IsNotExist(err) {
return nil
+163 -139
View File
@@ -19,12 +19,13 @@ const (
)
func isValidSortMethod(method sortMethod) bool {
for _, validMethod := range []sortMethod{naturalSort, nameSort, sizeSort, timeSort, atimeSort, ctimeSort, extSort} {
if method == validMethod {
return true
}
}
return false
return method == naturalSort ||
method == nameSort ||
method == sizeSort ||
method == timeSort ||
method == atimeSort ||
method == ctimeSort ||
method == extSort
}
const invalidSortErrorMessage = `sortby: value should either be 'natural', 'name', 'size', 'time', 'atime', 'ctime' or 'ext'`
@@ -53,6 +54,7 @@ var gOpts struct {
ignoredia bool
incfilter bool
incsearch bool
locale string
mouse bool
number bool
preview bool
@@ -105,26 +107,36 @@ var gOpts struct {
}
var gLocalOpts struct {
sortbys map[string]sortMethod
dirfirsts map[string]bool
dironlys map[string]bool
hiddens map[string]bool
reverses map[string]bool
infos map[string][]string
sortby map[string]sortMethod
dircounts map[string]bool
dirfirst map[string]bool
dironly map[string]bool
hidden map[string]bool
reverse map[string]bool
info map[string][]string
locale map[string]string
}
func localOptPaths(path string) []string {
var list []string
list = append(list, path)
list := []string{path}
for curr := path; !isRoot(curr); curr = filepath.Dir(curr) {
list = append(list, curr+string(filepath.Separator))
}
return list
}
func getDirCounts(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.dircounts[key]; ok {
return val
}
}
return gOpts.dircounts
}
func getDirFirst(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.dirfirsts[key]; ok {
if val, ok := gLocalOpts.dirfirst[key]; ok {
return val
}
}
@@ -133,7 +145,7 @@ func getDirFirst(path string) bool {
func getDirOnly(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.dironlys[key]; ok {
if val, ok := gLocalOpts.dironly[key]; ok {
return val
}
}
@@ -142,7 +154,7 @@ func getDirOnly(path string) bool {
func getHidden(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.hiddens[key]; ok {
if val, ok := gLocalOpts.hidden[key]; ok {
return val
}
}
@@ -151,7 +163,7 @@ func getHidden(path string) bool {
func getInfo(path string) []string {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.infos[key]; ok {
if val, ok := gLocalOpts.info[key]; ok {
return val
}
}
@@ -160,7 +172,7 @@ func getInfo(path string) []string {
func getReverse(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.reverses[key]; ok {
if val, ok := gLocalOpts.reverse[key]; ok {
return val
}
}
@@ -169,16 +181,25 @@ func getReverse(path string) bool {
func getSortBy(path string) sortMethod {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.sortbys[key]; ok {
if val, ok := gLocalOpts.sortby[key]; ok {
return val
}
}
return gOpts.sortby
}
func getLocale(path string) string {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.locale[key]; ok {
return val
}
}
return gOpts.locale
}
func init() {
gOpts.anchorfind = true
gOpts.autoquit = false
gOpts.autoquit = true
gOpts.dircache = true
gOpts.dircounts = false
gOpts.dirfirst = true
@@ -200,6 +221,7 @@ func init() {
gOpts.ignoredia = true
gOpts.incfilter = false
gOpts.incsearch = false
gOpts.locale = localeStrDisable
gOpts.mouse = false
gOpts.number = false
gOpts.preview = true
@@ -246,130 +268,132 @@ func init() {
gOpts.numberfmt = "\033[33m"
gOpts.tagfmt = "\033[31m"
gOpts.keys = make(map[string]expr)
gOpts.keys = map[string]expr{
"k": &callExpr{"up", nil, 1},
"<up>": &callExpr{"up", nil, 1},
"<m-up>": &callExpr{"up", nil, 1},
"<c-u>": &callExpr{"half-up", nil, 1},
"<c-b>": &callExpr{"page-up", nil, 1},
"<pgup>": &callExpr{"page-up", nil, 1},
"<c-y>": &callExpr{"scroll-up", nil, 1},
"<c-m-up>": &callExpr{"scroll-up", nil, 1},
"j": &callExpr{"down", nil, 1},
"<down>": &callExpr{"down", nil, 1},
"<m-down>": &callExpr{"down", nil, 1},
"<c-d>": &callExpr{"half-down", nil, 1},
"<c-f>": &callExpr{"page-down", nil, 1},
"<pgdn>": &callExpr{"page-down", nil, 1},
"<c-e>": &callExpr{"scroll-down", nil, 1},
"<c-m-down>": &callExpr{"scroll-down", nil, 1},
"h": &callExpr{"updir", nil, 1},
"<left>": &callExpr{"updir", nil, 1},
"l": &callExpr{"open", nil, 1},
"<right>": &callExpr{"open", nil, 1},
"q": &callExpr{"quit", nil, 1},
"gg": &callExpr{"top", nil, 1},
"<home>": &callExpr{"top", nil, 1},
"G": &callExpr{"bottom", nil, 1},
"<end>": &callExpr{"bottom", nil, 1},
"H": &callExpr{"high", nil, 1},
"M": &callExpr{"middle", nil, 1},
"L": &callExpr{"low", nil, 1},
"[": &callExpr{"jump-prev", nil, 1},
"]": &callExpr{"jump-next", nil, 1},
"<space>": &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1},
"t": &callExpr{"tag-toggle", nil, 1},
"v": &callExpr{"invert", nil, 1},
"u": &callExpr{"unselect", nil, 1},
"y": &callExpr{"copy", nil, 1},
"d": &callExpr{"cut", nil, 1},
"c": &callExpr{"clear", nil, 1},
"p": &callExpr{"paste", nil, 1},
"<c-l>": &callExpr{"redraw", nil, 1},
"<c-r>": &callExpr{"reload", nil, 1},
":": &callExpr{"read", nil, 1},
"$": &callExpr{"shell", nil, 1},
"%": &callExpr{"shell-pipe", nil, 1},
"!": &callExpr{"shell-wait", nil, 1},
"&": &callExpr{"shell-async", nil, 1},
"f": &callExpr{"find", nil, 1},
"F": &callExpr{"find-back", nil, 1},
";": &callExpr{"find-next", nil, 1},
",": &callExpr{"find-prev", nil, 1},
"/": &callExpr{"search", nil, 1},
"?": &callExpr{"search-back", nil, 1},
"n": &callExpr{"search-next", nil, 1},
"N": &callExpr{"search-prev", nil, 1},
"m": &callExpr{"mark-save", nil, 1},
"'": &callExpr{"mark-load", nil, 1},
`"`: &callExpr{"mark-remove", nil, 1},
`r`: &callExpr{"rename", nil, 1},
"<c-n>": &callExpr{"cmd-history-next", nil, 1},
"<c-p>": &callExpr{"cmd-history-prev", nil, 1},
gOpts.keys["k"] = &callExpr{"up", nil, 1}
gOpts.keys["<up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<m-up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1}
gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<pgup>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<c-y>"] = &callExpr{"scroll-up", nil, 1}
gOpts.keys["<c-m-up>"] = &callExpr{"scroll-up", nil, 1}
gOpts.keys["j"] = &callExpr{"down", nil, 1}
gOpts.keys["<down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<m-down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1}
gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<pgdn>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<c-e>"] = &callExpr{"scroll-down", nil, 1}
gOpts.keys["<c-m-down>"] = &callExpr{"scroll-down", nil, 1}
gOpts.keys["h"] = &callExpr{"updir", nil, 1}
gOpts.keys["<left>"] = &callExpr{"updir", nil, 1}
gOpts.keys["l"] = &callExpr{"open", nil, 1}
gOpts.keys["<right>"] = &callExpr{"open", nil, 1}
gOpts.keys["q"] = &callExpr{"quit", nil, 1}
gOpts.keys["gg"] = &callExpr{"top", nil, 1}
gOpts.keys["<home>"] = &callExpr{"top", nil, 1}
gOpts.keys["G"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1}
gOpts.keys["H"] = &callExpr{"high", nil, 1}
gOpts.keys["M"] = &callExpr{"middle", nil, 1}
gOpts.keys["L"] = &callExpr{"low", nil, 1}
gOpts.keys["["] = &callExpr{"jump-prev", nil, 1}
gOpts.keys["]"] = &callExpr{"jump-next", nil, 1}
gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
gOpts.keys["t"] = &callExpr{"tag-toggle", nil, 1}
gOpts.keys["v"] = &callExpr{"invert", nil, 1}
gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"copy", nil, 1}
gOpts.keys["d"] = &callExpr{"cut", nil, 1}
gOpts.keys["c"] = &callExpr{"clear", nil, 1}
gOpts.keys["p"] = &callExpr{"paste", nil, 1}
gOpts.keys["<c-l>"] = &callExpr{"redraw", nil, 1}
gOpts.keys["<c-r>"] = &callExpr{"reload", nil, 1}
gOpts.keys[":"] = &callExpr{"read", nil, 1}
gOpts.keys["$"] = &callExpr{"shell", nil, 1}
gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1}
gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1}
gOpts.keys["&"] = &callExpr{"shell-async", nil, 1}
gOpts.keys["f"] = &callExpr{"find", nil, 1}
gOpts.keys["F"] = &callExpr{"find-back", nil, 1}
gOpts.keys[";"] = &callExpr{"find-next", nil, 1}
gOpts.keys[","] = &callExpr{"find-prev", nil, 1}
gOpts.keys["/"] = &callExpr{"search", nil, 1}
gOpts.keys["?"] = &callExpr{"search-back", nil, 1}
gOpts.keys["n"] = &callExpr{"search-next", nil, 1}
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
"zh": &setExpr{"hidden!", ""},
"zr": &setExpr{"reverse!", ""},
"zn": &setExpr{"info", ""},
"zs": &setExpr{"info", "size"},
"zt": &setExpr{"info", "time"},
"za": &setExpr{"info", "size:time"},
"sn": &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1},
"ss": &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1},
"st": &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1},
"sa": &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1},
"sc": &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1},
"se": &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1},
"gh": &callExpr{"cd", []string{"~"}, 1},
}
gOpts.keys["zh"] = &setExpr{"hidden!", ""}
gOpts.keys["zr"] = &setExpr{"reverse!", ""}
gOpts.keys["zn"] = &setExpr{"info", ""}
gOpts.keys["zs"] = &setExpr{"info", "size"}
gOpts.keys["zt"] = &setExpr{"info", "time"}
gOpts.keys["za"] = &setExpr{"info", "size:time"}
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1}
gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1}
gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1}
gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1}
gOpts.cmdkeys = make(map[string]expr)
gOpts.cmdkeys["<space>"] = &callExpr{"cmd-insert", []string{" "}, 1}
gOpts.cmdkeys["<esc>"] = &callExpr{"cmd-escape", nil, 1}
gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-complete", nil, 1}
gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<down>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<up>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<backspace>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<backspace2>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<c-f>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<home>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<c-a>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<end>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-e>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-u>"] = &callExpr{"cmd-delete-home", nil, 1}
gOpts.cmdkeys["<c-k>"] = &callExpr{"cmd-delete-end", nil, 1}
gOpts.cmdkeys["<c-w>"] = &callExpr{"cmd-delete-unix-word", nil, 1}
gOpts.cmdkeys["<c-y>"] = &callExpr{"cmd-yank", nil, 1}
gOpts.cmdkeys["<c-t>"] = &callExpr{"cmd-transpose", nil, 1}
gOpts.cmdkeys["<c-c>"] = &callExpr{"cmd-interrupt", nil, 1}
gOpts.cmdkeys["<a-f>"] = &callExpr{"cmd-word", nil, 1}
gOpts.cmdkeys["<a-b>"] = &callExpr{"cmd-word-back", nil, 1}
gOpts.cmdkeys["<a-c>"] = &callExpr{"cmd-capitalize-word", nil, 1}
gOpts.cmdkeys["<a-d>"] = &callExpr{"cmd-delete-word", nil, 1}
gOpts.cmdkeys["<a-backspace>"] = &callExpr{"cmd-delete-word-back", nil, 1}
gOpts.cmdkeys["<a-backspace2>"] = &callExpr{"cmd-delete-word-back", nil, 1}
gOpts.cmdkeys["<a-u>"] = &callExpr{"cmd-uppercase-word", nil, 1}
gOpts.cmdkeys["<a-l>"] = &callExpr{"cmd-lowercase-word", nil, 1}
gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1}
gOpts.cmdkeys = map[string]expr{
"<space>": &callExpr{"cmd-insert", []string{" "}, 1},
"<esc>": &callExpr{"cmd-escape", nil, 1},
"<tab>": &callExpr{"cmd-complete", nil, 1},
"<enter>": &callExpr{"cmd-enter", nil, 1},
"<c-j>": &callExpr{"cmd-enter", nil, 1},
"<down>": &callExpr{"cmd-history-next", nil, 1},
"<c-n>": &callExpr{"cmd-history-next", nil, 1},
"<up>": &callExpr{"cmd-history-prev", nil, 1},
"<c-p>": &callExpr{"cmd-history-prev", nil, 1},
"<delete>": &callExpr{"cmd-delete", nil, 1},
"<c-d>": &callExpr{"cmd-delete", nil, 1},
"<backspace>": &callExpr{"cmd-delete-back", nil, 1},
"<backspace2>": &callExpr{"cmd-delete-back", nil, 1},
"<left>": &callExpr{"cmd-left", nil, 1},
"<c-b>": &callExpr{"cmd-left", nil, 1},
"<right>": &callExpr{"cmd-right", nil, 1},
"<c-f>": &callExpr{"cmd-right", nil, 1},
"<home>": &callExpr{"cmd-home", nil, 1},
"<c-a>": &callExpr{"cmd-home", nil, 1},
"<end>": &callExpr{"cmd-end", nil, 1},
"<c-e>": &callExpr{"cmd-end", nil, 1},
"<c-u>": &callExpr{"cmd-delete-home", nil, 1},
"<c-k>": &callExpr{"cmd-delete-end", nil, 1},
"<c-w>": &callExpr{"cmd-delete-unix-word", nil, 1},
"<c-y>": &callExpr{"cmd-yank", nil, 1},
"<c-t>": &callExpr{"cmd-transpose", nil, 1},
"<c-c>": &callExpr{"cmd-interrupt", nil, 1},
"<a-f>": &callExpr{"cmd-word", nil, 1},
"<a-b>": &callExpr{"cmd-word-back", nil, 1},
"<a-c>": &callExpr{"cmd-capitalize-word", nil, 1},
"<a-d>": &callExpr{"cmd-delete-word", nil, 1},
"<a-backspace>": &callExpr{"cmd-delete-word-back", nil, 1},
"<a-backspace2>": &callExpr{"cmd-delete-word-back", nil, 1},
"<a-u>": &callExpr{"cmd-uppercase-word", nil, 1},
"<a-l>": &callExpr{"cmd-lowercase-word", nil, 1},
"<a-t>": &callExpr{"cmd-transpose-word", nil, 1},
}
gOpts.cmds = make(map[string]expr)
gOpts.user = make(map[string]string)
gLocalOpts.sortbys = make(map[string]sortMethod)
gLocalOpts.dirfirsts = make(map[string]bool)
gLocalOpts.dironlys = make(map[string]bool)
gLocalOpts.hiddens = make(map[string]bool)
gLocalOpts.reverses = make(map[string]bool)
gLocalOpts.infos = make(map[string][]string)
gLocalOpts.sortby = make(map[string]sortMethod)
gLocalOpts.dircounts = make(map[string]bool)
gLocalOpts.dirfirst = make(map[string]bool)
gLocalOpts.dironly = make(map[string]bool)
gLocalOpts.hidden = make(map[string]bool)
gLocalOpts.reverse = make(map[string]bool)
gLocalOpts.info = make(map[string][]string)
gLocalOpts.locale = make(map[string]string)
setDefaults()
}
+22 -35
View File
@@ -3,6 +3,7 @@
package main
import (
"cmp"
"fmt"
"log"
"os"
@@ -10,6 +11,7 @@ import (
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
@@ -52,10 +54,7 @@ func init() {
}
if envEditor == "" {
envEditor = os.Getenv("EDITOR")
if envEditor == "" {
envEditor = "vi"
}
envEditor = cmp.Or(os.Getenv("EDITOR"), "vi")
}
if envPager == "" {
@@ -85,13 +84,11 @@ func init() {
}
gUser = u
config := os.Getenv("LF_CONFIG_HOME")
if config == "" {
config = os.Getenv("XDG_CONFIG_HOME")
}
if config == "" {
config = filepath.Join(gUser.HomeDir, ".config")
}
config := cmp.Or(
os.Getenv("LF_CONFIG_HOME"),
os.Getenv("XDG_CONFIG_HOME"),
filepath.Join(gUser.HomeDir, ".config"),
)
gConfigPaths = []string{
filepath.Join("/etc", "lf", "lfrc"),
@@ -108,23 +105,18 @@ func init() {
filepath.Join(config, "lf", "icons"),
}
data := os.Getenv("LF_DATA_HOME")
if data == "" {
data = os.Getenv("XDG_DATA_HOME")
}
if data == "" {
data = filepath.Join(gUser.HomeDir, ".local", "share")
}
data := cmp.Or(
os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"),
filepath.Join(gUser.HomeDir, ".local", "share"),
)
gFilesPath = filepath.Join(data, "lf", "files")
gMarksPath = filepath.Join(data, "lf", "marks")
gTagsPath = filepath.Join(data, "lf", "tags")
gHistoryPath = filepath.Join(data, "lf", "history")
runtime := os.Getenv("XDG_RUNTIME_DIR")
if runtime == "" {
runtime = os.TempDir()
}
runtime := cmp.Or(os.Getenv("XDG_RUNTIME_DIR"), os.TempDir())
gDefaultSocketPath = filepath.Join(runtime, fmt.Sprintf("lf.%s.sock", gUser.Username))
}
@@ -155,7 +147,7 @@ func shellKill(cmd *exec.Cmd) error {
pgid, err := unix.Getpgid(cmd.Process.Pid)
if err == nil && cmd.Process.Pid == pgid {
// kill the process group
err = unix.Kill(-pgid, 15)
err = unix.Kill(-pgid, syscall.SIGTERM)
if err == nil {
return nil
}
@@ -188,11 +180,8 @@ func isExecutable(f os.FileInfo) bool {
func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
hidden := false
for _, pattern := range hiddenfiles {
matched := matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path)
if strings.HasPrefix(pattern, "!") && matched {
hidden = false
} else if matched {
hidden = true
if matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path) {
hidden = !strings.HasPrefix(pattern, "!")
}
}
return hidden
@@ -200,31 +189,29 @@ func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
func userName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
uid := fmt.Sprint(stat.Uid)
uid := strconv.FormatUint(uint64(stat.Uid), 10)
if u, err := user.LookupId(uid); err == nil {
return u.Username
} else {
return uid
}
return uid
}
return ""
}
func groupName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
gid := fmt.Sprint(stat.Gid)
gid := strconv.FormatUint(uint64(stat.Gid), 10)
if g, err := user.LookupGroupId(gid); err == nil {
return g.Name
} else {
return gid
}
return gid
}
return ""
}
func linkCount(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
return fmt.Sprint(stat.Nlink)
return strconv.FormatUint(uint64(stat.Nlink), 10)
}
return ""
}
+9 -17
View File
@@ -1,6 +1,7 @@
package main
import (
"cmp"
"fmt"
"log"
"os"
@@ -47,10 +48,7 @@ func init() {
}
if envEditor == "" {
envEditor = os.Getenv("EDITOR")
if envEditor == "" {
envEditor = "notepad"
}
envEditor = cmp.Or(os.Getenv("EDITOR"), "notepad")
}
if envPager == "" {
@@ -76,10 +74,7 @@ func init() {
Username: username,
}
data := os.Getenv("LF_CONFIG_HOME")
if data == "" {
data = os.Getenv("LOCALAPPDATA")
}
data := cmp.Or(os.Getenv("LF_CONFIG_HOME"), os.Getenv("LOCALAPPDATA"))
gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
@@ -189,31 +184,28 @@ func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
hidden := false
for _, pattern := range hiddenfiles {
matched := matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path)
if strings.HasPrefix(pattern, "!") && matched {
hidden = false
} else if matched {
hidden = true
if matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path) {
hidden = !strings.HasPrefix(pattern, "!")
}
}
return hidden
}
func userName(f os.FileInfo) string {
func userName(_ os.FileInfo) string {
return ""
}
func groupName(f os.FileInfo) string {
func groupName(_ os.FileInfo) string {
return ""
}
func linkCount(f os.FileInfo) string {
func linkCount(_ os.FileInfo) string {
return ""
}
func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(windows.Errno) == 17
return err.(*os.LinkError).Err.(windows.Errno) == windows.ERROR_NOT_SAME_DEVICE
}
func quoteString(s string) string {
+2 -5
View File
@@ -324,9 +324,6 @@ func (p *parser) parseExpr() expr {
}
func (p *parser) parse() bool {
if p.expr = p.parseExpr(); p.expr == nil {
return false
}
return true
p.expr = p.parseExpr()
return p.expr != nil
}
+2 -2
View File
@@ -19,7 +19,7 @@ func serve() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
panic(err)
log.Fatalf("failed to open log file: %s", err)
}
defer f.Close()
log.SetOutput(f)
@@ -64,7 +64,7 @@ func echoerr(c net.Conn, msg string) {
log.Print(msg)
}
func echoerrf(c net.Conn, format string, a ...interface{}) {
func echoerrf(c net.Conn, format string, a ...any) {
echoerr(c, fmt.Sprintf(format, a...))
}
+1 -1
View File
@@ -60,7 +60,7 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
// HACK: fillers are used to control when tcell redraws the region where a sixel image is drawn.
// alternating between bold and regular is to clear the image before drawing a new one.
st := sxs.fillerStyle(reg.path)
for y := 0; y < win.h; y++ {
for y := range win.h {
st = win.print(screen, 0, y, st, strings.Repeat(string(gSixelFiller), win.w))
}
+134 -129
View File
@@ -145,7 +145,7 @@ var gKeyVal = map[tcell.Key]string{
var gValKey map[string]tcell.Key
func init() {
gValKey = make(map[string]tcell.Key)
gValKey = make(map[string]tcell.Key, len(gKeyVal))
for k, v := range gKeyVal {
gValKey[v] = k
}
@@ -166,11 +166,12 @@ func (win *win) renew(w, h, x, y int) {
func printLength(s string) int {
ind := 0
off := 0
for i := 0; i < len(s); i++ {
slen := len(s)
for i := 0; i < slen; i++ {
r, w := utf8.DecodeRuneInString(s[i:])
if r == gEscapeCode && i+1 < len(s) && s[i+1] == '[' {
j := strings.IndexAny(s[i:min(len(s), i+64)], "mK")
if r == gEscapeCode && i+1 < slen && s[i+1] == '[' {
j := strings.IndexAny(s[i:min(slen, i+64)], "mK")
if j == -1 {
continue
}
@@ -194,11 +195,12 @@ func printLength(s string) int {
func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) tcell.Style {
off := x
var comb []rune
for i := 0; i < len(s); i++ {
slen := len(s)
for i := 0; i < slen; i++ {
r, w := utf8.DecodeRuneInString(s[i:])
if r == gEscapeCode && i+1 < len(s) && s[i+1] == '[' {
j := strings.IndexAny(s[i:min(len(s), i+64)], "mK")
if r == gEscapeCode && i+1 < slen && s[i+1] == '[' {
j := strings.IndexAny(s[i:min(slen, i+64)], "mK")
if j == -1 {
continue
}
@@ -227,11 +229,11 @@ func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) t
i += w - 1
if r == '\t' {
s := gOpts.tabstop - (x-off)%gOpts.tabstop
for i := 0; i < s && x+i < win.w; i++ {
ind := gOpts.tabstop - (x-off)%gOpts.tabstop
for i := 0; i < ind && x+i < win.w; i++ {
screen.SetContent(win.x+x+i, win.y+y, ' ', nil, st)
}
x += s
x += ind
} else {
x += runewidth.RuneWidth(r)
}
@@ -240,7 +242,7 @@ func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) t
return st
}
func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...interface{}) {
func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...any) {
win.print(screen, x, y, st, fmt.Sprintf(format, a...))
}
@@ -288,21 +290,21 @@ func infotimefmt(t time.Time) string {
}
func fileInfo(f *file, d *dir, userWidth int, groupWidth int) string {
var info string
var info strings.Builder
for _, s := range getInfo(d.path) {
switch s {
case "size":
if f.IsDir() && gOpts.dircounts {
if f.IsDir() && getDirCounts(d.path) {
switch {
case f.dirCount < -1:
info = fmt.Sprintf("%s !", info)
info.WriteString(" !")
case f.dirCount < 0:
info = fmt.Sprintf("%s ?", info)
info.WriteString(" ?")
case f.dirCount < 1000:
info = fmt.Sprintf("%s %4d", info, f.dirCount)
fmt.Fprintf(&info, " %4d", f.dirCount)
default:
info = fmt.Sprintf("%s 999+", info)
info.WriteString(" 999+")
}
continue
}
@@ -313,25 +315,25 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int) string {
} else {
sz = humanize(f.TotalSize())
}
info = fmt.Sprintf("%s %4s", info, sz)
fmt.Fprintf(&info, " %4s", sz)
case "time":
info = fmt.Sprintf("%s %*s", info, max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
case "atime":
info = fmt.Sprintf("%s %*s", info, max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime))
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime))
case "ctime":
info = fmt.Sprintf("%s %*s", info, max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime))
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime))
case "perm":
info = fmt.Sprintf("%s %s", info, f.FileInfo.Mode().String())
info.WriteString(" " + f.FileInfo.Mode().String())
case "user":
info = fmt.Sprintf("%s %-*s", info, userWidth, userName(f.FileInfo))
fmt.Fprintf(&info, " %-*s", userWidth, userName(f.FileInfo))
case "group":
info = fmt.Sprintf("%s %-*s", info, groupWidth, groupName(f.FileInfo))
fmt.Fprintf(&info, " %-*s", groupWidth, groupName(f.FileInfo))
default:
log.Printf("unknown info type: %s", s)
}
}
return info
return info.String()
}
type dirContext struct {
@@ -354,7 +356,7 @@ type dirStyle struct {
role dirRole
}
func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirStyle, previewLoading bool) {
func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirStyle) {
if win.w < 5 || dir == nil {
return
}
@@ -365,32 +367,19 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
win.print(ui.screen, 2, 0, messageStyle, "permission denied")
return
}
if (dir.loading && len(dir.files) == 0) || (dirStyle.role == Preview && dir.loading && gOpts.dirpreviews) {
if dirStyle.role != Preview || previewLoading {
win.print(ui.screen, 2, 0, messageStyle, "loading...")
}
fileslen := len(dir.files)
if dir.loading && fileslen == 0 {
win.print(ui.screen, 2, 0, messageStyle, "loading...")
return
}
if dirStyle.role == Preview && gOpts.dirpreviews && len(gOpts.previewer) > 0 {
// Print previewer result instead of default directory print operation.
st := tcell.StyleDefault
for i, l := range dir.lines {
if i > win.h-1 {
break
}
st = win.print(ui.screen, 2, i, st, l)
}
return
}
if len(dir.files) == 0 {
if fileslen == 0 {
win.print(ui.screen, 2, 0, messageStyle, "empty")
return
}
beg := max(dir.ind-dir.pos, 0)
end := min(beg+win.h, len(dir.files))
end := min(beg+win.h, fileslen)
if beg > end {
return
@@ -403,7 +392,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if gOpts.number && gOpts.relativenumber {
lnwidth++
}
for j := 10; j <= len(dir.files); j *= 10 {
for j := 10; j <= fileslen; j *= 10 {
lnwidth++
}
}
@@ -485,9 +474,10 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
maxFilenameWidth := maxWidth - 1 - runeSliceWidth(icon)
info := fileInfo(f, dir, userWidth, groupWidth)
showInfo := len(info) > 0 && 2*len(info) < maxWidth
infolen := len(info)
showInfo := infolen > 0 && 2*infolen < maxWidth
if showInfo {
maxFilenameWidth -= len(info)
maxFilenameWidth -= infolen
}
filename := []rune(f.Name())
@@ -524,7 +514,9 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
line = append(line, ' ')
win.print(ui.screen, lnwidth+2, i, st, fmt.Sprintf(cursorFmt, string(line)))
} else {
if tag != " " {
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)
}
@@ -537,7 +529,8 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
win.print(ui.screen, lnwidth+2, i, iconStyle, string(icon))
}
win.print(ui.screen, lnwidth+2+runeSliceWidth(icon), i, st, string(filename))
line := append(filename, ' ')
win.print(ui.screen, lnwidth+2+runeSliceWidth(icon), i, st, string(line))
}
}
}
@@ -576,7 +569,7 @@ func getWidths(wtot int) []int {
}
wsum := 0
for i := 0; i < wlen-1; i++ {
for i := range wlen - 1 {
widths[i] = gOpts.ratios[i] * wtot / rsum
wsum += widths[i]
}
@@ -588,13 +581,12 @@ func getWidths(wtot int) []int {
func getWins(screen tcell.Screen) []*win {
wtot, htot := screen.Size()
var wins []*win
widths := getWidths(wtot)
wacc := 0
wlen := len(widths)
for i := 0; i < wlen; i++ {
wins := make([]*win, 0, wlen)
for i := range wlen {
if gOpts.drawbox {
wacc++
wins = append(wins, newWin(widths[i], htot-4, wacc, 2))
@@ -623,7 +615,7 @@ type ui struct {
keyChan chan string
tevChan chan tcell.Event
evChan chan tcell.Event
menuBuf *bytes.Buffer
menu string
cmdPrefix string
cmdAccLeft []rune
cmdAccRight []rune
@@ -725,10 +717,13 @@ func (ui *ui) echoerr(msg string) {
log.Printf("error: %s", msg)
}
func (ui *ui) echoerrf(format string, a ...interface{}) {
func (ui *ui) echoerrf(format string, a ...any) {
ui.echoerr(fmt.Sprintf(format, a...))
}
// This represents the preview for a regular file.
// This can also be used to represent the preview of a directory if
// `dirpreviews` is enabled.
type reg struct {
loading bool
volatile bool
@@ -761,10 +756,10 @@ func (ui *ui) loadFile(app *app, volatile bool) {
return
}
if curr.IsDir() {
ui.dirPrev = app.nav.loadDir(curr.path)
} else if curr.Mode().IsRegular() {
if curr.Mode().IsRegular() || (curr.IsDir() && gOpts.dirpreviews) {
ui.regPrev = app.nav.loadReg(curr.path, volatile)
} else if curr.IsDir() {
ui.dirPrev = app.nav.loadDir(curr.path)
}
}
@@ -802,14 +797,14 @@ func (ui *ui) loadFileInfo(nav *nav) {
replace("%t", curr.ModTime().Format(gOpts.timefmt))
replace("%l", curr.linkTarget)
fileInfo := ""
var fileInfo strings.Builder
for _, section := range strings.Split(statfmt, "\x1f") {
if !strings.Contains(section, "\x00") {
fileInfo += section
fileInfo.WriteString(section)
}
}
ui.msg = fileInfo
ui.msg = fileInfo.String()
}
func (ui *ui) drawPromptLine(nav *nav) {
@@ -879,7 +874,7 @@ func formatRulerOpt(name string, val string) string {
// display name of builtin options for clarity
if !strings.HasPrefix(name, "lf_user_") {
val = fmt.Sprintf("%s=%s", strings.TrimPrefix(name, "lf_"), val)
return fmt.Sprintf("%s=%s", strings.TrimPrefix(name, "lf_"), val)
}
return val
@@ -899,13 +894,11 @@ func (ui *ui) drawRuler(nav *nav) {
copy := 0
move := 0
if len(nav.saves) > 0 {
for _, cp := range nav.saves {
if cp {
copy++
} else {
move++
}
for _, cp := range nav.saves {
if cp {
copy++
} else {
move++
}
}
@@ -945,11 +938,11 @@ func (ui *ui) drawRuler(nav *nav) {
case "%f":
result = strings.Join(dir.filter, " ")
case "%i":
result = fmt.Sprint(ind)
result = strconv.Itoa(ind)
case "%t":
result = fmt.Sprint(tot)
result = strconv.Itoa(tot)
case "%h":
result = fmt.Sprint(hid)
result = strconv.Itoa(hid)
case "%d":
result = diskFree(dir.path)
default:
@@ -963,13 +956,13 @@ func (ui *ui) drawRuler(nav *nav) {
}
return result
})
ruler := ""
var ruler strings.Builder
for _, section := range strings.Split(rulerfmt, "\x1f") {
if !strings.Contains(section, "\x00") {
ruler += section
ruler.WriteString(section)
}
}
ui.msgWin.printRight(ui.screen, 0, st, ruler)
ui.msgWin.printRight(ui.screen, 0, st, ruler.String())
}
func (ui *ui) drawBox() {
@@ -1000,7 +993,7 @@ func (ui *ui) drawBox() {
}
wacc := 0
for wind := 0; wind < len(ui.wins)-1; wind++ {
for wind := range len(ui.wins) - 1 {
wacc += ui.wins[wind].w + 1
ui.screen.SetContent(wacc, 1, tcell.RuneTTee, nil, st)
for i := 2; i < h-2; i++ {
@@ -1026,13 +1019,7 @@ func (ui *ui) draw(nav *nav) {
st := tcell.StyleDefault
context := dirContext{selections: nav.selections, saves: nav.saves, tags: nav.tags}
// XXX: manual clean without flush to avoid flicker on Windows
wtot, htot := ui.screen.Size()
for i := 0; i < wtot; i++ {
for j := 0; j < htot; j++ {
ui.screen.SetContent(i, j, ' ', nil, st)
}
}
ui.screen.Clear()
ui.sxScreen.sixel = nil
ui.drawPromptLine(nav)
@@ -1041,15 +1028,14 @@ func (ui *ui) draw(nav *nav) {
if gOpts.preview {
wins--
}
for i := 0; i < wins; i++ {
for i := range wins {
role := Parent
if i == wins-1 {
role = Active
}
if dir := ui.dirOfWin(nav, i); dir != nil {
ui.wins[i].printDir(ui, dir, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: role},
nav.previewLoading)
&dirStyle{colors: ui.styles, icons: ui.icons, role: role})
}
}
@@ -1077,12 +1063,11 @@ func (ui *ui) draw(nav *nav) {
if err == nil {
preview := ui.wins[len(ui.wins)-1]
if curr.IsDir() {
preview.printDir(ui, ui.dirPrev, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: Preview},
nav.previewLoading)
} else if curr.Mode().IsRegular() {
if curr.Mode().IsRegular() || (curr.IsDir() && gOpts.dirpreviews) {
preview.printReg(ui.screen, ui.regPrev, nav.previewLoading, &ui.sxScreen)
} else if curr.IsDir() {
preview.printDir(ui, ui.dirPrev, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: Preview})
}
}
}
@@ -1091,8 +1076,8 @@ func (ui *ui) draw(nav *nav) {
ui.drawBox()
}
if ui.menuBuf != nil {
lines := strings.Split(ui.menuBuf.String(), "\n")
if ui.menu != "" {
lines := strings.Split(ui.menu, "\n")
lines = lines[:len(lines)-1]
@@ -1112,7 +1097,7 @@ func (ui *ui) draw(nav *nav) {
}
ui.screen.Show()
if ui.menuBuf == nil && ui.cmdPrefix == "" && ui.sxScreen.sixel != nil {
if ui.menu == "" && ui.cmdPrefix == "" && ui.sxScreen.sixel != nil {
ui.sxScreen.lastFile = ui.regPrev.path
ui.sxScreen.showSixels()
}
@@ -1132,11 +1117,11 @@ func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok b
return
}
func listExprMap(binds map[string]expr, title string) *bytes.Buffer {
func listExprMap(binds map[string]expr, title string) string {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
var keys []string
keys := make([]string, 0, len(binds))
for k := range binds {
keys = append(keys, k)
}
@@ -1149,18 +1134,18 @@ func listExprMap(binds map[string]expr, title string) *bytes.Buffer {
}
t.Flush()
return b
return b.String()
}
func listBinds(binds map[string]expr) *bytes.Buffer {
func listBinds(binds map[string]expr) string {
return listExprMap(binds, "keys")
}
func listCmds() *bytes.Buffer {
func listCmds() string {
return listExprMap(gOpts.cmds, "name")
}
func listJumps(jumps []string, ind int) *bytes.Buffer {
func listJumps(jumps []string, ind int) string {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
@@ -1181,10 +1166,10 @@ func listJumps(jumps []string, ind int) *bytes.Buffer {
}
t.Flush()
return b
return b.String()
}
func listHistory(history []cmdItem) *bytes.Buffer {
func listHistory(history []cmdItem) string {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
@@ -1197,14 +1182,14 @@ func listHistory(history []cmdItem) *bytes.Buffer {
}
t.Flush()
return b
return b.String()
}
func listMarks(marks map[string]string) *bytes.Buffer {
func listMarks(marks map[string]string) string {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
var keys []string
keys := make([]string, 0, len(marks))
for k := range marks {
keys = append(keys, k)
}
@@ -1217,7 +1202,25 @@ func listMarks(marks map[string]string) *bytes.Buffer {
}
t.Flush()
return b
return b.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)
return ""
}
b := new(strings.Builder)
for _, file := range dir.files {
fmt.Fprintln(b, file.path)
}
return b.String()
}
func (ui *ui) pollEvent() tcell.Event {
@@ -1313,10 +1316,10 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
} else {
val := gKeyVal[tev.Key()]
val = addSpecialKeyModifier(val, tev.Modifiers())
if val == "<esc>" && string(ui.keyAcc) != "" {
if val == "<esc>" && len(ui.keyAcc) != 0 {
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
ui.menu = ""
return draw
}
ui.keyAcc = append(ui.keyAcc, []rune(val)...)
@@ -1333,7 +1336,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
ui.echoerrf("unknown mapping: %s", string(ui.keyAcc))
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
ui.menu = ""
return draw
default:
if ok {
@@ -1346,21 +1349,22 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
}
expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok && count != 0 {
expr = &callExpr{e.name, e.args, e.count}
expr.(*callExpr).count = count
} else if e, ok := expr.(*listExpr); ok && count != 0 {
expr = &listExpr{e.exprs, e.count}
expr.(*listExpr).count = count
if count != 0 {
switch e := expr.(type) {
case *callExpr:
expr = &callExpr{name: e.name, args: e.args, count: count}
case *listExpr:
expr = &listExpr{exprs: e.exprs, count: count}
}
}
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
ui.menu = ""
return expr
}
if gOpts.showbinds {
ui.menuBuf = listBinds(binds)
ui.menu = listBinds(binds)
}
return draw
}
@@ -1409,7 +1413,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
ui.echoerrf("unknown mapping: %s", button)
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
ui.menu = ""
return draw
}
@@ -1582,15 +1586,17 @@ func anyKey() {
}
defer term.Restore(int(os.Stdin.Fd()), oldState)
b := make([]byte, 1)
b := make([]byte, 8)
os.Stdin.Read(b)
}
func listMatches(screen tcell.Screen, matches []string, selectedInd int) *bytes.Buffer {
if len(matches) < 2 {
return nil
func listMatches(screen tcell.Screen, matches []string, selectedInd int) string {
mlen := len(matches)
if mlen < 2 {
return ""
}
b := new(bytes.Buffer)
var b strings.Builder
wtot, _ := screen.Size()
wcol := 0
@@ -1602,19 +1608,18 @@ func listMatches(screen tcell.Screen, matches []string, selectedInd int) *bytes.
b.WriteString("possible matches\n")
for i := 0; i < len(matches); {
for j := 0; j < ncol && i < len(matches); i, j = i+1, j+1 {
for i := 0; i < mlen; {
for j := 0; j < ncol && i < mlen; i, j = i+1, j+1 {
target := matches[i]
if selectedInd == i {
target = fmt.Sprintf("\033[7m%s\033[0m%*s", target, wcol-len(target), "")
fmt.Fprintf(&b, "\033[7m%s\033[0m%*s", target, wcol-len(target), "")
} else {
target = fmt.Sprintf("%s%*s", target, wcol-len(target), "")
fmt.Fprintf(&b, "%s%*s", target, wcol-len(target), "")
}
b.WriteString(target)
}
b.WriteByte('\n')
}
return b
return b.String()
}
+48 -18
View File
@@ -64,18 +64,13 @@ func (watch *watch) stop() {
watch.events = nil
}
func (watch *watch) set(paths map[string]bool) {
func (watch *watch) add(path string) {
if watch.watcher == nil {
return
}
for _, path := range watch.watcher.WatchList() {
if !paths[path] {
watch.watcher.Remove(path)
}
}
for path := range paths {
// ignore /dev since write updates to /dev/tty causes high cpu usage
if path != "/dev" {
watch.watcher.Add(path)
}
}
@@ -85,20 +80,26 @@ func (watch *watch) loop() {
select {
case ev := <-watch.events:
if ev.Has(fsnotify.Create) {
dir := filepath.Dir(ev.Name)
watch.addLoad(dir)
watch.addUpdate(dir)
for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) {
watch.addLoad(path)
watch.addUpdate(path)
}
}
if ev.Has(fsnotify.Remove) || ev.Has(fsnotify.Rename) {
watch.delChan <- ev.Name
dir := filepath.Dir(ev.Name)
watch.addLoad(dir)
watch.addUpdate(dir)
dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) {
watch.delChan <- filepath.Join(path, file)
watch.addLoad(path)
watch.addUpdate(path)
}
}
if ev.Has(fsnotify.Write) || ev.Has(fsnotify.Chmod) {
watch.addUpdate(ev.Name)
dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) {
watch.addUpdate(filepath.Join(path, file))
}
}
case <-watch.loadTimer.C:
for path := range watch.loads {
@@ -109,7 +110,7 @@ func (watch *watch) loop() {
dir.sort()
watch.dirChan <- dir
}
watch.loads = make(map[string]bool)
clear(watch.loads)
case <-watch.updateTimer.C:
for path := range watch.updates {
if _, err := os.Lstat(path); err != nil {
@@ -117,7 +118,7 @@ func (watch *watch) loop() {
}
watch.fileChan <- newFile(path)
}
watch.updates = make(map[string]bool)
clear(watch.updates)
case <-watch.quit:
return
}
@@ -139,3 +140,32 @@ func (watch *watch) addUpdate(path string) {
}
watch.updates[path] = true
}
// Hacky workaround since fsnotify reports changes for only one path if a
// directory is located at more than one path (e.g. bind mounts).
func (watch *watch) getSameDirs(dir string) []string {
var paths []string
dirStat, err := os.Stat(dir)
if err != nil {
return nil
}
for _, path := range watch.watcher.WatchList() {
if path == dir {
paths = append(paths, path)
continue
}
stat, err := os.Stat(path)
if err != nil {
continue
}
if os.SameFile(stat, dirStat) {
paths = append(paths, path)
}
}
return paths
}