Compare commits

241 Commits
Author SHA1 Message Date
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
Gokcehan 13fe1931cd replace godep with go modules
Related #155
2019-04-20 23:12:22 +03:00
Gokcehan 2c87b0dcfe fix hidden sort 2019-03-31 23:52:39 +03:00
Gokcehan b2b22fb674 disable hidden on windows 2019-03-31 23:39:41 +03:00
Gokcehan 45270e389e export id variable after initialization 2019-03-31 19:45:11 +03:00
Gokcehan fee016f406 cleanup 2019-03-27 23:03:19 +03:00
Gokcehan 29de45e466 cleanup 2019-03-27 22:11:34 +03:00
Gokcehan 791b704257 add 'errorfmt' option to format error messages
Related #154
2019-03-27 22:07:41 +03:00
Gokcehan e3bc11408f update example configuration 2019-03-20 21:45:09 +03:00
Gokcehan 6f35abb4ca quote file variables on windows 2019-03-17 20:16:19 +03:00
Gokcehan 0eedb71d6c export permanent env vars on startup
Related #134
2019-03-17 19:52:34 +03:00
Gokcehan 1eedd29546 add file completion to search
Related #150
2019-03-14 01:20:06 +03:00
Gokcehan 866a7e6a2b cleanup 2019-03-13 22:28:20 +03:00
Gokcehan 1956a759c4 cleanup 2019-03-04 00:05:29 +03:00
Gokcehan 9656553974 cleanup 2019-03-03 22:29:34 +03:00
Gokcehan 31945fbcb5 update doc 2019-03-03 22:12:33 +03:00
Gokcehan 4a8943b6b7 cleanup 2019-03-02 16:49:02 +03:00
Gokcehan 885e896b4a check existing move operation before quit 2019-03-01 17:45:47 +03:00
Gokcehan 808404978e show move progress in the ruler 2019-03-01 17:44:50 +03:00
Gokcehan 99734c7dcf increase copy buffer size 2019-03-01 04:01:33 +03:00
Gokcehan f44ec4f5bd use reverse attribute for preview messages 2019-03-01 03:51:14 +03:00
Gokcehan 4d2a628550 log copy and move errors 2019-02-28 22:04:57 +03:00
Gokcehan 193285a65d add 'echomsg' and 'echoerr' commands for logging 2019-02-28 21:58:14 +03:00
Gokcehan 6ec2924b6b show copy progress in the ruler 2019-02-28 21:04:38 +03:00
Gokcehan 599ac11f26 cleanup 2019-02-26 21:27:04 +03:00
Gokcehan 728c5fbb2c check if src and dst are the same file before move 2019-02-26 21:25:34 +03:00
Gokcehan 0f47c5428b load directories after copy/move 2019-02-26 21:04:51 +03:00
Gokcehan 4865ce9b00 implement builtin move operation
Related #61 and #113
2019-02-26 20:32:30 +03:00
Gokcehan d6e9aece51 implement builtin copy operation
Related #61 and #113
2019-02-26 20:12:13 +03:00
Gokcehan fd1af47233 initialize termbox before logging
Related #138
2019-02-18 14:18:02 +03:00
Gokcehan 184762d83a remove background colors from defaults 2019-02-10 20:45:34 +03:00
Gokcehan 27f104b3e6 select first argument on startup
Related #101
2019-02-10 19:48:49 +03:00
Gokcehan 35930924a7 disable normal commands in cmap
Related #68
2019-02-10 19:28:14 +03:00
Gokcehan 4a1388a5c7 read configuration after initialization 2019-02-09 00:55:11 +03:00
Gokcehan 92e994ebf6 Revert "only echo when the output pauses in shell-pipe"
This reverts commit dd6a85f480.
2019-02-09 00:48:23 +03:00
Gokcehan 245db502cc execute multiple commands with command flag
Related #135
2019-02-08 19:54:04 +03:00
Gokcehan ca95bcf1d8 add shell prefixes to history 2019-02-08 19:19:28 +03:00
Gokcehan dd6a85f480 only echo when the output pauses in shell-pipe 2019-02-08 19:06:37 +03:00
Gokcehan db8f535b61 cleanup 2019-02-07 00:36:15 +03:00
Gokcehan 52be0b3aab handle shell-pipe prompts properly
Related #137
2019-02-07 00:34:42 +03:00
Gokcehan bd889a9e06 make 'delete' command prompting
Related #113
2019-02-06 15:56:41 +03:00
Gokcehan 951529ebc0 make read commands work when typed manually 2019-02-06 15:07:31 +03:00
Daniel Lewan 0fc14e3b2d add option to execute command on server initialization (#135) 2019-02-06 14:56:06 +03:00
Gokcehan 79b05dc365 update doc 2019-01-31 22:15:31 +03:00
Gokcehan c7fe60c541 keep command line mode for resize events 2019-01-31 21:55:32 +03:00
Gokcehan ec5fac3274 cleanup 2019-01-31 21:51:17 +03:00
Tomáš Martiček 90f0339fa9 Implemented line numbers (#133) 2019-01-27 17:31:29 +03:00
Gokcehan e0e5977008 update documentation 2019-01-18 23:09:18 +03:00
Gokcehan 85a6fe95c5 rename diacritics files 2019-01-18 21:21:31 +03:00
Gokcehan 55955fa5c1 add search and find to the documentation
Related #68
2019-01-18 20:41:17 +03:00
Daniel Lewan 993b227682 add fish completion to etc (#131) 2019-01-17 17:51:32 +03:00
Gokcehan d8b9bab3ea add 'color256' option to control color mode
Related #104
2019-01-08 22:47:41 +03:00
Gokcehan c5297d6b6b handle normal commands in cmap
Related #68
2018-12-29 21:39:06 +03:00
Gokcehan 8dd3f692b8 remove duplicates in autocompletion 2018-12-29 20:20:45 +03:00
Kallinteris Andreas 7e3f92f049 added ':delete' builtin command (#121)
* added ':delete' command

* fixed doc

* fixed typo

* added dummy function for delete for windows

* detacted the functionality from the OS

* now deletion works based on selections

* added effective selection

* delete no longer sends 'send sync'

* fixed typo

* fixed typo

* added DOC to effective selection

* added DOC to deleteFiles()

* fixed DOC typos

* added ability to overwrite :delete

* added ability to overwrite :delete
2018-12-29 20:14:20 +03:00
Gokcehan 3efdfd3bca update documentation 2018-12-03 15:46:17 +03:00
Gokcehan b101603a4a Revert "only draw ui when the output pauses in shell-pipe"
This reverts commit 8229d972b9.
2018-12-03 15:43:12 +03:00
martinlebeda c693b7eae4 add ignoredia and smartdia option for search and find without diacritics (#118) 2018-12-03 15:41:53 +03:00
Gokcehan 4ee6488a09 add 'incsearch' option for incremental searching
Related #68
2018-11-24 19:02:04 +03:00
Gokcehan 8229d972b9 only draw ui when the output pauses in shell-pipe 2018-11-08 20:00:54 +03:00
Gokcehan 6193885a55 remove notice from readme 2018-10-30 21:47:45 +03:00
Gokcehan 6b1748240c add notice to readme 2018-10-02 14:41:07 +03:00
Gokcehan 629a7f3297 update documentation 2018-08-29 19:28:22 +03:00
Gokcehan 5e67147204 check HOME and USER variables on startup
Related #108
2018-08-27 19:38:08 +03:00
Gokcehan 266a583adb use load instead of reload after shell-pipe
Related #109
2018-08-27 19:01:21 +03:00
Gokcehan b22384d634 keep index when selection is deleted
Related #109
2018-08-27 18:57:55 +03:00
Gokcehan 4ba3c3cda9 keep reverse direction in find and search 2018-08-23 01:55:50 +03:00
Gokcehan 4420e41c76 add 'anchorfind' option to control find start
Related #68
2018-08-23 01:37:07 +03:00
Gokcehan a59a5aa712 use zero value in findlen for arbitrary length
Related #68
2018-08-23 01:29:59 +03:00
Gokcehan 170e39b95e add 'findlen' option to control number of chars
Related #68
2018-08-22 20:57:47 +03:00
Gokcehan 011cca76d1 add find commands to find as you type
Related #68
2018-08-22 20:05:22 +03:00
Gokcehan 0b8de7c77e detach server on windows
Related #106
2018-08-01 00:21:55 +03:00
Gokcehan d3f9a3588f handle non-existent directories during reload 2018-07-30 20:56:57 +03:00
Gokcehan a0935fabcb handle removed directories during load 2018-07-30 18:41:14 +03:00
Gokcehan e82cbb820f export 'LF_LEVEL' variable for nested instances
Related #107
2018-07-28 16:52:54 +03:00
Gokcehan 9234bcd5b8 try to reconnect after sleep 2018-07-26 22:11:05 +03:00
Gokcehan 7dbb61f295 try to reconnect when server is not yet started
Related #106
2018-07-26 21:58:09 +03:00
Gokcehan 40002a7752 add 'quit' command to server protocol
Related #106
2018-07-22 20:44:56 +03:00
Gokcehan ffa913d943 update readme 2018-07-19 00:59:09 +03:00
Gokcehan abf2187271 save last directory as a mark
Related #76
2018-07-17 19:45:31 +03:00
Gokcehan ee7293e2f7 change system configuration path on unix 2018-07-13 22:46:37 +03:00
Gokcehan 95a9305f70 add marks and history file locations to doc 2018-07-12 21:47:19 +03:00
Gokcehan cdf4fcb810 write history to history file on quit
Related #81
2018-07-12 21:22:36 +03:00
Gokcehan 211bcd0444 write marks to marks file on quit
Related #76
2018-07-11 20:09:26 +03:00
Gokcehan 0d0f7451ac add 'mark-save' and 'mark-load' commands for marks
Related #76
2018-07-09 21:35:04 +03:00
Gokcehan a80900f41e rename mark to selection 2018-07-09 21:22:10 +03:00
Gokcehan 552182958a use pager variable for doc on windows 2018-07-08 14:27:35 +03:00
Gokcehan d86e9c991c add 'doc' command to view documentation
Related #100
2018-07-07 17:50:47 +03:00
Gokcehan e74a43bf0e cleanup 2018-07-07 17:34:04 +03:00
Gokcehan 9d4accbcde typo 2018-07-06 01:16:58 +03:00
Gokcehan db9d795cb0 cleanup 2018-07-06 01:12:20 +03:00
Gokcehan 2f3c52f9f2 update readme 2018-07-05 23:15:16 +03:00
Gokcehan 63892ee83c generate man page from the documentation 2018-07-05 23:09:53 +03:00
Gokcehan 2c14b3cd4a cleanup 2018-06-29 00:34:21 +03:00
Gokcehan e1b6d38386 add executable completion on windows 2018-06-29 00:12:54 +03:00
Gokcehan fef99c1d70 use env vars on windows 2018-06-28 23:37:01 +03:00
Gokcehan b8523c3258 rename 'remove' to 'delete' in example config 2018-06-28 21:55:56 +03:00
Gokcehan 4cbb211757 use env vars in example config 2018-06-28 21:53:42 +03:00
Gokcehan 5787ecd1bd add default environmental variables 2018-06-28 21:51:24 +03:00
Gokcehan 96f35e986d rename 'open-file' to 'open' 2018-06-28 21:20:43 +03:00
Gokcehan 07c16fede0 add configuration file locations to doc 2018-06-28 20:23:50 +03:00
Gokcehan 2d821216a8 read system-wide configuration on windows 2018-06-28 19:45:59 +03:00
Gokcehan 638d67c0e4 read system-wide configuration at '/etc/lfrc' 2018-06-28 19:44:50 +03:00
Gokcehan 6c319316e2 add 'source' command to read a configuration file
Related #97
2018-06-28 17:14:35 +03:00
Gokcehan 5d5d00e30b add special keys to default keybindings 2018-06-27 21:33:00 +03:00
Gokcehan d987c9e439 rename yank-delete-put to copy-cut-paste 2018-06-27 21:17:56 +03:00
Gokcehan b67b042d43 add shell options to example config 2018-06-26 22:24:41 +03:00
Gokcehan e99478e8a1 add 'shellopts' option to set shell arguments
Related #102
2018-06-26 21:14:55 +03:00
Gokcehan 4c54acebeb add optional version parameter to build scripts
Related #103
2018-06-26 17:09:05 +03:00
Gokcehan fe786aae4c add a build script for a static stripped binary
Related #99 and #103
2018-06-26 16:29:48 +03:00
Gokcehan a607e53e51 use dep for dependency management
Related #103
2018-06-26 00:46:50 +03:00
Gokcehan da126a3959 update readme 2018-06-16 16:59:41 +03:00
Gokcehan 6d20887b16 update preview when 'hidden' is changed 2018-06-16 16:34:14 +03:00
Gokcehan 078dc47e34 find hidden parents when 'hidden' is changed 2018-06-16 16:27:39 +03:00
Gokcehan 8070cd82b7 cleanup 2018-06-16 00:59:16 +03:00
Gokcehan 52974615f2 handle command properly with 'cmd-word'back' 2018-06-16 00:13:33 +03:00
Gokcehan 76a725eaf2 replace 'reload' with 'load' in documentaiton 2018-06-15 22:52:17 +03:00
Gokcehan 2e014b3c0a add tutorial link to readme
Related #94
2018-06-15 21:05:55 +03:00
Gokcehan 51101f7020 load all clients after running 'put' command 2018-06-15 16:34:44 +03:00
Gokcehan ba01f85340 add 'load' command to load modified dirs and files 2018-06-15 16:33:54 +03:00
Gokcehan 723357fe3d add 'period' option for periodic refresh
Related #73
2018-06-09 22:02:09 +03:00
Gokcehan e025c68130 keep cache when navigation is renewed 2018-06-08 21:47:28 +03:00
Gokcehan 7acc85f81c reload modified files when loading cache
Related #92
2018-06-07 22:49:53 +03:00
Gokcehan 4846a74320 reload modified directories when loading cache
Related #92
2018-06-07 22:19:55 +03:00
Gokcehan 9177ddd406 cleanup 2018-06-06 21:50:15 +03:00
Gokcehan 9d21a4f359 add key mappings to the doc 2018-06-06 21:39:44 +03:00
Gokcehan 20720c832d cleanup 2018-06-06 20:55:13 +03:00
Gokcehan 448f2a3cb2 restart server when crashed
Related #65
2018-06-05 22:11:20 +03:00
Gokcehan 397d5e0fac disable history when a command is running 2018-05-20 20:42:19 +03:00
Gokcehan 9400f07e45 skip searches from command history 2018-05-20 20:38:18 +03:00
Gokcehan a85e0da9b0 cleanup 2018-05-20 20:30:41 +03:00
Gokcehan 03b9fe0c5e skip whitespace before 'cmd-capitalize-word' 2018-05-16 15:13:05 +03:00
Gokcehan 42d57121f7 rename 'cmd-put' to 'cmd-yank' 2018-05-16 00:28:11 +03:00
Gokcehan ed8137a79c rename 'bot' to 'bottom' 2018-05-16 00:20:05 +03:00
Gokcehan d9761d2dc8 rename 'hist' to 'history' 2018-05-16 00:16:49 +03:00
Gokcehan 04f1d68d1e rename 'comp' to 'complete' 2018-05-16 00:05:06 +03:00
Gokcehan 3deea69c4d rename 'cmd-delete-beg' to 'cmd-delete-home' 2018-05-16 00:02:06 +03:00
Gokcehan 980a89c908 rename 'cmd-beg' to 'cmd-home' 2018-05-16 00:00:20 +03:00
Gokcehan de39594a46 add 'cmd-transpose-word' to swap words 2018-05-14 19:38:35 +03:00
Gokcehan 6e6cca33b8 add 'cmd-lowercase-word' to downcase word to end 2018-05-14 01:38:19 +03:00
Gokcehan 18f6d954a7 add 'cmd-uppercase-word' to upcase word to end 2018-05-14 01:30:53 +03:00
Gokcehan 1a95df7b64 add 'cmd-delete-word' to delete word to end 2018-05-14 01:25:26 +03:00
Gokcehan afefc30a67 rename 'cmd-delete-word' to 'cmd-delete-unix-word' 2018-05-14 01:19:26 +03:00
Gokcehan 0c672fef6f add 'cmd-capitalize-word' to upcase letter 2018-05-14 01:16:01 +03:00
Gokcehan bc67283f2a add tests for colors 2018-05-06 18:45:31 +03:00
Gokcehan f672a71f3d fix confusion of 8-bit color codes and attributes 2018-05-06 18:45:18 +03:00
Gokcehan ef709b5611 implement 'cmd-word' and 'cmd-word-back' commands
Related #67
2018-05-05 19:37:14 +03:00
Gokcehan 7543b2256c add support for alt keys
Related #67
2018-05-05 16:27:32 +03:00
Gokcehan 0855507298 fix default commands on windows 2018-04-28 18:34:24 +03:00
42 changed files with 5166 additions and 1409 deletions

No files matched your search

+1
View File
@@ -2,3 +2,4 @@ lf
lf.exe lf.exe
tags tags
dist/ dist/
vendor/
+2 -1
View File
@@ -1,6 +1,7 @@
language: go language: go
install: install:
- go get github.com/nsf/termbox-go - go get github.com/doronbehar/termbox-go
- go get gopkg.in/djherbis/times.v1
before_deploy: before_deploy:
- gen/xbuild.sh - gen/xbuild.sh
deploy: deploy:
+2 -2
View File
@@ -15,7 +15,7 @@
`lf` (as in "list files") is a terminal file manager written in Go. `lf` (as in "list files") is a terminal file manager written in Go.
It is heavily inspired by ranger with some missing and extra features. It is heavily inspired by ranger with some missing and extra features.
Some of the missing features are deliberately omitted since they are better handled by external tools. Some of the missing features are deliberately omitted since they are better handled by external tools.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information. See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts.
![multicol-screenshot](http://i.imgur.com/DaTUenu.png) ![multicol-screenshot](http://i.imgur.com/DaTUenu.png)
![singlecol-screenshot](http://i.imgur.com/p95xzUj.png) ![singlecol-screenshot](http://i.imgur.com/p95xzUj.png)
@@ -38,7 +38,7 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information.
## May-Futures ## May-Futures
- Bookmarks - Mouse control
## Installation ## Installation
+239 -58
View File
@@ -7,8 +7,11 @@ import (
"log" "log"
"os" "os"
"os/exec" "os/exec"
"strconv" "os/signal"
"path/filepath"
"strings" "strings"
"syscall"
"time"
) )
type cmdItem struct { type cmdItem struct {
@@ -17,24 +20,40 @@ type cmdItem struct {
} }
type app struct { type app struct {
ui *ui ui *ui
nav *nav nav *nav
quitChan chan bool ticker *time.Ticker
cmd *exec.Cmd quitChan chan bool
cmdIn io.WriteCloser cmd *exec.Cmd
cmdOutBuf []byte cmdIn io.WriteCloser
cmdHist []cmdItem cmdOutBuf []byte
cmdHistInd int cmdHistory []cmdItem
cmdHistoryBeg int
cmdHistoryInd int
} }
func newApp() *app { func newApp() *app {
ui := newUI() ui := newUI()
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,
quitChan: make(chan bool, 1), ticker: new(time.Ticker),
quitChan: quitChan,
} }
} }
@@ -43,33 +62,149 @@ func (app *app) readFile(path string) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
app.ui.printf("opening file: %s", err) app.ui.echoerrf("opening file: %s", err)
return return
} }
defer f.Close() defer f.Close()
p := newParser(f) p := newParser(f)
for p.parse() { for p.parse() {
p.expr.eval(app, nil) p.expr.eval(app, nil)
} }
if p.err != nil { if p.err != nil {
app.ui.printf("%s", p.err) app.ui.echoerrf("%s", p.err)
} }
} }
// This is the main event loop of the application. There are two channels to func (app *app) readHistory() error {
// read expressions from client and server. Reading and evaluation are done on f, err := os.Open(gHistoryPath)
// separate goroutines. if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("opening history file: %s", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2)
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
}
app.cmdHistoryBeg = len(app.cmdHistory)
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
return nil
}
func (app *app) writeHistory() error {
if len(app.cmdHistory) == 0 {
return nil
}
local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg)
copy(local, app.cmdHistory[app.cmdHistoryBeg:])
app.cmdHistory = nil
if err := app.readHistory(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
app.cmdHistory = append(app.cmdHistory, local...)
if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
f, err := os.Create(gHistoryPath)
if err != nil {
return fmt.Errorf("creating history file: %s", err)
}
defer f.Close()
if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
}
for _, cmd := range app.cmdHistory {
_, err = f.WriteString(fmt.Sprintf("%s %s\n", cmd.prefix, cmd.value))
if err != nil {
return fmt.Errorf("writing history file: %s", err)
}
}
return nil
}
// This is the main event loop of the application. Expressions are read from
// the client and the server on separate goroutines and sent here over channels
// for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update.
func (app *app) loop() { func (app *app) loop() {
clientChan := app.ui.readExpr() clientChan := app.ui.readExpr()
serverChan := readExpr() serverChan := readExpr()
if gSelect != "" {
go func() {
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}
}
}()
}
for _, path := range gConfigPaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
app.readFile(path)
}
}
if gCommand != "" {
p := newParser(strings.NewReader(gCommand))
for p.parse() {
p.expr.eval(app, nil)
}
if p.err != nil {
app.ui.echoerrf("%s", p.err)
}
}
for { for {
select { select {
case <-app.quitChan: case <-app.quitChan:
if app.nav.copyTotal > 0 {
app.ui.echoerr("quit: copy operation in progress")
continue
}
if app.nav.moveTotal > 0 {
app.ui.echoerr("quit: move operation in progress")
continue
}
if app.nav.deleteTotal > 0 {
app.ui.echoerr("quit: delete operation in progress")
continue
}
log.Print("bye!") log.Print("bye!")
if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err)
}
if gLastDirPath != "" { if gLastDirPath != "" {
f, err := os.Create(gLastDirPath) f, err := os.Create(gLastDirPath)
if err != nil { if err != nil {
@@ -77,19 +212,66 @@ 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)
} }
} }
return return
case n := <-app.nav.copyBytesChan:
app.nav.copyBytes += n
// n is usually 4096B so update roughly per 4096B x 1024 = 4MB copied
if app.nav.copyUpdate++; app.nav.copyUpdate >= 1024 {
app.nav.copyUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.copyTotalChan:
app.nav.copyTotal += n
if n < 0 {
app.nav.copyBytes += n
}
if app.nav.copyTotal == 0 {
app.nav.copyUpdate = 0
}
app.ui.draw(app.nav)
case n := <-app.nav.moveCountChan:
app.nav.moveCount += n
if app.nav.moveUpdate++; app.nav.moveUpdate >= 1000 {
app.nav.moveUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.moveTotalChan:
app.nav.moveTotal += n
if n < 0 {
app.nav.moveCount += n
}
if app.nav.moveTotal == 0 {
app.nav.moveUpdate = 0
}
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.find(prev.name(), app.nav.height) d.ind = prev.ind
d.sel(prev.name(), app.nav.height)
} }
app.nav.dirCache[d.path] = d app.nav.dirCache[d.path] = d
@@ -114,6 +296,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()
@@ -130,30 +314,23 @@ func (app *app) loop() {
case e := <-serverChan: case e := <-serverChan:
e.eval(app, nil) e.eval(app, nil)
app.ui.draw(app.nav) app.ui.draw(app.nav)
case <-app.ticker.C:
app.nav.renew()
app.ui.loadFile(app.nav)
app.ui.draw(app.nav)
} }
} }
} }
func (app *app) exportVars() { func (app *app) exportFiles() {
var envFile string var currFile string
if f, err := app.nav.currFile(); err == nil { if curr, err := app.nav.currFile(); err == nil {
envFile = f.path currFile = curr.path
} }
marks := app.nav.currMarks() currSelections := app.nav.currSelections()
envFiles := strings.Join(marks, gOpts.filesep) exportFiles(currFile, currSelections)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(marks) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
os.Setenv("id", strconv.Itoa(gClientID))
} }
func waitKey() error { func waitKey() error {
@@ -170,19 +347,20 @@ func waitKey() error {
return nil return nil
} }
// This function is used to run a command in shell. Following modes are used: // This function is used to run a shell command. Modes are as follows:
// //
// Prefix Wait Async Stdin Stdout Stderr UI action // Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume // $ No No Yes Yes Yes Pause and then resume
// % No No Yes Yes Yes Use statline for input/output // % No No Yes Yes Yes Statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume // ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing // & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) { func (app *app) runShell(s string, args []string, prefix string) {
app.exportVars() app.exportFiles()
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
@@ -192,6 +370,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 {
@@ -204,24 +384,19 @@ 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()
} }
if err != nil { if err != nil {
app.ui.printf("running shell: %s", err) app.ui.echoerrf("running shell: %s", err)
} }
switch prefix { switch prefix {
case "!": case "!":
if err := waitKey(); err != nil { if err := waitKey(); err != nil {
app.ui.printf("waiting key: %s", err) app.ui.echoerrf("waiting key: %s", err)
} }
} }
@@ -230,12 +405,12 @@ func (app *app) runShell(s string, args []string, prefix string) {
switch prefix { switch prefix {
case "%": case "%":
go func() { app.cmd = cmd
app.cmd = cmd app.cmdOutBuf = nil
app.cmdOutBuf = nil app.ui.msg = ""
app.ui.msg = "" app.ui.cmdPrefix = ">"
app.ui.cmdPrefix = ">"
go func() {
reader := bufio.NewReader(out) reader := bufio.NewReader(out)
for { for {
b, err := reader.ReadByte() b, err := reader.ReadByte()
@@ -254,7 +429,13 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
app.cmd = nil app.cmd = nil
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"reload", nil, 1} app.ui.exprChan <- &callExpr{"load", nil, 1}
}()
case "&":
go func() {
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
}() }()
} }
} }
+32 -23
View File
@@ -8,32 +8,37 @@ import (
"net" "net"
"os" "os"
"strings" "strings"
"time"
"github.com/nsf/termbox-go" "github.com/doronbehar/termbox-go"
) )
func run() { func run() {
logFile, err := os.Create(gLogPath)
if err != nil {
panic(err)
}
defer os.Remove(gLogPath)
defer logFile.Close()
log.SetOutput(logFile)
log.Print("hi!")
if err := termbox.Init(); err != nil { if err := termbox.Init(); err != nil {
log.Fatalf("initializing termbox: %s", err) log.Fatalf("initializing termbox: %s", err)
} }
defer termbox.Close() defer termbox.Close()
termbox.SetOutputMode(termbox.Output256) setColorMode()
f, err := os.Create(gLogPath)
if err != nil {
panic(err)
}
defer os.Remove(gLogPath)
defer f.Close()
log.SetOutput(f)
log.Print("hi!")
app := newApp() app := newApp()
if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) { if err := app.nav.readMarks(); err != nil {
app.readFile(gConfigPath) app.ui.echoerrf("reading marks file: %s", err)
}
if err := app.readHistory(); err != nil {
app.ui.echoerrf("reading history file: %s", err)
} }
app.loop() app.loop()
@@ -43,10 +48,14 @@ func readExpr() <-chan expr {
ch := make(chan expr) ch := make(chan expr)
go func() { go func() {
duration := 1 * time.Second
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { for err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err)) log.Printf("connecting server: %s", err)
return time.Sleep(duration)
duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath)
} }
fmt.Fprintf(c, "conn %d\n", gClientID) fmt.Fprintf(c, "conn %d\n", gClientID)
@@ -68,7 +77,7 @@ func readExpr() <-chan expr {
return ch return ch
} }
func saveFiles(list []string, copy bool) error { func saveFiles(list []string, cp bool) error {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { if err != nil {
return fmt.Errorf("dialing to save files: %s", err) return fmt.Errorf("dialing to save files: %s", err)
@@ -79,7 +88,7 @@ func saveFiles(list []string, copy bool) error {
fmt.Fprintln(c, "save") fmt.Fprintln(c, "save")
if copy { if cp {
fmt.Fprintln(c, "copy") fmt.Fprintln(c, "copy")
} else { } else {
fmt.Fprintln(c, "move") fmt.Fprintln(c, "move")
@@ -93,7 +102,7 @@ func saveFiles(list []string, copy bool) error {
return nil return nil
} }
func loadFiles() (list []string, copy bool, err error) { func loadFiles() (list []string, cp bool, err error) {
c, e := net.Dial(gSocketProt, gSocketPath) c, e := net.Dial(gSocketProt, gSocketPath)
if e != nil { if e != nil {
err = fmt.Errorf("dialing to load files: %s", e) err = fmt.Errorf("dialing to load files: %s", e)
@@ -109,9 +118,9 @@ func loadFiles() (list []string, copy bool, err error) {
switch s.Text() { switch s.Text() {
case "copy": case "copy":
copy = true cp = true
case "move": case "move":
copy = false cp = false
default: default:
err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text()) err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text())
return return
@@ -131,7 +140,7 @@ func loadFiles() (list []string, copy bool, err error) {
return return
} }
func sendRemote(cmd string) error { func remote(cmd string) error {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { if err != nil {
return fmt.Errorf("dialing to send server: %s", err) return fmt.Errorf("dialing to send server: %s", err)
+56 -32
View File
@@ -7,11 +7,34 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/nsf/termbox-go" "github.com/doronbehar/termbox-go"
) )
const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse
var gAnsiCodes = map[int]termbox.Attribute{
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 { type colorEntry struct {
fg termbox.Attribute fg termbox.Attribute
bg termbox.Attribute bg termbox.Attribute
@@ -28,25 +51,25 @@ func parseColors() colorMap {
return parseColorsBSD(env) return parseColorsBSD(env)
} }
// default values from dircolors // default values from dircolors with removed background colors
defaultColors := []string{ defaultColors := []string{
// "rs=0", // "rs=0",
"di=01;34", "di=01;34",
"ln=01;36", "ln=01;36",
// "mh=00", // "mh=00",
"pi=40;33", "pi=33", // "pi=40;33",
"so=01;35", "so=01;35",
"do=01;35", "do=01;35",
"bd=40;33;01", "bd=33;01", // "bd=40;33;01",
"cd=40;33;01", "cd=33;01", // "cd=40;33;01",
"or=40;31;01", "or=31;01", // "or=40;31;01",
// "mi=00", // "mi=00",
"su=37;41", "su=01;32", // "su=37;41",
"sg=30;43", "sg=01;32", // "sg=30;43",
"ca=30;41", // "ca=30;41",
"tw=30;42", "tw=01;34", // "tw=30;42",
"ow=34;42", "ow=01;34", // "ow=34;42",
"st=37;44", "st=01;34", // "st=37;44",
"ex=01;32", "ex=01;32",
} }
@@ -57,13 +80,12 @@ func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, term
toks := strings.Split(s, ";") toks := strings.Split(s, ";")
var nums []int var nums []int
for _, t := range toks { for _, tok := range toks {
if t == "" { if tok == "" {
fg = termbox.ColorDefault nums = append(nums, 0)
bg = termbox.ColorDefault continue
break
} }
n, err := strconv.Atoi(t) n, err := strconv.Atoi(tok)
if err != nil { if err != nil {
log.Printf("converting escape code: %s", err) log.Printf("converting escape code: %s", err)
continue continue
@@ -71,17 +93,19 @@ func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, term
nums = append(nums, n) nums = append(nums, n)
} }
// parse 256 color terminal ansi codes for i := 0; i < len(nums); i++ {
if len(nums) == 3 { n := nums[i]
if nums[0] == 48 && nums[1] == 5 { switch {
bg = termbox.Attribute(nums[2] + 1) 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
} }
if nums[0] == 38 && nums[1] == 5 {
fg = termbox.Attribute(nums[2] + 1)
}
}
for _, n := range nums {
attr, ok := gAnsiCodes[n] attr, ok := gAnsiCodes[n]
if !ok { if !ok {
log.Printf("unknown ansi code: %d", n) log.Printf("unknown ansi code: %d", n)
@@ -175,6 +199,10 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
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:
@@ -183,10 +211,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:
+77
View File
@@ -0,0 +1,77 @@
package main
import (
"testing"
"github.com/doronbehar/termbox-go"
)
func TestApplyAnsiCodes(t *testing.T) {
none := termbox.ColorDefault
tests := []struct {
s string
fg termbox.Attribute
bg termbox.Attribute
fgExp termbox.Attribute
bgExp termbox.Attribute
}{
{"", none, none, none, none},
{"", termbox.ColorRed, termbox.ColorRed, none, none},
{"", termbox.AttrBold, none, none, none},
{"", termbox.ColorRed | termbox.AttrBold, none, none, none},
{"0", none, none, none, none},
{"0", termbox.ColorRed, termbox.ColorRed, none, none},
{"0", termbox.AttrBold, none, none, none},
{"0", termbox.ColorRed | termbox.AttrBold, none, none, none},
{"1", none, none, termbox.AttrBold, none},
{"4", none, none, termbox.AttrUnderline, none},
{"7", none, none, termbox.AttrReverse, none},
{"1", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrBold, none},
{"4", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrUnderline, none},
{"7", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrReverse, none},
{"4", termbox.AttrBold, none, termbox.AttrBold | termbox.AttrUnderline, none},
{"4", termbox.ColorRed | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold | termbox.AttrUnderline, none},
{"31", none, none, termbox.ColorRed, none},
{"31", termbox.ColorGreen, none, termbox.ColorRed, none},
{"31", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none},
{"41", none, none, none, termbox.ColorRed},
{"41", none, termbox.ColorGreen, none, termbox.ColorRed},
{"1;31", none, none, termbox.ColorRed | termbox.AttrBold, none},
{"1;31", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none},
{"38;5;0", none, none, termbox.ColorBlack, none},
{"38;5;1", none, none, termbox.ColorRed, none},
{"38;5;8", none, none, termbox.Attribute(9), none},
{"38;5;16", none, none, termbox.Attribute(17), none},
{"38;5;232", none, none, termbox.Attribute(233), none},
{"38;5;1", termbox.ColorGreen, none, termbox.ColorRed, none},
{"38;5;1", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none},
{"48;5;0", none, none, none, termbox.ColorBlack},
{"48;5;1", none, none, none, termbox.ColorRed},
{"48;5;8", none, none, none, termbox.Attribute(9)},
{"48;5;16", none, none, none, termbox.Attribute(17)},
{"48;5;232", none, none, none, termbox.Attribute(233)},
{"48;5;1", none, termbox.ColorGreen, none, termbox.ColorRed},
{"1;38;5;1", none, none, termbox.ColorRed | termbox.AttrBold, none},
{"1;38;5;1", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none},
}
for _, test := range tests {
if fgGot, bgGot := applyAnsiCodes(test.s, test.fg, test.bg); fgGot != test.fgExp || bgGot != test.bgExp {
t.Errorf("at input '%s' with '%d' and '%d' expected '%d' and '%d' but got '%d' and '%d'",
test.s, test.fg, test.bg, test.fgExp, test.bgExp, fgGot, bgGot)
}
}
}
+161 -56
View File
@@ -24,34 +24,55 @@ var (
"open", "open",
"quit", "quit",
"top", "top",
"bot", "bottom",
"toggle", "toggle",
"invert", "invert",
"unmark", "unselect",
"yank", "copy",
"delete", "cut",
"put", "paste",
"clear", "clear",
"draw",
"redraw", "redraw",
"reload", "reload",
"read", "read",
"rename",
"shell", "shell",
"shell-pipe", "shell-pipe",
"shell-wait", "shell-wait",
"shell-async", "shell-async",
"find",
"find-back",
"find-next",
"find-prev",
"search", "search",
"search-back", "search-back",
"search-next", "search-next",
"search-prev", "search-prev",
"mark-save",
"mark-remove",
"mark-load",
"draw",
"load",
"sync", "sync",
"echo", "echo",
"echomsg",
"echoerr",
"cd", "cd",
"select", "select",
"glob-select",
"glob-unselect",
"source",
"push", "push",
"delete",
} }
gOptWords = []string{ gOptWords = []string{
"anchorfind",
"noanchorfind",
"anchorfind!",
"color256",
"nocolor256",
"color256!",
"dircounts", "dircounts",
"nodircounts", "nodircounts",
"dircounts!", "dircounts!",
@@ -67,32 +88,59 @@ var (
"hidden", "hidden",
"nohidden", "nohidden",
"hidden!", "hidden!",
"icons",
"noicons",
"icons!",
"ignorecase", "ignorecase",
"noignorecase", "noignorecase",
"ignorecase!", "ignorecase!",
"ignoredia",
"noignoredia",
"ignoredia!",
"incsearch",
"noincsearch",
"incsearch!",
"number",
"nonumber",
"number!",
"preview", "preview",
"nopreview", "nopreview",
"preview!", "preview!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"reverse", "reverse",
"noreverse", "noreverse",
"reverse!", "reverse!",
"smartcase", "smartcase",
"nosmartcase", "nosmartcase",
"smartcase!", "smartcase!",
"smartdia",
"nosmartdia",
"smartdia!",
"wrapscan", "wrapscan",
"nowrapscan", "nowrapscan",
"wrapscan!", "wrapscan!",
"wrapscroll",
"nowrapscroll",
"wrapscroll!",
"findlen",
"period",
"scrolloff", "scrolloff",
"tabstop", "tabstop",
"errorfmt",
"filesep", "filesep",
"hiddenfiles",
"ifs", "ifs",
"info",
"previewer", "previewer",
"promptfmt", "promptfmt",
"ratios",
"shell", "shell",
"shellopts",
"sortby", "sortby",
"timefmt", "timefmt",
"ratios", "truncatechar",
"info",
} }
) )
@@ -108,13 +156,15 @@ func matchLongest(s1, s2 string) string {
func matchWord(s string, words []string) (matches []string, longest string) { func matchWord(s string, words []string) (matches []string, longest string) {
for _, w := range words { for _, w := range words {
if strings.HasPrefix(w, s) { if !strings.HasPrefix(w, s) {
matches = append(matches, w) continue
if longest != "" { }
longest = matchLongest(longest, w)
} else if s != "" { matches = append(matches, w)
longest = w + " " if longest != "" {
} longest = matchLongest(longest, w)
} else if s != "" {
longest = w + " "
} }
} }
@@ -128,32 +178,35 @@ func matchWord(s string, words []string) (matches []string, longest string) {
func matchExec(s string) (matches []string, longest string) { func matchExec(s string) (matches []string, longest string) {
var words []string var words []string
paths := strings.Split(envPath, ":") paths := strings.Split(envPath, string(filepath.ListSeparator))
for _, p := range paths { for _, p := range paths {
if _, err := os.Stat(p); os.IsNotExist(err) { if _, err := os.Stat(p); os.IsNotExist(err) {
continue continue
} }
fi, err := ioutil.ReadDir(p) files, err := ioutil.ReadDir(p)
if err != nil { if err != nil {
log.Printf("reading path: %s", err) log.Printf("reading path: %s", err)
} }
for _, f := range fi { for _, f := range files {
if strings.HasPrefix(f.Name(), s) { if !strings.HasPrefix(f.Name(), s) {
f, err = os.Stat(filepath.Join(p, f.Name())) continue
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
if !f.Mode().IsRegular() || f.Mode()&0111 == 0 {
continue
}
words = append(words, f.Name())
} }
f, err = os.Stat(filepath.Join(p, f.Name()))
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
if !f.Mode().IsRegular() || !isExecutable(f) {
continue
}
log.Print(f.Name())
words = append(words, f.Name())
} }
} }
@@ -173,24 +226,25 @@ 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()
if err != nil { if err != nil {
log.Printf("getting current directory: %s", err) log.Printf("getting current directory: %s", err)
} else {
dir = wd + string(filepath.Separator) + dir
} }
dir = wd + string(filepath.Separator) + dir
} }
dir = unescape(filepath.Dir(dir)) dir = unescape(filepath.Dir(dir))
fi, err := ioutil.ReadDir(dir) files, err := ioutil.ReadDir(dir)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} }
for _, f := range fi { for _, f := range files {
f, err := os.Stat(filepath.Join(dir, f.Name())) f, err := os.Stat(filepath.Join(dir, f.Name()))
if err != nil { if err != nil {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
@@ -198,25 +252,29 @@ func matchFile(s string) (matches []string, longest string) {
} }
_, last := filepath.Split(s) _, last := filepath.Split(s)
if strings.HasPrefix(escape(f.Name()), last) { if !strings.HasPrefix(escape(f.Name()), last) {
name := f.Name() continue
if isRoot(s) || filepath.Base(s) != s { }
name = filepath.Join(filepath.Dir(s), f.Name())
} name := f.Name()
name = escape(name) if isRoot(s) || filepath.Base(s) != s {
item := f.Name() name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
if f.Mode().IsDir() { }
item += string(filepath.Separator) name = escape(name)
}
matches = append(matches, item) item := f.Name()
if longest != "" { if f.Mode().IsDir() {
longest = matchLongest(longest, name) item += escape(string(filepath.Separator))
} else if s != "" { }
if f.Mode().IsRegular() { matches = append(matches, item)
longest = name + " "
} else { if longest != "" {
longest = name + string(filepath.Separator) longest = matchLongest(longest, name)
} } else if s != "" {
if f.Mode().IsRegular() {
longest = name + " "
} else {
longest = name + escape(string(filepath.Separator))
} }
} }
} }
@@ -228,7 +286,7 @@ func matchFile(s string) (matches []string, longest string) {
return return
} }
func compCmd(acc []rune) (matches []string, longestAcc []rune) { func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
@@ -241,6 +299,15 @@ func compCmd(acc []rune) (matches []string, longestAcc []rune) {
words = append(words, c) words = append(words, c)
} }
sort.Strings(words) sort.Strings(words)
j := 0
for i := 1; i < len(words); i++ {
if words[j] == words[i] {
continue
}
j++
words[i], words[j] = words[j], words[i]
}
words = words[:j+1]
matches, longest = matchWord(s, words) matches, longest = matchWord(s, words)
longestAcc = []rune(longest) longestAcc = []rune(longest)
case 2: case 2:
@@ -267,7 +334,45 @@ func compCmd(acc []rune) (matches []string, longestAcc []rune) {
return return
} }
func compShell(acc []rune) (matches []string, longestAcc []rune) { func completeFile(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
files, err := ioutil.ReadDir(wd)
if err != nil {
log.Printf("reading directory: %s", err)
}
var longest string
for _, f := range files {
if !strings.HasPrefix(f.Name(), s) {
continue
}
matches = append(matches, f.Name())
if longest != "" {
longest = matchLongest(longest, f.Name())
} else if s != "" {
longest = f.Name()
}
}
if longest == "" {
longest = s
}
longestAcc = []rune(longest)
return
}
func completeShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
@@ -279,7 +384,7 @@ func compShell(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
View File
File renamed without changes.
+128
View File
@@ -0,0 +1,128 @@
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
func copySize(srcs []string) (int64, error) {
var total int64
for _, src := range srcs {
_, err := os.Stat(src)
if os.IsNotExist(err) {
return total, fmt.Errorf("src does not exist: %q", src)
}
err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk: %s", err)
}
total += info.Size()
return nil
})
if err != nil {
return total, err
}
}
return total, nil
}
func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
buf := make([]byte, 4096)
r, err := os.Open(src)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return err
}
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
w.Close()
os.Remove(dst)
return err
}
if n == 0 {
break
}
if _, err := w.Write(buf[:n]); err != nil {
return err
}
nums <- int64(n)
}
if err := w.Close(); err != nil {
os.Remove(dst)
return err
}
if err := os.Chmod(dst, info.Mode()); err != nil {
os.Remove(dst)
return err
}
return nil
}
func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
nums = make(chan int64, 1024)
errs = make(chan error, 1024)
go func() {
for _, src := range srcs {
dst := filepath.Join(dstDir, filepath.Base(src))
_, err := os.Lstat(dst)
if !os.IsNotExist(err) {
var newPath string
for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i)
_, err = os.Lstat(newPath)
}
dst = newPath
}
filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
errs <- fmt.Errorf("walk: %s", err)
return nil
}
rel, err := filepath.Rel(src, path)
if err != nil {
errs <- fmt.Errorf("relative: %s", err)
return nil
}
newPath := filepath.Join(dst, rel)
if info.IsDir() {
if err := os.MkdirAll(newPath, info.Mode()); err != nil {
errs <- fmt.Errorf("mkdir: %s", err)
}
nums <- info.Size()
} else {
if err := copyFile(path, newPath, info, nums); err != nil {
errs <- fmt.Errorf("copy: %s", err)
}
}
return nil
})
}
close(errs)
}()
return nums, errs
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"strconv"
"unicode"
)
var normMap map[rune]rune
func init() {
normMap = make(map[rune]rune)
// (not only) european
appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
)
// Vietnamese
appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
)
}
func appendTransliterate(base, norm string) {
normRunes := []rune(norm)
baseRunes := []rune(base)
lenNorm := len(normRunes)
lenBase := len(baseRunes)
if lenNorm != lenBase {
panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length
}
for i := 0; i < lenBase; i++ {
normMap[baseRunes[i]] = normRunes[i]
baseUpper := unicode.ToUpper(baseRunes[i])
normUpper := unicode.ToUpper(normRunes[i])
normMap[baseUpper] = normUpper
}
}
// Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string {
var normalizedRunes []rune
for _, baseRune := range baseString {
if normRune, ok := normMap[baseRune]; ok {
normalizedRunes = append(normalizedRunes, normRune)
} else {
normalizedRunes = append(normalizedRunes, baseRune)
}
}
return string(normalizedRunes)
}
+72
View File
@@ -0,0 +1,72 @@
package main
import (
"strconv"
"testing"
)
// typical czech test sentence ;-)
const baseTestString = "Příliš žluťoučký kůň příšerně úpěl ďábelské ódy"
func TestRemoveDiacritics(t *testing.T) {
testStr := baseTestString
expStr := "Prilis zlutoucky kun priserne upel dabelske ody"
checkRemoveDiacritics(testStr, expStr, t)
// other accents (non comlete, but all I founded)
testStr = "áéíóúýčďěňřšťžůåøĉĝĥĵŝŭšžõäöüàâçéèêëîïôùûüÿžščćđáéíóúąęėįųūčšžāēīūčšžļķņģáéíóúöüőűäöüëïąćęłńóśźżáàãâçéêíóõôăâîșțáäčďéíĺľňóôŕšťúýžáéíñóúüåäöâçîşûğăâđêôơưáàãảạ"
expStr = "aeiouycdenrstzuaocghjsuszoaouaaceeeeiiouuuyzsccdaeiouaeeiuucszaeiucszlkngaeiouououaoueiacelnoszzaaaaceeioooaaistaacdeillnoorstuyzaeinouuaaoacisugaadeoouaaaaa"
checkRemoveDiacritics(testStr, expStr, t)
testStr = "ÁÉÍÓÚÝČĎĚŇŘŠŤŽŮÅØĈĜĤĴŜŬŠŽÕÄÖÜÀÂÇÉÈÊËÎÏÔÙÛÜŸŽŠČĆĐÁÉÍÓÚĄĘĖĮŲŪČŠŽĀĒĪŪČŠŽĻĶŅĢÁÉÍÓÚÖÜŐŰÄÖÜËÏĄĆĘŁŃÓŚŹŻÁÀÃÂÇÉÊÍÓÕÔĂÂÎȘȚÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽÁÉÍÑÓÚÜÅÄÖÂÇÎŞÛĞĂÂĐÊÔƠƯÁÀÃẢẠ"
expStr = "AEIOUYCDENRSTZUAOCGHJSUSZOAOUAACEEEEIIOUUUYZSCCDAEIOUAEEIUUCSZAEIUCSZLKNGAEIOUOUOUAOUEIACELNOSZZAAAACEEIOOOAAISTAACDEILLNOORSTUYZAEINOUUAAOACISUGAADEOOUAAAAA"
checkRemoveDiacritics(testStr, expStr, t)
testStr = "áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ"
expStr = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd"
checkRemoveDiacritics(testStr, expStr, t)
testStr = "ÁẠÀẢÃĂẮẶẰẲẴÂẤẬẦẨẪÉẸÈẺẼÊẾỆỀỂỄÍỊÌỈĨÓỌÒỎÕÔỐỘỒỔỖƠỚỢỜỞỠÚỤÙỦŨƯỨỰỪỬỮÝỴỲỶỸĐ"
expStr = "AAAAAAAAAAAAAAAAAEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYYD"
checkRemoveDiacritics(testStr, expStr, t)
}
func checkRemoveDiacritics(testStr string, expStr string, t *testing.T) {
resultStr := removeDiacritics(testStr)
if resultStr != expStr {
t.Errorf("at input '%v' expected '%v' but got '%v'", testStr, expStr, resultStr)
}
}
func TestSearchSettings(t *testing.T) {
runSearch(t, true, false, true, true, "Veřejný", "vere", true)
runSearch(t, true, false, true, false, baseTestString, "Zlutoucky", true)
runSearch(t, true, false, true, false, baseTestString, "zlutoucky", true)
runSearch(t, true, true, true, false, baseTestString, "Zlutoucky", false)
runSearch(t, true, true, true, true, baseTestString, "zlutoucky", true)
runSearch(t, false, false, true, false, baseTestString, "žlutoucky", true)
runSearch(t, false, false, true, false, baseTestString, "Žlutoucky", false)
runSearch(t, false, false, true, true, baseTestString, "žluťoučký", true)
runSearch(t, false, false, true, false, baseTestString, "žluťoučký", true)
runSearch(t, false, false, false, false, baseTestString, "žluťoučký", true)
runSearch(t, false, false, false, false, baseTestString, "zlutoucky", false)
runSearch(t, false, false, true, true, baseTestString, "zlutoucky", true)
}
func runSearch(t *testing.T, ignorecase, smartcase, ignorediacritics, smartdiacritics bool, base, pattern string, expected bool) {
gOpts.ignorecase = ignorecase
gOpts.smartcase = smartcase
gOpts.ignoredia = ignorediacritics
gOpts.smartdia = smartdiacritics
matched, _ := searchMatch(base, pattern)
if matched != expected {
t.Errorf("False search for" +
" ignorecase = " + strconv.FormatBool(gOpts.ignorecase) + ", " +
" smartcase = " + strconv.FormatBool(gOpts.smartcase) + ", " +
" ignoredia = " + strconv.FormatBool(gOpts.ignoredia) + ", " +
" smartdia = " + strconv.FormatBool(gOpts.smartdia) + ", ")
}
}
+369 -146
View File
@@ -1,4 +1,5 @@
//go:generate gen/docstring.sh //go:generate gen/docstring.sh
//go:generate gen/man.sh
/* /*
lf is a terminal file manager. lf is a terminal file manager.
@@ -6,103 +7,164 @@ lf is a terminal file manager.
Source code can be found in the repository at https://github.com/gokcehan/lf. 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 This documentation can either be read from terminal using 'lf -doc' or online
at https://godoc.org/github.com/gokcehan/lf. 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.
You can run 'lf -help' to see descriptions of command line options.
Reference Reference
The following commands are provided by lf with default keybindings: The following commands are provided by lf with default keybindings:
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>') page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>') down (default 'j' and '<down>')
half-down (default '<c-d>') half-down (default '<c-d>')
page-down (default '<c-f>') 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') quit (default 'q')
top (default 'gg') top (default 'gg' and '<home>')
bot (default 'G') bottom (default 'G' and '<end>')
toggle (default '<space>') invert (default 'v')
invert (default 'v') unselect (default 'u')
unmark (default 'u') copy (default 'y')
yank (default 'y') cut (default 'd')
delete (default 'd') paste (default 'p')
put (default 'p') clear (default 'c')
clear (default 'c') redraw (default '<c-l>')
redraw (default '<c-l>') reload (default '<c-r>')
reload (default '<c-r>') read (default ':')
read (default ':') rename (default 'r')
shell (default '$') shell (default '$')
shell-pipe (default '%') shell-pipe (default '%')
shell-wait (default '!') shell-wait (default '!')
shell-async (default '&') shell-async (default '&')
search (default '/') find (default 'f')
search-back (default '?') find-back (default 'F')
search-next (default 'n') find-next (default ';')
search-prev (default 'N') find-prev (default ',')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default `"`)
The following commands are provided by lf without default keybindings: The following commands are provided by lf without default keybindings:
draw draw the ui draw draw the ui
sync synchronizes yanked/deleted files with server load load modified files and directories
echo prints its arguments to the message line sync synchronize copied/cut files with server
cd changes working directory to its argument echo print arguments to the message line
select changes current file selection to its argument echomsg same as echo but logging
push simulate key pushes given in its argument echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
toggle toggle the selection of the current file or its arguments
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
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 The following command line commands are provided by lf with default
keybindings: keybindings:
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-comp (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-hist-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-hist-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>') 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-beg (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-beg (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-put (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
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:
dircounts boolean (default off) anchorfind boolean (default on)
dirfirst boolean (default on) color256 boolean (default off)
drawbox boolean (default off) dircounts boolean (default off)
globsearch boolean (default off) dirfirst boolean (default on)
hidden boolean (default off) drawbox boolean (default off)
ignorecase boolean (default on) globsearch boolean (default off)
preview boolean (default on) hidden boolean (default off)
reverse boolean (default off) icons boolean (default off)
smartcase boolean (default on) ignorecase boolean (default on)
wrapscan boolean (default on) ignoredia boolean (default off)
scrolloff integer (default 0) incsearch boolean (default off)
tabstop integer (default 8) number boolean (default off)
filesep string (default "\n") preview boolean (default on)
ifs string (default '') (not exported if empty) relativenumber boolean (default off)
previewer string (default '') (not filtered if empty) reverse boolean (default off)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m") smartcase boolean (default on)
shell string (default 'sh') smartdia boolean (default off)
sortby string (default 'natural') wrapscan boolean (default on)
timefmt string (default 'Mon Jan _2 15:04:05 2006') wrapscroll boolean (default off)
ratios string (default '1:2:3') findlen integer (default 1) (zero to prompt until single match)
info string (default '') period integer (default 0) (zero to disable periodic loading)
scrolloff integer (default 0)
tabstop integer (default 8)
errorfmt string (default "\033[7;31;47m%s\033[0m")
filesep string (default "\n")
hiddenfiles string (default '.*')
ifs string (default '') (not exported if empty)
info string (default '')
previewer string (default '') (not filtered if empty)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
ratios string (default '1:2:3')
shell string (default 'sh')
shellopts string (default '')
sortby string (default 'natural')
timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~')
The following variables are exported for shell commands: The following variables are exported for shell commands:
$f current file $f current file
$fs marked file(s) separated with 'filesep' $fs selected file(s) separated with 'filesep'
$fx current file or marked file(s) if any $fx current file or selected file(s) if any
$id id number of the client $id id number of the client
The following variables are set to the corresponding values:
$LF_LEVEL current nesting level
The following default values are set to the environmental variables on unix
when they are not set or empty:
$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:
map zh set hidden! map zh set hidden!
@@ -114,30 +176,43 @@ 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 on unix: The following keybindings to applications are provided by default:
map e $$EDITOR $f ('vi' if empty) map e $$EDITOR $f
map i $$PAGER $f ('less' if empty) map i $$PAGER $f
map w $$SHELL ('sh' if empty) map w $$SHELL
The following keybindings to applications are provided by default on windows:
map e $notepad "%f%"
map i $more "%f%"
map w $cmd
Configuration Configuration
The configuration file should be located at: Configuration files should be located at:
$XDG_CONFIG_HOME/lf/lfrc os system-wide user-specific
unix /etc/lf/lfrc ~/.config/lf/lfrc
windows C:\ProgramData\lf\lfrc C:\Users\<user>\AppData\Local\lf\lfrc
If '$XDG_CONFIG_HOME' is not set, it defaults to '$HOME/.config' so the Marks file should be located at:
location should be:
~/.config/lf/lfrc unix ~/.local/share/lf/marks
windows C:\Users\<user>\AppData\Local\lf\marks
History file should be located at:
unix ~/.local/share/lf/history
windows C:\Users\<user>\AppData\Local\lf\history
You can configure the default values of following variables to change these
locations:
$XDG_CONFIG_HOME ~/.config
$XDG_DATA_HOME ~/.local/share
%ProgramData% C:\ProgramData
%LOCALAPPDATA% C:\Users\<user>\AppData\Local
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.
@@ -151,13 +226,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. The The same evaluator is used for the command line and the configuration file for
difference is that prefixes are not necessary in the command line. Instead read and shell commands. The difference is that prefixes are not necessary in
different modes are provided to read corresponding commands. Note that by the command line. Instead, different modes are provided to read corresponding
default these modes are mapped to the prefix keys above. commands. These modes are mapped to the prefix keys above by default.
Syntax Syntax
@@ -168,7 +241,8 @@ Characters from '#' to newline are comments and ignored:
There are three special commands ('set', 'map', and 'cmd') and their variants There are three special commands ('set', 'map', and 'cmd') and their variants
for configuration. for configuration.
'set' is used to set an option which can be boolean, integer, or string: Command 'set' is used to set an option which can be boolean, integer, or
string:
set hidden # boolean on set hidden # boolean on
set nohidden # boolean off set nohidden # boolean off
@@ -178,16 +252,16 @@ for configuration.
set sortby 'time' # string value with single quotes (whitespaces) set sortby 'time' # string value with single quotes (whitespaces)
set sortby "time" # string value with double quotes (backslash escapes) set sortby "time" # string value with double quotes (backslash escapes)
'map' is used to bind a key to a command which can be builtin command, custom Command 'map' is used to bind a key to a command which can be builtin command,
command, or shell command: custom command, or shell command:
map gh cd ~ # builtin command map gh cd ~ # builtin command
map D trash # custom command map D trash # custom command
map i $less $f # shell command map i $less $f # shell command
map u !du -h . # waiting shell command map U !du -sh # waiting shell command
'cmap' is used to bind a key to a command line command which can only be one of Command 'cmap' is used to bind a key to a command line command which can only
the builtin commands: be one of the builtin commands:
cmap <c-g> cmd-escape cmap <c-g> cmd-escape
@@ -196,9 +270,9 @@ You can delete an existing binding by leaving the expression empty:
map gh # deletes 'gh' mapping map gh # deletes 'gh' mapping
cmap <c-g> # deletes '<c-g>' mapping cmap <c-g> # deletes '<c-g>' mapping
'cmd' is used to define a custom command Command 'cmd' is used to define a custom command:
cmd usage $du -h . | less cmd usage $du -h -d1 | less
You can delete an existing command by leaving the expression empty: You can delete an existing command by leaving the expression empty:
@@ -221,6 +295,53 @@ prefix.
set info time set info time
}} }}
Key Mappings
Regular keys are assigned to a command with the usual syntax:
map a down
Keys combined with the shift key simply use the uppercase letter:
map A down
Special keys are written in between '<' and '>' characters and always use
lowercase letters:
map <enter> down
Angle brackets can be assigned with their special names:
map <lt> down
map <gt> down
Function keys are prefixed with 'f' character:
map <f-1> down
Keys combined with the control key are prefixed with 'c' character:
map <c-a> down
Keys combined with the alt key are assigned in two different ways depending on
the behavior of your terminal. Older terminals (e.g. xterm) may set the 8th bit
of a character when the alt key is pressed. On these terminals, you can use the
corresponding byte for the mapping:
map á down
Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key
when the alt key is pressed. lf uses the escape delaying mechanism to recognize
alt keys in these terminals (delay is 100ms). On these terminals, keys combined
with the alt key are prefixed with 'a' character:
map <a-a> down
Please note that, some key combinations are not possible due to the way
terminals work (e.g. control and h combination sends a backspace key instead).
The easiest way to find the name of a key combination is to press the key while
lf is running and read the name of the key from the unknown mapping error.
Push Mappings Push Mappings
The usual way to map a key sequence is to assign it to a named or unnamed The usual way to map a key sequence is to assign it to a named or unnamed
@@ -261,7 +382,7 @@ trash. A first attempt to write such a command may look like this:
fi fi
}} }}
We check '$fs' to see if there are any marked files. Otherwise we just delete We check '$fs' to see if there are any selected files. Otherwise we just delete
the current file. Since this is such a common pattern, a separate '$fx' the current file. Since this is such a common pattern, a separate '$fx'
variable is provided. We can use this variable to get rid of the conditional: variable is provided. We can use this variable to get rid of the conditional:
@@ -370,7 +491,7 @@ Since lf does not have control flow syntax, remote commands are used for such
needs. For example, you can configure the number of columns in the ui with needs. For example, you can configure the number of columns in the ui with
respect to the terminal width as follows: respect to the terminal width as follows:
cmd recol ${{ cmd recol %{{
w=$(tput cols) w=$(tput cols)
if [ $w -le 80 ]; then if [ $w -le 80 ]; then
lf -remote "send $id set ratios 1:2" lf -remote "send $id set ratios 1:2"
@@ -390,84 +511,141 @@ Setting the file selection is done with 'save' command:
Getting the file selection is similarly done with 'load' command: Getting the file selection is similarly done with 'load' command:
resp=$(lf -remote 'load') load=$(lf -remote 'load')
mode=$(echo "$resp" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$resp" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
# do something with $list # do something with $list
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
# do something else with $list # do something else with $list
fi fi
There is a 'quit' command to close client connections and quit the server:
lf -remote 'quit'
Lastly, there is a 'conn' command to connect the server as a client. This Lastly, there is a 'conn' command to connect the server as a client. This
should not be needed for users. should not be needed for users.
File Operations File Operations
lf uses the underlying 'cp' and 'mv' shell commands for file operations. For lf uses its own builtin copy and move operations by default. These are
this purpose, when you 'yank' (i.e. copy) a file, it doesn't actually copy the implemented as asynchronous operations and progress is shown in the bottom
file on the disk, but only records its name to memory. The actual file ruler. These commands do not overwrite existing files or directories with the
operation takes place when you do the 'put' in which case the 'cp' command is same name. Instead, a suffix that is compatible with '--backup=numbered' option
used. Similarly the 'mv' command is used for 'delete' (i.e. cut or kill) in GNU cp is added to the new files or directories. Only file modes are
followed by 'put'. These traditional names (e.g. 'yank', 'delete', and 'put') preserved and all other attributes are ignored including ownership, timestamps,
are picked instead of the other common convention (e.g. copy and cut) to context, links, and xattr. Special files such as character and block devices,
resemble the default keybinds for these operations. 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.
You can customize these operations by defining a 'put' command. This is a File operations can be performed on the current selected file or alternatively
special command that is called when it is defined instead of the builtin on multiple files by selecting them first. When you 'copy' a file, lf doesn't
implementation. The default behavior is similar to the following command: 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.
cmd put ${{ You can customize copy and move operations by defining a 'paste' command. This
is a special command that is called when it is defined instead of the builtin
implementation. You can use the following example as a starting point:
cmd paste %{{
load=$(lf -remote 'load') load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
cp -R -n $list . cp -R $list .
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
mv -n $list . mv $list .
fi fi
lf -remote "send $id reload" lf -remote 'send load'
lf -remote "$(printf 'save\nmove\n\n')" lf -remote 'send clear'
lf -remote "send sync"
}} }}
Some useful things are to use the backup option ('--backup') with 'cp' and 'mv' Some useful things to be considered are to use the backup ('--backup') and/or
commands if they support it (i.e. GNU implementation), change the command type preserve attributes ('-a') options with 'cp' and 'mv' commands if they support
to asynchronous, or use 'rsync' command with progress bar option for copying it (i.e. GNU implementation), change the command type to asynchronous, or use
and feed the progress to the client periodically with remote 'echo' calls. 'rsync' command with progress bar option for copying and feed the progress to
the client periodically with remote 'echo' calls.
By default, lf does not provide an actual file deletion command to protect new By default, lf does not assign 'delete' command to a key to protect new users.
users. You can define such a command and optionally assign a key if you like. You can customize file deletion by defining a 'delete' command. You can also
An example command to move selected files to a trash folder and remove files assign a key to this command if you like. An example command to move selected
completely are provided in the example configuration file. files to a trash folder and remove files completely after a prompt are provided
in the example configuration file.
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.
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:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
','). 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.
Some options effect both searching and finding. You can disable 'wrapscan'
option to prevent searches to wrap around at the end of the file list. You can
disable 'ignorecase' option to match cases in the pattern and the filename.
This option is already automatically overridden if the pattern contains upper
case characters. You can disable 'smartcase' option to disable this behavior.
Two similar options 'ignoredia' and 'smartdia' are provided to control matching
diacritics in latin letters.
Opening Files Opening Files
You can use 'open-file' command to open a file. This is a special command You can define a an 'open' command (default 'l' and '<right>') to configure
called by 'open' when the current file is not a directory. Normally a user maps file opening. This command is only called when the current file is not a
the 'open' command to a key (default 'l') and customize 'open-file' command as directory, otherwise the directory is entered instead. You can define it just
desired. You can define it just as you would define any other command: as you would define any other command:
cmd open-file $vi $fx cmd open $vi $fx
It is possible to use different command types: It is possible to use different command types:
cmd open-file &xdg-open $f cmd open &xdg-open $f
You may want to use either file extensions or mime types from 'file' command: You may want to use either file extensions or mime types from 'file' command:
cmd open-file ${{ cmd open ${{
case $(file --mime-type $f -b) in case $(file --mime-type $f -b) in
text/*) vi $fx;; text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac esac
}} }}
Following commands are provided by default: You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
cmd open-file &start "" "%f%" # windows Following command is provided by default:
cmd open-file &open "$f" # mac
cmd open-file &xdg-open "$f" # others cmd open &$OPENER $f
You may also use any other existing file openers as you like. Possible options You may also use any other existing file openers as you like. Possible options
are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's
@@ -517,6 +695,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,
@@ -534,6 +745,13 @@ 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
color escapes (e.g. '\033[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.
'\033[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.
Keeping this mechanism in mind, you can configure lf colors in two different 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 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 pick up those colors automatically. Depending on your terminal, you
@@ -546,5 +764,10 @@ 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 can be used even when GNU programs are not installed on the system. You can 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. combine this second method with the first method for best results.
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.
*/ */
package main package main
+378 -150
View File
@@ -1,4 +1,4 @@
// DO NOT EDIT! (AUTO-GENERATED) // Code generated by gen/docstring.sh DO NOT EDIT.
package main package main
@@ -9,104 +9,165 @@ Source code can be found in the repository at
https://github.com/gokcehan/lf. https://github.com/gokcehan/lf.
This documentation can either be read from terminal using 'lf -doc' or This documentation can either be read from terminal using 'lf -doc' or
online at https://godoc.org/github.com/gokcehan/lf. 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.
You can run 'lf -help' to see descriptions of command line options.
Reference Reference
The following commands are provided by lf with default keybindings: The following commands are provided by lf with default keybindings:
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>') page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>') down (default 'j' and '<down>')
half-down (default '<c-d>') half-down (default '<c-d>')
page-down (default '<c-f>') 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') quit (default 'q')
top (default 'gg') top (default 'gg' and '<home>')
bot (default 'G') bottom (default 'G' and '<end>')
toggle (default '<space>') invert (default 'v')
invert (default 'v') unselect (default 'u')
unmark (default 'u') copy (default 'y')
yank (default 'y') cut (default 'd')
delete (default 'd') paste (default 'p')
put (default 'p') clear (default 'c')
clear (default 'c') redraw (default '<c-l>')
redraw (default '<c-l>') reload (default '<c-r>')
reload (default '<c-r>') read (default ':')
read (default ':') rename (default 'r')
shell (default '$') shell (default '$')
shell-pipe (default '%') shell-pipe (default '%')
shell-wait (default '!') shell-wait (default '!')
shell-async (default '&') shell-async (default '&')
search (default '/') find (default 'f')
search-back (default '?') find-back (default 'F')
search-next (default 'n') find-next (default ';')
search-prev (default 'N') find-prev (default ',')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default '"')
The following commands are provided by lf without default keybindings: The following commands are provided by lf without default keybindings:
draw draw the ui draw draw the ui
sync synchronizes yanked/deleted files with server load load modified files and directories
echo prints its arguments to the message line sync synchronize copied/cut files with server
cd changes working directory to its argument echo print arguments to the message line
select changes current file selection to its argument echomsg same as echo but logging
push simulate key pushes given in its argument echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
toggle toggle the selection of the current file or its arguments
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
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 The following command line commands are provided by lf with default
keybindings: keybindings:
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-comp (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-hist-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-hist-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>') 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-beg (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-beg (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-put (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
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:
dircounts boolean (default off) anchorfind boolean (default on)
dirfirst boolean (default on) color256 boolean (default off)
drawbox boolean (default off) dircounts boolean (default off)
globsearch boolean (default off) dirfirst boolean (default on)
hidden boolean (default off) drawbox boolean (default off)
ignorecase boolean (default on) globsearch boolean (default off)
preview boolean (default on) hidden boolean (default off)
reverse boolean (default off) icons boolean (default off)
smartcase boolean (default on) ignorecase boolean (default on)
wrapscan boolean (default on) ignoredia boolean (default off)
scrolloff integer (default 0) incsearch boolean (default off)
tabstop integer (default 8) number boolean (default off)
filesep string (default "\n") preview boolean (default on)
ifs string (default '') (not exported if empty) relativenumber boolean (default off)
previewer string (default '') (not filtered if empty) reverse boolean (default off)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m") smartcase boolean (default on)
shell string (default 'sh') smartdia boolean (default off)
sortby string (default 'natural') wrapscan boolean (default on)
timefmt string (default 'Mon Jan _2 15:04:05 2006') wrapscroll boolean (default off)
ratios string (default '1:2:3') findlen integer (default 1) (zero to prompt until single match)
info string (default '') period integer (default 0) (zero to disable periodic loading)
scrolloff integer (default 0)
tabstop integer (default 8)
errorfmt string (default "\033[7;31;47m%s\033[0m")
filesep string (default "\n")
hiddenfiles string (default '.*')
ifs string (default '') (not exported if empty)
info string (default '')
previewer string (default '') (not filtered if empty)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
ratios string (default '1:2:3')
shell string (default 'sh')
shellopts string (default '')
sortby string (default 'natural')
timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~')
The following variables are exported for shell commands: The following variables are exported for shell commands:
$f current file $f current file
$fs marked file(s) separated with 'filesep' $fs selected file(s) separated with 'filesep'
$fx current file or marked file(s) if any $fx current file or selected file(s) if any
$id id number of the client $id id number of the client
The following variables are set to the corresponding values:
$LF_LEVEL current nesting level
The following default values are set to the environmental variables on unix
when they are not set or empty:
$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:
map zh set hidden! map zh set hidden!
@@ -118,32 +179,44 @@ 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 on unix: The following keybindings to applications are provided by default:
map e $$EDITOR $f ('vi' if empty) map e $$EDITOR $f
map i $$PAGER $f ('less' if empty) map i $$PAGER $f
map w $$SHELL ('sh' if empty) map w $$SHELL
The following keybindings to applications are provided by default on
windows:
map e $notepad "%f%"
map i $more "%f%"
map w $cmd
Configuration Configuration
The configuration file should be located at: Configuration files should be located at:
$XDG_CONFIG_HOME/lf/lfrc os system-wide user-specific
unix /etc/lf/lfrc ~/.config/lf/lfrc
windows C:\ProgramData\lf\lfrc C:\Users\<user>\AppData\Local\lf\lfrc
If '$XDG_CONFIG_HOME' is not set, it defaults to '$HOME/.config' so the Marks file should be located at:
location should be:
~/.config/lf/lfrc unix ~/.local/share/lf/marks
windows C:\Users\<user>\AppData\Local\lf\marks
History file should be located at:
unix ~/.local/share/lf/history
windows C:\Users\<user>\AppData\Local\lf\history
You can configure the default values of following variables to change these
locations:
$XDG_CONFIG_HOME ~/.config
$XDG_DATA_HOME ~/.local/share
%ProgramData% C:\ProgramData
%LOCALAPPDATA% C:\Users\<user>\AppData\Local
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.
@@ -158,13 +231,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
The difference is that prefixes are not necessary in the command line. for read and shell commands. The difference is that prefixes are not
Instead different modes are provided to read corresponding commands. Note necessary in the command line. Instead, different modes are provided to read
that by default these modes are mapped to the prefix keys above. corresponding commands. These modes are mapped to the prefix keys above by
default.
Syntax Syntax
@@ -176,7 +248,8 @@ Characters from '#' to newline are comments and ignored:
There are three special commands ('set', 'map', and 'cmd') and their There are three special commands ('set', 'map', and 'cmd') and their
variants for configuration. variants for configuration.
'set' is used to set an option which can be boolean, integer, or string: Command 'set' is used to set an option which can be boolean, integer, or
string:
set hidden # boolean on set hidden # boolean on
set nohidden # boolean off set nohidden # boolean off
@@ -186,16 +259,16 @@ variants for configuration.
set sortby 'time' # string value with single quotes (whitespaces) set sortby 'time' # string value with single quotes (whitespaces)
set sortby "time" # string value with double quotes (backslash escapes) set sortby "time" # string value with double quotes (backslash escapes)
'map' is used to bind a key to a command which can be builtin command, Command 'map' is used to bind a key to a command which can be builtin
custom command, or shell command: command, custom command, or shell command:
map gh cd ~ # builtin command map gh cd ~ # builtin command
map D trash # custom command map D trash # custom command
map i $less $f # shell command map i $less $f # shell command
map u !du -h . # waiting shell command map U !du -sh # waiting shell command
'cmap' is used to bind a key to a command line command which can only be one Command 'cmap' is used to bind a key to a command line command which can
of the builtin commands: only be one of the builtin commands:
cmap <c-g> cmd-escape cmap <c-g> cmd-escape
@@ -204,9 +277,9 @@ You can delete an existing binding by leaving the expression empty:
map gh # deletes 'gh' mapping map gh # deletes 'gh' mapping
cmap <c-g> # deletes '<c-g>' mapping cmap <c-g> # deletes '<c-g>' mapping
'cmd' is used to define a custom command Command 'cmd' is used to define a custom command:
cmd usage $du -h . | less cmd usage $du -h -d1 | less
You can delete an existing command by leaving the expression empty: You can delete an existing command by leaving the expression empty:
@@ -230,6 +303,55 @@ proper prefix.
}} }}
Key Mappings
Regular keys are assigned to a command with the usual syntax:
map a down
Keys combined with the shift key simply use the uppercase letter:
map A down
Special keys are written in between '<' and '>' characters and always use
lowercase letters:
map <enter> down
Angle brackets can be assigned with their special names:
map <lt> down
map <gt> down
Function keys are prefixed with 'f' character:
map <f-1> down
Keys combined with the control key are prefixed with 'c' character:
map <c-a> down
Keys combined with the alt key are assigned in two different ways depending
on the behavior of your terminal. Older terminals (e.g. xterm) may set the
8th bit of a character when the alt key is pressed. On these terminals, you
can use the corresponding byte for the mapping:
map á down
Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key
when the alt key is pressed. lf uses the escape delaying mechanism to
recognize alt keys in these terminals (delay is 100ms). On these terminals,
keys combined with the alt key are prefixed with 'a' character:
map <a-a> down
Please note that, some key combinations are not possible due to the way
terminals work (e.g. control and h combination sends a backspace key
instead). The easiest way to find the name of a key combination is to press
the key while lf is running and read the name of the key from the unknown
mapping error.
Push Mappings Push Mappings
The usual way to map a key sequence is to assign it to a named or unnamed The usual way to map a key sequence is to assign it to a named or unnamed
@@ -273,7 +395,7 @@ this:
fi fi
}} }}
We check '$fs' to see if there are any marked files. Otherwise we just We check '$fs' to see if there are any selected files. Otherwise we just
delete the current file. Since this is such a common pattern, a separate delete the current file. Since this is such a common pattern, a separate
'$fx' variable is provided. We can use this variable to get rid of the '$fx' variable is provided. We can use this variable to get rid of the
conditional: conditional:
@@ -391,7 +513,7 @@ Since lf does not have control flow syntax, remote commands are used for
such needs. For example, you can configure the number of columns in the ui such needs. For example, you can configure the number of columns in the ui
with respect to the terminal width as follows: with respect to the terminal width as follows:
cmd recol ${{ cmd recol %{{
w=$(tput cols) w=$(tput cols)
if [ $w -le 80 ]; then if [ $w -le 80 ]; then
lf -remote "send $id set ratios 1:2" lf -remote "send $id set ratios 1:2"
@@ -411,89 +533,147 @@ newline character. Setting the file selection is done with 'save' command:
Getting the file selection is similarly done with 'load' command: Getting the file selection is similarly done with 'load' command:
resp=$(lf -remote 'load') load=$(lf -remote 'load')
mode=$(echo "$resp" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$resp" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
# do something with $list # do something with $list
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
# do something else with $list # do something else with $list
fi fi
There is a 'quit' command to close client connections and quit the server:
lf -remote 'quit'
Lastly, there is a 'conn' command to connect the server as a client. This Lastly, there is a 'conn' command to connect the server as a client. This
should not be needed for users. should not be needed for users.
File Operations File Operations
lf uses the underlying 'cp' and 'mv' shell commands for file operations. For lf uses its own builtin copy and move operations by default. These are
this purpose, when you 'yank' (i.e. copy) a file, it doesn't actually copy implemented as asynchronous operations and progress is shown in the bottom
the file on the disk, but only records its name to memory. The actual file ruler. These commands do not overwrite existing files or directories with
operation takes place when you do the 'put' in which case the 'cp' command the same name. Instead, a suffix that is compatible with '--backup=numbered'
is used. Similarly the 'mv' command is used for 'delete' (i.e. cut or kill) option in GNU cp is added to the new files or directories. Only file modes
followed by 'put'. These traditional names (e.g. 'yank', 'delete', and are preserved and all other attributes are ignored including ownership,
'put') are picked instead of the other common convention (e.g. copy and cut) timestamps, context, links, and xattr. Special files such as character and
to resemble the default keybinds for these operations. 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.
You can customize these operations by defining a 'put' command. This is a File operations can be performed on the current selected file or
special command that is called when it is defined instead of the builtin alternatively on multiple files by selecting them first. When you 'copy' a
implementation. The default behavior is similar to the following command: 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.
cmd put ${{ You can customize copy and move operations by defining a 'paste' command.
This is a special command that is called when it is defined instead of the
builtin implementation. You can use the following example as a starting
point:
cmd paste %{{
load=$(lf -remote 'load') load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
cp -R -n $list . cp -R $list .
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
mv -n $list . mv $list .
fi fi
lf -remote "send $id reload" lf -remote 'send load'
lf -remote "$(printf 'save\nmove\n\n')" lf -remote 'send clear'
lf -remote "send sync"
}} }}
Some useful things are to use the backup option ('--backup') with 'cp' and Some useful things to be considered are to use the backup ('--backup')
'mv' commands if they support it (i.e. GNU implementation), change the and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if
command type to asynchronous, or use 'rsync' command with progress bar they support it (i.e. GNU implementation), change the command type to
option for copying and feed the progress to the client periodically with asynchronous, or use 'rsync' command with progress bar option for copying
remote 'echo' calls. and feed the progress to the client periodically with remote 'echo' calls.
By default, lf does not provide an actual file deletion command to protect By default, lf does not assign 'delete' command to a key to protect new
new users. You can define such a command and optionally assign a key if you users. You can customize file deletion by defining a 'delete' command. You
like. An example command to move selected files to a trash folder and remove can also assign a key to this command if you like. An example command to
files completely are provided in the example configuration file. move selected files to a trash folder and remove files completely after a
prompt are provided in the example configuration file.
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.
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:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
','). 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.
Some options effect both searching and finding. You can disable 'wrapscan'
option to prevent searches to wrap around at the end of the file list. You
can disable 'ignorecase' option to match cases in the pattern and the
filename. This option is already automatically overridden if the pattern
contains upper case characters. You can disable 'smartcase' option to
disable this behavior. Two similar options 'ignoredia' and 'smartdia' are
provided to control matching diacritics in latin letters.
Opening Files Opening Files
You can use 'open-file' command to open a file. This is a special command You can define a an 'open' command (default 'l' and '<right>') to configure
called by 'open' when the current file is not a directory. Normally a user file opening. This command is only called when the current file is not a
maps the 'open' command to a key (default 'l') and customize 'open-file' directory, otherwise the directory is entered instead. You can define it
command as desired. You can define it just as you would define any other just as you would define any other command:
command:
cmd open-file $vi $fx cmd open $vi $fx
It is possible to use different command types: It is possible to use different command types:
cmd open-file &xdg-open $f cmd open &xdg-open $f
You may want to use either file extensions or mime types from 'file' You may want to use either file extensions or mime types from 'file'
command: command:
cmd open-file ${{ cmd open ${{
case $(file --mime-type $f -b) in case $(file --mime-type $f -b) in
text/*) vi $fx;; text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac esac
}} }}
Following commands are provided by default: You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
cmd open-file &start "" "%f%" # windows Following command is provided by default:
cmd open-file &open "$f" # mac
cmd open-file &xdg-open "$f" # others cmd open &$OPENER $f
You may also use any other existing file openers as you like. Possible You may also use any other existing file openers as you like. Possible
options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle'
@@ -546,6 +726,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,
@@ -565,6 +780,13 @@ 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
3-bit color escapes (e.g. '\033[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. '\033[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.
Keeping this mechanism in mind, you can configure lf colors in two different 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 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 pick up those colors automatically. Depending on your terminal, you
@@ -578,4 +800,10 @@ 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.
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.
` `
+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})/"
+18
View File
@@ -0,0 +1,18 @@
# Autocompletion for fish shell.
#
# You may put this file to a directory in $fish_complete_path variable:
#
# mkdir -p ~/.config/fish/completions
# ln -s "/path/to/lf.fish" ~/.config/fish/completions
#
complete -c lf -o command -r -d 'command to execute on client initialization'
complete -c lf -o cpuprofile -r -d 'path to the file to write the CPU profile'
complete -c lf -o doc -d 'show documentation'
complete -c lf -o last-dir-path -r -d 'path to the file to write the last dir on exit (to use for cd)'
complete -c lf -o memprofile -r -d 'path to the file to write the memory profile'
complete -c lf -o remote -x -d 'send remote command to server'
complete -c lf -o selection-path -r -d 'path to the file to write selected files on open (to use as open file dialog)'
complete -c lf -o server -d 'start server (automatic)'
complete -c lf -o version -d 'show version'
complete -c lf -o help -d 'show help'
+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 "$_"'
+46 -24
View File
@@ -1,6 +1,15 @@
# interpreter for shell commands (needs to be POSIX compatible) # interpreter for shell commands (needs to be POSIX compatible)
set shell sh set shell sh
# set '-eu' options for shell commands
# These options are used to have safer shell commands. Option '-e' is used to
# exit on error and option '-u' is used to give error for unset variables.
# Option '-f' disables pathname expansion which can be useful when $f, $fs, and
# $fx variables contain names with '*' or '?' characters. However, this option
# is used selectively within individual commands as it can be limiting at
# times.
set shellopts '-eu'
# set internal field separator (IFS) to "\n" for shell commands # set internal field separator (IFS) to "\n" for shell commands
# This is useful to automatically split file names in $fs and $fx properly # This is useful to automatically split file names in $fs and $fx properly
# since default file separator used in these variables (i.e. 'filesep' option) # since default file separator used in these variables (i.e. 'filesep' option)
@@ -22,42 +31,45 @@ map X !$f
map o &mimeopen $f map o &mimeopen $f
map O $mimeopen --ask $f map O $mimeopen --ask $f
# show documentation (overrides 'search-back' command) # define a custom 'open' command
map ? $lf -doc | less # This command is called when current file is not a directory. You may want to
# use either file extensions and/or mime types here. Below uses an editor for
# define a custom 'open-file' command # text files and a file opener for the rest.
# 'open-file' is called by 'open' when current file is not a directory. You may cmd open ${{
# want to use either file extensions and/or mime types here. Below uses an
# editor for text files and a file opener for the rest.
cmd open-file ${{
case $(file --mime-type $f -b) in case $(file --mime-type $f -b) in
text/*) vi $fx;; text/*) $EDITOR $fx;;
*) for f in $fx; do xdg-open $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
# move current file or selected files to trash folder # move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options) # (also see 'man mv' for backup/overwrite options)
cmd trash %mv $fx ~/.trash cmd trash %set -f; mv $fx ~/.trash
# remove current file or selected files (prompting) # define a custom 'delete' command
cmd remove ${{ # cmd delete ${{
printf "$fx\n" # set -f
printf "remove?[y/n]" # printf "$fx\n"
read ans # printf "delete?[y/n]"
[ $ans = "y" ] && rm -rf $fx # read ans
}} # [ $ans = "y" ] && rm -rf $fx
# }}
# use '<delete>' key for either 'trash' or 'delete' command
# map <delete> trash
# map <delete> delete
# extract the current file with the right command # extract the current file with the right command
# (xkcd link: https://xkcd.com/1168/) # (xkcd link: https://xkcd.com/1168/)
cmd extract %{{ cmd extract ${{
set -f
case $f in case $f in
*.tar.bz|*.tar.bz2|*.tbz|*.tbz2) tar xjvf $f;; *.tar.bz|*.tar.bz2|*.tbz|*.tbz2) tar xjvf $f;;
*.tar.gz|*.tgz) tar xzvf $f;; *.tar.gz|*.tgz) tar xzvf $f;;
@@ -69,9 +81,19 @@ cmd extract %{{
}} }}
# compress current file or selected files with tar and gunzip # compress current file or selected files with tar and gunzip
cmd compress %{{ cmd tar ${{
set -f
mkdir $1 mkdir $1
cp -r $fx $1 cp -r $fx $1
tar czf $1.tar.gz $1 tar czf $1.tar.gz $1
rm -rf $1 rm -rf $1
}} }}
# compress current file or selected files with zip
cmd zip ${{
set -f
mkdir $1
cp -r $fx $1
zip -r $1.zip $1
rm -rf $1
}}
+976 -184
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},
}}, }},
}, },
Executable
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Builds a static stripped binary with version information.
#
# This script is used to build a binary for the current platform. Cgo is
# disabled to make sure the binary is statically linked. Appropriate flags are
# given to the go compiler to strip the binary. Current git tag is passed to
# the compiler by default to be used as the version in the binary.
[ -z $version ] && version=$(git describe --tags)
CGO_ENABLED=0 go build -ldflags="-s -w -X main.gVersion=$version" "$@"
+7 -7
View File
@@ -8,12 +8,12 @@
tmp=gen/docstring.go tmp=gen/docstring.go
echo "// DO NOT EDIT! (AUTO-GENERATED)" >> $tmp echo "// Code generated by gen/docstring.sh DO NOT EDIT." >> $tmp
echo >> $tmp echo >> $tmp
echo "package main" >> $tmp echo "package main" >> $tmp
echo >> $tmp echo >> $tmp
echo "var genDocString = \`" >> $tmp echo "var genDocString = \`" >> $tmp
go doc | tr "\`" "'" >> $tmp go doc | tr "\`" "'" >> $tmp
echo "\`" >> $tmp echo "\`" >> $tmp
mv $tmp docstring.go mv $tmp docstring.go
Executable
+69
View File
@@ -0,0 +1,69 @@
#!/bin/sh
# Generates `lf.1` man page using man macros with `go doc` output.
#
# This script is called in `doc.go` using `go generate` to generate a man page
# formatted with man macros from the documentation. A few additional sections
# such as `NAME` and `SYNOPSIS` are added to comply with man page conventions.
#
# Conversion logic implemented here from godoc output to man macros should not
# be considered compliant, as such it has inexact assumptions such as the use
# of spaces over tabs along with various corner cases that are not handled
# properly like character escaping. The intention here is to come up with
# something that can convert the current content in the documentation. For this
# reason, it is recommended to check the output after generation especially
# when the documentation is changed in a significant way.
out=lf.1
echo '.\" Code generated by gen/man.sh DO NOT EDIT.' > $out
cat << END >> $out
.TH LF 1
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
.SY lf
.OP \-cpuprofile path
.OP \-doc
.OP \-last-dir-path path
.OP \-memprofile path
.OP \-remote command
.OP \-selection-path path
.OP \-server
.OP \-version
.RI [ directory ]
.YS
.SH DESCRIPTION
END
go doc | awk '
BEGIN {
RS = ""
start = 1
}
# preformatted
/^ / {
gsub("\\\\", "\\e", $0)
print ".PP"
print ".EX"
print $0
print ".EE"
next
}
# heading
/^[^[:punct:]]*$/ {
print ".SH", toupper($0)
start = 1
next
}
# paragraph
{
gsub("\n", " ", $0)
gsub("\\\\", "\\e", $0)
if (start) { start = 0 } else { print ".PP" }
print $0
}
' >> $out
+5 -4
View File
@@ -3,13 +3,14 @@
# #
# This script is used to build binaries for all supported platforms. Cgo is # This script is used to build binaries for all supported platforms. Cgo is
# disabled to make sure binaries are statically linked. Appropriate flags are # disabled to make sure binaries are statically linked. Appropriate flags are
# given to the go compiler to strip binaries. These are then compressed in an # given to the go compiler to strip binaries. Current git tag is passed to the
# archive form (`.zip` for windows and `.tar.gz` for the rest) within a folder # compiler by default to be used as the version in binaries. These are then
# named `dist`. # compressed in an archive form (`.zip` for windows and `.tar.gz` for the rest)
# within a folder named `dist`.
set -o verbose set -o verbose
version=$(git describe --tags) [ -z $version ] && version=$(git describe --tags)
mkdir -p dist mkdir -p dist
+9
View File
@@ -0,0 +1,9 @@
module github.com/gokcehan/lf
go 1.12
require (
github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14
github.com/mattn/go-runewidth v0.0.9
gopkg.in/djherbis/times.v1 v1.2.0
)
+14
View File
@@ -0,0 +1,14 @@
github.com/doronbehar/termbox-go v0.0.0-20190817171036-93860e161317 h1:mdOm+1RdYwVwC4Wjb53M5L96fRwWJ8gI7YXwwiCsHTk=
github.com/doronbehar/termbox-go v0.0.0-20190817171036-93860e161317/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20191006140624-aa2cdd26fb8c h1:qvLYQAhDCaMq+XiQ+t4YLaTJtUyHC1r20odd6ryKYIk=
github.com/doronbehar/termbox-go v0.0.0-20191006140624-aa2cdd26fb8c/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05 h1:pmXx7j8+mmkFJB2+qoB1C/Mz8SWvMlHTxSWOptJrr7E=
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14 h1:KKPl27Vj3HRF384G7jW7K8uCRv0Ks+GuAOkGsz4qWAs=
github.com/doronbehar/termbox-go v0.0.0-20200711071547-71407e3bfa14/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
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 " "
}
+684
View File
@@ -0,0 +1,684 @@
.\" Code generated by gen/man.sh DO NOT EDIT.
.TH LF 1
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
.SY lf
.OP \-cpuprofile path
.OP \-doc
.OP \-last-dir-path path
.OP \-memprofile path
.OP \-remote command
.OP \-selection-path path
.OP \-server
.OP \-version
.RI [ directory ]
.YS
.SH DESCRIPTION
lf is a terminal file manager.
.PP
Source code can be found in the repository at https://github.com/gokcehan/lf.
.PP
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
You can run 'lf -help' to see descriptions of command line options.
.SH REFERENCE
The following commands are provided by lf with default keybindings:
.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>')
updir (default 'h' and '<left>')
open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
invert (default 'v')
unselect (default 'u')
copy (default 'y')
cut (default 'd')
paste (default 'p')
clear (default 'c')
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
rename (default 'r')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
shell-async (default '&')
find (default 'f')
find-back (default 'F')
find-next (default ';')
find-prev (default ',')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default `"`)
.EE
.PP
The following commands are provided by lf without default keybindings:
.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
toggle toggle the selection of the current file or its arguments
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
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
.EX
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>')
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-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
.EE
.PP
The following options can be used to customize the behavior of lf:
.PP
.EX
anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off)
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
hidden boolean (default off)
icons boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
incsearch boolean (default off)
number boolean (default off)
preview boolean (default on)
relativenumber boolean (default off)
reverse boolean (default off)
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
wrapscroll boolean (default off)
findlen integer (default 1) (zero to prompt until single match)
period integer (default 0) (zero to disable periodic loading)
scrolloff integer (default 0)
tabstop integer (default 8)
errorfmt string (default "\e033[7;31;47m%s\e033[0m")
filesep string (default "\en")
hiddenfiles string (default '.*')
ifs string (default '') (not exported if empty)
info string (default '')
previewer string (default '') (not filtered if empty)
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f\e033[0m")
ratios string (default '1:2:3')
shell string (default 'sh')
shellopts string (default '')
sortby string (default 'natural')
timefmt string (default 'Mon Jan _2 15:04:05 2006')
truncatechar string (default '~')
.EE
.PP
The following variables are exported for shell commands:
.PP
.EX
$f current file
$fs selected file(s) separated with 'filesep'
$fx current file or selected file(s) if any
$id id number of the client
.EE
.PP
The following variables are set to the corresponding values:
.PP
.EX
$LF_LEVEL current nesting level
.EE
.PP
The following default values are set to the environmental variables on unix when they are not set or empty:
.PP
.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
.PP
The following additional keybindings are provided by default:
.PP
.EX
map zh set hidden!
map zr set reverse!
map zn set info
map zs set info size
map zt set info time
map za set info size:time
map sn :set sortby natural; set info
map ss :set sortby size; set info size
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 <space> :toggle; down
.EE
.PP
The following keybindings to applications are provided by default:
.PP
.EX
map e $$EDITOR $f
map i $$PAGER $f
map w $$SHELL
.EE
.SH CONFIGURATION
Configuration files should be located at:
.PP
.EX
os system-wide user-specific
unix /etc/lf/lfrc ~/.config/lf/lfrc
windows C:\eProgramData\elf\elfrc C:\eUsers\e<user>\eAppData\eLocal\elf\elfrc
.EE
.PP
Marks file should be located at:
.PP
.EX
unix ~/.local/share/lf/marks
windows C:\eUsers\e<user>\eAppData\eLocal\elf\emarks
.EE
.PP
History file should be located at:
.PP
.EX
unix ~/.local/share/lf/history
windows C:\eUsers\e<user>\eAppData\eLocal\elf\ehistory
.EE
.PP
You can configure the default values of following variables to change these locations:
.PP
.EX
$XDG_CONFIG_HOME ~/.config
$XDG_DATA_HOME ~/.local/share
%ProgramData% C:\eProgramData
%LOCALAPPDATA% C:\eUsers\e<user>\eAppData\eLocal
.EE
.PP
A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example.
.SH PREFIXES
The following command prefixes are used by lf:
.PP
.EX
: read (default) builtin/custom command
$ shell shell command
% shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously
.EE
.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.
.SH SYNTAX
Characters from '#' to newline are comments and ignored:
.PP
.EX
# comments start with '#'
.EE
.PP
There are three special commands ('set', 'map', and 'cmd') and their variants for configuration.
.PP
Command 'set' is used to set an option which can be boolean, integer, or string:
.PP
.EX
set hidden # boolean on
set nohidden # boolean off
set hidden! # boolean toggle
set scrolloff 10 # integer value
set sortby time # string value w/o quotes
set sortby 'time' # string value with single quotes (whitespaces)
set sortby "time" # string value with double quotes (backslash escapes)
.EE
.PP
Command 'map' is used to bind a key to a command which can be builtin command, custom command, or shell command:
.PP
.EX
map gh cd ~ # builtin command
map D trash # custom command
map i $less $f # shell command
map U !du -sh # waiting shell command
.EE
.PP
Command 'cmap' is used to bind a key to a command line command which can only be one of the builtin commands:
.PP
.EX
cmap <c-g> cmd-escape
.EE
.PP
You can delete an existing binding by leaving the expression empty:
.PP
.EX
map gh # deletes 'gh' mapping
cmap <c-g> # deletes '<c-g>' mapping
.EE
.PP
Command 'cmd' is used to define a custom command:
.PP
.EX
cmd usage $du -h -d1 | less
.EE
.PP
You can delete an existing command by leaving the expression empty:
.PP
.EX
cmd trash # deletes 'trash' command
.EE
.PP
If there is no prefix then ':' is assumed:
.PP
.EX
map zt set info time
.EE
.PP
An explicit ':' can be provided to group statements until a newline which is especially useful for 'map' and 'cmd' commands:
.PP
.EX
map st :set sortby time; set info time
.EE
.PP
If you need multiline you can wrap statements in '{{' and '}}' after the proper prefix.
.PP
.EX
map st :{{
set sortby time
set info time
}}
.EE
.SH KEY MAPPINGS
Regular keys are assigned to a command with the usual syntax:
.PP
.EX
map a down
.EE
.PP
Keys combined with the shift key simply use the uppercase letter:
.PP
.EX
map A down
.EE
.PP
Special keys are written in between '<' and '>' characters and always use lowercase letters:
.PP
.EX
map <enter> down
.EE
.PP
Angle brackets can be assigned with their special names:
.PP
.EX
map <lt> down
map <gt> down
.EE
.PP
Function keys are prefixed with 'f' character:
.PP
.EX
map <f-1> down
.EE
.PP
Keys combined with the control key are prefixed with 'c' character:
.PP
.EX
map <c-a> down
.EE
.PP
Keys combined with the alt key are assigned in two different ways depending on the behavior of your terminal. Older terminals (e.g. xterm) may set the 8th bit of a character when the alt key is pressed. On these terminals, you can use the corresponding byte for the mapping:
.PP
.EX
map á down
.EE
.PP
Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key when the alt key is pressed. lf uses the escape delaying mechanism to recognize alt keys in these terminals (delay is 100ms). On these terminals, keys combined with the alt key are prefixed with 'a' character:
.PP
.EX
map <a-a> down
.EE
.PP
Please note that, some key combinations are not possible due to the way terminals work (e.g. control and h combination sends a backspace key instead). The easiest way to find the name of a key combination is to press the key while lf is running and read the name of the key from the unknown mapping error.
.SH PUSH MAPPINGS
The usual way to map a key sequence is to assign it to a named or unnamed command. While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times. For this reason 'push' command is provided by lf. This command is used to simulate key pushes given as its arguments. You can 'map' a key to a 'push' command with an argument to create various keybindings.
.PP
This is mainly useful for two purposes. First, it can be used to map a command with a command count:
.PP
.EX
map <c-j> push 10j
.EE
.PP
Second, it can be used to avoid typing the name when a command takes arguments:
.PP
.EX
map r push :rename<space>
.EE
.PP
One thing to be careful is that since 'push' command works with keys instead of commands it is possible to accidentally create recursive bindings:
.PP
.EX
map j push 2j
.EE
.PP
These types of bindings create a deadlock when executed.
.SH SHELL COMMANDS
Regular shell commands are the most basic command type that is useful for many purposes. For example, we can write a shell command to move selected file(s) to trash. A first attempt to write such a command may look like this:
.PP
.EX
cmd trash ${{
mkdir -p ~/.trash
if [ -z "$fs" ]; then
mv "$f" ~/.trash
else
IFS="`printf '\en\et'`"; mv $fs ~/.trash
fi
}}
.EE
.PP
We check '$fs' to see if there are any selected files. Otherwise we just delete the current file. Since this is such a common pattern, a separate '$fx' variable is provided. We can use this variable to get rid of the conditional:
.PP
.EX
cmd trash ${{
mkdir -p ~/.trash
IFS="`printf '\en\et'`"; mv $fx ~/.trash
}}
.EE
.PP
The trash directory is checked each time the command is executed. We can move it outside of the command so it would only run once at startup:
.PP
.EX
${{ mkdir -p ~/.trash }}
.EE
.PP
.EX
cmd trash ${{ IFS="`printf '\en\et'`"; mv $fx ~/.trash }}
.EE
.PP
Since these are one liners, we can drop '{{' and '}}':
.PP
.EX
$mkdir -p ~/.trash
.EE
.PP
.EX
cmd trash $IFS="`printf '\en\et'`"; mv $fx ~/.trash
.EE
.PP
Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\en"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation.
.SH PIPING SHELL COMMANDS
Regular shell commands have some limitations in some cases. When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again. Also, even when there is no output or error, the ui still needs to be paused while the command is running. This can cause flickering on the screen for short commands and similar distractions for longer commands.
.PP
Instead of pausing the ui, piping shell commands connects stdin, stdout, and stderr of the command to the statline in the bottom of the ui. This can be useful for programs following the unix philosophy to give no output in the success case, and brief error messages or prompts in other cases.
.PP
For example, following rename command prompts for overwrite in the statline if there is an existing file with the given name:
.PP
.EX
cmd rename %mv -i $f $1
.EE
.PP
You can also output error messages in the command and it will show up in the statline. For example, an alternative rename command may look like this:
.PP
.EX
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
.EE
.PP
One thing to be careful is that although input is still line buffered, output and error are byte buffered and verbose commands will be very slow to display.
.SH WAITING SHELL COMMANDS
Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished. These can be useful to see the output of a program before the ui is resumed. Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline.
.SH ASYNCHRONOUS SHELL COMMANDS
Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish. Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui.
.SH REMOTE COMMANDS
One of the more advanced features in lf is remote commands. All clients connect to a server on startup. It is possible to send commands to all or any of the connected clients over the common server. This is used internally to notify file selection changes to other clients.
.PP
To use this feature, you need to use a client which supports communicating with a UNIX-domain socket. OpenBSD implementation of netcat (nc) is one such example. You can use it to send a command to the socket file:
.PP
.EX
echo 'send echo hello world' | nc -U /tmp/lf.${USER}.sock
.EE
.PP
Since such a client may not be available everywhere, lf comes bundled with a command line flag to be used as such. When using lf, you do not need to specify the address of the socket file. This is the recommended way of using remote commands since it is shorter and immune to socket file address changes:
.PP
.EX
lf -remote 'send echo hello world'
.EE
.PP
In this command 'send' is used to send the rest of the string as a command to all connected clients. You can optionally give it an id number to send a command to a single client:
.PP
.EX
lf -remote 'send 1000 echo hello world'
.EE
.PP
All clients have a unique id number but you may not be aware of the id number when you are writing a command. For this purpose, an '$id' variable is exported to the environment for shell commands. You can use it to send a remote command from a client to the server which in return sends a command back to itself. So now you can display a message in the current client by calling the following in a shell command:
.PP
.EX
lf -remote "send $id echo hello world"
.EE
.PP
Since lf does not have control flow syntax, remote commands are used for such needs. For example, you can configure the number of columns in the ui with respect to the terminal width as follows:
.PP
.EX
cmd recol %{{
w=$(tput cols)
if [ $w -le 80 ]; then
lf -remote "send $id set ratios 1:2"
elif [ $w -le 160 ]; then
lf -remote "send $id set ratios 1:2:3"
else
lf -remote "send $id set ratios 1:2:3:5"
fi
}}
.EE
.PP
Besides 'send' command, there are also two commands to get or set the current file selection. Two possible modes 'copy' and 'move' specify whether selected files are to be copied or moved. File names are separated by newline character. Setting the file selection is done with 'save' command:
.PP
.EX
lf -remote "$(printf 'save\encopy\enfoo.txt\enbar.txt\enbaz.txt\en')"
.EE
.PP
Getting the file selection is similarly done with 'load' command:
.PP
.EX
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
# do something with $list
elif [ $mode = 'move' ]; then
# do something else with $list
fi
.EE
.PP
There is a 'quit' command to close client connections and quit the server:
.PP
.EX
lf -remote 'quit'
.EE
.PP
Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users.
.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. 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
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
You can customize copy and move operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. You can use the following example as a starting point:
.PP
.EX
cmd paste %{{
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
cp -R $list .
elif [ $mode = 'move' ]; then
mv $list .
fi
lf -remote 'send load'
lf -remote 'send clear'
}}
.EE
.PP
Some useful things to be considered are to use the backup ('--backup') and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls.
.PP
By default, lf does not assign 'delete' command to a key to protect new users. You can customize file deletion by defining a 'delete' command. You can also assign a key to this command if you like. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file.
.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.
.PP
Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. Alternatively, you can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. Possible candidates are 'up', 'down' and their variants, '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
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
Some options effect both searching and finding. You can disable 'wrapscan' option to prevent searches to wrap around at the end of the file list. You can disable 'ignorecase' option to match cases in the pattern and the filename. This option is already automatically overridden if the pattern contains upper case characters. You can disable 'smartcase' option to disable this behavior. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters.
.SH OPENING FILES
You can define a an 'open' command (default 'l' and '<right>') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command:
.PP
.EX
cmd open $vi $fx
.EE
.PP
It is possible to use different command types:
.PP
.EX
cmd open &xdg-open $f
.EE
.PP
You may want to use either file extensions or mime types from 'file' command:
.PP
.EX
cmd open ${{
case $(file --mime-type $f -b) in
text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac
}}
.EE
.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:
.PP
.EX
cmd open &$OPENER $f
.EE
.PP
You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few.
.SH PREVIEWING FILES
lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files as text to name few. For coloring lf recognizes ansi escape codes.
.PP
In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. lf passes the current file name as the first argument and the height of the preview pane as the second argument when running this file. Output of the execution is printed in the preview pane. You may want to use the same script in your pager mapping as well if any:
.PP
.EX
set previewer ~/.config/lf/pv.sh
map i $~/.config/lf/pv.sh $f | less -R
.EE
.PP
Since this script is called for each file selection change it needs to be as efficient as possible and this responsibility is left to the user. You may use file extensions to determine the type of file more efficiently compared to obtaining mime types from 'file' command. Extensions can then be used to match cleanly within a conditional:
.PP
.EX
#!/bin/sh
.EE
.PP
.EX
case "$1" in
*.tar*) tar tf "$1";;
*.zip) unzip -l "$1";;
*.rar) unrar l "$1";;
*.7z) 7z l "$1";;
*.pdf) pdftotext "$1" -;;
*) highlight -O ansi "$1" || cat "$1";;
esac
.EE
.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.
.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
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
If '$LS_COLORS' variable is not set, '$LSCOLORS' variable is checked instead. This variable is used by ls programs on unix systems such as Mac and BSDs. This variable has a simple syntax and supports 8 colors and bold attribute.
.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.
.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.
.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.
.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.
.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.
+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;
+68 -21
View File
@@ -4,15 +4,17 @@ import (
"flag" "flag"
"fmt" "fmt"
"log" "log"
"net"
"os" "os"
"os/exec"
"path/filepath" "path/filepath"
"runtime" "runtime"
"runtime/pprof" "runtime/pprof"
"strconv"
) )
var ( var (
envPath = os.Getenv("PATH") envPath = os.Getenv("PATH")
envLevel = os.Getenv("LF_LEVEL")
) )
var ( var (
@@ -24,6 +26,8 @@ var (
gSocketPath string gSocketPath string
gLogPath string gLogPath string
gServerLogPath string gServerLogPath string
gSelect string
gCommand string
gVersion string gVersion string
) )
@@ -33,15 +37,53 @@ func init() {
log.Printf("hostname: %s", err) log.Printf("hostname: %s", err)
} }
gHostname = h gHostname = h
if envLevel == "" {
envLevel = "0"
}
}
func exportEnvVars() {
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
level, err := strconv.Atoi(envLevel)
if err != nil {
log.Printf("reading lf level: %s", err)
}
level++
os.Setenv("LF_LEVEL", strconv.Itoa(level))
} }
func startServer() { func startServer() {
cmd := exec.Command(os.Args[0], "-server") cmd := detachedCommand(os.Args[0], "-server")
cmd.Dir = gUser.HomeDir
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
log.Printf("starting server: %s", err) log.Printf("starting server: %s", err)
} }
} }
func checkServer() {
if gSocketProt == "unix" {
if _, err := os.Stat(gSocketPath); os.IsNotExist(err) {
startServer()
} else if _, err := net.Dial(gSocketProt, gSocketPath); err != nil {
os.Remove(gSocketPath)
startServer()
}
} else {
if _, err := net.Dial(gSocketProt, gSocketPath); err != nil {
startServer()
}
}
}
func main() { func main() {
showDoc := flag.Bool( showDoc := flag.Bool(
"doc", "doc",
@@ -83,6 +125,11 @@ func main() {
"", "",
"path to the file to write selected files on open (to use as open file dialog)") "path to the file to write selected files on open (to use as open file dialog)")
flag.StringVar(&gCommand,
"command",
"",
"command to execute on client initialization")
flag.Parse() flag.Parse()
gSocketProt = gDefaultSocketProt gSocketProt = gDefaultSocketProt
@@ -99,36 +146,20 @@ func main() {
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
switch flag.NArg() {
case 0:
case 1:
dir := flag.Arg(0)
if err := os.Chdir(dir); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
default:
fmt.Fprintf(os.Stderr, "only single directory is allowed\n")
os.Exit(2)
}
switch { switch {
case *showDoc: case *showDoc:
fmt.Print(genDocString) fmt.Print(genDocString)
case *showVersion: case *showVersion:
fmt.Println(gVersion) fmt.Println(gVersion)
case *remoteCmd != "": case *remoteCmd != "":
if err := sendRemote(*remoteCmd); err != nil { if err := remote(*remoteCmd); err != nil {
log.Fatalf("remote command: %s", err) log.Fatalf("remote command: %s", err)
} }
case *serverMode: case *serverMode:
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:
// TODO: check if the socket is working checkServer()
if _, err := os.Stat(gSocketPath); os.IsNotExist(err) {
startServer()
}
gClientID = 1000 gClientID = 1000
gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID)) gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID))
@@ -137,6 +168,22 @@ func main() {
gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID)) gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID))
} }
switch flag.NArg() {
case 0:
_, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
case 1:
gSelect = flag.Arg(0)
default:
fmt.Fprintf(os.Stderr, "only single file or directory is allowed\n")
os.Exit(2)
}
exportEnvVars()
run() run()
} }
+34 -29
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)
} }
@@ -133,11 +133,10 @@ func splitWord(s string) (word, rest string) {
return return
} }
// This function converts a size in bytes to a human readable form. For this // This function converts a size in bytes to a human readable form using metric
// purpose metric suffixes are used (e.g. 1K = 1000). For values less than 10 // suffixes (e.g. 1K = 1000). For values less than 10 the first significant
// the first significant digit is shown, otherwise it is hidden. Numbers are // digit is shown, otherwise it is hidden. Numbers are always rounded down.
// always rounded down. For these reasons this function always show somewhat // This should be fine for most human beings.
// smaller values but it should be fine for most human beings.
func humanize(size int64) string { func humanize(size int64) string {
if size < 1000 { if size < 1000 {
return fmt.Sprintf("%dB", size) return fmt.Sprintf("%dB", size)
@@ -195,6 +194,12 @@ func naturalLess(s1, s2 string) bool {
return len(parts1) < len(parts2) return len(parts1) < len(parts2)
} }
var reAltKey = regexp.MustCompile(`<a-(.)>`)
var reWord = regexp.MustCompile(`(\pL|\pN)+`)
var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
var reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
func min(a, b int) int { func min(a, b int) int {
if a < b { if a < b {
return a return a
@@ -210,7 +215,7 @@ func max(a, b int) int {
} }
// We don't need no generic code // We don't need no generic code
// We don't need no thought control // We don't need no type control
// No dark templates in compiler // No dark templates in compiler
// Haskell leave them kids alone // Haskell leave them kids alone
// Hey Bjarne leave them kids alone // Hey Bjarne leave them kids alone
+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 {
+739 -260
View File
File diff suppressed because it is too large. Load diff
+98 -42
View File
@@ -9,6 +9,9 @@ const (
nameSort nameSort
sizeSort sizeSort
timeSort timeSort
atimeSort
ctimeSort
extSort
) )
type sortOption byte type sortOption byte
@@ -25,45 +28,77 @@ type sortType struct {
} }
var gOpts struct { var gOpts struct {
dircounts bool anchorfind bool
drawbox bool color256 bool
globsearch bool dircounts bool
ignorecase bool drawbox bool
preview bool globsearch bool
smartcase bool icons bool
wrapscan bool ignorecase bool
scrolloff int ignoredia bool
tabstop int incsearch bool
filesep string number bool
ifs string preview bool
previewer string relativenumber bool
promptfmt string smartcase bool
shell string smartdia bool
timefmt string wrapscan bool
ratios []int wrapscroll bool
info []string findlen int
keys map[string]expr period int
cmdkeys map[string]expr scrolloff int
cmds map[string]expr tabstop int
sortType sortType errorfmt string
filesep string
ifs string
previewer string
promptfmt string
shell string
timefmt string
truncatechar string
ratios []int
hiddenfiles []string
info []string
shellopts []string
keys map[string]expr
cmdkeys map[string]expr
cmds map[string]expr
sortType sortType
} }
func init() { func init() {
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.ignoredia = false
gOpts.incsearch = false
gOpts.number = false
gOpts.preview = true gOpts.preview = true
gOpts.relativenumber = false
gOpts.smartcase = true gOpts.smartcase = true
gOpts.smartdia = false
gOpts.wrapscan = true gOpts.wrapscan = true
gOpts.wrapscroll = false
gOpts.findlen = 1
gOpts.period = 0
gOpts.scrolloff = 0 gOpts.scrolloff = 0
gOpts.tabstop = 8 gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m%s\033[0m"
gOpts.filesep = "\n" gOpts.filesep = "\n"
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m" gOpts.ifs = ""
gOpts.previewer = ""
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.sortType = sortType{naturalSort, dirfirstSort} gOpts.sortType = sortType{naturalSort, dirfirstSort}
gOpts.keys = make(map[string]expr) gOpts.keys = make(map[string]expr)
@@ -72,24 +107,28 @@ func init() {
gOpts.keys["<up>"] = &callExpr{"up", nil, 1} gOpts.keys["<up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1} gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1}
gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1} gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<pgup>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["j"] = &callExpr{"down", nil, 1} gOpts.keys["j"] = &callExpr{"down", nil, 1}
gOpts.keys["<down>"] = &callExpr{"down", nil, 1} gOpts.keys["<down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1} gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1}
gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1} gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<pgdn>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["h"] = &callExpr{"updir", nil, 1} gOpts.keys["h"] = &callExpr{"updir", nil, 1}
gOpts.keys["<left>"] = &callExpr{"updir", nil, 1} gOpts.keys["<left>"] = &callExpr{"updir", nil, 1}
gOpts.keys["l"] = &callExpr{"open", nil, 1} gOpts.keys["l"] = &callExpr{"open", nil, 1}
gOpts.keys["<right>"] = &callExpr{"open", nil, 1} gOpts.keys["<right>"] = &callExpr{"open", nil, 1}
gOpts.keys["q"] = &callExpr{"quit", nil, 1} gOpts.keys["q"] = &callExpr{"quit", nil, 1}
gOpts.keys["gg"] = &callExpr{"top", nil, 1} gOpts.keys["gg"] = &callExpr{"top", nil, 1}
gOpts.keys["G"] = &callExpr{"bot", nil, 1} gOpts.keys["<home>"] = &callExpr{"top", nil, 1}
gOpts.keys["<space>"] = &callExpr{"toggle", nil, 1} gOpts.keys["G"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<end>"] = &callExpr{"bottom", 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{"unmark", nil, 1} gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"yank", nil, 1} gOpts.keys["y"] = &callExpr{"copy", nil, 1}
gOpts.keys["d"] = &callExpr{"delete", nil, 1} gOpts.keys["d"] = &callExpr{"cut", nil, 1}
gOpts.keys["c"] = &callExpr{"clear", nil, 1} gOpts.keys["c"] = &callExpr{"clear", nil, 1}
gOpts.keys["p"] = &callExpr{"put", nil, 1} gOpts.keys["p"] = &callExpr{"paste", nil, 1}
gOpts.keys["<c-l>"] = &callExpr{"redraw", nil, 1} gOpts.keys["<c-l>"] = &callExpr{"redraw", nil, 1}
gOpts.keys["<c-r>"] = &callExpr{"reload", nil, 1} gOpts.keys["<c-r>"] = &callExpr{"reload", nil, 1}
gOpts.keys[":"] = &callExpr{"read", nil, 1} gOpts.keys[":"] = &callExpr{"read", nil, 1}
@@ -97,12 +136,20 @@ func init() {
gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1} gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1}
gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1} gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1}
gOpts.keys["&"] = &callExpr{"shell-async", nil, 1} gOpts.keys["&"] = &callExpr{"shell-async", nil, 1}
gOpts.keys["f"] = &callExpr{"find", nil, 1}
gOpts.keys["F"] = &callExpr{"find-back", nil, 1}
gOpts.keys[";"] = &callExpr{"find-next", nil, 1}
gOpts.keys[","] = &callExpr{"find-prev", nil, 1}
gOpts.keys["/"] = &callExpr{"search", nil, 1} gOpts.keys["/"] = &callExpr{"search", nil, 1}
gOpts.keys["?"] = &callExpr{"search-back", nil, 1} gOpts.keys["?"] = &callExpr{"search-back", nil, 1}
gOpts.keys["n"] = &callExpr{"search-next", nil, 1} gOpts.keys["n"] = &callExpr{"search-next", nil, 1}
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1} gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-hist-next", nil, 1} gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-hist-prev", nil, 1} gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.keys["zh"] = &setExpr{"hidden!", ""} gOpts.keys["zh"] = &setExpr{"hidden!", ""}
gOpts.keys["zr"] = &setExpr{"reverse!", ""} gOpts.keys["zr"] = &setExpr{"reverse!", ""}
@@ -110,21 +157,23 @@ 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)
// TODO: rest of the keys
gOpts.cmdkeys["<space>"] = &callExpr{"cmd-insert", []string{" "}, 1} gOpts.cmdkeys["<space>"] = &callExpr{"cmd-insert", []string{" "}, 1}
gOpts.cmdkeys["<esc>"] = &callExpr{"cmd-escape", nil, 1} gOpts.cmdkeys["<esc>"] = &callExpr{"cmd-escape", nil, 1}
gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-comp", nil, 1} gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-complete", nil, 1}
gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1} gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1} gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-hist-next", nil, 1} gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-hist-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["<bs>"] = &callExpr{"cmd-delete-back", nil, 1}
@@ -133,16 +182,23 @@ func init() {
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}
gOpts.cmdkeys["<c-f>"] = &callExpr{"cmd-right", nil, 1} gOpts.cmdkeys["<c-f>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<home>"] = &callExpr{"cmd-beg", nil, 1} gOpts.cmdkeys["<home>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<c-a>"] = &callExpr{"cmd-beg", nil, 1} gOpts.cmdkeys["<c-a>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<end>"] = &callExpr{"cmd-end", nil, 1} gOpts.cmdkeys["<end>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-e>"] = &callExpr{"cmd-end", nil, 1} gOpts.cmdkeys["<c-e>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-u>"] = &callExpr{"cmd-delete-beg", nil, 1} gOpts.cmdkeys["<c-u>"] = &callExpr{"cmd-delete-home", nil, 1}
gOpts.cmdkeys["<c-k>"] = &callExpr{"cmd-delete-end", nil, 1} gOpts.cmdkeys["<c-k>"] = &callExpr{"cmd-delete-end", nil, 1}
gOpts.cmdkeys["<c-w>"] = &callExpr{"cmd-delete-word", nil, 1} gOpts.cmdkeys["<c-w>"] = &callExpr{"cmd-delete-unix-word", nil, 1}
gOpts.cmdkeys["<c-y>"] = &callExpr{"cmd-put", nil, 1} gOpts.cmdkeys["<c-y>"] = &callExpr{"cmd-yank", nil, 1}
gOpts.cmdkeys["<c-t>"] = &callExpr{"cmd-transpose", nil, 1} gOpts.cmdkeys["<c-t>"] = &callExpr{"cmd-transpose", nil, 1}
gOpts.cmdkeys["<c-c>"] = &callExpr{"cmd-interrupt", nil, 1} gOpts.cmdkeys["<c-c>"] = &callExpr{"cmd-interrupt", nil, 1}
gOpts.cmdkeys["<a-f>"] = &callExpr{"cmd-word", nil, 1}
gOpts.cmdkeys["<a-b>"] = &callExpr{"cmd-word-back", nil, 1}
gOpts.cmdkeys["<a-c>"] = &callExpr{"cmd-capitalize-word", nil, 1}
gOpts.cmdkeys["<a-d>"] = &callExpr{"cmd-delete-word", nil, 1}
gOpts.cmdkeys["<a-u>"] = &callExpr{"cmd-uppercase-word", nil, 1}
gOpts.cmdkeys["<a-l>"] = &callExpr{"cmd-lowercase-word", nil, 1}
gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1}
gOpts.cmds = make(map[string]expr) gOpts.cmds = make(map[string]expr)
+114 -60
View File
@@ -10,9 +10,12 @@ import (
"os/user" "os/user"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings"
"syscall"
) )
var ( var (
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")
@@ -25,14 +28,42 @@ var (
) )
var ( var (
gUser *user.User gUser *user.User
gConfigPath string gConfigPaths []string
gMarksPath string
gHistoryPath string
) )
func init() { func init() {
if envOpener == "" {
if runtime.GOOS == "darwin" {
envOpener = "open"
} else {
envOpener = "xdg-open"
}
}
if envEditor == "" {
envEditor = "vi"
}
if envPager == "" {
envPager = "less"
}
if envShell == "" {
envShell = "sh"
}
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
if os.Getenv("HOME") == "" {
log.Print("$HOME variable is empty or not set")
}
if os.Getenv("USER") == "" {
log.Print("$USER variable is empty or not set")
}
} }
gUser = u gUser = u
@@ -41,21 +72,36 @@ func init() {
config = filepath.Join(gUser.HomeDir, ".config") config = filepath.Join(gUser.HomeDir, ".config")
} }
gConfigPath = filepath.Join(config, "lf", "lfrc") gConfigPaths = []string{
filepath.Join("/etc", "lf", "lfrc"),
filepath.Join(config, "lf", "lfrc"),
}
data := os.Getenv("XDG_DATA_HOME")
if data == "" {
data = filepath.Join(gUser.HomeDir, ".local", "share")
}
gMarksPath = filepath.Join(data, "lf", "marks")
gHistoryPath = filepath.Join(data, "lf", "history")
gDefaultSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.sock", gUser.Username)) gDefaultSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.sock", gUser.Username))
} }
func pauseCommand() *exec.Cmd { func detachedCommand(name string, arg ...string) *exec.Cmd {
c := `echo return exec.Command(name, arg...)
echo -n 'Press any key to continue' }
old=$(stty -g)
stty raw -echo
eval "ignore=\$(dd bs=1 count=1 2> /dev/null)"
stty $old
echo`
return exec.Command(gOpts.shell, "-c", c) func pauseCommand() *exec.Cmd {
cmd := `echo
echo -n 'Press any key to continue'
old=$(stty -g)
stty raw -echo
eval "ignore=\$(dd bs=1 count=1 2> /dev/null)"
stty $old
echo`
return exec.Command(gOpts.shell, "-c", cmd)
} }
func shellCommand(s string, args []string) *exec.Cmd { func shellCommand(s string, args []string) *exec.Cmd {
@@ -65,59 +111,67 @@ func shellCommand(s string, args []string) *exec.Cmd {
args = append([]string{"-c", s, "--"}, args...) args = append([]string{"-c", s, "--"}, args...)
args = append(gOpts.shellopts, args...)
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func putCommand(list []string, dir *dir, copy bool) *exec.Cmd {
var sh string
var args []string
if copy {
sh = "cp"
args = append(args, "-R")
} else {
sh = "mv"
}
// XXX: POSIX standard states that -i flag shall do nothing when the
// response is not affirmative. Since this command is run with a nil stdin,
// it should not give an affirmative answer and in return this command
// should not overwrite existing files. Our intention here is to use the
// standard -i flag in place of non-standard -n flag to avoid overwrites.
args = append(args, "-i")
args = append(args, list...)
args = append(args, dir.path)
return exec.Command(sh, args...)
}
func setDefaults() { func setDefaults() {
if envEditor == "" { gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`}
gOpts.keys["e"] = &execExpr{"$", `vi "$f"`} gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`}
} else { gOpts.keys["i"] = &execExpr{"$", `$PAGER "$f"`}
gOpts.keys["e"] = &execExpr{"$", envEditor + ` "$f"`} gOpts.keys["w"] = &execExpr{"$", "$SHELL"}
}
if envPager == "" { gOpts.cmds["doc"] = &execExpr{"$", "lf -doc | $PAGER"}
gOpts.keys["i"] = &execExpr{"$", `less "$f"`} gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
} else {
gOpts.keys["i"] = &execExpr{"$", envPager + ` "$f"`}
}
if envShell == "" {
gOpts.keys["w"] = &execExpr{"$", "sh"}
} else {
gOpts.keys["w"] = &execExpr{"$", envShell}
}
if runtime.GOOS == "darwin" {
gOpts.cmds["open-file"] = &execExpr{"&", `open "$f"`}
} else {
gOpts.cmds["open-file"] = &execExpr{"&", `xdg-open "$f"`}
}
} }
func moveCursor(y, x int) { func isExecutable(f os.FileInfo) bool {
fmt.Printf("\033[%d;%dH", y, x) return f.Mode()&0111 != 0
}
func isHidden(f os.FileInfo, path string) bool {
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) {
envFile := f
envFiles := strings.Join(fs, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
} }
+100 -37
View File
@@ -1,14 +1,25 @@
package main package main
import ( import (
"fmt"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"os/user" "os/user"
"path/filepath" "path/filepath"
"strings" "strings"
"syscall"
) )
var (
envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL")
)
var envPathExt = os.Getenv("PATHEXT")
var ( var (
gDefaultShell = "cmd" gDefaultShell = "cmd"
gDefaultSocketProt = "tcp" gDefaultSocketProt = "tcp"
@@ -16,11 +27,29 @@ var (
) )
var ( var (
gUser *user.User gUser *user.User
gConfigPath string gConfigPaths []string
gMarksPath string
gHistoryPath string
) )
func init() { func init() {
if envOpener == "" {
envOpener = `start ""`
}
if envEditor == "" {
envEditor = "notepad"
}
if envPager == "" {
envPager = "more"
}
if envShell == "" {
envShell = "cmd"
}
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
@@ -30,7 +59,21 @@ func init() {
// remove domain prefix // remove domain prefix
gUser.Username = strings.Split(gUser.Username, `\`)[1] gUser.Username = strings.Split(gUser.Username, `\`)[1]
gConfigPath = filepath.Join(gUser.HomeDir, "AppData", "Local", "lf", "lfrc") data := os.Getenv("LOCALAPPDATA")
gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
filepath.Join(data, "lf", "lfrc"),
}
gMarksPath = filepath.Join(data, "lf", "marks")
gHistoryPath = filepath.Join(data, "lf", "history")
}
func detachedCommand(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 8}
return cmd
} }
func pauseCommand() *exec.Cmd { func pauseCommand() *exec.Cmd {
@@ -39,44 +82,64 @@ func pauseCommand() *exec.Cmd {
func shellCommand(s string, args []string) *exec.Cmd { func shellCommand(s string, args []string) *exec.Cmd {
args = append([]string{"/c", s}, args...) args = append([]string{"/c", s}, args...)
args = append(gOpts.shellopts, args...)
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func putCommand(list []string, dir *dir, copy bool) *exec.Cmd {
var args []string
sh := "robocopy"
if !copy {
args = []string{"/move"}
}
for _, f := range list {
stat, err := os.Stat(f)
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
base := filepath.Base(f)
dest := filepath.Dir(f)
if stat.IsDir() {
exec.Command(sh, append(args, f, filepath.Join(dir.path, base))...).Run()
} else {
exec.Command(sh, append(args, dest, dir.path, base)...).Run()
}
}
// TODO: return 0 on success
return exec.Command(sh, args...)
}
func setDefaults() { func setDefaults() {
gOpts.keys["e"] = &execExpr{"$", `notepad "%f%"`} gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"}
gOpts.keys["i"] = &execExpr{"$", `more "%f%"`} gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"}
gOpts.keys["w"] = &execExpr{"$", "cmd"} gOpts.keys["i"] = &execExpr{"!", "%PAGER% %f%"}
gOpts.cmds["open-file"] = &execExpr{"&", `start "" "%f%"`} gOpts.keys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.cmds["doc"] = &execExpr{"!", "lf -doc | %PAGER%"}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
} }
func moveCursor(y, x int) { func isExecutable(f os.FileInfo) bool {
// TODO: implement exts := strings.Split(envPathExt, string(filepath.ListSeparator))
return for _, e := range exts {
if strings.HasSuffix(strings.ToLower(f.Name()), strings.ToLower(e)) {
log.Print(f.Name(), e)
return true
}
}
return false
}
func isHidden(f os.FileInfo, path string) bool {
ptr, err := syscall.UTF16PtrFromString(filepath.Join(path, f.Name()))
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) {
envFile := fmt.Sprintf(`"%s"`, f)
var quotedFiles []string
for _, f := range fs {
quotedFiles = append(quotedFiles, fmt.Sprintf(`"%s"`, f))
}
envFiles := strings.Join(quotedFiles, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
} }
+3 -2
View File
@@ -23,7 +23,7 @@ package main
// ExecExpr = Prefix <value> '\n' // ExecExpr = Prefix <value> '\n'
// | Prefix '{{' <value> '}}' ';' // | Prefix '{{' <value> '}}' ';'
// //
// Prefix = '$' | '!' | '&' | '/' | '?' // Prefix = '$' | '%' | '!' | '&'
// //
// ListExpr = ':' Expr ListRest '\n' // ListExpr = ':' Expr ListRest '\n'
// | ':' '{{' Expr ListRest '}}' ';' // | ':' '{{' Expr ListRest '}}' ';'
@@ -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()
+24 -5
View File
@@ -13,15 +13,17 @@ var (
gCopyFile bool gCopyFile bool
gFileList []string gFileList []string
gConnList = make(map[int]net.Conn) gConnList = make(map[int]net.Conn)
gQuitChan = make(chan bool, 1)
gListener net.Listener
) )
func serve() { func serve() {
logFile, err := os.Create(gServerLogPath) f, err := os.Create(gServerLogPath)
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer logFile.Close() defer f.Close()
log.SetOutput(logFile) log.SetOutput(f)
log.Print("hi!") log.Print("hi!")
@@ -32,6 +34,8 @@ func serve() {
} }
defer l.Close() defer l.Close()
gListener = l
listen(l) listen(l)
} }
@@ -39,7 +43,13 @@ func listen(l net.Listener) {
for { for {
c, err := l.Accept() c, err := l.Accept()
if err != nil { if err != nil {
log.Printf("accepting connection: %s", err) select {
case <-gQuitChan:
log.Printf("bye!")
return
default:
log.Printf("accepting connection: %s", err)
}
} }
go handleConn(c) go handleConn(c)
} }
@@ -48,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())
@@ -61,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() != "" {
@@ -103,6 +114,14 @@ func handleConn(c net.Conn) {
} }
} }
} }
case "quit":
gQuitChan <- true
for _, c := range gConnList {
fmt.Fprintln(c, "echo server is quitting...")
c.Close()
}
gListener.Close()
break Loop
default: default:
log.Printf("listen: unexpected command: %s", word) log.Printf("listen: unexpected command: %s", word)
} }
+314 -205
View File
@@ -11,95 +11,73 @@ import (
"strconv" "strconv"
"strings" "strings"
"text/tabwriter" "text/tabwriter"
"time"
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"github.com/doronbehar/termbox-go"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
"github.com/nsf/termbox-go"
) )
const gEscapeCode = 27 const gEscapeCode = 27
var gAnsiCodes = map[int]termbox.Attribute{ var gKeyVal = map[termbox.Key]string{
0: termbox.ColorDefault, termbox.KeyF1: "<f-1>",
1: termbox.AttrBold, termbox.KeyF2: "<f-2>",
4: termbox.AttrUnderline, termbox.KeyF3: "<f-3>",
7: termbox.AttrReverse, termbox.KeyF4: "<f-4>",
30: termbox.ColorBlack, termbox.KeyF5: "<f-5>",
31: termbox.ColorRed, termbox.KeyF6: "<f-6>",
32: termbox.ColorGreen, termbox.KeyF7: "<f-7>",
33: termbox.ColorYellow, termbox.KeyF8: "<f-8>",
34: termbox.ColorBlue, termbox.KeyF9: "<f-9>",
35: termbox.ColorMagenta, termbox.KeyF10: "<f-10>",
36: termbox.ColorCyan, termbox.KeyF11: "<f-11>",
37: termbox.ColorWhite, termbox.KeyF12: "<f-12>",
40: termbox.ColorBlack, termbox.KeyInsert: "<insert>",
41: termbox.ColorRed, termbox.KeyDelete: "<delete>",
42: termbox.ColorGreen, termbox.KeyHome: "<home>",
43: termbox.ColorYellow, termbox.KeyEnd: "<end>",
44: termbox.ColorBlue, termbox.KeyPgup: "<pgup>",
45: termbox.ColorMagenta, termbox.KeyPgdn: "<pgdn>",
46: termbox.ColorCyan, termbox.KeyArrowUp: "<up>",
47: termbox.ColorWhite, termbox.KeyArrowDown: "<down>",
} termbox.KeyArrowLeft: "<left>",
termbox.KeyArrowRight: "<right>",
var gKeyVal = map[termbox.Key][]rune{ termbox.KeyCtrlSpace: "<c-space>",
termbox.KeyF1: {'<', 'f', '-', '1', '>'}, termbox.KeyCtrlA: "<c-a>",
termbox.KeyF2: {'<', 'f', '-', '2', '>'}, termbox.KeyCtrlB: "<c-b>",
termbox.KeyF3: {'<', 'f', '-', '3', '>'}, termbox.KeyCtrlC: "<c-c>",
termbox.KeyF4: {'<', 'f', '-', '4', '>'}, termbox.KeyCtrlD: "<c-d>",
termbox.KeyF5: {'<', 'f', '-', '5', '>'}, termbox.KeyCtrlE: "<c-e>",
termbox.KeyF6: {'<', 'f', '-', '6', '>'}, termbox.KeyCtrlF: "<c-f>",
termbox.KeyF7: {'<', 'f', '-', '7', '>'}, termbox.KeyCtrlG: "<c-g>",
termbox.KeyF8: {'<', 'f', '-', '8', '>'}, termbox.KeyBackspace: "<bs>",
termbox.KeyF9: {'<', 'f', '-', '9', '>'}, termbox.KeyTab: "<tab>",
termbox.KeyF10: {'<', 'f', '-', '1', '0', '>'}, termbox.KeyCtrlJ: "<c-j>",
termbox.KeyF11: {'<', 'f', '-', '1', '1', '>'}, termbox.KeyCtrlK: "<c-k>",
termbox.KeyF12: {'<', 'f', '-', '1', '2', '>'}, termbox.KeyCtrlL: "<c-l>",
termbox.KeyInsert: {'<', 'i', 'n', 's', 'e', 'r', 't', '>'}, termbox.KeyEnter: "<enter>",
termbox.KeyDelete: {'<', 'd', 'e', 'l', 'e', 't', 'e', '>'}, termbox.KeyCtrlN: "<c-n>",
termbox.KeyHome: {'<', 'h', 'o', 'm', 'e', '>'}, termbox.KeyCtrlO: "<c-o>",
termbox.KeyEnd: {'<', 'e', 'n', 'd', '>'}, termbox.KeyCtrlP: "<c-p>",
termbox.KeyPgup: {'<', 'p', 'g', 'u', 'p', '>'}, termbox.KeyCtrlQ: "<c-q>",
termbox.KeyPgdn: {'<', 'p', 'g', 'd', 'n', '>'}, termbox.KeyCtrlR: "<c-r>",
termbox.KeyArrowUp: {'<', 'u', 'p', '>'}, termbox.KeyCtrlS: "<c-s>",
termbox.KeyArrowDown: {'<', 'd', 'o', 'w', 'n', '>'}, termbox.KeyCtrlT: "<c-t>",
termbox.KeyArrowLeft: {'<', 'l', 'e', 'f', 't', '>'}, termbox.KeyCtrlU: "<c-u>",
termbox.KeyArrowRight: {'<', 'r', 'i', 'g', 'h', 't', '>'}, termbox.KeyCtrlV: "<c-v>",
termbox.KeyCtrlSpace: {'<', 'c', '-', 's', 'p', 'a', 'c', 'e', '>'}, termbox.KeyCtrlW: "<c-w>",
termbox.KeyCtrlA: {'<', 'c', '-', 'a', '>'}, termbox.KeyCtrlX: "<c-x>",
termbox.KeyCtrlB: {'<', 'c', '-', 'b', '>'}, termbox.KeyCtrlY: "<c-y>",
termbox.KeyCtrlC: {'<', 'c', '-', 'c', '>'}, termbox.KeyCtrlZ: "<c-z>",
termbox.KeyCtrlD: {'<', 'c', '-', 'd', '>'}, termbox.KeyEsc: "<esc>",
termbox.KeyCtrlE: {'<', 'c', '-', 'e', '>'}, termbox.KeyCtrlBackslash: "<c-\\>",
termbox.KeyCtrlF: {'<', 'c', '-', 'f', '>'}, termbox.KeyCtrlRsqBracket: "<c-]>",
termbox.KeyCtrlG: {'<', 'c', '-', 'g', '>'}, termbox.KeyCtrl6: "<c-6>",
termbox.KeyBackspace: {'<', 'b', 's', '>'}, termbox.KeyCtrlSlash: "<c-/>",
termbox.KeyTab: {'<', 't', 'a', 'b', '>'}, termbox.KeySpace: "<space>",
termbox.KeyCtrlJ: {'<', 'c', '-', 'j', '>'}, termbox.KeyBackspace2: "<bs2>",
termbox.KeyCtrlK: {'<', 'c', '-', 'k', '>'},
termbox.KeyCtrlL: {'<', 'c', '-', 'l', '>'},
termbox.KeyEnter: {'<', 'e', 'n', 't', 'e', 'r', '>'},
termbox.KeyCtrlN: {'<', 'c', '-', 'n', '>'},
termbox.KeyCtrlO: {'<', 'c', '-', 'o', '>'},
termbox.KeyCtrlP: {'<', 'c', '-', 'p', '>'},
termbox.KeyCtrlQ: {'<', 'c', '-', 'q', '>'},
termbox.KeyCtrlR: {'<', 'c', '-', 'r', '>'},
termbox.KeyCtrlS: {'<', 'c', '-', 's', '>'},
termbox.KeyCtrlT: {'<', 'c', '-', 't', '>'},
termbox.KeyCtrlU: {'<', 'c', '-', 'u', '>'},
termbox.KeyCtrlV: {'<', 'c', '-', 'v', '>'},
termbox.KeyCtrlW: {'<', 'c', '-', 'w', '>'},
termbox.KeyCtrlX: {'<', 'c', '-', 'x', '>'},
termbox.KeyCtrlY: {'<', 'c', '-', 'y', '>'},
termbox.KeyCtrlZ: {'<', 'c', '-', 'z', '>'},
termbox.KeyEsc: {'<', 'e', 's', 'c', '>'},
termbox.KeyCtrlBackslash: {'<', 'c', '-', '\\', '>'},
termbox.KeyCtrlRsqBracket: {'<', 'c', '-', ']', '>'},
termbox.KeyCtrl6: {'<', 'c', '-', '6', '>'},
termbox.KeyCtrlSlash: {'<', 'c', '-', '/', '>'},
termbox.KeySpace: {'<', 's', 'p', 'a', 'c', 'e', '>'},
termbox.KeyBackspace2: {'<', 'b', 's', '2', '>'},
} }
var gValKey map[string]termbox.Key var gValKey map[string]termbox.Key
@@ -107,7 +85,7 @@ var gValKey map[string]termbox.Key
func init() { func init() {
gValKey = make(map[string]termbox.Key) gValKey = make(map[string]termbox.Key)
for k, v := range gKeyVal { for k, v := range gKeyVal {
gValKey[string(v)] = k gValKey[v] = k
} }
} }
@@ -175,7 +153,11 @@ func (win *win) print(x, y int, fg, bg termbox.Attribute, s string) (termbox.Att
i += w - 1 i += w - 1
if r == '\t' { if r == '\t' {
x += gOpts.tabstop - (x-off)%gOpts.tabstop s := gOpts.tabstop - (x-off)%gOpts.tabstop
for i := 0; i < s && x+i < win.w; i++ {
termbox.SetCell(win.x+x+i, win.y+y, ' ', fg, bg)
}
x += s
} else { } else {
x += runewidth.RuneWidth(r) x += runewidth.RuneWidth(r)
} }
@@ -203,11 +185,15 @@ func (win *win) printReg(reg *reg) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
if reg.loading {
fg = termbox.AttrReverse
win.print(2, 0, fg, bg, "loading...")
return
}
for i, l := range reg.lines { for i, l := range reg.lines {
fg, bg = win.print(2, i, fg, bg, l) fg, bg = win.print(2, i, fg, bg, l)
} }
return
} }
func fileInfo(f *file, d *dir) string { func fileInfo(f *file, d *dir) string {
@@ -223,32 +209,36 @@ func fileInfo(f *file, d *dir) string {
continue continue
} }
if f.count == -1 { if f.dirCount == -1 {
d, err := os.Open(path) d, err := os.Open(path)
if err != nil { if err != nil {
f.count = -2 f.dirCount = -2
} }
names, err := d.Readdirnames(1000) names, err := d.Readdirnames(1000)
d.Close() d.Close()
if names == nil && err != io.EOF { if names == nil && err != io.EOF {
f.count = -2 f.dirCount = -2
} else { } else {
f.count = len(names) f.dirCount = len(names)
} }
} }
switch { switch {
case f.count < 0: case f.dirCount < 0:
info = fmt.Sprintf("%s ?", info) info = fmt.Sprintf("%s ?", info)
case f.count < 1000: case f.dirCount < 1000:
info = fmt.Sprintf("%s %4d", info, f.count) info = fmt.Sprintf("%s %4d", info, f.dirCount)
default: default:
info = fmt.Sprintf("%s 999+", info) info = fmt.Sprintf("%s 999+", info)
} }
case "time": case "time":
info = fmt.Sprintf("%s %12s", info, f.ModTime().Format("Jan _2 15:04")) info = fmt.Sprintf("%s %12s", info, f.ModTime().Format("Jan _2 15:04"))
case "atime":
info = fmt.Sprintf("%s %12s", info, f.accessTime.Format("Jan _2 15:04"))
case "ctime":
info = fmt.Sprintf("%s %12s", info, f.changeTime.Format("Jan _2 15:04"))
default: default:
log.Printf("unknown info type: %s", s) log.Printf("unknown info type: %s", s)
} }
@@ -257,44 +247,80 @@ func fileInfo(f *file, d *dir) string {
return info return info
} }
func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool, colors colorMap) { func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap, icons iconMap) {
if win.w < 5 || dir == nil { if win.w < 5 || dir == nil {
return return
} }
fg, bg := termbox.ColorDefault, termbox.ColorDefault
if dir.loading { if dir.loading {
fg = termbox.AttrBold win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "loading...")
win.print(2, 0, fg, bg, "loading...")
return return
} }
if len(dir.fi) == 0 { if dir.noPerm {
fg = termbox.AttrBold win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "permission denied")
win.print(2, 0, fg, bg, "empty") return
}
if len(dir.files) == 0 {
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "empty")
return return
} }
beg := max(dir.ind-dir.pos, 0) beg := max(dir.ind-dir.pos, 0)
end := min(beg+win.h, len(dir.fi)) end := min(beg+win.h, len(dir.files))
if beg > end { if beg > end {
return return
} }
for i, f := range dir.fi[beg:end] { var lnwidth int
fg, bg = colors.get(f) var lnformat string
if gOpts.number || gOpts.relativenumber {
lnwidth = 1
if gOpts.number && gOpts.relativenumber {
lnwidth++
}
for j := 10; j < len(dir.files); j *= 10 {
lnwidth++
}
lnformat = fmt.Sprintf("%%%d.d ", lnwidth)
}
for i, f := range dir.files[beg:end] {
fg, bg := colors.get(f)
if lnwidth > 0 {
var ln string
if gOpts.number && (!gOpts.relativenumber) {
ln = fmt.Sprintf(lnformat, i+1+beg)
} else if gOpts.relativenumber {
switch {
case i < dir.pos:
ln = fmt.Sprintf(lnformat, dir.pos-i)
case i > dir.pos:
ln = fmt.Sprintf(lnformat, i-dir.pos)
case gOpts.number:
ln = fmt.Sprintf(fmt.Sprintf("%%%d.d ", lnwidth-1), i+1+beg)
default:
ln = ""
}
}
win.print(0, i, termbox.ColorYellow, bg, ln)
}
path := filepath.Join(dir.path, f.Name()) path := filepath.Join(dir.path, f.Name())
if _, ok := marks[path]; ok { if _, ok := selections[path]; ok {
win.print(0, i, fg, termbox.ColorMagenta, " ") win.print(lnwidth, i, fg, termbox.ColorMagenta, " ")
} else if copy, ok := saves[path]; ok { } else if cp, ok := saves[path]; ok {
if copy { if cp {
win.print(0, i, fg, termbox.ColorYellow, " ") win.print(lnwidth, i, fg, termbox.ColorYellow, " ")
} else { } else {
win.print(0, i, fg, termbox.ColorRed, " ") win.print(lnwidth, i, fg, termbox.ColorRed, " ")
} }
} }
@@ -306,6 +332,11 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
s = append(s, ' ') s = append(s, ' ')
if gOpts.icons {
s = append(s, []rune(icons.get(f))...)
s = append(s, ' ')
}
for _, r := range f.Name() { for _, r := range f.Name() {
s = append(s, r) s = append(s, r)
} }
@@ -314,7 +345,7 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
if w > win.w-3 { if w > win.w-3 {
s = runeSliceWidthRange(s, 0, win.w-4) s = runeSliceWidthRange(s, 0, win.w-4)
s = append(s, '~') s = append(s, []rune(gOpts.truncatechar)...)
} else { } else {
for i := 0; i < win.w-3-w; i++ { for i := 0; i < win.w-3-w; i++ {
s = append(s, ' ') s = append(s, ' ')
@@ -325,10 +356,10 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
if len(info) > 0 && win.w-2 > 2*len(info) { if len(info) > 0 && win.w-2 > 2*len(info) {
if win.w-2 > w+len(info) { if win.w-2 > w+len(info) {
s = runeSliceWidthRange(s, 0, win.w-3-len(info)) s = runeSliceWidthRange(s, 0, win.w-3-len(info)-lnwidth)
} else { } else {
s = runeSliceWidthRange(s, 0, win.w-4-len(info)) s = runeSliceWidthRange(s, 0, win.w-4-len(info)-lnwidth)
s = append(s, '~') s = append(s, []rune(gOpts.truncatechar)...)
} }
for _, r := range info { for _, r := range info {
s = append(s, r) s = append(s, r)
@@ -337,7 +368,7 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
s = append(s, ' ') s = append(s, ' ')
win.print(1, i, fg, bg, string(s)) win.print(lnwidth+1, i, fg, bg, string(s))
} }
} }
@@ -356,16 +387,17 @@ type ui struct {
cmdPrefix string cmdPrefix string
cmdAccLeft []rune cmdAccLeft []rune
cmdAccRight []rune cmdAccRight []rune
cmdBuf []rune cmdYankBuf []rune
keyAcc []rune keyAcc []rune
keyCount []rune keyCount []rune
colors colorMap colors colorMap
icons iconMap
} }
func getWidths(wtot int) []int { func getWidths(wtot int) []int {
rsum := 0 rsum := 0
for _, rat := range gOpts.ratios { for _, r := range gOpts.ratios {
rsum += rat rsum += r
} }
wlen := len(gOpts.ratios) wlen := len(gOpts.ratios)
@@ -409,11 +441,27 @@ func getWins() []*win {
func newUI() *ui { func newUI() *ui {
wtot, htot := termbox.Size() wtot, htot := termbox.Size()
evChan := make(chan termbox.Event) evQueue := make(chan termbox.Event)
go func() { go func() {
for { for {
evChan <- termbox.PollEvent() evQueue <- termbox.PollEvent()
}
}()
evChan := make(chan termbox.Event)
go func() {
for {
ev := <-evQueue
if ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc {
select {
case ev2 := <-evQueue:
ev2.Mod = termbox.ModAlt
evChan <- ev2
continue
case <-time.After(100 * time.Millisecond):
}
}
evChan <- ev
} }
}() }()
@@ -425,6 +473,7 @@ func newUI() *ui {
keyChan: make(chan string, 1000), keyChan: make(chan string, 1000),
evChan: evChan, evChan: evChan,
colors: parseColors(), colors: parseColors(),
icons: parseIcons(),
} }
} }
@@ -455,21 +504,40 @@ func (ui *ui) sort() {
} }
name := ui.dirPrev.name() name := ui.dirPrev.name()
ui.dirPrev.sort() ui.dirPrev.sort()
ui.dirPrev.find(name, ui.wins[0].h) ui.dirPrev.sel(name, ui.wins[0].h)
} }
func (ui *ui) print(msg string) { func (ui *ui) echo(msg string) {
ui.msg = msg
}
func (ui *ui) echof(format string, a ...interface{}) {
ui.echo(fmt.Sprintf(format, a...))
}
func (ui *ui) echomsg(msg string) {
ui.msg = msg ui.msg = msg
log.Print(msg) log.Print(msg)
} }
func (ui *ui) printf(format string, a ...interface{}) { func (ui *ui) echomsgf(format string, a ...interface{}) {
ui.print(fmt.Sprintf(format, a...)) ui.echomsg(fmt.Sprintf(format, a...))
}
func (ui *ui) echoerr(msg string) {
ui.msg = fmt.Sprintf(gOpts.errorfmt, msg)
log.Printf("error: %s", msg)
}
func (ui *ui) echoerrf(format string, a ...interface{}) {
ui.echoerr(fmt.Sprintf(format, a...))
} }
type reg struct { type reg struct {
path string loading bool
lines []string loadTime time.Time
path string
lines []string
} }
func (ui *ui) loadFile(nav *nav) { func (ui *ui) loadFile(nav *nav) {
@@ -485,7 +553,7 @@ func (ui *ui) loadFile(nav *nav) {
if curr.IsDir() { if curr.IsDir() {
ui.dirPrev = nav.loadDir(curr.path) ui.dirPrev = nav.loadDir(curr.path)
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
ui.regPrev = nav.loadReg(ui, curr.path) ui.regPrev = nav.loadReg(curr.path)
} }
} }
@@ -495,16 +563,27 @@ func (ui *ui) loadFileInfo(nav *nav) {
return return
} }
ui.msg = fmt.Sprintf("%v %4s %v", curr.Mode(), humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt)) var linkTarget string
if curr.linkTarget != "" {
linkTarget = " -> " + curr.linkTarget
}
ui.echof("%v %4s %v%s", curr.Mode(), humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt), linkTarget)
} }
func (ui *ui) drawPromptLine(nav *nav) { func (ui *ui) drawPromptLine(nav *nav) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
dir := nav.currDir() pwd := nav.currDir().path
pwd := strings.Replace(dir.path, gUser.HomeDir, "~", -1) if strings.HasPrefix(pwd, gUser.HomeDir) {
pwd = filepath.Clean(pwd) pwd = filepath.Join("~", strings.TrimPrefix(pwd, gUser.HomeDir))
}
sep := string(filepath.Separator)
if !strings.HasSuffix(pwd, sep) {
pwd += sep
}
var fname string var fname string
curr, err := nav.currFile() curr, err := nav.currFile()
@@ -519,9 +598,11 @@ func (ui *ui) drawPromptLine(nav *nav) {
prompt = strings.Replace(prompt, "%f", fname, -1) prompt = strings.Replace(prompt, "%f", fname, -1)
if printLength(strings.Replace(prompt, "%w", pwd, -1)) > ui.promptWin.w { if printLength(strings.Replace(prompt, "%w", pwd, -1)) > ui.promptWin.w {
sep := string(filepath.Separator)
names := strings.Split(pwd, sep) names := strings.Split(pwd, sep)
for i := range names { for i := range names {
if names[i] == "" {
continue
}
r, _ := utf8.DecodeRuneInString(names[i]) r, _ := utf8.DecodeRuneInString(names[i])
names[i] = string(r) names[i] = string(r)
if printLength(strings.Replace(prompt, "%w", strings.Join(names, sep), -1)) <= ui.promptWin.w { if printLength(strings.Replace(prompt, "%w", strings.Join(names, sep), -1)) <= ui.promptWin.w {
@@ -539,20 +620,35 @@ func (ui *ui) drawPromptLine(nav *nav) {
func (ui *ui) drawStatLine(nav *nav) { func (ui *ui) drawStatLine(nav *nav) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
currDir := nav.currDir() dir := nav.currDir()
ui.msgWin.print(0, 0, fg, bg, ui.msg) ui.msgWin.print(0, 0, fg, bg, ui.msg)
tot := len(currDir.fi) tot := len(dir.files)
ind := min(currDir.ind+1, tot) ind := min(dir.ind+1, tot)
acc := string(ui.keyCount) + string(ui.keyAcc) acc := string(ui.keyCount) + string(ui.keyAcc)
ruler := fmt.Sprintf("%s %d/%d", acc, ind, tot) var progress string
if nav.copyTotal > 0 {
percentage := int((100 * float64(nav.copyBytes)) / float64(nav.copyTotal))
progress += fmt.Sprintf(" [%d%%]", percentage)
}
if nav.moveTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.moveCount, nav.moveTotal)
}
if nav.deleteTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.deleteCount, nav.deleteTotal)
}
ruler := fmt.Sprintf("%s%s %d/%d", acc, progress, ind, tot)
ui.msgWin.printRight(0, fg, bg, ruler) ui.msgWin.printRight(0, fg, bg, ruler)
} }
func (ui *ui) drawBox(nav *nav) { func (ui *ui) drawBox() {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
w, h := termbox.Size() w, h := termbox.Size()
@@ -600,7 +696,7 @@ func (ui *ui) draw(nav *nav) {
doff := len(nav.dirs) - length doff := len(nav.dirs) - length
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.marks, nav.saves, ui.colors) ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.selections, nav.saves, ui.colors, ui.icons)
} }
switch ui.cmdPrefix { switch ui.cmdPrefix {
@@ -621,20 +717,20 @@ func (ui *ui) draw(nav *nav) {
} }
if gOpts.preview { if gOpts.preview {
f, err := nav.currFile() curr, err := nav.currFile()
if err == nil { if err == nil {
preview := ui.wins[len(ui.wins)-1] preview := ui.wins[len(ui.wins)-1]
if f.IsDir() { if curr.IsDir() {
preview.printDir(ui.dirPrev, nav.marks, nav.saves, ui.colors) preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors, ui.icons)
} else if f.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
preview.printReg(ui.regPrev) preview.printReg(ui.regPrev)
} }
} }
} }
if gOpts.drawbox { if gOpts.drawbox {
ui.drawBox(nav) ui.drawBox()
} }
if ui.menuBuf != nil { if ui.menuBuf != nil {
@@ -657,21 +753,17 @@ func (ui *ui) draw(nav *nav) {
} }
termbox.Flush() termbox.Flush()
if ui.cmdPrefix == "" {
// leave the cursor at the beginning of the current file for screen readers
moveCursor(ui.wins[woff+length-1].y+nav.dirs[doff+length-1].pos+1, ui.wins[woff+length-1].x+1)
}
} }
func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) { func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) {
binds = make(map[string]expr) binds = make(map[string]expr)
for key, expr := range keys { for key, expr := range keys {
if strings.HasPrefix(key, prefix) { if !strings.HasPrefix(key, prefix) {
binds[key] = expr continue
if key == prefix { }
ok = true binds[key] = expr
} if key == prefix {
ok = true
} }
} }
return return
@@ -697,25 +789,49 @@ func listBinds(binds map[string]expr) *bytes.Buffer {
return b return b
} }
func listMarks(marks map[string]string) *bytes.Buffer {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
var keys []string
for k := range marks {
keys = append(keys, k)
}
sort.Strings(keys)
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "mark\tpath")
for _, k := range keys {
fmt.Fprintf(t, "%s\t%s\n", k, marks[k])
}
t.Flush()
return b
}
func (ui *ui) pollEvent() termbox.Event { func (ui *ui) pollEvent() termbox.Event {
select { select {
case key := <-ui.keyChan: case key := <-ui.keyChan:
ev := termbox.Event{Type: termbox.EventKey} ev := termbox.Event{Type: termbox.EventKey}
if len(key) == 1 { if utf8.RuneCountInString(key) == 1 {
ev.Ch, _ = utf8.DecodeRuneInString(key) ev.Ch, _ = utf8.DecodeRuneInString(key)
} else { } else {
switch key { switch {
case "<lt>": case key == "<lt>":
ev.Ch = '<' ev.Ch = '<'
case "<gt>": case key == "<gt>":
ev.Ch = '>' ev.Ch = '>'
case reAltKey.MatchString(key):
match := reAltKey.FindStringSubmatch(key)[1]
ev.Ch, _ = utf8.DecodeRuneInString(match)
ev.Mod = termbox.ModAlt
default: default:
if val, ok := gValKey[key]; ok { if val, ok := gValKey[key]; ok {
ev.Key = val ev.Key = val
} else { } else {
ev.Key = termbox.KeyEsc ev.Key = termbox.KeyEsc
ui.printf("unknown key: %s", key) ui.echoerrf("unknown key: %s", key)
} }
} }
} }
@@ -726,17 +842,9 @@ func (ui *ui) pollEvent() termbox.Event {
} }
} }
func readCmdEvent(ch chan<- expr, ev termbox.Event) { // This function is used to read a normal event on the client side. For keys,
if ev.Ch != 0 { // digits are interpreted as command counts but this is only done for digits
ch <- &callExpr{"cmd-insert", []string{string(ev.Ch)}, 1} // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k").
} else {
val := gKeyVal[ev.Key]
if expr, ok := gOpts.cmdkeys[string(val)]; ok {
ch <- expr
}
}
}
func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) { func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
draw := &callExpr{"draw", nil, 1} draw := &callExpr{"draw", nil, 1}
count := 1 count := 1
@@ -746,9 +854,11 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
if ev.Ch != 0 { if ev.Ch != 0 {
switch { switch {
case ev.Ch == '<': case ev.Ch == '<':
ui.keyAcc = append(ui.keyAcc, '<', 'l', 't', '>') ui.keyAcc = append(ui.keyAcc, []rune("<lt>")...)
case ev.Ch == '>': case ev.Ch == '>':
ui.keyAcc = append(ui.keyAcc, '<', 'g', 't', '>') ui.keyAcc = append(ui.keyAcc, []rune("<gt>")...)
case ev.Mod == termbox.ModAlt:
ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', ev.Ch, '>')
case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0: case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0:
ui.keyCount = append(ui.keyCount, ev.Ch) ui.keyCount = append(ui.keyCount, ev.Ch)
default: default:
@@ -756,12 +866,14 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
} }
} else { } else {
val := gKeyVal[ev.Key] val := gKeyVal[ev.Key]
if string(val) == "<esc>" { if val == "<esc>" {
ch <- draw ch <- draw
ui.keyAcc = nil ui.keyAcc = nil
ui.keyCount = nil ui.keyCount = nil
ui.menuBuf = nil
return
} }
ui.keyAcc = append(ui.keyAcc, val...) ui.keyAcc = append(ui.keyAcc, []rune(val)...)
} }
if len(ui.keyAcc) == 0 { if len(ui.keyAcc) == 0 {
@@ -773,12 +885,12 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
switch len(binds) { switch len(binds) {
case 0: case 0:
ui.printf("unknown mapping: %s", string(ui.keyAcc)) ui.echoerrf("unknown mapping: %s", string(ui.keyAcc))
ch <- draw ch <- draw
ui.keyAcc = nil ui.keyAcc = nil
ui.keyCount = nil ui.keyCount = nil
ui.menuBuf = nil ui.menuBuf = nil
case 1: default:
if ok { if ok {
if len(ui.keyCount) > 0 { if len(ui.keyCount) > 0 {
c, err := strconv.Atoi(string(ui.keyCount)) c, err := strconv.Atoi(string(ui.keyCount))
@@ -786,35 +898,11 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
log.Printf("converting command count: %s", err) log.Printf("converting command count: %s", err)
} }
count = c count = c
} else {
count = 1
} }
expr := gOpts.keys[string(ui.keyAcc)] expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok { if e, ok := expr.(*callExpr); ok {
e.count = count e.count = count
} } else if e, ok := expr.(*listExpr); ok {
ch <- expr
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
} else {
ui.menuBuf = listBinds(binds)
ch <- draw
}
default:
if ok {
// TODO: use a delay
if len(ui.keyCount) > 0 {
c, err := strconv.Atoi(string(ui.keyCount))
if err != nil {
log.Printf("converting command count: %s", err)
}
count = c
} else {
count = 1
}
expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok {
e.count = count e.count = count
} }
ch <- expr ch <- expr
@@ -828,14 +916,27 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
} }
case termbox.EventResize: case termbox.EventResize:
ch <- &callExpr{"redraw", nil, 1} ch <- &callExpr{"redraw", nil, 1}
default:
// TODO: handle other events
} }
} }
// This function is used to read expressions on the client side. Digits are func readCmdEvent(ch chan<- expr, ev termbox.Event) {
// interpreted as command counts but this is only done for digits preceding any if ev.Ch != 0 {
// non-digit characters (e.g. "42y2k" as 42 times "y2k"). if ev.Mod == termbox.ModAlt {
val := string([]rune{'<', 'a', '-', ev.Ch, '>'})
if expr, ok := gOpts.cmdkeys[val]; ok {
ch <- expr
}
} else {
ch <- &callExpr{"cmd-insert", []string{string(ev.Ch)}, 1}
}
} else {
val := gKeyVal[ev.Key]
if expr, ok := gOpts.cmdkeys[val]; ok {
ch <- expr
}
}
}
func (ui *ui) readExpr() <-chan expr { func (ui *ui) readExpr() <-chan expr {
ch := make(chan expr) ch := make(chan expr)
@@ -859,6 +960,14 @@ func (ui *ui) readExpr() <-chan expr {
return ch return ch
} }
func setColorMode() {
if gOpts.color256 {
termbox.SetOutputMode(termbox.Output256)
} else {
termbox.SetOutputMode(termbox.OutputNormal)
}
}
func (ui *ui) pause() { func (ui *ui) pause() {
termbox.Close() termbox.Close()
} }