Compare commits

113 Commits
Author SHA1 Message Date
Joe Lim 88b3c999af Fix count when parsing bottom command (#1240)
* Fix count when parsing `bottom` command

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

This reverts commit a0b6bb5a13.

* Alternate implementation

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

* Mention jump count in documentation

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

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

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

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

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-13 16:18:31 +03:00
Joe Lim 8f630e0cab Separate filter from selections in the ui ruler (#1223) 2023-05-13 14:19:50 +03:00
Joe Lim 35990bed12 Prevent scrolling to bottom when selecting files (#1222)
* Prevent scrolling to bottom when selecting files

* Use nav.currDir()
2023-05-13 13:58:03 +03:00
Gokcehan f04401ba4d build diskfree on all platforms
cc #1168
2023-04-30 22:10:15 +03:00
Gokcehan 2c86577b95 update doc
cc #1176
2023-04-30 16:40:52 +03:00
Joe Lim 4dbc15e4b0 Validate selmode setting (#1206) 2023-04-15 19:52:37 +03:00
Joe Lim c0dfb3c4f5 Fix statusbar spacing (#1205)
* Fix statusbar spacing

* Fix ruler option check
2023-04-15 19:51:51 +03:00
Gokcehan 55ad40ac0a add 'ruler' to completion
cc #1168
2023-04-09 14:58:11 +03:00
Gokcehan c1583032aa update doc
cc #1168
2023-04-09 14:54:41 +03:00
rrveexandrr eb84772032 Customizable statusline, df (#1168)
* opts statusline, df

* renamed infostat -> ruler; removed os_lin, os_bsd

* removed vscode

---------

Co-authored-by: rr <rr@arveex.eu>
2023-04-09 14:50:34 +03:00
Joe Lim 821b2fcd51 Fix crash when sorting files in a directory (#1204) 2023-04-09 14:32:40 +03:00
Joe Lim 734f11d61b Simplify edge calculation when scrolling down (#1194)
* Simplify edge calculation when scrolling down

* Alternate implementation

* Alternate implementation #2
2023-04-09 14:23:43 +03:00
RuMaks 28b550a7ec Use $VISUAL for the e command instead of $EDITOR (#1197)
* Use $VISUAL for the `e` command instead of $EDITOR

* update `os_windows.go` and `doc.go`
2023-04-09 01:44:09 +03:00
Ilya Grigoriev 1e1486fc02 Make :maps work on Windows and add :cmaps. (#1201)
* Make `:maps` work on Windows

This makes the `:maps` command from #1146 work on Windows.

This (as well as `:maps` itself) is based on @jackielli's work in #1146 and
#1152.

I intend to refactor the code in this or a separate PR, but I thought I'd
submit the critical and simple bit first.

* Add `:cmaps` command

After the naming scheme from #1146, it would seem weird to not have a :cmaps
command. This could help with issues like #876.
2023-04-09 00:51:52 +03:00
dependabot[bot] bb45d15b83 Bump golang.org/x/term from 0.6.0 to 0.7.0 (#1198)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.6.0 to 0.7.0.
- [Release notes](https://github.com/golang/term/releases)
- [Commits](https://github.com/golang/term/compare/v0.6.0...v0.7.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-04-08 23:40:31 +03:00
Joe Lim b5c83dbf7a Add support for moving to a specific line (#1196)
* Add support for moving to a specific line

* Update documentation
2023-04-08 23:40:16 +03:00
Ilya Grigoriev 27d316c006 lfrc.example: Add mkdir, add "show execution result" (#1188)
Show how to map `a` to mkdir. `` ` `` maps to "show execution
result". Norton Commander & its successors map it to `<c-o>`,
but I think that's better for something opening-relatred.

Whenever a `$` command gives an unexpected error, I want to see
what happened. There are many ways to do so, but the one I added
here seems the simplest and it took me a while to think of it.
We could also have an option to have `$` commands pause like `!`
commands when there's an error.
2023-04-08 22:35:39 +03:00
Gokcehan 83af3e1cb0 add file operations to non-features in readme
close #887

cc #1179
2023-04-02 19:08:51 +03:00
Ilya Grigoriev 27ab67aab7 Make the :doc command work even if lf is not in the PATH, add lf environment variable (#1176)
* Export a `$lf` environment variable with path to lf binary

If Go fails to find a path to the lf binary, `$lf` is set to the string `lf` so
that running `$lf` in scripts gives a reasonable error message.

* Make the `:doc` command work even if lf is not in the PATH

Previously, `:doc` executed `lf -doc`. Now, it executed `$lf -doc` or `%lf%
-doc`.

Before this change, `:doc` did not work if `lf` is not in the PATH. This is
likely to happen to new users who are trying out `lf` and need docs the most.

Moreover, if you made some changes to the docs and ran `lf` with `go run .`,
`:doc` would return the docs for the version of `lf` in the PATH instead of
what is expected.
2023-04-01 19:49:47 +03:00
Joe Lim 3ae67fc361 Export count as a variable when running commands (#1187) 2023-04-01 19:40:28 +03:00
Paul Ouellette f563263add Completion: always insert longest match (#1184)
Previously, longest common match completion would only apply if there
was a word before the cursor.

Suggested in #1090
2023-04-01 19:25:55 +03:00
Paul Ouellette 70171adf40 Fix infinite loop in listMatches (#1183)
This fixes an issue where listMatches could get stuck in an infinite
loop if one of the matches was longer than the window width.

Fixes #1090
2023-04-01 19:24:55 +03:00
Joe Lim 11caeddb35 Support custom line number colors (#1177)
* Support custom line number colors

* Move eval case
2023-04-01 16:05:44 +03:00
Joe Lim 6ffc4a4c8a Display zero when relativenumber is enabled (#1171) 2023-03-25 18:35:08 +03:00
Gokcehan 0eddc1e724 cleanup
cc #845 #1169
2023-03-25 18:25:09 +03:00
Joe Lim 43fced28e3 Use tcell constants for drawbox (#1170) 2023-03-21 20:30:03 +03:00
Joe Lim 68e2433d48 Improve preview loading message flickering (#1154)
* Improve preview loading

* Change timeout to 100 milliseconds

* Add previewtimeout option

* Start preview outside other goroutines

* Revert previewtimeout option
2023-03-21 19:49:37 +03:00
dependabot[bot] 25288fd90b Bump actions/setup-go from 3 to 4 (#1160)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v3...v4)

---
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-03-20 20:11:45 +03:00
rrveexandrr 122dee1f45 Enhance rename prompt (#1162)
* enhance rename ui

* gofmt

* default rename: cursor on dot

* fix basename length

* fix basename length... again

---------

Co-authored-by: rr <rr@arveex.eu>
2023-03-20 20:11:23 +03:00
Joe Lim 8652707299 Avoid refreshing previews for async shell commands (#1164) 2023-03-20 19:59:39 +03:00
Gokcehan 41cdd02572 update doc
cc #758
2023-03-16 18:11:29 +03:00
Gokcehan 207de6a506 add errors for unexpected boolean option values
cc #758
2023-03-16 17:51:59 +03:00
Gokcehan acb5693b11 cleanup 2023-03-16 17:35:56 +03:00
Gokcehan 85512625f8 add 'true/false' syntax for boolean options
cc #758
2023-03-16 17:24:41 +03:00
Joe Lim 0bf17dd3f0 Fix width used for line numbers (#1151) 2023-03-12 15:35:23 +03:00
Joe Lim db9de4d4de Refactor code for printing directories (#1150) 2023-03-12 15:34:44 +03:00
Joe Lim 9440b1b319 Update file info after reload command (#1149)
* Update status bar after reload

* Add comment
2023-03-12 15:30:16 +03:00
Jackie Li a85ce898a1 try to fix #916 (#1146) 2023-03-12 15:24:44 +03:00
Joe Lim 9f1428582f Remove commented code (#1141) 2023-03-12 15:11:25 +03:00
Joe Lim bcd058ace2 Delete stale dircache entry during rename (#1138)
* Delete stale dircache entry during rename

* Clear `regCache` as well

* Add comment
2023-03-12 15:11:09 +03:00
dependabot[bot] 382534c4ba Bump golang.org/x/term from 0.5.0 to 0.6.0 (#1137)
Bumps [golang.org/x/term](https://github.com/golang/term) from 0.5.0 to 0.6.0.
- [Release notes](https://github.com/golang/term/releases)
- [Commits](https://github.com/golang/term/compare/v0.5.0...v0.6.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-03-12 15:07:28 +03:00
dependabot[bot] c2cbc39ce5 Bump golang.org/x/sys from 0.5.0 to 0.6.0 (#1136)
Bumps [golang.org/x/sys](https://github.com/golang/sys) from 0.5.0 to 0.6.0.
- [Release notes](https://github.com/golang/sys/releases)
- [Commits](https://github.com/golang/sys/compare/v0.5.0...v0.6.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-03-12 15:04:23 +03:00
István Donkó a8e95ae40a Replace the obsolete Vue icon in the example file (#1123) 2023-03-12 15:04:07 +03:00
dependabot[bot] 3fc1db5d14 Bump github.com/gdamore/tcell/v2 (#1128)
Bumps [github.com/gdamore/tcell/v2](https://github.com/gdamore/tcell) from 2.5.4-0.20221019011350-d3cbfcfb7aa3 to 2.6.0.
- [Release notes](https://github.com/gdamore/tcell/releases)
- [Commits](https://github.com/gdamore/tcell/commits/v2.6.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-02-26 01:04:32 +03:00
Ilya Grigoriev 7a7e81e88c Update the Go version in go.mod to 1.18 (#1132)
* Replace functions from `ioutil` with same functions from `io`

This is demanded by staticcheck if we upgrade the go version in go.mod.

* Replace ioutil.ReadDir with os.ReadDir

* Update Go version to 1.18 in go.mod

This requires abandoning use of the `ioutil` module (see parent commits)
to pass `staticcheck`.
2023-02-26 01:01:04 +03:00
Ilya Grigoriev b02fd42df4 invert-below command to substitute for visual mode (#1101)
This command inverts the selection for the current file and all the files below
it. Using this command twice substitutes for having a "visual" mode. This is
described in more detail in the docs and in
https://github.com/gokcehan/lf/issues/477#issuecomment-1414563834.

Fixes #477. While that's not exactly what was asked for, I hope it's a suitable
replacement and seems more in the spirit of `lf`, at least until a better
replacement is implemented.
2023-02-26 01:00:54 +03:00
Gokcehan 752f059068 remove older than go1.17 instructions from readme 2023-02-25 23:25:52 +03:00
Gokcehan 326930f46f change go version from 1.17 to 1.18 2023-02-25 23:19:07 +03:00
dependabot[bot] 6c3366eec4 Bump actions/checkout from 2 to 3 (#1129)
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [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/v2...v3)

---
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-02-25 23:12:56 +03:00
dependabot[bot] 28936c7506 Bump dominikh/staticcheck-action from 1.2.0 to 1.3.0 (#1127)
Bumps [dominikh/staticcheck-action](https://github.com/dominikh/staticcheck-action) from 1.2.0 to 1.3.0.
- [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.2.0...v1.3.0)

---
updated-dependencies:
- dependency-name: dominikh/staticcheck-action
  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-02-25 23:12:18 +03:00
dependabot[bot] 960f23c288 Bump actions/setup-go from 2 to 3 (#1126)
Bumps [actions/setup-go](https://github.com/actions/setup-go) from 2 to 3.
- [Release notes](https://github.com/actions/setup-go/releases)
- [Commits](https://github.com/actions/setup-go/compare/v2...v3)

---
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-02-25 23:10:47 +03:00
sitiom 95a6f9584f Add Winget Releaser workflow (#1107)
* Add Winget Releaser workflow

* Add dependabot

* Update release.yml
2023-02-25 23:01:00 +03:00
David Pedersen cae576bb1d Navigate cmd history with up/down (#1112) 2023-02-25 20:41:32 +03:00
Ilya Grigoriev 6afefa5d09 Option to change look of cursors in parent dirs, rename an option. (#1106)
* Add `cursorparentfmt` option for cursors in parent dirs

The option defaults to the same value as `cursorfmt`, so the default look of `lf` is unchanged. However, I find it useful to make it different, since I seem to have so much trouble figuring out which of my cursors is the active one. :)

For example, here's what it looks like if one has `set cursorparentfmt "\033[7;90m"` in their `lfrc`:

https://user-images.githubusercontent.com/4123047/218299130-09ac411f-307a-489e-a4f0-4691710f8549.png

* Remove `cursorfmt` option to `cursoractivefmt`

This seems appropriate after introducing `cursorparentfmt`
2023-02-25 20:38:41 +03:00
Joe Lim c0c85f206f Fix documentation for dironly/dirpreviews options (#1105) 2023-02-12 14:38:58 +03:00
Ilya Grigoriev 530ab2c40a Allow separate styles for cursor in normal and preview panes, simplify tagfmt and errorfmt (#1086)
* Allow separate styles for cursor in normal and preview panes

This defines new `cursorfmt` and `crusorpreviewfmt` options to style cursor in normal/preview panes. This allows using a different style for the normal and preview cursor. The documentation includes several possible values these options can be set to.

The default behavior is an underline, same as in
https://github.com/gokcehan/lf/pull/1072, since it should not cause severe
problems and be visible on all terminals. It can now be easily changed, as explained in the docs. I also added an example to `etc/lfrc.example`.

See linked issues and PRs for the more context.

Fixes https://github.com/gokcehan/lf/issues/1038

Follows up on:

https://github.com/gokcehan/lf/pull/1072
https://github.com/gokcehan/lf/pull/924
https://github.com/gokcehan/lf/commit/b47cf6d5a5

* Simplify configuration of several formatting options

This simplifies the configuration of `cursorfmt`, `cursorpreviewfmt`, `tagfmt`,
and `errorfmt` options.

In almost all usecases, the value of these options had to end with `%s\033[0m`
to print the contents of filename/tag/error and reset the terminal style. Now,
if `%s` is not part of the option's value, `%s\033[0m` is appended
automatically. This simplifies configuration.

I retained the same behavior as before when `%s` is part of the string for
backwards compatibility. I think it should be considered deprecated, but it
also causes no harm.
2023-02-11 20:11:07 +03:00
Joe Lim 4a443cae58 Refresh preview even if selection doesn't change (#1074) 2023-02-11 20:01:46 +03:00
valoq 0b99aaed4e Add example to hiddenfiles documentation (#1073)
* Improve documentation

* fix missing quote

* update manpage
2023-02-11 20:01:20 +03:00
Ilya Grigoriev 6440281e82 Disallow exiting from rename: mode with backspace (#1060)
After looking at the list of possibilities for `app.ui.cmdPrefix` by searching
through the code, renaming looks to be the only remaining mode where exiting
via backspace doesn't make sense.

In particular, I don't think any commands other than `rename` commonly start
out with some editable text in the prompt. The other dangerous mode is the `>`
mode, but there exit-on-backspace was already disabled.

Fixes #1052, #1059
2023-02-11 20:00:08 +03:00
Ilya Grigoriev 2fe5e4d54e Bind Ctrl+MouseWheel to scroll up/down (#1051)
On my system, Shift+Mouse is captured by the terminal and
Alt+Mouse only works for one of the alt keys. Hence I picked
Ctrl.

This also allows binding of Ctrl+MouseButtons (but doesn't set
any such bindings). 

As a minor bonus, that should allow using Ctrl+Click to select
`lf`'s terminal without moving the cursor no matter where you
click.  On tmux, this doesn't work out of the box and requires
a change to `tmux.conf` along the following lines:

     bind-key -T root  C-MouseDown1Pane  select-pane -t = \; send-keys -M

You can omit the `send-keys -M` if you never want to pass
`Ctrl+Click` to any of your terminal apps. (Then it will work
without this PR).
2023-02-11 19:58:44 +03:00
Ilya Grigoriev a4fa5d36c9 Make lfcd examples safer for people who alias lf to lfcd (#1049)
People keep running into an infinite loop and being confused.
See https://github.com/gokcehan/lf/issues/140#issuecomment-1256368250
and https://github.com/gokcehan/lf/discussions/1043.

This fixes the issues in `lfcd.sh` and `lfcd.fish`. For the other
scripts, I'm not sure whether this issue exists or is fixable.

One of the discussions above also suggested the need to document
the key binding better.
2023-02-11 19:55:49 +03:00
Gokcehan b47cf6d5a5 revert dim colors for previews
cc #924 #1038
2022-12-24 23:15:46 +03:00
Penn Bauman aa78b26e44 updated gopkg.in/djherbis/times.v1 v1.2.0 to github.com/djherbis/times v1.5.0 (#1017) 2022-11-28 19:16:15 +03:00
Gokcehan 4440a15a8c add the current example open command to the doc
cc #991
2022-11-15 21:26:30 +03:00
devnull09 887748cefd Avoids flicker during open (#991)
* Avoids flicker during open

* Update lfrc.example

remove setsid after we execute is with open &{{ anyway
2022-11-15 21:07:30 +03:00
Gokcehan c1bcf71ece export lf_width and lf_height as env variables
cc #718 #975
2022-11-13 23:00:13 +03:00
valoq 459608e096 load file info after init (#994)
* load fileinfo after init

* do not overwrite error message if present
2022-11-13 17:20:27 +03:00
maidlover 9bb2487b14 Fix toggling of directory previews (#993)
* Fix toggling of directory previews

* Fix "dirpreviews!"

* Sort tab completion items consistently
2022-11-13 17:20:01 +03:00
Ilya Grigoriev 48d1899ec8 When clicking on file preview, only open files on right-click (+ doc fix) (#975)
* When clicking on file preview, only open files on right-click

Currently, when mouse is on, I often click on the preview accidentally
since it's such a large target. Moreover, there is very little space I
can click without having the `lf` state change drastically (since I must
click on the current file for the preview to stay the same).

This commit prevents that.

* (Minor): Change example in docs to work around a bug

Currently, the example fails confusingly for newer versions
of `tput`. See https://github.com/gokcehan/lf/issues/718.
2022-11-13 16:54:54 +03:00
Paul Ouellette a94015d221 Add mouse support for selecting and opening files (#963)
* Add mouse support for selecting and opening files

Left click to select, right click to open, similar to ranger.
Closes #919.

* Add default mouse wheel mappings

* Update tcell to d3cbfcf

Commit d3cbfcf fixes a bug where mouse wheel events were misdelivered as
button events.
2022-10-19 18:57:44 +03:00
Gaétan Lepage 8e919b8268 Fix user query when using libc implementation of os/user (#972) 2022-10-19 18:56:04 +03:00
Ilya Grigoriev e4fa885d26 Remove accidentally commited empty file (#970) 2022-10-18 15:34:18 +03:00
Ilya Grigoriev 624992ad7b Add staticcheck and go-generate Github check (#968)
* Fix Staticcheck errors & minor logic simplification

Simplify logic in ui.go. In that diff, `st` would already have the
Reversed flag set; there's no need to set it again.

Also, minor changes to remove all the statickcheck errors VS code's
Go extension complains about.

* Add staticcheck and Go 1.19 go-generate Github check

This adds a few Github action checks:

1. Check that `go fmt` and `go generate` were run on Go 1.19, following
up on https://github.com/gokcehan/lf/commit/654b8737b8a35729aa89aa93acf05ed5871b2616.
On earlier Go versions, `go generate` results in whitespace changes.

2. Check that [Staticcheck](https://staticcheck.io/) passes.
2022-10-16 18:54:34 +03:00
Ilya Grigoriev 04d40832f1 For directories in preview column, dim cursor (#924)
* For directories in preview column, dim cursor

When preview is on and consists of a directory listing, make the
cursor in there dimmer to emphasize it's not active. This makes it
visually obvious which cursor is active at all times, without
having to read the path. The active cursor is now always  the
rightmost bright one, regardless of whether the `preview` option
is on or off.

See screenshots in the pull request at
https://github.com/gokcehan/lf/pull/924.

Before this, I noticed that I often open a file by accident because
I got confused which of the three cursors on the screen is the active
one.

* No-op changes to ui.go

Reduce number of arguments to printDir and list non-configurable colors
2022-10-16 18:51:26 +03:00
Ilya Grigoriev f1312ca969 Fix Staticcheck errors & minor logic simplification (#967)
Simplify logic in ui.go. In that diff, `st` would already have the
Reversed flag set; there's no need to set it again.

Also, minor changes to remove all the statickcheck errors VS code's
Go extension complains about.
2022-10-16 18:50:41 +03:00
Ilya Grigoriev e570d5f65b Document mode-switching between : and !/$/%/& command-line modes (#966)
Documents #960, also known as
https://github.com/gokcehan/lf/pull/960/commits/52a151aba22f745e045427bf6c45511325abc6fa
2022-10-16 18:46:43 +03:00
Gokcehan 654b8737b8 update man generator for go1.19
cc #959 #961
2022-10-15 21:34:55 +03:00
Christian Zangl e10ef9111b add an on-select command (#864) 2022-10-15 21:06:09 +03:00
Paul Ouellette 747aff8763 Disable mouse drag events (#962)
This fixes an issue where mouse bindings would be repeated when clicking
and dragging.
2022-10-15 16:10:44 +03:00
Ilya Grigoriev 8b11ffd698 Switching back and forth between : and !/$/%/& command-line modes (#960)
# What this does

This makes the following changes:

1. If the we are in any of the shell command-line modes (after pressing one of
`!/$/%/&`) and the cursor is at the first character, pressing `backspace`
switches you to the `:` mode. Pressing `backspace` again will take you out of
the command-line mode as before (this commit extends the recent [escape on
backspace] functionality).

[escape on backspace]: https://github.com/gokcehan/lf/commit/36a7a18316580864f2f2ebd79e9ddae4858f6b60

2. Conversely, if we are in the `:` mode and the cursor is at the first
character, pressing one of `!/$/%/&` will take you to the corresponding mode
insted of inserting that character. This is a very minor change, since already
pressing `:!ls<ret>` and `!ls <ret>` in `lf` has the same effect. After this
commit, these will also look the same even before pressing `<ret>`.

3. There is a minor bugfix to the [escape on backspace] commit. In `>` mode
(when a program launched with `&` waits for input), `lf` currently switches to
normal mode on `backspace` without terminating the program. After this commit,
the "escape on backspace" functionality is disabled in `>` mode.

This idea is borrowed from the [Julia REPL modes].

[Julia REPL modes]: https://docs.julialang.org/en/v1/stdlib/REPL/#Help-mode

# What problems this solves

The main problem I want to solve is that I often type `$ls <many options>` and
realize I wanted `!ls` all along. Currently, there is no easy way to switch.
With this commit, it becomes trivial.

This problem also occurs when you scroll up to a `$ls <many options>` command
in history.

Finally, since `!` and `:!` have essentially the same effect in `lf`, I think
they should look the same.
2022-10-15 16:09:06 +03:00
Paul Ouellette cdbc9948f8 Completion code cleanup and improvements (#958)
- Clean up some code duplication.
- When completing files with menu completion while searching, don't
  escape the selected match.
- Don't recompute completions while cycling completion menu.
2022-10-15 16:05:17 +03:00
Paul Ouellette 8c490dddd2 Ignore case in filename completion (#954)
* Revert escaping changes from cb7aa13

The changes introduced a bug where escapes were removed when there are
no completion matches.

* Add option to ignore case in filename completion

* Remove compignorecase option and hardcode it
2022-10-15 16:04:14 +03:00
Christian Zangl a2fed6d16e add user defined options (#865) 2022-10-15 15:50:21 +03:00
Ailac 62621736b3 Getting command count from definition (#863)
* Get command default count from definition

The command count defined in opts.go will be respected. In order to do that a copy of the callExpr or listExpr command is created so that the defined count is not overridden.

* Copy the command only if we need to overwrite the count
2022-10-15 15:48:05 +03:00
Christian Zangl 21a32a7603 Add a selection mode that limits the selection to the current directory. (#849) 2022-10-15 15:43:15 +03:00
Salle Helevä 479ed924f7 Implement directory previews (#842)
* Directory previews, initial implementation.

* Continue previous; add goroutine for directory previews.

* Enable dirpreviews as an option, run gofmt and fix referencing nil.

* Only use dirpreviews if previewer script exists.

* Remove redundant function call to `dirPreview`.

* Remove unnecessary dev-comments.

* Send to `dirPreviewChan` also on modifying folder contents.
2022-10-15 15:42:08 +03:00
Paul Ouellette 4968b1da42 Reset history position when leaving command line (#953)
Previously the history position was only reset when executing the
history prev/next command in normal mode, so it was not reset if you
entered command-line mode then started moving through the history.
2022-10-01 16:39:11 +03:00
Franciosi fc71c6f8b9 README.md Update (#951)
s/MacOS/macOS, simple one
2022-10-01 16:38:50 +03:00
Gokcehan 0906d39676 update doc
cc #945
2022-10-01 16:37:39 +03:00
Seninha c5dfd6df51 implement gokcehan#606 (#945) 2022-10-01 16:36:26 +03:00
Paul Ouellette 165fecbea0 Fix minor incsearch weirdness (#944)
This fixes an issue where if you stared a search then deleted the search
text (with e.g. backspace) it would perform a search for the empty
string and move the selection to the next file.
2022-10-01 16:33:22 +03:00
Paul Ouellette 75869f0ac3 support italic escape code in previews (#936) 2022-10-01 16:32:39 +03:00
Paul Ouellette cb7aa13218 Fix a few completion bugs and add a few small features (#934)
* Fix some multibyte character completion bugs

- matchLongest now operates on runes instead of bytes so we don't
  complete part of a multibyte character.
- Fix some places that mixed string and rune slice indices.

* Fix wrong menu completion for subdirectories

When selecting a menu completion for a file in a subdirectory, the
entire filename would be appended to the command line, even if you had
already typed part of it.

* Escape file completions in menu completion

* Minor refactors and typo fixes

* Fix cmd-menu-complete-back bug

The first use of cmd-menu-complete-back after opening the completion
menu was incorrectly selecting the before-last completion instead of the
last completion.

* Allow completing broken symlinks

Also skip files with stat errors instead of returning.

* Add command to accept current menu selection

This is useful when completing filenames. For example

    cmap <c-y> :cmd-menu-accept; cmd-menu-complete

can be used to accept the selected directory completion, then complete
files in the directory.

* Complete command names for map and cmap
2022-10-01 16:31:58 +03:00
Paul Ouellette 5ba70d0f61 Documentation fixes and updates (#933)
- Document history option
- Use $() command substitution syntax because backticks are replaced
  with quotes in gen/docstring.sh
- Movement commands no longer close the search prompt (85aa3b9)
- Use the -L flag of the file command instead of readlink
2022-10-01 16:29:21 +03:00
desbma 01d3b69de0 feat: case insensitive extension matching for icons & colors (#908) 2022-10-01 16:27:14 +03:00
Paul Ouellette 17e1a84646 Fix missing completion for a few commands (#929) 2022-09-08 16:10:49 +03:00
ferreum b0cb9268d8 docs: update lifted restrictions on cmap (#886) 2022-08-06 15:53:26 +03:00
Christian Zangl e03143299d Add a spacer %S to the promptfmt (#867) 2022-07-10 15:32:55 +03:00
segf00lt da2d8a2979 added history options (#866)
* added history options

* sorry forgot to update docs
2022-07-10 15:32:34 +03:00
Gokcehan aee5c3371f handle colons in paths for tags properly
cc #857
2022-06-26 15:36:17 +03:00
SeekingBlues 36a7a18316 Go to normal mode when backspacing on empty prompt (#836)
This matches up with vim's behavior.
2022-05-21 13:54:17 +03:00
SeekingBlues 2104a501aa Fix user name, group name and link count display (#829)
These type assertions for `Stat_t` were changed from `syscall` to
the incorrect `unix` ones in c5bd676.

Fixes #800.
2022-05-12 19:25:50 +03:00
SeekingBlues addb6e243e Update docs of calcdirsize and dircounts (#827)
* Clarify what `-` means in the `size` info field.
* Reflect the fact that we no longer display the size of the
directory itself.
2022-05-09 14:28:06 +03:00
Gokcehan a89f0242bf update doc
cc #826
2022-05-08 19:52:59 +03:00
zxcat 6e17d2bd20 docs: fix number of special commands (#826)
* doc.go: fix "three special commands"

* lf.1: fix "three special commands"
2022-05-08 19:52:42 +03:00
tucuxi b0f2a2875a handle empty answer in delete (#809)
* handle empty answer in delete

* handle empty answer in delete
2022-05-08 14:53:34 +03:00
Gokcehan 745f1588ed add missing 'tagfmt' evaluation
cc #791
2022-05-08 14:28:26 +03:00
Gokcehan 7feb42db34 rename move commands to high/middle/low
cc #824
2022-05-08 14:03:32 +03:00
Christian Zangl 01fe12b2ce Add VIMs hi/mid/lo-screen commands (#824)
* add hi/mid/lo-screen commands and default keybindings

* doc
2022-05-08 13:58:56 +03:00
35 changed files with 3214 additions and 1617 deletions

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"
+26 -3
View File
@@ -14,15 +14,38 @@ jobs:
matrix: matrix:
os: [ubuntu-latest, windows-latest] os: [ubuntu-latest, windows-latest]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
with:
fetch-depth: 1
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v2 uses: actions/setup-go@v4
with: with:
go-version: 1.17 go-version: 1.18
- name: Build - name: Build
run: go build -v ./... run: go build -v ./...
- name: Test - name: Test
run: go test -v ./... run: go test -v ./...
- uses: dominikh/staticcheck-action@v1.3.0
with:
version: "2022.1.3"
install-go: false
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v4
with:
go-version: 1.19
- name: Test `go fmt && go generate` on Go 1.19 creates no diffs
run: go fmt && go generate && git diff --exit-code
+14 -3
View File
@@ -10,12 +10,12 @@ jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v3
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v2 uses: actions/setup-go@v4
with: with:
go-version: 1.17 go-version: 1.18
- name: Build - name: Build
run: gen/xbuild.sh run: gen/xbuild.sh
@@ -26,3 +26,14 @@ jobs:
files: dist/* files: dist/*
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
winget:
runs-on: windows-latest # Action can only run on Windows
needs: build
steps:
- uses: vedantmgoyal2009/winget-releaser@v2
with:
identifier: gokcehan.lf
version: ${{ github.ref_name }}
installers-regex: '-windows-\w+\.zip$'
token: ${{ secrets.WINGET_TOKEN }}
+5 -26
View File
@@ -18,7 +18,7 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tut
## Features ## Features
- Cross-platform (Linux, MacOS, BSDs, Windows) - Cross-platform (Linux, macOS, BSDs, Windows)
- Single binary without any runtime dependencies - Single binary without any runtime dependencies
- Fast startup and low memory footprint due to native code and static binaries - Fast startup and low memory footprint due to native code and static binaries
- Asynchronous IO operations to avoid UI locking - Asynchronous IO operations to avoid UI locking
@@ -31,6 +31,7 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tut
- Tabs or windows (better handled by window manager or terminal multiplexer) - Tabs or windows (better handled by window manager or terminal multiplexer)
- Builtin pager/editor (better handled by your pager/editor of choice) - Builtin pager/editor (better handled by your pager/editor of choice)
- Builtin commands for file operations (better handled by the underlying shell tools including but not limited to `mkdir`, `touch`, `chmod`, `chown`, `chgrp`, and `ln`)
## Installation ## Installation
@@ -40,42 +41,20 @@ See [releases](https://github.com/gokcehan/lf/releases) for pre-built binaries.
Building from the source requires [Go](https://go.dev/). Building from the source requires [Go](https://go.dev/).
On Unix (Go version < 1.17): On Unix:
```bash
env CGO_ENABLED=0 GO111MODULE=on go get -u -ldflags="-s -w" github.com/gokcehan/lf
```
On Unix (Go version >= 1.17):
```bash ```bash
env CGO_ENABLED=0 go install -ldflags="-s -w" github.com/gokcehan/lf@latest env CGO_ENABLED=0 go install -ldflags="-s -w" github.com/gokcehan/lf@latest
``` ```
On Windows `cmd` (Go version < 1.17): On Windows `cmd`:
```cmd
set CGO_ENABLED=0
set GO111MODULE=on
go get -u -ldflags="-s -w" github.com/gokcehan/lf
```
On Windows `cmd` (Go version >= 1.17):
```cmd ```cmd
set CGO_ENABLED=0 set CGO_ENABLED=0
go install -ldflags="-s -w" github.com/gokcehan/lf@latest go install -ldflags="-s -w" github.com/gokcehan/lf@latest
``` ```
On Windows `powershell` (Go version < 1.17): On Windows `powershell`:
```powershell
$env:CGO_ENABLED = '0'
$env:GO111MODULE = 'on'
go get -u -ldflags="-s -w" github.com/gokcehan/lf
```
On Windows `powershell` (Go version >= 1.17):
```powershell ```powershell
$env:CGO_ENABLED = '0' $env:CGO_ENABLED = '0'
+63 -7
View File
@@ -30,6 +30,9 @@ type app struct {
cmdHistory []cmdItem cmdHistory []cmdItem
cmdHistoryBeg int cmdHistoryBeg int
cmdHistoryInd int cmdHistoryInd int
menuCompActive bool
menuComps []string
menuCompInd int
} }
func newApp(ui *ui, nav *nav) *app { func newApp(ui *ui, nav *nav) *app {
@@ -59,9 +62,11 @@ func newApp(ui *ui, nav *nav) *app {
} }
func (app *app) quit() { func (app *app) quit() {
if gOpts.history {
if err := app.writeHistory(); err != nil { if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err) log.Printf("writing history file: %s", err)
} }
}
if !gSingleMode { if !gSingleMode {
if err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil { if err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil {
log.Printf("dropping connection: %s", err) log.Printf("dropping connection: %s", err)
@@ -237,6 +242,7 @@ func (app *app) writeHistory() error {
// separate goroutines and sent here for update. // separate goroutines and sent here for update.
func (app *app) loop() { func (app *app) loop() {
go app.nav.previewLoop(app.ui) go app.nav.previewLoop(app.ui)
go app.nav.dirPreviewLoop(app.ui)
var serverChan <-chan expr var serverChan <-chan expr
if !gSingleMode { if !gSingleMode {
@@ -318,6 +324,7 @@ func (app *app) loop() {
app.quit() app.quit()
app.nav.previewChan <- "" app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
log.Print("bye!") log.Print("bye!")
@@ -382,6 +389,7 @@ 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) app.nav.checkDir(d)
if gOpts.dircache { if gOpts.dircache {
@@ -405,7 +413,10 @@ func (app *app) loop() {
curr, err := app.nav.currFile() curr, err := app.nav.currFile()
if err == nil { if err == nil {
if d.path == app.nav.currDir().path { if d.path == app.nav.currDir().path {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
if app.ui.msg == "" {
app.ui.loadFileInfo(app.nav)
}
} }
if d.path == curr.path { if d.path == curr.path {
app.ui.dirPrev = d app.ui.dirPrev = d
@@ -427,7 +438,7 @@ func (app *app) loop() {
app.ui.draw(app.nav) app.ui.draw(app.nav)
case ev := <-app.ui.evChan: case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev) e := app.ui.readEvent(ev, app.nav)
if e == nil { if e == nil {
continue continue
} }
@@ -436,7 +447,7 @@ func (app *app) loop() {
for { for {
select { select {
case ev := <-app.ui.evChan: case ev := <-app.ui.evChan:
e = app.ui.readEvent(ev) e = app.ui.readEvent(ev, app.nav)
if e == nil { if e == nil {
continue continue
} }
@@ -454,12 +465,19 @@ func (app *app) loop() {
app.ui.draw(app.nav) app.ui.draw(app.nav)
case <-app.ticker.C: case <-app.ticker.C:
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, false) app.ui.loadFile(app, false)
app.ui.draw(app.nav)
case <-app.nav.previewTimer.C:
app.nav.previewLoading = true
app.ui.draw(app.nav) app.ui.draw(app.nav)
} }
} }
} }
type cleanFunc func()
var noopCleanFunc = func() {}
// This function is used to run a shell command. Modes are as follows: // This function is used to run a shell command. Modes are as follows:
// //
// Prefix Wait Async Stdin Stdout Stderr UI action // Prefix Wait Async Stdin Stdout Stderr UI action
@@ -467,8 +485,10 @@ func (app *app) loop() {
// % No No Yes Yes Yes Statline for input/output // % No No Yes Yes Yes Statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume // ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing // & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) { // $| 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.nav.exportFiles()
app.ui.exportSizes()
exportOpts() exportOpts()
cmd := shellCommand(s, args) cmd := shellCommand(s, args)
@@ -476,12 +496,32 @@ func (app *app) runShell(s string, args []string, prefix string) {
var out io.Reader var out io.Reader
var err error var err error
switch prefix { 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 "$", "!": case "$", "!":
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
app.nav.previewChan <- "" app.nav.previewChan <- ""
app.nav.dirPreviewChan <- nil
if err := app.ui.suspend(); err != nil { if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err) log.Printf("suspend: %s", err)
} }
@@ -498,7 +538,7 @@ func (app *app) runShell(s string, args []string, prefix string) {
case "%": case "%":
shellSetPG(cmd) shellSetPG(cmd)
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return noopCleanFunc
} }
stdin, err := cmd.StdinPipe() stdin, err := cmd.StdinPipe()
if err != nil { if err != nil {
@@ -526,7 +566,11 @@ func (app *app) runShell(s string, args []string, prefix string) {
anyKey() anyKey()
} }
app.ui.loadFile(app.nav, true) // 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 "%":
@@ -571,5 +615,17 @@ func (app *app) runShell(s string, args []string, prefix string) {
log.Printf("running shell: %s", err) log.Printf("running shell: %s", err)
} }
}() }()
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
}
+1 -2
View File
@@ -4,7 +4,6 @@ import (
"bufio" "bufio"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"log" "log"
"net" "net"
"os" "os"
@@ -34,7 +33,7 @@ func run() {
defer f.Close() defer f.Close()
log.SetOutput(f) log.SetOutput(f)
} else { } else {
log.SetOutput(ioutil.Discard) log.SetOutput(io.Discard)
} }
log.Print("hi!") log.Print("hi!")
+3 -1
View File
@@ -110,6 +110,8 @@ func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
st = st.Bold(true) st = st.Bold(true)
case n == 2: case n == 2:
st = st.Dim(true) st = st.Dim(true)
case n == 3:
st = st.Italic(true)
case n == 4: case n == 4:
st = st.Underline(true) st = st.Underline(true)
case n == 5 || n == 6: case n == 5 || n == 6:
@@ -319,7 +321,7 @@ func (sm styleMap) get(f *file) tcell.Style {
return val return val
} }
if val, ok := sm["*"+f.ext]; ok { if val, ok := sm["*"+strings.ToLower(f.ext)]; ok {
return val return val
} }
+1 -1
View File
@@ -74,7 +74,7 @@ func TestApplyAnsiCodes(t *testing.T) {
for _, test := range tests { for _, test := range tests {
if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp { if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%d' expected '%d' but got '%d'", t.Errorf("at input '%s' with '%v' expected '%v' but got '%v'",
test.s, test.st, test.stExp, stGot) test.s, test.st, test.stExp, stGot)
} }
} }
+130 -79
View File
@@ -1,7 +1,6 @@
package main package main
import ( import (
"io/ioutil"
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
@@ -13,7 +12,11 @@ var (
gCmdWords = []string{ gCmdWords = []string{
"set", "set",
"map", "map",
"maps",
"cmap",
"cmaps",
"cmd", "cmd",
"quit",
"up", "up",
"half-up", "half-up",
"page-up", "page-up",
@@ -24,20 +27,40 @@ var (
"scroll-down", "scroll-down",
"updir", "updir",
"open", "open",
"quit", "jump-next",
"jump-prev",
"jumps",
"top", "top",
"bottom", "bottom",
"high",
"middle",
"low",
"toggle", "toggle",
"invert", "invert",
"invert-below",
"unselect", "unselect",
"glob-select",
"glob-unselect",
"calcdirsize",
"copy", "copy",
"cut", "cut",
"paste", "paste",
"clear", "clear",
"sync",
"draw",
"redraw", "redraw",
"load",
"reload", "reload",
"read", "echo",
"echomsg",
"echoerr",
"cd",
"select",
"delete",
"rename", "rename",
"source",
"push",
"read",
"shell", "shell",
"shell-pipe", "shell-pipe",
"shell-wait", "shell-wait",
@@ -53,24 +76,37 @@ var (
"filter", "filter",
"setfilter", "setfilter",
"mark-save", "mark-save",
"mark-remove",
"mark-load", "mark-load",
"draw", "mark-remove",
"load",
"sync",
"echo",
"echomsg",
"echoerr",
"cd",
"calcdirsize",
"select",
"glob-select",
"glob-unselect",
"source",
"push",
"delete",
"tag", "tag",
"tag-toggle", "tag-toggle",
"cmd-escape",
"cmd-complete",
"cmd-menu-complete",
"cmd-menu-complete-back",
"cmd-menu-accept",
"cmd-enter",
"cmd-interrupt",
"cmd-history-next",
"cmd-history-prev",
"cmd-left",
"cmd-right",
"cmd-home",
"cmd-end",
"cmd-delete",
"cmd-delete-back",
"cmd-delete-home",
"cmd-delete-end",
"cmd-delete-unix-word",
"cmd-yank",
"cmd-transpose",
"cmd-transpose-word",
"cmd-word",
"cmd-word-back",
"cmd-delete-word",
"cmd-capitalize-word",
"cmd-uppercase-word",
"cmd-lowercase-word",
} }
gOptWords = []string{ gOptWords = []string{
@@ -80,6 +116,9 @@ var (
"autoquit", "autoquit",
"noautoquit", "noautoquit",
"autoquit!", "autoquit!",
"cursoractivefmt",
"cursorparentfmt",
"cursorpreviewfmt",
"dircache", "dircache",
"nodircache", "nodircache",
"dircache!", "dircache!",
@@ -92,6 +131,9 @@ var (
"dironly", "dironly",
"nodironly", "nodironly",
"dironly!", "dironly!",
"dirpreviews",
"nodirpreviews",
"dirpreviews!",
"drawbox", "drawbox",
"nodrawbox", "nodrawbox",
"drawbox!", "drawbox!",
@@ -131,6 +173,7 @@ var (
"reverse", "reverse",
"noreverse", "noreverse",
"reverse!", "reverse!",
"ruler",
"smartcase", "smartcase",
"nosmartcase", "nosmartcase",
"smartcase!", "smartcase!",
@@ -151,25 +194,29 @@ var (
"errorfmt", "errorfmt",
"filesep", "filesep",
"hiddenfiles", "hiddenfiles",
"history",
"ifs", "ifs",
"info", "info",
"numberfmt",
"previewer", "previewer",
"cleaner", "cleaner",
"promptfmt", "promptfmt",
"ratios", "ratios",
"selmode",
"shell", "shell",
"shellflag", "shellflag",
"shellopts", "shellopts",
"sortby", "sortby",
"timefmt", "timefmt",
"tempmarks", "tempmarks",
"tagfmt",
"infotimefmtnew", "infotimefmtnew",
"infotimefmtold", "infotimefmtold",
"truncatechar", "truncatechar",
} }
) )
func matchLongest(s1, s2 string) string { 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++ {
if s1[i] != s2[i] { if s1[i] != s2[i] {
@@ -179,28 +226,28 @@ func matchLongest(s1, s2 string) string {
return s1[:i] return s1[:i]
} }
func matchWord(s string, words []string) (matches []string, longest string) { func matchWord(s string, words []string) (matches []string, longest []rune) {
for _, w := range words { for _, w := range words {
if !strings.HasPrefix(w, s) { if !strings.HasPrefix(w, s) {
continue continue
} }
matches = append(matches, w) matches = append(matches, w)
if longest != "" { if len(longest) != 0 {
longest = matchLongest(longest, w) longest = matchLongest(longest, []rune(w))
} else if s != "" { } else if s != "" {
longest = w + " " longest = []rune(w + " ")
} }
} }
if longest == "" { if len(longest) == 0 {
longest = s longest = []rune(s)
} }
return return
} }
func matchExec(s string) (matches []string, longest string) { func matchExec(s string) (matches []string, longest []rune) {
var words []string var words []string
paths := strings.Split(envPath, string(filepath.ListSeparator)) paths := strings.Split(envPath, string(filepath.ListSeparator))
@@ -210,7 +257,7 @@ func matchExec(s string) (matches []string, longest string) {
continue continue
} }
files, err := ioutil.ReadDir(p) files, err := os.ReadDir(p)
if err != nil { if err != nil {
log.Printf("reading path: %s", err) log.Printf("reading path: %s", err)
} }
@@ -220,18 +267,18 @@ func matchExec(s string) (matches []string, longest string) {
continue continue
} }
f, err = os.Stat(filepath.Join(p, f.Name())) finfo, err := f.Info()
if err != nil { if err != nil {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
continue continue
} }
if !f.Mode().IsRegular() || !isExecutable(f) { if !finfo.Mode().IsRegular() || !isExecutable(finfo) {
continue continue
} }
log.Print(f.Name()) log.Print(finfo.Name())
words = append(words, f.Name()) words = append(words, finfo.Name())
} }
} }
@@ -250,7 +297,7 @@ func matchExec(s string) (matches []string, longest string) {
return matchWord(s, words) return matchWord(s, words)
} }
func matchFile(s string) (matches []string, longest string) { func matchFile(s string) (matches []string, longest []rune) {
dir := replaceTilde(s) dir := replaceTilde(s)
if !filepath.IsAbs(dir) { if !filepath.IsAbs(dir) {
@@ -262,28 +309,24 @@ func matchFile(s string) (matches []string, longest string) {
} }
} }
dir = unescape(filepath.Dir(dir)) dir = filepath.Dir(unescape(dir))
files, err := ioutil.ReadDir(dir) files, err := os.ReadDir(dir)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} }
for _, f := range files { for _, f := range files {
name := filepath.Join(dir, f.Name()) name := filepath.Join(dir, f.Name())
f, err := os.Stat(name) f, err := os.Lstat(name)
if err != nil { if err != nil {
fl, err := os.Lstat(name)
if err == nil && fl.Mode()&os.ModeSymlink != 0 {
continue
} else {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
return continue
}
} }
name = strings.ToLower(escape(f.Name()))
_, last := filepath.Split(s) _, last := filepath.Split(s)
if !strings.HasPrefix(escape(f.Name()), last) { if !strings.HasPrefix(name, strings.ToLower(last)) {
continue continue
} }
@@ -299,32 +342,25 @@ func matchFile(s string) (matches []string, longest string) {
} }
matches = append(matches, item) matches = append(matches, item)
if longest != "" { if longest == nil {
longest = matchLongest(longest, name)
} else if s != "" {
if f.Mode().IsRegular() { if f.Mode().IsRegular() {
longest = name + " " longest = []rune(name + " ")
} else { } else {
longest = name + escape(string(filepath.Separator)) longest = []rune(name + escape(string(filepath.Separator)))
} }
} else {
longest = matchLongest(longest, []rune(name))
} }
} }
if longest == "" { if len(longest) < len([]rune(s)) {
longest = s longest = []rune(s)
} }
return return
} }
func completeCmd(acc []rune) (matches []string, longestAcc []rune) { func matchCmd(s string) (matches []string, longest []rune) {
s := string(acc)
f := tokenize(s)
var longest string
switch len(f) {
case 1:
words := gCmdWords words := gCmdWords
for c := range gOpts.cmds { for c := range gOpts.cmds {
words = append(words, c) words = append(words, c)
@@ -340,25 +376,45 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
} }
words = words[:j+1] words = words[:j+1]
matches, longest = matchWord(s, words) matches, longest = matchWord(s, words)
longestAcc = []rune(longest) return
}
func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
var longest []rune
switch len(f) {
case 1:
matches, longestAcc = matchCmd(s)
case 2: case 2:
switch f[0] { switch f[0] {
case "set": case "set":
matches, longest = matchWord(f[1], gOptWords) matches, longest = matchWord(f[1], gOptWords)
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
case "map", "cmd": case "map", "cmap", "cmd":
longestAcc = acc longestAcc = acc
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
}
case 3:
switch f[0] {
case "map", "cmap":
matches, longest = matchCmd(f[2])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
default: default:
switch f[0] { switch f[0] {
case "set", "map", "cmd": case "set", "map", "cmap", "cmd":
longestAcc = acc longestAcc = acc
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
} }
@@ -373,33 +429,29 @@ func completeFile(acc []rune) (matches []string, longestAcc []rune) {
log.Printf("getting current directory: %s", err) log.Printf("getting current directory: %s", err)
} }
files, err := ioutil.ReadDir(wd) files, err := os.ReadDir(wd)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} }
var longest string
for _, f := range files { for _, f := range files {
if !strings.HasPrefix(f.Name(), s) { if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(s)) {
continue continue
} }
matches = append(matches, f.Name()) matches = append(matches, f.Name())
if longest != "" { if longestAcc == nil {
longest = matchLongest(longest, f.Name()) longestAcc = []rune(f.Name())
} else if s != "" { } else {
longest = f.Name() longestAcc = matchLongest(longestAcc, []rune(f.Name()))
} }
} }
if longest == "" { if len(longestAcc) < len(acc) {
longest = s longestAcc = acc
} }
longestAcc = []rune(longest)
return return
} }
@@ -407,15 +459,14 @@ func completeShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
var longest string var longest []rune
switch len(f) { switch len(f) {
case 1: case 1:
matches, longest = matchExec(s) matches, longestAcc = matchExec(s)
longestAcc = []rune(longest)
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...)
} }
return return
+4 -3
View File
@@ -18,10 +18,11 @@ func TestMatchLongest(t *testing.T) {
{"foo", "foobar", "foo"}, {"foo", "foobar", "foo"},
{"foo", "barfoo", ""}, {"foo", "barfoo", ""},
{"foobar", "foobaz", "fooba"}, {"foobar", "foobaz", "fooba"},
{"год", "гол", "го"},
} }
for _, test := range tests { for _, test := range tests {
if got := matchLongest(test.s1, test.s2); got != test.exp { if got := string(matchLongest([]rune(test.s1), []rune(test.s2))); got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got) t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got)
} }
} }
@@ -48,8 +49,8 @@ func TestMatchWord(t *testing.T) {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m) t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m)
} }
if l != test.longest { if ls := string(l); ls != test.longest {
t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, l) t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, ls)
} }
} }
} }
+19
View File
@@ -0,0 +1,19 @@
package main
import (
"log"
"golang.org/x/sys/unix"
)
func diskFree(wd string) string {
var stat unix.Statfs_t
if err := unix.Statfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.F_bavail)*uint64(stat.F_bsize)))
}
+21
View File
@@ -0,0 +1,21 @@
//go:build darwin || dragonfly || freebsd || linux
package main
import (
"log"
"golang.org/x/sys/unix"
)
func diskFree(wd string) string {
var stat unix.Statfs_t
if err := unix.Statfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize)))
}
+21
View File
@@ -0,0 +1,21 @@
//go:build illumos || netbsd || solaris
package main
import (
"log"
"golang.org/x/sys/unix"
)
func diskFree(wd string) string {
var stat unix.Statvfs_t
if err := unix.Statvfs(wd, &stat); err != nil {
log.Printf("diskfree: %s", err)
return ""
}
// Available blocks * size per block = available space in bytes
return "df: " + humanize(int64(uint64(stat.Bavail)*uint64(stat.Bsize)))
}
+23
View File
@@ -0,0 +1,23 @@
package main
import (
"log"
"golang.org/x/sys/windows"
)
func diskFree(wd string) string {
var free uint64
pathPtr, err := windows.UTF16PtrFromString(wd)
if err != nil {
log.Printf("diskfree: %s", err)
return ""
}
err = windows.GetDiskFreeSpaceEx(pathPtr, &free, nil, nil) // cwd, free, total, available
if err != nil {
log.Printf("diskfree: %s", err)
return ""
}
return "df: " + humanize(int64(free))
}
+282 -116
View File
@@ -12,7 +12,7 @@ A man page with the same content is also available in the repository at https://
You can run 'lf -help' to see descriptions of command line options. You can run 'lf -help' to see descriptions of command line options.
Quick Reference # Quick Reference
The following commands are provided by lf: The following commands are provided by lf:
@@ -31,8 +31,12 @@ The following commands are provided by lf:
jump-prev (default '[') jump-prev (default '[')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
high (default 'H')
middle (default 'M')
low (default 'L')
toggle toggle
invert (default 'v') invert (default 'v')
invert-below
unselect (default 'u') unselect (default 'u')
glob-select glob-select
glob-unselect glob-unselect
@@ -75,6 +79,9 @@ The following commands are provided by lf:
mark-remove (modal) (default '"') mark-remove (modal) (default '"')
tag tag
tag-toggle (default 't') tag-toggle (default 't')
maps
cmaps
jumps
The following command line commands are provided by lf: The following command line commands are provided by lf:
@@ -82,10 +89,11 @@ The following command line commands are provided by lf:
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-menu-complete cmd-menu-complete
cmd-menu-complete-back cmd-menu-complete-back
cmd-menu-accept
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>' and '<down>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>' and '<up>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
@@ -107,53 +115,62 @@ The following command line commands are provided by lf:
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
anchorfind bool (default on) anchorfind bool (default true)
autoquit bool (default off) autoquit bool (default false)
cleaner string (default '') cleaner string (default '')
dircache bool (default on) cursoractivefmt string (default "\033[7m")
dircounts bool (default off) cursorparentfmt string (default "\033[7m")
dirfirst bool (default on) cursorpreviewfmt string (default "\033[4m")
dironly bool (default off) dircache bool (default true)
drawbox bool (default off) dircounts bool (default false)
errorfmt string (default "\033[7;31;47m%s\033[0m") dirfirst bool (default true)
dironly bool (default false)
dirpreviews bool (default false)
drawbox bool (default false)
errorfmt string (default "\033[7;31;47m")
filesep string (default "\n") filesep string (default "\n")
findlen int (default 1) findlen int (default 1)
globsearch bool (default off) globsearch bool (default false)
hidden bool (default off) hidden bool (default false)
hiddenfiles []string (default '.*') hiddenfiles []string (default '.*')
icons bool (default off) history bool (default true)
icons bool (default false)
ifs string (default '') ifs string (default '')
ignorecase bool (default on) ignorecase bool (default true)
ignoredia bool (default on) ignoredia bool (default true)
incfilter bool (default off) incfilter bool (default false)
incsearch bool (default off) incsearch bool (default false)
info []string (default '') info []string (default '')
infotimefmtnew string (default 'Jan _2 15:04') infotimefmtnew string (default 'Jan _2 15:04')
infotimefmtold string (default 'Jan _2 2006') infotimefmtold string (default 'Jan _2 2006')
mouse bool (default off) mouse bool (default false)
number bool (default off) number bool (default false)
numberfmt string (default "\033[33m")
period int (default 0) period int (default 0)
preview bool (default on) preview bool (default true)
previewer string (default '') previewer string (default '')
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m") promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m")
ratios []int (default '1:2:3') ratios []int (default '1:2:3')
relativenumber bool (default off) relativenumber bool (default false)
reverse bool (default off) reverse bool (default false)
ruler []string (default 'acc:progress:selection:filter:ind')
scrolloff int (default 0) scrolloff int (default 0)
selmode string (default 'all')
shell string (default 'sh' for Unix and 'cmd' for Windows) shell string (default 'sh' for Unix and 'cmd' for Windows)
shellflag string (default '-c' for Unix and '/c' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows)
shellopts []string (default '') shellopts []string (default '')
smartcase bool (default on) smartcase bool (default true)
smartdia bool (default off) smartdia bool (default false)
sortby string (default 'natural') sortby string (default 'natural')
tabstop int (default 8) tabstop int (default 8)
tagfmt string (default "\033[31m%s\033[0m") tagfmt string (default "\033[31m")
tempmarks string (default '') tempmarks string (default '')
timefmt string (default 'Mon Jan _2 15:04:05 2006') timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~') truncatechar string (default '~')
waitmsg string (default 'Press any key to continue') waitmsg string (default 'Press any key to continue')
wrapscan bool (default on) wrapscan bool (default true)
wrapscroll bool (default off) wrapscroll bool (default false)
user_{option} string (default none)
The following environment variables are exported for shell commands: The following environment variables are exported for shell commands:
@@ -165,10 +182,16 @@ The following environment variables are exported for shell commands:
OLDPWD OLDPWD
LF_LEVEL LF_LEVEL
OPENER OPENER
VISUAL
EDITOR EDITOR
PAGER PAGER
SHELL SHELL
lf
lf_{option} lf_{option}
lf_user_{option}
lf_width
lf_height
lf_count
The following special shell commands are used to customize the behavior of lf when defined: The following special shell commands are used to customize the behavior of lf when defined:
@@ -178,6 +201,7 @@ The following special shell commands are used to customize the behavior of lf wh
delete delete
pre-cd pre-cd
on-cd on-cd
on-select
on-quit on-quit
The following commands/keybindings are provided by default: The following commands/keybindings are provided by default:
@@ -205,7 +229,18 @@ The following additional keybindings are provided by default:
map gh cd ~ map gh cd ~
map <space> :toggle; down map <space> :toggle; down
Configuration If the 'mouse' option is enabled, mouse buttons have the following default effects:
Left mouse button
Click on a file or directory to select it.
Right mouse button
Enter a directory or open a file. Also works on the preview window.
Scroll wheel
Move up or down. If Ctrl is pressed, scroll up or down.
# Configuration
Configuration files should be located at: Configuration files should be located at:
@@ -255,7 +290,7 @@ You can configure the default values of following variables to change these loca
A sample configuration file can be found at A sample configuration file can be found at
https://github.com/gokcehan/lf/blob/master/etc/lfrc.example https://github.com/gokcehan/lf/blob/master/etc/lfrc.example
Commands # Commands
This section shows information about builtin commands. This section shows information about builtin commands.
Modal commands do not take any arguments, but instead change the operation mode to read their input conveniently, and so they are meant to be assigned to keybindings. Modal commands do not take any arguments, but instead change the operation mode to read their input conveniently, and so they are meant to be assigned to keybindings.
@@ -294,6 +329,13 @@ Change the current working directory to the next/previous jumplist item.
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
Move the current file selection to the top/bottom of the directory. Move the current file selection to the top/bottom of the directory.
A count can be specified to move to a specific line, for example use `3G` to move to the third line.
high (default 'H')
middle (default 'M')
low (default 'L')
Move the current file selection to the high/middle/low of the screen.
toggle toggle
@@ -305,6 +347,17 @@ Reverse the selection of all files in the current directory (i.e. 'toggle' all f
Selections in other directories are not effected by this command. Selections in other directories are not effected by this command.
You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories.
invert-below
Reverse the selection (i.e. 'toggle') of all files at or after the current file in the current directory.
To select a contiguous block of files, use this command on the first file you want to select.
Then, move down to the first file you do *not* want to select (the one after the end of the desired selection) and use this command again.
This achieves an effect similar to the visual mode in vim.
This command is experimental and may be removed once a better replacement for the visual mode is implemented in 'lf'.
If you'd like to experiment with using this command, you should bind it to a key (e.g. 'V') for a better experience.
unselect (default 'u') unselect (default 'u')
Remove the selection of all files in all directories. Remove the selection of all files in all directories.
@@ -318,6 +371,7 @@ Select/unselect files that match the given glob.
Calculate the total size for each of the selected directories. Calculate the total size for each of the selected directories.
Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size. Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size.
If the total size of a directory is not calculated, it will be shown as '-'.
copy (default 'y') copy (default 'y')
@@ -460,10 +514,15 @@ You can define a new tag clearing command by combining 'tag' with 'tag-toggle' (
Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag. Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag.
Command Line Commands # Command Line Commands
This section shows information about command line commands. The prompt character specifies which of the several command-line modes you are in.
These should be mostly compatible with readline keybindings. For example, the 'read' command takes you to the ':' mode.
When the cursor is at the first character in ':' mode, pressing one of the keys '!', '$', '%', or '&' takes you to the corresponding mode.
You can go back with 'cmd-delete-back' ('<backspace>' by default).
The command line commands should be mostly compatible with readline keybindings.
A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters. A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters.
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
@@ -481,6 +540,10 @@ Autocomplete the current word with menu selection.
You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back'). You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back').
You can use the assigned keys assigned to display the menu and then cycle through completion options. You can use the assigned keys assigned to display the menu and then cycle through completion options.
cmd-menu-accept
Accept the currently selected match in menu completion and close the menu.
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
Execute the current line. Execute the current line.
@@ -489,8 +552,8 @@ Execute the current line.
Interrupt the current shell-pipe command and return to the normal mode. Interrupt the current shell-pipe command and return to the normal mode.
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>' and '<down>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>' and '<up>')
Go to next/previous item in the history. Go to next/previous item in the history.
@@ -505,9 +568,13 @@ Move the cursor to the left/right.
Move the cursor to the beginning/end of line. Move the cursor to the beginning/end of line.
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
Delete the next character.
cmd-delete-back (default '<backspace>' and '<backspace2>') cmd-delete-back (default '<backspace>' and '<backspace2>')
Delete the next character in forward/backward direction. Delete the previous character.
When at the beginning of a prompt, returns either to normal mode or to ':' mode.
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
@@ -542,16 +609,27 @@ Delete the next word in forward direction.
Capitalize/uppercase/lowercase the current word and jump to the next word. Capitalize/uppercase/lowercase the current word and jump to the next word.
Options maps
cmaps
List all key mappings in normal mode or command-line editing mode.
jumps
List the contents of the jump list, in order of the most recently visited locations.
Each location is marked with the count that can be used with the `jump-prev` and `jump-next` commands (e.g. use `3[` to move three spaces backwards in the jump list).
A '>' is used to mark the current location in the jump list.
# Options
This section shows information about options to customize the behavior. This section shows information about options to customize the behavior.
Character ':' is used as the separator for list options '[]int' and '[]string'. Character ':' is used as the separator for list options '[]int' and '[]string'.
anchorfind bool (default on) anchorfind bool (default true)
When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position. When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position.
autoquit bool (default off) autoquit bool (default false)
Automatically quit server when there are no clients left connected. Automatically quit server when there are no clients left connected.
@@ -560,38 +638,60 @@ Automatically quit server when there are no clients left connected.
Set the path of a cleaner file. Set the path of a cleaner file.
The file should be executable. The file should be executable.
This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled. This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled.
One argument is passed to the file, path to the file whose preview should be cleaned. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively.
Preview clearing is disabled when the value of this option is left empty. Preview clearing is disabled when the value of this option is left empty.
dircache bool (default on) cursoractivefmt string (default "\033[7m")
cursorparentfmt string (default "\033[7m")
cursorpreviewfmt string (default "\033[4m")
Format strings for highlighting the cursor.
`cursoractivefmt` applies in the current directory pane,
`cursorparentfmt` applies in panes that show parents of the current directory,
and `cursorpreviewfmt` applies in panes that preview directories.
The default is to make the active cursor and the parent directory cursor inverted. The preview cursor is underlined.
Some other possibilities to consider for the preview or parent cursors: an empty string for no cursor, "\033[7;2m" for dimmed inverted text (visibility varies by terminal), "\033[7;90m" for inverted text with grey (aka "brightblack") background.
If the format string contains the characters `%s`, it is interpreted as a format string for `fmt.Sprintf`. Such a string should end with the terminal reset sequence.
For example, "\033[4m%s\033[0m" has the same effect as "\033[4m".
dircache bool (default true)
Cache directory contents. Cache directory contents.
dircounts bool (default off) dircounts bool (default false)
When this option is enabled, directory sizes show the number of items inside instead of the size of directory file. When this option is enabled, directory sizes show the number of items inside instead of the total size of the directory, which needs to be calculated for each directory using 'calcdirsize'.
The former needs to be calculated by reading the directory and counting the items inside. This information needs to be calculated by reading the directory and counting the items inside.
The latter is directly provided by the operating system and it does not require any calculation, though it is non-intuitive and it can often be misleading. Therefore, this option is disabled by default for performance reasons.
This option is disabled by default for performance reasons.
This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information. This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information.
A thousand items are counted per directory at most, and bigger directories are shown as '999+'. 999 items are counted per directory at most, and bigger directories are shown as '999+'.
dirfirst bool (default on) dirfirst bool (default true)
Show directories first above regular files. Show directories first above regular files.
dironly bool (default off) dironly bool (default false)
Show only directories. Show only directories.
drawbox bool (default off) dirpreviews bool (default false)
If enabled, directories will also be passed to the previewer script. This allows custom previews for directories.
drawbox bool (default false)
Draw boxes around panes with box drawing characters. Draw boxes around panes with box drawing characters.
errorfmt string (default "\033[7;31;47m%s\033[0m") errorfmt string (default "\033[7;31;47m")
Format string of error messages shown in the bottom message line. Format string of error messages shown in the bottom message line.
If the format string contains the characters `%s`, it is interpreted as a format string for `fmt.Sprintf`. Such a string should end with the terminal reset sequence.
For example, "\033[4m%s\033[0m" has the same effect as "\033[4m".
filesep string (default "\n") filesep string (default "\n")
File separator used in environment variables 'fs' and 'fx'. File separator used in environment variables 'fs' and 'fx'.
@@ -601,13 +701,13 @@ File separator used in environment variables 'fs' and 'fx'.
Number of characters prompted for the find command. Number of characters prompted for the find command.
When this value is set to 0, find command prompts until there is only a single match left. When this value is set to 0, find command prompts until there is only a single match left.
globsearch bool (default off) globsearch bool (default false)
When this option is enabled, search command patterns are considered as globs, otherwise they are literals. When this option is enabled, search command patterns are considered as globs, otherwise they are literals.
With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...]' matches character sets or ranges.
Otherwise, these characters are interpreted as they are. Otherwise, these characters are interpreted as they are.
hidden bool (default off) hidden bool (default false)
Show hidden files. Show hidden files.
On Unix systems, hidden files are determined by the value of 'hiddenfiles'. On Unix systems, hidden files are determined by the value of 'hiddenfiles'.
@@ -617,10 +717,14 @@ On Windows, only files with hidden attributes are considered hidden files.
List of hidden file glob patterns. List of hidden file glob patterns.
Patterns can be given as relative or absolute paths. Patterns can be given as relative or absolute paths.
Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...]' to match character sets or ranges.
In addition, if a pattern starts with '!', then its matches are excluded from hidden files. In addition, if a pattern starts with '!', then its matches are excluded from hidden files. To add multiple patterns, use ':' as a separator. Example: '.*:lost+found:*.bak'
icons bool (default off) history bool (default true)
Save command history.
icons bool (default false)
Show icons before each item in the list. Show icons before each item in the list.
@@ -633,19 +737,19 @@ This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells
This option has no effect when the value is left empty. This option has no effect when the value is left empty.
This option does not have any effect on Windows. This option does not have any effect on Windows.
ignorecase bool (default on) ignorecase bool (default true)
Ignore case in sorting and search patterns. Ignore case in sorting and search patterns.
ignoredia bool (default on) ignoredia bool (default true)
Ignore diacritics in sorting and search patterns. Ignore diacritics in sorting and search patterns.
incsearch bool (default off) incsearch bool (default false)
Jump to the first match after each keystroke during searching. Jump to the first match after each keystroke during searching.
incfilter bool (default off) incfilter bool (default false)
Apply filter pattern after each keystroke during filtering. Apply filter pattern after each keystroke during filtering.
@@ -663,15 +767,19 @@ Format string of the file time shown in the info column when it matches this yea
Format string of the file time shown in the info column when it doesn't match this year. Format string of the file time shown in the info column when it doesn't match this year.
mouse bool (default off) mouse bool (default false)
Send mouse events as input. Send mouse events as input.
number bool (default off) number bool (default false)
Show the position number for directory items at the left side of pane. Show the position number for directory items at the left side of pane.
When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest. When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest.
numberfmt string (default "\033[33m")
Format string of the position number for each line.
period int (default 0) period int (default 0)
Set the interval in seconds for periodic checks of directory updates. Set the interval in seconds for periodic checks of directory updates.
@@ -680,7 +788,7 @@ Note that directories are already updated automatically in many cases.
This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf.
Periodic checks are disabled when the value of this option is set to zero. Periodic checks are disabled when the value of this option is set to zero.
preview bool (default on) preview bool (default true)
Show previews of files and directories at the right most pane. Show previews of files and directories at the right most pane.
If the file has more lines than the preview pane, rest of the lines are not read. If the file has more lines than the preview pane, rest of the lines are not read.
@@ -699,7 +807,7 @@ Preview filtering is disabled and files are displayed as they are when the value
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m") promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m")
Format string of the prompt shown in the top line. Format string of the prompt shown in the top line.
Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. '%S' may be used once and will provide a spacer so that the following parts are right aligned on the screen.
Home folder is shown as '~' in the working directory expansion. Home folder is shown as '~' in the working directory expansion.
Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen. Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen.
@@ -709,15 +817,32 @@ List of ratios of pane widths.
Number of items in the list determines the number of panes in the ui. Number of items in the list determines the number of panes in the ui.
When 'preview' option is enabled, the right most number is used for the width of preview pane. When 'preview' option is enabled, the right most number is used for the width of preview pane.
relativenumber bool (default off) relativenumber bool (default false)
Show the position number relative to the current line. Show the position number relative to the current line.
When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown.
reverse bool (default off) reverse bool (default false)
Reverse the direction of sort. Reverse the direction of sort.
ruler []string (default 'acc:progress:selection:filter:ind')
List of information shown in status line ruler.
Currently supported information types are 'acc', 'progress', 'selection', 'ind' and 'df'.
`acc` shows the pressed keys (e.g. for bindings with multiple key presses or counts given to bindings).
`progress` shows the progress of file operations (e.g. copying a large directory).
`selection` shows the number of files that are selected, or designated for being cut/copied.
`filter` shows 'F' if a filter is currently being applied.
`ind` shows the current position of the cursor as well as the number of files in the current directory.
`df` shows the amount of free disk space remaining.
selmode string (default 'all')
Selection mode for commands.
When set to 'all' it will use the selected files from all directories.
When set to 'dir' it will only use the selected files in the current directory.
scrolloff int (default 0) scrolloff int (default 0)
Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling. Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling.
@@ -737,12 +862,12 @@ Command line flag used to pass shell commands.
List of shell options to pass to the shell executable. List of shell options to pass to the shell executable.
smartcase bool (default on) smartcase bool (default true)
Override 'ignorecase' option when the pattern contains an uppercase character. Override 'ignorecase' option when the pattern contains an uppercase character.
This option has no effect when 'ignorecase' is disabled. This option has no effect when 'ignorecase' is disabled.
smartdia bool (default off) smartdia bool (default false)
Override 'ignoredia' option when the pattern contains a character with diacritic. Override 'ignoredia' option when the pattern contains a character with diacritic.
This option has no effect when 'ignoredia' is disabled. This option has no effect when 'ignoredia' is disabled.
@@ -756,10 +881,13 @@ Currently supported sort types are 'natural', 'name', 'size', 'time', 'ctime', '
Number of space characters to show for horizontal tabulation (U+0009) character. Number of space characters to show for horizontal tabulation (U+0009) character.
tagfmt string (default "\033[31m%s\033[0m") tagfmt string (default "\033[31m")
Format string of the tags. Format string of the tags.
If the format string contains the characters `%s`, it is interpreted as a format string for `fmt.Sprintf`. Such a string should end with the terminal reset sequence.
For example, "\033[4m%s\033[0m" has the same effect as "\033[4m".
tempmarks string (default '') tempmarks string (default '')
Marks to be considered temporary (e.g. 'abc' refers to marks 'a', 'b', and 'c'). Marks to be considered temporary (e.g. 'abc' refers to marks 'a', 'b', and 'c').
@@ -778,15 +906,21 @@ Truncate character shown at the end when the file name does not fit to the pane.
String shown after commands of shell-wait type. String shown after commands of shell-wait type.
wrapscan bool (default on) wrapscan bool (default true)
Searching can wrap around the file list. Searching can wrap around the file list.
wrapscroll bool (default off) wrapscroll bool (default false)
Scrolling can wrap around the file list. Scrolling can wrap around the file list.
Environment Variables user_{option} string (default none)
Any option that is prefixed with 'user_' is a user defined option and can be set to any string.
Inside a user defined command the value will be provided in the `lf_user_{option}` environment variable.
These options are not used by lf and are not persisted.
# Environment Variables
The following variables are exported for shell commands: The following variables are exported for shell commands:
These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f'). These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f').
@@ -823,25 +957,44 @@ For example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] && PS1="$PS1""(l
OPENER OPENER
If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others. If this variable is set in the environment, use the same value. Otherwise, this is set to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others.
EDITOR EDITOR
If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on Unix, 'notepad' in Windows. If VISUAL is set in the environment, use its value. Otherwise, use the value of the environment variable EDITOR. If neither variable is set, this is set to 'vi' on Unix, 'notepad' in Windows.
PAGER PAGER
If this variable is set in the environment, use the same value, otherwise set the value to 'less' on Unix, 'more' in Windows. If this variable is set in the environment, use the same value. Otherwise, this is set to 'less' on Unix, 'more' in Windows.
SHELL SHELL
If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on Unix, 'cmd' in Windows. If this variable is set in the environment, use the same value. Otherwise, this is set to 'sh' on Unix, 'cmd' in Windows.
lf
Absolute path to the currently running lf binary, if it can be found. Otherwise, this is set to the string 'lf'.
lf_{option} lf_{option}
Value of the {option}. Value of the {option}.
Special Commands lf_user_{option}
Value of the user_{option}.
lf_width
lf_height
Width/Height of the terminal.
lf_count
Value of the count associated with the current command.
# Special Commands
This section shows information about special shell commands.
open open
@@ -853,7 +1006,7 @@ This shell command can be defined to override the default 'paste' command.
rename rename
This shell command can be defined to override the default 'paste' command. This shell command can be defined to override the default 'rename' command.
delete delete
@@ -867,11 +1020,15 @@ This shell command can be defined to be executed before changing a directory.
This shell command can be defined to be executed after changing a directory. This shell command can be defined to be executed after changing a directory.
on-select
This shell command can be defined to be executed after the selection changes.
on-quit on-quit
This shell command can be defined to be executed before quit. This shell command can be defined to be executed before quit.
Prefixes # Prefixes
The following command prefixes are used by lf: The following command prefixes are used by lf:
@@ -886,18 +1043,20 @@ The difference is that prefixes are not necessary in the command line.
Instead, different modes are provided to read corresponding commands. Instead, different modes are provided to read corresponding commands.
These modes are mapped to the prefix keys above by default. These modes are mapped to the prefix keys above by default.
Syntax # Syntax
Characters from '#' to newline are comments and ignored: Characters from '#' to newline are comments and ignored:
# comments start with '#' # comments start with '#'
There are three special commands ('set', 'map', 'cmap', and 'cmd') for configuration. There are four special commands ('set', 'map', 'cmap', and 'cmd') for configuration.
Command 'set' is used to set an option which can be boolean, integer, or string: Command 'set' is used to set an option which can be boolean, integer, or string:
set hidden # boolean on set hidden # boolean enable
set nohidden # boolean off set hidden true # boolean enable
set nohidden # boolean disable
set hidden false # boolean disable
set hidden! # boolean toggle set hidden! # boolean toggle
set scrolloff 10 # integer value set scrolloff 10 # integer value
set sortby time # string value w/o quotes set sortby time # string value w/o quotes
@@ -911,9 +1070,10 @@ Command 'map' is used to bind a key to a command which can be builtin command, c
map i $less $f # shell command map i $less $f # shell command
map U !du -csh * # waiting shell command map U !du -csh * # waiting shell command
Command 'cmap' is used to bind a key to a command line command which can only be one of the builtin commands: Command 'cmap' is used to bind a key on the command line to a command line command or any other command:
cmap <c-g> cmd-escape cmap <c-g> cmd-escape
cmap <a-i> set incsearch!
You can delete an existing binding by leaving the expression empty: You can delete an existing binding by leaving the expression empty:
@@ -943,7 +1103,7 @@ If you need multiline you can wrap statements in '{{' and '}}' after the proper
set info time set info time
}} }}
Key Mappings # Key Mappings
Regular keys are assigned to a command with the usual syntax: Regular keys are assigned to a command with the usual syntax:
@@ -1003,7 +1163,7 @@ Mouse wheel events are also prefixed with 'm' character:
map <m-left> down map <m-left> down
map <m-right> down map <m-right> down
Push Mappings # Push Mappings
The usual way to map a key sequence is to assign it to a named or unnamed command. The usual way to map a key sequence is to assign it to a named or unnamed command.
While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times. While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times.
@@ -1026,7 +1186,7 @@ One thing to be careful is that since 'push' command works with keys instead of
These types of bindings create a deadlock when executed. These types of bindings create a deadlock when executed.
Shell Commands # Shell Commands
Regular shell commands are the most basic command type that is useful for many purposes. Regular shell commands are the most basic command type that is useful for many purposes.
For example, we can write a shell command to move selected file(s) to trash. For example, we can write a shell command to move selected file(s) to trash.
@@ -1037,7 +1197,7 @@ A first attempt to write such a command may look like this:
if [ -z "$fs" ]; then if [ -z "$fs" ]; then
mv "$f" ~/.trash mv "$f" ~/.trash
else else
IFS="`printf '\n\t'`"; mv $fs ~/.trash IFS="$(printf '\n\t')"; mv $fs ~/.trash
fi fi
}} }}
@@ -1048,7 +1208,7 @@ We can use this variable to get rid of the conditional:
cmd trash ${{ cmd trash ${{
mkdir -p ~/.trash mkdir -p ~/.trash
IFS="`printf '\n\t'`"; mv $fx ~/.trash IFS="$(printf '\n\t')"; mv $fx ~/.trash
}} }}
The trash directory is checked each time the command is executed. The trash directory is checked each time the command is executed.
@@ -1056,13 +1216,13 @@ We can move it outside of the command so it would only run once at startup:
${{ mkdir -p ~/.trash }} ${{ mkdir -p ~/.trash }}
cmd trash ${{ IFS="`printf '\n\t'`"; mv $fx ~/.trash }} cmd trash ${{ IFS="$(printf '\n\t')"; mv $fx ~/.trash }}
Since these are one liners, we can drop '{{' and '}}': Since these are one liners, we can drop '{{' and '}}':
$mkdir -p ~/.trash $mkdir -p ~/.trash
cmd trash $IFS="`printf '\n\t'`"; mv $fx ~/.trash cmd trash $IFS="$(printf '\n\t')"; mv $fx ~/.trash
Finally note that we set 'IFS' variable manually in these commands. Finally note that we set 'IFS' variable manually in these commands.
Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\n"'). Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\n"').
@@ -1070,7 +1230,7 @@ This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' wo
This option is not set by default as it can behave unexpectedly for new users. This option is not set by default as it can behave unexpectedly for new users.
However, use of this option is highly recommended and it is assumed in the rest of the documentation. However, use of this option is highly recommended and it is assumed in the rest of the documentation.
Piping Shell Commands # Piping Shell Commands
Regular shell commands have some limitations in some cases. Regular shell commands have some limitations in some cases.
When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again. When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again.
@@ -1091,18 +1251,18 @@ For example, an alternative rename command may look like this:
Note that input is line buffered and output and error are byte buffered. Note that input is line buffered and output and error are byte buffered.
Waiting Shell Commands # Waiting Shell Commands
Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished. Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished.
These can be useful to see the output of a program before the ui is resumed. These can be useful to see the output of a program before the ui is resumed.
Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline. Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline.
Asynchronous Shell Commands # Asynchronous Shell Commands
Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish. Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish.
Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui. Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui.
Remote Commands # Remote Commands
One of the more advanced features in lf is remote commands. One of the more advanced features in lf is remote commands.
All clients connect to a server on startup. All clients connect to a server on startup.
@@ -1138,10 +1298,9 @@ Since lf does not have control flow syntax, remote commands are used for such ne
For example, you can configure the number of columns in the ui with respect to the terminal width as follows: For example, you can configure the number of columns in the ui with respect to the terminal width as follows:
cmd recol %{{ cmd recol %{{
w=$(tput cols) if [ $lf_width -le 80 ]; then
if [ $w -le 80 ]; then
lf -remote "send $id set ratios 1:2" lf -remote "send $id set ratios 1:2"
elif [ $w -le 160 ]; then elif [ $lf_width -le 160 ]; then
lf -remote "send $id set ratios 1:2:3" lf -remote "send $id set ratios 1:2:3"
else else
lf -remote "send $id set ratios 1:2:3:5" lf -remote "send $id set ratios 1:2:3:5"
@@ -1156,7 +1315,7 @@ Besides 'send' command, there is a 'quit' command to quit the server when there
Lastly, there is a 'conn' command to connect the server as a client. Lastly, there is a 'conn' command to connect the server as a client.
This should not be needed for users. This should not be needed for users.
File Operations # File Operations
lf uses its own builtin copy and move operations by default. lf uses its own builtin copy and move operations by default.
These are implemented as asynchronous operations and progress is shown in the bottom ruler. These are implemented as asynchronous operations and progress is shown in the bottom ruler.
@@ -1197,7 +1356,7 @@ You can customize file deletion by defining a 'delete' command.
You can also assign a key to this command if you like. You can also assign a key to this command if you like.
An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file.
Searching Files # Searching Files
There are two mechanisms implemented in lf to search a file in the current directory. There are two mechanisms implemented in lf to search a file in the current directory.
Searching is the traditional method to move the selection to a file matching a given pattern. Searching is the traditional method to move the selection to a file matching a given pattern.
@@ -1208,14 +1367,10 @@ You can enable 'globsearch' option to match with a glob pattern.
Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges.
You can enable 'incsearch' option to jump to the current match at each keystroke while typing. You can enable 'incsearch' option to jump to the current match at each keystroke while typing.
In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search.
Alternatively, you can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. You can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards.
Possible candidates are 'up', 'down' and their variants, 'top', 'bottom', 'updir', and 'open' commands. For example, you can use the right arrow key to finish the search and open the selected file with the following mapping:
For example, you can use arrow keys to finish the search with the following mappings:
cmap <up> up cmap <right> :cmd-enter; open
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ',').
You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning.
@@ -1230,7 +1385,7 @@ This option is already automatically overridden if the pattern contains upper ca
You can disable 'smartcase' option to disable this behavior. You can disable 'smartcase' option to disable this behavior.
Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters.
Opening Files # Opening Files
You can define a an 'open' command (default 'l' and '<right>') to configure file opening. You can define a an 'open' command (default 'l' and '<right>') to configure file opening.
This command is only called when the current file is not a directory, otherwise the directory is entered instead. This command is only called when the current file is not a directory, otherwise the directory is entered instead.
@@ -1245,8 +1400,7 @@ It is possible to use different command types:
You may want to use either file extensions or mime types from 'file' command: You may want to use either file extensions or mime types from 'file' command:
cmd open ${{ cmd open ${{
test -L $f && f=$(readlink -f $f) case $(file --mime-type -Lb $f) in
case $(file --mime-type $f -b) in
text/*) vi $fx;; text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac esac
@@ -1254,6 +1408,18 @@ You may want to use either file extensions or mime types from 'file' command:
You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits. You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits.
Regular shell commands (i.e. '$') drop to terminal which results in a flicker for commands that finishes immediately (e.g. 'xdg-open' in the above example).
If you want to use asynchronous shell commands (i.e. '&') but also want to use the terminal when necessary (e.g. 'vi' in the above exxample), you can use a remote command:
cmd open &{{
case $(file --mime-type -Lb $f) in
text/*) lf -remote "send $id \$vi \$fx";;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac
}}
Note, asynchronous shell commands run in their own process group by default so they do not require the manual use of 'setsid'.
Following command is provided by default: Following command is provided by default:
cmd open &$OPENER $f cmd open &$OPENER $f
@@ -1261,11 +1427,11 @@ Following command is provided by default:
You may also use any other existing file openers as you like. You may also use any other existing file openers as you like.
Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few.
Previewing Files # Previewing Files
lf previews files on the preview pane by printing the file until the end or the preview pane is filled. lf previews files on the preview pane by printing the file until the end or the preview pane is filled.
This output can be enhanced by providing a custom preview script for filtering. This output can be enhanced by providing a custom preview script for filtering.
This can be used to highlight source codes, list contents of archive files or view pdf or image files to name few. This can be used to highlight source codes, list contents of archive files or view pdf or image files to name a few.
For coloring lf recognizes ansi escape codes. For coloring lf recognizes ansi escape codes.
In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. In order to use this feature you need to set the value of 'previewer' option to the path of an executable file.
@@ -1312,7 +1478,7 @@ Your system may already come with a preview filter named 'lesspipe'.
These filters may have a mechanism to add user customizations as well. These filters may have a mechanism to add user customizations as well.
See the related documentations for more information. See the related documentations for more information.
Changing Directory # Changing Directory
lf changes the working directory of the process to the current directory so that shell commands always work in the displayed directory. lf changes the working directory of the process to the current directory so that shell commands always work in the displayed directory.
After quitting, it returns to the original directory where it is first launched like all shell programs. After quitting, it returns to the original directory where it is first launched like all shell programs.
@@ -1351,7 +1517,7 @@ Note that all shell commands are possible but '%' and '&' are usually more appro
There is also a 'pre-cd' command, that works like 'on-cd', but is run before the directory is actually changed. There is also a 'pre-cd' command, that works like 'on-cd', but is run before the directory is actually changed.
Colors # Colors
lf tries to automatically adapt its colors to the environment. lf tries to automatically adapt its colors to the environment.
It starts with a default colorscheme and updates colors using values of existing environment variables possibly by overwriting its previous values. It starts with a default colorscheme and updates colors using values of existing environment variables possibly by overwriting its previous values.
@@ -1474,7 +1640,7 @@ https://github.com/gokcehan/lf/blob/master/etc/colors.example
You may also see the wiki page for ansi escape codes You may also see the wiki page for ansi escape codes
https://en.wikipedia.org/wiki/ANSI_escape_code https://en.wikipedia.org/wiki/ANSI_escape_code
Icons # Icons
Icons are configured using 'LF_ICONS' environment variable or an icons file. Icons are configured using 'LF_ICONS' environment variable or an icons file.
The variable uses the same syntax as 'LS_COLORS/LF_COLORS'. The variable uses the same syntax as 'LS_COLORS/LF_COLORS'.
+663 -519
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -148,7 +148,7 @@ fi  # FILE
*.tsx  *.tsx 
*.jl  *.jl 
*.pp  *.pp 
*.vue ﵂ *.vue
*.elm  *.elm 
*.swift  *.swift 
*.xcplayground  *.xcplayground 
+3 -2
View File
@@ -5,7 +5,7 @@
# mkdir -p ~/.config/fish/functions # mkdir -p ~/.config/fish/functions
# ln -s "/path/to/lfcd.fish" ~/.config/fish/functions # ln -s "/path/to/lfcd.fish" ~/.config/fish/functions
# #
# You may also like to assign a key to this command: # You may also like to assign a key (Ctrl-O) to this command:
# #
# bind \co 'set old_tty (stty -g); stty sane; lfcd; stty $old_tty; commandline -f repaint' # bind \co 'set old_tty (stty -g); stty sane; lfcd; stty $old_tty; commandline -f repaint'
# #
@@ -13,7 +13,8 @@
function lfcd function lfcd
set tmp (mktemp) set tmp (mktemp)
lf -last-dir-path=$tmp $argv # `command` is needed in case `lfcd` is aliased to `lf`
command lf -last-dir-path=$tmp $argv
if test -f "$tmp" if test -f "$tmp"
set dir (cat $tmp) set dir (cat $tmp)
rm -f $tmp rm -f $tmp
+3 -2
View File
@@ -8,7 +8,7 @@
# source "$LFCD" # source "$LFCD"
# fi # fi
# #
# You may also like to assign a key to this command: # You may also like to assign a key (Ctrl-O) to this command:
# #
# bind '"\C-o":"lfcd\C-m"' # bash # bind '"\C-o":"lfcd\C-m"' # bash
# bindkey -s '^o' 'lfcd\n' # zsh # bindkey -s '^o' 'lfcd\n' # zsh
@@ -16,7 +16,8 @@
lfcd () { lfcd () {
tmp="$(mktemp)" tmp="$(mktemp)"
lf -last-dir-path="$tmp" "$@" # `command` is needed in case `lfcd` is aliased to `lf`
command lf -last-dir-path="$tmp" "$@"
if [ -f "$tmp" ]; then if [ -f "$tmp" ]; then
dir="$(cat "$tmp")" dir="$(cat "$tmp")"
rm -f "$tmp" rm -f "$tmp"
+14 -6
View File
@@ -20,9 +20,15 @@ set ifs "\n"
# leave some space at the top and the bottom of the screen # leave some space at the top and the bottom of the screen
set scrolloff 10 set scrolloff 10
# Use the `dim` attribute instead of underline for the cursor in the preview pane
set cursorpreviewfmt "\033[7;2m"
# use enter for shell commands # use enter for shell commands
map <enter> shell map <enter> shell
# show the result of execution of previous commands
map ` !true
# execute current file (must be executable) # execute current file (must be executable)
map x $$f map x $$f
map X !$f map X !$f
@@ -35,14 +41,16 @@ map O $mimeopen --ask $f
# This command is called when current file is not a directory. You may want to # This command is called when current file is not a directory. You may want to
# use either file extensions and/or mime types here. Below uses an editor for # use either file extensions and/or mime types here. Below uses an editor for
# text files and a file opener for the rest. # text files and a file opener for the rest.
cmd open ${{ cmd open &{{
test -L $f && f=$(readlink -f $f) case $(file --mime-type -Lb $f) in
case $(file --mime-type $f -b) in text/*) lf -remote "send $id \$$EDITOR \$fx";;
text/*) $EDITOR $fx;; *) for f in $fx; do $OPENER $f > /dev/null 2> /dev/null & done;;
*) for f in $fx; do setsid $OPENER $f > /dev/null 2> /dev/null & done;;
esac esac
}} }}
# mkdir command. See wiki if you want it to select created dir
map a :push %mkdir<space>
# define a custom 'rename' command without prompt for overwrite # define a custom 'rename' command without prompt for overwrite
# cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 # cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
# map r push :rename<space> # map r push :rename<space>
@@ -60,7 +68,7 @@ cmd trash %set -f; mv $fx ~/.trash
# printf "$fx\n" # printf "$fx\n"
# printf "delete?[y/n]" # printf "delete?[y/n]"
# read ans # read ans
# [ $ans = "y" ] && rm -rf $fx # [ "$ans" = "y" ] && rm -rf $fx
# }} # }}
# use '<delete>' key for either 'trash' or 'delete' command # use '<delete>' key for either 'trash' or 'delete' command
+880 -426
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -58,7 +58,8 @@ BEGIN {
} }
# heading # heading
/^[^[:punct:]]*$/ { /^# *[^[:punct:]]*$/ {
gsub(/# */, "", $0)
print ".SH", toupper($0) print ".SH", toupper($0)
start = 1 start = 1
next next
+13 -6
View File
@@ -1,11 +1,18 @@
module github.com/gokcehan/lf module github.com/gokcehan/lf
go 1.12 go 1.18
require ( require (
github.com/gdamore/tcell/v2 v2.3.1 github.com/djherbis/times v1.5.0
github.com/mattn/go-runewidth v0.0.10 github.com/gdamore/tcell/v2 v2.6.0
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 github.com/mattn/go-runewidth v0.0.14
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d golang.org/x/sys v0.8.0
gopkg.in/djherbis/times.v1 v1.2.0 golang.org/x/term v0.8.0
)
require (
github.com/gdamore/encoding v1.0.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
golang.org/x/text v0.7.0 // indirect
) )
+40 -16
View File
@@ -1,20 +1,44 @@
github.com/djherbis/times v1.5.0 h1:79myA211VwPhFTqUk8xehWrsEO+zcIZj0zT8mXPVARU=
github.com/djherbis/times v1.5.0/go.mod h1:5q7FDLvbNg1L/KaBmPcWlVR9NmoKo3+ucqUA3ijQhA0=
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= github.com/gdamore/encoding v1.0.0 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.3.1 h1:htEXmKMzurgcnNH3VqQA7GYlCpdl9LCSNpzFpZOKhJE= github.com/gdamore/tcell/v2 v2.6.0 h1:OKbluoP9VYmJwZwq/iLb4BxwKcwGthaa1YNBJIyCySg=
github.com/gdamore/tcell/v2 v2.3.1/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU= github.com/gdamore/tcell/v2 v2.6.0/go.mod h1:be9omFATkdr0D9qewWW3d+MEvl5dha+Etb5y65J2H8Y=
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.0.3/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.10 h1:CoZ3S2P7pvtP45xOtBw+/mDL2z0RKI576gSkzRRpdGg= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=
github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/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/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-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.8.0 h1:n5xxQn2i3PC0yLAbjTpNT85q/Kgzcr2gIoX9OrJUols=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
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=
gopkg.in/djherbis/times.v1 v1.2.0 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8= 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/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+1 -1
View File
@@ -156,7 +156,7 @@ func (im iconMap) get(f *file) string {
return val return val
} }
if val, ok := im["*"+f.ext]; ok { if val, ok := im["*"+strings.ToLower(f.ext)]; ok {
return val return val
} }
+272 -87
View File
@@ -46,8 +46,12 @@ The following commands are provided by lf:
jump-prev (default '[') jump-prev (default '[')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
high (default 'H')
middle (default 'M')
low (default 'L')
toggle toggle
invert (default 'v') invert (default 'v')
invert-below
unselect (default 'u') unselect (default 'u')
glob-select glob-select
glob-unselect glob-unselect
@@ -90,6 +94,9 @@ The following commands are provided by lf:
mark-remove (modal) (default '"') mark-remove (modal) (default '"')
tag tag
tag-toggle (default 't') tag-toggle (default 't')
maps
cmaps
jumps
.EE .EE
.PP .PP
The following command line commands are provided by lf: The following command line commands are provided by lf:
@@ -99,10 +106,11 @@ The following command line commands are provided by lf:
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-menu-complete cmd-menu-complete
cmd-menu-complete-back cmd-menu-complete-back
cmd-menu-accept
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>' and '<down>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>' and '<up>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
@@ -126,53 +134,62 @@ The following command line commands are provided by lf:
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
.PP .PP
.EX .EX
anchorfind bool (default on) anchorfind bool (default true)
autoquit bool (default off) autoquit bool (default false)
cleaner string (default '') cleaner string (default '')
dircache bool (default on) cursoractivefmt string (default "\e033[7m")
dircounts bool (default off) cursorparentfmt string (default "\e033[7m")
dirfirst bool (default on) cursorpreviewfmt string (default "\e033[4m")
dironly bool (default off) dircache bool (default true)
drawbox bool (default off) dircounts bool (default false)
errorfmt string (default "\e033[7;31;47m%s\e033[0m") dirfirst bool (default true)
dironly bool (default false)
dirpreviews bool (default false)
drawbox bool (default false)
errorfmt string (default "\e033[7;31;47m")
filesep string (default "\en") filesep string (default "\en")
findlen int (default 1) findlen int (default 1)
globsearch bool (default off) globsearch bool (default false)
hidden bool (default off) hidden bool (default false)
hiddenfiles []string (default '.*') hiddenfiles []string (default '.*')
icons bool (default off) history bool (default true)
icons bool (default false)
ifs string (default '') ifs string (default '')
ignorecase bool (default on) ignorecase bool (default true)
ignoredia bool (default on) ignoredia bool (default true)
incfilter bool (default off) incfilter bool (default false)
incsearch bool (default off) incsearch bool (default false)
info []string (default '') info []string (default '')
infotimefmtnew string (default 'Jan _2 15:04') infotimefmtnew string (default 'Jan _2 15:04')
infotimefmtold string (default 'Jan _2 2006') infotimefmtold string (default 'Jan _2 2006')
mouse bool (default off) mouse bool (default false)
number bool (default off) number bool (default false)
numberfmt string (default "\e033[33m")
period int (default 0) period int (default 0)
preview bool (default on) preview bool (default true)
previewer string (default '') previewer string (default '')
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%d\e033[0m\e033[1m%f\e033[0m") promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%d\e033[0m\e033[1m%f\e033[0m")
ratios []int (default '1:2:3') ratios []int (default '1:2:3')
relativenumber bool (default off) relativenumber bool (default false)
reverse bool (default off) reverse bool (default false)
ruler []string (default 'acc:progress:selection:filter:ind')
scrolloff int (default 0) scrolloff int (default 0)
selmode string (default 'all')
shell string (default 'sh' for Unix and 'cmd' for Windows) shell string (default 'sh' for Unix and 'cmd' for Windows)
shellflag string (default '-c' for Unix and '/c' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows)
shellopts []string (default '') shellopts []string (default '')
smartcase bool (default on) smartcase bool (default true)
smartdia bool (default off) smartdia bool (default false)
sortby string (default 'natural') sortby string (default 'natural')
tabstop int (default 8) tabstop int (default 8)
tagfmt string (default "\e033[31m%s\e033[0m") tagfmt string (default "\e033[31m")
tempmarks string (default '') tempmarks string (default '')
timefmt string (default 'Mon Jan _2 15:04:05 2006') timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~') truncatechar string (default '~')
waitmsg string (default 'Press any key to continue') waitmsg string (default 'Press any key to continue')
wrapscan bool (default on) wrapscan bool (default true)
wrapscroll bool (default off) wrapscroll bool (default false)
user_{option} string (default none)
.EE .EE
.PP .PP
The following environment variables are exported for shell commands: The following environment variables are exported for shell commands:
@@ -186,10 +203,16 @@ The following environment variables are exported for shell commands:
OLDPWD OLDPWD
LF_LEVEL LF_LEVEL
OPENER OPENER
VISUAL
EDITOR EDITOR
PAGER PAGER
SHELL SHELL
lf
lf_{option} lf_{option}
lf_user_{option}
lf_width
lf_height
lf_count
.EE .EE
.PP .PP
The following special shell commands are used to customize the behavior of lf when defined: The following special shell commands are used to customize the behavior of lf when defined:
@@ -201,6 +224,7 @@ The following special shell commands are used to customize the behavior of lf wh
delete delete
pre-cd pre-cd
on-cd on-cd
on-select
on-quit on-quit
.EE .EE
.PP .PP
@@ -232,6 +256,23 @@ The following additional keybindings are provided by default:
map gh cd ~ map gh cd ~
map <space> :toggle; down map <space> :toggle; down
.EE .EE
.PP
If the 'mouse' option is enabled, mouse buttons have the following default effects:
.PP
.EX
Left mouse button
Click on a file or directory to select it.
.EE
.PP
.EX
Right mouse button
Enter a directory or open a file. Also works on the preview window.
.EE
.PP
.EX
Scroll wheel
Move up or down. If Ctrl is pressed, scroll up or down.
.EE
.SH CONFIGURATION .SH CONFIGURATION
Configuration files should be located at: Configuration files should be located at:
.PP .PP
@@ -341,7 +382,15 @@ Change the current working directory to the next/previous jumplist item.
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
.EE .EE
.PP .PP
Move the current file selection to the top/bottom of the directory. Move the current file selection to the top/bottom of the directory. A count can be specified to move to a specific line, for example use `3G` to move to the third line.
.PP
.EX
high (default 'H')
middle (default 'M')
low (default 'L')
.EE
.PP
Move the current file selection to the high/middle/low of the screen.
.PP .PP
.EX .EX
toggle toggle
@@ -355,6 +404,16 @@ Toggle the selection of the current file or files given as arguments.
.PP .PP
Reverse the selection of all files in the current directory (i.e. 'toggle' all files). Selections in other directories are not effected by this command. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories. Reverse the selection of all files in the current directory (i.e. 'toggle' all files). Selections in other directories are not effected by this command. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories.
.PP .PP
.EX
invert-below
.EE
.PP
Reverse the selection (i.e. 'toggle') of all files at or after the current file in the current directory.
.PP
To select a contiguous block of files, use this command on the first file you want to select. Then, move down to the first file you do *not* want to select (the one after the end of the desired selection) and use this command again. This achieves an effect similar to the visual mode in vim.
.PP
This command is experimental and may be removed once a better replacement for the visual mode is implemented in 'lf'. If you'd like to experiment with using this command, you should bind it to a key (e.g. 'V') for a better experience.
.PP
.EX .EX
unselect (default 'u') unselect (default 'u')
.EE .EE
@@ -372,7 +431,7 @@ Select/unselect files that match the given glob.
calcdirsize calcdirsize
.EE .EE
.PP .PP
Calculate the total size for each of the selected directories. Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size. Calculate the total size for each of the selected directories. Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size. If the total size of a directory is not calculated, it will be shown as '-'.
.PP .PP
.EX .EX
copy (default 'y') copy (default 'y')
@@ -567,7 +626,11 @@ Tag a file with '*' or a single width character given in the argument. You can d
.PP .PP
Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag. Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag.
.SH COMMAND LINE COMMANDS .SH COMMAND LINE COMMANDS
This section shows information about command line commands. These should be mostly compatible with readline keybindings. A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters. The prompt character specifies which of the several command-line modes you are in. For example, the 'read' command takes you to the ':' mode.
.PP
When the cursor is at the first character in ':' mode, pressing one of the keys '!', '$', '%', or '&' takes you to the corresponding mode. You can go back with 'cmd-delete-back' ('<backspace>' by default).
.PP
The command line commands should be mostly compatible with readline keybindings. A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters.
.PP .PP
.EX .EX
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
@@ -588,6 +651,12 @@ Autocomplete the current word.
.PP .PP
Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options. Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap <tab> cmd-menu-complete; cmap <backtab> cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options.
.PP .PP
.EX
cmd-menu-accept
.EE
.PP
Accept the currently selected match in menu completion and close the menu.
.PP
.EX .EX
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
.EE .EE
@@ -601,8 +670,8 @@ Execute the current line.
Interrupt the current shell-pipe command and return to the normal mode. Interrupt the current shell-pipe command and return to the normal mode.
.PP .PP
.EX .EX
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>' and '<down>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>' and '<up>')
.EE .EE
.PP .PP
Go to next/previous item in the history. Go to next/previous item in the history.
@@ -623,10 +692,15 @@ Move the cursor to the beginning/end of line.
.PP .PP
.EX .EX
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
.EE
.PP
Delete the next character.
.PP
.EX
cmd-delete-back (default '<backspace>' and '<backspace2>') cmd-delete-back (default '<backspace>' and '<backspace2>')
.EE .EE
.PP .PP
Delete the next character in forward/backward direction. Delete the previous character. When at the beginning of a prompt, returns either to normal mode or to ':' mode.
.PP .PP
.EX .EX
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
@@ -674,17 +748,30 @@ Delete the next word in forward direction.
.EE .EE
.PP .PP
Capitalize/uppercase/lowercase the current word and jump to the next word. Capitalize/uppercase/lowercase the current word and jump to the next word.
.PP
.EX
maps
cmaps
.EE
.PP
List all key mappings in normal mode or command-line editing mode.
.PP
.EX
jumps
.EE
.PP
List the contents of the jump list, in order of the most recently visited locations. Each location is marked with the count that can be used with the `jump-prev` and `jump-next` commands (e.g. use `3[` to move three spaces backwards in the jump list). A '>' is used to mark the current location in the jump list.
.SH OPTIONS .SH OPTIONS
This section shows information about options to customize the behavior. Character ':' is used as the separator for list options '[]int' and '[]string'. This section shows information about options to customize the behavior. Character ':' is used as the separator for list options '[]int' and '[]string'.
.PP .PP
.EX .EX
anchorfind bool (default on) anchorfind bool (default true)
.EE .EE
.PP .PP
When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position. When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position.
.PP .PP
.EX .EX
autoquit bool (default off) autoquit bool (default false)
.EE .EE
.PP .PP
Automatically quit server when there are no clients left connected. Automatically quit server when there are no clients left connected.
@@ -693,44 +780,66 @@ Automatically quit server when there are no clients left connected.
cleaner string (default '') (not called if empty) cleaner string (default '') (not called if empty)
.EE .EE
.PP .PP
Set the path of a cleaner file. The file should be executable. This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled. One argument is passed to the file, path to the file whose preview should be cleaned. Preview clearing is disabled when the value of this option is left empty. Set the path of a cleaner file. The file should be executable. This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Preview clearing is disabled when the value of this option is left empty.
.PP .PP
.EX .EX
dircache bool (default on) cursoractivefmt string (default "\e033[7m")
cursorparentfmt string (default "\e033[7m")
cursorpreviewfmt string (default "\e033[4m")
.EE
.PP
Format strings for highlighting the cursor. `cursoractivefmt` applies in the current directory pane, `cursorparentfmt` applies in panes that show parents of the current directory, and `cursorpreviewfmt` applies in panes that preview directories.
.PP
The default is to make the active cursor and the parent directory cursor inverted. The preview cursor is underlined.
.PP
Some other possibilities to consider for the preview or parent cursors: an empty string for no cursor, "\e033[7;2m" for dimmed inverted text (visibility varies by terminal), "\e033[7;90m" for inverted text with grey (aka "brightblack") background.
.PP
If the format string contains the characters `%s`, it is interpreted as a format string for `fmt.Sprintf`. Such a string should end with the terminal reset sequence. For example, "\e033[4m%s\e033[0m" has the same effect as "\e033[4m".
.PP
.EX
dircache bool (default true)
.EE .EE
.PP .PP
Cache directory contents. Cache directory contents.
.PP .PP
.EX .EX
dircounts bool (default off) dircounts bool (default false)
.EE .EE
.PP .PP
When this option is enabled, directory sizes show the number of items inside instead of the size of directory file. The former needs to be calculated by reading the directory and counting the items inside. The latter is directly provided by the operating system and it does not require any calculation, though it is non-intuitive and it can often be misleading. This option is disabled by default for performance reasons. This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information. A thousand items are counted per directory at most, and bigger directories are shown as '999+'. When this option is enabled, directory sizes show the number of items inside instead of the total size of the directory, which needs to be calculated for each directory using 'calcdirsize'. This information needs to be calculated by reading the directory and counting the items inside. Therefore, this option is disabled by default for performance reasons. This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information. 999 items are counted per directory at most, and bigger directories are shown as '999+'.
.PP .PP
.EX .EX
dirfirst bool (default on) dirfirst bool (default true)
.EE .EE
.PP .PP
Show directories first above regular files. Show directories first above regular files.
.PP .PP
.EX .EX
dironly bool (default off) dironly bool (default false)
.EE .EE
.PP .PP
Show only directories. Show only directories.
.PP .PP
.EX .EX
drawbox bool (default off) dirpreviews bool (default false)
.EE
.PP
If enabled, directories will also be passed to the previewer script. This allows custom previews for directories.
.PP
.EX
drawbox bool (default false)
.EE .EE
.PP .PP
Draw boxes around panes with box drawing characters. Draw boxes around panes with box drawing characters.
.PP .PP
.EX .EX
errorfmt string (default "\e033[7;31;47m%s\e033[0m") errorfmt string (default "\e033[7;31;47m")
.EE .EE
.PP .PP
Format string of error messages shown in the bottom message line. Format string of error messages shown in the bottom message line.
.PP .PP
If the format string contains the characters `%s`, it is interpreted as a format string for `fmt.Sprintf`. Such a string should end with the terminal reset sequence. For example, "\e033[4m%s\e033[0m" has the same effect as "\e033[4m".
.PP
.EX .EX
filesep string (default "\en") filesep string (default "\en")
.EE .EE
@@ -744,13 +853,13 @@ File separator used in environment variables 'fs' and 'fx'.
Number of characters prompted for the find command. When this value is set to 0, find command prompts until there is only a single match left. Number of characters prompted for the find command. When this value is set to 0, find command prompts until there is only a single match left.
.PP .PP
.EX .EX
globsearch bool (default off) globsearch bool (default false)
.EE .EE
.PP .PP
When this option is enabled, search command patterns are considered as globs, otherwise they are literals. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges. Otherwise, these characters are interpreted as they are. When this option is enabled, search command patterns are considered as globs, otherwise they are literals. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...]' matches character sets or ranges. Otherwise, these characters are interpreted as they are.
.PP .PP
.EX .EX
hidden bool (default off) hidden bool (default false)
.EE .EE
.PP .PP
Show hidden files. On Unix systems, hidden files are determined by the value of 'hiddenfiles'. On Windows, only files with hidden attributes are considered hidden files. Show hidden files. On Unix systems, hidden files are determined by the value of 'hiddenfiles'. On Windows, only files with hidden attributes are considered hidden files.
@@ -759,10 +868,16 @@ Show hidden files. On Unix systems, hidden files are determined by the value of
hiddenfiles []string (default '.*') hiddenfiles []string (default '.*')
.EE .EE
.PP .PP
List of hidden file glob patterns. Patterns can be given as relative or absolute paths. Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. In addition, if a pattern starts with '!', then its matches are excluded from hidden files. List of hidden file glob patterns. Patterns can be given as relative or absolute paths. Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...]' to match character sets or ranges. In addition, if a pattern starts with '!', then its matches are excluded from hidden files. To add multiple patterns, use ':' as a separator. Example: '.*:lost+found:*.bak'
.PP .PP
.EX .EX
icons bool (default off) history bool (default true)
.EE
.PP
Save command history.
.PP
.EX
icons bool (default false)
.EE .EE
.PP .PP
Show icons before each item in the list. Show icons before each item in the list.
@@ -774,25 +889,25 @@ Show icons before each item in the list.
Sets 'IFS' variable in shell commands. It works by adding the assignment to the beginning of the command string as "IFS='...'; ...". The reason is that 'IFS' variable is not inherited by the shell for security reasons. This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells. This option has no effect when the value is left empty. This option does not have any effect on Windows. Sets 'IFS' variable in shell commands. It works by adding the assignment to the beginning of the command string as "IFS='...'; ...". The reason is that 'IFS' variable is not inherited by the shell for security reasons. This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells. This option has no effect when the value is left empty. This option does not have any effect on Windows.
.PP .PP
.EX .EX
ignorecase bool (default on) ignorecase bool (default true)
.EE .EE
.PP .PP
Ignore case in sorting and search patterns. Ignore case in sorting and search patterns.
.PP .PP
.EX .EX
ignoredia bool (default on) ignoredia bool (default true)
.EE .EE
.PP .PP
Ignore diacritics in sorting and search patterns. Ignore diacritics in sorting and search patterns.
.PP .PP
.EX .EX
incsearch bool (default off) incsearch bool (default false)
.EE .EE
.PP .PP
Jump to the first match after each keystroke during searching. Jump to the first match after each keystroke during searching.
.PP .PP
.EX .EX
incfilter bool (default off) incfilter bool (default false)
.EE .EE
.PP .PP
Apply filter pattern after each keystroke during filtering. Apply filter pattern after each keystroke during filtering.
@@ -816,17 +931,23 @@ Format string of the file time shown in the info column when it matches this yea
Format string of the file time shown in the info column when it doesn't match this year. Format string of the file time shown in the info column when it doesn't match this year.
.PP .PP
.EX .EX
mouse bool (default off) mouse bool (default false)
.EE .EE
.PP .PP
Send mouse events as input. Send mouse events as input.
.PP .PP
.EX .EX
number bool (default off) number bool (default false)
.EE .EE
.PP .PP
Show the position number for directory items at the left side of pane. When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest. Show the position number for directory items at the left side of pane. When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest.
.PP .PP
.EX
numberfmt string (default "\e033[33m")
.EE
.PP
Format string of the position number for each line.
.PP
.EX .EX
period int (default 0) period int (default 0)
.EE .EE
@@ -834,7 +955,7 @@ Show the position number for directory items at the left side of pane. When 'rel
Set the interval in seconds for periodic checks of directory updates. This works by periodically calling the 'load' command. Note that directories are already updated automatically in many cases. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. Periodic checks are disabled when the value of this option is set to zero. Set the interval in seconds for periodic checks of directory updates. This works by periodically calling the 'load' command. Note that directories are already updated automatically in many cases. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. Periodic checks are disabled when the value of this option is set to zero.
.PP .PP
.EX .EX
preview bool (default on) preview bool (default true)
.EE .EE
.PP .PP
Show previews of files and directories at the right most pane. If the file has more lines than the preview pane, rest of the lines are not read. Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'. Show previews of files and directories at the right most pane. If the file has more lines than the preview pane, rest of the lines are not read. Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'.
@@ -849,7 +970,7 @@ Set the path of a previewer file to filter the content of regular files for prev
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%d\e033[0m\e033[1m%f\e033[0m") promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%d\e033[0m\e033[1m%f\e033[0m")
.EE .EE
.PP .PP
Format string of the prompt shown in the top line. Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. Home folder is shown as '~' in the working directory expansion. Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen. Format string of the prompt shown in the top line. Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. '%S' may be used once and will provide a spacer so that the following parts are right aligned on the screen. Home folder is shown as '~' in the working directory expansion. Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen.
.PP .PP
.EX .EX
ratios []int (default '1:2:3') ratios []int (default '1:2:3')
@@ -858,17 +979,29 @@ Format string of the prompt shown in the top line. Special expansions are provid
List of ratios of pane widths. Number of items in the list determines the number of panes in the ui. When 'preview' option is enabled, the right most number is used for the width of preview pane. List of ratios of pane widths. Number of items in the list determines the number of panes in the ui. When 'preview' option is enabled, the right most number is used for the width of preview pane.
.PP .PP
.EX .EX
relativenumber bool (default off) relativenumber bool (default false)
.EE .EE
.PP .PP
Show the position number relative to the current line. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown. Show the position number relative to the current line. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown.
.PP .PP
.EX .EX
reverse bool (default off) reverse bool (default false)
.EE .EE
.PP .PP
Reverse the direction of sort. Reverse the direction of sort.
.PP .PP
.EX
ruler []string (default 'acc:progress:selection:filter:ind')
.EE
.PP
List of information shown in status line ruler. Currently supported information types are 'acc', 'progress', 'selection', 'ind' and 'df'. `acc` shows the pressed keys (e.g. for bindings with multiple key presses or counts given to bindings). `progress` shows the progress of file operations (e.g. copying a large directory). `selection` shows the number of files that are selected, or designated for being cut/copied. `filter` shows 'F' if a filter is currently being applied. `ind` shows the current position of the cursor as well as the number of files in the current directory. `df` shows the amount of free disk space remaining.
.PP
.EX
selmode string (default 'all')
.EE
.PP
Selection mode for commands. When set to 'all' it will use the selected files from all directories. When set to 'dir' it will only use the selected files in the current directory.
.PP
.EX .EX
scrolloff int (default 0) scrolloff int (default 0)
.EE .EE
@@ -894,13 +1027,13 @@ Command line flag used to pass shell commands.
List of shell options to pass to the shell executable. List of shell options to pass to the shell executable.
.PP .PP
.EX .EX
smartcase bool (default on) smartcase bool (default true)
.EE .EE
.PP .PP
Override 'ignorecase' option when the pattern contains an uppercase character. This option has no effect when 'ignorecase' is disabled. Override 'ignorecase' option when the pattern contains an uppercase character. This option has no effect when 'ignorecase' is disabled.
.PP .PP
.EX .EX
smartdia bool (default off) smartdia bool (default false)
.EE .EE
.PP .PP
Override 'ignoredia' option when the pattern contains a character with diacritic. This option has no effect when 'ignoredia' is disabled. Override 'ignoredia' option when the pattern contains a character with diacritic. This option has no effect when 'ignoredia' is disabled.
@@ -918,11 +1051,13 @@ Sort type for directories. Currently supported sort types are 'natural', 'name',
Number of space characters to show for horizontal tabulation (U+0009) character. Number of space characters to show for horizontal tabulation (U+0009) character.
.PP .PP
.EX .EX
tagfmt string (default "\e033[31m%s\e033[0m") tagfmt string (default "\e033[31m")
.EE .EE
.PP .PP
Format string of the tags. Format string of the tags.
.PP .PP
If the format string contains the characters `%s`, it is interpreted as a format string for `fmt.Sprintf`. Such a string should end with the terminal reset sequence. For example, "\e033[4m%s\e033[0m" has the same effect as "\e033[4m".
.PP
.EX .EX
tempmarks string (default '') tempmarks string (default '')
.EE .EE
@@ -948,16 +1083,22 @@ Truncate character shown at the end when the file name does not fit to the pane.
String shown after commands of shell-wait type. String shown after commands of shell-wait type.
.PP .PP
.EX .EX
wrapscan bool (default on) wrapscan bool (default true)
.EE .EE
.PP .PP
Searching can wrap around the file list. Searching can wrap around the file list.
.PP .PP
.EX .EX
wrapscroll bool (default off) wrapscroll bool (default false)
.EE .EE
.PP .PP
Scrolling can wrap around the file list. Scrolling can wrap around the file list.
.PP
.EX
user_{option} string (default none)
.EE
.PP
Any option that is prefixed with 'user_' is a user defined option and can be set to any string. Inside a user defined command the value will be provided in the `lf_user_{option}` environment variable. These options are not used by lf and are not persisted.
.SH ENVIRONMENT VARIABLES .SH ENVIRONMENT VARIABLES
The following variables are exported for shell commands: These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f'). The following variables are exported for shell commands: These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f').
.PP .PP
@@ -1007,36 +1148,63 @@ The value of this variable is set to the current nesting level when you run lf f
OPENER OPENER
.EE .EE
.PP .PP
If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others. If this variable is set in the environment, use the same value. Otherwise, this is set to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others.
.PP .PP
.EX .EX
EDITOR EDITOR
.EE .EE
.PP .PP
If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on Unix, 'notepad' in Windows. If VISUAL is set in the environment, use its value. Otherwise, use the value of the environment variable EDITOR. If neither variable is set, this is set to 'vi' on Unix, 'notepad' in Windows.
.PP .PP
.EX .EX
PAGER PAGER
.EE .EE
.PP .PP
If this variable is set in the environment, use the same value, otherwise set the value to 'less' on Unix, 'more' in Windows. If this variable is set in the environment, use the same value. Otherwise, this is set to 'less' on Unix, 'more' in Windows.
.PP .PP
.EX .EX
SHELL SHELL
.EE .EE
.PP .PP
If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on Unix, 'cmd' in Windows. If this variable is set in the environment, use the same value. Otherwise, this is set to 'sh' on Unix, 'cmd' in Windows.
.PP
.EX
lf
.EE
.PP
Absolute path to the currently running lf binary, if it can be found. Otherwise, this is set to the string 'lf'.
.PP .PP
.EX .EX
lf_{option} lf_{option}
.EE .EE
.PP .PP
Value of the {option}. Value of the {option}.
.PP
.EX
lf_user_{option}
.EE
.PP
Value of the user_{option}.
.PP
.EX
lf_width
lf_height
.EE
.PP
Width/Height of the terminal.
.PP
.EX
lf_count
.EE
.PP
Value of the count associated with the current command.
.SH SPECIAL COMMANDS .SH SPECIAL COMMANDS
This section shows information about special shell commands.
.PP .PP
.EX .EX
open open
.EE .EE
.PP
This shell command can be defined to override the default 'open' command when the current file is not a directory. This shell command can be defined to override the default 'open' command when the current file is not a directory.
.PP .PP
.EX .EX
@@ -1049,7 +1217,7 @@ This shell command can be defined to override the default 'paste' command.
rename rename
.EE .EE
.PP .PP
This shell command can be defined to override the default 'paste' command. This shell command can be defined to override the default 'rename' command.
.PP .PP
.EX .EX
delete delete
@@ -1069,6 +1237,12 @@ This shell command can be defined to be executed before changing a directory.
.PP .PP
This shell command can be defined to be executed after changing a directory. This shell command can be defined to be executed after changing a directory.
.PP .PP
.EX
on-select
.EE
.PP
This shell command can be defined to be executed after the selection changes.
.PP
.EX .EX
on-quit on-quit
.EE .EE
@@ -1093,13 +1267,15 @@ Characters from '#' to newline are comments and ignored:
# comments start with '#' # comments start with '#'
.EE .EE
.PP .PP
There are three special commands ('set', 'map', 'cmap', and 'cmd') for configuration. There are four special commands ('set', 'map', 'cmap', and 'cmd') for configuration.
.PP .PP
Command 'set' is used to set an option which can be boolean, integer, or string: Command 'set' is used to set an option which can be boolean, integer, or string:
.PP .PP
.EX .EX
set hidden # boolean on set hidden # boolean enable
set nohidden # boolean off set hidden true # boolean enable
set nohidden # boolean disable
set hidden false # boolean disable
set hidden! # boolean toggle set hidden! # boolean toggle
set scrolloff 10 # integer value set scrolloff 10 # integer value
set sortby time # string value w/o quotes set sortby time # string value w/o quotes
@@ -1116,10 +1292,11 @@ Command 'map' is used to bind a key to a command which can be builtin command, c
map U !du -csh * # waiting shell command map U !du -csh * # waiting shell command
.EE .EE
.PP .PP
Command 'cmap' is used to bind a key to a command line command which can only be one of the builtin commands: Command 'cmap' is used to bind a key on the command line to a command line command or any other command:
.PP .PP
.EX .EX
cmap <c-g> cmd-escape cmap <c-g> cmd-escape
cmap <a-i> set incsearch!
.EE .EE
.PP .PP
You can delete an existing binding by leaving the expression empty: You can delete an existing binding by leaving the expression empty:
@@ -1265,7 +1442,7 @@ Regular shell commands are the most basic command type that is useful for many p
if [ -z "$fs" ]; then if [ -z "$fs" ]; then
mv "$f" ~/.trash mv "$f" ~/.trash
else else
IFS="`printf '\en\et'`"; mv $fs ~/.trash IFS="$(printf '\en\et')"; mv $fs ~/.trash
fi fi
}} }}
.EE .EE
@@ -1275,7 +1452,7 @@ We check '$fs' to see if there are any selected files. Otherwise we just delete
.EX .EX
cmd trash ${{ cmd trash ${{
mkdir -p ~/.trash mkdir -p ~/.trash
IFS="`printf '\en\et'`"; mv $fx ~/.trash IFS="$(printf '\en\et')"; mv $fx ~/.trash
}} }}
.EE .EE
.PP .PP
@@ -1286,7 +1463,7 @@ The trash directory is checked each time the command is executed. We can move it
.EE .EE
.PP .PP
.EX .EX
cmd trash ${{ IFS="`printf '\en\et'`"; mv $fx ~/.trash }} cmd trash ${{ IFS="$(printf '\en\et')"; mv $fx ~/.trash }}
.EE .EE
.PP .PP
Since these are one liners, we can drop '{{' and '}}': Since these are one liners, we can drop '{{' and '}}':
@@ -1296,7 +1473,7 @@ Since these are one liners, we can drop '{{' and '}}':
.EE .EE
.PP .PP
.EX .EX
cmd trash $IFS="`printf '\en\et'`"; mv $fx ~/.trash cmd trash $IFS="$(printf '\en\et')"; mv $fx ~/.trash
.EE .EE
.PP .PP
Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\en"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation. Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\en"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation.
@@ -1353,10 +1530,9 @@ Since lf does not have control flow syntax, remote commands are used for such ne
.PP .PP
.EX .EX
cmd recol %{{ cmd recol %{{
w=$(tput cols) if [ $lf_width -le 80 ]; then
if [ $w -le 80 ]; then
lf -remote "send $id set ratios 1:2" lf -remote "send $id set ratios 1:2"
elif [ $w -le 160 ]; then elif [ $lf_width -le 160 ]; then
lf -remote "send $id set ratios 1:2:3" lf -remote "send $id set ratios 1:2:3"
else else
lf -remote "send $id set ratios 1:2:3:5" lf -remote "send $id set ratios 1:2:3:5"
@@ -1400,13 +1576,10 @@ By default, lf does not assign 'delete' command to a key to protect new users. Y
.SH SEARCHING FILES .SH SEARCHING FILES
There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes. There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes.
.PP .PP
Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. Alternatively, you can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. Possible candidates are 'up', 'down' and their variants, 'top', 'bottom', 'updir', and 'open' commands. For example, you can use arrow keys to finish the search with the following mappings: Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. You can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. For example, you can use the right arrow key to finish the search and open the selected file with the following mapping:
.PP .PP
.EX .EX
cmap <up> up cmap <right> :cmd-enter; open
cmap <down> down
cmap <left> updir
cmap <right> open
.EE .EE
.PP .PP
Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial. Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial.
@@ -1429,8 +1602,7 @@ You may want to use either file extensions or mime types from 'file' command:
.PP .PP
.EX .EX
cmd open ${{ cmd open ${{
test -L $f && f=$(readlink -f $f) case $(file --mime-type -Lb $f) in
case $(file --mime-type $f -b) in
text/*) vi $fx;; text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac esac
@@ -1439,6 +1611,19 @@ You may want to use either file extensions or mime types from 'file' command:
.PP .PP
You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits. You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits.
.PP .PP
Regular shell commands (i.e. '$') drop to terminal which results in a flicker for commands that finishes immediately (e.g. 'xdg-open' in the above example). If you want to use asynchronous shell commands (i.e. '&') but also want to use the terminal when necessary (e.g. 'vi' in the above exxample), you can use a remote command:
.PP
.EX
cmd open &{{
case $(file --mime-type -Lb $f) in
text/*) lf -remote "send $id \e$vi \e$fx";;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac
}}
.EE
.PP
Note, asynchronous shell commands run in their own process group by default so they do not require the manual use of 'setsid'.
.PP
Following command is provided by default: Following command is provided by default:
.PP .PP
.EX .EX
@@ -1447,7 +1632,7 @@ Following command is provided by default:
.PP .PP
You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few. You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few.
.SH PREVIEWING FILES .SH PREVIEWING FILES
lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files to name few. For coloring lf recognizes ansi escape codes. lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files to name a few. For coloring lf recognizes ansi escape codes.
.PP .PP
In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Output of the execution is printed in the preview pane. You may also want to use the same script in your pager mapping as well: In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Output of the execution is printed in the preview pane. You may also want to use the same script in your pager mapping as well:
.PP .PP
+18 -7
View File
@@ -79,6 +79,13 @@ func exportEnvVars() {
level++ level++
os.Setenv("LF_LEVEL", strconv.Itoa(level)) os.Setenv("LF_LEVEL", strconv.Itoa(level))
lfPath, err := os.Executable()
if err != nil {
log.Printf("getting path to lf binary: %s", err)
lfPath = "lf"
}
os.Setenv("lf", lfPath)
} }
// used by exportOpts below // used by exportOpts below
@@ -109,12 +116,12 @@ func fieldToString(field reflect.Value) string {
} }
func exportOpts() { func exportOpts() {
e := reflect.ValueOf(&gOpts).Elem() v := reflect.ValueOf(gOpts)
t := v.Type()
for i := 0; i < e.NumField(); i++ { for i := 0; i < v.NumField(); i++ {
// Get name and prefix it with lf_ // Get field name and prefix it with lf_
name := e.Type().Field(i).Name name := "lf_" + t.Field(i).Name
name = fmt.Sprintf("lf_%s", name)
// Skip maps // Skip maps
if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" { if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" {
@@ -152,10 +159,14 @@ func exportOpts() {
dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0) dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0)
os.Setenv("lf_dirfirst", dirfirst) os.Setenv("lf_dirfirst", dirfirst)
} else if name == "lf_user" {
// set each user option
for key, value := range gOpts.user {
os.Setenv(name+"_"+key, value)
}
} else { } else {
field := e.Field(i) field := v.Field(i)
value := fieldToString(field) value := fieldToString(field)
os.Setenv(name, value) os.Setenv(name, value)
} }
} }
+1 -5
View File
@@ -91,7 +91,7 @@ func unescape(s string) string {
} }
// This function splits the given string by whitespaces. It is aware of escaped // This function splits the given string by whitespaces. It is aware of escaped
// whitespaces so that they are not splitted unintentionally. // whitespaces so that they are not split unintentionally.
func tokenize(s string) []string { func tokenize(s string) []string {
esc := false esc := false
var buf []rune var buf []rune
@@ -295,10 +295,6 @@ func max(a, b int) int {
return b return b
} }
func mod(a, b int) int {
return (a%b + b) % b
}
// We don't need no generic code // We don't need no generic code
// We don't need no type control // We don't need no type control
// No dark templates in compiler // No dark templates in compiler
+258 -49
View File
@@ -15,7 +15,7 @@ import (
"strings" "strings"
"time" "time"
times "gopkg.in/djherbis/times.v1" times "github.com/djherbis/times"
) )
type linkState byte type linkState byte
@@ -150,6 +150,7 @@ type dir struct {
ignorecase bool // ignorecase value from last sort ignorecase bool // ignorecase value from last sort
ignoredia bool // ignoredia value from last sort ignoredia bool // ignoredia value from last sort
noPerm bool // whether lf has no permission to open the directory noPerm bool // whether lf has no permission to open the directory
lines []string // lines of text to display if directory previews are enabled
} }
func newDir(path string) *dir { func newDir(path string) *dir {
@@ -161,6 +162,7 @@ func newDir(path string) *dir {
} }
return &dir{ return &dir{
loading: gOpts.dirpreviews, // Directory is loaded after previewer function exits.
loadTime: time, loadTime: time,
path: path, path: path,
files: files, files: files,
@@ -365,6 +367,7 @@ type nav struct {
deleteCountChan chan int deleteCountChan chan int
deleteTotalChan chan int deleteTotalChan chan int
previewChan chan string previewChan chan string
dirPreviewChan chan *dir
dirChan chan *dir dirChan chan *dir
regChan chan *reg regChan chan *reg
dirCache map[string]*dir dirCache map[string]*dir
@@ -385,11 +388,15 @@ type nav struct {
searchPos int searchPos int
prevFilter []string prevFilter []string
volatilePreview bool volatilePreview bool
previewTimer *time.Timer
previewLoading bool
jumpList []string jumpList []string
jumpListInd int jumpListInd int
} }
func (nav *nav) loadDirInternal(path string) *dir { func (nav *nav) loadDirInternal(path string) *dir {
nav.startPreview()
d := &dir{ d := &dir{
loading: true, loading: true,
loadTime: time.Now(), loadTime: time.Now(),
@@ -403,7 +410,11 @@ func (nav *nav) loadDirInternal(path string) *dir {
d := newDir(path) d := newDir(path)
d.sort() d.sort()
d.ind, d.pos = 0, 0 d.ind, d.pos = 0, 0
if gOpts.dirpreviews {
nav.dirPreviewChan <- d
}
nav.dirChan <- d nav.dirChan <- d
}() }()
return d return d
} }
@@ -441,12 +452,16 @@ func (nav *nav) checkDir(dir *dir) {
return return
} }
nav.startPreview()
dir.loading = true dir.loading = true
dir.loadTime = now dir.loadTime = now
go func() { go func() {
nd := newDir(dir.path) nd := newDir(dir.path)
nd.filter = dir.filter nd.filter = dir.filter
nd.sort() nd.sort()
if gOpts.dirpreviews {
nav.dirPreviewChan <- nd
}
nav.dirChan <- nd nav.dirChan <- nd
}() }()
case dir.sortType != gOpts.sortType || case dir.sortType != gOpts.sortType ||
@@ -455,10 +470,11 @@ func (nav *nav) checkDir(dir *dir) {
dir.ignorecase != gOpts.ignorecase || dir.ignorecase != gOpts.ignorecase ||
dir.ignoredia != gOpts.ignoredia: dir.ignoredia != gOpts.ignoredia:
dir.loading = true dir.loading = true
sd := *dir
go func() { go func() {
dir.sort() sd.sort()
dir.loading = false sd.loading = false
nav.dirChan <- dir nav.dirChan <- &sd
}() }()
} }
} }
@@ -470,7 +486,9 @@ func (nav *nav) getDirs(wd string) {
for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) { for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
dir := nav.loadDir(curr) dir := nav.loadDir(curr)
if base != "" {
dir.sel(base, nav.height) dir.sel(base, nav.height)
}
dirs = append(dirs, dir) dirs = append(dirs, dir)
} }
@@ -490,6 +508,7 @@ func newNav(height int) *nav {
deleteCountChan: make(chan int, 1024), deleteCountChan: make(chan int, 1024),
deleteTotalChan: make(chan int, 1024), deleteTotalChan: make(chan int, 1024),
previewChan: make(chan string, 1024), previewChan: make(chan string, 1024),
dirPreviewChan: make(chan *dir, 1024),
dirChan: make(chan *dir), dirChan: make(chan *dir),
regChan: make(chan *reg), regChan: make(chan *reg),
dirCache: make(map[string]*dir), dirCache: make(map[string]*dir),
@@ -500,6 +519,7 @@ func newNav(height int) *nav {
tags: make(map[string]string), tags: make(map[string]string),
selectionInd: 0, selectionInd: 0,
height: height, height: height,
previewTimer: time.NewTimer(0),
jumpList: make([]string, 0), jumpList: make([]string, 0),
jumpListInd: -1, jumpListInd: -1,
} }
@@ -523,7 +543,6 @@ func (nav *nav) addJumpList() {
} }
func (nav *nav) cdJumpListPrev() { func (nav *nav) cdJumpListPrev() {
// currPath := nav.currDir().path
if nav.jumpListInd > 0 { if nav.jumpListInd > 0 {
nav.jumpListInd -= 1 nav.jumpListInd -= 1
nav.cd(nav.jumpList[nav.jumpListInd]) nav.cd(nav.jumpList[nav.jumpListInd])
@@ -599,6 +618,23 @@ func (nav *nav) exportFiles() {
exportFiles(currFile, currSelections, nav.currDir().path) exportFiles(currFile, currSelections, nav.currDir().path)
} }
func (nav *nav) dirPreviewLoop(ui *ui) {
var prevPath string
for dir := range nav.dirPreviewChan {
if dir == nil && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview {
cmd := exec.Command(gOpts.cleaner, prevPath)
if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err)
}
nav.volatilePreview = false
} else if dir != nil {
win := ui.wins[len(ui.wins)-1]
nav.previewDir(dir, win)
prevPath = dir.path
}
}
}
func (nav *nav) previewLoop(ui *ui) { func (nav *nav) previewLoop(ui *ui) {
var prev string var prev string
for path := range nav.previewChan { for path := range nav.previewChan {
@@ -612,23 +648,28 @@ func (nav *nav) previewLoop(ui *ui) {
break loop break loop
} }
} }
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() nav.exportFiles()
exportOpts() exportOpts()
cmd := exec.Command(gOpts.cleaner, prev) cmd := exec.Command(gOpts.cleaner, prev,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y))
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
log.Printf("cleaning preview: %s", err) log.Printf("cleaning preview: %s", err)
} }
nav.volatilePreview = false nav.volatilePreview = false
} }
if len(path) != 0 { if len(path) != 0 {
win := ui.wins[len(ui.wins)-1]
nav.preview(path, win) nav.preview(path, win)
prev = path prev = path
} }
} }
} }
//lint:ignore U1000 This function is not used on Windows
func matchPattern(pattern, name, path string) bool { func matchPattern(pattern, name, path string) bool {
s := name s := name
@@ -644,7 +685,70 @@ func matchPattern(pattern, name, path string) bool {
return matched return matched
} }
func (nav *nav) previewDir(dir *dir, win *win) {
defer func() {
dir.loading = false
nav.dirChan <- dir
}()
var reader io.Reader
if len(gOpts.previewer) != 0 {
nav.exportFiles()
exportOpts()
cmd := exec.Command(gOpts.previewer, dir.path,
strconv.Itoa(win.w),
strconv.Itoa(win.h),
strconv.Itoa(win.x),
strconv.Itoa(win.y))
out, err := cmd.StdoutPipe()
if err != nil {
log.Printf("previewing dir: %s", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("previewing dir: %s", err)
out.Close()
return
}
defer func() {
if err := cmd.Wait(); err != nil {
if e, ok := err.(*exec.ExitError); ok {
if e.ExitCode() != 0 {
nav.volatilePreview = true
}
} else {
log.Printf("loading dir: %s", err)
}
}
}()
defer out.Close()
reader = out
buf := bufio.NewScanner(reader)
for i := 0; i < win.h && buf.Scan(); i++ {
for _, r := range buf.Text() {
if r == 0 {
dir.lines = []string{"\033[7mbinary\033[0m"}
return
}
}
dir.lines = append(dir.lines, buf.Text())
}
if buf.Err() != nil {
log.Printf("loading dir: %s", buf.Err())
}
}
}
func (nav *nav) preview(path string, win *win) { 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 }()
@@ -718,6 +822,7 @@ func (nav *nav) loadReg(path string, volatile bool) *reg {
if !ok || (volatile && r.volatile) { if !ok || (volatile && r.volatile) {
r := &reg{loading: true, loadTime: time.Now(), path: path, volatile: true} r := &reg{loading: true, loadTime: time.Now(), path: path, volatile: true}
nav.regCache[path] = r nav.regCache[path] = r
nav.startPreview()
nav.previewChan <- path nav.previewChan <- path
return r return r
} }
@@ -743,10 +848,17 @@ func (nav *nav) checkReg(reg *reg) {
if s.ModTime().After(reg.loadTime) { if s.ModTime().After(reg.loadTime) {
reg.loadTime = now reg.loadTime = now
nav.startPreview()
nav.previewChan <- reg.path nav.previewChan <- reg.path
} }
} }
func (nav *nav) startPreview() {
nav.previewTimer.Stop()
nav.previewLoading = false
nav.previewTimer.Reset(100 * time.Millisecond)
}
func (nav *nav) sort() { func (nav *nav) sort() {
for _, d := range nav.dirs { for _, d := range nav.dirs {
name := d.name() name := d.name()
@@ -816,11 +928,13 @@ 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
edge := min(min(nav.height/2, gOpts.scrolloff), maxind-dir.ind) // 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
// use a smaller value when the height is even and scrolloff is maxed half := nav.height / 2
// in order to stay at the same row as much as possible while up/down if nav.height%2 == 0 {
edge = min(edge, nav.height/2+nav.height%2-1) half--
}
edge := min(min(half, gOpts.scrolloff), maxind-dir.ind)
dir.pos = min(dir.pos, nav.height-edge-1) dir.pos = min(dir.pos, nav.height-edge-1)
dir.pos = min(dir.pos, maxind) dir.pos = min(dir.pos, maxind)
@@ -943,6 +1057,66 @@ func (nav *nav) bottom() bool {
return old != dir.ind return old != dir.ind
} }
func (nav *nav) high() bool {
dir := nav.currDir()
old := dir.ind
beg := max(dir.ind-dir.pos, 0)
offs := gOpts.scrolloff
if beg == 0 {
offs = 0
}
dir.ind = beg + offs
dir.pos = offs
return old != dir.ind
}
func (nav *nav) middle() bool {
dir := nav.currDir()
old := dir.ind
beg := max(dir.ind-dir.pos, 0)
end := min(beg+nav.height, len(dir.files))
half := (end - beg) / 2
dir.ind = beg + half
dir.pos = half
return old != dir.ind
}
func (nav *nav) low() bool {
dir := nav.currDir()
old := dir.ind
beg := max(dir.ind-dir.pos, 0)
end := min(beg+nav.height, len(dir.files))
offs := gOpts.scrolloff
if end == len(dir.files) {
offs = 0
}
dir.ind = end - 1 - offs
dir.pos = end - beg - 1 - offs
return old != dir.ind
}
func (nav *nav) move(index int) bool {
old := nav.currDir().ind
switch {
case index < old:
return nav.up(old - index)
case index > old:
return nav.down(index - old)
default:
return false
}
}
func (nav *nav) toggleSelection(path string) { func (nav *nav) toggleSelection(path string) {
if _, ok := nav.selections[path]; ok { if _, ok := nav.selections[path]; ok {
delete(nav.selections, path) delete(nav.selections, path)
@@ -1006,14 +1180,22 @@ func (nav *nav) tag(tag string) error {
return nil return nil
} }
func (nav *nav) invert() { func (nav *nav) invertAfter(ix int) {
dir := nav.currDir() dir := nav.currDir()
for _, f := range dir.files { for _, f := range dir.files[ix:] {
path := filepath.Join(dir.path, f.Name()) path := filepath.Join(dir.path, f.Name())
nav.toggleSelection(path) nav.toggleSelection(path)
} }
} }
func (nav *nav) invert() {
nav.invertAfter(0)
}
func (nav *nav) invertBelow() {
nav.invertAfter(nav.currDir().ind)
}
func (nav *nav) unselect() { func (nav *nav) unselect() {
nav.selections = make(map[string]int) nav.selections = make(map[string]int)
nav.selectionInd = 0 nav.selectionInd = 0
@@ -1037,20 +1219,20 @@ func (nav *nav) save(cp bool) error {
return nil return nil
} }
func (nav *nav) copyAsync(ui *ui, srcs []string, dstDir string) { func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) {
echo := &callExpr{"echoerr", []string{""}, 1} echo := &callExpr{"echoerr", []string{""}, 1}
_, err := os.Stat(dstDir) _, err := os.Stat(dstDir)
if os.IsNotExist(err) { if os.IsNotExist(err) {
echo.args[0] = err.Error() echo.args[0] = err.Error()
ui.exprChan <- echo app.ui.exprChan <- echo
return return
} }
total, err := copySize(srcs) total, err := copySize(srcs)
if err != nil { if err != nil {
echo.args[0] = err.Error() echo.args[0] = err.Error()
ui.exprChan <- echo app.ui.exprChan <- echo
return return
} }
@@ -1070,7 +1252,7 @@ loop:
} }
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
@@ -1078,27 +1260,27 @@ loop:
if gSingleMode { if gSingleMode {
nav.renew() nav.renew()
ui.loadFile(nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
if errCount == 0 { if errCount == 0 {
ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mCopied successfully\033[0m"}, 1} app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mCopied successfully\033[0m"}, 1}
} }
} }
func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) { func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) {
echo := &callExpr{"echoerr", []string{""}, 1} echo := &callExpr{"echoerr", []string{""}, 1}
_, err := os.Stat(dstDir) _, err := os.Stat(dstDir)
if os.IsNotExist(err) { if os.IsNotExist(err) {
echo.args[0] = err.Error() echo.args[0] = err.Error()
ui.exprChan <- echo app.ui.exprChan <- echo
return return
} }
@@ -1112,7 +1294,7 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
if err != nil { if err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
continue continue
} }
@@ -1122,7 +1304,7 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
if os.SameFile(srcStat, dstStat) { if os.SameFile(srcStat, dstStat) {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] rename %s %s: source and destination are the same file", errCount, src, dst) echo.args[0] = fmt.Sprintf("[%d] rename %s %s: source and destination are the same file", errCount, src, dst)
ui.exprChan <- echo app.ui.exprChan <- echo
continue continue
} else if !os.IsNotExist(err) { } else if !os.IsNotExist(err) {
var newPath string var newPath string
@@ -1138,7 +1320,7 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
total, err := copySize([]string{src}) total, err := copySize([]string{src})
if err != nil { if err != nil {
echo.args[0] = err.Error() echo.args[0] = err.Error()
ui.exprChan <- echo app.ui.exprChan <- echo
continue continue
} }
@@ -1158,7 +1340,7 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
} }
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
@@ -1168,13 +1350,13 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
if err := os.RemoveAll(src); err != nil { if err := os.RemoveAll(src); err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
} else { } else {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
} }
@@ -1183,21 +1365,21 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
if gSingleMode { if gSingleMode {
nav.renew() nav.renew()
ui.loadFile(nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
if errCount == 0 { if errCount == 0 {
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}
} }
} }
func (nav *nav) paste(ui *ui) error { func (nav *nav) paste(app *app) error {
srcs, cp, err := loadFiles() srcs, cp, err := loadFiles()
if err != nil { if err != nil {
return err return err
@@ -1210,9 +1392,9 @@ func (nav *nav) paste(ui *ui) error {
dstDir := nav.currDir().path dstDir := nav.currDir().path
if cp { if cp {
go nav.copyAsync(ui, srcs, dstDir) go nav.copyAsync(app, srcs, dstDir)
} else { } else {
go nav.moveAsync(ui, srcs, dstDir) go nav.moveAsync(app, srcs, dstDir)
if err := saveFiles(nil, false); err != nil { if err := saveFiles(nil, false); err != nil {
return fmt.Errorf("clearing copy/cut buffer: %s", err) return fmt.Errorf("clearing copy/cut buffer: %s", err)
} }
@@ -1231,7 +1413,7 @@ func (nav *nav) paste(ui *ui) error {
return nil return nil
} }
func (nav *nav) del(ui *ui) error { func (nav *nav) del(app *app) error {
list, err := nav.currFileOrSelections() list, err := nav.currFileOrSelections()
if err != nil { if err != nil {
return err return err
@@ -1249,7 +1431,7 @@ func (nav *nav) del(ui *ui) error {
if err := os.RemoveAll(path); err != nil { if err := os.RemoveAll(path); err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
@@ -1257,12 +1439,12 @@ func (nav *nav) del(ui *ui) error {
if gSingleMode { if gSingleMode {
nav.renew() nav.renew()
ui.loadFile(nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
errCount++ errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo app.ui.exprChan <- echo
} }
} }
}() }()
@@ -1283,6 +1465,12 @@ func (nav *nav) rename() error {
return err return err
} }
// It is possible for newPath to already have cache entries if it previously
// existed and was deleted. In this case the cache entries should be deleted
// before loading newPath to prevent displaying a stale preview. However,
// this clears only the current instance of lf, and not any other instances.
delete(nav.regCache, newPath)
delete(nav.dirCache, newPath)
dir := nav.loadDir(filepath.Dir(newPath)) dir := nav.loadDir(filepath.Dir(newPath))
if dir.loading { if dir.loading {
@@ -1306,7 +1494,7 @@ func (nav *nav) sync() error {
} }
oldmarks := nav.marks oldmarks := nav.marks
err = nav.readMarks() errMarks := nav.readMarks()
for _, ch := range gOpts.tempmarks { for _, ch := range gOpts.tempmarks {
tmp := string(ch) tmp := string(ch)
if v, e := oldmarks[tmp]; e { if v, e := oldmarks[tmp]; e {
@@ -1314,6 +1502,9 @@ func (nav *nav) sync() error {
} }
} }
err = nav.readTags() err = nav.readTags()
if errMarks != nil {
return errMarks
}
return err return err
} }
@@ -1351,13 +1542,18 @@ func (nav *nav) sel(path string) error {
base := filepath.Base(path) base := filepath.Base(path)
last := nav.dirs[len(nav.dirs)-1] last := nav.currDir()
if last.loading { if last.loading {
last.files = append(last.files, &file{FileInfo: lstat}) last.files = append(last.files, &file{FileInfo: lstat})
} }
last.sel(base, nav.height) for i, f := range last.files {
if f.Name() == base {
nav.move(i)
break
}
}
return nil return nil
} }
@@ -1620,9 +1816,12 @@ func (nav *nav) readTags() error {
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), ":", 2) text := scanner.Text()
if _, ok := nav.tags[toks[0]]; !ok { ind := strings.LastIndex(text, ":")
nav.tags[toks[0]] = toks[1] path := text[0:ind]
mark := text[ind+1:]
if _, ok := nav.tags[path]; !ok {
nav.tags[path] = mark
} }
} }
@@ -1689,27 +1888,37 @@ func (m indexedSelections) Swap(i, j int) {
func (m indexedSelections) Less(i, j int) bool { return m.indices[i] < m.indices[j] } func (m indexedSelections) Less(i, j int) bool { return m.indices[i] < m.indices[j] }
func (nav *nav) currSelections() []string { func (nav *nav) currSelections() []string {
currDirOnly := gOpts.selmode == "dir"
currDirPath := ""
if currDirOnly {
// select only from this directory
currDirPath = nav.currDir().path
}
paths := make([]string, 0, len(nav.selections)) paths := make([]string, 0, len(nav.selections))
indices := make([]int, 0, len(nav.selections)) indices := make([]int, 0, len(nav.selections))
for path, index := range nav.selections { for path, index := range nav.selections {
if !currDirOnly || filepath.Dir(path) == currDirPath {
paths = append(paths, path) paths = append(paths, path)
indices = append(indices, index) indices = append(indices, index)
} }
}
sort.Sort(indexedSelections{paths: paths, indices: indices}) sort.Sort(indexedSelections{paths: paths, indices: indices})
return paths return paths
} }
func (nav *nav) currFileOrSelections() (list []string, err error) { func (nav *nav) currFileOrSelections() (list []string, err error) {
if len(nav.selections) == 0 { sel := nav.currSelections()
if len(sel) == 0 {
curr, err := nav.currFile() curr, err := nav.currFile()
if err != nil { if err != nil {
return nil, errors.New("no file selected") return nil, errors.New("no file selected")
} }
return []string{curr.path}, nil return []string{curr.path}, nil
} }
return sel, nil
return nav.currSelections(), nil
} }
func (nav *nav) calcDirSize() error { func (nav *nav) calcDirSize() error {
+29 -2
View File
@@ -30,9 +30,13 @@ type sortType struct {
var gOpts struct { var gOpts struct {
anchorfind bool anchorfind bool
autoquit bool autoquit bool
cursoractivefmt string
cursorparentfmt string
cursorpreviewfmt string
dircache bool dircache bool
dircounts bool dircounts bool
dironly bool dironly bool
dirpreviews bool
drawbox bool drawbox bool
globsearch bool globsearch bool
icons bool icons bool
@@ -59,6 +63,7 @@ var gOpts struct {
previewer string previewer string
cleaner string cleaner string
promptfmt string promptfmt string
selmode string
shell string shell string
shellflag string shellflag string
timefmt string timefmt string
@@ -67,13 +72,17 @@ var gOpts struct {
truncatechar string truncatechar string
ratios []int ratios []int
hiddenfiles []string hiddenfiles []string
history bool
info []string info []string
ruler []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
sortType sortType sortType sortType
tempmarks string tempmarks string
numberfmt string
tagfmt string tagfmt string
} }
@@ -83,7 +92,11 @@ func init() {
gOpts.dircache = true gOpts.dircache = true
gOpts.dircounts = false gOpts.dircounts = false
gOpts.dironly = false gOpts.dironly = false
gOpts.dirpreviews = false
gOpts.drawbox = false gOpts.drawbox = false
gOpts.cursoractivefmt = "\033[7m"
gOpts.cursorparentfmt = "\033[7m"
gOpts.cursorpreviewfmt = "\033[4m"
gOpts.globsearch = false gOpts.globsearch = false
gOpts.icons = false gOpts.icons = false
gOpts.ignorecase = true gOpts.ignorecase = true
@@ -103,12 +116,13 @@ func init() {
gOpts.period = 0 gOpts.period = 0
gOpts.scrolloff = 0 gOpts.scrolloff = 0
gOpts.tabstop = 8 gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m%s\033[0m" gOpts.errorfmt = "\033[7;31;47m"
gOpts.filesep = "\n" gOpts.filesep = "\n"
gOpts.ifs = "" gOpts.ifs = ""
gOpts.previewer = "" gOpts.previewer = ""
gOpts.cleaner = "" gOpts.cleaner = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m" gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m"
gOpts.selmode = "all"
gOpts.shell = gDefaultShell gOpts.shell = gDefaultShell
gOpts.shellflag = gDefaultShellFlag gOpts.shellflag = gDefaultShellFlag
gOpts.timefmt = time.ANSIC gOpts.timefmt = time.ANSIC
@@ -117,26 +131,33 @@ func init() {
gOpts.truncatechar = "~" gOpts.truncatechar = "~"
gOpts.ratios = []int{1, 2, 3} gOpts.ratios = []int{1, 2, 3}
gOpts.hiddenfiles = []string{".*"} gOpts.hiddenfiles = []string{".*"}
gOpts.history = true
gOpts.info = nil gOpts.info = nil
gOpts.ruler = []string{"acc", "progress", "selection", "filter", "ind"}
gOpts.shellopts = nil gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort} gOpts.sortType = sortType{naturalSort, dirfirstSort}
gOpts.tempmarks = "'" gOpts.tempmarks = "'"
gOpts.tagfmt = "\033[31m%s\033[0m" gOpts.numberfmt = "\033[33m"
gOpts.tagfmt = "\033[31m"
gOpts.keys = make(map[string]expr) gOpts.keys = make(map[string]expr)
gOpts.keys["k"] = &callExpr{"up", nil, 1} gOpts.keys["k"] = &callExpr{"up", nil, 1}
gOpts.keys["<up>"] = &callExpr{"up", nil, 1} gOpts.keys["<up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<m-up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1} gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1}
gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1} gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<pgup>"] = &callExpr{"page-up", nil, 1} gOpts.keys["<pgup>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<c-y>"] = &callExpr{"scroll-up", nil, 1} gOpts.keys["<c-y>"] = &callExpr{"scroll-up", nil, 1}
gOpts.keys["<c-m-up>"] = &callExpr{"scroll-up", nil, 1}
gOpts.keys["j"] = &callExpr{"down", nil, 1} gOpts.keys["j"] = &callExpr{"down", nil, 1}
gOpts.keys["<down>"] = &callExpr{"down", nil, 1} gOpts.keys["<down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<m-down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1} gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1}
gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1} gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<pgdn>"] = &callExpr{"page-down", nil, 1} gOpts.keys["<pgdn>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<c-e>"] = &callExpr{"scroll-down", nil, 1} gOpts.keys["<c-e>"] = &callExpr{"scroll-down", nil, 1}
gOpts.keys["<c-m-down>"] = &callExpr{"scroll-down", nil, 1}
gOpts.keys["h"] = &callExpr{"updir", nil, 1} gOpts.keys["h"] = &callExpr{"updir", nil, 1}
gOpts.keys["<left>"] = &callExpr{"updir", nil, 1} gOpts.keys["<left>"] = &callExpr{"updir", nil, 1}
gOpts.keys["l"] = &callExpr{"open", nil, 1} gOpts.keys["l"] = &callExpr{"open", nil, 1}
@@ -146,6 +167,9 @@ func init() {
gOpts.keys["<home>"] = &callExpr{"top", nil, 1} gOpts.keys["<home>"] = &callExpr{"top", nil, 1}
gOpts.keys["G"] = &callExpr{"bottom", nil, 1} gOpts.keys["G"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1} gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1}
gOpts.keys["H"] = &callExpr{"high", nil, 1}
gOpts.keys["M"] = &callExpr{"middle", nil, 1}
gOpts.keys["L"] = &callExpr{"low", nil, 1}
gOpts.keys["["] = &callExpr{"jump-prev", nil, 1} gOpts.keys["["] = &callExpr{"jump-prev", nil, 1}
gOpts.keys["]"] = &callExpr{"jump-next", nil, 1} gOpts.keys["]"] = &callExpr{"jump-next", nil, 1}
gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1} gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
@@ -199,7 +223,9 @@ func init() {
gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-complete", nil, 1} gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-complete", nil, 1}
gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1} gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1} gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<down>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1} gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<up>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1} gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1}
@@ -228,6 +254,7 @@ func init() {
gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1} gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1}
gOpts.cmds = make(map[string]expr) gOpts.cmds = make(map[string]expr)
gOpts.user = make(map[string]string)
setDefaults() setDefaults()
} }
+18 -7
View File
@@ -11,13 +11,14 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
"syscall"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
var ( var (
envOpener = os.Getenv("OPENER") envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR") envEditor = os.Getenv("VISUAL")
envPager = os.Getenv("PAGER") envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
) )
@@ -49,9 +50,12 @@ func init() {
} }
} }
if envEditor == "" {
envEditor = os.Getenv("EDITOR")
if envEditor == "" { if envEditor == "" {
envEditor = "vi" envEditor = "vi"
} }
}
if envPager == "" { if envPager == "" {
envPager = "less" envPager = "less"
@@ -63,12 +67,19 @@ func init() {
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
// When the user is not in /etc/passwd (for e.g. LDAP) and CGO_ENABLED=1 in go env,
// the cgo implementation of user.Current() fails even when HOME and USER are set.
log.Printf("user: %s", err) log.Printf("user: %s", err)
if os.Getenv("HOME") == "" { if os.Getenv("HOME") == "" {
log.Print("$HOME variable is empty or not set") panic("$HOME variable is empty or not set")
} }
if os.Getenv("USER") == "" { if os.Getenv("USER") == "" {
log.Print("$USER variable is empty or not set") panic("$USER variable is empty or not set")
}
u = &user.User{
Username: os.Getenv("USER"),
HomeDir: os.Getenv("HOME"),
} }
} }
gUser = u gUser = u
@@ -151,7 +162,7 @@ func setDefaults() {
gOpts.keys["i"] = &execExpr{"$", `$PAGER "$f"`} gOpts.keys["i"] = &execExpr{"$", `$PAGER "$f"`}
gOpts.keys["w"] = &execExpr{"$", "$SHELL"} gOpts.keys["w"] = &execExpr{"$", "$SHELL"}
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}
} }
@@ -177,7 +188,7 @@ 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().(*unix.Stat_t); ok { if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if u, err := user.LookupId(fmt.Sprint(stat.Uid)); err == nil { if u, err := user.LookupId(fmt.Sprint(stat.Uid)); err == nil {
return fmt.Sprintf("%v ", u.Username) return fmt.Sprintf("%v ", u.Username)
} }
@@ -186,7 +197,7 @@ func userName(f os.FileInfo) string {
} }
func groupName(f os.FileInfo) string { func groupName(f os.FileInfo) string {
if stat, ok := f.Sys().(*unix.Stat_t); ok { if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if g, err := user.LookupGroupId(fmt.Sprint(stat.Gid)); err == nil { if g, err := user.LookupGroupId(fmt.Sprint(stat.Gid)); err == nil {
return fmt.Sprintf("%v ", g.Name) return fmt.Sprintf("%v ", g.Name)
} }
@@ -195,7 +206,7 @@ func groupName(f os.FileInfo) string {
} }
func linkCount(f os.FileInfo) string { func linkCount(f os.FileInfo) string {
if stat, ok := f.Sys().(*unix.Stat_t); ok { if stat, ok := f.Sys().(*syscall.Stat_t); ok {
return fmt.Sprintf("%v ", stat.Nlink) return fmt.Sprintf("%v ", stat.Nlink)
} }
return "" return ""
+5 -2
View File
@@ -14,7 +14,7 @@ import (
var ( var (
envOpener = os.Getenv("OPENER") envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR") envEditor = os.Getenv("VISUAL")
envPager = os.Getenv("PAGER") envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
) )
@@ -44,9 +44,12 @@ func init() {
envOpener = `start ""` envOpener = `start ""`
} }
if envEditor == "" {
envEditor = os.Getenv("EDITOR")
if envEditor == "" { if envEditor == "" {
envEditor = "notepad" envEditor = "notepad"
} }
}
if envPager == "" { if envPager == "" {
envPager = "more" envPager = "more"
@@ -115,7 +118,7 @@ func setDefaults() {
gOpts.keys["i"] = &execExpr{"!", "%PAGER% %f%"} gOpts.keys["i"] = &execExpr{"!", "%PAGER% %f%"}
gOpts.keys["w"] = &execExpr{"$", "%SHELL%"} gOpts.keys["w"] = &execExpr{"$", "%SHELL%"}
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}
} }
+1 -2
View File
@@ -2,7 +2,6 @@ package main
import ( import (
"io" "io"
"io/ioutil"
"log" "log"
"strconv" "strconv"
) )
@@ -38,7 +37,7 @@ type scanner struct {
} }
func newScanner(r io.Reader) *scanner { func newScanner(r io.Reader) *scanner {
buf, err := ioutil.ReadAll(r) buf, err := io.ReadAll(r)
if err != nil { if err != nil {
log.Printf("scanning: %s", err) log.Printf("scanning: %s", err)
} }
+1 -1
View File
@@ -61,7 +61,7 @@ func listen(l net.Listener) {
func echoerr(c net.Conn, msg string) { func echoerr(c net.Conn, msg string) {
fmt.Fprintln(c, msg) fmt.Fprintln(c, msg)
log.Printf(msg) log.Print(msg)
} }
func echoerrf(c net.Conn, format string, a ...interface{}) { func echoerrf(c net.Conn, format string, a ...interface{}) {
+368 -234
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) { func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool) {
if reg == nil { if reg == nil {
return return
} }
@@ -260,8 +260,10 @@ func (win *win) printReg(screen tcell.Screen, reg *reg) {
st := tcell.StyleDefault st := tcell.StyleDefault
if reg.loading { if reg.loading {
if previewLoading {
st = st.Reverse(true) st = st.Reverse(true)
win.print(screen, 2, 0, st, "loading...") win.print(screen, 2, 0, st, "loading...")
}
return return
} }
@@ -324,23 +326,63 @@ func fileInfo(f *file, d *dir) string {
return info return info
} }
func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]int, saves map[string]bool, tags map[string]string, colors styleMap, icons iconMap) { type dirContext struct {
selections map[string]int
saves map[string]bool
tags map[string]string
}
type dirRole byte
const (
Active dirRole = iota
Parent
Preview
)
type dirStyle struct {
colors styleMap
icons iconMap
role dirRole
}
// These colors are not currently customizeable
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
} }
messageStyle := tcell.StyleDefault.Reverse(true)
if dir.noPerm { if dir.noPerm {
win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "permission denied") win.print(screen, 2, 0, messageStyle, "permission denied")
return
}
if (dir.loading && len(dir.files) == 0) || (dirStyle.role == Preview && dir.loading && gOpts.dirpreviews) {
if dirStyle.role != Preview || previewLoading {
win.print(screen, 2, 0, messageStyle, "loading...")
}
return return
} }
if dir.loading && len(dir.files) == 0 { if dirStyle.role == Preview && gOpts.dirpreviews && len(gOpts.previewer) > 0 {
win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "loading...") // Print previewer result instead of default directory print operation.
return st := tcell.StyleDefault
for i, l := range dir.lines {
if i > win.h-1 {
break
} }
st = win.print(screen, 2, i, st, l)
}
return
}
if len(dir.files) == 0 { if len(dir.files) == 0 {
win.print(screen, 2, 0, tcell.StyleDefault.Reverse(true), "empty") win.print(screen, 2, 0, messageStyle, "empty")
return return
} }
@@ -352,69 +394,60 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
} }
var lnwidth int var lnwidth int
var lnformat string
if gOpts.number || gOpts.relativenumber { if gOpts.number || gOpts.relativenumber {
lnwidth = 1 lnwidth = 1
if gOpts.number && gOpts.relativenumber { if gOpts.number && gOpts.relativenumber {
lnwidth++ lnwidth++
} }
for j := 10; j < len(dir.files); j *= 10 { for j := 10; j <= len(dir.files); j *= 10 {
lnwidth++ lnwidth++
} }
lnformat = fmt.Sprintf("%%%d.d ", lnwidth)
} }
for i, f := range dir.files[beg:end] { for i, f := range dir.files[beg:end] {
st := colors.get(f) st := dirStyle.colors.get(f)
if lnwidth > 0 { if lnwidth > 0 {
var ln string var ln string
if gOpts.number && (!gOpts.relativenumber) { if gOpts.number && (!gOpts.relativenumber) {
ln = fmt.Sprintf(lnformat, i+1+beg) ln = fmt.Sprintf("%*d", lnwidth, i+1+beg)
} else if gOpts.relativenumber { } else if gOpts.relativenumber {
switch { switch {
case i < dir.pos: case i < dir.pos:
ln = fmt.Sprintf(lnformat, dir.pos-i) ln = fmt.Sprintf("%*d", lnwidth, dir.pos-i)
case i > dir.pos: case i > dir.pos:
ln = fmt.Sprintf(lnformat, i-dir.pos) ln = fmt.Sprintf("%*d", lnwidth, i-dir.pos)
case gOpts.number: case gOpts.number:
ln = fmt.Sprintf(fmt.Sprintf("%%%d.d ", lnwidth-1), i+1+beg) ln = fmt.Sprintf("%*d ", lnwidth-1, i+1+beg)
default: default:
ln = "" ln = fmt.Sprintf("%*d", lnwidth, 0)
} }
} }
win.print(screen, 0, i, tcell.StyleDefault.Foreground(tcell.ColorOlive), ln) win.print(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 := selections[path]; ok { if _, ok := context.selections[path]; ok {
win.print(screen, lnwidth, i, st.Background(tcell.ColorPurple), " ") win.print(screen, lnwidth, i, st.Background(SelectionColor), " ")
} else if cp, ok := saves[path]; ok { } else if cp, ok := context.saves[path]; ok {
if cp { if cp {
win.print(screen, lnwidth, i, st.Background(tcell.ColorOlive), " ") win.print(screen, lnwidth, i, st.Background(YankColor), " ")
} else { } else {
win.print(screen, lnwidth, i, st.Background(tcell.ColorMaroon), " ") win.print(screen, lnwidth, i, st.Background(CutColor), " ")
} }
} }
if i == dir.pos {
st = st.Reverse(true)
}
var s []rune var s []rune
s = append(s, ' ') s = append(s, ' ')
var iwidth int
if gOpts.icons { if gOpts.icons {
s = append(s, []rune(icons.get(f))...) s = append(s, []rune(dirStyle.icons.get(f))...)
s = append(s, ' ') s = append(s, ' ')
iwidth = 2
} }
for _, r := range f.Name() { for _, r := range f.Name() {
@@ -423,44 +456,109 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
w := runeSliceWidth(s) w := runeSliceWidth(s)
if w > win.w-3 { // make space for select marker, and leave another space at the end
s = runeSliceWidthRange(s, 0, win.w-4) 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)...) s = append(s, []rune(gOpts.truncatechar)...)
} else { } else {
for i := 0; i < win.w-3-w; i++ { for i := 0; i < maxlength-w; i++ {
s = append(s, ' ') s = append(s, ' ')
} }
} }
info := fileInfo(f, dir) info := fileInfo(f, dir)
if len(info) > 0 && win.w-lnwidth-iwidth-2 > 2*len(info) { if len(info) > 0 && 2*len(info) < maxlength {
if win.w-2 > w+len(info) { if w+len(info) > maxlength {
s = runeSliceWidthRange(s, 0, win.w-3-len(info)-lnwidth) s = runeSliceWidthRange(s, 0, maxlength-len(info)-1)
} else {
s = runeSliceWidthRange(s, 0, win.w-4-len(info)-lnwidth)
s = append(s, []rune(gOpts.truncatechar)...) s = append(s, []rune(gOpts.truncatechar)...)
} else {
s = runeSliceWidthRange(s, 0, maxlength-len(info))
} }
for _, r := range info { for _, r := range info {
s = append(s, r) s = append(s, r)
} }
} }
ce := ""
if i == dir.pos {
switch dirStyle.role {
case Active:
ce = gOpts.cursoractivefmt
case Parent:
ce = gOpts.cursorparentfmt
case Preview:
ce = gOpts.cursorpreviewfmt
}
}
cursorescapefmt := optionToFmtstr(ce)
s = append(s, ' ') s = append(s, ' ')
styledFilename := fmt.Sprintf(cursorescapefmt, string(s))
win.print(screen, lnwidth+1, i, st, styledFilename)
win.print(screen, lnwidth+1, i, st, string(s)) tag, ok := context.tags[path]
tag, ok := tags[path]
if ok { if ok {
if i == dir.pos { if i == dir.pos {
win.print(screen, lnwidth+1, i, st.Reverse(true), tag) win.print(screen, lnwidth+1, i, st, fmt.Sprintf(cursorescapefmt, tag))
} else { } else {
win.print(screen, lnwidth+1, i, tcell.StyleDefault, fmt.Sprintf(gOpts.tagfmt, tag)) win.print(screen, lnwidth+1, i, tcell.StyleDefault, fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag))
} }
} }
} }
} }
func getWidths(wtot int) []int {
rsum := 0
for _, r := range gOpts.ratios {
rsum += r
}
wlen := len(gOpts.ratios)
widths := make([]int, wlen)
if gOpts.drawbox {
wtot -= (wlen + 1)
}
wsum := 0
for i := 0; i < wlen-1; i++ {
widths[i] = gOpts.ratios[i] * wtot / rsum
wsum += widths[i]
}
widths[wlen-1] = wtot - wsum
return widths
}
func getWins(screen tcell.Screen) []*win {
wtot, htot := screen.Size()
var wins []*win
widths := getWidths(wtot)
wacc := 0
wlen := len(widths)
for i := 0; i < wlen; i++ {
if gOpts.drawbox {
wacc++
wins = append(wins, newWin(widths[i], htot-4, wacc, 2))
} else {
wins = append(wins, newWin(widths[i], htot-2, wacc, 1))
}
wacc += widths[i]
}
return wins
}
type ui struct { type ui struct {
screen tcell.Screen screen tcell.Screen
polling bool polling bool
@@ -476,7 +574,6 @@ type ui struct {
tevChan chan tcell.Event tevChan chan tcell.Event
evChan chan tcell.Event evChan chan tcell.Event
menuBuf *bytes.Buffer menuBuf *bytes.Buffer
menuSelected int
cmdPrefix string cmdPrefix string
cmdAccLeft []rune cmdAccLeft []rune
cmdAccRight []rune cmdAccRight []rune
@@ -486,50 +583,7 @@ type ui struct {
keyCount []rune keyCount []rune
styles styleMap styles styleMap
icons iconMap icons iconMap
} currentFile string
func getWidths(wtot int) []int {
rsum := 0
for _, r := range gOpts.ratios {
rsum += r
}
wlen := len(gOpts.ratios)
widths := make([]int, wlen)
wsum := 0
for i := 0; i < wlen-1; i++ {
widths[i] = gOpts.ratios[i] * wtot / rsum
wsum += widths[i]
}
widths[wlen-1] = wtot - wsum
if gOpts.drawbox {
widths[wlen-1]--
}
return widths
}
func getWins(screen tcell.Screen) []*win {
wtot, htot := screen.Size()
var wins []*win
widths := getWidths(wtot)
wacc := 0
wlen := len(widths)
for i := 0; i < wlen; i++ {
if gOpts.drawbox {
wins = append(wins, newWin(widths[i], htot-4, wacc+1, 2))
} else {
wins = append(wins, newWin(widths[i], htot-2, wacc, 1))
}
wacc += widths[i]
}
return wins
} }
func newUI(screen tcell.Screen) *ui { func newUI(screen tcell.Screen) *ui {
@@ -548,7 +602,7 @@ func newUI(screen tcell.Screen) *ui {
evChan: make(chan tcell.Event, 1000), evChan: make(chan tcell.Event, 1000),
styles: parseStyles(), styles: parseStyles(),
icons: parseIcons(), icons: parseIcons(),
menuSelected: -2, currentFile: "",
} }
go ui.pollEvents() go ui.pollEvents()
@@ -556,6 +610,16 @@ func newUI(screen tcell.Screen) *ui {
return ui return ui
} }
func (ui *ui) winAt(x, y int) (int, *win) {
for i := len(ui.wins) - 1; i >= 0; i-- {
w := ui.wins[i]
if x >= w.x && y >= w.y && y < w.y+w.h {
return i, w
}
}
return -1, nil
}
func (ui *ui) pollEvents() { func (ui *ui) pollEvents() {
var ev tcell.Event var ev tcell.Event
for { for {
@@ -569,21 +633,9 @@ func (ui *ui) pollEvents() {
} }
func (ui *ui) renew() { func (ui *ui) renew() {
ui.wins = getWins(ui.screen)
wtot, htot := ui.screen.Size() wtot, htot := ui.screen.Size()
widths := getWidths(wtot)
wacc := 0
wlen := len(widths)
for i := 0; i < wlen; i++ {
if gOpts.drawbox {
ui.wins[i].renew(widths[i], htot-4, wacc+1, 2)
} else {
ui.wins[i].renew(widths[i], htot-2, wacc, 1)
}
wacc += widths[i]
}
ui.promptWin.renew(wtot, 1, 0, 0) ui.promptWin.renew(wtot, 1, 0, 0)
ui.msgWin.renew(wtot, 1, 0, htot-1) ui.msgWin.renew(wtot, 1, 0, htot-1)
ui.menuWin.renew(wtot, 1, 0, htot-2) ui.menuWin.renew(wtot, 1, 0, htot-2)
@@ -611,12 +663,16 @@ func (ui *ui) echomsg(msg string) {
log.Print(msg) log.Print(msg)
} }
func (ui *ui) echomsgf(format string, a ...interface{}) { func optionToFmtstr(optstr string) string {
ui.echomsg(fmt.Sprintf(format, a...)) if !strings.Contains(optstr, "%s") {
return optstr + "%s\033[0m"
} else {
return optstr
}
} }
func (ui *ui) echoerr(msg string) { func (ui *ui) echoerr(msg string) {
ui.msg = fmt.Sprintf(gOpts.errorfmt, msg) ui.msg = fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg)
log.Printf("error: %s", msg) log.Printf("error: %s", msg)
} }
@@ -632,28 +688,33 @@ type reg struct {
lines []string lines []string
} }
func (ui *ui) loadFile(nav *nav, volatile bool) { func (ui *ui) loadFile(app *app, volatile bool) {
if !nav.init { if !app.nav.init {
return return
} }
curr, err := nav.currFile() curr, err := app.nav.currFile()
if err != nil { if err != nil {
return return
} }
if curr.path != ui.currentFile {
ui.currentFile = curr.path
onSelect(app)
}
if !gOpts.preview { if !gOpts.preview {
return return
} }
if volatile { if volatile {
nav.previewChan <- "" app.nav.previewChan <- ""
} }
if curr.IsDir() { if curr.IsDir() {
ui.dirPrev = nav.loadDir(curr.path) ui.dirPrev = app.nav.loadDir(curr.path)
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
ui.regPrev = nav.loadReg(curr.path, volatile) ui.regPrev = app.nav.loadReg(curr.path, volatile)
} }
} }
@@ -733,6 +794,13 @@ func (ui *ui) drawPromptLine(nav *nav) {
prompt = strings.Replace(prompt, "%F", "", -1) prompt = strings.Replace(prompt, "%F", "", -1)
} }
// spacer
avail := ui.promptWin.w - printLength(prompt) + 2
if avail > 0 {
prompt = strings.Replace(prompt, "%S", strings.Repeat(" ", avail), 1)
}
prompt = strings.Replace(prompt, "%S", "", -1)
ui.promptWin.print(ui.screen, 0, 0, st, prompt) ui.promptWin.print(ui.screen, 0, 0, st, prompt)
} }
@@ -747,7 +815,7 @@ func (ui *ui) drawStatLine(nav *nav) {
ind := min(dir.ind+1, tot) ind := min(dir.ind+1, tot)
acc := string(ui.keyCount) + string(ui.keyAcc) acc := string(ui.keyCount) + string(ui.keyAcc)
var selection string selection := []string{}
if len(nav.saves) > 0 { if len(nav.saves) > 0 {
copy := 0 copy := 0
@@ -760,39 +828,58 @@ func (ui *ui) drawStatLine(nav *nav) {
} }
} }
if copy > 0 { if copy > 0 {
selection += fmt.Sprintf(" \033[33;7m %d \033[0m", copy) selection = append(selection, fmt.Sprintf("\033[33;7m %d \033[0m", copy))
} }
if move > 0 { if move > 0 {
selection += fmt.Sprintf(" \033[31;7m %d \033[0m", move) selection = append(selection, fmt.Sprintf("\033[31;7m %d \033[0m", move))
} }
} }
if len(nav.selections) > 0 { currSelections := nav.currSelections()
selection += fmt.Sprintf(" \033[35;7m %d \033[0m", len(nav.selections)) if len(currSelections) > 0 {
selection = append(selection, fmt.Sprintf("\033[35;7m %d \033[0m", len(currSelections)))
} }
if len(dir.filter) != 0 { progress := []string{}
selection += " \033[34;7m F \033[0m"
}
var progress string
if nav.copyTotal > 0 { if nav.copyTotal > 0 {
percentage := int((100 * float64(nav.copyBytes)) / float64(nav.copyTotal)) percentage := int((100 * float64(nav.copyBytes)) / float64(nav.copyTotal))
progress += fmt.Sprintf(" [%d%%]", percentage) progress = append(progress, fmt.Sprintf("[%d%%]", percentage))
} }
if nav.moveTotal > 0 { if nav.moveTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.moveCount, nav.moveTotal) progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal))
} }
if nav.deleteTotal > 0 { if nav.deleteTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.deleteCount, nav.deleteTotal) progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal))
} }
ruler := fmt.Sprintf("%s%s%s %d/%d", acc, progress, selection, ind, tot) ruler := []string{}
for _, s := range gOpts.ruler {
switch s {
case "df":
df := diskFree(dir.path)
if df != "" {
ruler = append(ruler, df)
}
case "acc":
ruler = append(ruler, acc)
case "progress":
ruler = append(ruler, progress...)
case "selection":
ruler = append(ruler, selection...)
case "filter":
if len(dir.filter) != 0 {
ruler = append(ruler, "\033[34;7m F \033[0m")
}
case "ind":
ruler = append(ruler, fmt.Sprintf("%d/%d", ind, tot))
}
ui.msgWin.printRight(ui.screen, 0, st, ruler) }
ui.msgWin.printRight(ui.screen, 0, st, strings.Join(ruler, " "))
} }
func (ui *ui) drawBox() { func (ui *ui) drawBox() {
@@ -801,34 +888,48 @@ func (ui *ui) drawBox() {
w, h := ui.screen.Size() w, h := ui.screen.Size()
for i := 1; i < w-1; i++ { for i := 1; i < w-1; i++ {
ui.screen.SetContent(i, 1, '─', nil, st) ui.screen.SetContent(i, 1, tcell.RuneHLine, nil, st)
ui.screen.SetContent(i, h-2, '─', nil, st) ui.screen.SetContent(i, h-2, tcell.RuneHLine, nil, st)
} }
for i := 2; i < h-2; i++ { for i := 2; i < h-2; i++ {
ui.screen.SetContent(0, i, '│', nil, st) ui.screen.SetContent(0, i, tcell.RuneVLine, nil, st)
ui.screen.SetContent(w-1, i, '│', nil, st) ui.screen.SetContent(w-1, i, tcell.RuneVLine, nil, st)
} }
ui.screen.SetContent(0, 1, '┌', nil, st) ui.screen.SetContent(0, 1, tcell.RuneULCorner, nil, st)
ui.screen.SetContent(w-1, 1, '┐', nil, st) ui.screen.SetContent(w-1, 1, tcell.RuneURCorner, nil, st)
ui.screen.SetContent(0, h-2, '└', nil, st) ui.screen.SetContent(0, h-2, tcell.RuneLLCorner, nil, st)
ui.screen.SetContent(w-1, h-2, '┘', nil, st) ui.screen.SetContent(w-1, h-2, tcell.RuneLRCorner, nil, st)
wacc := 0 wacc := 0
for wind := 0; wind < len(ui.wins)-1; wind++ { for wind := 0; wind < len(ui.wins)-1; wind++ {
wacc += ui.wins[wind].w wacc += ui.wins[wind].w + 1
ui.screen.SetContent(wacc, 1, '┬', nil, st) ui.screen.SetContent(wacc, 1, tcell.RuneTTee, nil, st)
for i := 2; i < h-2; i++ { for i := 2; i < h-2; i++ {
ui.screen.SetContent(wacc, i, '│', nil, st) ui.screen.SetContent(wacc, i, tcell.RuneVLine, nil, st)
} }
ui.screen.SetContent(wacc, h-2, '┴', nil, st) ui.screen.SetContent(wacc, h-2, tcell.RuneBTee, nil, st)
} }
} }
func (ui *ui) dirOfWin(nav *nav, wind int) *dir {
wins := len(ui.wins)
if gOpts.preview {
wins--
}
ind := len(nav.dirs) - wins + wind
if ind < 0 {
return nil
}
return nav.dirs[ind]
}
func (ui *ui) draw(nav *nav) { func (ui *ui) draw(nav *nav) {
st := tcell.StyleDefault st := tcell.StyleDefault
context := dirContext{selections: nav.selections, saves: nav.saves, tags: nav.tags}
// XXX: manual clean without flush to avoid flicker on Windows
wtot, htot := ui.screen.Size() wtot, htot := ui.screen.Size()
for i := 0; i < wtot; i++ { for i := 0; i < wtot; i++ {
for j := 0; j < htot; j++ { for j := 0; j < htot; j++ {
@@ -838,17 +939,20 @@ func (ui *ui) draw(nav *nav) {
ui.drawPromptLine(nav) ui.drawPromptLine(nav)
length := min(len(ui.wins), len(nav.dirs)) wins := len(ui.wins)
woff := len(ui.wins) - length
if gOpts.preview { if gOpts.preview {
length = min(len(ui.wins)-1, len(nav.dirs)) wins--
woff = len(ui.wins) - 1 - length }
for i := 0; i < wins; i++ {
role := Parent
if i == wins-1 {
role = Active
}
if dir := ui.dirOfWin(nav, i); dir != nil {
ui.wins[i].printDir(ui.screen, dir, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: role},
nav.previewLoading)
} }
doff := len(nav.dirs) - length
for i := 0; i < length; i++ {
ui.wins[woff+i].printDir(ui.screen, nav.dirs[doff+i], nav.selections, nav.saves, nav.tags, ui.styles, ui.icons)
} }
switch ui.cmdPrefix { switch ui.cmdPrefix {
@@ -882,9 +986,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, nav.selections, nav.saves, nav.tags, ui.styles, ui.icons) preview.printDir(ui.screen, ui.dirPrev, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, role: Preview},
nav.previewLoading)
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
preview.printReg(ui.screen, ui.regPrev) preview.printReg(ui.screen, ui.regPrev, nav.previewLoading)
} }
} }
} }
@@ -950,6 +1056,30 @@ func listBinds(binds map[string]expr) *bytes.Buffer {
return b return b
} }
func listJumps(jumps []string, ind int) *bytes.Buffer {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
maxlength := len(strconv.Itoa(max(ind, len(jumps)-1-ind)))
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, " jump\tpath")
// print jumps in order of most recent, Vim uses the opposite order
for i := len(jumps) - 1; i >= 0; i-- {
switch {
case i < ind:
fmt.Fprintf(t, " %*d\t%s\n", maxlength, ind-i, jumps[i])
case i > ind:
fmt.Fprintf(t, " %*d\t%s\n", maxlength, i-ind, jumps[i])
default:
fmt.Fprintf(t, "> %*d\t%s\n", maxlength, 0, jumps[i])
}
}
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)
@@ -1011,9 +1141,9 @@ func (ui *ui) pollEvent() tcell.Event {
// 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").
func (ui *ui) readNormalEvent(ev tcell.Event) expr { func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {
draw := &callExpr{"draw", nil, 1} draw := &callExpr{"draw", nil, 1}
count := 1 count := 0
switch tev := ev.(type) { switch tev := ev.(type) {
case *tcell.EventKey: case *tcell.EventKey:
@@ -1067,11 +1197,15 @@ func (ui *ui) readNormalEvent(ev tcell.Event) expr {
count = c count = c
} }
expr := gOpts.keys[string(ui.keyAcc)] expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok {
e.count = count if e, ok := expr.(*callExpr); ok && count != 0 {
} else if e, ok := expr.(*listExpr); ok { expr = &callExpr{e.name, e.args, e.count}
e.count = count expr.(*callExpr).count = count
} else if e, ok := expr.(*listExpr); ok && count != 0 {
expr = &listExpr{e.exprs, e.count}
expr.(*listExpr).count = count
} }
ui.keyAcc = nil ui.keyAcc = nil
ui.keyCount = nil ui.keyCount = nil
ui.menuBuf = nil ui.menuBuf = nil
@@ -1081,6 +1215,10 @@ func (ui *ui) readNormalEvent(ev tcell.Event) expr {
return draw return draw
} }
case *tcell.EventMouse: case *tcell.EventMouse:
if ui.cmdPrefix != "" {
return nil
}
var button string var button string
switch tev.Buttons() { switch tev.Buttons() {
@@ -1111,22 +1249,71 @@ func (ui *ui) readNormalEvent(ev tcell.Event) expr {
case tcell.ButtonNone: case tcell.ButtonNone:
return nil return nil
} }
if tev.Modifiers() == tcell.ModCtrl {
expr, ok := gOpts.keys[button] button = "<c-" + button[1:]
if !ok { }
if expr, ok := gOpts.keys[button]; ok {
return expr
}
if button != "<m-1>" && button != "<m-2>" {
ui.echoerrf("unknown mapping: %s", button) ui.echoerrf("unknown mapping: %s", button)
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
return draw return draw
} }
return expr x, y := tev.Position()
wind, w := ui.winAt(x, y)
if wind == -1 {
return nil
}
var dir *dir
if gOpts.preview && wind == len(ui.wins)-1 {
curr, err := nav.currFile()
if err != nil {
return nil
} else if !curr.IsDir() || gOpts.dirpreviews {
if tev.Buttons() != tcell.Button2 {
return nil
}
return &callExpr{"open", nil, 1}
}
dir = ui.dirPrev
} else {
dir = ui.dirOfWin(nav, wind)
if dir == nil {
return nil
}
}
var file *file
ind := dir.ind - dir.pos + y - w.y
if ind < len(dir.files) {
file = dir.files[ind]
}
if file != nil {
sel := &callExpr{"select", []string{file.path}, 1}
if tev.Buttons() == tcell.Button1 {
return sel
}
if file.IsDir() {
return &callExpr{"cd", []string{file.path}, 1}
}
return &listExpr{[]expr{sel, &callExpr{"open", nil, 1}}, 1}
}
if tev.Buttons() == tcell.Button1 {
return &callExpr{"cd", []string{dir.path}, 1}
}
case *tcell.EventResize: case *tcell.EventResize:
return &callExpr{"redraw", nil, 1} return &callExpr{"redraw", nil, 1}
case *tcell.EventError: case *tcell.EventError:
log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When()) log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When())
return nil
case *tcell.EventInterrupt: case *tcell.EventInterrupt:
log.Printf("Got EventInterrupt: at %s", tev.When()) log.Printf("Got EventInterrupt: at %s", tev.When())
return nil
} }
return nil return nil
} }
@@ -1153,7 +1340,7 @@ func readCmdEvent(ev tcell.Event) expr {
return nil return nil
} }
func (ui *ui) readEvent(ev tcell.Event) expr { func (ui *ui) readEvent(ev tcell.Event, nav *nav) expr {
if ev == nil { if ev == nil {
return nil return nil
} }
@@ -1162,7 +1349,7 @@ func (ui *ui) readEvent(ev tcell.Event) expr {
return readCmdEvent(ev) return readCmdEvent(ev)
} }
return ui.readNormalEvent(ev) return ui.readNormalEvent(ev, nav)
} }
func (ui *ui) readExpr() { func (ui *ui) readExpr() {
@@ -1186,6 +1373,12 @@ func (ui *ui) resume() error {
return err return err
} }
func (ui *ui) exportSizes() {
w, h := ui.screen.Size()
os.Setenv("lf_width", strconv.Itoa(w))
os.Setenv("lf_height", strconv.Itoa(h))
}
func anyKey() { func anyKey() {
fmt.Print(gOpts.waitmsg) fmt.Print(gOpts.waitmsg)
defer fmt.Print("\n") defer fmt.Print("\n")
@@ -1199,94 +1392,35 @@ func anyKey() {
os.Stdin.Read(b) os.Stdin.Read(b)
} }
func listMatches(screen tcell.Screen, matches []string) (*bytes.Buffer, error) { func listMatches(screen tcell.Screen, matches []string, selectedInd int) *bytes.Buffer {
if len(matches) < 2 {
return nil
}
b := new(bytes.Buffer) b := new(bytes.Buffer)
wtot, _ := screen.Size() wtot, _ := screen.Size()
wcol := 0
for _, m := range matches {
wcol = max(wcol, len(m))
}
wcol += gOpts.tabstop - wcol%gOpts.tabstop
ncol := wtot / wcol
if _, err := b.WriteString("possible matches\n"); err != nil {
return b, err
}
for i := 0; i < len(matches); {
for j := 0; j < ncol && i < len(matches); i, j = i+1, j+1 {
target := matches[i]
if _, err := b.WriteString(fmt.Sprintf("%s%*s", target, wcol-len(target), "")); err != nil {
return nil, err
}
}
if err := b.WriteByte('\n'); err != nil {
return nil, err
}
}
return b, nil
}
func listMatchesMenu(ui *ui, matches []string) error {
b := new(bytes.Buffer)
wtot, _ := ui.screen.Size()
wcol := 0 wcol := 0
for _, m := range matches { for _, m := range matches {
wcol = max(wcol, len(m)) wcol = max(wcol, len(m))
} }
wcol += gOpts.tabstop - wcol%gOpts.tabstop wcol += gOpts.tabstop - wcol%gOpts.tabstop
ncol := max(wtot/wcol, 1)
ncol := wtot / wcol b.WriteString("possible matches\n")
n, err := b.WriteString("possible matches\n")
if err != nil {
return err
}
bytesWrote := n
for i := 0; i < len(matches); { for i := 0; i < len(matches); {
for j := 0; j < ncol && i < len(matches); i, j = i+1, j+1 { for j := 0; j < ncol && i < len(matches); i, j = i+1, j+1 {
target := matches[i] target := matches[i]
// Handle menu tab match only if wanted if selectedInd == i {
if ui.menuSelected == i {
toks := tokenize(string(ui.cmdAccLeft))
last := toks[len(toks)-1]
if strings.Contains(target, last) {
ui.cmdAccLeft = append(ui.cmdAccLeft[:len(ui.cmdAccLeft)-len(last)], []rune(target)...)
} else {
ui.cmdAccLeft = append(ui.cmdAccLeft, []rune(target)...)
}
target = fmt.Sprintf("\033[7m%s\033[0m%*s", target, wcol-len(target), "") target = fmt.Sprintf("\033[7m%s\033[0m%*s", target, wcol-len(target), "")
} else { } else {
target = fmt.Sprintf("%s%*s", target, wcol-len(target), "") target = fmt.Sprintf("%s%*s", target, wcol-len(target), "")
} }
b.WriteString(target)
n, err := b.WriteString(target) }
if err != nil { b.WriteByte('\n')
return err
} }
bytesWrote += n return b
}
if err := b.WriteByte('\n'); err != nil {
return err
}
bytesWrote += 1
}
ui.menuBuf = b
return nil
} }