Compare commits

141 Commits
Author SHA1 Message Date
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
48 changed files with 7948 additions and 6406 deletions

No files matched your search

+26 -11
View File
@@ -8,20 +8,20 @@ on:
jobs: jobs:
build: tests:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, windows-latest] os: [ubuntu-latest, windows-latest]
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
fetch-depth: 1 fetch-depth: 1
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v4 uses: actions/setup-go@v5
with: with:
go-version: 1.18 go-version: "1.18"
- name: Build - name: Build
run: go build -v ./... run: go build -v ./...
@@ -29,23 +29,38 @@ jobs:
- name: Test - name: Test
run: go test -v ./... run: go test -v ./...
- uses: dominikh/staticcheck-action@v1.3.0 - uses: dominikh/staticcheck-action@v1.3.1
with: with:
version: "2022.1.3" version: "2022.1.3"
install-go: false install-go: false
generate: cross-compile:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
with: with:
fetch-depth: 1 fetch-depth: 1
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v4 uses: actions/setup-go@v5
with: with:
go-version: 1.19 go-version: "1.18"
- name: Test `go fmt && go generate` on Go 1.19 creates no diffs - name: Cross-compile on all supported platforms
run: go fmt && go generate && git diff --exit-code 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.18"
- name: Test `go fmt` creates no diffs
run: go fmt && git diff --exit-code
+5 -5
View File
@@ -10,25 +10,25 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v4
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v4 uses: actions/setup-go@v5
with: with:
go-version: 1.18 go-version: "1.18"
- name: Build - name: Build
run: gen/xbuild.sh run: gen/xbuild.sh
- name: Release - name: Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v2
with: with:
files: dist/* files: dist/*
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
winget: winget:
runs-on: windows-latest # Action can only run on Windows runs-on: ubuntu-latest
needs: build needs: build
steps: steps:
- uses: vedantmgoyal2009/winget-releaser@v2 - 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.
+5 -6
View File
@@ -1,14 +1,13 @@
# LF # LF
[Google Groups](https://groups.google.com/forum/#!forum/lf-fm) [Google Groups](https://groups.google.com/forum/#!forum/lf-fm)
| [Doc](doc.md)
| [Wiki](https://github.com/gokcehan/lf/wiki) | [Wiki](https://github.com/gokcehan/lf/wiki)
| [#lf](https://web.libera.chat/#lf) (on Libera.Chat) | [#lf](https://web.libera.chat/#lf) (on Libera.Chat)
| [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge) | [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge)
[![Go Build](https://github.com/gokcehan/lf/actions/workflows/go.yml/badge.svg)](https://github.com/gokcehan/lf/actions/workflows/go.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf) [![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 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. 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.
@@ -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 - Server/client architecture and remote commands to manage multiple instances
- Extendable and configurable with shell commands - Extendable and configurable with shell commands
- Customizable keybindings (vi and readline defaults) - 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 ## 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 -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. 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. 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 ## Contributing
See [contributing](https://github.com/gokcehan/lf/wiki/Contributing) for guidelines. See [contributing](CONTRIBUTING.md) for guidelines.
+60 -100
View File
@@ -33,6 +33,7 @@ type app struct {
menuCompActive bool menuCompActive bool
menuComps []string menuComps []string
menuCompInd int menuCompInd int
selectionOut []string
} }
func newApp(ui *ui, nav *nav) *app { func newApp(ui *ui, nav *nav) *app {
@@ -48,14 +49,15 @@ func newApp(ui *ui, nav *nav) *app {
sigChan := make(chan os.Signal, 1) sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM) signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM)
go func() { go func() {
for {
switch <-sigChan { switch <-sigChan {
case os.Interrupt: case os.Interrupt:
return
case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM: case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
app.quit() app.quit()
os.Exit(3) os.Exit(3)
return return
} }
}
}() }()
return app return app
@@ -163,6 +165,7 @@ func saveFiles(list []string, cp bool) error {
fmt.Fprintln(files, f) fmt.Fprintln(files, f)
} }
files.Sync()
return nil return nil
} }
@@ -328,19 +331,6 @@ func (app *app) loop() {
log.Print("bye!") 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 return
case n := <-app.nav.copyBytesChan: case n := <-app.nav.copyBytesChan:
app.nav.copyBytes += n app.nav.copyBytes += n
@@ -389,13 +379,11 @@ func (app *app) loop() {
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
case d := <-app.nav.dirChan: case d := <-app.nav.dirChan:
app.nav.checkDir(d)
if gOpts.dircache { if gOpts.dircache {
prev, ok := app.nav.dirCache[d.path] prev, ok := app.nav.dirCache[d.path]
if ok { if ok {
d.ind = prev.ind d.ind = prev.ind
d.pos = prev.pos
d.sel(prev.name(), app.nav.height) d.sel(prev.name(), app.nav.height)
} }
@@ -414,7 +402,7 @@ func (app *app) loop() {
if err == nil { if err == nil {
if d.path == app.nav.currDir().path { if d.path == app.nav.currDir().path {
app.ui.loadFile(app, true) app.ui.loadFile(app, true)
if app.ui.msg == "" { if app.ui.msgIsStat {
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -425,8 +413,6 @@ func (app *app) loop() {
app.ui.draw(app.nav) app.ui.draw(app.nav)
case r := <-app.nav.regChan: case r := <-app.nav.regChan:
app.nav.checkReg(r)
app.nav.regCache[r.path] = r app.nav.regCache[r.path] = r
curr, err := app.nav.currFile() curr, err := app.nav.currFile()
@@ -466,7 +452,6 @@ func (app *app) loop() {
case <-app.ticker.C: case <-app.ticker.C:
app.nav.renew() app.nav.renew()
app.ui.loadFile(app, false) app.ui.loadFile(app, false)
app.ui.draw(app.nav)
case <-app.nav.previewTimer.C: case <-app.nav.previewTimer.C:
app.nav.previewLoading = true app.nav.previewLoading = true
app.ui.draw(app.nav) app.ui.draw(app.nav)
@@ -474,51 +459,7 @@ func (app *app) loop() {
} }
} }
type cleanFunc func() func (app *app) runCmdSync(cmd *exec.Cmd, pause_after bool) {
var noopCleanFunc = func() {}
// This function is used to run a shell command. Modes are as follows:
//
// Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume
// % 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 {
app.nav.exportFiles()
app.ui.exportSizes()
exportOpts()
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.Stderr = os.Stderr
app.nav.previewChan <- "" app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil app.nav.dirPreviewChan <- nil
@@ -529,16 +470,59 @@ func (app *app) runShell(s string, args []string, prefix string) cleanFunc {
if err := app.ui.resume(); err != nil { if err := app.ui.resume(); err != nil {
app.quit() app.quit()
os.Exit(3) os.Exit(3)
return
} }
}() }()
defer app.nav.renew()
err = cmd.Run() if err := cmd.Run(); err != nil {
case "%": app.ui.echoerrf("running shell: %s", err)
shellSetPG(cmd) }
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:
//
// Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume
// % 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
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 "$", "!":
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
app.runCmdSync(cmd, prefix == "!")
return
}
// We are running the command asynchronously
if prefix == "%" {
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return noopCleanFunc return
} }
stdin, err := cmd.StdinPipe() stdin, err := cmd.StdinPipe()
if err != nil { if err != nil {
@@ -551,27 +535,13 @@ func (app *app) runShell(s string, args []string, prefix string) cleanFunc {
} }
out = stdout out = stdout
cmd.Stderr = cmd.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) 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 { switch prefix {
case "%": case "%":
normal(app) normal(app)
@@ -614,18 +584,8 @@ func (app *app) runShell(s string, args []string, prefix string) cleanFunc {
if err := cmd.Wait(); err != nil { if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err) 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)
}
}
}
return noopCleanFunc
} }
+74
View File
@@ -8,11 +8,23 @@ import (
"net" "net"
"os" "os"
"strings" "strings"
"sync"
"time" "time"
"github.com/gdamore/tcell/v2" "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() { func run() {
var screen tcell.Screen var screen tcell.Screen
var err error var err error
@@ -24,6 +36,7 @@ func run() {
if gOpts.mouse { if gOpts.mouse {
screen.EnableMouse() screen.EnableMouse()
} }
screen.EnableFocus()
if gLogPath != "" { 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, 0600)
@@ -61,6 +74,52 @@ func run() {
app.loop() app.loop()
app.ui.screen.Fini() 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 { func readExpr() <-chan expr {
@@ -84,11 +143,26 @@ func readExpr() <-chan expr {
s := bufio.NewScanner(c) s := bufio.NewScanner(c)
for s.Scan() { for s.Scan() {
log.Printf("recv: %s", s.Text()) log.Printf("recv: %s", s.Text())
// `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())) p := newParser(strings.NewReader(s.Text()))
if p.parse() { if p.parse() {
ch <- p.expr ch <- p.expr
} }
} }
}
c.Close() c.Close()
}() }()
+10 -2
View File
@@ -81,6 +81,14 @@ func parseStyles() styleMap {
return sm return sm
} }
func parseEscapeSequence(s string) tcell.Style {
s = strings.TrimPrefix(s, "\033[")
if i := strings.IndexByte(s, 'm'); i >= 0 {
s = s[:i]
}
return applyAnsiCodes(s, tcell.StyleDefault)
}
func applyAnsiCodes(s string, st tcell.Style) tcell.Style { func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";") toks := strings.Split(s, ";")
@@ -293,10 +301,10 @@ func (sm styleMap) get(f *file) tcell.Style {
key = "pi" key = "pi"
case f.Mode()&os.ModeSocket != 0: case f.Mode()&os.ModeSocket != 0:
key = "so" key = "so"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeCharDevice != 0: case f.Mode()&os.ModeCharDevice != 0:
key = "cd" key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0: case f.Mode()&os.ModeSetuid != 0:
key = "su" key = "su"
case f.Mode()&os.ModeSetgid != 0: case f.Mode()&os.ModeSetgid != 0:
+47 -111
View File
@@ -4,6 +4,7 @@ import (
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"sort" "sort"
"strings" "strings"
) )
@@ -11,10 +12,9 @@ import (
var ( var (
gCmdWords = []string{ gCmdWords = []string{
"set", "set",
"setlocal",
"map", "map",
"maps",
"cmap", "cmap",
"cmaps",
"cmd", "cmd",
"quit", "quit",
"up", "up",
@@ -29,7 +29,6 @@ var (
"open", "open",
"jump-next", "jump-next",
"jump-prev", "jump-prev",
"jumps",
"top", "top",
"bottom", "bottom",
"high", "high",
@@ -42,6 +41,7 @@ var (
"glob-select", "glob-select",
"glob-unselect", "glob-unselect",
"calcdirsize", "calcdirsize",
"clearmaps",
"copy", "copy",
"cut", "cut",
"paste", "paste",
@@ -104,118 +104,52 @@ var (
"cmd-word", "cmd-word",
"cmd-word-back", "cmd-word-back",
"cmd-delete-word", "cmd-delete-word",
"cmd-delete-word-back",
"cmd-capitalize-word", "cmd-capitalize-word",
"cmd-uppercase-word", "cmd-uppercase-word",
"cmd-lowercase-word", "cmd-lowercase-word",
} }
gOptWords = []string{ gOptWords = getOptWords(gOpts)
"anchorfind", gLocalOptWords = getLocalOptWords(gLocalOpts)
"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",
}
) )
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 { func matchLongest(s1, s2 []rune) []rune {
i := 0 i := 0
for ; i < len(s1) && i < len(s2); i++ { for ; i < len(s1) && i < len(s2); i++ {
@@ -277,7 +211,6 @@ func matchExec(s string) (matches []string, longest []rune) {
continue continue
} }
log.Print(finfo.Name())
words = append(words, finfo.Name()) words = append(words, finfo.Name())
} }
} }
@@ -334,7 +267,7 @@ func matchFile(s string) (matches []string, longest []rune) {
if isRoot(s) || filepath.Base(s) != s { if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(unescape(s)), f.Name()) name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
} }
name = escape(name) name = escape(replaceTilde(name))
item := f.Name() item := f.Name()
if f.Mode().IsDir() { if f.Mode().IsDir() {
@@ -401,6 +334,9 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
} }
case 3: case 3:
switch f[0] { 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": case "map", "cmap":
matches, longest = matchCmd(f[2]) matches, longest = matchCmd(f[2])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
@@ -410,7 +346,7 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
} }
default: default:
switch f[0] { switch f[0] {
case "set", "map", "cmap", "cmd": case "set", "setlocal", "map", "cmap", "cmd":
longestAcc = acc longestAcc = acc
default: default:
matches, longest = matchFile(f[len(f)-1]) 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)
}
}
}
+38 -6
View File
@@ -5,6 +5,10 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings"
"github.com/djherbis/times"
) )
func copySize(srcs []string) (int64, error) { func copySize(srcs []string) (int64, error) {
@@ -32,7 +36,18 @@ func copySize(srcs []string) (int64, error) {
return total, nil return total, nil
} }
func copyFile(src, dst string, info os.FileInfo, nums chan int64) error { func copyFile(src, dst string, preserve []string, info os.FileInfo, nums chan int64) error {
var dst_mode os.FileMode = 0666
preserve_timestamps := false
for _, s := range preserve {
switch s {
case "timestamps":
preserve_timestamps = true
case "mode":
dst_mode = info.Mode()
}
}
buf := make([]byte, 4096) buf := make([]byte, 4096)
r, err := os.Open(src) r, err := os.Open(src)
@@ -41,7 +56,7 @@ func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
} }
defer r.Close() 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 { if err != nil {
return err return err
} }
@@ -70,22 +85,39 @@ func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
return err 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 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) nums = make(chan int64, 1024)
errs = make(chan error, 1024) errs = make(chan error, 1024)
go func() { go func() {
for _, src := range srcs { for _, src := range srcs {
dst := filepath.Join(dstDir, filepath.Base(src)) file := filepath.Base(src)
dst := filepath.Join(dstDir, file)
_, err := os.Lstat(dst) _, err := os.Lstat(dst)
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
ext := filepath.Ext(file)
basename := file[:len(file)-len(ext)]
var newPath string var newPath string
for i := 1; !os.IsNotExist(err); i++ { 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) _, err = os.Lstat(newPath)
} }
dst = newPath dst = newPath
@@ -117,7 +149,7 @@ func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
} }
nums <- info.Size() nums <- info.Size()
} else { } 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) errs <- fmt.Errorf("copy: %s", err)
} }
} }
-1670
View File
File diff suppressed because it is too large. Load diff
+1825
View File
File diff suppressed because it is too large. Load diff
+2063
View File
File diff suppressed because it is too large. Load diff
-1826
View File
File diff suppressed because it is too large. Load diff
+10 -6
View File
@@ -87,7 +87,7 @@ fi  # FILE
*.cc  *.cc 
*.cp  *.cp 
*.c  *.c 
*.cs *.cs 󰌛
*.h  *.h 
*.hh  *.hh 
*.hpp  *.hpp 
@@ -152,10 +152,10 @@ fi  # FILE
*.elm  *.elm 
*.swift  *.swift 
*.xcplayground  *.xcplayground 
*.tex ﭨ *.tex 󰙩
*.r ﳒ *.r 󰟔
*.rproj 鉶 *.rproj 󰗆
*.sol ﲹ *.sol 󰡪
*.pem  *.pem 
# file names (vim-devicons) (case-insensitive not supported in lf) # file names (vim-devicons) (case-insensitive not supported in lf)
@@ -188,12 +188,15 @@ fi  # FILE
*procfile  *procfile 
*dockerfile  *dockerfile 
*docker-compose.yml  *docker-compose.yml 
*docker-compose.yaml 
*compose.yml 
*compose.yaml 
*rakefile  *rakefile 
*config.ru  *config.ru 
*gemfile  *gemfile 
*makefile  *makefile 
*cmakelists.txt  *cmakelists.txt 
*robots.txt ﮧ *robots.txt 󰚩
# file names (case-sensitive adaptations) # file names (case-sensitive adaptations)
*Gruntfile.coffee  *Gruntfile.coffee 
@@ -209,6 +212,7 @@ fi  # FILE
*Procfile  *Procfile 
*Dockerfile  *Dockerfile 
*Docker-compose.yml  *Docker-compose.yml 
*Docker-compose.yaml 
*Rakefile  *Rakefile 
*Gemfile  *Gemfile 
*Makefile  *Makefile 
+2
View File
@@ -15,6 +15,8 @@ _lf () {
-last-dir-path -last-dir-path
-log -log
-memprofile -memprofile
-print-last-dir
-print-selection
-remote -remote
-selection-path -selection-path
-server -server
+1 -1
View File
@@ -9,7 +9,7 @@
# endif # 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 lf "C/-*/(${LF_ARGS})/"
complete lfcd "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 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 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 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 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 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)' 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('-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('-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('-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('-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('-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)') [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. # 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)]' '-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]' '-log[path to the log file to write messages]'
'-memprofile[path to the file to write the memory profile]' '-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]' '-remote[send remote command to server]'
'-selection-path[path to the file to write selected files on open (to use as open file dialog)]' '-selection-path[path to the file to write selected files on open (to use as open file dialog)]'
'-server[start server (automatic)]' '-server[start server (automatic)]'
+1 -10
View File
@@ -3,13 +3,4 @@ rem Change working dir in cmd.exe to last dir in lf on exit.
rem rem
rem You need to put this file to a folder in %PATH% variable. rem You need to put this file to a folder in %PATH% variable.
:tmploop for /f "usebackq tokens=*" %%d in (`lf -print-last-dir %*`) do cd %%d
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%"
+4 -13
View File
@@ -11,17 +11,8 @@
# #
# You may put this in a function called fish_user_key_bindings. # You may put this in a function called fish_user_key_bindings.
function lfcd function lfcd --wraps="lf" --description="lf - Terminal file manager (changing directory on exit)"
set tmp (mktemp) # `command` is needed in case `lfcd` is aliased to `lf`.
# `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.
command lf -last-dir-path=$tmp $argv cd "$(command lf -print-last-dir $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
end 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. # You may put this in one of the profiles found in $PROFILE.
# #
$tmp = [System.IO.Path]::GetTempFileName() lf -print-last-dir $args | Set-Location
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"
}
}
}
+1 -11
View File
@@ -15,16 +15,6 @@
# #
lfcd () { lfcd () {
tmp="$(mktemp)"
# `command` is needed in case `lfcd` is aliased to `lf` # `command` is needed in case `lfcd` is aliased to `lf`
command lf -last-dir-path="$tmp" "$@" cd "$(command lf -print-last-dir "$@")"
if [ -f "$tmp" ]; then
dir="$(cat "$tmp")"
rm -f "$tmp"
if [ -d "$dir" ]; then
if [ "$dir" != "$(pwd)" ]; then
cd "$dir"
fi
fi
fi
} }
+360 -713
View File
File diff suppressed because it is too large. Load diff
+149
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"fmt"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
@@ -191,6 +192,84 @@ var gEvalTests = []struct {
[]expr{&setExpr{"ratios", "1:2:3"}, &setExpr{"hidden", ""}}, []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 ~", "map gh cd ~",
[]string{"map", "gh", "cd", "~", "\n"}, []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) # compressed in an archive form (`.zip` for windows and `.tar.gz` for the rest)
# within a folder named `dist`. # 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 package() (
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 cd dist || return 1
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 # Since the function is surrounded by (), the cd only affects a subshell
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 OUTFILE=
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 case "$1" in
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 windows)
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 OUTFILE="lf-$1-$2.zip"
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 zip "$OUTFILE" lf.exe --move || return 1
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 OUTFILE="lf-$1-$2.tar.gz"
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 tar czf "$OUTFILE" lf --remove-files || return 1
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 esac
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 echo "dist/$OUTFILE successfully created."
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
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 build android arm64
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 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 if test -n "$ERRORS"; then
# 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 printf "\ngen/xbuild.sh: some targets failed to compile.\n"
# 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 exit 1
# 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 fi
# 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
+6 -6
View File
@@ -3,16 +3,16 @@ module github.com/gokcehan/lf
go 1.18 go 1.18
require ( require (
github.com/djherbis/times v1.5.0 github.com/djherbis/times v1.6.0
github.com/gdamore/tcell/v2 v2.6.0 github.com/gdamore/tcell/v2 v2.7.4
github.com/mattn/go-runewidth v0.0.14 github.com/mattn/go-runewidth v0.0.15
golang.org/x/sys v0.8.0 golang.org/x/sys v0.18.0
golang.org/x/term v0.8.0 golang.org/x/term v0.18.0
) )
require ( require (
github.com/gdamore/encoding v1.0.0 // indirect github.com/gdamore/encoding v1.0.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/rivo/uniseg v0.4.3 // indirect github.com/rivo/uniseg v0.4.3 // indirect
golang.org/x/text v0.7.0 // indirect golang.org/x/text v0.14.0 // indirect
) )
+19 -11
View File
@@ -1,13 +1,13 @@
github.com/djherbis/times v1.5.0 h1:79myA211VwPhFTqUk8xehWrsEO+zcIZj0zT8mXPVARU= github.com/djherbis/times v1.6.0 h1:w2ctJ92J8fBvWPxugmXIv7Nz7Q3iDMKNx9v5ocVH20c=
github.com/djherbis/times v1.5.0/go.mod h1:5q7FDLvbNg1L/KaBmPcWlVR9NmoKo3+ucqUA3ijQhA0= github.com/djherbis/times v1.6.0/go.mod h1:gOHeRAz2h+VJNZ5Gmc/o7iD9k4wW7NMVqieYCY99oc0=
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= 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/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.7.4 h1:sg6/UnTM9jGpZU+oFYAsDahfchWAFW8Xx2yFinNSAYU=
github.com/gdamore/tcell/v2 v2.6.0/go.mod h1:be9omFATkdr0D9qewWW3d+MEvl5dha+Etb5y65J2H8Y= github.com/gdamore/tcell/v2 v2.7.4/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= 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/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.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= 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 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
@@ -15,30 +15,38 @@ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5t
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/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.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0 h1:n5xxQn2i3PC0yLAbjTpNT85q/Kgzcr2gIoX9OrJUols= golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.18.0 h1:FcHjZXDMxI8mM3nwhX9HlKop4C0YQvCVCdwYl2wOtE8=
golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+2 -2
View File
@@ -128,10 +128,10 @@ func (im iconMap) get(f *file) string {
key = "pi" key = "pi"
case f.Mode()&os.ModeSocket != 0: case f.Mode()&os.ModeSocket != 0:
key = "so" key = "so"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeCharDevice != 0: case f.Mode()&os.ModeCharDevice != 0:
key = "cd" key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0: case f.Mode()&os.ModeSetuid != 0:
key = "su" key = "su"
case f.Mode()&os.ModeSetgid != 0: case f.Mode()&os.ModeSetgid != 0:
+2004 -1434
View File
File diff suppressed because it is too large. Load diff
+66 -39
View File
@@ -9,11 +9,17 @@ import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"runtime" "runtime"
"runtime/debug"
"runtime/pprof" "runtime/pprof"
"strconv" "strconv"
"strings" "strings"
_ "embed"
) )
//go:embed doc.txt
var genDocString string
var ( var (
envPath = os.Getenv("PATH") envPath = os.Getenv("PATH")
envLevel = os.Getenv("LF_LEVEL") envLevel = os.Getenv("LF_LEVEL")
@@ -23,6 +29,8 @@ type arrayFlag []string
var ( var (
gSingleMode bool gSingleMode bool
gPrintLastDir bool
gPrintSelection bool
gClientID int gClientID int
gHostname string gHostname string
gLastDirPath string gLastDirPath string
@@ -85,7 +93,7 @@ func exportEnvVars() {
log.Printf("getting path to lf binary: %s", err) log.Printf("getting path to lf binary: %s", err)
lfPath = "lf" lfPath = "lf"
} }
os.Setenv("lf", lfPath) os.Setenv("lf", quoteString(lfPath))
} }
// used by exportOpts below // used by exportOpts below
@@ -115,7 +123,8 @@ func fieldToString(field reflect.Value) string {
return value return value
} }
func exportOpts() { func getOptsMap() map[string]string {
opts := make(map[string]string)
v := reflect.ValueOf(gOpts) v := reflect.ValueOf(gOpts)
t := v.Type() t := v.Type()
@@ -128,48 +137,23 @@ func exportOpts() {
continue continue
} }
// Get string representation of the value if name == "lf_user" {
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" {
// set each user option // set each user option
for key, value := range gOpts.user { for key, value := range gOpts.user {
os.Setenv(name+"_"+key, value) opts[name+"_"+key] = value
} }
} else { } else {
field := v.Field(i) opts[name] = fieldToString(v.Field(i))
value := fieldToString(field)
os.Setenv(name, value)
} }
} }
return opts
}
func exportOpts() {
for key, value := range getOptsMap() {
os.Setenv(key, value)
}
} }
func startServer() { func startServer() {
@@ -194,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() { func main() {
flag.Usage = func() { flag.Usage = func() {
f := flag.CommandLine.Output() f := flag.CommandLine.Output()
@@ -227,6 +242,16 @@ func main() {
false, false,
"start a client without server") "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( remoteCmd := flag.String(
"remote", "remote",
"", "",
@@ -286,7 +311,7 @@ func main() {
case *showDoc: case *showDoc:
fmt.Print(genDocString) fmt.Print(genDocString)
case *showVersion: case *showVersion:
fmt.Println(gVersion) printVersion()
case *remoteCmd != "": case *remoteCmd != "":
if err := remote(*remoteCmd); err != nil { if err := remote(*remoteCmd); err != nil {
log.Fatalf("remote command: %s", err) log.Fatalf("remote command: %s", err)
@@ -304,6 +329,8 @@ func main() {
serve() serve()
default: default:
gSingleMode = *singleMode gSingleMode = *singleMode
gPrintLastDir = *printLastDir
gPrintSelection = *printSelection
if !gSingleMode { if !gSingleMode {
checkServer() checkServer()
+26 -9
View File
@@ -31,23 +31,39 @@ func runeSliceWidth(rs []rune) int {
} }
func runeSliceWidthRange(rs []rune, beg, end int) []rune { func runeSliceWidthRange(rs []rune, beg, end int) []rune {
if beg == end {
return []rune{}
}
curr := 0 curr := 0
b := 0 b := 0
foundb := false
for i, r := range rs { for i, r := range rs {
w := runewidth.RuneWidth(r) w := runewidth.RuneWidth(r)
switch { if curr >= beg && !foundb {
case curr == beg:
b = i b = i
case curr < beg && curr+w > beg: foundb = true
b = i + 1 }
case curr == end: if curr == end || curr+w > end {
return rs[b:i] return rs[b:i]
case curr > end:
return rs[b : i-1]
} }
curr += w 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 // This function is used to escape whitespaces and special characters with
@@ -275,7 +291,8 @@ func naturalLess(s1, s2 string) bool {
} }
} }
var reAltKey = regexp.MustCompile(`<a-(.)>`) var reModKey = regexp.MustCompile(`<(c|s|a)-(.+)>`)
var reRulerSub = regexp.MustCompile(`%[apmcsfithd]|%\{[^}]+\}`)
var reWord = regexp.MustCompile(`(\pL|\pN)+`) var reWord = regexp.MustCompile(`(\pL|\pN)+`)
var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`) var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
+51 -1
View File
@@ -55,21 +55,71 @@ func TestRuneSliceWidthRange(t *testing.T) {
end int end int
exp []rune exp []rune
}{ }{
{[]rune{}, 0, 0, []rune{}},
{[]rune{'a', 'b', 'c', 'd'}, 1, 3, []rune{'b', 'c'}}, {[]rune{'a', 'b', 'c', 'd'}, 1, 3, []rune{'b', 'c'}},
{[]rune{'a', 'ı', 'b', 'ş'}, 1, 3, []rune{'ı', 'b'}}, {[]rune{'a', 'ı', 'b', 'ş'}, 1, 3, []rune{'ı', 'b'}},
{[]rune{'世', '界', '世', '界'}, 2, 6, []rune{'界', '世'}}, {[]rune{'世', '界', '世', '界'}, 2, 6, []rune{'界', '世'}},
{[]rune{'世', '界', '世', '界'}, 3, 6, []rune{'世'}}, {[]rune{'世', '界', '世', '界'}, 3, 6, []rune{'世'}},
{[]rune{'世', '界', '世', '界'}, 2, 5, []rune{'界'}}, {[]rune{'世', '界', '世', '界'}, 2, 5, []rune{'界'}},
{[]rune{'世', '界', '世', '界'}, 3, 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, 5, []rune{'a', '界'}},
{[]rune{'世', 'a', '界', 'ı'}, 2, 4, []rune{'a'}}, {[]rune{'世', 'a', '界', 'ı'}, 2, 4, []rune{'a'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 5, []rune{'界'}}, {[]rune{'世', 'a', '界', 'ı'}, 3, 5, []rune{'界'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 4, []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 { for _, test := range tests {
if got := runeSliceWidthRange(test.rs, test.beg, test.end); !reflect.DeepEqual(got, test.exp) { 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)
} }
} }
} }
+184 -81
View File
@@ -15,7 +15,7 @@ import (
"strings" "strings"
"time" "time"
times "github.com/djherbis/times" "github.com/djherbis/times"
) )
type linkState byte type linkState byte
@@ -36,6 +36,7 @@ type file struct {
accessTime time.Time accessTime time.Time
changeTime time.Time changeTime time.Time
ext string ext string
err error
} }
func (file *file) TotalSize() int64 { func (file *file) TotalSize() int64 {
@@ -48,6 +49,17 @@ func (file *file) TotalSize() int64 {
return file.Size() 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(0000) }
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) { func readdir(path string) ([]*file, error) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
@@ -67,6 +79,18 @@ func readdir(path string) ([]*file, error) {
} }
if err != nil { if err != nil {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
files = append(files, &file{
FileInfo: &fakeStat{name: fname},
linkState: notLink,
linkTarget: "",
path: fpath,
dirCount: -1,
dirSize: -1,
accessTime: time.Unix(0, 0),
changeTime: time.Unix(0, 0),
ext: filepath.Ext(fpath),
err: err,
})
continue continue
} }
@@ -129,6 +153,7 @@ func readdir(path string) ([]*file, error) {
accessTime: at, accessTime: at,
changeTime: ct, changeTime: ct,
ext: ext, ext: ext,
err: nil,
}) })
} }
@@ -143,8 +168,11 @@ type dir struct {
path string // full path of directory path string // full path of directory
files []*file // displayed files in directory including or excluding hidden ones files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files) allFiles []*file // all files in directory including hidden ones (same array as files)
sortType sortType // sort method and options from last sort sortby sortMethod // sortby value from last sort
dirfirst bool // dirfirst value from last sort
dironly bool // dironly 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 hiddenfiles []string // hiddenfiles value from last sort
filter []string // last filter for this directory filter []string // last filter for this directory
ignorecase bool // ignorecase value from last sort ignorecase bool // ignorecase value from last sort
@@ -172,11 +200,11 @@ func newDir(path string) *dir {
} }
func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) { func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
if gOpts.ignorecase { if ignorecase {
s1 = strings.ToLower(s1) s1 = strings.ToLower(s1)
s2 = strings.ToLower(s2) s2 = strings.ToLower(s2)
} }
if gOpts.ignoredia { if ignoredia {
s1 = removeDiacritics(s1) s1 = removeDiacritics(s1)
s2 = removeDiacritics(s2) s2 = removeDiacritics(s2)
} }
@@ -184,40 +212,69 @@ func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) {
} }
func (dir *dir) sort() { func (dir *dir) sort() {
dir.sortType = gOpts.sortType dir.sortby = getSortBy(dir.path)
dir.dironly = gOpts.dironly dir.dirfirst = getDirFirst(dir.path)
dir.dironly = getDirOnly(dir.path)
dir.hidden = getHidden(dir.path)
dir.reverse = getReverse(dir.path)
dir.hiddenfiles = gOpts.hiddenfiles dir.hiddenfiles = gOpts.hiddenfiles
dir.ignorecase = gOpts.ignorecase dir.ignorecase = gOpts.ignorecase
dir.ignoredia = gOpts.ignoredia dir.ignoredia = gOpts.ignoredia
dir.files = dir.allFiles 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: case naturalSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return naturalLess(s1, s2) return naturalLess(s1, s2)
} else {
return naturalLess(s2, s1)
}
}) })
case nameSort: case nameSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia)
if !dir.reverse {
return s1 < s2 return s1 < s2
} else {
return s2 < s1
}
}) })
case sizeSort: case sizeSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].TotalSize() < dir.files[j].TotalSize() return dir.files[i].TotalSize() < dir.files[j].TotalSize()
} else {
return dir.files[j].TotalSize() < dir.files[i].TotalSize()
}
}) })
case timeSort: case timeSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].ModTime().Before(dir.files[j].ModTime()) return dir.files[i].ModTime().Before(dir.files[j].ModTime())
} else {
return dir.files[j].ModTime().Before(dir.files[i].ModTime())
}
}) })
case atimeSort: case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].accessTime.Before(dir.files[j].accessTime) return dir.files[i].accessTime.Before(dir.files[j].accessTime)
} else {
return dir.files[j].accessTime.Before(dir.files[i].accessTime)
}
}) })
case ctimeSort: case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if !dir.reverse {
return dir.files[i].changeTime.Before(dir.files[j].changeTime) return dir.files[i].changeTime.Before(dir.files[j].changeTime)
} else {
return dir.files[j].changeTime.Before(dir.files[i].changeTime)
}
}) })
case extSort: case extSort:
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
@@ -236,17 +293,15 @@ func (dir *dir) sort() {
// in order to also have natural sorting with the filenames // in order to also have natural sorting with the filenames
// combine the name with the ext but have the ext at the front // combine the name with the ext but have the ext at the front
if !dir.reverse {
return ext1 < ext2 || ext1 == ext2 && name1 < name2 return ext1 < ext2 || ext1 == ext2 && name1 < name2
} else {
return ext2 < ext1 || ext2 == ext1 && name2 < name1
}
}) })
} }
if dir.sortType.option&reverseSort != 0 { if dir.dirfirst {
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 {
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if dir.files[i].IsDir() == dir.files[j].IsDir() { if dir.files[i].IsDir() == dir.files[j].IsDir() {
return i < j return i < j
@@ -278,7 +333,7 @@ func (dir *dir) sort() {
// when hidden option is disabled, we move hidden files to the // when hidden option is disabled, we move hidden files to the
// beginning of our file list and then set the beginning of displayed // beginning of our file list and then set the beginning of displayed
// files to the first non-hidden file in the list // 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 { 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) { if isHidden(dir.files[i], dir.path, dir.hiddenfiles) && isHidden(dir.files[j], dir.path, dir.hiddenfiles) {
return i < j return i < j
@@ -344,8 +399,27 @@ func (dir *dir) sel(name string, height int) {
} }
} }
edge := min(min(height/2, gOpts.scrolloff), len(dir.files)-dir.ind-1) dir.boundPos(height)
dir.pos = min(dir.ind, height-edge-1) }
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 { type nav struct {
@@ -401,7 +475,11 @@ func (nav *nav) loadDirInternal(path string) *dir {
loading: true, loading: true,
loadTime: time.Now(), loadTime: time.Now(),
path: path, path: path,
sortType: gOpts.sortType, sortby: getSortBy(path),
dirfirst: getDirFirst(path),
dironly: getDirOnly(path),
hidden: getHidden(path),
reverse: getReverse(path),
hiddenfiles: gOpts.hiddenfiles, hiddenfiles: gOpts.hiddenfiles,
ignorecase: gOpts.ignorecase, ignorecase: gOpts.ignorecase,
ignoredia: gOpts.ignoredia, ignoredia: gOpts.ignoredia,
@@ -464,8 +542,11 @@ func (nav *nav) checkDir(dir *dir) {
} }
nav.dirChan <- nd nav.dirChan <- nd
}() }()
case dir.sortType != gOpts.sortType || case dir.sortby != getSortBy(dir.path) ||
dir.dironly != gOpts.dironly || dir.dirfirst != getDirFirst(dir.path) ||
dir.dironly != getDirOnly(dir.path) ||
dir.hidden != getHidden(dir.path) ||
dir.reverse != getReverse(dir.path) ||
!reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles) || !reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles) ||
dir.ignorecase != gOpts.ignorecase || dir.ignorecase != gOpts.ignorecase ||
dir.ignoredia != gOpts.ignoredia: dir.ignoredia != gOpts.ignoredia:
@@ -576,13 +657,8 @@ func (nav *nav) reload() error {
nav.dirCache = make(map[string]*dir) nav.dirCache = make(map[string]*dir)
nav.regCache = make(map[string]*reg) 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() curr, err := nav.currFile()
nav.getDirs(wd) nav.getDirs(nav.currDir().path)
if err == nil { if err == nil {
last := nav.dirs[len(nav.dirs)-1] last := nav.dirs[len(nav.dirs)-1]
last.files = append(last.files, curr) last.files = append(last.files, curr)
@@ -610,12 +686,24 @@ func (nav *nav) exportFiles() {
var currFile string var currFile string
if curr, err := nav.currFile(); err == nil { 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) { func (nav *nav) dirPreviewLoop(ui *ui) {
@@ -650,13 +738,12 @@ func (nav *nav) previewLoop(ui *ui) {
} }
win := ui.wins[len(ui.wins)-1] win := ui.wins[len(ui.wins)-1]
if clear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview { if clear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.cleaner, prev, cmd := exec.Command(gOpts.cleaner, prev,
strconv.Itoa(win.w), strconv.Itoa(win.w),
strconv.Itoa(win.h), strconv.Itoa(win.h),
strconv.Itoa(win.x), strconv.Itoa(win.x),
strconv.Itoa(win.y)) strconv.Itoa(win.y),
path)
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err) log.Printf("cleaning preview: %s", err)
} }
@@ -695,8 +782,6 @@ func (nav *nav) previewDir(dir *dir, win *win) {
var reader io.Reader var reader io.Reader
if len(gOpts.previewer) != 0 { if len(gOpts.previewer) != 0 {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.previewer, dir.path, cmd := exec.Command(gOpts.previewer, dir.path,
strconv.Itoa(win.w), strconv.Itoa(win.w),
strconv.Itoa(win.h), strconv.Itoa(win.h),
@@ -752,11 +837,9 @@ func (nav *nav) preview(path string, win *win) {
reg := &reg{loadTime: time.Now(), path: path} reg := &reg{loadTime: time.Now(), path: path}
defer func() { nav.regChan <- reg }() defer func() { nav.regChan <- reg }()
var reader io.Reader var reader *bufio.Reader
if len(gOpts.previewer) != 0 { if len(gOpts.previewer) != 0 {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.previewer, path, cmd := exec.Command(gOpts.previewer, path,
strconv.Itoa(win.w), strconv.Itoa(win.w),
strconv.Itoa(win.h), strconv.Itoa(win.h),
@@ -788,7 +871,7 @@ func (nav *nav) preview(path string, win *win) {
} }
}() }()
defer out.Close() defer out.Close()
reader = out reader = bufio.NewReader(out)
} else { } else {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
@@ -797,23 +880,43 @@ func (nav *nav) preview(path string, win *win) {
} }
defer f.Close() 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++ { // bufio.Scanner can't handle files containing long lines if they exceed the
for _, r := range buf.Text() { // size of its internal buffer
addLine := true
for len(reg.lines) < win.h {
line, isPrefix, err := reader.ReadLine()
if err != nil {
break
}
for _, r := range line {
if r == 0 { if r == 0 {
reg.lines = []string{"\033[7mbinary\033[0m"} reg.lines = []string{"\033[7mbinary\033[0m"}
return return
} }
} }
reg.lines = append(reg.lines, buf.Text())
if addLine {
reg.lines = append(reg.lines, string(line))
} }
if buf.Err() != nil { addLine = !isPrefix
log.Printf("loading file: %s", buf.Err())
} }
} }
@@ -904,8 +1007,7 @@ func (nav *nav) up(dist int) bool {
dir.ind = max(0, dir.ind) dir.ind = max(0, dir.ind)
dir.pos -= dist dir.pos -= dist
edge := min(min(nav.height/2, gOpts.scrolloff), dir.ind) dir.boundPos(nav.height)
dir.pos = max(dir.pos, edge)
return old != dir.ind return old != dir.ind
} }
@@ -928,16 +1030,7 @@ func (nav *nav) down(dist int) bool {
dir.ind = min(maxind, dir.ind) dir.ind = min(maxind, dir.ind)
dir.pos += dist dir.pos += dist
// use a smaller value for half when the height is even and scrolloff is dir.boundPos(nav.height)
// 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)
return old != dir.ind return old != dir.ind
} }
@@ -1062,7 +1155,7 @@ func (nav *nav) high() bool {
old := dir.ind old := dir.ind
beg := max(dir.ind-dir.pos, 0) beg := max(dir.ind-dir.pos, 0)
offs := gOpts.scrolloff offs := min(nav.height/2, gOpts.scrolloff)
if beg == 0 { if beg == 0 {
offs = 0 offs = 0
} }
@@ -1093,7 +1186,14 @@ func (nav *nav) low() bool {
old := dir.ind old := dir.ind
beg := max(dir.ind-dir.pos, 0) beg := max(dir.ind-dir.pos, 0)
end := min(beg+nav.height, len(dir.files)) 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) { if end == len(dir.files) {
offs = 0 offs = 0
} }
@@ -1238,7 +1338,7 @@ func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) {
nav.copyTotalChan <- total nav.copyTotalChan <- total
nums, errs := copyAll(srcs, dstDir) nums, errs := copyAll(srcs, dstDir, gOpts.preserve)
errCount := 0 errCount := 0
loop: loop:
@@ -1298,7 +1398,8 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
continue continue
} }
dst := filepath.Join(dstDir, filepath.Base(src)) file := filepath.Base(src)
dst := filepath.Join(dstDir, file)
dstStat, err := os.Stat(dst) dstStat, err := os.Stat(dst)
if os.SameFile(srcStat, dstStat) { if os.SameFile(srcStat, dstStat) {
@@ -1307,9 +1408,15 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
app.ui.exprChan <- echo app.ui.exprChan <- echo
continue continue
} else if !os.IsNotExist(err) { } else if !os.IsNotExist(err) {
ext := filepath.Ext(file)
basename := file[:len(file)-len(ext)]
var newPath string var newPath string
for i := 1; !os.IsNotExist(err); i++ { 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) _, err = os.Lstat(newPath)
} }
dst = newPath dst = newPath
@@ -1326,7 +1433,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
nav.copyTotalChan <- total nav.copyTotalChan <- total
nums, errs := copyAll([]string{src}, dstDir) nums, errs := copyAll([]string{src}, dstDir, []string{"mode", "timestamps"})
oldCount := errCount oldCount := errCount
loop: loop:
@@ -1375,6 +1482,7 @@ func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
} }
if errCount == 0 { if errCount == 0 {
app.ui.exprChan <- &callExpr{"clear", nil, 1}
app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mMoved successfully\033[0m"}, 1} app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mMoved successfully\033[0m"}, 1}
} }
} }
@@ -1395,19 +1503,6 @@ func (nav *nav) paste(app *app) error {
go nav.copyAsync(app, srcs, dstDir) go nav.copyAsync(app, srcs, dstDir)
} else { } else {
go nav.moveAsync(app, srcs, dstDir) 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 return nil
@@ -1761,9 +1856,12 @@ func (nav *nav) readMarks() error {
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), ":", 2) mark, path, found := strings.Cut(scanner.Text(), ":")
if _, ok := nav.marks[toks[0]]; !ok { if !found {
nav.marks[toks[0]] = toks[1] return fmt.Errorf("invalid marks file entry: %s", scanner.Text())
}
if _, ok := nav.marks[mark]; !ok {
nav.marks[mark] = path
} }
} }
@@ -1817,11 +1915,16 @@ func (nav *nav) readTags() error {
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
text := scanner.Text() text := scanner.Text()
ind := strings.LastIndex(text, ":") ind := strings.LastIndex(text, ":")
if ind == -1 {
return fmt.Errorf("invalid tags file entry: %s", text)
}
path := text[0:ind] path := text[0:ind]
mark := text[ind+1:] tag := text[ind+1:]
if _, ok := nav.tags[path]; !ok { if _, ok := nav.tags[path]; !ok {
nav.tags[path] = mark nav.tags[path] = tag
} }
} }
+133 -22
View File
@@ -1,44 +1,53 @@
package main package main
import "time" import (
"path/filepath"
type sortMethod byte "time"
const (
naturalSort sortMethod = iota
nameSort
sizeSort
timeSort
atimeSort
ctimeSort
extSort
) )
type sortOption byte // String values match the sortby string sent by the user at startup
type sortMethod string
const ( const (
dirfirstSort sortOption = 1 << iota naturalSort sortMethod = "natural"
hiddenSort nameSort sortMethod = "name"
reverseSort sizeSort sortMethod = "size"
timeSort sortMethod = "time"
atimeSort sortMethod = "atime"
ctimeSort sortMethod = "ctime"
extSort sortMethod = "ext"
) )
type sortType struct { func isValidSortMethod(method sortMethod) bool {
method sortMethod for _, validMethod := range []sortMethod{naturalSort, nameSort, sizeSort, timeSort, atimeSort, ctimeSort, extSort} {
option sortOption if method == validMethod {
return true
}
}
return false
} }
const invalidSortErrorMessage = `sortby: value should either be 'natural', 'name', 'size', 'time', 'atime', 'ctime' or 'ext'`
var gOpts struct { var gOpts struct {
anchorfind bool anchorfind bool
autoquit bool autoquit bool
borderfmt string
copyfmt string
cursoractivefmt string cursoractivefmt string
cursorparentfmt string cursorparentfmt string
cursorpreviewfmt string cursorpreviewfmt string
cutfmt string
hidecursorinactive bool
dircache bool dircache bool
dircounts bool dircounts bool
dirfirst bool
dironly bool dironly bool
dirpreviews bool dirpreviews bool
drawbox bool drawbox bool
dupfilefmt string
globsearch bool globsearch bool
hidden bool
icons bool icons bool
ignorecase bool ignorecase bool
ignoredia bool ignoredia bool
@@ -48,6 +57,10 @@ var gOpts struct {
number bool number bool
preview bool preview bool
relativenumber bool relativenumber bool
reverse bool
selectfmt string
sixel bool
sortby sortMethod
smartcase bool smartcase bool
smartdia bool smartdia bool
waitmsg string waitmsg string
@@ -66,38 +79,120 @@ var gOpts struct {
selmode string selmode string
shell string shell string
shellflag string shellflag string
statfmt string
timefmt string timefmt string
infotimefmtnew string infotimefmtnew string
infotimefmtold string infotimefmtold string
truncatechar string truncatechar string
truncatepct int
ratios []int ratios []int
hiddenfiles []string hiddenfiles []string
history bool history bool
info []string info []string
ruler []string ruler []string
rulerfmt string
preserve []string
shellopts []string shellopts []string
keys map[string]expr keys map[string]expr
cmdkeys map[string]expr cmdkeys map[string]expr
cmds map[string]expr cmds map[string]expr
user map[string]string user map[string]string
sortType sortType
tempmarks string tempmarks string
numberfmt string numberfmt string
tagfmt 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
}
func localOptPaths(path string) []string {
var list []string
list = append(list, 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 init() { func init() {
gOpts.anchorfind = true gOpts.anchorfind = true
gOpts.autoquit = false gOpts.autoquit = false
gOpts.dircache = true gOpts.dircache = true
gOpts.dircounts = false gOpts.dircounts = false
gOpts.dirfirst = true
gOpts.dironly = false gOpts.dironly = false
gOpts.dirpreviews = false gOpts.dirpreviews = false
gOpts.drawbox = false gOpts.drawbox = false
gOpts.dupfilefmt = "%f.~%n~"
gOpts.borderfmt = "\033[0m"
gOpts.copyfmt = "\033[7;33m"
gOpts.cursoractivefmt = "\033[7m" gOpts.cursoractivefmt = "\033[7m"
gOpts.cursorparentfmt = "\033[7m" gOpts.cursorparentfmt = "\033[7m"
gOpts.cursorpreviewfmt = "\033[4m" gOpts.cursorpreviewfmt = "\033[4m"
gOpts.cutfmt = "\033[7;31m"
gOpts.hidecursorinactive = false
gOpts.globsearch = false gOpts.globsearch = false
gOpts.hidden = false
gOpts.icons = false gOpts.icons = false
gOpts.ignorecase = true gOpts.ignorecase = true
gOpts.ignoredia = true gOpts.ignoredia = true
@@ -107,6 +202,10 @@ func init() {
gOpts.number = false gOpts.number = false
gOpts.preview = true gOpts.preview = true
gOpts.relativenumber = false gOpts.relativenumber = false
gOpts.reverse = false
gOpts.selectfmt = "\033[7;35m"
gOpts.sixel = false
gOpts.sortby = naturalSort
gOpts.smartcase = true gOpts.smartcase = true
gOpts.smartdia = false gOpts.smartdia = false
gOpts.waitmsg = "Press any key to continue" gOpts.waitmsg = "Press any key to continue"
@@ -125,17 +224,20 @@ func init() {
gOpts.selmode = "all" gOpts.selmode = "all"
gOpts.shell = gDefaultShell gOpts.shell = gDefaultShell
gOpts.shellflag = gDefaultShellFlag gOpts.shellflag = gDefaultShellFlag
gOpts.statfmt = "\033[36m%p\033[0m| %c| %u| %g| %S| %t| -> %l"
gOpts.timefmt = time.ANSIC gOpts.timefmt = time.ANSIC
gOpts.infotimefmtnew = "Jan _2 15:04" gOpts.infotimefmtnew = "Jan _2 15:04"
gOpts.infotimefmtold = "Jan _2 2006" gOpts.infotimefmtold = "Jan _2 2006"
gOpts.truncatechar = "~" gOpts.truncatechar = "~"
gOpts.truncatepct = 100
gOpts.ratios = []int{1, 2, 3} gOpts.ratios = []int{1, 2, 3}
gOpts.hiddenfiles = []string{".*"} gOpts.hiddenfiles = []string{".*"}
gOpts.history = true gOpts.history = true
gOpts.info = nil gOpts.info = nil
gOpts.ruler = []string{"acc", "progress", "selection", "filter", "ind"} gOpts.ruler = nil
gOpts.rulerfmt = " %a| %p| \033[7;31m %m \033[0m| \033[7;33m %c \033[0m| \033[7;35m %s \033[0m| \033[7;34m %f \033[0m| %i/%t"
gOpts.preserve = []string{"mode"}
gOpts.shellopts = nil gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort}
gOpts.tempmarks = "'" gOpts.tempmarks = "'"
gOpts.numberfmt = "\033[33m" gOpts.numberfmt = "\033[33m"
gOpts.tagfmt = "\033[31m" gOpts.tagfmt = "\033[31m"
@@ -249,6 +351,8 @@ func init() {
gOpts.cmdkeys["<a-b>"] = &callExpr{"cmd-word-back", 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-c>"] = &callExpr{"cmd-capitalize-word", nil, 1}
gOpts.cmdkeys["<a-d>"] = &callExpr{"cmd-delete-word", nil, 1} gOpts.cmdkeys["<a-d>"] = &callExpr{"cmd-delete-word", nil, 1}
gOpts.cmdkeys["<a-backspace>"] = &callExpr{"cmd-delete-word-back", nil, 1}
gOpts.cmdkeys["<a-backspace2>"] = &callExpr{"cmd-delete-word-back", nil, 1}
gOpts.cmdkeys["<a-u>"] = &callExpr{"cmd-uppercase-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-l>"] = &callExpr{"cmd-lowercase-word", nil, 1}
gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1} gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1}
@@ -256,5 +360,12 @@ func init() {
gOpts.cmds = make(map[string]expr) gOpts.cmds = make(map[string]expr)
gOpts.user = make(map[string]string) gOpts.user = make(map[string]string)
gLocalOpts.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)
setDefaults() setDefaults()
} }
+25 -20
View File
@@ -84,7 +84,10 @@ func init() {
} }
gUser = u gUser = u
config := os.Getenv("XDG_CONFIG_HOME") config := os.Getenv("LF_CONFIG_HOME")
if config == "" {
config = os.Getenv("XDG_CONFIG_HOME")
}
if config == "" { if config == "" {
config = filepath.Join(gUser.HomeDir, ".config") config = filepath.Join(gUser.HomeDir, ".config")
} }
@@ -104,7 +107,10 @@ func init() {
filepath.Join(config, "lf", "icons"), filepath.Join(config, "lf", "icons"),
} }
data := os.Getenv("XDG_DATA_HOME") data := os.Getenv("LF_DATA_HOME")
if data == "" {
data = os.Getenv("XDG_DATA_HOME")
}
if data == "" { if data == "" {
data = filepath.Join(gUser.HomeDir, ".local", "share") data = filepath.Join(gUser.HomeDir, ".local", "share")
} }
@@ -164,6 +170,10 @@ func setDefaults() {
gOpts.cmds["doc"] = &execExpr{"$", `"$lf" -doc | $PAGER`} gOpts.cmds["doc"] = &execExpr{"$", `"$lf" -doc | $PAGER`}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1} 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() { func setUserUmask() {
@@ -189,8 +199,11 @@ func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
func userName(f os.FileInfo) string { func userName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok { if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if u, err := user.LookupId(fmt.Sprint(stat.Uid)); err == nil { uid := fmt.Sprint(stat.Uid)
return fmt.Sprintf("%v ", u.Username) if u, err := user.LookupId(uid); err == nil {
return u.Username
} else {
return uid
} }
} }
return "" return ""
@@ -198,8 +211,11 @@ func userName(f os.FileInfo) string {
func groupName(f os.FileInfo) string { func groupName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok { if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if g, err := user.LookupGroupId(fmt.Sprint(stat.Gid)); err == nil { gid := fmt.Sprint(stat.Gid)
return fmt.Sprintf("%v ", g.Name) if g, err := user.LookupGroupId(gid); err == nil {
return g.Name
} else {
return gid
} }
} }
return "" return ""
@@ -207,7 +223,7 @@ func groupName(f os.FileInfo) string {
func linkCount(f os.FileInfo) string { func linkCount(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok { if stat, ok := f.Sys().(*syscall.Stat_t); ok {
return fmt.Sprintf("%v ", stat.Nlink) return fmt.Sprint(stat.Nlink)
} }
return "" return ""
} }
@@ -216,17 +232,6 @@ func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(unix.Errno) == unix.EXDEV return err.(*os.LinkError).Err.(unix.Errno) == unix.EXDEV
} }
func exportFiles(f string, fs []string, pwd string) { func quoteString(s string) string {
envFile := f return s
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)
}
} }
+39 -27
View File
@@ -59,16 +59,25 @@ func init() {
envShell = "cmd" envShell = "cmd"
} }
u, err := user.Current() homeDir, err := os.UserHomeDir()
if err != nil { if err != nil {
log.Printf("user: %s", err) panic(err)
} }
gUser = u
// remove domain prefix username := os.Getenv("USERNAME")
gUser.Username = strings.Split(gUser.Username, `\`)[1] if username == "" {
panic("$USERNAME variable is empty or not set")
}
data := os.Getenv("LOCALAPPDATA") gUser = &user.User{
HomeDir: homeDir,
Username: username,
}
data := os.Getenv("LF_CONFIG_HOME")
if data == "" {
data = os.Getenv("LOCALAPPDATA")
}
gConfigPaths = []string{ gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"), filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
@@ -98,10 +107,23 @@ func detachedCommand(name string, arg ...string) *exec.Cmd {
} }
func shellCommand(s string, args []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([]string{gOpts.shellflag, s}, args...)
args = append(gOpts.shellopts, args...) args = append(gOpts.shellopts, args...)
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
@@ -120,6 +142,10 @@ func setDefaults() {
gOpts.cmds["doc"] = &execExpr{"!", "%lf% -doc | %PAGER%"} gOpts.cmds["doc"] = &execExpr{"!", "%lf% -doc | %PAGER%"}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1} 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() {} func setUserUmask() {}
@@ -163,24 +189,10 @@ func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(windows.Errno) == 17 return err.(*os.LinkError).Err.(windows.Errno) == 17
} }
func exportFiles(f string, fs []string, pwd string) { func quoteString(s string) string {
envFile := fmt.Sprintf(`"%s"`, f) // Windows CMD requires special handling to deal with quoted arguments
if strings.ToLower(gOpts.shell) == "cmd" {
var quotedFiles []string return fmt.Sprintf(`"%s"`, s)
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)
} }
return s
} }
+35
View File
@@ -3,6 +3,7 @@ package main
// Grammar of the language used in the evaluator // Grammar of the language used in the evaluator
// //
// Expr = SetExpr // Expr = SetExpr
// | SetLocalExpr
// | MapExpr // | MapExpr
// | CMapExpr // | CMapExpr
// | CmdExpr // | CmdExpr
@@ -12,6 +13,8 @@ package main
// //
// SetExpr = 'set' <opt> <val> ';' // SetExpr = 'set' <opt> <val> ';'
// //
// SetLocalExpr = 'setlocal' <dir> <opt> <val> ';'
//
// MapExpr = 'map' <keys> Expr // MapExpr = 'map' <keys> Expr
// //
// CMapExpr = 'cmap' <key> Expr // CMapExpr = 'cmap' <key> Expr
@@ -50,6 +53,14 @@ type setExpr struct {
func (e *setExpr) String() string { return fmt.Sprintf("set %s %s", e.opt, e.val) } 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 { type mapExpr struct {
keys string keys string
expr expr expr expr
@@ -176,6 +187,30 @@ func (p *parser) parseExpr() expr {
s.scan() s.scan()
result = &setExpr{opt, val} 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": case "map":
var expr expr var expr expr
+27
View File
@@ -83,7 +83,10 @@ Loop:
if err != nil { if err != nil {
echoerr(c, "listen: conn: client id should be a number") echoerr(c, "listen: conn: client id should be a number")
} else { } else {
// lifetime of the connection is managed by the server and
// will be cleaned up via the `drop` command
gConnList[id] = c gConnList[id] = c
return
} }
} else { } else {
echoerr(c, "listen: conn: requires a client id") echoerr(c, "listen: conn: requires a client id")
@@ -95,6 +98,9 @@ Loop:
if err != nil { if err != nil {
echoerr(c, "listen: drop: client id should be a number") echoerr(c, "listen: drop: client id should be a number")
} else { } else {
if c2, ok := gConnList[id]; ok {
c2.Close()
}
delete(gConnList, id) delete(gConnList, id)
} }
} else { } 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": case "quit":
if len(gConnList) == 0 { if len(gConnList) == 0 {
gQuitChan <- struct{}{} 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
}
+291 -115
View File
@@ -252,7 +252,7 @@ func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string)
win.print(screen, win.w-printLength(s), y, st, s) win.print(screen, win.w-printLength(s), y, st, s)
} }
func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool) { func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs *sixelScreen) {
if reg == nil { if reg == nil {
return return
} }
@@ -274,6 +274,8 @@ func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool) {
st = win.print(screen, 2, i, st, l) st = win.print(screen, 2, i, st, l)
} }
sxs.printSixel(win, screen, reg)
} }
var gThisYear = time.Now().Year() var gThisYear = time.Now().Year()
@@ -288,7 +290,7 @@ func infotimefmt(t time.Time) string {
func fileInfo(f *file, d *dir) string { func fileInfo(f *file, d *dir) string {
var info string var info string
for _, s := range gOpts.info { for _, s := range getInfo(d.path) {
switch s { switch s {
case "size": case "size":
if !(f.IsDir() && gOpts.dircounts) { if !(f.IsDir() && gOpts.dircounts) {
@@ -346,12 +348,7 @@ type dirStyle struct {
role dirRole role dirRole
} }
// These colors are not currently customizeable func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirStyle, previewLoading bool) {
const SelectionColor = tcell.ColorPurple
const YankColor = tcell.ColorOlive
const CutColor = tcell.ColorMaroon
func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dirStyle *dirStyle, previewLoading bool) {
if win.w < 5 || dir == nil { if win.w < 5 || dir == nil {
return return
} }
@@ -359,12 +356,12 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dir
messageStyle := tcell.StyleDefault.Reverse(true) messageStyle := tcell.StyleDefault.Reverse(true)
if dir.noPerm { if dir.noPerm {
win.print(screen, 2, 0, messageStyle, "permission denied") win.print(ui.screen, 2, 0, messageStyle, "permission denied")
return return
} }
if (dir.loading && len(dir.files) == 0) || (dirStyle.role == Preview && dir.loading && gOpts.dirpreviews) { if (dir.loading && len(dir.files) == 0) || (dirStyle.role == Preview && dir.loading && gOpts.dirpreviews) {
if dirStyle.role != Preview || previewLoading { if dirStyle.role != Preview || previewLoading {
win.print(screen, 2, 0, messageStyle, "loading...") win.print(ui.screen, 2, 0, messageStyle, "loading...")
} }
return return
} }
@@ -377,12 +374,12 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dir
break break
} }
st = win.print(screen, 2, i, st, l) st = win.print(ui.screen, 2, i, st, l)
} }
return return
} }
if len(dir.files) == 0 { if len(dir.files) == 0 {
win.print(screen, 2, 0, messageStyle, "empty") win.print(ui.screen, 2, 0, messageStyle, "empty")
return return
} }
@@ -426,23 +423,31 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dir
} }
} }
win.print(screen, 0, i, tcell.StyleDefault, fmt.Sprintf(optionToFmtstr(gOpts.numberfmt), ln)) win.print(ui.screen, 0, i, tcell.StyleDefault, fmt.Sprintf(optionToFmtstr(gOpts.numberfmt), ln))
} }
path := filepath.Join(dir.path, f.Name()) path := filepath.Join(dir.path, f.Name())
if _, ok := context.selections[path]; ok { if _, ok := context.selections[path]; ok {
win.print(screen, lnwidth, i, st.Background(SelectionColor), " ") win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.selectfmt), " ")
} else if cp, ok := context.saves[path]; ok { } else if cp, ok := context.saves[path]; ok {
if cp { if cp {
win.print(screen, lnwidth, i, st.Background(YankColor), " ") win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.copyfmt), " ")
} else { } else {
win.print(screen, lnwidth, i, st.Background(CutColor), " ") win.print(ui.screen, lnwidth, i, parseEscapeSequence(gOpts.cutfmt), " ")
} }
} }
// make space for select marker, and leave another space at the end
maxWidth := win.w - lnwidth - 2
// make extra space to separate windows if drawbox is not enabled
if !gOpts.drawbox {
maxWidth -= 1
}
var s []rune var s []rune
// leave space for displaying the tag
s = append(s, ' ') s = append(s, ' ')
if gOpts.icons { if gOpts.icons {
@@ -450,44 +455,33 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dir
s = append(s, ' ') s = append(s, ' ')
} }
for _, r := range f.Name() { maxFilenameWidth := maxWidth - runeSliceWidth(s)
s = append(s, r)
}
w := runeSliceWidth(s)
// make space for select marker, and leave another space at the end
maxlength := win.w - lnwidth - 2
// make extra space to separate windows if drawbox is not enabled
if !gOpts.drawbox {
maxlength -= 1
}
if w > maxlength {
s = runeSliceWidthRange(s, 0, maxlength-1)
s = append(s, []rune(gOpts.truncatechar)...)
} else {
for i := 0; i < maxlength-w; i++ {
s = append(s, ' ')
}
}
info := fileInfo(f, dir) info := fileInfo(f, dir)
showInfo := len(info) > 0 && 2*len(info) < maxWidth
if showInfo {
maxFilenameWidth -= len(info)
}
if len(info) > 0 && 2*len(info) < maxlength { filename := []rune(f.Name())
if w+len(info) > maxlength { if runeSliceWidth(filename) > maxFilenameWidth {
s = runeSliceWidthRange(s, 0, maxlength-len(info)-1) truncatePos := (maxFilenameWidth - 1) * gOpts.truncatepct / 100
s = append(s, []rune(gOpts.truncatechar)...) lastPart := runeSliceWidthLastRange(filename, maxFilenameWidth-truncatePos-1)
} else { filename = runeSliceWidthRange(filename, 0, truncatePos)
s = runeSliceWidthRange(s, 0, maxlength-len(info)) filename = append(filename, []rune(gOpts.truncatechar)...)
filename = append(filename, lastPart...)
} }
for _, r := range info { for i := runeSliceWidth(filename); i < maxFilenameWidth; i++ {
s = append(s, r) filename = append(filename, ' ')
} }
s = append(s, filename...)
if showInfo {
s = append(s, []rune(info)...)
} }
ce := "" ce := ""
if i == dir.pos { if i == dir.pos && (ui.focused || !gOpts.hidecursorinactive) {
switch dirStyle.role { switch dirStyle.role {
case Active: case Active:
ce = gOpts.cursoractivefmt ce = gOpts.cursoractivefmt
@@ -501,14 +495,14 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dir
s = append(s, ' ') s = append(s, ' ')
styledFilename := fmt.Sprintf(cursorescapefmt, string(s)) styledFilename := fmt.Sprintf(cursorescapefmt, string(s))
win.print(screen, lnwidth+1, i, st, styledFilename) win.print(ui.screen, lnwidth+1, i, st, styledFilename)
tag, ok := context.tags[path] tag, ok := context.tags[path]
if ok { if ok {
if i == dir.pos { if i == dir.pos {
win.print(screen, lnwidth+1, i, st, fmt.Sprintf(cursorescapefmt, tag)) win.print(ui.screen, lnwidth+1, i, st, fmt.Sprintf(cursorescapefmt, tag))
} else { } else {
win.print(screen, lnwidth+1, i, tcell.StyleDefault, fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag)) win.print(ui.screen, lnwidth+1, i, tcell.StyleDefault, fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag))
} }
} }
} }
@@ -561,12 +555,15 @@ func getWins(screen tcell.Screen) []*win {
type ui struct { type ui struct {
screen tcell.Screen screen tcell.Screen
sxScreen sixelScreen
polling bool polling bool
focused bool
wins []*win wins []*win
promptWin *win promptWin *win
msgWin *win msgWin *win
menuWin *win menuWin *win
msg string msg string
msgIsStat bool
regPrev *reg regPrev *reg
dirPrev *dir dirPrev *dir
exprChan chan expr exprChan chan expr
@@ -592,10 +589,12 @@ func newUI(screen tcell.Screen) *ui {
ui := &ui{ ui := &ui{
screen: screen, screen: screen,
polling: true, polling: true,
focused: true,
wins: getWins(screen), wins: getWins(screen),
promptWin: newWin(wtot, 1, 0, 0), promptWin: newWin(wtot, 1, 0, 0),
msgWin: newWin(wtot, 1, 0, htot-1), msgWin: newWin(wtot, 1, 0, htot-1),
menuWin: newWin(wtot, 1, 0, htot-2), menuWin: newWin(wtot, 1, 0, htot-2),
msgIsStat: true,
exprChan: make(chan expr, 1000), exprChan: make(chan expr, 1000),
keyChan: make(chan string, 1000), keyChan: make(chan string, 1000),
tevChan: make(chan tcell.Event, 1000), tevChan: make(chan tcell.Event, 1000),
@@ -603,6 +602,7 @@ func newUI(screen tcell.Screen) *ui {
styles: parseStyles(), styles: parseStyles(),
icons: parseIcons(), icons: parseIcons(),
currentFile: "", currentFile: "",
sxScreen: sixelScreen{},
} }
go ui.pollEvents() go ui.pollEvents()
@@ -652,14 +652,11 @@ func (ui *ui) sort() {
func (ui *ui) echo(msg string) { func (ui *ui) echo(msg string) {
ui.msg = msg ui.msg = msg
} ui.msgIsStat = false
func (ui *ui) echof(format string, a ...interface{}) {
ui.echo(fmt.Sprintf(format, a...))
} }
func (ui *ui) echomsg(msg string) { func (ui *ui) echomsg(msg string) {
ui.msg = msg ui.echo(msg)
log.Print(msg) log.Print(msg)
} }
@@ -672,7 +669,7 @@ func optionToFmtstr(optstr string) string {
} }
func (ui *ui) echoerr(msg string) { func (ui *ui) echoerr(msg string) {
ui.msg = fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg) ui.echo(fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg))
log.Printf("error: %s", msg) log.Printf("error: %s", msg)
} }
@@ -686,6 +683,7 @@ type reg struct {
loadTime time.Time loadTime time.Time
path string path string
lines []string lines []string
sixel *string
} }
func (ui *ui) loadFile(app *app, volatile bool) { func (ui *ui) loadFile(app *app, volatile bool) {
@@ -703,14 +701,14 @@ func (ui *ui) loadFile(app *app, volatile bool) {
onSelect(app) onSelect(app)
} }
if !gOpts.preview {
return
}
if volatile { if volatile {
app.nav.previewChan <- "" app.nav.previewChan <- ""
} }
if !gOpts.preview {
return
}
if curr.IsDir() { if curr.IsDir() {
ui.dirPrev = app.nav.loadDir(curr.path) ui.dirPrev = app.nav.loadDir(curr.path)
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
@@ -728,19 +726,36 @@ func (ui *ui) loadFileInfo(nav *nav) {
return return
} }
var linkTarget string if curr.err != nil {
if curr.linkTarget != "" { ui.echoerrf("stat: %s", curr.err)
linkTarget = " -> " + curr.linkTarget return
} }
ui.echof("%v %v%v%v%4s %v%s", statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f")
curr.Mode(), replace := func(s string, val string) {
linkCount(curr), // optional if val == "" {
userName(curr), // optional val = "\x00"
groupName(curr), // optional }
humanize(curr.Size()), statfmt = strings.ReplaceAll(statfmt, s, val)
curr.ModTime().Format(gOpts.timefmt), }
linkTarget) replace("%p", curr.Mode().String())
replace("%c", linkCount(curr))
replace("%u", userName(curr))
replace("%g", groupName(curr))
replace("%s", humanize(curr.Size()))
replace("%S", fmt.Sprintf("%4s", humanize(curr.Size())))
replace("%t", curr.ModTime().Format(gOpts.timefmt))
replace("%l", curr.linkTarget)
fileInfo := ""
for _, section := range strings.Split(statfmt, "\x1f") {
if !strings.Contains(section, "\x00") {
fileInfo += section
}
}
ui.msg = fileInfo
ui.msgIsStat = true
} }
func (ui *ui) drawPromptLine(nav *nav) { func (ui *ui) drawPromptLine(nav *nav) {
@@ -804,7 +819,19 @@ func (ui *ui) drawPromptLine(nav *nav) {
ui.promptWin.print(ui.screen, 0, 0, st, prompt) ui.promptWin.print(ui.screen, 0, 0, st, prompt)
} }
func (ui *ui) drawStatLine(nav *nav) { func formatRulerOpt(name string, val string) string {
// handle escape character so it doesn't mess up the ruler
val = strings.ReplaceAll(val, "\033", "\033[7m\\033\033[0m")
// display name of builtin options for clarity
if !strings.HasPrefix(name, "lf_user_") {
val = fmt.Sprintf("%s=%s", strings.TrimPrefix(name, "lf_"), val)
}
return val
}
func (ui *ui) drawRuler(nav *nav) {
st := tcell.StyleDefault st := tcell.StyleDefault
dir := nav.currDir() dir := nav.currDir()
@@ -813,13 +840,14 @@ func (ui *ui) drawStatLine(nav *nav) {
tot := len(dir.files) tot := len(dir.files)
ind := min(dir.ind+1, tot) ind := min(dir.ind+1, tot)
hid := len(dir.allFiles) - tot
acc := string(ui.keyCount) + string(ui.keyAcc) acc := string(ui.keyCount) + string(ui.keyAcc)
selection := []string{} selection := []string{}
if len(nav.saves) > 0 {
copy := 0 copy := 0
move := 0 move := 0
if len(nav.saves) > 0 {
for _, cp := range nav.saves { for _, cp := range nav.saves {
if cp { if cp {
copy++ copy++
@@ -828,16 +856,19 @@ func (ui *ui) drawStatLine(nav *nav) {
} }
} }
if copy > 0 { if copy > 0 {
selection = append(selection, fmt.Sprintf("\033[33;7m %d \033[0m", copy)) copyStr := fmt.Sprintf(optionToFmtstr(gOpts.copyfmt), fmt.Sprintf(" %d ", copy))
selection = append(selection, copyStr)
} }
if move > 0 { if move > 0 {
selection = append(selection, fmt.Sprintf("\033[31;7m %d \033[0m", move)) moveStr := fmt.Sprintf(optionToFmtstr(gOpts.cutfmt), fmt.Sprintf(" %d ", move))
selection = append(selection, moveStr)
} }
} }
currSelections := nav.currSelections() currSelections := nav.currSelections()
if len(currSelections) > 0 { if len(currSelections) > 0 {
selection = append(selection, fmt.Sprintf("\033[35;7m %d \033[0m", len(currSelections))) selectStr := fmt.Sprintf(optionToFmtstr(gOpts.selectfmt), fmt.Sprintf(" %d ", len(currSelections)))
selection = append(selection, selectStr)
} }
progress := []string{} progress := []string{}
@@ -855,6 +886,10 @@ func (ui *ui) drawStatLine(nav *nav) {
progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal)) progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal))
} }
opts := getOptsMap()
// 'ruler' option is deprecated and can be removed in future
if len(gOpts.ruler) > 0 {
ruler := []string{} ruler := []string{}
for _, s := range gOpts.ruler { for _, s := range gOpts.ruler {
switch s { switch s {
@@ -875,15 +910,63 @@ func (ui *ui) drawStatLine(nav *nav) {
} }
case "ind": case "ind":
ruler = append(ruler, fmt.Sprintf("%d/%d", ind, tot)) ruler = append(ruler, fmt.Sprintf("%d/%d", ind, tot))
default:
if val, ok := opts[s]; ok {
ruler = append(ruler, formatRulerOpt(s, val))
}
} }
} }
ui.msgWin.printRight(ui.screen, 0, st, strings.Join(ruler, " ")) ui.msgWin.printRight(ui.screen, 0, st, strings.Join(ruler, " "))
return
}
rulerfmt := strings.ReplaceAll(gOpts.rulerfmt, "|", "\x1f")
rulerfmt = reRulerSub.ReplaceAllStringFunc(rulerfmt, func(s string) string {
var result string
switch s {
case "%a":
result = acc
case "%p":
result = strings.Join(progress, " ")
case "%m":
result = fmt.Sprintf("%.d", move)
case "%c":
result = fmt.Sprintf("%.d", copy)
case "%s":
result = fmt.Sprintf("%.d", len(currSelections))
case "%f":
result = strings.Join(dir.filter, " ")
case "%i":
result = fmt.Sprint(ind)
case "%t":
result = fmt.Sprint(tot)
case "%h":
result = fmt.Sprint(hid)
case "%d":
result = diskFree(dir.path)
default:
s = strings.TrimSuffix(strings.TrimPrefix(s, "%{"), "}")
if val, ok := opts[s]; ok {
result = formatRulerOpt(s, val)
}
}
if result == "" {
return "\x00"
}
return result
})
ruler := ""
for _, section := range strings.Split(rulerfmt, "\x1f") {
if !strings.Contains(section, "\x00") {
ruler += section
}
}
ui.msgWin.printRight(ui.screen, 0, st, ruler)
} }
func (ui *ui) drawBox() { func (ui *ui) drawBox() {
st := tcell.StyleDefault st := parseEscapeSequence(gOpts.borderfmt)
w, h := ui.screen.Size() w, h := ui.screen.Size()
@@ -936,6 +1019,7 @@ func (ui *ui) draw(nav *nav) {
ui.screen.SetContent(i, j, ' ', nil, st) ui.screen.SetContent(i, j, ' ', nil, st)
} }
} }
ui.sxScreen.sixel = nil
ui.drawPromptLine(nav) ui.drawPromptLine(nav)
@@ -949,7 +1033,7 @@ func (ui *ui) draw(nav *nav) {
role = Active role = Active
} }
if dir := ui.dirOfWin(nav, i); dir != nil { if dir := ui.dirOfWin(nav, i); dir != nil {
ui.wins[i].printDir(ui.screen, dir, &context, ui.wins[i].printDir(ui, dir, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: role}, &dirStyle{colors: ui.styles, icons: ui.icons, role: role},
nav.previewLoading) nav.previewLoading)
} }
@@ -957,27 +1041,21 @@ func (ui *ui) draw(nav *nav) {
switch ui.cmdPrefix { switch ui.cmdPrefix {
case "": case "":
ui.drawStatLine(nav) ui.drawRuler(nav)
ui.screen.HideCursor() ui.screen.HideCursor()
case ">": case ">":
prefix := ui.cmdPrefix[:min(ui.msgWin.w-1, len(ui.cmdPrefix))] maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end
pos := min(runeSliceWidth(ui.cmdAccLeft), ui.msgWin.w-len(prefix)-1) prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth)
left := ui.cmdAccLeft[runeSliceWidth(ui.cmdAccLeft)-pos:] left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix)-printLength(ui.msg))
right := ui.cmdAccRight ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+ui.msg)
ui.msgWin.printLine(ui.screen, 0, 0, st, prefix) ui.msgWin.print(ui.screen, runeSliceWidth(prefix)+printLength(ui.msg), 0, st, string(left)+string(ui.cmdAccRight))
ui.msgWin.print(ui.screen, len(prefix), 0, st, ui.msg) ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+printLength(ui.msg)+runeSliceWidth(left), ui.msgWin.y)
ui.msgWin.print(ui.screen, len(prefix)+printLength(ui.msg), 0, st, string(left))
ui.msgWin.print(ui.screen, len(prefix)+printLength(ui.msg)+runeSliceWidth(left), 0, st, string(right))
ui.screen.ShowCursor(ui.msgWin.x+len(prefix)+printLength(ui.msg)+runeSliceWidth(left), ui.msgWin.y)
default: default:
prefix := ui.cmdPrefix[:min(ui.msgWin.w-1, len(ui.cmdPrefix))] maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end
pos := min(runeSliceWidth(ui.cmdAccLeft), ui.msgWin.w-len(prefix)-1) prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth)
left := ui.cmdAccLeft[runeSliceWidth(ui.cmdAccLeft)-pos:] left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix))
right := ui.cmdAccRight ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+string(left)+string(ui.cmdAccRight))
ui.msgWin.printLine(ui.screen, 0, 0, st, prefix) ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+runeSliceWidth(left), ui.msgWin.y)
ui.msgWin.print(ui.screen, len(prefix), 0, st, string(left))
ui.msgWin.print(ui.screen, len(prefix)+runeSliceWidth(left), 0, st, string(right))
ui.screen.ShowCursor(ui.msgWin.x+len(prefix)+runeSliceWidth(left), ui.msgWin.y)
} }
if gOpts.preview { if gOpts.preview {
@@ -986,11 +1064,11 @@ func (ui *ui) draw(nav *nav) {
preview := ui.wins[len(ui.wins)-1] preview := ui.wins[len(ui.wins)-1]
if curr.IsDir() { if curr.IsDir() {
preview.printDir(ui.screen, ui.dirPrev, &context, preview.printDir(ui, ui.dirPrev, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: Preview}, &dirStyle{colors: ui.styles, icons: ui.icons, role: Preview},
nav.previewLoading) nav.previewLoading)
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
preview.printReg(ui.screen, ui.regPrev, nav.previewLoading) preview.printReg(ui.screen, ui.regPrev, nav.previewLoading, &ui.sxScreen)
} }
} }
} }
@@ -1020,6 +1098,11 @@ func (ui *ui) draw(nav *nav) {
} }
ui.screen.Show() ui.screen.Show()
if ui.menuBuf == nil && ui.cmdPrefix == "" && ui.sxScreen.sixel != nil {
ui.sxScreen.lastFile = ui.regPrev.path
ui.sxScreen.showSixels()
}
} }
func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) { func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) {
@@ -1036,7 +1119,7 @@ func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok b
return return
} }
func listBinds(binds map[string]expr) *bytes.Buffer { func listExprMap(binds map[string]expr, title string) *bytes.Buffer {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
@@ -1047,7 +1130,7 @@ func listBinds(binds map[string]expr) *bytes.Buffer {
sort.Strings(keys) sort.Strings(keys)
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "keys\tcommand") fmt.Fprintf(t, "%s\tcommand\n", title)
for _, k := range keys { for _, k := range keys {
fmt.Fprintf(t, "%s\t%v\n", k, binds[k]) fmt.Fprintf(t, "%s\t%v\n", k, binds[k])
} }
@@ -1056,6 +1139,14 @@ func listBinds(binds map[string]expr) *bytes.Buffer {
return b return b
} }
func listBinds(binds map[string]expr) *bytes.Buffer {
return listExprMap(binds, "keys")
}
func listCmds() *bytes.Buffer {
return listExprMap(gOpts.cmds, "name")
}
func listJumps(jumps []string, ind int) *bytes.Buffer { func listJumps(jumps []string, ind int) *bytes.Buffer {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
@@ -1080,6 +1171,22 @@ func listJumps(jumps []string, ind int) *bytes.Buffer {
return b return b
} }
func listHistory(history []cmdItem) *bytes.Buffer {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
maxlength := len(strconv.Itoa(len(history)))
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "number\tcommand")
for i, cmd := range history {
fmt.Fprintf(t, "%*d\t%s%s\n", maxlength, i+1, cmd.prefix, cmd.value)
}
t.Flush()
return b
}
func listMarks(marks map[string]string) *bytes.Buffer { func listMarks(marks map[string]string) *bytes.Buffer {
t := new(tabwriter.Writer) t := new(tabwriter.Writer)
b := new(bytes.Buffer) b := new(bytes.Buffer)
@@ -1105,32 +1212,44 @@ func (ui *ui) pollEvent() tcell.Event {
case val := <-ui.keyChan: case val := <-ui.keyChan:
var ch rune var ch rune
var mod tcell.ModMask var mod tcell.ModMask
k := tcell.KeyRune k := tcell.KeyRune
if utf8.RuneCountInString(val) == 1 { if key, ok := gValKey[val]; ok {
ch, _ = utf8.DecodeRuneInString(val) return tcell.NewEventKey(key, ch, mod)
} else { }
switch { switch {
case utf8.RuneCountInString(val) == 1:
ch, _ = utf8.DecodeRuneInString(val)
case val == "<lt>": case val == "<lt>":
ch = '<' ch = '<'
case val == "<gt>": case val == "<gt>":
ch = '>' ch = '>'
case val == "<space>": case val == "<space>":
ch = ' ' ch = ' '
case reAltKey.MatchString(val): case reModKey.MatchString(val):
match := reAltKey.FindStringSubmatch(val)[1] matches := reModKey.FindStringSubmatch(val)
ch, _ = utf8.DecodeRuneInString(match) switch matches[1] {
mod = tcell.ModMask(tcell.ModAlt) case "c":
default: mod = tcell.ModCtrl
if key, ok := gValKey[val]; ok { case "s":
mod = tcell.ModShift
case "a":
mod = tcell.ModAlt
}
val = matches[2]
if utf8.RuneCountInString(val) == 1 {
ch, _ = utf8.DecodeRuneInString(val)
break
} else if key, ok := gValKey["<"+val+">"]; ok {
k = key k = key
} else { break
}
fallthrough
default:
k = tcell.KeyESC k = tcell.KeyESC
ui.echoerrf("unknown key: %s", val) ui.echoerrf("unknown key: %s", val)
} }
}
}
return tcell.NewEventKey(k, ch, mod) return tcell.NewEventKey(k, ch, mod)
case ev := <-ui.tevChan: case ev := <-ui.tevChan:
@@ -1138,6 +1257,21 @@ func (ui *ui) pollEvent() tcell.Event {
} }
} }
func addSpecialKeyModifier(val string, mod tcell.ModMask) string {
switch {
case !strings.HasPrefix(val, "<"):
return val
case mod == tcell.ModCtrl && !strings.HasPrefix(val, "<c-"):
return "<c-" + val[1:]
case mod == tcell.ModShift:
return "<s-" + val[1:]
case mod == tcell.ModAlt:
return "<a-" + val[1:]
default:
return val
}
}
// This function is used to read a normal event on the client side. For keys, // This function is used to read a normal event on the client side. For keys,
// digits are interpreted as command counts but this is only done for digits // digits are interpreted as command counts but this is only done for digits
// preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k"). // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k").
@@ -1165,6 +1299,7 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
} }
} else { } else {
val := gKeyVal[tev.Key()] val := gKeyVal[tev.Key()]
val = addSpecialKeyModifier(val, tev.Modifiers())
if val == "<esc>" && string(ui.keyAcc) != "" { if val == "<esc>" && string(ui.keyAcc) != "" {
ui.keyAcc = nil ui.keyAcc = nil
ui.keyCount = nil ui.keyCount = nil
@@ -1314,6 +1449,9 @@ func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When()) log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When())
case *tcell.EventInterrupt: case *tcell.EventInterrupt:
log.Printf("Got EventInterrupt: at %s", tev.When()) log.Printf("Got EventInterrupt: at %s", tev.When())
case *tcell.EventFocus:
ui.focused = tev.Focused
return draw
} }
return nil return nil
} }
@@ -1332,6 +1470,7 @@ func readCmdEvent(ev tcell.Event) expr {
} }
} else { } else {
val := gKeyVal[tev.Key()] val := gKeyVal[tev.Key()]
val = addSpecialKeyModifier(val, tev.Modifiers())
if expr, ok := gOpts.cmdkeys[val]; ok { if expr, ok := gOpts.cmdkeys[val]; ok {
return expr return expr
} }
@@ -1373,6 +1512,43 @@ func (ui *ui) resume() error {
return err return err
} }
func (ui *ui) exportMode() {
getMode := func() string {
if strings.HasPrefix(ui.cmdPrefix, "delete") {
return "delete"
}
if strings.HasPrefix(ui.cmdPrefix, "replace") || strings.HasPrefix(ui.cmdPrefix, "create") {
return "rename"
}
switch ui.cmdPrefix {
case "filter: ":
return "filter"
case "find: ", "find-back: ":
return "find"
case "mark-save: ", "mark-load: ", "mark-remove: ":
return "mark"
case "rename: ":
return "rename"
case "/", "?":
return "search"
case ":":
return "command"
case "$", "%", "!", "&":
return "shell"
case ">":
return "pipe"
case "":
return "normal"
default:
return "unknown"
}
}
os.Setenv("lf_mode", getMode())
}
func (ui *ui) exportSizes() { func (ui *ui) exportSizes() {
w, h := ui.screen.Size() w, h := ui.screen.Size()
os.Setenv("lf_width", strconv.Itoa(w)) os.Setenv("lf_width", strconv.Itoa(w))
@@ -1380,8 +1556,8 @@ func (ui *ui) exportSizes() {
} }
func anyKey() { func anyKey() {
fmt.Print(gOpts.waitmsg) fmt.Fprint(os.Stderr, gOpts.waitmsg)
defer fmt.Print("\n") defer fmt.Fprint(os.Stderr, "\n")
oldState, err := term.MakeRaw(int(os.Stdin.Fd())) oldState, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil { if err != nil {
panic(err) panic(err)