Compare commits

48 Commits
Author SHA1 Message Date
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
23 changed files with 1641 additions and 1060 deletions

No files matched your search

+23
View File
@@ -15,6 +15,8 @@ jobs:
os: [ubuntu-latest, windows-latest] os: [ubuntu-latest, windows-latest]
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
with:
fetch-depth: 1
- name: Set up Go - name: Set up Go
uses: actions/setup-go@v2 uses: actions/setup-go@v2
@@ -26,3 +28,24 @@ jobs:
- name: Test - name: Test
run: go test -v ./... run: go test -v ./...
- uses: dominikh/staticcheck-action@v1.2.0
with:
version: "2022.1.3"
install-go: false
generate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 1
- name: Set up Go
uses: actions/setup-go@v2
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
+1 -1
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
+19 -5
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,7 +465,7 @@ 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) app.ui.draw(app.nav)
} }
} }
@@ -469,6 +480,7 @@ func (app *app) loop() {
// & No Yes No No No Do nothing // & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) { func (app *app) runShell(s string, args []string, prefix string) {
app.nav.exportFiles() app.nav.exportFiles()
app.ui.exportSizes()
exportOpts() exportOpts()
cmd := shellCommand(s, args) cmd := shellCommand(s, args)
@@ -482,6 +494,8 @@ func (app *app) runShell(s string, args []string, prefix string) {
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)
} }
@@ -526,7 +540,7 @@ func (app *app) runShell(s string, args []string, prefix string) {
anyKey() anyKey()
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
switch prefix { switch prefix {
case "%": case "%":
+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)
} }
} }
+112 -69
View File
@@ -13,7 +13,9 @@ var (
gCmdWords = []string{ gCmdWords = []string{
"set", "set",
"map", "map",
"cmap",
"cmd", "cmd",
"quit",
"up", "up",
"half-up", "half-up",
"page-up", "page-up",
@@ -24,20 +26,38 @@ var (
"scroll-down", "scroll-down",
"updir", "updir",
"open", "open",
"quit", "jump-next",
"jump-prev",
"top", "top",
"bottom", "bottom",
"high",
"middle",
"low",
"toggle", "toggle",
"invert", "invert",
"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 +73,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{
@@ -92,6 +125,9 @@ var (
"dironly", "dironly",
"nodironly", "nodironly",
"dironly!", "dironly!",
"dirpreviews",
"nodirpreviews",
"dirpreviews!",
"drawbox", "drawbox",
"nodrawbox", "nodrawbox",
"drawbox!", "drawbox!",
@@ -151,25 +187,28 @@ var (
"errorfmt", "errorfmt",
"filesep", "filesep",
"hiddenfiles", "hiddenfiles",
"history",
"ifs", "ifs",
"info", "info",
"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 +218,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))
@@ -250,7 +289,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,7 +301,7 @@ 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 := ioutil.ReadDir(dir)
if err != nil { if err != nil {
@@ -271,19 +310,15 @@ func matchFile(s string) (matches []string, longest string) {
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 +334,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) longest = matchLongest(longest, []rune(name))
} else if s != "" { } 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)))
} }
} }
} }
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 +368,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...)
} }
} }
@@ -378,28 +426,24 @@ func completeFile(acc []rune) (matches []string, longestAcc []rune) {
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 = matchLongest(longestAcc, []rune(f.Name()))
} else if s != "" { } else if s != "" {
longest = f.Name() longestAcc = []rune(f.Name())
} }
} }
if longest == "" { if len(longestAcc) < len(acc) {
longest = s longestAcc = acc
} }
longestAcc = []rune(longest)
return return
} }
@@ -407,15 +451,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)
} }
} }
} }
+137 -53
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,6 +31,9 @@ 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')
unselect (default 'u') unselect (default 'u')
@@ -82,6 +85,7 @@ 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>')
@@ -114,6 +118,7 @@ The following options can be used to customize the behavior of lf:
dircounts bool (default off) dircounts bool (default off)
dirfirst bool (default on) dirfirst bool (default on)
dironly bool (default off) dironly bool (default off)
dirpreviews bool (default off)
drawbox bool (default off) drawbox bool (default off)
errorfmt string (default "\033[7;31;47m%s\033[0m") errorfmt string (default "\033[7;31;47m%s\033[0m")
filesep string (default "\n") filesep string (default "\n")
@@ -121,6 +126,7 @@ The following options can be used to customize the behavior of lf:
globsearch bool (default off) globsearch bool (default off)
hidden bool (default off) hidden bool (default off)
hiddenfiles []string (default '.*') hiddenfiles []string (default '.*')
history bool (default on)
icons bool (default off) icons bool (default off)
ifs string (default '') ifs string (default '')
ignorecase bool (default on) ignorecase bool (default on)
@@ -140,6 +146,7 @@ The following options can be used to customize the behavior of lf:
relativenumber bool (default off) relativenumber bool (default off)
reverse bool (default off) reverse bool (default off)
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 '')
@@ -154,6 +161,7 @@ The following options can be used to customize the behavior of lf:
waitmsg string (default 'Press any key to continue') waitmsg string (default 'Press any key to continue')
wrapscan bool (default on) wrapscan bool (default on)
wrapscroll bool (default off) wrapscroll bool (default off)
user_{option} string (default none)
The following environment variables are exported for shell commands: The following environment variables are exported for shell commands:
@@ -169,6 +177,9 @@ The following environment variables are exported for shell commands:
PAGER PAGER
SHELL SHELL
lf_{option} lf_{option}
lf_user_{option}
lf_width
lf_height
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 +189,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 +217,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
Scroll up or down.
# Configuration
Configuration files should be located at: Configuration files should be located at:
@@ -255,7 +278,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.
@@ -295,6 +318,12 @@ Change the current working directory to the next/previous jumplist item.
Move the current file selection to the top/bottom of the directory. Move the current file selection to the top/bottom of the directory.
high (default 'H')
middle (default 'M')
low (default 'L')
Move the current file selection to the high/middle/low of the screen.
toggle toggle
Toggle the selection of the current file or files given as arguments. Toggle the selection of the current file or files given as arguments.
@@ -318,6 +347,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 +490,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 +516,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.
@@ -505,9 +544,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,7 +585,7 @@ 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 # 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'.
@@ -560,7 +603,7 @@ 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) dircache bool (default on)
@@ -569,12 +612,11 @@ Cache directory contents.
dircounts bool (default off) dircounts bool (default off)
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 on)
@@ -582,6 +624,10 @@ Show directories first above regular files.
dironly bool (default off) dironly bool (default off)
If enabled, directories will also be passed to the previewer script. This allows custom previews for directories.
dirpreviews bool (default off)
Show only directories. Show only directories.
drawbox bool (default off) drawbox bool (default off)
@@ -620,6 +666,10 @@ 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.
history bool (default on)
Save command history.
icons bool (default off) icons bool (default off)
Show icons before each item in the list. Show icons before each item in the list.
@@ -699,7 +749,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.
@@ -718,6 +768,12 @@ When 'number' is enabled, current line shows the absolute position, otherwise no
Reverse the direction of sort. Reverse the direction of sort.
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.
@@ -786,7 +842,13 @@ Searching can wrap around the file list.
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').
@@ -841,7 +903,18 @@ If this variable is set in the environment, use the same value, otherwise set th
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.
# Special Commands
This section shows information about special shell commands.
open open
@@ -853,7 +926,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 +940,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,13 +963,13 @@ 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:
@@ -911,9 +988,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 +1021,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 +1081,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 +1104,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 +1115,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 +1126,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 +1134,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 +1148,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 +1169,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 +1216,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 +1233,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 +1274,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 +1285,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 +1303,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 +1318,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 +1326,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 +1345,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 +1396,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 +1435,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 +1558,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'.
+508 -463
View File
File diff suppressed because it is too large. Load diff
+5 -6
View File
@@ -35,11 +35,10 @@ 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
}} }}
@@ -60,7 +59,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
+215 -213
View File
@@ -10,6 +10,8 @@ import (
"time" "time"
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"github.com/gdamore/tcell/v2"
) )
func (e *setExpr) eval(app *app, args []string) { func (e *setExpr) eval(app *app, args []string) {
@@ -43,19 +45,25 @@ func (e *setExpr) eval(app *app, args []string) {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "dirpreviews":
gOpts.dirpreviews = true
case "nodirpreviews":
gOpts.dirpreviews = false
case "dirpreviews!":
gOpts.dirpreviews = !gOpts.dirpreviews
case "nodironly": case "nodironly":
gOpts.dironly = false gOpts.dironly = false
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "dironly!": case "dironly!":
gOpts.dironly = !gOpts.dironly gOpts.dironly = !gOpts.dironly
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "dirfirst": case "dirfirst":
gOpts.sortType.option |= dirfirstSort gOpts.sortType.option |= dirfirstSort
app.nav.sort() app.nav.sort()
@@ -75,7 +83,7 @@ func (e *setExpr) eval(app *app, args []string) {
app.nav.height = app.ui.wins[0].h app.nav.height = app.ui.wins[0].h
app.nav.regCache = make(map[string]*reg) app.nav.regCache = make(map[string]*reg)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "nodrawbox": case "nodrawbox":
gOpts.drawbox = false gOpts.drawbox = false
app.ui.renew() app.ui.renew()
@@ -83,7 +91,7 @@ func (e *setExpr) eval(app *app, args []string) {
app.nav.height = app.ui.wins[0].h app.nav.height = app.ui.wins[0].h
app.nav.regCache = make(map[string]*reg) app.nav.regCache = make(map[string]*reg)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "drawbox!": case "drawbox!":
gOpts.drawbox = !gOpts.drawbox gOpts.drawbox = !gOpts.drawbox
app.ui.renew() app.ui.renew()
@@ -91,40 +99,46 @@ func (e *setExpr) eval(app *app, args []string) {
app.nav.height = app.ui.wins[0].h app.nav.height = app.ui.wins[0].h
app.nav.regCache = make(map[string]*reg) app.nav.regCache = make(map[string]*reg)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "globsearch": case "globsearch":
gOpts.globsearch = true gOpts.globsearch = true
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "noglobsearch": case "noglobsearch":
gOpts.globsearch = false gOpts.globsearch = false
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "globsearch!": case "globsearch!":
gOpts.globsearch = !gOpts.globsearch gOpts.globsearch = !gOpts.globsearch
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "hidden": case "hidden":
gOpts.sortType.option |= hiddenSort gOpts.sortType.option |= hiddenSort
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "nohidden": case "nohidden":
gOpts.sortType.option &= ^hiddenSort gOpts.sortType.option &= ^hiddenSort
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "hidden!": case "hidden!":
gOpts.sortType.option ^= hiddenSort gOpts.sortType.option ^= hiddenSort
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "history":
gOpts.history = true
case "nohistory":
gOpts.history = false
case "history!":
gOpts.history = !gOpts.history
case "icons": case "icons":
gOpts.icons = true gOpts.icons = true
case "noicons": case "noicons":
@@ -135,17 +149,17 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.ignorecase = true gOpts.ignorecase = true
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "noignorecase": case "noignorecase":
gOpts.ignorecase = false gOpts.ignorecase = false
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "ignorecase!": case "ignorecase!":
gOpts.ignorecase = !gOpts.ignorecase gOpts.ignorecase = !gOpts.ignorecase
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "ignoredia": case "ignoredia":
gOpts.ignoredia = true gOpts.ignoredia = true
app.nav.sort() app.nav.sort()
@@ -173,7 +187,7 @@ func (e *setExpr) eval(app *app, args []string) {
case "mouse": case "mouse":
if !gOpts.mouse { if !gOpts.mouse {
gOpts.mouse = true gOpts.mouse = true
app.ui.screen.EnableMouse() app.ui.screen.EnableMouse(tcell.MouseButtonEvents)
} }
case "nomouse": case "nomouse":
if gOpts.mouse { if gOpts.mouse {
@@ -186,7 +200,7 @@ func (e *setExpr) eval(app *app, args []string) {
app.ui.screen.DisableMouse() app.ui.screen.DisableMouse()
} else { } else {
gOpts.mouse = true gOpts.mouse = true
app.ui.screen.EnableMouse() app.ui.screen.EnableMouse(tcell.MouseButtonEvents)
} }
case "number": case "number":
gOpts.number = true gOpts.number = true
@@ -230,17 +244,17 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.smartcase = true gOpts.smartcase = true
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "nosmartcase": case "nosmartcase":
gOpts.smartcase = false gOpts.smartcase = false
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "smartcase!": case "smartcase!":
gOpts.smartcase = !gOpts.smartcase gOpts.smartcase = !gOpts.smartcase
app.nav.sort() app.nav.sort()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "smartdia": case "smartdia":
gOpts.smartdia = true gOpts.smartdia = true
case "nosmartdia": case "nosmartdia":
@@ -332,7 +346,7 @@ func (e *setExpr) eval(app *app, args []string) {
app.nav.sort() app.nav.sort()
app.nav.position() app.nav.position()
app.ui.sort() app.ui.sort()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "ifs": case "ifs":
gOpts.ifs = e.val gOpts.ifs = e.val
case "info": case "info":
@@ -377,7 +391,9 @@ func (e *setExpr) eval(app *app, args []string) {
} }
gOpts.ratios = rats gOpts.ratios = rats
app.ui.wins = getWins(app.ui.screen) app.ui.wins = getWins(app.ui.screen)
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "selmode":
gOpts.selmode = e.val
case "shell": case "shell":
gOpts.shell = e.val gOpts.shell = e.val
case "shellflag": case "shellflag":
@@ -416,6 +432,8 @@ func (e *setExpr) eval(app *app, args []string) {
} else { } else {
gOpts.tempmarks = "'" gOpts.tempmarks = "'"
} }
case "tagfmt":
gOpts.tagfmt = e.val
case "timefmt": case "timefmt":
gOpts.timefmt = e.val gOpts.timefmt = e.val
case "infotimefmtnew": case "infotimefmtnew":
@@ -430,7 +448,12 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.truncatechar = e.val gOpts.truncatechar = e.val
default: default:
// any key with the prefix user_ is accepted as a user defined option
if strings.HasPrefix(e.opt, "user_") {
gOpts.user[e.opt[5:]] = e.val
} else {
app.ui.echoerrf("unknown option: %s", e.opt) app.ui.echoerrf("unknown option: %s", e.opt)
}
return return
} }
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
@@ -476,6 +499,12 @@ func onChdir(app *app) {
} }
} }
func onSelect(app *app) {
if cmd, ok := gOpts.cmds["on-select"]; ok {
cmd.eval(app, nil)
}
}
func splitKeys(s string) (keys []string) { func splitKeys(s string) (keys []string) {
for i := 0; i < len(s); { for i := 0; i < len(s); {
r, w := utf8.DecodeRuneInString(s[i:]) r, w := utf8.DecodeRuneInString(s[i:])
@@ -495,14 +524,59 @@ func splitKeys(s string) (keys []string) {
return return
} }
func doComplete(app *app) (matches []string) {
switch app.ui.cmdPrefix {
case ":":
matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdAccLeft)
case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdAccLeft)
case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdAccLeft)
}
return
}
func menuComplete(app *app, dir int) {
if !app.menuCompActive {
app.ui.cmdTmp = app.ui.cmdAccLeft
app.menuComps = doComplete(app)
if len(app.menuComps) > 1 {
app.menuCompInd = -1
app.menuCompActive = true
}
} else {
app.menuCompInd += dir
if app.menuCompInd == len(app.menuComps) {
app.menuCompInd = 0
} else if app.menuCompInd < 0 {
app.menuCompInd = len(app.menuComps) - 1
}
comp := app.menuComps[app.menuCompInd]
toks := tokenize(string(app.ui.cmdTmp))
last := toks[len(toks)-1]
if app.ui.cmdPrefix != "/" && app.ui.cmdPrefix != "?" {
comp = escape(comp)
_, last = filepath.Split(last)
}
ind := len(app.ui.cmdTmp) - len([]rune(last))
app.ui.cmdAccLeft = append(app.ui.cmdTmp[:ind], []rune(comp)...)
}
app.ui.menuBuf = listMatches(app.ui.screen, app.menuComps, app.menuCompInd)
}
func update(app *app) { func update(app *app) {
// Remove the current menu buffer
app.ui.menuBuf = nil app.ui.menuBuf = nil
app.ui.menuSelected = -2 app.menuCompActive = false
switch { switch {
case gOpts.incsearch && app.ui.cmdPrefix == "/": case gOpts.incsearch && app.ui.cmdPrefix == "/":
app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight) app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight)
if app.nav.search == "" {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
old := dir.ind old := dir.ind
@@ -512,11 +586,14 @@ func update(app *app) {
if _, err := app.nav.searchNext(); err != nil { if _, err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search) app.ui.echoerrf("search: %s: %s", err, app.nav.search)
} else if old != dir.ind { } else if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case gOpts.incsearch && app.ui.cmdPrefix == "?": case gOpts.incsearch && app.ui.cmdPrefix == "?":
app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight) app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight)
if app.nav.search == "" {
return
}
dir := app.nav.currDir() dir := app.nav.currDir()
old := dir.ind old := dir.ind
@@ -526,7 +603,7 @@ func update(app *app) {
if _, err := app.nav.searchPrev(); err != nil { if _, err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search) app.ui.echoerrf("search: %s: %s", err, app.nav.search)
} else if old != dir.ind { } else if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case gOpts.incfilter && app.ui.cmdPrefix == "filter: ": case gOpts.incfilter && app.ui.cmdPrefix == "filter: ":
@@ -537,7 +614,7 @@ func update(app *app) {
if err := app.nav.setFilter(strings.Split(filter, " ")); err != nil { if err := app.nav.setFilter(strings.Split(filter, " ")); err != nil {
app.ui.echoerrf("filter: %s", err) app.ui.echoerrf("filter: %s", err)
} else if old != dir.ind { } else if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -562,7 +639,7 @@ func resetIncCmd(app *app) {
dir.pos = app.nav.searchPos dir.pos = app.nav.searchPos
if dir.ind != app.nav.searchInd { if dir.ind != app.nav.searchInd {
dir.ind = app.nav.searchInd dir.ind = app.nav.searchInd
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} else if gOpts.incfilter && app.ui.cmdPrefix == "filter: " { } else if gOpts.incfilter && app.ui.cmdPrefix == "filter: " {
@@ -570,7 +647,7 @@ func resetIncCmd(app *app) {
old := dir.ind old := dir.ind
app.nav.setFilter(app.nav.prevFilter) app.nav.setFilter(app.nav.prevFilter)
if old != dir.ind { if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -579,12 +656,12 @@ func resetIncCmd(app *app) {
func normal(app *app) { func normal(app *app) {
resetIncCmd(app) resetIncCmd(app)
app.ui.menuBuf = nil app.cmdHistoryInd = 0
app.ui.menuSelected = -2 app.menuCompActive = false
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
app.ui.cmdTmp = nil
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
} }
@@ -604,7 +681,7 @@ func insert(app *app, arg string) {
case 0: case 0:
app.ui.echoerrf("find: pattern not found: %s", app.nav.find) app.ui.echoerrf("find: pattern not found: %s", app.nav.find)
case 1: case 1:
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
default: default:
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
@@ -619,7 +696,7 @@ func insert(app *app, arg string) {
if moved, found := app.nav.findNext(); !found { if moved, found := app.nav.findNext(); !found {
app.ui.echoerrf("find: pattern not found: %s", app.nav.find) app.ui.echoerrf("find: pattern not found: %s", app.nav.find)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -633,7 +710,7 @@ func insert(app *app, arg string) {
case 0: case 0:
app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find) app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find)
case 1: case 1:
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
default: default:
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
@@ -648,7 +725,7 @@ func insert(app *app, arg string) {
if moved, found := app.nav.findPrev(); !found { if moved, found := app.nav.findPrev(); !found {
app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find) app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -658,21 +735,21 @@ func insert(app *app, arg string) {
normal(app) normal(app)
if arg == "y" { if arg == "y" {
if err := app.nav.del(app.ui); err != nil { if err := app.nav.del(app); err != nil {
app.ui.echoerrf("delete: %s", err) app.ui.echoerrf("delete: %s", err)
return return
} }
app.nav.unselect() app.nav.unselect()
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
app.ui.echoerrf("delete: %s", err) app.ui.echoerrf("delete: %s", err)
return return
} }
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case strings.HasPrefix(app.ui.cmdPrefix, "replace"): case strings.HasPrefix(app.ui.cmdPrefix, "replace"):
@@ -685,14 +762,14 @@ func insert(app *app, arg string) {
} }
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
return return
} }
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case strings.HasPrefix(app.ui.cmdPrefix, "create"): case strings.HasPrefix(app.ui.cmdPrefix, "create"):
@@ -709,14 +786,14 @@ func insert(app *app, arg string) {
} }
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
return return
} }
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case app.ui.cmdPrefix == "mark-save: ": case app.ui.cmdPrefix == "mark-save: ":
@@ -758,7 +835,7 @@ func insert(app *app, arg string) {
app.ui.echoerrf("%s", err) app.ui.echoerrf("%s", err)
return return
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
if wd != path { if wd != path {
@@ -785,7 +862,16 @@ func insert(app *app, arg string) {
app.ui.echoerrf("mark-remove: %s", err) app.ui.echoerrf("mark-remove: %s", err)
} }
} }
case app.ui.cmdPrefix == ":" && len(app.ui.cmdAccLeft) == 0:
switch arg {
case "!", "$", "%", "&":
app.ui.cmdPrefix = arg
return
}
fallthrough
default: default:
app.ui.menuBuf = nil
app.menuCompActive = false
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
} }
} }
@@ -797,7 +883,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.up(e.count) { if app.nav.up(e.count) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "half-up": case "half-up":
@@ -805,7 +891,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.up(e.count * app.nav.height / 2) { if app.nav.up(e.count * app.nav.height / 2) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "page-up": case "page-up":
@@ -813,7 +899,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.up(e.count * app.nav.height) { if app.nav.up(e.count * app.nav.height) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "scroll-up": case "scroll-up":
@@ -821,7 +907,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.scrollUp(e.count) { if app.nav.scrollUp(e.count) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "down": case "down":
@@ -829,7 +915,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.down(e.count) { if app.nav.down(e.count) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "half-down": case "half-down":
@@ -837,7 +923,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.down(e.count * app.nav.height / 2) { if app.nav.down(e.count * app.nav.height / 2) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "page-down": case "page-down":
@@ -845,7 +931,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.down(e.count * app.nav.height) { if app.nav.down(e.count * app.nav.height) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "scroll-down": case "scroll-down":
@@ -853,7 +939,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.scrollDown(e.count) { if app.nav.scrollDown(e.count) {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "updir": case "updir":
@@ -868,7 +954,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
restartIncCmd(app) restartIncCmd(app)
onChdir(app) onChdir(app)
@@ -890,7 +976,7 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.echoerrf("opening directory: %s", err) app.ui.echoerrf("opening directory: %s", err)
return return
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
restartIncCmd(app) restartIncCmd(app)
onChdir(app) onChdir(app)
@@ -931,7 +1017,7 @@ func (e *callExpr) eval(app *app, args []string) {
for i := 0; i < e.count; i++ { for i := 0; i < e.count; i++ {
app.nav.cdJumpListPrev() app.nav.cdJumpListPrev()
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
restartIncCmd(app) restartIncCmd(app)
onChdir(app) onChdir(app)
@@ -941,7 +1027,7 @@ func (e *callExpr) eval(app *app, args []string) {
for i := 0; i < e.count; i++ { for i := 0; i < e.count; i++ {
app.nav.cdJumpListNext() app.nav.cdJumpListNext()
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
restartIncCmd(app) restartIncCmd(app)
onChdir(app) onChdir(app)
@@ -952,7 +1038,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.top() { if app.nav.top() {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "bottom": case "bottom":
@@ -960,7 +1046,31 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
if app.nav.bottom() { if app.nav.bottom() {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav)
}
case "high":
if !app.nav.init {
return
}
if app.nav.high() {
app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav)
}
case "middle":
if !app.nav.init {
return
}
if app.nav.middle() {
app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav)
}
case "low":
if !app.nav.init {
return
}
if app.nav.low() {
app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "toggle": case "toggle":
@@ -1103,11 +1213,11 @@ func (e *callExpr) eval(app *app, args []string) {
if cmd, ok := gOpts.cmds["paste"]; ok { if cmd, ok := gOpts.cmds["paste"]; ok {
cmd.eval(app, e.args) cmd.eval(app, e.args)
} else if err := app.nav.paste(app.ui); err != nil { } else if err := app.nav.paste(app); err != nil {
app.ui.echoerrf("paste: %s", err) app.ui.echoerrf("paste: %s", err)
return return
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "delete": case "delete":
if !app.nav.init { if !app.nav.init {
@@ -1119,7 +1229,7 @@ func (e *callExpr) eval(app *app, args []string) {
app.nav.unselect() app.nav.unselect()
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
app.ui.echoerrf("delete: %s", err) app.ui.echoerrf("delete: %s", err)
@@ -1143,7 +1253,7 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.cmdPrefix = "delete " + strconv.Itoa(len(list)) + " items? [y/N] " app.ui.cmdPrefix = "delete " + strconv.Itoa(len(list)) + " items? [y/N] "
} }
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "clear": case "clear":
if !app.nav.init { if !app.nav.init {
@@ -1176,13 +1286,13 @@ func (e *callExpr) eval(app *app, args []string) {
app.nav.height = app.ui.wins[0].h app.nav.height = app.ui.wins[0].h
app.nav.regCache = make(map[string]*reg) app.nav.regCache = make(map[string]*reg)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "load": case "load":
if !app.nav.init { if !app.nav.init {
return return
} }
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
case "reload": case "reload":
if !app.nav.init { if !app.nav.init {
return return
@@ -1190,7 +1300,7 @@ func (e *callExpr) eval(app *app, args []string) {
if err := app.nav.reload(); err != nil { if err := app.nav.reload(); err != nil {
app.ui.echoerrf("reload: %s", err) app.ui.echoerrf("reload: %s", err)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "read": case "read":
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
@@ -1257,7 +1367,7 @@ func (e *callExpr) eval(app *app, args []string) {
} }
} }
if old != dir.ind { if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "find-prev": case "find-prev":
@@ -1274,7 +1384,7 @@ func (e *callExpr) eval(app *app, args []string) {
} }
} }
if old != dir.ind { if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "search": case "search":
@@ -1314,14 +1424,14 @@ func (e *callExpr) eval(app *app, args []string) {
if moved, err := app.nav.searchPrev(); err != nil { if moved, err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search) app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} else { } else {
if moved, err := app.nav.searchNext(); err != nil { if moved, err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search) app.ui.echoerrf("search: %s: %s", err, app.nav.search)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -1335,14 +1445,14 @@ func (e *callExpr) eval(app *app, args []string) {
if moved, err := app.nav.searchNext(); err != nil { if moved, err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search) app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} else { } else {
if moved, err := app.nav.searchPrev(); err != nil { if moved, err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search) app.ui.echoerrf("search: %s: %s", err, app.nav.search)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
} }
@@ -1372,7 +1482,7 @@ func (e *callExpr) eval(app *app, args []string) {
if err := app.nav.setFilter(e.args); err != nil { if err := app.nav.setFilter(e.args); err != nil {
app.ui.echoerrf("filter: %s", err) app.ui.echoerrf("filter: %s", err)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "mark-save": case "mark-save":
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
@@ -1402,7 +1512,7 @@ func (e *callExpr) eval(app *app, args []string) {
cmd.eval(app, e.args) cmd.eval(app, e.args)
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
@@ -1422,7 +1532,7 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.cmdPrefix = "rename: " app.ui.cmdPrefix = "rename: "
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(curr.Name())...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(curr.Name())...)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "sync": case "sync":
if err := app.nav.sync(); err != nil { if err := app.nav.sync(); err != nil {
@@ -1462,7 +1572,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
if wd != path { if wd != path {
@@ -1502,7 +1612,7 @@ func (e *callExpr) eval(app *app, args []string) {
return return
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
if wd != path { if wd != path {
@@ -1554,14 +1664,6 @@ func (e *callExpr) eval(app *app, args []string) {
if len(e.args) == 0 { if len(e.args) == 0 {
return return
} }
// Reset the completition menu as in bash/vim
// and update the pertinent variables
if app.ui.menuBuf != nil {
app.ui.menuBuf = nil
app.ui.menuSelected = -2
}
insert(app, e.args[0]) insert(app, e.args[0])
case "cmd-escape": case "cmd-escape":
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
@@ -1569,118 +1671,15 @@ func (e *callExpr) eval(app *app, args []string) {
} }
normal(app) normal(app)
case "cmd-complete": case "cmd-complete":
var matches []string matches := doComplete(app)
switch app.ui.cmdPrefix { app.ui.menuBuf = listMatches(app.ui.screen, matches, -1)
case ":":
matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdAccLeft)
case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdAccLeft)
case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdAccLeft)
default:
return
}
app.ui.draw(app.nav)
// If there are no multiple matches
// we do not need to show the list of matches
if len(matches) <= 1 {
app.ui.menuBuf = nil
return
}
if b, err := listMatches(app.ui.screen, matches); err != nil {
app.ui.echoerrf("cmd-complete: %s", err)
} else {
app.ui.menuBuf = b
}
case "cmd-menu-complete": case "cmd-menu-complete":
var target []rune menuComplete(app, 1)
// target will store the current menu query
// note that, as we will store the current selected value
// in cmdAccLeft, we can not call the complete function with its
// value, as it is already a final completition result
if app.ui.menuBuf == nil {
target = app.ui.cmdAccLeft
app.ui.cmdTmp = app.ui.cmdAccLeft
} else {
target = app.ui.cmdTmp
}
var matches []string
switch app.ui.cmdPrefix {
case ":":
matches, app.ui.cmdAccLeft = completeCmd(target)
case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(target)
case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(target)
default:
return
}
app.ui.draw(app.nav)
if len(matches) > 1 {
step := 1
// Check if the tab-selecttion was inited
if app.ui.menuSelected == -2 {
app.ui.menuSelected = -1
} else {
app.ui.menuSelected = mod(app.ui.menuSelected+step, len(matches))
}
if err := listMatchesMenu(app.ui, matches); err != nil {
app.ui.echoerrf("cmd-menu-complete: %s", err)
}
} else {
app.ui.menuBuf = nil
app.ui.menuSelected = -2
}
case "cmd-menu-complete-back": case "cmd-menu-complete-back":
var target []rune menuComplete(app, -1)
case "cmd-menu-accept":
if app.ui.menuBuf == nil {
target = app.ui.cmdAccLeft
app.ui.cmdTmp = app.ui.cmdAccLeft
} else {
target = app.ui.cmdTmp
}
var matches []string
switch app.ui.cmdPrefix {
case ":":
matches, app.ui.cmdAccLeft = completeCmd(target)
case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(target)
case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(target)
default:
return
}
app.ui.draw(app.nav)
if len(matches) > 1 {
step := -1
// Check if the tab-selecttion was inited
if app.ui.menuSelected == -2 {
app.ui.menuSelected = -1
} else {
app.ui.menuSelected = mod(app.ui.menuSelected+step, len(matches))
}
if err := listMatchesMenu(app.ui, matches); err != nil {
app.ui.echoerrf("cmd-menu-complete-back: %s", err)
}
} else {
app.ui.menuBuf = nil app.ui.menuBuf = nil
app.ui.menuSelected = -2 app.menuCompActive = false
}
case "cmd-enter": case "cmd-enter":
s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...)) s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...))
if len(s) == 0 && app.ui.cmdPrefix != "filter: " { if len(s) == 0 && app.ui.cmdPrefix != "filter: " {
@@ -1688,11 +1687,10 @@ func (e *callExpr) eval(app *app, args []string) {
} }
app.ui.menuBuf = nil app.ui.menuBuf = nil
app.ui.menuSelected = -2 app.menuCompActive = false
app.ui.cmdAccLeft = nil app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
app.ui.cmdTmp = nil
switch app.ui.cmdPrefix { switch app.ui.cmdPrefix {
case ":": case ":":
@@ -1741,7 +1739,7 @@ func (e *callExpr) eval(app *app, args []string) {
if _, err := app.nav.searchNext(); err != nil { if _, err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search) app.ui.echoerrf("search: %s: %s", err, app.nav.search)
} else if old != dir.ind { } else if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "?": case "?":
@@ -1757,7 +1755,7 @@ func (e *callExpr) eval(app *app, args []string) {
if _, err := app.nav.searchPrev(); err != nil { if _, err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search) app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
} else if old != dir.ind { } else if old != dir.ind {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "filter: ": case "filter: ":
@@ -1766,14 +1764,14 @@ func (e *callExpr) eval(app *app, args []string) {
if err := app.nav.setFilter(strings.Split(s, " ")); err != nil { if err := app.nav.setFilter(strings.Split(s, " ")); err != nil {
app.ui.echoerrf("filter: %s", err) app.ui.echoerrf("filter: %s", err)
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "find: ": case "find: ":
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
if moved, found := app.nav.findNext(); !found { if moved, found := app.nav.findNext(); !found {
app.ui.echoerrf("find: pattern not found: %s", app.nav.find) app.ui.echoerrf("find: pattern not found: %s", app.nav.find)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "find-back: ": case "find-back: ":
@@ -1781,7 +1779,7 @@ func (e *callExpr) eval(app *app, args []string) {
if moved, found := app.nav.findPrev(); !found { if moved, found := app.nav.findPrev(); !found {
app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find) app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find)
} else if moved { } else if moved {
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
case "rename: ": case "rename: ":
@@ -1833,7 +1831,7 @@ func (e *callExpr) eval(app *app, args []string) {
if gSingleMode { if gSingleMode {
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
} else { } else {
if err := remote("send load"); err != nil { if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err) app.ui.echoerrf("rename: %s", err)
@@ -1841,7 +1839,7 @@ func (e *callExpr) eval(app *app, args []string) {
} }
} }
app.ui.loadFile(app.nav, true) app.ui.loadFile(app, true)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
} }
default: default:
@@ -1855,31 +1853,27 @@ func (e *callExpr) eval(app *app, args []string) {
app.cmdHistoryInd-- app.cmdHistoryInd--
} }
if app.cmdHistoryInd == 0 { if app.cmdHistoryInd == 0 {
app.ui.menuBuf = nil normal(app)
app.ui.menuSelected = -2
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdTmp = nil
app.ui.cmdPrefix = ":" app.ui.cmdPrefix = ":"
return return
} }
cmd := app.cmdHistory[len(app.cmdHistory)-app.cmdHistoryInd] historyInd := app.cmdHistoryInd
cmd := app.cmdHistory[len(app.cmdHistory)-historyInd]
normal(app) normal(app)
app.cmdHistoryInd = historyInd
app.ui.cmdPrefix = cmd.prefix app.ui.cmdPrefix = cmd.prefix
app.ui.cmdAccLeft = []rune(cmd.value) app.ui.cmdAccLeft = []rune(cmd.value)
case "cmd-history-prev": case "cmd-history-prev":
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return
} }
if app.ui.cmdPrefix == "" {
app.cmdHistoryInd = 0
}
if app.cmdHistoryInd == len(app.cmdHistory) { if app.cmdHistoryInd == len(app.cmdHistory) {
return return
} }
app.cmdHistoryInd++ historyInd := app.cmdHistoryInd + 1
cmd := app.cmdHistory[len(app.cmdHistory)-app.cmdHistoryInd] cmd := app.cmdHistory[len(app.cmdHistory)-historyInd]
normal(app) normal(app)
app.cmdHistoryInd = historyInd
app.ui.cmdPrefix = cmd.prefix app.ui.cmdPrefix = cmd.prefix
app.ui.cmdAccLeft = []rune(cmd.value) app.ui.cmdAccLeft = []rune(cmd.value)
case "cmd-delete": case "cmd-delete":
@@ -1890,6 +1884,14 @@ func (e *callExpr) eval(app *app, args []string) {
update(app) update(app)
case "cmd-delete-back": case "cmd-delete-back":
if len(app.ui.cmdAccLeft) == 0 { if len(app.ui.cmdAccLeft) == 0 {
switch app.ui.cmdPrefix {
case "!", "$", "%", "&":
app.ui.cmdPrefix = ":"
case ">":
// Don't mess with the program waiting for input
default:
normal(app)
}
return return
} }
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1]
+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
+5 -5
View File
@@ -3,9 +3,9 @@ module github.com/gokcehan/lf
go 1.12 go 1.12
require ( require (
github.com/gdamore/tcell/v2 v2.3.1 github.com/gdamore/tcell/v2 v2.5.4-0.20221019011350-d3cbfcfb7aa3
github.com/mattn/go-runewidth v0.0.10 github.com/mattn/go-runewidth v0.0.14
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d golang.org/x/term v0.0.0-20210927222741-03fcf44c2211
gopkg.in/djherbis/times.v1 v1.2.0 github.com/djherbis/times v1.5.0
) )
+35 -16
View File
@@ -1,20 +1,39 @@
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.5.4-0.20221019011350-d3cbfcfb7aa3 h1:e5DXSPPfOBDJY9Z0geFZjEDok0/cUEI5QlPeTmqPV4I=
github.com/gdamore/tcell/v2 v2.3.1/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU= github.com/gdamore/tcell/v2 v2.5.4-0.20221019011350-d3cbfcfb7aa3/go.mod h1:XmCynGHvvGG7UFI6az9zzoEHBvZB1PGf5APwOJMFUyE=
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 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
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 h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
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.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
golang.org/x/text v0.4.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=
github.com/djherbis/times v1.5.0 h1:79myA211VwPhFTqUk8xehWrsEO+zcIZj0zT8mXPVARU=
github.com/djherbis/times v1.5.0/go.mod h1:5q7FDLvbNg1L/KaBmPcWlVR9NmoKo3+ucqUA3ijQhA0=
+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
} }
+130 -24
View File
@@ -46,6 +46,9 @@ 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')
unselect (default 'u') unselect (default 'u')
@@ -99,6 +102,7 @@ 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>')
@@ -133,6 +137,7 @@ The following options can be used to customize the behavior of lf:
dircounts bool (default off) dircounts bool (default off)
dirfirst bool (default on) dirfirst bool (default on)
dironly bool (default off) dironly bool (default off)
dirpreviews bool (default off)
drawbox bool (default off) drawbox bool (default off)
errorfmt string (default "\e033[7;31;47m%s\e033[0m") errorfmt string (default "\e033[7;31;47m%s\e033[0m")
filesep string (default "\en") filesep string (default "\en")
@@ -140,6 +145,7 @@ The following options can be used to customize the behavior of lf:
globsearch bool (default off) globsearch bool (default off)
hidden bool (default off) hidden bool (default off)
hiddenfiles []string (default '.*') hiddenfiles []string (default '.*')
history bool (default on)
icons bool (default off) icons bool (default off)
ifs string (default '') ifs string (default '')
ignorecase bool (default on) ignorecase bool (default on)
@@ -159,6 +165,7 @@ The following options can be used to customize the behavior of lf:
relativenumber bool (default off) relativenumber bool (default off)
reverse bool (default off) reverse bool (default off)
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 '')
@@ -173,6 +180,7 @@ The following options can be used to customize the behavior of lf:
waitmsg string (default 'Press any key to continue') waitmsg string (default 'Press any key to continue')
wrapscan bool (default on) wrapscan bool (default on)
wrapscroll bool (default off) wrapscroll bool (default off)
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:
@@ -190,6 +198,9 @@ The following environment variables are exported for shell commands:
PAGER PAGER
SHELL SHELL
lf_{option} lf_{option}
lf_user_{option}
lf_width
lf_height
.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 +212,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 +244,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
Scroll up or down.
.EE
.SH CONFIGURATION .SH CONFIGURATION
Configuration files should be located at: Configuration files should be located at:
.PP .PP
@@ -343,6 +372,14 @@ Change the current working directory to the next/previous jumplist item.
.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.
.PP .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
.EX .EX
toggle toggle
.EE .EE
@@ -372,7 +409,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 +604,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 +629,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
@@ -623,10 +670,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>')
@@ -693,7 +745,7 @@ 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) dircache bool (default on)
@@ -705,7 +757,7 @@ Cache directory contents.
dircounts bool (default off) dircounts bool (default off)
.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 on)
@@ -717,6 +769,12 @@ Show directories first above regular files.
dironly bool (default off) dironly bool (default off)
.EE .EE
.PP .PP
If enabled, directories will also be passed to the previewer script. This allows custom previews for directories.
.PP
.EX
dirpreviews bool (default off)
.EE
.PP
Show only directories. Show only directories.
.PP .PP
.EX .EX
@@ -761,6 +819,12 @@ Show hidden files. On Unix systems, hidden files are determined by the value of
.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.
.PP .PP
.EX
history bool (default on)
.EE
.PP
Save command history.
.PP
.EX .EX
icons bool (default off) icons bool (default off)
.EE .EE
@@ -849,7 +913,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')
@@ -869,6 +933,12 @@ Show the position number relative to the current line. When 'number' is enabled,
.PP .PP
Reverse the direction of sort. Reverse the direction of sort.
.PP .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
@@ -958,6 +1028,12 @@ Searching can wrap around the file list.
.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
@@ -1032,11 +1108,26 @@ If this variable is set in the environment, use the same value, otherwise set th
.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.
.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 +1140,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 +1160,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,7 +1190,7 @@ 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
@@ -1116,10 +1213,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 +1363,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 +1373,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 +1384,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 +1394,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 +1451,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 +1497,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 +1523,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 +1532,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 +1553,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
+5
View File
@@ -152,6 +152,11 @@ 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 := e.Field(i)
value := fieldToString(field) value := fieldToString(field)
+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
+195 -36
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
@@ -403,7 +406,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
} }
@@ -447,6 +454,9 @@ func (nav *nav) checkDir(dir *dir) {
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 ||
@@ -490,6 +500,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),
@@ -599,6 +610,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 +640,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 +677,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 }()
@@ -943,6 +1039,53 @@ 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) 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)
@@ -1037,20 +1180,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 +1213,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 +1221,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 +1255,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 +1265,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 +1281,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 +1301,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 +1311,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 +1326,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 +1353,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 +1374,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 +1392,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 +1400,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
} }
} }
}() }()
@@ -1306,7 +1449,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 +1457,9 @@ func (nav *nav) sync() error {
} }
} }
err = nav.readTags() err = nav.readTags()
if errMarks != nil {
return errMarks
}
return err return err
} }
@@ -1620,9 +1766,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 +1838,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 {
+13
View File
@@ -33,6 +33,7 @@ var gOpts struct {
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 +60,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,11 +69,13 @@ var gOpts struct {
truncatechar string truncatechar string
ratios []int ratios []int
hiddenfiles []string hiddenfiles []string
history bool
info []string info []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
tagfmt string tagfmt string
@@ -83,6 +87,7 @@ 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.globsearch = false gOpts.globsearch = false
gOpts.icons = false gOpts.icons = false
@@ -109,6 +114,7 @@ func init() {
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,6 +123,7 @@ 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.shellopts = nil gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort} gOpts.sortType = sortType{naturalSort, dirfirstSort}
@@ -127,12 +134,14 @@ func init() {
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["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}
@@ -146,6 +155,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}
@@ -228,6 +240,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()
} }
+13 -5
View File
@@ -11,6 +11,7 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
"syscall"
"golang.org/x/sys/unix" "golang.org/x/sys/unix"
) )
@@ -63,12 +64,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
@@ -177,7 +185,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 +194,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 +203,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 ""
+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{}) {
+212 -151
View File
@@ -324,23 +324,54 @@ 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 dirStyle struct {
colors styleMap
icons iconMap
previewing bool
}
// These colors are not currently customizeable
const LineNumberColor = tcell.ColorOlive
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) {
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.previewing && dir.loading && gOpts.dirpreviews) {
win.print(screen, 2, 0, messageStyle, "loading...")
return return
} }
if dir.loading && len(dir.files) == 0 { if dirStyle.previewing && 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
} }
@@ -366,7 +397,7 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
} }
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
@@ -386,18 +417,18 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
} }
} }
win.print(screen, 0, i, tcell.StyleDefault.Foreground(tcell.ColorOlive), ln) win.print(screen, 0, i, tcell.StyleDefault.Foreground(LineNumberColor), 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), " ")
} }
} }
@@ -412,7 +443,7 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
var iwidth int 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 iwidth = 2
} }
@@ -450,10 +481,10 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
win.print(screen, lnwidth+1, i, st, string(s)) win.print(screen, lnwidth+1, i, st, string(s))
tag, ok := tags[path] tag, ok := context.tags[path]
if ok { if ok {
if i == dir.pos { if i == dir.pos {
win.print(screen, lnwidth+1, i, st.Reverse(true), tag) win.print(screen, lnwidth+1, i, st, 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(gOpts.tagfmt, tag))
} }
@@ -461,33 +492,6 @@ func (win *win) printDir(screen tcell.Screen, dir *dir, selections map[string]in
} }
} }
type ui struct {
screen tcell.Screen
polling bool
wins []*win
promptWin *win
msgWin *win
menuWin *win
msg string
regPrev *reg
dirPrev *dir
exprChan chan expr
keyChan chan string
tevChan chan tcell.Event
evChan chan tcell.Event
menuBuf *bytes.Buffer
menuSelected int
cmdPrefix string
cmdAccLeft []rune
cmdAccRight []rune
cmdYankBuf []rune
cmdTmp []rune
keyAcc []rune
keyCount []rune
styles styleMap
icons iconMap
}
func getWidths(wtot int) []int { func getWidths(wtot int) []int {
rsum := 0 rsum := 0
for _, r := range gOpts.ratios { for _, r := range gOpts.ratios {
@@ -532,6 +536,33 @@ func getWins(screen tcell.Screen) []*win {
return wins return wins
} }
type ui struct {
screen tcell.Screen
polling bool
wins []*win
promptWin *win
msgWin *win
menuWin *win
msg string
regPrev *reg
dirPrev *dir
exprChan chan expr
keyChan chan string
tevChan chan tcell.Event
evChan chan tcell.Event
menuBuf *bytes.Buffer
cmdPrefix string
cmdAccLeft []rune
cmdAccRight []rune
cmdYankBuf []rune
cmdTmp []rune
keyAcc []rune
keyCount []rune
styles styleMap
icons iconMap
currentFile string
}
func newUI(screen tcell.Screen) *ui { func newUI(screen tcell.Screen) *ui {
wtot, htot := screen.Size() wtot, htot := screen.Size()
@@ -548,7 +579,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 +587,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 {
@@ -611,10 +652,6 @@ func (ui *ui) echomsg(msg string) {
log.Print(msg) log.Print(msg)
} }
func (ui *ui) echomsgf(format string, a ...interface{}) {
ui.echomsg(fmt.Sprintf(format, a...))
}
func (ui *ui) echoerr(msg string) { func (ui *ui) echoerr(msg string) {
ui.msg = fmt.Sprintf(gOpts.errorfmt, msg) ui.msg = fmt.Sprintf(gOpts.errorfmt, msg)
log.Printf("error: %s", msg) log.Printf("error: %s", msg)
@@ -632,28 +669,34 @@ 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 {
return
}
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 +776,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)
} }
@@ -767,8 +817,9 @@ func (ui *ui) drawStatLine(nav *nav) {
} }
} }
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 += fmt.Sprintf(" \033[35;7m %d \033[0m", len(currSelections))
} }
if len(dir.filter) != 0 { if len(dir.filter) != 0 {
@@ -826,8 +877,21 @@ func (ui *ui) drawBox() {
} }
} }
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}
wtot, htot := ui.screen.Size() wtot, htot := ui.screen.Size()
for i := 0; i < wtot; i++ { for i := 0; i < wtot; i++ {
@@ -838,17 +902,15 @@ 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++ {
if dir := ui.dirOfWin(nav, i); dir != nil {
ui.wins[i].printDir(ui.screen, dir, &context,
&dirStyle{colors: ui.styles, icons: ui.icons, previewing: false})
} }
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,7 +944,8 @@ 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, previewing: true})
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
preview.printReg(ui.screen, ui.regPrev) preview.printReg(ui.screen, ui.regPrev)
} }
@@ -1011,9 +1074,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 +1130,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 +1148,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 +1182,65 @@ func (ui *ui) readNormalEvent(ev tcell.Event) expr {
case tcell.ButtonNone: case tcell.ButtonNone:
return nil return nil
} }
if expr, ok := gOpts.keys[button]; ok {
expr, ok := gOpts.keys[button] return expr
if !ok {
ui.echoerrf("unknown mapping: %s", button)
return draw
} }
return expr if tev.Buttons() != tcell.Button1 && tev.Buttons() != tcell.Button2 {
return nil
}
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 +1267,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 +1276,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 +1300,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 +1319,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 := wtot / wcol ncol := wtot / wcol
n, err := b.WriteString("possible matches\n") 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
} }