Compare commits

69 Commits
Author SHA1 Message Date
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
37 changed files with 3191 additions and 2657 deletions

No files matched your search

+6 -6
View File
@@ -14,12 +14,12 @@ jobs:
matrix:
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: "1.23"
@@ -37,12 +37,12 @@ jobs:
cross-compile:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: "1.23"
@@ -52,12 +52,12 @@ jobs:
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: "1.23"
+2 -4
View File
@@ -10,10 +10,10 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
- name: Set up Go
uses: actions/setup-go@v5
uses: actions/setup-go@v6
with:
go-version: "1.23"
@@ -24,8 +24,6 @@ jobs:
uses: softprops/action-gh-release@v2
with:
files: dist/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
winget:
runs-on: ubuntu-latest
+60
View File
@@ -8,6 +8,66 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
- `Added`
- `Fixed`
## [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)
### 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`
- Implement the option somewhere in the code
- 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
## 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
- Add command name to `gCmdWords` in `complete.go` for tab completion
- 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
## 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 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.
+74 -35
View File
@@ -31,7 +31,8 @@ type app struct {
cmdHistoryBeg int
cmdHistoryInd int
menuCompActive bool
menuComps []string
menuCompTmp []string
menuComps []compMatch
menuCompInd int
selectionOut []string
watch *watch
@@ -115,7 +116,7 @@ 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)
if os.IsNotExist(err) {
err = nil
@@ -133,16 +134,16 @@ func loadFiles() (list []string, cp bool, err error) {
switch s.Text() {
case "copy":
cp = true
clipboard.mode = clipboardCopy
case "move":
cp = false
clipboard.mode = clipboardCut
default:
err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text())
return
}
for s.Scan() && s.Text() != "" {
list = append(list, s.Text())
clipboard.paths = append(clipboard.paths, s.Text())
}
if s.Err() != nil {
@@ -150,12 +151,12 @@ func loadFiles() (list []string, cp bool, err error) {
return
}
log.Printf("loading files: %v", list)
log.Printf("loading files: %v", clipboard.paths)
return
}
func saveFiles(list []string, cp bool) error {
func saveFiles(clipboard clipboard) error {
if err := os.MkdirAll(filepath.Dir(gFilesPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
@@ -166,16 +167,16 @@ func saveFiles(list []string, cp bool) error {
}
defer files.Close()
log.Printf("saving files: %v", list)
log.Printf("saving files: %v", clipboard.paths)
if cp {
if clipboard.mode == clipboardCopy {
fmt.Fprintln(files, "copy")
} else {
fmt.Fprintln(files, "move")
}
for _, f := range list {
fmt.Fprintln(files, f)
for _, path := range clipboard.paths {
fmt.Fprintln(files, path)
}
files.Sync()
@@ -317,7 +318,7 @@ func (app *app) loop() {
for {
select {
case <-app.quitChan:
if app.nav.copyTotal > 0 {
if app.nav.copyJobs > 0 {
app.ui.echoerr("quit: copy operation in progress")
continue
}
@@ -339,6 +340,9 @@ func (app *app) loop() {
log.Print("bye!")
return
case n := <-app.nav.copyJobsChan:
app.nav.copyJobs += n
app.ui.draw(app.nav)
case n := <-app.nav.copyBytesChan:
app.nav.copyBytes += n
// n is usually 32*1024B (default io.Copy() buffer) so update roughly per 32KB x 128 = 4MB copied
@@ -350,6 +354,7 @@ func (app *app) loop() {
app.nav.copyTotal += n
if n < 0 {
app.nav.copyBytes += n
app.nav.copyJobs -= 1
}
if app.nav.copyTotal == 0 {
app.nav.copyUpdate = 0
@@ -386,19 +391,17 @@ func (app *app) loop() {
}
app.ui.draw(app.nav)
case d := <-app.nav.dirChan:
if gOpts.dircache {
prev, ok := app.nav.dirCache[d.path]
if ok {
d.ind = prev.ind
d.pos = prev.pos
d.visualAnchor = min(prev.visualAnchor, len(d.files)-1)
d.filter = prev.filter
d.sort()
d.sel(prev.name(), app.nav.height)
}
app.nav.dirCache[d.path] = d
prev, ok := app.nav.dirCache[d.path]
if ok {
d.ind = prev.ind
d.pos = prev.pos
d.visualAnchor = min(prev.visualAnchor, len(d.files)-1)
d.visualWrap = prev.visualWrap
d.filter = prev.filter
d.sort()
d.sel(prev.name(), app.nav.height)
}
app.nav.dirCache[d.path] = d
var oldCurrPath string
if curr, err := app.nav.currFile(); err == nil {
@@ -417,9 +420,6 @@ func (app *app) loop() {
if err == nil {
if curr.path != oldCurrPath {
app.ui.loadFile(app, true)
if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav)
}
}
if d.path == curr.path {
app.ui.dirPrev = d
@@ -427,7 +427,13 @@ func (app *app) loop() {
}
app.watchDir(d)
onLoad(app, d.fileNames())
paths := []string{}
for _, file := range d.allFiles {
paths = append(paths, file.path)
}
onLoad(app, paths)
app.ui.draw(app.nav)
case r := <-app.nav.regChan:
app.nav.regCache[r.path] = r
@@ -436,9 +442,7 @@ func (app *app) loop() {
if err == nil {
if r.path == curr.path {
app.ui.regPrev = r
if gOpts.sixel {
app.ui.sxScreen.forceClear = true
}
app.ui.sxScreen.forceClear = true
}
}
@@ -462,10 +466,6 @@ func (app *app) loop() {
}
app.ui.loadFile(app, false)
if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav)
}
onLoad(app, []string{f.path})
app.ui.draw(app.nav)
case path := <-app.nav.delChan:
@@ -661,6 +661,45 @@ 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
}
app.menuCompTmp[len(app.menuCompTmp)-1] = app.menuComps[app.menuCompInd].result
app.ui.cmdAccLeft = []rune(strings.Join(app.menuCompTmp, " "))
}
app.ui.menu, app.ui.menuSelect = listMatches(app.ui.screen, app.menuComps, app.menuCompInd)
}
func (app *app) watchDir(dir *dir) {
if !gOpts.watch {
return
+11 -2
View File
@@ -49,6 +49,7 @@ func run() {
if gOpts.mouse {
screen.EnableMouse()
}
screen.EnablePaste()
ui := newUI(screen)
nav := newNav(ui.wins[0].h)
@@ -181,9 +182,17 @@ func remote(cmd string) error {
v.CloseWrite()
}
io.Copy(os.Stdout, c)
// The most straightforward way to write the reponse 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()
os.Stdout.Write(response)
return nil
}
+12 -10
View File
@@ -88,14 +88,6 @@ func parseStyles() styleMap {
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) {
if len(toks) == 0 {
return tcell.ColorDefault, 0, fmt.Errorf("invalid args: %v", toks)
@@ -136,8 +128,6 @@ 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:
@@ -173,6 +163,18 @@ loop:
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))
+7
View File
@@ -72,6 +72,13 @@ func TestApplyAnsiCodes(t *testing.T) {
{"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)},
+318 -266
View File
@@ -2,9 +2,11 @@ package main
import (
"log"
"maps"
"os"
"path/filepath"
"reflect"
"slices"
"sort"
"strings"
)
@@ -18,104 +20,104 @@ var (
"vmap",
"cmap",
"cmd",
"quit",
"up",
"half-up",
"page-up",
"scroll-up",
"down",
"half-down",
"page-down",
"scroll-down",
"updir",
"open",
"jump-next",
"jump-prev",
"top",
"addcustominfo",
"bottom",
"high",
"middle",
"low",
"toggle",
"invert",
"unselect",
"glob-select",
"glob-unselect",
"calcdirsize",
"cd",
"clear",
"clearmaps",
"copy",
"cut",
"paste",
"clear",
"sync",
"draw",
"redraw",
"load",
"reload",
"echo",
"echomsg",
"echoerr",
"cd",
"select",
"down",
"delete",
"rename",
"source",
"push",
"read",
"shell",
"shell-pipe",
"shell-wait",
"shell-async",
"draw",
"echo",
"echoerr",
"echomsg",
"filter",
"find",
"find-back",
"find-next",
"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-back",
"search-next",
"search-prev",
"filter",
"select",
"setfilter",
"mark-save",
"mark-load",
"mark-remove",
"shell",
"shell-async",
"shell-pipe",
"shell-wait",
"source",
"sync",
"tag",
"tag-toggle",
"addcustominfo",
"toggle",
"top",
"tty-write",
"cmd-escape",
"cmd-complete",
"cmd-menu-complete",
"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",
"unselect",
"up",
"updir",
"visual",
"visual-accept",
"visual-unselect",
"visual-discard",
"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-right",
"cmd-transpose",
"cmd-transpose-word",
"cmd-uppercase-word",
"cmd-word",
"cmd-word-back",
"cmd-yank",
}
gOptWords = getOptWords(gOpts)
@@ -158,50 +160,164 @@ func getLocalOptWords(localOpts any) (localOptWords []string) {
return
}
func matchLongest(s1, s2 []rune) []rune {
func commonPrefix(s1, s2 string) string {
r1 := []rune(s1)
r2 := []rune(s2)
i := 0
for ; i < len(s1) && i < len(s2); i++ {
if s1[i] != s2[i] {
for ; i < len(r1) && i < len(r2); i++ {
if r1[i] != r2[i] {
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 {
if !strings.HasPrefix(w, s) {
continue
}
matches = append(matches, w)
if len(longest) != 0 {
longest = matchLongest(longest, []rune(w))
} else if s != "" {
longest = []rune(w + " ")
matches = append(matches, compMatch{w, w})
if len(matches) == 1 {
result = w
} else {
result = commonPrefix(result, w)
}
}
if len(longest) == 0 {
longest = []rune(s)
switch len(matches) {
case 0:
result = s
case 1:
result += " "
}
return
}
func matchExec(s string) (matches []string, longest []rune) {
var words []string
func matchList(s string, words []string) (matches []compMatch, result string) {
toks := strings.Split(s, ":")
paths := strings.Split(envPath, string(filepath.ListSeparator))
for _, p := range paths {
if _, err := os.Stat(p); os.IsNotExist(err) {
for _, w := range words {
if slices.Contains(toks[:len(toks)-1], w) || !strings.HasPrefix(w, toks[len(toks)-1]) {
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 := append(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 matchExec(s string) (matches []compMatch, result string) {
var words []string
for _, p := range strings.Split(envPath, string(filepath.ListSeparator)) {
files, err := os.ReadDir(p)
if err != nil {
log.Printf("reading path: %s", err)
if !os.IsNotExist(err) {
log.Printf("reading path: %s", err)
}
continue
}
for _, f := range files {
@@ -215,170 +331,23 @@ func matchExec(s string) (matches []string, longest []rune) {
continue
}
if !finfo.Mode().IsRegular() || !isExecutable(finfo) {
continue
if finfo.Mode().IsRegular() && isExecutable(finfo) {
words = append(words, f.Name())
}
words = append(words, finfo.Name())
}
}
if len(words) > 0 {
sort.Strings(words)
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)
slices.Sort(words)
matches, result = matchWord(s, slices.Compact(words))
return
}
func matchFile(s string) (matches []string, longest []rune) {
dir := replaceTilde(s)
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 {
log.Printf("reading directory: %s", err)
}
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
}
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)
func matchSearch(s string) (matches []compMatch, result string) {
files, err := os.ReadDir(".")
if err != nil {
log.Printf("reading directory: %s", err)
result = s
return
}
for _, f := range files {
@@ -386,35 +355,118 @@ func completeFile(acc []rune) (matches []string, longestAcc []rune) {
continue
}
matches = append(matches, f.Name())
if longestAcc == nil {
longestAcc = []rune(f.Name())
matches = append(matches, compMatch{f.Name(), f.Name()})
if len(matches) == 1 {
result = f.Name()
} else {
longestAcc = matchLongest(longestAcc, []rune(f.Name()))
result = commonPrefix(strings.ToLower(result), strings.ToLower(f.Name()))
}
}
if len(longestAcc) < len(acc) {
longestAcc = acc
if len(matches) == 0 {
result = s
}
return
}
func completeShell(acc []rune) (matches []string, longestAcc []rune) {
func completeCmd(acc []rune) (matches []compMatch, result string) {
s := string(acc)
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 "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) == 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 "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) {
case 1:
matches, longestAcc = matchExec(s)
matches, result = matchExec(f[0])
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
matches, result = matchShellFile(f[len(f)-1])
}
f[len(f)-1] = result
result = strings.Join(f, " ")
return
}
func completeSearch(acc []rune) (matches []compMatch, result string) {
matches, result = matchSearch(string(acc))
return
}
+86 -50
View File
@@ -5,56 +5,6 @@ import (
"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) {
tests := []struct {
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)
}
}
}
+1 -1
View File
@@ -132,7 +132,7 @@ func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64,
newPath := filepath.Join(dst, rel)
switch {
case info.IsDir():
var dst_mode os.FileMode = os.ModePerm
var dst_mode = os.ModePerm
if slices.Contains(preserve, "mode") {
dst_mode = info.Mode()
}
+1 -1
View File
@@ -15,5 +15,5 @@ func diskFree(wd string) string {
}
// 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
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
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)
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.ignoredia = ignorediacritics
gOpts.smartdia = smartdiacritics
matched, _ := searchMatch(base, pattern, false)
matched, _ := searchMatch(base, pattern, textSearch)
if matched != expected {
t.Errorf("False search for ignorecase = %t, smartcase = %t, ignoredia = %t, smartdia = %t",
gOpts.ignorecase,
+272 -183
View File
@@ -10,7 +10,7 @@ lf - terminal file manager
[**-cpuprofile** *path*]
[**-doc**]
[**-last-dir-path** *path*]
[**-log path**]
[**-log** *path*]
[**-memprofile** *path*]
[**-print-last-dir**]
[**-print-selection**]
@@ -29,7 +29,7 @@ lf is a terminal file manager.
The source code can be found in the repository at https://github.com/gokcehan/lf
This documentation can either be read from the terminal using `lf -doc` or online at https://github.com/gokcehan/lf/blob/master/doc.md
You can also use the `doc` command (default `<f-1>`) inside lf to view the documentation in a pager.
You can also use the `help` command (default `<f-1>`) inside lf to view the documentation in a pager.
A man page with the same content is also available in the repository at https://github.com/gokcehan/lf/blob/master/lf.1
You can run `lf -help` to see descriptions of command line options.
@@ -57,13 +57,10 @@ The following commands are provided by lf:
middle (default 'M')
low (default 'L')
toggle
visual (default 'V')
invert (default 'v')
unselect (default 'u')
glob-select
glob-unselect
calcdirsize
clearmaps
copy (default 'y')
cut (default 'd')
paste (default 'p')
@@ -73,15 +70,8 @@ The following commands are provided by lf:
redraw (default '<c-l>')
load
reload (default '<c-r>')
echo
echomsg
echoerr
cd
select
delete (modal)
rename (modal) (default 'r')
source
push
read (modal) (default ':')
shell (modal) (default '$')
shell-pipe (modal) (default '%')
@@ -102,8 +92,18 @@ The following commands are provided by lf:
mark-remove (modal) (default '"')
tag
tag-toggle (default 't')
echo
echomsg
echoerr
cd
select
source
push
addcustominfo
calcdirsize
clearmaps
tty-write
visual (default 'V')
The following Visual mode commands are provided by lf:
@@ -114,6 +114,7 @@ The following Visual mode commands are provided by lf:
The following Command-line mode commands are provided by lf:
cmd-insert
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-menu-complete
@@ -154,7 +155,6 @@ The following options can be used to customize the behavior of lf:
cursorparentfmt string (default "\033[7m")
cursorpreviewfmt string (default "\033[4m")
cutfmt string (default "\033[7;31m")
dircache bool (default true)
dircounts bool (default false)
dirfirst bool (default true)
dironly bool (default false)
@@ -163,9 +163,8 @@ The following options can be used to customize the behavior of lf:
dupfilefmt string (default '%f.~%n~')
errorfmt string (default "\033[7;31;47m")
filesep string (default "\n")
filtermethod string (default 'text')
findlen int (default 1)
globfilter bool (default false)
globsearch bool (default false)
hidden bool (default false)
hiddenfiles []string (default '.*' for Unix and '' for Windows)
history bool (default true)
@@ -178,7 +177,9 @@ The following options can be used to customize the behavior of lf:
info []string (default '')
infotimefmtnew string (default 'Jan _2 15:04')
infotimefmtold string (default 'Jan _2 2006')
locale string (default '')
menufmt string (default "\033[0m")
menuheaderfmt string (default "\033[1m")
menuselectfmt string (default "\033[7m")
mouse bool (default false)
number bool (default false)
numberfmt string (default "\033[33m")
@@ -193,13 +194,14 @@ The following options can be used to customize the behavior of lf:
roundbox bool (default false)
rulerfmt string (default " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;34m %f \033[0m| %i/%t")
scrolloff int (default 0)
searchmethod string (default 'text')
selectfmt string (default "\033[7;35m")
selmode string (default 'all')
shell string (default 'sh' for Unix and 'cmd' for Windows)
shellflag string (default '-c' for Unix and '/c' for Windows)
shellopts []string (default '')
showbinds bool (default true)
sixel bool (default false)
sizeunits string (default 'binary')
smartcase bool (default true)
smartdia bool (default false)
sortby string (default 'natural')
@@ -235,6 +237,7 @@ The following environment variables are exported for shell commands:
lf
lf_{option}
lf_user_{option}
lf_flag_{flag}
lf_width
lf_height
lf_count
@@ -263,8 +266,8 @@ The following commands/keybindings are provided by default:
map e $$EDITOR "$f"
map i $$PAGER "$f"
map w $$SHELL
cmd doc $$lf -doc | $PAGER
map <f-1> doc
cmd help $$lf -doc | $PAGER
map <f-1> help
cmd maps $lf -remote "query $id maps" | $PAGER
cmd nmaps $lf -remote "query $id nmaps" | $PAGER
cmd vmaps $lf -remote "query $id vmaps" | $PAGER
@@ -276,14 +279,18 @@ The following commands/keybindings are provided by default:
map e $%EDITOR% %f%
map i !%PAGER% %f%
map w $%SHELL%
cmd doc !%lf% -doc | %PAGER%
map <f-1> doc
cmd help !%lf% -doc | %PAGER%
map <f-1> help
cmd maps !%lf% -remote "query %id% maps" | %PAGER%
cmd nmaps !%lf% -remote "query %id% nmaps" | %PAGER%
cmd vmaps !%lf% -remote "query %id% vmaps" | %PAGER%
cmd cmaps !%lf% -remote "query %id% cmaps" | %PAGER%
cmd cmds !%lf% -remote "query %id% cmds" | %PAGER%
The defaults for Windows are using `cmd` syntax.
A `PowerShell` compatible configuration file can be found at
https://github.com/gokcehan/lf/blob/master/etc/lfrc.ps1.example
The following additional keybindings are provided by default:
map zh set hidden!
@@ -296,6 +303,7 @@ The following additional keybindings are provided by default:
map ss :set sortby size; set info size
map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sb :set sortby btime; set info btime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~
@@ -307,7 +315,7 @@ If the `mouse` option is enabled, mouse buttons have the following default effec
Click on a file or directory to select it.
Right mouse button
Enter a directory or open a file. Also works on the preview window.
Enter a directory or open a file. Also works on the preview pane.
Scroll wheel
Move up or down. If Ctrl is pressed, scroll up or down.
@@ -318,19 +326,19 @@ Configuration files should be located at:
OS system-wide user-specific
Unix /etc/lf/lfrc ~/.config/lf/lfrc
Windows C:\ProgramData\lf\lfrc C:\Users\<user>\AppData\Local\lf\lfrc
Windows C:\ProgramData\lf\lfrc C:\Users\<user>\AppData\Roaming\lf\lfrc
The colors file should be located at:
OS system-wide user-specific
Unix /etc/lf/colors ~/.config/lf/colors
Windows C:\ProgramData\lf\colors C:\Users\<user>\AppData\Local\lf\colors
Windows C:\ProgramData\lf\colors C:\Users\<user>\AppData\Roaming\lf\colors
The icons file should be located at:
OS system-wide user-specific
Unix /etc/lf/icons ~/.config/lf/icons
Windows C:\ProgramData\lf\icons C:\Users\<user>\AppData\Local\lf\icons
Windows C:\ProgramData\lf\icons C:\Users\<user>\AppData\Roaming\lf\icons
The selection file should be located at:
@@ -364,12 +372,13 @@ You can configure these locations with the following variables given with their
~/.local/share
Windows
%ProgramData%
C:\ProgramData
%LF_CONFIG_HOME%
%XDG_CONFIG_HOME%
%APPDATA%
%LF_DATA_HOME%
%XDG_DATA_HOME%
%LOCALAPPDATA%
C:\Users\<user>\AppData\Local
A sample configuration file can be found at
https://github.com/gokcehan/lf/blob/master/etc/lfrc.example
@@ -414,27 +423,6 @@ Move the current file selection to the high/middle/low of the screen.
Toggle the selection of the current file or files given as arguments.
## visual (default `V`)
Switch to Visual mode.
If already in Visual mode, discard the visual selection and stay in Visual mode.
## visual-accept (default `V`)
Add the visual selection to the selection list, quit Visual mode and return to Normal mode.
## visual-unselect
Remove the visual selection from the selection list, quit Visual mode and return to Normal mode.
## visual-discard (default `<esc>`)
Discard the visual selection, quit Visual mode and return to Normal mode.
## visual-change (default `o`)
Go to the other end of the current Visual mode selection.
## invert (default `v`)
Reverse the selection of all files in the current directory (i.e. `toggle` all files).
@@ -449,34 +437,24 @@ Remove the selection of all files in all directories.
Select/unselect files that match the given glob.
## calcdirsize
Calculate the total size for each of the selected directories.
Option `info` should include `size` and option `dircounts` should be disabled to show this size.
If the total size of a directory is not calculated, it will be shown as `-`.
## clearmaps
Remove all keybindings associated with the `map`, `nmap` and `vmap` command.
This command can be used in the config file to remove the default keybindings.
For safety purposes, `:` is left mapped to the `read` command, and `cmap` keybindings are retained so that it is still possible to exit `lf` using `:quit`.
## copy (default `y`)
If there are no selections, save the path of the current file to the copy buffer, otherwise, copy the paths of selected files.
Save the paths of selected files to the clipboard as files to be copied.
If there are no selected files, the path of the current file is used instead.
## cut (default `d`)
If there are no selections, save the path of the current file to the cut buffer, otherwise, copy the paths of selected files.
Save the paths of selected files to the clipboard as files to be moved.
If there are no selected files, the path of the current file is used instead.
## paste (default `p`)
Copy/Move files in the copy/cut buffer to the current working directory.
Copy/Move files in the clipboard to the current working directory.
A custom `paste` command can be defined to override this default.
## clear (default `c`)
Clear file paths in copy/cut buffer.
Clear file paths in the clipboard.
## sync
@@ -501,26 +479,6 @@ This command is automatically called when required.
Flush the cache and reload all files and directories.
## echo
Print the given arguments to the message line at the bottom.
## echomsg
Print the given arguments to the message line at the bottom and also to the log file.
## echoerr
Print given arguments to the message line at the bottom as `errorfmt` and also to the log file.
## cd
Change the working directory to the given argument.
## select
Change the current file selection to the given argument.
## delete (modal)
Remove the current file or selected file(s).
@@ -531,14 +489,6 @@ A custom `delete` command can be defined to override this default.
Rename the current file using the built-in method.
A custom `rename` command can be defined to override this default.
## source
Read the configuration file given in the argument.
## push
Simulate key pushes given in the argument.
## read (modal) (default `:`)
Read a command to evaluate.
@@ -553,7 +503,7 @@ Read a shell command to execute piping its standard I/O to the bottom statline.
## shell-wait (modal) (default `!`)
Read a shell command to execute and wait for a key press in the end.
Read a shell command to execute and wait for a key press at the end.
## shell-async (modal) (default `&`)
@@ -561,11 +511,11 @@ Read a shell command to execute asynchronously without standard I/O.
## find (modal) (default `f`), find-back (modal) (default `F`), find-next (default `;`), find-prev (default `,`)
Read key(s) to find the appropriate file name match in the forward/backward direction and jump to the next/previous match.
Read key(s) to find the appropriate filename match in the forward/backward direction and jump to the next/previous match.
## search (default `/`), search-back (default `?`), search-next (default `n`), search-prev (default `N`)
Read a pattern to search for a file name match in the forward/backward direction and jump to the next/previous match.
Read a pattern to search for a filename match in the forward/backward direction and jump to the next/previous match.
## filter (modal), setfilter
@@ -593,7 +543,35 @@ You can define a new tag-clearing command by combining `tag` with `tag-toggle` (
## tag-toggle (default `t`)
Tag a file with `*` or a single width character given in the argument if the file is untagged, otherwise remove the tag.
Tag a file with `*` or a single-width character given in the argument if the file is untagged, otherwise remove the tag.
## echo
Print the given arguments to the message line at the bottom.
## echomsg
Print the given arguments to the message line at the bottom and also to the log file.
## echoerr
Print given arguments to the message line at the bottom as `errorfmt` and also to the log file.
## cd
Change the working directory to the given argument.
## select
Change the current file selection to the given argument.
## source
Read the configuration file given in the argument.
## push
Simulate key pushes given in the argument.
## addcustominfo
@@ -601,13 +579,48 @@ Update the `custom` info field of the given file with the given string.
The info string may contain ANSI escape codes to further customize its appearance.
If no info is provided, clear the file's info instead.
## calcdirsize
Calculate the total size for each of the selected directories.
Option `info` should include `size` and option `dircounts` should be disabled to show this size.
If the total size of a directory is not calculated, it will be shown as `-`.
## clearmaps
Remove all keybindings associated with the `map`, `nmap` and `vmap` command.
This command can be used in the config file to remove the default keybindings.
For safety purposes, `:` is left mapped to the `read` command, and `cmap` keybindings are retained so that it is still possible to exit `lf` using `:quit`.
## tty-write
Write the given string to the tty.
This is useful for sending escape sequences to the terminal to control its behavior (e.g. OSC 0 to set the window title).
Using `tty-write` is preferred over directly writing to `/dev/tty` because the latter is not synchronized and can interfere with drawing the UI.
# COMMAND LINE COMMANDS
## visual (default `V`)
Switch to Visual mode.
If already in Visual mode, discard the visual selection and stay in Visual mode.
# VISUAL MODE COMMANDS
## visual-accept (default `V`)
Add the visual selection to the selection list, quit Visual mode and return to Normal mode.
## visual-unselect
Remove the visual selection from the selection list, quit Visual mode and return to Normal mode.
## visual-discard (default `<esc>`)
Discard the visual selection, quit Visual mode and return to Normal mode.
## visual-change (default `o`)
Go to the other end of the current Visual mode selection.
# COMMAND-LINE MODE COMMANDS
The prompt character specifies which of the several Command-line modes you are in.
For example, the `read` command takes you to the `:` mode.
@@ -616,7 +629,12 @@ When the cursor is at the first character in `:` mode, pressing one of the keys
You can go back with `cmd-delete-back` (`<backspace>` by default).
The command line commands should be mostly compatible with readline keybindings.
A character refers to a Unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters.
A character refers to a Unicode code point, a word consists of letters and digits, and a Unix word consists of any non-blank characters.
## cmd-insert
Insert the character given in the argument.
This command is automatically called when required.
## cmd-escape (default `<esc>`)
@@ -671,7 +689,7 @@ Delete everything up to the beginning/end of the line.
## cmd-delete-unix-word (default `<c-w>`)
Delete the previous unix word.
Delete the previous Unix word.
## cmd-yank (default `<c-y>`)
@@ -704,7 +722,7 @@ Character `:` is used as the separator for list options `[]int` and `[]string`.
## anchorfind (bool) (default true)
When this option is enabled, the find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position.
When this option is enabled, the find command starts matching patterns from the beginning of filenames, otherwise, it can match at an arbitrary position.
## autoquit (bool) (default true)
@@ -719,14 +737,14 @@ Format string of the box drawing characters enabled by the `drawbox` option.
Set the path of a cleaner file.
The file should be executable.
This file is called if previewing is enabled, the previewer is set, and the previously selected file has its preview cache disabled.
The following arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, (5) vertical position of preview pane and (6) next file name to be previewed respectively.
The following arguments are passed to the file, (1) current filename, (2) width, (3) height, (4) horizontal position, (5) vertical position of preview pane and (6) next filename to be previewed respectively.
Preview cleaning is disabled when the value of this option is left empty.
## copyfmt (string) (default `\033[7;33m`)
Format string of the indicator for files to be copied.
## cursoractivefmt (string) (default `\033[7m`), cursorparentfmt string (default `\033[7m`), cursorpreviewfmt string (default `\033[4m`)
## cursoractivefmt (string) (default `\033[7m`), cursorparentfmt (string) (default `\033[7m`), cursorpreviewfmt (string) (default `\033[4m`)
Format strings for highlighting the cursor.
`cursoractivefmt` applies in the current directory pane,
@@ -744,10 +762,6 @@ For example, `\033[4m%s\033[0m` has the same effect as `\033[4m`.
Format string of the indicator for files to be cut.
## dircache (bool) (default true)
Cache directory contents.
## dircounts (bool) (default false)
When this option is enabled, directory sizes show the number of items inside instead of the total size of the directory, which needs to be calculated for each directory using `calcdirsize`.
@@ -759,6 +773,7 @@ This option only has an effect when `info` has a `size` field and the pane is wi
## dirfirst (bool) (default true)
Show directories first above regular files.
With `dircounts` enabled, sorting by `size` always separates directories and files, regardless of `dirfirst`.
## dironly (bool) (default false)
@@ -774,8 +789,8 @@ Draw boxes around panes with box drawing characters.
## dupfilefmt (string) (default `%f.~%n~`)
Format string of file name when creating duplicate files. With the default format, copying a file `abc.txt` to the same directory will result in a duplicate file called `abc.txt.~1~`.
Special expansions are provided, `%f` as the file name, `%b` for the basename (file name without extension), `%e` as the extension (including the dot) and `%n` as the number of duplicates.
Format string of filename when creating duplicate files. With the default format, copying a file `abc.txt` to the same directory will result in a duplicate file called `abc.txt.~1~`.
Special expansions are provided, `%f` as the file name, `%b` for the base name (file name without extension), `%e` as the extension (including the dot) and `%n` as the number of duplicates.
## errorfmt (string) (default `\033[7;31;47m`)
@@ -788,21 +803,17 @@ For example, `\033[4m%s\033[0m` has the same effect as `\033[4m`.
File separator used in environment variables `fs`, `fv` and `fx`.
## filtermethod (string) (default `text`)
How filter command patterns are treated.
Currently supported methods are `text` (i.e. string literals), `glob` (i.e. shell globs) and `regex` (i.e. regular expressions).
See `SEARCHING FILES` for more details.
## findlen (int) (default 1)
Number of characters prompted for the find command.
When this value is set to 0, find command prompts until there is only a single match left.
## globfilter (bool) (default false)
Patterns are treated as globs for the filter command, see `globsearch` for more details.
## globsearch (bool) (default false)
When this option is enabled, search command patterns are considered as globs, otherwise, they are literals.
With globbing, `*` matches any sequence, `?` matches any character, and `[...]` or `[^...]` matches character sets or ranges.
Otherwise, these characters are interpreted as they are.
## hidden (bool) (default false)
Show hidden files.
@@ -841,19 +852,30 @@ Ignore case in sorting and search patterns.
Ignore diacritics in sorting and search patterns.
## incsearch (bool) (default false)
Jump to the first match after each keystroke during searching.
## incfilter (bool) (default false)
Apply filter pattern after each keystroke during filtering.
## incsearch (bool) (default false)
Jump to the first match after each keystroke during searching.
## info ([]string) (default ``)
A list of information that is shown for directory items at the right side of the pane.
Currently supported information types are `size`, `time`, `atime`, `ctime`, `perm`, `user`, `group` and `custom`.
The `custom` type is empty by default and can be updated using the `addcustominfo` command.
The following information types are supported:
perm file permission
user user name
group group name
size file size
time time of last data modification
atime time of last access
btime time of file birth
ctime time of last status (inode) change
custom property defined via `addcustominfo` (empty by default)
Information is only shown when the pane width is more than twice the width of information.
## infotimefmtnew (string) (default `Jan _2 15:04`)
@@ -864,11 +886,17 @@ Format string of the file time shown in the info column when it matches this yea
Format string of the file time shown in the info column when it doesn't match this year.
## locale (string) (default ``)
## menufmt (string) (default `\033[0m`)
An IETF BCP 47 language tag (e.g. `zh-CN`) for specifying the locale used when using sort type `natural` and `name`.
An empty string means disable locale ordering, and the special value `*` is used to indicate reading the locale setting from the system environment.
This feature is currently experimental.
Format string of the menu.
## menuheaderfmt (string) (default `\033[1m`)
Format string of the header row in the menu.
## menuselectfmt (string) (default `\033[7m`)
Format string of the currently selected item in the menu.
## mouse (bool) (default false)
@@ -894,7 +922,7 @@ Periodic checks are disabled when the value of this option is set to zero.
## preserve ([]string) (default `mode`)
List of attributes that are preserved when copying files.
Currently supported attributes are `mode` (i.a. access mode) and `timestamps` (i.e. modification time and access time).
Currently supported attributes are `mode` (i.e. access mode) and `timestamps` (i.e. modification time and access time).
Note that preserving other attributes like ownership of change/birth timestamp is desirable, but not portably supported in Go.
## preview (bool) (default true)
@@ -907,7 +935,7 @@ Files containing the null character (U+0000) in the read portion are considered
Set the path of a previewer file to filter the content of regular files for previewing.
The file should be executable.
The following arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively.
The following arguments are passed to the file, (1) current filename, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively.
SIGPIPE signal is sent when enough lines are read.
If the previewer returns a non-zero exit code, then the preview cache for the given file is disabled.
This means that if the file is selected in the future, the previewer is called once again.
@@ -916,7 +944,17 @@ Preview filtering is disabled and files are displayed as they are when the value
## promptfmt (string) (default `\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m`)
Format string of the prompt shown in the top line.
Special expansions are provided, `%u` as the user name, `%h` as the hostname, `%w` as the working directory, `%d` as the working directory with a trailing path separator, `%f` as the file name, and `%F` as the current filter. `%S` may be used once and will provide a spacer so that the following parts are right aligned on the screen.
The following special expansions are supported:
%f file name
%h host name
%u user name
%w working directory
%d working directory (with trailing path separator)
%F current filter
%S spacer to right-align the following parts (can be used once)
The home folder is shown as `~` in the working directory expansion.
Directory names are automatically shortened to a single character starting from the leftmost parent when the prompt does not fit the screen.
@@ -942,11 +980,38 @@ Draw rounded outer corners when the `drawbox` option is enabled.
## rulerfmt (string) (default ` %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;36m %v \033[0m| \033[7;34m %f \033[0m| %i/%t`)
Format string of the ruler shown in the bottom right corner.
Special expansions are provided, `%a` as the pressed keys, `%p` as the progress of file operations, `%m` as the number of files to be cut (moved), `%c` as the number of files to be copied, `%s` as the number of selected files, `%v` as the number of visually selected files, `%f` as the filter, `%i` as the position of the cursor, `%t` as the number of files shown in the current directory, `%h` as the number of files hidden in the current directory, `%P` as the scroll percentage, and `%d` as the amount of free disk space remaining.
The following special expansions are supported:
%a pressed keys
%p progress of file operations
%m number of files to be cut (moved)
%c number of files to be copied
%s number of selected files
%v number of visually selected files
%t number of shown files in the current directory
%h number of hidden files in the current directory
%f current filter
%i cursor position
%P scroll percentage
%d amount of free disk space
Additional expansions are provided for environment variables exported by lf, in the form `%{lf_<name>}` (e.g. `%{lf_selmode}`). This is useful for displaying the current settings.
Expansions are also provided for user-defined options, in the form `%{lf_user_<name>}` (e.g. `%{lf_user_foo}`).
The `|` character splits the format string into sections. Any section containing a failed expansion (result is a blank string) is discarded and not shown.
## scrolloff (int) (default 0)
Minimum number of offset lines shown at all times at the top and bottom of the screen when scrolling.
The current line is kept in the middle when this option is set to a large value that is bigger than half the number of lines.
A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items.
## searchmethod (string) (default `text`)
How search command patterns are treated.
Currently supported methods are `text` (i.e. string literals), `glob` (i.e. shell globs) and `regex` (i.e. regular expressions).
See `SEARCHING FILES` for more details.
## selectfmt (string) (default `\033[7;35m`)
Format string of the indicator for files that are selected.
@@ -957,12 +1022,6 @@ Selection mode for commands.
When set to `all` it will use the selected files from all directories.
When set to `dir` it will only use the selected files in the current directory.
## scrolloff (int) (default 0)
Minimum number of offset lines shown at all times at the top and bottom of the screen when scrolling.
The current line is kept in the middle when this option is set to a large value that is bigger than the half of number of lines.
A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items.
## shell (string) (default `sh` for Unix and `cmd` for Windows)
Shell executable to use for shell commands.
@@ -980,9 +1039,9 @@ List of shell options to pass to the shell executable.
Show bindings associated with pressed keys.
## sixel (bool) (default false)
## sizeunits (string) (default `binary`)
Render sixel images in preview.
Determines whether file sizes are displayed using binary units (`1K` is 1024 bytes) or decimal units (`1K` is 1000 bytes).
## smartcase (bool) (default true)
@@ -997,12 +1056,36 @@ This option has no effect when `ignoredia` is disabled.
## sortby (string) (default `natural`)
Sort type for directories.
Currently supported sort types are `natural`, `name`, `size`, `time`, `ctime`, `atime`, `ext` and `custom`.
The following sort types are supported:
natural file name (track_2.flac comes before track_10.flac)
name file name (track_10.flac comes before track_2.flac)
ext file extension
size file size
time time of last data modification
atime time of last access
btime time of file birth
ctime time of last status (inode) change
custom property defined via `addcustominfo` (empty by default)
## statfmt (string) (default `\033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l`)
Format string of the file info shown in the bottom left corner.
Special expansions are provided, `%p` as the file permissions, `%c` as the link count, `%u` as the user, `%g` as the group, `%s` as the file size, `%S` as the file size but with a fixed width of four characters (left-padded with spaces), `%t` as the last modified time, `%l` as the link target, `%m` as the current mode and `%M` as the current mode but also shown in Normal mode (displaying `NORMAL` instead of a blank string).
The following special expansions are supported:
%p file permission
%c link count
%u user name
%g group name
%s file size
%S file size (left-padded with spaces to a fixed width of 5 characters)
%t time of last data modification
%l link target
%m current mode
%M current mode (displaying `NORMAL` instead of a blank string in Normal mode)
The `|` character splits the format string into sections. Any section containing a failed expansion (result is a blank string) is discarded and not shown.
## tabstop (int) (default 8)
@@ -1028,7 +1111,7 @@ Format string of the file modification time shown in the bottom line.
## truncatechar (string) (default `~`)
The truncate character that is shown at the end when the file name does not fit into the pane.
The truncate character that is shown at the end when the filename does not fit into the pane.
## truncatepct (int) (default 100)
@@ -1115,7 +1198,7 @@ For example, with POSIX shells, you can use `[ -n "$LF_LEVEL" ] && PS1="$PS1""(l
## OPENER
If this variable is set in the environment, use the same value. Otherwise, this is set to `start` in Windows, `open` in MacOS, `xdg-open` in others.
If this variable is set in the environment, use the same value. Otherwise, this is set to `start` in Windows, `open` in macOS, `xdg-open` in others.
## EDITOR
@@ -1141,6 +1224,10 @@ Value of the {option}.
Value of the user_{option}.
## lf_flag_{flag}
Value of the command line {flag}.
## lf_width, lf_height
Width/Height of the terminal.
@@ -1216,7 +1303,7 @@ This shell command can be defined to be executed before quitting.
The following command prefixes are used by lf:
: read (default) builtin/custom command
: read (default) built-in/custom command
$ shell shell command
% shell-pipe shell command running with the UI
! shell-wait shell command waiting for a key press
@@ -1244,12 +1331,12 @@ Command `set` is used to set an option which can be a boolean, integer, or strin
set hidden false # boolean disable
set hidden! # boolean toggle
set scrolloff 10 # integer value
set sortby time # string value w/o quotes
set sortby 'time' # string value with single quotes (whitespaces)
set sortby time # string value without quotes
set sortby 'time' # string value with single quotes (whitespace)
set sortby "time" # string value with double quotes (backslash escapes)
Command `setlocal` is used to set a local option for a directory which can be a boolean or string.
Currently supported local options are `dircounts`, `dirfirst`, `dironly`, `hidden`, `info`, `reverse`, `sortby` and `locale`.
Currently supported local options are `dircounts`, `dirfirst`, `dironly`, `hidden`, `info`, `reverse` and `sortby`.
Adding a trailing path separator (i.e. `/` for Unix and `\` for Windows) sets the option for the given directory along with its subdirectories:
setlocal /foo/bar hidden # boolean enable
@@ -1257,15 +1344,15 @@ Adding a trailing path separator (i.e. `/` for Unix and `\` for Windows) sets th
setlocal /foo/bar nohidden # boolean disable
setlocal /foo/bar hidden false # boolean disable
setlocal /foo/bar hidden! # boolean toggle
setlocal /foo/bar sortby time # string value w/o quotes
setlocal /foo/bar sortby 'time' # string value with single quotes (whitespaces)
setlocal /foo/bar sortby time # string value without quotes
setlocal /foo/bar sortby 'time' # string value with single quotes (whitespace)
setlocal /foo/bar sortby "time" # string value with double quotes (backslash escapes)
setlocal /foo/bar hidden # for only '/foo/bar' directory
setlocal /foo/bar/ hidden # for '/foo/bar' and its subdirectories (e.g. '/foo/bar/baz')
Command `map` is used to bind a key in Normal and Visual mode to a command which can be a builtin command, custom command, or shell command:
Command `map` is used to bind a key in Normal and Visual mode to a command which can be a built-in command, custom command, or shell command:
map gh cd ~ # builtin command
map gh cd ~ # built-in command
map D trash # custom command
map i $less $f # shell command
map U !du -csh * # waiting shell command
@@ -1288,9 +1375,9 @@ Command `cmap` is used to bind a key on the command line to a command line comma
You can delete an existing binding by leaving the expression empty:
map gh # deletes 'gh' mapping in normal and visual mode
nmap v # deletes 'v' mapping in normal mode
vmap o # deletes 'o' mapping in visual mode
map gh # deletes 'gh' mapping in Normal and Visual mode
nmap v # deletes 'v' mapping in Normal mode
vmap o # deletes 'o' mapping in Visual mode
cmap <c-g> # deletes '<c-g>' mapping
Command `cmd` is used to define a custom command:
@@ -1322,7 +1409,7 @@ Regular keys are assigned to a command with the usual syntax:
map a down
Keys combined with the shift key simply use the uppercase letter:
Keys combined with the Shift key simply use the uppercase letter:
map A down
@@ -1339,19 +1426,19 @@ Function keys are prefixed with `f` character:
map <f-1> down
Keys combined with the control key are prefixed with a `c` character:
Keys combined with the Ctrl key are prefixed with a `c` character:
map <c-a> down
Keys combined with the alt key are assigned in two different ways depending on the behavior of your terminal.
Older terminals (e.g. xterm) may set the 8th bit of a character when the alt key is pressed.
Keys combined with the Alt key are assigned in two different ways depending on the behavior of your terminal.
Older terminals (e.g. xterm) may set the 8th bit of a character when the Alt key is pressed.
On these terminals, you can use the corresponding byte for the mapping:
map á down
Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key when the alt key is pressed.
lf uses the escape delaying mechanism to recognize alt keys in these terminals (delay is 100ms).
On these terminals, keys combined with the alt key are prefixed with an `a` character:
Newer terminals (e.g. gnome-terminal) may prefix the key with an escape character when the Alt key is pressed.
lf uses the escape delaying mechanism to recognize Alt keys in these terminals (delay is 100ms).
On these terminals, keys combined with the Alt key are prefixed with an `a` character:
map <a-a> down
@@ -1451,18 +1538,18 @@ However, use of this option is highly recommended and it is assumed in the rest
# PIPING SHELL COMMANDS
Regular shell commands have some limitations in some cases.
When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again.
When an output or error message is given and the command exits afterwards, the UI is immediately resumed and there is no way to see the message without dropping to shell again.
Also, even when there is no output or error, the UI still needs to be paused while the command is running.
This can cause flickering on the screen for short commands and similar distractions for longer commands.
Instead of pausing the UI, piping shell commands connect stdin, stdout, and stderr of the command to the statline at the bottom of the UI.
This can be useful for programs following the Unix philosophy to give no output in the success case, and brief error messages or prompts in other cases.
For example, following rename command prompts for overwrite in the statline if there is an existing file with the given name:
For example, the following rename command prompts for overwrite in the statline if there is an existing file with the given name:
cmd rename %mv -i $f $1
You can also output error messages in the command and it will show up in the statline.
You can also output error messages in the command and they will show up in the statline.
For example, an alternative rename command may look like this:
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
@@ -1504,7 +1591,7 @@ You can optionally give it an ID number to send a command to a single client:
lf -remote 'send 1234 echo hello world'
All clients have a unique id number but you may not be aware of the id number when you are writing a command.
All clients have a unique ID number but you may not be aware of the ID number when you are writing a command.
For this purpose, an `$id` variable is exported to the environment for shell commands.
The value of this variable is set to the process ID of the client.
You can use it to send a remote command from a client to the server which in return sends a command back to itself.
@@ -1525,7 +1612,7 @@ For example, you can configure the number of columns in the UI with respect to t
fi
}}
In addition, the `query` command can be used to obtain information about a specific lf instance by providing its id:
In addition, the `query` command can be used to obtain information about a specific lf instance by providing its ID:
lf -remote "query $id maps"
@@ -1578,7 +1665,7 @@ Only file modes and (some) timestamps can be preserved (see `preserve` option),
Special files such as character and block devices, named pipes, and sockets are skipped and links are not followed.
Moving is performed using the rename operation of the underlying OS.
For cross-device moving, lf falls back to copying and then deletes the original files if there are no errors.
Operation errors are shown in the message line as well as the log file and they do not preemptively finish the corresponding file operation.
Operation errors are shown in the message line as well as the log file and they do not prematurely terminate the corresponding file operation.
File operations can be performed on the currently selected file or on multiple files by selecting them first.
When you `copy` a file, lf doesn't actually copy the file on the disk, but only records its name to a file.
@@ -1616,8 +1703,10 @@ Searching is the traditional method to move the selection to a file matching a g
Finding is an alternative way to search for a pattern possibly using fewer keystrokes.
The searching mechanism is implemented with commands `search` (default `/`), `search-back` (default `?`), `search-next` (default `n`), and `search-prev` (default `N`).
You can enable `globsearch` option to match with a glob pattern.
You can set `searchmethod` to `glob` to match using a glob pattern.
Globbing supports `*` to match any sequence, `?` to match any character, and `[...]` or `[^...]` to match character sets or ranges.
You can set `searchmethod` to `regex` to match using a regex pattern.
For a full overview of Go's RE2 syntax, see https://pkg.go.dev/regexp/syntax.
You can enable `incsearch` option to jump to the current match at each keystroke while typing.
In this mode, you can either use `cmd-enter` to accept the search or use `cmd-escape` to cancel the search.
You can also map some other commands with `cmap` to accept the search and execute the command immediately afterwards.
@@ -1631,10 +1720,10 @@ You can set the number of keys to match using `findlen` option.
If you set this value to zero, then the keys are read until there is only a single match.
The default values of these two options are set to jump to the first file with the given initial.
Some options effect both searching and finding.
Some options affect both searching and finding.
You can disable `wrapscan` option to prevent searches from being wrapped around at the end of the file list.
You can disable `ignorecase` option to match cases in the pattern and the filename.
This option is already automatically overridden if the pattern contains upper-case characters.
This option is already automatically overridden if the pattern contains uppercase characters.
You can disable `smartcase` option to disable this behavior.
Two similar options `ignoredia` and `smartdia` are provided to control matching diacritics in Latin letters.
@@ -1650,7 +1739,7 @@ It is possible to use different command types:
cmd open &xdg-open $f
You may want to use either file extensions or mime types from `file` command:
You may want to use either file extensions or MIME types from `file` command:
cmd open ${{
case $(file --mime-type -Lb $f) in
@@ -1684,11 +1773,11 @@ Possible options are `libfile-mimeinfo-perl` (executable name is `mimeopen`), `r
lf previews files on the preview pane by printing the file until the end or until the preview pane is filled.
This output can be enhanced by providing a custom preview script for filtering.
This can be used to highlight source codes, list contents of archive files or view PDF or image files to name a few.
This can be used to highlight source code, list contents of archive files or view PDF or image files to name a few.
For coloring lf recognizes ANSI escape codes.
To use this feature, you need to set the value of `previewer` option to the path of an executable file.
Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively.
Five arguments are passed to the file, (1) current filename, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively.
The output of the execution is printed in the preview pane.
You may also want to use the same script in your pager mapping as well:
@@ -1701,7 +1790,7 @@ For `less` pager, you may instead utilize `LESSOPEN` mechanism so that useful in
map i $LESSOPEN='| ~/.config/lf/pv.sh %s' less -R $f
Since this script is called for each file selection change it needs to be as efficient as possible and this responsibility is left to the user.
You may use file extensions to determine the type of file more efficiently compared to obtaining mime types from `file` command.
You may use file extensions to determine the type of file more efficiently compared to obtaining MIME types from `file` command.
Extensions can then be used to match cleanly within a conditional:
#!/bin/sh
@@ -1835,7 +1924,7 @@ It starts with a default color scheme and updates colors using values of existin
Colors are set in the following order:
1. default
2. LSCOLORS (Mac/BSD ls)
2. LSCOLORS (macOS/BSD ls)
3. LS_COLORS (GNU ls)
4. LF_COLORS (lf specific)
5. colors file (lf specific)
@@ -1944,7 +2033,7 @@ You may instead divide it into multiple lines in between double quotes by escapi
ex=01;32:\
"
The `ln` entry supports the special value `target`, which will use the link target to select a style. File name rules will still apply based on the link's name -- this mirrors GNU's `ls` and `dircolors` behavior.
The `ln` entry supports the special value `target`, which will use the link target to select a style. Filename rules will still apply based on the link's name -- this mirrors GNU's `ls` and `dircolors` behavior.
Having such a long variable definition in a shell configuration file might be undesirable.
You may instead use the colors file (refer to the [CONFIGURATION section](https://github.com/gokcehan/lf/blob/master/doc.md#configuration)) for configuration.
A sample colors file can be found at
@@ -1956,12 +2045,12 @@ https://en.wikipedia.org/wiki/ANSI_escape_code
Icons are configured using `LF_ICONS` environment variable or an icons file (refer to the [CONFIGURATION section](https://github.com/gokcehan/lf/blob/master/doc.md#configuration)).
The variable uses the same syntax as `LS_COLORS/LF_COLORS`.
Instead of colors, you should put a single characters as values of entries.
The `ln` entry supports the special value `target`, which will use the link target to select a icon. File name rules will still apply based on the link's name -- this mirrors GNU's `ls` and `dircolors` behavior.
Instead of colors, you should use single characters or symbols as values.
The `ln` entry supports the special value `target`, which will use the link target to select a icon. Filename rules will still apply based on the link's name -- this mirrors GNU's `ls` and `dircolors` behavior.
The icons file (refer to the [CONFIGURATION section](https://github.com/gokcehan/lf/blob/master/doc.md#configuration)) should consist of whitespace-separated arrays with a `#` character to start comments until the end of the line.
Each line should contain 1-3 columns, first column is filetype or filename pattern, second column is the icon, third column is an optional icon color. If there is only one column, means to disable rule for this filetype or pattern.
Each line should contain 1-3 columns: a file type or file name pattern, the icon, and an optional icon color. Using only one column disables all rules for that type or name.
Do not forget to add `set icons true` to your `lfrc` to see the icons.
Default values are as follows given with their matching order in lf:
Default values are listed below in the order lf matches them:
ln l
or l
+324 -252
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
map w $powershell
# change 'doc' command to use a different pager
cmd doc $lf -doc | less
# change 'help' command to use a different pager
cmd help $lf -doc | less
# leave some space at the top and the bottom of the screen
set scrolloff 10
+1 -2
View File
@@ -21,8 +21,7 @@ cmd open &&$Env:OPENER.Trim('"', ' ') "$Env:f"
map e $&$Env:EDITOR "$Env:f"
map i !&$Env:PAGER "$Env:f"
map w $&$Env:SHELL
cmd doc !&$Env:lf -doc | &$Env:PAGER
map <f-1> doc
cmd help !&$Env:lf -doc | &$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 vmaps !&$Env:lf -remote "query $Env:id vmaps" | &$Env:PAGER
+694 -777
View File
File diff suppressed because it is too large. Load diff
+5 -1
View File
@@ -6,6 +6,10 @@
# 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.
[ -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" "$@"
# vim: tabstop=4 shiftwidth=4 textwidth=80 colorcolumn=80
-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
+65 -15
View File
@@ -11,20 +11,70 @@
# 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)
set -o errexit -o nounset
pandoc \
--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
get_version() {
printf "r%s" $(($(git describe --tags --abbrev=0 | tr -d r) + 1))
}
pandoc \
--standalone \
--from gfm --to plain \
doc.md -o doc.txt
[ -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 \
--from gfm --to man \
--metadata=title:"LF" \
--metadata=section:"1" \
--metadata=date:"$date" \
--metadata=footer:"$version" \
--metadata=header:"DOCUMENTATION" \
doc.md -o lf.1
}
generate_plain_text() {
"${OCI_PROGRAM?}" run \
--rm \
--volume "$PWD:/data" \
"$@" "$PANDOC_IMAGE" \
--standalone \
--from gfm --to plain \
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
+4 -2
View File
@@ -8,7 +8,7 @@
# 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)
[ -z "${version:-}" ] && version=$(git describe --tags --abbrev=0)
test -d dist && {
echo "gen/xbuild.sh: WARNING: removing preexisting subdir 'dist'"
@@ -31,7 +31,7 @@ build() {
}
package() (
cd dist || return 1
cd dist || return 1
# Since the function is surrounded by (), the cd only affects a subshell
OUTFILE=
case "$1" in
@@ -90,3 +90,5 @@ if test -n "$ERRORS"; then
printf "\ngen/xbuild.sh: some targets failed to compile.\n"
exit 1
fi
# vim: tabstop=4 shiftwidth=4 textwidth=80 colorcolumn=80
+4 -5
View File
@@ -3,18 +3,17 @@ module github.com/gokcehan/lf
go 1.23.0
require (
github.com/Xuanwo/go-locale v1.1.3
github.com/djherbis/times v1.6.0
github.com/fsnotify/fsnotify v1.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
golang.org/x/sys v0.33.0
golang.org/x/term v0.32.0
golang.org/x/text v0.26.0
golang.org/x/sys v0.35.0
golang.org/x/term v0.34.0
)
require (
github.com/gdamore/encoding v1.0.1 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
golang.org/x/text v0.28.0 // indirect
)
+8 -43
View File
@@ -1,48 +1,30 @@
github.com/Xuanwo/go-locale v1.1.3 h1:EWZZJJt5rqPHHbqPRH1zFCn5D7xHjjebODctA4aUO3A=
github.com/Xuanwo/go-locale v1.1.3/go.mod h1:REn+F/c+AtGSWYACBSYZgl23AP+0lfQC+SEFPN+hj30=
github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw=
github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo=
github.com/gdamore/tcell/v2 v2.8.1 h1:KPNxyqclpWpWQlPLx6Xui1pMk8S+7+R37h3g07997NU=
github.com/gdamore/tcell/v2 v2.8.1/go.mod h1:bj8ori1BG3OYMjmb3IklZVWfZUJ1UBQt9JXrOCOhGWw=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/gdamore/tcell/v2 v2.9.0 h1:N6t+eqK7/xwtRPwxzs1PXeRWnm0H9l02CrgJ7DLn1ys=
github.com/gdamore/tcell/v2 v2.9.0/go.mod h1:8/ZoqM9rxzYphT9tH/9LnunhV9oPBqwS8WHGYm5nrmo=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -50,39 +32,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-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.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/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.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/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+277 -208
View File
File diff suppressed because it is too large. Load diff
+19 -8
View File
@@ -89,6 +89,16 @@ func exportEnvVars() {
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
func fieldToString(field reflect.Value) string {
kind := field.Kind()
@@ -257,41 +267,41 @@ func main() {
remoteCmd := flag.String(
"remote",
"",
"send remote command to server")
"send remote `command` to server")
cpuprofile := flag.String(
"cpuprofile",
"",
"path to the file to write the CPU profile")
"`path` to the file to write the CPU profile")
memprofile := flag.String(
"memprofile",
"",
"path to the file to write the memory profile")
"`path` to the file to write the memory profile")
flag.StringVar(&gLastDirPath,
"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,
"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,
"config",
"",
"path to the config file (instead of the usual paths)")
"`path` to the config file (instead of the usual paths)")
flag.Var(&gCommands,
"command",
"command to execute on client initialization")
"`command` to execute on client initialization")
flag.StringVar(&gLogPath,
"log",
"",
"path to the log file to write messages")
"`path` to the log file to write messages")
flag.Parse()
@@ -355,6 +365,7 @@ func main() {
}
exportEnvVars()
exportFlags()
run()
}
+151 -96
View File
@@ -2,9 +2,11 @@ package main
import (
"bufio"
"bytes"
"fmt"
"io"
"io/fs"
"math/big"
"path/filepath"
"regexp"
"strconv"
@@ -12,15 +14,20 @@ import (
"unicode"
"unicode/utf8"
"github.com/Xuanwo/go-locale"
"github.com/gdamore/tcell/v2"
"github.com/mattn/go-runewidth"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
const (
localeStrDisable = "" // disable locale ordering for this locale value
localeStrSys = "*" // replace this locale value with locale value read from environment
var (
reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`)
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 }
@@ -32,14 +39,6 @@ func replaceTilde(s string) string {
return s
}
func evalSymlinks(path string) string {
if target, err := filepath.EvalSymlinks(path); err == nil {
return target
}
return path
}
func runeSliceWidth(rs []rune) int {
w := 0
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
// backslashes in a given string.
func escape(s string) string {
func cmdEscape(s string) string {
buf := make([]rune, 0, len(s))
for _, r := range s {
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
// whitespaces and special characters in a given string.
func unescape(s string) string {
func cmdUnescape(s string) string {
esc := false
buf := make([]rune, 0, len(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
// whitespaces so that they are not split unintentionally.
// and quoted whitespaces so that they are not split unintentionally.
func tokenize(s string) []string {
esc := false
quote := false
var buf []rune
var toks []string
for _, r := range s {
if r == '\\' {
esc = true
buf = append(buf, r)
continue
}
if esc {
switch {
case esc:
esc = false
buf = append(buf, r)
continue
}
if !unicode.IsSpace(r) {
case r == '\\':
esc = true
buf = append(buf, r)
} else {
case r == '"':
quote = !quote
buf = append(buf, r)
case unicode.IsSpace(r) && !quote:
toks = append(toks, string(buf))
buf = nil
default:
buf = append(buf, r)
}
}
return append(toks, string(buf))
@@ -242,38 +242,52 @@ func readPairs(r io.Reader) ([][]string, error) {
return readArrays(r, 2, 2)
}
// This function converts a size in bytes to a human readable form using metric
// suffixes (e.g. 1K = 1000). For values less than 10 the first significant
// digit is shown, otherwise it is hidden. Numbers are always rounded down.
// This should be fine for most human beings.
func humanize(size int64) string {
if size < 1000 {
// This function converts a size in bytes to a human readable form using
// prefixes for either binary (1 KiB = 1024 B) or decimal (1 KB = 1000 B)
// multiples. The output should be no more than 5 characters long.
func humanize(size uint64) string {
var base uint64 = 1024
if gOpts.sizeunits == "decimal" {
base = 1000
}
if size < base {
return fmt.Sprintf("%dB", size)
}
suffix := []string{
"K", // kilo
"M", // mega
"G", // giga
"T", // tera
"P", // peta
"E", // exa
"Z", // zeta
"Y", // yotta
// *Note*: due to [`FileSize.Size()`](https://pkg.go.dev/io/fs#FileInfo)
// being `int64`, the maximum possible representable value would be 8 EiB or
// 9.2 EB.
prefixes := []string{
"K", // kibi (2^10) or kilo (10^3)
"M", // mebi (2^20) or mega (10^6)
"G", // gibi (2^30) or giga (10^9)
"T", // tebi (2^40) or tera (10^2)
"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
for _, s := range suffix {
if curr < 10 {
return fmt.Sprintf("%.1f%s", curr-0.0499, s)
curr := big.NewRat(int64(size), int64(base))
for _, prefix := range prefixes {
// if curr < 99.95 then round to 1 decimal place
if curr.Cmp(big.NewRat(9995, 100)) < 0 {
return fmt.Sprintf("%s%s", curr.FloatString(1), prefix)
}
if curr < 1000 {
return fmt.Sprintf("%d%s", int(curr), s)
// 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 /= 1000
curr.Quo(curr, big.NewRat(int64(base), 1))
}
return ""
return fmt.Sprintf("+999%s", prefixes[len(prefixes)-1])
}
// This function compares two strings for natural sorting which takes into
@@ -333,52 +347,6 @@ func getFileExtension(file fs.FileInfo) string {
return filepath.Ext(file.Name())
}
var (
reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`)
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]|$)`)
)
// 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)
if err != nil {
return localeTag, fmt.Errorf("invalid locale %q: %s", localeStr, err)
}
return localeTag, nil
}
// This function creates new collator for given locale. Passing empty string as
// as locale means reading locale value from environment.
//
// *Note*: this function returns error when given `localeStr` has value `localeStrDisable`
// or is an invalid locale tag.
func makeCollator(localeStr string, opts ...collate.Option) (*collate.Collator, error) {
if localeStr == localeStrDisable {
return nil, fmt.Errorf("locale is disabled")
}
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
// or a subpath of it.
// This is useful for clearing cached data when a directory is moved or deleted.
@@ -392,6 +360,26 @@ func deletePathRecursive[T any](m map[string]T, path string) {
}
}
// This function takes an escape sequence option (e.g. `\033[1m`) and outputs a
// complete format string (e.g. `\033[1m%s\033[0m`).
func optionToFmtstr(optstr string) string {
if !strings.Contains(optstr, "%s") {
return optstr + "%s\033[0m"
} else {
return optstr
}
}
// This function takes an escape sequence option (e.g. `\033[1m`) and converts
// it to a `tcell.Style` object.
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)
}
// This function is used to remove style-related ANSI escape sequences from
// a given string.
//
@@ -423,6 +411,73 @@ func stripAnsi(s string) string {
return b.String()
}
// This function reads lines from a file to be displayed as a preview.
// The number of lines to read is capped since files can be very large.
// Lines are split on `\n` characters, and `\r` characters are discarded.
// Sixel images are also detected and stored as separate lines.
// 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
}
if inSixel {
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)
}
}
last = b
}
}
// We don't need no generic code
// We don't need no type control
// No dark templates in compiler
+170 -63
View File
@@ -1,13 +1,14 @@
package main
import (
"math"
"os"
"reflect"
"strings"
"testing"
"time"
"golang.org/x/text/collate"
"github.com/gdamore/tcell/v2"
)
func TestIsRoot(t *testing.T) {
@@ -127,7 +128,7 @@ func TestRuneSliceWidthLastRange(t *testing.T) {
}
}
func TestEscape(t *testing.T) {
func TestCmdEscape(t *testing.T) {
tests := []struct {
s string
exp string
@@ -146,13 +147,13 @@ func TestEscape(t *testing.T) {
}
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)
}
}
}
func TestUnescape(t *testing.T) {
func TestCmdUnescape(t *testing.T) {
tests := []struct {
s string
exp string
@@ -171,7 +172,7 @@ func TestUnescape(t *testing.T) {
}
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)
}
}
@@ -184,8 +185,17 @@ func TestTokenize(t *testing.T) {
}{
{"", []string{""}},
{"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\"`}},
{`:rename foo\ bar`, []string{":rename", `foo\ bar`}},
{`!dir "C:\Program Files"`, []string{"!dir", `"C:\Program Files"`}},
}
for _, test := range tests {
@@ -247,29 +257,91 @@ func TestReadArrays(t *testing.T) {
func TestHumanize(t *testing.T) {
tests := []struct {
i int64
exp string
size uint64
expected string
}{
{0, "0B"},
{9, "9B"},
{99, "99B"},
{999, "999B"},
{1000, "1.0K"},
{1023, "1.0K"},
{1025, "1.0K"},
{1049, "1.0K"},
{1050, "1.0K"},
{1099, "1.0K"},
{9999, "9.9K"},
{10000, "10K"},
{10100, "10K"},
{10500, "10K"},
{1000000, "1.0M"},
{1, "1B"},
{2, "2B"},
{10, "10B"},
{100, "100B"},
{1000, "1000B"},
{1023, "1023B"},
{1024, "1.0K"},
{1025, "1.0K"}, // 1.000976563 KiB
{10188, "9.9K"}, // 9.94921875 KiB
{10189, "10.0K"}, // 9.950195313 KiB
{10240, "10.0K"}, // 10 KiB
{10291, "10.0K"}, // 10.049804688 KiB
{10292, "10.1K"}, // 10.05078125 KiB
{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 {
if got := humanize(test.i); got != test.exp {
t.Errorf("at input '%d' expected '%s' but got '%s'", test.i, test.exp, got)
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)
}
}
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)
}
}
}
@@ -338,51 +410,34 @@ func TestGetFileExtension(t *testing.T) {
}
}
func TestLocaleNaturalLess(t *testing.T) {
func TestOptionToFmtstr(t *testing.T) {
tests := []struct {
s1 string
s2 string
exp bool
s string
exp string
}{
// preserving behavior of `naturalLess`
{"foo", "bar", false},
{"bar", "baz", true},
{"foo", "123", false},
{"foo1", "foobar", true},
{"foo1", "foo10", true},
{"foo2", "foo10", true},
{"foo1", "foo10bar", true},
{"foo2", "foo10bar", true},
{"foo1bar", "foo10bar", true},
{"foo2bar", "foo10bar", true},
{"foo1bar", "foo10", true},
{"foo2bar", "foo10", true},
// locale sort
{"你好", "他好", true}, // \u4F60\u597D, \u4ED6\u597D
{"到这", "到那", false}, // \u5230\u8FD9, \u5230\u90A3
{"你说", "什么", true}, // \u4f60\u8bf4, \u4ec0\u4e48
{"你好", "World", false}, // \u4F60\u597D, \u57\u6f\u72\u6c\u64
{"甲1", "甲乙", true},
{"甲1", "甲10", true},
{"甲2", "甲10", true},
{"甲1", "甲10乙", true},
{"甲2", "甲10乙", true},
{"甲1乙", "甲10乙", true},
{"甲2乙", "甲10乙", true},
{"甲1乙", "甲10", true},
{"甲2乙", "甲10", true},
}
localeStr := "zh-CN"
collator, err := makeCollator(localeStr, collate.Numeric)
if err != nil {
t.Fatalf("failed to create collator for %q: %s", localeStr, err)
{"\033[1m", "\033[1m%s\033[0m"},
{"\033[1;7;31;42m", "\033[1;7;31;42m%s\033[0m"},
}
for _, test := range tests {
if got := collator.CompareString(test.s1, test.s2) < 0; got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got)
if got := optionToFmtstr(test.s); got != test.exp {
t.Errorf("at input %q expected %q but got %q", test.s, test.exp, got)
}
}
}
func TestParseEscapeSequence(t *testing.T) {
tests := []struct {
s string
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)
}
}
}
@@ -418,3 +473,55 @@ func TestStripAnsi(t *testing.T) {
}
}
}
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,
)
}
}
}
+243 -328
View File
@@ -6,10 +6,12 @@ import (
"fmt"
"io"
"log"
"maps"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"slices"
"sort"
"strconv"
@@ -17,7 +19,6 @@ import (
"time"
"github.com/djherbis/times"
"golang.org/x/text/collate"
)
type linkState byte
@@ -36,6 +37,7 @@ type file struct {
dirCount int
dirSize int64
accessTime time.Time
birthTime time.Time
changeTime time.Time
customInfo string
ext string
@@ -54,6 +56,7 @@ func newFile(path string) *file {
dirCount: -1,
dirSize: -1,
accessTime: time.Unix(0, 0),
birthTime: time.Unix(0, 0),
changeTime: time.Unix(0, 0),
customInfo: "",
ext: "",
@@ -80,13 +83,19 @@ func newFile(path string) *file {
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
// from times docs:
// ChangeTime() panics unless HasChangeTime() is true and
// BirthTime() panics unless HasBirthTime() is true.
// default to ModTime if BirthTime cannot be determined
bt := lstat.ModTime()
if ts.HasBirthTime() {
bt = ts.BirthTime()
}
// default to ModTime if ChangeTime cannot be determined
ct := lstat.ModTime()
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
dirCount := -1
@@ -95,7 +104,7 @@ func newFile(path string) *file {
if err != nil {
dirCount = -2
} else {
names, err := d.Readdirnames(1000)
names, err := d.Readdirnames(10000)
d.Close()
if names == nil && err != io.EOF {
@@ -114,6 +123,7 @@ func newFile(path string) *file {
dirCount: dirCount,
dirSize: -1,
accessTime: at,
birthTime: bt,
changeTime: ct,
customInfo: "",
ext: getFileExtension(lstat),
@@ -160,36 +170,35 @@ func readdir(path string) ([]*file, error) {
type dir struct {
loading bool // directory is loading from disk
loadTime time.Time // current loading or last load time
loadTime time.Time // last load time
ind int // index of current entry in files
pos int // position of current entry in ui
path string // full path of directory
files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files)
sortby sortMethod // sortby value from last sort
dircounts bool // dircounts value from last sort
dirfirst bool // dirfirst value from last sort
dironly bool // dironly value from last sort
hidden bool // hidden value from last sort
reverse bool // reverse value from last sort
visualAnchor int // index where visual mode was initiated
visualAnchor int // index where Visual mode was initiated
visualWrap int // wrap direction in Visual mode
hiddenfiles []string // hiddenfiles value from last sort
filter []string // last filter for this directory
ignorecase bool // ignorecase value from last sort
ignoredia bool // ignoredia value from last sort
locale string // locale value from last sort
noPerm bool // whether lf has no permission to open the directory
}
func newDir(path string) *dir {
time := time.Now()
files, err := readdir(path)
if err != nil {
log.Printf("reading directory: %s", err)
}
return &dir{
loadTime: time,
loadTime: time.Now(),
path: path,
files: files,
allFiles: files,
@@ -212,128 +221,115 @@ func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
func (dir *dir) sort() {
dir.sortby = getSortBy(dir.path)
dir.dircounts = getDirCounts(dir.path)
dir.dirfirst = getDirFirst(dir.path)
dir.dironly = getDirOnly(dir.path)
dir.hidden = getHidden(dir.path)
dir.reverse = getReverse(dir.path)
dir.locale = getLocale(dir.path)
dir.hiddenfiles = gOpts.hiddenfiles
dir.ignorecase = gOpts.ignorecase
dir.ignoredia = gOpts.ignoredia
dir.files = dir.allFiles
// When applying a filter, move all files not satisfying the predicate to
// the beginning, then take the subslice starting from the first file that
// does satisfy the predicate
applyFilter := func(fn func(f *file) bool) {
slices.SortStableFunc(dir.files, func(i, j *file) int {
switch {
case fn(i) == fn(j):
return 0
case !fn(i) && fn(j):
return -1
default:
return 1
}
})
i := slices.IndexFunc(dir.files, fn)
if i == -1 {
i = len(dir.files)
}
dir.files = dir.files[i:]
}
if dir.dironly {
applyFilter(func(f *file) bool { return f.IsDir() })
}
if !dir.hidden {
applyFilter(func(f *file) bool { return !isHidden(f, dir.path, dir.hiddenfiles) })
}
if len(dir.filter) != 0 {
applyFilter(func(f *file) bool { return !isFiltered(f, dir.filter) })
}
// reverse order cannot be applied after stable sorting, otherwise the order
// of equivalent elements will be reversed
applySort := func(fn func(i, j int) bool) {
if !dir.reverse {
sort.SliceStable(dir.files, fn)
} else {
sort.SliceStable(dir.files, func(i, j int) bool { return fn(j, i) })
}
}
switch dir.sortby {
case naturalSort:
if collator, err := makeCollator(dir.locale, collate.Numeric); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
})
}
case customSort:
if collator, err := makeCollator(dir.locale, collate.Numeric); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(stripAnsi(dir.files[i].customInfo), stripAnsi(dir.files[j].customInfo), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(stripAnsi(dir.files[i].customInfo), stripAnsi(dir.files[j].customInfo), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
})
}
applySort(func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
return naturalLess(s1, s2)
})
case nameSort:
if collator, err := makeCollator(dir.locale); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return s1 < s2
} else {
return s2 < s1
}
})
}
applySort(func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
return s1 < s2
})
case sizeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].TotalSize() < dir.files[j].TotalSize()
} else {
return dir.files[j].TotalSize() < dir.files[i].TotalSize()
sizeVal := func(f *file) int64 {
if f.IsDir() && dir.dircounts {
return int64(f.dirCount)
}
return f.TotalSize()
}
applySort(func(i, j int) bool {
s1, s2 := sizeVal(dir.files[i]), sizeVal(dir.files[j])
return s1 < s2
})
case timeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].ModTime().Before(dir.files[j].ModTime())
} else {
return dir.files[j].ModTime().Before(dir.files[i].ModTime())
}
applySort(func(i, j int) bool {
return dir.files[i].ModTime().Before(dir.files[j].ModTime())
})
case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
} else {
return dir.files[j].accessTime.Before(dir.files[i].accessTime)
}
applySort(func(i, j int) bool {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
})
case btimeSort:
applySort(func(i, j int) bool {
return dir.files[i].birthTime.Before(dir.files[j].birthTime)
})
case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
} else {
return dir.files[j].changeTime.Before(dir.files[i].changeTime)
}
applySort(func(i, j int) bool {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
})
case extSort:
sort.SliceStable(dir.files, func(i, j int) bool {
applySort(func(i, j int) bool {
ext1, ext2 := normalize(dir.files[i].ext, dir.files[j].ext, dir.ignorecase, dir.ignoredia)
name1, name2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return ext1 < ext2 || ext1 == ext2 && name1 < name2
} else {
return ext2 < ext1 || ext2 == ext1 && name2 < name1
}
return ext1 < ext2 || ext1 == ext2 && name1 < name2
})
case customSort:
applySort(func(i, j int) bool {
s1, s2 := normalize(stripAnsi(dir.files[i].customInfo), stripAnsi(dir.files[j].customInfo), dir.ignorecase, dir.ignoredia)
return naturalLess(s1, s2)
})
}
if dir.dirfirst {
// when sorting by size while also showing dircounts, we always display files
// and directories separately to avoid mixing file sizes and file counts
if dir.dirfirst || (dir.sortby == sizeSort && dir.dircounts) {
sort.SliceStable(dir.files, func(i, j int) bool {
if dir.files[i].IsDir() == dir.files[j].IsDir() {
return i < j
@@ -342,65 +338,6 @@ func (dir *dir) sort() {
})
}
// when dironly option is enabled, we move files to the beginning of our file
// list and then set the beginning of displayed files to the first directory
// in the list
if dir.dironly {
sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.files[i].IsDir() && !dir.files[j].IsDir() {
return i < j
}
return !dir.files[i].IsDir()
})
dir.files = func() []*file {
for i, f := range dir.files {
if f.IsDir() {
return dir.files[i:]
}
}
return dir.files[len(dir.files):]
}()
}
// when hidden option is disabled, we move hidden files to the
// beginning of our file list and then set the beginning of displayed
// files to the first non-hidden file in the list
if !dir.hidden {
sort.SliceStable(dir.files, func(i, j int) bool {
if isHidden(dir.files[i], dir.path, dir.hiddenfiles) && isHidden(dir.files[j], dir.path, dir.hiddenfiles) {
return i < j
}
return isHidden(dir.files[i], dir.path, dir.hiddenfiles)
})
for i, f := range dir.files {
if !isHidden(f, dir.path, dir.hiddenfiles) {
dir.files = dir.files[i:]
break
}
}
if len(dir.files) > 0 && isHidden(dir.files[len(dir.files)-1], dir.path, dir.hiddenfiles) {
dir.files = dir.files[len(dir.files):]
}
}
if len(dir.filter) != 0 {
sort.SliceStable(dir.files, func(i, j int) bool {
if isFiltered(dir.files[i], dir.filter) && isFiltered(dir.files[j], dir.filter) {
return i < j
}
return isFiltered(dir.files[i], dir.filter)
})
for i, f := range dir.files {
if !isFiltered(f, dir.filter) {
dir.files = dir.files[i:]
break
}
}
if len(dir.files) > 0 && isFiltered(dir.files[len(dir.files)-1], dir.filter) {
dir.files = dir.files[len(dir.files):]
}
}
dir.ind = max(dir.ind, 0)
dir.ind = min(dir.ind, len(dir.files)-1)
}
@@ -413,15 +350,6 @@ func (dir *dir) name() string {
return dir.files[dir.ind].Name()
}
func (d *dir) fileNames() []string {
names := []string{}
for _, file := range d.files {
names = append(names, file.path)
}
return names
}
func (nav *nav) isVisualMode() bool {
return nav.init && nav.currDir().visualAnchor != -1
}
@@ -432,13 +360,21 @@ func (dir *dir) visualSelections() []string {
return paths
}
beg, end := dir.ind, dir.visualAnchor
if beg > end {
beg, end = end, beg
var beg, end int
switch {
case dir.visualWrap == 0:
beg = min(dir.ind, dir.visualAnchor)
end = max(dir.ind, dir.visualAnchor)
case dir.visualWrap < 0:
beg = dir.ind
end = dir.visualAnchor - dir.visualWrap*len(dir.files)
case dir.visualWrap > 0:
beg = dir.visualAnchor
end = dir.ind + dir.visualWrap*len(dir.files)
}
for _, f := range dir.files[beg : end+1] {
paths = append(paths, f.path)
for i := beg; i < min(end+1, beg+len(dir.files)); i++ {
paths = append(paths, dir.files[i%len(dir.files)].path)
}
return paths
@@ -485,9 +421,22 @@ func (dir *dir) boundPos(height int) {
dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind))
}
type clipboardMode byte
const (
clipboardCopy = iota
clipboardCut
)
type clipboard struct {
paths []string
mode clipboardMode
}
type nav struct {
init bool
dirs []*dir
copyJobs int
copyBytes int64
copyTotal int64
copyUpdate int
@@ -497,6 +446,7 @@ type nav struct {
deleteCount int
deleteTotal int
deleteUpdate int
copyJobsChan chan int
copyBytesChan chan int64
copyTotalChan chan int64
moveCountChan chan int
@@ -510,7 +460,7 @@ type nav struct {
delChan chan string
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
clipboard clipboard
marks map[string]string
renameOldPath string
renameNewPath string
@@ -532,48 +482,40 @@ type nav struct {
jumpListInd int
}
func (nav *nav) loadDirInternal(path string) *dir {
d := &dir{
loading: true,
loadTime: time.Now(),
path: path,
sortby: getSortBy(path),
dirfirst: getDirFirst(path),
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
locale: getLocale(path),
visualAnchor: -1,
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
func (nav *nav) loadDir(path string) *dir {
d, ok := nav.dirCache[path]
if !ok {
go func() {
nav.dirChan <- newDir(path)
}()
d := &dir{
loading: true,
path: path,
sortby: getSortBy(path),
dircounts: getDirCounts(path),
dirfirst: getDirFirst(path),
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
visualAnchor: -1,
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
}
nav.dirCache[path] = d
return d
}
go func() {
d := newDir(path)
d.sort()
d.ind, d.pos = 0, 0
nav.dirChan <- d
}()
nav.checkDir(d)
return d
}
func (nav *nav) loadDir(path string) *dir {
if gOpts.dircache {
d, ok := nav.dirCache[path]
if !ok {
d = nav.loadDirInternal(path)
nav.dirCache[path] = d
return d
}
nav.checkDir(d)
return d
}
return nav.loadDirInternal(path)
}
func (nav *nav) checkDir(dir *dir) {
if dir.loading {
return
}
s, err := os.Stat(dir.path)
if err != nil {
log.Printf("getting directory info: %s", err)
@@ -582,26 +524,29 @@ func (nav *nav) checkDir(dir *dir) {
switch {
case s.ModTime().After(dir.loadTime):
now := time.Now()
// XXX: Linux builtin exFAT drivers are able to predict modifications in the future
// https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504
if s.ModTime().After(now) {
if s.ModTime().After(time.Now()) {
return
}
dir.loading = true
dir.loadTime = now
go func() {
nd := newDir(dir.path)
nav.dirChan <- nd
nav.dirChan <- newDir(dir.path)
}()
case dir.dircounts != getDirCounts(dir.path):
dir.loading = true
go func() {
nav.dirChan <- newDir(dir.path)
}()
// Although toggling dircounts can affect sorting, it is already handled by
// reloading the directory which should sort the files anyway, so it is not
// checked below.
case dir.sortby != getSortBy(dir.path) ||
dir.dirfirst != getDirFirst(dir.path) ||
dir.dironly != getDirOnly(dir.path) ||
dir.hidden != getHidden(dir.path) ||
dir.reverse != getReverse(dir.path) ||
dir.locale != getLocale(dir.path) ||
!reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles) ||
dir.ignorecase != gOpts.ignorecase ||
dir.ignoredia != gOpts.ignoredia:
@@ -637,6 +582,7 @@ func (nav *nav) getDirs(wd string) {
func newNav(height int) *nav {
nav := &nav{
copyJobsChan: make(chan int, 1024),
copyBytesChan: make(chan int64, 1024),
copyTotalChan: make(chan int64, 1024),
moveCountChan: make(chan int, 1024),
@@ -650,7 +596,6 @@ func newNav(height int) *nav {
delChan: make(chan string),
dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
marks: make(map[string]string),
selections: make(map[string]int),
tags: make(map[string]string),
@@ -867,43 +812,12 @@ func (nav *nav) preview(path string, win *win) {
reader = bufio.NewReader(f)
}
if gOpts.sixel {
prefix, err := reader.Peek(2)
if err == nil && string(prefix) == gSixelBegin {
b, err := io.ReadAll(reader)
if err != nil {
log.Printf("loading sixel: %s", err)
}
str := string(b)
reg.sixel = &str
return
}
}
// bufio.Scanner can't handle files containing long lines if they exceed the
// size of its internal buffer
line := []byte{}
for len(reg.lines) < win.h {
bytes, isPrefix, err := reader.ReadLine()
if err != nil {
if len(line) > 0 {
reg.lines = append(reg.lines, string(line))
}
break
}
if slices.Contains(bytes, 0) {
reg.lines = []string{"\033[7mbinary\033[0m"}
return
}
line = append(line, bytes...)
if !isPrefix {
reg.lines = append(reg.lines, string(line))
line = []byte{}
}
lines, binary, sixel := readLines(reader, win.h)
if binary {
lines = []string{"\033[7mbinary\033[0m"}
}
reg.lines = lines
reg.sixel = sixel
}
func (nav *nav) loadReg(path string, volatile bool) *reg {
@@ -985,6 +899,7 @@ func (nav *nav) up(dist int) bool {
if dir.ind == 0 {
if gOpts.wrapscroll {
nav.bottom()
dir.visualWrap -= 1
}
return old != dir.ind
}
@@ -1008,6 +923,7 @@ func (nav *nav) down(dist int) bool {
if dir.ind >= maxind {
if gOpts.wrapscroll {
nav.top()
dir.visualWrap += 1
}
return old != dir.ind
}
@@ -1225,8 +1141,6 @@ func (nav *nav) toggle() {
}
func (nav *nav) tagToggleSelection(path string, tag string) {
path = evalSymlinks(path)
if _, ok := nav.tags[path]; ok {
delete(nav.tags, path)
} else {
@@ -1262,7 +1176,7 @@ func (nav *nav) tag(tag string) error {
}
for _, path := range list {
nav.tags[evalSymlinks(path)] = tag
nav.tags[path] = tag
}
return nil
@@ -1281,38 +1195,44 @@ func (nav *nav) unselect() {
nav.selectionInd = 0
}
func (nav *nav) save(cp bool) error {
func (nav *nav) save(mode clipboardMode) error {
list, err := nav.currFileOrSelections()
if err != nil {
return err
}
if err := saveFiles(list, cp); err != nil {
clipboard := clipboard{list, mode}
if err := saveFiles(clipboard); err != nil {
return err
}
clear(nav.saves)
for _, f := range list {
nav.saves[f] = cp
}
nav.clipboard = clipboard
return nil
}
func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) {
echo := &callExpr{"echoerr", []string{""}, 1}
errCount := 0
sendErr := func(format string, a ...any) {
errCount++
msg := fmt.Sprintf("copy [%d]: %s", errCount, fmt.Sprintf(format, a...))
app.ui.exprChan <- &callExpr{"echoerr", []string{msg}, 1}
}
_, err := os.Stat(dstDir)
if os.IsNotExist(err) {
echo.args[0] = err.Error()
app.ui.exprChan <- echo
sendErr("%v", err)
return
}
// Indicate that a copy operation is in progress. Using the total bytes to
// determine this instead will mean that it is possible for copySize to take
// a while, but not be reflected in the UI until it has finished.
nav.copyJobsChan <- 1
total, err := copySize(srcs)
if err != nil {
echo.args[0] = err.Error()
app.ui.exprChan <- echo
sendErr("%v", err)
nav.copyJobsChan <- -1
return
}
@@ -1320,7 +1240,6 @@ func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) {
nums, errs := copyAll(srcs, dstDir, gOpts.preserve)
errCount := 0
loop:
for {
select {
@@ -1330,12 +1249,11 @@ loop:
if !ok {
break loop
}
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
}
}
nav.copyJobsChan <- -1
nav.copyTotalChan <- -total
if gSingleMode {
@@ -1343,9 +1261,7 @@ loop:
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
}
}
@@ -1355,26 +1271,27 @@ loop:
}
func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
echo := &callExpr{"echoerr", []string{""}, 1}
errCount := 0
sendErr := func(format string, a ...any) {
errCount++
msg := fmt.Sprintf("move [%d]: %s", errCount, fmt.Sprintf(format, a...))
app.ui.exprChan <- &callExpr{"echoerr", []string{msg}, 1}
}
_, err := os.Stat(dstDir)
if os.IsNotExist(err) {
echo.args[0] = err.Error()
app.ui.exprChan <- echo
sendErr("%v", err)
return
}
nav.moveTotalChan <- len(srcs)
errCount := 0
for _, src := range srcs {
nav.moveCountChan <- 1
srcStat, err := os.Lstat(src)
if err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
continue
}
@@ -1383,9 +1300,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
if dstStat, err := os.Stat(dst); err == nil {
if os.SameFile(srcStat, dstStat) {
errCount++
echo.args[0] = fmt.Sprintf("[%d] rename %s %s: source and destination are the same file", errCount, src, dst)
app.ui.exprChan <- echo
sendErr("rename %s %s: source and destination are the same file", src, dst)
continue
}
ext := getFileExtension(dstStat)
@@ -1404,10 +1319,12 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
if err := os.Rename(src, dst); err != nil {
if errCrossDevice(err) {
nav.copyJobsChan <- 1
total, err := copySize([]string{src})
if err != nil {
echo.args[0] = err.Error()
app.ui.exprChan <- echo
sendErr("%v", err)
nav.copyJobsChan <- -1
continue
}
@@ -1425,25 +1342,20 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
if !ok {
break loop
}
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
}
}
nav.copyJobsChan <- -1
nav.copyTotalChan <- -total
if errCount == oldCount {
if err := os.RemoveAll(src); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
}
}
} else {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
}
}
}
@@ -1455,9 +1367,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
app.ui.loadFile(app, true)
} else {
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
app.ui.exprChan <- echo
sendErr("%v", err)
}
}
@@ -1468,21 +1378,21 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
}
func (nav *nav) paste(app *app) error {
srcs, cp, err := loadFiles()
clipboard, err := loadFiles()
if err != nil {
return err
}
if len(srcs) == 0 {
return errors.New("no file in copy/cut buffer")
if len(clipboard.paths) == 0 {
return errors.New("no files in clipboard")
}
dstDir := nav.currDir().path
if cp {
go nav.copyAsync(app, srcs, dstDir)
if clipboard.mode == clipboardCopy {
go nav.copyAsync(app, clipboard.paths, dstDir)
} else {
go nav.moveAsync(app, srcs, dstDir)
go nav.moveAsync(app, clipboard.paths, dstDir)
}
return nil
@@ -1564,15 +1474,12 @@ func (nav *nav) rename() error {
}
func (nav *nav) sync() error {
list, cp, err := loadFiles()
clipboard, err := loadFiles()
if err != nil {
return err
}
clear(nav.saves)
for _, f := range list {
nav.saves[f] = cp
}
nav.clipboard = clipboard
tempmarks := make(map[string]string)
for _, ch := range gOpts.tempmarks {
@@ -1582,9 +1489,7 @@ func (nav *nav) sync() error {
}
}
errMarks := nav.readMarks()
for k, v := range tempmarks {
nav.marks[k] = v
}
maps.Copy(nav.marks, tempmarks)
err = nav.readTags()
@@ -1723,6 +1628,7 @@ func (nav *nav) findNext() (bool, bool) {
if gOpts.wrapscan {
for i := range dir.ind {
if findMatch(dir.files[i].Name(), nav.find) {
dir.visualWrap += 1
return nav.up(dir.ind - i), true
}
}
@@ -1740,6 +1646,7 @@ func (nav *nav) findPrev() (bool, bool) {
if gOpts.wrapscan {
for i := len(dir.files) - 1; i > dir.ind; i-- {
if findMatch(dir.files[i].Name(), nav.find) {
dir.visualWrap -= 1
return nav.down(i - dir.ind), true
}
}
@@ -1747,7 +1654,7 @@ func (nav *nav) findPrev() (bool, bool) {
return false, false
}
func searchMatch(name, pattern string, glob bool) (matched bool, err error) {
func searchMatch(name, pattern string, method searchMethod) (matched bool, err error) {
if gOpts.ignorecase {
lpattern := strings.ToLower(pattern)
if !gOpts.smartcase || lpattern == pattern {
@@ -1762,16 +1669,22 @@ func searchMatch(name, pattern string, glob bool) (matched bool, err error) {
name = removeDiacritics(name)
}
}
if glob {
switch method {
case textSearch:
return strings.Contains(name, pattern), nil
case globSearch:
return filepath.Match(pattern, name)
case regexSearch:
return regexp.MatchString(pattern, name)
default:
return false, fmt.Errorf("searchMatch: invalid searchMethod")
}
return strings.Contains(name, pattern), nil
}
func (nav *nav) searchNext() (bool, error) {
dir := nav.currDir()
for i := dir.ind + 1; i < len(dir.files); i++ {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
return false, err
} else if matched {
return nav.down(i - dir.ind), nil
@@ -1779,9 +1692,10 @@ func (nav *nav) searchNext() (bool, error) {
}
if gOpts.wrapscan {
for i := range dir.ind {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
return false, err
} else if matched {
dir.visualWrap += 1
return nav.up(dir.ind - i), nil
}
}
@@ -1792,7 +1706,7 @@ func (nav *nav) searchNext() (bool, error) {
func (nav *nav) searchPrev() (bool, error) {
dir := nav.currDir()
for i := dir.ind - 1; i >= 0; i-- {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
return false, err
} else if matched {
return nav.up(dir.ind - i), nil
@@ -1800,9 +1714,10 @@ func (nav *nav) searchPrev() (bool, error) {
}
if gOpts.wrapscan {
for i := len(dir.files) - 1; i > dir.ind; i-- {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.searchmethod); err != nil {
return false, err
} else if matched {
dir.visualWrap -= 1
return nav.down(i - dir.ind), nil
}
}
@@ -1812,7 +1727,7 @@ func (nav *nav) searchPrev() (bool, error) {
func isFiltered(f os.FileInfo, filter []string) bool {
for _, pattern := range filter {
matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.globfilter)
matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.filtermethod)
if err != nil {
log.Printf("Filter Error: %s", err)
return false
+101 -99
View File
@@ -15,6 +15,7 @@ const (
sizeSort sortMethod = "size"
timeSort sortMethod = "time"
atimeSort sortMethod = "atime"
btimeSort sortMethod = "btime"
ctimeSort sortMethod = "ctime"
extSort sortMethod = "ext"
customSort sortMethod = "custom"
@@ -26,100 +27,109 @@ func isValidSortMethod(method sortMethod) bool {
method == sizeSort ||
method == timeSort ||
method == atimeSort ||
method == btimeSort ||
method == ctimeSort ||
method == extSort ||
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 {
anchorfind bool
autoquit bool
borderfmt string
cleaner string
copyfmt string
cursoractivefmt string
cursorparentfmt string
cursorpreviewfmt string
cutfmt string
dircache bool
dircounts bool
dirfirst bool
dironly bool
dirpreviews bool
drawbox bool
dupfilefmt string
globfilter bool
globsearch bool
errorfmt string
filesep string
filtermethod searchMethod
findlen int
hidden bool
hiddenfiles []string
history bool
icons bool
ifs string
ignorecase bool
ignoredia bool
incfilter bool
incsearch bool
locale string
info []string
infotimefmtnew string
infotimefmtold string
menufmt string
menuheaderfmt string
menuselectfmt string
mouse bool
number bool
numberfmt string
period int
preserve []string
preview bool
previewer string
promptfmt string
ratios []int
relativenumber bool
reverse bool
roundbox bool
rulerfmt string
scrolloff int
searchmethod searchMethod
selectfmt string
visualfmt string
selmode string
shell string
shellflag string
shellopts []string
showbinds bool
sixel bool
sortby sortMethod
sizeunits string
smartcase bool
smartdia bool
sortby sortMethod
statfmt string
tabstop int
tagfmt string
tempmarks string
timefmt string
truncatechar string
truncatepct int
visualfmt string
waitmsg string
watch bool
wrapscan 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
vkeys map[string]expr
cmdkeys map[string]expr
cmds map[string]expr
user map[string]string
tempmarks string
numberfmt string
tagfmt string
}
var gLocalOpts struct {
sortby map[string]sortMethod
dircounts map[string]bool
dirfirst map[string]bool
dironly map[string]bool
hidden map[string]bool
reverse map[string]bool
info map[string][]string
locale map[string]string
reverse map[string]bool
sortby map[string]sortMethod
}
func localOptPaths(path string) []string {
@@ -193,88 +203,80 @@ func getSortBy(path string) sortMethod {
return gOpts.sortby
}
func getLocale(path string) string {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.locale[key]; ok {
return val
}
}
return gOpts.locale
}
func init() {
gOpts.anchorfind = true
gOpts.autoquit = 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.dirfirst = true
gOpts.dironly = false
gOpts.dirpreviews = false
gOpts.drawbox = false
gOpts.dupfilefmt = "%f.~%n~"
gOpts.borderfmt = "\033[0m"
gOpts.copyfmt = "\033[7;33m"
gOpts.cursoractivefmt = "\033[7m"
gOpts.cursorparentfmt = "\033[7m"
gOpts.cursorpreviewfmt = "\033[4m"
gOpts.cutfmt = "\033[7;31m"
gOpts.globfilter = false
gOpts.globsearch = false
gOpts.errorfmt = "\033[7;31;47m"
gOpts.filesep = "\n"
gOpts.filtermethod = textSearch
gOpts.findlen = 1
gOpts.hidden = false
gOpts.hiddenfiles = gDefaultHiddenFiles
gOpts.history = true
gOpts.icons = false
gOpts.ifs = ""
gOpts.ignorecase = true
gOpts.ignoredia = true
gOpts.incfilter = 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.number = false
gOpts.numberfmt = "\033[33m"
gOpts.period = 0
gOpts.preserve = []string{"mode"}
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.reverse = false
gOpts.roundbox = 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.visualfmt = "\033[7;36m"
gOpts.selmode = "all"
gOpts.shell = gDefaultShell
gOpts.shellflag = gDefaultShellFlag
gOpts.shellopts = nil
gOpts.showbinds = true
gOpts.sixel = false
gOpts.sortby = naturalSort
gOpts.sizeunits = "binary"
gOpts.smartcase = true
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.watch = false
gOpts.wrapscan = true
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{
"k": &callExpr{"up", nil, 1},
"<up>": &callExpr{"up", nil, 1},
@@ -344,25 +346,26 @@ func init() {
"ss": &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1},
"st": &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1},
"sa": &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1},
"sb": &listExpr{[]expr{&setExpr{"sortby", "btime"}, &setExpr{"info", "btime"}}, 1},
"sc": &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1},
"se": &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1},
"gh": &callExpr{"cd", []string{"~"}, 1},
}
// 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)
// 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["V"] = &callExpr{"visual", 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["<esc>"] = &callExpr{"visual-discard", nil, 1}
gOpts.vkeys["V"] = &callExpr{"visual-accept", 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{
"<space>": &callExpr{"cmd-insert", []string{" "}, 1},
"<esc>": &callExpr{"cmd-escape", nil, 1},
@@ -405,14 +408,13 @@ func init() {
gOpts.cmds = make(map[string]expr)
gOpts.user = make(map[string]string)
gLocalOpts.sortby = make(map[string]sortMethod)
gLocalOpts.dircounts = make(map[string]bool)
gLocalOpts.dirfirst = make(map[string]bool)
gLocalOpts.dironly = make(map[string]bool)
gLocalOpts.hidden = make(map[string]bool)
gLocalOpts.reverse = make(map[string]bool)
gLocalOpts.info = make(map[string][]string)
gLocalOpts.locale = make(map[string]string)
gLocalOpts.reverse = make(map[string]bool)
gLocalOpts.sortby = make(map[string]sortMethod)
setDefaults()
}
+31 -3
View File
@@ -164,9 +164,9 @@ func setDefaults() {
gOpts.nkeys["w"] = &execExpr{"$", "$SHELL"}
gOpts.vkeys["w"] = &execExpr{"$", "$SHELL"}
gOpts.cmds["doc"] = &execExpr{"$", `"$lf" -doc | $PAGER`}
gOpts.nkeys["<f-1>"] = &callExpr{"doc", nil, 1}
gOpts.vkeys["<f-1>"] = &callExpr{"doc", nil, 1}
gOpts.cmds["help"] = &execExpr{"$", `"$lf" -doc | $PAGER`}
gOpts.nkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.vkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.cmds["maps"] = &execExpr{"$", `"$lf" -remote "query $id maps" | $PAGER`}
gOpts.cmds["nmaps"] = &execExpr{"$", `"$lf" -remote "query $id nmaps" | $PAGER`}
@@ -229,3 +229,31 @@ func errCrossDevice(err error) bool {
func quoteString(s string) string {
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)
}
+30 -7
View File
@@ -74,23 +74,33 @@ func init() {
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{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
filepath.Join(data, "lf", "lfrc"),
filepath.Join(config, "lf", "lfrc"),
}
gColorsPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "colors"),
filepath.Join(data, "lf", "colors"),
filepath.Join(config, "lf", "colors"),
}
gIconsPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "icons"),
filepath.Join(data, "lf", "icons"),
filepath.Join(config, "lf", "icons"),
}
data := cmp.Or(
os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"),
os.Getenv("LOCALAPPDATA"),
)
gFilesPath = filepath.Join(data, "lf", "files")
gMarksPath = filepath.Join(data, "lf", "marks")
gTagsPath = filepath.Join(data, "lf", "tags")
@@ -150,9 +160,9 @@ func setDefaults() {
gOpts.nkeys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.vkeys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.cmds["doc"] = &execExpr{"!", "%lf% -doc | %PAGER%"}
gOpts.nkeys["<f-1>"] = &callExpr{"doc", nil, 1}
gOpts.vkeys["<f-1>"] = &callExpr{"doc", nil, 1}
gOpts.cmds["help"] = &execExpr{"!", "%lf% -doc | %PAGER%"}
gOpts.nkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.vkeys["<f-1>"] = &callExpr{"help", nil, 1}
gOpts.cmds["maps"] = &execExpr{"!", `%lf% -remote "query %id% maps" | %PAGER%`}
gOpts.cmds["nmaps"] = &execExpr{"!", `%lf% -remote "query %id% nmaps" | %PAGER%`}
@@ -221,3 +231,16 @@ func quoteString(s string) string {
}
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, `"`, "")
}
+49 -20
View File
@@ -6,12 +6,11 @@ import (
"log"
"os"
"strconv"
"strings"
"github.com/gdamore/tcell/v2"
)
const gSixelBegin = "\033P"
type sixelScreen struct {
lastFile string
lastWin win
@@ -29,7 +28,7 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return
}
if reg.sixel == nil {
if !reg.sixel {
sxs.lastFile = ""
return
}
@@ -40,26 +39,56 @@ func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
return
}
matches := reSixelSize.FindStringSubmatch(*reg.sixel)
if matches == nil {
log.Printf("sixel: failed to get image size")
return
}
iw, _ := strconv.Atoi(matches[1])
ih, _ := strconv.Atoi(matches[2])
y := win.y
var b strings.Builder
if os.Getenv("TMUX") != "" {
// tmux rounds the image height up to a multiple of 6, so we
// need to do the same to avoid overwriting the image, as tmux
// would remove the image if we touched it.
ih = (ih + 5) / 6 * 6
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 += 1
continue
}
matches := reSixelSize.FindStringSubmatch(line)
if matches == nil {
log.Printf("sixel: failed to get image size")
continue
}
iw, _ := strconv.Atoi(matches[1])
ih, _ := strconv.Atoi(matches[2])
if os.Getenv("TMUX") != "" {
// tmux rounds the image height up to a multiple of 6, so we
// need to do the same to avoid overwriting the image, as tmux
// would remove the image if we touched it.
ih = (ih + 5) / 6 * 6
}
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
}
screen.LockRegion(win.x, win.y, (iw+cw-1)/cw, (ih+ch-1)/ch, true)
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, *reg.sixel) // Print sixel
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
fmt.Fprint(os.Stderr, "\033[?2026h") // Begin synchronized update
fmt.Fprint(os.Stderr, "\0337") // Save cursor position
fmt.Fprint(os.Stderr, b.String()) // Write data
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
fmt.Fprint(os.Stderr, "\033[?2026l") // End synchronized update
sxs.lastFile = reg.path
sxs.lastWin = *win
+153 -129
View File
@@ -270,12 +270,14 @@ func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs
return
}
for i, l := range reg.lines {
if i > win.h-1 {
break
}
if !reg.sixel {
for i, l := range reg.lines {
if i > win.h-1 {
break
}
st = win.print(screen, 2, i, st, l)
st = win.print(screen, 0, i, st, l)
}
}
sxs.printSixel(win, screen, reg)
@@ -301,13 +303,13 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
if f.IsDir() && getDirCounts(d.path) {
switch {
case f.dirCount < -1:
info.WriteString(" !")
info.WriteString(" !")
case f.dirCount < 0:
info.WriteString(" ?")
case f.dirCount < 1000:
fmt.Fprintf(&info, " %4d", f.dirCount)
info.WriteString(" ?")
case f.dirCount < 10000:
fmt.Fprintf(&info, " %5d", f.dirCount)
default:
info.WriteString(" 999+")
info.WriteString(" 9999+")
}
continue
}
@@ -316,13 +318,15 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
if f.IsDir() && f.dirSize < 0 {
sz = "-"
} else {
sz = humanize(f.TotalSize())
sz = humanize(uint64(f.TotalSize()))
}
fmt.Fprintf(&info, " %4s", sz)
fmt.Fprintf(&info, " %5s", sz)
case "time":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime()))
case "atime":
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":
fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime))
case "perm":
@@ -347,7 +351,7 @@ func fileInfo(f *file, d *dir, userWidth int, groupWidth int, customWidth int) (
type dirContext struct {
selections map[string]int
saves map[string]bool
clipboard clipboard
tags map[string]string
}
@@ -457,8 +461,8 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.visualfmt), " ")
} else if _, ok := context.selections[path]; ok {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.selectfmt), " ")
} else if cp, ok := context.saves[path]; ok {
if cp {
} else if slices.Contains(context.clipboard.paths, path) {
if context.clipboard.mode == clipboardCopy {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.copyfmt), " ")
} else {
win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.cutfmt), " ")
@@ -473,7 +477,7 @@ func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirSty
}
tag := " "
if val, ok := context.tags[evalSymlinks(path)]; ok && len(val) > 0 {
if val, ok := context.tags[path]; ok && len(val) > 0 {
tag = val
}
@@ -635,6 +639,11 @@ func getWins(screen tcell.Screen) []*win {
return wins
}
type menuSelect struct {
x, y int
s string
}
type ui struct {
screen tcell.Screen
sxScreen sixelScreen
@@ -644,7 +653,6 @@ type ui struct {
msgWin *win
menuWin *win
msg string
msgIsStat bool
regPrev *reg
dirPrev *dir
exprChan chan expr
@@ -652,16 +660,17 @@ type ui struct {
tevChan chan tcell.Event
evChan chan tcell.Event
menu string
menuSelect *menuSelect
cmdPrefix string
cmdAccLeft []rune
cmdAccRight []rune
cmdYankBuf []rune
cmdTmp []rune
keyAcc []rune
keyCount []rune
styles styleMap
icons iconMap
currentFile string
pasteEvent bool
}
func newUI(screen tcell.Screen) *ui {
@@ -674,7 +683,6 @@ func newUI(screen tcell.Screen) *ui {
promptWin: newWin(wtot, 1, 0, 0),
msgWin: newWin(wtot, 1, 0, htot-1),
menuWin: newWin(wtot, 1, 0, htot-2),
msgIsStat: true,
exprChan: make(chan expr, 1000),
keyChan: make(chan string, 1000),
tevChan: make(chan tcell.Event, 1000),
@@ -732,7 +740,6 @@ func (ui *ui) sort() {
func (ui *ui) echo(msg string) {
ui.msg = msg
ui.msgIsStat = false
}
func (ui *ui) echomsg(msg string) {
@@ -740,14 +747,6 @@ func (ui *ui) echomsg(msg string) {
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) {
ui.echo(fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg))
log.Printf("error: %s", msg)
@@ -766,7 +765,7 @@ type reg struct {
loadTime time.Time
path string
lines []string
sixel *string
sixel bool
}
func (ui *ui) loadFile(app *app, volatile bool) {
@@ -799,57 +798,6 @@ func (ui *ui) loadFile(app *app, volatile bool) {
}
}
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) {
st := tcell.StyleDefault
@@ -923,13 +871,61 @@ func formatRulerOpt(name string, val string) string {
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", curr.Mode().String())
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.Split(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) {
st := tcell.StyleDefault
dir := nav.currDir()
ui.msgWin.print(ui.screen, 0, 0, st, ui.msg)
tot := len(dir.files)
ind := min(dir.ind+1, tot)
hid := len(dir.allFiles) - tot
@@ -950,12 +946,10 @@ func (ui *ui) drawRuler(nav *nav) {
copy := 0
move := 0
for _, cp := range nav.saves {
if cp {
copy++
} else {
move++
}
if nav.clipboard.mode == clipboardCopy {
copy = len(nav.clipboard.paths)
} else {
move = len(nav.clipboard.paths)
}
currSelections := nav.currSelections()
@@ -963,8 +957,12 @@ func (ui *ui) drawRuler(nav *nav) {
progress := []string{}
if nav.copyTotal > 0 {
progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal))
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 {
@@ -1063,6 +1061,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 {
wins := len(ui.wins)
if gOpts.preview {
@@ -1077,7 +1107,7 @@ func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
func (ui *ui) draw(nav *nav) {
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()
@@ -1100,6 +1130,7 @@ func (ui *ui) draw(nav *nav) {
switch ui.cmdPrefix {
case "":
ui.drawStat(nav)
ui.drawRuler(nav)
ui.screen.HideCursor()
case ">":
@@ -1136,25 +1167,7 @@ func (ui *ui) draw(nav *nav) {
ui.drawBox()
}
if ui.menu != "" {
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.drawMenu()
ui.screen.Show()
}
@@ -1396,6 +1409,10 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
switch tev := ev.(type) {
case *tcell.EventKey:
if ui.pasteEvent {
return nil
}
// KeyRune is a regular character
if tev.Key() == tcell.KeyRune {
switch {
@@ -1564,6 +1581,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
return &callExpr{"cd", []string{dir.path}, 1}
}
case *tcell.EventResize:
clear(nav.regCache)
return &callExpr{"redraw", nil, 1}
case *tcell.EventError:
log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When())
@@ -1575,6 +1593,12 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
} else {
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
}
@@ -1655,36 +1679,36 @@ func anyKey() {
os.Stdin.Read(b)
}
func listMatches(screen tcell.Screen, matches []string, selectedInd int) string {
mlen := len(matches)
if mlen < 2 {
return ""
func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) (string, *menuSelect) {
if len(matches) < 2 {
return "", nil
}
var b strings.Builder
wtot, _ := screen.Size()
wcol := 0
for _, m := range matches {
wcol = max(wcol, len(m))
wcol = max(wcol, runeSliceWidth([]rune(m.name)))
}
wcol += gOpts.tabstop - wcol%gOpts.tabstop
ncol := max(wtot/wcol, 1)
b.WriteString("possible matches\n")
var b strings.Builder
b.WriteString("possible matches")
for i := 0; i < mlen; {
for j := 0; j < ncol && i < mlen; i, j = i+1, j+1 {
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), "")
}
for i, match := range matches {
if i%ncol == 0 {
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
}