Compare commits

43 Commits
Author SHA1 Message Date
CatsDeservePets 8b8780299a feat: extend SGR support (#2749)
* feat: support `SGR` color resets and double underline

* test: add cases to TestApplySGR
2026-11-19 23:51:06 +01:00
CatsDeservePets d4b5b4647b docs: document ban on automated PRs in CONTRIBUTING.md (#2746) 2026-11-17 23:03:32 +01:00
valoq bdb4d901d1 fix: reject commands with parse errors (#2640) 2026-11-12 15:00:32 +01:00
valoq 901322f428 fix: skip invalid marks and tags entries (#2541) 2026-11-11 23:17:32 +01:00
dependabot[bot] 9b87b3f2c3 chore(deps): bump golang.org/x/sys from 0.49.0 to 0.50.0 (#2738)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.49.0 to 0.50.0.
- [Commits](https://github.com/golang/sys/compare/v0.49.0...v0.50.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-10 23:09:14 +01:00
CatsDeservePets 826c5fc0aa fix: prevent panic in shell-wait (#2736) 2026-11-09 23:14:51 +01:00
CatsDeservePets 59cbc97b50 docs: add code comment explaining draw (#2735) 2026-11-08 23:25:19 +01:00
CatsDeservePets 1d8a32edef feat: improve completion for boolean options (#2733) 2026-11-05 22:52:40 +00:00
valoq a127f13d58 fix: preserve tabs in -remote query output 2026-11-05 22:28:29 +00:00
Yang Baiandybai08 91e269fe5c fix: limit octal escapes in double quotes to three digits (#2725)
The scanner consumed every digit following a backslash as part of an
octal escape. A digit right after an escape was therefore swallowed:
"\0337" (ESC 7) became the single byte 0o337 instead of ESC followed by
"7", and "\0338" (ESC 8) failed to parse and became a NUL byte.

Stop after three digits, as in C and other languages with octal string
escapes. Escapes of up to three digits are read as before.

Co-authored-by: ybai08 <271969568+ybai08@users.noreply.github.com>
2026-11-04 00:55:48 +01:00
CatsDeservePets 5298e8813b docs: update CHANGELOG.md for #2684 (#2731) 2026-11-02 21:44:19 +01:00
CatsDeservePets d816166427 docs: update CHANGELOG.md for #2687, #2701, #2714, #2722 (#2727) 2026-10-30 22:22:59 +01:00
dependabot[bot] fb04a127b0 chore(deps): bump golang.org/x/term from 0.46.0 to 0.47.0 (#2709)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.46.0 to 0.47.0.
- [Commits](https://github.com/golang/term/compare/v0.46.0...v0.47.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-30 01:40:46 +01:00
dependabot[bot] a3aab4380b chore(deps): bump golang.org/x/sys from 0.48.0 to 0.49.0 (#2707)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.48.0 to 0.49.0.
- [Commits](https://github.com/golang/sys/compare/v0.48.0...v0.49.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-30 01:36:04 +01:00
dependabot[bot] 8875efcb30 chore(deps): bump github.com/gdamore/tcell/v3 from 3.5.0 to 3.6.0 (#2710)
Bumps [github.com/gdamore/tcell/v3](https://github.com/gdamore/tcell) from 3.5.0 to 3.6.0.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv3.md)
- [Commits](https://github.com/gdamore/tcell/compare/v3.5.0...v3.6.0)

---
updated-dependencies:
- dependency-name: github.com/gdamore/tcell/v3
  dependency-version: 3.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-30 01:23:16 +01:00
Yang Baiandybai08 6f9b1879f3 fix: order large numbers by value in natural sort (#2714)
naturalCmp parsed digit runs with strconv.Atoi and fell back to a plain
string comparison when parsing failed. Numbers that do not fit in an int
(20 digits or more on 64-bit platforms) were therefore compared
lexicographically, so '10000000000000000000' sorted before '9'. This also
made the comparison non-transitive ('9' < '10' < '10000000000000000000'
< '9'), which slices.SortStableFunc does not support.

Compare the digit runs directly instead: strip leading zeros, compare by
length, then by digits, keeping the existing tie-break on the length of
the original run.

Co-authored-by: ybai08 <271969568+ybai08@users.noreply.github.com>
2026-10-30 00:52:11 +01:00
CatsDeservePets a9d6c5d834 docs: explain jump list (#2724) 2026-10-29 01:13:55 +01:00
CatsDeservePets 78f781b1e6 feat: show marks in mark-save (#2722) 2026-10-27 03:33:18 +01:00
CatsDeservePets b44676154f chore: add issue templates (#2718) 2026-10-26 02:57:43 +01:00
CatsDeservePets 664d7c88e1 refactor: improve log and error messages (#2708) 2026-10-12 21:33:05 +02:00
valoq 5d3c7b7025 fix tilde expansion on file operations (#2687) 2026-10-09 23:15:45 +02:00
CatsDeservePets df5f71c523 fix: restore terminal state on termination signals (#2701) 2026-10-06 23:52:00 +02:00
CatsDeservePets 725e63c0a8 docs: update CHANGELOG.md for #2618, #2674, #2679 (#2694) 2026-10-01 23:51:51 +02:00
CatsDeservePets 20c85c9477 feat: support cd - (#2693)
* feat: support `cd -`

* docs: add documentation

* docs: update `CHANGELOG.md`
2026-10-01 02:59:29 +02:00
CatsDeservePets 1f31d6634e refactor: silence gopls hints (#2692) 2026-09-28 22:49:11 +02:00
CatsDeservePets 1a1cbc992e docs: fix usage indentation (#2691) 2026-09-28 21:10:19 +02:00
valoq 4f45fc2cda fix: dont copy irregular files (#2618)
* Fix: dont copy irregular files

* improve patch
2026-09-28 00:01:15 +02:00
dependabot[bot] 9ecf9ac660 chore(deps): bump golang.org/x/term from 0.45.0 to 0.46.0 (#2683) 2026-09-15 06:25:47 +00:00
dependabot[bot] 3eb06f2103 chore(deps): bump github.com/gdamore/tcell/v3 from 3.4.2 to 3.5.0 (#2684) 2026-09-15 06:24:23 +00:00
CatsDeservePets efd8e6e04a chore(deps): bump golangci-lint from 2.5.0 to 2.9.0 (#2681) 2026-09-09 13:29:40 +00:00
dependabot[bot] 281eda3c1a chore(deps): bump golang.org/x/sys from 0.47.0 to 0.48.0 (#2680) 2026-09-09 07:49:46 +02:00
valoq 5962d8d9b7 Fix: shorten home path correctly (#2679) 2026-09-08 14:48:04 +02:00
valoq 274b13df9e Fix: Main loop blocked by double quit (#2674) 2026-09-07 19:50:31 +00:00
dependabot[bot] 1c9029e9ec chore(deps): bump github.com/gdamore/tcell/v3 from 3.4.1 to 3.4.2 (#2671) 2026-08-25 02:37:20 +02:00
ivan 252ca3e425 fix: calculate target directory size for symlinks in calcdirsize (#2650) 2026-08-15 04:07:20 +02:00
CatsDeservePets e6789ab125 docs: update CHANGELOG.md for #2664 (#2665) 2026-08-14 01:43:39 +02:00
CatsDeservePets f918e34e9b fix: mouse selection (#2664) 2026-08-13 23:27:43 +02:00
CatsDeservePets 1f779c5d7e docs: update CHANGELOG.md for #2643 and #2657 (#2663) 2026-08-12 22:26:37 +02:00
CatsDeservePets 7351444397 docs: update usage message (#2662) 2026-08-11 16:08:55 +02:00
valoq 34ecd96967 fix: remove dead client connections (#2643) 2026-08-10 23:18:04 +02:00
CatsDeservePets 9f27e57c4b chore: remove roundbox deprecation message (#2658) 2026-08-02 22:44:18 +00:00
valoq 3eeafab106 fix: drop readline markers from colored prompts (#2657) 2026-08-02 16:53:32 +02:00
CatsDeservePets 685c6e24a5 docs: update CHANGELOG.md with missing r42 changes (#2654) 2026-07-31 13:19:15 +02:00
29 changed files with 451 additions and 143 deletions

No files matched your search

+41
View File
@@ -0,0 +1,41 @@
name: Bug report
description: Report a problem
labels: [bug]
body:
- type: markdown
attributes:
value: |
- Search [existing issues](https://github.com/gokcehan/lf/issues) before reporting.
- Verify bugs yourself. AI claims alone aren't proof.
- type: textarea
attributes:
label: Description
description: Describe the problem. Include logs (`lf -log lf.log`), images, or videos if useful.
validations:
required: true
- type: textarea
attributes:
label: Steps to reproduce
description: |
Describe how to reproduce or verify the problem.
- Try `lf -config /dev/null` (Windows: `lf -config NUL`) to skip loading your `lfrc`.
- If the problem disappears, include any settings or scripts needed to reproduce it.
validations:
required: true
- type: textarea
attributes:
label: lf version
description: Paste the output of `lf -version`.
render: text
validations:
required: true
- type: textarea
attributes:
label: Environment
description: Include your operating system, terminal, and any other details relevant to the issue.
placeholder: |
Operating system:
Terminal:
...
validations:
required: true
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Question
url: https://github.com/gokcehan/lf/discussions
about: Ask a question about using or configuring lf
@@ -0,0 +1,23 @@
name: Feature request
description: Suggest a feature or improvement
labels: [enhancement]
body:
- type: markdown
attributes:
value: Search [existing issues](https://github.com/gokcehan/lf/issues) before submitting.
- type: textarea
attributes:
label: Problem or use case
description: What is missing or difficult to do in lf?
validations:
required: true
- type: textarea
attributes:
label: Desired behavior
description: Describe how the feature should work. Include examples from other tools if relevant.
validations:
required: true
- type: textarea
attributes:
label: Configuration and workarounds
description: Have you tried achieving this through configuration or scripting? If so, what limitations did you encounter?
+1 -1
View File
@@ -42,7 +42,7 @@ jobs:
- name: golangci-lint - name: golangci-lint
uses: golangci/golangci-lint-action@v9 uses: golangci/golangci-lint-action@v9
with: with:
version: v2.5.0 version: v2.9.0
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
+25 -2
View File
@@ -10,6 +10,27 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
## Unreleased ## Unreleased
### Changed
- The `mark-save` command now displays a list of existing marks (#2722).
### Added
- The `cd` command now supports `-` to change to the previous directory (#2693).
### Fixed
- Attempting to copy irregular files now results in an error instead of causing the copy operation to hang (#2618).
- Dead client connections no longer prevent the `quit` server command from terminating the server (#2643).
- The `calcdirsize` command now calculates the size of the target directory for symbolic links instead of the size of the link itself (#2650).
- Readline markers in `promptfmt` are no longer rendered as visible characters (#2657).
- Selecting entries with the mouse no longer causes the file list to jump unexpectedly (#2664).
- A bug where executing the `quit` command multiple times in quick succession could cause `lf` to become unresponsive is now fixed (#2674).
- The home directory abbreviation `~` (#2679) and its expansion (#2687) no longer match partial path components.
- A bug where quitting `lf` required an additional key press on some platforms is now fixed (#2684).
- The terminal state is now restored when `lf` receives `SIGHUP`, `SIGQUIT`, or `SIGTERM` (#2701).
- Natural sorting now correctly compares numbers regardless of their length (#2714).
## [r42](https://github.com/gokcehan/lf/releases/tag/r42) ## [r42](https://github.com/gokcehan/lf/releases/tag/r42)
### Changed ### Changed
@@ -61,10 +82,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- Previews no longer flicker when the terminal height decreases (#2537). - Previews no longer flicker when the terminal height decreases (#2537).
- Symbolic linked directories are now updated properly when the `watch` option is enabled (#2550). - Symbolic linked directories are now updated properly when the `watch` option is enabled (#2550).
- Previews of modified files are now updated properly when the `preload` option is enabled (#2567). - Previews of modified files are now updated properly when the `preload` option is enabled (#2567).
- Previews of files other than the current file are now reloaded immediately after being modified when the `watch` option is enabled (#2594). - Previews of files other than the current file are now reloaded immediately after being modified when the `watch` option is enabled (#2594) (#2602) (#2648).
- The `loading...` message now shows for files that are reloading due to being modified (#2597). - The `loading...` message now shows for files that are reloading due to being modified (#2597).
- Attempting to copy a directory into itself will now result in an error (#2608). - Attempting to copy a directory into itself will now result in an error (#2608) (#2623).
- The permissions of state files (i.e. `files`/`history`/`marks`/`tags`) is now changed to only be accessible by the owner (#2612). - The permissions of state files (i.e. `files`/`history`/`marks`/`tags`) is now changed to only be accessible by the owner (#2612).
- Broken symbolic links are no longer silently overwritten when moving files (#2619).
- Using the `copy` or `cut` command with a path containing newline characters now results in an error instead of silently omitting the path (#2620).
## [r41](https://github.com/gokcehan/lf/releases/tag/r41) ## [r41](https://github.com/gokcehan/lf/releases/tag/r41)
+4
View File
@@ -12,6 +12,10 @@ If your feature can be implemented as a configuration option, **please add it to
For bug fixes, you can simply send a pull request. For bug fixes, you can simply send a pull request.
## Automated contributions
Pull requests generated entirely by AI tools or submitted as part of mass-submission campaigns are not accepted. Such pull requests may be closed without review and labeled as spam.
## Code conventions ## Code conventions
In addition to `gofmt` and friends (e.g. [go vet](https://pkg.go.dev/cmd/vet), [staticcheck](https://staticcheck.dev/), [golangci-lint](https://golangci-lint.run/)), we have a few conventions: In addition to `gofmt` and friends (e.g. [go vet](https://pkg.go.dev/cmd/vet), [staticcheck](https://staticcheck.dev/), [golangci-lint](https://golangci-lint.run/)), we have a few conventions:
+15 -4
View File
@@ -54,12 +54,14 @@ func newApp(ui *ui, nav *nav) *app {
signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM) signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM)
go func() { go func() {
for { for {
switch <-sigChan { sig := <-sigChan
switch sig {
case os.Interrupt: case os.Interrupt:
case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM: case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
log.Printf("received termination signal: %s", sig)
app.quit() app.quit()
app.ui.screen.Fini()
os.Exit(3) os.Exit(3)
return
} }
} }
}() }()
@@ -95,6 +97,14 @@ func (app *app) quit() {
} }
} }
// requestQuit signals the main loop to quit and never blocks when a request is already pending.
func (app *app) requestQuit() {
select {
case app.quitChan <- struct{}{}:
default:
}
}
func (app *app) readFile(path string) { func (app *app) readFile(path string) {
log.Printf("reading file: %s", path) log.Printf("reading file: %s", path)
@@ -529,10 +539,11 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
app.nav.previewChan <- "" app.nav.previewChan <- ""
if err := app.ui.suspend(); err != nil { if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err) log.Printf("suspending screen: %s", err)
} }
defer func() { defer func() {
if err := app.ui.resume(); err != nil { if err := app.ui.resume(); err != nil {
log.Printf("resuming screen: %s", err)
app.quit() app.quit()
os.Exit(3) os.Exit(3)
} }
@@ -542,7 +553,7 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
app.ui.echoerrf("running shell: %s", err) app.ui.echoerrf("running shell: %s", err)
} }
if pauseAfter { if pauseAfter {
anyKey() app.ui.anyKey()
} }
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
+5 -3
View File
@@ -31,7 +31,7 @@ func run() {
if gLogPath != "" { if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600) f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
if err != nil { if err != nil {
log.Fatalf("failed to open log file: %s", err) log.Fatalf("opening log file: %s", err)
} }
defer f.Close() defer f.Close()
log.SetOutput(f) log.SetOutput(f)
@@ -108,7 +108,7 @@ func printPath(label, path string, stdoutIsTerminal bool) {
func writeLastDir(filename, lastDir string) { func writeLastDir(filename, lastDir string) {
if strings.ContainsAny(lastDir, "\n\r") { if strings.ContainsAny(lastDir, "\n\r") {
log.Printf("last-dir: path contains newline: %q", lastDir) log.Printf("last-dir: skipping path with newline: %q", lastDir)
return return
} }
f, err := os.Create(filename) f, err := os.Create(filename)
@@ -153,7 +153,7 @@ func readExpr() <-chan expr {
c, err := net.Dial("unix", gSocketPath) c, err := net.Dial("unix", gSocketPath)
for err != nil { for err != nil {
log.Printf("connecting server: %s", err) log.Printf("connecting to server (retrying in %s): %s", duration, err)
time.Sleep(duration) time.Sleep(duration)
duration *= 2 duration *= 2
c, err = net.Dial("unix", gSocketPath) c, err = net.Dial("unix", gSocketPath)
@@ -187,6 +187,8 @@ func readExpr() <-chan expr {
p := newParser(strings.NewReader(s.Text())) p := newParser(strings.NewReader(s.Text()))
if p.parse() { if p.parse() {
ch <- p.expr ch <- p.expr
} else if p.err != nil {
ch <- &callExpr{"echoerr", []string{p.err.Error()}, 1}
} }
} }
} }
+20 -10
View File
@@ -127,8 +127,7 @@ var (
func getOptWords(opts any) (optWords []string) { func getOptWords(opts any) (optWords []string) {
t := reflect.TypeOf(opts) t := reflect.TypeOf(opts)
for i := range t.NumField() { for field := range t.Fields() {
field := t.Field(i)
switch field.Type.Kind() { switch field.Type.Kind() {
case reflect.Map: case reflect.Map:
continue continue
@@ -145,8 +144,7 @@ func getOptWords(opts any) (optWords []string) {
func getLocalOptWords(localOpts any) (localOptWords []string) { func getLocalOptWords(localOpts any) (localOptWords []string) {
t := reflect.TypeOf(localOpts) t := reflect.TypeOf(localOpts)
for i := range t.NumField() { for field := range t.Fields() {
field := t.Field(i)
name := field.Name name := field.Name
if field.Type.Kind() != reflect.Map { if field.Type.Kind() != reflect.Map {
continue continue
@@ -203,6 +201,18 @@ func matchWord(s string, words []string) (matches []compMatch, longest string) {
return return
} }
func matchOpt(s string, words []string) (matches []compMatch, longest string) {
matches, longest = matchWord(s, words)
if strings.HasPrefix(s, "no") {
// Show negated options without their prefix in the menu.
// TODO: Update if a future option ever starts with "no".
for i := range matches {
matches[i].name = matches[i].name[2:]
}
}
return
}
func matchList(s string, words []string) (matches []compMatch, longest string) { func matchList(s string, words []string) (matches []compMatch, longest string) {
toks := strings.Split(s, ":") toks := strings.Split(s, ":")
@@ -248,7 +258,7 @@ func matchFile(s string, dirOnly bool, escape, unescape func(string) string) (ma
} }
files, err := os.ReadDir(d) files, err := os.ReadDir(d)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("completing path: %s", err)
longest = s longest = s
return return
} }
@@ -318,7 +328,7 @@ func matchExec(s string) (matches []compMatch, longest string) {
files, err := os.ReadDir(p) files, err := os.ReadDir(p)
if err != nil { if err != nil {
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
log.Printf("reading path: %s", err) log.Printf("completing shell command: %s", err)
} }
continue continue
} }
@@ -330,7 +340,7 @@ func matchExec(s string) (matches []compMatch, longest string) {
finfo, err := f.Info() finfo, err := f.Info()
if err != nil { if err != nil {
log.Printf("getting file information: %s", err) log.Printf("completing shell command: %s", err)
continue continue
} }
@@ -348,7 +358,7 @@ func matchExec(s string) (matches []compMatch, longest string) {
func matchSearch(s string) (matches []compMatch, longest string) { func matchSearch(s string) (matches []compMatch, longest string) {
files, err := os.ReadDir(".") files, err := os.ReadDir(".")
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("completing search: %s", err)
longest = s longest = s
return return
} }
@@ -386,7 +396,7 @@ func completeCmd(s string) (matches []compMatch, longest string) {
switch f[0] { switch f[0] {
case "set": case "set":
if len(f) == 2 { if len(f) == 2 {
matches, longest = matchWord(f[1], gOptWords) matches, longest = matchOpt(f[1], gOptWords)
break break
} }
if len(f) != 3 { if len(f) != 3 {
@@ -422,7 +432,7 @@ func completeCmd(s string) (matches []compMatch, longest string) {
break break
} }
if len(f) == 3 { if len(f) == 3 {
matches, longest = matchWord(f[2], gLocalOptWords) matches, longest = matchOpt(f[2], gLocalOptWords)
break break
} }
if len(f) != 4 { if len(f) != 4 {
+8 -4
View File
@@ -140,8 +140,8 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
return nil return nil
} }
newPath := filepath.Join(dst, rel) newPath := filepath.Join(dst, rel)
switch { switch info.Mode() & os.ModeType {
case info.IsDir(): case os.ModeDir:
dstMode := os.ModePerm dstMode := os.ModePerm
if slices.Contains(preserve, "mode") { if slices.Contains(preserve, "mode") {
dstMode = info.Mode() dstMode = info.Mode()
@@ -153,7 +153,7 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
dirInfos[newPath] = info dirInfos[newPath] = info
} }
nums <- info.Size() nums <- info.Size()
case info.Mode()&os.ModeSymlink != 0: case os.ModeSymlink:
if rlink, err := os.Readlink(path); err != nil { if rlink, err := os.Readlink(path); err != nil {
errs <- fmt.Errorf("symlink: %w", err) errs <- fmt.Errorf("symlink: %w", err)
} else { } else {
@@ -162,8 +162,12 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
} }
} }
nums <- info.Size() nums <- info.Size()
default: case 0:
copyFile(path, newPath, preserve, info, nums, errs) copyFile(path, newPath, preserve, info, nums, errs)
default:
// pipes, sockets and devices cannot be copied like regular files
errs <- fmt.Errorf("cannot copy irregular file %s (named pipe, socket or device)", path)
nums <- info.Size()
} }
return nil return nil
}) })
+5 -3
View File
@@ -20,7 +20,7 @@ lf - terminal file manager
[**-server**] [**-server**]
[**-single**] [**-single**]
[**-version**] [**-version**]
[*cd-or-select-path*] [*path*]
# DESCRIPTION # DESCRIPTION
@@ -36,7 +36,7 @@ A man page with the same content is also available in the repository at https://
## POSITIONAL ARGUMENTS ## POSITIONAL ARGUMENTS
**cd-or-select-path** **path**
Set the starting location. If *path* is a directory, start in there. If it's a file, start in the file's parent directory and select the file. When no *path* is supplied, lf uses the current directory. Only accepts one argument. Set the starting location. If *path* is a directory, start in there. If it's a file, start in the file's parent directory and select the file. When no *path* is supplied, lf uses the current directory. Only accepts one argument.
@@ -522,7 +522,8 @@ A custom `open` command can be defined to override this default.
## jump-next (default `]`), jump-prev (default `[`) ## jump-next (default `]`), jump-prev (default `[`)
Change the current working directory to the next/previous jumplist item. Change the current working directory to the next/previous entry in the jump list.
The jump list is a history of directories visited during the current session.
## top (default `gg` and `<home>`), bottom (default `G` and `<end>`) ## top (default `gg` and `<home>`), bottom (default `G` and `<end>`)
@@ -674,6 +675,7 @@ Print given arguments to the message line at the bottom as `errorfmt` and also t
## cd ## cd
Change the working directory to the given argument. Change the working directory to the given argument.
If the argument is `-`, change to the previous directory stored in the special bookmark `'`.
## select ## select
+7 -4
View File
@@ -7,7 +7,7 @@ SYNOPSIS
lf [-command command] [-config path] [-cpuprofile path] [-doc] [-help] lf [-command command] [-config path] [-cpuprofile path] [-doc] [-help]
[-last-dir-path path] [-log path] [-memprofile path] [-print-last-dir] [-last-dir-path path] [-log path] [-memprofile path] [-print-last-dir]
[-print-selection] [-remote command] [-selection-path path] [-server] [-print-selection] [-remote command] [-selection-path path] [-server]
[-single] [-version] [cd-or-select-path] [-single] [-version] [path]
DESCRIPTION DESCRIPTION
@@ -26,7 +26,7 @@ OPTIONS
POSITIONAL ARGUMENTS POSITIONAL ARGUMENTS
cd-or-select-path path
Set the starting location. If path is a directory, start in there. Set the starting location. If path is a directory, start in there.
If it's a file, start in the file's parent directory and select the If it's a file, start in the file's parent directory and select the
@@ -542,7 +542,9 @@ override this default.
jump-next (default ]), jump-prev (default [) jump-next (default ]), jump-prev (default [)
Change the current working directory to the next/previous jumplist item. Change the current working directory to the next/previous entry in the
jump list. The jump list is a history of directories visited during the
current session.
top (default gg and <home>), bottom (default G and <end>) top (default gg and <home>), bottom (default G and <end>)
@@ -707,7 +709,8 @@ also to the log file.
cd cd
Change the working directory to the given argument. Change the working directory to the given argument. If the argument is
-, change to the previous directory stored in the special bookmark '.
select select
+26 -13
View File
@@ -154,9 +154,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil { if err == nil {
app.nav.sort() app.nav.sort()
} }
// DEPRECATED: remove after r42 is released
case "roundbox", "noroundbox", "roundbox!":
app.ui.echoerr("option 'roundbox' is deprecated, use 'borderstyle' instead")
case "showbinds", "noshowbinds", "showbinds!": case "showbinds", "noshowbinds", "showbinds!":
err = applyBoolOpt(&gOpts.showbinds, e) err = applyBoolOpt(&gOpts.showbinds, e)
case "smartcase", "nosmartcase", "smartcase!": case "smartcase", "nosmartcase", "smartcase!":
@@ -789,7 +786,7 @@ func resetIncCmd(app *app) {
dir := app.nav.currDir() dir := app.nav.currDir()
old := dir.ind old := dir.ind
if err := app.nav.setFilter(app.nav.prevFilter); err != nil { if err := app.nav.setFilter(app.nav.prevFilter); err != nil {
log.Printf("reset filter: %s", err) log.Printf("resetting filter: %s", err)
} else if old != dir.ind { } else if old != dir.ind {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
} }
@@ -992,13 +989,20 @@ func insert(app *app, arg string) {
} }
func cd(app *app, path string) error { func cd(app *app, path string) error {
wd := app.nav.currDir().path if path == "-" {
prev, ok := app.nav.marks["'"]
if !ok {
return errors.New("no previous directory")
}
path = prev
}
path, err := filepath.Abs(replaceTilde(path)) path, err := filepath.Abs(replaceTilde(path))
if err != nil { if err != nil {
return fmt.Errorf("getting absolute path: %w", err) return fmt.Errorf("getting absolute path: %w", err)
} }
wd := app.nav.currDir().path
if path == wd { if path == wd {
return nil return nil
} }
@@ -1007,7 +1011,7 @@ func cd(app *app, path string) error {
preChdir(app) preChdir(app)
if err := app.nav.cd(path); err != nil { if err := app.nav.cd(path); err != nil {
return fmt.Errorf("changing directory: %w", err) return err
} }
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
@@ -1049,7 +1053,7 @@ func (e *callExpr) eval(app *app, _ []string) {
switch e.name { switch e.name {
case "quit": case "quit":
app.quitChan <- struct{}{} app.requestQuit()
case "up": case "up":
if app.nav.up(e.count) { if app.nav.up(e.count) {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
@@ -1105,7 +1109,7 @@ func (e *callExpr) eval(app *app, _ []string) {
preChdir(app) preChdir(app)
err := app.nav.open() err := app.nav.open()
if err != nil { if err != nil {
app.ui.echoerrf("opening directory: %s", err) app.ui.echoerrf("open: %s", err)
return return
} }
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
@@ -1114,7 +1118,7 @@ func (e *callExpr) eval(app *app, _ []string) {
} else { } else {
if gSelectionPath != "" || gPrintSelection { if gSelectionPath != "" || gPrintSelection {
app.selectionOut, _ = app.nav.currFileOrSelections() app.selectionOut, _ = app.nav.currFileOrSelections()
app.quitChan <- struct{}{} app.requestQuit()
return return
} }
@@ -1278,6 +1282,8 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerrf("sync: %s", err) app.ui.echoerrf("sync: %s", err)
} }
case "draw": case "draw":
// Input handlers return this no-op instead of nil to
// trigger the screen update performed by [app.loop].
case "redraw": case "redraw":
app.ui.screen.Sync() app.ui.screen.Sync()
app.ui.renew() app.ui.renew()
@@ -1499,6 +1505,7 @@ func (e *callExpr) eval(app *app, _ []string) {
return return
} }
normal(app) normal(app)
app.ui.menu = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-save: " app.ui.cmdPrefix = "mark-save: "
case "mark-load": case "mark-load":
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
@@ -1600,7 +1607,13 @@ func (e *callExpr) eval(app *app, _ []string) {
if dir.loading { if dir.loading {
dir.files = append(dir.files, &file{FileInfo: lstat}) dir.files = append(dir.files, &file{FileInfo: lstat})
} }
dir.sel(filepath.Base(path), app.nav.height) name := filepath.Base(path)
for i, f := range dir.files {
if f.Name() == name {
app.nav.move(i)
break
}
}
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
case "source": case "source":
if len(e.args) != 1 { if len(e.args) != 1 {
@@ -1613,7 +1626,7 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerr("push: requires an argument") app.ui.echoerr("push: requires an argument")
return return
} }
log.Println("pushing keys", e.args[0]) log.Printf("pushing keys: %s", e.args[0])
for _, val := range splitKeys(e.args[0]) { for _, val := range splitKeys(e.args[0]) {
app.ui.evChan <- parseKey(val) app.ui.evChan <- parseKey(val)
} }
@@ -1677,7 +1690,7 @@ func (e *callExpr) eval(app *app, _ []string) {
tty, ok := app.ui.screen.Tty() tty, ok := app.ui.screen.Tty()
if !ok { if !ok {
log.Print("tty-write: failed to get tty") log.Print("tty-write: no tty available")
return return
} }
@@ -1901,7 +1914,7 @@ func (e *callExpr) eval(app *app, _ []string) {
} }
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
default: default:
log.Printf("entering unknown execution prefix: %q", app.ui.cmdPrefix) log.Printf("unknown execution prefix: %q", app.ui.cmdPrefix)
} }
case "cmd-interrupt": case "cmd-interrupt":
if app.cmd != nil { if app.cmd != nil {
+37
View File
@@ -84,6 +84,18 @@ var gEvalTests = []struct {
[]expr{&callExpr{"echo", []string{"hello\101world"}, 1}}, []expr{&callExpr{"echo", []string{"hello\101world"}, 1}},
}, },
{
`echo "hello\1011world"`,
[]string{"echo", "hello\1011world", "\n"},
[]expr{&callExpr{"echo", []string{"hello\1011world"}, 1}},
},
{
`tty-write "\0337\0338"`,
[]string{"tty-write", "\0337\0338", "\n"},
[]expr{&callExpr{"tty-write", []string{"\0337\0338"}, 1}},
},
{ {
`echo hello\ world`, `echo hello\ world`,
[]string{"echo", "hello world", "\n"}, []string{"echo", "hello world", "\n"},
@@ -661,3 +673,28 @@ func TestApplyLocalBoolOpt(t *testing.T) {
} }
} }
} }
func TestParseErrors(t *testing.T) {
for _, test := range []struct{ inp, err string }{
{`set dupfilefmt %f.~%n~`, `set dupfilefmt: value starting with "%" must be quoted`},
{`setlocal /tmp info $x`, `setlocal /tmp info: value starting with "$" must be quoted`},
{"set", "set: expected option"},
{"setlocal", "setlocal: expected directory"},
{"setlocal /tmp", "setlocal /tmp: expected option"},
{"map x :{{ set hidden }}", `set hidden: unexpected "}}"`},
{"map x ${{ echo", `missing "}}"`},
{"map x :{{\n echo", `missing "}}"`},
{"}}", `unexpected "}}"`},
} {
p := newParser(strings.NewReader(test.inp))
if p.parse() || p.err == nil || p.err.Error() != test.err {
t.Errorf("parse(%q) got error %v, want %q", test.inp, p.err, test.err)
}
}
for _, inp := range []string{`set dupfilefmt "%f.~%n~"`, `set hidden!`, "set hidden", "map x :{{ set hidden; }}", "map x ${{ echo hi }}"} {
p := newParser(strings.NewReader(inp))
if !p.parse() || p.err != nil {
t.Errorf("parse(%q) rejected: %v", inp, p.err)
}
}
}
+6 -6
View File
@@ -1,19 +1,19 @@
module github.com/gokcehan/lf module github.com/gokcehan/lf
go 1.25.0 go 1.26.0
require ( require (
github.com/clipperhouse/displaywidth v0.11.0 github.com/clipperhouse/displaywidth v0.11.0
github.com/djherbis/times v1.6.0 github.com/djherbis/times v1.6.0
github.com/fsnotify/fsnotify v1.10.1 github.com/fsnotify/fsnotify v1.10.1
github.com/gdamore/tcell/v3 v3.4.1 github.com/gdamore/tcell/v3 v3.6.0
golang.org/x/sys v0.47.0 golang.org/x/sys v0.50.0
golang.org/x/term v0.45.0 golang.org/x/term v0.47.0
) )
require ( require (
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/gdamore/encoding v1.0.1 // indirect github.com/gdamore/encoding v1.0.1 // indirect
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
golang.org/x/text v0.40.0 // indirect golang.org/x/text v0.42.0 // indirect
) )
+10 -10
View File
@@ -8,10 +8,10 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= 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/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo=
github.com/gdamore/tcell/v3 v3.4.1 h1:22227t1EUwqxTlmCX9vw0RUE2IEPGw6oYcNan+bPe4w= github.com/gdamore/tcell/v3 v3.6.0 h1:jW20qS6Tm38KVDqLHq9KWSvyjNl00FbhbD8rIAnHBws=
github.com/gdamore/tcell/v3 v3.4.1/go.mod h1:YWwuxZNi14VGQC5g2VGNEDRXpBraTwvVjMovRH6G6hw= github.com/gdamore/tcell/v3 v3.6.0/go.mod h1:CBZxkl2T+XxEyuBfOh4zaahqm27dngvhfBfCCZxJsgc=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4= github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 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-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.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
@@ -31,20 +31,20 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0= golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w= golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 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.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.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+9 -5
View File
@@ -1,6 +1,6 @@
.\" Automatically generated by Pandoc 3.7.0.2 .\" Automatically generated by Pandoc 3.7.0.2
.\" .\"
.TH "LF" "1" "2026\-07\-31" "r42" "DOCUMENTATION" .TH "LF" "1" "2026\-10\-29" "r43" "DOCUMENTATION"
.SH NAME .SH NAME
lf \- terminal file manager lf \- terminal file manager
.SH SYNOPSIS .SH SYNOPSIS
@@ -11,8 +11,7 @@ lf \- terminal file manager
\f[I]path\f[R]] [\f[B]\-print\-last\-dir\f[R]] \f[I]path\f[R]] [\f[B]\-print\-last\-dir\f[R]]
[\f[B]\-print\-selection\f[R]] [\f[B]\-remote\f[R] \f[I]command\f[R]] [\f[B]\-print\-selection\f[R]] [\f[B]\-remote\f[R] \f[I]command\f[R]]
[\f[B]\-selection\-path\f[R] \f[I]path\f[R]] [\f[B]\-server\f[R]] [\f[B]\-selection\-path\f[R] \f[I]path\f[R]] [\f[B]\-server\f[R]]
[\f[B]\-single\f[R]] [\f[B]\-version\f[R]] [\f[B]\-single\f[R]] [\f[B]\-version\f[R]] [\f[I]path\f[R]]
[\f[I]cd\-or\-select\-path\f[R]]
.SH DESCRIPTION .SH DESCRIPTION
lf is a terminal file manager. lf is a terminal file manager.
.PP .PP
@@ -33,7 +32,7 @@ A man page with the same content is also available in the repository at
.SH OPTIONS .SH OPTIONS
.SS POSITIONAL ARGUMENTS .SS POSITIONAL ARGUMENTS
.TP .TP
\f[B]cd\-or\-select\-path\f[R] \f[B]path\f[R]
Set the starting location. Set the starting location.
If \f[I]path\f[R] is a directory, start in there. If \f[I]path\f[R] is a directory, start in there.
If it\(aqs a file, start in the file\(aqs parent directory and select If it\(aqs a file, start in the file\(aqs parent directory and select
@@ -570,7 +569,10 @@ opener asynchronously with the current file as the argument.
A custom \f[CR]open\f[R] command can be defined to override this A custom \f[CR]open\f[R] command can be defined to override this
default. default.
.SS jump\-next (default \f[CR]]\f[R]), jump\-prev (default \f[CR][\f[R]) .SS jump\-next (default \f[CR]]\f[R]), jump\-prev (default \f[CR][\f[R])
Change the current working directory to the next/previous jumplist item. Change the current working directory to the next/previous entry in the
jump list.
The jump list is a history of directories visited during the current
session.
.SS top (default \f[CR]gg\f[R] and \f[CR]<home>\f[R]), bottom (default \f[CR]G\f[R] and \f[CR]<end>\f[R]) .SS top (default \f[CR]gg\f[R] and \f[CR]<home>\f[R]), bottom (default \f[CR]G\f[R] and \f[CR]<end>\f[R])
Move the current file selection to the top/bottom of the directory. Move the current file selection to the top/bottom of the directory.
A count can be specified to move to a specific line, for example, use A count can be specified to move to a specific line, for example, use
@@ -677,6 +679,8 @@ Print given arguments to the message line at the bottom as
\f[CR]errorfmt\f[R] and also to the log file. \f[CR]errorfmt\f[R] and also to the log file.
.SS cd .SS cd
Change the working directory to the given argument. Change the working directory to the given argument.
If the argument is \f[CR]\-\f[R], change to the previous directory
stored in the special bookmark \f[CR]\(aq\f[R].
.SS select .SS select
Change the current file selection to the given argument. Change the current file selection to the given argument.
.SS source .SS source
+9 -7
View File
@@ -82,7 +82,7 @@ func exportEnvVars() {
level, err := strconv.Atoi(envLevel) level, err := strconv.Atoi(envLevel)
if err != nil { if err != nil {
log.Printf("reading lf level: %s", err) log.Printf("parsing $LF_LEVEL: %s", err)
} }
level++ level++
@@ -183,7 +183,7 @@ func checkServer() {
startServer() startServer()
} else if _, err := net.Dial("unix", gSocketPath); err != nil { } else if _, err := net.Dial("unix", gSocketPath); err != nil {
if err := os.Remove(gSocketPath); err != nil { if err := os.Remove(gSocketPath); err != nil {
log.Print(err) log.Printf("removing socket: %s", err)
} }
startServer() startServer()
} }
@@ -225,10 +225,11 @@ func main() {
f := flag.CommandLine.Output() f := flag.CommandLine.Output()
fmt.Fprintf(f, `lf - Terminal file manager fmt.Fprintf(f, `lf - Terminal file manager
Usage: %s [options] [cd-or-select-path] Usage: %s [options] [path]
cd-or-select-path Arguments:
set the initial dir or file selection to the given argument path
set the initial directory or select the given file
Options: Options:
`, os.Args[0]) `, os.Args[0])
@@ -349,7 +350,8 @@ Options:
if term.IsTerminal(int(os.Stdout.Fd())) { if term.IsTerminal(int(os.Stdout.Fd())) {
lines := strings.Split(resp, "\n") lines := strings.Split(resp, "\n")
for i := range lines { for i := range lines {
lines[i] = sanitizeName(lines[i]) // using sanitizePreview instead of sanitizeName here to preserve tabs for printed tables
lines[i] = sanitizePreview(lines[i])
} }
resp = strings.Join(lines, "\n") resp = strings.Join(lines, "\n")
} }
@@ -380,7 +382,7 @@ Options:
case 1: case 1:
gSelect = flag.Arg(0) gSelect = flag.Arg(0)
default: default:
fmt.Fprintln(os.Stderr, "only single file or directory is allowed") fmt.Fprintln(os.Stderr, "only one file or directory may be specified")
os.Exit(2) os.Exit(2)
} }
+9 -8
View File
@@ -11,7 +11,6 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv"
"strings" "strings"
"unicode" "unicode"
@@ -32,8 +31,8 @@ var (
func isRoot(name string) bool { return filepath.Dir(name) == name } func isRoot(name string) bool { return filepath.Dir(name) == name }
func replaceTilde(s string) string { func replaceTilde(s string) string {
if strings.HasPrefix(s, "~") { if rest, ok := strings.CutPrefix(s, "~"); ok && (rest == "" || os.IsPathSeparator(rest[0])) {
return gUser.HomeDir + s[1:] return gUser.HomeDir + rest
} }
return s return s
} }
@@ -393,16 +392,18 @@ func naturalCmp(s1, s2 string) int {
tok2 := s2[lo2:hi2] tok2 := s2[lo2:hi2]
if isDigit1 && isDigit2 { if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(tok1) // compare the digits directly instead of parsing them, so that
num2, err2 := strconv.Atoi(tok2) // numbers too large for an int are still ordered by value
if err1 == nil && err2 == nil { num1 := strings.TrimLeft(tok1, "0")
if num1 != num2 { num2 := strings.TrimLeft(tok2, "0")
if len(num1) != len(num2) {
return cmp.Compare(len(num1), len(num2))
} else if num1 != num2 {
return cmp.Compare(num1, num2) return cmp.Compare(num1, num2)
} else if len(tok1) != len(tok2) { } else if len(tok1) != len(tok2) {
return cmp.Compare(len(tok1), len(tok2)) return cmp.Compare(len(tok1), len(tok2))
} }
} }
}
if tok1 != tok2 { if tok1 != tok2 {
return cmp.Compare(tok1, tok2) return cmp.Compare(tok1, tok2)
+6
View File
@@ -399,6 +399,12 @@ func TestNaturalCmp(t *testing.T) {
{"foo0bar", "foo00bar", -1}, {"foo0bar", "foo00bar", -1},
{"foo1", "foo01", -1}, {"foo1", "foo01", -1},
{"foo1bar", "foo01bar", -1}, {"foo1bar", "foo01bar", -1},
{"9", "10000000000000000000", -1},
{"foo9", "foo10000000000000000000", -1},
{"9223372036854775807", "9223372036854775808", -1},
{"99999999999999999999", "100000000000000000000", -1},
{"100000000000000000000", "0100000000000000000000", -1},
{"100000000000000000000a", "100000000000000000000b", -1},
} }
for _, test := range tests { for _, test := range tests {
+41 -22
View File
@@ -48,7 +48,7 @@ type file struct {
func newFile(path string) *file { func newFile(path string) *file {
lstat, err := os.Lstat(path) lstat, err := os.Lstat(path)
if err != nil { if err != nil {
log.Printf("getting file information: %s", err) log.Printf("getting file info: %s", err)
return &file{ return &file{
FileInfo: &fakeStat{name: filepath.Base(path)}, FileInfo: &fakeStat{name: filepath.Base(path)},
linkState: notLink, linkState: notLink,
@@ -100,13 +100,13 @@ func newFile(path string) *file {
if lstat.IsDir() && getDirCounts(filepath.Dir(path)) { if lstat.IsDir() && getDirCounts(filepath.Dir(path)) {
d, err := os.Open(path) d, err := os.Open(path)
if err != nil { if err != nil {
log.Printf("opening file: %s", err) log.Printf("counting directory entries: %s", err)
} else { } else {
names, err := d.Readdirnames(10000) names, err := d.Readdirnames(10000)
d.Close() d.Close()
if names == nil && err != io.EOF { if names == nil && err != io.EOF {
log.Printf("reading directory: %s", err) log.Printf("counting directory entries: %s", err)
} else { } else {
dirCount = len(names) dirCount = len(names)
} }
@@ -797,8 +797,7 @@ func (nav *nav) previewLoop(ui *ui) {
cmd.Stderr = &stderr cmd.Stderr = &stderr
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError if _, ok := errors.AsType[*exec.ExitError](err); !ok {
if !errors.As(err, &exitErr) {
log.Printf("cleaning preview: %s", err) log.Printf("cleaning preview: %s", err)
} }
} }
@@ -905,16 +904,15 @@ func (nav *nav) preview(path string, win *win, mode string) {
defer func() { defer func() {
if err := cmd.Wait(); err != nil { if err := cmd.Wait(); err != nil {
var exitErr *exec.ExitError if _, ok := errors.AsType[*exec.ExitError](err); ok {
if errors.As(err, &exitErr) {
reg.volatile = true reg.volatile = true
} else { } else {
log.Printf("loading file: %s", err) log.Printf("previewing file: %s", err)
} }
} }
if s := strings.TrimSpace(stderr.String()); s != "" { if s := strings.TrimSpace(stderr.String()); s != "" {
s = strings.Join(strings.Fields(s), " ") s = strings.Join(strings.Fields(s), " ")
log.Printf("loading file (stderr): %s", s) log.Printf("previewing file (stderr): %s", s)
} }
}() }()
defer out.Close() defer out.Close()
@@ -922,7 +920,7 @@ func (nav *nav) preview(path string, win *win, mode string) {
} else { } else {
lstat, err := os.Lstat(path) lstat, err := os.Lstat(path)
if err != nil { if err != nil {
log.Printf("lstat: %s", err) log.Printf("previewing file: %s", err)
return return
} }
@@ -932,7 +930,7 @@ func (nav *nav) preview(path string, win *win, mode string) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
log.Printf("opening file: %s", err) log.Printf("previewing file: %s", err)
return return
} }
@@ -1153,7 +1151,7 @@ func (nav *nav) open() error {
} }
if err := os.Chdir(curr.path); err != nil { if err := os.Chdir(curr.path); err != nil {
return fmt.Errorf("open: %w", err) return err
} }
nav.dirPaths = append(nav.dirPaths, curr.path) nav.dirPaths = append(nav.dirPaths, curr.path)
@@ -1816,7 +1814,7 @@ func isFiltered(f os.FileInfo, filter []string) bool {
for _, pattern := range filter { for _, pattern := range filter {
matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.filtermethod) matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.filtermethod)
if err != nil { if err != nil {
log.Printf("Filter Error: %s", err) log.Printf("applying filter: %s", err)
return false return false
} }
if strings.HasPrefix(pattern, "!") && matched { if strings.HasPrefix(pattern, "!") && matched {
@@ -1851,7 +1849,8 @@ func (nav *nav) readMarks() error {
for scanner.Scan() { for scanner.Scan() {
mark, path, found := strings.Cut(scanner.Text(), ":") mark, path, found := strings.Cut(scanner.Text(), ":")
if !found { if !found {
return fmt.Errorf("invalid marks file entry: %s", scanner.Text()) err = fmt.Errorf("invalid marks file entry: %q", scanner.Text())
continue
} }
if _, ok := nav.marks[mark]; !ok { if _, ok := nav.marks[mark]; !ok {
nav.marks[mark] = path nav.marks[mark] = path
@@ -1862,7 +1861,7 @@ func (nav *nav) readMarks() error {
return fmt.Errorf("reading marks file: %w", err) return fmt.Errorf("reading marks file: %w", err)
} }
return nil return err
} }
func (nav *nav) writeMarks() error { func (nav *nav) writeMarks() error {
@@ -1910,7 +1909,8 @@ func (nav *nav) readTags() error {
ind := strings.LastIndex(text, ":") ind := strings.LastIndex(text, ":")
if ind == -1 { if ind == -1 {
return fmt.Errorf("invalid tags file entry: %s", text) err = fmt.Errorf("invalid tags file entry: %q", text)
continue
} }
path := text[0:ind] path := text[0:ind]
@@ -1924,7 +1924,7 @@ func (nav *nav) readTags() error {
return fmt.Errorf("reading tags file: %w", err) return fmt.Errorf("reading tags file: %w", err)
} }
return nil return err
} }
func (nav *nav) writeTags() error { func (nav *nav) writeTags() error {
@@ -2007,15 +2007,32 @@ func (nav *nav) currFileOrSelections() ([]string, error) {
return nil, errors.New("no file selected") return nil, errors.New("no file selected")
} }
// calcSize returns the total size of the given directory. Symlinks pointing to
// directories are resolved beforehand, since `copySize` does not follow them.
func calcSize(f *file) (int64, error) {
path := f.path
if f.linkState == working {
var err error
path, err = filepath.EvalSymlinks(f.path)
if err != nil {
return 0, err
}
}
return copySize([]string{path})
}
func (nav *nav) calcDirSize() error { func (nav *nav) calcDirSize() error {
calc := func(f *file) error { calc := func(f *file) error {
if f.IsDir() { if !f.IsDir() {
total, err := copySize([]string{f.path}) return nil
}
total, err := calcSize(f)
if err != nil { if err != nil {
return err return err
} }
f.dirSize = total f.dirSize = total
}
return nil return nil
} }
@@ -2028,8 +2045,10 @@ func (nav *nav) calcDirSize() error {
} }
for sel := range nav.selections { for sel := range nav.selections {
lstat, err := os.Lstat(sel) // `os.Stat` is used instead of `os.Lstat` so that symlinks pointing to
if err != nil || !lstat.IsDir() { // directories are not skipped.
stat, err := os.Stat(sel)
if err != nil || !stat.IsDir() {
continue continue
} }
path, name := filepath.Dir(sel), filepath.Base(sel) path, name := filepath.Dir(sel), filepath.Base(sel)
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestDirSize(t *testing.T) {
tmp := t.TempDir()
dir := filepath.Join(tmp, "dir")
if err := os.Mkdir(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "file"), make([]byte, 4096), 0o644); err != nil {
t.Fatal(err)
}
link := filepath.Join(tmp, "link")
if err := os.Symlink(dir, link); err != nil {
t.Skipf("creating symlink: %s", err)
}
expected, err := calcSize(newFile(dir))
if err != nil {
t.Fatal(err)
}
got, err := calcSize(newFile(link))
if err != nil {
t.Fatal(err)
}
if got != expected {
t.Errorf("at symlink to directory expected %d but got %d", expected, got)
}
}
+35 -4
View File
@@ -231,12 +231,21 @@ func (p *parser) parseExpr() expr {
s.scan() s.scan()
if s.typ != tokenIdent { if s.typ != tokenIdent {
p.err = fmt.Errorf("expected identifier: %s", s.tok) p.err = fmt.Errorf("set: expected option")
return nil
} }
opt := s.tok opt := s.tok
s.scan() s.scan()
if s.typ != tokenSemicolon { if s.typ != tokenSemicolon {
if s.typ == tokenPrefix || s.typ == tokenColon {
p.err = fmt.Errorf("set %s: value starting with %q must be quoted", opt, s.tok)
return nil
}
if s.typ != tokenIdent {
p.err = fmt.Errorf("set %s: unexpected %q", opt, s.tok)
return nil
}
val = s.tok val = s.tok
s.scan() s.scan()
} }
@@ -249,18 +258,28 @@ func (p *parser) parseExpr() expr {
s.scan() s.scan()
if s.typ != tokenIdent { if s.typ != tokenIdent {
p.err = fmt.Errorf("expected directory: %s", s.tok) p.err = fmt.Errorf("setlocal: expected directory")
return nil
} }
dir := s.tok dir := s.tok
s.scan() s.scan()
if s.typ != tokenIdent { if s.typ != tokenIdent {
p.err = fmt.Errorf("expected identifier: %s", s.tok) p.err = fmt.Errorf("setlocal %s: expected option", dir)
return nil
} }
opt := s.tok opt := s.tok
s.scan() s.scan()
if s.typ != tokenSemicolon { if s.typ != tokenSemicolon {
if s.typ == tokenPrefix || s.typ == tokenColon {
p.err = fmt.Errorf("setlocal %s %s: value starting with %q must be quoted", dir, opt, s.tok)
return nil
}
if s.typ != tokenIdent {
p.err = fmt.Errorf("setlocal %s %s: unexpected %q", dir, opt, s.tok)
return nil
}
val = s.tok val = s.tok
s.scan() s.scan()
} }
@@ -359,6 +378,9 @@ func (p *parser) parseExpr() expr {
for { for {
e := p.parseExpr() e := p.parseExpr()
if e == nil { if e == nil {
if p.err == nil {
p.err = fmt.Errorf(`missing "}}"`)
}
return nil return nil
} }
exprs = append(exprs, e) exprs = append(exprs, e)
@@ -391,6 +413,10 @@ func (p *parser) parseExpr() expr {
s.scan() s.scan()
if s.typ == tokenLBraces { if s.typ == tokenLBraces {
s.scan() s.scan()
if s.typ != tokenCommand {
p.err = fmt.Errorf(`missing "}}"`)
return nil
}
expr = s.tok expr = s.tok
s.scan() s.scan()
} else { } else {
@@ -402,7 +428,7 @@ func (p *parser) parseExpr() expr {
result = &execExpr{prefix, expr} result = &execExpr{prefix, expr}
default: default:
p.err = fmt.Errorf("unexpected token: %s", s.tok) p.err = fmt.Errorf("unexpected %q", s.tok)
} }
return result return result
@@ -410,5 +436,10 @@ func (p *parser) parseExpr() expr {
func (p *parser) parse() bool { func (p *parser) parse() bool {
p.expr = p.parseExpr() p.expr = p.parseExpr()
if p.err != nil {
// never evaluate an expression that produced a parse error
p.expr = nil
return false
}
return p.expr != nil return p.expr != nil
} }
+3 -1
View File
@@ -237,8 +237,10 @@ scan:
case s.chr == 'v': case s.chr == 'v':
buf = append(buf, '\v') buf = append(buf, '\v')
case isDigit(s.chr): case isDigit(s.chr):
// like C, an octal escape is at most three digits long
// so that "\0337" is read as "\033" followed by "7"
var oct []byte var oct []byte
for isDigit(s.chr) { for len(oct) < 3 && isDigit(s.chr) {
oct = append(oct, s.chr) oct = append(oct, s.chr)
s.next() s.next()
} }
+23 -14
View File
@@ -29,7 +29,7 @@ func serve() {
if gLogPath != "" { if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600) f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
if err != nil { if err != nil {
log.Fatalf("failed to open log file: %s", err) log.Fatalf("opening log file: %s", err)
} }
defer f.Close() defer f.Close()
log.SetOutput(f) log.SetOutput(f)
@@ -73,37 +73,46 @@ func manage() {
case "broadcast": case "broadcast":
for id, c2 := range connList { for id, c2 := range connList {
if _, err := fmt.Fprintln(c2, cmd.msg); err != nil { if _, err := fmt.Fprintln(c2, cmd.msg); err != nil {
echoerrf(cmd.c, "failed to send command to client %v: %s", id, err) echoerrf(cmd.c, "sending command to client %v: %s", id, err)
c2.Close()
delete(connList, id)
} }
} }
case "send": case "send":
if c2, ok := connList[cmd.id]; ok { if c2, ok := connList[cmd.id]; ok {
if _, err := fmt.Fprintln(c2, cmd.msg); err != nil { if _, err := fmt.Fprintln(c2, cmd.msg); err != nil {
echoerrf(cmd.c, "failed to send command to client %v: %s", cmd.id, err) echoerrf(cmd.c, "sending command to client %v: %s", cmd.id, err)
} }
} else { } else {
echoerr(cmd.c, "listen: send: no such client id is connected") echoerrf(cmd.c, "listen: send: no client with ID %v connected", cmd.id)
} }
case "query": case "query":
c2, ok := connList[cmd.id] c2, ok := connList[cmd.id]
if !ok { if !ok {
echoerr(cmd.c, "listen: query: no such client id is connected") echoerrf(cmd.c, "listen: query: no client with ID %v connected", cmd.id)
break break
} }
if _, err := fmt.Fprintln(c2, "query "+cmd.msg); err != nil { if _, err := fmt.Fprintln(c2, "query "+cmd.msg); err != nil {
echoerrf(cmd.c, "failed to send query to client %v: %s", cmd.id, err) echoerrf(cmd.c, "sending query to client %v: %s", cmd.id, err)
break break
} }
s2 := bufio.NewScanner(c2) s2 := bufio.NewScanner(c2)
for s2.Scan() && s2.Text() != "" { for s2.Scan() && s2.Text() != "" {
if _, err := fmt.Fprintln(cmd.c, s2.Text()); err != nil { if _, err := fmt.Fprintln(cmd.c, s2.Text()); err != nil {
log.Printf("failed to forward query response from client %v: %s", cmd.id, err) log.Printf("forwarding query response from client %v: %s", cmd.id, err)
} }
} }
if s2.Err() != nil { if s2.Err() != nil {
echoerrf(cmd.c, "failed to read query response from client %v: %s", cmd.id, s2.Err()) echoerrf(cmd.c, "reading query response from client %v: %s", cmd.id, s2.Err())
} }
case "quit": case "quit":
for id, c := range connList {
// an empty line is ignored by clients and exposes dead connections
if _, err := fmt.Fprintln(c, ""); err != nil {
c.Close()
delete(connList, id)
}
}
if len(connList) == 0 { if len(connList) == 0 {
gQuitChan <- struct{}{} gQuitChan <- struct{}{}
gListener.Close() gListener.Close()
@@ -171,25 +180,25 @@ Loop:
word2, _ := splitWord(rest) word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2) id, err := strconv.Atoi(word2)
if err != nil { if err != nil {
echoerr(c, "listen: conn: client id should be a number") echoerr(c, "listen: conn: client ID must be a number")
} else { } else {
send(srvCmd{op: "conn", id: id, c: c}) send(srvCmd{op: "conn", id: id, c: c})
return return
} }
} else { } else {
echoerr(c, "listen: conn: requires a client id") echoerr(c, "listen: conn: requires a client ID")
} }
case "drop": case "drop":
if rest != "" { if rest != "" {
word2, _ := splitWord(rest) word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2) id, err := strconv.Atoi(word2)
if err != nil { if err != nil {
echoerr(c, "listen: drop: client id should be a number") echoerr(c, "listen: drop: client ID must be a number")
} else { } else {
send(srvCmd{op: "drop", id: id}) send(srvCmd{op: "drop", id: id})
} }
} else { } else {
echoerr(c, "listen: drop: requires a client id") echoerr(c, "listen: drop: requires a client ID")
} }
case "list": case "list":
send(srvCmd{op: "list", c: c}) send(srvCmd{op: "list", c: c})
@@ -205,13 +214,13 @@ Loop:
} }
case "query": case "query":
if rest == "" { if rest == "" {
echoerr(c, "listen: query: requires a client id") echoerr(c, "listen: query: requires a client ID")
break break
} }
word2, rest2 := splitWord(rest) word2, rest2 := splitWord(rest)
id, err := strconv.Atoi(word2) id, err := strconv.Atoi(word2)
if err != nil { if err != nil {
echoerr(c, "listen: query: client id should be a number") echoerr(c, "listen: query: client ID must be a number")
break break
} }
send(srvCmd{op: "query", id: id, msg: rest2, c: c}) send(srvCmd{op: "query", id: id, msg: rest2, c: c})
+11 -5
View File
@@ -162,7 +162,7 @@ loop:
st = st.Underline(false) st = st.Underline(false)
case "4", "4:1": case "4", "4:1":
st = st.Underline(true) st = st.Underline(true)
case "4:2": case "4:2", "21":
st = st.Underline(tcell.UnderlineStyleDouble) st = st.Underline(tcell.UnderlineStyleDouble)
case "4:3": case "4:3":
st = st.Underline(tcell.UnderlineStyleCurly) st = st.Underline(tcell.UnderlineStyleCurly)
@@ -200,11 +200,13 @@ loop:
case "38": case "38":
color, offset, err := parseColor(toks[i+1:]) color, offset, err := parseColor(toks[i+1:])
if err != nil { if err != nil {
log.Printf("error processing ansi code 38: %s", err) log.Printf("processing ANSI code 38: %s", err)
break loop break loop
} }
st = st.Foreground(color) st = st.Foreground(color)
i += offset i += offset
case "39":
st = st.Foreground(tcell.ColorDefault)
case "40", "41", "42", "43", "44", "45", "46", "47": case "40", "41", "42", "43", "44", "45", "46", "47":
n, _ := strconv.Atoi(toks[i]) n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 40)) st = st.Background(tcell.PaletteColor(n - 40))
@@ -214,21 +216,25 @@ loop:
case "48": case "48":
color, offset, err := parseColor(toks[i+1:]) color, offset, err := parseColor(toks[i+1:])
if err != nil { if err != nil {
log.Printf("error processing ansi code 48: %s", err) log.Printf("processing ANSI code 48: %s", err)
break loop break loop
} }
st = st.Background(color) st = st.Background(color)
i += offset i += offset
case "49":
st = st.Background(tcell.ColorDefault)
case "58": case "58":
color, offset, err := parseColor(toks[i+1:]) color, offset, err := parseColor(toks[i+1:])
if err != nil { if err != nil {
log.Printf("error processing ansi code 58: %s", err) log.Printf("processing ANSI code 58: %s", err)
break loop break loop
} }
st = st.Underline(color) st = st.Underline(color)
i += offset i += offset
case "59":
st = st.Underline(tcell.ColorDefault)
default: default:
log.Printf("unknown ansi code: %s", toks[i]) log.Printf("unknown ANSI code: %s", toks[i])
} }
} }
+4
View File
@@ -230,6 +230,7 @@ func TestApplySGR(t *testing.T) {
{"4:0", none.Underline(true), none}, {"4:0", none.Underline(true), none},
{"4:1", none, none.Underline(true)}, {"4:1", none, none.Underline(true)},
{"4:2", none, none.Underline(tcell.UnderlineStyleDouble)}, {"4:2", none, none.Underline(tcell.UnderlineStyleDouble)},
{"21", none, none.Underline(tcell.UnderlineStyleDouble)},
{"4:3", none, none.Underline(tcell.UnderlineStyleCurly)}, {"4:3", none, none.Underline(tcell.UnderlineStyleCurly)},
{"4:4", none, none.Underline(tcell.UnderlineStyleDotted)}, {"4:4", none, none.Underline(tcell.UnderlineStyleDotted)},
{"4:5", none, none.Underline(tcell.UnderlineStyleDashed)}, {"4:5", none, none.Underline(tcell.UnderlineStyleDashed)},
@@ -244,9 +245,11 @@ func TestApplySGR(t *testing.T) {
{"31", none, none.Foreground(color.Maroon)}, {"31", none, none.Foreground(color.Maroon)},
{"31", none.Foreground(color.Green), none.Foreground(color.Maroon)}, {"31", none.Foreground(color.Green), none.Foreground(color.Maroon)},
{"31", none.Foreground(color.Green).Bold(true), none.Foreground(color.Maroon).Bold(true)}, {"31", none.Foreground(color.Green).Bold(true), none.Foreground(color.Maroon).Bold(true)},
{"39", none.Foreground(color.Maroon).Bold(true), none.Bold(true)},
{"41", none, none.Background(color.Maroon)}, {"41", none, none.Background(color.Maroon)},
{"41", none.Background(color.Green), none.Background(color.Maroon)}, {"41", none.Background(color.Green), none.Background(color.Maroon)},
{"49", none.Background(color.Maroon).Bold(true), none.Bold(true)},
{"1;31", none, none.Foreground(color.Maroon).Bold(true)}, {"1;31", none, none.Foreground(color.Maroon).Bold(true)},
{"1;31", none.Foreground(color.Green), none.Foreground(color.Maroon).Bold(true)}, {"1;31", none.Foreground(color.Green), none.Foreground(color.Maroon).Bold(true)},
@@ -276,6 +279,7 @@ func TestApplySGR(t *testing.T) {
{"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))}, {"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))},
{"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))}, {"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))},
{"59", none.Underline(true, color.Maroon), none.Underline(true)},
// Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446 // Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446
{"38;5;34;1", none, none.Foreground(color.XTerm34).Bold(true)}, {"38;5;34;1", none, none.Foreground(color.XTerm34).Bold(true)},
+23 -15
View File
@@ -647,8 +647,9 @@ func (ui *ui) drawPromptLine(nav *nav) {
dir := nav.currDir() dir := nav.currDir()
pwd := sanitizeName(dir.path) pwd := sanitizeName(dir.path)
if after, ok := strings.CutPrefix(pwd, gUser.HomeDir); ok { // shorten the home directory itself and paths inside
pwd = filepath.Join("~", after) if rel, err := filepath.Rel(gUser.HomeDir, pwd); err == nil && filepath.IsLocal(rel) {
pwd = filepath.Join("~", rel)
} }
sep := string(filepath.Separator) sep := string(filepath.Separator)
@@ -660,7 +661,10 @@ func (ui *ui) drawPromptLine(nav *nav) {
var prompt string var prompt string
prompt = strings.ReplaceAll(gOpts.promptfmt, "%u", gUser.Username) // git style colored prompts contain hidden bytes that lf would print as extra characters
prompt = strings.ReplaceAll(gOpts.promptfmt, "\x01", "")
prompt = strings.ReplaceAll(prompt, "\x02", "")
prompt = strings.ReplaceAll(prompt, "%u", gUser.Username)
prompt = strings.ReplaceAll(prompt, "%h", gHostname) prompt = strings.ReplaceAll(prompt, "%h", gHostname)
prompt = strings.ReplaceAll(prompt, "%f", fname) prompt = strings.ReplaceAll(prompt, "%f", fname)
@@ -1349,7 +1353,7 @@ func listMarks(marks map[string]string) string {
func listFilesInCurrDir(nav *nav) string { func listFilesInCurrDir(nav *nav) string {
dir := nav.currDir() dir := nav.currDir()
if dir.loading { if dir.loading {
log.Printf("listFilesInCurrDir(): %s is still loading, `files` isn't ready for remote query", dir.path) log.Printf("listFilesInCurrDir: directory contents not loaded yet: %q", dir.path)
return "" return ""
} }
@@ -1422,7 +1426,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
expr := keys[ui.keyAcc] expr := keys[ui.keyAcc]
if ui.keyCount != "" { if ui.keyCount != "" {
if count, err := strconv.Atoi(ui.keyCount); err != nil { if count, err := strconv.Atoi(ui.keyCount); err != nil {
log.Printf("converting command count: %s", err) log.Printf("parsing command count: %s", err)
} else if count > 0 { } else if count > 0 {
switch e := expr.(type) { switch e := expr.(type) {
case *callExpr: case *callExpr:
@@ -1536,9 +1540,9 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
case *tcell.EventResize: case *tcell.EventResize:
return &callExpr{"redraw", nil, 1} return &callExpr{"redraw", nil, 1}
case *tcell.EventError: case *tcell.EventError:
log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When()) log.Printf("event error: %q at %s", tev.Error(), tev.When())
case *tcell.EventInterrupt: case *tcell.EventInterrupt:
log.Printf("Got EventInterrupt: at %s", tev.When()) log.Printf("event interrupt at %s", tev.When())
case *tcell.EventFocus: case *tcell.EventFocus:
if tev.Focused { if tev.Focused {
return &callExpr{"on-focus-gained", nil, 1} return &callExpr{"on-focus-gained", nil, 1}
@@ -1601,22 +1605,26 @@ func (ui *ui) exportSizes() {
os.Setenv("lf_height", strconv.Itoa(h)) os.Setenv("lf_height", strconv.Itoa(h))
} }
func anyKey() { func (ui *ui) anyKey() {
fmt.Fprint(os.Stderr, gOpts.waitmsg) fd := int(os.Stdin.Fd())
defer fmt.Fprintln(os.Stderr) oldState, err := term.MakeRaw(fd)
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil { if err != nil {
panic(err) ui.echoerrf("enabling raw mode: %s", err)
return
} }
defer fmt.Fprintln(os.Stderr)
defer func() { defer func() {
if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil { if err := term.Restore(fd, oldState); err != nil {
panic(err) ui.echoerrf("restoring terminal state: %s", err)
} }
}() }()
fmt.Fprint(os.Stderr, gOpts.waitmsg)
b := make([]byte, 8) b := make([]byte, 8)
if _, err := os.Stdin.Read(b); err != nil { if _, err := os.Stdin.Read(b); err != nil {
log.Printf("Failed to read key press: %s", err) ui.echoerrf("reading key press: %s", err)
} }
} }
+2 -2
View File
@@ -46,7 +46,7 @@ func (watch *watch) start() {
watcher, err := fsnotify.NewWatcher() watcher, err := fsnotify.NewWatcher()
if err != nil { if err != nil {
log.Printf("start watcher: %s", err) log.Printf("starting watcher: %s", err)
return return
} }
@@ -79,7 +79,7 @@ func (watch *watch) add(path string) {
} }
if err := watch.watcher.Add(path); err != nil { if err := watch.watcher.Add(path); err != nil {
log.Printf("watch path %s: %s", path, err) log.Printf("watching path %s: %s", path, err)
return return
} }