Compare commits

150 Commits
Author SHA1 Message Date
Joe Lim e17504b7ce Prepare for r39 release (#2281)
* Backout tcell updates

* Prepare for r39 release
2025-12-02 00:28:50 +11:00
dependabot[bot] fad7975e5e Bump github.com/gdamore/tcell/v2 from 2.12.0 to 2.12.1 (#2277) 2025-11-27 08:45:55 +01:00
dependabot[bot] 59589a7cde Bump github.com/gdamore/tcell/v2 from 2.11.0 to 2.12.0 (#2276)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.11.0 to 2.12.0.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv2.md)
- [Commits](https://github.com/gdamore/tcell/compare/v2.11.0...v2.12.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-25 20:38:51 +01:00
dependabot[bot] cc5bf4ae7b Bump github.com/gdamore/tcell/v2 from 2.10.0 to 2.11.0 (#2275)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.10.0 to 2.11.0.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv2.md)
- [Commits](https://github.com/gdamore/tcell/compare/v2.10.0...v2.11.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-24 22:17:47 +01:00
dependabot[bot] bc7161d4e8 Bump github.com/gdamore/tcell/v2 from 2.9.0 to 2.10.0 (#2271) 2025-11-23 18:38:41 +01:00
dependabot[bot] 1c2484c782 Bump actions/checkout from 5 to 6 (#2272) 2025-11-23 18:37:09 +01:00
CatsDeservePets 91ebcbc289 Update CHANGELOG.md
Remove note about directory sorting in reverse order.
2025-11-18 22:52:21 +01:00
CatsDeservePets 6e804b1ade Use ls-style permission strings (#2270) 2025-11-18 01:55:33 +01:00
Joe Lim 5749c9cd93 Order directories first when using reverse sort (#2269)
* Order directories first when using reverse sort

* Update `CHANGELOG.md`
2025-11-18 10:58:08 +11:00
CatsDeservePets c320102865 Fix formatting in README.md
- Follow-up to: https://github.com/gokcehan/lf/pull/2265
2025-11-15 06:00:28 +01:00
CatsDeservePets 568db57695 Remove outdated community links from README.md (#2265) 2025-11-15 05:43:21 +01:00
CatsDeservePets 9a091a2562 Remove deprecated sixel option (#2263) 2025-11-14 15:44:59 +01:00
Joe Lim 540d8ec9b9 Update CHANGELOG.md (#2261) 2025-11-13 12:15:20 +11:00
Joe Lim 3f46fba85b Alternate implementation for matching setlocal path (#2259)
* Alternate implementation for matching setlocal

* Handle escaped paths
2025-11-12 09:29:31 +01:00
dependabot[bot] 64081886c3 Bump golang.org/x/term from 0.36.0 to 0.37.0 (#2260) 2025-11-12 07:55:35 +01:00
Carlo Teubner 8da478bb86 Check errors and enable errcheck in lint config (#2242) 2025-11-10 10:17:18 +01:00
dependabot[bot] b6535060a6 Bump golangci/golangci-lint-action from 8 to 9 (#2257) 2025-11-10 03:28:21 +01:00
dependabot[bot] 3f261aa389 Bump golang.org/x/sys from 0.37.0 to 0.38.0 (#2258) 2025-11-10 03:28:05 +01:00
CatsDeservePets 58473275d5 Add completions for setlocal (#2254) 2025-11-08 00:56:51 +01:00
CatsDeservePets 40e7fb8e9e Allow relative paths for setlocal (#2253) 2025-11-07 23:58:59 +01:00
CatsDeservePets 0283b2a71a Hide already typed keys inside showbinds menu (#2249) 2025-11-07 02:08:52 +01:00
Joe Lim c19e3a68c1 Fix typo (#2250) 2025-11-06 23:56:27 +11:00
CatsDeservePets e45412d363 Add OSC 8 support (#2243)
* Add `OSC 8` support

* Rename functions

* Update tests

* Support grouped links

* Update `CHANGELOG.md`

* Move terminal sequence parsing to new file
2025-11-03 15:55:29 +01:00
CatsDeservePets 830f072961 Fix typo (#2248) 2025-11-02 23:20:31 +01:00
Joe Lim df06e7250e Display errors in config files (#2246)
* Display errors in config files

* Update `CHANGELOG.md`

* `clearmaps` should be a silent command
2025-11-01 18:52:15 +11:00
Joe Lim 5cdb6edd93 Fix implementation of silent commands (#2245)
* Fix implementation of silent commands

* Update `CHANGELOG.md`
2025-11-01 18:34:09 +11:00
Joe Lim 95711c39bf Deduplicate preload updates (#2244) 2025-11-01 18:03:26 +11:00
Joe Lim 5ae9a4cd81 Debounce resize triggers when preloading (#2240)
* Debounce resize triggers when preloading

* Clear all previews in cache
2025-10-30 13:52:29 +11:00
Carlo Teubner 49984bb606 .github: staticcheck-action → golangci-lint-action (#2238)
golangci-lint bundles many Go linters
(https://golangci-lint.run/docs/linters/). For now, we are going with its
default set of linters, which includes staticcheck, but with the
errcheck linter explicitly excluded because it generates a lot of lints;
I plan to address those and add errcheck in a subsequent contribution.
2025-10-29 11:23:52 +11:00
Joe Lim e158c344d2 Fix preload crash (#2237) 2025-10-28 19:01:24 +11:00
Joe Lim fc2b2f42a2 Avoid deadlock when preloading (#2236)
* Fix preload deadlock

* Add experimental flag
2025-10-28 15:50:04 +11:00
Joe Lim 928bf9e3bd Refactor previewable logic (#2235) 2025-10-28 15:27:59 +11:00
Carlo Teubner fc4b3637bb Miscellaneous tweaks and fixes (#2223)
* Miscellaneous tweaks and fixes

Mostly these were found by running golangci-lint with a bunch of linters
(more than the default set) enabled.

* fmt.Fprint -> fmt.Fprintln where possible

* Remove "nolint:staticcheck" for now
2025-10-28 15:10:32 +11:00
Joe Lim b12cb33918 Prevent window height from being negative (#2232) 2025-10-27 20:31:00 +11:00
Joe Lim 7776e73334 Fix check for invalid filters (#2231)
* Fix check for invalid filters

* Update `CHANGELOG.md`
2025-10-27 19:20:21 +11:00
dependabot[bot] 887da5d5e4 Bump actions/download-artifact from 5 to 6 (#2230)
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 5 to 6.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v5...v6)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-27 16:58:11 +11:00
dependabot[bot] 0e3912b151 Bump actions/upload-artifact from 4 to 5 (#2229)
Bumps [actions/upload-artifact](https://github.com/actions/upload-artifact) from 4 to 5.
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v4...v5)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-27 16:57:55 +11:00
CatsDeservePets 765a331977 Explicitly hide mode in showbinds menu (#2228) 2025-10-26 21:55:14 +01:00
CatsDeservePets 00ee9ee81a Update CHANGELOG.md (#2227) 2025-10-26 09:54:20 +01:00
CatsDeservePets ff169a80b9 Hide mode when listing single-mode binds (#2226) 2025-10-26 09:43:04 +01:00
Joe Lim d8a23be926 Add option for preloading file previews (#2206)
* Initial commit

* Add documentation

* Fix nav volatile preview state

* Use `previewer` for both preloading and previewing

* Generate documentation

* Update `CHANGELOG.md`
2025-10-24 13:26:34 +11:00
CatsDeservePets 56fd6c27ba Add image to README.md (#2222)
Add a new image for showcasing features.
2025-10-23 23:40:10 +02:00
Joe Lim 2563e6bef2 Revert "Add documentation"
This reverts commit 56489403f6.
2025-10-23 13:49:39 +11:00
Joe Lim 56489403f6 Add documentation 2025-10-22 13:04:42 +11:00
Joe Lim a7f7e84e81 Handle nav resizes (#2218)
* Handle nav resizes

* Update `CHANGELOG.md`
2025-10-21 21:46:19 +11:00
Joe LimandCatsDeservePets 7b6b6da100 Add ruler file for customizing the ruler (#2186)
* Add ruler file for customizing the ruler

* Update `CHANGELOG.md`

* Show ruler errors instead of logging them

* Allow multiple sections

* Show syntax errors for ruler file

* Add line percentage

* Add lower/upper functions

* Add back truncation

* Use fmt options

---------

Co-authored-by: CatsDeservePets <145048791+CatsDeservePets@users.noreply.github.com>
2025-10-21 20:04:05 +11:00
Joe Lim 5d93764c79 Fix CHANGELOG.md (#2217) 2025-10-21 17:22:57 +11:00
CatsDeservePets 512da3152d Rephrase some log messages (#2216) 2025-10-21 00:25:25 +02:00
CatsDeservePets cc112beb78 Append logs instead instead overwriting (#2215) 2025-10-20 23:48:44 +02:00
CatsDeservePets bbfef3e832 Update CHANGELOG.md (#2214) 2025-10-20 17:08:38 +02:00
CatsDeservePets 35c883e438 Fix overscroll related to drawbox (#2210) 2025-10-20 16:52:56 +02:00
CatsDeservePets a949d4a5d1 Unify [y/N] prompts (#2212) 2025-10-19 05:51:56 +02:00
CatsDeservePets 8a8f8180af Add file completions for cleaner and previewer (#2211) 2025-10-19 04:18:01 +02:00
CatsDeservePets 06376f9089 Fix spacing for empty custom info (#2208) 2025-10-18 19:28:50 +02:00
CatsDeservePets f74cf581b3 Add usage to documentation (#2200) 2025-10-17 04:40:07 +02:00
dependabot[bot] c84e445662 Bump golang.org/x/term from 0.35.0 to 0.36.0 (#2196)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.35.0 to 0.36.0.
- [Commits](https://github.com/golang/term/compare/v0.35.0...v0.36.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-09 23:01:19 +02:00
CatsDeservePets 2fb6cb2e17 Update CHANGELOG.md (#2199) 2025-10-09 22:58:31 +02:00
CatsDeservePets 9eb0872588 Add file completions for addcustominfo (#2198) 2025-10-09 22:28:57 +02:00
CatsDeservePets 4bfd3c8ac5 Silence gopls hints (#2195) 2025-10-09 02:18:16 +02:00
Joe Lim 4dc3d37684 Show error if source command fails (#2189)
* Show error if `source` command fails

* Update `CHANGELOG.md`

* reword
2025-10-03 12:19:25 +10:00
dependabot[bot] 76eb241023 Bump github.com/mattn/go-runewidth from 0.0.17 to 0.0.19 (#2187)
Bumps [github.com/mattn/go-runewidth](https://github.com/mattn/go-runewidth) from 0.0.17 to 0.0.19.
- [Commits](https://github.com/mattn/go-runewidth/compare/v0.0.17...v0.0.19)

---
updated-dependencies:
- dependency-name: github.com/mattn/go-runewidth
  dependency-version: 0.0.19
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-02 00:06:24 +10:00
CatsDeservePets 0fe6a3b20f Fix outdated documentation (#2185) 2025-09-29 23:23:39 +10:00
dependabot[bot] 72526aa1f5 Bump github.com/mattn/go-runewidth from 0.0.16 to 0.0.17 (#2183)
Bumps [github.com/mattn/go-runewidth](https://github.com/mattn/go-runewidth) from 0.0.16 to 0.0.17.
- [Commits](https://github.com/mattn/go-runewidth/compare/v0.0.16...v0.0.17)

---
updated-dependencies:
- dependency-name: github.com/mattn/go-runewidth
  dependency-version: 0.0.17
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-27 16:38:24 +10:00
Joe Lim b3b3ad8228 Fix copy progress bar missing after first time (#2181)
* Fix copy progress bar missing after first time

* Update `CHANGELOG.md`
2025-09-23 13:29:34 +10:00
Joe Lim 29627d455d Update CHANGELOG.md (#2178) 2025-09-20 18:33:07 +10:00
Joe Lim 00da40b9cd Refactor directory sorting code (#2177)
* Implement natural sorting

* Small refactor of filtering code

* Refactor sorting

* Refactor dirfirst as well

* reword

* reword2
2025-09-20 18:08:39 +10:00
Joe Lim b71910cf51 Update CHANGELOG.md and some cleanup (#2176) 2025-09-20 15:11:25 +10:00
Carlo Teubner f21e553557 shell-pipe: fix excessive waiting for output (#2155)
* shell-pipe: fix excessive waiting for output

There are some programs that keep their stdin/stdout/stderr open beyond
their process lifetime. An example is "wl-copy", which forks off into
the background and keeps stderr open.

Before this change, the behaviour of lf's shell-pipe (aka %) was to
first wait for an EOF from the stdout/stderr pipe of the process, and
only then to wait for the process to exit.

As a result, a command such as "%wl-copy foo" never stops showing the
">" command prefix indicator.

Fix this, by waiting for the EOF from the pipe and the process exit in
parallel, as well as setting the "exec.Cmd.WaitDelay" field.

(For some reason, the fix works even without setting WaitDelay, and it
also doesn't seem to wait for one second; I haven't investigated why
this is; the behaviour is an improvement either way.)

Additionally, improve handling errors when reading from the
stdout/stderr pipe:
- Always give up reading from the pipe, regardless of error kind
- Unless it is an expected error (EOF or (now) ErrClosed), log the error
- Compare errors using "errors.Is"

* shell-pipe: use os.Pipe not Cmd.StdoutPipe etc.

The source-code comment explains why.

Also remove WaitDelay, which wasn't working, and which we probably don't
want anyway; and fix some insufficient error handling (missing return).
2025-09-20 14:47:16 +10:00
Joe Lim b0932b02c2 Fix message clear bug during shell-pipe command (#2175) 2025-09-20 14:43:36 +10:00
Joe Lim 73d7837cfc Use parallel builds for release pipeline (#2172) 2025-09-20 01:37:34 +10:00
Joe Lim f4ae38f575 Run cross build in parallel for CI (#2171)
* Run cross build in parallel for CI

* Intentional failure

* Revert "Intentional failure"

This reverts commit 27521305d7.

* reorder

* Rename step
2025-09-20 00:31:04 +10:00
Joe Lim edf72c6304 Use version in go.mod for CI build (#2170)
* Use version in `go.mod` for CI

* reorder
2025-09-19 23:08:47 +10:00
Joe Lim 38bcd0ba3d Format yaml files (#2169) 2025-09-19 22:57:38 +10:00
Joe Lim d3816c6d6a Clear message after running cmap commands (#2168) 2025-09-19 20:45:11 +10:00
Joe Lim 2adac2e155 Refactor shell-pipe reader (#2167) 2025-09-19 20:22:49 +10:00
Joe Lim 1f8fb52889 Update CHANGELOG.md (#2166)
* Update `CHANGELOG.md`

* reword
2025-09-19 20:03:50 +10:00
Joe Lim 89ff7b0203 Implement smarter history navigation (#2161)
* Remove unnecessary space in history file

* Refactor history navigation

* Implement smarter history navigation

* Skip duplicate commands in history navigation

* Return to Normal mode if it started from there

* Reset history state when changing prompt

* Update documentation
2025-09-19 19:44:43 +10:00
Joe Lim 5e15655539 Prevent truncation from applying to file extension (#2159)
* Prevent truncation from applying to file extension

* Update documentation
2025-09-19 18:32:06 +10:00
Joe Lim f69aec80b1 Fix string representation of expr objects (#2165)
* Fix string representation of `expr` objects

* Add unit tests
2025-09-19 16:35:59 +10:00
CatsDeservePets 5aeb9a490b Add cmd-menu-discard command (#2146)
* [WIP] Add `cmd-menu-discard` command

* Add `compmenu` to $lf_mode

* Add `cmd-menu-discard` command

* Update documentation
2025-09-19 14:58:02 +10:00
Joe Lim 9e5f6af3b7 Bump go version to 1.24 (#2164) 2025-09-19 14:44:40 +10:00
Joe Lim 49f2a7c6c4 Prepare for r38 release (#2163) 2025-09-19 14:18:55 +10:00
CatsDeservePets d81c84bbb9 Update docs (#2160) 2025-09-19 03:39:15 +10:00
CatsDeservePets c5075b6455 Update documentation (#2149)
* Fix typos

* Unify spelling

* Improve grammar and wording

* Update usage of `filename` and `file name`

* Prefer `without` over `w/o`

* Generate docs
2025-09-18 13:41:24 +10:00
Joe Lim d2e125d264 Update CHANGELOG.md (#2157) 2025-09-17 15:32:49 +10:00
CatsDeservePets d2bcae2943 Unify usage and synopsis (#2153) 2025-09-17 15:17:21 +10:00
CatsDeservePets f050abc57c Fix: UI glitch with completion menu #2139 (#2140) 2025-09-10 12:28:33 +10:00
Joe Lim 9c0dc813a3 Update CHANGELOG.md (#2143) 2025-09-09 16:28:03 +10:00
Carlo Teubner 995413426c lf -remote: work around busyloop issue on Linux (#2138)
I noticed that running ":maps" in lf on Linux uses a whole CPU. I
managed to track it down to a bug in the Go standard library, for which
I entered https://github.com/golang/go/issues/75304.

Until that is fixed, it seems worth having a workaround for this.
2025-09-09 16:01:22 +10:00
CatsDeservePets b73daad7cc Fix typo in documentation (#2141) 2025-09-09 13:50:08 +10:00
CatsDeservePets f94c62661a Update documentation to mention PowerShell config (#2135) 2025-09-08 14:03:04 +10:00
dependabot[bot] 168a64a288 Bump actions/setup-go from 5 to 6 (#2133)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 5 to 6.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v5...v6)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-08 00:30:24 +10:00
Joe Lim 8dad85197f Remove padding for text previews (#2131)
* Remove offset for text previews

* Update `CHANGELOG.md`

* reword
2025-09-04 15:38:57 +10:00
Joe Lim d079cc8719 Fix copy progress bug when copying files with 0 size (#2130)
* Fix copy progress when copying files with 0 size

* typo

* Update `CHANGELOG.md`
2025-09-04 14:44:29 +10:00
Joe Lim f26b30be18 Rename doc command to help (#2125)
* Rename `doc` command to `help`

* Update `CHANGELOG.md`
2025-08-28 14:47:36 +10:00
Joe Lim ad5af1b2c7 Update CHANGELOG.md (#2124) 2025-08-27 20:01:11 +10:00
Joe Lim 7297e4f522 Add options for customizing the appearance of the menu (#2123)
* Refactor for loop

* Save menu selection

* Add options to customize menu style

* Add documentation
2025-08-27 19:49:07 +10:00
Joe Lim f2d2bb0f2c Draw menu over sixel images if they overlap (#2122)
* Refactor menu drawing code

* Fix menu and sixel overlap
2025-08-27 17:51:47 +10:00
Joe Lim 75334c25a5 Use ratio for more accurate humanize implementation (#2121) 2025-08-27 13:25:32 +10:00
Joe Lim ae583e96d3 Support XDG_CONFIG_HOME/XDG_DATA_HOME on Windows (#2119) 2025-08-26 22:55:45 +10:00
Joe Lim 4fe8f5a858 Add option to specify binary or decimal sizes (#2118)
* Add option to specify binary or decimal sizes

* Fix test case error message

* Add documentation

* Fix typo
2025-08-26 22:32:33 +10:00
Joe Lim 8150586bc2 Clear error messages after a command runs successfully (#2117)
* Draw stat info on demand

* Remove loadfileinfo function

* Fix clearmsg bug when opening directories

* Move visual code
2025-08-26 17:48:15 +10:00
Joe Lim 8f97bf806a Add unit tests for escape sequence parse functions (#2116) 2025-08-26 14:49:33 +10:00
Joe Lim 04afd78e65 Refactor dir.sort function (#2115)
* Refactor filtering code in `dir.sort` function

* Refactor sorting code in `dir.sort` function

* Fix bug
2025-08-26 14:16:54 +10:00
Joe Lim 4384e520b5 Update CONTRIBUTING.md (#2114) 2025-08-26 03:29:52 +10:00
Joe Lim e60c055be3 Remove experimental locale feature (#2111) 2025-08-26 01:41:01 +10:00
Joe Lim 06955cbacc Remove dircache option (#2110) 2025-08-25 23:06:30 +10:00
Joe Lim 13da770af6 Implement builtin support for sixel images, allow combining with text (#2109)
* Add function for reading lines in file

* Implement sixel drawing

* Remove sixel option

* Fix linting error
2025-08-25 22:19:14 +10:00
Joe Lim aba73884e3 Remove deprecated globfilter/globsearch options (#2108) 2025-08-25 15:14:28 +10:00
dependabot[bot] 5a4b0881d7 Bump github.com/gdamore/tcell/v2 from 2.8.1 to 2.9.0 (#2106)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.8.1 to 2.9.0.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv2.md)
- [Commits](https://github.com/gdamore/tcell/compare/v2.8.1...v2.9.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-25 15:06:06 +10:00
Joe Lim 6c13807a70 Prepare for r37 release (#2107) 2025-08-25 14:41:53 +10:00
Joe Lim 876e3067c6 Add support for disabling styles (#2101)
* Add support for disabling styles

* Update `CHANGELOG.md`
2025-08-18 15:45:47 +10:00
dependabot[bot] 17b576ead5 Bump actions/checkout from 4 to 5 (#2097)
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 5.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-13 12:44:28 +10:00
Joe Lim 2880cc92ed Remove explicit token in release workflow (#2096) 2025-08-12 16:07:47 +10:00
Joe Lim c9b023f546 Update CHANGELOG.md (#2094) 2025-08-12 14:47:17 +10:00
Joe Lim f716ce1b0f Show progress immediately when copying files (#2093) 2025-08-12 14:20:19 +10:00
Joe Lim 651264e4de Update CHANGELOG.md (#2092) 2025-08-11 21:10:40 +10:00
dependabot[bot] 3ac42fe1ad Bump golang.org/x/term from 0.33.0 to 0.34.0 (#2086)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.33.0 to 0.34.0.
- [Commits](https://github.com/golang/term/compare/v0.33.0...v0.34.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-08 13:35:45 +10:00
dependabot[bot] 0d005171f3 Bump golang.org/x/text from 0.27.0 to 0.28.0 (#2087)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.27.0 to 0.28.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.27.0...v0.28.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-08-08 13:29:58 +10:00
Joe Lim 56c28828f2 Fix multiple errors when moving or copying (#2089)
* Fix multiple errors when moving

* Fix multiple errors when copying
2025-08-08 13:25:03 +10:00
Joe Lim b38693f1c9 Fix missing errcount when moving cross devices fails (#2085)
* Fix missing errcount when moving cross devices fails

* Included count in error message
2025-08-08 11:46:07 +10:00
Joe Lim edc5d977cd Replace save buffer with clipboard struct (#2082) 2025-08-07 19:27:17 +10:00
Joe Lim 5ad11bdc84 Update CHANGELOG.md (#2080) 2025-08-07 16:35:23 +10:00
Joe Lim 02156a3806 Export command line flags as environment variables (#2079) 2025-08-07 15:59:13 +10:00
Joe Lim 42b36fd52c Improvements for command line completion (#2071)
- Refactor of the completion module, primarily to have the `match...` functions return the result for each possible match, so that they can be displayed when the user cycles through the completions using `cmd-menu-complete`/`cmd-menu-complete-back`
- Add support for completing list options (e.g. `set info user:group:size:time`)
- Provide different implementations for escaping/unescaping for `lfrc` command syntax, Unix and Windows. It is a bit hacky, but for now I want to keep `lf` as shell-agnostic as possible which means minimizing the logic based on `gOpts.shell`
- Fix alignment bug in the completion menu when displaying filenames with fullwidth characters
2025-08-07 15:14:25 +10:00
Joe Lim 88a599643d Pass all files for on-load hook command (#2077) 2025-08-06 19:23:40 +10:00
Joe Lim 9183e81f7f Reorder commands to be consistent with documentation (#2075) 2025-08-04 19:31:35 +10:00
Joe Lim 47b3bc5617 Sort options in alphabetical order (#2074)
* Sort options in alphabetical order

* Sort `eval.go` too
2025-08-04 16:26:33 +10:00
CatsDeservePets 44483d7872 Change order of gCmdWords (#2073)
* Special commands

* Normal mode commands

* Visual mode commands

* Command-line mode commands
2025-08-04 15:54:57 +10:00
Joe Lim 0a05a7106d Dircounts should have a width of 5 when displaying (#2072) 2025-07-31 17:12:01 +10:00
Joe Lim b0c3f8dbd7 Use the next upcoming version when generating lf.1 (#2068)
* Update man page to include version

* Use next version instead
2025-07-26 23:24:05 +10:00
Joe Lim d385c9bef8 Update CHANGELOG.md (#2067) 2025-07-26 22:44:42 +10:00
Andrew Voynov f6738eeda5 Update CONTRIBUTING.md for the updated gen/doc.sh (#2066) 2025-07-26 22:27:32 +10:00
Andrew Voynov a01e80b6ff Improve gen shell scripts (#2064)
* Improve gen shell scripts

* Remove unused gen/doc.sh

* Fix generated version in docs

* Make OCI program usage transparent

podman/docker/* as well as root(less) mode is detected automatically.
Formatted with 4 space indentation, added Vim modeline for convenience.

* Rename gen/doc{-with-docker,}.sh

Since the script is no longer docker-specific, it's better to drop the
more specific name.

* Add Vim modeline to build.sh and xbuild.sh
2025-07-26 22:00:03 +10:00
Joe Lim 46cc577d4a Cleanup (#2065) 2025-07-26 21:42:52 +10:00
CatsDeservePetsandJoe Lim ab662e6f33 Add filtermethod and searchmethod options (#2058)
* Add `filtermethod` and `searchmethod` options

* Rename `re` to `regex`

* Remove `globfilter` and `globsearch` options

* Add completions for `filtermethod` and `searchmethod`

* Update documentation

* Remove unnecessary if statement

* Fix unrelated typo

* Put options in alphabetical order

* Fix typo in documentation

* Rename variable for consistency

---------

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>
2025-07-26 21:25:45 +10:00
Andrew VoynovandJoe Lim 23b30ae1ee Change file size units to IEC 80000-13:2025 (binary multiples) (#2062)
* Change file size units from SI to IEC 80000-13:2025

Increase left-padded (%S) file size string length to 5 characters

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

* Add note about used IEC units for file size in docs

---------

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>
2025-07-26 19:03:13 +10:00
Joe Lim d60acef469 Refactor completion logic (#2061) 2025-07-22 22:13:11 +10:00
Joe Lim 5e24fd93d2 Ignore pasted input while in Normal mode (#2059) 2025-07-22 11:53:51 +10:00
Joe Lim 5b2d5ad99d Support wrapping while in Visual mode (#2056) 2025-07-20 19:54:30 +10:00
Joe Lim 041dfcc073 Revert "Respect symlinks when tagging files (#1997)" (#2055)
This reverts commit fe3a97c5d0.
2025-07-20 19:21:13 +10:00
CatsDeservePets c7b59d27ce Capitalize modes in code comments and documentation (#2054)
* Capitalize modes in documentation

* Capitalize modes in code comments
2025-07-20 12:08:24 +10:00
CatsDeservePets f27d82b391 Silence gopls hints (#2053) 2025-07-20 12:05:27 +10:00
Joe Lim 82a983d934 Separate config and data files for Windows (#2051) 2025-07-19 21:32:12 +10:00
Joe Lim 93400c11a0 Misc improvements for nav.checkDir (#2050)
* Misc improvements to `nav.checkDir`

* Fix case where `dircache` is disabled

* More fixes
2025-07-19 16:04:44 +10:00
Joe Lim c31b92491f Automatically load dircounts after enabling it (#2049) 2025-07-19 14:35:13 +10:00
dependabot[bot] f2d5d08952 Bump golang.org/x/text from 0.26.0 to 0.27.0 (#2036)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.26.0 to 0.27.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.26.0...v0.27.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-19 13:18:19 +10:00
dependabot[bot] 2788bc9b7f Bump golang.org/x/term from 0.32.0 to 0.33.0 (#2038)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.32.0 to 0.33.0.
- [Commits](https://github.com/golang/term/compare/v0.32.0...v0.33.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-07-19 13:08:42 +10:00
CatsDeservePets 87c994b9de Support btime in sortby and info (#2042)
* Add support for `btime` in `sortby` and `info`

* Update documentation

* Minor design improvements
2025-07-19 13:06:34 +10:00
CatsDeservePets 4758ef621c Respect dircounts when sorting by size (#668) (#2025)
* Respect `dircounts` when sorting by size

* Avoid mixing file sizes and counts when sorting by size

* Update documentation for sorting
2025-07-19 13:01:37 +10:00
52 changed files with 5918 additions and 3687 deletions

No files matched your search

+6 -6
View File
@@ -1,10 +1,10 @@
version: 2 version: 2
updates: updates:
- package-ecosystem: "github-actions" - package-ecosystem: github-actions
directory: "/" directory: /
schedule: schedule:
interval: "daily" interval: daily
- package-ecosystem: "gomod" - package-ecosystem: gomod
directory: "/" directory: /
schedule: schedule:
interval: "daily" interval: daily
+74 -35
View File
@@ -2,11 +2,23 @@ name: Go
on: on:
push: push:
branches: [ master ] branches: [master]
pull_request: pull_request:
branches: [ master ] branches: [master]
jobs: jobs:
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Setup Go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
- name: Check formatting
run: go fmt && git diff --exit-code
tests: tests:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
@@ -14,14 +26,12 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, windows-latest] os: [ubuntu-latest, windows-latest]
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
with:
fetch-depth: 1
- name: Set up Go - name: Setup Go
uses: actions/setup-go@v5 uses: actions/setup-go@v6
with: with:
go-version: "1.23" go-version-file: go.mod
- name: Build - name: Build
run: go build -v ./... run: go build -v ./...
@@ -29,38 +39,67 @@ jobs:
- name: Test - name: Test
run: go test -v ./... run: go test -v ./...
- uses: dominikh/staticcheck-action@v1.4.0 - name: golangci-lint
uses: golangci/golangci-lint-action@v9
with: with:
version: "2024.1.1" version: v2.5.0
install-go: false
cross-compile: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
include:
- { os: android, arch: arm64 }
- { os: darwin, arch: amd64 }
- { os: darwin, arch: arm64 }
- { os: dragonfly, arch: amd64 }
- { os: freebsd, arch: "386" }
- { os: freebsd, arch: amd64 }
- { os: freebsd, arch: arm }
- { os: illumos, arch: amd64 }
- { os: linux, arch: "386" }
- { os: linux, arch: amd64 }
- { os: linux, arch: arm }
- { os: linux, arch: arm64 }
- { os: linux, arch: ppc64 }
- { os: linux, arch: ppc64le }
- { os: linux, arch: mips }
- { os: linux, arch: mipsle }
- { os: linux, arch: mips64 }
- { os: linux, arch: mips64le }
- { os: linux, arch: s390x }
- { os: netbsd, arch: "386" }
- { os: netbsd, arch: amd64 }
- { os: netbsd, arch: arm }
- { os: openbsd, arch: "386" }
- { os: openbsd, arch: amd64 }
- { os: openbsd, arch: arm }
- { os: openbsd, arch: arm64 }
- { os: solaris, arch: amd64 }
- { os: windows, arch: "386" }
- { os: windows, arch: amd64 }
# Unsupported
# - { os: aix, arch: ppc64 }
# - { os: android, arch: "386" }
# - { os: android, arch: amd64 }
# - { os: android, arch: arm }
# - { os: js, arch: wasm }
# - { os: plan9, arch: "386" }
# - { os: plan9, arch: amd64 }
# - { os: plan9, arch: arm }
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
with: with:
fetch-depth: 1 fetch-depth: 0 # https://github.com/actions/checkout/issues/2199
fetch-tags: true
- name: Set up Go - name: Setup Go
uses: actions/setup-go@v5 uses: actions/setup-go@v6
with: with:
go-version: "1.23" go-version-file: go.mod
- name: Cross-compile on all supported platforms
run: gen/xbuild.sh
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Test `go fmt` creates no diffs
run: go fmt && git diff --exit-code
- name: Build
run: gen/build.sh
env:
GOOS: ${{ matrix.os }}
GOARCH: ${{ matrix.arch }}
+72 -9
View File
@@ -3,29 +3,92 @@ name: Release
on: on:
push: push:
tags: tags:
- '*' - "*"
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy:
matrix:
include:
- { os: android, arch: arm64 }
- { os: darwin, arch: amd64 }
- { os: darwin, arch: arm64 }
- { os: dragonfly, arch: amd64 }
- { os: freebsd, arch: "386" }
- { os: freebsd, arch: amd64 }
- { os: freebsd, arch: arm }
- { os: illumos, arch: amd64 }
- { os: linux, arch: "386" }
- { os: linux, arch: amd64 }
- { os: linux, arch: arm }
- { os: linux, arch: arm64 }
- { os: linux, arch: ppc64 }
- { os: linux, arch: ppc64le }
- { os: linux, arch: mips }
- { os: linux, arch: mipsle }
- { os: linux, arch: mips64 }
- { os: linux, arch: mips64le }
- { os: linux, arch: s390x }
- { os: netbsd, arch: "386" }
- { os: netbsd, arch: amd64 }
- { os: netbsd, arch: arm }
- { os: openbsd, arch: "386" }
- { os: openbsd, arch: amd64 }
- { os: openbsd, arch: arm }
- { os: openbsd, arch: arm64 }
- { os: solaris, arch: amd64 }
- { os: windows, arch: "386" }
- { os: windows, arch: amd64 }
# Unsupported
# - { os: aix, arch: ppc64 }
# - { os: android, arch: "386" }
# - { os: android, arch: amd64 }
# - { os: android, arch: arm }
# - { os: js, arch: wasm }
# - { os: plan9, arch: "386" }
# - { os: plan9, arch: amd64 }
# - { os: plan9, arch: arm }
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v6
- name: Set up Go - name: Setup Go
uses: actions/setup-go@v5 uses: actions/setup-go@v6
with: with:
go-version: "1.23" go-version-file: go.mod
- name: Build - name: Build
run: gen/xbuild.sh run: gen/build.sh
env:
GOOS: ${{ matrix.os }}
GOARCH: ${{ matrix.arch }}
- name: Package
run: gen/package.sh
env:
GOOS: ${{ matrix.os }}
GOARCH: ${{ matrix.arch }}
- name: Upload artifact
uses: actions/upload-artifact@v5
with:
name: lf-${{ matrix.os }}-${{ matrix.arch }}
path: dist/*
release:
runs-on: ubuntu-latest
needs: build
steps:
- name: Download artifacts
uses: actions/download-artifact@v6
with:
path: dist
merge-multiple: true
- name: Release - name: Release
uses: softprops/action-gh-release@v2 uses: softprops/action-gh-release@v2
with: with:
files: dist/* files: dist/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
winget: winget:
runs-on: ubuntu-latest runs-on: ubuntu-latest
+23
View File
@@ -0,0 +1,23 @@
version: "2"
linters:
settings:
errcheck:
exclude-functions:
- (*github.com/fsnotify/fsnotify.Watcher).Close
- (*net.TCPConn).CloseWrite
- (*net.UnixConn).CloseWrite
- (*os.File).Close
- (*os.File).Write
- (*text/tabwriter.Writer).Flush
- (io.Closer).Close
- (io.Writer).Write
- (net.Conn).Close
- (net.Listener).Close
- fmt.Fprintf
- fmt.Fprintln
- io.WriteString
- os.Setenv
- syscall.Close
issues:
max-issues-per-linter: 0 # no limit
max-same-issues: 0 # no limit
+96
View File
@@ -8,6 +8,102 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- `Added` - `Added`
- `Fixed` - `Fixed`
## [r39](https://github.com/gokcehan/lf/releases/tag/r39)
### Changed
- File extensions are now shown for long filenames even if they are truncated (#2159).
- The history file will no longer contain a space between the prefix and the actual command (e.g. `:quit` instead of `: quit`) for each line (#2161). The command `sed -i -E 's/^(.) /\1/' ~/.local/share/lf/history` can be run to make an existing history file compatible with the new format.
- The `cmd-history-next` and `cmd-history-prev` commands will now select only matching entries if part of the command is typed beforehand (#2161). Consecutive duplicate entries will also be skipped for convenience.
- The string representation of commands shown when displaying keybindings is simplified (e.g. `cd ~` instead of `cd -- [~]`) (#2165).
- `yes-no-prompts` now use the same design everywhere (#2212).
- Logs generated by `-log <path>` now get appended to `<path>` instead of overwriting it (#2215).
- The `showbinds` menu now hides the redundant `mode` column (#2226) (#2228) and omits already typed keys (#2249).
- The `setlocal` command no longer requires absolute paths (#2253).
- The string representation of file permissions now matches the traditional `Unix` format instead of the one used by `Go` (#2270).
### Added
- A new command `cmd-menu-discard` is added to allow exiting the completion menu with completions discarded (#2146).
- The `lf_mode` environment variable will now be set to `compmenu` if the completion menu is active (#2146).
- A `ruler` config file is added as an alternate method for customizing the ruler (#2186). This is intended to eventually replace the existing `rulerfmt`/`statfmt` options and must be enabled using the new `rulerfile` option. **This feature is currently experimental.**
- A new option `preload` is added to enable calling the `previewer` to generate previews in advance (#2206). **This feature is currently experimental.**
- `OSC 8` escape codes to render clickable hyperlinks are now supported (#2243).
### Fixed
- `shell-pipe` commands no longer wait for output if kept open after the command has finished running (#2155).
- Natural sorting now compares string lengths when dealing with equivalent numbers (e.g. `0` is ordered before `00`) (#2177).
- A bug where the copy progress indicator only displayed the first time a file was copied is now fixed (#2181).
- A bug where the `source` command does not show an error message upon failure is now fixed (#2189).
- The `addcustominfo` (#2198) and `setlocal` (#2254) (#2259) commands, as well as the `cleaner` and `previewer` options (#2211) now support filename completions.
- A bug where an empty `custom` info property would still take up space is now fixed (#2208).
- A bug where setting `drawbox` could lead to scrolling outside the view is now fixed (#2210) (#2218).
- The preview cache is now not cleared when setting `ratios` to its current value (#2218).
- Filtering is fixed when using special characters in the search pattern if the `filtermethod` is `text` (#2231).
- Custom commands that output messages (e.g. `cmd greet echo 'hello world'`) now display properly (#2245).
- Errors in config files are now displayed properly (#2246).
## [r38](https://github.com/gokcehan/lf/releases/tag/r38)
### Changed
- The deprecated `globfilter` and `globsearch` options are now removed (#2108).
- Sixel image support is now enabled by default, and the `sixel` option has been removed as it is no longer required (#2109).
- The `dircache` option has now been removed (#2110). This was previously used as a workaround to disable the directory cache since at the time changes to files were not detected reliably, but this is no longer the case.
- The experimental `locale` option has been removed in favor of the recommendation to use `addcustominfo`/`set sortby custom` for custom sorting (#2111).
- The existing `doc` command has been renamed to `help` so that it is more natural for users (#2125).
- Text previews are no longer displayed with a padding of two spaces by default (#2131). Instead, a custom padding can be added in the `previewer` script, for example by piping to `sed 's/^/ /'`.
### Added
- Sixel image previews can now display multiple images as well as text (#2109).
- A new option `sizeunits` is added to allow displaying file sizes in either binary or decimal units (#2118).
- `XDG_CONFIG_HOME` and `XDG_DATA_HOME` are now taken into account when looking up config/data files on Windows (#2119).
- Three new options `menufmt`, `menuheaderfmt`, and `menuselectfmt` are added to customize the appearance of the menu (#2123).
### Fixed
- Error messages are now cleared after running interactive commands such as `invert`/`unselect`/`tag-toggle` (#2117).
- The menu is now drawn over sixel images instead of being hidden behind it if they overlap (#2122).
- A bug which prevents the user from quitting when copying files with a size of 0 has been fixed (#2130).
- `lf -remote` should no longer busy wait and cause high CPU usage if its output is not being read (#2138).
- The parameter types for command line options shown by `lf -help` now match the synopsis in the documentation (#2153).
## [r37](https://github.com/gokcehan/lf/releases/tag/r37)
### Changed
- The default paths of files read by `lf` is changed on Windows, to separate configuration files from data files (#2051).
- Configuration files (`lfrc`/`colors`/`icons`) are now stored in `%APPDATA%`, which can be overridden by `%LF_CONFIG_HOME%`.
- Data files (`files`/`marks`/`tags`/`history`) are now stored in `%LOCALAPPDATA%`, which can be overridden by `%LF_DATA_HOME%`.
- The change for following symbolic links when tagging files from the previous release has been reverted (#2055). The previous change made it impossible to tag symbolic links separately from their targets, and also caused `lf` to run slowly in some cases.
- The existing `globfilter` and `globsearch` options are now deprecated in favor of the new `filtermethod` and `searchmethod` options, which support regex patterns (#2058).
- `set globfilter true` should be replaced by `set filtermethod glob`.
- `set globsearch true` should be replaced by `set searchmethod glob`.
- File sizes are now displayed using binary units (e.g. `1.0K` means 1024 bytes, not 1000 bytes) (#2062). The maximum width for displaying the file size has been increased from four to five characters.
### Added
- `dircounts` are now respected when sorting by size (#2025).
- The `info` and `sortby` options now support `btime` (file creation time) (#2042). This depends on support for file creation times from the underlying system.
- The selection in Visual mode now follows wrapping when `wrapscan`/`wrapscroll` is enabled (#2056).
- Input pasted from the terminal is now ignored while in Normal mode (#2059). This prevents pasted content from being treated as keybindings, which can result in dangerous unintended behavior.
- The Command-line mode completion now supports keywords for the `selmode` and `sortby` options (#2061), as well as the `info` and `preserve` options (#2071).
- Command line options are now exported as environment variables in the form `lf_flag_{flag}` (#2079).
- Support is added for terminal escape sequences that disable text styles (#2101).
### Fixed
- `dircounts` are now automatically populated after enabling it (#2049).
- A bug where directories are unsorted after reloading when `dircache` is disabled is now fixed (#2050).
- Filenames are now escaped when completing shell commands (#2071).
- A bug where completion menu entries are misaligned when containing fullwidth characters is now fixed (#2071).
- The `on-load` command now passes all files in the directory as arguments, not just files visible to the user (#2077).
- Failure to move files across different filesystems is now shown as an error instead of a success in the UI (#2085).
- Errors are now logged correctly when there are multiple errors during move/copy operations (#2089).
- The progress for copy operations is now displayed immediately in the UI, even if it takes time to calculate the total size of files to be copied (#2093).
## [r36](https://github.com/gokcehan/lf/releases/tag/r36) ## [r36](https://github.com/gokcehan/lf/releases/tag/r36)
### Changed ### Changed
+6 -3
View File
@@ -28,7 +28,7 @@ Adding a new option usually requires the following steps:
- Add option evaluation logic to `setExpr.eval` in `eval.go` - Add option evaluation logic to `setExpr.eval` in `eval.go`
- Implement the option somewhere in the code - Implement the option somewhere in the code
- Add option name and its default value to `Quick Reference` and `Options` sections in `doc.md` - Add option name and its default value to `Quick Reference` and `Options` sections in `doc.md`
- Run `gen/doc-with-docker.sh` to update the documentation - Run `gen/doc.sh` to update the documentation (optional as it requires `docker`/`podman`, but appreciated)
- Commit your changes and send a pull request - Commit your changes and send a pull request
## Adding a new builtin command ## Adding a new builtin command
@@ -40,11 +40,14 @@ Adding a new command usually requires the following steps:
- Implement the command somewhere in the code - Implement the command somewhere in the code
- Add command name to `gCmdWords` in `complete.go` for tab completion - Add command name to `gCmdWords` in `complete.go` for tab completion
- Add command name to `Quick Reference` and `Commands` sections in `doc.md` - Add command name to `Quick Reference` and `Commands` sections in `doc.md`
- Optionally, run `gen/doc-with-docker.sh` to update the documentation - Run `gen/doc.sh` to update the documentation (optional as it requires `docker`/`podman`, but appreciated)
- Commit your changes and send a pull request - Commit your changes and send a pull request
## Platform specific code ## Platform specific code
There are two files named `os.go` and `os_windows.go` for unix and windows specific code respectively. There are two files named `os.go` and `os_windows.go` for Unix and Windows specific code respectively.
If you add something to either of these files but not the other, you probably break the build for the other platform. If you add something to either of these files but not the other, you probably break the build for the other platform.
If your addition works the same in both platforms, your addition probably belongs to `main.go` instead. If your addition works the same in both platforms, your addition probably belongs to `main.go` instead.
There are also different variants of the `df` functionality provided by `df_openbsd.go`, `df_statfs.go`, `df_statvfs.go` and `df_windows.go`.
Where applicable, ensure that any changes you make are reflected across all of these files for consistency.
+2 -3
View File
@@ -1,9 +1,7 @@
# LF # LF
[Google Groups](https://groups.google.com/forum/#!forum/lf-fm) [Doc](doc.md)
| [Doc](doc.md)
| [Wiki](https://github.com/gokcehan/lf/wiki) | [Wiki](https://github.com/gokcehan/lf/wiki)
| [#lf](https://web.libera.chat/#lf) (on Libera.Chat)
| [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge) | [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge)
[![Go Build](https://github.com/gokcehan/lf/actions/workflows/go.yml/badge.svg)](https://github.com/gokcehan/lf/actions/workflows/go.yml) [![Go Build](https://github.com/gokcehan/lf/actions/workflows/go.yml/badge.svg)](https://github.com/gokcehan/lf/actions/workflows/go.yml)
@@ -14,6 +12,7 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tut
![icons-and-border](https://github.com/user-attachments/assets/d5623462-05ab-4921-aeb3-d377d4732f9e) ![icons-and-border](https://github.com/user-attachments/assets/d5623462-05ab-4921-aeb3-d377d4732f9e)
![image-preview](https://github.com/user-attachments/assets/9ff42a21-19dd-42fa-8407-5d055aa9d561) ![image-preview](https://github.com/user-attachments/assets/9ff42a21-19dd-42fa-8407-5d055aa9d561)
![new-features](https://github.com/user-attachments/assets/2a9a32aa-a764-438f-a810-e687e979dcee)
## Features ## Features
+162 -92
View File
@@ -2,23 +2,22 @@ package main
import ( import (
"bufio" "bufio"
"cmp"
"errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"os/signal" "os/signal"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"syscall" "syscall"
"time" "time"
) )
type cmdItem struct {
prefix string
value string
}
type app struct { type app struct {
ui *ui ui *ui
nav *nav nav *nav
@@ -27,11 +26,13 @@ type app struct {
cmd *exec.Cmd cmd *exec.Cmd
cmdIn io.WriteCloser cmdIn io.WriteCloser
cmdOutBuf []byte cmdOutBuf []byte
cmdHistory []cmdItem cmdHistory []string
cmdHistoryBeg int cmdHistoryBeg int
cmdHistoryInd int cmdHistoryInd int
cmdHistoryInput *string
menuCompActive bool menuCompActive bool
menuComps []string menuCompTmp []string
menuComps []compMatch
menuCompInd int menuCompInd int
selectionOut []string selectionOut []string
watch *watch watch *watch
@@ -115,71 +116,79 @@ func (app *app) readFile(path string) {
} }
} }
func loadFiles() (list []string, cp bool, err error) { func loadFiles() (clipboard clipboard, err error) {
files, err := os.Open(gFilesPath) files, err := os.Open(gFilesPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
err = nil err = nil
return return
} }
if err != nil { if err != nil {
err = fmt.Errorf("opening file selections file: %s", err) err = fmt.Errorf("opening file selections file: %w", err)
return return
} }
defer files.Close() defer files.Close()
s := bufio.NewScanner(files) s := bufio.NewScanner(files)
s.Scan() if !s.Scan() {
err = fmt.Errorf("scanning file list: %w", cmp.Or(s.Err(), io.EOF))
return
}
switch s.Text() { switch s.Text() {
case "copy": case "copy":
cp = true clipboard.mode = clipboardCopy
case "move": case "move":
cp = false clipboard.mode = clipboardCut
default: default:
err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text()) err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text())
return return
} }
for s.Scan() && s.Text() != "" { for s.Scan() && s.Text() != "" {
list = append(list, s.Text()) clipboard.paths = append(clipboard.paths, s.Text())
} }
if s.Err() != nil { if s.Err() != nil {
err = fmt.Errorf("scanning file list: %s", s.Err()) err = fmt.Errorf("scanning file list: %w", s.Err())
return return
} }
log.Printf("loading files: %v", list) log.Printf("loading clipboard: %v", clipboard.paths)
return return
} }
func saveFiles(list []string, cp bool) error { func saveFiles(clipboard clipboard) error {
if err := os.MkdirAll(filepath.Dir(gFilesPath), os.ModePerm); err != nil { if err := os.MkdirAll(filepath.Dir(gFilesPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err) return fmt.Errorf("creating data directory: %w", err)
} }
files, err := os.Create(gFilesPath) files, err := os.Create(gFilesPath)
if err != nil { if err != nil {
return fmt.Errorf("opening file selections file: %s", err) return fmt.Errorf("opening file selections file: %w", err)
} }
defer files.Close() defer files.Close()
log.Printf("saving files: %v", list) log.Printf("saving files: %v", clipboard.paths)
if cp { var clipboardModeStr string
fmt.Fprintln(files, "copy") if clipboard.mode == clipboardCopy {
clipboardModeStr = "copy"
} else { } else {
fmt.Fprintln(files, "move") clipboardModeStr = "move"
}
if _, err := fmt.Fprintln(files, clipboardModeStr); err != nil {
return fmt.Errorf("write clipboard mode to file: %w", err)
} }
for _, f := range list { for _, path := range clipboard.paths {
fmt.Fprintln(files, f) if _, err := fmt.Fprintln(files, path); err != nil {
return fmt.Errorf("write path to file: %w", err)
}
} }
files.Sync() return files.Sync()
return nil
} }
func (app *app) readHistory() error { func (app *app) readHistory() error {
@@ -188,26 +197,23 @@ func (app *app) readHistory() error {
return nil return nil
} }
if err != nil { if err != nil {
return fmt.Errorf("opening history file: %s", err) return fmt.Errorf("opening history file: %w", err)
} }
defer f.Close() defer f.Close()
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2) cmd := scanner.Text()
if toks[0] != ":" && toks[0] != "$" && toks[0] != "%" && toks[0] != "!" && toks[0] != "&" { if len(cmd) < 1 || !slices.Contains([]string{":", "$", "!", "%", "&"}, cmd[:1]) {
continue continue
} }
if len(toks) < 2 { app.cmdHistory = append(app.cmdHistory, cmd)
continue
}
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
} }
app.cmdHistoryBeg = len(app.cmdHistory) app.cmdHistoryBeg = len(app.cmdHistory)
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
return fmt.Errorf("reading history file: %s", err) return fmt.Errorf("reading history file: %w", err)
} }
return nil return nil
@@ -218,34 +224,31 @@ func (app *app) writeHistory() error {
return nil return nil
} }
local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg) local := slices.Clone(app.cmdHistory[app.cmdHistoryBeg:])
copy(local, app.cmdHistory[app.cmdHistoryBeg:])
app.cmdHistory = nil app.cmdHistory = nil
if err := app.readHistory(); err != nil { if err := app.readHistory(); err != nil {
return fmt.Errorf("reading history file: %s", err) return fmt.Errorf("reading history file: %w", err)
} }
app.cmdHistory = append(app.cmdHistory, local...) app.cmdHistory = append(app.cmdHistory, local...)
if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
f, err := os.Create(gHistoryPath)
if err != nil {
return fmt.Errorf("creating history file: %s", err)
}
defer f.Close()
if len(app.cmdHistory) > 1000 { if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:] app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
} }
for _, cmd := range app.cmdHistory { if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
_, err = fmt.Fprintf(f, "%s %s\n", cmd.prefix, cmd.value) return fmt.Errorf("creating data directory: %w", err)
}
f, err := os.Create(gHistoryPath)
if err != nil { if err != nil {
return fmt.Errorf("writing history file: %s", err) return fmt.Errorf("creating history file: %w", err)
}
defer f.Close()
for _, cmd := range app.cmdHistory {
if _, err = fmt.Fprintln(f, cmd); err != nil {
return fmt.Errorf("writing history file: %w", err)
} }
} }
@@ -257,6 +260,7 @@ func (app *app) writeHistory() error {
// for evaluation. Similarly directories and regular files are also read in // for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update. // separate goroutines and sent here for update.
func (app *app) loop() { func (app *app) loop() {
go app.nav.preloadLoop(app.ui)
go app.nav.previewLoop(app.ui) go app.nav.previewLoop(app.ui)
var serverChan <-chan expr var serverChan <-chan expr
@@ -297,7 +301,7 @@ func (app *app) loop() {
log.Printf("getting current directory: %s", err) log.Printf("getting current directory: %s", err)
} }
app.nav.getDirs(wd) app.nav.updateDirs(wd)
app.nav.addJumpList() app.nav.addJumpList()
app.nav.init = true app.nav.init = true
@@ -317,7 +321,7 @@ func (app *app) loop() {
for { for {
select { select {
case <-app.quitChan: case <-app.quitChan:
if app.nav.copyTotal > 0 { if app.nav.copyJobs > 0 {
app.ui.echoerr("quit: copy operation in progress") app.ui.echoerr("quit: copy operation in progress")
continue continue
} }
@@ -336,9 +340,12 @@ func (app *app) loop() {
app.nav.previewChan <- "" app.nav.previewChan <- ""
log.Print("bye!") log.Printf("*************** closing client, PID: %d ***************", os.Getpid())
return return
case n := <-app.nav.copyJobsChan:
app.nav.copyJobs += n
app.ui.draw(app.nav)
case n := <-app.nav.copyBytesChan: case n := <-app.nav.copyBytesChan:
app.nav.copyBytes += n app.nav.copyBytes += n
// n is usually 32*1024B (default io.Copy() buffer) so update roughly per 32KB x 128 = 4MB copied // n is usually 32*1024B (default io.Copy() buffer) so update roughly per 32KB x 128 = 4MB copied
@@ -386,19 +393,17 @@ func (app *app) loop() {
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
case d := <-app.nav.dirChan: case d := <-app.nav.dirChan:
if gOpts.dircache {
prev, ok := app.nav.dirCache[d.path] prev, ok := app.nav.dirCache[d.path]
if ok { if ok {
d.ind = prev.ind d.ind = prev.ind
d.pos = prev.pos d.pos = prev.pos
d.visualAnchor = min(prev.visualAnchor, len(d.files)-1) d.visualAnchor = min(prev.visualAnchor, len(d.files)-1)
d.visualWrap = prev.visualWrap
d.filter = prev.filter d.filter = prev.filter
d.sort() d.sort()
d.sel(prev.name(), app.nav.height) d.sel(prev.name(), app.nav.height)
} }
app.nav.dirCache[d.path] = d app.nav.dirCache[d.path] = d
}
var oldCurrPath string var oldCurrPath string
if curr, err := app.nav.currFile(); err == nil { if curr, err := app.nav.currFile(); err == nil {
@@ -417,9 +422,6 @@ func (app *app) loop() {
if err == nil { if err == nil {
if curr.path != oldCurrPath { if curr.path != oldCurrPath {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav)
}
} }
if d.path == curr.path { if d.path == curr.path {
app.ui.dirPrev = d app.ui.dirPrev = d
@@ -427,7 +429,17 @@ func (app *app) loop() {
} }
app.watchDir(d) app.watchDir(d)
onLoad(app, d.fileNames())
paths := []string{}
for _, file := range d.allFiles {
paths = append(paths, file.path)
}
onLoad(app, paths)
if d.path == app.nav.currDir().path {
app.nav.preload()
}
app.ui.draw(app.nav) app.ui.draw(app.nav)
case r := <-app.nav.regChan: case r := <-app.nav.regChan:
app.nav.regCache[r.path] = r app.nav.regCache[r.path] = r
@@ -436,8 +448,9 @@ func (app *app) loop() {
if err == nil { if err == nil {
if r.path == curr.path { if r.path == curr.path {
app.ui.regPrev = r app.ui.regPrev = r
if gOpts.sixel {
app.ui.sxScreen.forceClear = true app.ui.sxScreen.forceClear = true
if gOpts.preload && r.volatile {
app.ui.loadFile(app, true)
} }
} }
} }
@@ -461,11 +474,8 @@ func (app *app) loop() {
dir.sel(name, app.nav.height) dir.sel(name, app.nav.height)
} }
delete(app.nav.regCache, f.path)
app.ui.loadFile(app, false) app.ui.loadFile(app, false)
if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav)
}
onLoad(app, []string{f.path}) onLoad(app, []string{f.path})
app.ui.draw(app.nav) app.ui.draw(app.nav)
case path := <-app.nav.delChan: case path := <-app.nav.delChan:
@@ -480,7 +490,7 @@ func (app *app) loop() {
currPath := app.nav.currDir().path currPath := app.nav.currDir().path
if currPath == path || strings.HasPrefix(currPath, path+string(filepath.Separator)) { if currPath == path || strings.HasPrefix(currPath, path+string(filepath.Separator)) {
if wd, err := os.Getwd(); err == nil { if wd, err := os.Getwd(); err == nil {
app.nav.getDirs(wd) app.nav.updateDirs(wd)
} }
} }
case ev := <-app.ui.evChan: case ev := <-app.ui.evChan:
@@ -515,11 +525,13 @@ func (app *app) loop() {
case <-app.nav.previewTimer.C: case <-app.nav.previewTimer.C:
app.nav.previewLoading = true app.nav.previewLoading = true
app.ui.draw(app.nav) app.ui.draw(app.nav)
case <-app.nav.preloadTimer.C:
app.nav.preload()
} }
} }
} }
func (app *app) runCmdSync(cmd *exec.Cmd, pause_after bool) { 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 {
@@ -535,7 +547,7 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pause_after bool) {
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
app.ui.echoerrf("running shell: %s", err) app.ui.echoerrf("running shell: %s", err)
} }
if pause_after { if pauseAfter {
anyKey() anyKey()
} }
@@ -579,8 +591,6 @@ func (app *app) runShell(s string, args []string, prefix string) {
cmd := shellCommand(s, args) cmd := shellCommand(s, args)
var out io.Reader
var err error
switch prefix { switch prefix {
case "$", "!": case "$", "!":
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
@@ -592,25 +602,35 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
// We are running the command asynchronously // We are running the command asynchronously
var inReader, inWriter, outReader, outWriter *os.File
if prefix == "%" { if prefix == "%" {
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return
} }
stdin, err := cmd.StdinPipe()
// Cmd.StdoutPipe cannot be used as it requires the output to be fully
// read before calling Cmd.Wait, however in this case Cmd.Wait should
// only wait for the command to finish executing regardless of whether
// the output has been fully read or not.
inReader, inWriter, err := os.Pipe()
if err != nil { if err != nil {
log.Printf("writing stdin: %s", err) log.Printf("creating input pipe: %s", err)
return
} }
app.cmdIn = stdin cmd.Stdin = inReader
stdout, err := cmd.StdoutPipe() app.cmdIn = inWriter
outReader, outWriter, err = os.Pipe()
if err != nil { if err != nil {
log.Printf("reading stdout: %s", err) log.Printf("creating output pipe: %s", err)
return
} }
out = stdout cmd.Stdout = outWriter
cmd.Stderr = cmd.Stdout cmd.Stderr = outWriter
} }
shellSetPG(cmd) shellSetPG(cmd)
if err = cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
app.ui.echoerrf("running shell: %s", err) app.ui.echoerrf("running shell: %s", err)
} }
@@ -623,30 +643,36 @@ func (app *app) runShell(s string, args []string, prefix string) {
app.ui.echo("") app.ui.echo("")
go func() { go func() {
eol := false reader := bufio.NewReader(outReader)
reader := bufio.NewReader(out)
for { for {
b, err := reader.ReadByte() b, err := reader.ReadByte()
if err == io.EOF { if err != nil {
if !errors.Is(err, io.EOF) && !errors.Is(err, fs.ErrClosed) {
log.Printf("reading command output: %s", err)
}
break break
} }
if eol {
eol = false
app.cmdOutBuf = nil
}
app.cmdOutBuf = append(app.cmdOutBuf, b) app.cmdOutBuf = append(app.cmdOutBuf, b)
if b == '\n' || b == '\r' { if reader.Buffered() == 0 {
eol = true
}
if reader.Buffered() > 0 {
continue
}
app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1} app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1}
} }
if b == '\n' || b == '\r' {
app.cmdOutBuf = nil
}
}
}()
go func() {
if err := cmd.Wait(); err != nil { if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err) log.Printf("running shell: %s", err)
} }
inReader.Close()
inWriter.Close()
outReader.Close()
outWriter.Close()
app.cmd = nil app.cmd = nil
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"load", nil, 1} app.ui.exprChan <- &callExpr{"load", nil, 1}
@@ -661,6 +687,46 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
} }
func (app *app) doComplete() (matches []compMatch) {
var result string
switch app.ui.cmdPrefix {
case ":":
matches, result = completeCmd(app.ui.cmdAccLeft)
case "$", "%", "!", "&":
matches, result = completeShell(app.ui.cmdAccLeft)
case "/", "?":
matches, result = completeSearch(app.ui.cmdAccLeft)
}
app.ui.cmdAccLeft = []rune(result)
app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, matches, -1)
return
}
func (app *app) menuComplete(direction int) {
if !app.menuCompActive {
app.menuCompTmp = tokenize(string(app.ui.cmdAccLeft))
app.menuComps = app.doComplete()
if len(app.menuComps) > 1 {
app.menuCompInd = -1
app.menuCompActive = true
}
} else {
app.menuCompInd += direction
if app.menuCompInd == len(app.menuComps) {
app.menuCompInd = 0
} else if app.menuCompInd < 0 {
app.menuCompInd = len(app.menuComps) - 1
}
toks := slices.Clone(app.menuCompTmp)
toks[len(toks)-1] = app.menuComps[app.menuCompInd].result
app.ui.cmdAccLeft = []rune(strings.Join(toks, " "))
}
app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, app.menuComps, app.menuCompInd)
}
func (app *app) watchDir(dir *dir) { func (app *app) watchDir(dir *dir) {
if !gOpts.watch { if !gOpts.watch {
return return
@@ -678,6 +744,10 @@ func (app *app) watchDir(dir *dir) {
func (app *app) exportMode() { func (app *app) exportMode() {
getMode := func() string { getMode := func() string {
if app.menuCompActive {
return "compmenu"
}
if strings.HasPrefix(app.ui.cmdPrefix, "delete") { if strings.HasPrefix(app.ui.cmdPrefix, "delete") {
return "delete" return "delete"
} }
+33 -16
View File
@@ -27,7 +27,7 @@ func init() {
func run() { func run() {
if gLogPath != "" { if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 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("failed to open log file: %s", err)
} }
@@ -37,7 +37,7 @@ func run() {
log.SetOutput(io.Discard) log.SetOutput(io.Discard)
} }
log.Print("hi!") log.Printf("*************** starting client, PID: %d ***************", os.Getpid())
var screen tcell.Screen var screen tcell.Screen
var err error var err error
@@ -49,9 +49,10 @@ func run() {
if gOpts.mouse { if gOpts.mouse {
screen.EnableMouse() screen.EnableMouse()
} }
screen.EnablePaste()
ui := newUI(screen) ui := newUI(screen)
nav := newNav(ui.wins[0].h) nav := newNav(ui)
app := newApp(ui, nav) app := newApp(ui, nav)
if err := nav.sync(); err != nil { if err := nav.sync(); err != nil {
@@ -127,7 +128,9 @@ func readExpr() <-chan expr {
c, err = net.Dial(gSocketProt, gSocketPath) c, err = net.Dial(gSocketProt, gSocketPath)
} }
fmt.Fprintf(c, "conn %d\n", gClientID) if _, err := fmt.Fprintf(c, "conn %d\n", gClientID); err != nil {
log.Fatalf("registering with server: %s", err)
}
ch <- &callExpr{"sync", nil, 1} ch <- &callExpr{"sync", nil, 1}
ch <- &callExpr{"on-init", nil, 1} ch <- &callExpr{"on-init", nil, 1}
@@ -142,12 +145,11 @@ func readExpr() <-chan expr {
// running `$lf -remote "query $id <something>"`. // running `$lf -remote "query $id <something>"`.
if word, rest := splitWord(s.Text()); word == "query" { if word, rest := splitWord(s.Text()); word == "query" {
gState.mutex.Lock() gState.mutex.Lock()
state, ok := gState.data[rest] state := gState.data[rest]
gState.mutex.Unlock() gState.mutex.Unlock()
if ok { if _, err := fmt.Fprintln(c, state); err != nil {
fmt.Fprint(c, state) log.Fatalf("sending response to server: %s", err)
} }
fmt.Fprintln(c, "")
} else { } else {
p := newParser(strings.NewReader(s.Text())) p := newParser(strings.NewReader(s.Text()))
if p.parse() { if p.parse() {
@@ -156,6 +158,10 @@ func readExpr() <-chan expr {
} }
} }
if err := s.Err(); err != nil {
log.Printf("reading from server: %s", err)
}
c.Close() c.Close()
}() }()
@@ -165,25 +171,36 @@ func readExpr() <-chan expr {
func remote(cmd string) error { func remote(cmd string) error {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { if err != nil {
return fmt.Errorf("dialing to send server: %s", err) return fmt.Errorf("dialing to send server: %w", err)
} }
fmt.Fprintln(c, cmd) if _, err := fmt.Fprintln(c, cmd); err != nil {
return fmt.Errorf("sending command to server: %w", err)
}
// XXX: Standard net.Conn interface does not include a CloseWrite method // XXX: Standard net.Conn interface does not include a CloseWrite method
// but net.UnixConn and net.TCPConn implement it so the following should be // but net.UnixConn and net.TCPConn implement it so the following should be
// safe as long as we do not use other types of connections. We need // safe as long as we do not use other types of connections. We need
// CloseWrite to notify the server that this is not a persistent connection // CloseWrite to notify the server that this is not a persistent connection
// and it should be closed after the response. // and it should be closed after the response.
if v, ok := c.(interface { switch c := c.(type) {
CloseWrite() error case *net.TCPConn:
}); ok { c.CloseWrite()
v.CloseWrite() case *net.UnixConn:
c.CloseWrite()
} }
io.Copy(os.Stdout, c) // The most straightforward way to write the response to stdout would be
// to do "io.Copy(os.Stdout, c)". However, on Linux, if stdout is connected to
// something like a pager that isn't immediately reading everything,
// this runs into Go bug https://github.com/golang/go/issues/75304 and
// busy-loops, eating a whole CPU.
response, err := io.ReadAll(c)
if err != nil {
return fmt.Errorf("reading response from server: %w", err)
}
c.Close() c.Close()
os.Stdout.Write(response)
return nil return nil
} }
+2 -95
View File
@@ -88,14 +88,6 @@ func parseStyles() styleMap {
return sm return sm
} }
func parseEscapeSequence(s string) tcell.Style {
s = strings.TrimPrefix(s, "\033[")
if i := strings.IndexByte(s, 'm'); i >= 0 {
s = s[:i]
}
return applyAnsiCodes(s, tcell.StyleDefault)
}
func parseColor(toks []string) (tcell.Color, int, error) { func parseColor(toks []string) (tcell.Color, int, error) {
if len(toks) == 0 { if len(toks) == 0 {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks) return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
@@ -132,91 +124,6 @@ func parseColor(toks []string) (tcell.Color, int, error) {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks) return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
} }
func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";")
// ECMA-48 details the standard
// TODO: should we support turning off attributes?
// Probably because this is used for previewers too
tokslen := len(toks)
loop:
for i := 0; i < tokslen; i++ {
switch strings.TrimLeft(toks[i], "0") {
case "":
st = tcell.StyleDefault
case "1":
st = st.Bold(true)
case "2":
st = st.Dim(true)
case "3":
st = st.Italic(true)
case "4:0":
st = st.Underline(false)
case "4", "4:1":
st = st.Underline(true)
case "4:2":
st = st.Underline(tcell.UnderlineStyleDouble)
case "4:3":
st = st.Underline(tcell.UnderlineStyleCurly)
case "4:4":
st = st.Underline(tcell.UnderlineStyleDotted)
case "4:5":
st = st.Underline(tcell.UnderlineStyleDashed)
case "5", "6":
st = st.Blink(true)
case "7":
st = st.Reverse(true)
case "8":
// TODO: tcell PR for proper conceal
_, bg, _ := st.Decompose()
st = st.Foreground(bg)
case "9":
st = st.StrikeThrough(true)
case "30", "31", "32", "33", "34", "35", "36", "37":
n, _ := strconv.Atoi(toks[i])
st = st.Foreground(tcell.PaletteColor(n - 30))
case "90", "91", "92", "93", "94", "95", "96", "97":
n, _ := strconv.Atoi(toks[i])
st = st.Foreground(tcell.PaletteColor(n - 82))
case "38":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 38: %s", err)
break loop
}
st = st.Foreground(color)
i += offset
case "40", "41", "42", "43", "44", "45", "46", "47":
n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 40))
case "100", "101", "102", "103", "104", "105", "106", "107":
n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 92))
case "48":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 48: %s", err)
break loop
}
st = st.Background(color)
i += offset
case "58":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 58: %s", err)
break loop
}
st = st.Underline(color)
i += offset
default:
log.Printf("unknown ansi code: %s", toks[i])
}
}
return st
}
func (sm styleMap) parseFile(path string) { func (sm styleMap) parseFile(path string) {
log.Printf("reading file: %s", path) log.Printf("reading file: %s", path)
@@ -240,7 +147,7 @@ func (sm styleMap) parseFile(path string) {
// This function parses $LS_COLORS environment variable. // This function parses $LS_COLORS environment variable.
func (sm *styleMap) parseGNU(env string) { func (sm *styleMap) parseGNU(env string) {
for _, entry := range strings.Split(env, ":") { for entry := range strings.SplitSeq(env, ":") {
if entry == "" { if entry == "" {
continue continue
} }
@@ -269,7 +176,7 @@ func (sm *styleMap) parsePair(pair []string) {
sm.useLinkTarget = true sm.useLinkTarget = true
} }
sm.styles[key] = applyAnsiCodes(val, tcell.StyleDefault) sm.styles[key] = applySGR(val, tcell.StyleDefault)
} }
// This function parses $LSCOLORS environment variable. // This function parses $LSCOLORS environment variable.
-85
View File
@@ -34,88 +34,3 @@ func TestParseColor(t *testing.T) {
} }
} }
} }
func TestApplyAnsiCodes(t *testing.T) {
none := tcell.StyleDefault
tests := []struct {
s string
st tcell.Style
stExp tcell.Style
}{
{"", none, none},
{"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"", none.Bold(true), none},
{"", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"0", none, none},
{"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"0", none.Bold(true), none},
{"0", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"1", none, none.Bold(true)},
{"4", none, none.Underline(true)},
{"7", none, none.Reverse(true)},
{"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)},
{"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)},
{"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"4:0", none, none},
{"4:0", none.Underline(true), none},
{"4:1", none, none.Underline(true)},
{"4:2", none, none.Underline(tcell.UnderlineStyleDouble)},
{"4:3", none, none.Underline(tcell.UnderlineStyleCurly)},
{"4:4", none, none.Underline(tcell.UnderlineStyleDotted)},
{"4:5", none, none.Underline(tcell.UnderlineStyleDashed)},
{"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"41", none, none.Background(tcell.ColorMaroon)},
{"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"01;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"01;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none.Foreground(tcell.ColorGray)},
{"38;5;16", none, none.Foreground(tcell.Color16)},
{"38;5;232", none, none.Foreground(tcell.Color232)},
{"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"48;5;0", none, none.Background(tcell.ColorBlack)},
{"48;5;1", none, none.Background(tcell.ColorMaroon)},
{"48;5;8", none, none.Background(tcell.ColorGray)},
{"48;5;16", none, none.Background(tcell.Color16)},
{"48;5;232", none, none.Background(tcell.Color232)},
{"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"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))},
// Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446
{"38;5;34;1", none, none.Foreground(tcell.Color34).Bold(true)},
}
for _, test := range tests {
if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%v' expected '%v' but got '%v'",
test.s, test.st, test.stExp, stGot)
}
}
}
+351 -264
View File
@@ -2,9 +2,11 @@ package main
import ( import (
"log" "log"
"maps"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
"slices"
"sort" "sort"
"strings" "strings"
) )
@@ -18,104 +20,105 @@ var (
"vmap", "vmap",
"cmap", "cmap",
"cmd", "cmd",
"quit", "addcustominfo",
"up",
"half-up",
"page-up",
"scroll-up",
"down",
"half-down",
"page-down",
"scroll-down",
"updir",
"open",
"jump-next",
"jump-prev",
"top",
"bottom", "bottom",
"high",
"middle",
"low",
"toggle",
"invert",
"unselect",
"glob-select",
"glob-unselect",
"calcdirsize", "calcdirsize",
"cd",
"clear",
"clearmaps", "clearmaps",
"copy", "copy",
"cut", "cut",
"paste", "down",
"clear",
"sync",
"draw",
"redraw",
"load",
"reload",
"echo",
"echomsg",
"echoerr",
"cd",
"select",
"delete", "delete",
"rename", "draw",
"source", "echo",
"push", "echoerr",
"read", "echomsg",
"shell", "filter",
"shell-pipe",
"shell-wait",
"shell-async",
"find", "find",
"find-back", "find-back",
"find-next", "find-next",
"find-prev", "find-prev",
"glob-select",
"glob-unselect",
"half-down",
"half-up",
"high",
"invert",
"jump-next",
"jump-prev",
"load",
"low",
"mark-load",
"mark-remove",
"mark-save",
"middle",
"open",
"page-down",
"page-up",
"paste",
"push",
"quit",
"read",
"redraw",
"reload",
"rename",
"scroll-down",
"scroll-up",
"search", "search",
"search-back", "search-back",
"search-next", "search-next",
"search-prev", "search-prev",
"filter", "select",
"setfilter", "setfilter",
"mark-save", "shell",
"mark-load", "shell-async",
"mark-remove", "shell-pipe",
"shell-wait",
"source",
"sync",
"tag", "tag",
"tag-toggle", "tag-toggle",
"addcustominfo", "toggle",
"top",
"tty-write", "tty-write",
"cmd-escape", "unselect",
"cmd-complete", "up",
"cmd-menu-complete", "updir",
"cmd-menu-complete-back",
"cmd-menu-accept",
"cmd-enter",
"cmd-interrupt",
"cmd-history-next",
"cmd-history-prev",
"cmd-left",
"cmd-right",
"cmd-home",
"cmd-end",
"cmd-delete",
"cmd-delete-back",
"cmd-delete-home",
"cmd-delete-end",
"cmd-delete-unix-word",
"cmd-yank",
"cmd-transpose",
"cmd-transpose-word",
"cmd-word",
"cmd-word-back",
"cmd-delete-word",
"cmd-delete-word-back",
"cmd-capitalize-word",
"cmd-uppercase-word",
"cmd-lowercase-word",
"visual", "visual",
"visual-accept", "visual-accept",
"visual-unselect",
"visual-discard",
"visual-change", "visual-change",
"visual-discard",
"visual-unselect",
"cmd-capitalize-word",
"cmd-complete",
"cmd-delete",
"cmd-delete-back",
"cmd-delete-end",
"cmd-delete-home",
"cmd-delete-unix-word",
"cmd-delete-word",
"cmd-delete-word-back",
"cmd-end",
"cmd-enter",
"cmd-escape",
"cmd-history-next",
"cmd-history-prev",
"cmd-home",
"cmd-interrupt",
"cmd-left",
"cmd-lowercase-word",
"cmd-menu-accept",
"cmd-menu-complete",
"cmd-menu-complete-back",
"cmd-menu-discard",
"cmd-right",
"cmd-transpose",
"cmd-transpose-word",
"cmd-uppercase-word",
"cmd-word",
"cmd-word-back",
"cmd-yank",
} }
gOptWords = getOptWords(gOpts) gOptWords = getOptWords(gOpts)
@@ -158,51 +161,193 @@ func getLocalOptWords(localOpts any) (localOptWords []string) {
return return
} }
func matchLongest(s1, s2 []rune) []rune { func commonPrefix(s1, s2 string) string {
r1 := []rune(s1)
r2 := []rune(s2)
i := 0 i := 0
for ; i < len(s1) && i < len(s2); i++ { for ; i < len(r1) && i < len(r2); i++ {
if s1[i] != s2[i] { if r1[i] != r2[i] {
break break
} }
} }
return s1[:i]
return string(r1[:i])
} }
func matchWord(s string, words []string) (matches []string, longest []rune) { type compMatch struct {
name string // display name in completion menu
result string // result when cycling through completion menu
}
func matchWord(s string, words []string) (matches []compMatch, result string) {
for _, w := range words { for _, w := range words {
if !strings.HasPrefix(w, s) { if !strings.HasPrefix(w, s) {
continue continue
} }
matches = append(matches, w) matches = append(matches, compMatch{w, w})
if len(longest) != 0 { if len(matches) == 1 {
longest = matchLongest(longest, []rune(w)) result = w
} else if s != "" { } else {
longest = []rune(w + " ") result = commonPrefix(result, w)
} }
} }
if len(longest) == 0 { switch len(matches) {
longest = []rune(s) case 0:
result = s
case 1:
result += " "
} }
return return
} }
func matchExec(s string) (matches []string, longest []rune) { func matchList(s string, words []string) (matches []compMatch, result string) {
var words []string toks := strings.Split(s, ":")
paths := strings.Split(envPath, string(filepath.ListSeparator)) for _, w := range words {
if slices.Contains(toks[:len(toks)-1], w) || !strings.HasPrefix(w, toks[len(toks)-1]) {
for _, p := range paths {
if _, err := os.Stat(p); os.IsNotExist(err) {
continue continue
} }
matchResult := strings.Join(append(slices.Clone(toks[:len(toks)-1]), w), ":")
matches = append(matches, compMatch{w, matchResult})
if len(matches) == 1 {
result = matchResult
} else {
result = commonPrefix(result, matchResult)
}
}
switch len(matches) {
case 0:
result = s
case 1:
if result == s {
result += " "
}
}
return
}
func matchCmd(s string) (matches []compMatch, result string) {
words := slices.Concat(gCmdWords, slices.Collect(maps.Keys(gOpts.cmds)))
slices.Sort(words)
matches, result = matchWord(s, slices.Compact(words))
return
}
func matchFile(s string, dirOnly bool, escape func(string) string, unescape func(string) string) (matches []compMatch, result string) {
dir, file := filepath.Split(unescape(replaceTilde(s)))
d := dir
if dir == "" {
d = "."
}
files, err := os.ReadDir(d)
if err != nil {
log.Printf("reading directory: %s", err)
result = s
return
}
var commonName string
for _, f := range files {
isDir := false
if f.IsDir() {
isDir = true
} else if f.Type()&os.ModeSymlink != 0 {
if stat, err := os.Stat(filepath.Join(d, f.Name())); err == nil && stat.IsDir() {
isDir = true
}
}
if !isDir && dirOnly {
continue
}
if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(file)) {
continue
}
name := f.Name()
if isDir {
name += string(filepath.Separator)
}
matches = append(matches, compMatch{name, escape(dir + name)})
if len(matches) == 1 {
commonName = name
} else {
commonName = commonPrefix(strings.ToLower(commonName), strings.ToLower(name))
}
}
switch len(matches) {
case 0:
result = s
case 1:
result = escape(dir + commonName)
if !strings.HasSuffix(commonName, string(filepath.Separator)) {
result += " "
}
default:
result = escape(dir + commonName)
}
return
}
func matchCmdFile(s string, dirOnly bool) (matches []compMatch, result string) {
matches, result = matchFile(s, dirOnly, cmdEscape, cmdUnescape)
return
}
func matchShellFile(s string) (matches []compMatch, result string) {
matches, result = matchFile(s, false, shellEscape, shellUnescape)
return
}
func matchSetlocalDir(s string) (matches []compMatch, result string) {
matches, result = matchFile(s, true, cmdEscape, cmdUnescape)
if len(matches) == 0 {
return
}
trimSep := func(path string) string {
return strings.TrimSuffix(path, string(filepath.Separator))
}
trimSepEsc := func(path string) string {
return cmdEscape(trimSep(cmdUnescape(path)))
}
// add separate matches for path and recursive path
tmp := make([]compMatch, 0, len(matches)*2)
for _, match := range matches {
trimmedMatch := compMatch{trimSep(match.name), trimSepEsc(match.result)}
tmp = append(tmp, trimmedMatch, match)
}
matches = tmp
if result != s {
result = trimSepEsc(result)
}
return
}
func matchExec(s string) (matches []compMatch, result string) {
var words []string
for p := range strings.SplitSeq(envPath, string(filepath.ListSeparator)) {
files, err := os.ReadDir(p) files, err := os.ReadDir(p)
if err != nil { if err != nil {
if !os.IsNotExist(err) {
log.Printf("reading path: %s", err) log.Printf("reading path: %s", err)
} }
continue
}
for _, f := range files { for _, f := range files {
if !strings.HasPrefix(f.Name(), s) { if !strings.HasPrefix(f.Name(), s) {
@@ -215,170 +360,23 @@ func matchExec(s string) (matches []string, longest []rune) {
continue continue
} }
if !finfo.Mode().IsRegular() || !isExecutable(finfo) { if finfo.Mode().IsRegular() && isExecutable(finfo) {
continue words = append(words, f.Name())
} }
words = append(words, finfo.Name())
} }
} }
if len(words) > 0 { slices.Sort(words)
sort.Strings(words) matches, result = matchWord(s, slices.Compact(words))
return
uniq := words[:1]
for i := 1; i < len(words); i++ {
if words[i] != words[i-1] {
uniq = append(uniq, words[i])
}
}
words = uniq
}
return matchWord(s, words)
} }
func matchFile(s string) (matches []string, longest []rune) { func matchSearch(s string) (matches []compMatch, result string) {
dir := replaceTilde(s) files, err := os.ReadDir(".")
if !filepath.IsAbs(dir) {
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
} else {
dir = wd + string(filepath.Separator) + dir
}
}
dir = filepath.Dir(unescape(dir))
files, err := os.ReadDir(dir)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} result = s
for _, f := range files {
name := filepath.Join(dir, f.Name())
f, err := os.Lstat(name)
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
name = strings.ToLower(escape(f.Name()))
_, last := filepath.Split(s)
if !strings.HasPrefix(name, strings.ToLower(last)) {
continue
}
name = f.Name()
if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
}
name = escape(replaceTilde(name))
item := f.Name()
if f.Mode().IsDir() {
item += escape(string(filepath.Separator))
}
matches = append(matches, item)
if longest == nil {
if f.Mode().IsRegular() {
longest = []rune(name + " ")
} else {
longest = []rune(name + escape(string(filepath.Separator)))
}
} else {
longest = matchLongest(longest, []rune(name))
}
}
if len(longest) < len([]rune(s)) {
longest = []rune(s)
}
return return
}
func matchCmd(s string) (matches []string, longest []rune) {
words := make([]string, 0, len(gCmdWords)+len(gOpts.cmds))
words = append(words, gCmdWords...)
for c := range gOpts.cmds {
words = append(words, c)
}
sort.Strings(words)
j := 0
for i := 1; i < len(words); i++ {
if words[j] == words[i] {
continue
}
j++
words[i], words[j] = words[j], words[i]
}
words = words[:j+1]
matches, longest = matchWord(s, words)
return
}
func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
var longest []rune
switch len(f) {
case 1:
matches, longestAcc = matchCmd(s)
case 2:
switch f[0] {
case "set":
matches, longest = matchWord(f[1], gOptWords)
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
case "map", "nmap", "vmap", "cmap", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
}
case 3:
switch f[0] {
case "setlocal":
matches, longest = matchWord(f[2], gLocalOptWords)
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
case "map", "nmap", "vmap", "cmap":
matches, longest = matchCmd(f[2])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
case "addcustominfo":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
}
default:
switch f[0] {
case "set", "setlocal", "map", "nmap", "vmap", "cmap", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
}
}
return
}
func completeFile(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
files, err := os.ReadDir(wd)
if err != nil {
log.Printf("reading directory: %s", err)
} }
for _, f := range files { for _, f := range files {
@@ -386,35 +384,124 @@ func completeFile(acc []rune) (matches []string, longestAcc []rune) {
continue continue
} }
matches = append(matches, f.Name()) matches = append(matches, compMatch{f.Name(), f.Name()})
if len(matches) == 1 {
if longestAcc == nil { result = f.Name()
longestAcc = []rune(f.Name())
} else { } else {
longestAcc = matchLongest(longestAcc, []rune(f.Name())) result = commonPrefix(strings.ToLower(result), strings.ToLower(f.Name()))
} }
} }
if len(longestAcc) < len(acc) { if len(matches) == 0 {
longestAcc = acc result = s
} }
return return
} }
func completeShell(acc []rune) (matches []string, longestAcc []rune) { func completeCmd(acc []rune) (matches []compMatch, result string) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
var longest []rune if len(f) == 1 {
matches, result = matchCmd(s)
return
}
result = f[len(f)-1]
switch f[0] {
case "set":
if len(f) == 2 {
matches, result = matchWord(f[1], gOptWords)
break
}
if len(f) != 3 {
break
}
switch f[1] {
case "cleaner", "previewer":
matches, result = matchCmdFile(f[2], false)
case "filtermethod", "searchmethod":
matches, result = matchWord(f[2], []string{"glob", "regex", "text"})
case "info":
matches, result = matchList(f[2], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"})
case "preserve":
matches, result = matchList(f[2], []string{"mode", "timestamps"})
case "selmode":
matches, result = matchWord(f[2], []string{"all", "dir"})
case "sizeunits":
matches, result = matchWord(f[2], []string{"binary", "decimal"})
case "sortby":
matches, result = matchWord(f[2], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"})
default:
if slices.Contains(gOptWords, f[1]+"!") {
matches, result = matchWord(f[2], []string{"false", "true"})
}
}
case "setlocal":
if len(f) == 2 {
matches, result = matchSetlocalDir(f[1])
break
}
if len(f) == 3 {
matches, result = matchWord(f[2], gLocalOptWords)
break
}
if len(f) != 4 {
break
}
switch f[2] {
case "info":
matches, result = matchList(f[3], []string{"atime", "btime", "ctime", "custom", "group", "perm", "size", "time", "user"})
case "sortby":
matches, result = matchWord(f[3], []string{"atime", "btime", "ctime", "custom", "ext", "name", "natural", "size", "time"})
default:
if slices.Contains(gLocalOptWords, f[2]+"!") {
matches, result = matchWord(f[3], []string{"false", "true"})
}
}
case "map", "nmap", "vmap", "cmap":
if len(f) == 3 {
matches, result = matchCmd(f[2])
}
case "cmd":
case "cd":
if len(f) == 2 {
matches, result = matchCmdFile(f[1], true)
}
case "addcustominfo", "select", "source":
if len(f) == 2 {
matches, result = matchCmdFile(f[1], false)
}
case "toggle":
matches, result = matchCmdFile(f[len(f)-1], false)
default:
if !slices.Contains(gCmdWords, f[0]) {
matches, result = matchCmdFile(f[len(f)-1], false)
}
}
f[len(f)-1] = result
result = strings.Join(f, " ")
return
}
func completeShell(acc []rune) (matches []compMatch, result string) {
f := tokenize(string(acc))
switch len(f) { switch len(f) {
case 1: case 1:
matches, longestAcc = matchExec(s) matches, result = matchExec(f[0])
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, result = matchShellFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
f[len(f)-1] = result
result = strings.Join(f, " ")
return
}
func completeSearch(acc []rune) (matches []compMatch, result string) {
matches, result = matchSearch(string(acc))
return return
} }
+86 -50
View File
@@ -5,56 +5,6 @@ import (
"testing" "testing"
) )
func TestMatchLongest(t *testing.T) {
tests := []struct {
s1 string
s2 string
exp string
}{
{"", "", ""},
{"", "foo", ""},
{"foo", "", ""},
{"foo", "bar", ""},
{"foo", "foobar", "foo"},
{"foo", "barfoo", ""},
{"foobar", "foobaz", "fooba"},
{"год", "гол", "го"},
}
for _, test := range tests {
if got := string(matchLongest([]rune(test.s1), []rune(test.s2))); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got)
}
}
}
func TestMatchWord(t *testing.T) {
tests := []struct {
s string
words []string
matches []string
longest string
}{
{"", nil, nil, ""},
{"", []string{"foo", "bar", "baz"}, []string{"foo", "bar", "baz"}, ""},
{"fo", []string{"foo", "bar", "baz"}, []string{"foo"}, "foo "},
{"ba", []string{"foo", "bar", "baz"}, []string{"bar", "baz"}, "ba"},
{"fo", []string{"bar", "baz"}, nil, "fo"},
}
for _, test := range tests {
m, l := matchWord(test.s, test.words)
if !reflect.DeepEqual(m, test.matches) {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m)
}
if ls := string(l); ls != test.longest {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, ls)
}
}
}
func TestGetOptWords(t *testing.T) { func TestGetOptWords(t *testing.T) {
tests := []struct { tests := []struct {
opts any opts any
@@ -92,3 +42,89 @@ func TestGetLocalOptWords(t *testing.T) {
} }
} }
} }
func TestCommonPrefix(t *testing.T) {
tests := []struct {
s1 string
s2 string
exp string
}{
{"", "", ""},
{"", "foo", ""},
{"foo", "", ""},
{"foo", "bar", ""},
{"foo", "foobar", "foo"},
{"foo", "barfoo", ""},
{"foobar", "foobaz", "fooba"},
{"год", "гол", "го"},
}
for _, test := range tests {
if got := commonPrefix(test.s1, test.s2); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got)
}
}
}
func TestMatchWord(t *testing.T) {
tests := []struct {
s string
words []string
matches []compMatch
result string
}{
{"", nil, nil, ""},
{"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""},
{"fo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "},
{"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"},
{"fo", []string{"bar", "baz"}, nil, "fo"},
}
for _, test := range tests {
matches, result := matchWord(test.s, test.words)
if !reflect.DeepEqual(matches, test.matches) {
t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches)
}
if result != test.result {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result)
}
}
}
func TestMatchList(t *testing.T) {
tests := []struct {
s string
words []string
matches []compMatch
result string
}{
{"", nil, nil, ""},
{"", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}, {"bar", "bar"}, {"baz", "baz"}}, ""},
{"f", []string{"bar", "baz"}, nil, "f"},
{"f", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo"},
{"b", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"},
{"ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "bar"}, {"baz", "baz"}}, "ba"},
{"foo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "foo"}}, "foo "},
{"foo:", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "foo:bar"}, {"baz", "foo:baz"}}, "foo:ba"},
{"foo:f", []string{"foo", "bar", "baz"}, nil, "foo:f"},
{"foo:b", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "foo:bar"}, {"baz", "foo:baz"}}, "foo:ba"},
{"foo:ba", []string{"foo", "bar", "baz"}, []compMatch{{"bar", "foo:bar"}, {"baz", "foo:baz"}}, "foo:ba"},
{"bar:b", []string{"foo", "bar", "baz"}, []compMatch{{"baz", "bar:baz"}}, "bar:baz"},
{"bar:f", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "bar:foo"}}, "bar:foo"},
{"bar:foo", []string{"foo", "bar", "baz"}, []compMatch{{"foo", "bar:foo"}}, "bar:foo "},
}
for _, test := range tests {
matches, result := matchList(test.s, test.words)
if !reflect.DeepEqual(matches, test.matches) {
t.Errorf("at input '%s' with '%s' expected '%v' but got '%v'", test.s, test.words, test.matches, matches)
}
if result != test.result {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.result, result)
}
}
}
+38 -28
View File
@@ -41,7 +41,7 @@ func copySize(srcs []string) (int64, error) {
err = filepath.Walk(src, func(_ string, info os.FileInfo, err error) error { err = filepath.Walk(src, func(_ string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
return fmt.Errorf("walk: %s", err) return fmt.Errorf("walk: %w", err)
} }
total += info.Size() total += info.Size()
return nil return nil
@@ -54,43 +54,52 @@ func copySize(srcs []string) (int64, error) {
return total, nil return total, nil
} }
func copyFile(src, dst string, preserve []string, info os.FileInfo, nums chan int64) error { func copyFile(src, dst string, preserve []string, info os.FileInfo, nums chan<- int64, errs chan<- error) {
r, err := os.Open(src) r, err := os.Open(src)
if err != nil { if err != nil {
return err errs <- err
return
} }
defer r.Close() defer r.Close()
var dst_mode os.FileMode = 0o666 var dstMode os.FileMode = 0o666
if slices.Contains(preserve, "mode") { if slices.Contains(preserve, "mode") {
dst_mode = info.Mode() dstMode = info.Mode()
} }
w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, dst_mode) w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, dstMode)
if err != nil { if err != nil {
return err errs <- err
return
} }
if _, err := io.Copy(NewProgressWriter(w, nums), r); err != nil { if _, err := io.Copy(NewProgressWriter(w, nums), r); err != nil {
errs <- err
w.Close() w.Close()
os.Remove(dst) if err = os.Remove(dst); err != nil {
return err errs <- err
}
return
} }
if err := w.Close(); err != nil { if err := w.Close(); err != nil {
os.Remove(dst) errs <- err
return err if err = os.Remove(dst); err != nil {
errs <- err
}
return
} }
if slices.Contains(preserve, "timestamps") { if slices.Contains(preserve, "timestamps") {
atime := times.Get(info).AccessTime() atime := times.Get(info).AccessTime()
mtime := info.ModTime() mtime := info.ModTime()
if err := os.Chtimes(dst, atime, mtime); err != nil { if err := os.Chtimes(dst, atime, mtime); err != nil {
os.Remove(dst) errs <- err
return err if err = os.Remove(dst); err != nil {
errs <- err
}
return
} }
} }
return nil
} }
func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64, errs chan error) { func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64, errs chan error) {
@@ -119,25 +128,25 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
dst = newPath dst = newPath
} }
filepath.Walk(src, func(path string, info os.FileInfo, err error) error { err := filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil { if err != nil {
errs <- fmt.Errorf("walk: %s", err) errs <- fmt.Errorf("walk: %w", err)
return nil return nil
} }
rel, err := filepath.Rel(src, path) rel, err := filepath.Rel(src, path)
if err != nil { if err != nil {
errs <- fmt.Errorf("relative: %s", err) errs <- fmt.Errorf("relative: %w", err)
return nil return nil
} }
newPath := filepath.Join(dst, rel) newPath := filepath.Join(dst, rel)
switch { switch {
case info.IsDir(): case info.IsDir():
var dst_mode os.FileMode = os.ModePerm dstMode := os.ModePerm
if slices.Contains(preserve, "mode") { if slices.Contains(preserve, "mode") {
dst_mode = info.Mode() dstMode = info.Mode()
} }
if err := os.MkdirAll(newPath, dst_mode); err != nil { if err := os.MkdirAll(newPath, dstMode); err != nil {
errs <- fmt.Errorf("mkdir: %s", err) errs <- fmt.Errorf("mkdir: %w", err)
} }
if slices.Contains(preserve, "timestamps") { if slices.Contains(preserve, "timestamps") {
dirInfos[newPath] = info dirInfos[newPath] = info
@@ -145,27 +154,28 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
nums <- info.Size() nums <- info.Size()
case info.Mode()&os.ModeSymlink != 0: case info.Mode()&os.ModeSymlink != 0:
if rlink, err := os.Readlink(path); err != nil { if rlink, err := os.Readlink(path); err != nil {
errs <- fmt.Errorf("symlink: %s", err) errs <- fmt.Errorf("symlink: %w", err)
} else { } else {
if err := os.Symlink(rlink, newPath); err != nil { if err := os.Symlink(rlink, newPath); err != nil {
errs <- fmt.Errorf("symlink: %s", err) errs <- fmt.Errorf("symlink: %w", err)
} }
} }
nums <- info.Size() nums <- info.Size()
default: default:
if err := copyFile(path, newPath, preserve, info, nums); err != nil { copyFile(path, newPath, preserve, info, nums, errs)
errs <- fmt.Errorf("copy: %s", err)
}
} }
return nil return nil
}) })
if err != nil {
errs <- fmt.Errorf("walk: %w", err)
}
} }
for path, info := range dirInfos { for path, info := range dirInfos {
atime := times.Get(info).AccessTime() atime := times.Get(info).AccessTime()
mtime := info.ModTime() mtime := info.ModTime()
if err := os.Chtimes(path, atime, mtime); err != nil { if err := os.Chtimes(path, atime, mtime); err != nil {
errs <- fmt.Errorf("chtimes: %s", err) errs <- fmt.Errorf("chtimes: %w", err)
} }
} }
+1 -1
View File
@@ -15,5 +15,5 @@ func diskFree(wd string) string {
} }
// Available blocks * size per block = available space in bytes // Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.F_bavail)*uint64(stat.F_bsize))) return "df: " + humanize(uint64(stat.F_bavail)*uint64(stat.F_bsize))
} }
+1 -1
View File
@@ -17,5 +17,5 @@ func diskFree(wd string) string {
} }
// Available blocks * size per block = available space in bytes // Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize))) return "df: " + humanize(uint64(stat.Bavail)*uint64(stat.Bsize))
} }
+1 -1
View File
@@ -17,5 +17,5 @@ func diskFree(wd string) string {
} }
// Available blocks * size per block = available space in bytes // Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize))) return "df: " + humanize(uint64(stat.Bavail)*uint64(stat.Bsize))
} }
+1 -1
View File
@@ -19,5 +19,5 @@ func diskFree(wd string) string {
log.Printf("diskfree: %s", err) log.Printf("diskfree: %s", err)
return "" return ""
} }
return "df: " + humanize(int64(free)) return "df: " + humanize(free)
} }
+1 -1
View File
@@ -60,7 +60,7 @@ func runSearch(t *testing.T, ignorecase, smartcase, ignorediacritics, smartdiacr
gOpts.smartcase = smartcase gOpts.smartcase = smartcase
gOpts.ignoredia = ignorediacritics gOpts.ignoredia = ignorediacritics
gOpts.smartdia = smartdiacritics gOpts.smartdia = smartdiacritics
matched, _ := searchMatch(base, pattern, false) matched, _ := searchMatch(base, pattern, textSearch)
if matched != expected { if matched != expected {
t.Errorf("False search for ignorecase = %t, smartcase = %t, ignoredia = %t, smartdia = %t", t.Errorf("False search for ignorecase = %t, smartcase = %t, ignoredia = %t, smartdia = %t",
gOpts.ignorecase, gOpts.ignorecase,
+491 -224
View File
File diff suppressed because it is too large. Load diff
+593 -307
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -22,8 +22,8 @@ map i $less %f%
# change the shell used in default shell keybinding # change the shell used in default shell keybinding
map w $powershell map w $powershell
# change 'doc' command to use a different pager # change 'help' command to use a different pager
cmd doc $lf -doc | less cmd help $lf -doc | less
# leave some space at the top and the bottom of the screen # leave some space at the top and the bottom of the screen
set scrolloff 10 set scrolloff 10
+1 -1
View File
@@ -66,7 +66,7 @@ cmd trash %set -f; mv -t ~/.trash $fx
# cmd delete ${{ # cmd delete ${{
# set -f # set -f
# printf "$fx\n" # printf "$fx\n"
# printf "delete?[y/n]" # printf "delete? [y/N] "
# read ans # read ans
# [ "$ans" = "y" ] && rm -rf $fx # [ "$ans" = "y" ] && rm -rf $fx
# }} # }}
+1 -2
View File
@@ -21,8 +21,7 @@ cmd open &&$Env:OPENER.Trim('"', ' ') "$Env:f"
map e $&$Env:EDITOR "$Env:f" map e $&$Env:EDITOR "$Env:f"
map i !&$Env:PAGER "$Env:f" map i !&$Env:PAGER "$Env:f"
map w $&$Env:SHELL map w $&$Env:SHELL
cmd doc !&$Env:lf -doc | &$Env:PAGER cmd help !&$Env:lf -doc | &$Env:PAGER
map <f-1> doc
cmd maps !&$Env:lf -remote "query $Env:id maps" | &$Env:PAGER cmd maps !&$Env:lf -remote "query $Env:id maps" | &$Env:PAGER
cmd nmaps !&$Env:lf -remote "query $Env:id nmaps" | &$Env:PAGER cmd nmaps !&$Env:lf -remote "query $Env:id nmaps" | &$Env:PAGER
cmd vmaps !&$Env:lf -remote "query $Env:id vmaps" | &$Env:PAGER cmd vmaps !&$Env:lf -remote "query $Env:id vmaps" | &$Env:PAGER
+20
View File
@@ -0,0 +1,20 @@
{{with .Message -}}
{{. -}}
{{else with .Stat -}}
{{.Permissions | printf "\033[36m%s\033[0m" -}}
{{with .LinkCount}} {{.}}{{end -}}
{{with .User}} {{.}}{{end -}}
{{with .Group}} {{.}}{{end -}}
{{.Size | humanize | printf " %5s" -}}
{{.ModTime | printf " %s" -}}
{{with .Target}} -> {{.}}{{end -}}
{{end -}}
{{.SPACER -}}
{{with .Keys}} {{.}}{{end -}}
{{with .Progress}} {{join . " "}}{{end -}}
{{with .Copy}} {{len . | printf "%s %d \033[0m" $.Options.copyfmt}}{{end -}}
{{with .Cut}} {{len . | printf "%s %d \033[0m" $.Options.cutfmt}}{{end -}}
{{with .Select}} {{len . | printf "%s %d \033[0m" $.Options.selectfmt}}{{end -}}
{{with .Visual}} {{len . | printf "%s %d \033[0m" $.Options.visualfmt}}{{end -}}
{{with .Filter}} {{join . " " | printf "\033[7;34m %s \033[0m"}}{{end -}}
{{printf " %d/%d" .Index .Total}}
+904 -1004
View File
File diff suppressed because it is too large. Load diff
+41
View File
@@ -521,6 +521,47 @@ func TestParse(t *testing.T) {
} }
} }
func TestExprString(t *testing.T) {
tests := []struct {
e expr
exp string
}{
{&setExpr{"hidden!", ""}, "set hidden!"},
{&setExpr{"hidden", "true"}, "set hidden true"},
{&setLocalExpr{"~", "hidden!", ""}, "setlocal ~ hidden!"},
{&setLocalExpr{"~", "hidden", "true"}, "setlocal ~ hidden true"},
{&mapExpr{"q", nil}, "map q"},
{&mapExpr{"q", &callExpr{"quit", nil, 1}}, "map q quit"},
{&nmapExpr{"q", nil}, "nmap q"},
{&nmapExpr{"q", &callExpr{"quit", nil, 1}}, "nmap q quit"},
{&vmapExpr{"q", nil}, "vmap q"},
{&vmapExpr{"q", &callExpr{"quit", nil, 1}}, "vmap q quit"},
{&cmapExpr{"q", nil}, "cmap q"},
{&cmapExpr{"q", &callExpr{"quit", nil, 1}}, "cmap q quit"},
{&cmdExpr{"foo", nil}, "cmd foo"},
{&cmdExpr{"foo", &callExpr{"quit", nil, 1}}, "cmd foo quit"},
{&callExpr{"quit", nil, 1}, "quit"},
{&callExpr{"cd", []string{"~"}, 1}, "cd ~"},
{&execExpr{"$", "du -h . | less"}, "${{ du -h . | less }}"},
{
&execExpr{"$", `
mkdir foo
cp $fs foo
tar -czvf foo.tar.gz foo
rm -rf foo
`},
"${{ mkdir foo ... }}",
},
{&listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}, ":{{ toggle; down; }}"},
}
for _, test := range tests {
if got := test.e.String(); got != test.exp {
t.Errorf("at test '%#v' expected '%s' but got '%s'", test.e, test.exp, got)
}
}
}
func TestSplitKeys(t *testing.T) { func TestSplitKeys(t *testing.T) {
inps := []struct { inps := []struct {
s string s string
+5 -1
View File
@@ -6,6 +6,10 @@
# given to the go compiler to strip the binary. Current git tag is passed to # given to the go compiler to strip the binary. Current git tag is passed to
# the compiler by default to be used as the version in the binary. # the compiler by default to be used as the version in the binary.
[ -z $version ] && version=$(git describe --tags) set -o errexit -o nounset
[ -z "${version:-}" ] && version=$(git describe --tags --abbrev=0)
CGO_ENABLED=0 go build -ldflags="-s -w -X main.gVersion=$version" "$@" CGO_ENABLED=0 go build -ldflags="-s -w -X main.gVersion=$version" "$@"
# vim: tabstop=4 shiftwidth=4 textwidth=80 colorcolumn=80
+45
View File
@@ -0,0 +1,45 @@
local stringify = pandoc.utils.stringify
local List = pandoc.List
local DefinitionList = pandoc.DefinitionList
-- We use bold paragraphs for flags (e.g. **-help**)
local function is_term(b)
return b.tag == "Para" and b.content[1] and b.content[1].tag == "Strong"
end
-- GitHub-flavored markdown lacks native definition lists (i.e. ":" syntax).
-- Therefore, we generate them on the fly to get a better-looking "OPTIONS"
-- section in man pages and plain-text help without changing the source file.
function Blocks(blocks)
local out = List()
local i = 1
local in_opts, lvl = false, nil
while blocks[i] do
local b = blocks[i]
i = i + 1
if b.tag == "Header" then
-- Apply definition lists inside "OPTIONS" only
if stringify(b.content) == "OPTIONS" then
in_opts, lvl = true, b.level
else
in_opts = in_opts and b.level > lvl
end
out:insert(b)
elseif in_opts and is_term(b) then
-- Collect definition for current term
local def = List()
while blocks[i] and blocks[i].tag ~= "Header" and not is_term(blocks[i]) do
def:insert(blocks[i])
i = i + 1
end
out:insert(DefinitionList({ { b.content, { def } } }))
else
-- Pass through unchanged
out:insert(b)
end
end
return out
end
-32
View File
@@ -1,32 +0,0 @@
#!/bin/sh
# Generates `lf.1` and `doc.txt` from the `doc.md` file.
#
# This script is used to generate a man page and a plain text conversion of the
# markdown documentation using pandoc (https://pandoc.org/). GitHub Flavored
# Markdown (GFM) (https://github.github.com/gfm/) is used for the markdown
# input format. The markdown file is automatically rendered in the GitHub
# repository (https://github.com/gokcehan/lf/blob/master/doc.md). The man page
# file `lf.1` is meant to be used for installations on Unix systems. The plain
# text file `doc.txt` is embedded in the binary to be displayed on request with
# the `-doc` command line flag. Thus the same documentation is used for online
# and terminal display.
[ -z $version ] && version=$(git describe --tags)
[ -z $date ] && date=$(date +%F)
PANDOC_IMAGE=pandoc/minimal:3.7
docker run --rm -v "$PWD:/data" --user "$(id -u):$(id -g)" $PANDOC_IMAGE \
--standalone \
--from gfm --to man \
--metadata=title:"LF" \
--metadata=section:"1" \
--metadata=date:"$date" \
--metadata=footer:"$version" \
--metadata=header:"DOCUMENTATION" \
doc.md -o lf.1
docker run --rm -v "$PWD:/data" --user "$(id -u):$(id -g)" $PANDOC_IMAGE \
--standalone \
--from gfm --to plain \
doc.md -o doc.txt
+56 -4
View File
@@ -11,11 +11,24 @@
# the `-doc` command line flag. Thus the same documentation is used for online # the `-doc` command line flag. Thus the same documentation is used for online
# and terminal display. # and terminal display.
[ -z $version ] && version=$(git describe --tags) set -o errexit -o nounset
[ -z $date ] && date=$(date +%F)
pandoc \ get_version() {
printf "r%s" $(($(git describe --tags --abbrev=0 | tr -d r) + 1))
}
[ -z "${version:-}" ] && version=$(get_version)
[ -z "${date:-}" ] && date=$(date +%F)
PANDOC_IMAGE=pandoc/minimal:3.7
generate_man_page() {
"${OCI_PROGRAM?}" run \
--rm \
--volume "$PWD:/data" \
"$@" "$PANDOC_IMAGE" \
--standalone \ --standalone \
--lua-filter /data/gen/deflist.lua \
--from gfm --to man \ --from gfm --to man \
--metadata=title:"LF" \ --metadata=title:"LF" \
--metadata=section:"1" \ --metadata=section:"1" \
@@ -23,8 +36,47 @@ pandoc \
--metadata=footer:"$version" \ --metadata=footer:"$version" \
--metadata=header:"DOCUMENTATION" \ --metadata=header:"DOCUMENTATION" \
doc.md -o lf.1 doc.md -o lf.1
}
pandoc \ generate_plain_text() {
"${OCI_PROGRAM?}" run \
--rm \
--volume "$PWD:/data" \
"$@" "$PANDOC_IMAGE" \
--standalone \ --standalone \
--lua-filter /data/gen/deflist.lua \
--from gfm --to plain \ --from gfm --to plain \
doc.md -o doc.txt doc.md -o doc.txt
}
is_rootless() {
case "$OCI_PROGRAM" in
podman) podman info -f '{{.Host.Security.Rootless}}' | grep -q true ;;
docker) docker info -f '{{.SecurityOptions}}' | grep -q rootless ;;
*) echo >&2 \
"Unknown OCI program \"$OCI_PROGRAM\", assuming rootless mode" ;;
esac
}
# You can set your own OCI_PROGRAM, which assumes it runs in rootless mode.
if [ -z "${OCI_PROGRAM:-}" ]; then
if command -v podman > /dev/null; then
OCI_PROGRAM=podman
elif command -v docker > /dev/null; then
OCI_PROGRAM=docker
fi
fi
if is_rootless; then
generate_man_page
else
generate_man_page --user "$(id -u):$(id -g)"
fi
if is_rootless; then
generate_plain_text
else
generate_plain_text --user "$(id -u):$(id -g)"
fi
# vim: tabstop=4 shiftwidth=4 textwidth=80 colorcolumn=80
Executable
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
# Compresses a binary into an archived form.
#
# This script is used to compress a binary built from `build.sh` into an
# archive. `.zip` is used for Windows and `.tar.gz` otherwise. The archive is
# placed inside a directory named `dist`.
set -o errexit -o nounset
mkdir -p dist
if [ "$GOOS" = "windows" ]; then
zip "dist/lf-${GOOS}-${GOARCH}.zip" lf.exe
else
tar czf "dist/lf-${GOOS}-${GOARCH}.tar.gz" lf
fi
# vim: tabstop=4 shiftwidth=4 textwidth=80 colorcolumn=80
-92
View File
@@ -1,92 +0,0 @@
#!/bin/sh
# Generates cross builds for all supported platforms.
#
# This script is used to build binaries for all supported platforms. Cgo is
# disabled to make sure binaries are statically linked. Appropriate flags are
# given to the go compiler to strip binaries. Current git tag is passed to the
# compiler by default to be used as the version in binaries. These are then
# compressed in an archive form (`.zip` for windows and `.tar.gz` for the rest)
# within a folder named `dist`.
[ -z "$version" ] && version=$(git describe --tags)
test -d dist && {
echo "gen/xbuild.sh: WARNING: removing preexisting subdir 'dist'"
rm -r dist || exit 5
}
mkdir dist || exit 5
ERRORS=
build() {
# https://golang.org/doc/install/source#environment
echo "=== Building for GOOS=$1 and GOARCH=$2."
CGO_ENABLED=0 GOOS="$1" GOARCH="$2" go build -o dist/ \
-ldflags="-s -w -X main.gVersion=$version"
if test "$?" != "0"; then
ERRORS=1
else
package "$1" "$2" || exit 5
fi
}
package() (
cd dist || return 1
# Since the function is surrounded by (), the cd only affects a subshell
OUTFILE=
case "$1" in
windows)
OUTFILE="lf-$1-$2.zip"
zip "$OUTFILE" lf.exe --move || return 1
;;
*)
OUTFILE="lf-$1-$2.tar.gz"
tar czf "$OUTFILE" lf --remove-files || return 1
;;
esac
echo "dist/$OUTFILE successfully created."
)
build android arm64
build darwin amd64
build darwin arm64
build dragonfly amd64
build freebsd 386
build freebsd amd64
build freebsd arm
build illumos amd64
build linux 386
build linux amd64
build linux arm
build linux arm64
build linux ppc64
build linux ppc64le
build linux mips
build linux mipsle
build linux mips64
build linux mips64le
build linux s390x
build netbsd 386
build netbsd amd64
build netbsd arm
build openbsd 386
build openbsd amd64
build openbsd arm
build openbsd arm64
build solaris amd64
build windows 386
build windows amd64
# Unsupported
# build aix ppc64
# build android 386
# build android amd64
# build android arm
# build js wasm
# build plan9 386
# build plan9 amd64
# build plan9 arm
if test -n "$ERRORS"; then
printf "\ngen/xbuild.sh: some targets failed to compile.\n"
exit 1
fi
+8 -9
View File
@@ -1,20 +1,19 @@
module github.com/gokcehan/lf module github.com/gokcehan/lf
go 1.23.0 go 1.24.0
require ( require (
github.com/Xuanwo/go-locale v1.1.3
github.com/djherbis/times v1.6.0 github.com/djherbis/times v1.6.0
github.com/fsnotify/fsnotify v1.9.0 github.com/fsnotify/fsnotify v1.9.0
github.com/gdamore/tcell/v2 v2.8.1 github.com/gdamore/tcell/v2 v2.9.0
github.com/mattn/go-runewidth v0.0.16 github.com/mattn/go-runewidth v0.0.19
golang.org/x/sys v0.33.0 golang.org/x/sys v0.38.0
golang.org/x/term v0.32.0 golang.org/x/term v0.37.0
golang.org/x/text v0.26.0
) )
require ( require (
github.com/clipperhouse/uax29/v2 v2.2.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.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect golang.org/x/text v0.29.0 // indirect
) )
+14 -50
View File
@@ -1,48 +1,29 @@
github.com/Xuanwo/go-locale v1.1.3 h1:EWZZJJt5rqPHHbqPRH1zFCn5D7xHjjebODctA4aUO3A= github.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY=
github.com/Xuanwo/go-locale v1.1.3/go.mod h1:REn+F/c+AtGSWYACBSYZgl23AP+0lfQC+SEFPN+hj30= github.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c= github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0= github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= github.com/gdamore/encoding v1.0.1 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/v2 v2.8.1 h1:KPNxyqclpWpWQlPLx6Xui1pMk8S+7+R37h3g07997NU= github.com/gdamore/tcell/v2 v2.9.0 h1:N6t+eqK7/xwtRPwxzs1PXeRWnm0H9l02CrgJ7DLn1ys=
github.com/gdamore/tcell/v2 v2.8.1/go.mod h1:bj8ori1BG3OYMjmb3IklZVWfZUJ1UBQt9JXrOCOhGWw= github.com/gdamore/tcell/v2 v2.9.0/go.mod h1:8/ZoqM9rxzYphT9tH/9LnunhV9oPBqwS8WHGYm5nrmo=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= 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=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -50,39 +31,22 @@ 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.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-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.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU= golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg=
golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ=
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.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
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=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+2 -2
View File
@@ -88,7 +88,7 @@ func (im *iconMap) parseFile(path string) {
} }
func (im *iconMap) parseEnv(env string) { func (im *iconMap) parseEnv(env string) {
for _, entry := range strings.Split(env, ":") { for entry := range strings.SplitSeq(env, ":") {
if entry == "" { if entry == "" {
continue continue
} }
@@ -123,7 +123,7 @@ func (im *iconMap) parseArray(arr []string) {
} }
case 3: case 3:
icon, color := arr[1], arr[2] icon, color := arr[1], arr[2]
im.icons[key] = iconWithStyle(icon, applyAnsiCodes(color, tcell.StyleDefault)) im.icons[key] = iconWithStyle(icon, applySGR(color, tcell.StyleDefault))
} }
} }
+579 -287
View File
File diff suppressed because it is too large. Load diff
+33 -11
View File
@@ -89,6 +89,16 @@ func exportEnvVars() {
os.Setenv("LF_LEVEL", strconv.Itoa(level)) os.Setenv("LF_LEVEL", strconv.Itoa(level))
} }
func exportFlags() {
os.Setenv("lf_flag_config", gConfigPath)
os.Setenv("lf_flag_last_dir_path", gLastDirPath)
os.Setenv("lf_flag_log", gLogPath)
os.Setenv("lf_flag_print_last_dir", strconv.FormatBool(gPrintLastDir))
os.Setenv("lf_flag_print_selection", strconv.FormatBool(gPrintSelection))
os.Setenv("lf_flag_selection_path", gSelectionPath)
os.Setenv("lf_flag_single", strconv.FormatBool(gSingleMode))
}
// used by exportOpts below // used by exportOpts below
func fieldToString(field reflect.Value) string { func fieldToString(field reflect.Value) string {
kind := field.Kind() kind := field.Kind()
@@ -170,7 +180,9 @@ func checkServer() {
if _, err := os.Stat(gSocketPath); os.IsNotExist(err) { if _, err := os.Stat(gSocketPath); os.IsNotExist(err) {
startServer() startServer()
} else if _, err := net.Dial(gSocketProt, gSocketPath); err != nil { } else if _, err := net.Dial(gSocketProt, gSocketPath); err != nil {
os.Remove(gSocketPath) if err := os.Remove(gSocketPath); err != nil {
log.Print(err)
}
startServer() startServer()
} }
} else { } else {
@@ -229,6 +241,11 @@ func main() {
false, false,
"show documentation") "show documentation")
showHelp := flag.Bool(
"help",
false,
"show help")
showVersion := flag.Bool( showVersion := flag.Bool(
"version", "version",
false, false,
@@ -257,41 +274,41 @@ func main() {
remoteCmd := flag.String( remoteCmd := flag.String(
"remote", "remote",
"", "",
"send remote command to server") "send remote `command` to server")
cpuprofile := flag.String( cpuprofile := flag.String(
"cpuprofile", "cpuprofile",
"", "",
"path to the file to write the CPU profile") "`path` to the file to write the CPU profile")
memprofile := flag.String( memprofile := flag.String(
"memprofile", "memprofile",
"", "",
"path to the file to write the memory profile") "`path` to the file to write the memory profile")
flag.StringVar(&gLastDirPath, flag.StringVar(&gLastDirPath,
"last-dir-path", "last-dir-path",
"", "",
"path to the file to write the last dir on exit (to use for cd)") "`path` to the file to write the last dir on exit (to use for cd)")
flag.StringVar(&gSelectionPath, flag.StringVar(&gSelectionPath,
"selection-path", "selection-path",
"", "",
"path to the file to write selected files on open (to use as open file dialog)") "`path` to the file to write selected files on open (to use as open file dialog)")
flag.StringVar(&gConfigPath, flag.StringVar(&gConfigPath,
"config", "config",
"", "",
"path to the config file (instead of the usual paths)") "`path` to the config file (instead of the usual paths)")
flag.Var(&gCommands, flag.Var(&gCommands,
"command", "command",
"command to execute on client initialization") "`command` to execute on client initialization")
flag.StringVar(&gLogPath, flag.StringVar(&gLogPath,
"log", "log",
"", "",
"path to the log file to write messages") "`path` to the log file to write messages")
flag.Parse() flag.Parse()
@@ -320,6 +337,8 @@ func main() {
switch { switch {
case *showDoc: case *showDoc:
fmt.Print(genDocString) fmt.Print(genDocString)
case *showHelp:
flag.Usage()
case *showVersion: case *showVersion:
printVersion() printVersion()
case *remoteCmd != "": case *remoteCmd != "":
@@ -327,7 +346,9 @@ func main() {
log.Fatalf("remote command: %s", err) log.Fatalf("remote command: %s", err)
} }
case *serverMode: case *serverMode:
os.Chdir(gUser.HomeDir) if err := os.Chdir(gUser.HomeDir); err != nil {
log.Print(err)
}
serve() serve()
default: default:
gSingleMode = *singleMode gSingleMode = *singleMode
@@ -350,11 +371,12 @@ func main() {
case 1: case 1:
gSelect = flag.Arg(0) gSelect = flag.Arg(0)
default: default:
fmt.Fprintf(os.Stderr, "only single file or directory is allowed\n") fmt.Fprintln(os.Stderr, "only single file or directory is allowed")
os.Exit(2) os.Exit(2)
} }
exportEnvVars() exportEnvVars()
exportFlags()
run() run()
} }
+246 -146
View File
@@ -2,25 +2,32 @@ package main
import ( import (
"bufio" "bufio"
"bytes"
"cmp"
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
"math/big"
"os"
"path/filepath" "path/filepath"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
"unicode/utf8"
"github.com/Xuanwo/go-locale"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
"golang.org/x/text/collate"
"golang.org/x/text/language"
) )
const ( var (
localeStrDisable = "" // disable locale ordering for this locale value reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`)
localeStrSys = "*" // replace this locale value with locale value read from environment reRulerSub = regexp.MustCompile(`%[apmcsvfithPd]|%\{[^}]+\}`)
reSixelSize = regexp.MustCompile(`"1;1;(\d+);(\d+)`)
)
var (
reWord = regexp.MustCompile(`(\pL|\pN)+`)
reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
) )
func isRoot(name string) bool { return filepath.Dir(name) == name } func isRoot(name string) bool { return filepath.Dir(name) == name }
@@ -32,14 +39,6 @@ func replaceTilde(s string) string {
return s return s
} }
func evalSymlinks(path string) string {
if target, err := filepath.EvalSymlinks(path); err == nil {
return target
}
return path
}
func runeSliceWidth(rs []rune) int { func runeSliceWidth(rs []rune) int {
w := 0 w := 0
for _, r := range rs { for _, r := range rs {
@@ -86,7 +85,7 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
// This function is used to escape whitespaces and special characters with // This function is used to escape whitespaces and special characters with
// backslashes in a given string. // backslashes in a given string.
func escape(s string) string { func cmdEscape(s string) string {
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
for _, r := range s { for _, r := range s {
if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' { if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
@@ -99,7 +98,7 @@ func escape(s string) string {
// This function is used to remove backslashes that are used to escape // This function is used to remove backslashes that are used to escape
// whitespaces and special characters in a given string. // whitespaces and special characters in a given string.
func unescape(s string) string { func cmdUnescape(s string) string {
esc := false esc := false
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
for _, r := range s { for _, r := range s {
@@ -125,27 +124,28 @@ func unescape(s string) string {
} }
// This function splits the given string by whitespaces. It is aware of escaped // This function splits the given string by whitespaces. It is aware of escaped
// whitespaces so that they are not split unintentionally. // and quoted whitespaces so that they are not split unintentionally.
func tokenize(s string) []string { func tokenize(s string) []string {
esc := false esc := false
quote := false
var buf []rune var buf []rune
var toks []string var toks []string
for _, r := range s { for _, r := range s {
if r == '\\' { switch {
esc = true case esc:
buf = append(buf, r)
continue
}
if esc {
esc = false esc = false
buf = append(buf, r) buf = append(buf, r)
continue case r == '\\':
} esc = true
if !unicode.IsSpace(r) {
buf = append(buf, r) buf = append(buf, r)
} else { case r == '"':
quote = !quote
buf = append(buf, r)
case unicode.IsSpace(r) && !quote:
toks = append(toks, string(buf)) toks = append(toks, string(buf))
buf = nil buf = nil
default:
buf = append(buf, r)
} }
} }
return append(toks, string(buf)) return append(toks, string(buf))
@@ -172,7 +172,7 @@ func splitWord(s string) (word, rest string) {
// or double quotes can be used to escape whitespaces. Hash characters can be // or double quotes can be used to escape whitespaces. Hash characters can be
// used to add a comment until the end of line. Leading and trailing space is // used to add a comment until the end of line. Leading and trailing space is
// trimmed. Empty lines are skipped. // trimmed. Empty lines are skipped.
func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) { func readArrays(r io.Reader, minCols, maxCols int) ([][]string, error) {
var arrays [][]string var arrays [][]string
s := bufio.NewScanner(r) s := bufio.NewScanner(r)
for s.Scan() { for s.Scan() {
@@ -208,11 +208,11 @@ func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) {
}) })
arrlen := len(arr) arrlen := len(arr)
if arrlen < min_cols || arrlen > max_cols { if arrlen < minCols || arrlen > maxCols {
if min_cols == max_cols { if minCols == maxCols {
return nil, fmt.Errorf("expected %d columns but found: %s", min_cols, s.Text()) return nil, fmt.Errorf("expected %d columns but found: %s", minCols, s.Text())
} }
return nil, fmt.Errorf("expected %d~%d columns but found: %s", min_cols, max_cols, s.Text()) return nil, fmt.Errorf("expected %d~%d columns but found: %s", minCols, maxCols, s.Text())
} }
for i := range arrlen { for i := range arrlen {
@@ -235,87 +235,157 @@ func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) {
arrays = append(arrays, arr) arrays = append(arrays, arr)
} }
return arrays, nil return arrays, s.Err()
} }
func readPairs(r io.Reader) ([][]string, error) { func readPairs(r io.Reader) ([][]string, error) {
return readArrays(r, 2, 2) return readArrays(r, 2, 2)
} }
// This function converts a size in bytes to a human readable form using metric // This function converts a size in bytes to a human readable form using
// suffixes (e.g. 1K = 1000). For values less than 10 the first significant // prefixes for either binary (1 KiB = 1024 B) or decimal (1 KB = 1000 B)
// digit is shown, otherwise it is hidden. Numbers are always rounded down. // multiples. The output should be no more than 5 characters long.
// This should be fine for most human beings. func humanize(size uint64) string {
func humanize(size int64) string { var base uint64 = 1024
if size < 1000 { if gOpts.sizeunits == "decimal" {
base = 1000
}
if size < base {
return fmt.Sprintf("%dB", size) return fmt.Sprintf("%dB", size)
} }
suffix := []string{ // *Note*: due to [`FileSize.Size()`](https://pkg.go.dev/io/fs#FileInfo)
"K", // kilo // being `int64`, the maximum possible representable value would be 8 EiB or
"M", // mega // 9.2 EB.
"G", // giga prefixes := []string{
"T", // tera "K", // kibi (2^10) or kilo (10^3)
"P", // peta "M", // mebi (2^20) or mega (10^6)
"E", // exa "G", // gibi (2^30) or giga (10^9)
"Z", // zeta "T", // tebi (2^40) or tera (10^2)
"Y", // yotta "P", // pebi (2^50) or peta (10^15)
"E", // exbi (2^60) or exa (10^18)
"Z", // zebi (2^70) or zetta (10^21)
"Y", // yobi (2^80) or yotta (10^24)
"R", // robi (2^90) or ronna (10^27)
"Q", // quebi (2^100) or quetta (10^30)
} }
curr := float64(size) / 1000 curr := big.NewRat(int64(size), int64(base))
for _, s := range suffix {
if curr < 10 { for _, prefix := range prefixes {
return fmt.Sprintf("%.1f%s", curr-0.0499, s) // if curr < 99.95 then round to 1 decimal place
} if curr.Cmp(big.NewRat(9995, 100)) < 0 {
if curr < 1000 { return fmt.Sprintf("%s%s", curr.FloatString(1), prefix)
return fmt.Sprintf("%d%s", int(curr), s)
}
curr /= 1000
} }
return "" // if curr < base-0.5 then round to the nearest integer
if curr.Cmp(new(big.Rat).Sub(big.NewRat(int64(base), 1), big.NewRat(1, 2))) < 0 {
return fmt.Sprintf("%s%s", curr.FloatString(0), prefix)
}
curr.Quo(curr, big.NewRat(int64(base), 1))
}
return fmt.Sprintf("+999%s", prefixes[len(prefixes)-1])
}
// This function returns an ls(1)-style string representation of the given file
// mode, to avoid using Go's implementation, which slightly differs.
func permString(m os.FileMode) string {
// re-use Perm()'s "-rwxrwxrwx" output and write type into b[0]
b := []byte(m.Perm().String())
switch {
case m&os.ModeSymlink != 0:
b[0] = 'l'
case m&os.ModeDir != 0:
b[0] = 'd'
case m&os.ModeNamedPipe != 0:
b[0] = 'p'
case m&os.ModeSocket != 0:
b[0] = 's'
case m&os.ModeCharDevice != 0:
b[0] = 'c'
case m&os.ModeDevice != 0:
b[0] = 'b'
default:
b[0] = '-'
}
// patch exec slots with suid/sgid/sticky flags
if m&os.ModeSetuid != 0 {
if b[3] == 'x' {
b[3] = 's'
} else {
b[3] = 'S'
}
}
if m&os.ModeSetgid != 0 {
if b[6] == 'x' {
b[6] = 's'
} else {
b[6] = 'S'
}
}
if m&os.ModeSticky != 0 {
if b[9] == 'x' {
b[9] = 't'
} else {
b[9] = 'T'
}
}
return string(b)
} }
// This function compares two strings for natural sorting which takes into // This function compares two strings for natural sorting which takes into
// account values of numbers in strings. For example, '2' is less than '10', // account the values of numbers in strings. For example, '2' is ordered before
// and similarly 'foo2bar' is less than 'foo10bar', but 'bar2bar' is greater // '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing
// than 'foo10bar'. // numbers, if they have the same value then the length of the string is also
func naturalLess(s1, s2 string) bool { // compared, so '0' is ordered before '00'.
lo1, lo2, hi1, hi2 := 0, 0, 0, 0 func naturalCmp(s1, s2 string) int {
s1len := len(s1) s1len := len(s1)
s2len := len(s2) s2len := len(s2)
var lo1, lo2, hi1, hi2 int
for { for {
if hi1 >= s1len { switch {
return hi2 != s2len case hi1 >= s1len && hi2 >= s2len:
} return 0
case hi1 >= s1len && hi2 < s2len:
if hi2 >= s2len { return -1
return false case hi1 < s1len && hi2 >= s2len:
return 1
} }
lo1 = hi1
isDigit1 := isDigit(s1[hi1]) isDigit1 := isDigit(s1[hi1])
for hi1 < s1len && isDigit(s1[hi1]) == isDigit1 {
hi1++
}
tok1 := s1[lo1:hi1]
lo2 = hi2
isDigit2 := isDigit(s2[hi2]) isDigit2 := isDigit(s2[hi2])
for hi2 < s2len && isDigit(s2[hi2]) == isDigit2 {
for lo1 = hi1; hi1 < s1len && isDigit(s1[hi1]) == isDigit1; hi1++ { hi2++
}
for lo2 = hi2; hi2 < s2len && isDigit(s2[hi2]) == isDigit2; hi2++ {
}
if s1[lo1:hi1] == s2[lo2:hi2] {
continue
} }
tok2 := s2[lo2:hi2]
if isDigit1 && isDigit2 { if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(s1[lo1:hi1]) num1, err1 := strconv.Atoi(tok1)
num2, err2 := strconv.Atoi(s2[lo2:hi2]) num2, err2 := strconv.Atoi(tok2)
if err1 == nil && err2 == nil { if err1 == nil && err2 == nil {
return num1 < num2 if num1 != num2 {
return cmp.Compare(num1, num2)
} else if len(tok1) != len(tok2) {
return cmp.Compare(len(tok1), len(tok2))
}
} }
} }
return s1[lo1:hi1] < s2[lo2:hi2] if tok1 != tok2 {
return cmp.Compare(tok1, tok2)
}
} }
} }
@@ -333,50 +403,34 @@ func getFileExtension(file fs.FileInfo) string {
return filepath.Ext(file.Name()) return filepath.Ext(file.Name())
} }
var ( // This function truncates a filename at a given position.
reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`) // The position is specified as percentage indicating where the truncation
reRulerSub = regexp.MustCompile(`%[apmcsvfithPd]|%\{[^}]+\}`) // character will appear (0 means left, 50 means middle, 100 means right).
reSixelSize = regexp.MustCompile(`"1;1;(\d+);(\d+)`) // The file extension is not affected by truncation, however it will be clipped
) // if it exceeds the allowed width.
func truncateFilename(file fs.FileInfo, maxWidth int, truncatePct int, truncateChar rune) string {
var ( filename := file.Name()
reWord = regexp.MustCompile(`(\pL|\pN)+`) if runeSliceWidth([]rune(filename)) <= maxWidth {
reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`) return filename
reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
)
// This function parses given locale string into language tag value. Passing empty
// string as locale means reading locale value from environment.
func getLocaleTag(localeStr string) (language.Tag, error) {
if localeStr == localeStrSys {
// read environment locale
return locale.Detect()
} }
localeTag, err := language.Parse(localeStr) ext := getFileExtension(file)
if err != nil { avail := maxWidth - runewidth.RuneWidth(truncateChar) - runeSliceWidth([]rune(ext))
return localeTag, fmt.Errorf("invalid locale %q: %s", localeStr, err) if avail < 0 {
result := append([]rune{truncateChar}, []rune(ext)...)
return string(runeSliceWidthRange(result, 0, maxWidth))
} }
return localeTag, nil basename := []rune(strings.TrimSuffix(filename, ext))
} left := runeSliceWidthRange(basename, 0, avail*truncatePct/100)
right := runeSliceWidthLastRange(basename, avail-runeSliceWidth(left))
// This function creates new collator for given locale. Passing empty string as var result []rune
// as locale means reading locale value from environment. result = append(result, left...)
// result = append(result, truncateChar)
// *Note*: this function returns error when given `localeStr` has value `localeStrDisable` result = append(result, right...)
// or is an invalid locale tag. result = append(result, []rune(ext)...)
func makeCollator(localeStr string, opts ...collate.Option) (*collate.Collator, error) { return string(result)
if localeStr == localeStrDisable {
return nil, fmt.Errorf("locale is disabled")
}
localeTag, err := getLocaleTag(localeStr)
if err != nil {
return nil, err
}
return collate.New(localeTag, opts...), nil
} }
// This function deletes entries from a map if the key is either the given path // This function deletes entries from a map if the key is either the given path
@@ -392,35 +446,81 @@ func deletePathRecursive[T any](m map[string]T, path string) {
} }
} }
// This function is used to remove style-related ANSI escape sequences from // This function takes an escape sequence option (e.g. `\033[1m`) and outputs a
// a given string. // complete format string (e.g. `\033[1m%s\033[0m`).
// func optionToFmtstr(optstr string) string {
// *Note*: this function is based entirely on `printLength()` and strips only if !strings.Contains(optstr, "%s") {
// style-related escape sequences and the `erase in line` sequence. Other codes return optstr + "%s\033[0m"
// (e.g., cursor moves), as well as broken escape sequences, aren't removed. } else {
// This prevents mismatches between the two functions and avoids misalignment return optstr
// when rendering the UI. }
func stripAnsi(s string) string { }
var b strings.Builder
slen := len(s)
for i := 0; i < slen; i++ {
r, w := utf8.DecodeRuneInString(s[i:])
if r == gEscapeCode && i+1 < slen && s[i+1] == '[' { // This function reads lines from a file to be displayed as a preview.
j := strings.IndexAny(s[i:min(slen, i+64)], "mK") // The number of lines to read is capped since files can be very large.
if j == -1 { // Lines are split on `\n` characters, and `\r` characters are discarded.
continue // Sixel images are also detected and stored as separate lines.
// The presence of a null byte outside a sixel image indicates a binary file.
func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool, sixel bool) {
var buf bytes.Buffer
var last byte
inSixel := false
for {
b, err := reader.ReadByte()
if err != nil {
if buf.Len() > 0 {
lines = append(lines, buf.String())
}
return
} }
i += j if inSixel {
continue buf.WriteByte(b)
if b == '\\' && last == '\033' {
lines = append(lines, buf.String())
buf.Reset()
if len(lines) >= maxLines {
return
}
inSixel = false
}
} else {
switch {
case b == 0:
return nil, true, false
case b == '\033':
// withhold as it could be the start of a sixel image
case b == 'P' && last == '\033':
if buf.Len() > 0 {
lines = append(lines, buf.String())
buf.Reset()
if len(lines) >= maxLines {
return
}
}
buf.WriteByte(last)
buf.WriteByte(b)
inSixel = true
sixel = true
case last == '\033':
// not a sixel image
buf.WriteByte(last)
buf.WriteByte(b)
case b == '\r':
case b == '\n':
lines = append(lines, buf.String())
buf.Reset()
if len(lines) >= maxLines {
return
}
default:
buf.WriteByte(b)
}
} }
i += w - 1 last = b
b.WriteRune(r)
} }
return b.String()
} }
// We don't need no generic code // We don't need no generic code
+227 -103
View File
@@ -1,13 +1,12 @@
package main package main
import ( import (
"math"
"os" "os"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
"time" "time"
"golang.org/x/text/collate"
) )
func TestIsRoot(t *testing.T) { func TestIsRoot(t *testing.T) {
@@ -127,7 +126,7 @@ func TestRuneSliceWidthLastRange(t *testing.T) {
} }
} }
func TestEscape(t *testing.T) { func TestCmdEscape(t *testing.T) {
tests := []struct { tests := []struct {
s string s string
exp string exp string
@@ -146,13 +145,13 @@ func TestEscape(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
if got := escape(test.s); !reflect.DeepEqual(got, test.exp) { if got := cmdEscape(test.s); !reflect.DeepEqual(got, test.exp) {
t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got)
} }
} }
} }
func TestUnescape(t *testing.T) { func TestCmdUnescape(t *testing.T) {
tests := []struct { tests := []struct {
s string s string
exp string exp string
@@ -171,7 +170,7 @@ func TestUnescape(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
if got := unescape(test.s); !reflect.DeepEqual(got, test.exp) { if got := cmdUnescape(test.s); !reflect.DeepEqual(got, test.exp) {
t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got)
} }
} }
@@ -184,8 +183,17 @@ func TestTokenize(t *testing.T) {
}{ }{
{"", []string{""}}, {"", []string{""}},
{"foo", []string{"foo"}}, {"foo", []string{"foo"}},
{`foo\`, []string{`foo\`}},
{`foo"`, []string{`foo"`}},
{"foo bar", []string{"foo", "bar"}}, {"foo bar", []string{"foo", "bar"}},
{`foo\ bar`, []string{`foo\ bar`}},
{`"foo bar"`, []string{`"foo bar"`}},
{`"foo" "bar"`, []string{`"foo"`, `"bar"`}},
{`"foo "bar"`, []string{`"foo "bar"`}},
{`"foo\" bar"`, []string{`"foo\" bar"`}},
{`\"foo bar\"`, []string{`\"foo`, `bar\"`}},
{`:rename foo\ bar`, []string{":rename", `foo\ bar`}}, {`:rename foo\ bar`, []string{":rename", `foo\ bar`}},
{`!dir "C:\Program Files"`, []string{"!dir", `"C:\Program Files"`}},
} }
for _, test := range tests { for _, test := range tests {
@@ -222,8 +230,8 @@ func TestSplitWord(t *testing.T) {
func TestReadArrays(t *testing.T) { func TestReadArrays(t *testing.T) {
tests := []struct { tests := []struct {
s string s string
min_cols int minCols int
max_cols int maxCols int
exp [][]string exp [][]string
}{ }{
{"foo bar", 2, 2, [][]string{{"foo", "bar"}}}, {"foo bar", 2, 2, [][]string{{"foo", "bar"}}},
@@ -239,7 +247,7 @@ func TestReadArrays(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
if got, _ := readArrays(strings.NewReader(test.s), test.min_cols, test.max_cols); !reflect.DeepEqual(got, test.exp) { if got, _ := readArrays(strings.NewReader(test.s), test.minCols, test.maxCols); !reflect.DeepEqual(got, test.exp) {
t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got)
} }
} }
@@ -247,56 +255,130 @@ func TestReadArrays(t *testing.T) {
func TestHumanize(t *testing.T) { func TestHumanize(t *testing.T) {
tests := []struct { tests := []struct {
i int64 size uint64
exp string expected string
}{ }{
{0, "0B"}, {0, "0B"},
{9, "9B"}, {1, "1B"},
{99, "99B"}, {2, "2B"},
{999, "999B"}, {10, "10B"},
{1000, "1.0K"}, {100, "100B"},
{1023, "1.0K"}, {1000, "1000B"},
{1025, "1.0K"}, {1023, "1023B"},
{1049, "1.0K"}, {1024, "1.0K"},
{1050, "1.0K"}, {1025, "1.0K"}, // 1.000976563 KiB
{1099, "1.0K"}, {10188, "9.9K"}, // 9.94921875 KiB
{9999, "9.9K"}, {10189, "10.0K"}, // 9.950195313 KiB
{10000, "10K"}, {10240, "10.0K"}, // 10 KiB
{10100, "10K"}, {10291, "10.0K"}, // 10.049804688 KiB
{10500, "10K"}, {10292, "10.1K"}, // 10.05078125 KiB
{1000000, "1.0M"}, {10342, "10.1K"}, // 10.099609375 KiB
{102348, "99.9K"}, // 99.94921875 KiB
{102349, "100K"}, // 99.950195313 KiB
{1023487, "999K"}, // 999.499023438 KiB
{1023488, "1000K"}, // 999.5 KiB
{1048063, "1023K"}, // 1023.499023438 KiB
{1048064, "1.0M"}, // 1023.5 KiB
{1072693248, "1023M"}, // 1023 MiB
{1073217535, "1023M"}, // 1023.499999046 MiB
{1073217536, "1.0G"}, // 1023.5 MiB
{1073741824, "1.0G"}, // 1 GiB
{1610612736, "1.5G"}, // 1.5 GiB
{1319413953332, "1.2T"}, // 1.2 TiB
{1463669878895412, "1.3P"}, // 1.3 PiB
{7955158381787244544, "6.9E"}, // 6.9 EiB
{math.MaxInt64, "8.0E"}, // 8 EiB
} }
gOpts.sizeunits = "binary"
for _, test := range tests { for _, test := range tests {
if got := humanize(test.i); got != test.exp { if got := humanize(test.size); got != test.expected {
t.Errorf("at input '%d' expected '%s' but got '%s'", test.i, test.exp, got) t.Errorf("at input ('%d', '%s') expected '%s' but got '%s'", test.size, gOpts.sizeunits, test.expected, got)
}
}
tests = []struct {
size uint64
expected string
}{
{0, "0B"},
{1, "1B"},
{2, "2B"},
{10, "10B"},
{100, "100B"},
{999, "999B"},
{1000, "1.0K"},
{1001, "1.0K"},
{1049, "1.0K"},
{1050, "1.1K"},
{1051, "1.1K"},
{9949, "9.9K"},
{9950, "10.0K"},
{9951, "10.0K"},
{9999, "10.0K"},
{10000, "10.0K"},
{10001, "10.0K"},
{99949, "99.9K"},
{99950, "100K"},
{99951, "100K"},
{999499, "999K"},
{999500, "1.0M"},
{999501, "1.0M"},
{999999, "1.0M"},
{1000000, "1.0M"},
{1000001, "1.0M"},
{999499999, "999M"},
{999500000, "1.0G"},
{999500001, "1.0G"},
{999999999, "1.0G"},
{1000000000, "1.0G"},
{1000000001, "1.0G"},
{math.MaxInt64, "9.2E"},
}
gOpts.sizeunits = "decimal"
for _, test := range tests {
if got := humanize(test.size); got != test.expected {
t.Errorf("at input ('%d', '%s') expected '%s' but got '%s'", test.size, gOpts.sizeunits, test.expected, got)
} }
} }
} }
func TestNaturalLess(t *testing.T) { func TestNaturalCmp(t *testing.T) {
tests := []struct { tests := []struct {
s1 string s1 string
s2 string s2 string
exp bool exp int
}{ }{
{"foo", "bar", false}, {"", "", 0},
{"bar", "baz", true}, {"a", "a", 0},
{"foo", "123", false}, {"", "a", -1},
{"foo1", "foobar", true}, {"a", "b", -1},
{"foo1", "foo10", true}, {"a", "ab", -1},
{"foo2", "foo10", true}, {"0", "0", 0},
{"foo1", "foo10bar", true}, {"0", "00", -1},
{"foo2", "foo10bar", true}, {"1", "1", 0},
{"foo1bar", "foo10bar", true}, {"1", "01", -1},
{"foo2bar", "foo10bar", true}, {"2", "10", -1},
{"foo1bar", "foo10", true}, {"123", "foo", -1},
{"foo2bar", "foo10", true}, {"foo", "foo1", -1},
{"foo1", "foobar", -1},
{"foo1", "foobar1", -1},
{"foo2", "foo10", -1},
{"foo2bar", "foo10bar", -1},
{"foo0", "foo00", -1},
{"foo0bar", "foo00bar", -1},
{"foo1", "foo01", -1},
{"foo1bar", "foo01bar", -1},
} }
for _, test := range tests { for _, test := range tests {
if got := naturalLess(test.s1, test.s2); got != test.exp { if got := naturalCmp(test.s1, test.s2); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got) t.Errorf("at input '%s' and '%s' expected '%d' but got '%d'", test.s1, test.s2, test.exp, got)
}
if got := naturalCmp(test.s2, test.s1); got != -test.exp {
t.Errorf("at input '%s' and '%s' expected '%d' but got '%d'", test.s2, test.s1, -test.exp, got)
} }
} }
} }
@@ -338,83 +420,125 @@ func TestGetFileExtension(t *testing.T) {
} }
} }
func TestLocaleNaturalLess(t *testing.T) { func TestTruncateFilename(t *testing.T) {
tests := []struct { tests := []struct {
s1 string file fakeFileInfo
s2 string maxWidth int
exp bool truncatePct int
exp string
}{ }{
// preserving behavior of `naturalLess` {fakeFileInfo{"foo", false}, 0, 0, ""},
{"foo", "bar", false}, {fakeFileInfo{"foo", false}, 0, 100, ""},
{"bar", "baz", true}, {fakeFileInfo{"foo", false}, 1, 0, "~"},
{"foo", "123", false}, {fakeFileInfo{"foo", false}, 1, 100, "~"},
{"foo1", "foobar", true}, {fakeFileInfo{"foo", false}, 2, 0, "~o"},
{"foo1", "foo10", true}, {fakeFileInfo{"foo", false}, 2, 100, "f~"},
{"foo2", "foo10", true}, {fakeFileInfo{"foo", false}, 3, 0, "foo"},
{"foo1", "foo10bar", true}, {fakeFileInfo{"foo", false}, 3, 100, "foo"},
{"foo2", "foo10bar", true}, {fakeFileInfo{"foo", false}, 4, 0, "foo"},
{"foo1bar", "foo10bar", true}, {fakeFileInfo{"foo", false}, 4, 100, "foo"},
{"foo2bar", "foo10bar", true}, {fakeFileInfo{"foo.txt", false}, 0, 0, ""},
{"foo1bar", "foo10", true}, {fakeFileInfo{"foo.txt", false}, 0, 100, ""},
{"foo2bar", "foo10", true}, {fakeFileInfo{"foo.txt", false}, 1, 0, "~"},
{fakeFileInfo{"foo.txt", false}, 1, 100, "~"},
// locale sort {fakeFileInfo{"foo.txt", false}, 2, 0, "~."},
{"你好", "他好", true}, // \u4F60\u597D, \u4ED6\u597D {fakeFileInfo{"foo.txt", false}, 2, 100, "~."},
{"到这", "到那", false}, // \u5230\u8FD9, \u5230\u90A3 {fakeFileInfo{"foo.txt", false}, 3, 0, "~.t"},
{"你说", "什么", true}, // \u4f60\u8bf4, \u4ec0\u4e48 {fakeFileInfo{"foo.txt", false}, 3, 100, "~.t"},
{"你好", "World", false}, // \u4F60\u597D, \u57\u6f\u72\u6c\u64 {fakeFileInfo{"foo.txt", false}, 4, 0, "~.tx"},
{"甲1", "甲乙", true}, {fakeFileInfo{"foo.txt", false}, 4, 100, "~.tx"},
{"甲1", "甲10", true}, {fakeFileInfo{"foo.txt", false}, 5, 0, "~.txt"},
{"甲2", "甲10", true}, {fakeFileInfo{"foo.txt", false}, 5, 100, "~.txt"},
{"甲1", "甲10乙", true}, {fakeFileInfo{"foo.txt", false}, 6, 0, "~o.txt"},
{"甲2", "甲10乙", true}, {fakeFileInfo{"foo.txt", false}, 6, 100, "f~.txt"},
{"甲1乙", "甲10乙", true}, {fakeFileInfo{"foobarbaz", false}, 7, 0, "~barbaz"},
{"甲2乙", "甲10乙", true}, {fakeFileInfo{"foobarbaz", false}, 7, 50, "foo~baz"},
{"甲1乙", "甲10", true}, {fakeFileInfo{"foobarbaz", false}, 7, 100, "foobar~"},
{"甲2乙", "甲10", true}, {fakeFileInfo{"foobarbaz.txt", false}, 11, 0, "~barbaz.txt"},
} {fakeFileInfo{"foobarbaz.txt", false}, 11, 50, "foo~baz.txt"},
{fakeFileInfo{"foobarbaz.txt", false}, 11, 100, "foobar~.txt"},
localeStr := "zh-CN" {fakeFileInfo{"foobarbaz.d", true}, 9, 0, "~barbaz.d"},
collator, err := makeCollator(localeStr, collate.Numeric) {fakeFileInfo{"foobarbaz.d", true}, 9, 50, "foob~az.d"},
if err != nil { {fakeFileInfo{"foobarbaz.d", true}, 9, 100, "foobarba~"},
t.Fatalf("failed to create collator for %q: %s", localeStr, err) {fakeFileInfo{"世界世界.txt", false}, 10, 0, "~世界.txt"},
{fakeFileInfo{"世界世界.txt", false}, 10, 50, "世~界.txt"},
{fakeFileInfo{"世界世界.txt", false}, 10, 100, "世界~.txt"},
{fakeFileInfo{"世界世界.txt", false}, 11, 0, "~界世界.txt"},
{fakeFileInfo{"世界世界.txt", false}, 11, 50, "世~世界.txt"},
{fakeFileInfo{"世界世界.txt", false}, 11, 100, "世界世~.txt"},
} }
for _, test := range tests { for _, test := range tests {
if got := collator.CompareString(test.s1, test.s2) < 0; got != test.exp { if got := truncateFilename(test.file, test.maxWidth, test.truncatePct, '~'); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got) t.Errorf("at input (%v, %v, %v) expected '%s' but got '%s'", test.file, test.maxWidth, test.truncatePct, test.exp, got)
} }
} }
} }
func TestStripAnsi(t *testing.T) { func TestOptionToFmtstr(t *testing.T) {
tests := []struct { tests := []struct {
s string s string
exp string exp string
}{ }{
{"", ""}, // empty {"\033[1m", "\033[1m%s\033[0m"},
{"foo bar", "foo bar"}, // plain text {"\033[1;7;31;42m", "\033[1;7;31;42m%s\033[0m"},
{"\033[31mRed\033[0m", "Red"}, // octal syntax
{"\x1b[31mRed\x1b[0m", "Red"}, // hexadecimal syntax
{"foo\x1b[31mRed", "fooRed"}, // no reset parameter
{
"foo\x1b[1;31;102mBoldRedGreen\x1b[0mbar",
"fooBoldRedGreenbar",
}, // multiple attributes
{
"misc.go:func \x1b[01;31m\x1b[KstripAnsi\x1b[m\x1b[K(s string) string {",
"misc.go:func stripAnsi(s string) string {",
}, // `grep` output containing `erase in line` sequence
} }
for _, test := range tests { for _, test := range tests {
if got := stripAnsi(test.s); got != test.exp { if got := optionToFmtstr(test.s); got != test.exp {
t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got) t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got)
} }
// we rely on both functions extracting the same runes }
// to avoid misalignment }
if printLength(test.s) != len(stripAnsi(test.s)) {
t.Errorf("at input %q expected '%d' but got '%d'", test.s, printLength(test.s), len(stripAnsi(test.s))) func TestReadLines(t *testing.T) {
} tests := []struct {
s string
maxLines int
lines []string
binary bool
sixel bool
}{
{"", 10, nil, false, false},
{"\r", 10, nil, false, false},
{"\r\n", 10, []string{""}, false, false},
{"\r\r\n", 10, []string{""}, false, false},
{"\n\n", 10, []string{"", ""}, false, false},
{"foo", 10, []string{"foo"}, false, false},
{"foo\n", 10, []string{"foo"}, false, false},
{"foo\r\n", 10, []string{"foo"}, false, false},
{"foo\nbar", 10, []string{"foo", "bar"}, false, false},
{"foo\nbar\n", 10, []string{"foo", "bar"}, false, false},
{"foo\r\nbar", 10, []string{"foo", "bar"}, false, false},
{"foo\r\nbar\r\n", 10, []string{"foo", "bar"}, false, false},
{"\033[31mfoo\033[0m", 10, []string{"\033[31mfoo\033[0m"}, false, false},
{"\000", 10, nil, true, false},
{"foo\r\n\000\r\nbar\r\n", 10, nil, true, false},
{"\033P\033\\", 10, []string{"\033P\033\\"}, false, true},
{"\033Pq\"1;1;1;1#0@\033\\", 10, []string{"\033Pq\"1;1;1;1#0@\033\\"}, false, true},
{"\033P\000\033\\", 10, []string{"\033P\000\033\\"}, false, true},
{"\033P\n\033\\", 10, []string{"\033P\n\033\\"}, false, true},
{"\033P\r\n\033\\", 10, []string{"\033P\r\n\033\\"}, false, true},
{"\033P\033\\\033P\033\\", 10, []string{"\033P\033\\", "\033P\033\\"}, false, true},
{"foo\033P\033\\bar", 10, []string{"foo", "\033P\033\\", "bar"}, false, true},
{"foo\033P\033\\bar\033P\033\\baz", 10, []string{"foo", "\033P\033\\", "bar", "\033P\033\\", "baz"}, false, true},
{"foo\nbar\nbaz", 2, []string{"foo", "bar"}, false, false},
{"foo\nbar\nbaz\n", 2, []string{"foo", "bar"}, false, false},
{"foo\nbar\033P\033\\", 2, []string{"foo", "bar"}, false, false},
{"foo\nbar\nbaz", 3, []string{"foo", "bar", "baz"}, false, false},
{"foo\nbar\nbaz\n", 3, []string{"foo", "bar", "baz"}, false, false},
{"foo\nbar\033P\033\\", 3, []string{"foo", "bar", "\033P\033\\"}, false, true},
}
for _, test := range tests {
lines, binary, sixel := readLines(strings.NewReader(test.s), test.maxLines)
if !reflect.DeepEqual(lines, test.lines) || binary != test.binary || sixel != test.sixel {
t.Errorf(
"at input (%q, %v) expected (%#v, %v, %v) but got (%#v, %v, %v)",
test.s, test.maxLines,
test.lines, test.binary, test.sixel,
lines, binary, sixel,
)
}
} }
} }
+424 -386
View File
File diff suppressed because it is too large. Load diff
+105 -99
View File
@@ -15,6 +15,7 @@ const (
sizeSort sortMethod = "size" sizeSort sortMethod = "size"
timeSort sortMethod = "time" timeSort sortMethod = "time"
atimeSort sortMethod = "atime" atimeSort sortMethod = "atime"
btimeSort sortMethod = "btime"
ctimeSort sortMethod = "ctime" ctimeSort sortMethod = "ctime"
extSort sortMethod = "ext" extSort sortMethod = "ext"
customSort sortMethod = "custom" customSort sortMethod = "custom"
@@ -26,100 +27,111 @@ func isValidSortMethod(method sortMethod) bool {
method == sizeSort || method == sizeSort ||
method == timeSort || method == timeSort ||
method == atimeSort || method == atimeSort ||
method == btimeSort ||
method == ctimeSort || method == ctimeSort ||
method == extSort || method == extSort ||
method == customSort method == customSort
} }
const invalidSortErrorMessage = `sortby: value should either be 'natural', 'name', 'size', 'time', 'atime', 'ctime', 'ext' or 'custom'` const invalidSortErrorMessage = `sortby: value should either be 'natural', 'name', 'size', 'time', 'atime', 'btime', 'ctime', 'ext' or 'custom'`
type searchMethod string
const (
textSearch searchMethod = "text"
globSearch searchMethod = "glob"
regexSearch searchMethod = "regex"
)
var gOpts struct { var gOpts struct {
anchorfind bool anchorfind bool
autoquit bool autoquit bool
borderfmt string borderfmt string
cleaner string
copyfmt string copyfmt string
cursoractivefmt string cursoractivefmt string
cursorparentfmt string cursorparentfmt string
cursorpreviewfmt string cursorpreviewfmt string
cutfmt string cutfmt string
dircache bool
dircounts bool dircounts bool
dirfirst bool dirfirst bool
dironly bool dironly bool
dirpreviews bool dirpreviews bool
drawbox bool drawbox bool
dupfilefmt string dupfilefmt string
globfilter bool errorfmt string
globsearch bool filesep string
filtermethod searchMethod
findlen int
hidden bool hidden bool
hiddenfiles []string
history bool
icons bool icons bool
ifs string
ignorecase bool ignorecase bool
ignoredia bool ignoredia bool
incfilter bool incfilter bool
incsearch bool incsearch bool
locale string info []string
infotimefmtnew string
infotimefmtold string
menufmt string
menuheaderfmt string
menuselectfmt string
mouse bool mouse bool
number bool number bool
numberfmt string
period int
preload bool
preserve []string
preview bool preview bool
previewer string
promptfmt string
ratios []int
relativenumber bool relativenumber bool
reverse bool reverse bool
roundbox bool roundbox bool
rulerfile bool
rulerfmt string
scrolloff int
searchmethod searchMethod
selectfmt string selectfmt string
visualfmt string selmode string
shell string
shellflag string
shellopts []string
showbinds bool showbinds bool
sixel bool sizeunits string
sortby sortMethod
smartcase bool smartcase bool
smartdia bool smartdia bool
sortby sortMethod
statfmt string
tabstop int
tagfmt string
tempmarks string
timefmt string
truncatechar string
truncatepct int
visualfmt string
waitmsg string waitmsg string
watch bool watch bool
wrapscan bool wrapscan bool
wrapscroll bool wrapscroll bool
findlen int
period int
scrolloff int
tabstop int
errorfmt string
filesep string
ifs string
previewer string
cleaner string
promptfmt string
selmode string
shell string
shellflag string
statfmt string
timefmt string
infotimefmtnew string
infotimefmtold string
truncatechar string
truncatepct int
ratios []int
hiddenfiles []string
history bool
info []string
rulerfmt string
preserve []string
shellopts []string
nkeys map[string]expr nkeys map[string]expr
vkeys map[string]expr vkeys map[string]expr
cmdkeys map[string]expr cmdkeys map[string]expr
cmds map[string]expr cmds map[string]expr
user map[string]string user map[string]string
tempmarks string
numberfmt string
tagfmt string
} }
var gLocalOpts struct { var gLocalOpts struct {
sortby map[string]sortMethod
dircounts map[string]bool dircounts map[string]bool
dirfirst map[string]bool dirfirst map[string]bool
dironly map[string]bool dironly map[string]bool
hidden map[string]bool hidden map[string]bool
reverse map[string]bool
info map[string][]string info map[string][]string
locale map[string]string reverse map[string]bool
sortby map[string]sortMethod
} }
func localOptPaths(path string) []string { func localOptPaths(path string) []string {
@@ -193,88 +205,82 @@ func getSortBy(path string) sortMethod {
return gOpts.sortby return gOpts.sortby
} }
func getLocale(path string) string {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.locale[key]; ok {
return val
}
}
return gOpts.locale
}
func init() { func init() {
gOpts.anchorfind = true gOpts.anchorfind = true
gOpts.autoquit = true gOpts.autoquit = true
gOpts.dircache = true gOpts.borderfmt = "\033[0m"
gOpts.cleaner = ""
gOpts.copyfmt = "\033[7;33m"
gOpts.cursoractivefmt = "\033[7m"
gOpts.cursorparentfmt = "\033[7m"
gOpts.cursorpreviewfmt = "\033[4m"
gOpts.cutfmt = "\033[7;31m"
gOpts.dircounts = false gOpts.dircounts = false
gOpts.dirfirst = true gOpts.dirfirst = true
gOpts.dironly = false gOpts.dironly = false
gOpts.dirpreviews = false gOpts.dirpreviews = false
gOpts.drawbox = false gOpts.drawbox = false
gOpts.dupfilefmt = "%f.~%n~" gOpts.dupfilefmt = "%f.~%n~"
gOpts.borderfmt = "\033[0m" gOpts.errorfmt = "\033[7;31;47m"
gOpts.copyfmt = "\033[7;33m" gOpts.filesep = "\n"
gOpts.cursoractivefmt = "\033[7m" gOpts.filtermethod = textSearch
gOpts.cursorparentfmt = "\033[7m" gOpts.findlen = 1
gOpts.cursorpreviewfmt = "\033[4m"
gOpts.cutfmt = "\033[7;31m"
gOpts.globfilter = false
gOpts.globsearch = false
gOpts.hidden = false gOpts.hidden = false
gOpts.hiddenfiles = gDefaultHiddenFiles
gOpts.history = true
gOpts.icons = false gOpts.icons = false
gOpts.ifs = ""
gOpts.ignorecase = true gOpts.ignorecase = true
gOpts.ignoredia = true gOpts.ignoredia = true
gOpts.incfilter = false gOpts.incfilter = false
gOpts.incsearch = false gOpts.incsearch = false
gOpts.locale = localeStrDisable gOpts.info = nil
gOpts.infotimefmtnew = "Jan _2 15:04"
gOpts.infotimefmtold = "Jan _2 2006"
gOpts.menufmt = "\033[0m"
gOpts.menuheaderfmt = "\033[1m"
gOpts.menuselectfmt = "\033[7m"
gOpts.mouse = false gOpts.mouse = false
gOpts.number = false gOpts.number = false
gOpts.numberfmt = "\033[33m"
gOpts.period = 0
gOpts.preload = false
gOpts.preserve = []string{"mode"}
gOpts.preview = true gOpts.preview = true
gOpts.previewer = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m"
gOpts.ratios = []int{1, 2, 3}
gOpts.relativenumber = false gOpts.relativenumber = false
gOpts.reverse = false gOpts.reverse = false
gOpts.roundbox = false gOpts.roundbox = false
gOpts.rulerfile = false
gOpts.rulerfmt = " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t"
gOpts.scrolloff = 0
gOpts.searchmethod = textSearch
gOpts.selectfmt = "\033[7;35m" gOpts.selectfmt = "\033[7;35m"
gOpts.visualfmt = "\033[7;36m" gOpts.selmode = "all"
gOpts.shell = gDefaultShell
gOpts.shellflag = gDefaultShellFlag
gOpts.shellopts = nil
gOpts.showbinds = true gOpts.showbinds = true
gOpts.sixel = false gOpts.sizeunits = "binary"
gOpts.sortby = naturalSort
gOpts.smartcase = true gOpts.smartcase = true
gOpts.smartdia = false gOpts.smartdia = false
gOpts.sortby = naturalSort
gOpts.statfmt = "\033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l"
gOpts.tabstop = 8
gOpts.tagfmt = "\033[31m"
gOpts.tempmarks = "'"
gOpts.timefmt = time.ANSIC
gOpts.truncatechar = "~"
gOpts.truncatepct = 100
gOpts.visualfmt = "\033[7;36m"
gOpts.waitmsg = "Press any key to continue" gOpts.waitmsg = "Press any key to continue"
gOpts.watch = false gOpts.watch = false
gOpts.wrapscan = true gOpts.wrapscan = true
gOpts.wrapscroll = false gOpts.wrapscroll = false
gOpts.findlen = 1
gOpts.period = 0
gOpts.scrolloff = 0
gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m"
gOpts.filesep = "\n"
gOpts.ifs = ""
gOpts.previewer = ""
gOpts.cleaner = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m"
gOpts.selmode = "all"
gOpts.shell = gDefaultShell
gOpts.shellflag = gDefaultShellFlag
gOpts.statfmt = "\033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l"
gOpts.timefmt = time.ANSIC
gOpts.infotimefmtnew = "Jan _2 15:04"
gOpts.infotimefmtold = "Jan _2 2006"
gOpts.truncatechar = "~"
gOpts.truncatepct = 100
gOpts.ratios = []int{1, 2, 3}
gOpts.hiddenfiles = gDefaultHiddenFiles
gOpts.history = true
gOpts.info = nil
gOpts.rulerfmt = " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t"
gOpts.preserve = []string{"mode"}
gOpts.shellopts = nil
gOpts.tempmarks = "'"
gOpts.numberfmt = "\033[33m"
gOpts.tagfmt = "\033[31m"
// normal and visual mode // Normal and Visual mode
keys := map[string]expr{ keys := map[string]expr{
"k": &callExpr{"up", nil, 1}, "k": &callExpr{"up", nil, 1},
"<up>": &callExpr{"up", nil, 1}, "<up>": &callExpr{"up", nil, 1},
@@ -344,25 +350,26 @@ func init() {
"ss": &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}, "ss": &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1},
"st": &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1}, "st": &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1},
"sa": &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1}, "sa": &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1},
"sb": &listExpr{[]expr{&setExpr{"sortby", "btime"}, &setExpr{"info", "btime"}}, 1},
"sc": &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1}, "sc": &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1},
"se": &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1}, "se": &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1},
"gh": &callExpr{"cd", []string{"~"}, 1}, "gh": &callExpr{"cd", []string{"~"}, 1},
} }
// insert bindings that apply to both normal & visual mode first // insert bindings that apply to both Normal & Visual mode first
gOpts.nkeys = maps.Clone(keys) gOpts.nkeys = maps.Clone(keys)
// now add normal mode specific ones // now add Normal mode specific ones
gOpts.nkeys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1} gOpts.nkeys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
gOpts.nkeys["V"] = &callExpr{"visual", nil, 1} gOpts.nkeys["V"] = &callExpr{"visual", nil, 1}
gOpts.nkeys["v"] = &callExpr{"invert", nil, 1} gOpts.nkeys["v"] = &callExpr{"invert", nil, 1}
// now do the same for visual mode // now do the same for Visual mode
gOpts.vkeys = maps.Clone(keys) gOpts.vkeys = maps.Clone(keys)
gOpts.vkeys["<esc>"] = &callExpr{"visual-discard", nil, 1} gOpts.vkeys["<esc>"] = &callExpr{"visual-discard", nil, 1}
gOpts.vkeys["V"] = &callExpr{"visual-accept", nil, 1} gOpts.vkeys["V"] = &callExpr{"visual-accept", nil, 1}
gOpts.vkeys["o"] = &callExpr{"visual-change", nil, 1} gOpts.vkeys["o"] = &callExpr{"visual-change", nil, 1}
// command line mode bindings can be assigned directly // Command-line mode bindings can be assigned directly
gOpts.cmdkeys = map[string]expr{ gOpts.cmdkeys = map[string]expr{
"<space>": &callExpr{"cmd-insert", []string{" "}, 1}, "<space>": &callExpr{"cmd-insert", []string{" "}, 1},
"<esc>": &callExpr{"cmd-escape", nil, 1}, "<esc>": &callExpr{"cmd-escape", nil, 1},
@@ -405,14 +412,13 @@ func init() {
gOpts.cmds = make(map[string]expr) gOpts.cmds = make(map[string]expr)
gOpts.user = make(map[string]string) gOpts.user = make(map[string]string)
gLocalOpts.sortby = make(map[string]sortMethod)
gLocalOpts.dircounts = make(map[string]bool) gLocalOpts.dircounts = make(map[string]bool)
gLocalOpts.dirfirst = make(map[string]bool) gLocalOpts.dirfirst = make(map[string]bool)
gLocalOpts.dironly = make(map[string]bool) gLocalOpts.dironly = make(map[string]bool)
gLocalOpts.hidden = make(map[string]bool) gLocalOpts.hidden = make(map[string]bool)
gLocalOpts.reverse = make(map[string]bool)
gLocalOpts.info = make(map[string][]string) gLocalOpts.info = make(map[string][]string)
gLocalOpts.locale = make(map[string]string) gLocalOpts.reverse = make(map[string]bool)
gLocalOpts.sortby = make(map[string]sortMethod)
setDefaults() setDefaults()
} }
+37 -3
View File
@@ -38,6 +38,7 @@ var (
gConfigPaths []string gConfigPaths []string
gColorsPaths []string gColorsPaths []string
gIconsPaths []string gIconsPaths []string
gRulerPaths []string
gFilesPath string gFilesPath string
gMarksPath string gMarksPath string
gTagsPath string gTagsPath string
@@ -105,6 +106,11 @@ func init() {
filepath.Join(config, "lf", "icons"), filepath.Join(config, "lf", "icons"),
} }
gRulerPaths = []string{
filepath.Join("/etc", "lf", "ruler"),
filepath.Join(config, "lf", "ruler"),
}
data := cmp.Or( data := cmp.Or(
os.Getenv("LF_DATA_HOME"), os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"), os.Getenv("XDG_DATA_HOME"),
@@ -164,9 +170,9 @@ func setDefaults() {
gOpts.nkeys["w"] = &execExpr{"$", "$SHELL"} gOpts.nkeys["w"] = &execExpr{"$", "$SHELL"}
gOpts.vkeys["w"] = &execExpr{"$", "$SHELL"} gOpts.vkeys["w"] = &execExpr{"$", "$SHELL"}
gOpts.cmds["doc"] = &execExpr{"$", `"$lf" -doc | $PAGER`} gOpts.cmds["help"] = &execExpr{"$", `"$lf" -doc | $PAGER`}
gOpts.nkeys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.nkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.vkeys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.vkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.cmds["maps"] = &execExpr{"$", `"$lf" -remote "query $id maps" | $PAGER`} gOpts.cmds["maps"] = &execExpr{"$", `"$lf" -remote "query $id maps" | $PAGER`}
gOpts.cmds["nmaps"] = &execExpr{"$", `"$lf" -remote "query $id nmaps" | $PAGER`} gOpts.cmds["nmaps"] = &execExpr{"$", `"$lf" -remote "query $id nmaps" | $PAGER`}
@@ -229,3 +235,31 @@ func errCrossDevice(err error) bool {
func quoteString(s string) string { func quoteString(s string) string {
return s return s
} }
func shellEscape(s string) string {
buf := make([]rune, 0, len(s))
for _, r := range s {
if strings.ContainsRune(" !\"$&'()*,:;<=>?@[\\]^`{|}", r) {
buf = append(buf, '\\')
}
buf = append(buf, r)
}
return string(buf)
}
func shellUnescape(s string) string {
esc := false
buf := make([]rune, 0, len(s))
for _, r := range s {
if r == '\\' && !esc {
esc = true
continue
}
esc = false
buf = append(buf, r)
}
if esc {
buf = append(buf, '\\')
}
return string(buf)
}
+38 -10
View File
@@ -36,6 +36,7 @@ var (
gConfigPaths []string gConfigPaths []string
gColorsPaths []string gColorsPaths []string
gIconsPaths []string gIconsPaths []string
gRulerPaths []string
gFilesPath string gFilesPath string
gTagsPath string gTagsPath string
gMarksPath string gMarksPath string
@@ -74,23 +75,38 @@ func init() {
Username: username, Username: username,
} }
data := cmp.Or(os.Getenv("LF_CONFIG_HOME"), os.Getenv("LOCALAPPDATA")) config := cmp.Or(
os.Getenv("LF_CONFIG_HOME"),
os.Getenv("XDG_CONFIG_HOME"),
os.Getenv("APPDATA"),
)
gConfigPaths = []string{ gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"), filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
filepath.Join(data, "lf", "lfrc"), filepath.Join(config, "lf", "lfrc"),
} }
gColorsPaths = []string{ gColorsPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "colors"), filepath.Join(os.Getenv("ProgramData"), "lf", "colors"),
filepath.Join(data, "lf", "colors"), filepath.Join(config, "lf", "colors"),
} }
gIconsPaths = []string{ gIconsPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "icons"), filepath.Join(os.Getenv("ProgramData"), "lf", "icons"),
filepath.Join(data, "lf", "icons"), filepath.Join(config, "lf", "icons"),
} }
gRulerPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "ruler"),
filepath.Join(config, "lf", "ruler"),
}
data := cmp.Or(
os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"),
os.Getenv("LOCALAPPDATA"),
)
gFilesPath = filepath.Join(data, "lf", "files") gFilesPath = filepath.Join(data, "lf", "files")
gMarksPath = filepath.Join(data, "lf", "marks") gMarksPath = filepath.Join(data, "lf", "marks")
gTagsPath = filepath.Join(data, "lf", "tags") gTagsPath = filepath.Join(data, "lf", "tags")
@@ -134,7 +150,7 @@ func shellCommand(s string, args []string) *exec.Cmd {
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func shellSetPG(cmd *exec.Cmd) { func shellSetPG(_ *exec.Cmd) {
} }
func shellKill(cmd *exec.Cmd) error { func shellKill(cmd *exec.Cmd) error {
@@ -150,9 +166,9 @@ func setDefaults() {
gOpts.nkeys["w"] = &execExpr{"$", "%SHELL%"} gOpts.nkeys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.vkeys["w"] = &execExpr{"$", "%SHELL%"} gOpts.vkeys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.cmds["doc"] = &execExpr{"!", "%lf% -doc | %PAGER%"} gOpts.cmds["help"] = &execExpr{"!", "%lf% -doc | %PAGER%"}
gOpts.nkeys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.nkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.vkeys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.vkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.cmds["maps"] = &execExpr{"!", `%lf% -remote "query %id% maps" | %PAGER%`} gOpts.cmds["maps"] = &execExpr{"!", `%lf% -remote "query %id% maps" | %PAGER%`}
gOpts.cmds["nmaps"] = &execExpr{"!", `%lf% -remote "query %id% nmaps" | %PAGER%`} gOpts.cmds["nmaps"] = &execExpr{"!", `%lf% -remote "query %id% nmaps" | %PAGER%`}
@@ -164,8 +180,7 @@ func setDefaults() {
func setUserUmask() {} func setUserUmask() {}
func isExecutable(f os.FileInfo) bool { func isExecutable(f os.FileInfo) bool {
exts := strings.Split(envPathExt, string(filepath.ListSeparator)) for e := range strings.SplitSeq(envPathExt, string(filepath.ListSeparator)) {
for _, e := range exts {
if strings.HasSuffix(strings.ToLower(f.Name()), strings.ToLower(e)) { if strings.HasSuffix(strings.ToLower(f.Name()), strings.ToLower(e)) {
log.Print(f.Name(), e) log.Print(f.Name(), e)
return true return true
@@ -221,3 +236,16 @@ func quoteString(s string) string {
} }
return s return s
} }
func shellEscape(s string) string {
for _, r := range s {
if strings.ContainsRune(" !%&'()+,;=[]^`{}~", r) {
return fmt.Sprintf(`"%s"`, s)
}
}
return s
}
func shellUnescape(s string) string {
return strings.ReplaceAll(s, `"`, "")
}
+45 -8
View File
@@ -57,7 +57,12 @@ type setExpr struct {
val string val string
} }
func (e *setExpr) String() string { return fmt.Sprintf("set %s %s", e.opt, e.val) } func (e *setExpr) String() string {
if e.val == "" {
return fmt.Sprintf("set %s", e.opt)
}
return fmt.Sprintf("set %s %s", e.opt, e.val)
}
type setLocalExpr struct { type setLocalExpr struct {
path string path string
@@ -65,42 +70,72 @@ type setLocalExpr struct {
val string val string
} }
func (e *setLocalExpr) String() string { return fmt.Sprintf("setlocal %s %s %s", e.path, e.opt, e.val) } func (e *setLocalExpr) String() string {
if e.val == "" {
return fmt.Sprintf("setlocal %s %s", e.path, e.opt)
}
return fmt.Sprintf("setlocal %s %s %s", e.path, e.opt, e.val)
}
type mapExpr struct { type mapExpr struct {
keys string keys string
expr expr expr expr
} }
func (e *mapExpr) String() string { return fmt.Sprintf("map %s %s", e.keys, e.expr) } func (e *mapExpr) String() string {
if e.expr == nil {
return fmt.Sprintf("map %s", e.keys)
}
return fmt.Sprintf("map %s %s", e.keys, e.expr)
}
type nmapExpr struct { type nmapExpr struct {
keys string keys string
expr expr expr expr
} }
func (e *nmapExpr) String() string { return fmt.Sprintf("nmap %s %s", e.keys, e.expr) } func (e *nmapExpr) String() string {
if e.expr == nil {
return fmt.Sprintf("nmap %s", e.keys)
}
return fmt.Sprintf("nmap %s %s", e.keys, e.expr)
}
type vmapExpr struct { type vmapExpr struct {
keys string keys string
expr expr expr expr
} }
func (e *vmapExpr) String() string { return fmt.Sprintf("vmap %s %s", e.keys, e.expr) } func (e *vmapExpr) String() string {
if e.expr == nil {
return fmt.Sprintf("vmap %s", e.keys)
}
return fmt.Sprintf("vmap %s %s", e.keys, e.expr)
}
type cmapExpr struct { type cmapExpr struct {
key string key string
expr expr expr expr
} }
func (e *cmapExpr) String() string { return fmt.Sprintf("cmap %s %s", e.key, e.expr) } func (e *cmapExpr) String() string {
if e.expr == nil {
return fmt.Sprintf("cmap %s", e.key)
}
return fmt.Sprintf("cmap %s %s", e.key, e.expr)
}
type cmdExpr struct { type cmdExpr struct {
name string name string
expr expr expr expr
} }
func (e *cmdExpr) String() string { return fmt.Sprintf("cmd %s %s", e.name, e.expr) } func (e *cmdExpr) String() string {
if e.expr == nil {
return fmt.Sprintf("cmd %s", e.name)
}
return fmt.Sprintf("cmd %s %s", e.name, e.expr)
}
type callExpr struct { type callExpr struct {
name string name string
@@ -108,7 +143,9 @@ type callExpr struct {
count int count int
} }
func (e *callExpr) String() string { return fmt.Sprintf("%s -- %s", e.name, e.args) } func (e *callExpr) String() string {
return strings.Join(append([]string{e.name}, e.args...), " ")
}
type execExpr struct { type execExpr struct {
prefix string prefix string
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"fmt"
"log"
"os"
"strings"
"text/template"
_ "embed"
)
//go:embed etc/ruler.default
var gDefaultRuler string
type statData struct {
Path string
Name string
Size uint64
Permissions string
ModTime string
LinkCount string
User string
Group string
Target string
}
type rulerData struct {
SPACER string
Message string
Keys string
Progress []string
Copy []string
Cut []string
Select []string
Visual []string
Index int
Total int
Hidden int
LinePercentage string
ScrollPercentage string
Filter []string
Mode string
Options map[string]string
UserOptions map[string]string
Stat *statData
}
func parseRuler() (*template.Template, error) {
funcs := template.FuncMap{
"df": func() string { return diskFree(".") },
"env": os.Getenv,
"humanize": humanize,
"join": strings.Join,
"lower": strings.ToLower,
"substr": func(s string, start, length int) string { return string([]rune(s)[start : start+length]) },
"upper": strings.ToUpper,
}
for i := len(gRulerPaths) - 1; i >= 0; i-- {
path := gRulerPaths[i]
if _, err := os.Stat(path); os.IsNotExist(err) {
continue
}
log.Printf("reading file: %s", path)
return template.New("ruler").Funcs(funcs).ParseFiles(path)
}
return template.New("ruler").Funcs(funcs).Parse(gDefaultRuler)
}
func renderRuler(ruler *template.Template, data rulerData, width int) (string, string, error) {
var b strings.Builder
if err := ruler.Execute(&b, data); err != nil {
return "", "", err
}
s := strings.TrimSuffix(b.String(), "\n")
s = strings.ReplaceAll(s, "\n", "\033[0;7m\\n\033[0m")
sections := strings.Split(s, "\x1f")
if len(sections) == 1 {
return s, "", nil
}
wtot := 0
for _, section := range sections {
wtot += printLength(section)
}
if wtot > width {
return sections[0], strings.Join(sections[1:], ""), nil
}
wspacer := max(width-wtot, 0) / (len(sections) - 1)
wspacerLast := max(width-wtot-wspacer*(len(sections)-2), 0)
b.Reset()
for i, section := range sections {
switch i {
case 0:
b.WriteString(section)
case len(sections) - 1:
fmt.Fprintf(&b, "%*s%s", wspacerLast, "", section)
default:
fmt.Fprintf(&b, "%*s%s", wspacer, "", section)
}
}
return b.String(), "", nil
}
+20 -8
View File
@@ -17,7 +17,7 @@ var (
func serve() { func serve() {
if gLogPath != "" { if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 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("failed to open log file: %s", err)
} }
@@ -25,7 +25,7 @@ func serve() {
log.SetOutput(f) log.SetOutput(f)
} }
log.Print("hi!") log.Print("*************** starting server ***************")
if gSocketProt == "unix" { if gSocketProt == "unix" {
setUserUmask() setUserUmask()
@@ -49,7 +49,7 @@ func listen(l net.Listener) {
if err != nil { if err != nil {
select { select {
case <-gQuitChan: case <-gQuitChan:
log.Printf("bye!") log.Print("*************** closing server ***************")
return return
default: default:
log.Printf("accepting connection: %s", err) log.Printf("accepting connection: %s", err)
@@ -111,12 +111,16 @@ Loop:
word2, rest2 := splitWord(rest) word2, rest2 := splitWord(rest)
id, err := strconv.Atoi(word2) id, err := strconv.Atoi(word2)
if err != nil { if err != nil {
for _, c := range gConnList { for id, c2 := range gConnList {
fmt.Fprintln(c, rest) if _, err := fmt.Fprintln(c2, rest); err != nil {
echoerrf(c, "failed to send command to client %v: %s", id, err)
}
} }
} else { } else {
if c2, ok := gConnList[id]; ok { if c2, ok := gConnList[id]; ok {
fmt.Fprintln(c2, rest2) if _, err := fmt.Fprintln(c2, rest2); err != nil {
echoerrf(c, "failed to send command to client %v: %s", id, err)
}
} else { } else {
echoerr(c, "listen: send: no such client id is connected") echoerr(c, "listen: send: no such client id is connected")
} }
@@ -138,10 +142,18 @@ Loop:
echoerr(c, "listen: query: no such client id is connected") echoerr(c, "listen: query: no such client id is connected")
break break
} }
fmt.Fprintln(c2, "query "+rest2) if _, err := fmt.Fprintln(c2, "query "+rest2); err != nil {
echoerrf(c, "failed to send query to client %v: %s", id, err)
break
}
s2 := bufio.NewScanner(c2) s2 := bufio.NewScanner(c2)
for s2.Scan() && s2.Text() != "" { for s2.Scan() && s2.Text() != "" {
fmt.Fprintln(c, s2.Text()) if _, err := fmt.Fprintln(c, s2.Text()); err != nil {
log.Printf("failed to forward query response from client %v: %s", id, err)
}
}
if s2.Err() != nil {
echoerrf(c, "failed to read query response from client %v: %s", id, s2.Err())
} }
case "quit": case "quit":
if len(gConnList) == 0 { if len(gConnList) == 0 {
+40 -11
View File
@@ -6,12 +6,11 @@ import (
"log" "log"
"os" "os"
"strconv" "strconv"
"strings"
"github.com/gdamore/tcell/v2" "github.com/gdamore/tcell/v2"
) )
const gSixelBegin = "\033P"
type sixelScreen struct { type sixelScreen struct {
lastFile string lastFile string
lastWin win lastWin win
@@ -29,7 +28,7 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return return
} }
if reg.sixel == nil { if !reg.sixel {
sxs.lastFile = "" sxs.lastFile = ""
return return
} }
@@ -40,11 +39,28 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return return
} }
matches := reSixelSize.FindStringSubmatch(*reg.sixel) y := win.y
if matches == nil { var b strings.Builder
log.Printf("sixel: failed to get image size")
return for _, line := range reg.lines {
if !strings.HasPrefix(line, "\033P") {
if y >= win.y+win.h {
break
} }
screen.LockRegion(win.x, y, printLength(line), 1, true)
fmt.Fprintf(&b, "\033[%d;%dH", y+1, win.x+1)
b.WriteString(line)
y++
continue
}
matches := reSixelSize.FindStringSubmatch(line)
if matches == nil {
log.Print("sixel: failed to get image size")
continue
}
iw, _ := strconv.Atoi(matches[1]) iw, _ := strconv.Atoi(matches[1])
ih, _ := strconv.Atoi(matches[2]) ih, _ := strconv.Atoi(matches[2])
@@ -55,11 +71,24 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
ih = (ih + 5) / 6 * 6 ih = (ih + 5) / 6 * 6
} }
screen.LockRegion(win.x, win.y, (iw+cw-1)/cw, (ih+ch-1)/ch, true) sw := (iw + cw - 1) / cw
sh := (ih + ch - 1) / ch
if y+sh-1 >= win.y+win.h {
break
}
screen.LockRegion(win.x, y, sw, sh, true)
fmt.Fprintf(&b, "\033[%d;%dH", y+1, win.x+1)
b.WriteString(line)
y += sh
}
fmt.Fprint(os.Stderr, "\033[?2026h") // Begin synchronized update
fmt.Fprint(os.Stderr, "\0337") // Save cursor position fmt.Fprint(os.Stderr, "\0337") // Save cursor position
fmt.Fprintf(os.Stderr, "\033[%d;%dH", win.y+1, win.x+1) // Move cursor to position fmt.Fprint(os.Stderr, b.String()) // Write data
fmt.Fprint(os.Stderr, *reg.sixel) // Print sixel
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
fmt.Fprint(os.Stderr, "\033[?2026l") // End synchronized update
sxs.lastFile = reg.path sxs.lastFile = reg.path
sxs.lastWin = *win sxs.lastWin = *win
@@ -75,7 +104,7 @@ func cellSize(screen tcell.Screen) (int, int, error) {
ws, err := tty.WindowSize() ws, err := tty.WindowSize()
if err != nil { if err != nil {
return -1, -1, fmt.Errorf("failed to get window size: %s", err) return -1, -1, fmt.Errorf("failed to get window size: %w", err)
} }
cw, ch := ws.CellDimensions() cw, ch := ws.CellDimensions()
+261
View File
@@ -0,0 +1,261 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"log"
"strconv"
"strings"
"unicode/utf8"
"github.com/gdamore/tcell/v2"
)
// This function is used to remove style-related ANSI escape sequences from
// a given string.
//
// *Note*: this function is based entirely on `printLength()` and strips only
// style-related sequences, `erase in line` and `OSC 8` sequences. Other codes
// (e.g., cursor moves), as well as broken escape sequences, aren't removed.
// This prevents mismatches between the two functions and avoids misalignment
// when rendering the UI.
func stripTermSequence(s string) string {
var b strings.Builder
slen := len(s)
for i := 0; i < slen; i++ {
seq := readTermSequence(s[i:])
if seq != "" {
i += len(seq) - 1 // skip known sequence
continue
}
r, w := utf8.DecodeRuneInString(s[i:])
i += w - 1
b.WriteRune(r)
}
return b.String()
}
// This function is used to extract and return a terminal sequence from a given
// string. If no supported sequence could be found, an empty string is returned.
//
// CSI (Control Sequence Introducer):
// - SGR (Select Graphic Rendition) `m`, used for text styling
// - EL (Erase in Line) `K`, returned only so we can skip it
//
// OSC (Operating System Command):
// - OSC 8, hyperlinks
func readTermSequence(s string) string {
slen := len(s)
// must start with ESC
if slen < 2 || s[0] != byte(gEscapeCode) {
return ""
}
switch s[1] {
case '[': // CSI
i := strings.IndexAny(s[:min(slen, 64)], "mK")
if i == -1 {
return ""
}
return s[:i+1]
case ']': // OSC
if slen < 4 || s[2] != '8' || s[3] != ';' {
return ""
}
// find string terminator
for i := 4; i < slen; i++ {
b := s[i]
// BEL (XTerm)
if b == 0x07 {
return s[:i+1]
}
// ESC\ (ECMA-48)
if b == byte(gEscapeCode) && i+1 < slen && s[i+1] == '\\' {
return s[:i+2]
}
}
// TODO: C1 forms?
return ""
default:
return ""
}
}
// This function takes an escape sequence option (e.g. `\033[1m`) and converts
// it to a `tcell.Style` object.
// Legacy function that only accepts SGR. Kept for convenience.
func parseEscapeSequence(s string) tcell.Style {
s = strings.TrimPrefix(s, "\033[")
if i := strings.IndexByte(s, 'm'); i >= 0 {
s = s[:i]
}
return applySGR(s, tcell.StyleDefault)
}
// This function takes an escape sequence (e.g. `\033[1m`) and applies it
// to the given `tcell.Style` object.
// Accepts SGR and OSC sequences.
func applyTermSequence(s string, st tcell.Style) tcell.Style {
slen := len(s)
if slen < 2 || s[0] != byte(gEscapeCode) {
return st
}
switch s[1] {
case '[':
if s[slen-1] == 'm' {
return applySGR(s[2:slen-1], st)
}
return st
case ']':
// trim terminator (BEL or ESC\), then parse body
if s[slen-1] == 0x07 {
return applyOSC(s[2:slen-1], st)
} else if slen >= 2 && s[slen-2] == byte(gEscapeCode) && s[slen-1] == '\\' {
return applyOSC(s[2:slen-2], st)
}
return st
default:
return st
}
}
func applySGR(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";")
// ECMA-48 details the standard
tokslen := len(toks)
loop:
for i := 0; i < tokslen; i++ {
switch strings.TrimLeft(toks[i], "0") {
case "":
st = tcell.StyleDefault
case "1":
st = st.Bold(true)
case "2":
st = st.Dim(true)
case "3":
st = st.Italic(true)
case "4:0":
st = st.Underline(false)
case "4", "4:1":
st = st.Underline(true)
case "4:2":
st = st.Underline(tcell.UnderlineStyleDouble)
case "4:3":
st = st.Underline(tcell.UnderlineStyleCurly)
case "4:4":
st = st.Underline(tcell.UnderlineStyleDotted)
case "4:5":
st = st.Underline(tcell.UnderlineStyleDashed)
case "5", "6":
st = st.Blink(true)
case "7":
st = st.Reverse(true)
case "8":
// TODO: tcell PR for proper conceal
_, bg, _ := st.Decompose()
st = st.Foreground(bg)
case "9":
st = st.StrikeThrough(true)
case "22":
st = st.Bold(false).Dim(false)
case "23":
st = st.Italic(false)
case "24":
st = st.Underline(false)
case "25":
st = st.Blink(false)
case "27":
st = st.Reverse(false)
case "29":
st = st.StrikeThrough(false)
case "30", "31", "32", "33", "34", "35", "36", "37":
n, _ := strconv.Atoi(toks[i])
st = st.Foreground(tcell.PaletteColor(n - 30))
case "90", "91", "92", "93", "94", "95", "96", "97":
n, _ := strconv.Atoi(toks[i])
st = st.Foreground(tcell.PaletteColor(n - 82))
case "38":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 38: %s", err)
break loop
}
st = st.Foreground(color)
i += offset
case "40", "41", "42", "43", "44", "45", "46", "47":
n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 40))
case "100", "101", "102", "103", "104", "105", "106", "107":
n, _ := strconv.Atoi(toks[i])
st = st.Background(tcell.PaletteColor(n - 92))
case "48":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 48: %s", err)
break loop
}
st = st.Background(color)
i += offset
case "58":
color, offset, err := parseColor(toks[i+1:])
if err != nil {
log.Printf("error processing ansi code 58: %s", err)
break loop
}
st = st.Underline(color)
i += offset
default:
log.Printf("unknown ansi code: %s", toks[i])
}
}
return st
}
// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
func applyOSC(body string, st tcell.Style) tcell.Style {
genAutoID := func(url string) string {
sum := sha256.Sum256([]byte(url))
return "lf_hyperlink_" + hex.EncodeToString(sum[:8])
}
extractID := func(params string) string {
for seg := range strings.SplitSeq(params, ":") {
if seg == "" {
continue
}
if k, v, ok := strings.Cut(seg, "="); ok && k == "id" {
return v
}
}
return ""
}
toks := strings.SplitN(body, ";", 3)
if len(toks) < 2 {
return st
}
switch toks[0] {
case "8":
if len(toks) < 3 {
return st
}
url := toks[2]
if url == "" {
return st
}
// Optional property used to identify grouped hyperlinks.
// Use hash as a fallback to ensure a "unique" id.
if id := extractID(toks[1]); id != "" {
st = st.UrlId(id)
} else {
st = st.UrlId(genAutoID(url))
}
return st.Url(url)
default:
return st
}
}
+221
View File
@@ -0,0 +1,221 @@
package main
import (
"testing"
"github.com/gdamore/tcell/v2"
)
func TestStripTermSequence(t *testing.T) {
tests := []struct {
s string
exp string
}{
{"", ""}, // empty
{"foo bar", "foo bar"}, // plain text
{"\033[31mRed\033[0m", "Red"}, // octal syntax
{"\x1b[31mRed\x1b[0m", "Red"}, // hexadecimal syntax
{"foo\x1b[31mRed", "fooRed"}, // no reset parameter
{
"foo\x1b[1;31;102mBoldRedGreen\x1b[0mbar",
"fooBoldRedGreenbar",
}, // multiple attributes
{
"misc.go:func \x1b[01;31m\x1b[KstripTermSequence\x1b[m\x1b[K(s string) string {",
"misc.go:func stripTermSequence(s string) string {",
}, // `grep` output containing `erase in line` sequence
// OSC 8 hyperlinks
{
"\x1b]8;;https://example.com\x1b\\example.com\x1b]8;;\x1b\\",
"example.com",
}, // open/close with ST (ESC\)
{
"\x1b]8;;https://example.com\x07example.com\x1b]8;;\x07",
"example.com",
}, // open/close with BEL
{
"\x1b]8;id=42;https://example.com\x1b\\label\x1b]8;;\x1b\\",
"label",
}, // params present
{
"\x1b]8;;https://example.com\x1b\\example.com",
"example.com",
}, // open without close
}
for _, test := range tests {
if got := stripTermSequence(test.s); got != test.exp {
t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got)
}
// we rely on both functions extracting the same runes
// to avoid misalignment
if printLength(test.s) != len(stripTermSequence(test.s)) {
t.Errorf("at input %q expected '%d' but got '%d'", test.s, printLength(test.s), len(stripTermSequence(test.s)))
}
}
}
func TestReadTermSequence(t *testing.T) {
tests := []struct {
s, exp string
}{
{"", ""}, // empty
{"foo bar", ""}, // plain text
{"\x1b", ""}, // lone ESC
{"\x1bX", ""}, // unknown ESC sequence
{"\x1b[31m", "\x1b[31m"}, // CSI SGR
{"\x1b[K", "\x1b[K"}, // CSI EL
{"\x1b[1;31m", "\x1b[1;31m"}, // CSI SGR (multiple params)
{"\x1b[31", ""}, // CSI incomplete (no terminator)
{"foo\x1b[31m", ""}, // doesn't start with ESC
{"\x1b]8;;https://example.com\x1b\\", "\x1b]8;;https://example.com\x1b\\"}, // OSC 8 (ST terminator)
{"\x1b]8;;https://example.com\x07", "\x1b]8;;https://example.com\x07"}, // OSC 8 (BEL terminator)
{"\x1b]0;title\x07", ""}, // non-OSC8 OSC (ignored)
}
for _, tc := range tests {
if got := readTermSequence(tc.s); got != tc.exp {
t.Errorf("input %q: got %q, want %q", tc.s, got, tc.exp)
}
}
}
func TestParseEscapeSequence(t *testing.T) {
tests := []struct {
s string
exp tcell.Style
}{
{"\033[1m", tcell.StyleDefault.Bold(true)},
{"\033[1;7;31;42m", tcell.StyleDefault.Bold(true).Reverse(true).Foreground(tcell.ColorMaroon).Background(tcell.ColorGreen)},
}
for _, test := range tests {
if got := parseEscapeSequence(test.s); got != test.exp {
t.Errorf("at input %q expected '%v' but got '%v'", test.s, test.exp, got)
}
}
}
func TestApplyTermSequence(t *testing.T) {
tests := []struct {
s string
exp tcell.Style
}{
{"", tcell.StyleDefault},
{"\x1b[1m", tcell.StyleDefault.Bold(true)},
{"\x1b[1;7;31;42m", tcell.StyleDefault.Bold(true).Reverse(true).Foreground(tcell.ColorMaroon).Background(tcell.ColorGreen)},
{
"\x1b]8;;https://example.com\x1b\\",
tcell.StyleDefault.UrlId("lf_hyperlink_100680ad546ce6a5").Url("https://example.com"),
}, // OSC 8 terminated with ST (ESC\), no `id` provided
{
"\x1b]8;;https://example.com\x07",
tcell.StyleDefault.UrlId("lf_hyperlink_100680ad546ce6a5").Url("https://example.com"),
}, // OSC 8 terminated with BEL, no `id` provided
{
"\x1b]8;id=42;https://example.com\x1b\\",
tcell.StyleDefault.UrlId("42").Url("https://example.com"),
}, // OSC 8, `id` provided
}
for _, test := range tests {
if got := applyTermSequence(test.s, tcell.StyleDefault); got != test.exp {
t.Errorf("at input %q expected '%v' but got '%v'", test.s, test.exp, got)
}
}
}
func TestApplySGR(t *testing.T) {
none := tcell.StyleDefault
tests := []struct {
s string
st tcell.Style
stExp tcell.Style
}{
{"", none, none},
{"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"", none.Bold(true), none},
{"", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"0", none, none},
{"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"0", none.Bold(true), none},
{"0", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"1", none, none.Bold(true)},
{"4", none, none.Underline(true)},
{"7", none, none.Reverse(true)},
{"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)},
{"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)},
{"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"4:0", none, none},
{"4:0", none.Underline(true), none},
{"4:1", none, none.Underline(true)},
{"4:2", none, none.Underline(tcell.UnderlineStyleDouble)},
{"4:3", none, none.Underline(tcell.UnderlineStyleCurly)},
{"4:4", none, none.Underline(tcell.UnderlineStyleDotted)},
{"4:5", none, none.Underline(tcell.UnderlineStyleDashed)},
{"22", none.Italic(true).Bold(true).Dim(true), none.Italic(true)},
{"23", none.Bold(true).Italic(true), none.Bold(true)},
{"24", none.Bold(true).Underline(true), none.Bold(true)},
{"25", none.Bold(true).Blink(true), none.Bold(true)},
{"27", none.Bold(true).Reverse(true), none.Bold(true)},
{"29", none.Bold(true).StrikeThrough(true), none.Bold(true)},
{"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"41", none, none.Background(tcell.ColorMaroon)},
{"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"01;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"01;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none.Foreground(tcell.ColorGray)},
{"38;5;16", none, none.Foreground(tcell.Color16)},
{"38;5;232", none, none.Foreground(tcell.Color232)},
{"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"48;5;0", none, none.Background(tcell.ColorBlack)},
{"48;5;1", none, none.Background(tcell.ColorMaroon)},
{"48;5;8", none, none.Background(tcell.ColorGray)},
{"48;5;16", none, none.Background(tcell.Color16)},
{"48;5;232", none, none.Background(tcell.Color232)},
{"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"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))},
// Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446
{"38;5;34;1", none, none.Foreground(tcell.Color34).Bold(true)},
}
for _, test := range tests {
if stGot := applySGR(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%v' expected '%v' but got '%v'",
test.s, test.st, test.stExp, stGot)
}
}
}
+370 -193
View File
@@ -6,11 +6,13 @@ import (
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"slices" "slices"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"text/tabwriter" "text/tabwriter"
"text/template"
"time" "time"
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
@@ -169,18 +171,13 @@ func printLength(s string) int {
off := 0 off := 0
slen := len(s) slen := len(s)
for i := 0; i < slen; i++ { for i := 0; i < slen; i++ {
seq := readTermSequence(s[i:])
if seq != "" {
i += len(seq) - 1
continue
}
r, w := utf8.DecodeRuneInString(s[i:]) r, w := utf8.DecodeRuneInString(s[i:])
if r == gEscapeCode && i+1 < slen && s[i+1] == '[' {
j := strings.IndexAny(s[i:min(slen, i+64)], "mK")
if j == -1 {
continue
}
i += j
continue
}
i += w - 1 i += w - 1
if r == '\t' { if r == '\t' {
@@ -198,21 +195,14 @@ func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) t
var comb []rune var comb []rune
slen := len(s) slen := len(s)
for i := 0; i < slen; i++ { for i := 0; i < slen; i++ {
seq := readTermSequence(s[i:])
if seq != "" {
st = applyTermSequence(seq, st)
i += len(seq) - 1
continue
}
r, w := utf8.DecodeRuneInString(s[i:]) r, w := utf8.DecodeRuneInString(s[i:])
if r == gEscapeCode && i+1 < slen && s[i+1] == '[' {
j := strings.IndexAny(s[i:min(slen, i+64)], "mK")
if j == -1 {
continue
}
if s[i+j] == 'm' {
st = applyAnsiCodes(s[i+2:i+j], st)
}
i += j
continue
}
for { for {
rc, wc := utf8.DecodeRuneInString(s[i+w:]) rc, wc := utf8.DecodeRuneInString(s[i+w:])
if !unicode.Is(unicode.Mn, rc) { if !unicode.Is(unicode.Mn, rc) {
@@ -270,12 +260,14 @@ func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs
return return
} }
if !reg.sixel {
for i, l := range reg.lines { for i, l := range reg.lines {
if i > win.h-1 { if i > win.h-1 {
break break
} }
st = win.print(screen, 2, i, st, l) st = win.print(screen, 0, i, st, l)
}
} }
sxs.printSixel(win, screen, reg) sxs.printSixel(win, screen, reg)
@@ -304,10 +296,10 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
info.WriteString(" !") info.WriteString(" !")
case f.dirCount < 0: case f.dirCount < 0:
info.WriteString(" ?") info.WriteString(" ?")
case f.dirCount < 1000: case f.dirCount < 10000:
fmt.Fprintf(&info, " %4d", f.dirCount) fmt.Fprintf(&info, " %5d", f.dirCount)
default: default:
info.WriteString(" 999+") info.WriteString(" 9999+")
} }
continue continue
} }
@@ -316,22 +308,28 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
if f.IsDir() && f.dirSize < 0 { if f.IsDir() && f.dirSize < 0 {
sz = "-" sz = "-"
} else { } else {
sz = humanize(f.TotalSize()) sz = humanize(uint64(f.TotalSize()))
} }
fmt.Fprintf(&info, " %4s", sz) fmt.Fprintf(&info, " %5s", sz)
case "time": case "time":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime())) fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
case "atime": case "atime":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime)) fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime))
case "btime":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.birthTime))
case "ctime": case "ctime":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime)) fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime))
case "perm": case "perm":
info.WriteString(" " + f.FileInfo.Mode().String()) info.WriteString(" " + permString(f.Mode()))
case "user": case "user":
fmt.Fprintf(&info, " %-*s", userWidth, userName(f.FileInfo)) fmt.Fprintf(&info, " %-*s", userWidth, userName(f.FileInfo))
case "group": case "group":
fmt.Fprintf(&info, " %-*s", groupWidth, groupName(f.FileInfo)) fmt.Fprintf(&info, " %-*s", groupWidth, groupName(f.FileInfo))
case "custom": case "custom":
// Prevent useless spacers, as `custom` allows empty values
if customWidth < 1 {
continue
}
// To allow for the usage of escape sequences, store `custom` // To allow for the usage of escape sequences, store `custom`
// separately and print it later using the offset. // separately and print it later using the offset.
off = info.Len() off = info.Len()
@@ -347,7 +345,7 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
type dirContext struct { type dirContext struct {
selections map[string]int selections map[string]int
saves map[string]bool clipboard clipboard
tags map[string]string tags map[string]string
} }
@@ -409,6 +407,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
var userWidth int var userWidth int
var groupWidth int var groupWidth int
var customWidth int var customWidth int
var fetchedCustom bool
// Only fetch user/group/custom widths if configured to display them // Only fetch user/group/custom widths if configured to display them
for _, s := range getInfo(dir.path) { for _, s := range getInfo(dir.path) {
@@ -419,9 +418,10 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
groupWidth = getGroupWidth(dir, beg, end) groupWidth = getGroupWidth(dir, beg, end)
case "custom": case "custom":
customWidth = getCustomWidth(dir, beg, end) customWidth = getCustomWidth(dir, beg, end)
fetchedCustom = true // Can have a length of 0
} }
if userWidth > 0 && groupWidth > 0 && customWidth > 0 { if userWidth > 0 && groupWidth > 0 && fetchedCustom {
break break
} }
} }
@@ -433,7 +433,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
if lnwidth > 0 { if lnwidth > 0 {
var ln string var ln string
if gOpts.number && (!gOpts.relativenumber) { if gOpts.number && !gOpts.relativenumber {
ln = fmt.Sprintf("%*d", lnwidth, i+1+beg) ln = fmt.Sprintf("%*d", lnwidth, i+1+beg)
} else if gOpts.relativenumber { } else if gOpts.relativenumber {
switch { switch {
@@ -453,27 +453,31 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
path := filepath.Join(dir.path, f.Name()) path := filepath.Join(dir.path, f.Name())
var fmtStr string
if slices.Contains(visualSelections, path) { if slices.Contains(visualSelections, path) {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.visualfmt), " ") fmtStr = gOpts.visualfmt
} else if _, ok := context.selections[path]; ok { } else if _, ok := context.selections[path]; ok {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.selectfmt), " ") fmtStr = gOpts.selectfmt
} else if cp, ok := context.saves[path]; ok { } else if slices.Contains(context.clipboard.paths, path) {
if cp { if context.clipboard.mode == clipboardCopy {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.copyfmt), " ") fmtStr = gOpts.copyfmt
} else { } else {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.cutfmt), " ") fmtStr = gOpts.cutfmt
} }
} }
if fmtStr != "" {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(fmtStr), " ")
}
// make space for select marker, and leave another space at the end // make space for select marker, and leave another space at the end
maxWidth := win.w - lnwidth - 2 maxWidth := win.w - lnwidth - 2
// make extra space to separate windows if drawbox is not enabled // make extra space to separate windows if drawbox is not enabled
if !gOpts.drawbox { if !gOpts.drawbox {
maxWidth -= 1 maxWidth--
} }
tag := " " tag := " "
if val, ok := context.tags[evalSymlinks(path)]; ok && len(val) > 0 { if val, ok := context.tags[path]; ok && len(val) > 0 {
tag = val tag = val
} }
@@ -481,8 +485,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
var iconDef iconDef var iconDef iconDef
if gOpts.icons { if gOpts.icons {
iconDef = dirStyle.icons.get(f) iconDef = dirStyle.icons.get(f)
icon = append(icon, []rune(iconDef.icon)...) icon = slices.Concat([]rune(iconDef.icon), []rune{' '})
icon = append(icon, ' ')
} }
// subtract space for tag and icon // subtract space for tag and icon
@@ -495,14 +498,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
maxFilenameWidth -= infolen maxFilenameWidth -= infolen
} }
filename := []rune(f.Name()) filename := []rune(truncateFilename(f, maxFilenameWidth, gOpts.truncatepct, []rune(gOpts.truncatechar)[0]))
if runeSliceWidth(filename) > maxFilenameWidth {
truncatePos := (maxFilenameWidth - 1) * gOpts.truncatepct / 100
lastPart := runeSliceWidthLastRange(filename, maxFilenameWidth-truncatePos-1)
filename = runeSliceWidthRange(filename, 0, truncatePos)
filename = append(filename, []rune(gOpts.truncatechar)...)
filename = append(filename, lastPart...)
}
for j := runeSliceWidth(filename); j < maxFilenameWidth; j++ { for j := runeSliceWidth(filename); j < maxFilenameWidth; j++ {
filename = append(filename, ' ') filename = append(filename, ' ')
} }
@@ -526,13 +522,12 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
// print tag separately as it can contain color escape sequences // print tag separately as it can contain color escape sequences
win.print(ui.screen, lnwidth+1, i, st, fmt.Sprintf(cursorFmt, tag)) win.print(ui.screen, lnwidth+1, i, st, fmt.Sprintf(cursorFmt, tag))
line := append(icon, filename...) line := slices.Concat(icon, filename, []rune{' '})
line = append(line, ' ')
win.print(ui.screen, lnwidth+2, i, st, fmt.Sprintf(cursorFmt, string(line))) win.print(ui.screen, lnwidth+2, i, st, fmt.Sprintf(cursorFmt, string(line)))
// print over the empty space we reserved for the custom info // print over the empty space we reserved for the custom info
if showInfo && custom != "" { if showInfo && custom != "" {
win.print(ui.screen, off, i, st, fmt.Sprintf(cursorFmt, stripAnsi(custom))) win.print(ui.screen, off, i, st, fmt.Sprintf(cursorFmt, stripTermSequence(custom)))
} }
} else { } else {
if tag == " " { if tag == " " {
@@ -550,7 +545,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
win.print(ui.screen, lnwidth+2, i, iconStyle, string(icon)) win.print(ui.screen, lnwidth+2, i, iconStyle, string(icon))
} }
line := append(filename, ' ') line := slices.Concat(filename, []rune{' '})
win.print(ui.screen, lnwidth+2+runeSliceWidth(icon), i, st, string(line)) win.print(ui.screen, lnwidth+2+runeSliceWidth(icon), i, st, string(line))
// print over the empty space we reserved for the custom info // print over the empty space we reserved for the custom info
@@ -625,9 +620,9 @@ func getWins(screen tcell.Screen) []*win {
for i := range wlen { for i := range wlen {
if gOpts.drawbox { if gOpts.drawbox {
wacc++ wacc++
wins = append(wins, newWin(widths[i], htot-4, wacc, 2)) wins = append(wins, newWin(widths[i], max(htot-4, 0), wacc, 2))
} else { } else {
wins = append(wins, newWin(widths[i], htot-2, wacc, 1)) wins = append(wins, newWin(widths[i], max(htot-2, 0), wacc, 1))
} }
wacc += widths[i] wacc += widths[i]
} }
@@ -635,6 +630,11 @@ func getWins(screen tcell.Screen) []*win {
return wins return wins
} }
type menuSelect struct {
x, y int
s string
}
type ui struct { type ui struct {
screen tcell.Screen screen tcell.Screen
sxScreen sixelScreen sxScreen sixelScreen
@@ -644,7 +644,6 @@ type ui struct {
msgWin *win msgWin *win
menuWin *win menuWin *win
msg string msg string
msgIsStat bool
regPrev *reg regPrev *reg
dirPrev *dir dirPrev *dir
exprChan chan expr exprChan chan expr
@@ -652,16 +651,19 @@ type ui struct {
tevChan chan tcell.Event tevChan chan tcell.Event
evChan chan tcell.Event evChan chan tcell.Event
menu string menu string
menuSelect *menuSelect
cmdPrefix string cmdPrefix string
cmdAccLeft []rune cmdAccLeft []rune
cmdAccRight []rune cmdAccRight []rune
cmdYankBuf []rune cmdYankBuf []rune
cmdTmp []rune
keyAcc []rune keyAcc []rune
keyCount []rune keyCount []rune
styles styleMap styles styleMap
icons iconMap icons iconMap
ruler *template.Template
rulerErr error
currentFile string currentFile string
pasteEvent bool
} }
func newUI(screen tcell.Screen) *ui { func newUI(screen tcell.Screen) *ui {
@@ -674,7 +676,6 @@ func newUI(screen tcell.Screen) *ui {
promptWin: newWin(wtot, 1, 0, 0), promptWin: newWin(wtot, 1, 0, 0),
msgWin: newWin(wtot, 1, 0, htot-1), msgWin: newWin(wtot, 1, 0, htot-1),
menuWin: newWin(wtot, 1, 0, htot-2), menuWin: newWin(wtot, 1, 0, htot-2),
msgIsStat: true,
exprChan: make(chan expr, 1000), exprChan: make(chan expr, 1000),
keyChan: make(chan string, 1000), keyChan: make(chan string, 1000),
tevChan: make(chan tcell.Event, 1000), tevChan: make(chan tcell.Event, 1000),
@@ -684,6 +685,7 @@ func newUI(screen tcell.Screen) *ui {
currentFile: "", currentFile: "",
sxScreen: sixelScreen{}, sxScreen: sixelScreen{},
} }
ui.ruler, ui.rulerErr = parseRuler()
go ui.pollEvents() go ui.pollEvents()
@@ -732,7 +734,6 @@ func (ui *ui) sort() {
func (ui *ui) echo(msg string) { func (ui *ui) echo(msg string) {
ui.msg = msg ui.msg = msg
ui.msgIsStat = false
} }
func (ui *ui) echomsg(msg string) { func (ui *ui) echomsg(msg string) {
@@ -740,14 +741,6 @@ func (ui *ui) echomsg(msg string) {
log.Print(msg) log.Print(msg)
} }
func optionToFmtstr(optstr string) string {
if !strings.Contains(optstr, "%s") {
return optstr + "%s\033[0m"
} else {
return optstr
}
}
func (ui *ui) echoerr(msg string) { func (ui *ui) echoerr(msg string) {
ui.echo(fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg)) ui.echo(fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg))
log.Printf("error: %s", msg) log.Printf("error: %s", msg)
@@ -766,7 +759,7 @@ type reg struct {
loadTime time.Time loadTime time.Time
path string path string
lines []string lines []string
sixel *string sixel bool
} }
func (ui *ui) loadFile(app *app, volatile bool) { func (ui *ui) loadFile(app *app, volatile bool) {
@@ -792,72 +785,21 @@ func (ui *ui) loadFile(app *app, volatile bool) {
return return
} }
if curr.Mode().IsRegular() || (curr.IsDir() && gOpts.dirpreviews) { if curr.isPreviewable() {
ui.regPrev = app.nav.loadReg(curr.path, volatile) ui.regPrev = app.nav.loadReg(curr.path, volatile)
} else if curr.IsDir() { } else if curr.IsDir() {
ui.dirPrev = app.nav.loadDir(curr.path) ui.dirPrev = app.nav.loadDir(curr.path)
} }
} }
func (ui *ui) loadFileInfo(nav *nav) {
if !nav.init {
return
}
ui.msg = ""
ui.msgIsStat = true
curr, err := nav.currFile()
if err != nil {
return
}
if curr.err != nil {
ui.echoerrf("stat: %s", curr.err)
return
}
statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f")
replace := func(s string, val string) {
if val == "" {
val = "\x00"
}
statfmt = strings.ReplaceAll(statfmt, s, val)
}
if nav.isVisualMode() {
replace("%m", "VISUAL")
replace("%M", "VISUAL")
} else {
replace("%m", "")
replace("%M", "NORMAL")
}
replace("%p", curr.Mode().String())
replace("%c", linkCount(curr))
replace("%u", userName(curr))
replace("%g", groupName(curr))
replace("%s", humanize(curr.Size()))
replace("%S", fmt.Sprintf("%4s", humanize(curr.Size())))
replace("%t", curr.ModTime().Format(gOpts.timefmt))
replace("%l", curr.linkTarget)
var fileInfo strings.Builder
for _, section := range strings.Split(statfmt, "\x1f") {
if !strings.Contains(section, "\x00") {
fileInfo.WriteString(section)
}
}
ui.msg = fileInfo.String()
}
func (ui *ui) drawPromptLine(nav *nav) { func (ui *ui) drawPromptLine(nav *nav) {
st := tcell.StyleDefault st := tcell.StyleDefault
dir := nav.currDir() dir := nav.currDir()
pwd := dir.path pwd := dir.path
if strings.HasPrefix(pwd, gUser.HomeDir) { if after, ok := strings.CutPrefix(pwd, gUser.HomeDir); ok {
pwd = filepath.Join("~", strings.TrimPrefix(pwd, gUser.HomeDir)) pwd = filepath.Join("~", after)
} }
sep := string(filepath.Separator) sep := string(filepath.Separator)
@@ -923,13 +865,61 @@ func formatRulerOpt(name string, val string) string {
return val return val
} }
func (ui *ui) drawStat(nav *nav) {
if ui.msg != "" {
ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, ui.msg)
return
}
curr, err := nav.currFile()
if err != nil {
return
}
if curr.err != nil {
ui.echoerrf("stat: %s", curr.err)
ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, ui.msg)
return
}
statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f")
replace := func(s string, val string) {
if val == "" {
val = "\x00"
}
statfmt = strings.ReplaceAll(statfmt, s, val)
}
if nav.isVisualMode() {
replace("%m", "VISUAL")
replace("%M", "VISUAL")
} else {
replace("%m", "")
replace("%M", "NORMAL")
}
replace("%p", permString(curr.Mode()))
replace("%c", linkCount(curr))
replace("%u", userName(curr))
replace("%g", groupName(curr))
replace("%s", humanize(uint64(curr.Size())))
replace("%S", fmt.Sprintf("%5s", humanize(uint64(curr.Size()))))
replace("%t", curr.ModTime().Format(gOpts.timefmt))
replace("%l", curr.linkTarget)
var fileInfo strings.Builder
for section := range strings.SplitSeq(statfmt, "\x1f") {
if !strings.Contains(section, "\x00") {
fileInfo.WriteString(section)
}
}
ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, fileInfo.String())
}
func (ui *ui) drawRuler(nav *nav) { func (ui *ui) drawRuler(nav *nav) {
st := tcell.StyleDefault st := tcell.StyleDefault
dir := nav.currDir() dir := nav.currDir()
ui.msgWin.print(ui.screen, 0, 0, st, ui.msg)
tot := len(dir.files) tot := len(dir.files)
ind := min(dir.ind+1, tot) ind := min(dir.ind+1, tot)
hid := len(dir.allFiles) - tot hid := len(dir.allFiles) - tot
@@ -948,14 +938,12 @@ func (ui *ui) drawRuler(nav *nav) {
percentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height)) percentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height))
} }
copy := 0 numClipCopy := 0
move := 0 numClipMove := 0
for _, cp := range nav.saves { if nav.clipboard.mode == clipboardCopy {
if cp { numClipCopy = len(nav.clipboard.paths)
copy++
} else { } else {
move++ numClipMove = len(nav.clipboard.paths)
}
} }
currSelections := nav.currSelections() currSelections := nav.currSelections()
@@ -963,9 +951,13 @@ func (ui *ui) drawRuler(nav *nav) {
progress := []string{} progress := []string{}
if nav.copyTotal > 0 { if nav.copyJobs > 0 {
if nav.copyTotal == 0 {
progress = append(progress, fmt.Sprintf("[0%%]"))
} else {
progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal)) progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal))
} }
}
if nav.moveTotal > 0 { if nav.moveTotal > 0 {
progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal)) progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal))
@@ -986,9 +978,9 @@ func (ui *ui) drawRuler(nav *nav) {
case "%p": case "%p":
result = strings.Join(progress, " ") result = strings.Join(progress, " ")
case "%m": case "%m":
result = fmt.Sprintf("%.d", move) result = fmt.Sprintf("%.d", numClipMove)
case "%c": case "%c":
result = fmt.Sprintf("%.d", copy) result = fmt.Sprintf("%.d", numClipCopy)
case "%s": case "%s":
result = fmt.Sprintf("%.d", len(currSelections)) result = fmt.Sprintf("%.d", len(currSelections))
case "%v": case "%v":
@@ -1017,7 +1009,7 @@ func (ui *ui) drawRuler(nav *nav) {
return result return result
}) })
var ruler strings.Builder var ruler strings.Builder
for _, section := range strings.Split(rulerfmt, "\x1f") { for section := range strings.SplitSeq(rulerfmt, "\x1f") {
if !strings.Contains(section, "\x00") { if !strings.Contains(section, "\x00") {
ruler.WriteString(section) ruler.WriteString(section)
} }
@@ -1025,6 +1017,137 @@ func (ui *ui) drawRuler(nav *nav) {
ui.msgWin.printRight(ui.screen, 0, st, ruler.String()) ui.msgWin.printRight(ui.screen, 0, st, ruler.String())
} }
func (ui *ui) drawRulerFile(nav *nav) {
if ui.rulerErr != nil {
err := fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), fmt.Errorf("parsing ruler: %w", ui.rulerErr))
ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, err)
return
}
var stat *statData
curr, err := nav.currFile()
if err == nil {
if curr.err == nil {
stat = &statData{
Path: curr.path,
Name: curr.Name(),
Size: uint64(curr.Size()),
Permissions: permString(curr.Mode()),
ModTime: curr.ModTime().Format(gOpts.timefmt),
LinkCount: linkCount(curr),
User: userName(curr),
Group: groupName(curr),
Target: curr.linkTarget,
}
} else {
ui.echoerrf("stat: %s", curr.err)
}
}
dir := nav.currDir()
tot := len(dir.files)
ind := min(dir.ind+1, tot)
hid := len(dir.allFiles) - tot
var linePercentage string
if tot == 0 {
linePercentage = "100%"
} else {
linePercentage = fmt.Sprintf("%d%%", ind*100/tot)
}
var scrollPercentage string
beg := max(dir.ind-dir.pos, 0)
switch {
case tot <= nav.height:
scrollPercentage = "All"
case beg == 0:
scrollPercentage = "Top"
case beg == tot-nav.height:
scrollPercentage = "Bot"
default:
scrollPercentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height))
}
var copiedPaths []string
var cutPaths []string
if nav.clipboard.mode == clipboardCopy {
copiedPaths = nav.clipboard.paths
} else {
cutPaths = nav.clipboard.paths
}
currSelections := nav.currSelections()
currVSelections := nav.currDir().visualSelections()
progress := []string{}
if nav.copyJobs > 0 {
if nav.copyTotal == 0 {
progress = append(progress, fmt.Sprintf("[0%%]"))
} else {
progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal))
}
}
if nav.moveTotal > 0 {
progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal))
}
if nav.deleteTotal > 0 {
progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal))
}
mode := "NORMAL"
if nav.isVisualMode() {
mode = "VISUAL"
}
options := make(map[string]string)
v := reflect.ValueOf(gOpts)
t := v.Type()
for i := range v.NumField() {
name := t.Field(i).Name
switch name {
case "nkeys", "vkeys", "cmdkeys", "cmds", "user":
continue
default:
options[name] = fieldToString(v.Field(i))
}
}
data := rulerData{
SPACER: "\x1f",
Message: ui.msg,
Keys: string(ui.keyCount) + string(ui.keyAcc),
Progress: progress,
Copy: copiedPaths,
Cut: cutPaths,
Select: currSelections,
Visual: currVSelections,
Index: ind,
Total: tot,
Hidden: hid,
LinePercentage: linePercentage,
ScrollPercentage: scrollPercentage,
Filter: dir.filter,
Mode: mode,
Options: options,
UserOptions: gOpts.user,
Stat: stat,
}
left, right, err := renderRuler(ui.ruler, data, ui.msgWin.w)
if err != nil {
err := fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), fmt.Errorf("rendering ruler: %w", err))
ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, err)
return
}
ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, left)
ui.msgWin.printRight(ui.screen, 0, tcell.StyleDefault, right)
}
func (ui *ui) drawBox() { func (ui *ui) drawBox() {
st := parseEscapeSequence(gOpts.borderfmt) st := parseEscapeSequence(gOpts.borderfmt)
@@ -1063,6 +1186,38 @@ func (ui *ui) drawBox() {
} }
} }
func (ui *ui) drawMenu() {
if ui.menu == "" {
return
}
lines := strings.Split(ui.menu, "\n")
lines = lines[:len(lines)-1]
ui.menuWin.h = len(lines)
ui.menuWin.y = ui.msgWin.y - ui.menuWin.h
// clear sixel image if it overlaps with the menu
ui.screen.LockRegion(ui.menuWin.x, ui.menuWin.y, ui.menuWin.w, ui.menuWin.h, false)
ui.sxScreen.forceClear = true
for i, line := range lines {
var st tcell.Style
if i == 0 {
st = parseEscapeSequence(gOpts.menuheaderfmt)
} else {
st = parseEscapeSequence(gOpts.menufmt)
}
ui.menuWin.printLine(ui.screen, 0, i, st, line)
}
if ui.menuSelect != nil {
st := parseEscapeSequence(gOpts.menuselectfmt)
ui.menuWin.print(ui.screen, ui.menuSelect.x, ui.menuSelect.y, st, ui.menuSelect.s)
}
}
func (ui *ui) dirOfWin(nav *nav, wind int) *dir { func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
wins := len(ui.wins) wins := len(ui.wins)
if gOpts.preview { if gOpts.preview {
@@ -1077,7 +1232,7 @@ func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
func (ui *ui) draw(nav *nav) { func (ui *ui) draw(nav *nav) {
st := tcell.StyleDefault st := tcell.StyleDefault
context := dirContext{selections: nav.selections, saves: nav.saves, tags: nav.tags} context := dirContext{selections: nav.selections, clipboard: nav.clipboard, tags: nav.tags}
ui.screen.Clear() ui.screen.Clear()
@@ -1100,7 +1255,12 @@ func (ui *ui) draw(nav *nav) {
switch ui.cmdPrefix { switch ui.cmdPrefix {
case "": case "":
if gOpts.rulerfile {
ui.drawRulerFile(nav)
} else {
ui.drawStat(nav)
ui.drawRuler(nav) ui.drawRuler(nav)
}
ui.screen.HideCursor() ui.screen.HideCursor()
case ">": case ">":
maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end
@@ -1122,7 +1282,7 @@ func (ui *ui) draw(nav *nav) {
preview := ui.wins[len(ui.wins)-1] preview := ui.wins[len(ui.wins)-1]
ui.sxScreen.clearSixel(preview, ui.screen, curr.path) ui.sxScreen.clearSixel(preview, ui.screen, curr.path)
if gOpts.preview { if gOpts.preview {
if curr.Mode().IsRegular() || (curr.IsDir() && gOpts.dirpreviews) { if curr.isPreviewable() {
preview.printReg(ui.screen, ui.regPrev, nav.previewLoading, &ui.sxScreen) preview.printReg(ui.screen, ui.regPrev, nav.previewLoading, &ui.sxScreen)
} else if curr.IsDir() { } else if curr.IsDir() {
ui.sxScreen.lastFile = "" ui.sxScreen.lastFile = ""
@@ -1136,25 +1296,7 @@ func (ui *ui) draw(nav *nav) {
ui.drawBox() ui.drawBox()
} }
if ui.menu != "" { ui.drawMenu()
lines := strings.Split(ui.menu, "\n")
lines = lines[:len(lines)-1]
ui.menuWin.h = len(lines) - 1
ui.menuWin.y = ui.wins[0].h - ui.menuWin.h
if gOpts.drawbox {
ui.menuWin.y += 2
}
ui.menuWin.printLine(ui.screen, 0, 0, st.Bold(true), lines[0])
for i, line := range lines[1:] {
ui.menuWin.printLine(ui.screen, 0, i+1, st, "")
ui.menuWin.print(ui.screen, 0, i+1, st, line)
}
}
ui.screen.Show() ui.screen.Show()
} }
@@ -1177,6 +1319,7 @@ func listBinds(binds map[string]map[string]expr) string {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
// merge keys by command across modes
m := make(map[string]map[string]string) m := make(map[string]map[string]string)
for mode, keys := range binds { for mode, keys := range binds {
for key, expr := range keys { for key, expr := range keys {
@@ -1191,6 +1334,7 @@ func listBinds(binds map[string]map[string]expr) string {
mode, key, cmd string mode, key, cmd string
} }
// collect normalized entries
var entries []entry var entries []entry
for key, cmds := range m { for key, cmds := range m {
for cmd, modes := range cmds { for cmd, modes := range cmds {
@@ -1208,7 +1352,7 @@ func listBinds(binds map[string]map[string]expr) string {
}) })
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "mode\tkeys\tcommand") fmt.Fprintln(t, "mode\tkey\tcommand")
for _, e := range entries { for _, e := range entries {
fmt.Fprintf(t, "%s\t%s\t%s\n", e.mode, e.key, e.cmd) fmt.Fprintf(t, "%s\t%s\t%s\n", e.mode, e.key, e.cmd)
} }
@@ -1217,6 +1361,27 @@ func listBinds(binds map[string]map[string]expr) string {
return b.String() return b.String()
} }
func listMatchingBinds(binds map[string]expr, prefix string) string {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
keys := make([]string, 0, len(binds))
for k := range binds {
keys = append(keys, k)
}
sort.Strings(keys)
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "key\tcommand")
for _, k := range keys {
remain, _ := strings.CutPrefix(k, prefix)
fmt.Fprintf(t, "%s\t%v\n", remain, binds[k])
}
t.Flush()
return b.String()
}
func listCmds(cmds map[string]expr) string { func listCmds(cmds map[string]expr) string {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
@@ -1261,7 +1426,7 @@ func listJumps(jumps []string, ind int) string {
return b.String() return b.String()
} }
func listHistory(history []cmdItem) string { func listHistory(history []string) string {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
@@ -1270,7 +1435,7 @@ func listHistory(history []cmdItem) string {
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "number\tcommand") fmt.Fprintln(t, "number\tcommand")
for i, cmd := range history { for i, cmd := range history {
fmt.Fprintf(t, "%*d\t%s%s\n", maxlength, i+1, cmd.prefix, cmd.value) fmt.Fprintf(t, "%*d\t%s\n", maxlength, i+1, cmd)
} }
t.Flush() t.Flush()
@@ -1388,14 +1553,16 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
count := 0 count := 0
keys := gOpts.nkeys keys := gOpts.nkeys
mode := "n"
if nav.isVisualMode() { if nav.isVisualMode() {
keys = gOpts.vkeys keys = gOpts.vkeys
mode = "v"
} }
switch tev := ev.(type) { switch tev := ev.(type) {
case *tcell.EventKey: case *tcell.EventKey:
if ui.pasteEvent {
return nil
}
// KeyRune is a regular character // KeyRune is a regular character
if tev.Key() == tcell.KeyRune { if tev.Key() == tcell.KeyRune {
switch { switch {
@@ -1463,9 +1630,8 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
return expr return expr
} }
if gOpts.showbinds { if gOpts.showbinds {
ui.menu = listBinds(map[string]map[string]expr{ // mode and already typed keys are obvious here; no need to clutter the menu
mode: binds, ui.menu = listMatchingBinds(binds, string(ui.keyAcc))
})
} }
return draw return draw
} }
@@ -1575,15 +1741,20 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
} else { } else {
return &callExpr{"on-focus-lost", nil, 1} return &callExpr{"on-focus-lost", nil, 1}
} }
case *tcell.EventPaste:
if tev.Start() {
ui.pasteEvent = true
} else if tev.End() {
ui.pasteEvent = false
}
} }
return nil return nil
} }
func readCmdEvent(ev tcell.Event) expr { func readCmdEvent(ev tcell.Event) expr {
switch tev := ev.(type) { if tev, ok := ev.(*tcell.EventKey); ok {
case *tcell.EventKey:
if tev.Key() == tcell.KeyRune { if tev.Key() == tcell.KeyRune {
if tev.Modifiers() == tcell.ModMask(tcell.ModAlt) { if tev.Modifiers() == tcell.ModAlt {
val := string([]rune{'<', 'a', '-', tev.Rune(), '>'}) val := string([]rune{'<', 'a', '-', tev.Rune(), '>'})
if expr, ok := gOpts.cmdkeys[val]; ok { if expr, ok := gOpts.cmdkeys[val]; ok {
return expr return expr
@@ -1644,47 +1815,53 @@ func (ui *ui) exportSizes() {
func anyKey() { func anyKey() {
fmt.Fprint(os.Stderr, gOpts.waitmsg) fmt.Fprint(os.Stderr, gOpts.waitmsg)
defer fmt.Fprint(os.Stderr, "\n") defer fmt.Fprintln(os.Stderr)
oldState, err := term.MakeRaw(int(os.Stdin.Fd())) oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer term.Restore(int(os.Stdin.Fd()), oldState) defer func() {
if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil {
panic(err)
}
}()
b := make([]byte, 8) b := make([]byte, 8)
os.Stdin.Read(b) if _, err := os.Stdin.Read(b); err != nil {
log.Printf("Failed to read key press: %s", err)
}
} }
func listMatches(screen tcell.Screen, matches []string, selectedInd int) string { func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) (string, *menuSelect) {
mlen := len(matches) if len(matches) < 2 {
if mlen < 2 { return "", nil
return ""
} }
var b strings.Builder
wtot, _ := screen.Size() wtot, _ := screen.Size()
wcol := 0 wcol := 0
for _, m := range matches { for _, m := range matches {
wcol = max(wcol, len(m)) wcol = max(wcol, runeSliceWidth([]rune(m.name)))
} }
wcol += gOpts.tabstop - wcol%gOpts.tabstop wcol += gOpts.tabstop - wcol%gOpts.tabstop
ncol := max(wtot/wcol, 1) ncol := max(wtot/wcol, 1)
b.WriteString("possible matches\n") var b strings.Builder
b.WriteString("possible matches")
for i := 0; i < mlen; { for i, match := range matches {
for j := 0; j < ncol && i < mlen; i, j = i+1, j+1 { if i%ncol == 0 {
target := matches[i]
if selectedInd == i {
fmt.Fprintf(&b, "\033[7m%s\033[0m%*s", target, wcol-len(target), "")
} else {
fmt.Fprintf(&b, "%s%*s", target, wcol-len(target), "")
}
}
b.WriteByte('\n') b.WriteByte('\n')
} }
w := runeSliceWidth([]rune(match.name))
fmt.Fprintf(&b, "%s%*s", match.name, wcol-w, "")
}
return b.String() b.WriteByte('\n')
var selection *menuSelect
if selectedInd != -1 {
selection = &menuSelect{selectedInd % ncol * wcol, selectedInd/ncol + 1, matches[selectedInd].name}
}
return b.String(), selection
} }
+3 -1
View File
@@ -71,7 +71,9 @@ func (watch *watch) add(path string) {
// ignore /dev since write updates to /dev/tty causes high cpu usage // ignore /dev since write updates to /dev/tty causes high cpu usage
if path != "/dev" { if path != "/dev" {
watch.watcher.Add(path) if err := watch.watcher.Add(path); err != nil {
log.Printf("watch path %s: %s", path, err)
}
} }
} }