Compare commits

279 Commits
r8 ... r21
Author SHA1 Message Date
Gokcehan 1544d62206 update readme 2021-02-27 23:16:27 +03:00
Gokcehan 8742f25706 update doc 2021-02-27 22:56:18 +03:00
Gokcehan ced1ccd0c3 update doc 2021-02-22 01:45:48 +03:00
Gokcehan 7dfdcb51c0 unset shellopts when empty 2021-02-21 19:21:06 +03:00
Gokcehan 2c3cd35a5d use x/term instead of stty/pause to prompt any key
cc #480
2021-02-21 18:01:20 +03:00
Gokcehan c071e37316 cleanup 2021-02-21 17:48:23 +03:00
Gokcehan 4c0efdcb41 use suspend/resume api in tcell v2.2.0
cc #480
2021-02-21 17:34:38 +03:00
Gokcehan 1b93f2232e show number of selected/saved files in status line
cc #143
2021-02-13 17:45:18 +03:00
Gokcehan 9ec336fcdb update doc
cc #581
2021-02-12 20:54:18 +03:00
Nikita 6422bd7492 Fix symlink handling (#581)
* Fix replace dialog for symlinks

If the oldPath is a symlink to the newPath or vice versa, than os.Stat()
would resolve this symlink, and both the oldStat and newStat would be
the same. Hence, the replace dialog would not appear and the newPath
file would be overwritten by the oldPath file whilst the oldPath would
be deleted.

It is the same story when the oldPath and newPath are both symlinks to
the same file.

* Fix completion in the case of broken symlinks

If the current directory contains broken symlinks then matchFile() would
return at first broken symlink.

Let's consider the following example:

$ ls -F ~/
broken@ dir/ file

The broken@ is a symlink to ~/foo - non existent file.

If one would enter the following command in lf:

:cd ~/<tab>

it would not suggest possible completion options because matchFile()
would return as soon as it meet the broken symlink.

* Don't resolve symlinks when move files/dirs (#571)

This will allow to move broken symlinks.

* Fix symlinks copying/moving (#571)

Copy symlinks, do not try to resolve it and copy the file pointed by
this symlink. Also this allows to copy symlink to directory.
2021-02-12 20:50:48 +03:00
Gokcehan 60d6119858 add link/user/group to statline when available
cc #365
2021-02-12 16:01:54 +03:00
Gokcehan 3e403bb888 update sigpipe error fix in the doc 2021-02-06 00:19:09 +03:00
Gokcehan 9d451ffd19 use ascii space/digits in scanner
cc #572
2021-01-30 18:29:32 +03:00
Gokcehan 2aa50aecaf show unknown mapping error for unbind mouse events
cc #268 #570
2021-01-29 19:47:28 +03:00
Gokcehan 13d19d84f9 add 'mouse' option to enable/disable mouse events
cc #268 #570
2021-01-29 19:36:27 +03:00
neeshy 1163efb7aa Avoid redundantly loading previews for search/find (#569)
* Avoid redundantly loading previews for find

* Avoid redundantly loading previews for search
2021-01-29 18:27:27 +03:00
Gokcehan c6cf0e61ba only combine non-spacing mark characters
cc #565
2021-01-27 02:22:40 +03:00
Gokcehan ea1ff74e55 update doc 2021-01-24 16:33:49 +03:00
neeshy 873cfe87a1 Reduce declaration and assignment (#564)
Some code cleanup for #562
2021-01-21 01:01:49 +03:00
neeshy 3f66f08b84 Exhaust queued entries in previewChan prior to calling preview script (#562)
* Use ranged for loop over channel

And rename variable "path" to "prev"

* Exhaust queued entries in previewChan prior to calling preview script
2021-01-19 04:42:01 +03:00
Gokcehan cb6ae713b4 update readme 2021-01-19 01:53:13 +03:00
Gokcehan e0317611ef avoid loading redundant previews for top/bottom
cc #531
2021-01-19 01:47:09 +03:00
Gokcehan 7481040c2d enable top/bottom in cmap mappings 2021-01-19 01:45:42 +03:00
Gokcehan a13c14fb07 add support for mouse buttons and wheels
cc #268
2021-01-19 01:20:34 +03:00
Gokcehan af988284a4 update doc 2021-01-18 23:44:26 +03:00
Gokcehan f54acae958 avoid loading redundant previews for up/down
cc #531
2021-01-18 21:30:52 +03:00
Gokcehan 2af2c6de31 fix tab character when printing
cc #496
2021-01-18 21:27:34 +03:00
Gokcehan d6c5590ad0 display combining characters in the text
cc #496
2021-01-18 20:48:31 +03:00
gotroyb127 d27748e9b5 minor doc fix (#560)
Related #545
2021-01-18 19:02:51 +03:00
Gokcehan 1f9c0b1d4c update doc 2021-01-11 00:42:47 +03:00
Gokcehan 2e4ed8f867 fix default promptfmt to use %d instead of %w
cc #545
2021-01-11 00:40:14 +03:00
SPFab 07d42c9a80 Added new Promptfmt Option to remove trailing separator (#545)
* Added new Promptfmt Option to remove trailing seperator

* Small fix

* small fix with multiple format options
also renamed the format options
2021-01-11 00:37:41 +03:00
Gokcehan 9f8bbe26e2 add trailing star to match names for colors/icons
cc #543
2021-01-07 01:17:56 +03:00
Marius 8e09df5969 Allow multiple -command flags (#552) 2021-01-07 01:10:54 +03:00
neeshy b5f6f6edee Don't redraw volatile previews on ticker period (#546) 2021-01-04 17:01:29 +03:00
Eduard Ganiukov d62dd9353f client: use PID as a client ID (#550)
Fixes: #549
2021-01-03 01:58:01 +03:00
Gokcehan 42eb27823e consider icons/numbers when showing info
cc #548
2021-01-03 01:53:06 +03:00
Gokcehan ab6c00c73d update doc
cc #531
2021-01-03 01:35:30 +03:00
Gokcehan bfa527fcea fix order of color/icon matches
cc #543
2021-01-03 01:02:40 +03:00
neeshy 1e94f4533e Guarantee preview/previewClear ordering (#537)
* Use chan struct{} in place of chan bool

* Revert "nav.checkReg now returns a boolean instead of calling nav.preview"

* Guarantee preview/previewClear ordering

* Pass the file path to the cleaner script
2020-12-27 04:23:03 +03:00
Gokcehan 72567c9237 update doc
Related #505
2020-12-27 03:27:33 +03:00
Gokcehan 3b78309b89 parse LF_COLORS variable for lf specific colors 2020-12-26 21:25:35 +03:00
Gokcehan d81b9eb858 parse env variables cumulatively for colors/icons 2020-12-26 21:24:35 +03:00
Gokcehan ae79db38da cleanup 2020-12-26 21:14:06 +03:00
Gokcehan 99d6b7fd44 match extension before type for colors/icons
Related #505
2020-12-26 20:39:41 +03:00
Marius 3dc7ec69ba make sortby ext work as expected (#539) 2020-12-26 16:36:43 +03:00
neeshy 82f03102a5 Add ability to use image previewers (#531)
* Return early on error in nav.preview

* nav.checkReg now returns a boolean instead of calling nav.preview

* Pass width, height, x, and y parameters to preview script

* Check previewer for exit code

If non-zero the preview will be assumed to have side-effects.

* Add the cleaner option

This is called upon selection changes if the previous preview was
volatile. To this end, volatilePreview was added to the nav struct
2020-12-24 16:13:20 +03:00
Gokcehan c2fe88e9a0 cleanup 2020-12-24 15:49:01 +03:00
sitiom f7c504493f Add PowerShell autocompletion script (#535)
* Add PowerShell autocompletion script

* Update lf.ps1
2020-12-24 15:45:12 +03:00
Gokcehan 42ef82b2c8 only clean full paths for colors/icons
Related #505
2020-12-24 15:42:36 +03:00
Gokcehan 9255408000 clean path in patterns in colors/icons
Related #505
2020-12-24 03:30:11 +03:00
Gokcehan e4e11e5507 update fish keybinding example
Related #499
2020-12-24 02:44:08 +03:00
Gokcehan eedcc258c2 cleanup 2020-12-24 02:28:25 +03:00
sitiom e7f5f90b0c Add PowerShell keybinding example for lfcd (#532)
* Add PowerShell keybinding example

* Update lfcd.ps1
2020-12-24 01:21:35 +03:00
Gokcehan de691bf4e8 match trailing slash as dirs in colors/icons
Related #505 #506
2020-12-24 01:04:13 +03:00
Gokcehan 1aed76c10d match path/name/base patterns in colors/icons
Related #505 #506
2020-12-23 04:55:10 +03:00
Gokcehan 4438721488 fix build on windows 2020-12-19 18:05:21 +03:00
Gokcehan 9e5d386304 golint 2020-12-19 17:56:27 +03:00
Gokcehan ed5104cfdb update doc 2020-12-19 17:25:44 +03:00
Gokcehan fd688c675b remove deprecated color256 option 2020-12-19 16:59:09 +03:00
Gokcehan 851e079a82 Fix colors for BSD style LSCOLORS for tcell/v2
Related #526
2020-12-19 02:11:38 +03:00
Gokcehan cae9ada56c update doc 2020-12-11 17:07:34 +03:00
Gokcehan 6f525ba047 cleanup 2020-12-11 16:47:56 +03:00
Gokcehan f9382f72d4 update doc 2020-12-11 16:36:03 +03:00
neeshy c1814c8a4e Fix issue on *NIX where server dies when controlling terminal is closed (#517) 2020-12-11 16:34:11 +03:00
Gokcehan 90b3b166e1 import tcell/v2 from gitlab.com/Provessor/lfp 2020-12-04 23:59:12 +03:00
Marius 73d1a81d85 Fix default promptfmt in documentation (#509)
%w already has a trailing slash
see: https://github.com/gokcehan/lf/blob/f68406b93c35fcb8abfdbb3768192b4d15a25d52/opts.go#L92
2020-11-27 22:12:55 +03:00
Gokcehan 5d204a1331 avoid reloading previews modified in the future
Related #453
2020-11-25 23:43:30 +03:00
Gokcehan 654a14ea7d lazy drawing in shell-pipe commands 2020-11-23 00:13:31 +03:00
Gokcehan ce5c5845e7 use year instead of hh:mm for old files in info
Related #507
2020-11-22 17:18:17 +03:00
Gokcehan c629b3d4ce fix race when options are changed while sorting
Related #502
2020-11-18 22:46:59 +03:00
Gokcehan 8dd4be0ddb change fish keybinding example
Related #499
2020-11-14 00:28:13 +03:00
Gokcehan 3db3445822 add bash completion script 2020-11-09 01:49:13 +03:00
Gokcehan fa5623fca8 add example configuration files for windows
Related #431
2020-11-08 16:56:01 +03:00
Gokcehan 65e593b68f initialize ignorecase/ignoredia for loading dirs
Related #478
2020-11-07 01:13:11 +03:00
Gokcehan 70ec01fc3b fix crash for 'bottom' at startup
Related #498
2020-11-06 20:51:31 +03:00
Gokcehan 8eb596c670 update doc
Related #499
2020-11-06 20:25:31 +03:00
Gokcehan d46ccfc805 resort directories if ignorecase/ignoredia change
Related #320
2020-11-06 20:10:54 +03:00
Gokcehan e8f115848f avoid reloading directories modified in the future
Related #453
2020-11-06 19:57:27 +03:00
Gokcehan f68406b93c enable 'ignoredia' by default
Related #320
2020-11-06 16:03:02 +03:00
Gokcehan c2f2d54cee apply 'ignorecase' and 'ignoredia' to sorting
Related #320
2020-11-06 16:02:58 +03:00
Gokcehan 24489924b7 avoid memory allocations in natural sorting 2020-11-06 15:14:38 +03:00
Gokcehan f877960661 go fmt 2020-11-06 15:14:26 +03:00
Gokcehan 279b0cf250 fix logging when setting 'info' option to empty 2020-10-27 03:07:38 +03:00
Gokcehan f69c24e357 handle signals properly
Related #485
2020-10-21 00:31:04 +03:00
Jonathan Neidel e1cabfbf56 Fix typo (#487)
depreciated -> deprecated
2020-10-17 22:56:22 +03:00
Gokcehan 6fa6137124 cleanup
Related #482
2020-10-14 22:03:25 +03:00
2pacand2pac 17ed724e67 Completition menu cycling #72 (#482)
* utility modulus function

* ui adapt for tab menu cycle

* refactor(listMatches) for tab menu cycle

* refactor(draw) handle tab menu selection highlight

* refactor(eval) cmd-complete cycle + reset handles

* feat: added backtab counter-cycle in the completition menu

* cleanup

* docs changes

* refactor: make tab cycle own commands

* docs: tab cycle documentation

* bug: the matches list was not complete because index +2 after row end

* refactor(tab cycle): handle the complete menu command print

* refactor(tab cycle): make the cmdTmp varibale mymic cmdAccLeft + check for partial commands

* refactor(tab cycle): fix how to handle the menu completiton from different events

* fix(tab cycle): fix cmd-complete so that it works with new tab cycle commands

* style: changed puprle to reverse

* cleaned up cycle logic + reverted listMatches

* cleaned up eval logic for cycle feat.

* cleanup

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

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

* move related functions to main.go

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

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

This also has a test to mitigate it in the future

Remove `colormode` option

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

retire gitter channel in favor of irc/matrix

Export options as environment variables (#448)

* Export options as environment variables

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

* Do not export some of the options

* Add support for arrays and fix numbers

* Fix comments

* Replace 1 and 0 with true and false

* Export hidden,reverse,dirfirst and sortby options

* Fix comments

* Little fix

* Simplify boolean conversion

log readlink errors instead of fail

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

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

* Do not export some of the options

* Add support for arrays and fix numbers

* Fix comments

* Replace 1 and 0 with true and false

* Export hidden,reverse,dirfirst and sortby options

* Fix comments

* Little fix

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

* Print message only when there's no errors

* Don't print number of copied files

* Fix error handling

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

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

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

* Add ability to set truncatechar via `set` command

* Add completion for truncatechar option

* Actually use truncatechar option when truncating

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

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

* harden and improve syntax

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

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

* Changed where appropriate so that tilde replacements happens correctly.

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

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

* Do not handle SIGINT

* Cancel current copy/move/delete operation

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

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

* rename lf-complete.csh to lf.csh

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

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

* Reversed some sloppy new lines from previous commit

* Move delete operations to delete.go

* Simplify to use RemoveAll before

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

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

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

* mkdirAll if necessary

* updated TODO's

* rename with replace prompting

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

* renewing now (no set period is needed)

* documentation, keybidning change, load file info after renaming

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

* loadfileinfo after prompts too

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

* Revert "markclear"

This reverts commit 5e3a188618.

* Revert "Revert "markclear""

This reverts commit a7a3bfebbf.

* markclear with arguments

* docs

* reverted some whitepsace

* some inline comments

* additional error handling

* wrong argument case

* consider case when argument specified clears all marks

* code cleanup and removed readMarks from writeMarks

* indentation :/

* discussed changes implemnted

* return readMarks error in sync()

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

* documentation

* indentation

* indentation

* indentation

* save

* merge glob selects

* check if selected before toggling

* glob-unselect

* identation ...

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

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

No files matched your search

+5 -2
View File
@@ -1,8 +1,11 @@
language: go language: go
install:
- go get github.com/nsf/termbox-go go:
- 1.15.x
before_deploy: before_deploy:
- gen/xbuild.sh - gen/xbuild.sh
deploy: deploy:
provider: releases provider: releases
api_key: api_key:
Generated
-21
View File
@@ -1,21 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
branch = "master"
name = "github.com/mattn/go-runewidth"
packages = ["."]
revision = "ce7b0b5c7b45a81508558cd1dba6bb1e4ddb51bb"
[[projects]]
branch = "master"
name = "github.com/nsf/termbox-go"
packages = ["."]
revision = "5c94acc5e6eb520f1bcd183974e01171cc4c23b3"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "8508b73787d4948edb76ccc25789c311a4ab84d4c8c0b96b267857e2e88d974e"
solver-name = "gps-cdcl"
solver-version = 1
-38
View File
@@ -1,38 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[[constraint]]
branch = "master"
name = "github.com/mattn/go-runewidth"
[[constraint]]
branch = "master"
name = "github.com/nsf/termbox-go"
[prune]
go-tests = true
unused-packages = true
+17 -11
View File
@@ -7,8 +7,7 @@
[![Build Status](https://travis-ci.org/gokcehan/lf.svg?branch=master)](https://travis-ci.org/gokcehan/lf) [![Build Status](https://travis-ci.org/gokcehan/lf.svg?branch=master)](https://travis-ci.org/gokcehan/lf)
[![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf) [![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf)
[![GoDoc](https://godoc.org/github.com/gokcehan/lf?status.svg)](https://godoc.org/github.com/gokcehan/lf) [![Go Reference](https://pkg.go.dev/badge/github.com/gokcehan/lf.svg)](https://pkg.go.dev/github.com/gokcehan/lf)
[![Join the chat at https://gitter.im/lf-fm/Lobby](https://badges.gitter.im/lf-fm/Lobby.svg)](https://gitter.im/lf-fm/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> This is a work in progress. Use at your own risk. > This is a work in progress. Use at your own risk.
@@ -34,21 +33,28 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tut
- Tabs or windows (handled by window manager or terminal multiplexer) - Tabs or windows (handled by window manager or terminal multiplexer)
- Builtin pager/editor (handled by your pager/editor of choice) - Builtin pager/editor (handled by your pager/editor of choice)
- Image previews (cool but no standard available)
## May-Futures
- Mouse control
## Installation ## Installation
See [packages](https://github.com/gokcehan/lf/wiki/Packages) for community maintained packages.
See [releases](https://github.com/gokcehan/lf/releases) for pre-built binaries. See [releases](https://github.com/gokcehan/lf/releases) for pre-built binaries.
If you like to build from the source: If you like to build from the source on unix:
go get -u github.com/gokcehan/lf env CGO_ENABLED=0 GO111MODULE=on go get -u -ldflags="-s -w" github.com/gokcehan/lf
See [packages](https://github.com/gokcehan/lf/wiki/Packages) for community maintained packages. On windows `cmd`:
set CGO_ENABLED=0
set GO111MODULE=on
go get -u -ldflags="-s -w" github.com/gokcehan/lf
On windows `powershell`:
$env:CGO_ENABLED = '0'
$env:GO111MODULE = 'on'
go get -u -ldflags="-s -w" github.com/gokcehan/lf
## Usage ## Usage
@@ -56,7 +62,7 @@ After the installation `lf` command should start the application in the current
Run `lf -help` to see command line options. Run `lf -help` to see command line options.
Run `lf -doc` to see the [documentation](https://godoc.org/github.com/gokcehan/lf). Run `lf -doc` to see the [documentation](https://pkg.go.dev/github.com/gokcehan/lf).
See [etc](etc) directory to integrate `lf` to your shell or editor. See [etc](etc) directory to integrate `lf` to your shell or editor.
An example configuration file can also be found in this directory. An example configuration file can also be found in this directory.
+193 -84
View File
@@ -7,9 +7,10 @@ import (
"log" "log"
"os" "os"
"os/exec" "os/exec"
"os/signal"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"syscall"
"time" "time"
) )
@@ -22,7 +23,7 @@ type app struct {
ui *ui ui *ui
nav *nav nav *nav
ticker *time.Ticker ticker *time.Ticker
quitChan chan bool quitChan chan struct{}
cmd *exec.Cmd cmd *exec.Cmd
cmdIn io.WriteCloser cmdIn io.WriteCloser
cmdOutBuf []byte cmdOutBuf []byte
@@ -31,16 +32,31 @@ type app struct {
cmdHistoryInd int cmdHistoryInd int
} }
func newApp() *app { func newApp(ui *ui, nav *nav) *app {
ui := newUI() quitChan := make(chan struct{}, 1)
nav := newNav(ui.wins[0].h)
return &app{ app := &app{
ui: ui, ui: ui,
nav: nav, nav: nav,
ticker: new(time.Ticker), ticker: new(time.Ticker),
quitChan: make(chan bool, 1), quitChan: quitChan,
} }
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM)
go func() {
switch <-sigChan {
case os.Interrupt:
return
case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM:
app.writeHistory()
os.Remove(gLogPath)
os.Exit(3)
return
}
}()
return app
} }
func (app *app) readFile(path string) { func (app *app) readFile(path string) {
@@ -48,7 +64,7 @@ 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()
@@ -60,7 +76,7 @@ func (app *app) readFile(path string) {
} }
if p.err != nil { if p.err != nil {
app.ui.printf("%s", p.err) app.ui.echoerrf("%s", p.err)
} }
} }
@@ -77,6 +93,12 @@ func (app *app) readHistory() error {
scanner := bufio.NewScanner(f) scanner := bufio.NewScanner(f)
for scanner.Scan() { for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2) toks := strings.SplitN(scanner.Text(), " ", 2)
if toks[0] != ":" && toks[0] != "$" && toks[0] != "%" && toks[0] != "!" && toks[0] != "&" {
continue
}
if len(toks) < 2 {
continue
}
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]}) app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
} }
@@ -133,18 +155,65 @@ func (app *app) writeHistory() error {
// for evaluation. Similarly directories and regular files are also read in // for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update. // separate goroutines and sent here for update.
func (app *app) loop() { func (app *app) loop() {
clientChan := app.ui.readExpr() go app.nav.previewLoop(app.ui)
serverChan := readExpr() serverChan := readExpr()
app.ui.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)
}
}
for _, cmd := range gCommands {
p := newParser(strings.NewReader(cmd))
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:
log.Print("bye!") if app.nav.copyTotal > 0 {
app.ui.echoerr("quit: copy operation in progress")
if err := app.nav.writeMarks(); err != nil { continue
log.Printf("writing marks file: %s", err)
} }
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
}
app.nav.previewChan <- ""
log.Print("bye!")
if err := app.writeHistory(); err != nil { if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err) log.Printf("writing history file: %s", err)
} }
@@ -156,16 +225,62 @@ 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.ind = prev.ind d.ind = prev.ind
@@ -185,7 +300,7 @@ func (app *app) loop() {
curr, err := app.nav.currFile() curr, err := app.nav.currFile()
if err == nil { if err == nil {
if d.path == app.nav.currDir().path { if d.path == app.nav.currDir().path {
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav, true)
} }
if d.path == curr.path { if d.path == curr.path {
app.ui.dirPrev = d app.ui.dirPrev = d
@@ -194,6 +309,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()
@@ -204,7 +321,27 @@ func (app *app) loop() {
} }
app.ui.draw(app.nav) app.ui.draw(app.nav)
case e := <-clientChan: case ev := <-app.ui.evChan:
e := app.ui.readEvent(ev)
if e == nil {
continue
}
e.eval(app, nil)
loop:
for {
select {
case ev := <-app.ui.evChan:
e = app.ui.readEvent(ev)
if e == nil {
continue
}
e.eval(app, nil)
default:
break loop
}
}
app.ui.draw(app.nav)
case e := <-app.ui.exprChan:
e.eval(app, nil) e.eval(app, nil)
app.ui.draw(app.nav) app.ui.draw(app.nav)
case e := <-serverChan: case e := <-serverChan:
@@ -212,60 +349,21 @@ func (app *app) loop() {
app.ui.draw(app.nav) app.ui.draw(app.nav)
case <-app.ticker.C: case <-app.ticker.C:
app.nav.renew() app.nav.renew()
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav, false)
app.ui.draw(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
} }
selections := app.nav.currSelections() currSelections := app.nav.currSelections()
envFiles := strings.Join(selections, gOpts.filesep) exportFiles(currFile, currSelections)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(selections) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
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 waitKey() error {
cmd := pauseCommand()
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("waiting key: %s", err)
}
return nil
} }
// This function is used to run a shell command. Modes are as follows: // This function is used to run a shell command. Modes are as follows:
@@ -276,20 +374,25 @@ func waitKey() error {
// ! 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()
exportOpts()
cmd := shellCommand(s, args) cmd := shellCommand(s, args)
var out io.Reader var out io.Reader
var err error
switch prefix { switch prefix {
case "$", "!": case "$", "!":
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
app.ui.pause() app.nav.previewChan <- ""
app.ui.suspend()
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 {
@@ -302,49 +405,49 @@ 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 { anyKey()
app.ui.printf("waiting key: %s", err)
}
} }
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav, true)
app.ui.loadFileInfo(app.nav)
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() {
eol := false
reader := bufio.NewReader(out) reader := bufio.NewReader(out)
for { for {
b, err := reader.ReadByte() b, err := reader.ReadByte()
if err == io.EOF { if err == io.EOF {
break break
} }
app.cmdOutBuf = append(app.cmdOutBuf, b) if eol {
app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1} eol = false
if b == '\n' || b == '\r' {
app.cmdOutBuf = nil app.cmdOutBuf = nil
} }
app.cmdOutBuf = append(app.cmdOutBuf, b)
if b == '\n' || b == '\r' {
eol = true
}
if reader.Buffered() > 0 {
continue
}
app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1}
} }
if err := cmd.Wait(); err != nil { if err := cmd.Wait(); err != nil {
@@ -354,5 +457,11 @@ func (app *app) runShell(s string, args []string, prefix string) {
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"load", nil, 1} app.ui.exprChan <- &callExpr{"load", nil, 1}
}() }()
case "&":
go func() {
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
}()
} }
} }
+21 -19
View File
@@ -10,10 +10,21 @@ import (
"strings" "strings"
"time" "time"
"github.com/nsf/termbox-go" "github.com/gdamore/tcell/v2"
) )
func run() { func run() {
var screen tcell.Screen
var err error
if screen, err = tcell.NewScreen(); err != nil {
log.Fatalf("creating screen: %s", err)
} else if err = screen.Init(); err != nil {
log.Fatalf("initializing screen: %s", err)
}
if gOpts.mouse {
screen.EnableMouse()
}
f, err := os.Create(gLogPath) f, err := os.Create(gLogPath)
if err != nil { if err != nil {
panic(err) panic(err)
@@ -24,30 +35,21 @@ func run() {
log.Print("hi!") log.Print("hi!")
if err := termbox.Init(); err != nil { ui := newUI(screen)
log.Fatalf("initializing termbox: %s", err) nav := newNav(ui.wins[0].h)
} app := newApp(ui, nav)
defer termbox.Close()
termbox.SetOutputMode(termbox.Output256)
app := newApp()
for _, path := range gConfigPaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
app.readFile(path)
}
}
if err := app.nav.readMarks(); err != nil { if err := app.nav.readMarks(); err != nil {
app.ui.printf("reading marks file: %s", err) app.ui.echoerrf("reading marks file: %s", err)
} }
if err := app.readHistory(); err != nil { if err := app.readHistory(); err != nil {
app.ui.printf("reading history file: %s", err) app.ui.echoerrf("reading history file: %s", err)
} }
app.loop() app.loop()
app.ui.screen.Fini()
} }
func readExpr() <-chan expr { func readExpr() <-chan expr {
@@ -58,7 +60,7 @@ func readExpr() <-chan expr {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
for err != nil { for err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err)) log.Printf("connecting server: %s", err)
time.Sleep(duration) time.Sleep(duration)
duration *= 2 duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath) c, err = net.Dial(gSocketProt, gSocketPath)
@@ -146,7 +148,7 @@ func loadFiles() (list []string, cp 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)
+188 -141
View File
@@ -7,76 +7,75 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/nsf/termbox-go" "github.com/gdamore/tcell/v2"
) )
const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse type styleMap map[string]tcell.Style
var gAnsiCodes = map[int]termbox.Attribute{ func parseStyles() styleMap {
0: termbox.ColorDefault, sm := make(styleMap)
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 { // Default values from dircolors
fg termbox.Attribute //
bg termbox.Attribute // no* NORMAL 00
} // fi FILE 00
// rs* RESET 0
// di DIR 01;34
// ln LINK 01;36
// mh* MULTIHARDLINK 00
// pi FIFO 40;33
// so SOCK 01;35
// do* DOOR 01;35
// bd BLK 40;33;01
// cd CHR 40;33;01
// or ORPHAN 40;31;01
// mi* MISSING 00
// su SETUID 37;41
// sg SETGID 30;43
// ca* CAPABILITY 30;41
// tw STICKY_OTHER_WRITABLE 30;42
// ow OTHER_WRITABLE 34;42
// st STICKY 37;44
// ex EXEC 01;32
//
// (Entries marked with * are not implemented in lf)
type colorMap map[string]colorEntry // default values from dircolors with background colors removed
func parseColors() colorMap {
if env := os.Getenv("LS_COLORS"); env != "" {
return parseColorsGNU(env)
}
if env := os.Getenv("LSCOLORS"); env != "" {
return parseColorsBSD(env)
}
// default values from dircolors
defaultColors := []string{ defaultColors := []string{
// "rs=0", "fi=00",
"di=01;34", "di=01;34",
"ln=01;36", "ln=01;36",
// "mh=00", "pi=33",
"pi=40;33",
"so=01;35", "so=01;35",
"do=01;35", "bd=33;01",
"bd=40;33;01", "cd=33;01",
"cd=40;33;01", "or=31;01",
"or=40;31;01", "su=01;32",
// "mi=00", "sg=01;32",
"su=37;41", "tw=01;34",
"sg=30;43", "ow=01;34",
"ca=30;41", "st=01;34",
"tw=30;42",
"ow=34;42",
"st=37;44",
"ex=01;32", "ex=01;32",
} }
return parseColorsGNU(strings.Join(defaultColors, ":")) sm.parseGNU(strings.Join(defaultColors, ":"))
if env := os.Getenv("LSCOLORS"); env != "" {
sm.parseBSD(env)
}
if env := os.Getenv("LS_COLORS"); env != "" {
sm.parseGNU(env)
}
if env := os.Getenv("LF_COLORS"); env != "" {
sm.parseGNU(env)
}
return sm
} }
func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, termbox.Attribute) { func applyAnsiCodes(s string, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";") toks := strings.Split(s, ";")
var nums []int var nums []int
@@ -93,149 +92,197 @@ func applyAnsiCodes(s string, fg, bg termbox.Attribute) (termbox.Attribute, term
nums = append(nums, n) nums = append(nums, n)
} }
// ECMA-48 details the standard
// TODO: should we support turning off attributes?
// Probably because this is used for previewers too
for i := 0; i < len(nums); i++ { for i := 0; i < len(nums); i++ {
n := nums[i] n := nums[i]
switch { switch {
case n == 38 && i+2 < len(nums) && nums[i+1] == 5:
fg &= gAnsiColorResetMask
fg |= termbox.Attribute(nums[i+2] + 1)
i += 2
continue
case n == 48 && i+2 < len(nums) && nums[i+1] == 5:
bg = termbox.Attribute(nums[i+2] + 1)
i += 2
continue
}
attr, ok := gAnsiCodes[n]
if !ok {
log.Printf("unknown ansi code: %d", n)
continue
}
switch {
case n == 0: case n == 0:
fg, bg = attr, attr st = tcell.StyleDefault
case n == 1 || n == 4 || n == 7: case n == 1:
fg |= attr st = st.Bold(true)
case 30 <= n && n <= 37: case n == 2:
fg &= gAnsiColorResetMask st = st.Dim(true)
fg |= attr case n == 4:
case 40 <= n && n <= 47: st = st.Underline(true)
bg = attr case n == 5 || n == 6:
st = st.Blink(true)
case n == 7:
st = st.Reverse(true)
case n == 8:
// TODO: tcell PR for proper conceal
_, bg, _ := st.Decompose()
st = st.Foreground(bg)
case n == 9:
st = st.StrikeThrough(true)
case n >= 30 && n <= 37:
st = st.Foreground(tcell.PaletteColor(n - 30))
case n == 38:
if i+3 <= len(nums) && nums[i+1] == 5 {
st = st.Foreground(tcell.PaletteColor(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
st = st.Foreground(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
int32(nums[i+4])))
i += 4
} else {
log.Printf("unknown ansi code or incorrect form: %d", n)
}
case n >= 40 && n <= 47:
st = st.Background(tcell.PaletteColor(n - 40))
case n == 48:
if i+3 <= len(nums) && nums[i+1] == 5 {
st = st.Background(tcell.PaletteColor(nums[i+2]))
i += 2
} else if i+5 <= len(nums) && nums[i+1] == 2 {
st = st.Background(tcell.NewRGBColor(
int32(nums[i+2]),
int32(nums[i+3]),
int32(nums[i+4])))
i += 4
} else {
log.Printf("unknown ansi code or incorrect form: %d", n)
}
default:
log.Printf("unknown ansi code: %d", n)
} }
} }
return fg, bg return st
} }
// This function parses $LS_COLORS environment variable. // This function parses $LS_COLORS environment variable.
func parseColorsGNU(env string) colorMap { func (sm styleMap) parseGNU(env string) {
colors := make(colorMap) for _, entry := range strings.Split(env, ":") {
entries := strings.Split(env, ":")
for _, entry := range entries {
if entry == "" { if entry == "" {
continue continue
} }
pair := strings.Split(entry, "=") pair := strings.Split(entry, "=")
if len(pair) != 2 { if len(pair) != 2 {
log.Printf("invalid $LS_COLORS entry: %s", entry) log.Printf("invalid $LS_COLORS entry: %s", entry)
return colors return
}
key, val := pair[0], pair[1]
fg, bg := applyAnsiCodes(val, termbox.ColorDefault, termbox.ColorDefault)
colors[key] = colorEntry{fg: fg, bg: bg}
} }
return colors key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
sm[key] = applyAnsiCodes(val, tcell.StyleDefault)
}
} }
// This function parses $LSCOLORS environment variable. // This function parses $LSCOLORS environment variable.
func parseColorsBSD(env string) colorMap { func (sm styleMap) parseBSD(env string) {
colors := make(colorMap)
if len(env) != 22 { if len(env) != 22 {
log.Printf("invalid $LSCOLORS variable: %s", env) log.Printf("invalid $LSCOLORS variable: %s", env)
return colors return
} }
colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"} colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"}
colorCodes := map[byte]termbox.Attribute{
'a': termbox.ColorBlack, getStyle := func(r1, r2 byte) tcell.Style {
'b': termbox.ColorRed, st := tcell.StyleDefault
'c': termbox.ColorGreen,
'd': termbox.ColorYellow, // brown switch {
'e': termbox.ColorBlue, case r1 == 'x':
'f': termbox.ColorMagenta, st = st.Foreground(tcell.ColorDefault)
'g': termbox.ColorCyan, case 'A' <= r1 && r1 <= 'H':
'h': termbox.ColorWhite, // light grey st = st.Foreground(tcell.PaletteColor(int(r1 - 'A'))).Bold(true)
'A': termbox.AttrBold | termbox.ColorBlack, case 'a' <= r1 && r1 <= 'h':
'B': termbox.AttrBold | termbox.ColorRed, st = st.Foreground(tcell.PaletteColor(int(r1 - 'a')))
'C': termbox.AttrBold | termbox.ColorGreen, default:
'D': termbox.AttrBold | termbox.ColorYellow, // brown log.Printf("invalid $LSCOLORS entry: %c", r1)
'E': termbox.AttrBold | termbox.ColorBlue, return tcell.StyleDefault
'F': termbox.AttrBold | termbox.ColorMagenta,
'G': termbox.AttrBold | termbox.ColorCyan,
'H': termbox.AttrBold | termbox.ColorWhite, // light grey
'x': termbox.ColorDefault,
} }
getColor := func(r byte) termbox.Attribute { switch {
if color, ok := colorCodes[r]; ok { case r2 == 'x':
return color st = st.Background(tcell.ColorDefault)
case 'a' <= r2 && r2 <= 'h':
st = st.Background(tcell.PaletteColor(int(r2 - 'a')))
default:
log.Printf("invalid $LSCOLORS entry: %c", r2)
return tcell.StyleDefault
} }
log.Printf("invalid $LSCOLORS entry: %c", r) return st
return termbox.ColorDefault
} }
for i, key := range colorNames { for i, key := range colorNames {
colors[key] = colorEntry{fg: getColor(env[i*2]), bg: getColor(env[i*2+1])} sm[key] = getStyle(env[i*2], env[i*2+1])
} }
return colors
} }
func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) { func (sm styleMap) get(f *file) tcell.Style {
if val, ok := sm[f.path]; ok {
return val
}
if f.IsDir() {
if val, ok := sm[f.Name()+"/"]; ok {
return val
}
}
var key string var key string
switch { 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: case f.linkState == working:
key = "ln" key = "ln"
case f.linkState == broken: case f.linkState == broken:
key = "or" key = "or"
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&0002 != 0:
key = "ow"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
case f.IsDir():
key = "di"
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:
key = "so" key = "so"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeDevice != 0: case f.Mode()&os.ModeDevice != 0:
key = "bd" key = "bd"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeSetuid != 0: case f.Mode()&os.ModeSetuid != 0:
key = "su" key = "su"
case f.Mode()&os.ModeSetgid != 0: case f.Mode()&os.ModeSetgid != 0:
key = "sg" key = "sg"
case f.Mode().IsRegular() && f.Mode()&0111 != 0: case f.Mode()&0111 != 0:
key = "ex" key = "ex"
default:
key = "*" + filepath.Ext(f.Name())
} }
if val, ok := cm[key]; ok { if val, ok := sm[key]; ok {
return val.fg, val.bg return val
} }
if val, ok := cm["fi"]; ok { if val, ok := sm[f.Name()+"*"]; ok {
return val.fg, val.bg return val
} }
return termbox.ColorDefault, termbox.ColorDefault if val, ok := sm[filepath.Base(f.Name())+".*"]; ok {
return val
}
if val, ok := sm["*"+f.ext]; ok {
return val
}
if val, ok := sm["fi"]; ok {
return val
}
return tcell.StyleDefault
} }
+51 -47
View File
@@ -3,75 +3,79 @@ package main
import ( import (
"testing" "testing"
"github.com/nsf/termbox-go" "github.com/gdamore/tcell/v2"
) )
func TestApplyAnsiCodes(t *testing.T) { func TestApplyAnsiCodes(t *testing.T) {
none := termbox.ColorDefault none := tcell.StyleDefault
tests := []struct { tests := []struct {
s string s string
fg termbox.Attribute st tcell.Style
bg termbox.Attribute stExp tcell.Style
fgExp termbox.Attribute
bgExp termbox.Attribute
}{ }{
{"", none, none, none, none}, {"", none, none},
{"", termbox.ColorRed, termbox.ColorRed, none, none}, {"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"", termbox.AttrBold, none, none, none}, {"", none.Bold(true), none},
{"", termbox.ColorRed | termbox.AttrBold, none, none, none}, {"", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"0", none, none, none, none}, {"0", none, none},
{"0", termbox.ColorRed, termbox.ColorRed, none, none}, {"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"0", termbox.AttrBold, none, none, none}, {"0", none.Bold(true), none},
{"0", termbox.ColorRed | termbox.AttrBold, none, none, none}, {"0", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"1", none, none, termbox.AttrBold, none}, {"1", none, none.Bold(true)},
{"4", none, none, termbox.AttrUnderline, none}, {"4", none, none.Underline(true)},
{"7", none, none, termbox.AttrReverse, none}, {"7", none, none.Reverse(true)},
{"1", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrBold, none}, {"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"4", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrUnderline, none}, {"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)},
{"7", termbox.ColorRed, none, termbox.ColorRed | termbox.AttrReverse, none}, {"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)},
{"4", termbox.AttrBold, none, termbox.AttrBold | termbox.AttrUnderline, none}, {"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", termbox.ColorRed | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold | termbox.AttrUnderline, none}, {"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"31", none, none, termbox.ColorRed, none}, {"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", termbox.ColorGreen, none, termbox.ColorRed, none}, {"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, {"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"41", none, none, none, termbox.ColorRed}, {"41", none, none.Background(tcell.ColorMaroon)},
{"41", none, termbox.ColorGreen, none, termbox.ColorRed}, {"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;31", none, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none, termbox.ColorBlack, none}, {"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none, termbox.ColorRed, none}, {"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none, termbox.Attribute(9), none}, {"38;5;8", none, none.Foreground(tcell.ColorGray)},
{"38;5;16", none, none, termbox.Attribute(17), none}, {"38;5;16", none, none.Foreground(tcell.Color16)},
{"38;5;232", none, none, termbox.Attribute(233), none}, {"38;5;232", none, none.Foreground(tcell.Color232)},
{"38;5;1", termbox.ColorGreen, none, termbox.ColorRed, none}, {"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"38;5;1", termbox.ColorGreen | termbox.AttrBold, none, termbox.ColorRed | termbox.AttrBold, none}, {"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"48;5;0", none, none, none, termbox.ColorBlack}, {"48;5;0", none, none.Background(tcell.ColorBlack)},
{"48;5;1", none, none, none, termbox.ColorRed}, {"48;5;1", none, none.Background(tcell.ColorMaroon)},
{"48;5;8", none, none, none, termbox.Attribute(9)}, {"48;5;8", none, none.Background(tcell.ColorGray)},
{"48;5;16", none, none, none, termbox.Attribute(17)}, {"48;5;16", none, none.Background(tcell.Color16)},
{"48;5;232", none, none, none, termbox.Attribute(233)}, {"48;5;232", none, none.Background(tcell.Color232)},
{"48;5;1", none, termbox.ColorGreen, none, termbox.ColorRed}, {"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;38;5;1", none, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;38;5;1", termbox.ColorGreen, none, termbox.ColorRed | termbox.AttrBold, none}, {"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))},
{"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))},
// Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446
{"38;5;34;1", none, none.Foreground(tcell.Color34).Bold(true)},
} }
for _, test := range tests { for _, test := range tests {
if fgGot, bgGot := applyAnsiCodes(test.s, test.fg, test.bg); fgGot != test.fgExp || bgGot != test.bgExp { if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%d' and '%d' expected '%d' and '%d' but got '%d' and '%d'", t.Errorf("at input '%s' with '%d' expected '%d' but got '%d'",
test.s, test.fg, test.bg, test.fgExp, test.bgExp, fgGot, bgGot) test.s, test.st, test.stExp, stGot)
} }
} }
} }
+100 -12
View File
@@ -32,11 +32,10 @@ var (
"cut", "cut",
"paste", "paste",
"clear", "clear",
"draw",
"redraw", "redraw",
"load",
"reload", "reload",
"read", "read",
"rename",
"shell", "shell",
"shell-pipe", "shell-pipe",
"shell-wait", "shell-wait",
@@ -50,13 +49,21 @@ var (
"search-next", "search-next",
"search-prev", "search-prev",
"mark-save", "mark-save",
"mark-remove",
"mark-load", "mark-load",
"draw",
"load",
"sync", "sync",
"echo", "echo",
"echomsg",
"echoerr",
"cd", "cd",
"select", "select",
"glob-select",
"glob-unselect",
"source", "source",
"push", "push",
"delete",
} }
gOptWords = []string{ gOptWords = []string{
@@ -78,35 +85,63 @@ var (
"hidden", "hidden",
"nohidden", "nohidden",
"hidden!", "hidden!",
"icons",
"noicons",
"icons!",
"ignorecase", "ignorecase",
"noignorecase", "noignorecase",
"ignorecase!", "ignorecase!",
"ignoredia",
"noignoredia",
"ignoredia!",
"incsearch",
"noincsearch",
"incsearch!",
"mouse",
"nomouse",
"mouse!",
"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", "findlen",
"period", "period",
"scrolloff", "scrolloff",
"tabstop", "tabstop",
"errorfmt",
"filesep", "filesep",
"hiddenfiles",
"ifs", "ifs",
"info",
"previewer", "previewer",
"cleaner",
"promptfmt", "promptfmt",
"ratios",
"shell", "shell",
"shellopts",
"sortby", "sortby",
"timefmt", "timefmt",
"ratios", "truncatechar",
"info",
"shellopts",
} }
) )
@@ -192,7 +227,7 @@ func matchExec(s string) (matches []string, longest string) {
} }
func matchFile(s string) (matches []string, longest string) { func matchFile(s string) (matches []string, longest string) {
dir := strings.Replace(s, "~", gUser.HomeDir, -1) dir := replaceTilde(s)
if !filepath.IsAbs(dir) { if !filepath.IsAbs(dir) {
wd, err := os.Getwd() wd, err := os.Getwd()
@@ -211,26 +246,32 @@ func matchFile(s string) (matches []string, longest string) {
} }
for _, f := range files { for _, f := range files {
f, err := os.Stat(filepath.Join(dir, f.Name())) name := filepath.Join(dir, f.Name())
f, err := os.Stat(name)
if err != nil { if err != nil {
fl, err := os.Lstat(name)
if err == nil && fl.Mode()&os.ModeSymlink != 0 {
continue
} else {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
return return
} }
}
_, last := filepath.Split(s) _, last := filepath.Split(s)
if !strings.HasPrefix(escape(f.Name()), last) { if !strings.HasPrefix(escape(f.Name()), last) {
continue continue
} }
name := f.Name() name = f.Name()
if isRoot(s) || filepath.Base(s) != s { if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(s), f.Name()) name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
} }
name = escape(name) name = escape(name)
item := f.Name() item := f.Name()
if f.Mode().IsDir() { if f.Mode().IsDir() {
item += string(filepath.Separator) item += escape(string(filepath.Separator))
} }
matches = append(matches, item) matches = append(matches, item)
@@ -240,7 +281,7 @@ func matchFile(s string) (matches []string, longest string) {
if f.Mode().IsRegular() { if f.Mode().IsRegular() {
longest = name + " " longest = name + " "
} else { } else {
longest = name + string(filepath.Separator) longest = name + escape(string(filepath.Separator))
} }
} }
} }
@@ -265,6 +306,15 @@ func completeCmd(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:
@@ -291,6 +341,44 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
return return
} }
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) { func completeShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
@@ -303,7 +391,7 @@ func completeShell(acc []rune) (matches []string, longestAcc []rune) {
longestAcc = []rune(longest) longestAcc = []rune(longest)
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...)
} }
return return
+137
View File
@@ -0,0 +1,137 @@
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
func copySize(srcs []string) (int64, error) {
var total int64
for _, src := range srcs {
_, err := os.Lstat(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 info.Mode()&os.ModeSymlink != 0 { /* Symlink */
if rlink, err := os.Readlink(path); err != nil {
errs <- fmt.Errorf("symlink: %s", err)
} else {
if err := os.Symlink(rlink, newPath); err != nil {
errs <- fmt.Errorf("symlink: %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) + ", ")
}
}
+980 -267
View File
File diff suppressed because it is too large. Load diff
+992 -142
View File
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
# Autocompletion for bash shell.
#
# You may put this file to a directory used by bash-completion:
#
# mkdir -p ~/.local/share/bash-completion/completions
# ln -s "/path/to/lf.bash" ~/.local/share/bash-completion/completions
#
_lf () {
local -a opts=(
-command
-cpuprofile
-doc
-last-dir-path
-memprofile
-remote
-selection-path
-server
-version
-help
)
if [[ $2 == -* ]]; then
COMPREPLY=( $(compgen -W "${opts[*]}" -- "$2") )
else
COMPREPLY=( $(compgen -f -d -- "$2") )
fi
}
complete -o filenames -F _lf lf lfcd
+15
View File
@@ -0,0 +1,15 @@
# Autocompletion for tcsh shell.
#
# You need to either copy the content of this file to your shell rc file
# (e.g. ~/.tcshrc) or source this file directly:
#
# set LF_COMPLETE = "/path/to/lf.csh"
# if ( -f "$LF_COMPLETE" ) then
# source "$LF_COMPLETE"
# endif
#
set LF_ARGS = "-command -cpuprofile -doc -last-dir-path -memprofile -remote -selection-path -server -version -help "
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'
+26
View File
@@ -0,0 +1,26 @@
# Autocompletion for powershell.
#
# You need to either copy the content of this file to $PROFILE or call this
# script directly.
#
using namespace System.Management.Automation
Register-ArgumentCompleter -Native -CommandName 'lf' -ScriptBlock {
param($wordToComplete)
$completions = @(
[CompletionResult]::new('-command ', '-command', [CompletionResultType]::ParameterName, 'command to execute on client initialization')
[CompletionResult]::new('-cpuprofile ', '-cpuprofile', [CompletionResultType]::ParameterName, 'path to the file to write the CPU profile')
[CompletionResult]::new('-doc', '-doc', [CompletionResultType]::ParameterName, 'show documentation')
[CompletionResult]::new('-last-dir-path ', '-last-dir-path', [CompletionResultType]::ParameterName, 'path to the file to write the last dir on exit (to use for cd)')
[CompletionResult]::new('-memprofile ', '-memprofile', [CompletionResultType]::ParameterName, 'path to the file to write the memory profile')
[CompletionResult]::new('-remote ', '-remote', [CompletionResultType]::ParameterName, 'send remote command to server')
[CompletionResult]::new('-selection-path ', '-selection-path', [CompletionResultType]::ParameterName, 'path to the file to write selected files on open (to use as open file dialog)')
[CompletionResult]::new('-server', '-server', [CompletionResultType]::ParameterName, 'start server (automatic)')
[CompletionResult]::new('-version', '-version', [CompletionResultType]::ParameterName, 'show version')
)
if ($wordToComplete.StartsWith('-')) {
$completions.Where{ $_.CompletionText -like "$wordToComplete*" } | Sort-Object -Property ListItemText
}
}
+28
View File
@@ -0,0 +1,28 @@
#compdef lf
# Autocompletion for zsh shell.
#
# You need to rename this file to _lf and add containing folder to $fpath in
# ~/.zshrc file:
#
# fpath=(/path/to/directory/containing/the/file $fpath)
# autoload -U compinit
# compinit
#
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%"
+14
View File
@@ -0,0 +1,14 @@
# Change working dir in tcsh to last dir in lf on exit (adapted from ranger).
#
# 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 "$_"'
+2 -2
View File
@@ -7,9 +7,9 @@
# #
# You may also like to assign a key to this command: # You may also like to assign a key to this command:
# #
# bind \co 'lfcd; commandline -f repaint' # bind \co 'set old_tty (stty -g); stty sane; lfcd; stty $old_tty; commandline -f repaint'
# #
# You need to put this in a function called fish_user_key_bindings. # You may put this in a function called fish_user_key_bindings.
function lfcd function lfcd
set tmp (mktemp) set tmp (mktemp)
+11
View File
@@ -1,6 +1,17 @@
# Change working dir in powershell to last dir in lf on exit. # Change working dir in powershell to last dir in lf on exit.
# #
# You need to put this file to a folder in $ENV:PATH variable. # You need to put this file to a folder in $ENV:PATH variable.
#
# You may also like to assign a key to this command:
#
# Set-PSReadLineKeyHandler -Chord Ctrl+o -ScriptBlock {
# [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine()
# [Microsoft.PowerShell.PSConsoleReadLine]::Insert('lfcd.ps1')
# [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
# }
#
# You may put this in one of the profiles found in $PROFILE.
#
$tmp = [System.IO.Path]::GetTempFileName() $tmp = [System.IO.Path]::GetTempFileName()
lf -last-dir-path="$tmp" $args lf -last-dir-path="$tmp" $args
+32
View File
@@ -0,0 +1,32 @@
# interpreter for shell commands
set shell cmd
# Shell commands with multiline definitions and/or positional arguments and/or
# quotes do not work in Windows. For anything but the simplest shell commands,
# it is recommended to create separate script files and simply call them here
# in commands or mappings.
# change the editor used in default editor keybinding
# There is no builtin terminal editor installed in Windows. The default editor
# mapping uses 'notepad' which launches in a separate GUI window. You may
# instead install a terminal editor of your choice and replace the default
# editor keybinding accordingly.
map e $vim %f%
# change the pager used in default pager keybinding
# The standard pager used in Windows is 'more' which is not a very capable
# pager. You may instead install a pager of your choice and replace the default
# pager keybinding accordingly.
map i $less %f%
# change the shell used in default shell keybinding
map w $powershell
# change 'doc' command to use a different pager
cmd doc $lf -doc | less
# leave some space at the top and the bottom of the screen
set scrolloff 10
# use enter for shell commands
map <enter> shell
+17 -13
View File
@@ -38,29 +38,33 @@ map O $mimeopen --ask $f
cmd open ${{ cmd open ${{
case $(file --mime-type $f -b) in case $(file --mime-type $f -b) in
text/*) $EDITOR $fx;; text/*) $EDITOR $fx;;
*) for f in $fx; do $OPENER $f > /dev/null 2> /dev/null & done;; *) for f in $fx; do setsid $OPENER $f > /dev/null 2> /dev/null & done;;
esac esac
}} }}
# rename current file without overwrite # define a custom 'rename' command without prompt for overwrite
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 # cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
map r push :rename<space> # map r push :rename<space>
# make sure trash folder exists # make sure trash folder exists
%mkdir -p ~/.trash # %mkdir -p ~/.trash
# 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 %set -f; mv $fx ~/.trash cmd trash %set -f; mv $fx ~/.trash
# delete current file or selected files (prompting) # define a custom 'delete' command
cmd delete ${{ # cmd delete ${{
set -f # set -f
printf "$fx\n" # printf "$fx\n"
printf "delete?[y/n]" # printf "delete?[y/n]"
read ans # read ans
[ $ans = "y" ] && rm -rf $fx # [ $ans = "y" ] && rm -rf $fx
}} # }}
# use '<delete>' key for either 'trash' or 'delete' command
# 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/)
+36
View File
@@ -0,0 +1,36 @@
# interpreter for shell commands
set shell powershell
# Shell commands with multiline definitions and/or positional arguments and/or
# quotes do not work in Windows. For anything but the simplest shell commands,
# it is recommended to create separate script files and simply call them here
# in commands or mappings.
#
# Also, the default keybindings are defined using cmd syntax (i.e. '%EDITOR%')
# which does not work with powershell. Therefore, you need to override these
# keybindings with explicit choices accordingly.
# change the editor used in default editor keybinding
# There is no builtin terminal editor installed in Windows. The default editor
# mapping uses 'notepad' which launches in a separate GUI window. You may
# instead install a terminal editor of your choice and replace the default
# editor keybinding accordingly.
map e $vim $Env:f
# change the pager used in default pager keybinding
# The standard pager used in Windows is 'more' which is not a very capable
# pager. You may instead install a pager of your choice and replace the default
# pager keybinding accordingly.
map i $less $Env:f
# change the shell used in default shell keybinding
map w $powershell
# change 'doc' command to use a different pager
cmd doc $lf -doc | less
# leave some space at the top and the bottom of the screen
set scrolloff 10
# use enter for shell commands
map <enter> shell
+844 -249
View File
File diff suppressed because it is too large. Load diff
+63 -25
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{ },
[]expr{&cmdExpr{
"gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1}, &callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""}}}, &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{ },
[]expr{&mapExpr{
"gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1}, &callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""}}}, &setExpr{"hidden", ""},
}, 1},
}}, }},
}, },
+1
View File
@@ -23,6 +23,7 @@ cat << END >> $out
lf \- terminal file manager lf \- terminal file manager
.SH SYNOPSIS .SH SYNOPSIS
.SY lf .SY lf
.OP \-command command
.OP \-cpuprofile path .OP \-cpuprofile path
.OP \-doc .OP \-doc
.OP \-last-dir-path path .OP \-last-dir-path path
+41 -24
View File
@@ -14,28 +14,45 @@ set -o verbose
mkdir -p dist mkdir -p dist
CGO_ENABLED=0 GOOS=darwin GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-darwin-386.tar.gz lf --remove-files # https://golang.org/doc/install/source#environment
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-darwin-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-dragonfly-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-freebsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-freebsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-freebsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-ppc64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-ppc64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mips.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mipsle.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mips64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-linux-mips64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-netbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-netbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-netbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-openbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-openbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && sync && tar czf dist/lf-openbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && sync && zip dist/lf-windows-386.zip lf.exe --move CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && sync && zip dist/lf-windows-amd64.zip lf.exe --move CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-dragonfly-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=illumos GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-illumos-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mipsle.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64le.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=linux GOARCH=s390x go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-s390x.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-386.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=openbsd GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=solaris GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-solaris-amd64.tar.gz lf --remove-files
CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-386.zip lf.exe --move
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-amd64.zip lf.exe --move
# not supported
# CGO_ENABLED=0 GOOS=aix GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-aix-ppc64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-386.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-amd64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=android GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-arm64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-js-wasm.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-386.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-amd64.tar.gz lf --remove-files
# CGO_ENABLED=0 GOOS=plan9 GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-arm.tar.gz lf --remove-files
+10
View File
@@ -0,0 +1,10 @@
module github.com/gokcehan/lf
go 1.12
require (
github.com/gdamore/tcell/v2 v2.2.0
github.com/mattn/go-runewidth v0.0.10
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d
gopkg.in/djherbis/times.v1 v1.2.0
)
+20
View File
@@ -0,0 +1,20 @@
github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
github.com/gdamore/tcell/v2 v2.2.0 h1:vSyEgKwraXPSOkvCk7IwOSyX+Pv3V2cV9CikJMXg4U4=
github.com/gdamore/tcell/v2 v2.2.0/go.mod h1:cTTuF84Dlj/RqmaCIV5p4w8uG1zWdk0SF6oBpwHp4fU=
github.com/lucasb-eyer/go-colorful v1.0.3 h1:QIbQXiugsb+q10B+MI+7DI1oQLdmnep86tWFlaaUAac=
github.com/lucasb-eyer/go-colorful v1.0.3/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-runewidth v0.0.10 h1:CoZ3S2P7pvtP45xOtBw+/mDL2z0RKI576gSkzRRpdGg=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY=
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf h1:MZ2shdL+ZM/XzY3ZGOnh4Nlpnxz5GSOhOmtHo3iPU6M=
golang.org/x/term v0.0.0-20201210144234-2321bbc49cbf/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d h1:SZxvLBoTP5yHO3Frd4z4vrF+DBX9vMVanchswa69toE=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/djherbis/times.v1 v1.2.0 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM=
gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8=
+129
View File
@@ -0,0 +1,129 @@
package main
import (
"log"
"os"
"path/filepath"
"strings"
)
type iconMap map[string]string
func parseIcons() iconMap {
im := make(iconMap)
defaultIcons := []string{
"fi=🗎",
"di=🗀",
"ln=🗎",
"pi=🗎",
"so=🗎",
"bd=🗎",
"cd=🗎",
"or=🗎",
"su=🗎",
"sg=🗎",
"tw=🗀",
"ow=🗀",
"st=🗀",
"ex=🗎",
}
im.parseEnv(strings.Join(defaultIcons, ":"))
if env := os.Getenv("LF_ICONS"); env != "" {
im.parseEnv(env)
}
return im
}
func (im iconMap) parseEnv(env string) {
for _, entry := range strings.Split(env, ":") {
if entry == "" {
continue
}
pair := strings.Split(entry, "=")
if len(pair) != 2 {
log.Printf("invalid $LF_ICONS entry: %s", entry)
return
}
key, val := pair[0], pair[1]
key = replaceTilde(key)
if filepath.IsAbs(key) {
key = filepath.Clean(key)
}
im[key] = val
}
}
func (im iconMap) get(f *file) string {
if val, ok := im[f.path]; ok {
return val
}
if f.IsDir() {
if val, ok := im[f.Name()+"/"]; ok {
return val
}
}
var key string
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:
key = "tw"
case f.IsDir() && f.Mode()&0002 != 0:
key = "ow"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
case f.IsDir():
key = "di"
case f.Mode()&os.ModeNamedPipe != 0:
key = "pi"
case f.Mode()&os.ModeSocket != 0:
key = "so"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeSetuid != 0:
key = "su"
case f.Mode()&os.ModeSetgid != 0:
key = "sg"
case f.Mode()&0111 != 0:
key = "ex"
}
if val, ok := im[key]; ok {
return val
}
if val, ok := im[f.Name()+"*"]; ok {
return val
}
if val, ok := im[filepath.Base(f.Name())+".*"]; ok {
return val
}
if val, ok := im["*"+f.ext]; ok {
return val
}
if val, ok := im["fi"]; ok {
return val
}
return " "
}
+968 -109
View File
File diff suppressed because it is too large. Load diff
+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;
+125 -13
View File
@@ -7,8 +7,11 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"reflect"
"runtime" "runtime"
"runtime/pprof" "runtime/pprof"
"strconv"
"strings"
) )
var ( var (
@@ -16,6 +19,8 @@ var (
envLevel = os.Getenv("LF_LEVEL") envLevel = os.Getenv("LF_LEVEL")
) )
type arrayFlag []string
var ( var (
gClientID int gClientID int
gHostname string gHostname string
@@ -25,9 +30,20 @@ var (
gSocketPath string gSocketPath string
gLogPath string gLogPath string
gServerLogPath string gServerLogPath string
gSelect string
gCommands arrayFlag
gVersion string gVersion string
) )
func (a *arrayFlag) Set(v string) error {
*a = append(*a, v)
return nil
}
func (a *arrayFlag) String() string {
return strings.Join(*a, ", ")
}
func init() { func init() {
h, err := os.Hostname() h, err := os.Hostname()
if err != nil { if err != nil {
@@ -40,6 +56,104 @@ func init() {
} }
} }
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))
}
// used by exportOpts below
func fieldToString(field reflect.Value) string {
kind := field.Kind()
var value string
switch kind {
case reflect.Int:
value = strconv.Itoa(int(field.Int()))
case reflect.Bool:
value = strconv.FormatBool(field.Bool())
case reflect.Slice:
for i := 0; i < field.Len(); i++ {
element := field.Index(i)
if i == 0 {
value = fieldToString(element)
} else {
value += ":" + fieldToString(element)
}
}
default:
value = field.String()
}
return value
}
func exportOpts() {
e := reflect.ValueOf(&gOpts).Elem()
for i := 0; i < e.NumField(); i++ {
// Get name and prefix it with lf_
name := e.Type().Field(i).Name
name = fmt.Sprintf("lf_%s", name)
// Skip maps
if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" {
continue
}
// Get string representation of the value
if name == "lf_sortType" {
var sortby string
switch gOpts.sortType.method {
case naturalSort:
sortby = "natural"
case nameSort:
sortby = "name"
case sizeSort:
sortby = "size"
case timeSort:
sortby = "time"
case ctimeSort:
sortby = "ctime"
case atimeSort:
sortby = "atime"
case extSort:
sortby = "ext"
}
os.Setenv("lf_sortby", sortby)
reverse := strconv.FormatBool(gOpts.sortType.option&reverseSort != 0)
os.Setenv("lf_reverse", reverse)
hidden := strconv.FormatBool(gOpts.sortType.option&hiddenSort != 0)
os.Setenv("lf_hidden", hidden)
dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0)
os.Setenv("lf_dirfirst", dirfirst)
} else {
field := e.Field(i)
value := fieldToString(field)
os.Setenv(name, value)
}
}
}
func startServer() { func startServer() {
cmd := detachedCommand(os.Args[0], "-server") cmd := detachedCommand(os.Args[0], "-server")
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
@@ -103,6 +217,10 @@ 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.Var(&gCommands,
"command",
"command to execute on client initialization")
flag.Parse() flag.Parse()
gSocketProt = gDefaultSocketProt gSocketProt = gDefaultSocketProt
@@ -125,22 +243,18 @@ func main() {
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:
os.Chdir(gUser.HomeDir)
gServerLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.server.log", gUser.Username)) gServerLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.server.log", gUser.Username))
serve() serve()
default: default:
checkServer() checkServer()
gClientID = 1000 gClientID = os.Getpid()
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))
for _, err := os.Stat(gLogPath); !os.IsNotExist(err); _, err = os.Stat(gLogPath) {
gClientID++
gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID))
}
switch flag.NArg() { switch flag.NArg() {
case 0: case 0:
_, err := os.Getwd() _, err := os.Getwd()
@@ -149,16 +263,14 @@ func main() {
os.Exit(2) os.Exit(2)
} }
case 1: case 1:
dir := flag.Arg(0) gSelect = flag.Arg(0)
if err := os.Chdir(dir); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
default: default:
fmt.Fprintf(os.Stderr, "only single directory is allowed\n") fmt.Fprintf(os.Stderr, "only single file or directory is allowed\n")
os.Exit(2) os.Exit(2)
} }
exportEnvVars()
run() run()
} }
+57 -41
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,25 +62,28 @@ 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) buf = append(buf, r)
} else {
buf = append(buf, '\\', r)
} }
continue if esc {
} buf = append(buf, '\\')
buf = append(buf, r)
} }
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)
@@ -167,32 +166,45 @@ func humanize(size int64) string {
return "" return ""
} }
// This regexp is used to partition a given string as numbers and non-numbers. // This function compares two strings for natural sorting which takes into
// For instance, if your input is 'foo123bar456' you get a slice of 'foo', // account values of numbers in strings. For example, '2' is less than '10',
// '123', 'bar', and '456'. This is useful for natural sorting which takes into // and similarly 'foo2bar' is less than 'foo10bar', but 'bar2bar' is greater
// account values of numbers within strings. // than 'foo10bar'.
var rePart = regexp.MustCompile(`\d+|\D+`)
func naturalLess(s1, s2 string) bool { func naturalLess(s1, s2 string) bool {
parts1 := rePart.FindAllString(s1, -1) lo1, lo2, hi1, hi2 := 0, 0, 0, 0
parts2 := rePart.FindAllString(s2, -1) for {
if hi1 >= len(s1) {
return hi2 != len(s2)
}
for i := 0; i < len(parts1) && i < len(parts2); i++ { if hi2 >= len(s2) {
if parts1[i] == parts2[i] { return false
}
isDigit1 := isDigit(s1[hi1])
isDigit2 := isDigit(s2[hi2])
for lo1 = hi1; hi1 < len(s1) && isDigit(s1[hi1]) == isDigit1; hi1++ {
}
for lo2 = hi2; hi2 < len(s2) && isDigit(s2[hi2]) == isDigit2; hi2++ {
}
if s1[lo1:hi1] == s2[lo2:hi2] {
continue continue
} }
num1, err1 := strconv.Atoi(parts1[i]) if isDigit1 && isDigit2 {
num2, err2 := strconv.Atoi(parts2[i]) num1, err1 := strconv.Atoi(s1[lo1:hi1])
num2, err2 := strconv.Atoi(s2[lo2:hi2])
if err1 == nil && err2 == nil { if err1 == nil && err2 == nil {
return num1 < num2 return num1 < num2
} }
return parts1[i] < parts2[i]
} }
return len(parts1) < len(parts2) return s1[lo1:hi1] < s2[lo2:hi2]
}
} }
var reAltKey = regexp.MustCompile(`<a-(.)>`) var reAltKey = regexp.MustCompile(`<a-(.)>`)
@@ -215,6 +227,10 @@ func max(a, b int) int {
return b return b
} }
func mod(a, b int) int {
return (a%b + b) % b
}
// We don't need no generic code // We don't need no generic code
// We don't need no type control // We don't need no type control
// No dark templates in compiler // No dark templates in compiler
+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 {
+626 -192
View File
File diff suppressed because it is too large. Load diff
+41 -7
View File
@@ -9,6 +9,9 @@ const (
nameSort nameSort
sizeSort sizeSort
timeSort timeSort
atimeSort
ctimeSort
extSort
) )
type sortOption byte type sortOption byte
@@ -29,21 +32,33 @@ var gOpts struct {
dircounts bool dircounts bool
drawbox bool drawbox bool
globsearch bool globsearch bool
icons bool
ignorecase bool ignorecase bool
ignoredia bool
incsearch bool
mouse bool
number bool
preview bool preview bool
relativenumber bool
smartcase bool smartcase bool
smartdia bool
wrapscan bool wrapscan bool
wrapscroll bool
findlen int findlen int
period int period int
scrolloff int scrolloff int
tabstop int tabstop int
errorfmt string
filesep string filesep string
ifs string ifs string
previewer string previewer string
cleaner string
promptfmt string promptfmt string
shell string shell string
timefmt string timefmt string
truncatechar string
ratios []int ratios []int
hiddenfiles []string
info []string info []string
shellopts []string shellopts []string
keys map[string]expr keys map[string]expr
@@ -57,19 +72,33 @@ func init() {
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 = true
gOpts.incsearch = false
gOpts.mouse = 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.findlen = 1
gOpts.period = 0 gOpts.period = 0
gOpts.scrolloff = 0 gOpts.scrolloff = 0
gOpts.tabstop = 8 gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m%s\033[0m"
gOpts.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.cleaner = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m"
gOpts.shell = gDefaultShell gOpts.shell = gDefaultShell
gOpts.timefmt = time.ANSIC gOpts.timefmt = time.ANSIC
gOpts.truncatechar = "~"
gOpts.ratios = []int{1, 2, 3} gOpts.ratios = []int{1, 2, 3}
gOpts.hiddenfiles = []string{".*"}
gOpts.info = nil gOpts.info = nil
gOpts.shellopts = nil gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort} gOpts.sortType = sortType{naturalSort, dirfirstSort}
@@ -95,7 +124,7 @@ func init() {
gOpts.keys["<home>"] = &callExpr{"top", nil, 1} gOpts.keys["<home>"] = &callExpr{"top", nil, 1}
gOpts.keys["G"] = &callExpr{"bottom", nil, 1} gOpts.keys["G"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1} gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<space>"] = &callExpr{"toggle", nil, 1} gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
gOpts.keys["v"] = &callExpr{"invert", nil, 1} gOpts.keys["v"] = &callExpr{"invert", nil, 1}
gOpts.keys["u"] = &callExpr{"unselect", nil, 1} gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"copy", nil, 1} gOpts.keys["y"] = &callExpr{"copy", nil, 1}
@@ -119,6 +148,8 @@ func init() {
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1} gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1} gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1} gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1} gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1} gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
@@ -128,9 +159,12 @@ func init() {
gOpts.keys["zs"] = &setExpr{"info", "size"} gOpts.keys["zs"] = &setExpr{"info", "size"}
gOpts.keys["zt"] = &setExpr{"info", "time"} gOpts.keys["zt"] = &setExpr{"info", "time"}
gOpts.keys["za"] = &setExpr{"info", "size:time"} gOpts.keys["za"] = &setExpr{"info", "size:time"}
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}} gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}} gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}} gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1}
gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1}
gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1}
gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1} gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1}
gOpts.cmdkeys = make(map[string]expr) gOpts.cmdkeys = make(map[string]expr)
@@ -144,8 +178,8 @@ func init() {
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1} gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<bs>"] = &callExpr{"cmd-delete-back", nil, 1} gOpts.cmdkeys["<backspace>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<bs2>"] = &callExpr{"cmd-delete-back", nil, 1} gOpts.cmdkeys["<backspace2>"] = &callExpr{"cmd-delete-back", nil, 1}
gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil, 1} gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil, 1} gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1} gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1}
+76 -42
View File
@@ -10,6 +10,8 @@ import (
"os/user" "os/user"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings"
"syscall"
) )
var ( var (
@@ -87,19 +89,9 @@ func init() {
} }
func detachedCommand(name string, arg ...string) *exec.Cmd { func detachedCommand(name string, arg ...string) *exec.Cmd {
return exec.Command(name, arg...) cmd := exec.Command(name, arg...)
} cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
return cmd
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 {
@@ -114,31 +106,6 @@ func shellCommand(s string, args []string) *exec.Cmd {
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func pasteCommand(list []string, dir *dir, cp bool) *exec.Cmd {
var sh string
var args []string
if cp {
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() {
gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`} gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`}
gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`} gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`}
@@ -149,10 +116,77 @@ func setDefaults() {
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
} }
func moveCursor(y, x int) {
fmt.Printf("\033[%d;%dH", y, x)
}
func isExecutable(f os.FileInfo) bool { func isExecutable(f os.FileInfo) bool {
return f.Mode()&0111 != 0 return f.Mode()&0111 != 0
} }
func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool {
hidden := false
for _, pattern := range hiddenfiles {
matched := matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path)
if strings.HasPrefix(pattern, "!") && matched {
hidden = false
} else if matched {
hidden = true
}
}
return hidden
}
func userName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if u, err := user.LookupId(fmt.Sprint(stat.Uid)); err == nil {
return fmt.Sprintf("%v ", u.Username)
}
}
return ""
}
func groupName(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
if g, err := user.LookupGroupId(fmt.Sprint(stat.Gid)); err == nil {
return fmt.Sprintf("%v ", g.Name)
}
}
return ""
}
func linkCount(f os.FileInfo) string {
if stat, ok := f.Sys().(*syscall.Stat_t); ok {
return fmt.Sprintf("%v ", stat.Nlink)
}
return ""
}
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)
}
}
+51 -41
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"fmt"
"log" "log"
"os" "os"
"os/exec" "os/exec"
@@ -17,14 +18,12 @@ var (
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
) )
var ( var envPathExt = os.Getenv("PATHEXT")
envPathExt = os.Getenv("PATHEXT")
)
var ( var (
gDefaultShell = "cmd" gDefaultShell = "cmd"
gDefaultSocketProt = "tcp" gDefaultSocketProt = "tcp"
gDefaultSocketPath = ":12345" gDefaultSocketPath = "127.0.0.1:12345"
) )
var ( var (
@@ -36,7 +35,7 @@ var (
func init() { func init() {
if envOpener == "" { if envOpener == "" {
envOpener = "start" envOpener = `start ""`
} }
if envEditor == "" { if envEditor == "" {
@@ -77,10 +76,6 @@ func detachedCommand(name string, arg ...string) *exec.Cmd {
return cmd return cmd
} }
func pauseCommand() *exec.Cmd {
return exec.Command("cmd", "/c", "pause")
}
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...)
@@ -89,33 +84,6 @@ func shellCommand(s string, args []string) *exec.Cmd {
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func pasteCommand(list []string, dir *dir, cp bool) *exec.Cmd {
var args []string
sh := "robocopy"
if !cp {
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.cmds["open"] = &execExpr{"&", "%OPENER% %f%"} gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"}
gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"} gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"}
@@ -126,11 +94,6 @@ func setDefaults() {
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1} gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
} }
func moveCursor(y, x int) {
// TODO: implement
return
}
func isExecutable(f os.FileInfo) bool { func isExecutable(f os.FileInfo) bool {
exts := strings.Split(envPathExt, string(filepath.ListSeparator)) exts := strings.Split(envPathExt, string(filepath.ListSeparator))
for _, e := range exts { for _, e := range exts {
@@ -141,3 +104,50 @@ func isExecutable(f os.FileInfo) bool {
} }
return false return false
} }
func isHidden(f os.FileInfo, path string, hiddenfiles []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 userName(f os.FileInfo) string {
return ""
}
func groupName(f os.FileInfo) string {
return ""
}
func linkCount(f os.FileInfo) string {
return ""
}
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)
}
}
+2 -1
View File
@@ -114,6 +114,7 @@ func (e *execExpr) String() string {
type listExpr struct { type listExpr struct {
exprs []expr exprs []expr
count int
} }
func (e *listExpr) String() string { func (e *listExpr) String() string {
@@ -265,7 +266,7 @@ func (p *parser) parseExpr() expr {
s.scan() s.scan()
result = &listExpr{exprs} result = &listExpr{exprs, 1}
case tokenPrefix: case tokenPrefix:
var expr string var expr string
+29 -27
View File
@@ -5,7 +5,6 @@ import (
"io/ioutil" "io/ioutil"
"log" "log"
"strconv" "strconv"
"unicode"
) )
type tokenType byte type tokenType byte
@@ -82,15 +81,23 @@ func (s *scanner) peek() byte {
} }
func isSpace(b byte) bool { func isSpace(b byte) bool {
return unicode.IsSpace(rune(b)) switch b {
case '\t', '\n', '\v', '\f', '\r', ' ':
return true
}
return false
} }
func isDigit(b byte) bool { func isDigit(b byte) bool {
return unicode.IsDigit(rune(b)) return '0' <= b && b <= '9'
} }
func isPrefix(b byte) bool { func isPrefix(b byte) bool {
return b == '$' || b == '%' || b == '!' || b == '&' switch b {
case '$', '%', '!', '&':
return true
}
return false
} }
func (s *scanner) scan() bool { func (s *scanner) scan() bool {
@@ -177,9 +184,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 +200,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 +220,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,14 +248,16 @@ 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)
}
s.next()
continue
} }
} else {
buf = append(buf, s.chr) buf = append(buf, s.chr)
s.next() s.next()
} }
}
s.typ = tokenIdent s.typ = tokenIdent
s.tok = string(buf) s.tok = string(buf)
s.next() s.next()
@@ -293,12 +298,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()
} else { continue
s.next()
}
} }
buf = append(buf, s.chr) buf = append(buf, s.chr)
s.next() s.next()
+5 -4
View File
@@ -13,7 +13,7 @@ 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) gQuitChan = make(chan struct{}, 1)
gListener net.Listener gListener net.Listener
) )
@@ -58,6 +58,7 @@ func listen(l net.Listener) {
func handleConn(c net.Conn) { func handleConn(c net.Conn) {
s := bufio.NewScanner(c) s := bufio.NewScanner(c)
Loop:
for s.Scan() { for s.Scan() {
log.Printf("listen: %s", s.Text()) log.Printf("listen: %s", s.Text())
word, rest := splitWord(s.Text()) word, rest := splitWord(s.Text())
@@ -71,7 +72,7 @@ func handleConn(c net.Conn) {
gCopyFile = false gCopyFile = false
default: default:
log.Printf("unexpected option to copy file(s): %s", s.Text()) log.Printf("unexpected option to copy file(s): %s", s.Text())
break break Loop
} }
gFileList = nil gFileList = nil
for s.Scan() && s.Text() != "" { for s.Scan() && s.Text() != "" {
@@ -114,13 +115,13 @@ func handleConn(c net.Conn) {
} }
} }
case "quit": case "quit":
gQuitChan <- true gQuitChan <- struct{}{}
for _, c := range gConnList { for _, c := range gConnList {
fmt.Fprintln(c, "echo server is quitting...") fmt.Fprintln(c, "echo server is quitting...")
c.Close() c.Close()
} }
gListener.Close() gListener.Close()
break break Loop
default: default:
log.Printf("listen: unexpected command: %s", word) log.Printf("listen: unexpected command: %s", word)
} }
+625 -301
View File
File diff suppressed because it is too large. Load diff