Compare commits

..
Author SHA1 Message Date
dependabot[bot] 4ea01d0417 chore(deps): bump golang.org/x/term from 0.47.0 to 0.48.0
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.47.0 to 0.48.0.
- [Commits](https://github.com/golang/term/compare/v0.47.0...v0.48.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-13 02:12:41 +00: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
27 changed files with 442 additions and 148 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
uses: golangci/golangci-lint-action@v9
with:
version: v2.5.0
version: v2.9.0
build:
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
### 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)
### 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).
- 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 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).
- 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).
- 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)
+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)
go func() {
for {
switch <-sigChan {
sig := <-sigChan
switch sig {
case os.Interrupt:
case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
log.Printf("received termination signal: %s", sig)
app.quit()
app.ui.screen.Fini()
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) {
log.Printf("reading file: %s", path)
@@ -529,10 +539,11 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
app.nav.previewChan <- ""
if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err)
log.Printf("suspending screen: %s", err)
}
defer func() {
if err := app.ui.resume(); err != nil {
log.Printf("resuming screen: %s", err)
app.quit()
os.Exit(3)
}
@@ -542,7 +553,7 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) {
app.ui.echoerrf("running shell: %s", err)
}
if pauseAfter {
anyKey()
app.ui.anyKey()
}
app.ui.loadFile(app, true)
+5 -3
View File
@@ -31,7 +31,7 @@ func run() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
if err != nil {
log.Fatalf("failed to open log file: %s", err)
log.Fatalf("opening log file: %s", err)
}
defer f.Close()
log.SetOutput(f)
@@ -108,7 +108,7 @@ func printPath(label, path string, stdoutIsTerminal bool) {
func writeLastDir(filename, lastDir string) {
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
}
f, err := os.Create(filename)
@@ -153,7 +153,7 @@ func readExpr() <-chan expr {
c, err := net.Dial("unix", gSocketPath)
for err != nil {
log.Printf("connecting server: %s", err)
log.Printf("connecting to server (retrying in %s): %s", duration, err)
time.Sleep(duration)
duration *= 2
c, err = net.Dial("unix", gSocketPath)
@@ -187,6 +187,8 @@ func readExpr() <-chan expr {
p := newParser(strings.NewReader(s.Text()))
if p.parse() {
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) {
t := reflect.TypeOf(opts)
for i := range t.NumField() {
field := t.Field(i)
for field := range t.Fields() {
switch field.Type.Kind() {
case reflect.Map:
continue
@@ -145,8 +144,7 @@ func getOptWords(opts any) (optWords []string) {
func getLocalOptWords(localOpts any) (localOptWords []string) {
t := reflect.TypeOf(localOpts)
for i := range t.NumField() {
field := t.Field(i)
for field := range t.Fields() {
name := field.Name
if field.Type.Kind() != reflect.Map {
continue
@@ -203,6 +201,18 @@ func matchWord(s string, words []string) (matches []compMatch, longest string) {
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) {
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)
if err != nil {
log.Printf("reading directory: %s", err)
log.Printf("completing path: %s", err)
longest = s
return
}
@@ -318,7 +328,7 @@ func matchExec(s string) (matches []compMatch, longest string) {
files, err := os.ReadDir(p)
if err != nil {
if !os.IsNotExist(err) {
log.Printf("reading path: %s", err)
log.Printf("completing shell command: %s", err)
}
continue
}
@@ -330,7 +340,7 @@ func matchExec(s string) (matches []compMatch, longest string) {
finfo, err := f.Info()
if err != nil {
log.Printf("getting file information: %s", err)
log.Printf("completing shell command: %s", err)
continue
}
@@ -348,7 +358,7 @@ func matchExec(s string) (matches []compMatch, longest string) {
func matchSearch(s string) (matches []compMatch, longest string) {
files, err := os.ReadDir(".")
if err != nil {
log.Printf("reading directory: %s", err)
log.Printf("completing search: %s", err)
longest = s
return
}
@@ -386,7 +396,7 @@ func completeCmd(s string) (matches []compMatch, longest string) {
switch f[0] {
case "set":
if len(f) == 2 {
matches, longest = matchWord(f[1], gOptWords)
matches, longest = matchOpt(f[1], gOptWords)
break
}
if len(f) != 3 {
@@ -422,7 +432,7 @@ func completeCmd(s string) (matches []compMatch, longest string) {
break
}
if len(f) == 3 {
matches, longest = matchWord(f[2], gLocalOptWords)
matches, longest = matchOpt(f[2], gLocalOptWords)
break
}
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
}
newPath := filepath.Join(dst, rel)
switch {
case info.IsDir():
switch info.Mode() & os.ModeType {
case os.ModeDir:
dstMode := os.ModePerm
if slices.Contains(preserve, "mode") {
dstMode = info.Mode()
@@ -153,7 +153,7 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
dirInfos[newPath] = info
}
nums <- info.Size()
case info.Mode()&os.ModeSymlink != 0:
case os.ModeSymlink:
if rlink, err := os.Readlink(path); err != nil {
errs <- fmt.Errorf("symlink: %w", err)
} else {
@@ -162,8 +162,12 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
}
}
nums <- info.Size()
default:
case 0:
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
})
+5 -3
View File
@@ -20,7 +20,7 @@ lf - terminal file manager
[**-server**]
[**-single**]
[**-version**]
[*cd-or-select-path*]
[*path*]
# DESCRIPTION
@@ -36,7 +36,7 @@ A man page with the same content is also available in the repository at https://
## 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.
@@ -522,7 +522,8 @@ A custom `open` command can be defined to override this 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>`)
@@ -674,6 +675,7 @@ Print given arguments to the message line at the bottom as `errorfmt` and also t
## cd
Change the working directory to the given argument.
If the argument is `-`, change to the previous directory stored in the special bookmark `'`.
## select
+7 -4
View File
@@ -7,7 +7,7 @@ SYNOPSIS
lf [-command command] [-config path] [-cpuprofile path] [-doc] [-help]
[-last-dir-path path] [-log path] [-memprofile path] [-print-last-dir]
[-print-selection] [-remote command] [-selection-path path] [-server]
[-single] [-version] [cd-or-select-path]
[-single] [-version] [path]
DESCRIPTION
@@ -26,7 +26,7 @@ OPTIONS
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
@@ -542,7 +542,9 @@ override this 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>)
@@ -707,7 +709,8 @@ also to the log file.
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
+26 -13
View File
@@ -154,9 +154,6 @@ func (e *setExpr) eval(app *app, _ []string) {
if err == nil {
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!":
err = applyBoolOpt(&gOpts.showbinds, e)
case "smartcase", "nosmartcase", "smartcase!":
@@ -789,7 +786,7 @@ func resetIncCmd(app *app) {
dir := app.nav.currDir()
old := dir.ind
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 {
app.ui.loadFile(app, true)
}
@@ -992,13 +989,20 @@ func insert(app *app, arg string) {
}
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))
if err != nil {
return fmt.Errorf("getting absolute path: %w", err)
}
wd := app.nav.currDir().path
if path == wd {
return nil
}
@@ -1007,7 +1011,7 @@ func cd(app *app, path string) error {
preChdir(app)
if err := app.nav.cd(path); err != nil {
return fmt.Errorf("changing directory: %w", err)
return err
}
app.ui.loadFile(app, true)
@@ -1049,7 +1053,7 @@ func (e *callExpr) eval(app *app, _ []string) {
switch e.name {
case "quit":
app.quitChan <- struct{}{}
app.requestQuit()
case "up":
if app.nav.up(e.count) {
app.ui.loadFile(app, true)
@@ -1105,7 +1109,7 @@ func (e *callExpr) eval(app *app, _ []string) {
preChdir(app)
err := app.nav.open()
if err != nil {
app.ui.echoerrf("opening directory: %s", err)
app.ui.echoerrf("open: %s", err)
return
}
app.ui.loadFile(app, true)
@@ -1114,7 +1118,7 @@ func (e *callExpr) eval(app *app, _ []string) {
} else {
if gSelectionPath != "" || gPrintSelection {
app.selectionOut, _ = app.nav.currFileOrSelections()
app.quitChan <- struct{}{}
app.requestQuit()
return
}
@@ -1278,6 +1282,8 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerrf("sync: %s", err)
}
case "draw":
// Input handlers return this no-op instead of nil to
// trigger the screen update performed by [app.loop].
case "redraw":
app.ui.screen.Sync()
app.ui.renew()
@@ -1499,6 +1505,7 @@ func (e *callExpr) eval(app *app, _ []string) {
return
}
normal(app)
app.ui.menu = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-save: "
case "mark-load":
if app.ui.cmdPrefix == ">" {
@@ -1600,7 +1607,13 @@ func (e *callExpr) eval(app *app, _ []string) {
if dir.loading {
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)
case "source":
if len(e.args) != 1 {
@@ -1613,7 +1626,7 @@ func (e *callExpr) eval(app *app, _ []string) {
app.ui.echoerr("push: requires an argument")
return
}
log.Println("pushing keys", e.args[0])
log.Printf("pushing keys: %s", e.args[0])
for _, val := range splitKeys(e.args[0]) {
app.ui.evChan <- parseKey(val)
}
@@ -1677,7 +1690,7 @@ func (e *callExpr) eval(app *app, _ []string) {
tty, ok := app.ui.screen.Tty()
if !ok {
log.Print("tty-write: failed to get tty")
log.Print("tty-write: no tty available")
return
}
@@ -1901,7 +1914,7 @@ func (e *callExpr) eval(app *app, _ []string) {
}
app.ui.loadFile(app, true)
default:
log.Printf("entering unknown execution prefix: %q", app.ui.cmdPrefix)
log.Printf("unknown execution prefix: %q", app.ui.cmdPrefix)
}
case "cmd-interrupt":
if app.cmd != nil {
+37
View File
@@ -84,6 +84,18 @@ var gEvalTests = []struct {
[]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`,
[]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
go 1.25.0
go 1.26.0
require (
github.com/clipperhouse/displaywidth v0.11.0
github.com/djherbis/times v1.6.0
github.com/fsnotify/fsnotify v1.10.1
github.com/gdamore/tcell/v3 v3.4.1
golang.org/x/sys v0.47.0
golang.org/x/term v0.45.0
github.com/gdamore/tcell/v3 v3.6.0
golang.org/x/sys v0.50.0
golang.org/x/term v0.48.0
)
require (
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/gdamore/encoding v1.0.1 // indirect
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
golang.org/x/text v0.40.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // 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/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw=
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.4.1/go.mod h1:YWwuxZNi14VGQC5g2VGNEDRXpBraTwvVjMovRH6G6hw=
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/gdamore/tcell/v3 v3.6.0 h1:jW20qS6Tm38KVDqLHq9KWSvyjNl00FbhbD8rIAnHBws=
github.com/gdamore/tcell/v3 v3.6.0/go.mod h1:CBZxkl2T+XxEyuBfOh4zaahqm27dngvhfBfCCZxJsgc=
github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss=
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=
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=
@@ -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-20220722155257-8c9f86f7a55f/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.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
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-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.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk=
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
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/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
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-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
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
.\"
.TH "LF" "1" "2026\-07\-31" "r42" "DOCUMENTATION"
.TH "LF" "1" "2026\-10\-29" "r43" "DOCUMENTATION"
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
@@ -11,8 +11,7 @@ lf \- terminal file manager
\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]\-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[I]cd\-or\-select\-path\f[R]]
[\f[B]\-single\f[R]] [\f[B]\-version\f[R]] [\f[I]path\f[R]]
.SH DESCRIPTION
lf is a terminal file manager.
.PP
@@ -33,7 +32,7 @@ A man page with the same content is also available in the repository at
.SH OPTIONS
.SS POSITIONAL ARGUMENTS
.TP
\f[B]cd\-or\-select\-path\f[R]
\f[B]path\f[R]
Set the starting location.
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
@@ -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
default.
.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])
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
@@ -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.
.SS cd
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
Change the current file selection to the given argument.
.SS source
+9 -7
View File
@@ -82,7 +82,7 @@ func exportEnvVars() {
level, err := strconv.Atoi(envLevel)
if err != nil {
log.Printf("reading lf level: %s", err)
log.Printf("parsing $LF_LEVEL: %s", err)
}
level++
@@ -183,7 +183,7 @@ func checkServer() {
startServer()
} else if _, err := net.Dial("unix", gSocketPath); err != nil {
if err := os.Remove(gSocketPath); err != nil {
log.Print(err)
log.Printf("removing socket: %s", err)
}
startServer()
}
@@ -225,10 +225,11 @@ func main() {
f := flag.CommandLine.Output()
fmt.Fprintf(f, `lf - Terminal file manager
Usage: %s [options] [cd-or-select-path]
Usage: %s [options] [path]
cd-or-select-path
set the initial dir or file selection to the given argument
Arguments:
path
set the initial directory or select the given file
Options:
`, os.Args[0])
@@ -349,7 +350,8 @@ Options:
if term.IsTerminal(int(os.Stdout.Fd())) {
lines := strings.Split(resp, "\n")
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")
}
@@ -380,7 +382,7 @@ Options:
case 1:
gSelect = flag.Arg(0)
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)
}
+12 -11
View File
@@ -11,7 +11,6 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
@@ -32,8 +31,8 @@ var (
func isRoot(name string) bool { return filepath.Dir(name) == name }
func replaceTilde(s string) string {
if strings.HasPrefix(s, "~") {
return gUser.HomeDir + s[1:]
if rest, ok := strings.CutPrefix(s, "~"); ok && (rest == "" || os.IsPathSeparator(rest[0])) {
return gUser.HomeDir + rest
}
return s
}
@@ -393,14 +392,16 @@ func naturalCmp(s1, s2 string) int {
tok2 := s2[lo2:hi2]
if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(tok1)
num2, err2 := strconv.Atoi(tok2)
if err1 == nil && err2 == nil {
if num1 != num2 {
return cmp.Compare(num1, num2)
} else if len(tok1) != len(tok2) {
return cmp.Compare(len(tok1), len(tok2))
}
// compare the digits directly instead of parsing them, so that
// numbers too large for an int are still ordered by value
num1 := strings.TrimLeft(tok1, "0")
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)
} else if len(tok1) != len(tok2) {
return cmp.Compare(len(tok1), len(tok2))
}
}
+6
View File
@@ -399,6 +399,12 @@ func TestNaturalCmp(t *testing.T) {
{"foo0bar", "foo00bar", -1},
{"foo1", "foo01", -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 {
+44 -25
View File
@@ -48,7 +48,7 @@ type file struct {
func newFile(path string) *file {
lstat, err := os.Lstat(path)
if err != nil {
log.Printf("getting file information: %s", err)
log.Printf("getting file info: %s", err)
return &file{
FileInfo: &fakeStat{name: filepath.Base(path)},
linkState: notLink,
@@ -100,13 +100,13 @@ func newFile(path string) *file {
if lstat.IsDir() && getDirCounts(filepath.Dir(path)) {
d, err := os.Open(path)
if err != nil {
log.Printf("opening file: %s", err)
log.Printf("counting directory entries: %s", err)
} else {
names, err := d.Readdirnames(10000)
d.Close()
if names == nil && err != io.EOF {
log.Printf("reading directory: %s", err)
log.Printf("counting directory entries: %s", err)
} else {
dirCount = len(names)
}
@@ -797,8 +797,7 @@ func (nav *nav) previewLoop(ui *ui) {
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
var exitErr *exec.ExitError
if !errors.As(err, &exitErr) {
if _, ok := errors.AsType[*exec.ExitError](err); !ok {
log.Printf("cleaning preview: %s", err)
}
}
@@ -905,16 +904,15 @@ func (nav *nav) preview(path string, win *win, mode string) {
defer func() {
if err := cmd.Wait(); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if _, ok := errors.AsType[*exec.ExitError](err); ok {
reg.volatile = true
} else {
log.Printf("loading file: %s", err)
log.Printf("previewing file: %s", err)
}
}
if s := strings.TrimSpace(stderr.String()); s != "" {
s = strings.Join(strings.Fields(s), " ")
log.Printf("loading file (stderr): %s", s)
log.Printf("previewing file (stderr): %s", s)
}
}()
defer out.Close()
@@ -922,7 +920,7 @@ func (nav *nav) preview(path string, win *win, mode string) {
} else {
lstat, err := os.Lstat(path)
if err != nil {
log.Printf("lstat: %s", err)
log.Printf("previewing file: %s", err)
return
}
@@ -932,7 +930,7 @@ func (nav *nav) preview(path string, win *win, mode string) {
f, err := os.Open(path)
if err != nil {
log.Printf("opening file: %s", err)
log.Printf("previewing file: %s", err)
return
}
@@ -1153,7 +1151,7 @@ func (nav *nav) open() error {
}
if err := os.Chdir(curr.path); err != nil {
return fmt.Errorf("open: %w", err)
return err
}
nav.dirPaths = append(nav.dirPaths, curr.path)
@@ -1816,7 +1814,7 @@ func isFiltered(f os.FileInfo, filter []string) bool {
for _, pattern := range filter {
matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.filtermethod)
if err != nil {
log.Printf("Filter Error: %s", err)
log.Printf("applying filter: %s", err)
return false
}
if strings.HasPrefix(pattern, "!") && matched {
@@ -1851,7 +1849,8 @@ func (nav *nav) readMarks() error {
for scanner.Scan() {
mark, path, found := strings.Cut(scanner.Text(), ":")
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 {
nav.marks[mark] = path
@@ -1862,7 +1861,7 @@ func (nav *nav) readMarks() error {
return fmt.Errorf("reading marks file: %w", err)
}
return nil
return err
}
func (nav *nav) writeMarks() error {
@@ -1910,7 +1909,8 @@ func (nav *nav) readTags() error {
ind := strings.LastIndex(text, ":")
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]
@@ -1924,7 +1924,7 @@ func (nav *nav) readTags() error {
return fmt.Errorf("reading tags file: %w", err)
}
return nil
return err
}
func (nav *nav) writeTags() error {
@@ -2007,15 +2007,32 @@ func (nav *nav) currFileOrSelections() ([]string, error) {
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 {
calc := func(f *file) error {
if f.IsDir() {
total, err := copySize([]string{f.path})
if err != nil {
return err
}
f.dirSize = total
if !f.IsDir() {
return nil
}
total, err := calcSize(f)
if err != nil {
return err
}
f.dirSize = total
return nil
}
@@ -2028,8 +2045,10 @@ func (nav *nav) calcDirSize() error {
}
for sel := range nav.selections {
lstat, err := os.Lstat(sel)
if err != nil || !lstat.IsDir() {
// `os.Stat` is used instead of `os.Lstat` so that symlinks pointing to
// directories are not skipped.
stat, err := os.Stat(sel)
if err != nil || !stat.IsDir() {
continue
}
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()
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
s.scan()
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
s.scan()
}
@@ -249,18 +258,28 @@ func (p *parser) parseExpr() expr {
s.scan()
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
s.scan()
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
s.scan()
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
s.scan()
}
@@ -359,6 +378,9 @@ func (p *parser) parseExpr() expr {
for {
e := p.parseExpr()
if e == nil {
if p.err == nil {
p.err = fmt.Errorf(`missing "}}"`)
}
return nil
}
exprs = append(exprs, e)
@@ -391,6 +413,10 @@ func (p *parser) parseExpr() expr {
s.scan()
if s.typ == tokenLBraces {
s.scan()
if s.typ != tokenCommand {
p.err = fmt.Errorf(`missing "}}"`)
return nil
}
expr = s.tok
s.scan()
} else {
@@ -402,7 +428,7 @@ func (p *parser) parseExpr() expr {
result = &execExpr{prefix, expr}
default:
p.err = fmt.Errorf("unexpected token: %s", s.tok)
p.err = fmt.Errorf("unexpected %q", s.tok)
}
return result
@@ -410,5 +436,10 @@ func (p *parser) parseExpr() expr {
func (p *parser) parse() bool {
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
}
+3 -1
View File
@@ -237,8 +237,10 @@ scan:
case s.chr == 'v':
buf = append(buf, '\v')
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
for isDigit(s.chr) {
for len(oct) < 3 && isDigit(s.chr) {
oct = append(oct, s.chr)
s.next()
}
+23 -14
View File
@@ -29,7 +29,7 @@ func serve() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600)
if err != nil {
log.Fatalf("failed to open log file: %s", err)
log.Fatalf("opening log file: %s", err)
}
defer f.Close()
log.SetOutput(f)
@@ -73,37 +73,46 @@ func manage() {
case "broadcast":
for id, c2 := range connList {
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":
if c2, ok := connList[cmd.id]; ok {
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 {
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":
c2, ok := connList[cmd.id]
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
}
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
}
s2 := bufio.NewScanner(c2)
for s2.Scan() && s2.Text() != "" {
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 {
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":
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 {
gQuitChan <- struct{}{}
gListener.Close()
@@ -171,25 +180,25 @@ Loop:
word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: conn: client id should be a number")
echoerr(c, "listen: conn: client ID must be a number")
} else {
send(srvCmd{op: "conn", id: id, c: c})
return
}
} else {
echoerr(c, "listen: conn: requires a client id")
echoerr(c, "listen: conn: requires a client ID")
}
case "drop":
if rest != "" {
word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: drop: client id should be a number")
echoerr(c, "listen: drop: client ID must be a number")
} else {
send(srvCmd{op: "drop", id: id})
}
} else {
echoerr(c, "listen: drop: requires a client id")
echoerr(c, "listen: drop: requires a client ID")
}
case "list":
send(srvCmd{op: "list", c: c})
@@ -205,13 +214,13 @@ Loop:
}
case "query":
if rest == "" {
echoerr(c, "listen: query: requires a client id")
echoerr(c, "listen: query: requires a client ID")
break
}
word2, rest2 := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: query: client id should be a number")
echoerr(c, "listen: query: client ID must be a number")
break
}
send(srvCmd{op: "query", id: id, msg: rest2, c: c})
+4 -4
View File
@@ -200,7 +200,7 @@ loop:
case "38":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 38: %s", err)
log.Printf("processing ANSI code 38: %s", err)
break loop
}
st = st.Foreground(color)
@@ -214,7 +214,7 @@ loop:
case "48":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 48: %s", err)
log.Printf("processing ANSI code 48: %s", err)
break loop
}
st = st.Background(color)
@@ -222,13 +222,13 @@ loop:
case "58":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 58: %s", err)
log.Printf("processing ANSI code 58: %s", err)
break loop
}
st = st.Underline(color)
i += offset
default:
log.Printf("unknown ansi code: %s", toks[i])
log.Printf("unknown ANSI code: %s", toks[i])
}
}
+23 -15
View File
@@ -647,8 +647,9 @@ func (ui *ui) drawPromptLine(nav *nav) {
dir := nav.currDir()
pwd := sanitizeName(dir.path)
if after, ok := strings.CutPrefix(pwd, gUser.HomeDir); ok {
pwd = filepath.Join("~", after)
// shorten the home directory itself and paths inside
if rel, err := filepath.Rel(gUser.HomeDir, pwd); err == nil && filepath.IsLocal(rel) {
pwd = filepath.Join("~", rel)
}
sep := string(filepath.Separator)
@@ -660,7 +661,10 @@ func (ui *ui) drawPromptLine(nav *nav) {
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, "%f", fname)
@@ -1349,7 +1353,7 @@ func listMarks(marks map[string]string) string {
func listFilesInCurrDir(nav *nav) string {
dir := nav.currDir()
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 ""
}
@@ -1422,7 +1426,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
expr := keys[ui.keyAcc]
if ui.keyCount != "" {
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 {
switch e := expr.(type) {
case *callExpr:
@@ -1536,9 +1540,9 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
case *tcell.EventResize:
return &callExpr{"redraw", nil, 1}
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:
log.Printf("Got EventInterrupt: at %s", tev.When())
log.Printf("event interrupt at %s", tev.When())
case *tcell.EventFocus:
if tev.Focused {
return &callExpr{"on-focus-gained", nil, 1}
@@ -1601,22 +1605,26 @@ func (ui *ui) exportSizes() {
os.Setenv("lf_height", strconv.Itoa(h))
}
func anyKey() {
fmt.Fprint(os.Stderr, gOpts.waitmsg)
defer fmt.Fprintln(os.Stderr)
oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
func (ui *ui) anyKey() {
fd := int(os.Stdin.Fd())
oldState, err := term.MakeRaw(fd)
if err != nil {
panic(err)
ui.echoerrf("enabling raw mode: %s", err)
return
}
defer fmt.Fprintln(os.Stderr)
defer func() {
if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil {
panic(err)
if err := term.Restore(fd, oldState); err != nil {
ui.echoerrf("restoring terminal state: %s", err)
}
}()
fmt.Fprint(os.Stderr, gOpts.waitmsg)
b := make([]byte, 8)
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()
if err != nil {
log.Printf("start watcher: %s", err)
log.Printf("starting watcher: %s", err)
return
}
@@ -79,7 +79,7 @@ func (watch *watch) add(path string) {
}
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
}