Compare commits

440 Commits
Author SHA1 Message Date
Gokcehan 1b71c33afd update doc 2021-10-10 00:01:01 +03:00
Gokcehan f01fab6257 fix crash when hidden is changed
cc #615 #657
2021-10-09 22:49:12 +03:00
SPFab 85aa3b9dc6 Cmap fixes (#691)
* fixed bug when switching commands

* filter and searches are now reset, whenever prompt is reset

* don't interrupt %-shell commands

* filter and search are now correctly started and stoped on cd

* movement commands now don't stop prompts

* forgot shell-pipe check in delete command
2021-08-29 18:28:29 +03:00
SPFabGerman 5566f82596 fixed bug, where ~ is not a absolute directory (#690) 2021-08-25 19:36:14 +03:00
SPFab 0edf0823b7 cmap now accepts all expressions (#686) 2021-08-25 18:28:47 +03:00
SPFab 05a48ea315 added pre-cd command (#685)
* added special pre-cd command

* added documentation
2021-08-23 17:11:56 +03:00
SPFab ff0933ca03 Added filter command (#667)
* added first version of interactive filter

* small fix when loading new file

* don't reset filter when directory is reloaded automatically

* reapply filter when options for searching change

* current filter or arguments now prefilled in the prompt

* empty filter can now be supplied

* added new setfilter command for use in scripts

* added incfilter option

* added very basic documentation

* added filter indication in statusbar

* added option to display filter to prompt
2021-08-21 16:40:24 +03:00
Gokcehan 6c46b217af add completion for dircache option 2021-08-01 17:06:04 +03:00
Gokcehan bdd1747e43 update doc 2021-08-01 17:04:37 +03:00
Yegor Bychin ee5b3f4813 add an option to disable directory cache (#673)
* add an option to disable directory cache

* change option name to `dircache`

* change 4 whitespaces to tab
2021-08-01 17:00:10 +03:00
Matthew Tooheyandmtoohey31 75eba115d2 implement dironly option (#669)
Co-authored-by: mtoohey31 <mtoohey31@users.noreply.github.com>
2021-07-31 16:10:25 +03:00
SeerLite 8adbd2b9ef Don't use the absolute path when saving bookmarks (#659)
The absolute path of symlinks were getting saved, so bookmarking a symlink
directory would cause the absolute path to be saved and loaded instead.
What's saved now is the current path string as understood by lf instead, so
path to symlinks can be saved too and they won't get dereferenced when
loading.
2021-07-09 16:34:45 +03:00
Gokcehan 55b9189713 build release only on tags 2021-06-20 01:43:45 +03:00
Gokcehan b763c30cc5 deprecate travis in favor of github actions 2021-06-20 01:38:53 +03:00
gokcehan 61489ad00b Create release.yml 2021-06-20 01:37:44 +03:00
gokcehan 1ff3910c70 Create go.yml 2021-06-20 01:12:57 +03:00
Gokcehan 1966a30deb bump go version 2021-06-20 01:01:06 +03:00
ratijas 50e3a6856e PowerShell: use native Camel-Case style for commands (#650)
In PowerShell land it is preferred to use Camel Case for command names,
options and parameters, so lets respect that.
2021-06-19 23:41:14 +03:00
Gokcehan 9885c4be7a trim command prefix when it is longer than width
cc #648
2021-06-13 01:09:19 +03:00
Gokcehan 29aa77aa27 update doc 2021-06-13 00:36:48 +03:00
István Donkó 6e9f53f4bb Fix minor typo (#647)
* Fix minor typo

lf.1 will need to be regenerated as well.

* Fix minor typo
2021-06-13 00:36:16 +03:00
Gokcehan 099cccdcb5 show remote error when client id does not exists
cc #495
2021-06-13 00:27:43 +03:00
Gokcehan 4220868cc7 create data directory first before selection file
cc #645
2021-06-12 23:29:54 +03:00
Gokcehan eaaf08e425 ignore erase line escape code
cc #440
2021-05-30 20:43:17 +03:00
Gokcehan f885af55f2 add support for bright fg/bg ansi escape codes
cc #307
2021-05-30 19:26:08 +03:00
Gokcehan 599e42c12b calculate rune widths properly in shell outputs 2021-05-30 17:35:44 +03:00
Gokcehan 5d439419ea scroll when the prompt is longer than the width
cc #269
2021-05-30 17:24:19 +03:00
Gokcehan 5d02b557d3 follow links in 'open' examples
cc #634
2021-05-22 01:46:13 +03:00
Gokcehan 7acb69c40a echo logged server errors back to client as well 2021-05-21 16:54:01 +03:00
Gokcehan 7cdb7495ea add a command line parameter for single use
cc #177
2021-05-19 23:38:05 +03:00
Gokcehan d6acf4a6ec update doc 2021-05-19 22:25:26 +03:00
Gokcehan 06a30eda19 add 'autoquit' option to auto quit server on quit
cc #177
2021-05-19 21:55:19 +03:00
Gokcehan 7bf895e301 add server quit command to quit without clients
cc #177
2021-05-19 21:47:53 +03:00
Gokcehan 1841bba3e6 rename server quit command to quit!
cc #177
2021-05-19 21:47:08 +03:00
Gokcehan 6ca07b1bfc drop client connections on quit
cc #177
2021-05-19 21:45:27 +03:00
Gokcehan ec330c1bc5 use a local file instead of server load and save
cc #177
2021-05-19 19:54:50 +03:00
Gokcehan d31cd98b58 bump tcell to v2.3.1
cc #616 #621
2021-05-16 22:52:15 +03:00
Marius 0cd634e9a8 Preserve ' bookmark on sync (#624) 2021-05-13 21:31:25 +03:00
Marius 843afdfe4f Make ratios behave like ratios (#622)
Integer division causes miscalculation of pane widths. With `set ratios 100:200:300` the first two panes have width 0, the third pane will take up all space (unless you happen to have a huge terminal). I noticed this when fine tuning ratios, e.g. going from `1:2:3` to something like `10:21:30`.
2021-05-13 21:25:04 +03:00
Gokcehan 1bd78220e2 avoid crash with dir preview when hidden changes
cc #615
2021-04-28 18:50:24 +03:00
Gokcehan 202a998731 invalidate reg cache when drawbox option changes
cc #602
2021-04-25 16:51:40 +03:00
Gokcehan 8739087fe1 increase lookahead length for color escapes
cc #609
2021-04-15 17:23:25 +03:00
Gokcehan 628bf408b4 invalidate reg cache when height changes in resize
cc #610
2021-04-14 14:49:41 +03:00
Gokcehan 4601e74d66 export OLDPWD variable as the initial directory
cc #601
2021-04-13 23:48:49 +03:00
Gokcehan c8f60623f3 cleanup 2021-04-13 23:29:26 +03:00
Gokcehan fec767d11b dont change findlen to force find with cmd-enter
cc #605
2021-04-13 20:32:01 +03:00
gotroyb127 0dcfb3d4fe force find at cmd-enter (#605)
cc #559
2021-04-06 19:02:16 +03:00
gotroyb127 0cfd34f30d add 'waitmsg' option to configure the message after shell-wait commands (#604) 2021-04-06 18:57:23 +03:00
Gokcehan 229b7b1ade export PWD on windows to fix broken build
cc #591
2021-04-04 18:30:00 +03:00
Gokcehan ca0068514a add 'shellflag' option to customize shell flag
cc #597
2021-04-04 18:23:14 +03:00
Gokcehan aebff483a7 update tcell version to fix delete key on st
cc #486
2021-03-30 01:34:58 +03:00
Gokcehan 5166eef0b3 change to local tcell fork
cc #586
2021-03-30 01:12:58 +03:00
Gokcehan 73be81595e handle ui suspend/resume errors
cc #592
2021-03-28 18:54:40 +03:00
Gokcehan 06bf58851b update doc
cc #591
2021-03-19 14:00:00 +03:00
SeerLite b7aaa23bd0 Export $PWD to shell (#591)
Most shells use $PWD to show the right working directory when it's a
symlink. Without it, they'd fall back to the absolute path instead.
2021-03-19 13:58:10 +03:00
SPFab a9cb7156a3 added ability to use custom config file (#587) 2021-03-09 14:35:50 +03:00
Gokcehan 91f40b1f02 update example config 2021-03-03 18:06:44 +03:00
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
Gokcehan 629a7f3297 update documentation 2018-08-29 19:28:22 +03:00
Gokcehan 5e67147204 check HOME and USER variables on startup
Related #108
2018-08-27 19:38:08 +03:00
Gokcehan 266a583adb use load instead of reload after shell-pipe
Related #109
2018-08-27 19:01:21 +03:00
Gokcehan b22384d634 keep index when selection is deleted
Related #109
2018-08-27 18:57:55 +03:00
Gokcehan 4ba3c3cda9 keep reverse direction in find and search 2018-08-23 01:55:50 +03:00
Gokcehan 4420e41c76 add 'anchorfind' option to control find start
Related #68
2018-08-23 01:37:07 +03:00
Gokcehan a59a5aa712 use zero value in findlen for arbitrary length
Related #68
2018-08-23 01:29:59 +03:00
Gokcehan 170e39b95e add 'findlen' option to control number of chars
Related #68
2018-08-22 20:57:47 +03:00
Gokcehan 011cca76d1 add find commands to find as you type
Related #68
2018-08-22 20:05:22 +03:00
Gokcehan 0b8de7c77e detach server on windows
Related #106
2018-08-01 00:21:55 +03:00
Gokcehan d3f9a3588f handle non-existent directories during reload 2018-07-30 20:56:57 +03:00
Gokcehan a0935fabcb handle removed directories during load 2018-07-30 18:41:14 +03:00
Gokcehan e82cbb820f export 'LF_LEVEL' variable for nested instances
Related #107
2018-07-28 16:52:54 +03:00
Gokcehan 9234bcd5b8 try to reconnect after sleep 2018-07-26 22:11:05 +03:00
Gokcehan 7dbb61f295 try to reconnect when server is not yet started
Related #106
2018-07-26 21:58:09 +03:00
Gokcehan 40002a7752 add 'quit' command to server protocol
Related #106
2018-07-22 20:44:56 +03:00
Gokcehan ffa913d943 update readme 2018-07-19 00:59:09 +03:00
Gokcehan abf2187271 save last directory as a mark
Related #76
2018-07-17 19:45:31 +03:00
Gokcehan ee7293e2f7 change system configuration path on unix 2018-07-13 22:46:37 +03:00
Gokcehan 95a9305f70 add marks and history file locations to doc 2018-07-12 21:47:19 +03:00
Gokcehan cdf4fcb810 write history to history file on quit
Related #81
2018-07-12 21:22:36 +03:00
Gokcehan 211bcd0444 write marks to marks file on quit
Related #76
2018-07-11 20:09:26 +03:00
Gokcehan 0d0f7451ac add 'mark-save' and 'mark-load' commands for marks
Related #76
2018-07-09 21:35:04 +03:00
Gokcehan a80900f41e rename mark to selection 2018-07-09 21:22:10 +03:00
Gokcehan 552182958a use pager variable for doc on windows 2018-07-08 14:27:35 +03:00
Gokcehan d86e9c991c add 'doc' command to view documentation
Related #100
2018-07-07 17:50:47 +03:00
Gokcehan e74a43bf0e cleanup 2018-07-07 17:34:04 +03:00
Gokcehan 9d4accbcde typo 2018-07-06 01:16:58 +03:00
Gokcehan db9d795cb0 cleanup 2018-07-06 01:12:20 +03:00
Gokcehan 2f3c52f9f2 update readme 2018-07-05 23:15:16 +03:00
Gokcehan 63892ee83c generate man page from the documentation 2018-07-05 23:09:53 +03:00
Gokcehan 2c14b3cd4a cleanup 2018-06-29 00:34:21 +03:00
Gokcehan e1b6d38386 add executable completion on windows 2018-06-29 00:12:54 +03:00
Gokcehan fef99c1d70 use env vars on windows 2018-06-28 23:37:01 +03:00
Gokcehan b8523c3258 rename 'remove' to 'delete' in example config 2018-06-28 21:55:56 +03:00
Gokcehan 4cbb211757 use env vars in example config 2018-06-28 21:53:42 +03:00
Gokcehan 5787ecd1bd add default environmental variables 2018-06-28 21:51:24 +03:00
Gokcehan 96f35e986d rename 'open-file' to 'open' 2018-06-28 21:20:43 +03:00
Gokcehan 07c16fede0 add configuration file locations to doc 2018-06-28 20:23:50 +03:00
Gokcehan 2d821216a8 read system-wide configuration on windows 2018-06-28 19:45:59 +03:00
Gokcehan 638d67c0e4 read system-wide configuration at '/etc/lfrc' 2018-06-28 19:44:50 +03:00
Gokcehan 6c319316e2 add 'source' command to read a configuration file
Related #97
2018-06-28 17:14:35 +03:00
Gokcehan 5d5d00e30b add special keys to default keybindings 2018-06-27 21:33:00 +03:00
Gokcehan d987c9e439 rename yank-delete-put to copy-cut-paste 2018-06-27 21:17:56 +03:00
Gokcehan b67b042d43 add shell options to example config 2018-06-26 22:24:41 +03:00
Gokcehan e99478e8a1 add 'shellopts' option to set shell arguments
Related #102
2018-06-26 21:14:55 +03:00
Gokcehan 4c54acebeb add optional version parameter to build scripts
Related #103
2018-06-26 17:09:05 +03:00
Gokcehan fe786aae4c add a build script for a static stripped binary
Related #99 and #103
2018-06-26 16:29:48 +03:00
Gokcehan a607e53e51 use dep for dependency management
Related #103
2018-06-26 00:46:50 +03:00
Gokcehan da126a3959 update readme 2018-06-16 16:59:41 +03:00
Gokcehan 6d20887b16 update preview when 'hidden' is changed 2018-06-16 16:34:14 +03:00
Gokcehan 078dc47e34 find hidden parents when 'hidden' is changed 2018-06-16 16:27:39 +03:00
Gokcehan 8070cd82b7 cleanup 2018-06-16 00:59:16 +03:00
Gokcehan 52974615f2 handle command properly with 'cmd-word'back' 2018-06-16 00:13:33 +03:00
Gokcehan 76a725eaf2 replace 'reload' with 'load' in documentaiton 2018-06-15 22:52:17 +03:00
Gokcehan 2e014b3c0a add tutorial link to readme
Related #94
2018-06-15 21:05:55 +03:00
Gokcehan 51101f7020 load all clients after running 'put' command 2018-06-15 16:34:44 +03:00
Gokcehan ba01f85340 add 'load' command to load modified dirs and files 2018-06-15 16:33:54 +03:00
Gokcehan 723357fe3d add 'period' option for periodic refresh
Related #73
2018-06-09 22:02:09 +03:00
Gokcehan e025c68130 keep cache when navigation is renewed 2018-06-08 21:47:28 +03:00
Gokcehan 7acc85f81c reload modified files when loading cache
Related #92
2018-06-07 22:49:53 +03:00
Gokcehan 4846a74320 reload modified directories when loading cache
Related #92
2018-06-07 22:19:55 +03:00
Gokcehan 9177ddd406 cleanup 2018-06-06 21:50:15 +03:00
Gokcehan 9d21a4f359 add key mappings to the doc 2018-06-06 21:39:44 +03:00
Gokcehan 20720c832d cleanup 2018-06-06 20:55:13 +03:00
Gokcehan 448f2a3cb2 restart server when crashed
Related #65
2018-06-05 22:11:20 +03:00
Gokcehan 397d5e0fac disable history when a command is running 2018-05-20 20:42:19 +03:00
Gokcehan 9400f07e45 skip searches from command history 2018-05-20 20:38:18 +03:00
Gokcehan a85e0da9b0 cleanup 2018-05-20 20:30:41 +03:00
Gokcehan 03b9fe0c5e skip whitespace before 'cmd-capitalize-word' 2018-05-16 15:13:05 +03:00
Gokcehan 42d57121f7 rename 'cmd-put' to 'cmd-yank' 2018-05-16 00:28:11 +03:00
Gokcehan ed8137a79c rename 'bot' to 'bottom' 2018-05-16 00:20:05 +03:00
Gokcehan d9761d2dc8 rename 'hist' to 'history' 2018-05-16 00:16:49 +03:00
Gokcehan 04f1d68d1e rename 'comp' to 'complete' 2018-05-16 00:05:06 +03:00
Gokcehan 3deea69c4d rename 'cmd-delete-beg' to 'cmd-delete-home' 2018-05-16 00:02:06 +03:00
Gokcehan 980a89c908 rename 'cmd-beg' to 'cmd-home' 2018-05-16 00:00:20 +03:00
Gokcehan de39594a46 add 'cmd-transpose-word' to swap words 2018-05-14 19:38:35 +03:00
Gokcehan 6e6cca33b8 add 'cmd-lowercase-word' to downcase word to end 2018-05-14 01:38:19 +03:00
Gokcehan 18f6d954a7 add 'cmd-uppercase-word' to upcase word to end 2018-05-14 01:30:53 +03:00
Gokcehan 1a95df7b64 add 'cmd-delete-word' to delete word to end 2018-05-14 01:25:26 +03:00
Gokcehan afefc30a67 rename 'cmd-delete-word' to 'cmd-delete-unix-word' 2018-05-14 01:19:26 +03:00
Gokcehan 0c672fef6f add 'cmd-capitalize-word' to upcase letter 2018-05-14 01:16:01 +03:00
Gokcehan bc67283f2a add tests for colors 2018-05-06 18:45:31 +03:00
Gokcehan f672a71f3d fix confusion of 8-bit color codes and attributes 2018-05-06 18:45:18 +03:00
Gokcehan ef709b5611 implement 'cmd-word' and 'cmd-word-back' commands
Related #67
2018-05-05 19:37:14 +03:00
Gokcehan 7543b2256c add support for alt keys
Related #67
2018-05-05 16:27:32 +03:00
Gokcehan 0855507298 fix default commands on windows 2018-04-28 18:34:24 +03:00
Gokcehan 6b235beb39 update documentation 2018-04-21 00:11:54 +03:00
Gokcehan d267bc70d4 null check directory preview before sort 2018-04-20 22:19:37 +03:00
Gokcehan 3b043752a4 sort cached directories asynchronously 2018-04-20 21:28:56 +03:00
Gokcehan a0e1d4d59a sort cached directories while loading 2018-04-18 23:08:28 +03:00
Gokcehan 09b1daaade sort directory preview when options are changed 2018-04-18 21:57:41 +03:00
Gokcehan 8eb9055622 add 'drawbox' option to draw box around windows 2018-04-15 19:26:51 +03:00
Gokcehan d608eb4a56 handle resize events properly 2018-04-15 18:18:39 +03:00
Gokcehan ad4fc51805 add tilde to filename if shortened 2018-04-14 23:16:31 +03:00
Gokcehan ebd599deca remove 'lscolors' option
Related #37
2018-04-14 21:21:39 +03:00
Gokcehan 5a9a829252 handle 256 colors in $LS_COLORS
Related #37
2018-04-14 21:18:39 +03:00
M1rt f92e0f53a5 LSCOLORS & LS_COLORS support (#96)
* LSCOLORS & LS_COLORS support

* Renamed lsColors to gColors

* Fixed gOptWords & setExpr.eval()
2018-04-14 14:58:29 +03:00
Gokcehan 54dbf5cbe4 use 'redraw' for resize event 2018-04-12 22:56:09 +03:00
Gokcehan c1fc79b6ae replace 'redraw' commands with 'draw' 2018-04-12 21:54:40 +03:00
Gokcehan 4d3437a198 add builtin 'draw' command to update efficiently 2018-04-12 21:48:32 +03:00
Gokcehan 9d14888ba2 add missing arguments to test cases 2018-04-12 21:29:54 +03:00
Gokcehan 68a23a10e1 show command counts in the ruler
Related #66
2018-04-12 19:14:50 +03:00
Gokcehan 03619c3cbb handle command counts efficiently
Related #66
2018-04-12 18:04:37 +03:00
51 changed files with 10342 additions and 2451 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
name: Go
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.15
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
+28
View File
@@ -0,0 +1,28 @@
name: Release
on:
push:
tags:
- '*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.15
- name: Build
run: gen/xbuild.sh
- name: Release
uses: softprops/action-gh-release@v1
with:
files: dist/*
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+1
View File
@@ -2,3 +2,4 @@ lf
lf.exe
tags
dist/
vendor/
-16
View File
@@ -1,16 +0,0 @@
language: go
install:
- go get github.com/nsf/termbox-go
before_deploy:
- gen/xbuild.sh
deploy:
provider: releases
api_key:
secure: RdZAOPWooYq73iFQIjqe9+Awr7oA8m0j0tn1tUUfLjP+PGYpuz2lf1SHW/UjPcxySFkkBxnNPC1xgqmxekmvZadBaQbApqko4e47zCF0Pe91QG9OcDFaiJUWb7wcg+UDLoS0lJq8mcKYoi6bV76syOk0gBunLUmuYYpz/hR4lbalfq5//fD6sOOJ9cJPjeuG7LwYqbyw/8VwQWpiWgK9Sb5gu7+ZBgXkLG+/5OSHW8yNHGmtkw5sjMr4jQnNt2ixXVe5OdQ14mvRx0n4vlnzjNjmY6cPjEeqAc9eniOJ5o99k1OnR3H5kmNgI749q+VAkdu/uJfHiLXL1zerReb4SSTU+tTw9c7JYTcjBHlCT11CHlksVu55hHAbFvPkIpLfoRvdqrcjUyEHiCI/HbWiHhsQ+Gve+tpIcgu/aAC2TEsQ+vmmaXbOFcUsG77XP8gn1y+Spkyzou7tUvypIXduDSKFIvI51HYK2F5t5ttG6zJw9lpmmuoUWvCvbGvdAW893O6ef+iZvBoZYRjdeWvIqh/no2gWi1CRa4ZPSZWkn9NoE/2koaCQkrx9RHmEeLIukZVAT6ZViwvhMAOrvXQdKTDwbQ3ovMdtDvGcvjGz9k5xwnWrIcF7MV7nf7sj/JlcX2tulevcSLsYeBvcuTUFzy90erMy70MS01wp0I/IgpY=
skip_cleanup: true
file_glob: true
file: dist/*
name: $TRAVIS_TAG
on:
tags: true
repo: gokcehan/lf
+19 -15
View File
@@ -5,17 +5,15 @@
| [#lf](https://webchat.freenode.net/?channels=lf) (on Freenode)
| [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge)
[![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)
[![GoDoc](https://godoc.org/github.com/gokcehan/lf?status.svg)](https://godoc.org/github.com/gokcehan/lf)
[![Join the chat at https://gitter.im/lf-fm/Lobby](https://badges.gitter.im/lf-fm/Lobby.svg)](https://gitter.im/lf-fm/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Go Reference](https://pkg.go.dev/badge/github.com/gokcehan/lf.svg)](https://pkg.go.dev/github.com/gokcehan/lf)
> This is a work in progress. Use at your own risk.
`lf` (as in "list files") is a terminal file manager written in Go.
It is heavily inspired by ranger with some missing and extra features.
Some of the missing features are deliberately omitted since they are better handled by external tools.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts.
![multicol-screenshot](http://i.imgur.com/DaTUenu.png)
![singlecol-screenshot](http://i.imgur.com/p95xzUj.png)
@@ -26,7 +24,7 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information.
- Single binary without any runtime dependencies (except for terminfo database)
- Fast startup and low memory footprint (due to native code and static binaries)
- Server/client architecture to share file selection between multiple instances
- Configurable with shell commands (sync or async)
- Configuration with shell commands
- Customizable keybindings (vi and readline defaults)
- Preview filtering (for source highlight, archives, pdfs/images as text etc.)
@@ -34,22 +32,28 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information.
- Tabs or windows (handled by window manager or terminal multiplexer)
- Builtin pager/editor (handled by your pager/editor of choice)
- Image previews (cool but no standard available)
## May-Futures
- Bookmarks
- Colorschemes
## 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.
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
@@ -57,7 +61,7 @@ After the installation `lf` command should start the application in the current
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.
An example configuration file can also be found in this directory.
+406 -96
View File
@@ -7,8 +7,11 @@ import (
"log"
"os"
"os/exec"
"strconv"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
)
type cmdItem struct {
@@ -17,25 +20,59 @@ type cmdItem struct {
}
type app struct {
ui *ui
nav *nav
quitChan chan bool
cmd *exec.Cmd
cmdIn io.WriteCloser
cmdOutBuf []byte
cmdHist []cmdItem
cmdHistInd int
ui *ui
nav *nav
ticker *time.Ticker
quitChan chan struct{}
cmd *exec.Cmd
cmdIn io.WriteCloser
cmdOutBuf []byte
cmdHistory []cmdItem
cmdHistoryBeg int
cmdHistoryInd int
}
func newApp() *app {
ui := newUI()
nav := newNav(ui.wins[0].h)
func newApp(ui *ui, nav *nav) *app {
quitChan := make(chan struct{}, 1)
return &app{
app := &app{
ui: ui,
nav: nav,
quitChan: make(chan bool, 1),
ticker: new(time.Ticker),
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.quit()
os.Exit(3)
return
}
}()
return app
}
func (app *app) quit() {
if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err)
}
if !gSingleMode {
if err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil {
log.Printf("dropping connection: %s", err)
}
if gOpts.autoquit {
if err := remote("quit"); err != nil {
log.Printf("auto quitting server: %s", err)
}
}
}
os.Remove(gLogPath)
}
func (app *app) readFile(path string) {
@@ -43,31 +80,233 @@ func (app *app) readFile(path string) {
f, err := os.Open(path)
if err != nil {
app.ui.printf("opening file: %s", err)
app.ui.echoerrf("opening file: %s", err)
return
}
defer f.Close()
p := newParser(f)
for p.parse() {
p.expr.eval(app, nil)
}
if p.err != nil {
app.ui.printf("%s", p.err)
app.ui.echoerrf("%s", p.err)
}
}
// This is the main event loop of the application. There are two channels to
// read expressions from client and server. Reading and evaluation are done on
// separate goroutines.
func loadFiles() (list []string, cp bool, err error) {
files, err := os.Open(gFilesPath)
if os.IsNotExist(err) {
err = nil
return
}
if err != nil {
err = fmt.Errorf("opening file selections file: %s", err)
return
}
defer files.Close()
s := bufio.NewScanner(files)
s.Scan()
switch s.Text() {
case "copy":
cp = true
case "move":
cp = false
default:
err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text())
return
}
for s.Scan() && s.Text() != "" {
list = append(list, s.Text())
}
if s.Err() != nil {
err = fmt.Errorf("scanning file list: %s", s.Err())
return
}
log.Printf("loading files: %v", list)
return
}
func saveFiles(list []string, cp bool) error {
if err := os.MkdirAll(filepath.Dir(gFilesPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
files, err := os.Create(gFilesPath)
if err != nil {
return fmt.Errorf("opening file selections file: %s", err)
}
defer files.Close()
log.Printf("saving files: %v", list)
if cp {
fmt.Fprintln(files, "copy")
} else {
fmt.Fprintln(files, "move")
}
for _, f := range list {
fmt.Fprintln(files, f)
}
return nil
}
func (app *app) readHistory() error {
f, err := os.Open(gHistoryPath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("opening history file: %s", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2)
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.cmdHistoryBeg = len(app.cmdHistory)
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
return nil
}
func (app *app) writeHistory() error {
if len(app.cmdHistory) == 0 {
return nil
}
local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg)
copy(local, app.cmdHistory[app.cmdHistoryBeg:])
app.cmdHistory = nil
if err := app.readHistory(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
app.cmdHistory = append(app.cmdHistory, local...)
if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
f, err := os.Create(gHistoryPath)
if err != nil {
return fmt.Errorf("creating history file: %s", err)
}
defer f.Close()
if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
}
for _, cmd := range app.cmdHistory {
_, err = f.WriteString(fmt.Sprintf("%s %s\n", cmd.prefix, cmd.value))
if err != nil {
return fmt.Errorf("writing history file: %s", err)
}
}
return nil
}
// This is the main event loop of the application. Expressions are read from
// the client and the server on separate goroutines and sent here over channels
// for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update.
func (app *app) loop() {
clientChan := app.ui.readExpr()
serverChan := readExpr()
go app.nav.previewLoop(app.ui)
var serverChan <-chan expr
if !gSingleMode {
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}
}
}()
}
if gConfigPath != "" {
if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) {
app.readFile(gConfigPath)
} else {
log.Printf("config file does not exist: %s", err)
}
} else {
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 {
select {
case <-app.quitChan:
if app.nav.copyTotal > 0 {
app.ui.echoerr("quit: copy operation in progress")
continue
}
if app.nav.moveTotal > 0 {
app.ui.echoerr("quit: move operation in progress")
continue
}
if app.nav.deleteTotal > 0 {
app.ui.echoerr("quit: delete operation in progress")
continue
}
app.quit()
app.nav.previewChan <- ""
log.Print("bye!")
if gLastDirPath != "" {
@@ -77,22 +316,71 @@ func (app *app) loop() {
}
defer f.Close()
dir := app.nav.currDir()
_, err = f.WriteString(dir.path)
_, err = f.WriteString(app.nav.currDir().path)
if err != nil {
log.Printf("writing last dir file: %s", err)
}
}
return
case d := <-app.nav.dirChan:
prev, ok := app.nav.dirCache[d.path]
if ok {
d.find(prev.name(), app.nav.height)
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:
app.nav.checkDir(d)
app.nav.dirCache[d.path] = d
if gOpts.dircache {
prev, ok := app.nav.dirCache[d.path]
if ok {
d.ind = prev.ind
d.sel(prev.name(), app.nav.height)
}
app.nav.dirCache[d.path] = d
}
for i := range app.nav.dirs {
if app.nav.dirs[i].path == d.path {
@@ -105,7 +393,7 @@ func (app *app) loop() {
curr, err := app.nav.currFile()
if err == nil {
if d.path == app.nav.currDir().path {
app.ui.loadFile(app.nav)
app.ui.loadFile(app.nav, true)
}
if d.path == curr.path {
app.ui.dirPrev = d
@@ -114,6 +402,8 @@ func (app *app) loop() {
app.ui.draw(app.nav)
case r := <-app.nav.regChan:
app.nav.checkReg(r)
app.nav.regCache[r.path] = r
curr, err := app.nav.currFile()
@@ -124,77 +414,90 @@ func (app *app) loop() {
}
app.ui.draw(app.nav)
case e := <-clientChan:
for i := 0; i < e.count; i++ {
e.expr.eval(app, nil)
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)
app.ui.draw(app.nav)
case e := <-serverChan:
e.eval(app, nil)
app.ui.draw(app.nav)
case <-app.ticker.C:
app.nav.renew()
app.ui.loadFile(app.nav, false)
app.ui.draw(app.nav)
}
}
}
func (app *app) exportVars() {
var envFile string
if f, err := app.nav.currFile(); err == nil {
envFile = f.path
func (app *app) exportFiles() {
var currFile string
if curr, err := app.nav.currFile(); err == nil {
currFile = curr.path
}
marks := app.nav.currMarks()
currSelections := app.nav.currSelections()
envFiles := strings.Join(marks, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(marks) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
os.Setenv("id", strconv.Itoa(gClientID))
exportFiles(currFile, currSelections, app.nav.currDir().path)
}
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 command in shell. Following modes are used:
// This function is used to run a shell command. Modes are as follows:
//
// Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume
// % No No Yes Yes Yes Use statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing
// Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume
// % No No Yes Yes Yes Statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) {
app.exportVars()
app.exportFiles()
exportOpts()
cmd := shellCommand(s, args)
var out io.Reader
var err error
switch prefix {
case "$", "!":
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
app.ui.pause()
defer app.ui.resume()
defer app.nav.renew(app.ui.wins[0].h)
app.nav.previewChan <- ""
if err := app.ui.suspend(); err != nil {
log.Printf("suspend: %s", err)
}
defer func() {
if err := app.ui.resume(); err != nil {
app.quit()
os.Exit(3)
return
}
}()
defer app.nav.renew()
err = cmd.Run()
case "%":
if app.ui.cmdPrefix == ">" {
return
}
stdin, err := cmd.StdinPipe()
if err != nil {
log.Printf("writing stdin: %s", err)
@@ -206,49 +509,50 @@ func (app *app) runShell(s string, args []string, prefix string) {
}
out = stdout
cmd.Stderr = cmd.Stdout
}
var err error
switch prefix {
case "$", "!":
err = cmd.Run()
case "%", "&":
fallthrough
case "&":
err = cmd.Start()
}
if err != nil {
app.ui.printf("running shell: %s", err)
app.ui.echoerrf("running shell: %s", err)
}
switch prefix {
case "!":
if err := waitKey(); err != nil {
app.ui.printf("waiting key: %s", err)
}
anyKey()
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
app.ui.loadFile(app.nav, true)
switch prefix {
case "%":
go func() {
app.cmd = cmd
app.cmdOutBuf = nil
app.ui.msg = ""
app.ui.cmdPrefix = ">"
normal(app)
app.cmd = cmd
app.cmdOutBuf = nil
app.ui.msg = ""
app.ui.cmdPrefix = ">"
go func() {
eol := false
reader := bufio.NewReader(out)
for {
b, err := reader.ReadByte()
if err == io.EOF {
break
}
app.cmdOutBuf = append(app.cmdOutBuf, b)
app.ui.exprChan <- multiExpr{&callExpr{"echo", []string{string(app.cmdOutBuf)}}, 1}
if b == '\n' || b == '\r' {
if eol {
eol = false
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 {
@@ -256,7 +560,13 @@ func (app *app) runShell(s string, args []string, prefix string) {
}
app.cmd = nil
app.ui.cmdPrefix = ""
app.ui.exprChan <- multiExpr{&callExpr{"reload", nil}, 1}
app.ui.exprChan <- &callExpr{"load", nil, 1}
}()
case "&":
go func() {
if err := cmd.Wait(); err != nil {
log.Printf("running shell: %s", err)
}
}()
}
}
+38 -81
View File
@@ -8,50 +8,70 @@ import (
"net"
"os"
"strings"
"time"
"github.com/nsf/termbox-go"
"github.com/gdamore/tcell/v2"
)
func run() {
logFile, err := os.Create(gLogPath)
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)
if err != nil {
panic(err)
}
defer os.Remove(gLogPath)
defer logFile.Close()
log.SetOutput(logFile)
defer f.Close()
log.SetOutput(f)
log.Print("hi!")
if err := termbox.Init(); err != nil {
log.Fatalf("initializing termbox: %s", err)
ui := newUI(screen)
nav := newNav(ui.wins[0].h)
app := newApp(ui, nav)
if err := nav.sync(); err != nil {
app.ui.echoerrf("sync: %s", err)
}
defer termbox.Close()
termbox.SetOutputMode(termbox.Output256)
if err := app.nav.readMarks(); err != nil {
app.ui.echoerrf("reading marks file: %s", err)
}
app := newApp()
if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) {
app.readFile(gConfigPath)
if err := app.readHistory(); err != nil {
app.ui.echoerrf("reading history file: %s", err)
}
app.loop()
app.ui.screen.Fini()
}
func readExpr() <-chan expr {
ch := make(chan expr)
go func() {
duration := 1 * time.Second
c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err))
return
for err != nil {
log.Printf("connecting server: %s", err)
time.Sleep(duration)
duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath)
}
fmt.Fprintf(c, "conn %d\n", gClientID)
ch <- &callExpr{"sync", nil}
ch <- &callExpr{"sync", nil, 1}
s := bufio.NewScanner(c)
for s.Scan() {
@@ -68,70 +88,7 @@ func readExpr() <-chan expr {
return ch
}
func saveFiles(list []string, copy bool) error {
c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil {
return fmt.Errorf("dialing to save files: %s", err)
}
defer c.Close()
log.Printf("saving files: %v", list)
fmt.Fprintln(c, "save")
if copy {
fmt.Fprintln(c, "copy")
} else {
fmt.Fprintln(c, "move")
}
for _, f := range list {
fmt.Fprintln(c, f)
}
fmt.Fprintln(c)
return nil
}
func loadFiles() (list []string, copy bool, err error) {
c, e := net.Dial(gSocketProt, gSocketPath)
if e != nil {
err = fmt.Errorf("dialing to load files: %s", e)
return
}
defer c.Close()
fmt.Fprintln(c, "load")
s := bufio.NewScanner(c)
s.Scan()
switch s.Text() {
case "copy":
copy = true
case "move":
copy = false
default:
err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text())
return
}
for s.Scan() && s.Text() != "" {
list = append(list, s.Text())
}
if s.Err() != nil {
err = fmt.Errorf("scanning file list: %s", s.Err())
return
}
log.Printf("loading files: %v", list)
return
}
func sendRemote(cmd string) error {
func remote(cmd string) error {
c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil {
return fmt.Errorf("dialing to send server: %s", err)
+292
View File
@@ -0,0 +1,292 @@
package main
import (
"log"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/gdamore/tcell/v2"
)
type styleMap map[string]tcell.Style
func parseStyles() styleMap {
sm := make(styleMap)
// Default values from dircolors
//
// 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)
// default values from dircolors with background colors removed
defaultColors := []string{
"fi=00",
"di=01;34",
"ln=01;36",
"pi=33",
"so=01;35",
"bd=33;01",
"cd=33;01",
"or=31;01",
"su=01;32",
"sg=01;32",
"tw=01;34",
"ow=01;34",
"st=01;34",
"ex=01;32",
}
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, st tcell.Style) tcell.Style {
toks := strings.Split(s, ";")
var nums []int
for _, tok := range toks {
if tok == "" {
nums = append(nums, 0)
continue
}
n, err := strconv.Atoi(tok)
if err != nil {
log.Printf("converting escape code: %s", err)
continue
}
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++ {
n := nums[i]
switch {
case n == 0:
st = tcell.StyleDefault
case n == 1:
st = st.Bold(true)
case n == 2:
st = st.Dim(true)
case n == 4:
st = st.Underline(true)
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 >= 90 && n <= 97:
st = st.Foreground(tcell.PaletteColor(n - 82))
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 >= 100 && n <= 107:
st = st.Background(tcell.PaletteColor(n - 92))
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 st
}
// This function parses $LS_COLORS environment variable.
func (sm styleMap) parseGNU(env string) {
for _, entry := range strings.Split(env, ":") {
if entry == "" {
continue
}
pair := strings.Split(entry, "=")
if len(pair) != 2 {
log.Printf("invalid $LS_COLORS entry: %s", entry)
return
}
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.
func (sm styleMap) parseBSD(env string) {
if len(env) != 22 {
log.Printf("invalid $LSCOLORS variable: %s", env)
return
}
colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"}
getStyle := func(r1, r2 byte) tcell.Style {
st := tcell.StyleDefault
switch {
case r1 == 'x':
st = st.Foreground(tcell.ColorDefault)
case 'A' <= r1 && r1 <= 'H':
st = st.Foreground(tcell.PaletteColor(int(r1 - 'A'))).Bold(true)
case 'a' <= r1 && r1 <= 'h':
st = st.Foreground(tcell.PaletteColor(int(r1 - 'a')))
default:
log.Printf("invalid $LSCOLORS entry: %c", r1)
return tcell.StyleDefault
}
switch {
case r2 == 'x':
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
}
return st
}
for i, key := range colorNames {
sm[key] = getStyle(env[i*2], env[i*2+1])
}
}
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
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 := sm[key]; ok {
return val
}
if val, ok := sm[f.Name()+"*"]; ok {
return val
}
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
}
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"testing"
"github.com/gdamore/tcell/v2"
)
func TestApplyAnsiCodes(t *testing.T) {
none := tcell.StyleDefault
tests := []struct {
s string
st tcell.Style
stExp tcell.Style
}{
{"", none, none},
{"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"", none.Bold(true), none},
{"", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"0", none, none},
{"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none},
{"0", none.Bold(true), none},
{"0", none.Foreground(tcell.ColorMaroon).Bold(true), none},
{"1", none, none.Bold(true)},
{"4", none, none.Underline(true)},
{"7", none, none.Reverse(true)},
{"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)},
{"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)},
{"4", none.Bold(true), none.Bold(true).Underline(true)},
{"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)},
{"31", none, none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"41", none, none.Background(tcell.ColorMaroon)},
{"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"38;5;0", none, none.Foreground(tcell.ColorBlack)},
{"38;5;1", none, none.Foreground(tcell.ColorMaroon)},
{"38;5;8", none, none.Foreground(tcell.ColorGray)},
{"38;5;16", none, none.Foreground(tcell.Color16)},
{"38;5;232", none, none.Foreground(tcell.Color232)},
{"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)},
{"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)},
{"48;5;0", none, none.Background(tcell.ColorBlack)},
{"48;5;1", none, none.Background(tcell.ColorMaroon)},
{"48;5;8", none, none.Background(tcell.ColorGray)},
{"48;5;16", none, none.Background(tcell.Color16)},
{"48;5;232", none, none.Background(tcell.Color232)},
{"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)},
{"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)},
{"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 {
if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp {
t.Errorf("at input '%s' with '%d' expected '%d' but got '%d'",
test.s, test.st, test.stExp, stGot)
}
}
}
-282
View File
@@ -1,282 +0,0 @@
package main
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
)
var (
gCmdWords = []string{
"set",
"map",
"cmd",
"up",
"half-up",
"page-up",
"down",
"half-down",
"page-down",
"updir",
"open",
"quit",
"top",
"bot",
"toggle",
"invert",
"unmark",
"yank",
"delete",
"put",
"clear",
"redraw",
"reload",
"read",
"shell",
"shell-pipe",
"shell-wait",
"shell-async",
"search",
"search-back",
"search-next",
"search-prev",
"sync",
"echo",
"cd",
"select",
"push",
}
gOptWords = []string{
"dircounts",
"nodircounts",
"dircounts!",
"dirfirst",
"nodirfirst",
"dirfirst!",
"globsearch",
"noglobsearch",
"globsearch!",
"hidden",
"nohidden",
"hidden!",
"ignorecase",
"noignorecase",
"ignorecase!",
"preview",
"nopreview",
"preview!",
"reverse",
"noreverse",
"reverse!",
"smartcase",
"nosmartcase",
"smartcase!",
"wrapscan",
"nowrapscan",
"wrapscan!",
"scrolloff",
"tabstop",
"filesep",
"ifs",
"previewer",
"promptfmt",
"shell",
"sortby",
"timefmt",
"ratios",
"info",
}
)
func matchLongest(s1, s2 string) string {
i := 0
for ; i < len(s1) && i < len(s2); i++ {
if s1[i] != s2[i] {
break
}
}
return s1[:i]
}
func matchWord(s string, words []string) (matches []string, longest string) {
for _, w := range words {
if strings.HasPrefix(w, s) {
matches = append(matches, w)
if longest != "" {
longest = matchLongest(longest, w)
} else if s != "" {
longest = w + " "
}
}
}
if longest == "" {
longest = s
}
return
}
func matchExec(s string) (matches []string, longest string) {
var words []string
paths := strings.Split(envPath, ":")
for _, p := range paths {
if _, err := os.Stat(p); os.IsNotExist(err) {
continue
}
fi, err := ioutil.ReadDir(p)
if err != nil {
log.Printf("reading path: %s", err)
}
for _, f := range fi {
if strings.HasPrefix(f.Name(), s) {
f, err = os.Stat(filepath.Join(p, f.Name()))
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
if !f.Mode().IsRegular() || f.Mode()&0111 == 0 {
continue
}
words = append(words, f.Name())
}
}
}
sort.Strings(words)
if len(words) > 0 {
uniq := words[:1]
for i := 1; i < len(words); i++ {
if words[i] != words[i-1] {
uniq = append(uniq, words[i])
}
}
words = uniq
}
return matchWord(s, words)
}
func matchFile(s string) (matches []string, longest string) {
dir := strings.Replace(s, "~", gUser.HomeDir, -1)
if !filepath.IsAbs(dir) {
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
dir = wd + string(filepath.Separator) + dir
}
dir = unescape(filepath.Dir(dir))
fi, err := ioutil.ReadDir(dir)
if err != nil {
log.Printf("reading directory: %s", err)
}
for _, f := range fi {
f, err := os.Stat(filepath.Join(dir, f.Name()))
if err != nil {
log.Printf("getting file information: %s", err)
return
}
_, last := filepath.Split(s)
if strings.HasPrefix(escape(f.Name()), last) {
name := f.Name()
if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(s), f.Name())
}
name = escape(name)
item := f.Name()
if f.Mode().IsDir() {
item += string(filepath.Separator)
}
matches = append(matches, item)
if longest != "" {
longest = matchLongest(longest, name)
} else if s != "" {
if f.Mode().IsRegular() {
longest = name + " "
} else {
longest = name + string(filepath.Separator)
}
}
}
}
if longest == "" {
longest = s
}
return
}
func compCmd(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
var longest string
switch len(f) {
case 1:
words := gCmdWords
for c := range gOpts.cmds {
words = append(words, c)
}
sort.Strings(words)
matches, longest = matchWord(s, words)
longestAcc = []rune(longest)
case 2:
switch f[0] {
case "set":
matches, longest = matchWord(f[1], gOptWords)
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
case "map", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
}
default:
switch f[0] {
case "set", "map", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
}
}
return
}
func compShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
var longest string
switch len(f) {
case 1:
matches, longest = matchExec(s)
longestAcc = []rune(longest)
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
}
return
}
+414
View File
@@ -0,0 +1,414 @@
package main
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"sort"
"strings"
)
var (
gCmdWords = []string{
"set",
"map",
"cmd",
"up",
"half-up",
"page-up",
"down",
"half-down",
"page-down",
"updir",
"open",
"quit",
"top",
"bottom",
"toggle",
"invert",
"unselect",
"copy",
"cut",
"paste",
"clear",
"redraw",
"reload",
"read",
"rename",
"shell",
"shell-pipe",
"shell-wait",
"shell-async",
"find",
"find-back",
"find-next",
"find-prev",
"search",
"search-back",
"search-next",
"search-prev",
"filter",
"setfilter",
"mark-save",
"mark-remove",
"mark-load",
"draw",
"load",
"sync",
"echo",
"echomsg",
"echoerr",
"cd",
"select",
"glob-select",
"glob-unselect",
"source",
"push",
"delete",
}
gOptWords = []string{
"anchorfind",
"noanchorfind",
"anchorfind!",
"autoquit",
"noautoquit",
"autoquit!",
"dircache",
"nodircache",
"dircache!",
"dircounts",
"nodircounts",
"dircounts!",
"dirfirst",
"nodirfirst",
"dirfirst!",
"dironly",
"nodironly",
"dironly!",
"drawbox",
"nodrawbox",
"drawbox!",
"globsearch",
"noglobsearch",
"globsearch!",
"hidden",
"nohidden",
"hidden!",
"icons",
"noicons",
"icons!",
"ignorecase",
"noignorecase",
"ignorecase!",
"ignoredia",
"noignoredia",
"ignoredia!",
"incsearch",
"noincsearch",
"incsearch!",
"incfilter",
"noincfilter",
"incfilter!",
"mouse",
"nomouse",
"mouse!",
"number",
"nonumber",
"number!",
"preview",
"nopreview",
"preview!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"reverse",
"noreverse",
"reverse!",
"smartcase",
"nosmartcase",
"smartcase!",
"smartdia",
"nosmartdia",
"smartdia!",
"waitmsg",
"wrapscan",
"nowrapscan",
"wrapscan!",
"wrapscroll",
"nowrapscroll",
"wrapscroll!",
"findlen",
"period",
"scrolloff",
"tabstop",
"errorfmt",
"filesep",
"hiddenfiles",
"ifs",
"info",
"previewer",
"cleaner",
"promptfmt",
"ratios",
"shell",
"shellflag",
"shellopts",
"sortby",
"timefmt",
"truncatechar",
}
)
func matchLongest(s1, s2 string) string {
i := 0
for ; i < len(s1) && i < len(s2); i++ {
if s1[i] != s2[i] {
break
}
}
return s1[:i]
}
func matchWord(s string, words []string) (matches []string, longest string) {
for _, w := range words {
if !strings.HasPrefix(w, s) {
continue
}
matches = append(matches, w)
if longest != "" {
longest = matchLongest(longest, w)
} else if s != "" {
longest = w + " "
}
}
if longest == "" {
longest = s
}
return
}
func matchExec(s string) (matches []string, longest string) {
var words []string
paths := strings.Split(envPath, string(filepath.ListSeparator))
for _, p := range paths {
if _, err := os.Stat(p); os.IsNotExist(err) {
continue
}
files, err := ioutil.ReadDir(p)
if err != nil {
log.Printf("reading path: %s", err)
}
for _, f := range files {
if !strings.HasPrefix(f.Name(), s) {
continue
}
f, err = os.Stat(filepath.Join(p, f.Name()))
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
if !f.Mode().IsRegular() || !isExecutable(f) {
continue
}
log.Print(f.Name())
words = append(words, f.Name())
}
}
sort.Strings(words)
if len(words) > 0 {
uniq := words[:1]
for i := 1; i < len(words); i++ {
if words[i] != words[i-1] {
uniq = append(uniq, words[i])
}
}
words = uniq
}
return matchWord(s, words)
}
func matchFile(s string) (matches []string, longest string) {
dir := replaceTilde(s)
if !filepath.IsAbs(dir) {
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
} else {
dir = wd + string(filepath.Separator) + dir
}
}
dir = unescape(filepath.Dir(dir))
files, err := ioutil.ReadDir(dir)
if err != nil {
log.Printf("reading directory: %s", err)
}
for _, f := range files {
name := filepath.Join(dir, f.Name())
f, err := os.Stat(name)
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)
return
}
}
_, last := filepath.Split(s)
if !strings.HasPrefix(escape(f.Name()), last) {
continue
}
name = f.Name()
if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
}
name = escape(name)
item := f.Name()
if f.Mode().IsDir() {
item += escape(string(filepath.Separator))
}
matches = append(matches, item)
if longest != "" {
longest = matchLongest(longest, name)
} else if s != "" {
if f.Mode().IsRegular() {
longest = name + " "
} else {
longest = name + escape(string(filepath.Separator))
}
}
}
if longest == "" {
longest = s
}
return
}
func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
var longest string
switch len(f) {
case 1:
words := gCmdWords
for c := range gOpts.cmds {
words = append(words, c)
}
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)
longestAcc = []rune(longest)
case 2:
switch f[0] {
case "set":
matches, longest = matchWord(f[1], gOptWords)
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
case "map", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
}
default:
switch f[0] {
case "set", "map", "cmd":
longestAcc = acc
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
}
}
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) {
s := string(acc)
f := tokenize(s)
var longest string
switch len(f) {
case 1:
matches, longest = matchExec(s)
longestAcc = []rune(longest)
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...)
}
return
}
View File
File renamed without changes.
+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) + ", ")
}
}
+1164 -277
View File
File diff suppressed because it is too large. Load diff
+1220 -187
View File
File diff suppressed because it is too large. Load diff
+31
View File
@@ -0,0 +1,31 @@
# 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
-config
-cpuprofile
-doc
-last-dir-path
-memprofile
-remote
-selection-path
-server
-single
-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 -config -cpuprofile -doc -last-dir-path -memprofile -remote -selection-path -server -single -version -help "
complete lf "C/-*/(${LF_ARGS})/"
complete lfcd "C/-*/(${LF_ARGS})/"
+20
View File
@@ -0,0 +1,20 @@
# 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 config -r -d 'path to the config file (instead of the usual paths)'
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 single -d 'start a client without server'
complete -c lf -o version -d 'show version'
complete -c lf -o help -d 'show help'
+29
View File
@@ -0,0 +1,29 @@
# 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('-config ', '-config', [CompletionResultType]::ParameterName, 'path to the config file (instead of the usual paths)')
[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('-single', '-single', [CompletionResultType]::ParameterName, 'start a client without server')
[CompletionResult]::new('-version', '-version', [CompletionResultType]::ParameterName, 'show version')
[CompletionResult]::new('-help', '-help', [CompletionResultType]::ParameterName, 'show help')
)
if ($wordToComplete.StartsWith('-')) {
$completions.Where{ $_.CompletionText -like "$wordToComplete*" } | Sort-Object -Property ListItemText
}
}
+31
View File
@@ -0,0 +1,31 @@
#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]'
'-config[path to the config file (instead of the usual paths)]'
'-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)]'
'-single[start a client without server]'
'-version[show version]'
'-help[show help]'
'*: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
set tmpfile="%tmp%\lf.%random%.tmp"
if exist "%tmpfile%" goto:tmploop
lf -last-dir-path="%tmpfile%" %*
if not exist "%tmpfile%" exit
set /p dir=<"%tmpfile%"
del /f "%tmpfile%"
if exist %tmpfile% goto:tmploop
lf -last-dir-path=%tmpfile% %*
if not exist %tmpfile% exit
set /p dir=<%tmpfile%
del /f %tmpfile%
if not exist "%dir%" 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:
#
# 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
set tmp (mktemp)
+15 -4
View File
@@ -1,13 +1,24 @@
# 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 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()
lf -last-dir-path="$tmp" $args
if (test-path -pathtype leaf "$tmp") {
$dir = type "$tmp"
remove-item -force "$tmp"
if (test-path -pathtype container "$dir") {
if (Test-Path -PathType Leaf "$tmp") {
$dir = Get-Content "$tmp"
Remove-Item -Force "$tmp"
if (Test-Path -PathType Container "$dir") {
if ("$dir" -ne "$pwd") {
cd "$dir"
}
+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
+48 -25
View File
@@ -1,6 +1,15 @@
# interpreter for shell commands (needs to be POSIX compatible)
# interpreter for shell commands
set shell sh
# set '-eu' options for shell commands
# These options are used to have safer shell commands. Option '-e' is used to
# exit on error and option '-u' is used to give error for unset variables.
# Option '-f' disables pathname expansion which can be useful when $f, $fs, and
# $fx variables contain names with '*' or '?' characters. However, this option
# is used selectively within individual commands as it can be limiting at
# times.
set shellopts '-eu'
# set internal field separator (IFS) to "\n" for shell commands
# This is useful to automatically split file names in $fs and $fx properly
# since default file separator used in these variables (i.e. 'filesep' option)
@@ -22,42 +31,46 @@ map X !$f
map o &mimeopen $f
map O $mimeopen --ask $f
# show documentation (overrides 'search-back' command)
map ? $lf -doc | less
# define a custom 'open-file' command
# 'open-file' is called by 'open' when current file is not a directory. You may
# want to use either file extensions and/or mime types here. Below uses an
# editor for text files and a file opener for the rest.
cmd open-file ${{
# define a custom 'open' command
# This command is called when current file is not a directory. You may want to
# use either file extensions and/or mime types here. Below uses an editor for
# text files and a file opener for the rest.
cmd open ${{
test -L $f && f=$(readlink -f $f)
case $(file --mime-type $f -b) in
text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
text/*) $EDITOR $fx;;
*) for f in $fx; do setsid $OPENER $f > /dev/null 2> /dev/null & done;;
esac
}}
# rename current file without overwrite
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
map r push :rename<space>
# define a custom 'rename' command without prompt for overwrite
# cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
# map r push :rename<space>
# make sure trash folder exists
%mkdir -p ~/.trash
# %mkdir -p ~/.trash
# move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options)
cmd trash %mv $fx ~/.trash
cmd trash %set -f; mv $fx ~/.trash
# remove current file or selected files (prompting)
cmd remove ${{
printf "$fx\n"
printf "remove?[y/n]"
read ans
[ $ans = "y" ] && rm -rf $fx
}}
# define a custom 'delete' command
# cmd delete ${{
# set -f
# printf "$fx\n"
# printf "delete?[y/n]"
# read ans
# [ $ans = "y" ] && rm -rf $fx
# }}
# use '<delete>' key for either 'trash' or 'delete' command
# map <delete> trash
# map <delete> delete
# extract the current file with the right command
# (xkcd link: https://xkcd.com/1168/)
cmd extract %{{
cmd extract ${{
set -f
case $f in
*.tar.bz|*.tar.bz2|*.tbz|*.tbz2) tar xjvf $f;;
*.tar.gz|*.tgz) tar xzvf $f;;
@@ -69,9 +82,19 @@ cmd extract %{{
}}
# compress current file or selected files with tar and gunzip
cmd compress %{{
cmd tar ${{
set -f
mkdir $1
cp -r $fx $1
tar czf $1.tar.gz $1
rm -rf $1
}}
# compress current file or selected files with zip
cmd zip ${{
set -f
mkdir $1
cp -r $fx $1
zip -r $1.zip $1
rm -rf $1
}}
+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
+1524 -249
View File
File diff suppressed because it is too large. Load diff
+86 -48
View File
@@ -26,85 +26,91 @@ var gEvalTests = []struct {
{
"echo hello",
[]string{"echo", "hello", "\n"},
[]expr{&callExpr{"echo", []string{"hello"}}},
[]expr{&callExpr{"echo", []string{"hello"}, 1}},
},
{
"echo hello world",
[]string{"echo", "hello", "world", "\n"},
[]expr{&callExpr{"echo", []string{"hello", "world"}}},
[]expr{&callExpr{"echo", []string{"hello", "world"}, 1}},
},
{
"echo 'hello world'",
[]string{"echo", "hello world", "\n"},
[]expr{&callExpr{"echo", []string{"hello world"}}},
[]expr{&callExpr{"echo", []string{"hello world"}, 1}},
},
{
`echo "hello world"`,
[]string{"echo", "hello world", "\n"},
[]expr{&callExpr{"echo", []string{"hello world"}}},
[]expr{&callExpr{"echo", []string{"hello world"}, 1}},
},
{
`echo "hello\"world"`,
[]string{"echo", `hello"world`, "\n"},
[]expr{&callExpr{"echo", []string{`hello"world`}}},
[]expr{&callExpr{"echo", []string{`hello"world`}, 1}},
},
{
`echo "hello\tworld"`,
[]string{"echo", "hello\tworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\tworld"}}},
[]expr{&callExpr{"echo", []string{"hello\tworld"}, 1}},
},
{
`echo "hello\nworld"`,
[]string{"echo", "hello\nworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\nworld"}}},
[]expr{&callExpr{"echo", []string{"hello\nworld"}, 1}},
},
{
`echo "hello\zworld"`,
[]string{"echo", "helloworld", "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}}},
[]string{"echo", `hello\zworld`, "\n"},
[]expr{&callExpr{"echo", []string{`hello\zworld`}, 1}},
},
{
`echo "hello\0world"`,
[]string{"echo", "hello\000world", "\n"},
[]expr{&callExpr{"echo", []string{"hello\000world"}}},
[]expr{&callExpr{"echo", []string{"hello\000world"}, 1}},
},
{
`echo "hello\101world"`,
[]string{"echo", "hello\101world", "\n"},
[]expr{&callExpr{"echo", []string{"hello\101world"}}},
[]expr{&callExpr{"echo", []string{"hello\101world"}, 1}},
},
{
`echo hello\ world`,
[]string{"echo", "hello world", "\n"},
[]expr{&callExpr{"echo", []string{"hello world"}}},
[]expr{&callExpr{"echo", []string{"hello world"}, 1}},
},
{
`echo hello\ world`,
"echo hello\\\tworld",
[]string{"echo", "hello\tworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\tworld"}}},
[]expr{&callExpr{"echo", []string{"hello\tworld"}, 1}},
},
{
"echo hello\\\nworld",
[]string{"echo", "hello\nworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\nworld"}}},
[]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`,
[]string{"echo", "helloworld", "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}}},
[]string{"echo", "hellozworld", "\n"},
[]expr{&callExpr{"echo", []string{"hellozworld"}, 1}},
},
{
@@ -125,6 +131,18 @@ var gEvalTests = []struct {
[]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",
[]string{"set", "ratios", "1:2:3", "\n"},
@@ -140,55 +158,67 @@ var gEvalTests = []struct {
{
":set ratios 1:2:3",
[]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",
[]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;",
[]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",
[]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", ""}},
},
{
"map gh cd ~",
[]string{"map", "gh", "cd", "~", "\n"},
[]expr{&mapExpr{"gh", &callExpr{"cd", []string{"~"}}}},
[]expr{&mapExpr{"gh", &callExpr{"cd", []string{"~"}, 1}}},
},
{
"map gh cd ~;",
[]string{"map", "gh", "cd", "~", ";"},
[]expr{&mapExpr{"gh", &callExpr{"cd", []string{"~"}}}},
[]expr{&mapExpr{"gh", &callExpr{"cd", []string{"~"}, 1}}},
},
{
"map gh :cd ~",
[]string{"map", "gh", ":", "cd", "~", "\n", "\n"},
[]expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}}}}}},
[]expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}, 1}}},
},
{
"map gh :cd ~;",
[]string{"map", "gh", ":", "cd", "~", ";", "\n"},
[]expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}}}}}},
[]expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}, 1}}},
},
{
"cmap <c-g> cmd-escape",
[]string{"cmap", "<c-g>", "cmd-escape", "\n"},
[]expr{&cmapExpr{"<c-g>", "cmd-escape"}},
[]expr{&cmapExpr{"<c-g>", &callExpr{"cmd-escape", nil, 1}}},
},
{
@@ -206,55 +236,55 @@ var gEvalTests = []struct {
{
"map u usage",
[]string{"map", "u", "usage", "\n"},
[]expr{&mapExpr{"u", &callExpr{"usage", nil}}},
[]expr{&mapExpr{"u", &callExpr{"usage", nil, 1}}},
},
{
"map u usage;",
[]string{"map", "u", "usage", ";"},
[]expr{&mapExpr{"u", &callExpr{"usage", nil}}},
[]expr{&mapExpr{"u", &callExpr{"usage", nil, 1}}},
},
{
"map u :usage",
[]string{"map", "u", ":", "usage", "\n", "\n"},
[]expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil}}}}},
[]expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}, 1}}},
},
{
"map u :usage;",
[]string{"map", "u", ":", "usage", ";", "\n"},
[]expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil}}}}},
[]expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}, 1}}},
},
{
"map r push :rename<space>",
[]string{"map", "r", "push", ":rename<space>", "\n"},
[]expr{&mapExpr{"r", &callExpr{"push", []string{":rename<space>"}}}},
[]expr{&mapExpr{"r", &callExpr{"push", []string{":rename<space>"}, 1}}},
},
{
"map r push :rename<space>;",
[]string{"map", "r", "push", ":rename<space>;", "\n"},
[]expr{&mapExpr{"r", &callExpr{"push", []string{":rename<space>;"}}}},
[]expr{&mapExpr{"r", &callExpr{"push", []string{":rename<space>;"}, 1}}},
},
{
"map r push :rename<space> # trailing comments are allowed after a space",
[]string{"map", "r", "push", ":rename<space>", "\n"},
[]expr{&mapExpr{"r", &callExpr{"push", []string{":rename<space>"}}}},
[]expr{&mapExpr{"r", &callExpr{"push", []string{":rename<space>"}, 1}}},
},
{
"map r :push :rename<space>",
[]string{"map", "r", ":", "push", ":rename<space>", "\n", "\n"},
[]expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}}}}}},
[]expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}, 1}}, 1}}},
},
{
"map r :push :rename<space> ; set hidden",
[]string{"map", "r", ":", "push", ":rename<space>", ";", "set", "hidden", "\n", "\n"},
[]expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}}, &setExpr{"hidden", ""}}}}},
[]expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename<space>"}, 1}, &setExpr{"hidden", ""}}, 1}}},
},
{
@@ -272,19 +302,19 @@ var gEvalTests = []struct {
{
"map u usage /",
[]string{"map", "u", "usage", "/", "\n"},
[]expr{&mapExpr{"u", &callExpr{"usage", []string{"/"}}}},
[]expr{&mapExpr{"u", &callExpr{"usage", []string{"/"}, 1}}},
},
{
"map ss :set sortby size; set info size",
[]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;",
[]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 ~
set hidden
}}`,
[]string{"cmd", "gohome", ":", "{{",
[]string{
"cmd", "gohome", ":", "{{",
"cd", "~", "\n",
"set", "hidden", "\n",
"}}", "\n"},
[]expr{&cmdExpr{"gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}},
&setExpr{"hidden", ""}}},
"}}", "\n",
},
[]expr{&cmdExpr{
"gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}, 1},
}},
},
@@ -307,13 +341,17 @@ var gEvalTests = []struct {
cd ~
set hidden
}}`,
[]string{"map", "gh", ":", "{{",
[]string{
"map", "gh", ":", "{{",
"cd", "~", "\n",
"set", "hidden", "\n",
"}}", "\n"},
[]expr{&mapExpr{"gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}},
&setExpr{"hidden", ""}}},
"}}", "\n",
},
[]expr{&mapExpr{
"gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}, 1},
}},
},
Executable
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Builds a static stripped binary with version information.
#
# This script is used to build a binary for the current platform. Cgo is
# disabled to make sure the binary is statically linked. Appropriate flags are
# given to the go compiler to strip the binary. Current git tag is passed to
# the compiler by default to be used as the version in the binary.
[ -z $version ] && version=$(git describe --tags)
CGO_ENABLED=0 go build -ldflags="-s -w -X main.gVersion=$version" "$@"
+7 -7
View File
@@ -8,12 +8,12 @@
tmp=gen/docstring.go
echo "// DO NOT EDIT! (AUTO-GENERATED)" >> $tmp
echo >> $tmp
echo "package main" >> $tmp
echo >> $tmp
echo "var genDocString = \`" >> $tmp
go doc | tr "\`" "'" >> $tmp
echo "\`" >> $tmp
echo "// Code generated by gen/docstring.sh DO NOT EDIT." >> $tmp
echo >> $tmp
echo "package main" >> $tmp
echo >> $tmp
echo "var genDocString = \`" >> $tmp
go doc | tr "\`" "'" >> $tmp
echo "\`" >> $tmp
mv $tmp docstring.go
Executable
+73
View File
@@ -0,0 +1,73 @@
#!/bin/sh
# Generates `lf.1` man page using man macros with `go doc` output.
#
# This script is called in `doc.go` using `go generate` to generate a man page
# formatted with man macros from the documentation. A few additional sections
# such as `NAME` and `SYNOPSIS` are added to comply with man page conventions.
#
# Conversion logic implemented here from godoc output to man macros should not
# be considered compliant, as such it has inexact assumptions such as the use
# of spaces over tabs along with various corner cases that are not handled
# properly like character escaping. The intention here is to come up with
# something that can convert the current content in the documentation. For this
# reason, it is recommended to check the output after generation especially
# when the documentation is changed in a significant way.
out=lf.1
echo '.\" Code generated by gen/man.sh DO NOT EDIT.' > $out
cat << END >> $out
.TH LF 1
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
.SY lf
.OP \-command command
.OP \-config path
.OP \-cpuprofile path
.OP \-doc
.OP \-last-dir-path path
.OP \-memprofile path
.OP \-remote command
.OP \-selection-path path
.OP \-server
.OP \-single
.OP \-version
.OP \-help
.RI [ directory ]
.YS
.SH DESCRIPTION
END
go doc | awk '
BEGIN {
RS = ""
start = 1
}
# preformatted
/^ / {
gsub("\\\\", "\\e", $0)
print ".PP"
print ".EX"
print $0
print ".EE"
next
}
# heading
/^[^[:punct:]]*$/ {
print ".SH", toupper($0)
start = 1
next
}
# paragraph
{
gsub("\n", " ", $0)
gsub("\\\\", "\\e", $0)
if (start) { start = 0 } else { print ".PP" }
print $0
}
' >> $out
+46 -28
View File
@@ -3,38 +3,56 @@
#
# This script is used to build binaries for all supported platforms. Cgo is
# disabled to make sure binaries are statically linked. Appropriate flags are
# given to the go compiler to strip binaries. These are then compressed in an
# archive form (`.zip` for windows and `.tar.gz` for the rest) within a folder
# named `dist`.
# given to the go compiler to strip binaries. Current git tag is passed to the
# compiler by default to be used as the version in binaries. These are then
# compressed in an archive form (`.zip` for windows and `.tar.gz` for the rest)
# within a folder named `dist`.
set -o verbose
version=$(git describe --tags)
[ -z $version ] && version=$(git describe --tags)
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
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
# https://golang.org/doc/install/source#environment
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=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=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=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.3.1
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
)
+19
View File
@@ -0,0 +1,19 @@
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.3.1 h1:htEXmKMzurgcnNH3VqQA7GYlCpdl9LCSNpzFpZOKhJE=
github.com/gdamore/tcell/v2 v2.3.1/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/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 " "
}
+1535
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;
+185 -29
View File
@@ -4,18 +4,25 @@ import (
"flag"
"fmt"
"log"
"net"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"runtime/pprof"
"strconv"
"strings"
)
var (
envPath = os.Getenv("PATH")
envPath = os.Getenv("PATH")
envLevel = os.Getenv("LF_LEVEL")
)
type arrayFlag []string
var (
gSingleMode bool
gClientID int
gHostname string
gLastDirPath string
@@ -24,24 +31,159 @@ var (
gSocketPath string
gLogPath string
gServerLogPath string
gSelect string
gConfigPath string
gCommands arrayFlag
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() {
h, err := os.Hostname()
if err != nil {
log.Printf("hostname: %s", err)
}
gHostname = h
if envLevel == "" {
envLevel = "0"
}
}
func exportEnvVars() {
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
dir, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
os.Setenv("OLDPWD", dir)
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() {
cmd := exec.Command(os.Args[0], "-server")
cmd := detachedCommand(os.Args[0], "-server")
if err := cmd.Start(); err != nil {
log.Printf("starting server: %s", err)
}
}
func checkServer() {
if gSocketProt == "unix" {
if _, err := os.Stat(gSocketPath); os.IsNotExist(err) {
startServer()
} else if _, err := net.Dial(gSocketProt, gSocketPath); err != nil {
os.Remove(gSocketPath)
startServer()
}
} else {
if _, err := net.Dial(gSocketProt, gSocketPath); err != nil {
startServer()
}
}
}
func main() {
showDoc := flag.Bool(
"doc",
@@ -53,16 +195,21 @@ func main() {
false,
"show version")
remoteCmd := flag.String(
"remote",
"",
"send remote command to server")
serverMode := flag.Bool(
"server",
false,
"start server (automatic)")
singleMode := flag.Bool(
"single",
false,
"start a client without server")
remoteCmd := flag.String(
"remote",
"",
"send remote command to server")
cpuprofile := flag.String(
"cpuprofile",
"",
@@ -83,6 +230,15 @@ func main() {
"",
"path to the file to write selected files on open (to use as open file dialog)")
flag.StringVar(&gConfigPath,
"config",
"",
"path to the config file (instead of the usual paths)")
flag.Var(&gCommands,
"command",
"command to execute on client initialization")
flag.Parse()
gSocketProt = gDefaultSocketProt
@@ -99,44 +255,44 @@ func main() {
defer pprof.StopCPUProfile()
}
switch flag.NArg() {
case 0:
case 1:
dir := flag.Arg(0)
if err := os.Chdir(dir); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
default:
fmt.Fprintf(os.Stderr, "only single directory is allowed\n")
os.Exit(2)
}
switch {
case *showDoc:
fmt.Print(genDocString)
case *showVersion:
fmt.Println(gVersion)
case *remoteCmd != "":
if err := sendRemote(*remoteCmd); err != nil {
if err := remote(*remoteCmd); err != nil {
log.Fatalf("remote command: %s", err)
}
case *serverMode:
os.Chdir(gUser.HomeDir)
gServerLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.server.log", gUser.Username))
serve()
default:
// TODO: check if the socket is working
if _, err := os.Stat(gSocketPath); os.IsNotExist(err) {
startServer()
gSingleMode = *singleMode
if !gSingleMode {
checkServer()
}
gClientID = 1000
gClientID = os.Getpid()
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() {
case 0:
_, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
case 1:
gSelect = flag.Arg(0)
default:
fmt.Fprintf(os.Stderr, "only single file or directory is allowed\n")
os.Exit(2)
}
exportEnvVars()
run()
}
+68 -46
View File
@@ -13,6 +13,13 @@ import (
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 {
w := 0
for _, r := range rs {
@@ -41,22 +48,12 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune {
return nil
}
// This function is used to escape whitespaces with backlashes in a given
// string. If a whitespace is already escaped then it is not escaped again.
// This function is used to escape whitespaces and special characters with
// backlashes in a given string.
func escape(s string) string {
esc := false
buf := make([]rune, 0, len(s))
for _, r := range s {
if r == '\\' {
esc = true
continue
}
if esc {
esc = false
buf = append(buf, '\\', r)
continue
}
if unicode.IsSpace(r) {
if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
@@ -65,26 +62,29 @@ func escape(s string) string {
}
// This function is used to remove backlashes that are used to escape
// whitespaces in a given string.
// whitespaces and special characters in a given string.
func unescape(s string) string {
esc := false
buf := make([]rune, 0, len(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 == '\\' {
esc = true
continue
}
if esc {
esc = false
if unicode.IsSpace(r) {
buf = append(buf, r)
} else {
buf = append(buf, '\\', r)
}
continue
}
esc = false
buf = append(buf, r)
}
if esc {
buf = append(buf, '\\')
}
return string(buf)
}
@@ -133,11 +133,10 @@ func splitWord(s string) (word, rest string) {
return
}
// This function converts a size in bytes to a human readable form. For this
// purpose metric suffixes are used (e.g. 1K = 1000). For values less than 10
// the first significant digit is shown, otherwise it is hidden. Numbers are
// always rounded down. For these reasons this function always show somewhat
// smaller values but it should be fine for most human beings.
// This function converts a size in bytes to a human readable form using metric
// suffixes (e.g. 1K = 1000). For values less than 10 the first significant
// digit is shown, otherwise it is hidden. Numbers are always rounded down.
// This should be fine for most human beings.
func humanize(size int64) string {
if size < 1000 {
return fmt.Sprintf("%dB", size)
@@ -167,34 +166,53 @@ func humanize(size int64) string {
return ""
}
// This regexp is used to partition a given string as numbers and non-numbers.
// For instance, if your input is 'foo123bar456' you get a slice of 'foo',
// '123', 'bar', and '456'. This is useful for natural sorting which takes into
// account values of numbers within strings.
var rePart = regexp.MustCompile(`\d+|\D+`)
// This function compares two strings for natural sorting which takes into
// account values of numbers in strings. For example, '2' is less than '10',
// and similarly 'foo2bar' is less than 'foo10bar', but 'bar2bar' is greater
// than 'foo10bar'.
func naturalLess(s1, s2 string) bool {
parts1 := rePart.FindAllString(s1, -1)
parts2 := rePart.FindAllString(s2, -1)
lo1, lo2, hi1, hi2 := 0, 0, 0, 0
for {
if hi1 >= len(s1) {
return hi2 != len(s2)
}
for i := 0; i < len(parts1) && i < len(parts2); i++ {
if parts1[i] == parts2[i] {
if hi2 >= len(s2) {
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
}
num1, err1 := strconv.Atoi(parts1[i])
num2, err2 := strconv.Atoi(parts2[i])
if isDigit1 && isDigit2 {
num1, err1 := strconv.Atoi(s1[lo1:hi1])
num2, err2 := strconv.Atoi(s2[lo2:hi2])
if err1 == nil && err2 == nil {
return num1 < num2
if err1 == nil && err2 == nil {
return num1 < num2
}
}
return parts1[i] < parts2[i]
return s1[lo1:hi1] < s2[lo2:hi2]
}
return len(parts1) < len(parts2)
}
var reAltKey = regexp.MustCompile(`<a-(.)>`)
var reWord = regexp.MustCompile(`(\pL|\pN)+`)
var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
var reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
func min(a, b int) int {
if a < b {
return a
@@ -209,8 +227,12 @@ func max(a, b int) int {
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 thought control
// We don't need no type control
// No dark templates in compiler
// Haskell leave them kids alone
// Hey Bjarne leave them kids alone
+14 -3
View File
@@ -80,8 +80,13 @@ func TestEscape(t *testing.T) {
{"foo", "foo"},
{"foo 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 {
@@ -98,9 +103,15 @@ func TestUnescape(t *testing.T) {
}{
{"", ""},
{"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\\tbar`, `foo\tbar`},
{"foo\\\tbar", "foo\tbar"},
{`foo\`, `foo\`},
}
for _, test := range tests {
+1008 -301
View File
File diff suppressed because it is too large. Load diff
+181 -93
View File
@@ -2,89 +2,168 @@ package main
import "time"
type sortMethod byte
const (
naturalSort sortMethod = iota
nameSort
sizeSort
timeSort
atimeSort
ctimeSort
extSort
)
type sortOption byte
const (
dirfirstSort sortOption = 1 << iota
hiddenSort
reverseSort
)
type sortType struct {
method sortMethod
option sortOption
}
var gOpts struct {
dircounts bool
dirfirst bool
globsearch bool
hidden bool
ignorecase bool
preview bool
reverse bool
smartcase bool
wrapscan bool
scrolloff int
tabstop int
filesep string
ifs string
previewer string
promptfmt string
shell string
sortby string
timefmt string
ratios []int
info []string
keys map[string]expr
cmdkeys map[string]expr
cmds map[string]expr
anchorfind bool
autoquit bool
dircache bool
dircounts bool
dironly bool
drawbox bool
globsearch bool
icons bool
ignorecase bool
ignoredia bool
incfilter bool
incsearch bool
mouse bool
number bool
preview bool
relativenumber bool
smartcase bool
smartdia bool
waitmsg string
wrapscan bool
wrapscroll bool
findlen int
period int
scrolloff int
tabstop int
errorfmt string
filesep string
ifs string
previewer string
cleaner string
promptfmt string
shell string
shellflag string
timefmt string
truncatechar string
ratios []int
hiddenfiles []string
info []string
shellopts []string
keys map[string]expr
cmdkeys map[string]expr
cmds map[string]expr
sortType sortType
}
func init() {
gOpts.anchorfind = true
gOpts.autoquit = false
gOpts.dircache = true
gOpts.dircounts = false
gOpts.dirfirst = true
gOpts.dironly = false
gOpts.drawbox = false
gOpts.globsearch = false
gOpts.hidden = false
gOpts.icons = false
gOpts.ignorecase = true
gOpts.ignoredia = true
gOpts.incfilter = false
gOpts.incsearch = false
gOpts.mouse = false
gOpts.number = false
gOpts.preview = true
gOpts.reverse = false
gOpts.relativenumber = false
gOpts.smartcase = true
gOpts.smartdia = false
gOpts.waitmsg = "Press any key to continue"
gOpts.wrapscan = true
gOpts.wrapscroll = false
gOpts.findlen = 1
gOpts.period = 0
gOpts.scrolloff = 0
gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m%s\033[0m"
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.sortby = "natural"
gOpts.shellflag = gDefaultShellFlag
gOpts.timefmt = time.ANSIC
gOpts.truncatechar = "~"
gOpts.ratios = []int{1, 2, 3}
gOpts.hiddenfiles = []string{".*"}
gOpts.info = nil
gOpts.shellopts = nil
gOpts.sortType = sortType{naturalSort, dirfirstSort}
gOpts.keys = make(map[string]expr)
gOpts.keys["k"] = &callExpr{"up", nil}
gOpts.keys["<up>"] = &callExpr{"up", nil}
gOpts.keys["<c-u>"] = &callExpr{"half-up", nil}
gOpts.keys["<c-b>"] = &callExpr{"page-up", nil}
gOpts.keys["j"] = &callExpr{"down", nil}
gOpts.keys["<down>"] = &callExpr{"down", nil}
gOpts.keys["<c-d>"] = &callExpr{"half-down", nil}
gOpts.keys["<c-f>"] = &callExpr{"page-down", nil}
gOpts.keys["h"] = &callExpr{"updir", nil}
gOpts.keys["<left>"] = &callExpr{"updir", nil}
gOpts.keys["l"] = &callExpr{"open", nil}
gOpts.keys["<right>"] = &callExpr{"open", nil}
gOpts.keys["q"] = &callExpr{"quit", nil}
gOpts.keys["gg"] = &callExpr{"top", nil}
gOpts.keys["G"] = &callExpr{"bot", nil}
gOpts.keys["<space>"] = &callExpr{"toggle", nil}
gOpts.keys["v"] = &callExpr{"invert", nil}
gOpts.keys["u"] = &callExpr{"unmark", nil}
gOpts.keys["y"] = &callExpr{"yank", nil}
gOpts.keys["d"] = &callExpr{"delete", nil}
gOpts.keys["c"] = &callExpr{"clear", nil}
gOpts.keys["p"] = &callExpr{"put", nil}
gOpts.keys["<c-l>"] = &callExpr{"redraw", nil}
gOpts.keys["<c-r>"] = &callExpr{"reload", nil}
gOpts.keys[":"] = &callExpr{"read", nil}
gOpts.keys["$"] = &callExpr{"shell", nil}
gOpts.keys["%"] = &callExpr{"shell-pipe", nil}
gOpts.keys["!"] = &callExpr{"shell-wait", nil}
gOpts.keys["&"] = &callExpr{"shell-async", nil}
gOpts.keys["/"] = &callExpr{"search", nil}
gOpts.keys["?"] = &callExpr{"search-back", nil}
gOpts.keys["n"] = &callExpr{"search-next", nil}
gOpts.keys["N"] = &callExpr{"search-prev", nil}
gOpts.keys["<c-n>"] = &callExpr{"cmd-hist-next", nil}
gOpts.keys["<c-p>"] = &callExpr{"cmd-hist-prev", nil}
gOpts.keys["k"] = &callExpr{"up", nil, 1}
gOpts.keys["<up>"] = &callExpr{"up", nil, 1}
gOpts.keys["<c-u>"] = &callExpr{"half-up", nil, 1}
gOpts.keys["<c-b>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["<pgup>"] = &callExpr{"page-up", nil, 1}
gOpts.keys["j"] = &callExpr{"down", nil, 1}
gOpts.keys["<down>"] = &callExpr{"down", nil, 1}
gOpts.keys["<c-d>"] = &callExpr{"half-down", nil, 1}
gOpts.keys["<c-f>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["<pgdn>"] = &callExpr{"page-down", nil, 1}
gOpts.keys["h"] = &callExpr{"updir", nil, 1}
gOpts.keys["<left>"] = &callExpr{"updir", nil, 1}
gOpts.keys["l"] = &callExpr{"open", nil, 1}
gOpts.keys["<right>"] = &callExpr{"open", nil, 1}
gOpts.keys["q"] = &callExpr{"quit", nil, 1}
gOpts.keys["gg"] = &callExpr{"top", nil, 1}
gOpts.keys["<home>"] = &callExpr{"top", nil, 1}
gOpts.keys["G"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<space>"] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1}
gOpts.keys["v"] = &callExpr{"invert", nil, 1}
gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"copy", nil, 1}
gOpts.keys["d"] = &callExpr{"cut", nil, 1}
gOpts.keys["c"] = &callExpr{"clear", nil, 1}
gOpts.keys["p"] = &callExpr{"paste", nil, 1}
gOpts.keys["<c-l>"] = &callExpr{"redraw", nil, 1}
gOpts.keys["<c-r>"] = &callExpr{"reload", nil, 1}
gOpts.keys[":"] = &callExpr{"read", nil, 1}
gOpts.keys["$"] = &callExpr{"shell", nil, 1}
gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1}
gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1}
gOpts.keys["&"] = &callExpr{"shell-async", nil, 1}
gOpts.keys["f"] = &callExpr{"find", nil, 1}
gOpts.keys["F"] = &callExpr{"find-back", nil, 1}
gOpts.keys[";"] = &callExpr{"find-next", nil, 1}
gOpts.keys[","] = &callExpr{"find-prev", nil, 1}
gOpts.keys["/"] = &callExpr{"search", nil, 1}
gOpts.keys["?"] = &callExpr{"search-back", nil, 1}
gOpts.keys["n"] = &callExpr{"search-next", nil, 1}
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.keys["zh"] = &setExpr{"hidden!", ""}
gOpts.keys["zr"] = &setExpr{"reverse!", ""}
@@ -92,39 +171,48 @@ func init() {
gOpts.keys["zs"] = &setExpr{"info", "size"}
gOpts.keys["zt"] = &setExpr{"info", "time"}
gOpts.keys["za"] = &setExpr{"info", "size:time"}
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}}
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}
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.cmdkeys = make(map[string]expr)
// TODO: rest of the keys
gOpts.cmdkeys["<space>"] = &callExpr{"cmd-insert", []string{" "}}
gOpts.cmdkeys["<esc>"] = &callExpr{"cmd-escape", nil}
gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-comp", nil}
gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil}
gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil}
gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-hist-next", nil}
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-hist-prev", nil}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil}
gOpts.cmdkeys["<bs>"] = &callExpr{"cmd-delete-back", nil}
gOpts.cmdkeys["<bs2>"] = &callExpr{"cmd-delete-back", nil}
gOpts.cmdkeys["<left>"] = &callExpr{"cmd-left", nil}
gOpts.cmdkeys["<c-b>"] = &callExpr{"cmd-left", nil}
gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil}
gOpts.cmdkeys["<c-f>"] = &callExpr{"cmd-right", nil}
gOpts.cmdkeys["<home>"] = &callExpr{"cmd-beg", nil}
gOpts.cmdkeys["<c-a>"] = &callExpr{"cmd-beg", nil}
gOpts.cmdkeys["<end>"] = &callExpr{"cmd-end", nil}
gOpts.cmdkeys["<c-e>"] = &callExpr{"cmd-end", nil}
gOpts.cmdkeys["<c-u>"] = &callExpr{"cmd-delete-beg", nil}
gOpts.cmdkeys["<c-k>"] = &callExpr{"cmd-delete-end", nil}
gOpts.cmdkeys["<c-w>"] = &callExpr{"cmd-delete-word", nil}
gOpts.cmdkeys["<c-y>"] = &callExpr{"cmd-put", nil}
gOpts.cmdkeys["<c-t>"] = &callExpr{"cmd-transpose", nil}
gOpts.cmdkeys["<c-c>"] = &callExpr{"cmd-interrupt", nil}
gOpts.cmdkeys["<space>"] = &callExpr{"cmd-insert", []string{" "}, 1}
gOpts.cmdkeys["<esc>"] = &callExpr{"cmd-escape", nil, 1}
gOpts.cmdkeys["<tab>"] = &callExpr{"cmd-complete", nil, 1}
gOpts.cmdkeys["<enter>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-j>"] = &callExpr{"cmd-enter", nil, 1}
gOpts.cmdkeys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.cmdkeys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
gOpts.cmdkeys["<delete>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<c-d>"] = &callExpr{"cmd-delete", nil, 1}
gOpts.cmdkeys["<backspace>"] = &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["<c-b>"] = &callExpr{"cmd-left", nil, 1}
gOpts.cmdkeys["<right>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<c-f>"] = &callExpr{"cmd-right", nil, 1}
gOpts.cmdkeys["<home>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<c-a>"] = &callExpr{"cmd-home", nil, 1}
gOpts.cmdkeys["<end>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-e>"] = &callExpr{"cmd-end", nil, 1}
gOpts.cmdkeys["<c-u>"] = &callExpr{"cmd-delete-home", nil, 1}
gOpts.cmdkeys["<c-k>"] = &callExpr{"cmd-delete-end", nil, 1}
gOpts.cmdkeys["<c-w>"] = &callExpr{"cmd-delete-unix-word", nil, 1}
gOpts.cmdkeys["<c-y>"] = &callExpr{"cmd-yank", nil, 1}
gOpts.cmdkeys["<c-t>"] = &callExpr{"cmd-transpose", nil, 1}
gOpts.cmdkeys["<c-c>"] = &callExpr{"cmd-interrupt", nil, 1}
gOpts.cmdkeys["<a-f>"] = &callExpr{"cmd-word", nil, 1}
gOpts.cmdkeys["<a-b>"] = &callExpr{"cmd-word-back", nil, 1}
gOpts.cmdkeys["<a-c>"] = &callExpr{"cmd-capitalize-word", nil, 1}
gOpts.cmdkeys["<a-d>"] = &callExpr{"cmd-delete-word", nil, 1}
gOpts.cmdkeys["<a-u>"] = &callExpr{"cmd-uppercase-word", nil, 1}
gOpts.cmdkeys["<a-l>"] = &callExpr{"cmd-lowercase-word", nil, 1}
gOpts.cmdkeys["<a-t>"] = &callExpr{"cmd-transpose-word", nil, 1}
gOpts.cmds = make(map[string]expr)
+135 -62
View File
@@ -10,9 +10,12 @@ import (
"os/user"
"path/filepath"
"runtime"
"strings"
"syscall"
)
var (
envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL")
@@ -20,19 +23,49 @@ var (
var (
gDefaultShell = "sh"
gDefaultShellFlag = "-c"
gDefaultSocketProt = "unix"
gDefaultSocketPath string
)
var (
gUser *user.User
gConfigPath string
gUser *user.User
gConfigPaths []string
gFilesPath string
gMarksPath string
gHistoryPath string
)
func init() {
if envOpener == "" {
if runtime.GOOS == "darwin" {
envOpener = "open"
} else {
envOpener = "xdg-open"
}
}
if envEditor == "" {
envEditor = "vi"
}
if envPager == "" {
envPager = "less"
}
if envShell == "" {
envShell = "sh"
}
u, err := user.Current()
if err != nil {
log.Printf("user: %s", err)
if os.Getenv("HOME") == "" {
log.Print("$HOME variable is empty or not set")
}
if os.Getenv("USER") == "" {
log.Print("$USER variable is empty or not set")
}
}
gUser = u
@@ -41,21 +74,27 @@ func init() {
config = filepath.Join(gUser.HomeDir, ".config")
}
gConfigPath = filepath.Join(config, "lf", "lfrc")
gConfigPaths = []string{
filepath.Join("/etc", "lf", "lfrc"),
filepath.Join(config, "lf", "lfrc"),
}
data := os.Getenv("XDG_DATA_HOME")
if data == "" {
data = filepath.Join(gUser.HomeDir, ".local", "share")
}
gFilesPath = filepath.Join(data, "lf", "files")
gMarksPath = filepath.Join(data, "lf", "marks")
gHistoryPath = filepath.Join(data, "lf", "history")
gDefaultSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.sock", gUser.Username))
}
func pauseCommand() *exec.Cmd {
c := `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", c)
func detachedCommand(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
return cmd
}
func shellCommand(s string, args []string) *exec.Cmd {
@@ -63,61 +102,95 @@ func shellCommand(s string, args []string) *exec.Cmd {
s = fmt.Sprintf("IFS='%s'; %s", gOpts.ifs, s)
}
args = append([]string{"-c", s, "--"}, args...)
args = append([]string{gOpts.shellflag, s, "--"}, args...)
args = append(gOpts.shellopts, args...)
return exec.Command(gOpts.shell, args...)
}
func putCommand(list []string, dir *dir, copy bool) *exec.Cmd {
var sh string
var args []string
if copy {
sh = "cp"
args = append(args, "-R")
} else {
sh = "mv"
}
// XXX: POSIX standard states that -i flag shall do nothing when the
// response is not affirmative. Since this command is run with a nil stdin,
// it should not give an affirmative answer and in return this command
// should not overwrite existing files. Our intention here is to use the
// standard -i flag in place of non-standard -n flag to avoid overwrites.
args = append(args, "-i")
args = append(args, list...)
args = append(args, dir.path)
return exec.Command(sh, args...)
}
func setDefaults() {
if envEditor == "" {
gOpts.keys["e"] = &execExpr{"$", `vi "$f"`}
} else {
gOpts.keys["e"] = &execExpr{"$", envEditor + ` "$f"`}
}
gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`}
gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`}
gOpts.keys["i"] = &execExpr{"$", `$PAGER "$f"`}
gOpts.keys["w"] = &execExpr{"$", "$SHELL"}
if envPager == "" {
gOpts.keys["i"] = &execExpr{"$", `less "$f"`}
} else {
gOpts.keys["i"] = &execExpr{"$", envPager + ` "$f"`}
}
if envShell == "" {
gOpts.keys["w"] = &execExpr{"$", "sh"}
} else {
gOpts.keys["w"] = &execExpr{"$", envShell}
}
if runtime.GOOS == "darwin" {
gOpts.cmds["open-file"] = &execExpr{"&", `open "$f"`}
} else {
gOpts.cmds["open-file"] = &execExpr{"&", `xdg-open "$f"`}
}
gOpts.cmds["doc"] = &execExpr{"$", "lf -doc | $PAGER"}
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 {
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, pwd string) {
envFile := f
envFiles := strings.Join(fs, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
os.Setenv("PWD", pwd)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
}
+116 -41
View File
@@ -1,26 +1,57 @@
package main
import (
"fmt"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"syscall"
)
var (
envOpener = os.Getenv("OPENER")
envEditor = os.Getenv("EDITOR")
envPager = os.Getenv("PAGER")
envShell = os.Getenv("SHELL")
)
var envPathExt = os.Getenv("PATHEXT")
var (
gDefaultShell = "cmd"
gDefaultShellFlag = "/c"
gDefaultSocketProt = "tcp"
gDefaultSocketPath = ":12345"
gDefaultSocketPath = "127.0.0.1:12345"
)
var (
gUser *user.User
gConfigPath string
gUser *user.User
gConfigPaths []string
gFilesPath string
gMarksPath string
gHistoryPath string
)
func init() {
if envOpener == "" {
envOpener = `start ""`
}
if envEditor == "" {
envEditor = "notepad"
}
if envPager == "" {
envPager = "more"
}
if envShell == "" {
envShell = "cmd"
}
u, err := user.Current()
if err != nil {
log.Printf("user: %s", err)
@@ -30,53 +61,97 @@ func init() {
// remove domain prefix
gUser.Username = strings.Split(gUser.Username, `\`)[1]
gConfigPath = filepath.Join(gUser.HomeDir, "AppData", "Local", "lf", "lfrc")
data := os.Getenv("LOCALAPPDATA")
gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
filepath.Join(data, "lf", "lfrc"),
}
gFilesPath = filepath.Join(data, "lf", "files")
gMarksPath = filepath.Join(data, "lf", "marks")
gHistoryPath = filepath.Join(data, "lf", "history")
}
func pauseCommand() *exec.Cmd {
return exec.Command("cmd", "/c", "pause")
func detachedCommand(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 8}
return cmd
}
func shellCommand(s string, args []string) *exec.Cmd {
args = append([]string{"/c", s}, args...)
args = append([]string{gOpts.shellflag, s}, args...)
args = append(gOpts.shellopts, args...)
return exec.Command(gOpts.shell, args...)
}
func putCommand(list []string, dir *dir, copy bool) *exec.Cmd {
var args []string
sh := "robocopy"
if !copy {
args = []string{"/move"}
}
for _, f := range list {
stat, err := os.Stat(f)
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
base := filepath.Base(f)
dest := filepath.Dir(f)
if stat.IsDir() {
exec.Command(sh, append(args, f, filepath.Join(dir.path, base))...).Run()
} else {
exec.Command(sh, append(args, dest, dir.path, base)...).Run()
}
}
// TODO: return 0 on success
return exec.Command(sh, args...)
}
func setDefaults() {
gOpts.keys["e"] = &execExpr{"$", `notepad "%f%"`}
gOpts.keys["i"] = &execExpr{"$", `more "%f%"`}
gOpts.keys["w"] = &execExpr{"$", "cmd"}
gOpts.cmds["open-file"] = &execExpr{"&", `start "" "%f%"`}
gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"}
gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"}
gOpts.keys["i"] = &execExpr{"!", "%PAGER% %f%"}
gOpts.keys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.cmds["doc"] = &execExpr{"!", "lf -doc | %PAGER%"}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
}
func moveCursor(y, x int) {
// TODO: implement
return
func isExecutable(f os.FileInfo) bool {
exts := strings.Split(envPathExt, string(filepath.ListSeparator))
for _, e := range exts {
if strings.HasSuffix(strings.ToLower(f.Name()), strings.ToLower(e)) {
log.Print(f.Name(), e)
return true
}
}
return false
}
func isHidden(f os.FileInfo, path string, 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, pwd 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)
os.Setenv("PWD", pwd)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
}
+15 -17
View File
@@ -14,7 +14,7 @@ package main
//
// MapExpr = 'map' <keys> Expr
//
// CMapExpr = 'cmap' <key> <cmd> ';'
// CMapExpr = 'cmap' <key> Expr
//
// CmdExpr = 'cmd' <name> Expr
//
@@ -23,7 +23,7 @@ package main
// ExecExpr = Prefix <value> '\n'
// | Prefix '{{' <value> '}}' ';'
//
// Prefix = '$' | '!' | '&' | '/' | '?'
// Prefix = '$' | '%' | '!' | '&'
//
// ListExpr = ':' Expr ListRest '\n'
// | ':' '{{' Expr ListRest '}}' ';'
@@ -58,11 +58,11 @@ type mapExpr struct {
func (e *mapExpr) String() string { return fmt.Sprintf("map %s %s", e.keys, e.expr) }
type cmapExpr struct {
key string
cmd string
key string
expr expr
}
func (e *cmapExpr) String() string { return fmt.Sprintf("cmap %s %s", e.key, e.cmd) }
func (e *cmapExpr) String() string { return fmt.Sprintf("cmap %s %s", e.key, e.expr) }
type cmdExpr struct {
name string
@@ -72,8 +72,9 @@ type cmdExpr struct {
func (e *cmdExpr) String() string { return fmt.Sprintf("cmd %s %s", e.name, e.expr) }
type callExpr struct {
name string
args []string
name string
args []string
count int
}
func (e *callExpr) String() string { return fmt.Sprintf("%s -- %s", e.name, e.args) }
@@ -113,6 +114,7 @@ func (e *execExpr) String() string {
type listExpr struct {
exprs []expr
count int
}
func (e *listExpr) String() string {
@@ -189,23 +191,19 @@ func (p *parser) parseExpr() expr {
result = &mapExpr{keys, expr}
case "cmap":
var cmd string
var expr expr
s.scan()
key := s.tok
s.scan()
if s.typ != tokenSemicolon {
if s.typ != tokenIdent {
p.err = fmt.Errorf("expected command: %s", s.tok)
}
cmd = s.tok
expr = p.parseExpr()
} else {
s.scan()
}
s.scan()
result = &cmapExpr{key, cmd}
result = &cmapExpr{key, expr}
case "cmd":
var expr expr
@@ -230,7 +228,7 @@ func (p *parser) parseExpr() expr {
s.scan()
result = &callExpr{name, args}
result = &callExpr{name, args, 1}
}
case tokenColon:
s.scan()
@@ -264,7 +262,7 @@ func (p *parser) parseExpr() expr {
s.scan()
result = &listExpr{exprs}
result = &listExpr{exprs, 1}
case tokenPrefix:
var expr string
+31 -29
View File
@@ -5,7 +5,6 @@ import (
"io/ioutil"
"log"
"strconv"
"unicode"
)
type tokenType byte
@@ -82,15 +81,23 @@ func (s *scanner) peek() byte {
}
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 {
return unicode.IsDigit(rune(b))
return '0' <= b && b <= '9'
}
func isPrefix(b byte) bool {
return b == '$' || b == '%' || b == '!' || b == '&'
switch b {
case '$', '%', '!', '&':
return true
}
return false
}
func (s *scanner) scan() bool {
@@ -177,9 +184,6 @@ scan:
s.tok = string(s.buf[beg:s.off])
s.cmd = false
s.sem = true
case s.chr == '\r':
s.next()
goto scan
case s.chr == '\n':
if s.sem {
s.typ = tokenSemicolon
@@ -196,7 +200,7 @@ scan:
}
goto scan
case isSpace(s.chr):
for !s.eof && isSpace(s.chr) {
for !s.eof && isSpace(s.chr) && s.chr != '\n' {
s.next()
}
goto scan
@@ -216,25 +220,24 @@ scan:
for !s.eof && s.chr != '"' {
if s.chr == '\\' {
s.next()
switch s.chr {
case '"', '\\':
switch {
case s.chr == '"' || s.chr == '\\':
buf = append(buf, s.chr)
case 'a':
case s.chr == 'a':
buf = append(buf, '\a')
case 'b':
case s.chr == 'b':
buf = append(buf, '\b')
case 'f':
case s.chr == 'f':
buf = append(buf, '\f')
case 'n':
case s.chr == 'n':
buf = append(buf, '\n')
case 'r':
case s.chr == 'r':
buf = append(buf, '\r')
case 't':
case s.chr == 't':
buf = append(buf, '\t')
case 'v':
case s.chr == 'v':
buf = append(buf, '\v')
}
if isDigit(s.chr) {
case isDigit(s.chr):
var oct []byte
for isDigit(s.chr) {
oct = append(oct, s.chr)
@@ -245,13 +248,15 @@ scan:
log.Printf("scanning: %s", err)
}
buf = append(buf, byte(n))
} else {
s.next()
continue
default:
buf = append(buf, '\\', s.chr)
}
} else {
buf = append(buf, s.chr)
s.next()
continue
}
buf = append(buf, s.chr)
s.next()
}
s.typ = tokenIdent
s.tok = string(buf)
@@ -293,12 +298,9 @@ scan:
for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' {
if s.chr == '\\' {
s.next()
if isSpace(s.chr) {
buf = append(buf, s.chr)
s.next()
} else {
s.next()
}
buf = append(buf, s.chr)
s.next()
continue
}
buf = append(buf, s.chr)
s.next()
+58 -37
View File
@@ -10,18 +10,18 @@ import (
)
var (
gCopyFile bool
gFileList []string
gConnList = make(map[int]net.Conn)
gQuitChan = make(chan struct{}, 1)
gListener net.Listener
)
func serve() {
logFile, err := os.Create(gServerLogPath)
f, err := os.Create(gServerLogPath)
if err != nil {
panic(err)
}
defer logFile.Close()
log.SetOutput(logFile)
defer f.Close()
log.SetOutput(f)
log.Print("hi!")
@@ -32,6 +32,8 @@ func serve() {
}
defer l.Close()
gListener = l
listen(l)
}
@@ -39,55 +41,58 @@ func listen(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
log.Printf("accepting connection: %s", err)
select {
case <-gQuitChan:
log.Printf("bye!")
return
default:
log.Printf("accepting connection: %s", err)
}
}
go handleConn(c)
}
}
func echoerr(c net.Conn, msg string) {
fmt.Fprintln(c, msg)
log.Printf(msg)
}
func echoerrf(c net.Conn, format string, a ...interface{}) {
echoerr(c, fmt.Sprintf(format, a...))
}
func handleConn(c net.Conn) {
s := bufio.NewScanner(c)
Loop:
for s.Scan() {
log.Printf("listen: %s", s.Text())
word, rest := splitWord(s.Text())
switch word {
case "save":
s.Scan()
switch s.Text() {
case "copy":
gCopyFile = true
case "move":
gCopyFile = false
default:
log.Printf("unexpected option to copy file(s): %s", s.Text())
break
}
gFileList = nil
for s.Scan() && s.Text() != "" {
gFileList = append(gFileList, s.Text())
}
case "load":
if gCopyFile {
fmt.Fprintln(c, "copy")
} else {
fmt.Fprintln(c, "move")
}
for _, f := range gFileList {
fmt.Fprintln(c, f)
}
fmt.Fprintln(c)
case "conn":
if rest != "" {
word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
log.Print("listen: conn: client id should be a number")
echoerr(c, "listen: conn: client id should be a number")
} else {
gConnList[id] = c
}
} else {
log.Print("listen: conn: requires a client id")
echoerr(c, "listen: conn: requires a client id")
}
case "drop":
if rest != "" {
word2, _ := splitWord(rest)
id, err := strconv.Atoi(word2)
if err != nil {
echoerr(c, "listen: drop: client id should be a number")
} else {
delete(gConnList, id)
}
} else {
echoerr(c, "listen: drop: requires a client id")
}
case "send":
if rest != "" {
@@ -98,18 +103,34 @@ func handleConn(c net.Conn) {
fmt.Fprintln(c, rest)
}
} else {
if c, ok := gConnList[id]; ok {
fmt.Fprintln(c, rest2)
if c2, ok := gConnList[id]; ok {
fmt.Fprintln(c2, rest2)
} else {
echoerr(c, "listen: send: no such client id is connected")
}
}
}
case "quit":
if len(gConnList) == 0 {
gQuitChan <- struct{}{}
gListener.Close()
break Loop
}
case "quit!":
gQuitChan <- struct{}{}
for _, c := range gConnList {
fmt.Fprintln(c, "echo server is quitting...")
c.Close()
}
gListener.Close()
break Loop
default:
log.Printf("listen: unexpected command: %s", word)
echoerrf(c, "listen: unexpected command: %s", word)
}
}
if s.Err() != nil {
log.Printf("listening: %s", s.Err())
echoerrf(c, "listening: %s", s.Err())
}
c.Close()
+849 -470
View File
File diff suppressed because it is too large. Load diff