Compare commits

223 Commits
Author SHA1 Message Date
Joe Lim c25647d364 Prepare for r34 release (#1909) 2025-02-09 22:50:06 +11:00
Joe Lim 4f0a5d6211 Automatically unselect files after watch remove (#1901) 2025-02-03 10:45:53 +11:00
Joe Lim 7595e05957 Add workaround for equivalent paths for watch option (#1895)
* Add workaround for equivalent paths for watch option

* Add comment

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-01-15 13:24:35 +11:00
dependabot[bot] df0b62af30 Bump golang.org/x/term from 0.27.0 to 0.28.0 (#1884)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.27.0 to 0.28.0.
- [Commits](https://github.com/golang/term/compare/v0.27.0...v0.28.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-01-15 13:16:06 +11:00
Joe Lim 2095efa661 Various fixes for updating dircounts with watch enabled (#1881)
* Fix file size bug when copying files

* Don't remove existing watches

* Bump fsnotify

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-12-05 18:20:00 +11:00
dependabot[bot] 085717bc9f Bump golang.org/x/text from 0.20.0 to 0.21.0 (#1870)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.20.0 to 0.21.0.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.20.0...v0.21.0)

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-08 15:26:04 +11:00
dependabot[bot] dec026e2aa Bump golang.org/x/term from 0.25.0 to 0.26.0 (#1841)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.25.0 to 0.26.0.
- [Commits](https://github.com/golang/term/compare/v0.25.0...v0.26.0)

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-04 18:02:56 +11:00
David Pedersen b5b7b84568 Bump Go to 1.23 (#1832) 2024-11-04 18:01:08 +11:00
David Pedersen fa2fa19ab0 Small optimizations for opts.go (#1831)
* Small optimizations for opts.go

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

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

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

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

* Doc and error message improvement

* Simplify predicated checking of localized sorting.

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

---
updated-dependencies:
- dependency-name: github.com/fsnotify/fsnotify
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-11-02 00:05:18 +11:00
Joe Lim f96a070ff0 Update doc (#1822) 2024-11-01 23:38:01 +11:00
Joe Lim 78413a6c9e cleanup (#1816) 2024-10-22 23:54:49 +11:00
yarikandyarik 6cd51210e3 Add option to hide listBinds when pressing keys (#1815)
* add drawbinds option

* rename drawbinds to showbinds and change its place in docs

* minor changes in wording of showbinds option

* fix missing newlines

---------

Co-authored-by: yarik <dazzywi@github.com>
2024-10-22 23:45:48 +11:00
zenyu 440c258287 Remove redundant initialization for marks and tags (#1811) 2024-10-15 10:14:58 +11:00
Joe Lim 4de690db5e Clear fileinfo if the directory is empty (#1808) 2024-10-11 10:18:13 +11:00
Joe Lim f066df674a Clear error when opening files (#1809) 2024-10-11 10:15:33 +11:00
dependabot[bot] 382095bfb5 Bump golang.org/x/term from 0.24.0 to 0.25.0 (#1803)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.24.0 to 0.25.0.
- [Commits](https://github.com/golang/term/compare/v0.24.0...v0.25.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-10-08 21:04:23 +11:00
Joe Lim 0d4b545390 Remove unnecessary code when sorting by extension (#1805) 2024-10-08 20:54:12 +11:00
Oscar Wallberg 1c56620f57 feat: add mode, user and group info parameters (#1799)
* feat: add mode, user and group info parameters

* fix: correct function names

* fix: change mode to perm
2024-09-14 00:25:26 +10:00
dependabot[bot] e9cb31f2eb Bump golang.org/x/term from 0.23.0 to 0.24.0 (#1797)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.23.0 to 0.24.0.
- [Commits](https://github.com/golang/term/compare/v0.23.0...v0.24.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-09-05 18:15:23 +10:00
Joe Lim 505c4ef6c0 Display line numbers on the main window only (#1789) 2024-08-10 22:39:21 +10:00
dependabot[bot] efde1a2ef3 Bump golang.org/x/sys from 0.23.0 to 0.24.0 (#1788)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.23.0 to 0.24.0.
- [Commits](https://github.com/golang/sys/compare/v0.23.0...v0.24.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-09 23:14:30 +10:00
dependabot[bot] 0f8359f301 Bump golang.org/x/term from 0.22.0 to 0.23.0 (#1785)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.22.0 to 0.23.0.
- [Commits](https://github.com/golang/term/compare/v0.22.0...v0.23.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-07 16:29:22 +10:00
dependabot[bot] b258d8fbf0 Bump golang.org/x/sys from 0.22.0 to 0.23.0 (#1783)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.22.0 to 0.23.0.
- [Commits](https://github.com/golang/sys/compare/v0.22.0...v0.23.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-08-06 09:32:08 +10:00
Joe Lim c2224cb97a Fix printing tags if it contains color (#1782) 2024-07-30 14:46:42 +10:00
dependabot[bot] 534710dcc7 Bump github.com/mattn/go-runewidth from 0.0.15 to 0.0.16 (#1779)
Bumps [github.com/mattn/go-runewidth](https://github.com/mattn/go-runewidth) from 0.0.15 to 0.0.16.
- [Commits](https://github.com/mattn/go-runewidth/compare/v0.0.15...v0.0.16)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-23 13:37:46 +10:00
Joe Lim b819d90be2 Fix clipped icon colors in Windows Terminal (#1777)
* Fix clipped icon colors in Windows Terminal

* Only print components if necessary
2024-07-16 10:30:08 +10:00
Jaehaks 26dc2f1ebd fix(lfcd.cmd) : cd to other drive / fix non-english encoding (#1772)
1) add `/d` to cd command for moving other drive
2) change code page number to read non-english output of `lf -print-last-dir` although current code page is 949
2024-07-08 10:13:42 +10:00
Joe Lim ddea7bff1b Remove deprecated ruler option (#1766)
* Remove deprecated `ruler` option

* Remove unused variable
2024-07-08 10:09:13 +10:00
dependabot[bot] b1f3dbe5ed Bump golang.org/x/term from 0.21.0 to 0.22.0 (#1771)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.21.0 to 0.22.0.
- [Commits](https://github.com/golang/term/compare/v0.21.0...v0.22.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-07-05 17:46:42 +10:00
Joe Lim e9faf966a0 Replace hidecursorinactive with hook commands (#1763)
* Replace `hidecursorinactive` with hook commands

* Remove `focusreport` setting
2024-07-01 12:17:22 +10:00
Joe Lim 67038762cc Invalidate cache for recreated files (#1756)
* Invalidate cache for recreated files

* Sanity check for file updates

* Prevent load when watching

* Revert "Prevent load when watching"

This reverts commit 4cf4629a87.

* Load is redundant when watch is enabled
2024-06-23 10:17:21 +10:00
Joe Lim 38ddfea9a0 Update file info for chmod events with watch mode (#1758) 2024-06-23 08:21:42 +10:00
Joe Lim adaf464fea Update documentation (#1755) 2024-06-22 16:38:52 +10:00
Joe Lim e350e0b735 Use fsnotify for watching file updates (#1667)
* Add watch option

* Implement directory changes

* Implement file changes

* Fix for dircounts

* Remove test code

* fix dircounts

* Set watches on cd instead of select

* Set watches on startup too

* Watch newly created directories

* Add chmod events

* Avoid using multiple threads

Seems to cause issues if there are multiple threads and each one of them
is loading the same new file, in which case there is a race condition.

* Reduce logic when updating files

* Throttle write updates

* Use timer instead of ticker

* Fix file write out-of-band timing issue

* Fix cursor when renaming

* Prevent file showing at bottom during rename

* Watch new directory when created

* Revert "Watch new directory when created"

This reverts commit 6856804313.

* Reapply "Watch new directory when created"

This reverts commit 1c29f34981.

* Try batching renew updates

* Big rewrite

* Reload individual directories

* Change delay to 100 milliseconds

* Use separate goroutine for loading files/dirs

* Fix filter resetting

* Add documentation
2024-06-22 16:29:05 +10:00
Joe Lim 73030b5607 Prevent preview flicker when directories are reloaded (#1697) 2024-06-17 19:27:58 +10:00
Joe Lim 8d7b192340 Prevent image preview flicker when deleting files (#1691) 2024-06-17 19:19:10 +10:00
Catalin Ancutei 791341990c Taking hidden files parameter into account in windows (#1684)
* taking hidden files parameter into account

* Updated doc and removed irelevant linter comment

* fixed doc

* fixed doc again

* Defaulted to empty string on windows
2024-06-17 19:03:29 +10:00
MahouShoujoMivutilde 2d3cc97f78 Use 32KB buffer for copyFile() (reduces copy time by 30%) (#1749)
* Use 32KB buffer for `copyFile()` (reduces copy time by 30%)

This makes `:paste` comparable in performance to `cp --reflink=never`
for large files.

For large number of small files improvements are less substantial
(compared to `cp -r --reflink=never`), though still noticeable.

In both cases the copy takes about 30% less time than with `buf` size at 4096.

32KB is the same number `io.Copy()` uses internally (when it can), and is about where improvements stop.

Context:
https://github.com/gokcehan/lf/issues/1685#issuecomment-2163934296

* Apply suggested changes

* Just delete incomplete an file on all errors

* Mention new progress UI update frequency

* Return the old (each 4MB copied) progress update frequency

(progress UI updates don't seem to impact performance much)
2024-06-14 15:30:23 +10:00
dependabot[bot] 0c72034322 Bump golang.org/x/term from 0.20.0 to 0.21.0 (#1742)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.20.0 to 0.21.0.
- [Commits](https://github.com/golang/term/compare/v0.20.0...v0.21.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-06-05 13:17:36 +10:00
Joe Lim 9b9082a10b Fix image previews containing long lines (#1737)
To reproduce, use `chafa --polite on -f symbols` for an image preview.
2024-06-04 10:09:21 +10:00
Andrew aaf5bbb22b Update lfcd.nu (#1728)
The previous code caused an error telling to use a spread operator
2024-05-26 02:05:37 +10:00
dependabot[bot] 12e99fdb64 Bump golang.org/x/term from 0.19.0 to 0.20.0 (#1703)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.19.0 to 0.20.0.
- [Commits](https://github.com/golang/term/compare/v0.19.0...v0.20.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-05-08 14:20:21 +10:00
Mario D'Andrea a6375d56c6 Remove call to getFileExtension when Lstat fails (#1698) 2024-05-06 11:15:18 +10:00
David Pedersen a018257d50 gofumpt lint and misc cleanup (#1682)
* gofumpt lint and misc cleanup

* Reorder fileInfo dircounts code to be clearer
2024-04-20 21:42:28 +02:00
Daniel Zhang 6cabb0e8e4 Support icon color (#1674)
* Support icon color

* Rename variables

* Test for readArrays

* Add doc and examples for icon color
2024-04-20 21:41:37 +02:00
Joe Lim ce12116418 Run on-quit when terminal closes (#1681) 2024-04-07 15:47:49 +02:00
David Pedersen 63815aaa75 Move get file extension logic to util (#1670)
* Move get file extension logic to util

* Update TestGetFileExtension to use fake file

* Add more test cases to TestGetFileExtension
2024-04-07 15:38:32 +02:00
J-KappesandGökçehan Kara 647fa469fb Rounded Corners (#1653)
* add option to draw outer corners rounded

* gofmt

---------

Co-authored-by: Gökçehan Kara <gokcehankara@gmail.com>
2024-04-07 15:36:54 +02:00
Catalin Ancutei f507b618c9 Added globfilter command (#1650)
* Added globfilter command

* Kept the alphabetical order and applied other sugestions

* Used pandoc to update docs
2024-04-07 15:36:17 +02:00
lorentzforcesandGökçehan Kara 5b108037a3 Use symlink target for stat styling & icons (#566) (#1644)
* use symlink target for stat styling & icons (#566)

Support LS_COLORS/dircolors use of "target" for symlinks to select icons
and styles for them according to the target stat. This mainly applies to
directories - file name-based styles will still be based on the name of
the link, not its target. This mirrors `ls` behavior.

* remove unnecessary debugging and factor out parsePair in color parsing

* move conditional to switch block

* clarify ln target behavior in docs

* run gofmt on single file

---------

Co-authored-by: Gökçehan Kara <gokcehankara@gmail.com>
2024-04-07 15:35:46 +02:00
Catalin Ancutei 21d256d7da unix sockets on windows (#1637)
* Added support for unix sockets on windows

* Keep the fallback port consistent with the one before

* Moved socket check at the bottom of the init function

* Creating the unix socket in temp dir
2024-04-07 15:32:32 +02:00
dependabot[bot] 47634f22bd Bump golang.org/x/term from 0.18.0 to 0.19.0 (#1678)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.18.0 to 0.19.0.
- [Commits](https://github.com/golang/term/compare/v0.18.0...v0.19.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-07 15:31:23 +02:00
dependabot[bot] 448d7b7631 Bump golang.org/x/sys from 0.18.0 to 0.19.0 (#1677)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.18.0 to 0.19.0.
- [Commits](https://github.com/golang/sys/compare/v0.18.0...v0.19.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-04-07 15:18:25 +02:00
Joe Lim 6e6682fc1f Enable focus reporting only for hidecursorinactive (#1676) 2024-04-07 15:17:23 +02:00
Gokcehan d26eb0108a update doc 2024-03-31 21:54:18 +02:00
Joe Lim ac016fee16 Skip drawing UI for period timer (#1666) 2024-03-31 21:19:16 +02:00
David Pedersen 702d67575e Ignore extension when renaming directory (#1664) 2024-03-31 21:19:08 +02:00
Joe Lim 1e10e95f4d Revert "Trigger update after copy/move (#1638)" (#1661)
This reverts commit ddcd308614.
2024-03-26 18:52:14 +11:00
dependabot[bot] c9d28f6e9d Bump dominikh/staticcheck-action from 1.3.0 to 1.3.1 (#1658)
Bumps [dominikh/staticcheck-action](https://github.com/dominikh/staticcheck-action) from 1.3.0 to 1.3.1.
- [Release notes](https://github.com/dominikh/staticcheck-action/releases)
- [Changelog](https://github.com/dominikh/staticcheck-action/blob/master/CHANGES.md)
- [Commits](https://github.com/dominikh/staticcheck-action/compare/v1.3.0...v1.3.1)

---
updated-dependencies:
- dependency-name: dominikh/staticcheck-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-25 15:22:44 +11:00
Joe Lim a1edda1f70 Clear only when cut succeeds (#1652) 2024-03-24 20:13:17 +01:00
valoq ddcd308614 Trigger update after copy/move (#1638)
* trigger update after copy/move

* trigger refresh after returnign from shell

* add renew after returning from shell

* move file update
2024-03-24 20:12:47 +01:00
Michael Gallo 951795c789 Directories added to dirChan no longer trigger checkDir (#1607)
* Directories added to dirChan no longer trigger checkDir

removed unneeded blank line

* removed possibly looping checkReg call
2024-03-24 20:12:35 +01:00
dependabot[bot] c19cc15079 Bump softprops/action-gh-release from 1 to 2 (#1633)
Bumps [softprops/action-gh-release](https://github.com/softprops/action-gh-release) from 1 to 2.
- [Release notes](https://github.com/softprops/action-gh-release/releases)
- [Changelog](https://github.com/softprops/action-gh-release/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/action-gh-release/compare/v1...v2)

---
updated-dependencies:
- dependency-name: softprops/action-gh-release
  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>
2024-03-24 19:43:41 +01:00
Catalin Ancutei 4b076d199b Fixed tags on windows (#1646)
* Fixed tags on windows

* Use the variable text directly in error message
2024-03-18 10:01:00 +11:00
Joe Lim d2136df538 Clear cached sixels after horizontal resize (#1629) 2024-03-10 13:08:38 +11:00
Joe Lim 44c6aead23 Make documentation generating step optional (#1628) 2024-03-09 19:50:02 +01:00
Nuckle 43c2683ca8 Add more file extensions for docker icon (#1626) 2024-03-06 20:02:14 +01:00
dependabot[bot] d89afb8c7d Bump golang.org/x/term from 0.17.0 to 0.18.0 (#1624)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.17.0 to 0.18.0.
- [Commits](https://github.com/golang/term/compare/v0.17.0...v0.18.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-05 17:39:36 +11:00
dependabot[bot] 853bcc524b Bump github.com/gdamore/tcell/v2 from 2.7.1 to 2.7.4 (#1621)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.7.1 to 2.7.4.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv2.md)
- [Commits](https://github.com/gdamore/tcell/compare/v2.7.1...v2.7.4)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-04 17:37:37 +11:00
Joe Lim 055ce47224 Fix crash if tags/marks contains invalid entry (#1614)
* Fix crash if tags file contains invalid entry

* Fix crash if marks file contains invalid entry
2024-03-04 10:11:42 +11:00
Catalin Ancutei 8ee8592b91 avoid using the user.Current on windows to avoid slow startup (#1617)
* avoid using the user.Current on windows to avoid slow startup

* formated os_windows.go
2024-03-03 21:31:12 +01:00
dependabot[bot] 0c02239b17 Bump github.com/gdamore/tcell/v2 from 2.7.0 to 2.7.1 (#1608)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.7.0 to 2.7.1.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Changelog](https://github.com/gdamore/tcell/blob/main/CHANGESv2.md)
- [Commits](https://github.com/gdamore/tcell/compare/v2.7.0...v2.7.1)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-20 13:24:29 +11:00
Joe Lim cf996263bb Export mode for use in scripting keybindings (#1594)
* Export mode

* Add pipe mode

* Add documentation
2024-02-12 10:27:57 +11:00
Joe Lim ab54329570 Dynamically generate list of completions (#1595)
* Dynamically generate list of completions

* Update contribution guide

* Add unit tests
2024-02-12 10:19:17 +11:00
Joe Lim ac32468629 Fix tilde expansion when using setlocal (#1596) 2024-02-12 10:13:13 +11:00
dependabot[bot] d654f09885 Bump golang.org/x/term from 0.16.0 to 0.17.0 (#1601)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.16.0 to 0.17.0.
- [Commits](https://github.com/golang/term/compare/v0.16.0...v0.17.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-02-08 14:29:23 +11:00
Joe Lim 8374080815 Refactor eval code (#1591)
* 1

* globsearch

* hidden

* some more options

* ignorecase and ignoredia

* fix ignorecase/ignoredia

turns out position and loadfile are required here too since the list of
files can change (similar to hidden option)

* incfilter/incsearch

* mouse

* some more options

* preview

* remaining bool options

* fix more options that can change list of files

* Add applyLocalBoolOpt

* Use applyLocalBoolOpt

* Add position and loadfile fixes
2024-02-05 10:29:19 +11:00
M Bakhtiyar Ali 8bbcbdd0ea Update lfcd.nu to support nushell >= 0.87.0 (#1575)
* Update lfcd.nu to support nushell >= 0.87.0 

Deprecated def-env in favor of def --env
https://www.nushell.sh/blog/2023-11-14-nushell_0_87_0.html#deprecated-commands-toc

* Update lfcd.nu using `-print-last-dir` introduced in #1402
2024-02-04 18:38:12 +01:00
Jan Tatje 2007ae51a1 Fallback to showing UID/GID if user/group lookup fails (#1590)
If you mount a filesystem from another computer then UID/GID might
not be mapped to any user. This changes it so that lf shows the UID
and GID instead of nothing if user/group lookup fails.
2024-02-04 18:34:02 +01:00
Joe Lim 8a14749154 Update generated documentation (#1580) 2024-01-18 14:51:04 +11:00
Joe Lim b401318046 Implement sort options as separate variables (#1577) 2024-01-18 11:15:06 +11:00
Joe Lim 6af25565d4 Simplify eval for tempmarks option (#1571) 2024-01-13 13:40:02 +01:00
Joe Lim ce32bc67b9 Add missing completions for nohistory and history! (#1570) 2024-01-13 13:39:26 +01:00
postsolar 27c71f8210 lf.zsh: make completions complete both lf and lfcd (#1564)
* Leave a note on how to add shell completions for `lfcd` in ZSH

* Revert "Leave a note on how to add shell completions for `lfcd` in ZSH"

@joelim-work suggested a better idea: to make `lf.zsh` complete both `lf` and `lfcd`

This reverts commit c28393dd43.

* Make `lf.zsh` complete both `lf` and `lfcd`
2024-01-08 00:00:25 +11:00
dependabot[bot] 43610eaf40 Bump golang.org/x/term from 0.15.0 to 0.16.0 (#1567)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.15.0 to 0.16.0.
- [Commits](https://github.com/golang/term/compare/v0.15.0...v0.16.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-05 14:21:51 +11:00
Joe Lim c88b8eaa65 Update documentation contributing guidelines (#1565)
* Update documentation contributing guidelines

* intentional error

* Revert "intentional error"

This reverts commit f77d2466d6.
2024-01-02 10:02:49 +11:00
Joe Lim f8399eb6e0 Allow customization for cut/copy/select colors (#1540)
* Allow customization for cut/copy/select colors

* Add documentation
2024-01-01 06:35:54 +11:00
Christian Zangl 488294588e generate doc with pandoc in docker (#1555) 2023-12-26 16:16:52 +01:00
Joe Lim 27cbf9403c Reload file info after mark-save/mark-remove (#1544) 2023-12-26 15:58:33 +01:00
Joe Lim 12ce649681 Improve refreshing of file statinfo (#1536) 2023-12-26 15:56:20 +01:00
Michael GalloandJoe Lim e1ab72516d sortMethod simplification. (#1535)
* made sortMethod a string enum to reduce comparisons and repetition

* main uses sortmethod directly instead of converting it into a string

* updated sortmethod validity check to no longer require slices package

* Update opts.go

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

---------

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>
2023-12-26 15:55:42 +01:00
Joe Lim f13325f78d Use string values for go-version (#1534) 2023-12-26 15:42:08 +01:00
David Pedersen a51462dcb9 Show git commit if version information is missing (#1517)
* Show git commit if version information is missing

* Update version command format
2023-12-26 15:41:15 +01:00
Christian Zangl 075caac3a9 Add hidecursorinactive option to indicate status when terminal loses focus (#965)
* Enable focus events through configuration by using focus (option) and on-ui-enter/on-ui-exit events.

* Revert doc

This reverts commit 77f113639f.

* Revert rune evt

This reverts commit 77f113639f.

* hidecursorinactive with tcell

* cleanup

* cleanup
2023-12-26 15:37:11 +01:00
Matthew Toohey 2a4adb323f continue responding to signals after initial sigint (#1549) 2023-12-16 19:26:16 +11:00
Michael Gallo d8b7df87cb normalize now properly uses boolean parameters (#1526) 2023-12-11 15:51:33 +11:00
Joe Lim ec9bdad90d Fix low/high crash for big scrolloff values (#1504) 2023-12-11 15:41:27 +11:00
hankertrix 03b7321938 Update doc.md (#1518)
* Update doc.md

Make the icon and colour configuration file more clear, as the names and locations of both files were not explicitly stated.

* Used a reference to the configuration section instead

Also edited the English for spelling and grammar mistakes.
2023-12-11 15:26:18 +11:00
postsolar e9571ab1d7 Enable completions and add description for lfcd.fish and simplify the code (#1503)
* Enable completions and add description for lfcd.fish

A simple addition of `--wraps=lf` to the function definition will enable the standard lf completions to be used for `lfcd` function as well.

* Simplify lfcd.fish

* lfcd.fish: unquote $argv

* lfcd.fish: further simplify

* lfcd.fish: cd only on clean exit

* lfcd.fish: further simplify and add a coment on quoting semantics

* lfcd.fish: amend comment style
2023-12-11 15:12:30 +11:00
Joshua Li 31f4a4e16f fix basename being . when it is empty (#1525)
* fix basename being `.` when it is empty

* remove unnecessary call of `filepath.Base`
2023-12-11 15:02:07 +11:00
dependabot[bot] cbdae8e7f3 Bump github.com/gdamore/tcell/v2 from 2.6.0 to 2.7.0 (#1533)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.6.0 to 2.7.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.6.0...v2.7.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-11 14:22:15 +11:00
dependabot[bot] ff0ca39a4c Bump actions/setup-go from 4 to 5 (#1527)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 4 to 5.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/setup-go
  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>
2023-12-11 14:02:12 +11:00
dependabot[bot] 6abce04855 Bump golang.org/x/term from 0.14.0 to 0.15.0 (#1511)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.14.0 to 0.15.0.
- [Commits](https://github.com/golang/term/compare/v0.14.0...v0.15.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-28 17:37:44 +11:00
dependabot[bot] 7bd5756330 Bump golang.org/x/sys from 0.14.0 to 0.15.0 (#1510)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.14.0 to 0.15.0.
- [Commits](https://github.com/golang/sys/compare/v0.14.0...v0.15.0)

---
updated-dependencies:
- dependency-name: golang.org/x/sys
  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>
2023-11-28 17:33:03 +11:00
Gökçehan Kara 9698ecddf1 use markdown for the documentation (#1474)
* add doc.md

* use h2 for doc sections

* use h3 for doc commands/options/vars

* use backticks instead of quotes in the doc

* merge multiple commands/options in the doc

* change header levels in the doc

* add man page sections to the doc

* remove extra spaces in headers in the doc

* add man and plain conversions of the doc

* update doc

* add missing flags to the doc

* replace the old documentation with the new one

* remove old doc files

* remove the doc instructions from CONTRIBUTING.md

* change the links to the doc

* shorten long links in the readme
2023-11-12 15:43:06 +01:00
Alexander LunegovandJoe Lim ade9e986e5 Use -print-last-dir option for lfcd.ps1 (#1491)
* Use `-print-last-dir` option for `lfcd.ps1`

* chore(etc/lfcd.ps1): use `Set-Location` instead of `cd`

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

---------

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>
2023-11-08 23:16:01 +11:00
dependabot[bot] ae678f7102 Bump golang.org/x/term from 0.13.0 to 0.14.0 (#1492)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.13.0 to 0.14.0.
- [Commits](https://github.com/golang/term/compare/v0.13.0...v0.14.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-08 18:00:04 +11:00
dependabot[bot] f6e7d0fd0e Bump golang.org/x/sys from 0.13.0 to 0.14.0 (#1486)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.13.0 to 0.14.0.
- [Commits](https://github.com/golang/sys/compare/v0.13.0...v0.14.0)

---
updated-dependencies:
- dependency-name: golang.org/x/sys
  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>
2023-11-06 14:12:15 +11:00
Joe Lim dcd2ea8164 Preserve attributes when moving across devices (#1482) 2023-11-06 13:57:11 +11:00
Joe Lim f52fffbff6 Force sync when writing to cut/copy buffer file (#1480) 2023-10-30 09:40:39 +11:00
Joe Lim b3cb2dc2b4 Add on-redraw hook command (#1479)
* Add `on-redraw` hook command

* Add documentation
2023-10-30 09:40:24 +11:00
Joe Lim 7c23c27c59 Refactor sixel peek in previewer code (#1477) 2023-10-30 09:40:02 +11:00
dependabot[bot] 838fee6f13 Bump github.com/djherbis/times from 1.5.0 to 1.6.0 (#1478)
Bumps [github.com/djherbis/times](https://github.com/djherbis/times) from 1.5.0 to 1.6.0.
- [Release notes](https://github.com/djherbis/times/releases)
- [Commits](https://github.com/djherbis/times/compare/v1.5.0...v1.6.0)

---
updated-dependencies:
- dependency-name: github.com/djherbis/times
  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>
2023-10-29 19:55:30 +01:00
Joe Lim b420dee145 Fix detection of character vs block devices (#1469) 2023-10-22 21:42:12 +02:00
Joe Lim 9ab2c2ec6f Print sixel data to stderr instead of stdout (#1451) 2023-10-22 21:06:19 +02:00
Abderrahmane TAHRI JOUTI 1a3bcb28a1 Use -print-last-dir option for lfcd.cmd (#1444)
* exit lf not the cmd

* exit successfully

* use -print-last-dir
2023-10-22 20:43:03 +02:00
Joe Lim 154d7182c0 Fix preview for files containing long lines (#1447)
* Fix preview for files containing long lines

* Limit lines read to preview window height

* Refactor

* Make comment more clear
2023-10-22 20:37:40 +02:00
Ching Pei Yang b4af8f47c8 doc: Add comments about sixel filler (#1443) 2023-10-22 20:33:19 +02:00
dependabot[bot] beedda2d67 Bump golang.org/x/term from 0.12.0 to 0.13.0 (#1461)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.12.0 to 0.13.0.
- [Commits](https://github.com/golang/term/compare/v0.12.0...v0.13.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-06 15:12:47 +11:00
Joe Lim dddf437c42 Add spaces to rulerfmt to separate from statinfo (#1437) 2023-09-23 11:32:19 +10:00
Gokcehan c8163439f5 move contributing guide to the repo 2023-09-17 14:40:38 +03:00
veltza 6c54b8870c Fix sixel filler character (#1422)
The sixel implementation uses the Braille pattern blank character
(U+2800) as a filler character, which is problematic because U+2800
is not a proper Unicode whitespace character. This fix changes the
filler character to a proper Unicode whitespace character U+2000.

Quote from https://en.wikipedia.org/wiki/Whitespace_character:
"The Braille Patterns Unicode block contains U+2800 BRAILLE PATTERN
BLANK, a Braille pattern with no dots raised. Some fonts display the
character as a fixed-width blank, however the Unicode standard
explicitly states that it does not act as a space."
2023-09-16 16:15:13 +03:00
raslop ffc756c5ff Export user-options on change (#1418)
* Export user-options when they are evaluated

If one has an external previewer that uses an lf user-option (e.g.
"preview-mode") and some key-kindings that change this user-option (e.g.
to "hex", "simple", "fancy") and send a "reload" command to lf, then the
expectation after pressing the keys is, that the prewiever is called
with an updated value of the user-option. Though this did not happen
since #1354, as this caused random crashes.

This change exports user-defined options immediately when they are
evaluated.

* Fix: Add explaining comment
2023-09-11 16:17:42 +03:00
Joe Lim 9068801831 Add query server command to expose internal state (#1384)
* Implement recv mechanism

* Implement recv commands

* Add mutex for state data structure

* Use string to store data instead of byte buffer

* Remove runPagerOn function

* Add history command

* Add documentation

* Add default `maps` command

* Add default `cmds` command

* Reduce locking time

* Remove empty line

* Fix documentation for `recv`

* Add comment about `recv` thread

* Change `recv` to `query`

* Fix comment

* test

* Add comment about connection lifetime

* Map `cmaps` by default
2023-09-08 18:52:19 +10:00
dependabot[bot] c56e319211 Bump actions/checkout from 3 to 4 (#1413)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [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/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  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>
2023-09-05 13:19:00 +10:00
dependabot[bot] a67e43ab66 Bump golang.org/x/term from 0.11.0 to 0.12.0 (#1412)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.11.0 to 0.12.0.
- [Commits](https://github.com/golang/term/compare/v0.11.0...v0.12.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-09-04 15:22:41 +10:00
dependabot[bot] 072818982c Bump golang.org/x/sys from 0.11.0 to 0.12.0 (#1411)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.11.0 to 0.12.0.
- [Commits](https://github.com/golang/sys/compare/v0.11.0...v0.12.0)

---
updated-dependencies:
- dependency-name: golang.org/x/sys
  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>
2023-09-04 15:11:18 +10:00
Gokcehan 1dd269ec42 cleanup 2023-09-03 20:05:46 +03:00
Gokcehan 764fbe65ef cleanup
cc #1409
2023-09-03 20:04:02 +03:00
Gokcehan 1a1537946c add yanking to 'cmd-delete-word[-back]' commands
cc #1409
2023-09-03 19:59:32 +03:00
Jan-Peter Dhallé 791dfff8dc Add cmd-delete-word-back command (#1409)
* add `cmd-delete-word-back`

Implementation of zsh-like backwards word deletion.

* add unixwords option and evaluate, short description in doc

* remove unixwords configuration option

* remove yank, bind delete word back to alt-backspace, update docs

* minor changes to docs

* small fixes
2023-09-03 19:52:07 +03:00
Joe Lim 439fb038e5 Add rulerfmt option for improved ruler customization (#1386)
* Implement basic rulerfmt mechanism

* Add deprecation warning for ruler option

* Implement basic placeholders

* Add placeholder for number of hidden files

* Implement placeholders for options

* Add documentation
2023-09-03 13:31:50 +10:00
Gökçehan Kara 8d013c9375 add 'setlocal' for directory specific options (#1381)
* add 'setlocal' for option 'sortby'

* save each local option separately

* add 'setlocal' for option 'reverse'

* add 'setlocal' for option 'dirfirst'

* add 'setlocal' for option 'hidden'

* add 'setlocal' for option 'dironly'

* add 'setlocal' for option 'info'

* add boolean toggling for 'setlocal' options

* check if the path is absolute for 'setlocal'

* add 'setlocal' options to completion

* add tests for 'setlocal'

* add 'setlocal' to the documentation

* use trailing '/' in 'setlocal' for subdir matching

* cleanup

* add 'setlocal' subdirs to the documentation
2023-09-02 22:22:56 +03:00
Joe Lim 990cea7e04 Display statfmt file size with fixed width (#1405) 2023-09-02 11:55:30 +10:00
Joe Lim 6aa3d2aa18 Add -print-last-dir and -print-selection flags (#1402)
* Add `-print-last-dir` and `-print-selection` flags

* Add shell completions

* Update `lfcd.sh` example to use new flag
2023-08-31 10:10:31 +10:00
Joe Lim 63d21b5a3e Allow lastdir/selection to be written to stdout (#1399)
* Allow lastdir/selection to be written to `stdout`

* Quick fix for runPagerOn
2023-08-28 11:30:16 +10:00
Jan Tatje e0abb29a00 List files even when lstat fails (#1382)
Implements a `fakeStat` struct with dummy values and stores the
error in `file.err`, then shows the error instead of FileInfo, if
the file is inaccesible.

Fixes #1359
2023-08-26 15:58:48 +03:00
Gokcehan a280b6c7d3 remove WIP notice from readme 2023-08-24 22:47:04 +03:00
sitiom 219ebe5c31 Change Winget Releaser job to ubuntu-latest (#1391) 2023-08-19 16:33:02 +03:00
Ching Pei Yang 59dd325439 fix: empty file previews as binary (#1387) 2023-08-14 11:20:48 +10:00
Ching Pei YangandJoe Lim dd8294952f sixel preview (#1211)
* Sixel patch (#1)

* new struct type sixel

* add sixel detection logic in printReg

* new ShowSixels that prints sixels to the screen

* placeholder function UnshowSixels

* run `ui.ShowSixels` after `ui.screen.Sync`

* fix sixel placed on wrong coordinates

* change sixel termination sequence to prevent other escape sequence being run inside it

* process multi-line sixel sequence

* fixed bug where string before sixel image is not printed

* add sixelDimPx and pxToCells

* add getTermPixels for unix

* remove unused method UnshowSixels

* fix: remove unneeded ShowSixels

* add new fields sixel.wPx,hPx and reg.sixels

* modify sixel processing logic

detecting sixels in preview script now fills corresponding area with braille blank `\u2800` and saves sixel to reg.sixels

* modify sixel processing logic

printReg doesn't process sixels directly anymore

* reset sixels buffer at the start of `draw`

* rename `ui.ShowSixels` to `showSixels`

* add constants `gSixelBegin` and `gSixelTerminate`

* add check to prevent arbitrary escape code being passed to stdin

* fix cursor out of place in command line mode

* fix bug where sixel in drawn at old location after horizontal resize

* add ui.wPx and ui.hPx

* buffer sixel sequences before printing

* add check for valid terminal size(px) before previewing sixel

* clean up

* placeholder function getTermPixels for windows

* function sixelDimPx now considers image size given in the optional raster attributes field

* change sixel image alignment to emulate behavior of a terminal
- images used to always draw on a new line
- images is now placed where it starts:
```
printf 'abc <sixel sequence> xyz'
```
would result in:
```
abc +------+
    | img  |
    | here |
    +------+
xyz
```

old behavior:
```
abc
+------+
| img  |
| here |
+------+
xyz
```

* fix bug where raster attributes are wrongly parsed in sixelDimPx

* prevent drawing sixels while menu is active

* introduce sixelScreen struct and refactor screen width,height in px to use new struct

* fix prevent nested sixel sequences

* fix bug where rejected sixels cause indexing error

* add "alternating filler" to trick tcell into redrawing when switching between different images

* fix filler string wrongly indented

* add comment

* replace pxToCells() with sixelScreen.pxToCells()

* add trim sixel height during preview

* add tests for trimSixelHeight

* prevent sixel redrawing during input prompts

* change sixel filler to braille space

* clean up

* use strings.Index instead of regex for simple search

* fix comment

* refactor: remove nested if-block

* refactor: move sixel related stuff into sixel.go

* remove unused function

* allow long lines from previewer

* rework preview to accept only single-line sixels

- multi-line support removed for simplicity in the code base

* add new option `sixel`

* add eval logic and completion of `sixel` option

* doc: new option 'sixel'

* refactor: use newSixelScreen() for init

* fix bug where image is not always cleared

* refactor: separate sixel tests

* improved error handling

* rename & comments for clarity

* refactor: renderPreviewLine should not use gOpts

* rename for clarity

* fix: filler style changed more than needed

The filler style now only changes when the file in preview is changed

* rename

* fix: forgot to rename this

* increase max line size

* remove unneeded reassignment

* fix position of multiple sixel on same line

* refactor: extract code into function

* update docs

* reorder variable

* remove unneeded var

* avoid unneeded ioctl calls

* fixup! fix typo

* rework/simplify previewing sixels

Remove support for multiple sixels on the same line, and the line must start with 'ESC P' to be considered a sixel.

* separate sixel detection logic from text scanning

* rework: stricter sixel validation and remove trimming

* revert unneeded changes

* strip validation logic

* refactor: use singular sixel instead of slice

multiple sixel preview is no longer supported

* fix: bug where first 2 char of non-sixel is missing

* docs: fix wrong option type

* set sixelScreen.wpx, hpx to 0 on error

* remove terminal px size

* fix: bug where quitting might leave terminal in bold

cleanup

* update docs

* remove unneeded sixel type

* cleanup unused func argument

* cleanup unneeded function

* refactor: more readable

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

* cleanup unneeded var

* cleanup unneeded constructor

* cleanup unused func arg

---------

Co-authored-by: Joe Lim <50560759+joelim-work@users.noreply.github.com>
2023-08-12 18:52:01 +03:00
dependabot[bot] b2f8673cb9 Bump golang.org/x/term from 0.10.0 to 0.11.0 (#1373)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.10.0 to 0.11.0.
- [Commits](https://github.com/golang/term/compare/v0.10.0...v0.11.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-08-07 18:08:33 +10:00
dependabot[bot] 687ac4b23c Bump golang.org/x/sys from 0.10.0 to 0.11.0 (#1372)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.10.0 to 0.11.0.
- [Commits](https://github.com/golang/sys/compare/v0.10.0...v0.11.0)

---
updated-dependencies:
- dependency-name: golang.org/x/sys
  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>
2023-08-07 18:02:30 +10:00
Joe Lim 1c52e3ad68 Wrap filenames in quotes only for Windows CMD (#1371) 2023-08-07 17:56:14 +10:00
Joe Lim b3ac207c34 Fix cursor location when printing statline (#1348)
* Fix cursor location when printing statline

* Reset style after shell output

* cleanup
2023-08-07 17:43:54 +10:00
Joe Lim 2620f492c2 Remove environment exports from preview thread (#1354) 2023-07-27 10:09:51 +10:00
dependabot[bot] 95b3613a68 Bump github.com/mattn/go-runewidth from 0.0.14 to 0.0.15 (#1351)
Bumps [github.com/mattn/go-runewidth](https://github.com/mattn/go-runewidth) from 0.0.14 to 0.0.15.
- [Commits](https://github.com/mattn/go-runewidth/compare/v0.0.14...v0.0.15)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-24 22:00:17 +10:00
Jonáš Dujava 42c16f1882 Clean image preview on set preview! (#1350)
Properly clean (`ueberzug`) image preview when disabling it using
for example `set preview!`.

Also change "clearing" to "cleaning" in docs.
2023-07-22 14:24:35 +03:00
Joe Lim 23418adc00 Support optional fields for statfmt option (#1337)
* Support optional fields for `statfmt` option

* Add documentation

* Use special bytes for safety
2023-07-17 11:03:09 +10:00
Joe Lim 443838e06f Call load after shell-async commands (#1345) 2023-07-17 10:19:04 +10:00
mauerlaeufer 3c681c2fac Added autocompletion and a simple lfcd script for nushell. (#1341)
* Added autocompletion and a simple lfcd script for nushell.

* nu-lfcd script & small style improvements. Moved the autocompletion to a seperate file.

* Update lfcd.nu to print to stderr instead of stdout

* Fixed the comments inside lf.nu
2023-07-16 18:30:35 +03:00
Joe Lim a3127a2dc3 Merge pull request #1335 from joelim-work/load-non-volatile
Prevent image preview flicker for `load` command
2023-07-12 08:54:36 +10:00
Joe Lim a7541390f3 Merge pull request #1336 from joelim-work/ci-badge
Add CI build badge
2023-07-12 08:54:19 +10:00
Gokcehan ac40dddfa1 update doc
cc #1324
2023-07-11 22:21:36 +03:00
Joe Lim ddb86396ab Add CI build badge 2023-07-07 01:49:42 +10:00
Joe Lim b98ef3f935 Prevent image preview flicker for load command 2023-07-06 21:27:00 +10:00
dependabot[bot] 2f3c170d1b Bump golang.org/x/term from 0.9.0 to 0.10.0
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.9.0 to 0.10.0.
- [Commits](https://github.com/golang/term/compare/v0.9.0...v0.10.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-05 21:17:41 -07:00
dependabot[bot] dc2627de23 Bump golang.org/x/sys from 0.9.0 to 0.10.0
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.9.0 to 0.10.0.
- [Commits](https://github.com/golang/sys/compare/v0.9.0...v0.10.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-04 23:31:03 -07:00
David Pedersen f20d0e5fb4 Make duplicated file format configurable (#1315)
* Make duplicated file format configurable

* Add %b and %f options to dupfilefmt
2023-07-04 12:29:24 +03:00
Joe Lim 835c5b35e2 Prevent following symbolic links when reloading (#1327) 2023-07-04 12:26:34 +03:00
Joe Lim 592e7fe4be Improve windows shell handling (#1309)
* Improve windows shell handling

* Add shell in command line

* Fix shellopts bug

* Add quote string

* Refactor `exportFiles` function

* Add defaults for Windows

* Revert "Add defaults for Windows"

Accidental commit

This reverts commit 5ff32650fe.

* Separate handling for CMD vs PowerShell

* Add case insensitive check
2023-07-03 17:31:45 +03:00
Joe Lim 56ab5ccc61 Allow blank input lines for shell-pipe commands (#1308) 2023-07-03 14:25:20 +03:00
Gokcehan 067ffa8f1a add support for LF_CONFIG/DATA_HOME on unix
cc #1209 #1253
2023-07-03 14:14:56 +03:00
Joe Lim bc0bc6e3be Remove test log statement during autocompletion (#1307) 2023-07-03 13:41:58 +03:00
dependabot[bot] 807d2f5f2d Bump golang.org/x/term from 0.8.0 to 0.9.0 (#1304)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.8.0 to 0.9.0.
- [Commits](https://github.com/golang/term/compare/v0.8.0...v0.9.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-07-03 13:41:10 +03:00
Ilya Grigoriev c11931d3e6 Make CI cross-compile lf for every supported platform; support darwin-arm64 (#1298)
* Create CI job to run `gen/xbuild.sh`, adjust `xbuild.sh` to make it possible

This reworks the gen/xbuild.sh script to exit with a failure if any of the targets don't compile. It also adds a CI job to try cross-compiling for every platform on every pull request.

The new check is a little slow and compute-expensive, but I am hoping it's well within the quota.

See #1299 for a demo of how the CI would have failed after #1288 and before #1295.

Screenshot: https://github.com/gokcehan/lf/assets/4123047/3d7a6b7c-8642-4d4c-a98a-c8b886c0b184

Thanks to @joelim-work for numerous improvements and an alternate
implementation I heavily borrowed from
(https://github.com/joelim-work/lf/blob/ci/gen/xbuild.sh)

* Refactor xbuild.sh some more to decrease repetition

I can remove this commit if people prefer.

* Generate darwin-arm64 binaries as we have users using it

Arm Macs are becoming popular. We have at least one
user: https://github.com/gokcehan/lf/issues/1294. It
seems lf works fine there.
2023-07-03 13:08:12 +03:00
raslop b1a851953b Flexible filename truncation (#1029)
* allow flexible truncation of filenames

As of now, lf truncates always at the end. So for long filenames one can
not see the end (especially not the file ending, like .jpeg or .pdf).

[MidnightCommander](https://github.com/MidnightCommander/mc/) truncates
too long filenames in the middle, so it's possible to see the beginning
and the end of the too long filename.

This commit allows to specify a flexible point for the truncation in
percent of the available space.

* The default value of 100 for the new `truncatepct` option means no
change in lf behaviour.

* More adhering to naming convention.

* Improve error message for invalid `truncatepct` values.

* Remove redundant test cases.

* FIXUP Add dummy empty line to make `go fmt` happy.

* Avoid explicit "cast" to rune array.

* fix(doc.go): remove line with single dot

This was there to avoid that `go fmt` touches the next item with `waitmsg`.
However, removing the spaces before the example list items has the same
effect.
2023-07-03 12:48:51 +03:00
Joe Lim e885abe1a3 Fix formatting of nlink on other platforms (#1295) 2023-06-10 11:50:02 +03:00
Joe Lim 2ab4b14e88 Add statfmt option (#1288)
* Add `fileinfofmt` option

* echof is now unused

* Use different default for Windows

* Add new line to docs

* Indent placeholders description in documentation

* Change option name to `statfmt`

* Use plain text format for documentation
2023-06-09 14:45:35 +03:00
Joe Lim 59f32193ae Fix load issue when deleting files (#1292) 2023-06-08 19:38:23 +03:00
Joe Lim 07cf7dd1bd Bound cursor position after terminal resize (#1290) 2023-06-08 17:17:32 +03:00
Joe Lim 027538eabf Avoid refreshing previews for shell pipe commands (#1281) 2023-06-04 19:04:29 +03:00
Joe Lim 2c13e0d7d6 Add clearmaps command (#1286) 2023-06-04 18:56:39 +03:00
Joe Lim c874a2c56f Add doc to default keybindings in documentation (#1285) 2023-06-04 18:54:06 +03:00
Gokcehan 751788ee84 cleanup
cc #1279
2023-06-04 18:39:43 +03:00
Joe Lim 51d0fec017 Simplify run pager function (#1279)
* Simplify run pager function

* RunPagerOn
2023-06-04 18:38:38 +03:00
Joe Lim 7c33da2bc2 Refactor filename truncation code (#1272)
* Refactor filename truncation code

* Another refactor
2023-06-04 16:25:50 +03:00
Joe Lim 014d18d3ea Fix runeSliceWidthRange implementation (#1273)
* Fix `runeSliceWidthRange` implementation

* Add empty test case
2023-06-04 16:22:46 +03:00
Joe Lim c3d44123bb Fix typo in misc tests (#1270) 2023-06-04 16:19:39 +03:00
Munif Tanjim 14fb8a0aac Update icons.example for nerd-font v3 release (#1271)
ref: https://github.com/ryanoasis/nerd-fonts/releases/tag/v3.0.0
2023-06-04 16:16:54 +03:00
Jonáš Dujava 06d0a7eeac Disallow exiting from 'filter' mode with backspace (#1269) 2023-06-04 16:14:19 +03:00
Ilya Grigoriev 9e1edcd9d3 No-op nesting reduction (#1266) 2023-06-04 16:06:58 +03:00
Ilya Grigoriev b57d76bf97 cmds command to list all custom commands (aka cmd mappings) (#1265)
This is a natural complement to the recently introduces `maps` and `cmaps`.

I considered using a different output format, since `cmd` definitions can be
long, but I decided against it for now. `lf` already abbreviates commands that
take up several lines, and we can change the output format later if needed.
2023-06-04 16:05:13 +03:00
Joe Lim a9d90bc560 Cleanup import of times package (#1262) 2023-05-24 12:34:59 +03:00
Joe Lim ae1c1389dd Fix stable sort when reverse option is enabled (#1261) 2023-05-24 12:34:00 +03:00
Joe Lim e08eebb115 Add support for displaying lf options in the ruler (#1257)
* Add support for displaying lf options in the ruler

* Print escape character as plain text

* Document user defined options

* Change escape rules

* Use reflect instead of environment table

* Factor out common option map logic

* Improve error message slightly

* Display blank option values
2023-05-24 12:30:38 +03:00
Gokcehan 0ac1491bfb cleanup
cc #1026
2023-05-21 19:41:41 +03:00
raslop fdb320d30c preserve mtime when copying files (#1026)
* make it possible to preserve mtime and atime when copying files

Preserving other attributes like ownership, ctime or btime of a file is
desired but currently not possible to implement in a portable way with go.

Fixes #869
Relates to #779

* FIXUP use cp-compatible default for not-preserving mode
2023-05-21 19:41:01 +03:00
Joe Lim 24bba6288d Bound cursor position when selecting file (#1247) 2023-05-21 15:14:43 +03:00
Joe Lim 5b934c2b91 Expand tilde during autocompletion (#1246) 2023-05-21 15:09:28 +03:00
Ilya Grigoriev 346c439f76 Refactor pager commands & synchronous shell commands (no-op) (#1243)
* Refactor piping to pager: extract to separate function, simplify invocation

This is meant to be straightforward and clearly a no-op,\
at the cost of being a bit verbose.

* Refactor: reduce duplication between sync shell commands and pager

* Refactor: minor cleanup of async shell functions

After the previous refactors, the logic for async shell commands can
be simplified somewhat. There is likely room for further improvements,
but that is beyond the scope of this PR.

* Remove duplicated shellSetPG invocation

See https://github.com/gokcehan/lf/pull/1243#discussion_r1193078282
2023-05-21 15:08:49 +03:00
Gokcehan 5bf78dc087 cleanup
cc #1253
2023-05-21 01:57:39 +03:00
Alok Mishra 8fee7f0927 LF_CONFIG_HOME environment variable (#1253)
* Added LF_CONFIG_HOME environment variable

* Added and generated documentation for LF_CONFIG_HOME
2023-05-21 01:53:55 +03:00
Joe Lim 3b942a8a39 Support custom colors for drawbox characters (#1251) 2023-05-20 17:53:05 +03:00
Joe Lim 1be7d2689a Support modifiers in special key mappings (#1248)
* Support modifiers in mappings

* Update docs

* Support cmap keybindings as well

* Implement push

* Move order of escape key check

* Add safety check

* Fix safety check

* Factor out common logic
2023-05-20 17:37:39 +03:00
Joe Lim 88b3c999af Fix count when parsing bottom command (#1240)
* Fix count when parsing `bottom` command

* Revert "Fix count when parsing `bottom` command"

This reverts commit a0b6bb5a13.

* Alternate implementation

* Add comment
2023-05-13 16:58:21 +03:00
Joe Lim 24e224ca65 Add jumps command for displaying the jump list (#1233)
* Add `jumps` command for displaying the jump list

* Mention jump count in documentation

* Reverse order
2023-05-13 16:43:08 +03:00
Joe Lim 2a5c54c81a Minor cleanup of reflect code (#1229) 2023-05-13 16:30:19 +03:00
dependabot[bot] db46fb2b37 Bump golang.org/x/term from 0.7.0 to 0.8.0 (#1225)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.7.0 to 0.8.0.
- [Commits](https://github.com/golang/term/compare/v0.7.0...v0.8.0)

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-13 16:28:33 +03:00
dependabot[bot] f036e07a5c Bump golang.org/x/sys from 0.7.0 to 0.8.0 (#1224)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.7.0 to 0.8.0.
- [Commits](https://github.com/golang/sys/compare/v0.7.0...v0.8.0)

---
updated-dependencies:
- dependency-name: golang.org/x/sys
  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>
2023-05-13 16:18:31 +03:00
Joe Lim 8f630e0cab Separate filter from selections in the ui ruler (#1223) 2023-05-13 14:19:50 +03:00
Joe Lim 35990bed12 Prevent scrolling to bottom when selecting files (#1222)
* Prevent scrolling to bottom when selecting files

* Use nav.currDir()
2023-05-13 13:58:03 +03:00
Gokcehan f04401ba4d build diskfree on all platforms
cc #1168
2023-04-30 22:10:15 +03:00
56 changed files with 9897 additions and 7169 deletions

No files matched your search

+27 -12
View File
@@ -8,20 +8,20 @@ on:
jobs:
build:
tests:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: 1.18
go-version: "1.23"
- name: Build
run: go build -v ./...
@@ -29,23 +29,38 @@ jobs:
- name: Test
run: go test -v ./...
- uses: dominikh/staticcheck-action@v1.3.0
- uses: dominikh/staticcheck-action@v1.3.1
with:
version: "2022.1.3"
version: "2024.1.1"
install-go: false
generate:
cross-compile:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: 1.19
go-version: "1.23"
- name: Test `go fmt && go generate` on Go 1.19 creates no diffs
run: go fmt && go generate && git diff --exit-code
- name: Cross-compile on all supported platforms
run: gen/xbuild.sh
formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Test `go fmt` creates no diffs
run: go fmt && git diff --exit-code
+5 -5
View File
@@ -10,25 +10,25 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v4
uses: actions/setup-go@v5
with:
go-version: 1.18
go-version: "1.23"
- name: Build
run: gen/xbuild.sh
- name: Release
uses: softprops/action-gh-release@v1
uses: softprops/action-gh-release@v2
with:
files: dist/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
winget:
runs-on: windows-latest # Action can only run on Windows
runs-on: ubuntu-latest
needs: build
steps:
- uses: vedantmgoyal2009/winget-releaser@v2
+50
View File
@@ -0,0 +1,50 @@
# Contributing
Code contributions are always welcomed in lf.
If you are going to introduce a new feature, it is best to open an issue first for discussion. If your feature can be implemented as a configuration option **please add it to the [wiki](https://github.com/gokcehan/lf/wiki)**.
For bug fixes, you can simply send a pull request.
## Code conventions
In addition to `gofmt` and friends (e.g. [go vet](https://pkg.go.dev/cmd/vet), [staticcheck](https://staticcheck.dev/), [golangci-lint](https://golangci-lint.run/)), we have a few conventions:
- Global variables are best avoided except when they are not.
Global variable names are prefixed with `g` as in `gFooBar`.
Exceptions are variables holding values of environmental variables which are prefixed with `env` as in `envFooBar` and regular expressions which are prefixed with `re` as in `reFooBar` when they are global.
- Type and function names are small case as in `fooBar` since we don't use exporting.
- For file name variables, `name`, `fname`, or `filename` should refer to the base name of the file as in `baz.txt`, and `path`, `fpath`, or `filepath` should refer to the full path of the file as in `/foo/bar/baz.txt`.
- Run `go fmt` to ensure that files are formatted correctly.
Use the surrounding code as reference when in doubt as usual.
## Adding a new option
Adding a new option usually requires the following steps:
- Add option name/type to `gOpts` struct in `opts.go`
- Add default option value to `init` function in `opts.go`
- 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
- Commit your changes and send a pull request
## Adding a new builtin command
Adding a new command usually requires the following steps:
- Add default key if any to `init` function in `opts.go`
- Add command evaluation logic to `callExpr.eval` in `eval.go`
- 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
- 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.
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.
+6 -7
View File
@@ -1,16 +1,15 @@
# LF
[Google Groups](https://groups.google.com/forum/#!forum/lf-fm)
| [Doc](doc.md)
| [Wiki](https://github.com/gokcehan/lf/wiki)
| [#lf](https://web.libera.chat/#lf) (on Libera.Chat)
| [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge)
[![Go Build](https://github.com/gokcehan/lf/actions/workflows/go.yml/badge.svg)](https://github.com/gokcehan/lf/actions/workflows/go.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf)
[![Go Reference](https://pkg.go.dev/badge/github.com/gokcehan/lf.svg)](https://pkg.go.dev/github.com/gokcehan/lf)
> This is a work in progress. Use at your own risk.
`lf` (as in "list files") is a terminal file manager written in Go with a heavy inspiration from ranger file manager.
`lf` (as in "list files") is a terminal file manager written in Go with a heavy inspiration from [`ranger`](https://github.com/ranger/ranger) file manager.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts.
![multicol-screenshot](http://i.imgur.com/DaTUenu.png)
@@ -25,7 +24,7 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tut
- Server/client architecture and remote commands to manage multiple instances
- Extendable and configurable with shell commands
- Customizable keybindings (vi and readline defaults)
- A reasonable set of other features (see the [documentation](https://pkg.go.dev/github.com/gokcehan/lf))
- A reasonable set of other features (see the [documentation](doc.md))
## Non-Features
@@ -67,7 +66,7 @@ After the installation `lf` command should start the application in the current
Run `lf -help` to see command line options.
Run `lf -doc` to see the [documentation](https://pkg.go.dev/github.com/gokcehan/lf).
Run `lf -doc` to see the [documentation](doc.md).
See [etc](etc) directory to integrate `lf` to your shell and/or editor.
Example configuration files along with example colors and icons files can also be found in this directory.
@@ -78,4 +77,4 @@ See [tips](https://github.com/gokcehan/lf/wiki/Tips) for more examples.
## Contributing
See [contributing](https://github.com/gokcehan/lf/wiki/Contributing) for guidelines.
See [contributing](CONTRIBUTING.md) for guidelines.
+126 -103
View File
@@ -33,6 +33,9 @@ type app struct {
menuCompActive bool
menuComps []string
menuCompInd int
selectionOut []string
watch *watch
quitting bool
}
func newApp(ui *ui, nav *nav) *app {
@@ -43,18 +46,20 @@ func newApp(ui *ui, nav *nav) *app {
nav: nav,
ticker: new(time.Ticker),
quitChan: quitChan,
watch: newWatch(nav.dirChan, nav.fileChan, nav.delChan),
}
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM)
go func() {
switch <-sigChan {
case os.Interrupt:
return
case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
app.quit()
os.Exit(3)
return
for {
switch <-sigChan {
case os.Interrupt:
case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
app.quit()
os.Exit(3)
return
}
}
}()
@@ -62,6 +67,16 @@ func newApp(ui *ui, nav *nav) *app {
}
func (app *app) quit() {
// Using synchronous shell commands for `on-quit` can cause this to be
// called again, so a guard variable is introduced here to prevent an
// infinite loop.
if app.quitting {
return
}
app.quitting = true
onQuit(app)
if gOpts.history {
if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err)
@@ -163,6 +178,7 @@ func saveFiles(list []string, cp bool) error {
fmt.Fprintln(files, f)
}
files.Sync()
return nil
}
@@ -227,7 +243,7 @@ func (app *app) writeHistory() error {
}
for _, cmd := range app.cmdHistory {
_, err = f.WriteString(fmt.Sprintf("%s %s\n", cmd.prefix, cmd.value))
_, err = fmt.Fprintf(f, "%s %s\n", cmd.prefix, cmd.value)
if err != nil {
return fmt.Errorf("writing history file: %s", err)
}
@@ -317,10 +333,6 @@ func (app *app) loop() {
continue
}
if cmd, ok := gOpts.cmds["on-quit"]; ok {
cmd.eval(app, nil)
}
app.quit()
app.nav.previewChan <- ""
@@ -328,24 +340,11 @@ func (app *app) loop() {
log.Print("bye!")
if gLastDirPath != "" {
f, err := os.Create(gLastDirPath)
if err != nil {
log.Printf("opening last dir file: %s", err)
}
defer f.Close()
_, err = f.WriteString(app.nav.currDir().path)
if err != nil {
log.Printf("writing last dir file: %s", err)
}
}
return
case n := <-app.nav.copyBytesChan:
app.nav.copyBytes += n
// n is usually 4096B so update roughly per 4096B x 1024 = 4MB copied
if app.nav.copyUpdate++; app.nav.copyUpdate >= 1024 {
// n is usually 32*1024B (default io.Copy() buffer) so update roughly per 32KB x 128 = 4MB copied
if app.nav.copyUpdate++; app.nav.copyUpdate >= 128 {
app.nav.copyUpdate = 0
app.ui.draw(app.nav)
}
@@ -389,19 +388,24 @@ func (app *app) loop() {
}
app.ui.draw(app.nav)
case d := <-app.nav.dirChan:
app.nav.checkDir(d)
if gOpts.dircache {
prev, ok := app.nav.dirCache[d.path]
if ok {
d.ind = prev.ind
d.pos = prev.pos
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 {
oldCurrPath = curr.path
}
for i := range app.nav.dirs {
if app.nav.dirs[i].path == d.path {
app.nav.dirs[i] = d
@@ -412,9 +416,9 @@ func (app *app) loop() {
curr, err := app.nav.currFile()
if err == nil {
if d.path == app.nav.currDir().path {
if curr.path != oldCurrPath {
app.ui.loadFile(app, true)
if app.ui.msg == "" {
if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav)
}
}
@@ -423,10 +427,10 @@ func (app *app) loop() {
}
}
app.watchDir(d)
app.ui.draw(app.nav)
case r := <-app.nav.regChan:
app.nav.checkReg(r)
app.nav.regCache[r.path] = r
curr, err := app.nav.currFile()
@@ -437,6 +441,37 @@ func (app *app) loop() {
}
app.ui.draw(app.nav)
case f := <-app.nav.fileChan:
for _, dir := range app.nav.dirCache {
if dir.path != filepath.Dir(f.path) {
continue
}
for i := range dir.allFiles {
if dir.allFiles[i].path == f.path {
dir.allFiles[i] = f
break
}
}
name := dir.name()
dir.sort()
dir.sel(name, app.nav.height)
}
app.ui.loadFile(app, false)
if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav)
}
app.ui.draw(app.nav)
case path := <-app.nav.delChan:
delete(app.nav.dirCache, path)
delete(app.nav.regCache, path)
delete(app.nav.selections, path)
if len(app.nav.selections) == 0 {
app.nav.selectionInd = 0
}
case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev, app.nav)
if e == nil {
@@ -466,7 +501,6 @@ func (app *app) loop() {
case <-app.ticker.C:
app.nav.renew()
app.ui.loadFile(app, false)
app.ui.draw(app.nav)
case <-app.nav.previewTimer.C:
app.nav.previewLoading = true
app.ui.draw(app.nav)
@@ -474,9 +508,30 @@ func (app *app) loop() {
}
}
type cleanFunc func()
func (app *app) runCmdSync(cmd *exec.Cmd, pause_after bool) {
app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
var noopCleanFunc = func() {}
if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err)
}
defer func() {
if err := app.ui.resume(); err != nil {
app.quit()
os.Exit(3)
}
}()
if err := cmd.Run(); err != nil {
app.ui.echoerrf("running shell: %s", err)
}
if pause_after {
anyKey()
}
app.ui.loadFile(app, true)
app.nav.renew()
}
// This function is used to run a shell command. Modes are as follows:
//
@@ -485,60 +540,38 @@ var noopCleanFunc = func() {}
// % No No Yes Yes Yes Statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing
// $| No No Pipe Yes Yes Pause, Pipe execute, return cleanup to resume
func (app *app) runShell(s string, args []string, prefix string) cleanFunc {
func (app *app) runShell(s string, args []string, prefix string) {
app.nav.exportFiles()
app.ui.exportSizes()
app.ui.exportMode()
exportOpts()
gState.mutex.Lock()
gState.data["maps"] = listBinds(gOpts.keys).String()
gState.data["cmaps"] = listBinds(gOpts.cmdkeys).String()
gState.data["cmds"] = listCmds().String()
gState.data["jumps"] = listJumps(app.nav.jumpList, app.nav.jumpListInd).String()
gState.data["history"] = listHistory(app.cmdHistory).String()
gState.mutex.Unlock()
cmd := shellCommand(s, args)
var out io.Reader
var err error
switch prefix {
case "$|":
var stdin io.WriteCloser
stdin, err = cmd.StdinPipe()
if err != nil {
log.Printf("writing stdin: %s", err)
}
app.cmdIn = stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err)
}
err = cmd.Start()
case "$", "!":
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
app.runCmdSync(cmd, prefix == "!")
return
}
if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err)
}
defer func() {
if err := app.ui.resume(); err != nil {
app.quit()
os.Exit(3)
return
}
}()
defer app.nav.renew()
err = cmd.Run()
case "%":
shellSetPG(cmd)
// We are running the command asynchronously
if prefix == "%" {
if app.ui.cmdPrefix == ">" {
return noopCleanFunc
return
}
stdin, err := cmd.StdinPipe()
if err != nil {
@@ -551,27 +584,13 @@ func (app *app) runShell(s string, args []string, prefix string) cleanFunc {
}
out = stdout
cmd.Stderr = cmd.Stdout
fallthrough
case "&":
shellSetPG(cmd)
err = cmd.Start()
}
if err != nil {
shellSetPG(cmd)
if err = cmd.Start(); err != nil {
app.ui.echoerrf("running shell: %s", err)
}
switch prefix {
case "!":
anyKey()
}
// Asynchronous shell invocations return immediately without waiting for the
// command to finish, so there is no point refreshing the preview if nothing
// has changed yet.
volatile := prefix != "&"
app.ui.loadFile(app, volatile)
switch prefix {
case "%":
normal(app)
@@ -614,18 +633,22 @@ func (app *app) runShell(s string, args []string, prefix string) cleanFunc {
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
app.ui.exprChan <- &callExpr{"load", nil, 1}
}()
case "$|":
return func() {
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
app.nav.renew()
if err := app.ui.resume(); err != nil {
app.quit()
os.Exit(3)
}
}
}
func (app *app) watchDir(dir *dir) {
if !gOpts.watch {
return
}
app.watch.add(dir.path)
// ensure dircounts are updated for child directories
for _, file := range dir.allFiles {
if file.IsDir() {
app.watch.add(file.path)
}
}
return noopCleanFunc
}
+79 -13
View File
@@ -8,11 +8,23 @@ import (
"net"
"os"
"strings"
"sync"
"time"
"github.com/gdamore/tcell/v2"
)
type State struct {
mutex sync.Mutex
data map[string]string
}
var gState State
func init() {
gState.data = make(map[string]string)
}
func run() {
var screen tcell.Screen
var err error
@@ -26,7 +38,7 @@ func run() {
}
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
panic(err)
}
@@ -46,14 +58,6 @@ func run() {
app.ui.echoerrf("sync: %s", err)
}
if err := app.nav.readMarks(); err != nil {
app.ui.echoerrf("reading marks file: %s", err)
}
if err := app.nav.readTags(); err != nil {
app.ui.echoerrf("reading tags file: %s", err)
}
if err := app.readHistory(); err != nil {
app.ui.echoerrf("reading history file: %s", err)
}
@@ -61,13 +65,59 @@ func run() {
app.loop()
app.ui.screen.Fini()
if gLastDirPath != "" {
writeLastDir(gLastDirPath, app.nav.currDir().path)
}
if gSelectionPath != "" && len(app.selectionOut) > 0 {
writeSelection(gSelectionPath, app.selectionOut)
}
if gPrintLastDir {
fmt.Println(app.nav.currDir().path)
}
if gPrintSelection && len(app.selectionOut) > 0 {
for _, file := range app.selectionOut {
fmt.Println(file)
}
}
}
func writeLastDir(filename string, lastDir string) {
f, err := os.Create(filename)
if err != nil {
log.Printf("opening last dir file: %s", err)
return
}
defer f.Close()
_, err = f.WriteString(lastDir)
if err != nil {
log.Printf("writing last dir file: %s", err)
}
}
func writeSelection(filename string, selection []string) {
f, err := os.Create(filename)
if err != nil {
log.Printf("opening selection file: %s", err)
return
}
defer f.Close()
_, err = f.WriteString(strings.Join(selection, "\n"))
if err != nil {
log.Printf("writing selection file: %s", err)
}
}
func readExpr() <-chan expr {
ch := make(chan expr)
go func() {
duration := 1 * time.Second
duration := 100 * time.Millisecond
c, err := net.Dial(gSocketProt, gSocketPath)
for err != nil {
@@ -80,13 +130,29 @@ func readExpr() <-chan expr {
fmt.Fprintf(c, "conn %d\n", gClientID)
ch <- &callExpr{"sync", nil, 1}
ch <- &callExpr{"on-init", nil, 1}
s := bufio.NewScanner(c)
for s.Scan() {
log.Printf("recv: %s", s.Text())
p := newParser(strings.NewReader(s.Text()))
if p.parse() {
ch <- p.expr
// `query` has to be handled outside of the main thread, which is
// blocked when running a synchronous shell command ("$" or "!").
// This is important since `query` is often the result of the user
// running `$lf -remote "query $id <something>"`.
if word, rest := splitWord(s.Text()); word == "query" {
gState.mutex.Lock()
state, ok := gState.data[rest]
gState.mutex.Unlock()
if ok {
fmt.Fprint(c, state)
}
fmt.Fprintln(c, "")
} else {
p := newParser(strings.NewReader(s.Text()))
if p.parse() {
ch <- p.expr
}
}
}
+57 -42
View File
@@ -10,10 +10,16 @@ import (
"github.com/gdamore/tcell/v2"
)
type styleMap map[string]tcell.Style
type styleMap struct {
styles map[string]tcell.Style
useLinkTarget bool
}
func parseStyles() styleMap {
sm := make(styleMap)
sm := styleMap{
styles: make(map[string]tcell.Style),
useLinkTarget: false,
}
// Default values from dircolors
//
@@ -81,10 +87,18 @@ 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 applyAnsiCodes(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";")
var nums []int
nums := make([]int, 0, len(toks))
for _, tok := range toks {
if tok == "" {
nums = append(nums, 0)
@@ -101,7 +115,8 @@ func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
// ECMA-48 details the standard
// TODO: should we support turning off attributes?
// Probably because this is used for previewers too
for i := 0; i < len(nums); i++ {
numslen := len(nums)
for i := 0; i < numslen; i++ {
n := nums[i]
switch {
case n == 0:
@@ -129,10 +144,10 @@ func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
case n >= 90 && n <= 97:
st = st.Foreground(tcell.PaletteColor(n - 82))
case n == 38:
if i+3 <= len(nums) && nums[i+1] == 5 {
if i+3 <= numslen && nums[i+1] == 5 {
st = st.Foreground(tcell.PaletteColor(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
} else if i+5 <= numslen && nums[i+1] == 2 {
st = st.Foreground(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
@@ -146,10 +161,10 @@ func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
case n >= 100 && n <= 107:
st = st.Background(tcell.PaletteColor(n - 92))
case n == 48:
if i+3 <= len(nums) && nums[i+1] == 5 {
if i+3 <= numslen && nums[i+1] == 5 {
st = st.Background(tcell.PaletteColor(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
} else if i+5 <= numslen && nums[i+1] == 2 {
st = st.Background(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
@@ -183,20 +198,12 @@ func (sm styleMap) parseFile(path string) {
}
for _, pair := range pairs {
key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
sm[key] = applyAnsiCodes(val, tcell.StyleDefault)
sm.parsePair(pair)
}
}
// This function parses $LS_COLORS environment variable.
func (sm styleMap) parseGNU(env string) {
func (sm *styleMap) parseGNU(env string) {
for _, entry := range strings.Split(env, ":") {
if entry == "" {
continue
@@ -209,18 +216,26 @@ func (sm styleMap) parseGNU(env string) {
return
}
key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
sm[key] = applyAnsiCodes(val, tcell.StyleDefault)
sm.parsePair(pair)
}
}
func (sm *styleMap) parsePair(pair []string) {
key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
if key == "ln" && val == "target" {
sm.useLinkTarget = true
}
sm.styles[key] = applyAnsiCodes(val, tcell.StyleDefault)
}
// This function parses $LSCOLORS environment variable.
func (sm styleMap) parseBSD(env string) {
if len(env) != 22 {
@@ -259,17 +274,17 @@ func (sm styleMap) parseBSD(env string) {
}
for i, key := range colorNames {
sm[key] = getStyle(env[i*2], env[i*2+1])
sm.styles[key] = getStyle(env[i*2], env[i*2+1])
}
}
func (sm styleMap) get(f *file) tcell.Style {
if val, ok := sm[f.path]; ok {
if val, ok := sm.styles[f.path]; ok {
return val
}
if f.IsDir() {
if val, ok := sm[f.Name()+"/"]; ok {
if val, ok := sm.styles[f.Name()+"/"]; ok {
return val
}
}
@@ -277,13 +292,13 @@ func (sm styleMap) get(f *file) tcell.Style {
var key string
switch {
case f.linkState == working:
case f.linkState == working && !sm.useLinkTarget:
key = "ln"
case f.linkState == broken:
key = "or"
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0o002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&0002 != 0:
case f.IsDir() && f.Mode()&0o002 != 0:
key = "ow"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
@@ -293,39 +308,39 @@ func (sm styleMap) get(f *file) tcell.Style {
key = "pi"
case f.Mode()&os.ModeSocket != 0:
key = "so"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0:
key = "su"
case f.Mode()&os.ModeSetgid != 0:
key = "sg"
case f.Mode()&0111 != 0:
case f.Mode()&0o111 != 0:
key = "ex"
}
if val, ok := sm[key]; ok {
if val, ok := sm.styles[key]; ok {
return val
}
if val, ok := sm[f.Name()+"*"]; ok {
if val, ok := sm.styles[f.Name()+"*"]; ok {
return val
}
if val, ok := sm["*"+f.Name()]; ok {
if val, ok := sm.styles["*"+f.Name()]; ok {
return val
}
if val, ok := sm[filepath.Base(f.Name())+".*"]; ok {
if val, ok := sm.styles[filepath.Base(f.Name())+".*"]; ok {
return val
}
if val, ok := sm["*"+strings.ToLower(f.ext)]; ok {
if val, ok := sm.styles["*"+strings.ToLower(f.ext)]; ok {
return val
}
if val, ok := sm["fi"]; ok {
if val, ok := sm.styles["fi"]; ok {
return val
}
+51 -113
View File
@@ -4,6 +4,7 @@ import (
"log"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
)
@@ -11,10 +12,9 @@ import (
var (
gCmdWords = []string{
"set",
"setlocal",
"map",
"maps",
"cmap",
"cmaps",
"cmd",
"quit",
"up",
@@ -41,6 +41,7 @@ var (
"glob-select",
"glob-unselect",
"calcdirsize",
"clearmaps",
"copy",
"cut",
"paste",
@@ -103,118 +104,52 @@ var (
"cmd-word",
"cmd-word-back",
"cmd-delete-word",
"cmd-delete-word-back",
"cmd-capitalize-word",
"cmd-uppercase-word",
"cmd-lowercase-word",
}
gOptWords = []string{
"anchorfind",
"noanchorfind",
"anchorfind!",
"autoquit",
"noautoquit",
"autoquit!",
"cursoractivefmt",
"cursorparentfmt",
"cursorpreviewfmt",
"dircache",
"nodircache",
"dircache!",
"dircounts",
"nodircounts",
"dircounts!",
"dirfirst",
"nodirfirst",
"dirfirst!",
"dironly",
"nodironly",
"dironly!",
"dirpreviews",
"nodirpreviews",
"dirpreviews!",
"drawbox",
"nodrawbox",
"drawbox!",
"globsearch",
"noglobsearch",
"globsearch!",
"hidden",
"nohidden",
"hidden!",
"icons",
"noicons",
"icons!",
"ignorecase",
"noignorecase",
"ignorecase!",
"ignoredia",
"noignoredia",
"ignoredia!",
"incsearch",
"noincsearch",
"incsearch!",
"incfilter",
"noincfilter",
"incfilter!",
"mouse",
"nomouse",
"mouse!",
"number",
"nonumber",
"number!",
"preview",
"nopreview",
"preview!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"reverse",
"noreverse",
"reverse!",
"ruler",
"smartcase",
"nosmartcase",
"smartcase!",
"smartdia",
"nosmartdia",
"smartdia!",
"waitmsg",
"wrapscan",
"nowrapscan",
"wrapscan!",
"wrapscroll",
"nowrapscroll",
"wrapscroll!",
"findlen",
"period",
"scrolloff",
"tabstop",
"errorfmt",
"filesep",
"hiddenfiles",
"history",
"ifs",
"info",
"numberfmt",
"previewer",
"cleaner",
"promptfmt",
"ratios",
"selmode",
"shell",
"shellflag",
"shellopts",
"sortby",
"timefmt",
"tempmarks",
"tagfmt",
"infotimefmtnew",
"infotimefmtold",
"truncatechar",
}
gOptWords = getOptWords(gOpts)
gLocalOptWords = getLocalOptWords(gLocalOpts)
)
func getOptWords(opts any) (optWords []string) {
t := reflect.TypeOf(opts)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
switch field.Type.Kind() {
case reflect.Map:
continue
case reflect.Bool:
name := field.Name
optWords = append(optWords, name, "no"+name, name+"!")
default:
optWords = append(optWords, field.Name)
}
}
sort.Strings(optWords)
return
}
func getLocalOptWords(localOpts any) (localOptWords []string) {
t := reflect.TypeOf(localOpts)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
name := strings.TrimSuffix(field.Name, "s")
if field.Type.Kind() != reflect.Map {
continue
}
if field.Type.Elem().Kind() == reflect.Bool {
localOptWords = append(localOptWords, name, "no"+name, name+"!")
} else {
localOptWords = append(localOptWords, name)
}
}
sort.Strings(localOptWords)
return
}
func matchLongest(s1, s2 []rune) []rune {
i := 0
for ; i < len(s1) && i < len(s2); i++ {
@@ -276,14 +211,13 @@ func matchExec(s string) (matches []string, longest []rune) {
continue
}
log.Print(finfo.Name())
words = append(words, finfo.Name())
}
}
sort.Strings(words)
if len(words) > 0 {
sort.Strings(words)
uniq := words[:1]
for i := 1; i < len(words); i++ {
if words[i] != words[i-1] {
@@ -333,7 +267,7 @@ func matchFile(s string) (matches []string, longest []rune) {
if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
}
name = escape(name)
name = escape(replaceTilde(name))
item := f.Name()
if f.Mode().IsDir() {
@@ -360,7 +294,8 @@ func matchFile(s string) (matches []string, longest []rune) {
}
func matchCmd(s string) (matches []string, longest []rune) {
words := gCmdWords
words := make([]string, 0, len(gCmdWords)+len(gOpts.cmds))
words = append(words, gCmdWords...)
for c := range gOpts.cmds {
words = append(words, c)
}
@@ -400,6 +335,9 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
}
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", "cmap":
matches, longest = matchCmd(f[2])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
@@ -409,7 +347,7 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
}
default:
switch f[0] {
case "set", "map", "cmap", "cmd":
case "set", "setlocal", "map", "cmap", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
+38
View File
@@ -54,3 +54,41 @@ func TestMatchWord(t *testing.T) {
}
}
}
func TestGetOptWords(t *testing.T) {
tests := []struct {
opts any
exp []string
}{
{struct{ feature bool }{}, []string{"feature", "feature!", "nofeature"}},
{struct{ feature int }{}, []string{"feature"}},
{struct{ feature string }{}, []string{"feature"}},
{struct{ feature []string }{}, []string{"feature"}},
}
for _, test := range tests {
result := getOptWords(test.opts)
if !reflect.DeepEqual(result, test.exp) {
t.Errorf("at input '%#v' expected '%s' but got '%s'", test.opts, test.exp, result)
}
}
}
func TestGetLocalOptWords(t *testing.T) {
tests := []struct {
localOpts any
exp []string
}{
{struct{ features map[string]bool }{}, []string{"feature", "feature!", "nofeature"}},
{struct{ features map[string]int }{}, []string{"feature"}},
{struct{ features map[string]string }{}, []string{"feature"}},
{struct{ features map[string][]string }{}, []string{"feature"}},
}
for _, test := range tests {
result := getLocalOptWords(test.localOpts)
if !reflect.DeepEqual(result, test.exp) {
t.Errorf("at input '%#v' expected '%s' but got '%s'", test.localOpts, test.exp, result)
}
}
}
+62 -27
View File
@@ -5,8 +5,30 @@ import (
"io"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/djherbis/times"
)
type ProgressWriter struct {
writer io.Writer
nums chan<- int64
}
func NewProgressWriter(writer io.Writer, nums chan<- int64) *ProgressWriter {
return &ProgressWriter{
writer: writer,
nums: nums,
}
}
func (progressWriter *ProgressWriter) Write(b []byte) (int, error) {
n, err := progressWriter.writer.Write(b)
progressWriter.nums <- int64(n)
return n, err
}
func copySize(srcs []string) (int64, error) {
var total int64
@@ -16,14 +38,13 @@ func copySize(srcs []string) (int64, error) {
return total, fmt.Errorf("src does not exist: %q", src)
}
err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
err = filepath.Walk(src, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk: %s", err)
}
total += info.Size()
return nil
})
if err != nil {
return total, err
}
@@ -32,8 +53,17 @@ func copySize(srcs []string) (int64, error) {
return total, nil
}
func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
buf := make([]byte, 4096)
func copyFile(src, dst string, preserve []string, info os.FileInfo, nums chan int64) error {
var dst_mode os.FileMode = 0o666
preserve_timestamps := false
for _, s := range preserve {
switch s {
case "timestamps":
preserve_timestamps = true
case "mode":
dst_mode = info.Mode()
}
}
r, err := os.Open(src)
if err != nil {
@@ -41,28 +71,16 @@ func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
}
defer r.Close()
w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode())
w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, dst_mode)
if err != nil {
return err
}
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
w.Close()
os.Remove(dst)
return err
}
if n == 0 {
break
}
if _, err := w.Write(buf[:n]); err != nil {
return err
}
nums <- int64(n)
_, err = io.Copy(NewProgressWriter(w, nums), r)
if err != nil {
w.Close()
os.Remove(dst)
return err
}
if err := w.Close(); err != nil {
@@ -70,22 +88,39 @@ func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
return err
}
if preserve_timestamps {
ts := times.Get(info)
mtime := info.ModTime()
atime := ts.AccessTime()
if err := os.Chtimes(dst, atime, mtime); err != nil {
os.Remove(dst)
return err
}
}
return nil
}
func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
func copyAll(srcs []string, dstDir string, preserve []string) (nums chan int64, errs chan error) {
nums = make(chan int64, 1024)
errs = make(chan error, 1024)
go func() {
for _, src := range srcs {
dst := filepath.Join(dstDir, filepath.Base(src))
file := filepath.Base(src)
dst := filepath.Join(dstDir, file)
_, err := os.Lstat(dst)
lstat, err := os.Lstat(dst)
if !os.IsNotExist(err) {
ext := getFileExtension(lstat)
basename := file[:len(file)-len(ext)]
var newPath string
for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i)
file = strings.ReplaceAll(gOpts.dupfilefmt, "%f", basename+ext)
file = strings.ReplaceAll(file, "%b", basename)
file = strings.ReplaceAll(file, "%e", ext)
file = strings.ReplaceAll(file, "%n", strconv.Itoa(i))
newPath = filepath.Join(dstDir, file)
_, err = os.Lstat(newPath)
}
dst = newPath
@@ -117,7 +152,7 @@ func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
}
nums <- info.Size()
} else {
if err := copyFile(path, newPath, info, nums); err != nil {
if err := copyFile(path, newPath, preserve, info, nums); err != nil {
errs <- fmt.Errorf("copy: %s", err)
}
}
+19
View File
@@ -0,0 +1,19 @@
package main
import (
"log"
"golang.org/x/sys/unix"
)
func diskFree(wd string) string {
var stat unix.Statfs_t
if err := unix.Statfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.F_bavail)*uint64(stat.F_bsize)))
}
+21
View File
@@ -0,0 +1,21 @@
//go:build darwin || dragonfly || freebsd || linux
package main
import (
"log"
"golang.org/x/sys/unix"
)
func diskFree(wd string) string {
var stat unix.Statfs_t
if err := unix.Statfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize)))
}
+21
View File
@@ -0,0 +1,21 @@
//go:build illumos || netbsd || solaris
package main
import (
"log"
"golang.org/x/sys/unix"
)
func diskFree(wd string) string {
var stat unix.Statvfs_t
if err := unix.Statvfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize)))
}
+23
View File
@@ -0,0 +1,23 @@
package main
import (
"log"
"golang.org/x/sys/windows"
)
func diskFree(wd string) string {
var free uint64
pathPtr, err := windows.UTF16PtrFromString(wd)
if err != nil {
log.Printf("diskfree: %s", err)
return ""
}
err = windows.GetDiskFreeSpaceEx(pathPtr, &free, nil, nil) // cwd, free, total, available
if err != nil {
log.Printf("diskfree: %s", err)
return ""
}
return "df: " + humanize(int64(free))
}
+36 -42
View File
@@ -1,51 +1,45 @@
package main
import (
"strconv"
"unicode"
)
var normMap = map[rune]rune{
// lowercase (not only) european
'ě': 'e', 'ř': 'r', 'ů': 'u', 'ø': 'o', 'ĉ': 'c', 'ĝ': 'g', 'ĥ': 'h', 'ĵ': 'j', 'ŝ': 's',
'ŭ': 'u', 'è': 'e', 'ù': 'u', 'ÿ': 'y', 'ė': 'e', 'į': 'i', 'ų': 'u', 'ā': 'a', 'ē': 'e',
'ī': 'i', 'ū': 'u', 'ļ': 'l', 'ķ': 'k', 'ņ': 'n', 'ģ': 'g', 'ő': 'o', 'ű': 'u', 'ë': 'e',
'ï': 'i', 'ą': 'a', 'ć': 'c', 'ę': 'e', 'ł': 'l', 'ń': 'n', 'ś': 's', 'ź': 'z', 'ż': 'z',
'õ': 'o', 'ș': 's', 'ț': 't', 'č': 'c', 'ď': 'd', 'ĺ': 'l', 'ľ': 'l', 'ň': 'n', 'ŕ': 'r',
'š': 's', 'ť': 't', 'ý': 'y', 'ž': 'z', 'é': 'e', 'í': 'i', 'ñ': 'n', 'ó': 'o', 'ú': 'u',
'ü': 'u', 'å': 'a', 'ä': 'a', 'ö': 'o', 'ç': 'c', 'î': 'i', 'ş': 's', 'û': 'u', 'ğ': 'g',
'ă': 'a', 'â': 'a', 'đ': 'd', 'ê': 'e', 'ô': 'o', 'ơ': 'o', 'ư': 'u', 'á': 'a', 'à': 'a',
'ã': 'a', 'ả': 'a', 'ạ': 'a',
// uppercase (not only) european
'Ě': 'E', 'Ř': 'R', 'Ů': 'U', 'Ø': 'O', 'Ĉ': 'C', 'Ĝ': 'G', 'Ĥ': 'H', 'Ĵ': 'J', 'Ŝ': 'S',
'Ŭ': 'U', 'È': 'E', 'Ù': 'U', 'Ÿ': 'Y', 'Ė': 'E', 'Į': 'I', 'Ų': 'U', 'Ā': 'A', 'Ē': 'E',
'Ī': 'I', 'Ū': 'U', 'Ļ': 'L', 'Ķ': 'K', 'Ņ': 'N', 'Ģ': 'G', 'Ő': 'O', 'Ű': 'U', 'Ë': 'E',
'Ï': 'I', 'Ą': 'A', 'Ć': 'C', 'Ę': 'E', 'Ł': 'L', 'Ń': 'N', 'Ś': 'S', 'Ź': 'Z', 'Ż': 'Z',
'Õ': 'O', 'Ș': 'S', 'Ț': 'T', 'Č': 'C', 'Ď': 'D', 'Ĺ': 'L', 'Ľ': 'L', 'Ň': 'N', 'Ŕ': 'R',
'Š': 'S', 'Ť': 'T', 'Ý': 'Y', 'Ž': 'Z', 'É': 'E', 'Í': 'I', 'Ñ': 'N', 'Ó': 'O', 'Ú': 'U',
'Ü': 'U', 'Å': 'A', 'Ä': 'A', 'Ö': 'O', 'Ç': 'C', 'Î': 'I', 'Ş': 'S', 'Û': 'U', 'Ğ': 'G',
'Ă': 'A', 'Â': 'A', 'Đ': 'D', 'Ê': 'E', 'Ô': 'O', 'Ơ': 'O', 'Ư': 'U', 'Á': 'A', 'À': 'A',
'Ã': 'A', 'Ả': 'A', 'Ạ': 'A',
var normMap map[rune]rune
func init() {
normMap = make(map[rune]rune)
// (not only) european
appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
)
// Vietnamese
appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
)
// lowercase Vietnamese
'ắ': 'a', 'ặ': 'a', 'ằ': 'a', 'ẳ': 'a', 'ẵ': 'a', 'ấ': 'a', 'ậ': 'a', 'ầ': 'a', 'ẩ': 'a',
'ẫ': 'a', 'ẹ': 'e', 'ẻ': 'e', 'ẽ': 'e', 'ế': 'e', 'ệ': 'e', 'ề': 'e', 'ể': 'e', 'ễ': 'e',
'i': 'i', 'ị': 'i', 'ì': 'i', 'ỉ': 'i', 'ĩ': 'i', 'o': 'o', 'ọ': 'o', 'ò': 'o', 'ỏ': 'o',
'ố': 'o', 'ộ': 'o', 'ồ': 'o', 'ổ': 'o', 'ỗ': 'o', 'ớ': 'o', 'ợ': 'o', 'ờ': 'o', 'ở': 'o',
'ỡ': 'o', 'ụ': 'u', 'ủ': 'u', 'ũ': 'u', 'ứ': 'u', 'ự': 'u', 'ừ': 'u', 'ử': 'u', 'ữ': 'u',
'y': 'y', 'ỵ': 'y', 'ỳ': 'y', 'ỷ': 'y', 'ỹ': 'y',
// uppercase Vietnamese
'Ắ': 'A', 'Ặ': 'A', 'Ằ': 'A', 'Ẳ': 'A', 'Ẵ': 'A', 'Ấ': 'A', 'Ậ': 'A', 'Ầ': 'A', 'Ẩ': 'A',
'Ẫ': 'A', 'Ẹ': 'E', 'Ẻ': 'E', 'Ẽ': 'E', 'Ế': 'E', 'Ệ': 'E', 'Ề': 'E', 'Ể': 'E', 'Ễ': 'E',
'I': 'I', 'Ị': 'I', 'Ì': 'I', 'Ỉ': 'I', 'Ĩ': 'I', 'O': 'O', 'Ọ': 'O', 'Ò': 'O', 'Ỏ': 'O',
'Ố': 'O', 'Ộ': 'O', 'Ồ': 'O', 'Ổ': 'O', 'Ỗ': 'O', 'Ớ': 'O', 'Ợ': 'O', 'Ờ': 'O', 'Ở': 'O',
'Ỡ': 'O', 'Ụ': 'U', 'Ủ': 'U', 'Ũ': 'U', 'Ứ': 'U', 'Ự': 'U', 'Ừ': 'U', 'Ử': 'U', 'Ữ': 'U',
'Y': 'Y', 'Ỵ': 'Y', 'Ỳ': 'Y', 'Ỷ': 'Y', 'Ỹ': 'Y',
}
func appendTransliterate(base, norm string) {
normRunes := []rune(norm)
baseRunes := []rune(base)
lenNorm := len(normRunes)
lenBase := len(baseRunes)
if lenNorm != lenBase {
panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length
}
for i := 0; i < lenBase; i++ {
normMap[baseRunes[i]] = normRunes[i]
baseUpper := unicode.ToUpper(baseRunes[i])
normUpper := unicode.ToUpper(normRunes[i])
normMap[baseUpper] = normUpper
}
}
// Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string {
var normalizedRunes []rune
normalizedRunes := make([]rune, 0, len(baseString))
for _, baseRune := range baseString {
if normRune, ok := normMap[baseRune]; ok {
normalizedRunes = append(normalizedRunes, normRune)
+2 -2
View File
@@ -13,7 +13,7 @@ func TestRemoveDiacritics(t *testing.T) {
expStr := "Prilis zlutoucky kun priserne upel dabelske ody"
checkRemoveDiacritics(testStr, expStr, t)
// other accents (non comlete, but all I founded)
// other accents (non complete, but all I found)
testStr = "áéíóúýčďěňřšťžůåøĉĝĥĵŝŭšžõäöüàâçéèêëîïôùûüÿžščćđáéíóúąęėįųūčšžāēīūčšžļķņģáéíóúöüőűäöüëïąćęłńóśźżáàãâçéêíóõôăâîșțáäčďéíĺľňóôŕšťúýžáéíñóúüåäöâçîşûğăâđêôơưáàãảạ"
expStr = "aeiouycdenrstzuaocghjsuszoaouaaceeeeiiouuuyzsccdaeiouaeeiuucszaeiucszlkngaeiouououaoueiacelnoszzaaaaceeioooaaistaacdeillnoorstuyzaeinouuaaoacisugaadeoouaaaaa"
checkRemoveDiacritics(testStr, expStr, t)
@@ -61,7 +61,7 @@ func runSearch(t *testing.T, ignorecase, smartcase, ignorediacritics, smartdiacr
gOpts.smartcase = smartcase
gOpts.ignoredia = ignorediacritics
gOpts.smartdia = smartdiacritics
matched, _ := searchMatch(base, pattern)
matched, _ := searchMatch(base, pattern, false)
if matched != expected {
t.Errorf("False search for" +
" ignorecase = " + strconv.FormatBool(gOpts.ignorecase) + ", " +
-1657
View File
File diff suppressed because it is too large. Load diff
+1854
View File
File diff suppressed because it is too large. Load diff
+2101
View File
File diff suppressed because it is too large. Load diff
-1810
View File
File diff suppressed because it is too large. Load diff
+26 -6
View File
@@ -35,6 +35,22 @@ sg g # SETGID
ex  # EXEC
fi  # FILE
# disable some default filetype icons, let them choose icon by filename
# ln  # LINK
# or  # ORPHAN
# tw # STICKY_OTHER_WRITABLE
# ow # OTHER_WRITABLE
# st # STICKY
# di  # DIR
# pi # FIFO
# so # SOCK
# bd # BLK
# cd # CHR
# su # SETUID
# sg # SETGID
# ex # EXEC
# fi  # FILE
# file extensions (vim-devicons)
*.styl 
*.sass 
@@ -87,7 +103,7 @@ fi  # FILE
*.cc 
*.cp 
*.c 
*.cs
*.cs 󰌛
*.h 
*.hh 
*.hpp 
@@ -152,10 +168,10 @@ fi  # FILE
*.elm 
*.swift 
*.xcplayground 
*.tex ﭨ
*.r ﳒ
*.rproj 鉶
*.sol ﲹ
*.tex 󰙩
*.r 󰟔
*.rproj 󰗆
*.sol 󰡪
*.pem 
# file names (vim-devicons) (case-insensitive not supported in lf)
@@ -188,12 +204,15 @@ fi  # FILE
*procfile 
*dockerfile 
*docker-compose.yml 
*docker-compose.yaml 
*compose.yml 
*compose.yaml 
*rakefile 
*config.ru 
*gemfile 
*makefile 
*cmakelists.txt 
*robots.txt ﮧ
*robots.txt 󰚩
# file names (case-sensitive adaptations)
*Gruntfile.coffee 
@@ -209,6 +228,7 @@ fi  # FILE
*Procfile 
*Dockerfile 
*Docker-compose.yml 
*Docker-compose.yaml 
*Rakefile 
*Gemfile 
*Makefile 
+377
View File
@@ -0,0 +1,377 @@
# vim:ft=conf
# These examples require Nerd Fonts or a compatible font to be used.
# See https://www.nerdfonts.com for more information.
# default values from lf (with matching order)
# ln l # LINK
# or l # ORPHAN
# tw t # STICKY_OTHER_WRITABLE
# ow d # OTHER_WRITABLE
# st t # STICKY
# di d # DIR
# pi p # FIFO
# so s # SOCK
# bd b # BLK
# cd c # CHR
# su u # SETUID
# sg g # SETGID
# ex x # EXEC
# fi - # FILE
# file types (with matching order)
ln  # LINK
or  # ORPHAN
tw t # STICKY_OTHER_WRITABLE
ow  # OTHER_WRITABLE
st t # STICKY
di  # DIR
pi p # FIFO
so s # SOCK
bd b # BLK
cd c # CHR
su u # SETUID
sg g # SETGID
ex  # EXEC
fi  # FILE
# disable some default filetype icons, let them choose icon by filename
# ln  # LINK
# or  # ORPHAN
# tw # STICKY_OTHER_WRITABLE
# ow # OTHER_WRITABLE
# st # STICKY
# di  # DIR
# pi # FIFO
# so # SOCK
# bd # BLK
# cd # CHR
# su # SETUID
# sg # SETGID
# ex # EXEC
# fi  # FILE
# file extensions (vim-devicons)
*.styl  00;38;2;141;193;73
*.sass  00;38;2;245;83;133
*.scss  00;38;2;245;83;133
*.htm  00;38;2;227;76;38
*.html  00;38;2;227;76;38
*.slim  00;38;2;227;76;38
*.haml  00;38;2;234;234;225
*.ejs  00;38;2;203;203;65
*.css  00;38;2;86;61;124
*.less  00;38;2;86;61;124
*.md  00;38;2;81;154;186
*.mdx  00;38;2;81;154;186
*.markdown  00;38;2;81;154;186
*.rmd  00;38;2;81;154;186
*.json  00;38;2;149;157;165
*.webmanifest  00;38;2;241;224;90
*.js  00;38;2;203;203;65
*.mjs  00;38;2;241;224;90
*.jsx  00;38;2;81;154;186
*.rb  00;38;2;112;21;22
*.gemspec  00;38;2;112;21;22
*.rake  00;38;2;112;21;22
*.php  00;38;2;160;116;196
*.py  00;38;2;81;154;186
*.pyc  00;38;2;81;154;186
*.pyo  00;38;2;81;154;186
*.pyd  00;38;2;81;154;186
*.coffee  00;38;2;203;203;65
*.mustache  00;38;2;227;121;51
*.hbs  00;38;2;240;119;43
*.conf  00;38;2;109;128;134
*.ini  00;38;2;109;128;134
*.yml  00;38;2;149;157;165
*.yaml  00;38;2;149;157;165
*.toml  00;38;2;109;128;134
*.bat  00;38;2;193;241;46
*.mk  00;38;2;109;128;134
*.jpg  00;38;2;160;116;196
*.jpeg  00;38;2;160;116;196
*.bmp  00;38;2;160;116;196
*.png  00;38;2;160;116;196
*.webp  00;38;2;160;116;196
*.gif  00;38;2;160;116;196
*.ico  00;38;2;203;203;65
*.twig  00;38;2;141;193;73
*.cpp  00;38;2;81;154;186
*.c++  00;38;2;89;158;255
*.cxx  00;38;2;81;154;186
*.cc  00;38;2;81;154;186
*.cp  00;38;2;81;154;186
*.c  00;38;2;89;158;255
*.cs 󰌛 00;38;2;89;103;6
*.h  00;38;2;160;116;196
*.hh  00;38;2;160;116;196
*.hpp  00;38;2;160;116;196
*.hxx  00;38;2;160;116;196
*.hs  00;38;2;160;116;196
*.lhs  00;38;2;160;116;196
*.nix  00;38;2;126;186;228
*.lua  00;38;2;81;160;207
*.java  00;38;2;204;62;68
*.sh  00;38;2;137;224;81
*.fish  00;38;2;137;224;81
*.bash  00;38;2;137;224;81
*.zsh  00;38;2;137;224;81
*.ksh  00;38;2;137;224;81
*.csh  00;38;2;137;224;81
*.awk  00;38;2;137;224;81
*.ps1  00;38;2;137;224;81
*.ml λ 00;38;2;227;121;51
*.mli λ 00;38;2;227;121;51
*.diff  00;38;2;65;83;91
*.db  00;38;2;218;216;216
*.sql  00;38;2;218;216;216
*.dump  00;38;2;218;216;216
*.clj  00;38;2;141;193;73
*.cljc  00;38;2;141;193;73
*.cljs  00;38;2;81;154;186
*.edn  00;38;2;81;154;186
*.scala  00;38;2;204;62;68
*.go  00;38;2;81;154;186
*.dart  00;38;2;3;88;156
*.xul  00;38;2;227;121;51
*.sln  00;38;2;133;76;199
*.suo  00;38;2;133;76;199
*.pl  00;38;2;81;154;186
*.pm  00;38;2;81;154;186
*.t  00;38;2;81;154;186
*.rss  00;38;2;251;157;59
'*.f#'  00;38;2;81;154;186
*.fsscript  00;38;2;81;154;186
*.fsx  00;38;2;81;154;186
*.fs  00;38;2;81;154;186
*.fsi  00;38;2;81;154;186
*.rs  00;38;2;222;165;132
*.rlib  00;38;2;222;165;132
*.d  00;38;2;66;120;25
*.erl  00;38;2;184;57;152
*.hrl  00;38;2;184;57;152
*.ex  00;38;2;160;116;196
*.exs  00;38;2;160;116;196
*.eex  00;38;2;160;116;196
*.leex  00;38;2;160;116;196
*.heex  00;38;2;160;116;196
*.vim  00;38;2;1;152;51
*.ai  00;38;2;203;203;65
*.psd  00;38;2;81;154;186
*.psb  00;38;2;81;154;186
*.ts  00;38;2;81;154;186
*.tsx  00;38;2;81;154;186
*.jl  00;38;2;162;112;186
*.pp  00;38;2;255;166;26
*.vue  00;38;2;141;193;73
*.elm  00;38;2;81;154;186
*.swift  00;38;2;227;121;51
*.xcplayground  00;38;2;227;121;51
*.tex 󰙩 00;38;2;61;97;23
*.r 󰟔 00;38;2;53;138;91
*.rproj 󰗆 00;38;2;53;138;91
*.sol 󰡪 00;38;2;81;154;186
*.pem  00;38;2;205;155;62
# file names (vim-devicons) (case-insensitive not supported in lf)
*gruntfile.coffee  00;38;2;227;121;51
*gruntfile.js  00;38;2;227;121;51
*gruntfile.ls  00;38;2;227;121;51
*gulpfile.coffee  00;38;2;204;62;68
*gulpfile.js  00;38;2;204;62;68
*gulpfile.ls  00;38;2;204;62;68
*mix.lock  00;38;2;160;116;196
*dropbox  00;38;2;0;97;254
*.ds_store  00;38;2;77;90;94
*.gitconfig  00;38;2;65;83;91
*.gitignore  00;38;2;65;83;91
*.gitattributes  00;38;2;65;83;91
*.gitlab-ci.yml  00;38;2;226;67;41
*.bashrc  00;38;2;137;224;81
*.zshrc  00;38;2;137;224;81
*.zshenv  00;38;2;137;224;81
*.zprofile  00;38;2;137;224;81
*.vimrc  00;38;2;1;152;51
*.gvimrc  00;38;2;1;152;51
*_vimrc  00;38;2;1;152;51
*_gvimrc  00;38;2;1;152;51
*.bashprofile  00;38;2;137;224;81
*favicon.ico  00;38;2;203;203;65
*license  00;38;2;203;203;65
*node_modules  00;38;2;232;39;75
*react.jsx  00;38;2;81;154;186
*procfile  00;38;2;160;116;196
*dockerfile  00;38;2;81;154;186
*docker-compose.yml  00;38;2;81;154;186
*docker-compose.yaml  00;38;2;81;154;186
*compose.yml  00;38;2;81;154;186
*compose.yaml  00;38;2;81;154;186
*rakefile  00;38;2;112;21;22
*config.ru  00;38;2;112;21;22
*gemfile  00;38;2;112;21;22
*makefile  00;38;2;109;128;134
*cmakelists.txt  00;38;2;109;128;134
*robots.txt 󰚩 00;38;2;109;128;134
# file names (case-sensitive adaptations)
*Gruntfile.coffee  00;38;2;227;121;51
*Gruntfile.js  00;38;2;227;121;51
*Gruntfile.ls  00;38;2;227;121;51
*Gulpfile.coffee  00;38;2;204;62;68
*Gulpfile.js  00;38;2;204;62;68
*Gulpfile.ls  00;38;2;204;62;68
*Dropbox  00;38;2;0;97;254
*.DS_Store  00;38;2;193;241;46
*LICENSE  00;38;2;203;203;65
*React.jsx  00;38;2;81;154;186
*Procfile  00;38;2;160;116;196
*Dockerfile  00;38;2;81;154;186
*Docker-compose.yml  00;38;2;81;154;186
*Docker-compose.yaml  00;38;2;81;154;186
*Rakefile  00;38;2;112;21;22
*Gemfile  00;38;2;112;21;22
*Makefile  00;38;2;109;128;134
*CMakeLists.txt  00;38;2;109;128;134
# file patterns (vim-devicons) (patterns not supported in lf)
# .*jquery.*\.js$  00;38;2;227;117;187
# .*angular.*\.js$  00;38;2;226;50;55
# .*backbone.*\.js$  00;38;2;0;113;181
# .*require.*\.js$  00;38;2;244;74;65
# .*materialize.*\.js$  00;38;2;238;110;115
# .*materialize.*\.css$  00;38;2;238;110;115
# .*mootools.*\.js$  00;38;2;236;236;236
# .*vimrc.*  00;38;2;1;152;51
# Vagrantfile$  00;38;2;21;99;255
# file patterns (file name adaptations)
*jquery.min.js  00;38;2;227;117;187
*angular.min.js  00;38;2;226;50;55
*backbone.min.js  00;38;2;0;113;181
*require.min.js  00;38;2;244;74;65
*materialize.min.js  00;38;2;238;110;115
*materialize.min.css  00;38;2;238;110;115
*mootools.min.js  00;38;2;236;236;236
*vimrc  00;38;2;1;152;51
Vagrantfile  00;38;2;21;99;255
# archives or compressed (extensions from dircolors defaults)
*.tar 
*.tgz 
*.arc 
*.arj 
*.taz 
*.lha 
*.lz4 
*.lzh 
*.lzma 
*.tlz 
*.txz 
*.tzo 
*.t7z 
*.zip 
*.z 
*.dz 
*.gz 
*.lrz 
*.lz 
*.lzo 
*.xz 
*.zst 
*.tzst 
*.bz2 
*.bz 
*.tbz 
*.tbz2 
*.tz 
*.deb 
*.rpm 
*.jar 
*.war 
*.ear 
*.sar 
*.rar 
*.alz 
*.ace 
*.zoo 
*.cpio 
*.7z 
*.rz 
*.cab 
*.wim 
*.swm 
*.dwm 
*.esd 
# image formats (extensions from dircolors defaults)
*.jpg 
*.jpeg 
*.mjpg 
*.mjpeg 
*.gif 
*.bmp 
*.pbm 
*.pgm 
*.ppm 
*.tga 
*.xbm 
*.xpm 
*.tif 
*.tiff 
*.png 
*.svg 
*.svgz 
*.mng 
*.pcx 
*.mov 
*.mpg 
*.mpeg 
*.m2v 
*.mkv 
*.webm 
*.ogm 
*.mp4 
*.m4v 
*.mp4v 
*.vob 
*.qt 
*.nuv 
*.wmv 
*.asf 
*.rm 
*.rmvb 
*.flc 
*.avi 
*.fli 
*.flv 
*.gl 
*.dl 
*.xcf 
*.xwd 
*.yuv 
*.cgm 
*.emf 
*.ogv 
*.ogx 
# audio formats (extensions from dircolors defaults)
*.aac 
*.au 
*.flac 
*.m4a 
*.mid 
*.midi 
*.mka 
*.mp3 
*.mpc 
*.ogg 
*.ra 
*.wav 
*.oga 
*.opus 
*.spx 
*.xspf 
# other formats
*.pdf  00;38;2;179;11;0
+2
View File
@@ -15,6 +15,8 @@ _lf () {
-last-dir-path
-log
-memprofile
-print-last-dir
-print-selection
-remote
-selection-path
-server
+1 -1
View File
@@ -9,7 +9,7 @@
# endif
#
set LF_ARGS = "-command -config -cpuprofile -doc -last-dir-path -log -memprofile -remote -selection-path -server -single -version -help "
set LF_ARGS = "-command -config -cpuprofile -doc -last-dir-path -log -memprofile -print-last-dir -print-selection -remote -selection-path -server -single -version -help "
complete lf "C/-*/(${LF_ARGS})/"
complete lfcd "C/-*/(${LF_ARGS})/"
+2
View File
@@ -13,6 +13,8 @@ complete -c lf -o doc -d 'show documentation'
complete -c lf -o last-dir-path -r -d 'path to the file to write the last dir on exit (to use for cd)'
complete -c lf -o log -r -d 'path to the log file to write messages'
complete -c lf -o memprofile -r -d 'path to the file to write the memory profile'
complete -c lf -o print-last-dir -d 'print the last dir to stdout on exit (to use for cd)'
complete -c lf -o print-selection -d 'print the selected files to stdout on open (to use as open file dialog)'
complete -c lf -o remote -x -d 'send remote command to server'
complete -c lf -o selection-path -r -d 'path to the file to write selected files on open (to use as open file dialog)'
complete -c lf -o server -d 'start server (automatic)'
+31
View File
@@ -0,0 +1,31 @@
# Autocompletion for nushell.
#
# Documentation: https://www.nushell.sh/book/externs.html
# To enable autocompletion you may put this file into a directory:
#
# mkdir -p ~/.config/nushell/completions
# ln -s "/path/to/lf.nu" ~/.config/nushell/completions
#
# Then you need to source this file in your nu config (Open the config with the
# command 'config nu' inside the nushell) by adding:
#
# source ~/.config/nushell/completions/lf.nu
export extern "lf" [
--command # command to execute on client initialization
--config: string # path to the config file (instead of the usual paths)
--cpuprofile: string # path to the file to write the CPU profile
--doc # show documentation
--last-dir-path: string # path to the file to write the last dir on exit (to use for cd)
--log: string # path to the log file to write messages
--memprofile: string # path to the file to write the memory profile
--print-last-dir # print the last dir to stdout on exit (to use for cd)
--print-selection # print the selected files to stdout on open (to use as open file dialog)
--remote: string # send remote command to server
--selection-path: string # path to the file to write selected files on open (to use as open file dialog)
--server # start server (automatic)
--single # start a client without server
--version # show version
--help # show help
]
+2
View File
@@ -16,6 +16,8 @@ Register-ArgumentCompleter -Native -CommandName 'lf' -ScriptBlock {
[CompletionResult]::new('-last-dir-path ', '-last-dir-path', [CompletionResultType]::ParameterName, 'path to the file to write the last dir on exit (to use for cd)')
[CompletionResult]::new('-log ', '-log', [CompletionResultType]::ParameterName, 'path to the log file to write messages')
[CompletionResult]::new('-memprofile ', '-memprofile', [CompletionResultType]::ParameterName, 'path to the file to write the memory profile')
[CompletionResult]::new('-print-last-dir', '-print-last-dir', [CompletionResultType]::ParameterName, 'print the last dir to stdout on exit (to use for cd)')
[CompletionResult]::new('-print-selection', '-print-selection', [CompletionResultType]::ParameterName, 'print the selected files to stdout on open (to use as open file dialog)')
[CompletionResult]::new('-remote ', '-remote', [CompletionResultType]::ParameterName, 'send remote command to server')
[CompletionResult]::new('-selection-path ', '-selection-path', [CompletionResultType]::ParameterName, 'path to the file to write selected files on open (to use as open file dialog)')
[CompletionResult]::new('-server', '-server', [CompletionResultType]::ParameterName, 'start server (automatic)')
+3 -1
View File
@@ -1,4 +1,4 @@
#compdef lf
#compdef lf lfcd
# Autocompletion for zsh shell.
#
@@ -20,6 +20,8 @@ arguments=(
'-last-dir-path[path to the file to write the last dir on exit (to use for cd)]'
'-log[path to the log file to write messages]'
'-memprofile[path to the file to write the memory profile]'
'-print-last-dir[print the last dir to stdout on exit (to use for cd)]'
'-print-selection[print the selected files to stdout on open (to use as open file dialog)]'
'-remote[send remote command to server]'
'-selection-path[path to the file to write selected files on open (to use as open file dialog)]'
'-server[start server (automatic)]'
+2 -10
View File
@@ -3,13 +3,5 @@ rem Change working dir in cmd.exe to last dir in lf on exit.
rem
rem You need to put this file to a folder in %PATH% variable.
:tmploop
set tmpfile="%tmp%\lf.%random%.tmp"
if exist %tmpfile% goto:tmploop
lf -last-dir-path=%tmpfile% %*
if not exist %tmpfile% exit
set /p dir=<%tmpfile%
del /f %tmpfile%
if not exist "%dir%" exit
if "%dir%" == "%cd%" exit
cd /d "%dir%"
chcp 65001 > nul 2>&1
for /f "usebackq tokens=*" %%d in (`lf -print-last-dir %*`) do cd /d %%d
+4 -13
View File
@@ -11,17 +11,8 @@
#
# You may put this in a function called fish_user_key_bindings.
function lfcd
set tmp (mktemp)
# `command` is needed in case `lfcd` is aliased to `lf`
command lf -last-dir-path=$tmp $argv
if test -f "$tmp"
set dir (cat $tmp)
rm -f $tmp
if test -d "$dir"
if test "$dir" != (pwd)
cd $dir
end
end
end
function lfcd --wraps="lf" --description="lf - Terminal file manager (changing directory on exit)"
# `command` is needed in case `lfcd` is aliased to `lf`.
# Quotes will cause `cd` to not change directory if `lf` prints nothing to stdout due to an error.
cd "$(command lf -print-last-dir $argv)"
end
+25
View File
@@ -0,0 +1,25 @@
# Change working dir in shell to last dir in lf on exit (adapted from ranger).
#
# You need to add this to your Nushell Enviroment Config File
# (Execute 'config env' in the nushell to open it).
# You may also like to assign a key (Ctrl-O) to this command:
# See the documentation: https://www.nushell.sh/book/line_editor.html#keybindings
#
# keybindings: [
# {
# name: lfcd
# modifier: control
# keycode: char_o
# mode: [emacs, vi_normal, vi_insert]
# event: {
# send: executehostcommand
# cmd: "lfcd"
# }
# }
# ]
# For nushell version >= 0.87.0
def --env --wrapped lfcd [...args: string] {
cd (lf -print-last-dir ...$args)
}
+1 -11
View File
@@ -13,14 +13,4 @@
# You may put this in one of the profiles found in $PROFILE.
#
$tmp = [System.IO.Path]::GetTempFileName()
lf -last-dir-path="$tmp" $args
if (Test-Path -PathType Leaf "$tmp") {
$dir = Get-Content "$tmp"
Remove-Item -Force "$tmp"
if (Test-Path -PathType Container "$dir") {
if ("$dir" -ne "$pwd") {
cd "$dir"
}
}
}
lf -print-last-dir $args | Set-Location
+1 -11
View File
@@ -15,16 +15,6 @@
#
lfcd () {
tmp="$(mktemp)"
# `command` is needed in case `lfcd` is aliased to `lf`
command lf -last-dir-path="$tmp" "$@"
if [ -f "$tmp" ]; then
dir="$(cat "$tmp")"
rm -f "$tmp"
if [ -d "$dir" ]; then
if [ "$dir" != "$(pwd)" ]; then
cd "$dir"
fi
fi
fi
cd "$(command lf -print-last-dir "$@")"
}
+494 -781
View File
File diff suppressed because it is too large. Load diff
+149
View File
@@ -1,6 +1,7 @@
package main
import (
"fmt"
"reflect"
"strings"
"testing"
@@ -191,6 +192,84 @@ var gEvalTests = []struct {
[]expr{&setExpr{"ratios", "1:2:3"}, &setExpr{"hidden", ""}},
},
{
"setlocal /foo/bar hidden # trailing comments are allowed",
[]string{"setlocal", "/foo/bar", "hidden", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "hidden", ""}},
},
{
"setlocal /foo/bar hidden; setlocal /foo/bar reverse",
[]string{"setlocal", "/foo/bar", "hidden", ";", "setlocal", "/foo/bar", "reverse", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "hidden", ""}, &setLocalExpr{"/foo/bar", "reverse", ""}},
},
{
"setlocal /foo/bar hidden\nsetlocal /foo/bar reverse",
[]string{"setlocal", "/foo/bar", "hidden", "\n", "setlocal", "/foo/bar", "reverse", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "hidden", ""}, &setLocalExpr{"/foo/bar", "reverse", ""}},
},
{
`setlocal /foo/bar info ""`,
[]string{"setlocal", "/foo/bar", "info", "", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "info", ""}},
},
{
`setlocal /foo/bar info "size"`,
[]string{"setlocal", "/foo/bar", "info", "size", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "info", "size"}},
},
{
"setlocal /foo/bar info size:time",
[]string{"setlocal", "/foo/bar", "info", "size:time", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}},
},
{
"setlocal /foo/bar info size:time;",
[]string{"setlocal", "/foo/bar", "info", "size:time", ";"},
[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}},
},
{
":setlocal /foo/bar info size:time",
[]string{":", "setlocal", "/foo/bar", "info", "size:time", "\n", "\n"},
[]expr{&listExpr{[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}}, 1}},
},
{
":setlocal /foo/bar info size:time\nsetlocal /foo/bar hidden",
[]string{":", "setlocal", "/foo/bar", "info", "size:time", "\n", "\n", "setlocal", "/foo/bar", "hidden", "\n"},
[]expr{&listExpr{[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}}, 1}, &setLocalExpr{"/foo/bar", "hidden", ""}},
},
{
":setlocal /foo/bar info size:time;",
[]string{":", "setlocal", "/foo/bar", "info", "size:time", ";", "\n"},
[]expr{&listExpr{[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}}, 1}},
},
{
":setlocal /foo/bar info size:time;\nsetlocal /foo/bar hidden",
[]string{":", "setlocal", "/foo/bar", "info", "size:time", ";", "\n", "setlocal", "/foo/bar", "hidden", "\n"},
[]expr{&listExpr{[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}}, 1}, &setLocalExpr{"/foo/bar", "hidden", ""}},
},
{
"setlocal /foo/bar info size:time\n setlocal /foo/bar hidden",
[]string{"setlocal", "/foo/bar", "info", "size:time", "\n", "setlocal", "/foo/bar", "hidden", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}, &setLocalExpr{"/foo/bar", "hidden", ""}},
},
{
"setlocal /foo/bar info size:time \nsetlocal /foo/bar hidden",
[]string{"setlocal", "/foo/bar", "info", "size:time", "\n", "setlocal", "/foo/bar", "hidden", "\n"},
[]expr{&setLocalExpr{"/foo/bar", "info", "size:time"}, &setLocalExpr{"/foo/bar", "hidden", ""}},
},
{
"map gh cd ~",
[]string{"map", "gh", "cd", "~", "\n"},
@@ -459,3 +538,73 @@ func TestSplitKeys(t *testing.T) {
}
}
}
func TestApplyBoolOpt(t *testing.T) {
tests := []struct {
opt bool
e setExpr
exp bool
}{
{true, setExpr{"feature", ""}, true},
{true, setExpr{"feature", "true"}, true},
{true, setExpr{"feature", "false"}, false},
{false, setExpr{"feature", ""}, true},
{false, setExpr{"feature", "true"}, true},
{false, setExpr{"feature", "false"}, false},
{true, setExpr{"nofeature", ""}, false},
{false, setExpr{"nofeature", ""}, false},
{true, setExpr{"feature!", ""}, false},
{false, setExpr{"feature!", ""}, true},
}
for _, test := range tests {
testStr := fmt.Sprintf("%v", test)
if err := applyBoolOpt(&test.opt, &test.e); err != nil {
t.Errorf("at test '%s' expected '%t' but got an error '%s'", testStr, test.exp, err)
continue
}
if test.opt != test.exp {
t.Errorf("at test '%s' expected '%t' but got '%t'", testStr, test.exp, test.opt)
}
}
}
func TestApplyLocalBoolOpt(t *testing.T) {
tests := []struct {
localOpt map[string]bool
globalOpt bool
e setLocalExpr
exp bool
}{
{map[string]bool{}, false, setLocalExpr{"/", "feature", ""}, true},
{map[string]bool{}, false, setLocalExpr{"/", "feature", "true"}, true},
{map[string]bool{}, false, setLocalExpr{"/", "feature", "false"}, false},
{map[string]bool{}, false, setLocalExpr{"/", "nofeature", ""}, false},
{map[string]bool{}, true, setLocalExpr{"/", "feature!", ""}, false},
{map[string]bool{}, false, setLocalExpr{"/", "feature!", ""}, true},
{map[string]bool{"/": true}, false, setLocalExpr{"/", "feature", ""}, true},
{map[string]bool{"/": true}, false, setLocalExpr{"/", "feature", "true"}, true},
{map[string]bool{"/": true}, false, setLocalExpr{"/", "feature", "false"}, false},
{map[string]bool{"/": true}, false, setLocalExpr{"/", "nofeature", ""}, false},
{map[string]bool{"/": true}, true, setLocalExpr{"/", "feature!", ""}, false},
{map[string]bool{"/": true}, false, setLocalExpr{"/", "feature!", ""}, false},
{map[string]bool{"/": false}, false, setLocalExpr{"/", "feature", ""}, true},
{map[string]bool{"/": false}, false, setLocalExpr{"/", "feature", "true"}, true},
{map[string]bool{"/": false}, false, setLocalExpr{"/", "feature", "false"}, false},
{map[string]bool{"/": false}, false, setLocalExpr{"/", "nofeature", ""}, false},
{map[string]bool{"/": false}, true, setLocalExpr{"/", "feature!", ""}, true},
{map[string]bool{"/": false}, false, setLocalExpr{"/", "feature!", ""}, true},
}
for _, test := range tests {
testStr := fmt.Sprintf("%v", test)
if err := applyLocalBoolOpt(test.localOpt, test.globalOpt, &test.e); err != nil {
t.Errorf("at test '%s' expected '%t' but got an error '%s'", testStr, test.exp, err)
continue
}
result := test.localOpt[test.e.path]
if result != test.exp {
t.Errorf("at test '%s' expected '%t' but got '%t'", testStr, test.exp, result)
}
}
}
+32
View File
@@ -0,0 +1,32 @@
#!/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:2.11
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
Executable
+30
View File
@@ -0,0 +1,30 @@
#!/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 \
--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
pandoc \
--standalone \
--from gfm --to plain \
doc.md -o doc.txt
-19
View File
@@ -1,19 +0,0 @@
#!/bin/sh
# Generates `docstring.go` having `genDocString` variable with `go doc` output.
#
# This script is called in `doc.go` using `go generate` to embed the
# documentation inside the binary in order to show it on request with `-doc`
# command line flag. Thus the same documentation is used for online and
# terminal display.
tmp=gen/docstring.go
echo "// Code generated by gen/docstring.sh DO NOT EDIT." >> $tmp
echo >> $tmp
echo "package main" >> $tmp
echo >> $tmp
echo "var genDocString = \`" >> $tmp
go doc | tr "\`" "'" >> $tmp
echo "\`" >> $tmp
mv $tmp docstring.go
-75
View File
@@ -1,75 +0,0 @@
#!/bin/sh
# Generates `lf.1` man page using man macros with `go doc` output.
#
# This script is called in `doc.go` using `go generate` to generate a man page
# formatted with man macros from the documentation. A few additional sections
# such as `NAME` and `SYNOPSIS` are added to comply with man page conventions.
#
# Conversion logic implemented here from godoc output to man macros should not
# be considered compliant, as such it has inexact assumptions such as the use
# of spaces over tabs along with various corner cases that are not handled
# properly like character escaping. The intention here is to come up with
# something that can convert the current content in the documentation. For this
# reason, it is recommended to check the output after generation especially
# when the documentation is changed in a significant way.
out=lf.1
echo '.\" Code generated by gen/man.sh DO NOT EDIT.' > $out
cat << END >> $out
.TH LF 1
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
.SY lf
.OP \-command command
.OP \-config path
.OP \-cpuprofile path
.OP \-doc
.OP \-last-dir-path path
.OP \-log path
.OP \-memprofile path
.OP \-remote command
.OP \-selection-path path
.OP \-server
.OP \-single
.OP \-version
.OP \-help
.RI [ cd-or-select-path ]
.YS
.SH DESCRIPTION
END
go doc | awk '
BEGIN {
RS = ""
start = 1
}
# preformatted
/^ / {
gsub("\\\\", "\\e", $0)
print ".PP"
print ".EX"
print $0
print ".EE"
next
}
# heading
/^# *[^[:punct:]]*$/ {
gsub(/# */, "", $0)
print ".SH", toupper($0)
start = 1
next
}
# paragraph
{
gsub("\n", " ", $0)
gsub("\\\\", "\\e", $0)
if (start) { start = 0 } else { print ".PP" }
print $0
}
' >> $out
+76 -42
View File
@@ -8,51 +8,85 @@
# compressed in an archive form (`.zip` for windows and `.tar.gz` for the rest)
# within a folder named `dist`.
set -o verbose
[ -z "$version" ] && version=$(git describe --tags)
[ -z $version ] && version=$(git describe --tags)
test -d dist && {
echo "gen/xbuild.sh: WARNING: removing preexisting subdir 'dist'"
rm -r dist || exit 5
}
mkdir dist || exit 5
mkdir -p dist
ERRORS=
# https://golang.org/doc/install/source#environment
build() {
# https://golang.org/doc/install/source#environment
echo "=== Building for GOOS=$1 and GOARCH=$2."
CGO_ENABLED=0 GOOS="$1" GOARCH="$2" go build -o dist/ \
-ldflags="-s -w -X main.gVersion=$version"
if test "$?" != "0"; then
ERRORS=1
else
package "$1" "$2" || exit 5
fi
}
CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-dragonfly-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=illumos GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-illumos-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mipsle.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=s390x go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-s390x.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=solaris GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-solaris-amd64.tar.gz lf --remove-files
package() (
cd dist || return 1
# Since the function is surrounded by (), the cd only affects a subshell
OUTFILE=
case "$1" in
windows)
OUTFILE="lf-$1-$2.zip"
zip "$OUTFILE" lf.exe --move || return 1
;;
*)
OUTFILE="lf-$1-$2.tar.gz"
tar czf "$OUTFILE" lf --remove-files || return 1
;;
esac
echo "dist/$OUTFILE successfully created."
)
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-386.zip lf.exe --move
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-amd64.zip lf.exe --move
build android arm64
build darwin amd64
build darwin arm64
build dragonfly amd64
build freebsd 386
build freebsd amd64
build freebsd arm
build illumos amd64
build linux 386
build linux amd64
build linux arm
build linux arm64
build linux ppc64
build linux ppc64le
build linux mips
build linux mipsle
build linux mips64
build linux mips64le
build linux s390x
build netbsd 386
build netbsd amd64
build netbsd arm
build openbsd 386
build openbsd amd64
build openbsd arm
build openbsd arm64
build solaris amd64
build windows 386
build windows amd64
# Unsupported
# build aix ppc64
# build android 386
# build android amd64
# build android arm
# build js wasm
# build plan9 386
# build plan9 amd64
# build plan9 arm
# not supported
# CGO_ENABLED=0 GOOS=aix GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-aix-ppc64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-386.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-amd64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-arm64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-js-wasm.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-386.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-amd64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-arm.tar.gz lf --remove-files
if test -n "$ERRORS"; then
printf "\ngen/xbuild.sh: some targets failed to compile.\n"
exit 1
fi
+11 -9
View File
@@ -1,18 +1,20 @@
module github.com/gokcehan/lf
go 1.18
go 1.23
require (
github.com/djherbis/times v1.5.0
github.com/gdamore/tcell/v2 v2.6.0
github.com/mattn/go-runewidth v0.0.14
golang.org/x/sys v0.7.0
golang.org/x/term v0.7.0
github.com/Xuanwo/go-locale v1.1.2
github.com/djherbis/times v1.6.0
github.com/fsnotify/fsnotify v1.8.0
github.com/gdamore/tcell/v2 v2.8.1
github.com/mattn/go-runewidth v0.0.16
golang.org/x/sys v0.29.0
golang.org/x/term v0.28.0
golang.org/x/text v0.21.0
)
require (
github.com/gdamore/encoding v1.0.0 // indirect
github.com/gdamore/encoding v1.0.1 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
golang.org/x/text v0.7.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
)
+55 -14
View File
@@ -1,44 +1,85 @@
github.com/djherbis/times v1.5.0 h1:79myA211VwPhFTqUk8xehWrsEO+zcIZj0zT8mXPVARU=
github.com/djherbis/times v1.5.0/go.mod h1:5q7FDLvbNg1L/KaBmPcWlVR9NmoKo3+ucqUA3ijQhA0=
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/tcell/v2 v2.6.0 h1:OKbluoP9VYmJwZwq/iLb4BxwKcwGthaa1YNBJIyCySg=
github.com/gdamore/tcell/v2 v2.6.0/go.mod h1:be9omFATkdr0D9qewWW3d+MEvl5dha+Etb5y65J2H8Y=
github.com/Xuanwo/go-locale v1.1.2 h1:6H+olvrQcyVOZ+GAC2rXu4armacTT4ZrFCA0mB24XVo=
github.com/Xuanwo/go-locale v1.1.2/go.mod h1:1JBER4QV7Ji39GJ4AvVlfvqmTUqopzxQxdg2mXYOw94=
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.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw=
github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo=
github.com/gdamore/tcell/v2 v2.8.1 h1:KPNxyqclpWpWQlPLx6Xui1pMk8S+7+R37h3g07997NU=
github.com/gdamore/tcell/v2 v2.8.1/go.mod h1:bj8ori1BG3OYMjmb3IklZVWfZUJ1UBQt9JXrOCOhGWw=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220615213510-4f61da869c0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.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 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.7.0 h1:BEvjmm5fURWqcfbSKTdpkDXYBrUS1c0m8agp14W48vQ=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
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 h1:/Ts8HFuMR2E6IP/jlo7QVLZHggjKQbhu/7H0LJFr3Gg=
golang.org/x/term v0.28.0/go.mod h1:Sw/lC2IAUZ92udQNf3WodGtn4k/XoLyZoh8v/8uiwek=
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 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
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 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
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=
+69 -40
View File
@@ -5,12 +5,34 @@ import (
"os"
"path/filepath"
"strings"
"github.com/gdamore/tcell/v2"
)
type iconMap map[string]string
type iconDef struct {
icon string
hasStyle bool
style tcell.Style
}
type iconMap struct {
icons map[string]iconDef
useLinkTarget bool
}
func iconWithoutStyle(icon string) iconDef {
return iconDef{icon, false, tcell.StyleDefault}
}
func iconWithStyle(icon string, style tcell.Style) iconDef {
return iconDef{icon, true, style}
}
func parseIcons() iconMap {
im := make(iconMap)
im := iconMap{
icons: make(map[string]iconDef),
useLinkTarget: false,
}
defaultIcons := []string{
"ln=l",
@@ -44,7 +66,7 @@ func parseIcons() iconMap {
return im
}
func (im iconMap) parseFile(path string) {
func (im *iconMap) parseFile(path string) {
log.Printf("reading file: %s", path)
f, err := os.Open(path)
@@ -54,26 +76,18 @@ func (im iconMap) parseFile(path string) {
}
defer f.Close()
pairs, err := readPairs(f)
arrs, err := readArrays(f, 1, 3)
if err != nil {
log.Printf("reading icons file: %s", err)
return
}
for _, pair := range pairs {
key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
im[key] = val
for _, arr := range arrs {
im.parseArray(arr)
}
}
func (im iconMap) parseEnv(env string) {
func (im *iconMap) parseEnv(env string) {
for _, entry := range strings.Split(env, ":") {
if entry == "" {
continue
@@ -86,25 +100,40 @@ func (im iconMap) parseEnv(env string) {
return
}
key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
im[key] = val
im.parseArray(pair)
}
}
func (im iconMap) get(f *file) string {
if val, ok := im[f.path]; ok {
func (im *iconMap) parseArray(arr []string) {
key := replaceTilde(arr[0])
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
switch len(arr) {
case 1:
delete(im.icons, key)
case 2:
icon := arr[1]
if key == "ln" && icon == "target" {
im.useLinkTarget = true
} else {
im.icons[key] = iconWithoutStyle(icon)
}
case 3:
icon, color := arr[1], arr[2]
im.icons[key] = iconWithStyle(icon, applyAnsiCodes(color, tcell.StyleDefault))
}
}
func (im iconMap) get(f *file) iconDef {
if val, ok := im.icons[f.path]; ok {
return val
}
if f.IsDir() {
if val, ok := im[f.Name()+"/"]; ok {
if val, ok := im.icons[f.Name()+"/"]; ok {
return val
}
}
@@ -112,13 +141,13 @@ func (im iconMap) get(f *file) string {
var key string
switch {
case f.linkState == working:
case f.linkState == working && !im.useLinkTarget:
key = "ln"
case f.linkState == broken:
key = "or"
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0o002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&0002 != 0:
case f.IsDir() && f.Mode()&0o002 != 0:
key = "ow"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
@@ -128,41 +157,41 @@ func (im iconMap) get(f *file) string {
key = "pi"
case f.Mode()&os.ModeSocket != 0:
key = "so"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0:
key = "su"
case f.Mode()&os.ModeSetgid != 0:
key = "sg"
case f.Mode()&0111 != 0:
case f.Mode()&0o111 != 0:
key = "ex"
}
if val, ok := im[key]; ok {
if val, ok := im.icons[key]; ok {
return val
}
if val, ok := im[f.Name()+"*"]; ok {
if val, ok := im.icons[f.Name()+"*"]; ok {
return val
}
if val, ok := im["*"+f.Name()]; ok {
if val, ok := im.icons["*"+f.Name()]; ok {
return val
}
if val, ok := im[filepath.Base(f.Name())+".*"]; ok {
if val, ok := im.icons[filepath.Base(f.Name())+".*"]; ok {
return val
}
if val, ok := im["*"+strings.ToLower(f.ext)]; ok {
if val, ok := im.icons["*"+strings.ToLower(f.ext)]; ok {
return val
}
if val, ok := im["fi"]; ok {
if val, ok := im.icons["fi"]; ok {
return val
}
return " "
return iconWithoutStyle(" ")
}
+2061 -1454
View File
File diff suppressed because it is too large. Load diff
+83 -57
View File
@@ -9,11 +9,17 @@ import (
"path/filepath"
"reflect"
"runtime"
"runtime/debug"
"runtime/pprof"
"strconv"
"strings"
_ "embed"
)
//go:embed doc.txt
var genDocString string
var (
envPath = os.Getenv("PATH")
envLevel = os.Getenv("LF_LEVEL")
@@ -22,18 +28,20 @@ var (
type arrayFlag []string
var (
gSingleMode bool
gClientID int
gHostname string
gLastDirPath string
gSelectionPath string
gSocketProt string
gSocketPath string
gLogPath string
gSelect string
gConfigPath string
gCommands arrayFlag
gVersion string
gSingleMode bool
gPrintLastDir bool
gPrintSelection bool
gClientID int
gHostname string
gLastDirPath string
gSelectionPath string
gSocketProt string
gSocketPath string
gLogPath string
gSelect string
gConfigPath string
gCommands arrayFlag
gVersion string
)
func (a *arrayFlag) Set(v string) error {
@@ -85,7 +93,7 @@ func exportEnvVars() {
log.Printf("getting path to lf binary: %s", err)
lfPath = "lf"
}
os.Setenv("lf", lfPath)
os.Setenv("lf", quoteString(lfPath))
}
// used by exportOpts below
@@ -115,62 +123,37 @@ func fieldToString(field reflect.Value) string {
return value
}
func exportOpts() {
e := reflect.ValueOf(&gOpts).Elem()
func getOptsMap() map[string]string {
opts := make(map[string]string)
v := reflect.ValueOf(gOpts)
t := v.Type()
for i := 0; i < e.NumField(); i++ {
// Get name and prefix it with lf_
name := e.Type().Field(i).Name
name = fmt.Sprintf("lf_%s", name)
for i := 0; i < v.NumField(); i++ {
// Get field name and prefix it with lf_
name := "lf_" + t.Field(i).Name
// Skip maps
if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" {
continue
}
// Get string representation of the value
if name == "lf_sortType" {
var sortby string
switch gOpts.sortType.method {
case naturalSort:
sortby = "natural"
case nameSort:
sortby = "name"
case sizeSort:
sortby = "size"
case timeSort:
sortby = "time"
case ctimeSort:
sortby = "ctime"
case atimeSort:
sortby = "atime"
case extSort:
sortby = "ext"
}
os.Setenv("lf_sortby", sortby)
reverse := strconv.FormatBool(gOpts.sortType.option&reverseSort != 0)
os.Setenv("lf_reverse", reverse)
hidden := strconv.FormatBool(gOpts.sortType.option&hiddenSort != 0)
os.Setenv("lf_hidden", hidden)
dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0)
os.Setenv("lf_dirfirst", dirfirst)
} else if name == "lf_user" {
if name == "lf_user" {
// set each user option
for key, value := range gOpts.user {
os.Setenv(name+"_"+key, value)
opts[name+"_"+key] = value
}
} else {
field := e.Field(i)
value := fieldToString(field)
os.Setenv(name, value)
opts[name] = fieldToString(v.Field(i))
}
}
return opts
}
func exportOpts() {
for key, value := range getOptsMap() {
os.Setenv(key, value)
}
}
func startServer() {
@@ -195,6 +178,37 @@ func checkServer() {
}
}
func printVersion() {
if gVersion != "" {
fmt.Println(gVersion)
return
}
buildInfo, ok := debug.ReadBuildInfo()
if !ok {
return
}
var vcsRevision, vcsTime, vcsModified string
for _, setting := range buildInfo.Settings {
switch setting.Key {
case "vcs.revision":
vcsRevision = setting.Value
case "vcs.time":
vcsTime = setting.Value
case "vcs.modified":
if setting.Value == "true" {
vcsModified = " (dirty)"
}
}
}
if vcsRevision != "" {
fmt.Printf("Built at commit: %s%s %s\n", vcsRevision, vcsModified, vcsTime)
}
fmt.Printf("Go version: %s\n", buildInfo.GoVersion)
}
func main() {
flag.Usage = func() {
f := flag.CommandLine.Output()
@@ -228,6 +242,16 @@ func main() {
false,
"start a client without server")
printLastDir := flag.Bool(
"print-last-dir",
false,
"print the last dir to stdout on exit (to use for cd)")
printSelection := flag.Bool(
"print-selection",
false,
"print the selected files to stdout on open (to use as open file dialog)")
remoteCmd := flag.String(
"remote",
"",
@@ -287,7 +311,7 @@ func main() {
case *showDoc:
fmt.Print(genDocString)
case *showVersion:
fmt.Println(gVersion)
printVersion()
case *remoteCmd != "":
if err := remote(*remoteCmd); err != nil {
log.Fatalf("remote command: %s", err)
@@ -305,6 +329,8 @@ func main() {
serve()
default:
gSingleMode = *singleMode
gPrintLastDir = *printLastDir
gPrintSelection = *printSelection
if !gSingleMode {
checkServer()
+119 -45
View File
@@ -4,20 +4,29 @@ import (
"bufio"
"fmt"
"io"
"io/fs"
"path/filepath"
"regexp"
"strconv"
"strings"
"unicode"
"github.com/Xuanwo/go-locale"
"github.com/mattn/go-runewidth"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
const (
localeStrDisable = "" // disable locale ordering for this locale value
localeStrSys = "*" // replace this locale value with locale value read from environment
)
func isRoot(name string) bool { return filepath.Dir(name) == name }
func replaceTilde(s string) string {
if strings.HasPrefix(s, "~") {
s = strings.Replace(s, "~", gUser.HomeDir, 1)
return gUser.HomeDir + s[1:]
}
return s
}
@@ -31,27 +40,43 @@ func runeSliceWidth(rs []rune) int {
}
func runeSliceWidthRange(rs []rune, beg, end int) []rune {
if beg == end {
return []rune{}
}
curr := 0
b := 0
foundb := false
for i, r := range rs {
w := runewidth.RuneWidth(r)
switch {
case curr == beg:
if curr >= beg && !foundb {
b = i
case curr < beg && curr+w > beg:
b = i + 1
case curr == end:
foundb = true
}
if curr == end || curr+w > end {
return rs[b:i]
case curr > end:
return rs[b : i-1]
}
curr += w
}
return nil
return rs[b:]
}
// Returns the last runes of `rs` that take up at most `maxWidth` space.
func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune {
lastWidth := 0
for i := len(rs) - 1; i >= 0; i-- {
w := runewidth.RuneWidth(rs[i])
if lastWidth+w > maxWidth {
return rs[i+1:]
}
lastWidth += w
}
return rs
}
// This function is used to escape whitespaces and special characters with
// backlashes in a given string.
// backslashes in a given string.
func escape(s string) string {
buf := make([]rune, 0, len(s))
for _, r := range s {
@@ -63,7 +88,7 @@ func escape(s string) string {
return string(buf)
}
// This function is used to remove backlashes that are used to escape
// This function is used to remove backslashes that are used to escape
// whitespaces and special characters in a given string.
func unescape(s string) string {
esc := false
@@ -114,8 +139,7 @@ func tokenize(s string) []string {
buf = nil
}
}
toks = append(toks, string(buf))
return toks
return append(toks, string(buf))
}
// This function splits the first word of a string delimited by whitespace from
@@ -135,12 +159,12 @@ func splitWord(s string) (word, rest string) {
return
}
// This function reads whitespace separated string pairs at each line. Single
// This function reads whitespace separated string arrays at each line. Single
// or double quotes can be used to escape whitespaces. Hash characters can be
// used to add a comment until the end of line. Leading and trailing space is
// trimmed. Empty lines are skipped.
func readPairs(r io.Reader) ([][]string, error) {
var pairs [][]string
func readArrays(r io.Reader, min_cols, max_cols int) ([][]string, error) {
var arrays [][]string
s := bufio.NewScanner(r)
for s.Scan() {
line := s.Text()
@@ -165,7 +189,7 @@ func readPairs(r io.Reader) ([][]string, error) {
}
squote, dquote = false, false
pair := strings.FieldsFunc(line, func(r rune) bool {
arr := strings.FieldsFunc(line, func(r rune) bool {
if r == '\'' && !dquote {
squote = !squote
} else if r == '"' && !squote {
@@ -173,15 +197,19 @@ func readPairs(r io.Reader) ([][]string, error) {
}
return !squote && !dquote && unicode.IsSpace(r)
})
arrlen := len(arr)
if len(pair) != 2 {
return nil, fmt.Errorf("expected pair but found: %s", s.Text())
if arrlen < min_cols || arrlen > max_cols {
if min_cols == max_cols {
return nil, fmt.Errorf("expected %d columns but found: %s", min_cols, s.Text())
}
return nil, fmt.Errorf("expected %d~%d columns but found: %s", min_cols, max_cols, s.Text())
}
for i := 0; i < len(pair); i++ {
for i := 0; i < arrlen; i++ {
squote, dquote = false, false
buf := make([]rune, 0, len(pair[i]))
for _, r := range pair[i] {
buf := make([]rune, 0, len(arr[i]))
for _, r := range arr[i] {
if r == '\'' && !dquote {
squote = !squote
continue
@@ -192,13 +220,17 @@ func readPairs(r io.Reader) ([][]string, error) {
}
buf = append(buf, r)
}
pair[i] = string(buf)
arr[i] = string(buf)
}
pairs = append(pairs, pair)
arrays = append(arrays, arr)
}
return pairs, nil
return arrays, nil
}
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
@@ -225,7 +257,8 @@ func humanize(size int64) string {
for _, s := range suffix {
if curr < 10 {
return fmt.Sprintf("%.1f%s", curr-0.0499, s)
} else if curr < 1000 {
}
if curr < 1000 {
return fmt.Sprintf("%d%s", int(curr), s)
}
curr /= 1000
@@ -240,22 +273,24 @@ func humanize(size int64) string {
// than 'foo10bar'.
func naturalLess(s1, s2 string) bool {
lo1, lo2, hi1, hi2 := 0, 0, 0, 0
s1len := len(s1)
s2len := len(s2)
for {
if hi1 >= len(s1) {
return hi2 != len(s2)
if hi1 >= s1len {
return hi2 != s2len
}
if hi2 >= len(s2) {
if hi2 >= s2len {
return false
}
isDigit1 := isDigit(s1[hi1])
isDigit2 := isDigit(s2[hi2])
for lo1 = hi1; hi1 < len(s1) && isDigit(s1[hi1]) == isDigit1; hi1++ {
for lo1 = hi1; hi1 < s1len && isDigit(s1[hi1]) == isDigit1; hi1++ {
}
for lo2 = hi2; hi2 < len(s2) && isDigit(s2[hi2]) == isDigit2; hi2++ {
for lo2 = hi2; hi2 < s2len && isDigit(s2[hi2]) == isDigit2; hi2++ {
}
if s1[lo1:hi1] == s2[lo2:hi2] {
@@ -275,24 +310,63 @@ func naturalLess(s1, s2 string) bool {
}
}
var reAltKey = regexp.MustCompile(`<a-(.)>`)
var reWord = regexp.MustCompile(`(\pL|\pN)+`)
var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
var reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
func min(a, b int) int {
if a < b {
return a
// This function returns the extension of a file with a leading dot
// it returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
func getFileExtension(file fs.FileInfo) string {
if file.IsDir() {
return ""
}
return b
if strings.Count(file.Name(), ".") == 1 && file.Name()[0] == '.' {
// hidden file without extension
return ""
}
return filepath.Ext(file.Name())
}
func max(a, b int) int {
if a > b {
return a
var (
reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`)
reRulerSub = regexp.MustCompile(`%[apmcsfithd]|%\{[^}]+\}`)
)
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()
}
return b
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
}
// We don't need no generic code
+156 -13
View File
@@ -5,6 +5,9 @@ import (
"reflect"
"strings"
"testing"
"time"
"golang.org/x/text/collate"
)
func TestIsRoot(t *testing.T) {
@@ -55,21 +58,71 @@ func TestRuneSliceWidthRange(t *testing.T) {
end int
exp []rune
}{
{[]rune{}, 0, 0, []rune{}},
{[]rune{'a', 'b', 'c', 'd'}, 1, 3, []rune{'b', 'c'}},
{[]rune{'a', 'ı', 'b', 'ş'}, 1, 3, []rune{'ı', 'b'}},
{[]rune{'世', '界', '世', '界'}, 2, 6, []rune{'界', '世'}},
{[]rune{'世', '界', '世', '界'}, 3, 6, []rune{'世'}},
{[]rune{'世', '界', '世', '界'}, 2, 5, []rune{'界'}},
{[]rune{'世', '界', '世', '界'}, 3, 5, []rune{}},
{[]rune{'世', '界', '世', '界'}, 4, 4, []rune{}},
{[]rune{'世', '界', '世', '界'}, 5, 5, []rune{}},
{[]rune{'世', '界', '世', '界'}, 4, 7, []rune{'世'}},
{[]rune{'世', '界', '世', '界'}, 4, 8, []rune{'世', '界'}},
{[]rune{'世', 'a', '界', 'ı'}, 2, 5, []rune{'a', '界'}},
{[]rune{'世', 'a', '界', 'ı'}, 2, 4, []rune{'a'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 5, []rune{'界'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 4, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 3, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 4, 4, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 4, 6, []rune{'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 5, 6, []rune{'ı'}},
}
for _, test := range tests {
if got := runeSliceWidthRange(test.rs, test.beg, test.end); !reflect.DeepEqual(got, test.exp) {
t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.rs, got)
t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.exp, got)
}
}
}
func TestRuneSliceWidthLastRange(t *testing.T) {
tests := []struct {
rs []rune
maxWidth int
exp []rune
}{
{[]rune{}, 0, []rune{}},
{[]rune{}, 1, []rune{}},
{[]rune{'a', 'ı', 'b', ' '}, 0, []rune{}},
{[]rune{'a', 'ı', 'b', ' '}, 1, []rune{' '}},
{[]rune{'a', 'ı', 'b', ' '}, 2, []rune{'b', ' '}},
{[]rune{'a', 'ı', 'b', ' '}, 3, []rune{'ı', 'b', ' '}},
{[]rune{'a', 'ı', 'b', ' '}, 4, []rune{'a', 'ı', 'b', ' '}},
{[]rune{'a', 'ı', 'b', ' '}, 5, []rune{'a', 'ı', 'b', ' '}},
{[]rune{'世', '界', '世', '界'}, 0, []rune{}},
{[]rune{'世', '界', '世', '界'}, 1, []rune{}},
{[]rune{'世', '界', '世', '界'}, 2, []rune{'界'}},
{[]rune{'世', '界', '世', '界'}, 3, []rune{'界'}},
{[]rune{'世', '界', '世', '界'}, 4, []rune{'世', '界'}},
{[]rune{'世', '界', '世', '界'}, 5, []rune{'世', '界'}},
{[]rune{'世', '界', '世', '界'}, 6, []rune{'界', '世', '界'}},
{[]rune{'世', '界', '世', '界'}, 7, []rune{'界', '世', '界'}},
{[]rune{'世', '界', '世', '界'}, 8, []rune{'世', '界', '世', '界'}},
{[]rune{'世', '界', '世', '界'}, 9, []rune{'世', '界', '世', '界'}},
{[]rune{'世', 'a', '界', 'ı'}, 0, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 1, []rune{'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 2, []rune{'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, []rune{'界', 'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 4, []rune{'a', '界', 'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 5, []rune{'a', '界', 'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 6, []rune{'世', 'a', '界', 'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 7, []rune{'世', 'a', '界', 'ı'}},
}
for _, test := range tests {
if got := runeSliceWidthLastRange(test.rs, test.maxWidth); !reflect.DeepEqual(got, test.exp) {
t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.exp, got)
}
}
}
@@ -166,23 +219,27 @@ func TestSplitWord(t *testing.T) {
}
}
func TestReadPairs(t *testing.T) {
func TestReadArrays(t *testing.T) {
tests := []struct {
s string
exp [][]string
s string
min_cols int
max_cols int
exp [][]string
}{
{"foo bar", [][]string{{"foo", "bar"}}},
{"foo bar ", [][]string{{"foo", "bar"}}},
{" foo bar", [][]string{{"foo", "bar"}}},
{" foo bar ", [][]string{{"foo", "bar"}}},
{"foo bar#baz", [][]string{{"foo", "bar"}}},
{"foo bar #baz", [][]string{{"foo", "bar"}}},
{`'foo#baz' bar`, [][]string{{"foo#baz", "bar"}}},
{`"foo#baz" bar`, [][]string{{"foo#baz", "bar"}}},
{"foo bar", 2, 2, [][]string{{"foo", "bar"}}},
{"foo bar ", 2, 2, [][]string{{"foo", "bar"}}},
{" foo bar", 2, 2, [][]string{{"foo", "bar"}}},
{" foo bar ", 2, 2, [][]string{{"foo", "bar"}}},
{"foo bar#baz", 2, 2, [][]string{{"foo", "bar"}}},
{"foo bar #baz", 2, 2, [][]string{{"foo", "bar"}}},
{`'foo#baz' bar`, 2, 2, [][]string{{"foo#baz", "bar"}}},
{`"foo#baz" bar`, 2, 2, [][]string{{"foo#baz", "bar"}}},
{"foo bar baz", 3, 3, [][]string{{"foo", "bar", "baz"}}},
{`"foo bar baz"`, 1, 1, [][]string{{"foo bar baz"}}},
}
for _, test := range tests {
if got, _ := readPairs(strings.NewReader(test.s)); !reflect.DeepEqual(got, test.exp) {
if got, _ := readArrays(strings.NewReader(test.s), test.min_cols, test.max_cols); !reflect.DeepEqual(got, test.exp) {
t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got)
}
}
@@ -243,3 +300,89 @@ func TestNaturalLess(t *testing.T) {
}
}
}
type fakeFileInfo struct {
name string
isDir bool
}
func (fileinfo fakeFileInfo) Name() string { return fileinfo.name }
func (fileinfo fakeFileInfo) Size() int64 { return 0 }
func (fileinfo fakeFileInfo) Mode() os.FileMode { return os.FileMode(0o000) }
func (fileinfo fakeFileInfo) ModTime() time.Time { return time.Unix(0, 0) }
func (fileinfo fakeFileInfo) IsDir() bool { return fileinfo.isDir }
func (fileinfo fakeFileInfo) Sys() any { return nil }
func TestGetFileExtension(t *testing.T) {
tests := []struct {
name string
fileName string
isDir bool
expectedExtension string
}{
{"normal file", "file.txt", false, ".txt"},
{"file without extension", "file", false, ""},
{"hidden file", ".gitignore", false, ""},
{"hidden file with extension", ".file.txt", false, ".txt"},
{"directory", "dir", true, ""},
{"hidden directory", ".git", true, ""},
{"directory with dot", "profile.d", true, ""},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := getFileExtension(fakeFileInfo{test.fileName, test.isDir}); got != test.expectedExtension {
t.Errorf("at input '%s' expected '%s' but got '%s'", test.fileName, test.expectedExtension, got)
}
})
}
}
func TestLocaleNaturalLess(t *testing.T) {
tests := []struct {
s1 string
s2 string
exp bool
}{
// preserving behavior of `naturalLess`
{"foo", "bar", false},
{"bar", "baz", true},
{"foo", "123", false},
{"foo1", "foobar", true},
{"foo1", "foo10", true},
{"foo2", "foo10", true},
{"foo1", "foo10bar", true},
{"foo2", "foo10bar", true},
{"foo1bar", "foo10bar", true},
{"foo2bar", "foo10bar", true},
{"foo1bar", "foo10", true},
{"foo2bar", "foo10", true},
// locale sort
{"你好", "他好", true}, // \u4F60\u597D, \u4ED6\u597D
{"到这", "到那", false}, // \u5230\u8FD9, \u5230\u90A3
{"你说", "什么", true}, // \u4f60\u8bf4, \u4ec0\u4e48
{"你好", "World", false}, // \u4F60\u597D, \u57\u6f\u72\u6c\u64
{"甲1", "甲乙", true},
{"甲1", "甲10", true},
{"甲2", "甲10", true},
{"甲1", "甲10乙", true},
{"甲2", "甲10乙", true},
{"甲1乙", "甲10乙", true},
{"甲2乙", "甲10乙", true},
{"甲1乙", "甲10", true},
{"甲2乙", "甲10", true},
}
localeStr := "zh-CN"
collator, err := makeCollator(localeStr, collate.Numeric)
if err != nil {
t.Fatalf("failed to create collator for %q: %s", localeStr, err)
}
for _, test := range tests {
if got := collator.CompareString(test.s1, test.s2) < 0; got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got)
}
}
}
+342 -216
View File
@@ -15,7 +15,8 @@ import (
"strings"
"time"
times "github.com/djherbis/times"
"github.com/djherbis/times"
"golang.org/x/text/collate"
)
type linkState byte
@@ -36,6 +37,85 @@ type file struct {
accessTime time.Time
changeTime time.Time
ext string
err error
}
func newFile(path string) *file {
lstat, err := os.Lstat(path)
if err != nil {
log.Printf("getting file information: %s", err)
return &file{
FileInfo: &fakeStat{name: filepath.Base(path)},
linkState: notLink,
linkTarget: "",
path: path,
dirCount: -1,
dirSize: -1,
accessTime: time.Unix(0, 0),
changeTime: time.Unix(0, 0),
ext: "",
err: err,
}
}
var linkState linkState
var linkTarget string
if lstat.Mode()&os.ModeSymlink != 0 {
stat, err := os.Stat(path)
if err == nil {
linkState = working
lstat = stat
} else {
linkState = broken
}
linkTarget, err = os.Readlink(path)
if err != nil {
log.Printf("reading link target: %s", err)
}
}
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
dirCount := -1
if lstat.IsDir() && gOpts.dircounts {
d, err := os.Open(path)
if err != nil {
dirCount = -2
} else {
names, err := d.Readdirnames(1000)
d.Close()
if names == nil && err != io.EOF {
dirCount = -2
} else {
dirCount = len(names)
}
}
}
return &file{
FileInfo: lstat,
linkState: linkState,
linkTarget: linkTarget,
path: path,
dirCount: dirCount,
dirSize: -1,
accessTime: at,
changeTime: ct,
ext: getFileExtension(lstat),
err: nil,
}
}
func (file *file) TotalSize() int64 {
@@ -48,6 +128,17 @@ func (file *file) TotalSize() int64 {
return file.Size()
}
type fakeStat struct {
name string
}
func (fs *fakeStat) Name() string { return fs.name }
func (fs *fakeStat) Size() int64 { return 0 }
func (fs *fakeStat) Mode() os.FileMode { return os.FileMode(0o000) }
func (fs *fakeStat) ModTime() time.Time { return time.Unix(0, 0) }
func (fs *fakeStat) IsDir() bool { return false }
func (fs *fakeStat) Sys() any { return nil }
func readdir(path string) ([]*file, error) {
f, err := os.Open(path)
if err != nil {
@@ -58,99 +149,32 @@ func readdir(path string) ([]*file, error) {
files := make([]*file, 0, len(names))
for _, fname := range names {
fpath := filepath.Join(path, fname)
lstat, err := os.Lstat(fpath)
if os.IsNotExist(err) {
continue
}
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
var linkState linkState
var linkTarget string
if lstat.Mode()&os.ModeSymlink != 0 {
stat, err := os.Stat(fpath)
if err == nil {
linkState = working
lstat = stat
} else {
linkState = broken
}
linkTarget, err = os.Readlink(fpath)
if err != nil {
log.Printf("reading link target: %s", err)
}
}
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
// returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
ext := filepath.Ext(fpath)
dirCount := -1
if lstat.IsDir() && gOpts.dircounts {
d, err := os.Open(fpath)
if err != nil {
dirCount = -2
} else {
names, err := d.Readdirnames(1000)
d.Close()
if names == nil && err != io.EOF {
dirCount = -2
} else {
dirCount = len(names)
}
}
}
files = append(files, &file{
FileInfo: lstat,
linkState: linkState,
linkTarget: linkTarget,
path: fpath,
dirCount: dirCount,
dirSize: -1,
accessTime: at,
changeTime: ct,
ext: ext,
})
files = append(files, newFile(filepath.Join(path, fname)))
}
return files, err
}
type dir struct {
loading bool // directory is loading from disk
loadTime time.Time // current loading or 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)
sortType sortType // sort method and options from last sort
dironly bool // dironly value from last sort
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
noPerm bool // whether lf has no permission to open the directory
lines []string // lines of text to display if directory previews are enabled
loading bool // directory is loading from disk
loadTime time.Time // current loading or 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
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
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
lines []string // lines of text to display if directory previews are enabled
}
func newDir(path string) *dir {
@@ -172,11 +196,11 @@ func newDir(path string) *dir {
}
func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
if gOpts.ignorecase {
if ignorecase {
s1 = strings.ToLower(s1)
s2 = strings.ToLower(s2)
}
if gOpts.ignoredia {
if ignoredia {
s1 = removeDiacritics(s1)
s2 = removeDiacritics(s2)
}
@@ -184,69 +208,108 @@ func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
}
func (dir *dir) sort() {
dir.sortType = gOpts.sortType
dir.dironly = gOpts.dironly
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)
dir.hiddenfiles = gOpts.hiddenfiles
dir.ignorecase = gOpts.ignorecase
dir.ignoredia = gOpts.ignoredia
dir.files = dir.allFiles
switch dir.sortType.method {
// reverse order cannot be applied after stable sorting, otherwise the order
// of equivalent elements will be reversed
switch dir.sortby {
case naturalSort:
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
return naturalLess(s1, s2)
})
if collator, err := makeCollator(dir.locale, collate.Numeric); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
})
}
case nameSort:
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
return s1 < s2
})
if collator, err := makeCollator(dir.locale); err == nil {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
result := collator.CompareString(s1, s2)
if !dir.reverse {
return result < 0
} else {
return result > 0
}
})
} else {
sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return s1 < s2
} else {
return s2 < s1
}
})
}
case sizeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].TotalSize() < dir.files[j].TotalSize()
if !dir.reverse {
return dir.files[i].TotalSize() < dir.files[j].TotalSize()
} else {
return dir.files[j].TotalSize() < dir.files[i].TotalSize()
}
})
case timeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].ModTime().Before(dir.files[j].ModTime())
if !dir.reverse {
return dir.files[i].ModTime().Before(dir.files[j].ModTime())
} else {
return dir.files[j].ModTime().Before(dir.files[i].ModTime())
}
})
case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
if !dir.reverse {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
} else {
return dir.files[j].accessTime.Before(dir.files[i].accessTime)
}
})
case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
if !dir.reverse {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
} else {
return dir.files[j].changeTime.Before(dir.files[i].changeTime)
}
})
case extSort:
sort.SliceStable(dir.files, func(i, j int) bool {
ext1, ext2 := normalize(dir.files[i].ext, dir.files[j].ext, dir.ignorecase, dir.ignoredia)
// if the extension could not be determined (directories, files without)
// use a zero byte so that these files can be ranked higher
if ext1 == "" {
ext1 = "\x00"
}
if ext2 == "" {
ext2 = "\x00"
}
name1, name2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
// in order to also have natural sorting with the filenames
// combine the name with the ext but have the ext at the front
return ext1 < ext2 || ext1 == ext2 && name1 < name2
if !dir.reverse {
return ext1 < ext2 || ext1 == ext2 && name1 < name2
} else {
return ext2 < ext1 || ext2 == ext1 && name2 < name1
}
})
}
if dir.sortType.option&reverseSort != 0 {
for i, j := 0, len(dir.files)-1; i < j; i, j = i+1, j-1 {
dir.files[i], dir.files[j] = dir.files[j], dir.files[i]
}
}
if dir.sortType.option&dirfirstSort != 0 {
if dir.dirfirst {
sort.SliceStable(dir.files, func(i, j int) bool {
if dir.files[i].IsDir() == dir.files[j].IsDir() {
return i < j
@@ -278,7 +341,7 @@ func (dir *dir) sort() {
// 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.sortType.option&hiddenSort == 0 {
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
@@ -344,8 +407,27 @@ func (dir *dir) sel(name string, height int) {
}
}
edge := min(min(height/2, gOpts.scrolloff), len(dir.files)-dir.ind-1)
dir.pos = min(dir.ind, height-edge-1)
dir.boundPos(height)
}
func (dir *dir) boundPos(height int) {
if len(dir.files) <= height {
dir.pos = dir.ind
return
}
edge := min(height/2, gOpts.scrolloff)
dir.pos = max(dir.pos, edge)
// use a smaller value for half when the height is even and scrolloff is
// maxed in order to stay at the same row while scrolling up and down
if height%2 == 0 {
edge = min(height/2-1, gOpts.scrolloff)
}
dir.pos = min(dir.pos, height-1-edge)
dir.pos = min(dir.pos, dir.ind)
dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind))
}
type nav struct {
@@ -370,6 +452,8 @@ type nav struct {
dirPreviewChan chan *dir
dirChan chan *dir
regChan chan *reg
fileChan chan *file
delChan chan string
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
@@ -401,7 +485,12 @@ func (nav *nav) loadDirInternal(path string) *dir {
loading: true,
loadTime: time.Now(),
path: path,
sortType: gOpts.sortType,
sortby: getSortBy(path),
dirfirst: getDirFirst(path),
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
locale: getLocale(path),
hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia,
@@ -414,7 +503,6 @@ func (nav *nav) loadDirInternal(path string) *dir {
nav.dirPreviewChan <- d
}
nav.dirChan <- d
}()
return d
}
@@ -457,15 +545,17 @@ func (nav *nav) checkDir(dir *dir) {
dir.loadTime = now
go func() {
nd := newDir(dir.path)
nd.filter = dir.filter
nd.sort()
if gOpts.dirpreviews {
nav.dirPreviewChan <- nd
}
nav.dirChan <- nd
}()
case dir.sortType != gOpts.sortType ||
dir.dironly != gOpts.dironly ||
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:
@@ -486,7 +576,9 @@ func (nav *nav) getDirs(wd string) {
for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
dir := nav.loadDir(curr)
dir.sel(base, nav.height)
if base != "" {
dir.sel(base, nav.height)
}
dirs = append(dirs, dir)
}
@@ -509,6 +601,8 @@ func newNav(height int) *nav {
dirPreviewChan: make(chan *dir, 1024),
dirChan: make(chan *dir),
regChan: make(chan *reg),
fileChan: make(chan *file),
delChan: make(chan string),
dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
@@ -574,13 +668,8 @@ func (nav *nav) reload() error {
nav.dirCache = make(map[string]*dir)
nav.regCache = make(map[string]*reg)
wd, err := os.Getwd()
if err != nil {
return fmt.Errorf("getting current directory: %s", err)
}
curr, err := nav.currFile()
nav.getDirs(wd)
nav.getDirs(nav.currDir().path)
if err == nil {
last := nav.dirs[len(nav.dirs)-1]
last.files = append(last.files, curr)
@@ -608,12 +697,24 @@ func (nav *nav) exportFiles() {
var currFile string
if curr, err := nav.currFile(); err == nil {
currFile = curr.path
currFile = quoteString(curr.path)
}
currSelections := nav.currSelections()
var selections []string
for _, selection := range nav.currSelections() {
selections = append(selections, quoteString(selection))
}
currSelections := strings.Join(selections, gOpts.filesep)
exportFiles(currFile, currSelections, nav.currDir().path)
os.Setenv("f", currFile)
os.Setenv("fs", currSelections)
os.Setenv("PWD", quoteString(nav.currDir().path))
if len(selections) == 0 {
os.Setenv("fx", currFile)
} else {
os.Setenv("fx", currSelections)
}
}
func (nav *nav) dirPreviewLoop(ui *ui) {
@@ -648,13 +749,12 @@ func (nav *nav) previewLoop(ui *ui) {
}
win := ui.wins[len(ui.wins)-1]
if clear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.cleaner, prev,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y))
strconv.Itoa(win.y),
path)
if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err)
}
@@ -667,7 +767,6 @@ func (nav *nav) previewLoop(ui *ui) {
}
}
//lint:ignore U1000 This function is not used on Windows
func matchPattern(pattern, name, path string) bool {
s := name
@@ -684,7 +783,6 @@ func matchPattern(pattern, name, path string) bool {
}
func (nav *nav) previewDir(dir *dir, win *win) {
defer func() {
dir.loading = false
nav.dirChan <- dir
@@ -693,8 +791,6 @@ func (nav *nav) previewDir(dir *dir, win *win) {
var reader io.Reader
if len(gOpts.previewer) != 0 {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.previewer, dir.path,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
@@ -742,19 +838,15 @@ func (nav *nav) previewDir(dir *dir, win *win) {
log.Printf("loading dir: %s", buf.Err())
}
}
}
func (nav *nav) preview(path string, win *win) {
reg := &reg{loadTime: time.Now(), path: path}
defer func() { nav.regChan <- reg }()
var reader io.Reader
var reader *bufio.Reader
if len(gOpts.previewer) != 0 {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.previewer, path,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
@@ -786,7 +878,7 @@ func (nav *nav) preview(path string, win *win) {
}
}()
defer out.Close()
reader = out
reader = bufio.NewReader(out)
} else {
f, err := os.Open(path)
if err != nil {
@@ -795,23 +887,47 @@ func (nav *nav) preview(path string, win *win) {
}
defer f.Close()
reader = f
reader = bufio.NewReader(f)
}
buf := bufio.NewScanner(reader)
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
}
}
for i := 0; i < win.h && buf.Scan(); i++ {
for _, r := range buf.Text() {
if r == 0 {
// 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
}
for _, byte := range bytes {
if byte == 0 {
reg.lines = []string{"\033[7mbinary\033[0m"}
return
}
}
reg.lines = append(reg.lines, buf.Text())
}
if buf.Err() != nil {
log.Printf("loading file: %s", buf.Err())
line = append(line, bytes...)
if !isPrefix {
reg.lines = append(reg.lines, string(line))
line = []byte{}
}
}
}
@@ -902,8 +1018,7 @@ func (nav *nav) up(dist int) bool {
dir.ind = max(0, dir.ind)
dir.pos -= dist
edge := min(min(nav.height/2, gOpts.scrolloff), dir.ind)
dir.pos = max(dir.pos, edge)
dir.boundPos(nav.height)
return old != dir.ind
}
@@ -926,16 +1041,7 @@ func (nav *nav) down(dist int) bool {
dir.ind = min(maxind, dir.ind)
dir.pos += dist
// use a smaller value for half when the height is even and scrolloff is
// maxed in order to stay at the same row while scrolling up and down
half := nav.height / 2
if nav.height%2 == 0 {
half--
}
edge := min(min(half, gOpts.scrolloff), maxind-dir.ind)
dir.pos = min(dir.pos, nav.height-edge-1)
dir.pos = min(dir.pos, maxind)
dir.boundPos(nav.height)
return old != dir.ind
}
@@ -1060,7 +1166,7 @@ func (nav *nav) high() bool {
old := dir.ind
beg := max(dir.ind-dir.pos, 0)
offs := gOpts.scrolloff
offs := min(nav.height/2, gOpts.scrolloff)
if beg == 0 {
offs = 0
}
@@ -1091,7 +1197,14 @@ func (nav *nav) low() bool {
old := dir.ind
beg := max(dir.ind-dir.pos, 0)
end := min(beg+nav.height, len(dir.files))
offs := gOpts.scrolloff
offs := min(nav.height/2, gOpts.scrolloff)
// use a smaller value for half when the height is even and scrolloff is
// maxed in order to stay at the same row when using both high and low
if nav.height%2 == 0 {
offs = min(nav.height/2-1, gOpts.scrolloff)
}
if end == len(dir.files) {
offs = 0
}
@@ -1236,7 +1349,7 @@ func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) {
nav.copyTotalChan <- total
nums, errs := copyAll(srcs, dstDir)
nums, errs := copyAll(srcs, dstDir, gOpts.preserve)
errCount := 0
loop:
@@ -1296,7 +1409,8 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
continue
}
dst := filepath.Join(dstDir, filepath.Base(src))
file := filepath.Base(src)
dst := filepath.Join(dstDir, file)
dstStat, err := os.Stat(dst)
if os.SameFile(srcStat, dstStat) {
@@ -1305,9 +1419,15 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
app.ui.exprChan <- echo
continue
} else if !os.IsNotExist(err) {
ext := getFileExtension(dstStat)
basename := file[:len(file)-len(ext)]
var newPath string
for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i)
file = strings.ReplaceAll(gOpts.dupfilefmt, "%f", basename+ext)
file = strings.ReplaceAll(file, "%b", basename)
file = strings.ReplaceAll(file, "%e", ext)
file = strings.ReplaceAll(file, "%n", strconv.Itoa(i))
newPath = filepath.Join(dstDir, file)
_, err = os.Lstat(newPath)
}
dst = newPath
@@ -1324,7 +1444,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
nav.copyTotalChan <- total
nums, errs := copyAll([]string{src}, dstDir)
nums, errs := copyAll([]string{src}, dstDir, []string{"mode", "timestamps"})
oldCount := errCount
loop:
@@ -1373,6 +1493,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
}
if errCount == 0 {
app.ui.exprChan <- &callExpr{"clear", nil, 1}
app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mMoved successfully\033[0m"}, 1}
}
}
@@ -1393,19 +1514,6 @@ func (nav *nav) paste(app *app) error {
go nav.copyAsync(app, srcs, dstDir)
} else {
go nav.moveAsync(app, srcs, dstDir)
if err := saveFiles(nil, false); err != nil {
return fmt.Errorf("clearing copy/cut buffer: %s", err)
}
if gSingleMode {
if err := nav.sync(); err != nil {
return fmt.Errorf("paste: %s", err)
}
} else {
if err := remote("send sync"); err != nil {
return fmt.Errorf("paste: %s", err)
}
}
}
return nil
@@ -1472,7 +1580,13 @@ func (nav *nav) rename() error {
dir := nav.loadDir(filepath.Dir(newPath))
if dir.loading {
dir.files = append(dir.files, &file{FileInfo: lstat})
for i := range dir.allFiles {
if dir.allFiles[i].path == oldPath {
dir.allFiles[i] = &file{FileInfo: lstat}
break
}
}
dir.sort()
}
dir.sel(lstat.Name(), nav.height)
@@ -1540,13 +1654,18 @@ func (nav *nav) sel(path string) error {
base := filepath.Base(path)
last := nav.dirs[len(nav.dirs)-1]
last := nav.currDir()
if last.loading {
last.files = append(last.files, &file{FileInfo: lstat})
}
last.sel(base, nav.height)
for i, f := range last.files {
if f.Name() == base {
nav.move(i)
break
}
}
return nil
}
@@ -1654,7 +1773,7 @@ func (nav *nav) findPrev() (bool, bool) {
return false, false
}
func searchMatch(name, pattern string) (matched bool, err error) {
func searchMatch(name, pattern string, glob bool) (matched bool, err error) {
if gOpts.ignorecase {
lpattern := strings.ToLower(pattern)
if !gOpts.smartcase || lpattern == pattern {
@@ -1669,7 +1788,7 @@ func searchMatch(name, pattern string) (matched bool, err error) {
name = removeDiacritics(name)
}
}
if gOpts.globsearch {
if glob {
return filepath.Match(pattern, name)
}
return strings.Contains(name, pattern), nil
@@ -1678,7 +1797,7 @@ func searchMatch(name, pattern string) (matched bool, err error) {
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); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
return false, err
} else if matched {
return nav.down(i - dir.ind), nil
@@ -1686,7 +1805,7 @@ func (nav *nav) searchNext() (bool, error) {
}
if gOpts.wrapscan {
for i := 0; i < dir.ind; i++ {
if matched, err := searchMatch(dir.files[i].Name(), nav.search); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
return false, err
} else if matched {
return nav.up(dir.ind - i), nil
@@ -1699,7 +1818,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); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
return false, err
} else if matched {
return nav.up(dir.ind - i), nil
@@ -1707,7 +1826,7 @@ 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); err != nil {
if matched, err := searchMatch(dir.files[i].Name(), nav.search, gOpts.globsearch); err != nil {
return false, err
} else if matched {
return nav.down(i - dir.ind), nil
@@ -1719,7 +1838,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, "!"))
matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!"), gOpts.globfilter)
if err != nil {
log.Printf("Filter Error: %s", err)
return false
@@ -1754,9 +1873,12 @@ func (nav *nav) readMarks() error {
scanner := bufio.NewScanner(f)
for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), ":", 2)
if _, ok := nav.marks[toks[0]]; !ok {
nav.marks[toks[0]] = toks[1]
mark, path, found := strings.Cut(scanner.Text(), ":")
if !found {
return fmt.Errorf("invalid marks file entry: %s", scanner.Text())
}
if _, ok := nav.marks[mark]; !ok {
nav.marks[mark] = path
}
}
@@ -1787,7 +1909,7 @@ func (nav *nav) writeMarks() error {
sort.Strings(keys)
for _, k := range keys {
_, err = f.WriteString(fmt.Sprintf("%s:%s\n", k, nav.marks[k]))
_, err = fmt.Fprintf(f, "%s:%s\n", k, nav.marks[k])
if err != nil {
return fmt.Errorf("writing marks file: %s", err)
}
@@ -1810,11 +1932,16 @@ func (nav *nav) readTags() error {
scanner := bufio.NewScanner(f)
for scanner.Scan() {
text := scanner.Text()
ind := strings.LastIndex(text, ":")
if ind == -1 {
return fmt.Errorf("invalid tags file entry: %s", text)
}
path := text[0:ind]
mark := text[ind+1:]
tag := text[ind+1:]
if _, ok := nav.tags[path]; !ok {
nav.tags[path] = mark
nav.tags[path] = tag
}
}
@@ -1843,7 +1970,7 @@ func (nav *nav) writeTags() error {
sort.Strings(keys)
for _, k := range keys {
_, err = f.WriteString(fmt.Sprintf("%s:%s\n", k, nav.tags[k]))
_, err = fmt.Fprintf(f, "%s:%s\n", k, nav.tags[k])
if err != nil {
return fmt.Errorf("writing tags file: %s", err)
}
@@ -1881,7 +2008,6 @@ func (m indexedSelections) Swap(i, j int) {
func (m indexedSelections) Less(i, j int) bool { return m.indices[i] < m.indices[j] }
func (nav *nav) currSelections() []string {
currDirOnly := gOpts.selmode == "dir"
currDirPath := ""
if currDirOnly {
+263 -135
View File
@@ -1,56 +1,74 @@
package main
import "time"
type sortMethod byte
const (
naturalSort sortMethod = iota
nameSort
sizeSort
timeSort
atimeSort
ctimeSort
extSort
import (
"path/filepath"
"time"
)
type sortOption byte
// String values match the sortby string sent by the user at startup
type sortMethod string
const (
dirfirstSort sortOption = 1 << iota
hiddenSort
reverseSort
naturalSort sortMethod = "natural"
nameSort sortMethod = "name"
sizeSort sortMethod = "size"
timeSort sortMethod = "time"
atimeSort sortMethod = "atime"
ctimeSort sortMethod = "ctime"
extSort sortMethod = "ext"
)
type sortType struct {
method sortMethod
option sortOption
func isValidSortMethod(method sortMethod) bool {
return method == naturalSort ||
method == nameSort ||
method == sizeSort ||
method == timeSort ||
method == atimeSort ||
method == ctimeSort ||
method == extSort
}
const invalidSortErrorMessage = `sortby: value should either be 'natural', 'name', 'size', 'time', 'atime', 'ctime' or 'ext'`
var gOpts struct {
anchorfind bool
autoquit bool
borderfmt 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
hidden bool
icons bool
ignorecase bool
ignoredia bool
incfilter bool
incsearch bool
locale string
mouse bool
number bool
preview bool
relativenumber bool
reverse bool
roundbox bool
selectfmt string
showbinds bool
sixel bool
sortby sortMethod
smartcase bool
smartdia bool
waitmsg string
watch bool
wrapscan bool
wrapscroll bool
findlen int
@@ -66,50 +84,148 @@ var gOpts struct {
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
ruler []string
rulerfmt string
preserve []string
shellopts []string
keys map[string]expr
cmdkeys map[string]expr
cmds map[string]expr
user map[string]string
sortType sortType
tempmarks string
numberfmt string
tagfmt string
}
var gLocalOpts struct {
sortbys map[string]sortMethod
dirfirsts map[string]bool
dironlys map[string]bool
hiddens map[string]bool
reverses map[string]bool
infos map[string][]string
locales map[string]string
}
func localOptPaths(path string) []string {
list := []string{path}
for curr := path; !isRoot(curr); curr = filepath.Dir(curr) {
list = append(list, curr+string(filepath.Separator))
}
return list
}
func getDirFirst(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.dirfirsts[key]; ok {
return val
}
}
return gOpts.dirfirst
}
func getDirOnly(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.dironlys[key]; ok {
return val
}
}
return gOpts.dironly
}
func getHidden(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.hiddens[key]; ok {
return val
}
}
return gOpts.hidden
}
func getInfo(path string) []string {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.infos[key]; ok {
return val
}
}
return gOpts.info
}
func getReverse(path string) bool {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.reverses[key]; ok {
return val
}
}
return gOpts.reverse
}
func getSortBy(path string) sortMethod {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.sortbys[key]; ok {
return val
}
}
return gOpts.sortby
}
func getLocale(path string) string {
for _, key := range localOptPaths(path) {
if val, ok := gLocalOpts.locales[key]; ok {
return val
}
}
return gOpts.locale
}
func init() {
gOpts.anchorfind = true
gOpts.autoquit = false
gOpts.autoquit = true
gOpts.dircache = true
gOpts.dircounts = false
gOpts.dirfirst = true
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.hidden = false
gOpts.icons = false
gOpts.ignorecase = true
gOpts.ignoredia = true
gOpts.incfilter = false
gOpts.incsearch = false
gOpts.locale = localeStrDisable
gOpts.mouse = false
gOpts.number = false
gOpts.preview = true
gOpts.relativenumber = false
gOpts.reverse = false
gOpts.roundbox = false
gOpts.selectfmt = "\033[7;35m"
gOpts.showbinds = true
gOpts.sixel = false
gOpts.sortby = naturalSort
gOpts.smartcase = true
gOpts.smartdia = false
gOpts.waitmsg = "Press any key to continue"
gOpts.watch = false
gOpts.wrapscan = true
gOpts.wrapscroll = false
gOpts.findlen = 1
@@ -125,136 +241,148 @@ func init() {
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 = []string{".*"}
gOpts.hiddenfiles = gDefaultHiddenFiles
gOpts.history = true
gOpts.info = nil
gOpts.ruler = []string{"acc", "progress", "selection", "ind"}
gOpts.rulerfmt = " %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"
gOpts.preserve = []string{"mode"}
gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort}
gOpts.tempmarks = "'"
gOpts.numberfmt = "\033[33m"
gOpts.tagfmt = "\033[31m"
gOpts.keys = make(map[string]expr)
gOpts.keys = map[string]expr{
"k": &callExpr{"up", nil, 1},
"<up>": &callExpr{"up", nil, 1},
"<m-up>": &callExpr{"up", nil, 1},
"<c-u>": &callExpr{"half-up", nil, 1},
"<c-b>": &callExpr{"page-up", nil, 1},
"<pgup>": &callExpr{"page-up", nil, 1},
"<c-y>": &callExpr{"scroll-up", nil, 1},
"<c-m-up>": &callExpr{"scroll-up", nil, 1},
"j": &callExpr{"down", nil, 1},
"<down>": &callExpr{"down", nil, 1},
"<m-down>": &callExpr{"down", nil, 1},
"<c-d>": &callExpr{"half-down", nil, 1},
"<c-f>": &callExpr{"page-down", nil, 1},
"<pgdn>": &callExpr{"page-down", nil, 1},
"<c-e>": &callExpr{"scroll-down", nil, 1},
"<c-m-down>": &callExpr{"scroll-down", nil, 1},
"h": &callExpr{"updir", nil, 1},
"<left>": &callExpr{"updir", nil, 1},
"l": &callExpr{"open", nil, 1},
"<right>": &callExpr{"open", nil, 1},
"q": &callExpr{"quit", nil, 1},
"gg": &callExpr{"top", nil, 1},
"<home>": &callExpr{"top", nil, 1},
"G": &callExpr{"bottom", nil, 1},
"<end>": &callExpr{"bottom", nil, 1},
"H": &callExpr{"high", nil, 1},
"M": &callExpr{"middle", nil, 1},
"L": &callExpr{"low", nil, 1},
"[": &callExpr{"jump-prev", nil, 1},
"]": &callExpr{"jump-next", nil, 1},
"<space>": &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1},
"t": &callExpr{"tag-toggle", nil, 1},
"v": &callExpr{"invert", nil, 1},
"u": &callExpr{"unselect", nil, 1},
"y": &callExpr{"copy", nil, 1},
"d": &callExpr{"cut", nil, 1},
"c": &callExpr{"clear", nil, 1},
"p": &callExpr{"paste", nil, 1},
"<c-l>": &callExpr{"redraw", nil, 1},
"<c-r>": &callExpr{"reload", nil, 1},
":": &callExpr{"read", nil, 1},
"$": &callExpr{"shell", nil, 1},
"%": &callExpr{"shell-pipe", nil, 1},
"!": &callExpr{"shell-wait", nil, 1},
"&": &callExpr{"shell-async", nil, 1},
"f": &callExpr{"find", nil, 1},
"F": &callExpr{"find-back", nil, 1},
";": &callExpr{"find-next", nil, 1},
",": &callExpr{"find-prev", nil, 1},
"/": &callExpr{"search", nil, 1},
"?": &callExpr{"search-back", nil, 1},
"n": &callExpr{"search-next", nil, 1},
"N": &callExpr{"search-prev", nil, 1},
"m": &callExpr{"mark-save", nil, 1},
"'": &callExpr{"mark-load", nil, 1},
`"`: &callExpr{"mark-remove", nil, 1},
`r`: &callExpr{"rename", nil, 1},
"<c-n>": &callExpr{"cmd-history-next", nil, 1},
"<c-p>": &callExpr{"cmd-history-prev", nil, 1},
gOpts.keys["k"] = &callExpr{"up", nil, 1}
gOpts.keys["<up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<m-up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1}
gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<pgup>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<c-y>"] = &callExpr{"scroll-up", nil, 1}
gOpts.keys["<c-m-up>"] = &callExpr{"scroll-up", nil, 1}
gOpts.keys["j"] = &callExpr{"down", nil, 1}
gOpts.keys["<down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<m-down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1}
gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<pgdn>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<c-e>"] = &callExpr{"scroll-down", nil, 1}
gOpts.keys["<c-m-down>"] = &callExpr{"scroll-down", nil, 1}
gOpts.keys["h"] = &callExpr{"updir", nil, 1}
gOpts.keys["<left>"] = &callExpr{"updir", nil, 1}
gOpts.keys["l"] = &callExpr{"open", nil, 1}
gOpts.keys["<right>"] = &callExpr{"open", nil, 1}
gOpts.keys["q"] = &callExpr{"quit", nil, 1}
gOpts.keys["gg"] = &callExpr{"top", nil, 0}
gOpts.keys["<home>"] = &callExpr{"top", nil, 0}
gOpts.keys["G"] = &callExpr{"bottom", nil, 0}
gOpts.keys["<end>"] = &callExpr{"bottom", nil, 0}
gOpts.keys["H"] = &callExpr{"high", nil, 1}
gOpts.keys["M"] = &callExpr{"middle", nil, 1}
gOpts.keys["L"] = &callExpr{"low", nil, 1}
gOpts.keys["["] = &callExpr{"jump-prev", nil, 1}
gOpts.keys["]"] = &callExpr{"jump-next", nil, 1}
gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
gOpts.keys["t"] = &callExpr{"tag-toggle", nil, 1}
gOpts.keys["v"] = &callExpr{"invert", nil, 1}
gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"copy", nil, 1}
gOpts.keys["d"] = &callExpr{"cut", nil, 1}
gOpts.keys["c"] = &callExpr{"clear", nil, 1}
gOpts.keys["p"] = &callExpr{"paste", nil, 1}
gOpts.keys["<c-l>"] = &callExpr{"redraw", nil, 1}
gOpts.keys["<c-r>"] = &callExpr{"reload", nil, 1}
gOpts.keys[":"] = &callExpr{"read", nil, 1}
gOpts.keys["$"] = &callExpr{"shell", nil, 1}
gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1}
gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1}
gOpts.keys["&"] = &callExpr{"shell-async", nil, 1}
gOpts.keys["f"] = &callExpr{"find", nil, 1}
gOpts.keys["F"] = &callExpr{"find-back", nil, 1}
gOpts.keys[";"] = &callExpr{"find-next", nil, 1}
gOpts.keys[","] = &callExpr{"find-prev", nil, 1}
gOpts.keys["/"] = &callExpr{"search", nil, 1}
gOpts.keys["?"] = &callExpr{"search-back", nil, 1}
gOpts.keys["n"] = &callExpr{"search-next", nil, 1}
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
"zh": &setExpr{"hidden!", ""},
"zr": &setExpr{"reverse!", ""},
"zn": &setExpr{"info", ""},
"zs": &setExpr{"info", "size"},
"zt": &setExpr{"info", "time"},
"za": &setExpr{"info", "size:time"},
"sn": &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1},
"ss": &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1},
"st": &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1},
"sa": &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1},
"sc": &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1},
"se": &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1},
"gh": &callExpr{"cd", []string{"~"}, 1},
}
gOpts.keys["zh"] = &setExpr{"hidden!", ""}
gOpts.keys["zr"] = &setExpr{"reverse!", ""}
gOpts.keys["zn"] = &setExpr{"info", ""}
gOpts.keys["zs"] = &setExpr{"info", "size"}
gOpts.keys["zt"] = &setExpr{"info", "time"}
gOpts.keys["za"] = &setExpr{"info", "size:time"}
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1}
gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1}
gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1}
gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1}
gOpts.cmdkeys = make(map[string]expr)
gOpts.cmdkeys["<space>"] = &callExpr{"cmd-insert", []string{" "}, 1}
gOpts.cmdkeys["<esc>"] = &callExpr{"cmd-escape", nil, 1}
gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-complete", nil, 1}
gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<down>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<up>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<backspace>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<backspace2>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<c-f>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<home>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<c-a>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<end>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-e>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-u>"] = &callExpr{"cmd-delete-home", nil, 1}
gOpts.cmdkeys["<c-k>"] = &callExpr{"cmd-delete-end", nil, 1}
gOpts.cmdkeys["<c-w>"] = &callExpr{"cmd-delete-unix-word", nil, 1}
gOpts.cmdkeys["<c-y>"] = &callExpr{"cmd-yank", nil, 1}
gOpts.cmdkeys["<c-t>"] = &callExpr{"cmd-transpose", nil, 1}
gOpts.cmdkeys["<c-c>"] = &callExpr{"cmd-interrupt", nil, 1}
gOpts.cmdkeys["<a-f>"] = &callExpr{"cmd-word", nil, 1}
gOpts.cmdkeys["<a-b>"] = &callExpr{"cmd-word-back", nil, 1}
gOpts.cmdkeys["<a-c>"] = &callExpr{"cmd-capitalize-word", nil, 1}
gOpts.cmdkeys["<a-d>"] = &callExpr{"cmd-delete-word", nil, 1}
gOpts.cmdkeys["<a-u>"] = &callExpr{"cmd-uppercase-word", nil, 1}
gOpts.cmdkeys["<a-l>"] = &callExpr{"cmd-lowercase-word", nil, 1}
gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1}
gOpts.cmdkeys = map[string]expr{
"<space>": &callExpr{"cmd-insert", []string{" "}, 1},
"<esc>": &callExpr{"cmd-escape", nil, 1},
"<tab>": &callExpr{"cmd-complete", nil, 1},
"<enter>": &callExpr{"cmd-enter", nil, 1},
"<c-j>": &callExpr{"cmd-enter", nil, 1},
"<down>": &callExpr{"cmd-history-next", nil, 1},
"<c-n>": &callExpr{"cmd-history-next", nil, 1},
"<up>": &callExpr{"cmd-history-prev", nil, 1},
"<c-p>": &callExpr{"cmd-history-prev", nil, 1},
"<delete>": &callExpr{"cmd-delete", nil, 1},
"<c-d>": &callExpr{"cmd-delete", nil, 1},
"<backspace>": &callExpr{"cmd-delete-back", nil, 1},
"<backspace2>": &callExpr{"cmd-delete-back", nil, 1},
"<left>": &callExpr{"cmd-left", nil, 1},
"<c-b>": &callExpr{"cmd-left", nil, 1},
"<right>": &callExpr{"cmd-right", nil, 1},
"<c-f>": &callExpr{"cmd-right", nil, 1},
"<home>": &callExpr{"cmd-home", nil, 1},
"<c-a>": &callExpr{"cmd-home", nil, 1},
"<end>": &callExpr{"cmd-end", nil, 1},
"<c-e>": &callExpr{"cmd-end", nil, 1},
"<c-u>": &callExpr{"cmd-delete-home", nil, 1},
"<c-k>": &callExpr{"cmd-delete-end", nil, 1},
"<c-w>": &callExpr{"cmd-delete-unix-word", nil, 1},
"<c-y>": &callExpr{"cmd-yank", nil, 1},
"<c-t>": &callExpr{"cmd-transpose", nil, 1},
"<c-c>": &callExpr{"cmd-interrupt", nil, 1},
"<a-f>": &callExpr{"cmd-word", nil, 1},
"<a-b>": &callExpr{"cmd-word-back", nil, 1},
"<a-c>": &callExpr{"cmd-capitalize-word", nil, 1},
"<a-d>": &callExpr{"cmd-delete-word", nil, 1},
"<a-backspace>": &callExpr{"cmd-delete-word-back", nil, 1},
"<a-backspace2>": &callExpr{"cmd-delete-word-back", nil, 1},
"<a-u>": &callExpr{"cmd-uppercase-word", nil, 1},
"<a-l>": &callExpr{"cmd-lowercase-word", nil, 1},
"<a-t>": &callExpr{"cmd-transpose-word", nil, 1},
}
gOpts.cmds = make(map[string]expr)
gOpts.user = make(map[string]string)
gLocalOpts.sortbys = make(map[string]sortMethod)
gLocalOpts.dirfirsts = make(map[string]bool)
gLocalOpts.dironlys = make(map[string]bool)
gLocalOpts.hiddens = make(map[string]bool)
gLocalOpts.reverses = make(map[string]bool)
gLocalOpts.infos = make(map[string][]string)
gLocalOpts.locales = make(map[string]string)
setDefaults()
}
+39 -57
View File
@@ -3,6 +3,7 @@
package main
import (
"cmp"
"fmt"
"log"
"os"
@@ -10,6 +11,7 @@ import (
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
@@ -24,10 +26,11 @@ var (
)
var (
gDefaultShell = "sh"
gDefaultShellFlag = "-c"
gDefaultSocketProt = "unix"
gDefaultSocketPath string
gDefaultShell = "sh"
gDefaultShellFlag = "-c"
gDefaultSocketProt = "unix"
gDefaultSocketPath string
gDefaultHiddenFiles = []string{".*"}
)
var (
@@ -51,10 +54,7 @@ func init() {
}
if envEditor == "" {
envEditor = os.Getenv("EDITOR")
if envEditor == "" {
envEditor = "vi"
}
envEditor = cmp.Or(os.Getenv("EDITOR"), "vi")
}
if envPager == "" {
@@ -84,10 +84,11 @@ func init() {
}
gUser = u
config := os.Getenv("XDG_CONFIG_HOME")
if config == "" {
config = filepath.Join(gUser.HomeDir, ".config")
}
config := cmp.Or(
os.Getenv("LF_CONFIG_HOME"),
os.Getenv("XDG_CONFIG_HOME"),
filepath.Join(gUser.HomeDir, ".config"),
)
gConfigPaths = []string{
filepath.Join("/etc", "lf", "lfrc"),
@@ -104,20 +105,18 @@ func init() {
filepath.Join(config, "lf", "icons"),
}
data := os.Getenv("XDG_DATA_HOME")
if data == "" {
data = filepath.Join(gUser.HomeDir, ".local", "share")
}
data := cmp.Or(
os.Getenv("LF_DATA_HOME"),
os.Getenv("XDG_DATA_HOME"),
filepath.Join(gUser.HomeDir, ".local", "share"),
)
gFilesPath = filepath.Join(data, "lf", "files")
gMarksPath = filepath.Join(data, "lf", "marks")
gTagsPath = filepath.Join(data, "lf", "tags")
gHistoryPath = filepath.Join(data, "lf", "history")
runtime := os.Getenv("XDG_RUNTIME_DIR")
if runtime == "" {
runtime = os.TempDir()
}
runtime := cmp.Or(os.Getenv("XDG_RUNTIME_DIR"), os.TempDir())
gDefaultSocketPath = filepath.Join(runtime, fmt.Sprintf("lf.%s.sock", gUser.Username))
}
@@ -148,7 +147,7 @@ func shellKill(cmd *exec.Cmd) error {
pgid, err := unix.Getpgid(cmd.Process.Pid)
if err == nil && cmd.Process.Pid == pgid {
// kill the process group
err = unix.Kill(-pgid, 15)
err = unix.Kill(-pgid, syscall.SIGTERM)
if err == nil {
return nil
}
@@ -164,24 +163,25 @@ func setDefaults() {
gOpts.cmds["doc"] = &execExpr{"$", `"$lf" -doc | $PAGER`}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
gOpts.cmds["maps"] = &execExpr{"$", `"$lf" -remote "query $id maps" | $PAGER`}
gOpts.cmds["cmaps"] = &execExpr{"$", `"$lf" -remote "query $id cmaps" | $PAGER`}
gOpts.cmds["cmds"] = &execExpr{"$", `"$lf" -remote "query $id cmds" | $PAGER`}
}
func setUserUmask() {
unix.Umask(0077)
unix.Umask(0o077)
}
func isExecutable(f os.FileInfo) bool {
return f.Mode()&0111 != 0
return f.Mode()&0o111 != 0
}
func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
hidden := false
for _, pattern := range hiddenfiles {
matched := matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path)
if strings.HasPrefix(pattern, "!") && matched {
hidden = false
} else if matched {
hidden = true
if matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path) {
hidden = !strings.HasPrefix(pattern, "!")
}
}
return hidden
@@ -189,25 +189,29 @@ func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
func userName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if u, err := user.LookupId(fmt.Sprint(stat.Uid)); err == nil {
return fmt.Sprintf("%v ", u.Username)
uid := strconv.FormatUint(uint64(stat.Uid), 10)
if u, err := user.LookupId(uid); err == nil {
return u.Username
}
return uid
}
return ""
}
func groupName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if g, err := user.LookupGroupId(fmt.Sprint(stat.Gid)); err == nil {
return fmt.Sprintf("%v ", g.Name)
gid := strconv.FormatUint(uint64(stat.Gid), 10)
if g, err := user.LookupGroupId(gid); err == nil {
return g.Name
}
return gid
}
return ""
}
func linkCount(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
return fmt.Sprintf("%v ", stat.Nlink)
return strconv.FormatUint(uint64(stat.Nlink), 10)
}
return ""
}
@@ -216,28 +220,6 @@ func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(unix.Errno) == unix.EXDEV
}
func exportFiles(f string, fs []string, pwd string) {
envFile := f
envFiles := strings.Join(fs, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
os.Setenv("PWD", pwd)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
}
func diskFree(wd string) string {
var stat unix.Statfs_t
if err := unix.Statfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize)))
func quoteString(s string) string {
return s
}
+71 -56
View File
@@ -1,6 +1,7 @@
package main
import (
"cmp"
"fmt"
"log"
"os"
@@ -8,6 +9,7 @@ import (
"os/user"
"path/filepath"
"strings"
"syscall"
"golang.org/x/sys/windows"
)
@@ -22,10 +24,11 @@ var (
var envPathExt = os.Getenv("PATHEXT")
var (
gDefaultShell = "cmd"
gDefaultShellFlag = "/c"
gDefaultSocketProt = "tcp"
gDefaultSocketPath = "127.0.0.1:12345"
gDefaultShell = "cmd"
gDefaultShellFlag = "/c"
gDefaultSocketProt = "unix"
gDefaultSocketPath string
gDefaultHiddenFiles []string
)
var (
@@ -45,10 +48,7 @@ func init() {
}
if envEditor == "" {
envEditor = os.Getenv("EDITOR")
if envEditor == "" {
envEditor = "notepad"
}
envEditor = cmp.Or(os.Getenv("EDITOR"), "notepad")
}
if envPager == "" {
@@ -59,16 +59,22 @@ func init() {
envShell = "cmd"
}
u, err := user.Current()
homeDir, err := os.UserHomeDir()
if err != nil {
log.Printf("user: %s", err)
panic(err)
}
gUser = u
// remove domain prefix
gUser.Username = strings.Split(gUser.Username, `\`)[1]
username := os.Getenv("USERNAME")
if username == "" {
panic("$USERNAME variable is empty or not set")
}
data := os.Getenv("LOCALAPPDATA")
gUser = &user.User{
HomeDir: homeDir,
Username: username,
}
data := cmp.Or(os.Getenv("LF_CONFIG_HOME"), os.Getenv("LOCALAPPDATA"))
gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
@@ -89,6 +95,16 @@ func init() {
gMarksPath = filepath.Join(data, "lf", "marks")
gTagsPath = filepath.Join(data, "lf", "tags")
gHistoryPath = filepath.Join(data, "lf", "history")
socket, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM, 0)
if err != nil {
gDefaultSocketProt = "tcp"
gDefaultSocketPath = "127.0.0.1:12345"
} else {
runtime := os.TempDir()
gDefaultSocketPath = filepath.Join(runtime, fmt.Sprintf("lf.%s.sock", gUser.Username))
syscall.Close(socket)
}
}
func detachedCommand(name string, arg ...string) *exec.Cmd {
@@ -98,10 +114,23 @@ func detachedCommand(name string, arg ...string) *exec.Cmd {
}
func shellCommand(s string, args []string) *exec.Cmd {
// Windows CMD requires special handling to deal with quoted arguments
if strings.ToLower(gOpts.shell) == "cmd" {
var builder strings.Builder
builder.WriteString(s)
for _, arg := range args {
fmt.Fprintf(&builder, ` "%s"`, arg)
}
shellOpts := strings.Join(gOpts.shellopts, " ")
cmdline := fmt.Sprintf(`%s %s %s "%s"`, gOpts.shell, shellOpts, gOpts.shellflag, builder.String())
cmd := exec.Command(gOpts.shell)
cmd.SysProcAttr = &windows.SysProcAttr{CmdLine: cmdline}
return cmd
}
args = append([]string{gOpts.shellflag, s}, args...)
args = append(gOpts.shellopts, args...)
return exec.Command(gOpts.shell, args...)
}
@@ -120,6 +149,10 @@ func setDefaults() {
gOpts.cmds["doc"] = &execExpr{"!", "%lf% -doc | %PAGER%"}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
gOpts.cmds["maps"] = &execExpr{"!", `%lf% -remote "query %id% maps" | %PAGER%`}
gOpts.cmds["cmaps"] = &execExpr{"!", `%lf% -remote "query %id% cmaps" | %PAGER%`}
gOpts.cmds["cmds"] = &execExpr{"!", `%lf% -remote "query %id% cmds" | %PAGER%`}
}
func setUserUmask() {}
@@ -144,59 +177,41 @@ func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
if err != nil {
return false
}
return attrs&windows.FILE_ATTRIBUTE_HIDDEN != 0
if attrs&windows.FILE_ATTRIBUTE_HIDDEN != 0 {
return true
}
hidden := false
for _, pattern := range hiddenfiles {
if matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path) {
hidden = !strings.HasPrefix(pattern, "!")
}
}
return hidden
}
func userName(f os.FileInfo) string {
func userName(_ os.FileInfo) string {
return ""
}
func groupName(f os.FileInfo) string {
func groupName(_ os.FileInfo) string {
return ""
}
func linkCount(f os.FileInfo) string {
func linkCount(_ os.FileInfo) string {
return ""
}
func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(windows.Errno) == 17
return err.(*os.LinkError).Err.(windows.Errno) == windows.ERROR_NOT_SAME_DEVICE
}
func exportFiles(f string, fs []string, pwd string) {
envFile := fmt.Sprintf(`"%s"`, f)
var quotedFiles []string
for _, f := range fs {
quotedFiles = append(quotedFiles, fmt.Sprintf(`"%s"`, f))
}
envFiles := strings.Join(quotedFiles, gOpts.filesep)
envPWD := fmt.Sprintf(`"%s"`, pwd)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
os.Setenv("PWD", envPWD)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
func quoteString(s string) string {
// Windows CMD requires special handling to deal with quoted arguments
if strings.ToLower(gOpts.shell) == "cmd" {
return fmt.Sprintf(`"%s"`, s)
}
}
func diskFree(wd string) string {
var free uint64
pathPtr, err := windows.UTF16PtrFromString(wd)
if err != nil {
log.Printf("diskfree: %s", err)
return ""
}
err = windows.GetDiskFreeSpaceEx(pathPtr, &free, nil, nil) // cwd, free, total, available
if err != nil {
log.Printf("diskfree: %s", err)
return ""
}
return "df: " + humanize(int64(free))
return s
}
+56 -24
View File
@@ -2,34 +2,37 @@ package main
// Grammar of the language used in the evaluator
//
// Expr = SetExpr
// | MapExpr
// | CMapExpr
// | CmdExpr
// | CallExpr
// | ExecExpr
// | ListExpr
// Expr = SetExpr
// | SetLocalExpr
// | MapExpr
// | CMapExpr
// | CmdExpr
// | CallExpr
// | ExecExpr
// | ListExpr
//
// SetExpr = 'set' <opt> <val> ';'
// SetExpr = 'set' <opt> <val> ';'
//
// MapExpr = 'map' <keys> Expr
// SetLocalExpr = 'setlocal' <dir> <opt> <val> ';'
//
// CMapExpr = 'cmap' <key> Expr
// MapExpr = 'map' <keys> Expr
//
// CmdExpr = 'cmd' <name> Expr
// CMapExpr = 'cmap' <key> Expr
//
// CallExpr = <name> <args> ';'
// CmdExpr = 'cmd' <name> Expr
//
// ExecExpr = Prefix <value> '\n'
// | Prefix '{{' <value> '}}' ';'
// CallExpr = <name> <args> ';'
//
// Prefix = '$' | '%' | '!' | '&'
// ExecExpr = Prefix <value> '\n'
// | Prefix '{{' <value> '}}' ';'
//
// ListExpr = ':' Expr ListRest '\n'
// | ':' '{{' Expr ListRest '}}' ';'
// Prefix = '$' | '%' | '!' | '&'
//
// ListRest = Nil
// | Expr ListExpr
// ListExpr = ':' Expr ListRest '\n'
// | ':' '{{' Expr ListRest '}}' ';'
//
// ListRest = Nil
// | Expr ListExpr
import (
"bytes"
@@ -50,6 +53,14 @@ type setExpr struct {
func (e *setExpr) String() string { return fmt.Sprintf("set %s %s", e.opt, e.val) }
type setLocalExpr struct {
path string
opt string
val string
}
func (e *setLocalExpr) String() string { return fmt.Sprintf("setlocal %s %s %s", e.path, e.opt, e.val) }
type mapExpr struct {
keys string
expr expr
@@ -176,6 +187,30 @@ func (p *parser) parseExpr() expr {
s.scan()
result = &setExpr{opt, val}
case "setlocal":
var val string
s.scan()
if s.typ != tokenIdent {
p.err = fmt.Errorf("expected directory: %s", s.tok)
}
dir := s.tok
s.scan()
if s.typ != tokenIdent {
p.err = fmt.Errorf("expected identifier: %s", s.tok)
}
opt := s.tok
s.scan()
if s.typ != tokenSemicolon {
val = s.tok
s.scan()
}
s.scan()
result = &setLocalExpr{dir, opt, val}
case "map":
var expr expr
@@ -289,9 +324,6 @@ func (p *parser) parseExpr() expr {
}
func (p *parser) parse() bool {
if p.expr = p.parseExpr(); p.expr == nil {
return false
}
return true
p.expr = p.parseExpr()
return p.expr != nil
}
+28 -1
View File
@@ -17,7 +17,7 @@ var (
func serve() {
if gLogPath != "" {
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
panic(err)
}
@@ -83,7 +83,10 @@ Loop:
if err != nil {
echoerr(c, "listen: conn: client id should be a number")
} else {
// lifetime of the connection is managed by the server and
// will be cleaned up via the `drop` command
gConnList[id] = c
return
}
} else {
echoerr(c, "listen: conn: requires a client id")
@@ -95,6 +98,9 @@ Loop:
if err != nil {
echoerr(c, "listen: drop: client id should be a number")
} else {
if c2, ok := gConnList[id]; ok {
c2.Close()
}
delete(gConnList, id)
}
} else {
@@ -116,6 +122,27 @@ Loop:
}
}
}
case "query":
if rest == "" {
echoerr(c, "listen: query: requires a client id")
break
}
word2, rest2 := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: query: client id should be a number")
break
}
c2, ok := gConnList[id]
if !ok {
echoerr(c, "listen: query: no such client id is connected")
break
}
fmt.Fprintln(c2, "query "+rest2)
s2 := bufio.NewScanner(c2)
for s2.Scan() && s2.Text() != "" {
fmt.Fprintln(c, s2.Text())
}
case "quit":
if len(gConnList) == 0 {
gQuitChan <- struct{}{}
+69
View File
@@ -0,0 +1,69 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/gdamore/tcell/v2"
)
const (
gSixelBegin = "\033P"
// The filler character should be:
// - rarely used: the filler is used to trick tcell into redrawing, if the
// filler character appears in the user's preview, that cell might not
// be cleaned up properly
// - ideally renders as empty space: the filler alternates between bold
// and regular, using a non-space would look weird to the user.
gSixelFiller = '\u2000'
)
type sixelScreen struct {
xprev, yprev int
sixel *string
altFill bool
lastFile string // TODO maybe use hash of sixels instead to flip altFill
}
func (sxs *sixelScreen) fillerStyle(filePath string) tcell.Style {
if sxs.lastFile != filePath {
sxs.altFill = !sxs.altFill
}
if sxs.altFill {
return tcell.StyleDefault.Bold(true)
}
return tcell.StyleDefault
}
func (sxs *sixelScreen) showSixels() {
if sxs.sixel == nil {
return
}
// XXX: workaround for bug where quitting lf might leave the terminal in bold
fmt.Fprint(os.Stderr, "\033[0m")
fmt.Fprint(os.Stderr, "\0337") // Save cursor position
fmt.Fprintf(os.Stderr, "\033[%d;%dH", sxs.yprev, sxs.xprev) // Move cursor to position
fmt.Fprint(os.Stderr, *sxs.sixel) //
fmt.Fprint(os.Stderr, "\0338") // Restore cursor position
}
func (sxs *sixelScreen) printSixel(win *win, screen tcell.Screen, reg *reg) {
if reg.sixel == nil {
return
}
// HACK: fillers are used to control when tcell redraws the region where a sixel image is drawn.
// alternating between bold and regular is to clear the image before drawing a new one.
st := sxs.fillerStyle(reg.path)
for y := 0; y < win.h; y++ {
st = win.print(screen, 0, y, st, strings.Repeat(string(gSixelFiller), win.w))
}
sxs.xprev, sxs.yprev = win.x+1, win.y+1
sxs.sixel = reg.sixel
}
+468 -245
View File
File diff suppressed because it is too large. Load diff
+171
View File
@@ -0,0 +1,171 @@
package main
import (
"log"
"os"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
type watch struct {
watcher *fsnotify.Watcher
events <-chan fsnotify.Event
quit chan struct{}
loads map[string]bool
loadTimer *time.Timer
updates map[string]bool
updateTimer *time.Timer
dirChan chan<- *dir
fileChan chan<- *file
delChan chan<- string
}
func newWatch(dirChan chan<- *dir, fileChan chan<- *file, delChan chan<- string) *watch {
return &watch{
quit: make(chan struct{}),
loads: make(map[string]bool),
loadTimer: time.NewTimer(0),
updates: make(map[string]bool),
updateTimer: time.NewTimer(0),
dirChan: dirChan,
fileChan: fileChan,
delChan: delChan,
}
}
func (watch *watch) start() {
if watch.watcher != nil {
return
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Printf("start watcher: %s", err)
return
}
watch.watcher = watcher
watch.events = watcher.Events
go watch.loop()
}
func (watch *watch) stop() {
if watch.watcher == nil {
return
}
watch.quit <- struct{}{}
watch.watcher.Close()
watch.watcher = nil
watch.events = nil
}
func (watch *watch) add(path string) {
if watch.watcher == nil {
return
}
// ignore /dev since write updates to /dev/tty causes high cpu usage
if path != "/dev" {
watch.watcher.Add(path)
}
}
func (watch *watch) loop() {
for {
select {
case ev := <-watch.events:
if ev.Has(fsnotify.Create) {
for _, path := range watch.getSameDirs(filepath.Dir(ev.Name)) {
watch.addLoad(path)
watch.addUpdate(path)
}
}
if ev.Has(fsnotify.Remove) || ev.Has(fsnotify.Rename) {
dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) {
watch.delChan <- filepath.Join(path, file)
watch.addLoad(path)
watch.addUpdate(path)
}
}
if ev.Has(fsnotify.Write) || ev.Has(fsnotify.Chmod) {
dir, file := filepath.Split(ev.Name)
for _, path := range watch.getSameDirs(dir) {
watch.addUpdate(filepath.Join(path, file))
}
}
case <-watch.loadTimer.C:
for path := range watch.loads {
if _, err := os.Lstat(path); err != nil {
continue
}
dir := newDir(path)
dir.sort()
watch.dirChan <- dir
}
watch.loads = make(map[string]bool)
case <-watch.updateTimer.C:
for path := range watch.updates {
if _, err := os.Lstat(path); err != nil {
continue
}
watch.fileChan <- newFile(path)
}
watch.updates = make(map[string]bool)
case <-watch.quit:
return
}
}
}
func (watch *watch) addLoad(path string) {
if len(watch.loads) == 0 {
watch.loadTimer.Stop()
watch.loadTimer.Reset(10 * time.Millisecond)
}
watch.loads[path] = true
}
func (watch *watch) addUpdate(path string) {
if len(watch.updates) == 0 {
watch.updateTimer.Stop()
watch.updateTimer.Reset(10 * time.Millisecond)
}
watch.updates[path] = true
}
// Hacky workaround since fsnotify reports changes for only one path if a
// directory is located at more than one path (e.g. bind mounts).
func (watch *watch) getSameDirs(dir string) []string {
var paths []string
dirStat, err := os.Stat(dir)
if err != nil {
return nil
}
for _, path := range watch.watcher.WatchList() {
if path == dir {
paths = append(paths, path)
continue
}
stat, err := os.Stat(path)
if err != nil {
continue
}
if os.SameFile(stat, dirStat) {
paths = append(paths, path)
}
}
return paths
}