Compare commits

130 Commits
Author SHA1 Message Date
Gokcehan 228a20ffd1 rename bs to backspace 2020-10-10 17:34:29 +03:00
Gokcehan 8979e2b260 update cross build script 2020-10-10 16:53:52 +03:00
Gokcehan 6a286673ce initialize hiddenfiles for loading directories
Related #478
2020-10-06 22:24:55 +03:00
Gokcehan 4c89535e18 add descriptions of variables to the documentation 2020-10-02 23:37:39 +03:00
Gokcehan 88749a3da1 check hiddenfiles option for dir updates
Related #476
2020-10-02 21:50:55 +03:00
Alexey Yerin cf79726d21 feat: add ability to map lone <esc> (#475)
Since d2414f7580 <esc> resets key buffer
but this feature prevents binding lone <esc>
2020-10-02 21:30:31 +03:00
Gokcehan 50dd374f77 fix race in previews with lazy drawing
Related #445
2020-09-25 23:08:29 +03:00
Gokcehan 1460f49b3e update readme 2020-09-24 23:38:09 +03:00
Gokcehan 969dee3621 add descriptions of options to the documentation
Related #321
2020-09-24 02:00:36 +03:00
Gokcehan 36798b4c24 update doc
Related #469
2020-09-22 04:22:08 +03:00
gotroyb127 7a3bd15903 always export lf_options before previewing (#468)
* always export lf_options before previewing

related functions were moved to `os.go`
and now exportOpts isn't called through
an app, so it can be called independently

* move related functions to main.go

so they get compiled on windows too
2020-09-18 00:50:45 +03:00
Gokcehan 76c85d9459 add descriptions of cmds to the documentation
Related #321
2020-09-13 18:14:25 +03:00
Gokcehan 355075cf75 cleanup 2020-09-13 14:55:17 +03:00
Himujjal Upadhyaya 1186bf6382 [Minor Fix]: Doc update for Windows Users (#465)
A minor change was fixed in `doc.go:142` for Windows Users. Clear instructions for using `$f`, `$fs`, `$fx` and `$id` in Windows as `%f%`, `%fs%`, `%fx%` and `%id%`.
2020-09-10 19:17:09 +03:00
Provessor 61442f8880 A more robust server starting mechanism (#463)
now lf will start the server in the current directory (which will then
Chdir to the user's home directory) to ensure it is always starting as
the user intended.
2020-09-09 14:08:52 +03:00
Gokcehan ec512dfe31 read events in the main loop
Related #445
2020-09-07 18:40:57 +03:00
gotroyb127 f248ce77a1 fixes 'numbers are bold when the filename is bold' (#462)
* fixes 'numbers are bold when the filename is bold'

* do it correctly
2020-09-06 17:52:11 +03:00
Gokcehan 3c8b5a5630 avoid overwriting messages after shell commands
Related #441
2020-09-05 17:41:17 +03:00
Gokcehan b608682580 load modified previews after shell-pipe commands 2020-09-05 14:09:52 +03:00
Gokcehan ab6549679b rename backspace/backspace2 to bs/bs2 again
Related #445
2020-09-05 12:56:12 +03:00
Gokcehan 5e9580500c show loading directories with previous file list
Related #414
2020-09-05 12:55:27 +03:00
Gokcehan ebf3bcc76b resume with a new goroutine instead of busy wait
Related #461
2020-09-05 12:36:31 +03:00
Gokcehan f1f28018a6 add missing keys for push command
Related #445
2020-09-04 23:59:20 +03:00
Gokcehan b40ebdcb33 fix regular keys in push commands
Related #445
2020-09-04 21:25:19 +03:00
Gokcehan 4f5b4e6dbf remove manual escape delaying mechanism
Related #459
2020-09-04 18:25:40 +03:00
Gokcehan 4f02cf47c7 use the same input goroutine when ui is resumed
Related #459
2020-09-04 18:07:50 +03:00
Gokcehan eab7b61846 only listen 127.0.0.1 in the server
Related #456
2020-09-02 00:43:55 +03:00
Gokcehan 658af50006 do not crash with corrupted history entries
Related #455
2020-09-01 23:57:40 +03:00
Gokcehan bc0000f274 go mod tidy
Related #439
2020-09-01 23:10:16 +03:00
Provessor 24f01f4988 Replace termbox-go with tcell (#439)
Fix colour construction issue

This also has a test to mitigate it in the future

Remove `colormode` option

The original issue it was trying to solve is no longer present with
tcell (it being a holdover from `color256` on termbox) so it is not
needed.

retire gitter channel in favor of irc/matrix

Export options as environment variables (#448)

* Export options as environment variables

Any options from gOpts are available via lf_OPTION environment
variables. For now it works only on booleans, integers and strings (no
array support)

* Do not export some of the options

* Add support for arrays and fix numbers

* Fix comments

* Replace 1 and 0 with true and false

* Export hidden,reverse,dirfirst and sortby options

* Fix comments

* Little fix

* Simplify boolean conversion

log readlink errors instead of fail

Related #447 and #374
2020-09-01 15:42:44 +03:00
Gokcehan d25faf7186 add descriptions of commands to the documentation
Related #321
2020-09-01 00:00:38 +03:00
Gokcehan e36b1b0484 set travis version to go1.15.x 2020-08-20 02:19:34 +03:00
Gokcehan 1d95991054 remove redundant syncs in cross build script 2020-08-20 02:18:52 +03:00
Gokcehan fa45a8b649 go mod tidy 2020-08-20 02:16:23 +03:00
Gokcehan 1c8def356d log readlink errors instead of fail
Related #447 and #374
2020-08-19 23:35:42 +03:00
Alexey Yerin 25c2f037cb Export options as environment variables (#448)
* Export options as environment variables

Any options from gOpts are available via lf_OPTION environment
variables. For now it works only on booleans, integers and strings (no
array support)

* Do not export some of the options

* Add support for arrays and fix numbers

* Fix comments

* Replace 1 and 0 with true and false

* Export hidden,reverse,dirfirst and sortby options

* Fix comments

* Little fix

* Simplify boolean conversion
2020-08-19 23:05:50 +03:00
Gokcehan 143de6e7eb retire gitter channel in favor of irc/matrix 2020-08-02 04:00:48 +03:00
Gokcehan 2b445aa205 update doc 2020-07-26 00:29:50 +03:00
Gokcehan d2414f7580 escape key disables key binding lookup
Related #361
2020-07-26 00:24:04 +03:00
Gokcehan 8be63a9c83 cleanup 2020-07-22 01:55:21 +03:00
Alexey Yerin c630293cc2 Print message in status line after copying/moving (#427)
* Print message in status line after copying/moving

* Print message only when there's no errors

* Don't print number of copied files

* Fix error handling

* Send message to channel instead of direct ui.echo
2020-07-22 01:53:02 +03:00
Gokcehan 9c891307f3 cleanup 2020-07-20 02:47:33 +03:00
Gokcehan 9539daf8df handle relative paths in 'toggle' command 2020-07-20 02:22:31 +03:00
Gokcehan 7174b7e307 handle broken links with 'select' command
Related #201
2020-07-20 02:15:30 +03:00
Gokcehan 6d1a840587 handle unicode characters in 'push' command
Related #250
2020-07-20 01:36:22 +03:00
Gokcehan 490a4a9d07 clear previous errors in prompting commands
Related #185
2020-07-20 01:09:54 +03:00
Gokcehan a6544757db cleanup 2020-07-20 00:44:37 +03:00
Gokcehan f8daa60b31 expand '%w' in 'promptfmt' with a trailing slash
Related #421
2020-07-20 00:19:42 +03:00
Alexey Yerin 3b49e1a2b6 Add check for truncatechar (#420)
* Add check for truncatechar

When value is longer than 1 character, it throws an error

* Use runeSliceWidth instead of len
2020-07-19 21:28:06 +03:00
Alexey Yerin d0cd181eb6 Ability to customize filename truncating (#417)
* Add truncatechar option

* Add ability to set truncatechar via `set` command

* Add completion for truncatechar option

* Actually use truncatechar option when truncating

* Add truncatechar option to docs
2020-07-18 03:08:25 +03:00
Gokcehan 9880104c12 quote filenames in prompts 2020-07-17 02:17:24 +03:00
Gokcehan ffdcb71897 make select work properly with loading directories
Related #370
2020-07-17 02:12:10 +03:00
Gokcehan 707d927788 handle abs paths in rename 2020-07-17 00:46:46 +03:00
Gokcehan 0a22e7c5c8 check reg and dir while loading 2020-07-17 00:33:37 +03:00
Gokcehan 2f056ad359 select new file after rename
Related #197
2020-07-17 00:28:32 +03:00
Gokcehan e7fb56391f remove redundant parameter in ui renew 2020-07-16 23:17:11 +03:00
Gokcehan 3e36500901 check modtime/sorting again when dirs are updated
Related #338
2020-07-16 23:13:40 +03:00
gotroyb127 f2e3c7a0ce shell-async commands now don't create zombie processes (#407) 2020-07-14 19:44:13 +03:00
gotroyb127 75e59cdd08 'toggle' command now toggles selection on its arguments when at least one (#409)
* 'toggle' command now toggles selection on its arguments when given and some cleanup

* update doc
2020-07-14 19:28:01 +03:00
Doron Behar 001ee5bfae Update termbox related modules to fix #392 (#404) 2020-07-11 22:28:34 +03:00
Gokcehan e1b939bf7c skip trailing spaces in scanner
Related #301
2020-07-04 04:07:01 +03:00
Gokcehan ce4ea6ea53 start server process in home directory
Related #287
2020-07-04 03:41:37 +03:00
Gokcehan 45552cf809 use correct search directions with incsearch
Related #284
2020-07-04 03:32:05 +03:00
Gokcehan c937dab9e9 remove hidden cursor movement
Related #22 and #381
2020-07-04 01:21:07 +03:00
Gokcehan 1119ba0d25 expand tab characters to spaces 2020-07-04 01:08:35 +03:00
Gokcehan 83a6e506d2 implement hidden option in windows 2020-07-04 00:41:12 +03:00
Gokcehan bc2a80fd6e handle cross-device linking in windows 2020-07-04 00:16:16 +03:00
Gokcehan e2bf773f3b fallback to copy-del for cross-device linking
Related #151
2020-07-03 21:42:13 +03:00
gotroyb127 4d3e1cfd6e added a count field to listExpr and toggle now ignores count (#394) 2020-07-03 18:29:55 +03:00
Gokcehan fd73a53f84 update doc
Related #352 and #386
2020-06-17 06:35:28 +03:00
Ivan Podmazov cbb559346d fix toggle behaviour (#352) (#386) 2020-06-17 06:17:30 +03:00
Gokcehan 5d1136abfe keep the destination file before rename
Related #343
2020-06-17 05:19:16 +03:00
Gokcehan 0e3910652a cleanup 2020-06-11 04:11:40 +03:00
Gokcehan 99cee56d6e reload directories when 'hiddenfiles' is changed 2020-06-11 03:16:24 +03:00
Gokcehan 25e487cc51 check pattern errors when 'hiddenfiles' is set 2020-06-11 03:14:45 +03:00
Adam Abrams 72facea2a0 add hiddenFiles option (#372)
* add hiddenFiles option

* harden and improve syntax

* refactor name and add to docs
2020-06-11 02:52:15 +03:00
wedensandwedens 8933a3eafe show symlink destination (#374)
Co-authored-by: wedens <kirill.wedens@gmail.com>
2020-06-09 02:38:46 +03:00
gotroyb127 41e0bb32cd fix tilde expansion and numbering (#373)
* Fixed issue #346 and changed the format of numbers when both relativenumber and number are set.

* Fixed issue #349 (incorrect replacement of '~' with user's home direcotry).

* Changed where appropriate so that tilde replacements happens correctly.

* Added a function to replace tilde with user's home directory, only when it should.

* Renamed ReplaceTilde to replaceTilde so that it won't get exported and removed some ';' at the end of some lines.
2020-06-07 20:53:25 +03:00
Provessor c49140ab36 Properly handle SIGHUP and SIGTERM (#305)
* Properly handle SIGHUP, SIGINT and SIGTERM

* Do not handle SIGINT

* Cancel current copy/move/delete operation

* Better cancel current operation
2020-04-13 19:32:42 +03:00
Gokcehan 933b49d095 cleanup 2020-04-13 18:24:15 +03:00
Gokcehan c5d05b7683 add 'on-cd' to the documentation
Related #291
2020-04-13 17:58:03 +03:00
ath3 9c1836c18b Add possibility to execute commands when directory changes (on_chdir) (#291)
* Add possibility to execute commands when cwd changes (on_chdir)

* Renamed function and special command on_chdir (onChdir, on-cd), support select command
2020-03-20 22:01:47 +03:00
Doron Behar 6693709f36 Use doronbehar's fork of termbox (#311) 2020-03-20 21:59:30 +03:00
Vladimir Bauer 17949fc25a case 1 is unnecessary because there is the same logic in default (#293) 2020-03-18 23:44:10 +03:00
Gokcehan 3c5abbbc5d Revert "Error clear (#192)"
This reverts commit 30d3078559.
2019-12-23 16:33:45 +03:00
Gokcehan e0747fa2f9 use rune indices for word matching
Related #193
2019-12-23 16:00:10 +03:00
Gokcehan b0064df32c convert string indices to rune slice indices
Related #193
2019-12-23 02:35:32 +03:00
Nicholas Christopoulos 74eab96637 [t]csh files added (lfcd,lf-complete) (#264)
* [t]csh files added (lfcd,lf-complete)

* rename lf-complete.csh to lf.csh

* rename lf-complete.csh to lf.csh; i forgot the comment-line

* convert ^O esc-code to ^O string
2019-12-19 22:11:23 +03:00
David Pedersen d63e7a2076 Don't rename when name is the same. Fix #253 (#266)
Currently, renaming a file without changing the name will prompt for
replacing and then delete the file. This will instead cancel the
renaming if the old and new names are the same.
2019-12-18 01:39:02 +03:00
Gokcehan d5f989f373 show progress for delete operation
Related #238
2019-12-02 19:50:13 +03:00
Juris Arturs Majors f76bf30f65 Asynchronous delete (#238)
* Asynchronous deletion, similar to moving

* Reversed some sloppy new lines from previous commit

* Move delete operations to delete.go

* Simplify to use RemoveAll before

* Send errors directly to ui.exprChan directly
2019-12-02 14:27:58 +03:00
Gokcehan 8327505398 handle closing double quote properly
Related #249
2019-10-26 03:05:07 +03:00
Gokcehan 74ef9fcd83 escape path separator on windows 2019-10-25 20:51:22 +03:00
Gokcehan 0482340d5e keep trailing backslash during reverse escape 2019-10-25 20:50:00 +03:00
Gokcehan 7a4d1cc275 escape special characters with backslash 2019-10-25 20:17:49 +03:00
Juris Arturs Majors cd396605da Add automatically generated zsh completion (#239)
* Add automatically generated zsh completion

* Rename to lf.zsh and add simple installation instructions
2019-10-07 22:48:17 +03:00
Gokcehan c43026d1e2 cleanup 2019-10-07 22:31:51 +03:00
arolle 7b89126e04 Correct abbreviation of the home directory (#241)
The path has to start with the home directory to be shortened to `~`.
Previously a user named `user` would see `/media/backup~/files` when
browsing `/media/backup/home/user/files`.
2019-10-07 22:30:52 +03:00
Gokcehan ff4c36565c mention setsid in the documentation
Related #148 and #233
2019-10-07 20:23:08 +03:00
Vladimir Bauer cfc9e355b3 reduce switch times a bit (#236) 2019-10-07 19:08:39 +03:00
Gokcehan bc33f3154a cleanup 2019-10-04 21:49:18 +03:00
Kennedy Mwenja 9991a40e87 Sort by file extensions (#230)
- preserve natural ordering of filenames if extensions are the same
  or are missing
- files without extensions rank higher on ascending sort and lower
  on descending sort
2019-10-04 21:44:52 +03:00
Gokcehan 41339a9e5a add times library to travis 2019-09-18 21:57:00 +03:00
Kennedy Mwenja 9515bd73d0 Sort By Access Time and Change Time (#226)
- Add access time and change time as sort by types. This is
  powered by github.com/djherbis/times.
- Fall back to modification time if access time and change time
  cannot be determined.
- Add `sa` and `sc` as default bindings for sort by access time and
  sort by change time respectively.
- Add access time and change time to info types allowing them to be
  displayed by the file list in the ui
2019-09-18 21:52:30 +03:00
Doron Behar d13cc79bc4 Add lf.desktop (#222) 2019-08-30 17:32:23 +03:00
Yong Jie bba32beb8a Fix bug where lfcd.cmd does not CD to different drive (#221) 2019-08-28 20:05:18 +03:00
Daniel Martí 50ac367626 fix ineffective breaks, remove unused parameters (#210)
While at it, simplify a few pieces of code.
2019-08-12 14:52:27 +03:00
Gokcehan 3b34b20cb8 change default icons for special directories
Related #207
2019-08-12 14:41:58 +03:00
Gokcehan 6982ffe4cf allow double backslash escape without quotes
Related #142
2019-08-05 22:28:55 +03:00
Gokcehan 488bf9f6b6 cleanup 2019-07-30 17:06:11 +03:00
David Pedersen 2ab866d474 Make prompt for delete command more descriptive (#206)
This will make the prompt shown when running the delete command more descriptive.
Before: `delete?[y/N]:`
Now when deleting one file: `delete /tmp/abc [y/N]?`
Now when deleting selection: `delete 3 items [y/N]?`
2019-07-23 22:33:43 +03:00
Gokcehan 9f661344ed allow defining a custom rename command 2019-07-21 20:40:57 +03:00
Juris Arturs Majors bfd01e5ed8 draft rename (#197)
*  basic structure

* working rename, without making dir's and selection change

* mkdirAll if necessary

* updated TODO's

* rename with replace prompting

* path prompt and moved functionality to nav.rename()

* renewing now (no set period is needed)

* documentation, keybidning change, load file info after renaming

* go generate
2019-07-20 19:31:19 +03:00
Juris Arturs Majors 27861f06e2 correct message for folders that lf has no permission for (#203) 2019-07-20 15:44:20 +03:00
Andrew Rabert cb36e87b80 Use symlink color for directories (#195)
Resolves https://github.com/gokcehan/lf/issues/156
2019-07-02 12:43:53 +03:00
Juris Arturs Majors 30d3078559 Error clear (#192)
* reset ui msg string

* loadfileinfo after prompts too

* removed legacy from previous pr...
2019-06-30 18:53:45 +03:00
Gokcehan db224f04fe add icon support
Related #158 and #164
2019-06-28 18:08:11 +03:00
Gokcehan afca893153 clear error message on succesful commands
Related #185 and #187
2019-06-26 17:52:29 +03:00
Juris Arturs Majors 16db95707e Mark clear (#190)
* markclear

* Revert "markclear"

This reverts commit 5e3a188618.

* Revert "Revert "markclear""

This reverts commit a7a3bfebbf.

* markclear with arguments

* docs

* reverted some whitepsace

* some inline comments

* additional error handling

* wrong argument case

* consider case when argument specified clears all marks

* code cleanup and removed readMarks from writeMarks

* indentation :/

* discussed changes implemnted

* return readMarks error in sync()

* remove reset marks
2019-06-25 21:38:34 +03:00
Juris Arturs Majors bf39c7c63b glob-select implementation (#184)
* glob-select logical implementation

* documentation

* indentation

* indentation

* indentation

* save

* merge glob selects

* check if selected before toggling

* glob-unselect

* identation ...

* return early
2019-06-20 18:17:47 +03:00
ath3 eb8e516cfb Check ratios before enabling preview (#174) 2019-06-12 16:45:40 +03:00
Alexandr Bruyako 34f39f90b2 remove unused "uppercase" param of appendTransliterate(), improve readability (#172) 2019-05-27 19:39:38 +03:00
Gokcehan 4c6241ca42 clean path before select
Related #167
2019-05-18 18:21:16 +03:00
Gokcehan 8388b4f385 Revert "do not cd when select on directory"
This reverts commit f071a3ae70.

Related #167
2019-05-18 18:20:58 +03:00
Gokcehan 80ab2e4fc4 cd if first argument is a directory
Related #167
2019-05-18 17:51:32 +03:00
Gokcehan f071a3ae70 do not cd when select on directory
Related #167
2019-05-17 21:48:19 +03:00
David Pedersen f3407b2d61 Remain in command mode after cmd-history-next (#168) 2019-05-17 18:52:58 +03:00
Gokcehan a5199960ed update documentation 2019-05-14 20:27:16 +03:00
Gokcehan e69a229578 allow movement commands in cmap
Related #68
2019-05-14 20:21:24 +03:00
David Pedersen e815adc6a6 Add Wrap Scroll functionality. Fixes #126 (#166) 2019-05-12 17:21:45 +03:00
35 changed files with 4153 additions and 1399 deletions

No files matched your search

+5 -2
View File
@@ -1,8 +1,11 @@
language: go language: go
install:
- go get github.com/nsf/termbox-go go:
- 1.15.x
before_deploy: before_deploy:
- gen/xbuild.sh - gen/xbuild.sh
deploy: deploy:
provider: releases provider: releases
api_key: api_key:
+15 -4
View File
@@ -8,7 +8,6 @@
[![Build Status](https://travis-ci.org/gokcehan/lf.svg?branch=master)](https://travis-ci.org/gokcehan/lf) [![Build Status](https://travis-ci.org/gokcehan/lf.svg?branch=master)](https://travis-ci.org/gokcehan/lf)
[![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf) [![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf)
[![GoDoc](https://godoc.org/github.com/gokcehan/lf?status.svg)](https://godoc.org/github.com/gokcehan/lf) [![GoDoc](https://godoc.org/github.com/gokcehan/lf?status.svg)](https://godoc.org/github.com/gokcehan/lf)
[![Join the chat at https://gitter.im/lf-fm/Lobby](https://badges.gitter.im/lf-fm/Lobby.svg)](https://gitter.im/lf-fm/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> This is a work in progress. Use at your own risk. > This is a work in progress. Use at your own risk.
@@ -42,13 +41,25 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tut
## Installation ## Installation
See [packages](https://github.com/gokcehan/lf/wiki/Packages) for community maintained packages.
See [releases](https://github.com/gokcehan/lf/releases) for pre-built binaries. See [releases](https://github.com/gokcehan/lf/releases) for pre-built binaries.
If you like to build from the source: If you like to build from the source on unix:
go get -u github.com/gokcehan/lf env CGO_ENABLED=0 GO111MODULE=on go get -u -ldflags="-s -w" github.com/gokcehan/lf
See [packages](https://github.com/gokcehan/lf/wiki/Packages) for community maintained packages. On windows `cmd`:
set CGO_ENABLED=0
set GO111MODULE=on
go get -u -ldflags="-s -w" github.com/gokcehan/lf
On windows `powershell`:
$env:CGO_ENABLED = '0'
$env:GO111MODULE = 'on'
go get -u -ldflags="-s -w" github.com/gokcehan/lf
## Usage ## Usage
+96 -23
View File
@@ -7,9 +7,13 @@ import (
"log" "log"
"os" "os"
"os/exec" "os/exec"
"os/signal"
"path/filepath" "path/filepath"
"strings" "strings"
"syscall"
"time" "time"
"github.com/gdamore/tcell"
) )
type cmdItem struct { type cmdItem struct {
@@ -30,15 +34,28 @@ type app struct {
cmdHistoryInd int cmdHistoryInd int
} }
func newApp() *app { func newApp(screen tcell.Screen) *app {
ui := newUI() ui := newUI(screen)
nav := newNav(ui.wins[0].h) nav := newNav(ui.wins[0].h)
quitChan := make(chan bool, 1)
osChan := make(chan os.Signal, 1)
signal.Notify(osChan, os.Interrupt, syscall.SIGHUP, syscall.SIGTERM)
go func() {
<-osChan
nav.copyTotalChan <- -nav.copyTotal
nav.moveTotalChan <- -nav.moveTotal
nav.deleteTotalChan <- -nav.deleteTotal
quitChan <- true
return
}()
return &app{ return &app{
ui: ui, ui: ui,
nav: nav, nav: nav,
ticker: new(time.Ticker), ticker: new(time.Ticker),
quitChan: make(chan bool, 1), quitChan: quitChan,
} }
} }
@@ -76,6 +93,12 @@ func (app *app) readHistory() error {
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2) toks := strings.SplitN(scanner.Text(), " ", 2)
if toks[0] != ":" && toks[0] != "$" && toks[0] != "%" && toks[0] != "!" && toks[0] != "&" {
continue
}
if len(toks) < 2 {
continue
}
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]}) app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
} }
@@ -132,12 +155,20 @@ func (app *app) writeHistory() error {
// for evaluation. Similarly directories and regular files are also read in // for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update. // separate goroutines and sent here for update.
func (app *app) loop() { func (app *app) loop() {
clientChan := app.ui.readExpr()
serverChan := readExpr() serverChan := readExpr()
app.ui.readExpr()
if gSelect != "" { if gSelect != "" {
go func() { go func() {
app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1} lstat, err := os.Lstat(gSelect)
if err != nil {
app.ui.exprChan <- &callExpr{"echoerr", []string{err.Error()}, 1}
} else if lstat.IsDir() {
app.ui.exprChan <- &callExpr{"cd", []string{gSelect}, 1}
} else {
app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1}
}
}() }()
} }
@@ -172,12 +203,13 @@ func (app *app) loop() {
continue continue
} }
log.Print("bye!") if app.nav.deleteTotal > 0 {
app.ui.echoerr("quit: delete operation in progress")
if err := app.nav.writeMarks(); err != nil { continue
log.Printf("writing marks file: %s", err)
} }
log.Print("bye!")
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)
} }
@@ -189,9 +221,7 @@ func (app *app) loop() {
} }
defer f.Close() defer f.Close()
dir := app.nav.currDir() _, err = f.WriteString(app.nav.currDir().path)
_, err = f.WriteString(dir.path)
if err != nil { if err != nil {
log.Printf("writing last dir file: %s", err) log.Printf("writing last dir file: %s", err)
} }
@@ -229,7 +259,24 @@ func (app *app) loop() {
app.nav.moveUpdate = 0 app.nav.moveUpdate = 0
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
case n := <-app.nav.deleteCountChan:
app.nav.deleteCount += n
if app.nav.deleteUpdate++; app.nav.deleteUpdate >= 1000 {
app.nav.deleteUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.deleteTotalChan:
app.nav.deleteTotal += n
if n < 0 {
app.nav.deleteCount += n
}
if app.nav.deleteTotal == 0 {
app.nav.deleteUpdate = 0
}
app.ui.draw(app.nav)
case d := <-app.nav.dirChan: case d := <-app.nav.dirChan:
app.nav.checkDir(d)
prev, ok := app.nav.dirCache[d.path] prev, ok := app.nav.dirCache[d.path]
if ok { if ok {
d.ind = prev.ind d.ind = prev.ind
@@ -258,6 +305,8 @@ func (app *app) loop() {
app.ui.draw(app.nav) app.ui.draw(app.nav)
case r := <-app.nav.regChan: case r := <-app.nav.regChan:
app.nav.checkReg(r)
app.nav.regCache[r.path] = r app.nav.regCache[r.path] = r
curr, err := app.nav.currFile() curr, err := app.nav.currFile()
@@ -268,7 +317,27 @@ func (app *app) loop() {
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
case e := <-clientChan: case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev)
if e == nil {
continue
}
e.eval(app, nil)
loop:
for {
select {
case ev := <-app.ui.evChan:
e = app.ui.readEvent(ev)
if e == nil {
continue
}
e.eval(app, nil)
default:
break loop
}
}
app.ui.draw(app.nav)
case e := <-app.ui.exprChan:
e.eval(app, nil) e.eval(app, nil)
app.ui.draw(app.nav) app.ui.draw(app.nav)
case e := <-serverChan: case e := <-serverChan:
@@ -284,8 +353,8 @@ func (app *app) loop() {
func (app *app) exportFiles() { func (app *app) exportFiles() {
var currFile string var currFile string
if f, err := app.nav.currFile(); err == nil { if curr, err := app.nav.currFile(); err == nil {
currFile = f.path currFile = curr.path
} }
currSelections := app.nav.currSelections() currSelections := app.nav.currSelections()
@@ -316,10 +385,12 @@ func waitKey() error {
// & 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.exportFiles() app.exportFiles()
exportOpts()
cmd := shellCommand(s, args) cmd := shellCommand(s, args)
var out io.Reader var out io.Reader
var err error
switch prefix { switch prefix {
case "$", "!": case "$", "!":
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
@@ -329,6 +400,8 @@ func (app *app) runShell(s string, args []string, prefix string) {
app.ui.pause() app.ui.pause()
defer app.ui.resume() defer app.ui.resume()
defer app.nav.renew() defer app.nav.renew()
err = cmd.Run()
case "%": case "%":
stdin, err := cmd.StdinPipe() stdin, err := cmd.StdinPipe()
if err != nil { if err != nil {
@@ -341,13 +414,8 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
out = stdout out = stdout
cmd.Stderr = cmd.Stdout cmd.Stderr = cmd.Stdout
} fallthrough
case "&":
var err error
switch prefix {
case "$", "!":
err = cmd.Run()
case "%", "&":
err = cmd.Start() err = cmd.Start()
} }
@@ -363,7 +431,6 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
switch prefix { switch prefix {
case "%": case "%":
@@ -393,5 +460,11 @@ func (app *app) runShell(s string, args []string, prefix string) {
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"load", nil, 1} app.ui.exprChan <- &callExpr{"load", nil, 1}
}() }()
case "&":
go func() {
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
}()
} }
} }
+10 -8
View File
@@ -10,16 +10,17 @@ import (
"strings" "strings"
"time" "time"
"github.com/nsf/termbox-go" "github.com/gdamore/tcell"
) )
func run() { func run() {
if err := termbox.Init(); err != nil { var screen tcell.Screen
log.Fatalf("initializing termbox: %s", err) var err error
if screen, err = tcell.NewScreen(); err != nil {
log.Fatalf("creating screen: %s", err)
} else if err = screen.Init(); err != nil {
log.Fatalf("initializing screen: %s", err)
} }
defer termbox.Close()
setColorMode()
f, err := os.Create(gLogPath) f, err := os.Create(gLogPath)
if err != nil { if err != nil {
@@ -31,7 +32,7 @@ func run() {
log.Print("hi!") log.Print("hi!")
app := newApp() app := newApp(screen)
if err := app.nav.readMarks(); err != nil { if err := app.nav.readMarks(); err != nil {
app.ui.echoerrf("reading marks file: %s", err) app.ui.echoerrf("reading marks file: %s", err)
@@ -42,6 +43,7 @@ func run() {
} }
app.loop() app.loop()
app.ui.screen.Fini()
} }
func readExpr() <-chan expr { func readExpr() <-chan expr {
@@ -52,7 +54,7 @@ func readExpr() <-chan expr {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
for err != nil { for err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err)) log.Printf("connecting server: %s", err)
time.Sleep(duration) time.Sleep(duration)
duration *= 2 duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath) c, err = net.Dial(gSocketProt, gSocketPath)
+94 -105
View File
@@ -7,48 +7,18 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/nsf/termbox-go" "github.com/gdamore/tcell"
) )
const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse type styleMap map[string]tcell.Style
var gAnsiCodes = map[int]termbox.Attribute{ func parseStyles() styleMap {
0: termbox.ColorDefault,
1: termbox.AttrBold,
4: termbox.AttrUnderline,
7: termbox.AttrReverse,
30: termbox.ColorBlack,
31: termbox.ColorRed,
32: termbox.ColorGreen,
33: termbox.ColorYellow,
34: termbox.ColorBlue,
35: termbox.ColorMagenta,
36: termbox.ColorCyan,
37: termbox.ColorWhite,
40: termbox.ColorBlack,
41: termbox.ColorRed,
42: termbox.ColorGreen,
43: termbox.ColorYellow,
44: termbox.ColorBlue,
45: termbox.ColorMagenta,
46: termbox.ColorCyan,
47: termbox.ColorWhite,
}
type colorEntry struct {
fg termbox.Attribute
bg termbox.Attribute
}
type colorMap map[string]colorEntry
func parseColors() colorMap {
if env := os.Getenv("LS_COLORS"); env != "" { if env := os.Getenv("LS_COLORS"); env != "" {
return parseColorsGNU(env) return parseStylesGNU(env)
} }
if env := os.Getenv("LSCOLORS"); env != "" { if env := os.Getenv("LSCOLORS"); env != "" {
return parseColorsBSD(env) return parseStylesBSD(env)
} }
// default values from dircolors with removed background colors // default values from dircolors with removed background colors
@@ -73,10 +43,10 @@ func parseColors() colorMap {
"ex=01;32", "ex=01;32",
} }
return parseColorsGNU(strings.Join(defaultColors, ":")) return parseStylesGNU(strings.Join(defaultColors, ":"))
} }
func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, termbox.Attribute) { func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";") toks := strings.Split(s, ";")
var nums []int var nums []int
@@ -93,43 +63,63 @@ func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, term
nums = append(nums, n) nums = append(nums, n)
} }
// ECMA-48 details the standard
for i := 0; i < len(nums); i++ { for i := 0; i < len(nums); i++ {
n := nums[i] n := nums[i]
switch { switch {
case n == 38 && i+2 < len(nums) && nums[i+1] == 5:
fg &= gAnsiColorResetMask
fg |= termbox.Attribute(nums[i+2] + 1)
i += 2
continue
case n == 48 && i+2 < len(nums) && nums[i+1] == 5:
bg = termbox.Attribute(nums[i+2] + 1)
i += 2
continue
}
attr, ok := gAnsiCodes[n]
if !ok {
log.Printf("unknown ansi code: %d", n)
continue
}
switch {
case n == 0: case n == 0:
fg, bg = attr, attr st = tcell.StyleDefault
case n == 1 || n == 4 || n == 7: case n == 1:
fg |= attr st = st.Bold(true)
case 30 <= n && n <= 37: case n == 2:
fg &= gAnsiColorResetMask st = st.Dim(true)
fg |= attr case n == 4:
case 40 <= n && n <= 47: st = st.Underline(true)
bg = attr case n == 5 || n == 6:
st = st.Blink(true)
case n == 7:
st = st.Reverse(true)
case n >= 30 && n <= 37:
st = st.Foreground(tcell.Color(n - 30))
case n == 38:
if i+3 <= len(nums) && nums[i+1] == 5 {
st = st.Foreground(tcell.Color(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
st = st.Foreground(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
int32(nums[i+4])))
i += 4
} else {
log.Printf("unknown ansi code or incorrect form: %d", n)
}
case n >= 40 && n <= 47:
st = st.Background(tcell.Color(n - 40))
case n == 48:
if i+3 <= len(nums) && nums[i+1] == 5 {
st = st.Background(tcell.Color(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
st = st.Background(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
int32(nums[i+4])))
i += 4
} else {
log.Printf("unknown ansi code or incorrect form: %d", n)
}
default:
log.Printf("unknown ansi code: %d", n)
} }
} }
return fg, bg return st
} }
// This function parses $LS_COLORS environment variable. // This function parses $LS_COLORS environment variable.
func parseColorsGNU(env string) colorMap { func parseStylesGNU(env string) styleMap {
colors := make(colorMap) styles := make(styleMap)
entries := strings.Split(env, ":") entries := strings.Split(env, ":")
for _, entry := range entries { for _, entry := range entries {
@@ -139,66 +129,69 @@ func parseColorsGNU(env string) colorMap {
pair := strings.Split(entry, "=") pair := strings.Split(entry, "=")
if len(pair) != 2 { if len(pair) != 2 {
log.Printf("invalid $LS_COLORS entry: %s", entry) log.Printf("invalid $LS_COLORS entry: %s", entry)
return colors return styles
} }
key, val := pair[0], pair[1] key, val := pair[0], pair[1]
fg, bg := applyAnsiCodes(val, termbox.ColorDefault, termbox.ColorDefault) styles[key] = applyAnsiCodes(val, tcell.StyleDefault)
colors[key] = colorEntry{fg: fg, bg: bg}
} }
return colors return styles
} }
// This function parses $LSCOLORS environment variable. // This function parses $LSCOLORS environment variable.
func parseColorsBSD(env string) colorMap { func parseStylesBSD(env string) styleMap {
colors := make(colorMap) styles := make(styleMap)
if len(env) != 22 { if len(env) != 22 {
log.Printf("invalid $LSCOLORS variable: %s", env) log.Printf("invalid $LSCOLORS variable: %s", env)
return colors return styles
} }
colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"} colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"}
colorCodes := map[byte]termbox.Attribute{
'a': termbox.ColorBlack,
'b': termbox.ColorRed,
'c': termbox.ColorGreen,
'd': termbox.ColorYellow, // brown
'e': termbox.ColorBlue,
'f': termbox.ColorMagenta,
'g': termbox.ColorCyan,
'h': termbox.ColorWhite, // light grey
'A': termbox.AttrBold | termbox.ColorBlack,
'B': termbox.AttrBold | termbox.ColorRed,
'C': termbox.AttrBold | termbox.ColorGreen,
'D': termbox.AttrBold | termbox.ColorYellow, // brown
'E': termbox.AttrBold | termbox.ColorBlue,
'F': termbox.AttrBold | termbox.ColorMagenta,
'G': termbox.AttrBold | termbox.ColorCyan,
'H': termbox.AttrBold | termbox.ColorWhite, // light grey
'x': termbox.ColorDefault,
}
getColor := func(r byte) termbox.Attribute { getStyle := func(r1, r2 byte) tcell.Style {
if color, ok := colorCodes[r]; ok { st := tcell.StyleDefault
return color
switch {
case r1 == 'x':
st = st.Foreground(tcell.ColorDefault)
case 'A' <= r1 && r1 <= 'H':
st = st.Foreground(tcell.Color(r1 - 'A')).Bold(true)
case 'a' <= r1 && r1 <= 'h':
st = st.Foreground(tcell.Color(r1 - 'a'))
default:
log.Printf("invalid $LSCOLORS entry: %c", r1)
return tcell.StyleDefault
} }
log.Printf("invalid $LSCOLORS entry: %c", r) switch {
return termbox.ColorDefault case r2 == 'x':
st = st.Background(tcell.ColorDefault)
case 'a' <= r2 && r2 <= 'h':
st = st.Background(tcell.Color(r2 - 'a'))
default:
log.Printf("invalid $LSCOLORS entry: %c", r2)
return tcell.StyleDefault
}
return st
} }
for i, key := range colorNames { for i, key := range colorNames {
colors[key] = colorEntry{fg: getColor(env[i*2]), bg: getColor(env[i*2+1])} styles[key] = getStyle(env[i*2], env[i*2+1])
} }
return colors return styles
} }
func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) { func (cm styleMap) get(f *file) tcell.Style {
var key string var key string
switch { switch {
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0: case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw" key = "tw"
case f.IsDir() && f.Mode()&os.ModeSticky != 0: case f.IsDir() && f.Mode()&os.ModeSticky != 0:
@@ -207,10 +200,6 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
key = "ow" key = "ow"
case f.IsDir(): case f.IsDir():
key = "di" key = "di"
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.Mode()&os.ModeNamedPipe != 0: case f.Mode()&os.ModeNamedPipe != 0:
key = "pi" key = "pi"
case f.Mode()&os.ModeSocket != 0: case f.Mode()&os.ModeSocket != 0:
@@ -230,12 +219,12 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
} }
if val, ok := cm[key]; ok { if val, ok := cm[key]; ok {
return val.fg, val.bg return val
} }
if val, ok := cm["fi"]; ok { if val, ok := cm["fi"]; ok {
return val.fg, val.bg return val
} }
return termbox.ColorDefault, termbox.ColorDefault return tcell.StyleDefault
} }
+51 -47
View File
@@ -3,75 +3,79 @@ package main
import ( import (
"testing" "testing"
"github.com/nsf/termbox-go" "github.com/gdamore/tcell"
) )
func TestApplyAnsiCodes(t *testing.T) { func TestApplyAnsiCodes(t *testing.T) {
none := termbox.ColorDefault none := tcell.StyleDefault
tests := []struct { tests := []struct {
s string s string
fg termbox.Attribute st tcell.Style
bg termbox.Attribute stExp tcell.Style
fgExp termbox.Attribute
bgExp termbox.Attribute
}{ }{
{"", none, none, none, none}, {"", none, none},
{"", termbox.ColorRed, termbox.ColorRed, none, none}, {"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"", termbox.AttrBold, none, none, none}, {"", none.Bold(true), none},
{"", termbox.ColorRed | termbox.AttrBold, none, none, none}, {"", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"0", none, none, none, none}, {"0", none, none},
{"0", termbox.ColorRed, termbox.ColorRed, none, none}, {"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"0", termbox.AttrBold, none, none, none}, {"0", none.Bold(true), none},
{"0", termbox.ColorRed | termbox.AttrBold, none, none, none}, {"0", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"1", none, none, termbox.AttrBold, none}, {"1", none, none.Bold(true)},
{"4", none, none, termbox.AttrUnderline, none}, {"4", none, none.Underline(true)},
{"7", none, none, termbox.AttrReverse, none}, {"7", none, none.Reverse(true)},
{"1", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrBold, none}, {"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"4", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrUnderline, none}, {"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)},
{"7", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrReverse, none}, {"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)},
{"4", termbox.AttrBold, none, termbox.AttrBold | termbox.AttrUnderline, none}, {"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", termbox.ColorRed | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold | termbox.AttrUnderline, none}, {"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"31", none, none, termbox.ColorRed, none}, {"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", termbox.ColorGreen, none, termbox.ColorRed, none}, {"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, {"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"41", none, none, none, termbox.ColorRed}, {"41", none, none.Background(tcell.ColorMaroon)},
{"41", none, termbox.ColorGreen, none, termbox.ColorRed}, {"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;31", none, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none, termbox.ColorBlack, none}, {"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none, termbox.ColorRed, none}, {"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none, termbox.Attribute(9), none}, {"38;5;8", none, none.Foreground(tcell.Color(8))},
{"38;5;16", none, none, termbox.Attribute(17), none}, {"38;5;16", none, none.Foreground(tcell.Color(16))},
{"38;5;232", none, none, termbox.Attribute(233), none}, {"38;5;232", none, none.Foreground(tcell.Color(232))},
{"38;5;1", termbox.ColorGreen, none, termbox.ColorRed, none}, {"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"38;5;1", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, {"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"48;5;0", none, none, none, termbox.ColorBlack}, {"48;5;0", none, none.Background(tcell.ColorBlack)},
{"48;5;1", none, none, none, termbox.ColorRed}, {"48;5;1", none, none.Background(tcell.ColorMaroon)},
{"48;5;8", none, none, none, termbox.Attribute(9)}, {"48;5;8", none, none.Background(tcell.Color(8))},
{"48;5;16", none, none, none, termbox.Attribute(17)}, {"48;5;16", none, none.Background(tcell.Color(16))},
{"48;5;232", none, none, none, termbox.Attribute(233)}, {"48;5;232", none, none.Background(tcell.Color(232))},
{"48;5;1", none, termbox.ColorGreen, none, termbox.ColorRed}, {"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;38;5;1", none, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;38;5;1", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))},
{"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))},
// Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446
{"38;5;34;1", none, none.Foreground(tcell.Color(34)).Bold(true)},
} }
for _, test := range tests { for _, test := range tests {
if fgGot, bgGot := applyAnsiCodes(test.s, test.fg, test.bg); fgGot != test.fgExp || bgGot != test.bgExp { if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%d' and '%d' expected '%d' and '%d' but got '%d' and '%d'", t.Errorf("at input '%s' with '%d' expected '%d' but got '%d'",
test.s, test.fg, test.bg, test.fgExp, test.bgExp, fgGot, bgGot) test.s, test.st, test.stExp, stGot)
} }
} }
} }
+29 -20
View File
@@ -31,13 +31,11 @@ var (
"copy", "copy",
"cut", "cut",
"paste", "paste",
"delete",
"clear", "clear",
"draw",
"redraw", "redraw",
"load",
"reload", "reload",
"read", "read",
"rename",
"shell", "shell",
"shell-pipe", "shell-pipe",
"shell-wait", "shell-wait",
@@ -51,24 +49,27 @@ var (
"search-next", "search-next",
"search-prev", "search-prev",
"mark-save", "mark-save",
"mark-remove",
"mark-load", "mark-load",
"draw",
"load",
"sync", "sync",
"echo", "echo",
"echomsg", "echomsg",
"echoerr", "echoerr",
"cd", "cd",
"select", "select",
"glob-select",
"glob-unselect",
"source", "source",
"push", "push",
"delete",
} }
gOptWords = []string{ gOptWords = []string{
"anchorfind", "anchorfind",
"noanchorfind", "noanchorfind",
"anchorfind!", "anchorfind!",
"color256",
"nocolor256",
"color256!",
"dircounts", "dircounts",
"nodircounts", "nodircounts",
"dircounts!", "dircounts!",
@@ -84,6 +85,9 @@ var (
"hidden", "hidden",
"nohidden", "nohidden",
"hidden!", "hidden!",
"icons",
"noicons",
"icons!",
"ignorecase", "ignorecase",
"noignorecase", "noignorecase",
"ignorecase!", "ignorecase!",
@@ -93,9 +97,15 @@ var (
"incsearch", "incsearch",
"noincsearch", "noincsearch",
"incsearch!", "incsearch!",
"number",
"nonumber",
"number!",
"preview", "preview",
"nopreview", "nopreview",
"preview!", "preview!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"reverse", "reverse",
"noreverse", "noreverse",
"reverse!", "reverse!",
@@ -108,27 +118,26 @@ var (
"wrapscan", "wrapscan",
"nowrapscan", "nowrapscan",
"wrapscan!", "wrapscan!",
"number", "wrapscroll",
"nonumber", "nowrapscroll",
"number!", "wrapscroll!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"findlen", "findlen",
"period", "period",
"scrolloff", "scrolloff",
"tabstop", "tabstop",
"errorfmt", "errorfmt",
"filesep", "filesep",
"hiddenfiles",
"ifs", "ifs",
"info",
"previewer", "previewer",
"promptfmt", "promptfmt",
"ratios",
"shell", "shell",
"shellopts",
"sortby", "sortby",
"timefmt", "timefmt",
"ratios", "truncatechar",
"info",
"shellopts",
} }
) )
@@ -214,7 +223,7 @@ func matchExec(s string) (matches []string, longest string) {
} }
func matchFile(s string) (matches []string, longest string) { func matchFile(s string) (matches []string, longest string) {
dir := strings.Replace(s, "~", gUser.HomeDir, -1) dir := replaceTilde(s)
if !filepath.IsAbs(dir) { if !filepath.IsAbs(dir) {
wd, err := os.Getwd() wd, err := os.Getwd()
@@ -246,13 +255,13 @@ func matchFile(s string) (matches []string, longest string) {
name := f.Name() name := f.Name()
if isRoot(s) || filepath.Base(s) != s { if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(s), f.Name()) name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
} }
name = escape(name) name = escape(name)
item := f.Name() item := f.Name()
if f.Mode().IsDir() { if f.Mode().IsDir() {
item += string(filepath.Separator) item += escape(string(filepath.Separator))
} }
matches = append(matches, item) matches = append(matches, item)
@@ -262,7 +271,7 @@ func matchFile(s string) (matches []string, longest string) {
if f.Mode().IsRegular() { if f.Mode().IsRegular() {
longest = name + " " longest = name + " "
} else { } else {
longest = name + string(filepath.Separator) longest = name + escape(string(filepath.Separator))
} }
} }
} }
@@ -372,7 +381,7 @@ func completeShell(acc []rune) (matches []string, longestAcc []rune) {
longestAcc = []rune(longest) 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(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...)
} }
return return
+2 -2
View File
@@ -86,12 +86,12 @@ func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
for _, src := range srcs { for _, src := range srcs {
dst := filepath.Join(dstDir, filepath.Base(src)) dst := filepath.Join(dstDir, filepath.Base(src))
_, err := os.Stat(dst) _, err := os.Lstat(dst)
if !os.IsNotExist(err) { if !os.IsNotExist(err) {
var newPath string var newPath string
for i := 1; !os.IsNotExist(err); i++ { for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i) newPath = fmt.Sprintf("%s.~%d~", dst, i)
_, err = os.Stat(newPath) _, err = os.Lstat(newPath)
} }
dst = newPath dst = newPath
} }
+9 -16
View File
@@ -2,7 +2,7 @@ package main
import ( import (
"strconv" "strconv"
"strings" "unicode"
) )
var normMap map[rune]rune var normMap map[rune]rune
@@ -14,19 +14,16 @@ func init() {
appendTransliterate( appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ", "ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa", "eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
true,
) )
// Vietnamese // Vietnamese
appendTransliterate( appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ", "áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd", "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
true,
) )
} }
func appendTransliterate(base, norm string, uppercase bool) { func appendTransliterate(base, norm string) {
normRunes := []rune(norm) normRunes := []rune(norm)
baseRunes := []rune(base) baseRunes := []rune(base)
@@ -36,24 +33,20 @@ func appendTransliterate(base, norm string, uppercase bool) {
panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length
} }
for i, baseRune := range baseRunes { for i := 0; i < lenBase; i++ {
normMap[baseRune] = normRunes[i] normMap[baseRunes[i]] = normRunes[i]
}
if uppercase { baseUpper := unicode.ToUpper(baseRunes[i])
upperBase := strings.ToUpper(base) normUpper := unicode.ToUpper(normRunes[i])
upperNorm := strings.ToUpper(norm)
normRune := []rune(upperNorm) normMap[baseUpper] = normUpper
for i, baseRune := range []rune(upperBase) {
normMap[baseRune] = normRune[i]
}
} }
} }
// Remove diacritics and make lowercase. // Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string { func removeDiacritics(baseString string) string {
var normalizedRunes []rune var normalizedRunes []rune
for _, baseRune := range []rune(baseString) { for _, baseRune := range baseString {
if normRune, ok := normMap[baseRune]; ok { if normRune, ok := normMap[baseRune]; ok {
normalizedRunes = append(normalizedRunes, normRune) normalizedRunes = append(normalizedRunes, normRune)
} else { } else {
+662 -123
View File
@@ -12,10 +12,11 @@ at https://godoc.org/github.com/gokcehan/lf. You can also use 'doc' command
You can run 'lf -help' to see descriptions of command line options. You can run 'lf -help' to see descriptions of command line options.
Reference Quick Reference
The following commands are provided by lf with default keybindings: The following commands are provided by lf:
quit (default 'q')
up (default 'k' and '<up>') up (default 'k' and '<up>')
half-up (default '<c-u>') half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>') page-up (default '<c-b>' and '<pgup>')
@@ -24,138 +25,132 @@ The following commands are provided by lf with default keybindings:
page-down (default '<c-f>' and '<pgdn>') page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>') updir (default 'h' and '<left>')
open (default 'l' and '<right>') open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
toggle (default '<space>') toggle
invert (default 'v') invert (default 'v')
unselect (default 'u') unselect (default 'u')
glob-select
glob-unselect
copy (default 'y') copy (default 'y')
cut (default 'd') cut (default 'd')
paste (default 'p') paste (default 'p')
clear (default 'c') clear (default 'c')
sync
draw
redraw (default '<c-l>') redraw (default '<c-l>')
load
reload (default '<c-r>') reload (default '<c-r>')
read (default ':') echo
shell (default '$') echomsg
shell-pipe (default '%') echoerr
shell-wait (default '!') cd
shell-async (default '&') select
find (default 'f') delete (modal)
find-back (default 'F') rename (modal) (default 'r')
source
push
read (modal) (default ':')
shell (modal) (default '$')
shell-pipe (modal) (default '%')
shell-wait (modal) (default '!')
shell-async (modal) (default '&')
find (modal) (default 'f')
find-back (modal) (default 'F')
find-next (default ';') find-next (default ';')
find-prev (default ',') find-prev (default ',')
search (default '/') search (modal) (default '/')
search-back (default '?') search-back (modal) (default '?')
search-next (default 'n') search-next (default 'n')
search-prev (default 'N') search-prev (default 'N')
mark-save (default 'm') mark-save (modal) (default 'm')
mark-load (default "'") mark-load (modal) (default "'")
mark-remove (modal) (default `"`)
The following commands are provided by lf without default keybindings: The following command line commands are provided by lf:
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default
keybindings:
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>') cmd-end (default '<c-e>' and '<end>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<backspace>' and '<backspace2>')
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-transpose-word (default '<a-t>')
cmd-word (default '<a-f>') cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>') cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>') cmd-delete-word (default '<a-d>')
cmd-capitalize-word (default '<a-c>')
cmd-uppercase-word (default '<a-u>') cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>') cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
anchorfind boolean (default on) anchorfind bool (default on)
color256 boolean (default off) dircounts bool (default off)
dircounts boolean (default off) dirfirst bool (default on)
dirfirst boolean (default on) drawbox bool (default off)
drawbox boolean (default off) errorfmt string (default "\033[7;31;47m%s\033[0m")
globsearch boolean (default off) filesep string (default "\n")
hidden boolean (default off) findlen int (default 1)
ignorecase boolean (default on) globsearch bool (default off)
ignoredia boolean (default off) hidden bool (default off)
incsearch boolean (default off) hiddenfiles []string (default '.*')
preview boolean (default on) icons bool (default off)
reverse boolean (default off) ifs string (default '')
smartcase boolean (default on) ignorecase bool (default on)
smartdia boolean (default off) ignoredia bool (default off)
wrapscan boolean (default on) incsearch bool (default off)
number boolean (default off) info []string (default '')
relativenumber boolean (default off) number bool (default off)
findlen integer (default 1) (zero to prompt until single match) period int (default 0)
period integer (default 0) (zero to disable periodic loading) preview bool (default on)
scrolloff integer (default 0) previewer string (default '')
tabstop integer (default 8) promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
errorfmt string (default "\033[7;31;47m%s\033[0m") ratios []int (default '1:2:3')
filesep string (default "\n") relativenumber bool (default off)
ifs string (default '') (not exported if empty) reverse bool (default off)
previewer string (default '') (not filtered if empty) scrolloff int (default 0)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m") shell string (default 'sh' for unix and 'cmd' for windows)
shell string (default 'sh') shellopts []string (default '')
sortby string (default 'natural') smartcase bool (default on)
timefmt string (default 'Mon Jan _2 15:04:05 2006') smartdia bool (default off)
ratios string (default '1:2:3') sortby string (default 'natural')
info string (default '') tabstop int (default 8)
shellopts string (default '') timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~')
wrapscan bool (default on)
wrapscroll bool (default off)
The following variables are exported for shell commands: The following environment variables are exported for shell commands:
$f current file f
$fs selected file(s) separated with 'filesep' fs
$fx current file or selected file(s) if any fx
$id id number of the client id
LF_LEVEL
OPENER
EDITOR
PAGER
SHELL
The following variables are set to the corresponding values: The following commands/keybindings are provided by default:
$LF_LEVEL current nesting level unix windows
cmd open &$OPENER "$f" cmd open &%OPENER% %f%
The following default values are set to the environmental variables on unix map e $$EDITOR "$f" map e $%EDITOR% %f%
when they are not set or empty: map i $$PAGER "$f" map i !%PAGER% %f%
map w $$SHELL map w $%SHELL%
$OPENER open # macos
$OPENER xdg-open # others
$EDITOR vi
$PAGER less
$SHELL sh
The following default values are set to the environmental variables on windows
when they are not set or empty:
%OPENER% start
%EDITOR% notepad
%PAGER% more
%SHELL% cmd
The following additional keybindings are provided by default: The following additional keybindings are provided by default:
@@ -168,13 +163,11 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info map sn :set sortby natural; set info
map ss :set sortby size; set info size map ss :set sortby size; set info size
map st :set sortby time; set info time map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~ map gh cd ~
map <space> :toggle; down
The following keybindings to applications are provided by default:
map e $$EDITOR $f
map i $$PAGER $f
map w $$SHELL
Configuration Configuration
@@ -205,6 +198,507 @@ locations:
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
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.
quit (default 'q')
Quit lf and return to the shell.
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
Move the current file selection upwards/downwards by one/half a page/full page.
updir (default 'h' and '<left>')
Change the current working directory to the parent directory.
open (default 'l' and '<right>')
If the current file is a directory, then change the current directory to it, otherwise, execute the 'open' command.
A default 'open' command is provided to call the default system opener asynchronously with the current file as the argument.
A custom 'open' command can be defined to override this default.
(See also 'OPENER' variable and 'Opening Files' section)
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
Move the current file selection to the top/bottom of the directory.
toggle
Toggle the selection of the current file or files given as arguments.
invert (default 'v')
Reverse the selection of all files in the current directory (i.e. 'toggle' all files).
Selections in other directories are not effected by this command.
You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. `cmd select-all :unselect; invert`), though this will also remove selections in other directories.
unselect (default 'u')
Remove the selection of all files in all directories.
glob-select
Select files that match the given glob.
glob-unselect
Unselect files that match the given glob.
copy (default 'y')
If there are no selections, save the path of the current file to the copy buffer, otherwise, copy the paths of selected files.
cut (default 'd')
If there are no selections, save the path of the current file to the cut buffer, otherwise, copy the paths of selected files.
paste (default 'p')
Copy/Move files in copy/cut buffer to the current working directory.
clear (default 'c')
Clear file paths in copy/cut buffer.
sync
Synchronize copied/cut files with server.
This command is automatically called when required.
draw
Draw the screen.
This command is automatically called when required.
redraw (default '<c-l>')
Synchronize the terminal and redraw the screen.
load
Load modified files and directories.
This command is automatically called when required.
reload (default '<c-r>')
Flush the cache and reload all files and directories.
echo
Print given arguments to the message line at the bottom.
echomsg
Print given arguments to the message line at the bottom and also to the log file.
echoerr
Print given arguments to the message line at the bottom in red color and also to the log file.
cd
Change the working directory to the given argument.
select
Change the current file selection to the given argument.
delete (modal)
Remove the current file or selected file(s).
rename (modal) (default 'r')
Rename the current file using the builtin method.
A custom 'rename' command can be defined to override this default.
source
Read the configuration file given in the argument.
push
Simulate key pushes given in the argument.
read (modal) (default ':')
Read a command to evaluate.
shell (modal) (default '$')
Read a shell command to execute.
(See also 'Prefixes' and 'Shell Commands' sections)
shell-pipe (modal) (default '%')
Read a shell command to execute piping its standard I/O to the bottom statline.
(See also 'Prefixes' and 'Piping Shell Commands' sections)
shell-wait (modal) (default '!')
Read a shell command to execute and wait for a key press in the end.
(See also 'Prefixes' and 'Waiting Shell Commands' sections)
shell-async (modal) (default '&')
Read a shell command to execute synchronously without standard I/O.
find (modal) (default 'f')
find-back (modal) (default 'F')
find-next (default ';')
find-prev (default ',')
Read key(s) to find the appropriate file name match in the forward/backward direction and jump to the next/previous match.
(See also 'anchorfind', 'findlen', 'wrapscan', 'ignorecase', 'smartcase', 'ignoredia', and 'smartdia' options and 'Searching Files' section)
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
Read a pattern to search for a file name match in the forward/backward direction and jump to the next/previous match.
(See also 'globsearch', 'incsearch', 'wrapscan', 'ignorecase', 'smartcase', 'ignoredia', and 'smartdia' options and 'Searching Files' section)
mark-save (modal) (default 'm')
Save the current directory as a bookmark assigned to the given key.
mark-load (modal) (default "'")
Change the current directory to the bookmark assigned to the given key.
A special bookmark "'" holds the previous directory after a 'mark-load', 'cd', or 'select' command.
mark-remove (modal) (default `"`)
Remove a bookmark assigned to the given key.
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.
cmd-escape (default '<esc>')
Quit command line mode and return to normal mode.
cmd-complete (default '<tab>')
Autocomplete the current word.
cmd-enter (default '<c-j>' and '<enter>')
Execute the current line.
cmd-interrupt (default '<c-c>')
Interrupt the current shell-pipe command and return to the normal mode.
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
Go to next/previous item in the history.
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
Move the cursor to the left/right.
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
Move the cursor to the beginning/end of line.
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<backspace>' and '<backspace2>')
Delete the next character in forward/backward direction.
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
Delete everything up to the beginning/end of line.
cmd-delete-unix-word (default '<c-w>')
Delete the previous unix word.
cmd-yank (default '<c-y>')
Paste the buffer content containing the last deleted item.
cmd-transpose (default '<c-t>')
cmd-transpose-word (default '<a-t>')
Transpose the positions of last two characters/words.
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
Move the cursor by one word in forward/backward direction.
cmd-delete-word (default '<a-d>')
Delete the next word in forward direction.
cmd-capitalize-word (default '<a-c>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
Capitalize/uppercase/lowercase the current word and jump to the next word.
Options
This section shows information about options to customize the behavior.
Character ':' is used as the separator for list options '[]int' and '[]string'.
anchorfind bool (default on)
When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position.
dircounts bool (default off)
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+'.
dirfirst bool (default on)
Show directories first above regular files.
drawbox bool (default off)
Draw boxes around panes with box drawing characters.
errorfmt string (default "\033[7;31;47m%s\033[0m")
Format string of error messages shown in the bottom message line.
filesep string (default "\n")
File separator used in environment variables 'fs' and 'fx'.
findlen int (default 1)
Number of characters prompted for the find command.
When this value is set to 0, find command prompts until there is only a single match left.
globsearch bool (default off)
When this option is enabled, search command patterns are considered as globs, otherwise they are literals.
With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges.
Otherwise, these characters are interpreted as they are.
hidden bool (default off)
Show hidden files.
On unix systems, hidden files are determined by the value of 'hiddenfiles'.
On windows, only files with hidden attributes are considered hidden files.
hiddenfiles []string (default '.*')
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.
icons bool (default off)
Show icons before each item in the list.
By default, only two icons, 🗀 (U+1F5C0) and 🗎 (U+1F5CE), are used for directories and files respectively, as they are supported in the unicode standard.
Icons can be configured with an environment variable named 'LF_ICONS'.
The syntax of this variable is similar to 'LS_COLORS'.
See the wiki page for an example icon configuration.
ifs string (default '')
Sets 'IFS' variable in shell commands.
It works by adding the assignment to the beginning of the command string as 'IFS='...'; ...'.
The reason is that 'IFS' variable is not inherited by the shell for security reasons.
This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells.
This option has no effect when the value is left empty.
This option does not have any effect on windows.
ignorecase bool (default on)
Ignore case in search patterns.
ignoredia bool (default off)
Ignore diacritics in search patterns.
incsearch bool (default off)
Jump to the first match after each keystroke during searching.
info []string (default '')
List of information shown for directory items at the right side of pane.
Currently supported information types are 'size', 'time', 'atime', and 'ctime'.
Information is only shown when the pane width is more than twice the width of information.
number bool (default off)
Show the position number for directory items at the left side of pane.
When 'relativenumber' is enabled, only the current line shows the absolute position and relative positions are shown for the rest.
period int (default 0)
Set the interval in seconds for periodic checks of directory updates.
This works by periodically calling the 'load' command.
Note that directories are already updated automatically in many cases.
This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf.
Periodic checks are disabled when the value of this option is set to zero.
preview bool (default on)
Show previews of files and directories at the right most pane.
If the file has more lines than the preview pane, rest of the lines are not read.
Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'.
previewer string (default '') (not filtered if empty)
Set the path of a previewer file to filter the content of regular files for previewing.
The file should be executable.
Two arguments are passed to the file, first is the current file name, and second is the height of preview pane.
SIGPIPE signal is sent when enough lines are read.
Preview filtering is disabled and files are displayed as they are when the value of this option is left empty.
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
Format string of the prompt shown in the top line.
Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, and '%f' as the file name.
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.
ratios []int (default '1:2:3')
List of ratios of pane widths.
Number of items in the list determines the number of panes in the ui.
When 'preview' option is enabled, the right most number is used for the width of preview pane.
relativenumber bool (default off)
Show the position number relative to the current line.
When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown.
reverse bool (default off)
Reverse the direction of sort.
scrolloff int (default 0)
Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling.
The current line is kept in the middle when this option is set to a large value that is bigger than the half of number of lines.
A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items.
shell string (default 'sh' for unix and 'cmd' for windows)
Shell executable to use for shell commands.
Shell commands are executed as 'shell shellopts -c command -- arguments'.
On windows, '/c' is used instead of '-c' which should work in 'cmd' and 'powershell'.
shellopts []string (default '')
List of shell options to pass to the shell executable.
smartcase bool (default on)
Override 'ignorecase' option when the pattern contains an uppercase character.
This option has no effect when 'ignorecase' is disabled.
smartdia bool (default off)
Override 'ignoredia' option when the pattern contains a character with diacritic.
This option has no effect when 'ignoredia' is disabled.
sortby string (default 'natural')
Sort type for directories.
Currently supported sort types are 'natural', 'name', 'size', 'time', 'ctime', 'atime', and 'ext'.
tabstop int (default 8)
Number of space characters to show for horizontal tabulation (U+0009) character.
timefmt string (default 'Mon Jan _2 15:04:05 2006')
Format string of the file modification time shown in the bottom line.
truncatechar string (default '~')
Truncate character shown at the end when the file name does not fit to the pane.
wrapscan bool (default on)
Searching can wrap around the file list.
wrapscroll bool (default off)
Scrolling can wrap around the file list.
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').
f
Current file selection as a full path.
fs
Selected file(s) separated with the value of 'filesep' option as full path(s).
fx
Selected file(s) (i.e. 'fs') if there are any selected files, otherwise current file selection (i.e. 'f').
id
Id of the running client.
LF_LEVEL
The value of this variable is set to the current nesting level when you run lf from a shell spawned inside lf.
You can add the value of this variable to your shell prompt to make it clear that your shell runs inside lf.
For example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] && PS1="$PS1""(lf level: $LF_LEVEL) "' in your shell configuration file (e.g. '~/.bashrc').
OPENER
If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others.
EDITOR
If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on unix, 'notepad' in Windows.
PAGER
If this variable is set in the environment, use the same value, otherwise set the value to 'less' on unix, 'more' in Windows.
SHELL
If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on unix, 'cmd' in Windows.
Prefixes Prefixes
The following command prefixes are used by lf: The following command prefixes are used by lf:
@@ -214,14 +708,11 @@ The following command prefixes are used by lf:
% shell-pipe shell command running with the ui % shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press ! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously & shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
The same evaluator is used for the command line and the configuration file for The same evaluator is used for the command line and the configuration file for
read and shell commands. The difference is that prefixes are not necessary in read and shell commands. The difference is that prefixes are not necessary in
the command line. Instead, different modes are provided to read corresponding the command line. Instead, different modes are provided to read corresponding
commands. These modes are mapped to the prefix keys above by default. Searching commands. These modes are mapped to the prefix keys above by default.
commands are only used from the command line.
Syntax Syntax
@@ -528,11 +1019,10 @@ in GNU cp is added to the new files or directories. Only file modes are
preserved and all other attributes are ignored including ownership, timestamps, preserved and all other attributes are ignored including ownership, timestamps,
context, links, and xattr. Special files such as character and block devices, context, links, and xattr. Special files such as character and block devices,
named pipes, and sockets are skipped and links are followed. Moving is named pipes, and sockets are skipped and links are followed. Moving is
performed using the rename operation of the underlying OS. This can fail to performed using the rename operation of the underlying OS. For cross-device
move files between different partitions when it needs to copy files. For these moving, lf falls back to copying and then deletes the original files if there
cases, users are expected to explicitly copy files and then delete the old ones are no errors. Operation errors are shown in the message line as well as the
manually. Operation errors are shown in the message line as well as the log log file and they do not preemptively finish the corresponding file operation.
file and they do not preemptively finish the corresponding file operation.
File operations can be performed on the current selected file or alternatively File operations can be performed on the current selected file or alternatively
on multiple files by selecting them first. When you 'copy' a file, lf doesn't on multiple files by selecting them first. When you 'copy' a file, lf doesn't
@@ -583,7 +1073,16 @@ Globbing supports '*' to match any sequence, '?' to match any character, and
'[...]' or '[^...] to match character sets or ranges. You can enable '[...]' or '[^...] to match character sets or ranges. You can enable
'incsearch' option to jump to the current match at each keystroke while typing. '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 In this mode, you can either use 'cmd-enter' to accept the search or use
'cmd-escape' to cancel the search. '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, 'updir',
and 'open' commands. For example, you can use arrow keys to finish the search
with the following mappings:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'), Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
@@ -623,6 +1122,9 @@ You may want to use either file extensions or mime types from 'file' command:
esac esac
}} }}
You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
Following command is provided by default: Following command is provided by default:
cmd open &$OPENER $f cmd open &$OPENER $f
@@ -675,6 +1177,39 @@ pipe with a SIGPIPE when enough lines are read. When everything else fails, you
can make use of the height argument to only feed the first portion of the file can make use of the height argument to only feed the first portion of the file
to a program for preview. to a program for preview.
Changing 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. If you want to stay in the current directory after quitting, you can
use one of the example wrapper shell scripts provided in the repository.
There is a special command 'on-cd' that runs a shell command when it is defined
and the directory is changed. You can define it just as you would define any
other command:
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\033[32;1m%u@%h\033[0m:\033[34;1m%w\033[0m\033[1m%f$git\033[0m"
lf -remote "send $id set promptfmt \"$fmt\""
}}
This command runs whenever you change directory but not on startup. You can add
an extra call to make it run on startup as well:
cmd on-cd &{{ # ... }}
on-cd
Note that all shell commands are possible but `%` and `&` are usually more
appropriate as `$` and `!` causes flickers and pauses respectively.
Colorschemes Colorschemes
lf tries to automatically adapt its colors to the environment. On startup, lf tries to automatically adapt its colors to the environment. On startup,
@@ -692,25 +1227,29 @@ If both of these environment variables are not set, then lf fallbacks to its
default colorscheme. Default lf colors are taken from GNU dircolors defaults. default colorscheme. Default lf colors are taken from GNU dircolors defaults.
These defaults use 8 basic colors and bold attribute. These defaults use 8 basic colors and bold attribute.
You should also note that lf uses 8 color mode by default which uses sgr 3-bit It is worth noting that lf uses as many colors are advertised by your terminal's
color escapes (e.g. '\033[34m'). If you want to use 256 colors, you need to entry in your systems terminfo or infocmp database, if this is not present lf
enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. will default to an internal database. For terminals supporting 24-bit (or
'\033[38;5;4m'). This option is intended to eliminate differences between "true") color that do not have a database entry (or one that does not advertise
default colors used by ls and lf since terminals may render 3-bit and 8-bit all capabilities), support can be enabled by either setting the '$COLORTERM'
escapes differently even for the same color. variable to "truecolor" or ensuring '$TERM' is set to a value that ends with
"-truecolor".
Keeping this mechanism in mind, you can configure lf colors in two different Keeping this in mind, you can configure lf colors in two different ways. First,
ways. First, you can configure 8 basic colors used by your terminal and lf you can configure 8 basic colors used by your terminal and lf should pick up
should pick up those colors automatically. Depending on your terminal, you those colors automatically. Depending on your terminal, you should be able to
should be able to select your colors from a 24-bit palette. This is the select your colors from a 24-bit palette. This is the recommended approach as
recommended approach as colors used by other programs will also match each colors used by other programs will also match each other.
other.
Second, you can set the values of environmental variables mentioned above for Second, you can set the values of environmental variables mentioned above for
fine grained customization. This is useful to change colors used for different fine grained customization. This is useful to change colors used for different
file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it
it can be used even when GNU programs are not installed on the system. You can can be used even when GNU programs are not installed on the system. You can
combine this second method with the first method for best results. combine this second method with the first method for best results. lf can also
be configured to ignore your terminal theme and output colors "as they were
intended" by translating all numbered colors into a 24-bit output that matches
the description; this can be enabled by setting the environment variable
'$TCELL_TRUECOLOR' to "on" (or any text except ""/nothing or "disable").
Lastly, you may also want to configure the colors of the prompt line to match Lastly, you may also want to configure the colors of the prompt line to match
the rest of the colors. Colors of the prompt line can be configured using the the rest of the colors. Colors of the prompt line can be configured using the
+711 -119
View File
@@ -15,10 +15,11 @@ command (default '<f-1>') inside lf to view the documentation in a pager.
You can run 'lf -help' to see descriptions of command line options. You can run 'lf -help' to see descriptions of command line options.
Reference Quick Reference
The following commands are provided by lf with default keybindings: The following commands are provided by lf:
quit (default 'q')
up (default 'k' and '<up>') up (default 'k' and '<up>')
half-up (default '<c-u>') half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>') page-up (default '<c-b>' and '<pgup>')
@@ -27,138 +28,132 @@ The following commands are provided by lf with default keybindings:
page-down (default '<c-f>' and '<pgdn>') page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>') updir (default 'h' and '<left>')
open (default 'l' and '<right>') open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
toggle (default '<space>') toggle
invert (default 'v') invert (default 'v')
unselect (default 'u') unselect (default 'u')
glob-select
glob-unselect
copy (default 'y') copy (default 'y')
cut (default 'd') cut (default 'd')
paste (default 'p') paste (default 'p')
clear (default 'c') clear (default 'c')
sync
draw
redraw (default '<c-l>') redraw (default '<c-l>')
load
reload (default '<c-r>') reload (default '<c-r>')
read (default ':') echo
shell (default '$') echomsg
shell-pipe (default '%') echoerr
shell-wait (default '!') cd
shell-async (default '&') select
find (default 'f') delete (modal)
find-back (default 'F') rename (modal) (default 'r')
source
push
read (modal) (default ':')
shell (modal) (default '$')
shell-pipe (modal) (default '%')
shell-wait (modal) (default '!')
shell-async (modal) (default '&')
find (modal) (default 'f')
find-back (modal) (default 'F')
find-next (default ';') find-next (default ';')
find-prev (default ',') find-prev (default ',')
search (default '/') search (modal) (default '/')
search-back (default '?') search-back (modal) (default '?')
search-next (default 'n') search-next (default 'n')
search-prev (default 'N') search-prev (default 'N')
mark-save (default 'm') mark-save (modal) (default 'm')
mark-load (default "'") mark-load (modal) (default "'")
mark-remove (modal) (default '"')
The following commands are provided by lf without default keybindings: The following command line commands are provided by lf:
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default
keybindings:
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>') cmd-end (default '<c-e>' and '<end>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<backspace>' and '<backspace2>')
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-transpose-word (default '<a-t>')
cmd-word (default '<a-f>') cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>') cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>') cmd-delete-word (default '<a-d>')
cmd-capitalize-word (default '<a-c>')
cmd-uppercase-word (default '<a-u>') cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>') cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
anchorfind boolean (default on) anchorfind bool (default on)
color256 boolean (default off) dircounts bool (default off)
dircounts boolean (default off) dirfirst bool (default on)
dirfirst boolean (default on) drawbox bool (default off)
drawbox boolean (default off) errorfmt string (default "\033[7;31;47m%s\033[0m")
globsearch boolean (default off) filesep string (default "\n")
hidden boolean (default off) findlen int (default 1)
ignorecase boolean (default on) globsearch bool (default off)
ignoredia boolean (default off) hidden bool (default off)
incsearch boolean (default off) hiddenfiles []string (default '.*')
preview boolean (default on) icons bool (default off)
reverse boolean (default off) ifs string (default '')
smartcase boolean (default on) ignorecase bool (default on)
smartdia boolean (default off) ignoredia bool (default off)
wrapscan boolean (default on) incsearch bool (default off)
number boolean (default off) info []string (default '')
relativenumber boolean (default off) number bool (default off)
findlen integer (default 1) (zero to prompt until single match) period int (default 0)
period integer (default 0) (zero to disable periodic loading) preview bool (default on)
scrolloff integer (default 0) previewer string (default '')
tabstop integer (default 8) promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
errorfmt string (default "\033[7;31;47m%s\033[0m") ratios []int (default '1:2:3')
filesep string (default "\n") relativenumber bool (default off)
ifs string (default ”) (not exported if empty) reverse bool (default off)
previewer string (default ”) (not filtered if empty) scrolloff int (default 0)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m") shell string (default 'sh' for unix and 'cmd' for windows)
shell string (default 'sh') shellopts []string (default '')
sortby string (default 'natural') smartcase bool (default on)
timefmt string (default 'Mon Jan _2 15:04:05 2006') smartdia bool (default off)
ratios string (default '1:2:3') sortby string (default 'natural')
info string (default ”) tabstop int (default 8)
shellopts string (default ”) timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~')
wrapscan bool (default on)
wrapscroll bool (default off)
The following variables are exported for shell commands: The following environment variables are exported for shell commands:
$f current file f
$fs selected file(s) separated with 'filesep' fs
$fx current file or selected file(s) if any fx
$id id number of the client id
LF_LEVEL
OPENER
EDITOR
PAGER
SHELL
The following variables are set to the corresponding values: The following commands/keybindings are provided by default:
$LF_LEVEL current nesting level unix windows
cmd open &$OPENER "$f" cmd open &%OPENER% %f%
The following default values are set to the environmental variables on unix map e $$EDITOR "$f" map e $%EDITOR% %f%
when they are not set or empty: map i $$PAGER "$f" map i !%PAGER% %f%
map w $$SHELL map w $%SHELL%
$OPENER open # macos
$OPENER xdg-open # others
$EDITOR vi
$PAGER less
$SHELL sh
The following default values are set to the environmental variables on
windows when they are not set or empty:
%OPENER% start
%EDITOR% notepad
%PAGER% more
%SHELL% cmd
The following additional keybindings are provided by default: The following additional keybindings are provided by default:
@@ -171,13 +166,11 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info map sn :set sortby natural; set info
map ss :set sortby size; set info size map ss :set sortby size; set info size
map st :set sortby time; set info time map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~ map gh cd ~
map <space> :toggle; down
The following keybindings to applications are provided by default:
map e $$EDITOR $f
map i $$PAGER $f
map w $$SHELL
Configuration Configuration
@@ -210,6 +203,557 @@ 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
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.
quit (default 'q')
Quit lf and return to the shell.
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
Move the current file selection upwards/downwards by one/half a page/full
page.
updir (default 'h' and '<left>')
Change the current working directory to the parent directory.
open (default 'l' and '<right>')
If the current file is a directory, then change the current directory to it,
otherwise, execute the 'open' command. A default 'open' command is provided
to call the default system opener asynchronously with the current file as
the argument. A custom 'open' command can be defined to override this
default.
(See also 'OPENER' variable and 'Opening Files' section)
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
Move the current file selection to the top/bottom of the directory.
toggle
Toggle the selection of the current file or files given as arguments.
invert (default 'v')
Reverse the selection of all files in the current directory (i.e. 'toggle'
all files). Selections in other directories are not effected by this
command. You can define a new command to select all files in the directory
by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect;
invert'), though this will also remove selections in other directories.
unselect (default 'u')
Remove the selection of all files in all directories.
glob-select
Select files that match the given glob.
glob-unselect
Unselect files that match the given glob.
copy (default 'y')
If there are no selections, save the path of the current file to the copy
buffer, otherwise, copy the paths of selected files.
cut (default 'd')
If there are no selections, save the path of the current file to the cut
buffer, otherwise, copy the paths of selected files.
paste (default 'p')
Copy/Move files in copy/cut buffer to the current working directory.
clear (default 'c')
Clear file paths in copy/cut buffer.
sync
Synchronize copied/cut files with server. This command is automatically
called when required.
draw
Draw the screen. This command is automatically called when required.
redraw (default '<c-l>')
Synchronize the terminal and redraw the screen.
load
Load modified files and directories. This command is automatically called
when required.
reload (default '<c-r>')
Flush the cache and reload all files and directories.
echo
Print given arguments to the message line at the bottom.
echomsg
Print given arguments to the message line at the bottom and also to the log
file.
echoerr
Print given arguments to the message line at the bottom in red color and
also to the log file.
cd
Change the working directory to the given argument.
select
Change the current file selection to the given argument.
delete (modal)
Remove the current file or selected file(s).
rename (modal) (default 'r')
Rename the current file using the builtin method. A custom 'rename' command
can be defined to override this default.
source
Read the configuration file given in the argument.
push
Simulate key pushes given in the argument.
read (modal) (default ':')
Read a command to evaluate.
shell (modal) (default '$')
Read a shell command to execute.
(See also 'Prefixes' and 'Shell Commands' sections)
shell-pipe (modal) (default '%')
Read a shell command to execute piping its standard I/O to the bottom
statline.
(See also 'Prefixes' and 'Piping Shell Commands' sections)
shell-wait (modal) (default '!')
Read a shell command to execute and wait for a key press in the end.
(See also 'Prefixes' and 'Waiting Shell Commands' sections)
shell-async (modal) (default '&')
Read a shell command to execute synchronously without standard I/O.
find (modal) (default 'f')
find-back (modal) (default 'F')
find-next (default ';')
find-prev (default ',')
Read key(s) to find the appropriate file name match in the forward/backward
direction and jump to the next/previous match.
(See also 'anchorfind', 'findlen', 'wrapscan', 'ignorecase', 'smartcase',
'ignoredia', and 'smartdia' options and 'Searching Files' section)
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
Read a pattern to search for a file name match in the forward/backward
direction and jump to the next/previous match.
(See also 'globsearch', 'incsearch', 'wrapscan', 'ignorecase', 'smartcase',
'ignoredia', and 'smartdia' options and 'Searching Files' section)
mark-save (modal) (default 'm')
Save the current directory as a bookmark assigned to the given key.
mark-load (modal) (default "'")
Change the current directory to the bookmark assigned to the given key. A
special bookmark "'" holds the previous directory after a 'mark-load', 'cd',
or 'select' command.
mark-remove (modal) (default '"')
Remove a bookmark assigned to the given key.
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.
cmd-escape (default '<esc>')
Quit command line mode and return to normal mode.
cmd-complete (default '<tab>')
Autocomplete the current word.
cmd-enter (default '<c-j>' and '<enter>')
Execute the current line.
cmd-interrupt (default '<c-c>')
Interrupt the current shell-pipe command and return to the normal mode.
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
Go to next/previous item in the history.
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
Move the cursor to the left/right.
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
Move the cursor to the beginning/end of line.
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<backspace>' and '<backspace2>')
Delete the next character in forward/backward direction.
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
Delete everything up to the beginning/end of line.
cmd-delete-unix-word (default '<c-w>')
Delete the previous unix word.
cmd-yank (default '<c-y>')
Paste the buffer content containing the last deleted item.
cmd-transpose (default '<c-t>')
cmd-transpose-word (default '<a-t>')
Transpose the positions of last two characters/words.
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
Move the cursor by one word in forward/backward direction.
cmd-delete-word (default '<a-d>')
Delete the next word in forward direction.
cmd-capitalize-word (default '<a-c>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
Capitalize/uppercase/lowercase the current word and jump to the next word.
Options
This section shows information about options to customize the behavior.
Character ':' is used as the separator for list options '[]int' and
'[]string'.
anchorfind bool (default on)
When this option is enabled, find command starts matching patterns from the
beginning of file names, otherwise, it can match at an arbitrary position.
dircounts bool (default off)
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+'.
dirfirst bool (default on)
Show directories first above regular files.
drawbox bool (default off)
Draw boxes around panes with box drawing characters.
errorfmt string (default "\033[7;31;47m%s\033[0m")
Format string of error messages shown in the bottom message line.
filesep string (default "\n")
File separator used in environment variables 'fs' and 'fx'.
findlen int (default 1)
Number of characters prompted for the find command. When this value is set
to 0, find command prompts until there is only a single match left.
globsearch bool (default off)
When this option is enabled, search command patterns are considered as
globs, otherwise they are literals. With globbing, '*' matches any sequence,
'?' matches any character, and '[...]' or '[^...] matches character sets or
ranges. Otherwise, these characters are interpreted as they are.
hidden bool (default off)
Show hidden files. On unix systems, hidden files are determined by the value
of 'hiddenfiles'. On windows, only files with hidden attributes are
considered hidden files.
hiddenfiles []string (default '.*')
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.
icons bool (default off)
Show icons before each item in the list. By default, only two icons, 🗀
(U+1F5C0) and 🗎 (U+1F5CE), are used for directories and files respectively,
as they are supported in the unicode standard. Icons can be configured with
an environment variable named 'LF_ICONS'. The syntax of this variable is
similar to 'LS_COLORS'. See the wiki page for an example icon configuration.
ifs string (default '')
Sets 'IFS' variable in shell commands. It works by adding the assignment to
the beginning of the command string as 'IFS='...'; ...'. The reason is that
'IFS' variable is not inherited by the shell for security reasons. This
method assumes a POSIX shell syntax and so it can fail for non-POSIX shells.
This option has no effect when the value is left empty. This option does not
have any effect on windows.
ignorecase bool (default on)
Ignore case in search patterns.
ignoredia bool (default off)
Ignore diacritics in search patterns.
incsearch bool (default off)
Jump to the first match after each keystroke during searching.
info []string (default '')
List of information shown for directory items at the right side of pane.
Currently supported information types are 'size', 'time', 'atime', and
'ctime'. Information is only shown when the pane width is more than twice
the width of information.
number bool (default off)
Show the position number for directory items at the left side of pane. When
'relativenumber' is enabled, only the current line shows the absolute
position and relative positions are shown for the rest.
period int (default 0)
Set the interval in seconds for periodic checks of directory updates. This
works by periodically calling the 'load' command. Note that directories are
already updated automatically in many cases. This option can be useful when
there is an external process changing the displayed directory and you are
not doing anything in lf. Periodic checks are disabled when the value of
this option is set to zero.
preview bool (default on)
Show previews of files and directories at the right most pane. If the file
has more lines than the preview pane, rest of the lines are not read. Files
containing the null character (U+0000) in the read portion are considered
binary files and displayed as 'binary'.
previewer string (default '') (not filtered if empty)
Set the path of a previewer file to filter the content of regular files for
previewing. The file should be executable. Two arguments are passed to the
file, first is the current file name, and second is the height of preview
pane. SIGPIPE signal is sent when enough lines are read. Preview filtering
is disabled and files are displayed as they are when the value of this
option is left empty.
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
Format string of the prompt shown in the top line. Special expansions are
provided, '%u' as the user name, '%h' as the host name, '%w' as the working
directory, and '%f' as the file name. 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.
ratios []int (default '1:2:3')
List of ratios of pane widths. Number of items in the list determines the
number of panes in the ui. When 'preview' option is enabled, the right most
number is used for the width of preview pane.
relativenumber bool (default off)
Show the position number relative to the current line. When 'number' is
enabled, current line shows the absolute position, otherwise nothing is
shown.
reverse bool (default off)
Reverse the direction of sort.
scrolloff int (default 0)
Minimum number of offset lines shown at all times in the top and the bottom
of the screen when scrolling. The current line is kept in the middle when
this option is set to a large value that is bigger than the half of number
of lines. A smaller offset can be used when the current file is close to the
beginning or end of the list to show the maximum number of items.
shell string (default 'sh' for unix and 'cmd' for windows)
Shell executable to use for shell commands. Shell commands are executed as
'shell shellopts -c command -- arguments'. On windows, '/c' is used instead
of '-c' which should work in 'cmd' and 'powershell'.
shellopts []string (default '')
List of shell options to pass to the shell executable.
smartcase bool (default on)
Override 'ignorecase' option when the pattern contains an uppercase
character. This option has no effect when 'ignorecase' is disabled.
smartdia bool (default off)
Override 'ignoredia' option when the pattern contains a character with
diacritic. This option has no effect when 'ignoredia' is disabled.
sortby string (default 'natural')
Sort type for directories. Currently supported sort types are 'natural',
'name', 'size', 'time', 'ctime', 'atime', and 'ext'.
tabstop int (default 8)
Number of space characters to show for horizontal tabulation (U+0009)
character.
timefmt string (default 'Mon Jan _2 15:04:05 2006')
Format string of the file modification time shown in the bottom line.
truncatechar string (default '~')
Truncate character shown at the end when the file name does not fit to the
pane.
wrapscan bool (default on)
Searching can wrap around the file list.
wrapscroll bool (default off)
Scrolling can wrap around the file list.
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').
f
Current file selection as a full path.
fs
Selected file(s) separated with the value of 'filesep' option as full
path(s).
fx
Selected file(s) (i.e. 'fs') if there are any selected files, otherwise
current file selection (i.e. 'f').
id
Id of the running client.
LF_LEVEL
The value of this variable is set to the current nesting level when you run
lf from a shell spawned inside lf. You can add the value of this variable to
your shell prompt to make it clear that your shell runs inside lf. For
example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] &&
PS1="$PS1""(lf level: $LF_LEVEL) "' in your shell configuration file (e.g.
'~/.bashrc').
OPENER
If this variable is set in the environment, use the same value, otherwise
set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others.
EDITOR
If this variable is set in the environment, use the same value, otherwise
set the value to 'vi' on unix, 'notepad' in Windows.
PAGER
If this variable is set in the environment, use the same value, otherwise
set the value to 'less' on unix, 'more' in Windows.
SHELL
If this variable is set in the environment, use the same value, otherwise
set the value to 'sh' on unix, 'cmd' in Windows.
Prefixes Prefixes
The following command prefixes are used by lf: The following command prefixes are used by lf:
@@ -219,14 +763,12 @@ The following command prefixes are used by lf:
% shell-pipe shell command running with the ui % shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press ! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously & shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
The same evaluator is used for the command line and the configuration file The same evaluator is used for the command line and the configuration file
for read and shell commands. The difference is that prefixes are not for read and shell commands. The difference is that prefixes are not
necessary in the command line. Instead, different modes are provided to read necessary in the command line. Instead, different modes are provided to read
corresponding commands. These modes are mapped to the prefix keys above by corresponding commands. These modes are mapped to the prefix keys above by
default. Searching commands are only used from the command line. default.
Syntax Syntax
@@ -550,10 +1092,9 @@ option in GNU cp is added to the new files or directories. Only file modes
are preserved and all other attributes are ignored including ownership, are preserved and all other attributes are ignored including ownership,
timestamps, context, links, and xattr. Special files such as character and timestamps, context, links, and xattr. Special files such as character and
block devices, named pipes, and sockets are skipped and links are followed. block devices, named pipes, and sockets are skipped and links are followed.
Moving is performed using the rename operation of the underlying OS. This Moving is performed using the rename operation of the underlying OS. For
can fail to move files between different partitions when it needs to copy cross-device moving, lf falls back to copying and then deletes the original
files. For these cases, users are expected to explicitly copy files and then files if there are no errors. Operation errors are shown in the message line
delete the old ones manually. Operation errors are shown in the message line
as well as the log file and they do not preemptively finish the as well as the log file and they do not preemptively finish the
corresponding file operation. corresponding file operation.
@@ -608,7 +1149,16 @@ pattern. Globbing supports '*' to match any sequence, '?' to match any
character, and '[...]' or '[^...] to match character sets or ranges. You can character, and '[...]' or '[^...] to match character sets or ranges. You can
enable 'incsearch' option to jump to the current match at each keystroke 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 while typing. In this mode, you can either use 'cmd-enter' to accept the
search or use 'cmd-escape' to cancel the search. 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, 'updir', and 'open' commands. For example, you can use arrow
keys to finish the search with the following mappings:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'), Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
@@ -650,6 +1200,9 @@ command:
esac esac
}} }}
You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
Following command is provided by default: Following command is provided by default:
cmd open &$OPENER $f cmd open &$OPENER $f
@@ -705,6 +1258,41 @@ everything else fails, you can make use of the height argument to only feed
the first portion of the file to a program for preview. the first portion of the file to a program for preview.
Changing 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. If you want to stay in the current directory after quitting,
you can use one of the example wrapper shell scripts provided in the
repository.
There is a special command 'on-cd' that runs a shell command when it is
defined and the directory is changed. You can define it just as you would
define any other command:
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\033[32;1m%u@%h\033[0m:\033[34;1m%w\033[0m\033[1m%f$git\033[0m"
lf -remote "send $id set promptfmt \"$fmt\""
}}
This command runs whenever you change directory but not on startup. You can
add an extra call to make it run on startup as well:
cmd on-cd &{{ # ... }}
on-cd
Note that all shell commands are possible but '%' and '&' are usually more
appropriate as '$' and '!' causes flickers and pauses respectively.
Colorschemes Colorschemes
lf tries to automatically adapt its colors to the environment. On startup, lf tries to automatically adapt its colors to the environment. On startup,
@@ -724,26 +1312,30 @@ If both of these environment variables are not set, then lf fallbacks to its
default colorscheme. Default lf colors are taken from GNU dircolors default colorscheme. Default lf colors are taken from GNU dircolors
defaults. These defaults use 8 basic colors and bold attribute. defaults. These defaults use 8 basic colors and bold attribute.
You should also note that lf uses 8 color mode by default which uses sgr It is worth noting that lf uses as many colors are advertised by your
3-bit color escapes (e.g. '\033[34m'). If you want to use 256 colors, you terminal's entry in your systems terminfo or infocmp database, if this is
need to enable 'color256' option which then makes lf use sgr 8-bit color not present lf will default to an internal database. For terminals
escapes (e.g. '\033[38;5;4m'). This option is intended to eliminate supporting 24-bit (or "true") color that do not have a database entry (or
differences between default colors used by ls and lf since terminals may one that does not advertise all capabilities), support can be enabled by
render 3-bit and 8-bit escapes differently even for the same color. either setting the '$COLORTERM' variable to "truecolor" or ensuring '$TERM'
is set to a value that ends with "-truecolor".
Keeping this mechanism in mind, you can configure lf colors in two different Keeping this in mind, you can configure lf colors in two different ways.
ways. First, you can configure 8 basic colors used by your terminal and lf First, you can configure 8 basic colors used by your terminal and lf should
should pick up those colors automatically. Depending on your terminal, you pick up those colors automatically. Depending on your terminal, you should
should be able to select your colors from a 24-bit palette. This is the be able to select your colors from a 24-bit palette. This is the recommended
recommended approach as colors used by other programs will also match each approach as colors used by other programs will also match each other.
other.
Second, you can set the values of environmental variables mentioned above Second, you can set the values of environmental variables mentioned above
for fine grained customization. This is useful to change colors used for for fine grained customization. This is useful to change colors used for
different file types and extensions. '$LS_COLORS' is more powerful than different file types and extensions. '$LS_COLORS' is more powerful than
'$LSCOLORS' and it can be used even when GNU programs are not installed on '$LSCOLORS' and it can be used even when GNU programs are not installed on
the system. You can combine this second method with the first method for the system. You can combine this second method with the first method for
best results. best results. lf can also be configured to ignore your terminal theme and
output colors "as they were intended" by translating all numbered colors
into a 24-bit output that matches the description; this can be enabled by
setting the environment variable '$TCELL_TRUECOLOR' to "on" (or any text
except ""/nothing or "disable").
Lastly, you may also want to configure the colors of the prompt line to Lastly, you may also want to configure the colors of the prompt line to
match the rest of the colors. Colors of the prompt line can be configured match the rest of the colors. Colors of the prompt line can be configured
+12
View File
@@ -0,0 +1,12 @@
#
# For using these completions you must load it from .tcshrc
#
# source ~/.config/lf/lf.csh
#
set lf_args = "-command -cpuprofile -doc --help -last-dir-path -memprofile -remote -selection-path -server -version --version"
uncomplete lf
uncomplete lfcd
complete lf "C/-*/(${lf_args})/"
complete lfcd "C/-*/(${lf_args})/"
+29
View File
@@ -0,0 +1,29 @@
#compdef lf
# For using these completions you must:
# - rename this file to _lf
# - add the containing folder to $fpath in .zshrc, like this:
# '''
# fpath=(/path/to/folder/containing_lf $fpath)
# autoload -U compinit
# compinit
# '''
#
# zsh completions for 'lf'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
local arguments
arguments=(
'-command[command to execute on client initialization]'
'-cpuprofile[path to the file to write the CPU profile]'
'-doc[show documentation]'
'-last-dir-path[path to the file to write the last dir on exit (to use for cd)]'
'-memprofile[path to the file to write the memory profile]'
'-remote[send remote command to server]'
'-selection-path[path to the file to write selected files on open (to use as open file dialog)]'
'-server[start server (automatic)]'
'-version[show version]'
'*:filename:_files'
)
_arguments -s $arguments
+6 -6
View File
@@ -5,11 +5,11 @@ rem You need to put this file to a folder in %PATH% variable.
:tmploop :tmploop
set tmpfile="%tmp%\lf.%random%.tmp" set tmpfile="%tmp%\lf.%random%.tmp"
if exist "%tmpfile%" goto:tmploop if exist %tmpfile% goto:tmploop
lf -last-dir-path="%tmpfile%" %* lf -last-dir-path=%tmpfile% %*
if not exist "%tmpfile%" exit if not exist %tmpfile% exit
set /p dir=<"%tmpfile%" set /p dir=<%tmpfile%
del /f "%tmpfile%" del /f %tmpfile%
if not exist "%dir%" exit if not exist "%dir%" exit
if "%dir%" == "%cd%" exit if "%dir%" == "%cd%" exit
cd "%dir%" cd /d "%dir%"
+13
View File
@@ -0,0 +1,13 @@
# Change working dir in shell to last dir in lf on exit.
#
# You need to either copy the content of this file to your shell rc file
# (e.g. ~/.tcshrc) or source this file directly:
#
# setenv LF_HOME "${HOME}/.config/lf"
# [ -e "${LF_HOME}/lfcd.csh" ] && source "${LF_HOME}/lfcd.csh"
#
# You may also like to assign a key to this command:
#
# bindkey -c "^O" lfcd
#
alias lfcd 'set _=`mktemp` && lf -last-dir-path=$_ "\!*" && set _=`cat $_ && rm -f $_` && [ -d "$_" ] && cd "$_"'
+4 -4
View File
@@ -38,13 +38,13 @@ map O $mimeopen --ask $f
cmd open ${{ cmd open ${{
case $(file --mime-type $f -b) in case $(file --mime-type $f -b) in
text/*) $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
}} }}
# rename current file without overwrite # define a custom 'rename' command without prompt for overwrite
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 # cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
map r push :rename<space> # map r push :rename<space>
# make sure trash folder exists # make sure trash folder exists
# %mkdir -p ~/.trash # %mkdir -p ~/.trash
+428 -180
View File
File diff suppressed because it is too large. Load diff
+65 -27
View File
@@ -67,8 +67,8 @@ var gEvalTests = []struct {
{ {
`echo "hello\zworld"`, `echo "hello\zworld"`,
[]string{"echo", "helloworld", "\n"}, []string{"echo", `hello\zworld`, "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}, 1}}, []expr{&callExpr{"echo", []string{`hello\zworld`}, 1}},
}, },
{ {
@@ -90,7 +90,7 @@ var gEvalTests = []struct {
}, },
{ {
`echo hello\ world`, "echo hello\\\tworld",
[]string{"echo", "hello\tworld", "\n"}, []string{"echo", "hello\tworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\tworld"}, 1}}, []expr{&callExpr{"echo", []string{"hello\tworld"}, 1}},
}, },
@@ -101,10 +101,16 @@ var gEvalTests = []struct {
[]expr{&callExpr{"echo", []string{"hello\nworld"}, 1}}, []expr{&callExpr{"echo", []string{"hello\nworld"}, 1}},
}, },
{
`echo hello\\world`,
[]string{"echo", `hello\world`, "\n"},
[]expr{&callExpr{"echo", []string{`hello\world`}, 1}},
},
{ {
`echo hello\zworld`, `echo hello\zworld`,
[]string{"echo", "helloworld", "\n"}, []string{"echo", "hellozworld", "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}, 1}}, []expr{&callExpr{"echo", []string{"hellozworld"}, 1}},
}, },
{ {
@@ -125,6 +131,18 @@ var gEvalTests = []struct {
[]expr{&setExpr{"hidden", ""}, &setExpr{"preview", ""}}, []expr{&setExpr{"hidden", ""}, &setExpr{"preview", ""}},
}, },
{
`set ifs ""`,
[]string{"set", "ifs", "", "\n"},
[]expr{&setExpr{"ifs", ""}},
},
{
`set ifs "\n"`,
[]string{"set", "ifs", "\n", "\n"},
[]expr{&setExpr{"ifs", "\n"}},
},
{ {
"set ratios 1:2:3", "set ratios 1:2:3",
[]string{"set", "ratios", "1:2:3", "\n"}, []string{"set", "ratios", "1:2:3", "\n"},
@@ -140,25 +158,37 @@ var gEvalTests = []struct {
{ {
":set ratios 1:2:3", ":set ratios 1:2:3",
[]string{":", "set", "ratios", "1:2:3", "\n", "\n"}, []string{":", "set", "ratios", "1:2:3", "\n", "\n"},
[]expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}}}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}},
}, },
{ {
":set ratios 1:2:3\nset hidden", ":set ratios 1:2:3\nset hidden",
[]string{":", "set", "ratios", "1:2:3", "\n", "\n", "set", "hidden", "\n"}, []string{":", "set", "ratios", "1:2:3", "\n", "\n", "set", "hidden", "\n"},
[]expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}}, &setExpr{"hidden", ""}}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}, &setExpr{"hidden", ""}},
}, },
{ {
":set ratios 1:2:3;", ":set ratios 1:2:3;",
[]string{":", "set", "ratios", "1:2:3", ";", "\n"}, []string{":", "set", "ratios", "1:2:3", ";", "\n"},
[]expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}}}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}},
}, },
{ {
":set ratios 1:2:3;\nset hidden", ":set ratios 1:2:3;\nset hidden",
[]string{":", "set", "ratios", "1:2:3", ";", "\n", "set", "hidden", "\n"}, []string{":", "set", "ratios", "1:2:3", ";", "\n", "set", "hidden", "\n"},
[]expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}}, &setExpr{"hidden", ""}}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}, &setExpr{"hidden", ""}},
},
{
"set ratios 1:2:3\n set hidden",
[]string{"set", "ratios", "1:2:3", "\n", "set", "hidden", "\n"},
[]expr{&setExpr{"ratios", "1:2:3"}, &setExpr{"hidden", ""}},
},
{
"set ratios 1:2:3 \nset hidden",
[]string{"set", "ratios", "1:2:3", "\n", "set", "hidden", "\n"},
[]expr{&setExpr{"ratios", "1:2:3"}, &setExpr{"hidden", ""}},
}, },
{ {
@@ -176,13 +206,13 @@ var gEvalTests = []struct {
{ {
"map gh :cd ~", "map gh :cd ~",
[]string{"map", "gh", ":", "cd", "~", "\n", "\n"}, []string{"map", "gh", ":", "cd", "~", "\n", "\n"},
[]expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}}}}, []expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}, 1}}},
}, },
{ {
"map gh :cd ~;", "map gh :cd ~;",
[]string{"map", "gh", ":", "cd", "~", ";", "\n"}, []string{"map", "gh", ":", "cd", "~", ";", "\n"},
[]expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}}}}, []expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}, 1}}},
}, },
{ {
@@ -218,13 +248,13 @@ var gEvalTests = []struct {
{ {
"map u :usage", "map u :usage",
[]string{"map", "u", ":", "usage", "\n", "\n"}, []string{"map", "u", ":", "usage", "\n", "\n"},
[]expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}}}}, []expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}, 1}}},
}, },
{ {
"map u :usage;", "map u :usage;",
[]string{"map", "u", ":", "usage", ";", "\n"}, []string{"map", "u", ":", "usage", ";", "\n"},
[]expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}}}}, []expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}, 1}}},
}, },
{ {
@@ -248,13 +278,13 @@ var gEvalTests = []struct {
{ {
"map r :push :rename<space>", "map r :push :rename<space>",
[]string{"map", "r", ":", "push", ":rename<space>", "\n", "\n"}, []string{"map", "r", ":", "push", ":rename<space>", "\n", "\n"},
[]expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}, 1}}}}}, []expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}, 1}}, 1}}},
}, },
{ {
"map r :push :rename<space> ; set hidden", "map r :push :rename<space> ; set hidden",
[]string{"map", "r", ":", "push", ":rename<space>", ";", "set", "hidden", "\n", "\n"}, []string{"map", "r", ":", "push", ":rename<space>", ";", "set", "hidden", "\n", "\n"},
[]expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}, 1}, &setExpr{"hidden", ""}}}}}, []expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}, 1}, &setExpr{"hidden", ""}}, 1}}},
}, },
{ {
@@ -278,13 +308,13 @@ var gEvalTests = []struct {
{ {
"map ss :set sortby size; set info size", "map ss :set sortby size; set info size",
[]string{"map", "ss", ":", "set", "sortby", "size", ";", "set", "info", "size", "\n", "\n"}, []string{"map", "ss", ":", "set", "sortby", "size", ";", "set", "info", "size", "\n", "\n"},
[]expr{&mapExpr{"ss", &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}}}}, []expr{&mapExpr{"ss", &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}}},
}, },
{ {
"map ss :set sortby size; set info size;", "map ss :set sortby size; set info size;",
[]string{"map", "ss", ":", "set", "sortby", "size", ";", "set", "info", "size", ";", "\n"}, []string{"map", "ss", ":", "set", "sortby", "size", ";", "set", "info", "size", ";", "\n"},
[]expr{&mapExpr{"ss", &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}}}}, []expr{&mapExpr{"ss", &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}}},
}, },
{ {
@@ -292,13 +322,17 @@ var gEvalTests = []struct {
cd ~ cd ~
set hidden set hidden
}}`, }}`,
[]string{"cmd", "gohome", ":", "{{", []string{
"cmd", "gohome", ":", "{{",
"cd", "~", "\n", "cd", "~", "\n",
"set", "hidden", "\n", "set", "hidden", "\n",
"}}", "\n"}, "}}", "\n",
[]expr{&cmdExpr{"gohome", &listExpr{[]expr{ },
&callExpr{"cd", []string{"~"}, 1}, []expr{&cmdExpr{
&setExpr{"hidden", ""}}}, "gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}, 1},
}}, }},
}, },
@@ -307,13 +341,17 @@ var gEvalTests = []struct {
cd ~ cd ~
set hidden set hidden
}}`, }}`,
[]string{"map", "gh", ":", "{{", []string{
"map", "gh", ":", "{{",
"cd", "~", "\n", "cd", "~", "\n",
"set", "hidden", "\n", "set", "hidden", "\n",
"}}", "\n"}, "}}", "\n",
[]expr{&mapExpr{"gh", &listExpr{[]expr{ },
&callExpr{"cd", []string{"~"}, 1}, []expr{&mapExpr{
&setExpr{"hidden", ""}}}, "gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}, 1},
}}, }},
}, },
+41 -24
View File
@@ -14,28 +14,45 @@ set -o verbose
mkdir -p dist mkdir -p dist
CGO_ENABLED=0 GOOS=darwin GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-darwin-386.tar.gz lf --remove-files # https://golang.org/doc/install/source#environment
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-darwin-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-dragonfly-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-freebsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-freebsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-freebsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-ppc64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-ppc64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mips.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mipsle.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mips64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mips64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-netbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-netbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-netbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-openbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-openbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-openbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && zip dist/lf-windows-386.zip lf.exe --move CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && zip dist/lf-windows-amd64.zip lf.exe --move CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-dragonfly-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=illumos GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-illumos-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mipsle.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=s390x go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-s390x.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=solaris GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-solaris-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-386.zip lf.exe --move
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-amd64.zip lf.exe --move
# not supported
# CGO_ENABLED=0 GOOS=aix GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-aix-ppc64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-386.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-amd64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-arm64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-js-wasm.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-386.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-amd64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-arm.tar.gz lf --remove-files
+3 -2
View File
@@ -3,6 +3,7 @@ module github.com/gokcehan/lf
go 1.12 go 1.12
require ( require (
github.com/mattn/go-runewidth v0.0.4 github.com/gdamore/tcell v1.3.0
github.com/nsf/termbox-go v0.0.0-20190325093121-288510b9734e github.com/mattn/go-runewidth v0.0.9
gopkg.in/djherbis/times.v1 v1.2.0
) )
+16 -7
View File
@@ -1,8 +1,17 @@
github.com/mattn/go-runewidth v0.0.3 h1:a+kO+98RDGEfo6asOGMmpodZq4FNtnGP54yps8BzLR4= github.com/DATA-DOG/go-sqlmock v1.3.3 h1:CWUqKXe0s8A2z6qCgkP4Kru7wC11YoAnoupUKFDnH08=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y= github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/tcell v1.3.0 h1:r35w0JBADPZCVQijYebl6YMWWtHRqVEGt7kL2eBADRM=
github.com/gdamore/tcell v1.3.0/go.mod h1:Hjvr+Ofd+gLglo7RYKxxnzCBmev3BzsS67MebKS4zMM=
github.com/lucasb-eyer/go-colorful v1.0.2 h1:mCMFu6PgSozg9tDNMMK3g18oJBX7oYGrC09mS6CXfO4=
github.com/lucasb-eyer/go-colorful v1.0.2/go.mod h1:0MS4r+7BZKSJ5mw4/S5MPN+qHFF1fYclkSPilDOKW0s=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/nsf/termbox-go v0.0.0-20180613055208-5c94acc5e6eb h1:YahEjAGkJtCrkqgVHhX6n8ZX+CZ3hDRL9fjLYugLfSs= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/nsf/termbox-go v0.0.0-20180613055208-5c94acc5e6eb/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/nsf/termbox-go v0.0.0-20190325093121-288510b9734e h1:Vbib8wJAaMEF9jusI/kMSYMr/LtRzM7+F9MJgt/nH8k= golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756 h1:9nuHUbU8dRnRRfj9KjWUVrJeoexdbeMjttk6Oh1rD10=
github.com/nsf/termbox-go v0.0.0-20190325093121-288510b9734e/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ= golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/djherbis/times.v1 v1.2.0 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM=
gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8=
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"log"
"os"
"path/filepath"
"strings"
)
type iconMap map[string]string
func parseIcons() iconMap {
if env := os.Getenv("LF_ICONS"); env != "" {
return parseIconsEnv(env)
}
defaultIcons := []string{
"tw=🗀",
"st=🗀",
"ow=🗀",
"di=🗀",
"fi=🗎",
}
return parseIconsEnv(strings.Join(defaultIcons, ":"))
}
func parseIconsEnv(env string) iconMap {
icons := make(iconMap)
entries := strings.Split(env, ":")
for _, entry := range entries {
if entry == "" {
continue
}
pair := strings.Split(entry, "=")
if len(pair) != 2 {
log.Printf("invalid $LF_ICONS entry: %s", entry)
return icons
}
key, val := pair[0], pair[1]
icons[key] = val
}
return icons
}
func (im iconMap) get(f *file) string {
var key string
switch {
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
case f.IsDir() && f.Mode()&0002 != 0:
key = "ow"
case f.IsDir():
key = "di"
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.Mode()&os.ModeNamedPipe != 0:
key = "pi"
case f.Mode()&os.ModeSocket != 0:
key = "so"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0:
key = "su"
case f.Mode()&os.ModeSetgid != 0:
key = "sg"
case f.Mode().IsRegular() && f.Mode()&0111 != 0:
key = "ex"
default:
key = "*" + filepath.Ext(f.Name())
}
if val, ok := im[key]; ok {
return val
}
if val, ok := im["fi"]; ok {
return val
}
return " "
}
+756 -111
View File
@@ -22,10 +22,11 @@ Source code can be found in the repository at https://github.com/gokcehan/lf.
This documentation can either be read from terminal using 'lf -doc' or online at https://godoc.org/github.com/gokcehan/lf. You can also use 'doc' command (default '<f-1>') inside lf to view the documentation in a pager. This documentation can either be read from terminal using 'lf -doc' or online at https://godoc.org/github.com/gokcehan/lf. You can also use 'doc' command (default '<f-1>') inside lf to view the documentation in a pager.
.PP .PP
You can run 'lf -help' to see descriptions of command line options. You can run 'lf -help' to see descriptions of command line options.
.SH REFERENCE .SH QUICK REFERENCE
The following commands are provided by lf with default keybindings: The following commands are provided by lf:
.PP .PP
.EX .EX
quit (default 'q')
up (default 'k' and '<up>') up (default 'k' and '<up>')
half-up (default '<c-u>') half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>') page-up (default '<c-b>' and '<pgup>')
@@ -34,149 +35,140 @@ The following commands are provided by lf with default keybindings:
page-down (default '<c-f>' and '<pgdn>') page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>') updir (default 'h' and '<left>')
open (default 'l' and '<right>') open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
toggle (default '<space>') toggle
invert (default 'v') invert (default 'v')
unselect (default 'u') unselect (default 'u')
glob-select
glob-unselect
copy (default 'y') copy (default 'y')
cut (default 'd') cut (default 'd')
paste (default 'p') paste (default 'p')
clear (default 'c') clear (default 'c')
sync
draw
redraw (default '<c-l>') redraw (default '<c-l>')
load
reload (default '<c-r>') reload (default '<c-r>')
read (default ':') echo
shell (default '$') echomsg
shell-pipe (default '%') echoerr
shell-wait (default '!') cd
shell-async (default '&') select
find (default 'f') delete (modal)
find-back (default 'F') rename (modal) (default 'r')
source
push
read (modal) (default ':')
shell (modal) (default '$')
shell-pipe (modal) (default '%')
shell-wait (modal) (default '!')
shell-async (modal) (default '&')
find (modal) (default 'f')
find-back (modal) (default 'F')
find-next (default ';') find-next (default ';')
find-prev (default ',') find-prev (default ',')
search (default '/') search (modal) (default '/')
search-back (default '?') search-back (modal) (default '?')
search-next (default 'n') search-next (default 'n')
search-prev (default 'N') search-prev (default 'N')
mark-save (default 'm') mark-save (modal) (default 'm')
mark-load (default "'") mark-load (modal) (default "'")
mark-remove (modal) (default `"`)
.EE .EE
.PP .PP
The following commands are provided by lf without default keybindings: The following command line commands are provided by lf:
.PP
.EX
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
.EE
.PP
The following command line commands are provided by lf with default keybindings:
.PP .PP
.EX .EX
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-interrupt (default '<c-c>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>') cmd-end (default '<c-e>' and '<end>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<backspace>' and '<backspace2>')
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-transpose-word (default '<a-t>')
cmd-word (default '<a-f>') cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>') cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>') cmd-delete-word (default '<a-d>')
cmd-capitalize-word (default '<a-c>')
cmd-uppercase-word (default '<a-u>') cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>') cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
.EE .EE
.PP .PP
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
.PP .PP
.EX .EX
anchorfind boolean (default on) anchorfind bool (default on)
color256 boolean (default off) dircounts bool (default off)
dircounts boolean (default off) dirfirst bool (default on)
dirfirst boolean (default on) drawbox bool (default off)
drawbox boolean (default off) errorfmt string (default "\e033[7;31;47m%s\e033[0m")
globsearch boolean (default off) filesep string (default "\en")
hidden boolean (default off) findlen int (default 1)
ignorecase boolean (default on) globsearch bool (default off)
ignoredia boolean (default off) hidden bool (default off)
incsearch boolean (default off) hiddenfiles []string (default '.*')
preview boolean (default on) icons bool (default off)
reverse boolean (default off) ifs string (default '')
smartcase boolean (default on) ignorecase bool (default on)
smartdia boolean (default off) ignoredia bool (default off)
wrapscan boolean (default on) incsearch bool (default off)
number boolean (default off) info []string (default '')
relativenumber boolean (default off) number bool (default off)
findlen integer (default 1) (zero to prompt until single match) period int (default 0)
period integer (default 0) (zero to disable periodic loading) preview bool (default on)
scrolloff integer (default 0) previewer string (default '')
tabstop integer (default 8) promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f\e033[0m")
errorfmt string (default "\e033[7;31;47m%s\e033[0m") ratios []int (default '1:2:3')
filesep string (default "\en") relativenumber bool (default off)
ifs string (default ”) (not exported if empty) reverse bool (default off)
previewer string (default ”) (not filtered if empty) scrolloff int (default 0)
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f\e033[0m") shell string (default 'sh' for unix and 'cmd' for windows)
shell string (default 'sh') shellopts []string (default '')
sortby string (default 'natural') smartcase bool (default on)
timefmt string (default 'Mon Jan _2 15:04:05 2006') smartdia bool (default off)
ratios string (default '1:2:3') sortby string (default 'natural')
info string (default ”) tabstop int (default 8)
shellopts string (default ”) timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~')
wrapscan bool (default on)
wrapscroll bool (default off)
.EE .EE
.PP .PP
The following variables are exported for shell commands: The following environment variables are exported for shell commands:
.PP .PP
.EX .EX
$f current file f
$fs selected file(s) separated with 'filesep' fs
$fx current file or selected file(s) if any fx
$id id number of the client id
LF_LEVEL
OPENER
EDITOR
PAGER
SHELL
.EE .EE
.PP .PP
The following variables are set to the corresponding values: The following commands/keybindings are provided by default:
.PP .PP
.EX .EX
$LF_LEVEL current nesting level unix windows
.EE cmd open &$OPENER "$f" cmd open &%OPENER% %f%
.PP map e $$EDITOR "$f" map e $%EDITOR% %f%
The following default values are set to the environmental variables on unix when they are not set or empty: map i $$PAGER "$f" map i !%PAGER% %f%
.PP map w $$SHELL map w $%SHELL%
.EX
$OPENER open # macos
$OPENER xdg-open # others
$EDITOR vi
$PAGER less
$SHELL sh
.EE
.PP
The following default values are set to the environmental variables on windows when they are not set or empty:
.PP
.EX
%OPENER% start
%EDITOR% notepad
%PAGER% more
%SHELL% cmd
.EE .EE
.PP .PP
The following additional keybindings are provided by default: The following additional keybindings are provided by default:
@@ -191,15 +183,11 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info map sn :set sortby natural; set info
map ss :set sortby size; set info size map ss :set sortby size; set info size
map st :set sortby time; set info time map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~ map gh cd ~
.EE map <space> :toggle; down
.PP
The following keybindings to applications are provided by default:
.PP
.EX
map e $$EDITOR $f
map i $$PAGER $f
map w $$SHELL
.EE .EE
.SH CONFIGURATION .SH CONFIGURATION
Configuration files should be located at: Configuration files should be located at:
@@ -234,6 +222,629 @@ You can configure the default values of following variables to change these loca
.EE .EE
.PP .PP
A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example. A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example.
.SH 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.
.PP
.EX
quit (default 'q')
.EE
.PP
Quit lf and return to the shell.
.PP
.EX
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
.EE
.PP
Move the current file selection upwards/downwards by one/half a page/full page.
.PP
.EX
updir (default 'h' and '<left>')
.EE
.PP
Change the current working directory to the parent directory.
.PP
.EX
open (default 'l' and '<right>')
.EE
.PP
If the current file is a directory, then change the current directory to it, otherwise, execute the 'open' command. A default 'open' command is provided to call the default system opener asynchronously with the current file as the argument. A custom 'open' command can be defined to override this default.
.PP
(See also 'OPENER' variable and 'Opening Files' section)
.PP
.EX
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
.EE
.PP
Move the current file selection to the top/bottom of the directory.
.PP
.EX
toggle
.EE
.PP
Toggle the selection of the current file or files given as arguments.
.PP
.EX
invert (default 'v')
.EE
.PP
Reverse the selection of all files in the current directory (i.e. 'toggle' all files). Selections in other directories are not effected by this command. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. `cmd select-all :unselect; invert`), though this will also remove selections in other directories.
.PP
.EX
unselect (default 'u')
.EE
.PP
Remove the selection of all files in all directories.
.PP
.EX
glob-select
.EE
.PP
Select files that match the given glob.
.PP
.EX
glob-unselect
.EE
.PP
Unselect files that match the given glob.
.PP
.EX
copy (default 'y')
.EE
.PP
If there are no selections, save the path of the current file to the copy buffer, otherwise, copy the paths of selected files.
.PP
.EX
cut (default 'd')
.EE
.PP
If there are no selections, save the path of the current file to the cut buffer, otherwise, copy the paths of selected files.
.PP
.EX
paste (default 'p')
.EE
.PP
Copy/Move files in copy/cut buffer to the current working directory.
.PP
.EX
clear (default 'c')
.EE
.PP
Clear file paths in copy/cut buffer.
.PP
.EX
sync
.EE
.PP
Synchronize copied/cut files with server. This command is automatically called when required.
.PP
.EX
draw
.EE
.PP
Draw the screen. This command is automatically called when required.
.PP
.EX
redraw (default '<c-l>')
.EE
.PP
Synchronize the terminal and redraw the screen.
.PP
.EX
load
.EE
.PP
Load modified files and directories. This command is automatically called when required.
.PP
.EX
reload (default '<c-r>')
.EE
.PP
Flush the cache and reload all files and directories.
.PP
.EX
echo
.EE
.PP
Print given arguments to the message line at the bottom.
.PP
.EX
echomsg
.EE
.PP
Print given arguments to the message line at the bottom and also to the log file.
.PP
.EX
echoerr
.EE
.PP
Print given arguments to the message line at the bottom in red color and also to the log file.
.PP
.EX
cd
.EE
.PP
Change the working directory to the given argument.
.PP
.EX
select
.EE
.PP
Change the current file selection to the given argument.
.PP
.EX
delete (modal)
.EE
.PP
Remove the current file or selected file(s).
.PP
.EX
rename (modal) (default 'r')
.EE
.PP
Rename the current file using the builtin method. A custom 'rename' command can be defined to override this default.
.PP
.EX
source
.EE
.PP
Read the configuration file given in the argument.
.PP
.EX
push
.EE
.PP
Simulate key pushes given in the argument.
.PP
.EX
read (modal) (default ':')
.EE
.PP
Read a command to evaluate.
.PP
.EX
shell (modal) (default '$')
.EE
.PP
Read a shell command to execute.
.PP
(See also 'Prefixes' and 'Shell Commands' sections)
.PP
.EX
shell-pipe (modal) (default '%')
.EE
.PP
Read a shell command to execute piping its standard I/O to the bottom statline.
.PP
(See also 'Prefixes' and 'Piping Shell Commands' sections)
.PP
.EX
shell-wait (modal) (default '!')
.EE
.PP
Read a shell command to execute and wait for a key press in the end.
.PP
(See also 'Prefixes' and 'Waiting Shell Commands' sections)
.PP
.EX
shell-async (modal) (default '&')
.EE
.PP
Read a shell command to execute synchronously without standard I/O.
.PP
.EX
find (modal) (default 'f')
find-back (modal) (default 'F')
find-next (default ';')
find-prev (default ',')
.EE
.PP
Read key(s) to find the appropriate file name match in the forward/backward direction and jump to the next/previous match.
.PP
(See also 'anchorfind', 'findlen', 'wrapscan', 'ignorecase', 'smartcase', 'ignoredia', and 'smartdia' options and 'Searching Files' section)
.PP
.EX
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
.EE
.PP
Read a pattern to search for a file name match in the forward/backward direction and jump to the next/previous match.
.PP
(See also 'globsearch', 'incsearch', 'wrapscan', 'ignorecase', 'smartcase', 'ignoredia', and 'smartdia' options and 'Searching Files' section)
.PP
.EX
mark-save (modal) (default 'm')
.EE
.PP
Save the current directory as a bookmark assigned to the given key.
.PP
.EX
mark-load (modal) (default "'")
.EE
.PP
Change the current directory to the bookmark assigned to the given key. A special bookmark "'" holds the previous directory after a 'mark-load', 'cd', or 'select' command.
.PP
.EX
mark-remove (modal) (default `"`)
.EE
.PP
Remove a bookmark assigned to the given key.
.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.
.PP
.EX
cmd-escape (default '<esc>')
.EE
.PP
Quit command line mode and return to normal mode.
.PP
.EX
cmd-complete (default '<tab>')
.EE
.PP
Autocomplete the current word.
.PP
.EX
cmd-enter (default '<c-j>' and '<enter>')
.EE
.PP
Execute the current line.
.PP
.EX
cmd-interrupt (default '<c-c>')
.EE
.PP
Interrupt the current shell-pipe command and return to the normal mode.
.PP
.EX
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
.EE
.PP
Go to next/previous item in the history.
.PP
.EX
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
.EE
.PP
Move the cursor to the left/right.
.PP
.EX
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
.EE
.PP
Move the cursor to the beginning/end of line.
.PP
.EX
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<backspace>' and '<backspace2>')
.EE
.PP
Delete the next character in forward/backward direction.
.PP
.EX
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
.EE
.PP
Delete everything up to the beginning/end of line.
.PP
.EX
cmd-delete-unix-word (default '<c-w>')
.EE
.PP
Delete the previous unix word.
.PP
.EX
cmd-yank (default '<c-y>')
.EE
.PP
Paste the buffer content containing the last deleted item.
.PP
.EX
cmd-transpose (default '<c-t>')
cmd-transpose-word (default '<a-t>')
.EE
.PP
Transpose the positions of last two characters/words.
.PP
.EX
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
.EE
.PP
Move the cursor by one word in forward/backward direction.
.PP
.EX
cmd-delete-word (default '<a-d>')
.EE
.PP
Delete the next word in forward direction.
.PP
.EX
cmd-capitalize-word (default '<a-c>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
.EE
.PP
Capitalize/uppercase/lowercase the current word and jump to the next word.
.SH OPTIONS
This section shows information about options to customize the behavior. Character ':' is used as the separator for list options '[]int' and '[]string'.
.PP
.EX
anchorfind bool (default on)
.EE
.PP
When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position.
.PP
.EX
dircounts bool (default off)
.EE
.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+'.
.PP
.EX
dirfirst bool (default on)
.EE
.PP
Show directories first above regular files.
.PP
.EX
drawbox bool (default off)
.EE
.PP
Draw boxes around panes with box drawing characters.
.PP
.EX
errorfmt string (default "\e033[7;31;47m%s\e033[0m")
.EE
.PP
Format string of error messages shown in the bottom message line.
.PP
.EX
filesep string (default "\en")
.EE
.PP
File separator used in environment variables 'fs' and 'fx'.
.PP
.EX
findlen int (default 1)
.EE
.PP
Number of characters prompted for the find command. When this value is set to 0, find command prompts until there is only a single match left.
.PP
.EX
globsearch bool (default off)
.EE
.PP
When this option is enabled, search command patterns are considered as globs, otherwise they are literals. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges. Otherwise, these characters are interpreted as they are.
.PP
.EX
hidden bool (default off)
.EE
.PP
Show hidden files. On unix systems, hidden files are determined by the value of 'hiddenfiles'. On windows, only files with hidden attributes are considered hidden files.
.PP
.EX
hiddenfiles []string (default '.*')
.EE
.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.
.PP
.EX
icons bool (default off)
.EE
.PP
Show icons before each item in the list. By default, only two icons, 🗀 (U+1F5C0) and 🗎 (U+1F5CE), are used for directories and files respectively, as they are supported in the unicode standard. Icons can be configured with an environment variable named 'LF_ICONS'. The syntax of this variable is similar to 'LS_COLORS'. See the wiki page for an example icon configuration.
.PP
.EX
ifs string (default '')
.EE
.PP
Sets 'IFS' variable in shell commands. It works by adding the assignment to the beginning of the command string as 'IFS='...'; ...'. The reason is that 'IFS' variable is not inherited by the shell for security reasons. This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells. This option has no effect when the value is left empty. This option does not have any effect on windows.
.PP
.EX
ignorecase bool (default on)
.EE
.PP
Ignore case in search patterns.
.PP
.EX
ignoredia bool (default off)
.EE
.PP
Ignore diacritics in search patterns.
.PP
.EX
incsearch bool (default off)
.EE
.PP
Jump to the first match after each keystroke during searching.
.PP
.EX
info []string (default '')
.EE
.PP
List of information shown for directory items at the right side of pane. Currently supported information types are 'size', 'time', 'atime', and 'ctime'. Information is only shown when the pane width is more than twice the width of information.
.PP
.EX
number bool (default off)
.EE
.PP
Show the position number for directory items at the left side of pane. When 'relativenumber' is enabled, only the current line shows the absolute position and relative positions are shown for the rest.
.PP
.EX
period int (default 0)
.EE
.PP
Set the interval in seconds for periodic checks of directory updates. This works by periodically calling the 'load' command. Note that directories are already updated automatically in many cases. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. Periodic checks are disabled when the value of this option is set to zero.
.PP
.EX
preview bool (default on)
.EE
.PP
Show previews of files and directories at the right most pane. If the file has more lines than the preview pane, rest of the lines are not read. Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'.
.PP
.EX
previewer string (default '') (not filtered if empty)
.EE
.PP
Set the path of a previewer file to filter the content of regular files for previewing. The file should be executable. Two arguments are passed to the file, first is the current file name, and second is the height of preview pane. SIGPIPE signal is sent when enough lines are read. Preview filtering is disabled and files are displayed as they are when the value of this option is left empty.
.PP
.EX
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f\e033[0m")
.EE
.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, and '%f' as the file name. 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
.EX
ratios []int (default '1:2:3')
.EE
.PP
List of ratios of pane widths. Number of items in the list determines the number of panes in the ui. When 'preview' option is enabled, the right most number is used for the width of preview pane.
.PP
.EX
relativenumber bool (default off)
.EE
.PP
Show the position number relative to the current line. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown.
.PP
.EX
reverse bool (default off)
.EE
.PP
Reverse the direction of sort.
.PP
.EX
scrolloff int (default 0)
.EE
.PP
Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling. The current line is kept in the middle when this option is set to a large value that is bigger than the half of number of lines. A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items.
.PP
.EX
shell string (default 'sh' for unix and 'cmd' for windows)
.EE
.PP
Shell executable to use for shell commands. Shell commands are executed as 'shell shellopts -c command -- arguments'. On windows, '/c' is used instead of '-c' which should work in 'cmd' and 'powershell'.
.PP
.EX
shellopts []string (default '')
.EE
.PP
List of shell options to pass to the shell executable.
.PP
.EX
smartcase bool (default on)
.EE
.PP
Override 'ignorecase' option when the pattern contains an uppercase character. This option has no effect when 'ignorecase' is disabled.
.PP
.EX
smartdia bool (default off)
.EE
.PP
Override 'ignoredia' option when the pattern contains a character with diacritic. This option has no effect when 'ignoredia' is disabled.
.PP
.EX
sortby string (default 'natural')
.EE
.PP
Sort type for directories. Currently supported sort types are 'natural', 'name', 'size', 'time', 'ctime', 'atime', and 'ext'.
.PP
.EX
tabstop int (default 8)
.EE
.PP
Number of space characters to show for horizontal tabulation (U+0009) character.
.PP
.EX
timefmt string (default 'Mon Jan _2 15:04:05 2006')
.EE
.PP
Format string of the file modification time shown in the bottom line.
.PP
.EX
truncatechar string (default '~')
.EE
.PP
Truncate character shown at the end when the file name does not fit to the pane.
.PP
.EX
wrapscan bool (default on)
.EE
.PP
Searching can wrap around the file list.
.PP
.EX
wrapscroll bool (default off)
.EE
.PP
Scrolling can wrap around the file list.
.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').
.PP
.EX
f
.EE
.PP
Current file selection as a full path.
.PP
.EX
fs
.EE
.PP
Selected file(s) separated with the value of 'filesep' option as full path(s).
.PP
.EX
fx
.EE
.PP
Selected file(s) (i.e. 'fs') if there are any selected files, otherwise current file selection (i.e. 'f').
.PP
.EX
id
.EE
.PP
Id of the running client.
.PP
.EX
LF_LEVEL
.EE
.PP
The value of this variable is set to the current nesting level when you run lf from a shell spawned inside lf. You can add the value of this variable to your shell prompt to make it clear that your shell runs inside lf. For example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] && PS1="$PS1""(lf level: $LF_LEVEL) "' in your shell configuration file (e.g. '~/.bashrc').
.PP
.EX
OPENER
.EE
.PP
If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others.
.PP
.EX
EDITOR
.EE
.PP
If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on unix, 'notepad' in Windows.
.PP
.EX
PAGER
.EE
.PP
If this variable is set in the environment, use the same value, otherwise set the value to 'less' on unix, 'more' in Windows.
.PP
.EX
SHELL
.EE
.PP
If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on unix, 'cmd' in Windows.
.SH PREFIXES .SH PREFIXES
The following command prefixes are used by lf: The following command prefixes are used by lf:
.PP .PP
@@ -243,11 +854,9 @@ The following command prefixes are used by lf:
% shell-pipe shell command running with the ui % shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press ! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously & shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
.EE .EE
.PP .PP
The same evaluator is used for the command line and the configuration file for read and shell commands. The difference is that prefixes are not necessary in the command line. Instead, different modes are provided to read corresponding commands. These modes are mapped to the prefix keys above by default. Searching commands are only used from the command line. The same evaluator is used for the command line and the configuration file for read and shell commands. The difference is that prefixes are not necessary in the command line. Instead, different modes are provided to read corresponding commands. These modes are mapped to the prefix keys above by default.
.SH SYNTAX .SH SYNTAX
Characters from '#' to newline are comments and ignored: Characters from '#' to newline are comments and ignored:
.PP .PP
@@ -531,7 +1140,7 @@ There is a 'quit' command to close client connections and quit the server:
.PP .PP
Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users. Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users.
.SH FILE OPERATIONS .SH FILE OPERATIONS
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 commands do not overwrite existing files or directories with the same name. Instead, a suffix that is compatible with '--backup=numbered' option in GNU cp is added to the new files or directories. Only file modes are preserved and all other attributes are ignored including ownership, timestamps, context, links, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are followed. Moving is performed using the rename operation of the underlying OS. This can fail to move files between different partitions when it needs to copy files. For these cases, users are expected to explicitly copy files and then delete the old ones manually. Operation errors are shown in the message line as well as the log file and they do not preemptively finish the corresponding file operation. 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 commands do not overwrite existing files or directories with the same name. Instead, a suffix that is compatible with '--backup=numbered' option in GNU cp is added to the new files or directories. Only file modes are preserved and all other attributes are ignored including ownership, timestamps, context, links, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are followed. Moving is performed using the rename operation of the underlying OS. For cross-device moving, lf falls back to copying and then deletes the original files if there are no errors. Operation errors are shown in the message line as well as the log file and they do not preemptively finish the corresponding file operation.
.PP .PP
File operations can be performed on the current selected file or alternatively on multiple files by selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to memory. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file. File operations can be performed on the current selected file or alternatively on multiple files by selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to memory. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file.
.PP .PP
@@ -558,7 +1167,14 @@ 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. 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, 'updir', and 'open' commands. For example, you can use arrow keys to finish the search with the following mappings:
.PP
.EX
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
.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.
.PP .PP
@@ -587,6 +1203,8 @@ You may want to use either file extensions or mime types from 'file' command:
}} }}
.EE .EE
.PP .PP
You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits.
.PP
Following command is provided by default: Following command is provided by default:
.PP .PP
.EX .EX
@@ -622,6 +1240,33 @@ Since this script is called for each file selection change it needs to be as eff
.EE .EE
.PP .PP
Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview. Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview.
.SH CHANGING 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. If you want to stay in the current directory after quitting, you can use one of the example wrapper shell scripts provided in the repository.
.PP
There is a special command 'on-cd' that runs a shell command when it is defined and the directory is changed. You can define it just as you would define any other command:
.PP
.EX
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w\e033[0m\e033[1m%f$git\e033[0m"
lf -remote "send $id set promptfmt \e"$fmt\e""
}}
.EE
.PP
This command runs whenever you change directory but not on startup. You can add an extra call to make it run on startup as well:
.PP
.EX
cmd on-cd &{{ # ... }}
on-cd
.EE
.PP
Note that all shell commands are possible but `%` and `&` are usually more appropriate as `$` and `!` causes flickers and pauses respectively.
.SH COLORSCHEMES .SH COLORSCHEMES
lf tries to automatically adapt its colors to the environment. On startup, first '$LS_COLORS' environment variable is checked. This variable is used by GNU ls to configure its colors based on file types and extensions. The value of this variable is often set by GNU dircolors in a shell configuration file. dircolors program itself can be configured with a configuration file. dircolors supports 256 colors along with common attributes such as bold and underline. lf tries to automatically adapt its colors to the environment. On startup, first '$LS_COLORS' environment variable is checked. This variable is used by GNU ls to configure its colors based on file types and extensions. The value of this variable is often set by GNU dircolors in a shell configuration file. dircolors program itself can be configured with a configuration file. dircolors supports 256 colors along with common attributes such as bold and underline.
.PP .PP
@@ -629,10 +1274,10 @@ If '$LS_COLORS' variable is not set, '$LSCOLORS' variable is checked instead. Th
.PP .PP
If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute.
.PP .PP
You should also note that lf uses 8 color mode by default which uses sgr 3-bit color escapes (e.g. '\e033[34m'). If you want to use 256 colors, you need to enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. '\e033[38;5;4m'). This option is intended to eliminate differences between default colors used by ls and lf since terminals may render 3-bit and 8-bit escapes differently even for the same color. It is worth noting that lf uses as many colors are advertised by your terminal's entry in your systems terminfo or infocmp database, if this is not present lf will default to an internal database. For terminals supporting 24-bit (or "true") color that do not have a database entry (or one that does not advertise all capabilities), support can be enabled by either setting the '$COLORTERM' variable to "truecolor" or ensuring '$TERM' is set to a value that ends with "-truecolor".
.PP .PP
Keeping this mechanism in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. Keeping this in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other.
.PP .PP
Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. lf can also be configured to ignore your terminal theme and output colors "as they were intended" by translating all numbered colors into a 24-bit output that matches the description; this can be enabled by setting the environment variable '$TCELL_TRUECOLOR' to "on" (or any text except ""/nothing or "disable").
.PP .PP
Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line. Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line.
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=lf
Comment=Launches the lf file manager
Icon=utilities-terminal
Terminal=true
Exec=lf
Categories=ConsoleOnly;System;FileTools;FileManager
MimeType=inode/directory;
+83
View File
@@ -7,6 +7,7 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"runtime" "runtime"
"runtime/pprof" "runtime/pprof"
"strconv" "strconv"
@@ -50,6 +51,7 @@ func exportEnvVars() {
os.Setenv("EDITOR", envEditor) os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager) os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell) os.Setenv("SHELL", envShell)
os.Setenv("TCELL_TRUECOLOR", envTcellTruecolor)
level, err := strconv.Atoi(envLevel) level, err := strconv.Atoi(envLevel)
if err != nil { if err != nil {
@@ -61,6 +63,86 @@ func exportEnvVars() {
os.Setenv("LF_LEVEL", strconv.Itoa(level)) os.Setenv("LF_LEVEL", strconv.Itoa(level))
} }
// used by exportOpts below
func fieldToString(field reflect.Value) string {
kind := field.Kind()
var value string
switch kind {
case reflect.Int:
value = strconv.Itoa(int(field.Int()))
case reflect.Bool:
value = strconv.FormatBool(field.Bool())
case reflect.Slice:
for i := 0; i < field.Len(); i++ {
element := field.Index(i)
if i == 0 {
value = fieldToString(element)
} else {
value += ":" + fieldToString(element)
}
}
default:
value = field.String()
}
return value
}
func exportOpts() {
e := reflect.ValueOf(&gOpts).Elem()
for i := 0; i < e.NumField(); i++ {
// Get name and prefix it with lf_
name := e.Type().Field(i).Name
name = fmt.Sprintf("lf_%s", name)
// Skip maps
if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" {
continue
}
// Get string representation of the value
if name == "lf_sortType" {
var sortby string
switch gOpts.sortType.method {
case naturalSort:
sortby = "natural"
case nameSort:
sortby = "name"
case sizeSort:
sortby = "size"
case timeSort:
sortby = "time"
case ctimeSort:
sortby = "ctime"
case atimeSort:
sortby = "atime"
case extSort:
sortby = "ext"
}
os.Setenv("lf_sortby", sortby)
reverse := strconv.FormatBool(gOpts.sortType.option&reverseSort != 0)
os.Setenv("lf_reverse", reverse)
hidden := strconv.FormatBool(gOpts.sortType.option&hiddenSort != 0)
os.Setenv("lf_hidden", hidden)
dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0)
os.Setenv("lf_dirfirst", dirfirst)
} else {
field := e.Field(i)
value := fieldToString(field)
os.Setenv(name, value)
}
}
}
func startServer() { func startServer() {
cmd := detachedCommand(os.Args[0], "-server") cmd := detachedCommand(os.Args[0], "-server")
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
@@ -155,6 +237,7 @@ func main() {
log.Fatalf("remote command: %s", err) log.Fatalf("remote command: %s", err)
} }
case *serverMode: case *serverMode:
os.Chdir(gUser.HomeDir)
gServerLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.server.log", gUser.Username)) gServerLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.server.log", gUser.Username))
serve() serve()
default: default:
+23 -23
View File
@@ -13,6 +13,13 @@ import (
func isRoot(name string) bool { return filepath.Dir(name) == name } func isRoot(name string) bool { return filepath.Dir(name) == name }
func replaceTilde(s string) string {
if strings.HasPrefix(s, "~") {
s = strings.Replace(s, "~", gUser.HomeDir, 1)
}
return s
}
func runeSliceWidth(rs []rune) int { func runeSliceWidth(rs []rune) int {
w := 0 w := 0
for _, r := range rs { for _, r := range rs {
@@ -41,22 +48,12 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune {
return nil return nil
} }
// This function is used to escape whitespaces with backlashes in a given // This function is used to escape whitespaces and special characters with
// string. If a whitespace is already escaped then it is not escaped again. // backlashes in a given string.
func escape(s string) string { func escape(s string) string {
esc := false
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
for _, r := range s { for _, r := range s {
if r == '\\' { if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
esc = true
continue
}
if esc {
esc = false
buf = append(buf, '\\', r)
continue
}
if unicode.IsSpace(r) {
buf = append(buf, '\\') buf = append(buf, '\\')
} }
buf = append(buf, r) buf = append(buf, r)
@@ -65,26 +62,29 @@ func escape(s string) string {
} }
// This function is used to remove backlashes that are used to escape // This function is used to remove backlashes that are used to escape
// whitespaces in a given string. // whitespaces and special characters in a given string.
func unescape(s string) string { func unescape(s string) string {
esc := false esc := false
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
for _, r := range s { for _, r := range s {
if esc {
if !unicode.IsSpace(r) && r != '\\' && r != ';' && r != '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
esc = false
continue
}
if r == '\\' { if r == '\\' {
esc = true esc = true
continue continue
} }
if esc { esc = false
esc = false
if unicode.IsSpace(r) {
buf = append(buf, r)
} else {
buf = append(buf, '\\', r)
}
continue
}
buf = append(buf, r) buf = append(buf, r)
} }
if esc {
buf = append(buf, '\\')
}
return string(buf) return string(buf)
} }
+14 -3
View File
@@ -80,8 +80,13 @@ func TestEscape(t *testing.T) {
{"foo", "foo"}, {"foo", "foo"},
{"foo bar", `foo\ bar`}, {"foo bar", `foo\ bar`},
{"foo bar", `foo\ \ bar`}, {"foo bar", `foo\ \ bar`},
{`foo\ bar`, `foo\ bar`}, {`foo\bar`, `foo\\bar`},
{`foo\bar`, `foo\bar`}, {`foo\ bar`, `foo\\\ bar`},
{`foo;bar`, `foo\;bar`},
{`foo#bar`, `foo\#bar`},
{`foo\tbar`, `foo\\tbar`},
{"foo\tbar", "foo\\\tbar"},
{`foo\`, `foo\\`},
} }
for _, test := range tests { for _, test := range tests {
@@ -98,9 +103,15 @@ func TestUnescape(t *testing.T) {
}{ }{
{"", ""}, {"", ""},
{"foo", "foo"}, {"foo", "foo"},
{`foo\bar`, `foo\bar`},
{`foo\ bar`, "foo bar"}, {`foo\ bar`, "foo bar"},
{`foo\ \ bar`, "foo bar"}, {`foo\ \ bar`, "foo bar"},
{`foo\\bar`, `foo\bar`},
{`foo\\\ bar`, `foo\ bar`},
{`foo\;bar`, `foo;bar`},
{`foo\#bar`, `foo#bar`},
{`foo\\tbar`, `foo\tbar`},
{"foo\\\tbar", "foo\tbar"},
{`foo\`, `foo\`},
} }
for _, test := range tests { for _, test := range tests {
+360 -174
View File
@@ -9,10 +9,13 @@ import (
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"reflect"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"time" "time"
times "gopkg.in/djherbis/times.v1"
) )
type linkState byte type linkState byte
@@ -25,9 +28,13 @@ const (
type file struct { type file struct {
os.FileInfo os.FileInfo
linkState linkState linkState linkState
path string linkTarget string
dirCount int path string
dirCount int
accessTime time.Time
changeTime time.Time
ext string
} }
func readdir(path string) ([]*file, error) { func readdir(path string) ([]*file, error) {
@@ -51,6 +58,7 @@ func readdir(path string) ([]*file, error) {
} }
var linkState linkState var linkState linkState
var linkTarget string
if lstat.Mode()&os.ModeSymlink != 0 { if lstat.Mode()&os.ModeSymlink != 0 {
stat, err := os.Stat(fpath) stat, err := os.Stat(fpath)
@@ -60,13 +68,36 @@ func readdir(path string) ([]*file, error) {
} else { } else {
linkState = broken linkState = broken
} }
linkTarget, err = os.Readlink(fpath)
if err != nil {
log.Printf("reading link target: %s", err)
}
} }
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
// returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
ext := filepath.Ext(fpath)
files = append(files, &file{ files = append(files, &file{
FileInfo: lstat, FileInfo: lstat,
linkState: linkState, linkState: linkState,
path: fpath, linkTarget: linkTarget,
dirCount: -1, path: fpath,
dirCount: -1,
accessTime: at,
changeTime: ct,
ext: ext,
}) })
} }
@@ -74,14 +105,16 @@ func readdir(path string) ([]*file, error) {
} }
type dir struct { type dir struct {
loading bool // directory is loading from disk loading bool // directory is loading from disk
loadTime time.Time // current loading or last load time loadTime time.Time // current loading or last load time
ind int // index of current entry in files ind int // index of current entry in files
pos int // position of current entry in ui pos int // position of current entry in ui
path string // full path of directory path string // full path of directory
files []*file // displayed files in directory including or excluding hidden ones files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files) allFiles []*file // all files in directory including hidden ones (same array as files)
sortType sortType // sort method and options from last sort sortType sortType // sort method and options from last sort
hiddenfiles []string // hiddenfiles value from last sort
noPerm bool // whether lf has no permission to open the directory
} }
func newDir(path string) *dir { func newDir(path string) *dir {
@@ -97,11 +130,13 @@ func newDir(path string) *dir {
path: path, path: path,
files: files, files: files,
allFiles: files, allFiles: files,
noPerm: os.IsPermission(err),
} }
} }
func (dir *dir) sort() { func (dir *dir) sort() {
dir.sortType = gOpts.sortType dir.sortType = gOpts.sortType
dir.hiddenfiles = gOpts.hiddenfiles
dir.files = dir.allFiles dir.files = dir.allFiles
@@ -122,6 +157,34 @@ func (dir *dir) sort() {
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].ModTime().Before(dir.files[j].ModTime()) return dir.files[i].ModTime().Before(dir.files[j].ModTime())
}) })
case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
})
case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
})
case extSort:
sort.SliceStable(dir.files, func(i, j int) bool {
leftExt := strings.ToLower(dir.files[i].ext)
rightExt := strings.ToLower(dir.files[j].ext)
// if the extension could not be determined (directories, files without)
// use a zero byte so that these files can be ranked higher
if leftExt == "" {
leftExt = "\x00"
}
if rightExt == "" {
rightExt = "\x00"
}
// in order to also have natural sorting with the filenames
// combine the name with the ext but have the ext at the front
left := leftExt + strings.ToLower(dir.files[i].Name())
right := rightExt + strings.ToLower(dir.files[j].Name())
return left < right
})
} }
if gOpts.sortType.option&reverseSort != 0 { if gOpts.sortType.option&reverseSort != 0 {
@@ -144,13 +207,13 @@ func (dir *dir) sort() {
// files to the first non-hidden file in the list // files to the first non-hidden file in the list
if gOpts.sortType.option&hiddenSort == 0 { if gOpts.sortType.option&hiddenSort == 0 {
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if isHidden(dir.files[i]) && isHidden(dir.files[j]) { if isHidden(dir.files[i], dir.path) && isHidden(dir.files[j], dir.path) {
return i < j return i < j
} }
return isHidden(dir.files[i]) return isHidden(dir.files[i], dir.path)
}) })
for i, f := range dir.files { for i, f := range dir.files {
if !isHidden(f) { if !isHidden(f, dir.path) {
dir.files = dir.files[i:] dir.files = dir.files[i:]
return return
} }
@@ -188,74 +251,84 @@ func (dir *dir) sel(name string, height int) {
} }
type nav struct { type nav struct {
dirs []*dir dirs []*dir
copyBytes int64 copyBytes int64
copyTotal int64 copyTotal int64
copyUpdate int copyUpdate int
moveCount int moveCount int
moveTotal int moveTotal int
moveUpdate int moveUpdate int
copyBytesChan chan int64 deleteCount int
copyTotalChan chan int64 deleteTotal int
moveCountChan chan int deleteUpdate int
moveTotalChan chan int copyBytesChan chan int64
dirChan chan *dir copyTotalChan chan int64
regChan chan *reg moveCountChan chan int
dirCache map[string]*dir moveTotalChan chan int
regCache map[string]*reg deleteCountChan chan int
saves map[string]bool deleteTotalChan chan int
marks map[string]string dirChan chan *dir
selections map[string]int regChan chan *reg
selectionInd int dirCache map[string]*dir
height int regCache map[string]*reg
find string saves map[string]bool
findBack bool marks map[string]string
search string renameOldPath string
searchBack bool renameNewPath string
searchInd int selections map[string]int
searchPos int selectionInd int
height int
find string
findBack bool
search string
searchBack bool
searchInd int
searchPos int
} }
func (nav *nav) loadDir(path string) *dir { func (nav *nav) loadDir(path string) *dir {
d, ok := nav.dirCache[path] d, ok := nav.dirCache[path]
if !ok { if !ok {
d := &dir{loading: true, loadTime: time.Now(), path: path, sortType: gOpts.sortType, hiddenfiles: gOpts.hiddenfiles}
nav.dirCache[path] = d
go func() { go func() {
d := newDir(path) d := newDir(path)
d.sort() d.sort()
d.ind, d.pos = 0, 0 d.ind, d.pos = 0, 0
nav.dirChan <- d nav.dirChan <- d
}() }()
d := &dir{loading: true, path: path, sortType: gOpts.sortType}
nav.dirCache[path] = d
return d return d
} }
s, err := os.Stat(d.path) nav.checkDir(d)
return d
}
func (nav *nav) checkDir(dir *dir) {
s, err := os.Stat(dir.path)
if err != nil { if err != nil {
return d log.Printf("getting directory info: %s", err)
return
} }
switch { switch {
case s.ModTime().After(d.loadTime): case s.ModTime().After(dir.loadTime):
dir.loading = true
dir.loadTime = time.Now()
go func() { go func() {
d.loadTime = time.Now() nd := newDir(dir.path)
nd := newDir(path)
nd.sort() nd.sort()
nd.sel(d.name(), nav.height)
nav.dirChan <- nd nav.dirChan <- nd
}() }()
case d.sortType != gOpts.sortType: case dir.sortType != gOpts.sortType || !reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles):
dir.loading = true
go func() { go func() {
d.loading = true dir.sort()
name := d.name() dir.loading = false
d.sort() nav.dirChan <- dir
d.sel(name, nav.height)
d.loading = false
nav.dirChan <- d
}() }()
} }
return d
} }
func (nav *nav) getDirs(wd string) { func (nav *nav) getDirs(wd string) {
@@ -281,19 +354,21 @@ func newNav(height int) *nav {
} }
nav := &nav{ nav := &nav{
copyBytesChan: make(chan int64, 1024), copyBytesChan: make(chan int64, 1024),
copyTotalChan: make(chan int64, 1024), copyTotalChan: make(chan int64, 1024),
moveCountChan: make(chan int, 1024), moveCountChan: make(chan int, 1024),
moveTotalChan: make(chan int, 1024), moveTotalChan: make(chan int, 1024),
dirChan: make(chan *dir), deleteCountChan: make(chan int, 1024),
regChan: make(chan *reg), deleteTotalChan: make(chan int, 1024),
dirCache: make(map[string]*dir), dirChan: make(chan *dir),
regCache: make(map[string]*reg), regChan: make(chan *reg),
saves: make(map[string]bool), dirCache: make(map[string]*dir),
marks: make(map[string]string), regCache: make(map[string]*reg),
selections: make(map[string]int), saves: make(map[string]bool),
selectionInd: 0, marks: make(map[string]string),
height: height, selections: make(map[string]int),
selectionInd: 0,
height: height,
} }
nav.getDirs(wd) nav.getDirs(wd)
@@ -303,27 +378,15 @@ func newNav(height int) *nav {
func (nav *nav) renew() { func (nav *nav) renew() {
for _, d := range nav.dirs { for _, d := range nav.dirs {
go func(d *dir) { nav.checkDir(d)
s, err := os.Stat(d.path)
if err != nil {
log.Printf("getting directory info: %s", err)
return
}
if d.loadTime.After(s.ModTime()) {
return
}
d.loadTime = time.Now()
nd := newDir(d.path)
nd.sort()
nav.dirChan <- nd
}(d)
} }
for m := range nav.selections { for m := range nav.selections {
if _, err := os.Stat(m); os.IsNotExist(err) { if _, err := os.Lstat(m); os.IsNotExist(err) {
delete(nav.selections, m) delete(nav.selections, m)
} }
} }
if len(nav.selections) == 0 { if len(nav.selections) == 0 {
nav.selectionInd = 0 nav.selectionInd = 0
} }
@@ -356,16 +419,14 @@ func (nav *nav) position() {
} }
} }
func (nav *nav) preview() { func (nav *nav) preview(path string) {
curr, err := nav.currFile() reg := &reg{loadTime: time.Now(), path: path}
if err != nil {
return
}
var reader io.Reader var reader io.Reader
if len(gOpts.previewer) != 0 { if len(gOpts.previewer) != 0 {
cmd := exec.Command(gOpts.previewer, curr.path, strconv.Itoa(nav.height)) exportOpts()
cmd := exec.Command(gOpts.previewer, path, strconv.Itoa(nav.height))
out, err := cmd.StdoutPipe() out, err := cmd.StdoutPipe()
if err != nil { if err != nil {
@@ -380,7 +441,7 @@ func (nav *nav) preview() {
defer out.Close() defer out.Close()
reader = out reader = out
} else { } else {
f, err := os.Open(curr.path) f, err := os.Open(path)
if err != nil { if err != nil {
log.Printf("opening file: %s", err) log.Printf("opening file: %s", err)
} }
@@ -389,8 +450,6 @@ func (nav *nav) preview() {
reader = f reader = f
} }
reg := &reg{loadTime: time.Now(), path: curr.path}
buf := bufio.NewScanner(reader) buf := bufio.NewScanner(reader)
for i := 0; i < nav.height && buf.Scan(); i++ { for i := 0; i < nav.height && buf.Scan(); i++ {
@@ -411,28 +470,32 @@ func (nav *nav) preview() {
nav.regChan <- reg nav.regChan <- reg
} }
func (nav *nav) loadReg(ui *ui, path string) *reg { func (nav *nav) loadReg(path string) *reg {
r, ok := nav.regCache[path] r, ok := nav.regCache[path]
if !ok { if !ok {
go nav.preview() r := &reg{loading: true, loadTime: time.Now(), path: path}
r := &reg{loading: true, path: path}
nav.regCache[path] = r nav.regCache[path] = r
go nav.preview(path)
return r return r
} }
s, err := os.Stat(r.path) nav.checkReg(r)
if err != nil {
return r
}
if s.ModTime().After(r.loadTime) {
r.loadTime = time.Now()
go nav.preview()
}
return r return r
} }
func (nav *nav) checkReg(reg *reg) {
s, err := os.Stat(reg.path)
if err != nil {
return
}
if s.ModTime().After(reg.loadTime) {
reg.loadTime = time.Now()
go nav.preview(reg.path)
}
}
func (nav *nav) sort() { func (nav *nav) sort() {
for _, d := range nav.dirs { for _, d := range nav.dirs {
name := d.name() name := d.name()
@@ -445,6 +508,9 @@ func (nav *nav) up(dist int) {
dir := nav.currDir() dir := nav.currDir()
if dir.ind == 0 { if dir.ind == 0 {
if gOpts.wrapscroll {
nav.bottom()
}
return return
} }
@@ -462,6 +528,9 @@ func (nav *nav) down(dist int) {
maxind := len(dir.files) - 1 maxind := len(dir.files) - 1
if dir.ind >= maxind { if dir.ind >= maxind {
if gOpts.wrapscroll {
nav.top()
}
return return
} }
@@ -547,14 +616,12 @@ func (nav *nav) toggle() {
} }
nav.toggleSelection(curr.path) nav.toggleSelection(curr.path)
nav.down(1)
} }
func (nav *nav) invert() { func (nav *nav) invert() {
last := nav.currDir() dir := nav.currDir()
for _, f := range last.files { for _, f := range dir.files {
path := filepath.Join(last.path, f.Name()) path := filepath.Join(dir.path, f.Name())
nav.toggleSelection(path) nav.toggleSelection(path)
} }
} }
@@ -626,6 +693,10 @@ loop:
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo ui.exprChan <- echo
} }
if errCount == 0 {
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(ui *ui, srcs []string, dstDir string) {
@@ -664,15 +735,54 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
var newPath string var newPath string
for i := 1; !os.IsNotExist(err); i++ { for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i) newPath = fmt.Sprintf("%s.~%d~", dst, i)
_, err = os.Stat(newPath) _, err = os.Lstat(newPath)
} }
dst = newPath dst = newPath
} }
if err := os.Rename(src, dst); err != nil { if err := os.Rename(src, dst); err != nil {
errCount++ if errCrossDevice(err) {
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) total, err := copySize([]string{src})
ui.exprChan <- echo if err != nil {
echo.args[0] = err.Error()
ui.exprChan <- echo
continue
}
nav.copyTotalChan <- total
nums, errs := copyAll([]string{src}, dstDir)
oldCount := errCount
loop:
for {
select {
case n := <-nums:
nav.copyBytesChan <- n
case err, ok := <-errs:
if !ok {
break loop
}
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
nav.copyTotalChan <- -total
if errCount == oldCount {
if err := os.RemoveAll(src); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
} else {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
} }
} }
@@ -683,6 +793,10 @@ func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo ui.exprChan <- echo
} }
if errCount == 0 {
ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mMoved successfully\033[0m"}, 1}
}
} }
func (nav *nav) paste(ui *ui) error { func (nav *nav) paste(ui *ui) error {
@@ -714,19 +828,61 @@ func (nav *nav) paste(ui *ui) error {
return nil return nil
} }
func (nav *nav) del() error { func (nav *nav) del(ui *ui) error {
list, err := nav.currFileOrSelections() list, err := nav.currFileOrSelections()
if err != nil { if err != nil {
return err return err
} }
for _, path := range list { go func() {
if err := os.RemoveAll(path); err != nil { echo := &callExpr{"echoerr", []string{""}, 1}
return err errCount := 0
nav.deleteTotalChan <- len(list)
for _, path := range list {
nav.deleteCountChan <- 1
if err := os.RemoveAll(path); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
} }
nav.deleteTotalChan <- -len(list)
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}()
return nil
}
func (nav *nav) rename() error {
oldPath := nav.renameOldPath
newPath := nav.renameNewPath
if err := os.Rename(oldPath, newPath); err != nil {
return err
} }
lstat, err := os.Lstat(newPath)
if err != nil {
return err
}
dir := nav.loadDir(filepath.Dir(newPath))
if dir.loading {
dir.files = append(dir.files, &file{FileInfo: lstat})
}
dir.sel(lstat.Name(), nav.height)
return nil return nil
} }
@@ -741,11 +897,11 @@ func (nav *nav) sync() error {
nav.saves[f] = cp nav.saves[f] = cp
} }
return nil return nav.readMarks()
} }
func (nav *nav) cd(wd string) error { func (nav *nav) cd(wd string) error {
wd = strings.Replace(wd, "~", gUser.HomeDir, -1) wd = replaceTilde(wd)
wd = filepath.Clean(wd) wd = filepath.Clean(wd)
if !filepath.IsAbs(wd) { if !filepath.IsAbs(wd) {
@@ -762,7 +918,10 @@ func (nav *nav) cd(wd string) error {
} }
func (nav *nav) sel(path string) error { func (nav *nav) sel(path string) error {
lstat, err := os.Stat(path) path = replaceTilde(path)
path = filepath.Clean(path)
lstat, err := os.Lstat(path)
if err != nil { if err != nil {
return fmt.Errorf("select: %s", err) return fmt.Errorf("select: %s", err)
} }
@@ -776,10 +935,36 @@ func (nav *nav) sel(path string) error {
base := filepath.Base(path) base := filepath.Base(path)
last := nav.dirs[len(nav.dirs)-1] last := nav.dirs[len(nav.dirs)-1]
if last.loading { if last.loading {
last.files = append(last.files, &file{FileInfo: lstat}) last.files = append(last.files, &file{FileInfo: lstat})
} else { }
last.sel(base, nav.height)
last.sel(base, nav.height)
return nil
}
func (nav *nav) globSel(pattern string, invert bool) error {
dir := nav.currDir()
anyMatched := false
for i := 0; i < len(dir.files); i++ {
matched, err := filepath.Match(pattern, dir.files[i].Name())
if err != nil {
return fmt.Errorf("glob-select: %s", err)
}
if matched {
anyMatched = true
fpath := filepath.Join(dir.path, dir.files[i].Name())
if _, ok := nav.selections[fpath]; ok == invert {
nav.toggleSelection(fpath)
}
}
}
if !anyMatched {
return fmt.Errorf("glob-select: pattern not found: %s", pattern)
} }
return nil return nil
@@ -809,9 +994,9 @@ func findMatch(name, pattern string) bool {
func (nav *nav) findSingle() int { func (nav *nav) findSingle() int {
count := 0 count := 0
index := 0 index := 0
last := nav.currDir() dir := nav.currDir()
for i := 0; i < len(last.files); i++ { for i := 0; i < len(dir.files); i++ {
if findMatch(last.files[i].Name(), nav.find) { if findMatch(dir.files[i].Name(), nav.find) {
count++ count++
if count > 1 { if count > 1 {
return count return count
@@ -820,27 +1005,27 @@ func (nav *nav) findSingle() int {
} }
} }
if count == 1 { if count == 1 {
if index > last.ind { if index > dir.ind {
nav.down(index - last.ind) nav.down(index - dir.ind)
} else { } else {
nav.up(last.ind - index) nav.up(dir.ind - index)
} }
} }
return count return count
} }
func (nav *nav) findNext() bool { func (nav *nav) findNext() bool {
last := nav.currDir() dir := nav.currDir()
for i := last.ind + 1; i < len(last.files); i++ { for i := dir.ind + 1; i < len(dir.files); i++ {
if findMatch(last.files[i].Name(), nav.find) { if findMatch(dir.files[i].Name(), nav.find) {
nav.down(i - last.ind) nav.down(i - dir.ind)
return true return true
} }
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := 0; i < last.ind; i++ { for i := 0; i < dir.ind; i++ {
if findMatch(last.files[i].Name(), nav.find) { if findMatch(dir.files[i].Name(), nav.find) {
nav.up(last.ind - i) nav.up(dir.ind - i)
return true return true
} }
} }
@@ -849,17 +1034,17 @@ func (nav *nav) findNext() bool {
} }
func (nav *nav) findPrev() bool { func (nav *nav) findPrev() bool {
last := nav.currDir() dir := nav.currDir()
for i := last.ind - 1; i >= 0; i-- { for i := dir.ind - 1; i >= 0; i-- {
if findMatch(last.files[i].Name(), nav.find) { if findMatch(dir.files[i].Name(), nav.find) {
nav.up(last.ind - i) nav.up(dir.ind - i)
return true return true
} }
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := len(last.files) - 1; i > last.ind; i-- { for i := len(dir.files) - 1; i > dir.ind; i-- {
if findMatch(last.files[i].Name(), nav.find) { if findMatch(dir.files[i].Name(), nav.find) {
nav.down(i - last.ind) nav.down(i - dir.ind)
return true return true
} }
} }
@@ -889,25 +1074,25 @@ func searchMatch(name, pattern string) (matched bool, err error) {
} }
func (nav *nav) searchNext() error { func (nav *nav) searchNext() error {
last := nav.currDir() dir := nav.currDir()
for i := last.ind + 1; i < len(last.files); i++ { for i := dir.ind + 1; i < len(dir.files); i++ {
matched, err := searchMatch(last.files[i].Name(), nav.search) matched, err := searchMatch(dir.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
if matched { if matched {
nav.down(i - last.ind) nav.down(i - dir.ind)
return nil return nil
} }
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := 0; i < last.ind; i++ { for i := 0; i < dir.ind; i++ {
matched, err := searchMatch(last.files[i].Name(), nav.search) matched, err := searchMatch(dir.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
if matched { if matched {
nav.up(last.ind - i) nav.up(dir.ind - i)
return nil return nil
} }
} }
@@ -916,25 +1101,25 @@ func (nav *nav) searchNext() error {
} }
func (nav *nav) searchPrev() error { func (nav *nav) searchPrev() error {
last := nav.currDir() dir := nav.currDir()
for i := last.ind - 1; i >= 0; i-- { for i := dir.ind - 1; i >= 0; i-- {
matched, err := searchMatch(last.files[i].Name(), nav.search) matched, err := searchMatch(dir.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
if matched { if matched {
nav.up(last.ind - i) nav.up(dir.ind - i)
return nil return nil
} }
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := len(last.files) - 1; i > last.ind; i-- { for i := len(dir.files) - 1; i > dir.ind; i-- {
matched, err := searchMatch(last.files[i].Name(), nav.search) matched, err := searchMatch(dir.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
if matched { if matched {
nav.down(i - last.ind) nav.down(i - dir.ind)
return nil return nil
} }
} }
@@ -942,7 +1127,16 @@ func (nav *nav) searchPrev() error {
return nil return nil
} }
func (nav *nav) removeMark(mark string) error {
if _, ok := nav.marks[mark]; ok {
delete(nav.marks, mark)
return nil
}
return fmt.Errorf("no such mark")
}
func (nav *nav) readMarks() error { func (nav *nav) readMarks() error {
nav.marks = make(map[string]string)
f, err := os.Open(gMarksPath) f, err := os.Open(gMarksPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil return nil
@@ -968,14 +1162,6 @@ func (nav *nav) readMarks() error {
} }
func (nav *nav) writeMarks() error { func (nav *nav) writeMarks() error {
if len(nav.marks) == 0 {
return nil
}
if err := nav.readMarks(); err != nil {
return fmt.Errorf("reading marks file: %s", err)
}
if err := os.MkdirAll(filepath.Dir(gMarksPath), os.ModePerm); err != nil { if err := os.MkdirAll(filepath.Dir(gMarksPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err) return fmt.Errorf("creating data directory: %s", err)
} }
@@ -1007,12 +1193,12 @@ func (nav *nav) currDir() *dir {
} }
func (nav *nav) currFile() (*file, error) { func (nav *nav) currFile() (*file, error) {
last := nav.dirs[len(nav.dirs)-1] dir := nav.dirs[len(nav.dirs)-1]
if len(last.files) == 0 { if len(dir.files) == 0 {
return nil, fmt.Errorf("empty directory") return nil, fmt.Errorf("empty directory")
} }
return last.files[last.ind], nil return dir.files[dir.ind], nil
} }
type indexedSelections struct { type indexedSelections struct {
+33 -19
View File
@@ -9,6 +9,9 @@ const (
nameSort nameSort
sizeSort sizeSort
timeSort timeSort
atimeSort
ctimeSort
extSort
) )
type sortOption byte type sortOption byte
@@ -26,19 +29,20 @@ type sortType struct {
var gOpts struct { var gOpts struct {
anchorfind bool anchorfind bool
color256 bool
dircounts bool dircounts bool
drawbox bool drawbox bool
globsearch bool globsearch bool
icons bool
ignorecase bool ignorecase bool
incsearch bool
preview bool
smartcase bool
ignoredia bool ignoredia bool
incsearch bool
number bool
preview bool
relativenumber bool
smartcase bool
smartdia bool smartdia bool
wrapscan bool wrapscan bool
number bool wrapscroll bool
relativenumber bool
findlen int findlen int
period int period int
scrolloff int scrolloff int
@@ -50,7 +54,9 @@ var gOpts struct {
promptfmt string promptfmt string
shell string shell string
timefmt string timefmt string
truncatechar string
ratios []int ratios []int
hiddenfiles []string
info []string info []string
shellopts []string shellopts []string
keys map[string]expr keys map[string]expr
@@ -61,19 +67,20 @@ var gOpts struct {
func init() { func init() {
gOpts.anchorfind = true gOpts.anchorfind = true
gOpts.color256 = false
gOpts.dircounts = false gOpts.dircounts = false
gOpts.drawbox = false gOpts.drawbox = false
gOpts.globsearch = false gOpts.globsearch = false
gOpts.icons = false
gOpts.ignorecase = true gOpts.ignorecase = true
gOpts.incsearch = false
gOpts.preview = true
gOpts.smartcase = true
gOpts.ignoredia = false gOpts.ignoredia = false
gOpts.incsearch = false
gOpts.number = false
gOpts.preview = true
gOpts.relativenumber = false
gOpts.smartcase = true
gOpts.smartdia = false gOpts.smartdia = false
gOpts.wrapscan = true gOpts.wrapscan = true
gOpts.number = false gOpts.wrapscroll = false
gOpts.relativenumber = false
gOpts.findlen = 1 gOpts.findlen = 1
gOpts.period = 0 gOpts.period = 0
gOpts.scrolloff = 0 gOpts.scrolloff = 0
@@ -82,10 +89,12 @@ func init() {
gOpts.filesep = "\n" gOpts.filesep = "\n"
gOpts.ifs = "" gOpts.ifs = ""
gOpts.previewer = "" gOpts.previewer = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m" gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%w\033[0m\033[1m%f\033[0m"
gOpts.shell = gDefaultShell gOpts.shell = gDefaultShell
gOpts.timefmt = time.ANSIC gOpts.timefmt = time.ANSIC
gOpts.truncatechar = "~"
gOpts.ratios = []int{1, 2, 3} gOpts.ratios = []int{1, 2, 3}
gOpts.hiddenfiles = []string{".*"}
gOpts.info = nil gOpts.info = nil
gOpts.shellopts = nil gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort} gOpts.sortType = sortType{naturalSort, dirfirstSort}
@@ -111,7 +120,7 @@ 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["<space>"] = &callExpr{"toggle", nil, 1} gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
gOpts.keys["v"] = &callExpr{"invert", nil, 1} gOpts.keys["v"] = &callExpr{"invert", nil, 1}
gOpts.keys["u"] = &callExpr{"unselect", nil, 1} gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"copy", nil, 1} gOpts.keys["y"] = &callExpr{"copy", nil, 1}
@@ -135,6 +144,8 @@ func init() {
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1} gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1} gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1} gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1} gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1} gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
@@ -144,9 +155,12 @@ func init() {
gOpts.keys["zs"] = &setExpr{"info", "size"} gOpts.keys["zs"] = &setExpr{"info", "size"}
gOpts.keys["zt"] = &setExpr{"info", "time"} gOpts.keys["zt"] = &setExpr{"info", "time"}
gOpts.keys["za"] = &setExpr{"info", "size:time"} gOpts.keys["za"] = &setExpr{"info", "size:time"}
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}} gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}} gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}} gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1}
gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1}
gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1}
gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1} gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1}
gOpts.cmdkeys = make(map[string]expr) gOpts.cmdkeys = make(map[string]expr)
@@ -160,8 +174,8 @@ func init() {
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1} gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<bs>"] = &callExpr{"cmd-delete-back", nil, 1} gOpts.cmdkeys["<backspace>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<bs2>"] = &callExpr{"cmd-delete-back", nil, 1} gOpts.cmdkeys["<backspace2>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil, 1} gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil, 1} gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1} gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1}
+40 -10
View File
@@ -11,13 +11,15 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
"syscall"
) )
var ( var (
envOpener = os.Getenv("OPENER") envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR") envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER") envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
envTcellTruecolor = os.Getenv("TCELL_TRUECOLOR")
) )
var ( var (
@@ -54,6 +56,10 @@ func init() {
envShell = "sh" envShell = "sh"
} }
if envTcellTruecolor == "" {
envTcellTruecolor = "disable"
}
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
@@ -125,16 +131,40 @@ func setDefaults() {
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
} }
func moveCursor(y, x int) {
fmt.Printf("\033[%d;%dH", y, x)
}
func isExecutable(f os.FileInfo) bool { func isExecutable(f os.FileInfo) bool {
return f.Mode()&0111 != 0 return f.Mode()&0111 != 0
} }
func isHidden(f os.FileInfo) bool { func isHidden(f os.FileInfo, path string) bool {
return f.Name()[0] == '.' hidden := false
for _, pattern := range gOpts.hiddenfiles {
matched := matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path)
if strings.HasPrefix(pattern, "!") && matched {
hidden = false
} else if matched {
hidden = true
}
}
return hidden
}
func matchPattern(pattern, name, path string) bool {
s := name
pattern = replaceTilde(pattern)
if filepath.IsAbs(pattern) {
s = filepath.Join(path, name)
}
// pattern errors are checked when 'hiddenfiles' option is set
matched, _ := filepath.Match(pattern, s)
return matched
}
func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(syscall.Errno) == syscall.EXDEV
} }
func exportFiles(f string, fs []string) { func exportFiles(f string, fs []string) {
+25 -16
View File
@@ -12,20 +12,19 @@ import (
) )
var ( var (
envOpener = os.Getenv("OPENER") envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR") envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER") envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
envTcellTruecolor = os.Getenv("TCELL_TRUECOLOR")
) )
var ( var envPathExt = os.Getenv("PATHEXT")
envPathExt = os.Getenv("PATHEXT")
)
var ( var (
gDefaultShell = "cmd" gDefaultShell = "cmd"
gDefaultSocketProt = "tcp" gDefaultSocketProt = "tcp"
gDefaultSocketPath = ":12345" gDefaultSocketPath = "127.0.0.1:12345"
) )
var ( var (
@@ -52,6 +51,10 @@ func init() {
envShell = "cmd" envShell = "cmd"
} }
if envTcellTruecolor == "" {
envTcellTruecolor = "disable"
}
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
@@ -100,11 +103,6 @@ func setDefaults() {
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
} }
func moveCursor(y, x int) {
// TODO: implement
return
}
func isExecutable(f os.FileInfo) bool { func isExecutable(f os.FileInfo) bool {
exts := strings.Split(envPathExt, string(filepath.ListSeparator)) exts := strings.Split(envPathExt, string(filepath.ListSeparator))
for _, e := range exts { for _, e := range exts {
@@ -116,9 +114,20 @@ func isExecutable(f os.FileInfo) bool {
return false return false
} }
func isHidden(f os.FileInfo) bool { func isHidden(f os.FileInfo, path string) bool {
// TODO: implement ptr, err := syscall.UTF16PtrFromString(filepath.Join(path, f.Name()))
return false if err != nil {
return false
}
attrs, err := syscall.GetFileAttributes(ptr)
if err != nil {
return false
}
return attrs&syscall.FILE_ATTRIBUTE_HIDDEN != 0
}
func errCrossDevice(err error) bool {
return err.(*os.LinkError).Err.(syscall.Errno) == 17
} }
func exportFiles(f string, fs []string) { func exportFiles(f string, fs []string) {
+2 -1
View File
@@ -114,6 +114,7 @@ func (e *execExpr) String() string {
type listExpr struct { type listExpr struct {
exprs []expr exprs []expr
count int
} }
func (e *listExpr) String() string { func (e *listExpr) String() string {
@@ -265,7 +266,7 @@ func (p *parser) parseExpr() expr {
s.scan() s.scan()
result = &listExpr{exprs} result = &listExpr{exprs, 1}
case tokenPrefix: case tokenPrefix:
var expr string var expr string
+20 -25
View File
@@ -177,9 +177,6 @@ scan:
s.tok = string(s.buf[beg:s.off]) s.tok = string(s.buf[beg:s.off])
s.cmd = false s.cmd = false
s.sem = true s.sem = true
case s.chr == '\r':
s.next()
goto scan
case s.chr == '\n': case s.chr == '\n':
if s.sem { if s.sem {
s.typ = tokenSemicolon s.typ = tokenSemicolon
@@ -196,7 +193,7 @@ scan:
} }
goto scan goto scan
case isSpace(s.chr): case isSpace(s.chr):
for !s.eof && isSpace(s.chr) { for !s.eof && isSpace(s.chr) && s.chr != '\n' {
s.next() s.next()
} }
goto scan goto scan
@@ -216,25 +213,24 @@ scan:
for !s.eof && s.chr != '"' { for !s.eof && s.chr != '"' {
if s.chr == '\\' { if s.chr == '\\' {
s.next() s.next()
switch s.chr { switch {
case '"', '\\': case s.chr == '"' || s.chr == '\\':
buf = append(buf, s.chr) buf = append(buf, s.chr)
case 'a': case s.chr == 'a':
buf = append(buf, '\a') buf = append(buf, '\a')
case 'b': case s.chr == 'b':
buf = append(buf, '\b') buf = append(buf, '\b')
case 'f': case s.chr == 'f':
buf = append(buf, '\f') buf = append(buf, '\f')
case 'n': case s.chr == 'n':
buf = append(buf, '\n') buf = append(buf, '\n')
case 'r': case s.chr == 'r':
buf = append(buf, '\r') buf = append(buf, '\r')
case 't': case s.chr == 't':
buf = append(buf, '\t') buf = append(buf, '\t')
case 'v': case s.chr == 'v':
buf = append(buf, '\v') buf = append(buf, '\v')
} case isDigit(s.chr):
if isDigit(s.chr) {
var oct []byte var oct []byte
for isDigit(s.chr) { for isDigit(s.chr) {
oct = append(oct, s.chr) oct = append(oct, s.chr)
@@ -245,13 +241,15 @@ scan:
log.Printf("scanning: %s", err) log.Printf("scanning: %s", err)
} }
buf = append(buf, byte(n)) buf = append(buf, byte(n))
} else { continue
s.next() default:
buf = append(buf, '\\', s.chr)
} }
} else {
buf = append(buf, s.chr)
s.next() s.next()
continue
} }
buf = append(buf, s.chr)
s.next()
} }
s.typ = tokenIdent s.typ = tokenIdent
s.tok = string(buf) s.tok = string(buf)
@@ -293,12 +291,9 @@ scan:
for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' { for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' {
if s.chr == '\\' { if s.chr == '\\' {
s.next() s.next()
if isSpace(s.chr) { buf = append(buf, s.chr)
buf = append(buf, s.chr) s.next()
s.next() continue
} else {
s.next()
}
} }
buf = append(buf, s.chr) buf = append(buf, s.chr)
s.next() s.next()
+3 -2
View File
@@ -58,6 +58,7 @@ func listen(l net.Listener) {
func handleConn(c net.Conn) { func handleConn(c net.Conn) {
s := bufio.NewScanner(c) s := bufio.NewScanner(c)
Loop:
for s.Scan() { for s.Scan() {
log.Printf("listen: %s", s.Text()) log.Printf("listen: %s", s.Text())
word, rest := splitWord(s.Text()) word, rest := splitWord(s.Text())
@@ -71,7 +72,7 @@ func handleConn(c net.Conn) {
gCopyFile = false gCopyFile = false
default: default:
log.Printf("unexpected option to copy file(s): %s", s.Text()) log.Printf("unexpected option to copy file(s): %s", s.Text())
break break Loop
} }
gFileList = nil gFileList = nil
for s.Scan() && s.Text() != "" { for s.Scan() && s.Text() != "" {
@@ -120,7 +121,7 @@ func handleConn(c net.Conn) {
c.Close() c.Close()
} }
gListener.Close() gListener.Close()
break break Loop
default: default:
log.Printf("listen: unexpected command: %s", word) log.Printf("listen: unexpected command: %s", word)
} }
+393 -296
View File
File diff suppressed because it is too large. Load diff