Compare commits

128 Commits
r7 ... r14
Author SHA1 Message Date
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
36 changed files with 2918 additions and 970 deletions

No files matched your search

+2 -1
View File
@@ -1,6 +1,7 @@
language: go language: go
install: install:
- go get github.com/nsf/termbox-go - go get github.com/doronbehar/termbox-go
- go get gopkg.in/djherbis/times.v1
before_deploy: before_deploy:
- gen/xbuild.sh - gen/xbuild.sh
deploy: deploy:
Generated
-21
View File
@@ -1,21 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
branch = "master"
name = "github.com/mattn/go-runewidth"
packages = ["."]
revision = "ce7b0b5c7b45a81508558cd1dba6bb1e4ddb51bb"
[[projects]]
branch = "master"
name = "github.com/nsf/termbox-go"
packages = ["."]
revision = "5c94acc5e6eb520f1bcd183974e01171cc4c23b3"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "8508b73787d4948edb76ccc25789c311a4ab84d4c8c0b96b267857e2e88d974e"
solver-name = "gps-cdcl"
solver-version = 1
-38
View File
@@ -1,38 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[[constraint]]
branch = "master"
name = "github.com/mattn/go-runewidth"
[[constraint]]
branch = "master"
name = "github.com/nsf/termbox-go"
[prune]
go-tests = true
unused-packages = true
+115 -45
View File
@@ -8,7 +8,6 @@ import (
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"time" "time"
) )
@@ -48,7 +47,7 @@ func (app *app) readFile(path string) {
f, err := os.Open(path) f, err := os.Open(path)
if err != nil { if err != nil {
app.ui.printf("opening file: %s", err) app.ui.echoerrf("opening file: %s", err)
return return
} }
defer f.Close() defer f.Close()
@@ -60,7 +59,7 @@ func (app *app) readFile(path string) {
} }
if p.err != nil { if p.err != nil {
app.ui.printf("%s", p.err) app.ui.echoerrf("%s", p.err)
} }
} }
@@ -136,15 +135,57 @@ func (app *app) loop() {
clientChan := app.ui.readExpr() clientChan := app.ui.readExpr()
serverChan := readExpr() serverChan := readExpr()
if gSelect != "" {
go func() {
stat, err := os.Stat(gSelect)
if err != nil {
app.ui.exprChan <- &callExpr{"echoerr", []string{err.Error()}, 1}
} else if stat.IsDir() {
app.ui.exprChan <- &callExpr{"cd", []string{gSelect}, 1}
} else {
app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1}
}
}()
}
for _, path := range gConfigPaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
app.readFile(path)
}
}
if gCommand != "" {
p := newParser(strings.NewReader(gCommand))
for p.parse() {
p.expr.eval(app, nil)
}
if p.err != nil {
app.ui.echoerrf("%s", p.err)
}
}
for { for {
select { select {
case <-app.quitChan: case <-app.quitChan:
log.Print("bye!") if app.nav.copyTotal > 0 {
app.ui.echoerr("quit: copy operation in progress")
if err := app.nav.writeMarks(); err != nil { continue
log.Printf("writing marks file: %s", err)
} }
if app.nav.moveTotal > 0 {
app.ui.echoerr("quit: move operation in progress")
continue
}
if app.nav.deleteTotal > 0 {
app.ui.echoerr("quit: delete operation in progress")
continue
}
log.Print("bye!")
if err := app.writeHistory(); err != nil { if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err) log.Printf("writing history file: %s", err)
} }
@@ -165,10 +206,57 @@ func (app *app) loop() {
} }
return return
case n := <-app.nav.copyBytesChan:
app.nav.copyBytes += n
// n is usually 4096B so update roughly per 4096B x 1024 = 4MB copied
if app.nav.copyUpdate++; app.nav.copyUpdate >= 1024 {
app.nav.copyUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.copyTotalChan:
app.nav.copyTotal += n
if n < 0 {
app.nav.copyBytes += n
}
if app.nav.copyTotal == 0 {
app.nav.copyUpdate = 0
}
app.ui.draw(app.nav)
case n := <-app.nav.moveCountChan:
app.nav.moveCount += n
if app.nav.moveUpdate++; app.nav.moveUpdate >= 1000 {
app.nav.moveUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.moveTotalChan:
app.nav.moveTotal += n
if n < 0 {
app.nav.moveCount += n
}
if app.nav.moveTotal == 0 {
app.nav.moveUpdate = 0
}
app.ui.draw(app.nav)
case n := <-app.nav.deleteCountChan:
app.nav.deleteCount += n
if app.nav.deleteUpdate++; app.nav.deleteUpdate >= 1000 {
app.nav.deleteUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.deleteTotalChan:
app.nav.deleteTotal += n
if n < 0 {
app.nav.deleteCount += n
}
if app.nav.deleteTotal == 0 {
app.nav.deleteUpdate = 0
}
app.ui.draw(app.nav)
case d := <-app.nav.dirChan: case d := <-app.nav.dirChan:
prev, ok := app.nav.dirCache[d.path] prev, ok := app.nav.dirCache[d.path]
if ok { if ok {
d.find(prev.name(), app.nav.height) d.ind = prev.ind
d.sel(prev.name(), app.nav.height)
} }
app.nav.dirCache[d.path] = d app.nav.dirCache[d.path] = d
@@ -217,31 +305,15 @@ func (app *app) loop() {
} }
} }
func (app *app) exportVars() { func (app *app) exportFiles() {
var envFile string var currFile string
if f, err := app.nav.currFile(); err == nil { if f, err := app.nav.currFile(); err == nil {
envFile = f.path currFile = f.path
} }
selections := app.nav.currSelections() currSelections := app.nav.currSelections()
envFiles := strings.Join(selections, gOpts.filesep) exportFiles(currFile, currSelections)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(selections) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
} }
func waitKey() error { func waitKey() error {
@@ -266,11 +338,12 @@ func waitKey() error {
// ! Yes No Yes Yes Yes Pause and then resume // ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing // & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) { func (app *app) runShell(s string, args []string, prefix string) {
app.exportVars() app.exportFiles()
cmd := shellCommand(s, args) cmd := shellCommand(s, args)
var out io.Reader var out io.Reader
var err error
switch prefix { switch prefix {
case "$", "!": case "$", "!":
cmd.Stdin = os.Stdin cmd.Stdin = os.Stdin
@@ -280,6 +353,8 @@ func (app *app) runShell(s string, args []string, prefix string) {
app.ui.pause() app.ui.pause()
defer app.ui.resume() defer app.ui.resume()
defer app.nav.renew() defer app.nav.renew()
err = cmd.Run()
case "%": case "%":
stdin, err := cmd.StdinPipe() stdin, err := cmd.StdinPipe()
if err != nil { if err != nil {
@@ -292,24 +367,19 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
out = stdout out = stdout
cmd.Stderr = cmd.Stdout cmd.Stderr = cmd.Stdout
} fallthrough
case "&":
var err error
switch prefix {
case "$", "!":
err = cmd.Run()
case "%", "&":
err = cmd.Start() err = cmd.Start()
} }
if err != nil { if err != nil {
app.ui.printf("running shell: %s", err) app.ui.echoerrf("running shell: %s", err)
} }
switch prefix { switch prefix {
case "!": case "!":
if err := waitKey(); err != nil { if err := waitKey(); err != nil {
app.ui.printf("waiting key: %s", err) app.ui.echoerrf("waiting key: %s", err)
} }
} }
@@ -318,12 +388,12 @@ func (app *app) runShell(s string, args []string, prefix string) {
switch prefix { switch prefix {
case "%": case "%":
go func() { app.cmd = cmd
app.cmd = cmd app.cmdOutBuf = nil
app.cmdOutBuf = nil app.ui.msg = ""
app.ui.msg = "" app.ui.cmdPrefix = ">"
app.ui.cmdPrefix = ">"
go func() {
reader := bufio.NewReader(out) reader := bufio.NewReader(out)
for { for {
b, err := reader.ReadByte() b, err := reader.ReadByte()
@@ -342,7 +412,7 @@ func (app *app) runShell(s string, args []string, prefix string) {
} }
app.cmd = nil app.cmd = nil
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"reload", nil, 1} app.ui.exprChan <- &callExpr{"load", nil, 1}
}() }()
} }
} }
+19 -20
View File
@@ -8,11 +8,19 @@ import (
"net" "net"
"os" "os"
"strings" "strings"
"time"
"github.com/nsf/termbox-go" "github.com/doronbehar/termbox-go"
) )
func run() { func run() {
if err := termbox.Init(); err != nil {
log.Fatalf("initializing termbox: %s", err)
}
defer termbox.Close()
setColorMode()
f, err := os.Create(gLogPath) f, err := os.Create(gLogPath)
if err != nil { if err != nil {
panic(err) panic(err)
@@ -23,27 +31,14 @@ func run() {
log.Print("hi!") log.Print("hi!")
if err := termbox.Init(); err != nil {
log.Fatalf("initializing termbox: %s", err)
}
defer termbox.Close()
termbox.SetOutputMode(termbox.Output256)
app := newApp() app := newApp()
for _, path := range gConfigPaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
app.readFile(path)
}
}
if err := app.nav.readMarks(); err != nil { if err := app.nav.readMarks(); err != nil {
app.ui.printf("reading marks file: %s", err) app.ui.echoerrf("reading marks file: %s", err)
} }
if err := app.readHistory(); err != nil { if err := app.readHistory(); err != nil {
app.ui.printf("reading history file: %s", err) app.ui.echoerrf("reading history file: %s", err)
} }
app.loop() app.loop()
@@ -53,10 +48,14 @@ func readExpr() <-chan expr {
ch := make(chan expr) ch := make(chan expr)
go func() { go func() {
duration := 1 * time.Second
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { for err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err)) log.Printf("connecting server: %s", err)
return time.Sleep(duration)
duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath)
} }
fmt.Fprintf(c, "conn %d\n", gClientID) fmt.Fprintf(c, "conn %d\n", gClientID)
@@ -141,7 +140,7 @@ func loadFiles() (list []string, cp bool, err error) {
return return
} }
func sendRemote(cmd string) error { func remote(cmd string) error {
c, err := net.Dial(gSocketProt, gSocketPath) c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil { if err != nil {
return fmt.Errorf("dialing to send server: %s", err) return fmt.Errorf("dialing to send server: %s", err)
+16 -16
View File
@@ -7,7 +7,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/nsf/termbox-go" "github.com/doronbehar/termbox-go"
) )
const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse
@@ -51,25 +51,25 @@ func parseColors() colorMap {
return parseColorsBSD(env) return parseColorsBSD(env)
} }
// default values from dircolors // default values from dircolors with removed background colors
defaultColors := []string{ defaultColors := []string{
// "rs=0", // "rs=0",
"di=01;34", "di=01;34",
"ln=01;36", "ln=01;36",
// "mh=00", // "mh=00",
"pi=40;33", "pi=33", // "pi=40;33",
"so=01;35", "so=01;35",
"do=01;35", "do=01;35",
"bd=40;33;01", "bd=33;01", // "bd=40;33;01",
"cd=40;33;01", "cd=33;01", // "cd=40;33;01",
"or=40;31;01", "or=31;01", // "or=40;31;01",
// "mi=00", // "mi=00",
"su=37;41", "su=01;32", // "su=37;41",
"sg=30;43", "sg=01;32", // "sg=30;43",
"ca=30;41", // "ca=30;41",
"tw=30;42", "tw=01;34", // "tw=30;42",
"ow=34;42", "ow=01;34", // "ow=34;42",
"st=37;44", "st=01;34", // "st=37;44",
"ex=01;32", "ex=01;32",
} }
@@ -199,6 +199,10 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
var key string var key string
switch { switch {
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0: case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw" key = "tw"
case f.IsDir() && f.Mode()&os.ModeSticky != 0: case f.IsDir() && f.Mode()&os.ModeSticky != 0:
@@ -207,10 +211,6 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
key = "ow" key = "ow"
case f.IsDir(): case f.IsDir():
key = "di" key = "di"
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.Mode()&os.ModeNamedPipe != 0: case f.Mode()&os.ModeNamedPipe != 0:
key = "pi" key = "pi"
case f.Mode()&os.ModeSocket != 0: case f.Mode()&os.ModeSocket != 0:
+1 -1
View File
@@ -3,7 +3,7 @@ package main
import ( import (
"testing" "testing"
"github.com/nsf/termbox-go" "github.com/doronbehar/termbox-go"
) )
func TestApplyAnsiCodes(t *testing.T) { func TestApplyAnsiCodes(t *testing.T) {
+93 -5
View File
@@ -31,6 +31,7 @@ var (
"copy", "copy",
"cut", "cut",
"paste", "paste",
"delete",
"clear", "clear",
"draw", "draw",
"redraw", "redraw",
@@ -41,21 +42,37 @@ var (
"shell-pipe", "shell-pipe",
"shell-wait", "shell-wait",
"shell-async", "shell-async",
"find",
"find-back",
"find-next",
"find-prev",
"search", "search",
"search-back", "search-back",
"search-next", "search-next",
"search-prev", "search-prev",
"mark-save", "mark-save",
"mark-remove",
"mark-load", "mark-load",
"rename",
"sync", "sync",
"echo", "echo",
"echomsg",
"echoerr",
"cd", "cd",
"select", "select",
"glob-select",
"glob-unselect",
"source", "source",
"push", "push",
} }
gOptWords = []string{ gOptWords = []string{
"anchorfind",
"noanchorfind",
"anchorfind!",
"color256",
"nocolor256",
"color256!",
"dircounts", "dircounts",
"nodircounts", "nodircounts",
"dircounts!", "dircounts!",
@@ -68,12 +85,21 @@ var (
"globsearch", "globsearch",
"noglobsearch", "noglobsearch",
"globsearch!", "globsearch!",
"icons",
"noicons",
"icons!",
"hidden", "hidden",
"nohidden", "nohidden",
"hidden!", "hidden!",
"ignorecase", "ignorecase",
"noignorecase", "noignorecase",
"ignorecase!", "ignorecase!",
"ignoredia",
"noignoredia",
"ignoredia!",
"incsearch",
"noincsearch",
"incsearch!",
"preview", "preview",
"nopreview", "nopreview",
"preview!", "preview!",
@@ -83,12 +109,26 @@ var (
"smartcase", "smartcase",
"nosmartcase", "nosmartcase",
"smartcase!", "smartcase!",
"smartdia",
"nosmartdia",
"smartdia!",
"wrapscan", "wrapscan",
"nowrapscan", "nowrapscan",
"wrapscan!", "wrapscan!",
"wrapscroll",
"nowrapscroll",
"wrapscroll!",
"number",
"nonumber",
"number!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"findlen",
"period", "period",
"scrolloff", "scrolloff",
"tabstop", "tabstop",
"errorfmt",
"filesep", "filesep",
"ifs", "ifs",
"previewer", "previewer",
@@ -190,8 +230,9 @@ func matchFile(s string) (matches []string, longest string) {
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
log.Printf("getting current directory: %s", err) log.Printf("getting current directory: %s", err)
} else {
dir = wd + string(filepath.Separator) + dir
} }
dir = wd + string(filepath.Separator) + dir
} }
dir = unescape(filepath.Dir(dir)) dir = unescape(filepath.Dir(dir))
@@ -215,13 +256,13 @@ func matchFile(s string) (matches []string, longest string) {
name := f.Name() name := f.Name()
if isRoot(s) || filepath.Base(s) != s { if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(s), f.Name()) name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
} }
name = escape(name) name = escape(name)
item := f.Name() item := f.Name()
if f.Mode().IsDir() { if f.Mode().IsDir() {
item += string(filepath.Separator) item += escape(string(filepath.Separator))
} }
matches = append(matches, item) matches = append(matches, item)
@@ -231,7 +272,7 @@ func matchFile(s string) (matches []string, longest string) {
if f.Mode().IsRegular() { if f.Mode().IsRegular() {
longest = name + " " longest = name + " "
} else { } else {
longest = name + string(filepath.Separator) longest = name + escape(string(filepath.Separator))
} }
} }
} }
@@ -256,6 +297,15 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
words = append(words, c) words = append(words, c)
} }
sort.Strings(words) sort.Strings(words)
j := 0
for i := 1; i < len(words); i++ {
if words[j] == words[i] {
continue
}
j++
words[i], words[j] = words[j], words[i]
}
words = words[:j+1]
matches, longest = matchWord(s, words) matches, longest = matchWord(s, words)
longestAcc = []rune(longest) longestAcc = []rune(longest)
case 2: case 2:
@@ -282,6 +332,44 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
return return
} }
func completeFile(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
files, err := ioutil.ReadDir(wd)
if err != nil {
log.Printf("reading directory: %s", err)
}
var longest string
for _, f := range files {
if !strings.HasPrefix(f.Name(), s) {
continue
}
matches = append(matches, f.Name())
if longest != "" {
longest = matchLongest(longest, f.Name())
} else if s != "" {
longest = f.Name()
}
}
if longest == "" {
longest = s
}
longestAcc = []rune(longest)
return
}
func completeShell(acc []rune) (matches []string, longestAcc []rune) { func completeShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc) s := string(acc)
f := tokenize(s) f := tokenize(s)
@@ -294,7 +382,7 @@ func completeShell(acc []rune) (matches []string, longestAcc []rune) {
longestAcc = []rune(longest) longestAcc = []rune(longest)
default: default:
matches, longest = matchFile(f[len(f)-1]) matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...)
} }
return return
+128
View File
@@ -0,0 +1,128 @@
package main
import (
"fmt"
"io"
"os"
"path/filepath"
)
func copySize(srcs []string) (int64, error) {
var total int64
for _, src := range srcs {
_, err := os.Stat(src)
if os.IsNotExist(err) {
return total, fmt.Errorf("src does not exist: %q", src)
}
err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("walk: %s", err)
}
total += info.Size()
return nil
})
if err != nil {
return total, err
}
}
return total, nil
}
func copyFile(src, dst string, info os.FileInfo, nums chan int64) error {
buf := make([]byte, 4096)
r, err := os.Open(src)
if err != nil {
return err
}
defer r.Close()
w, err := os.Create(dst)
if err != nil {
return err
}
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
w.Close()
os.Remove(dst)
return err
}
if n == 0 {
break
}
if _, err := w.Write(buf[:n]); err != nil {
return err
}
nums <- int64(n)
}
if err := w.Close(); err != nil {
os.Remove(dst)
return err
}
if err := os.Chmod(dst, info.Mode()); err != nil {
os.Remove(dst)
return err
}
return nil
}
func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) {
nums = make(chan int64, 1024)
errs = make(chan error, 1024)
go func() {
for _, src := range srcs {
dst := filepath.Join(dstDir, filepath.Base(src))
_, err := os.Stat(dst)
if !os.IsNotExist(err) {
var newPath string
for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i)
_, err = os.Stat(newPath)
}
dst = newPath
}
filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
errs <- fmt.Errorf("walk: %s", err)
return nil
}
rel, err := filepath.Rel(src, path)
if err != nil {
errs <- fmt.Errorf("relative: %s", err)
return nil
}
newPath := filepath.Join(dst, rel)
if info.IsDir() {
if err := os.MkdirAll(newPath, info.Mode()); err != nil {
errs <- fmt.Errorf("mkdir: %s", err)
}
nums <- info.Size()
} else {
if err := copyFile(path, newPath, info, nums); err != nil {
errs <- fmt.Errorf("copy: %s", err)
}
}
return nil
})
}
close(errs)
}()
return nums, errs
}
+57
View File
@@ -0,0 +1,57 @@
package main
import (
"strconv"
"unicode"
)
var normMap map[rune]rune
func init() {
normMap = make(map[rune]rune)
// (not only) european
appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
)
// Vietnamese
appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
)
}
func appendTransliterate(base, norm string) {
normRunes := []rune(norm)
baseRunes := []rune(base)
lenNorm := len(normRunes)
lenBase := len(baseRunes)
if lenNorm != lenBase {
panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length
}
for i := 0; i < lenBase; i++ {
normMap[baseRunes[i]] = normRunes[i]
baseUpper := unicode.ToUpper(baseRunes[i])
normUpper := unicode.ToUpper(normRunes[i])
normMap[baseUpper] = normUpper
}
}
// Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string {
var normalizedRunes []rune
for _, baseRune := range baseString {
if normRune, ok := normMap[baseRune]; ok {
normalizedRunes = append(normalizedRunes, normRune)
} else {
normalizedRunes = append(normalizedRunes, baseRune)
}
}
return string(normalizedRunes)
}
+72
View File
@@ -0,0 +1,72 @@
package main
import (
"strconv"
"testing"
)
// typical czech test sentence ;-)
const baseTestString = "Příliš žluťoučký kůň příšerně úpěl ďábelské ódy"
func TestRemoveDiacritics(t *testing.T) {
testStr := baseTestString
expStr := "Prilis zlutoucky kun priserne upel dabelske ody"
checkRemoveDiacritics(testStr, expStr, t)
// other accents (non comlete, but all I founded)
testStr = "áéíóúýčďěňřšťžůåøĉĝĥĵŝŭšžõäöüàâçéèêëîïôùûüÿžščćđáéíóúąęėįųūčšžāēīūčšžļķņģáéíóúöüőűäöüëïąćęłńóśźżáàãâçéêíóõôăâîșțáäčďéíĺľňóôŕšťúýžáéíñóúüåäöâçîşûğăâđêôơưáàãảạ"
expStr = "aeiouycdenrstzuaocghjsuszoaouaaceeeeiiouuuyzsccdaeiouaeeiuucszaeiucszlkngaeiouououaoueiacelnoszzaaaaceeioooaaistaacdeillnoorstuyzaeinouuaaoacisugaadeoouaaaaa"
checkRemoveDiacritics(testStr, expStr, t)
testStr = "ÁÉÍÓÚÝČĎĚŇŘŠŤŽŮÅØĈĜĤĴŜŬŠŽÕÄÖÜÀÂÇÉÈÊËÎÏÔÙÛÜŸŽŠČĆĐÁÉÍÓÚĄĘĖĮŲŪČŠŽĀĒĪŪČŠŽĻĶŅĢÁÉÍÓÚÖÜŐŰÄÖÜËÏĄĆĘŁŃÓŚŹŻÁÀÃÂÇÉÊÍÓÕÔĂÂÎȘȚÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽÁÉÍÑÓÚÜÅÄÖÂÇÎŞÛĞĂÂĐÊÔƠƯÁÀÃẢẠ"
expStr = "AEIOUYCDENRSTZUAOCGHJSUSZOAOUAACEEEEIIOUUUYZSCCDAEIOUAEEIUUCSZAEIUCSZLKNGAEIOUOUOUAOUEIACELNOSZZAAAACEEIOOOAAISTAACDEILLNOORSTUYZAEINOUUAAOACISUGAADEOOUAAAAA"
checkRemoveDiacritics(testStr, expStr, t)
testStr = "áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ"
expStr = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd"
checkRemoveDiacritics(testStr, expStr, t)
testStr = "ÁẠÀẢÃĂẮẶẰẲẴÂẤẬẦẨẪÉẸÈẺẼÊẾỆỀỂỄÍỊÌỈĨÓỌÒỎÕÔỐỘỒỔỖƠỚỢỜỞỠÚỤÙỦŨƯỨỰỪỬỮÝỴỲỶỸĐ"
expStr = "AAAAAAAAAAAAAAAAAEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYYD"
checkRemoveDiacritics(testStr, expStr, t)
}
func checkRemoveDiacritics(testStr string, expStr string, t *testing.T) {
resultStr := removeDiacritics(testStr)
if resultStr != expStr {
t.Errorf("at input '%v' expected '%v' but got '%v'", testStr, expStr, resultStr)
}
}
func TestSearchSettings(t *testing.T) {
runSearch(t, true, false, true, true, "Veřejný", "vere", true)
runSearch(t, true, false, true, false, baseTestString, "Zlutoucky", true)
runSearch(t, true, false, true, false, baseTestString, "zlutoucky", true)
runSearch(t, true, true, true, false, baseTestString, "Zlutoucky", false)
runSearch(t, true, true, true, true, baseTestString, "zlutoucky", true)
runSearch(t, false, false, true, false, baseTestString, "žlutoucky", true)
runSearch(t, false, false, true, false, baseTestString, "Žlutoucky", false)
runSearch(t, false, false, true, true, baseTestString, "žluťoučký", true)
runSearch(t, false, false, true, false, baseTestString, "žluťoučký", true)
runSearch(t, false, false, false, false, baseTestString, "žluťoučký", true)
runSearch(t, false, false, false, false, baseTestString, "zlutoucky", false)
runSearch(t, false, false, true, true, baseTestString, "zlutoucky", true)
}
func runSearch(t *testing.T, ignorecase, smartcase, ignorediacritics, smartdiacritics bool, base, pattern string, expected bool) {
gOpts.ignorecase = ignorecase
gOpts.smartcase = smartcase
gOpts.ignoredia = ignorediacritics
gOpts.smartdia = smartdiacritics
matched, _ := searchMatch(base, pattern)
if matched != expected {
t.Errorf("False search for" +
" ignorecase = " + strconv.FormatBool(gOpts.ignorecase) + ", " +
" smartcase = " + strconv.FormatBool(gOpts.smartcase) + ", " +
" ignoredia = " + strconv.FormatBool(gOpts.ignoredia) + ", " +
" smartdia = " + strconv.FormatBool(gOpts.smartdia) + ", ")
}
}
+247 -112
View File
@@ -16,102 +16,124 @@ Reference
The following commands are provided by lf with default keybindings: The following commands are provided by lf with default keybindings:
up (default 'k' and '<up>') up (default 'k' and '<up>')
half-up (default '<c-u>') half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>') page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>') down (default 'j' and '<down>')
half-down (default '<c-d>') half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>') page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>') updir (default 'h' and '<left>')
open (default 'l' and '<right>') open (default 'l' and '<right>')
quit (default 'q') quit (default 'q')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
toggle (default '<space>') toggle (default '<space>')
invert (default 'v') invert (default 'v')
unselect (default 'u') unselect (default 'u')
copy (default 'y') copy (default 'y')
cut (default 'd') cut (default 'd')
paste (default 'p') paste (default 'p')
clear (default 'c') clear (default 'c')
redraw (default '<c-l>') redraw (default '<c-l>')
reload (default '<c-r>') reload (default '<c-r>')
read (default ':') read (default ':')
shell (default '$') rename (default 'r')
shell-pipe (default '%') shell (default '$')
shell-wait (default '!') shell-pipe (default '%')
shell-async (default '&') shell-wait (default '!')
search (default '/') shell-async (default '&')
search-back (default '?') find (default 'f')
search-next (default 'n') find-back (default 'F')
search-prev (default 'N') find-next (default ';')
mark-save (default 'm') find-prev (default ',')
mark-load (default "'") search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default `"`)
The following commands are provided by lf without default keybindings: The following commands are provided by lf without default keybindings:
draw draw the ui draw draw the ui
load load modified files and directories load load modified files and directories
sync synchronizes copied/cut files with server sync synchronize copied/cut files with server
echo prints its arguments to the message line echo print arguments to the message line
cd changes working directory to its argument echomsg same as echo but logging
select changes current file selection to its argument echoerr same as echomsg but red color
source reads the configuration file in its argument cd change working directory to the argument
push simulate key pushes given in its argument select change current file selection to the argument
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default The following command line commands are provided by lf with default
keybindings: keybindings:
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>') cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>') cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>') cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>') cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>') cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>') cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>') cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>') cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>') cmd-transpose-word (default '<a-t>')
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
dircounts boolean (default off) anchorfind boolean (default on)
dirfirst boolean (default on) color256 boolean (default off)
drawbox boolean (default off) dircounts boolean (default off)
globsearch boolean (default off) dirfirst boolean (default on)
hidden boolean (default off) drawbox boolean (default off)
ignorecase boolean (default on) globsearch boolean (default off)
preview boolean (default on) icons boolean (default off)
reverse boolean (default off) hidden boolean (default off)
smartcase boolean (default on) ignorecase boolean (default on)
wrapscan boolean (default on) ignoredia boolean (default off)
period integer (default 0) incsearch boolean (default off)
scrolloff integer (default 0) preview boolean (default on)
tabstop integer (default 8) reverse boolean (default off)
filesep string (default "\n") smartcase boolean (default on)
ifs string (default '') (not exported if empty) smartdia boolean (default off)
previewer string (default '') (not filtered if empty) wrapscan boolean (default on)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m") wrapscroll boolean (default off)
shell string (default 'sh') number boolean (default off)
sortby string (default 'natural') relativenumber boolean (default off)
timefmt string (default 'Mon Jan _2 15:04:05 2006') findlen integer (default 1) (zero to prompt until single match)
ratios string (default '1:2:3') period integer (default 0) (zero to disable periodic loading)
info string (default '') scrolloff integer (default 0)
shellopts string (default '') tabstop integer (default 8)
errorfmt string (default "\033[7;31;47m%s\033[0m")
filesep string (default "\n")
ifs string (default '') (not exported if empty)
previewer string (default '') (not filtered if empty)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
shell string (default 'sh')
sortby string (default 'natural')
timefmt string (default 'Mon Jan _2 15:04:05 2006')
ratios string (default '1:2:3')
info string (default '')
shellopts string (default '')
The following variables are exported for shell commands: The following variables are exported for shell commands:
@@ -120,6 +142,10 @@ The following variables are exported for shell commands:
$fx current file or selected file(s) if any $fx current file or selected file(s) if any
$id id number of the client $id id number of the client
The following variables are set to the corresponding values:
$LF_LEVEL current nesting level
The following default values are set to the environmental variables on unix The following default values are set to the environmental variables on unix
when they are not set or empty: when they are not set or empty:
@@ -148,6 +174,9 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info map sn :set sortby natural; set info
map ss :set sortby size; set info size map ss :set sortby size; set info size
map st :set sortby time; set info time map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~ map gh cd ~
The following keybindings to applications are provided by default: The following keybindings to applications are provided by default:
@@ -194,14 +223,11 @@ The following command prefixes are used by lf:
% shell-pipe shell command running with the ui % shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press ! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously & shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
The same evaluator is used for the command line and the configuration file for The same evaluator is used for the command line and the configuration file for
read and shell commands. The difference is that prefixes are not necessary in read and shell commands. The difference is that prefixes are not necessary in
the command line. Instead, different modes are provided to read corresponding the command line. Instead, different modes are provided to read corresponding
commands. These modes are mapped to the prefix keys above by default. Searching commands. These modes are mapped to the prefix keys above by default.
commands are only used from the command line.
Syntax Syntax
@@ -491,50 +517,111 @@ Getting the file selection is similarly done with 'load' command:
# do something else with $list # do something else with $list
fi fi
There is a 'quit' command to close client connections and quit the server:
lf -remote 'quit'
Lastly, there is a 'conn' command to connect the server as a client. This Lastly, there is a 'conn' command to connect the server as a client. This
should not be needed for users. should not be needed for users.
File Operations File Operations
lf uses the underlying 'cp' and 'mv' shell commands for file operations. For lf uses its own builtin copy and move operations by default. These are
this purpose, when you 'copy' a file, it doesn't actually copy the file on the implemented as asynchronous operations and progress is shown in the bottom
disk, but only records its name to memory. The actual file operation takes ruler. These commands do not overwrite existing files or directories with the
place when you 'paste' in which case the 'cp' command is used. Similarly the same name. Instead, a suffix that is compatible with '--backup=numbered' option
'mv' command is used for 'cut' followed by 'paste'. in GNU cp is added to the new files or directories. Only file modes are
preserved and all other attributes are ignored including ownership, timestamps,
context, links, and xattr. Special files such as character and block devices,
named pipes, and sockets are skipped and links are followed. Moving is
performed using the rename operation of the underlying OS. This can fail to
move files between different partitions when it needs to copy files. For these
cases, users are expected to explicitly copy files and then delete the old ones
manually. Operation errors are shown in the message line as well as the log
file and they do not preemptively finish the corresponding file operation.
You can customize these operations by defining a 'paste' command. This is a File operations can be performed on the current selected file or alternatively
special command that is called when it is defined instead of the builtin on multiple files by selecting them first. When you 'copy' a file, lf doesn't
implementation. The default behavior is similar to the following command: actually copy the file on the disk, but only records its name to memory. The
actual file copying takes place when you 'paste'. Similarly 'paste' after a
'cut' operation moves the file.
You can customize copy and move operations by defining a 'paste' command. This
is a special command that is called when it is defined instead of the builtin
implementation. You can use the following example as a starting point:
cmd paste %{{ cmd paste %{{
load=$(lf -remote 'load') load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
cp -R -n $list . cp -R $list .
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
mv -n $list . mv $list .
fi fi
lf -remote 'send load' lf -remote 'send load'
lf -remote 'send clear' lf -remote 'send clear'
}} }}
Some useful things are to use the backup option ('--backup') with 'cp' and 'mv' Some useful things to be considered are to use the backup ('--backup') and/or
commands if they support it (i.e. GNU implementation), change the command type preserve attributes ('-a') options with 'cp' and 'mv' commands if they support
to asynchronous, or use 'rsync' command with progress bar option for copying it (i.e. GNU implementation), change the command type to asynchronous, or use
and feed the progress to the client periodically with remote 'echo' calls. 'rsync' command with progress bar option for copying and feed the progress to
the client periodically with remote 'echo' calls.
By default, lf does not provide an actual file deletion command to protect new By default, lf does not assign 'delete' command to a key to protect new users.
users. You can define such a command and optionally assign a key if you like. You can customize file deletion by defining a 'delete' command. You can also
An example command to move selected files to a trash folder and remove files assign a key to this command if you like. An example command to move selected
completely are provided in the example configuration file. files to a trash folder and remove files completely after a prompt are provided
in the example configuration file.
Searching Files
There are two mechanisms implemented in lf to search a file in the current
directory. Searching is the traditional method to move the selection to a file
matching a given pattern. Finding is an alternative way to search for a pattern
possibly using fewer keystrokes.
Searching mechanism is implemented with commands 'search' (default '/'),
'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev'
(default 'N'). You can enable 'globsearch' option to match with a glob pattern.
Globbing supports '*' to match any sequence, '?' to match any character, and
'[...]' or '[^...] to match character sets or ranges. You can enable
'incsearch' option to jump to the current match at each keystroke while typing.
In this mode, you can either use 'cmd-enter' to accept the search or use
'cmd-escape' to cancel the search. Alternatively, you can also map some other
commands with 'cmap' to accept the search and execute the command immediately
afterwards. Possible candidates are 'up', 'down' and their variants, 'updir',
and 'open' commands. For example, you can use arrow keys to finish the search
with the following mappings:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
','). You can disable 'anchorfind' option to match a pattern at an arbitrary
position in the filename instead of the beginning. You can set the number of
keys to match using 'findlen' option. If you set this value to zero, then the
the keys are read until there is only a single match. Default values of these
two options are set to jump to the first file with the given initial.
Some options effect both searching and finding. You can disable 'wrapscan'
option to prevent searches to wrap around at the end of the file list. You can
disable 'ignorecase' option to match cases in the pattern and the filename.
This option is already automatically overridden if the pattern contains upper
case characters. You can disable 'smartcase' option to disable this behavior.
Two similar options 'ignoredia' and 'smartdia' are provided to control matching
diacritics in latin letters.
Opening Files Opening Files
You can define a an 'open' command (default 'l') to configure file opening. You can define a an 'open' command (default 'l' and '<right>') to configure
This command is only called when the current file is not a directory, otherwise file opening. This command is only called when the current file is not a
the directory is entered instead. You can define it just as you would define directory, otherwise the directory is entered instead. You can define it just
any other command: as you would define any other command:
cmd open $vi $fx cmd open $vi $fx
@@ -551,6 +638,9 @@ You may want to use either file extensions or mime types from 'file' command:
esac esac
}} }}
You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
Following command is provided by default: Following command is provided by default:
cmd open &$OPENER $f cmd open &$OPENER $f
@@ -603,6 +693,39 @@ pipe with a SIGPIPE when enough lines are read. When everything else fails, you
can make use of the height argument to only feed the first portion of the file can make use of the height argument to only feed the first portion of the file
to a program for preview. to a program for preview.
Changing Directory
lf changes the working directory of the process to the current directory so
that shell commands always work in the displayed directory. After quitting, it
returns to the original directory where it is first launched like all shell
programs. If you want to stay in the current directory after quitting, you can
use one of the example wrapper shell scripts provided in the repository.
There is a special command 'on-cd' that runs a shell command when it is defined
and the directory is changed. You can define it just as you would define any
other command:
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f$git\033[0m"
lf -remote "send $id set promptfmt \"$fmt\""
}}
This command runs whenever you change directory but not on startup. You can add
an extra call to make it run on startup as well:
cmd on-cd &{{ # ... }}
on-cd
Note that all shell commands are possible but `%` and `&` are usually more
appropriate as `$` and `!` causes flickers and pauses respectively.
Colorschemes Colorschemes
lf tries to automatically adapt its colors to the environment. On startup, lf tries to automatically adapt its colors to the environment. On startup,
@@ -620,6 +743,13 @@ If both of these environment variables are not set, then lf fallbacks to its
default colorscheme. Default lf colors are taken from GNU dircolors defaults. default colorscheme. Default lf colors are taken from GNU dircolors defaults.
These defaults use 8 basic colors and bold attribute. These defaults use 8 basic colors and bold attribute.
You should also note that lf uses 8 color mode by default which uses sgr 3-bit
color escapes (e.g. '\033[34m'). If you want to use 256 colors, you need to
enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g.
'\033[38;5;4m'). This option is intended to eliminate differences between
default colors used by ls and lf since terminals may render 3-bit and 8-bit
escapes differently even for the same color.
Keeping this mechanism in mind, you can configure lf colors in two different Keeping this mechanism in mind, you can configure lf colors in two different
ways. First, you can configure 8 basic colors used by your terminal and lf ways. First, you can configure 8 basic colors used by your terminal and lf
should pick up those colors automatically. Depending on your terminal, you should pick up those colors automatically. Depending on your terminal, you
@@ -632,5 +762,10 @@ fine grained customization. This is useful to change colors used for different
file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and
it can be used even when GNU programs are not installed on the system. You can it can be used even when GNU programs are not installed on the system. You can
combine this second method with the first method for best results. combine this second method with the first method for best results.
Lastly, you may also want to configure the colors of the prompt line to match
the rest of the colors. Colors of the prompt line can be configured using the
'promptfmt' option which can include hardcoded colors as ansi escapes. See the
default value of this option to have an idea about how to color this line.
*/ */
package main package main
+253 -112
View File
@@ -19,102 +19,124 @@ Reference
The following commands are provided by lf with default keybindings: The following commands are provided by lf with default keybindings:
up (default 'k' and '<up>') up (default 'k' and '<up>')
half-up (default '<c-u>') half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>') page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>') down (default 'j' and '<down>')
half-down (default '<c-d>') half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>') page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>') updir (default 'h' and '<left>')
open (default 'l' and '<right>') open (default 'l' and '<right>')
quit (default 'q') quit (default 'q')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
toggle (default '<space>') toggle (default '<space>')
invert (default 'v') invert (default 'v')
unselect (default 'u') unselect (default 'u')
copy (default 'y') copy (default 'y')
cut (default 'd') cut (default 'd')
paste (default 'p') paste (default 'p')
clear (default 'c') clear (default 'c')
redraw (default '<c-l>') redraw (default '<c-l>')
reload (default '<c-r>') reload (default '<c-r>')
read (default ':') read (default ':')
shell (default '$') rename (default 'r')
shell-pipe (default '%') shell (default '$')
shell-wait (default '!') shell-pipe (default '%')
shell-async (default '&') shell-wait (default '!')
search (default '/') shell-async (default '&')
search-back (default '?') find (default 'f')
search-next (default 'n') find-back (default 'F')
search-prev (default 'N') find-next (default ';')
mark-save (default 'm') find-prev (default ',')
mark-load (default "'") search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default '"')
The following commands are provided by lf without default keybindings: The following commands are provided by lf without default keybindings:
draw draw the ui draw draw the ui
load load modified files and directories load load modified files and directories
sync synchronizes copied/cut files with server sync synchronize copied/cut files with server
echo prints its arguments to the message line echo print arguments to the message line
cd changes working directory to its argument echomsg same as echo but logging
select changes current file selection to its argument echoerr same as echomsg but red color
source reads the configuration file in its argument cd change working directory to the argument
push simulate key pushes given in its argument select change current file selection to the argument
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default The following command line commands are provided by lf with default
keybindings: keybindings:
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>') cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>') cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>') cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>') cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>') cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>') cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>') cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>') cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>') cmd-transpose-word (default '<a-t>')
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
dircounts boolean (default off) anchorfind boolean (default on)
dirfirst boolean (default on) color256 boolean (default off)
drawbox boolean (default off) dircounts boolean (default off)
globsearch boolean (default off) dirfirst boolean (default on)
hidden boolean (default off) drawbox boolean (default off)
ignorecase boolean (default on) globsearch boolean (default off)
preview boolean (default on) icons boolean (default off)
reverse boolean (default off) hidden boolean (default off)
smartcase boolean (default on) ignorecase boolean (default on)
wrapscan boolean (default on) ignoredia boolean (default off)
period integer (default 0) incsearch boolean (default off)
scrolloff integer (default 0) preview boolean (default on)
tabstop integer (default 8) reverse boolean (default off)
filesep string (default "\n") smartcase boolean (default on)
ifs string (default '') (not exported if empty) smartdia boolean (default off)
previewer string (default '') (not filtered if empty) wrapscan boolean (default on)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m") wrapscroll boolean (default off)
shell string (default 'sh') number boolean (default off)
sortby string (default 'natural') relativenumber boolean (default off)
timefmt string (default 'Mon Jan _2 15:04:05 2006') findlen integer (default 1) (zero to prompt until single match)
ratios string (default '1:2:3') period integer (default 0) (zero to disable periodic loading)
info string (default '') scrolloff integer (default 0)
shellopts string (default '') tabstop integer (default 8)
errorfmt string (default "\033[7;31;47m%s\033[0m")
filesep string (default "\n")
ifs string (default '') (not exported if empty)
previewer string (default '') (not filtered if empty)
promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m")
shell string (default 'sh')
sortby string (default 'natural')
timefmt string (default 'Mon Jan _2 15:04:05 2006')
ratios string (default '1:2:3')
info string (default '')
shellopts string (default '')
The following variables are exported for shell commands: The following variables are exported for shell commands:
@@ -123,6 +145,10 @@ The following variables are exported for shell commands:
$fx current file or selected file(s) if any $fx current file or selected file(s) if any
$id id number of the client $id id number of the client
The following variables are set to the corresponding values:
$LF_LEVEL current nesting level
The following default values are set to the environmental variables on unix The following default values are set to the environmental variables on unix
when they are not set or empty: when they are not set or empty:
@@ -151,6 +177,9 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info map sn :set sortby natural; set info
map ss :set sortby size; set info size map ss :set sortby size; set info size
map st :set sortby time; set info time map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~ map gh cd ~
The following keybindings to applications are provided by default: The following keybindings to applications are provided by default:
@@ -199,14 +228,12 @@ The following command prefixes are used by lf:
% shell-pipe shell command running with the ui % shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press ! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously & shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
The same evaluator is used for the command line and the configuration file The same evaluator is used for the command line and the configuration file
for read and shell commands. The difference is that prefixes are not for read and shell commands. The difference is that prefixes are not
necessary in the command line. Instead, different modes are provided to read necessary in the command line. Instead, different modes are provided to read
corresponding commands. These modes are mapped to the prefix keys above by corresponding commands. These modes are mapped to the prefix keys above by
default. Searching commands are only used from the command line. default.
Syntax Syntax
@@ -512,53 +539,116 @@ Getting the file selection is similarly done with 'load' command:
# do something else with $list # do something else with $list
fi fi
There is a 'quit' command to close client connections and quit the server:
lf -remote 'quit'
Lastly, there is a 'conn' command to connect the server as a client. This Lastly, there is a 'conn' command to connect the server as a client. This
should not be needed for users. should not be needed for users.
File Operations File Operations
lf uses the underlying 'cp' and 'mv' shell commands for file operations. For lf uses its own builtin copy and move operations by default. These are
this purpose, when you 'copy' a file, it doesn't actually copy the file on implemented as asynchronous operations and progress is shown in the bottom
the disk, but only records its name to memory. The actual file operation ruler. These commands do not overwrite existing files or directories with
takes place when you 'paste' in which case the 'cp' command is used. the same name. Instead, a suffix that is compatible with '--backup=numbered'
Similarly the 'mv' command is used for 'cut' followed by 'paste'. option in GNU cp is added to the new files or directories. Only file modes
are preserved and all other attributes are ignored including ownership,
timestamps, context, links, and xattr. Special files such as character and
block devices, named pipes, and sockets are skipped and links are followed.
Moving is performed using the rename operation of the underlying OS. This
can fail to move files between different partitions when it needs to copy
files. For these cases, users are expected to explicitly copy files and then
delete the old ones manually. Operation errors are shown in the message line
as well as the log file and they do not preemptively finish the
corresponding file operation.
You can customize these operations by defining a 'paste' command. This is a File operations can be performed on the current selected file or
special command that is called when it is defined instead of the builtin alternatively on multiple files by selecting them first. When you 'copy' a
implementation. The default behavior is similar to the following command: file, lf doesn't actually copy the file on the disk, but only records its
name to memory. The actual file copying takes place when you 'paste'.
Similarly 'paste' after a 'cut' operation moves the file.
You can customize copy and move operations by defining a 'paste' command.
This is a special command that is called when it is defined instead of the
builtin implementation. You can use the following example as a starting
point:
cmd paste %{{ cmd paste %{{
load=$(lf -remote 'load') load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
cp -R -n $list . cp -R $list .
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
mv -n $list . mv $list .
fi fi
lf -remote 'send load' lf -remote 'send load'
lf -remote 'send clear' lf -remote 'send clear'
}} }}
Some useful things are to use the backup option ('--backup') with 'cp' and Some useful things to be considered are to use the backup ('--backup')
'mv' commands if they support it (i.e. GNU implementation), change the and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if
command type to asynchronous, or use 'rsync' command with progress bar they support it (i.e. GNU implementation), change the command type to
option for copying and feed the progress to the client periodically with asynchronous, or use 'rsync' command with progress bar option for copying
remote 'echo' calls. and feed the progress to the client periodically with remote 'echo' calls.
By default, lf does not provide an actual file deletion command to protect By default, lf does not assign 'delete' command to a key to protect new
new users. You can define such a command and optionally assign a key if you users. You can customize file deletion by defining a 'delete' command. You
like. An example command to move selected files to a trash folder and remove can also assign a key to this command if you like. An example command to
files completely are provided in the example configuration file. move selected files to a trash folder and remove files completely after a
prompt are provided in the example configuration file.
Searching Files
There are two mechanisms implemented in lf to search a file in the current
directory. Searching is the traditional method to move the selection to a
file matching a given pattern. Finding is an alternative way to search for a
pattern possibly using fewer keystrokes.
Searching mechanism is implemented with commands 'search' (default '/'),
'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev'
(default 'N'). You can enable 'globsearch' option to match with a glob
pattern. Globbing supports '*' to match any sequence, '?' to match any
character, and '[...]' or '[^...] to match character sets or ranges. You can
enable 'incsearch' option to jump to the current match at each keystroke
while typing. In this mode, you can either use 'cmd-enter' to accept the
search or use 'cmd-escape' to cancel the search. Alternatively, you can also
map some other commands with 'cmap' to accept the search and execute the
command immediately afterwards. Possible candidates are 'up', 'down' and
their variants, 'updir', and 'open' commands. For example, you can use arrow
keys to finish the search with the following mappings:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
','). You can disable 'anchorfind' option to match a pattern at an arbitrary
position in the filename instead of the beginning. You can set the number of
keys to match using 'findlen' option. If you set this value to zero, then
the the keys are read until there is only a single match. Default values of
these two options are set to jump to the first file with the given initial.
Some options effect both searching and finding. You can disable 'wrapscan'
option to prevent searches to wrap around at the end of the file list. You
can disable 'ignorecase' option to match cases in the pattern and the
filename. This option is already automatically overridden if the pattern
contains upper case characters. You can disable 'smartcase' option to
disable this behavior. Two similar options 'ignoredia' and 'smartdia' are
provided to control matching diacritics in latin letters.
Opening Files Opening Files
You can define a an 'open' command (default 'l') to configure file opening. You can define a an 'open' command (default 'l' and '<right>') to configure
This command is only called when the current file is not a directory, file opening. This command is only called when the current file is not a
otherwise the directory is entered instead. You can define it just as you directory, otherwise the directory is entered instead. You can define it
would define any other command: just as you would define any other command:
cmd open $vi $fx cmd open $vi $fx
@@ -576,6 +666,9 @@ command:
esac esac
}} }}
You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
Following command is provided by default: Following command is provided by default:
cmd open &$OPENER $f cmd open &$OPENER $f
@@ -631,6 +724,41 @@ everything else fails, you can make use of the height argument to only feed
the first portion of the file to a program for preview. the first portion of the file to a program for preview.
Changing Directory
lf changes the working directory of the process to the current directory so
that shell commands always work in the displayed directory. After quitting,
it returns to the original directory where it is first launched like all
shell programs. If you want to stay in the current directory after quitting,
you can use one of the example wrapper shell scripts provided in the
repository.
There is a special command 'on-cd' that runs a shell command when it is
defined and the directory is changed. You can define it just as you would
define any other command:
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f$git\033[0m"
lf -remote "send $id set promptfmt \"$fmt\""
}}
This command runs whenever you change directory but not on startup. You can
add an extra call to make it run on startup as well:
cmd on-cd &{{ # ... }}
on-cd
Note that all shell commands are possible but '%' and '&' are usually more
appropriate as '$' and '!' causes flickers and pauses respectively.
Colorschemes Colorschemes
lf tries to automatically adapt its colors to the environment. On startup, lf tries to automatically adapt its colors to the environment. On startup,
@@ -650,6 +778,13 @@ If both of these environment variables are not set, then lf fallbacks to its
default colorscheme. Default lf colors are taken from GNU dircolors default colorscheme. Default lf colors are taken from GNU dircolors
defaults. These defaults use 8 basic colors and bold attribute. defaults. These defaults use 8 basic colors and bold attribute.
You should also note that lf uses 8 color mode by default which uses sgr
3-bit color escapes (e.g. '\033[34m'). If you want to use 256 colors, you
need to enable 'color256' option which then makes lf use sgr 8-bit color
escapes (e.g. '\033[38;5;4m'). This option is intended to eliminate
differences between default colors used by ls and lf since terminals may
render 3-bit and 8-bit escapes differently even for the same color.
Keeping this mechanism in mind, you can configure lf colors in two different Keeping this mechanism in mind, you can configure lf colors in two different
ways. First, you can configure 8 basic colors used by your terminal and lf ways. First, you can configure 8 basic colors used by your terminal and lf
should pick up those colors automatically. Depending on your terminal, you should pick up those colors automatically. Depending on your terminal, you
@@ -663,4 +798,10 @@ different file types and extensions. '$LS_COLORS' is more powerful than
'$LSCOLORS' and it can be used even when GNU programs are not installed on '$LSCOLORS' and it can be used even when GNU programs are not installed on
the system. You can combine this second method with the first method for the system. You can combine this second method with the first method for
best results. best results.
Lastly, you may also want to configure the colors of the prompt line to
match the rest of the colors. Colors of the prompt line can be configured
using the 'promptfmt' option which can include hardcoded colors as ansi
escapes. See the default value of this option to have an idea about how to
color this line.
` `
+12
View File
@@ -0,0 +1,12 @@
#
# For using these completions you must load it from .tcshrc
#
# source ~/.config/lf/lf.csh
#
set lf_args = "-command -cpuprofile -doc --help -last-dir-path -memprofile -remote -selection-path -server -version --version"
uncomplete lf
uncomplete lfcd
complete lf "C/-*/(${lf_args})/"
complete lfcd "C/-*/(${lf_args})/"
+18
View File
@@ -0,0 +1,18 @@
# Autocompletion for fish shell.
#
# You may put this file to a directory in $fish_complete_path variable:
#
# mkdir -p ~/.config/fish/completions
# ln -s "/path/to/lf.fish" ~/.config/fish/completions
#
complete -c lf -o command -r -d 'command to execute on client initialization'
complete -c lf -o cpuprofile -r -d 'path to the file to write the CPU profile'
complete -c lf -o doc -d 'show documentation'
complete -c lf -o last-dir-path -r -d 'path to the file to write the last dir on exit (to use for cd)'
complete -c lf -o memprofile -r -d 'path to the file to write the memory profile'
complete -c lf -o remote -x -d 'send remote command to server'
complete -c lf -o selection-path -r -d 'path to the file to write selected files on open (to use as open file dialog)'
complete -c lf -o server -d 'start server (automatic)'
complete -c lf -o version -d 'show version'
complete -c lf -o help -d 'show help'
+29
View File
@@ -0,0 +1,29 @@
#compdef lf
# For using these completions you must:
# - rename this file to _lf
# - add the containing folder to $fpath in .zshrc, like this:
# '''
# fpath=(/path/to/folder/containing_lf $fpath)
# autoload -U compinit
# compinit
# '''
#
# zsh completions for 'lf'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
local arguments
arguments=(
'-command[command to execute on client initialization]'
'-cpuprofile[path to the file to write the CPU profile]'
'-doc[show documentation]'
'-last-dir-path[path to the file to write the last dir on exit (to use for cd)]'
'-memprofile[path to the file to write the memory profile]'
'-remote[send remote command to server]'
'-selection-path[path to the file to write selected files on open (to use as open file dialog)]'
'-server[start server (automatic)]'
'-version[show version]'
'*:filename:_files'
)
_arguments -s $arguments
+6 -6
View File
@@ -5,11 +5,11 @@ rem You need to put this file to a folder in %PATH% variable.
:tmploop :tmploop
set tmpfile="%tmp%\lf.%random%.tmp" set tmpfile="%tmp%\lf.%random%.tmp"
if exist "%tmpfile%" goto:tmploop if exist %tmpfile% goto:tmploop
lf -last-dir-path="%tmpfile%" %* lf -last-dir-path=%tmpfile% %*
if not exist "%tmpfile%" exit if not exist %tmpfile% exit
set /p dir=<"%tmpfile%" set /p dir=<%tmpfile%
del /f "%tmpfile%" del /f %tmpfile%
if not exist "%dir%" exit if not exist "%dir%" exit
if "%dir%" == "%cd%" exit if "%dir%" == "%cd%" exit
cd "%dir%" cd /d "%dir%"
+13
View File
@@ -0,0 +1,13 @@
# Change working dir in shell to last dir in lf on exit.
#
# You need to either copy the content of this file to your shell rc file
# (e.g. ~/.tcshrc) or source this file directly:
#
# setenv LF_HOME "${HOME}/.config/lf"
# [ -e "${LF_HOME}/lfcd.csh" ] && source "${LF_HOME}/lfcd.csh"
#
# You may also like to assign a key to this command:
#
# bindkey -c "^O" lfcd
#
alias lfcd 'set _=`mktemp` && lf -last-dir-path=$_ "\!*" && set _=`cat $_ && rm -f $_` && [ -d "$_" ] && cd "$_"'
+17 -13
View File
@@ -38,29 +38,33 @@ map O $mimeopen --ask $f
cmd open ${{ cmd open ${{
case $(file --mime-type $f -b) in case $(file --mime-type $f -b) in
text/*) $EDITOR $fx;; text/*) $EDITOR $fx;;
*) for f in $fx; do $OPENER $f > /dev/null 2> /dev/null & done;; *) for f in $fx; do setsid $OPENER $f > /dev/null 2> /dev/null & done;;
esac esac
}} }}
# rename current file without overwrite # define a custom 'rename' command without prompt for overwrite
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 # cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
map r push :rename<space> # map r push :rename<space>
# make sure trash folder exists # make sure trash folder exists
%mkdir -p ~/.trash # %mkdir -p ~/.trash
# move current file or selected files to trash folder # move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options) # (also see 'man mv' for backup/overwrite options)
cmd trash %set -f; mv $fx ~/.trash cmd trash %set -f; mv $fx ~/.trash
# delete current file or selected files (prompting) # define a custom 'delete' command
cmd delete ${{ # cmd delete ${{
set -f # set -f
printf "$fx\n" # printf "$fx\n"
printf "delete?[y/n]" # printf "delete?[y/n]"
read ans # read ans
[ $ans = "y" ] && rm -rf $fx # [ $ans = "y" ] && rm -rf $fx
}} # }}
# use '<delete>' key for either 'trash' or 'delete' command
# map <delete> trash
# map <delete> delete
# extract the current file with the right command # extract the current file with the right command
# (xkcd link: https://xkcd.com/1168/) # (xkcd link: https://xkcd.com/1168/)
+654 -167
View File
File diff suppressed because it is too large. Load diff
+41 -15
View File
@@ -67,8 +67,8 @@ var gEvalTests = []struct {
{ {
`echo "hello\zworld"`, `echo "hello\zworld"`,
[]string{"echo", "helloworld", "\n"}, []string{"echo", `hello\zworld`, "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}, 1}}, []expr{&callExpr{"echo", []string{`hello\zworld`}, 1}},
}, },
{ {
@@ -90,7 +90,7 @@ var gEvalTests = []struct {
}, },
{ {
`echo hello\ world`, "echo hello\\\tworld",
[]string{"echo", "hello\tworld", "\n"}, []string{"echo", "hello\tworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\tworld"}, 1}}, []expr{&callExpr{"echo", []string{"hello\tworld"}, 1}},
}, },
@@ -101,10 +101,16 @@ var gEvalTests = []struct {
[]expr{&callExpr{"echo", []string{"hello\nworld"}, 1}}, []expr{&callExpr{"echo", []string{"hello\nworld"}, 1}},
}, },
{
`echo hello\\world`,
[]string{"echo", `hello\world`, "\n"},
[]expr{&callExpr{"echo", []string{`hello\world`}, 1}},
},
{ {
`echo hello\zworld`, `echo hello\zworld`,
[]string{"echo", "helloworld", "\n"}, []string{"echo", "hellozworld", "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}, 1}}, []expr{&callExpr{"echo", []string{"hellozworld"}, 1}},
}, },
{ {
@@ -125,6 +131,18 @@ var gEvalTests = []struct {
[]expr{&setExpr{"hidden", ""}, &setExpr{"preview", ""}}, []expr{&setExpr{"hidden", ""}, &setExpr{"preview", ""}},
}, },
{
`set ifs ""`,
[]string{"set", "ifs", "", "\n"},
[]expr{&setExpr{"ifs", ""}},
},
{
`set ifs "\n"`,
[]string{"set", "ifs", "\n", "\n"},
[]expr{&setExpr{"ifs", "\n"}},
},
{ {
"set ratios 1:2:3", "set ratios 1:2:3",
[]string{"set", "ratios", "1:2:3", "\n"}, []string{"set", "ratios", "1:2:3", "\n"},
@@ -292,13 +310,17 @@ var gEvalTests = []struct {
cd ~ cd ~
set hidden set hidden
}}`, }}`,
[]string{"cmd", "gohome", ":", "{{", []string{
"cmd", "gohome", ":", "{{",
"cd", "~", "\n", "cd", "~", "\n",
"set", "hidden", "\n", "set", "hidden", "\n",
"}}", "\n"}, "}}", "\n",
[]expr{&cmdExpr{"gohome", &listExpr{[]expr{ },
&callExpr{"cd", []string{"~"}, 1}, []expr{&cmdExpr{
&setExpr{"hidden", ""}}}, "gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}},
}}, }},
}, },
@@ -307,13 +329,17 @@ var gEvalTests = []struct {
cd ~ cd ~
set hidden set hidden
}}`, }}`,
[]string{"map", "gh", ":", "{{", []string{
"map", "gh", ":", "{{",
"cd", "~", "\n", "cd", "~", "\n",
"set", "hidden", "\n", "set", "hidden", "\n",
"}}", "\n"}, "}}", "\n",
[]expr{&mapExpr{"gh", &listExpr{[]expr{ },
&callExpr{"cd", []string{"~"}, 1}, []expr{&mapExpr{
&setExpr{"hidden", ""}}}, "gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}},
}}, }},
}, },
+9
View File
@@ -0,0 +1,9 @@
module github.com/gokcehan/lf
go 1.12
require (
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05
github.com/mattn/go-runewidth v0.0.4
gopkg.in/djherbis/times.v1 v1.2.0
)
+10
View File
@@ -0,0 +1,10 @@
github.com/doronbehar/termbox-go v0.0.0-20190817171036-93860e161317 h1:mdOm+1RdYwVwC4Wjb53M5L96fRwWJ8gI7YXwwiCsHTk=
github.com/doronbehar/termbox-go v0.0.0-20190817171036-93860e161317/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20191006140624-aa2cdd26fb8c h1:qvLYQAhDCaMq+XiQ+t4YLaTJtUyHC1r20odd6ryKYIk=
github.com/doronbehar/termbox-go v0.0.0-20191006140624-aa2cdd26fb8c/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05 h1:pmXx7j8+mmkFJB2+qoB1C/Mz8SWvMlHTxSWOptJrr7E=
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
gopkg.in/djherbis/times.v1 v1.2.0 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM=
gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8=
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"log"
"os"
"path/filepath"
"strings"
)
type iconMap map[string]string
func parseIcons() iconMap {
if env := os.Getenv("LF_ICONS"); env != "" {
return parseIconsEnv(env)
}
defaultIcons := []string{
"tw=🗀",
"st=🗀",
"ow=🗀",
"di=🗀",
"fi=🗎",
}
return parseIconsEnv(strings.Join(defaultIcons, ":"))
}
func parseIconsEnv(env string) iconMap {
icons := make(iconMap)
entries := strings.Split(env, ":")
for _, entry := range entries {
if entry == "" {
continue
}
pair := strings.Split(entry, "=")
if len(pair) != 2 {
log.Printf("invalid $LF_ICONS entry: %s", entry)
return icons
}
key, val := pair[0], pair[1]
icons[key] = val
}
return icons
}
func (im iconMap) get(f *file) string {
var key string
switch {
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
case f.IsDir() && f.Mode()&0002 != 0:
key = "ow"
case f.IsDir():
key = "di"
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.Mode()&os.ModeNamedPipe != 0:
key = "pi"
case f.Mode()&os.ModeSocket != 0:
key = "so"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0:
key = "su"
case f.Mode()&os.ModeSetgid != 0:
key = "sg"
case f.Mode().IsRegular() && f.Mode()&0111 != 0:
key = "ex"
default:
key = "*" + filepath.Ext(f.Name())
}
if val, ok := im[key]; ok {
return val
}
if val, ok := im["fi"]; ok {
return val
}
return " "
}
+181 -96
View File
@@ -26,107 +26,129 @@ You can run 'lf -help' to see descriptions of command line options.
The following commands are provided by lf with default keybindings: The following commands are provided by lf with default keybindings:
.PP .PP
.EX .EX
up (default 'k' and '<up>') up (default 'k' and '<up>')
half-up (default '<c-u>') half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>') page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>') down (default 'j' and '<down>')
half-down (default '<c-d>') half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>') page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>') updir (default 'h' and '<left>')
open (default 'l' and '<right>') open (default 'l' and '<right>')
quit (default 'q') quit (default 'q')
top (default 'gg' and '<home>') top (default 'gg' and '<home>')
bottom (default 'G' and '<end>') bottom (default 'G' and '<end>')
toggle (default '<space>') toggle (default '<space>')
invert (default 'v') invert (default 'v')
unselect (default 'u') unselect (default 'u')
copy (default 'y') copy (default 'y')
cut (default 'd') cut (default 'd')
paste (default 'p') paste (default 'p')
clear (default 'c') clear (default 'c')
redraw (default '<c-l>') redraw (default '<c-l>')
reload (default '<c-r>') reload (default '<c-r>')
read (default ':') read (default ':')
shell (default '$') rename (default 'r')
shell-pipe (default '%') shell (default '$')
shell-wait (default '!') shell-pipe (default '%')
shell-async (default '&') shell-wait (default '!')
search (default '/') shell-async (default '&')
search-back (default '?') find (default 'f')
search-next (default 'n') find-back (default 'F')
search-prev (default 'N') find-next (default ';')
mark-save (default 'm') find-prev (default ',')
mark-load (default "'") search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default `"`)
.EE .EE
.PP .PP
The following commands are provided by lf without default keybindings: The following commands are provided by lf without default keybindings:
.PP .PP
.EX .EX
draw draw the ui draw draw the ui
load load modified files and directories load load modified files and directories
sync synchronizes copied/cut files with server sync synchronize copied/cut files with server
echo prints its arguments to the message line echo print arguments to the message line
cd changes working directory to its argument echomsg same as echo but logging
select changes current file selection to its argument echoerr same as echomsg but red color
source reads the configuration file in its argument cd change working directory to the argument
push simulate key pushes given in its argument select change current file selection to the argument
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
.EE .EE
.PP .PP
The following command line commands are provided by lf with default keybindings: The following command line commands are provided by lf with default keybindings:
.PP .PP
.EX .EX
cmd-escape (default '<esc>') cmd-escape (default '<esc>')
cmd-complete (default '<tab>') cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>') cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>') cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>') cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>') cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>') cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>') cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>') cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>') cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>') cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>') cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>') cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>') cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>') cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>') cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>') cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>') cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>') cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>') cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>') cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>') cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>') cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>') cmd-transpose-word (default '<a-t>')
.EE .EE
.PP .PP
The following options can be used to customize the behavior of lf: The following options can be used to customize the behavior of lf:
.PP .PP
.EX .EX
dircounts boolean (default off) anchorfind boolean (default on)
dirfirst boolean (default on) color256 boolean (default off)
drawbox boolean (default off) dircounts boolean (default off)
globsearch boolean (default off) dirfirst boolean (default on)
hidden boolean (default off) drawbox boolean (default off)
ignorecase boolean (default on) globsearch boolean (default off)
preview boolean (default on) icons boolean (default off)
reverse boolean (default off) hidden boolean (default off)
smartcase boolean (default on) ignorecase boolean (default on)
wrapscan boolean (default on) ignoredia boolean (default off)
period integer (default 0) incsearch boolean (default off)
scrolloff integer (default 0) preview boolean (default on)
tabstop integer (default 8) reverse boolean (default off)
filesep string (default "\en") smartcase boolean (default on)
ifs string (default '') (not exported if empty) smartdia boolean (default off)
previewer string (default '') (not filtered if empty) wrapscan boolean (default on)
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f\e033[0m") wrapscroll boolean (default off)
shell string (default 'sh') number boolean (default off)
sortby string (default 'natural') relativenumber boolean (default off)
timefmt string (default 'Mon Jan _2 15:04:05 2006') findlen integer (default 1) (zero to prompt until single match)
ratios string (default '1:2:3') period integer (default 0) (zero to disable periodic loading)
info string (default '') scrolloff integer (default 0)
shellopts string (default '') tabstop integer (default 8)
errorfmt string (default "\e033[7;31;47m%s\e033[0m")
filesep string (default "\en")
ifs string (default '') (not exported if empty)
previewer string (default '') (not filtered if empty)
promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f\e033[0m")
shell string (default 'sh')
sortby string (default 'natural')
timefmt string (default 'Mon Jan _2 15:04:05 2006')
ratios string (default '1:2:3')
info string (default '')
shellopts string (default '')
.EE .EE
.PP .PP
The following variables are exported for shell commands: The following variables are exported for shell commands:
@@ -138,6 +160,12 @@ The following variables are exported for shell commands:
$id id number of the client $id id number of the client
.EE .EE
.PP .PP
The following variables are set to the corresponding values:
.PP
.EX
$LF_LEVEL current nesting level
.EE
.PP
The following default values are set to the environmental variables on unix when they are not set or empty: The following default values are set to the environmental variables on unix when they are not set or empty:
.PP .PP
.EX .EX
@@ -169,6 +197,9 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info map sn :set sortby natural; set info
map ss :set sortby size; set info size map ss :set sortby size; set info size
map st :set sortby time; set info time map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~ map gh cd ~
.EE .EE
.PP .PP
@@ -221,11 +252,9 @@ The following command prefixes are used by lf:
% shell-pipe shell command running with the ui % shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press ! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously & shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
.EE .EE
.PP .PP
The same evaluator is used for the command line and the configuration file for read and shell commands. The difference is that prefixes are not necessary in the command line. Instead, different modes are provided to read corresponding commands. These modes are mapped to the prefix keys above by default. Searching commands are only used from the command line. The same evaluator is used for the command line and the configuration file for read and shell commands. The difference is that prefixes are not necessary in the command line. Instead, different modes are provided to read corresponding commands. These modes are mapped to the prefix keys above by default.
.SH SYNTAX .SH SYNTAX
Characters from '#' to newline are comments and ignored: Characters from '#' to newline are comments and ignored:
.PP .PP
@@ -501,11 +530,19 @@ Getting the file selection is similarly done with 'load' command:
fi fi
.EE .EE
.PP .PP
There is a 'quit' command to close client connections and quit the server:
.PP
.EX
lf -remote 'quit'
.EE
.PP
Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users. Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users.
.SH FILE OPERATIONS .SH FILE OPERATIONS
lf uses the underlying 'cp' and 'mv' shell commands for file operations. For this purpose, when you 'copy' a file, it doesn't actually copy the file on the disk, but only records its name to memory. The actual file operation takes place when you 'paste' in which case the 'cp' command is used. Similarly the 'mv' command is used for 'cut' followed by 'paste'. lf uses its own builtin copy and move operations by default. These are implemented as asynchronous operations and progress is shown in the bottom ruler. These commands do not overwrite existing files or directories with the same name. Instead, a suffix that is compatible with '--backup=numbered' option in GNU cp is added to the new files or directories. Only file modes are preserved and all other attributes are ignored including ownership, timestamps, context, links, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are followed. Moving is performed using the rename operation of the underlying OS. This can fail to move files between different partitions when it needs to copy files. For these cases, users are expected to explicitly copy files and then delete the old ones manually. Operation errors are shown in the message line as well as the log file and they do not preemptively finish the corresponding file operation.
.PP .PP
You can customize these operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. The default behavior is similar to the following command: File operations can be performed on the current selected file or alternatively on multiple files by selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to memory. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file.
.PP
You can customize copy and move operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. You can use the following example as a starting point:
.PP .PP
.EX .EX
cmd paste %{{ cmd paste %{{
@@ -513,20 +550,35 @@ You can customize these operations by defining a 'paste' command. This is a spec
mode=$(echo "$load" | sed -n '1p') mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d') list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then if [ $mode = 'copy' ]; then
cp -R -n $list . cp -R $list .
elif [ $mode = 'move' ]; then elif [ $mode = 'move' ]; then
mv -n $list . mv $list .
fi fi
lf -remote 'send load' lf -remote 'send load'
lf -remote 'send clear' lf -remote 'send clear'
}} }}
.EE .EE
.PP .PP
Some useful things are to use the backup option ('--backup') with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls. Some useful things to be considered are to use the backup ('--backup') and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls.
.PP .PP
By default, lf does not provide an actual file deletion command to protect new users. You can define such a command and optionally assign a key if you like. An example command to move selected files to a trash folder and remove files completely are provided in the example configuration file. By default, lf does not assign 'delete' command to a key to protect new users. You can customize file deletion by defining a 'delete' command. You can also assign a key to this command if you like. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file.
.SH SEARCHING FILES
There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes.
.PP
Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. Alternatively, you can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. Possible candidates are 'up', 'down' and their variants, 'updir', and 'open' commands. For example, you can use arrow keys to finish the search with the following mappings:
.PP
.EX
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
.EE
.PP
Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial.
.PP
Some options effect both searching and finding. You can disable 'wrapscan' option to prevent searches to wrap around at the end of the file list. You can disable 'ignorecase' option to match cases in the pattern and the filename. This option is already automatically overridden if the pattern contains upper case characters. You can disable 'smartcase' option to disable this behavior. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters.
.SH OPENING FILES .SH OPENING FILES
You can define a an 'open' command (default 'l') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command: You can define a an 'open' command (default 'l' and '<right>') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command:
.PP .PP
.EX .EX
cmd open $vi $fx cmd open $vi $fx
@@ -549,6 +601,8 @@ You may want to use either file extensions or mime types from 'file' command:
}} }}
.EE .EE
.PP .PP
You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits.
.PP
Following command is provided by default: Following command is provided by default:
.PP .PP
.EX .EX
@@ -584,6 +638,33 @@ Since this script is called for each file selection change it needs to be as eff
.EE .EE
.PP .PP
Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview. Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview.
.SH CHANGING DIRECTORY
lf changes the working directory of the process to the current directory so that shell commands always work in the displayed directory. After quitting, it returns to the original directory where it is first launched like all shell programs. If you want to stay in the current directory after quitting, you can use one of the example wrapper shell scripts provided in the repository.
.PP
There is a special command 'on-cd' that runs a shell command when it is defined and the directory is changed. You can define it just as you would define any other command:
.PP
.EX
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f$git\e033[0m"
lf -remote "send $id set promptfmt \e"$fmt\e""
}}
.EE
.PP
This command runs whenever you change directory but not on startup. You can add an extra call to make it run on startup as well:
.PP
.EX
cmd on-cd &{{ # ... }}
on-cd
.EE
.PP
Note that all shell commands are possible but `%` and `&` are usually more appropriate as `$` and `!` causes flickers and pauses respectively.
.SH COLORSCHEMES .SH COLORSCHEMES
lf tries to automatically adapt its colors to the environment. On startup, first '$LS_COLORS' environment variable is checked. This variable is used by GNU ls to configure its colors based on file types and extensions. The value of this variable is often set by GNU dircolors in a shell configuration file. dircolors program itself can be configured with a configuration file. dircolors supports 256 colors along with common attributes such as bold and underline. lf tries to automatically adapt its colors to the environment. On startup, first '$LS_COLORS' environment variable is checked. This variable is used by GNU ls to configure its colors based on file types and extensions. The value of this variable is often set by GNU dircolors in a shell configuration file. dircolors program itself can be configured with a configuration file. dircolors supports 256 colors along with common attributes such as bold and underline.
.PP .PP
@@ -591,6 +672,10 @@ If '$LS_COLORS' variable is not set, '$LSCOLORS' variable is checked instead. Th
.PP .PP
If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute.
.PP .PP
You should also note that lf uses 8 color mode by default which uses sgr 3-bit color escapes (e.g. '\e033[34m'). If you want to use 256 colors, you need to enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. '\e033[38;5;4m'). This option is intended to eliminate differences between default colors used by ls and lf since terminals may render 3-bit and 8-bit escapes differently even for the same color.
.PP
Keeping this mechanism in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. Keeping this mechanism in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other.
.PP .PP
Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results.
.PP
Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line.
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=lf
Comment=Launches the lf file manager
Icon=utilities-terminal
Terminal=true
Exec=lf
Categories=ConsoleOnly;System;FileTools;FileManager
MimeType=inode/directory;
+50 -17
View File
@@ -6,14 +6,15 @@ import (
"log" "log"
"net" "net"
"os" "os"
"os/exec"
"path/filepath" "path/filepath"
"runtime" "runtime"
"runtime/pprof" "runtime/pprof"
"strconv"
) )
var ( var (
envPath = os.Getenv("PATH") envPath = os.Getenv("PATH")
envLevel = os.Getenv("LF_LEVEL")
) )
var ( var (
@@ -25,6 +26,8 @@ var (
gSocketPath string gSocketPath string
gLogPath string gLogPath string
gServerLogPath string gServerLogPath string
gSelect string
gCommand string
gVersion string gVersion string
) )
@@ -34,10 +37,32 @@ func init() {
log.Printf("hostname: %s", err) log.Printf("hostname: %s", err)
} }
gHostname = h gHostname = h
if envLevel == "" {
envLevel = "0"
}
}
func exportEnvVars() {
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
level, err := strconv.Atoi(envLevel)
if err != nil {
log.Printf("reading lf level: %s", err)
}
level++
os.Setenv("LF_LEVEL", strconv.Itoa(level))
} }
func startServer() { func startServer() {
cmd := exec.Command(os.Args[0], "-server") cmd := detachedCommand(os.Args[0], "-server")
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
log.Printf("starting server: %s", err) log.Printf("starting server: %s", err)
} }
@@ -99,6 +124,11 @@ func main() {
"", "",
"path to the file to write selected files on open (to use as open file dialog)") "path to the file to write selected files on open (to use as open file dialog)")
flag.StringVar(&gCommand,
"command",
"",
"command to execute on client initialization")
flag.Parse() flag.Parse()
gSocketProt = gDefaultSocketProt gSocketProt = gDefaultSocketProt
@@ -115,26 +145,13 @@ func main() {
defer pprof.StopCPUProfile() defer pprof.StopCPUProfile()
} }
switch flag.NArg() {
case 0:
case 1:
dir := flag.Arg(0)
if err := os.Chdir(dir); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
default:
fmt.Fprintf(os.Stderr, "only single directory is allowed\n")
os.Exit(2)
}
switch { switch {
case *showDoc: case *showDoc:
fmt.Print(genDocString) fmt.Print(genDocString)
case *showVersion: case *showVersion:
fmt.Println(gVersion) fmt.Println(gVersion)
case *remoteCmd != "": case *remoteCmd != "":
if err := sendRemote(*remoteCmd); err != nil { if err := remote(*remoteCmd); err != nil {
log.Fatalf("remote command: %s", err) log.Fatalf("remote command: %s", err)
} }
case *serverMode: case *serverMode:
@@ -150,6 +167,22 @@ func main() {
gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID)) gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID))
} }
switch flag.NArg() {
case 0:
_, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
case 1:
gSelect = flag.Arg(0)
default:
fmt.Fprintf(os.Stderr, "only single file or directory is allowed\n")
os.Exit(2)
}
exportEnvVars()
run() run()
} }
+20 -28
View File
@@ -41,22 +41,12 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune {
return nil return nil
} }
// This function is used to escape whitespaces with backlashes in a given // This function is used to escape whitespaces and special characters with
// string. If a whitespace is already escaped then it is not escaped again. // backlashes in a given string.
func escape(s string) string { func escape(s string) string {
esc := false
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
for _, r := range s { for _, r := range s {
if r == '\\' { if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
esc = true
continue
}
if esc {
esc = false
buf = append(buf, '\\', r)
continue
}
if unicode.IsSpace(r) {
buf = append(buf, '\\') buf = append(buf, '\\')
} }
buf = append(buf, r) buf = append(buf, r)
@@ -65,26 +55,29 @@ func escape(s string) string {
} }
// This function is used to remove backlashes that are used to escape // This function is used to remove backlashes that are used to escape
// whitespaces in a given string. // whitespaces and special characters in a given string.
func unescape(s string) string { func unescape(s string) string {
esc := false esc := false
buf := make([]rune, 0, len(s)) buf := make([]rune, 0, len(s))
for _, r := range s { for _, r := range s {
if esc {
if !unicode.IsSpace(r) && r != '\\' && r != ';' && r != '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
esc = false
continue
}
if r == '\\' { if r == '\\' {
esc = true esc = true
continue continue
} }
if esc { esc = false
esc = false
if unicode.IsSpace(r) {
buf = append(buf, r)
} else {
buf = append(buf, '\\', r)
}
continue
}
buf = append(buf, r) buf = append(buf, r)
} }
if esc {
buf = append(buf, '\\')
}
return string(buf) return string(buf)
} }
@@ -133,11 +126,10 @@ func splitWord(s string) (word, rest string) {
return return
} }
// This function converts a size in bytes to a human readable form. For this // This function converts a size in bytes to a human readable form using metric
// purpose metric suffixes are used (e.g. 1K = 1000). For values less than 10 // suffixes (e.g. 1K = 1000). For values less than 10 the first significant
// the first significant digit is shown, otherwise it is hidden. Numbers are // digit is shown, otherwise it is hidden. Numbers are always rounded down.
// always rounded down. For these reasons this function always show somewhat // This should be fine for most human beings.
// smaller values but it should be fine for most human beings.
func humanize(size int64) string { func humanize(size int64) string {
if size < 1000 { if size < 1000 {
return fmt.Sprintf("%dB", size) return fmt.Sprintf("%dB", size)
+14 -3
View File
@@ -80,8 +80,13 @@ func TestEscape(t *testing.T) {
{"foo", "foo"}, {"foo", "foo"},
{"foo bar", `foo\ bar`}, {"foo bar", `foo\ bar`},
{"foo bar", `foo\ \ bar`}, {"foo bar", `foo\ \ bar`},
{`foo\ bar`, `foo\ bar`}, {`foo\bar`, `foo\\bar`},
{`foo\bar`, `foo\bar`}, {`foo\ bar`, `foo\\\ bar`},
{`foo;bar`, `foo\;bar`},
{`foo#bar`, `foo\#bar`},
{`foo\tbar`, `foo\\tbar`},
{"foo\tbar", "foo\\\tbar"},
{`foo\`, `foo\\`},
} }
for _, test := range tests { for _, test := range tests {
@@ -98,9 +103,15 @@ func TestUnescape(t *testing.T) {
}{ }{
{"", ""}, {"", ""},
{"foo", "foo"}, {"foo", "foo"},
{`foo\bar`, `foo\bar`},
{`foo\ bar`, "foo bar"}, {`foo\ bar`, "foo bar"},
{`foo\ \ bar`, "foo bar"}, {`foo\ \ bar`, "foo bar"},
{`foo\\bar`, `foo\bar`},
{`foo\\\ bar`, `foo\ bar`},
{`foo\;bar`, `foo;bar`},
{`foo\#bar`, `foo#bar`},
{`foo\\tbar`, `foo\tbar`},
{"foo\\\tbar", "foo\tbar"},
{`foo\`, `foo\`},
} }
for _, test := range tests { for _, test := range tests {
+468 -95
View File
@@ -13,6 +13,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
times "gopkg.in/djherbis/times.v1"
) )
type linkState byte type linkState byte
@@ -25,9 +27,12 @@ const (
type file struct { type file struct {
os.FileInfo os.FileInfo
linkState linkState linkState linkState
path string path string
dirCount int dirCount int
accessTime time.Time
changeTime time.Time
ext string
} }
func readdir(path string) ([]*file, error) { func readdir(path string) ([]*file, error) {
@@ -62,11 +67,29 @@ func readdir(path string) ([]*file, error) {
} }
} }
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
// returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
ext := filepath.Ext(fpath)
files = append(files, &file{ files = append(files, &file{
FileInfo: lstat, FileInfo: lstat,
linkState: linkState, linkState: linkState,
path: fpath, path: fpath,
dirCount: -1, dirCount: -1,
accessTime: at,
changeTime: ct,
ext: ext,
}) })
} }
@@ -82,6 +105,7 @@ type dir struct {
files []*file // displayed files in directory including or excluding hidden ones files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files) allFiles []*file // all files in directory including hidden ones (same array as files)
sortType sortType // sort method and options from last sort sortType sortType // sort method and options from last sort
noPerm bool // whether lf has no permission to open the directory
} }
func newDir(path string) *dir { func newDir(path string) *dir {
@@ -97,6 +121,7 @@ func newDir(path string) *dir {
path: path, path: path,
files: files, files: files,
allFiles: files, allFiles: files,
noPerm: os.IsPermission(err),
} }
} }
@@ -122,6 +147,34 @@ func (dir *dir) sort() {
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].ModTime().Before(dir.files[j].ModTime()) return dir.files[i].ModTime().Before(dir.files[j].ModTime())
}) })
case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
})
case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
})
case extSort:
sort.SliceStable(dir.files, func(i, j int) bool {
leftExt := strings.ToLower(dir.files[i].ext)
rightExt := strings.ToLower(dir.files[j].ext)
// if the extension could not be determined (directories, files without)
// use a zero byte so that these files can be ranked higher
if leftExt == "" {
leftExt = "\x00"
}
if rightExt == "" {
rightExt = "\x00"
}
// in order to also have natural sorting with the filenames
// combine the name with the ext but have the ext at the front
left := leftExt + strings.ToLower(dir.files[i].Name())
right := rightExt + strings.ToLower(dir.files[j].Name())
return left < right
})
} }
if gOpts.sortType.option&reverseSort != 0 { if gOpts.sortType.option&reverseSort != 0 {
@@ -144,13 +197,13 @@ func (dir *dir) sort() {
// files to the first non-hidden file in the list // files to the first non-hidden file in the list
if gOpts.sortType.option&hiddenSort == 0 { if gOpts.sortType.option&hiddenSort == 0 {
sort.SliceStable(dir.files, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if dir.files[i].Name()[0] == '.' && dir.files[j].Name()[0] == '.' { if isHidden(dir.files[i]) && isHidden(dir.files[j]) {
return i < j return i < j
} }
return dir.files[i].Name()[0] == '.' return isHidden(dir.files[i])
}) })
for i, f := range dir.files { for i, f := range dir.files {
if f.Name()[0] != '.' { if !isHidden(f) {
dir.files = dir.files[i:] dir.files = dir.files[i:]
return return
} }
@@ -166,7 +219,7 @@ func (dir *dir) name() string {
return dir.files[dir.ind].Name() return dir.files[dir.ind].Name()
} }
func (dir *dir) find(name string, height int) { func (dir *dir) sel(name string, height int) {
if len(dir.files) == 0 { if len(dir.files) == 0 {
dir.ind, dir.pos = 0, 0 dir.ind, dir.pos = 0, 0
return return
@@ -188,17 +241,38 @@ func (dir *dir) find(name string, height int) {
} }
type nav struct { type nav struct {
dirs []*dir dirs []*dir
dirChan chan *dir copyBytes int64
regChan chan *reg copyTotal int64
dirCache map[string]*dir copyUpdate int
regCache map[string]*reg moveCount int
saves map[string]bool moveTotal int
marks map[string]string moveUpdate int
selections map[string]int deleteCount int
selectionInd int deleteTotal int
height int deleteUpdate int
search string copyBytesChan chan int64
copyTotalChan chan int64
moveCountChan chan int
moveTotalChan chan int
deleteCountChan chan int
deleteTotalChan chan int
dirChan chan *dir
regChan chan *reg
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
marks map[string]string
renameCache []string
selections map[string]int
selectionInd int
height int
find string
findBack bool
search string
searchBack bool
searchInd int
searchPos int
} }
func (nav *nav) loadDir(path string) *dir { func (nav *nav) loadDir(path string) *dir {
@@ -226,7 +300,7 @@ func (nav *nav) loadDir(path string) *dir {
d.loadTime = time.Now() d.loadTime = time.Now()
nd := newDir(path) nd := newDir(path)
nd.sort() nd.sort()
nd.find(d.name(), nav.height) nd.sel(d.name(), nav.height)
nav.dirChan <- nd nav.dirChan <- nd
}() }()
case d.sortType != gOpts.sortType: case d.sortType != gOpts.sortType:
@@ -234,7 +308,7 @@ func (nav *nav) loadDir(path string) *dir {
d.loading = true d.loading = true
name := d.name() name := d.name()
d.sort() d.sort()
d.find(name, nav.height) d.sel(name, nav.height)
d.loading = false d.loading = false
nav.dirChan <- d nav.dirChan <- d
}() }()
@@ -248,7 +322,7 @@ func (nav *nav) getDirs(wd string) {
for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) { for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
dir := nav.loadDir(curr) dir := nav.loadDir(curr)
dir.find(base, nav.height) dir.sel(base, nav.height)
dirs = append(dirs, dir) dirs = append(dirs, dir)
} }
@@ -266,15 +340,22 @@ func newNav(height int) *nav {
} }
nav := &nav{ nav := &nav{
dirChan: make(chan *dir), copyBytesChan: make(chan int64, 1024),
regChan: make(chan *reg), copyTotalChan: make(chan int64, 1024),
dirCache: make(map[string]*dir), moveCountChan: make(chan int, 1024),
regCache: make(map[string]*reg), moveTotalChan: make(chan int, 1024),
saves: make(map[string]bool), deleteCountChan: make(chan int, 1024),
marks: make(map[string]string), deleteTotalChan: make(chan int, 1024),
selections: make(map[string]int), dirChan: make(chan *dir),
selectionInd: 0, regChan: make(chan *reg),
height: height, dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
marks: make(map[string]string),
renameCache: make([]string, 2),
selections: make(map[string]int),
selectionInd: 0,
height: height,
} }
nav.getDirs(wd) nav.getDirs(wd)
@@ -288,6 +369,7 @@ func (nav *nav) renew() {
s, err := os.Stat(d.path) s, err := os.Stat(d.path)
if err != nil { if err != nil {
log.Printf("getting directory info: %s", err) log.Printf("getting directory info: %s", err)
return
} }
if d.loadTime.After(s.ModTime()) { if d.loadTime.After(s.ModTime()) {
return return
@@ -309,13 +391,13 @@ func (nav *nav) renew() {
} }
} }
func (nav *nav) reload() { func (nav *nav) reload() error {
nav.dirCache = make(map[string]*dir) nav.dirCache = make(map[string]*dir)
nav.regCache = make(map[string]*reg) nav.regCache = make(map[string]*reg)
wd, err := os.Getwd() wd, err := os.Getwd()
if err != nil { if err != nil {
log.Printf("getting current directory: %s", err) return fmt.Errorf("getting current directory: %s", err)
} }
curr, err := nav.currFile() curr, err := nav.currFile()
@@ -324,12 +406,14 @@ func (nav *nav) reload() {
last := nav.dirs[len(nav.dirs)-1] last := nav.dirs[len(nav.dirs)-1]
last.files = append(last.files, curr) last.files = append(last.files, curr)
} }
return nil
} }
func (nav *nav) position() { func (nav *nav) position() {
path := nav.currDir().path path := nav.currDir().path
for i := len(nav.dirs) - 2; i >= 0; i-- { for i := len(nav.dirs) - 2; i >= 0; i-- {
nav.dirs[i].find(filepath.Base(path), nav.height) nav.dirs[i].sel(filepath.Base(path), nav.height)
path = filepath.Dir(path) path = filepath.Dir(path)
} }
} }
@@ -374,7 +458,7 @@ func (nav *nav) preview() {
for i := 0; i < nav.height && buf.Scan(); i++ { for i := 0; i < nav.height && buf.Scan(); i++ {
for _, r := range buf.Text() { for _, r := range buf.Text() {
if r == 0 { if r == 0 {
reg.lines = []string{"\033[1mbinary\033[0m"} reg.lines = []string{"\033[7mbinary\033[0m"}
nav.regChan <- reg nav.regChan <- reg
return return
} }
@@ -389,7 +473,7 @@ func (nav *nav) preview() {
nav.regChan <- reg nav.regChan <- reg
} }
func (nav *nav) loadReg(ui *ui, path string) *reg { func (nav *nav) loadReg(path string) *reg {
r, ok := nav.regCache[path] r, ok := nav.regCache[path]
if !ok { if !ok {
go nav.preview() go nav.preview()
@@ -415,7 +499,7 @@ func (nav *nav) sort() {
for _, d := range nav.dirs { for _, d := range nav.dirs {
name := d.name() name := d.name()
d.sort() d.sort()
d.find(name, nav.height) d.sel(name, nav.height)
} }
} }
@@ -423,6 +507,9 @@ func (nav *nav) up(dist int) {
dir := nav.currDir() dir := nav.currDir()
if dir.ind == 0 { if dir.ind == 0 {
if gOpts.wrapscroll {
nav.bottom()
}
return return
} }
@@ -440,6 +527,9 @@ func (nav *nav) down(dist int) {
maxind := len(dir.files) - 1 maxind := len(dir.files) - 1
if dir.ind >= maxind { if dir.ind >= maxind {
if gOpts.wrapscroll {
nav.top()
}
return return
} }
@@ -543,56 +633,210 @@ func (nav *nav) unselect() {
} }
func (nav *nav) save(cp bool) error { func (nav *nav) save(cp bool) error {
if len(nav.selections) == 0 { list, err := nav.currFileOrSelections()
curr, err := nav.currFile() if err != nil {
if err != nil { return err
return errors.New("no file selected") }
}
if err := saveFiles([]string{curr.path}, cp); err != nil { if err := saveFiles(list, cp); err != nil {
return err return err
} }
nav.saves = make(map[string]bool) nav.saves = make(map[string]bool)
nav.saves[curr.path] = cp for _, f := range list {
} else { nav.saves[f] = cp
selections := nav.currSelections()
if err := saveFiles(selections, cp); err != nil {
return err
}
nav.saves = make(map[string]bool)
for f := range nav.selections {
nav.saves[f] = cp
}
} }
return nil return nil
} }
func (nav *nav) paste() error { func (nav *nav) copyAsync(ui *ui, srcs []string, dstDir string) {
list, cp, err := loadFiles() echo := &callExpr{"echoerr", []string{""}, 1}
_, err := os.Stat(dstDir)
if os.IsNotExist(err) {
echo.args[0] = err.Error()
ui.exprChan <- echo
return
}
total, err := copySize(srcs)
if err != nil {
echo.args[0] = err.Error()
ui.exprChan <- echo
return
}
nav.copyTotalChan <- total
nums, errs := copyAll(srcs, dstDir)
errCount := 0
loop:
for {
select {
case n := <-nums:
nav.copyBytesChan <- n
case err, ok := <-errs:
if !ok {
break loop
}
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
nav.copyTotalChan <- -total
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
func (nav *nav) moveAsync(ui *ui, srcs []string, dstDir string) {
echo := &callExpr{"echoerr", []string{""}, 1}
_, err := os.Stat(dstDir)
if os.IsNotExist(err) {
echo.args[0] = err.Error()
ui.exprChan <- echo
return
}
nav.moveTotalChan <- len(srcs)
errCount := 0
for _, src := range srcs {
nav.moveCountChan <- 1
srcStat, err := os.Stat(src)
if err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
continue
}
dst := filepath.Join(dstDir, filepath.Base(src))
dstStat, err := os.Stat(dst)
if os.SameFile(srcStat, dstStat) {
errCount++
echo.args[0] = fmt.Sprintf("[%d] rename %s %s: source and destination are the same file", errCount, src, dst)
ui.exprChan <- echo
continue
} else if !os.IsNotExist(err) {
var newPath string
for i := 1; !os.IsNotExist(err); i++ {
newPath = fmt.Sprintf("%s.~%d~", dst, i)
_, err = os.Stat(newPath)
}
dst = newPath
}
if err := os.Rename(src, dst); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
nav.moveTotalChan <- -len(srcs)
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
func (nav *nav) paste(ui *ui) error {
srcs, cp, err := loadFiles()
if err != nil { if err != nil {
return err return err
} }
if len(list) == 0 { if len(srcs) == 0 {
return errors.New("no file in copy/cut buffer") return errors.New("no file in copy/cut buffer")
} }
dir := nav.currDir() dstDir := nav.currDir().path
cmd := pasteCommand(list, dir, cp) if cp {
go nav.copyAsync(ui, srcs, dstDir)
if err := cmd.Run(); err != nil { } else {
return fmt.Errorf("pasting files: %s", err) go nav.moveAsync(ui, srcs, dstDir)
} }
if err := saveFiles(nil, false); err != nil { if err := saveFiles(nil, false); err != nil {
return fmt.Errorf("clearing copy/cut buffer: %s", err) return fmt.Errorf("clearing copy/cut buffer: %s", err)
} }
if err := remote("send sync"); err != nil {
return fmt.Errorf("paste: %s", err)
}
return nil
}
func (nav *nav) del(ui *ui) error {
list, err := nav.currFileOrSelections()
if err != nil {
return err
}
go func() {
echo := &callExpr{"echoerr", []string{""}, 1}
errCount := 0
nav.deleteTotalChan <- len(list)
for _, path := range list {
nav.deleteCountChan <- 1
if err := os.RemoveAll(path); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
nav.deleteTotalChan <- -len(list)
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}()
return nil
}
func (nav *nav) rename() error {
oldPath := nav.renameCache[0]
newPath := nav.renameCache[1]
dir, _ := filepath.Split(newPath)
os.MkdirAll(dir, os.ModePerm)
if _, err := os.Stat(newPath); err == nil { // file exists
if err := os.Remove(newPath); err != nil {
return err
}
}
if err := os.Rename(oldPath, newPath); err != nil {
return err
}
// TODO: change selection
if err := nav.sel(newPath); err != nil {
return err
}
return nil return nil
} }
@@ -607,7 +851,7 @@ func (nav *nav) sync() error {
nav.saves[f] = cp nav.saves[f] = cp
} }
return nil return nav.readMarks()
} }
func (nav *nav) cd(wd string) error { func (nav *nav) cd(wd string) error {
@@ -627,7 +871,10 @@ func (nav *nav) cd(wd string) error {
return nil return nil
} }
func (nav *nav) find(path string) error { func (nav *nav) sel(path string) error {
path = strings.Replace(path, "~", gUser.HomeDir, -1)
path = filepath.Clean(path)
lstat, err := os.Stat(path) lstat, err := os.Stat(path)
if err != nil { if err != nil {
return fmt.Errorf("select: %s", err) return fmt.Errorf("select: %s", err)
@@ -645,13 +892,36 @@ func (nav *nav) find(path string) error {
if last.loading { if last.loading {
last.files = append(last.files, &file{FileInfo: lstat}) last.files = append(last.files, &file{FileInfo: lstat})
} else { } else {
last.find(base, nav.height) last.sel(base, nav.height)
} }
return nil return nil
} }
func match(pattern, name string) (matched bool, err error) { func (nav *nav) globSel(pattern string, invert bool) error {
curDir := nav.currDir()
anyMatches := false
for i := 0; i < len(curDir.files); i++ {
match, err := filepath.Match(pattern, curDir.files[i].Name())
if err != nil {
return fmt.Errorf("glob-select: %s", err)
}
if match {
anyMatches = true
fpath := filepath.Join(curDir.path, curDir.files[i].Name())
if _, ok := nav.selections[fpath]; ok == invert {
nav.toggleSelection(fpath)
}
}
}
if !anyMatches {
return fmt.Errorf("glob-select: pattern not found: %s", pattern)
}
return nil
}
func findMatch(name, pattern string) bool {
if gOpts.ignorecase { if gOpts.ignorecase {
lpattern := strings.ToLower(pattern) lpattern := strings.ToLower(pattern)
if !gOpts.smartcase || lpattern == pattern { if !gOpts.smartcase || lpattern == pattern {
@@ -659,6 +929,95 @@ func match(pattern, name string) (matched bool, err error) {
name = strings.ToLower(name) name = strings.ToLower(name)
} }
} }
if gOpts.ignoredia {
lpattern := removeDiacritics(pattern)
if !gOpts.smartdia || lpattern == pattern {
pattern = lpattern
name = removeDiacritics(name)
}
}
if gOpts.anchorfind {
return strings.HasPrefix(name, pattern)
}
return strings.Contains(name, pattern)
}
func (nav *nav) findSingle() int {
count := 0
index := 0
last := nav.currDir()
for i := 0; i < len(last.files); i++ {
if findMatch(last.files[i].Name(), nav.find) {
count++
if count > 1 {
return count
}
index = i
}
}
if count == 1 {
if index > last.ind {
nav.down(index - last.ind)
} else {
nav.up(last.ind - index)
}
}
return count
}
func (nav *nav) findNext() bool {
last := nav.currDir()
for i := last.ind + 1; i < len(last.files); i++ {
if findMatch(last.files[i].Name(), nav.find) {
nav.down(i - last.ind)
return true
}
}
if gOpts.wrapscan {
for i := 0; i < last.ind; i++ {
if findMatch(last.files[i].Name(), nav.find) {
nav.up(last.ind - i)
return true
}
}
}
return false
}
func (nav *nav) findPrev() bool {
last := nav.currDir()
for i := last.ind - 1; i >= 0; i-- {
if findMatch(last.files[i].Name(), nav.find) {
nav.up(last.ind - i)
return true
}
}
if gOpts.wrapscan {
for i := len(last.files) - 1; i > last.ind; i-- {
if findMatch(last.files[i].Name(), nav.find) {
nav.down(i - last.ind)
return true
}
}
}
return false
}
func searchMatch(name, pattern string) (matched bool, err error) {
if gOpts.ignorecase {
lpattern := strings.ToLower(pattern)
if !gOpts.smartcase || lpattern == pattern {
pattern = lpattern
name = strings.ToLower(name)
}
}
if gOpts.ignoredia {
lpattern := removeDiacritics(pattern)
if !gOpts.smartdia || lpattern == pattern {
pattern = lpattern
name = removeDiacritics(name)
}
}
if gOpts.globsearch { if gOpts.globsearch {
return filepath.Match(pattern, name) return filepath.Match(pattern, name)
} }
@@ -668,7 +1027,7 @@ func match(pattern, name string) (matched bool, err error) {
func (nav *nav) searchNext() error { func (nav *nav) searchNext() error {
last := nav.currDir() last := nav.currDir()
for i := last.ind + 1; i < len(last.files); i++ { for i := last.ind + 1; i < len(last.files); i++ {
matched, err := match(nav.search, last.files[i].Name()) matched, err := searchMatch(last.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
@@ -679,7 +1038,7 @@ func (nav *nav) searchNext() error {
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := 0; i < last.ind; i++ { for i := 0; i < last.ind; i++ {
matched, err := match(nav.search, last.files[i].Name()) matched, err := searchMatch(last.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
@@ -695,7 +1054,7 @@ func (nav *nav) searchNext() error {
func (nav *nav) searchPrev() error { func (nav *nav) searchPrev() error {
last := nav.currDir() last := nav.currDir()
for i := last.ind - 1; i >= 0; i-- { for i := last.ind - 1; i >= 0; i-- {
matched, err := match(nav.search, last.files[i].Name()) matched, err := searchMatch(last.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
@@ -706,7 +1065,7 @@ func (nav *nav) searchPrev() error {
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := len(last.files) - 1; i > last.ind; i-- { for i := len(last.files) - 1; i > last.ind; i-- {
matched, err := match(nav.search, last.files[i].Name()) matched, err := searchMatch(last.files[i].Name(), nav.search)
if err != nil { if err != nil {
return err return err
} }
@@ -719,20 +1078,16 @@ func (nav *nav) searchPrev() error {
return nil return nil
} }
func (nav *nav) currDir() *dir { func (nav *nav) removeMark(mark string) error {
return nav.dirs[len(nav.dirs)-1] if _, ok := nav.marks[mark]; ok {
} delete(nav.marks, mark)
return nil
func (nav *nav) currFile() (*file, error) {
last := nav.dirs[len(nav.dirs)-1]
if len(last.files) == 0 {
return nil, fmt.Errorf("empty directory")
} }
return last.files[last.ind], nil return fmt.Errorf("no such mark")
} }
func (nav *nav) readMarks() error { func (nav *nav) readMarks() error {
nav.marks = make(map[string]string)
f, err := os.Open(gMarksPath) f, err := os.Open(gMarksPath)
if os.IsNotExist(err) { if os.IsNotExist(err) {
return nil return nil
@@ -758,14 +1113,6 @@ func (nav *nav) readMarks() error {
} }
func (nav *nav) writeMarks() error { func (nav *nav) writeMarks() error {
if len(nav.marks) == 0 {
return nil
}
if err := nav.readMarks(); err != nil {
return fmt.Errorf("reading marks file: %s", err)
}
if err := os.MkdirAll(filepath.Dir(gMarksPath), os.ModePerm); err != nil { if err := os.MkdirAll(filepath.Dir(gMarksPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err) return fmt.Errorf("creating data directory: %s", err)
} }
@@ -792,6 +1139,19 @@ func (nav *nav) writeMarks() error {
return nil return nil
} }
func (nav *nav) currDir() *dir {
return nav.dirs[len(nav.dirs)-1]
}
func (nav *nav) currFile() (*file, error) {
last := nav.dirs[len(nav.dirs)-1]
if len(last.files) == 0 {
return nil, fmt.Errorf("empty directory")
}
return last.files[last.ind], nil
}
type indexedSelections struct { type indexedSelections struct {
paths []string paths []string
indices []int indices []int
@@ -816,3 +1176,16 @@ func (nav *nav) currSelections() []string {
sort.Sort(indexedSelections{paths: paths, indices: indices}) sort.Sort(indexedSelections{paths: paths, indices: indices})
return paths return paths
} }
func (nav *nav) currFileOrSelections() (list []string, err error) {
if len(nav.selections) == 0 {
curr, err := nav.currFile()
if err != nil {
return nil, errors.New("no file selected")
}
return []string{curr.path}, nil
}
return nav.currSelections(), nil
}
+59 -23
View File
@@ -9,6 +9,9 @@ const (
nameSort nameSort
sizeSort sizeSort
timeSort timeSort
atimeSort
ctimeSort
extSort
) )
type sortOption byte type sortOption byte
@@ -25,43 +28,67 @@ type sortType struct {
} }
var gOpts struct { var gOpts struct {
dircounts bool anchorfind bool
drawbox bool color256 bool
globsearch bool dircounts bool
ignorecase bool drawbox bool
preview bool globsearch bool
smartcase bool icons bool
wrapscan bool ignorecase bool
period int incsearch bool
scrolloff int preview bool
tabstop int smartcase bool
filesep string ignoredia bool
ifs string smartdia bool
previewer string wrapscan bool
promptfmt string wrapscroll bool
shell string number bool
timefmt string relativenumber bool
ratios []int findlen int
info []string period int
shellopts []string scrolloff int
keys map[string]expr tabstop int
cmdkeys map[string]expr errorfmt string
cmds map[string]expr filesep string
sortType sortType ifs string
previewer string
promptfmt string
shell string
timefmt string
ratios []int
info []string
shellopts []string
keys map[string]expr
cmdkeys map[string]expr
cmds map[string]expr
sortType sortType
} }
func init() { func init() {
gOpts.anchorfind = true
gOpts.color256 = false
gOpts.dircounts = false gOpts.dircounts = false
gOpts.drawbox = false gOpts.drawbox = false
gOpts.globsearch = false gOpts.globsearch = false
gOpts.icons = false
gOpts.ignorecase = true gOpts.ignorecase = true
gOpts.incsearch = false
gOpts.preview = true gOpts.preview = true
gOpts.smartcase = true gOpts.smartcase = true
gOpts.ignoredia = false
gOpts.smartdia = false
gOpts.wrapscan = true gOpts.wrapscan = true
gOpts.wrapscroll = false
gOpts.number = false
gOpts.relativenumber = false
gOpts.findlen = 1
gOpts.period = 0 gOpts.period = 0
gOpts.scrolloff = 0 gOpts.scrolloff = 0
gOpts.tabstop = 8 gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m%s\033[0m"
gOpts.filesep = "\n" gOpts.filesep = "\n"
gOpts.ifs = ""
gOpts.previewer = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m" gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m"
gOpts.shell = gDefaultShell gOpts.shell = gDefaultShell
gOpts.timefmt = time.ANSIC gOpts.timefmt = time.ANSIC
@@ -105,12 +132,18 @@ func init() {
gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1} gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1}
gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1} gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1}
gOpts.keys["&"] = &callExpr{"shell-async", nil, 1} gOpts.keys["&"] = &callExpr{"shell-async", nil, 1}
gOpts.keys["f"] = &callExpr{"find", nil, 1}
gOpts.keys["F"] = &callExpr{"find-back", nil, 1}
gOpts.keys[";"] = &callExpr{"find-next", nil, 1}
gOpts.keys[","] = &callExpr{"find-prev", nil, 1}
gOpts.keys["/"] = &callExpr{"search", nil, 1} gOpts.keys["/"] = &callExpr{"search", nil, 1}
gOpts.keys["?"] = &callExpr{"search-back", nil, 1} gOpts.keys["?"] = &callExpr{"search-back", nil, 1}
gOpts.keys["n"] = &callExpr{"search-next", nil, 1} gOpts.keys["n"] = &callExpr{"search-next", nil, 1}
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1} gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1} gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1} gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1} gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1} gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
@@ -123,6 +156,9 @@ func init() {
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}} gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}} gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}} gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}}
gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}}
gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}}
gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1} gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1}
gOpts.cmdkeys = make(map[string]expr) gOpts.cmdkeys = make(map[string]expr)
+29 -25
View File
@@ -10,6 +10,7 @@ import (
"os/user" "os/user"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings"
) )
var ( var (
@@ -56,6 +57,12 @@ func init() {
u, err := user.Current() u, err := user.Current()
if err != nil { if err != nil {
log.Printf("user: %s", err) log.Printf("user: %s", err)
if os.Getenv("HOME") == "" {
log.Print("$HOME variable is empty or not set")
}
if os.Getenv("USER") == "" {
log.Print("$USER variable is empty or not set")
}
} }
gUser = u gUser = u
@@ -80,6 +87,10 @@ func init() {
gDefaultSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.sock", gUser.Username)) gDefaultSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.sock", gUser.Username))
} }
func detachedCommand(name string, arg ...string) *exec.Cmd {
return exec.Command(name, arg...)
}
func pauseCommand() *exec.Cmd { func pauseCommand() *exec.Cmd {
cmd := `echo cmd := `echo
echo -n 'Press any key to continue' echo -n 'Press any key to continue'
@@ -104,31 +115,6 @@ func shellCommand(s string, args []string) *exec.Cmd {
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func pasteCommand(list []string, dir *dir, cp bool) *exec.Cmd {
var sh string
var args []string
if cp {
sh = "cp"
args = append(args, "-R")
} else {
sh = "mv"
}
// XXX: POSIX standard states that -i flag shall do nothing when the
// response is not affirmative. Since this command is run with a nil
// stdin, it should not give an affirmative answer and in return this
// command should not overwrite existing files. Our intention here is
// to use the standard -i flag in place of non-standard -n flag to
// avoid overwrites.
args = append(args, "-i")
args = append(args, list...)
args = append(args, dir.path)
return exec.Command(sh, args...)
}
func setDefaults() { func setDefaults() {
gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`} gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`}
gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`} gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`}
@@ -146,3 +132,21 @@ func moveCursor(y, x int) {
func isExecutable(f os.FileInfo) bool { func isExecutable(f os.FileInfo) bool {
return f.Mode()&0111 != 0 return f.Mode()&0111 != 0
} }
func isHidden(f os.FileInfo) bool {
return f.Name()[0] == '.'
}
func exportFiles(f string, fs []string) {
envFile := f
envFiles := strings.Join(fs, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
}
+34 -31
View File
@@ -1,12 +1,14 @@
package main package main
import ( import (
"fmt"
"log" "log"
"os" "os"
"os/exec" "os/exec"
"os/user" "os/user"
"path/filepath" "path/filepath"
"strings" "strings"
"syscall"
) )
var ( var (
@@ -16,9 +18,7 @@ var (
envShell = os.Getenv("SHELL") envShell = os.Getenv("SHELL")
) )
var ( var envPathExt = os.Getenv("PATHEXT")
envPathExt = os.Getenv("PATHEXT")
)
var ( var (
gDefaultShell = "cmd" gDefaultShell = "cmd"
@@ -35,7 +35,7 @@ var (
func init() { func init() {
if envOpener == "" { if envOpener == "" {
envOpener = "start" envOpener = `start ""`
} }
if envEditor == "" { if envEditor == "" {
@@ -70,6 +70,12 @@ func init() {
gHistoryPath = filepath.Join(data, "lf", "history") gHistoryPath = filepath.Join(data, "lf", "history")
} }
func detachedCommand(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 8}
return cmd
}
func pauseCommand() *exec.Cmd { func pauseCommand() *exec.Cmd {
return exec.Command("cmd", "/c", "pause") return exec.Command("cmd", "/c", "pause")
} }
@@ -82,33 +88,6 @@ func shellCommand(s string, args []string) *exec.Cmd {
return exec.Command(gOpts.shell, args...) return exec.Command(gOpts.shell, args...)
} }
func pasteCommand(list []string, dir *dir, cp bool) *exec.Cmd {
var args []string
sh := "robocopy"
if !cp {
args = []string{"/move"}
}
for _, f := range list {
stat, err := os.Stat(f)
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
base := filepath.Base(f)
dest := filepath.Dir(f)
if stat.IsDir() {
exec.Command(sh, append(args, f, filepath.Join(dir.path, base))...).Run()
} else {
exec.Command(sh, append(args, dest, dir.path, base)...).Run()
}
}
// TODO: return 0 on success
return exec.Command(sh, args...)
}
func setDefaults() { func setDefaults() {
gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"} gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"}
gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"} gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"}
@@ -134,3 +113,27 @@ func isExecutable(f os.FileInfo) bool {
} }
return false return false
} }
func isHidden(f os.FileInfo) bool {
// TODO: implement
return false
}
func exportFiles(f string, fs []string) {
envFile := fmt.Sprintf(`"%s"`, f)
var quotedFiles []string
for _, f := range fs {
quotedFiles = append(quotedFiles, fmt.Sprintf(`"%s"`, f))
}
envFiles := strings.Join(quotedFiles, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(fs) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
}
+19 -21
View File
@@ -216,25 +216,24 @@ scan:
for !s.eof && s.chr != '"' { for !s.eof && s.chr != '"' {
if s.chr == '\\' { if s.chr == '\\' {
s.next() s.next()
switch s.chr { switch {
case '"', '\\': case s.chr == '"' || s.chr == '\\':
buf = append(buf, s.chr) buf = append(buf, s.chr)
case 'a': case s.chr == 'a':
buf = append(buf, '\a') buf = append(buf, '\a')
case 'b': case s.chr == 'b':
buf = append(buf, '\b') buf = append(buf, '\b')
case 'f': case s.chr == 'f':
buf = append(buf, '\f') buf = append(buf, '\f')
case 'n': case s.chr == 'n':
buf = append(buf, '\n') buf = append(buf, '\n')
case 'r': case s.chr == 'r':
buf = append(buf, '\r') buf = append(buf, '\r')
case 't': case s.chr == 't':
buf = append(buf, '\t') buf = append(buf, '\t')
case 'v': case s.chr == 'v':
buf = append(buf, '\v') buf = append(buf, '\v')
} case isDigit(s.chr):
if isDigit(s.chr) {
var oct []byte var oct []byte
for isDigit(s.chr) { for isDigit(s.chr) {
oct = append(oct, s.chr) oct = append(oct, s.chr)
@@ -245,13 +244,15 @@ scan:
log.Printf("scanning: %s", err) log.Printf("scanning: %s", err)
} }
buf = append(buf, byte(n)) buf = append(buf, byte(n))
} else { continue
s.next() default:
buf = append(buf, '\\', s.chr)
} }
} else {
buf = append(buf, s.chr)
s.next() s.next()
continue
} }
buf = append(buf, s.chr)
s.next()
} }
s.typ = tokenIdent s.typ = tokenIdent
s.tok = string(buf) s.tok = string(buf)
@@ -293,12 +294,9 @@ scan:
for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' { for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' {
if s.chr == '\\' { if s.chr == '\\' {
s.next() s.next()
if isSpace(s.chr) { buf = append(buf, s.chr)
buf = append(buf, s.chr) s.next()
s.next() continue
} else {
s.next()
}
} }
buf = append(buf, s.chr) buf = append(buf, s.chr)
s.next() s.next()
+21 -2
View File
@@ -13,6 +13,8 @@ var (
gCopyFile bool gCopyFile bool
gFileList []string gFileList []string
gConnList = make(map[int]net.Conn) gConnList = make(map[int]net.Conn)
gQuitChan = make(chan bool, 1)
gListener net.Listener
) )
func serve() { func serve() {
@@ -32,6 +34,8 @@ func serve() {
} }
defer l.Close() defer l.Close()
gListener = l
listen(l) listen(l)
} }
@@ -39,7 +43,13 @@ func listen(l net.Listener) {
for { for {
c, err := l.Accept() c, err := l.Accept()
if err != nil { if err != nil {
log.Printf("accepting connection: %s", err) select {
case <-gQuitChan:
log.Printf("bye!")
return
default:
log.Printf("accepting connection: %s", err)
}
} }
go handleConn(c) go handleConn(c)
} }
@@ -48,6 +58,7 @@ func listen(l net.Listener) {
func handleConn(c net.Conn) { func handleConn(c net.Conn) {
s := bufio.NewScanner(c) s := bufio.NewScanner(c)
Loop:
for s.Scan() { for s.Scan() {
log.Printf("listen: %s", s.Text()) log.Printf("listen: %s", s.Text())
word, rest := splitWord(s.Text()) word, rest := splitWord(s.Text())
@@ -61,7 +72,7 @@ func handleConn(c net.Conn) {
gCopyFile = false gCopyFile = false
default: default:
log.Printf("unexpected option to copy file(s): %s", s.Text()) log.Printf("unexpected option to copy file(s): %s", s.Text())
break break Loop
} }
gFileList = nil gFileList = nil
for s.Scan() && s.Text() != "" { for s.Scan() && s.Text() != "" {
@@ -103,6 +114,14 @@ func handleConn(c net.Conn) {
} }
} }
} }
case "quit":
gQuitChan <- true
for _, c := range gConnList {
fmt.Fprintln(c, "echo server is quitting...")
c.Close()
}
gListener.Close()
break Loop
default: default:
log.Printf("listen: unexpected command: %s", word) log.Printf("listen: unexpected command: %s", word)
} }
+111 -57
View File
@@ -15,8 +15,8 @@ import (
"unicode" "unicode"
"unicode/utf8" "unicode/utf8"
"github.com/doronbehar/termbox-go"
"github.com/mattn/go-runewidth" "github.com/mattn/go-runewidth"
"github.com/nsf/termbox-go"
) )
const gEscapeCode = 27 const gEscapeCode = 27
@@ -182,7 +182,7 @@ func (win *win) printReg(reg *reg) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
if reg.loading { if reg.loading {
fg = termbox.AttrBold fg = termbox.AttrReverse
win.print(2, 0, fg, bg, "loading...") win.print(2, 0, fg, bg, "loading...")
return return
} }
@@ -190,8 +190,6 @@ func (win *win) printReg(reg *reg) {
for i, l := range reg.lines { for i, l := range reg.lines {
fg, bg = win.print(2, i, fg, bg, l) fg, bg = win.print(2, i, fg, bg, l)
} }
return
} }
func fileInfo(f *file, d *dir) string { func fileInfo(f *file, d *dir) string {
@@ -233,6 +231,10 @@ func fileInfo(f *file, d *dir) string {
} }
case "time": case "time":
info = fmt.Sprintf("%s %12s", info, f.ModTime().Format("Jan _2 15:04")) info = fmt.Sprintf("%s %12s", info, f.ModTime().Format("Jan _2 15:04"))
case "atime":
info = fmt.Sprintf("%s %12s", info, f.accessTime.Format("Jan _2 15:04"))
case "ctime":
info = fmt.Sprintf("%s %12s", info, f.changeTime.Format("Jan _2 15:04"))
default: default:
log.Printf("unknown info type: %s", s) log.Printf("unknown info type: %s", s)
} }
@@ -241,22 +243,23 @@ func fileInfo(f *file, d *dir) string {
return info return info
} }
func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap) { func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap, icons iconMap) {
if win.w < 5 || dir == nil { if win.w < 5 || dir == nil {
return return
} }
fg, bg := termbox.ColorDefault, termbox.ColorDefault
if dir.loading { if dir.loading {
fg = termbox.AttrBold win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "loading...")
win.print(2, 0, fg, bg, "loading...") return
}
if dir.noPerm {
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "permission denied")
return return
} }
if len(dir.files) == 0 { if len(dir.files) == 0 {
fg = termbox.AttrBold win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "empty")
win.print(2, 0, fg, bg, "empty")
return return
} }
@@ -267,18 +270,45 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b
return return
} }
var lnwidth int
var lnformat string
if gOpts.number || gOpts.relativenumber {
lnwidth = 1
for j := 10; j < len(dir.files); j *= 10 {
lnwidth++
}
lnformat = fmt.Sprintf("%%%d.d ", lnwidth)
}
for i, f := range dir.files[beg:end] { for i, f := range dir.files[beg:end] {
fg, bg = colors.get(f) fg, bg := colors.get(f)
if lnwidth > 0 {
var ln string
if gOpts.number && (!gOpts.relativenumber || i == dir.pos) {
ln = fmt.Sprintf(lnformat, i+1+beg)
} else if gOpts.relativenumber {
if i < dir.pos {
ln = fmt.Sprintf(lnformat, dir.pos-i)
} else {
ln = fmt.Sprintf(lnformat, i-dir.pos)
}
}
win.print(0, i, termbox.ColorYellow, bg, ln)
}
path := filepath.Join(dir.path, f.Name()) path := filepath.Join(dir.path, f.Name())
if _, ok := selections[path]; ok { if _, ok := selections[path]; ok {
win.print(0, i, fg, termbox.ColorMagenta, " ") win.print(lnwidth, i, fg, termbox.ColorMagenta, " ")
} else if cp, ok := saves[path]; ok { } else if cp, ok := saves[path]; ok {
if cp { if cp {
win.print(0, i, fg, termbox.ColorYellow, " ") win.print(lnwidth, i, fg, termbox.ColorYellow, " ")
} else { } else {
win.print(0, i, fg, termbox.ColorRed, " ") win.print(lnwidth, i, fg, termbox.ColorRed, " ")
} }
} }
@@ -290,6 +320,11 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b
s = append(s, ' ') s = append(s, ' ')
if gOpts.icons {
s = append(s, []rune(icons.get(f))...)
s = append(s, ' ')
}
for _, r := range f.Name() { for _, r := range f.Name() {
s = append(s, r) s = append(s, r)
} }
@@ -321,7 +356,7 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b
s = append(s, ' ') s = append(s, ' ')
win.print(1, i, fg, bg, string(s)) win.print(lnwidth+1, i, fg, bg, string(s))
} }
} }
@@ -344,6 +379,7 @@ type ui struct {
keyAcc []rune keyAcc []rune
keyCount []rune keyCount []rune
colors colorMap colors colorMap
icons iconMap
} }
func getWidths(wtot int) []int { func getWidths(wtot int) []int {
@@ -425,6 +461,7 @@ func newUI() *ui {
keyChan: make(chan string, 1000), keyChan: make(chan string, 1000),
evChan: evChan, evChan: evChan,
colors: parseColors(), colors: parseColors(),
icons: parseIcons(),
} }
} }
@@ -455,16 +492,33 @@ func (ui *ui) sort() {
} }
name := ui.dirPrev.name() name := ui.dirPrev.name()
ui.dirPrev.sort() ui.dirPrev.sort()
ui.dirPrev.find(name, ui.wins[0].h) ui.dirPrev.sel(name, ui.wins[0].h)
} }
func (ui *ui) print(msg string) { func (ui *ui) echo(msg string) {
ui.msg = msg
}
func (ui *ui) echof(format string, a ...interface{}) {
ui.echo(fmt.Sprintf(format, a...))
}
func (ui *ui) echomsg(msg string) {
ui.msg = msg ui.msg = msg
log.Print(msg) log.Print(msg)
} }
func (ui *ui) printf(format string, a ...interface{}) { func (ui *ui) echomsgf(format string, a ...interface{}) {
ui.print(fmt.Sprintf(format, a...)) ui.echomsg(fmt.Sprintf(format, a...))
}
func (ui *ui) echoerr(msg string) {
ui.msg = fmt.Sprintf(gOpts.errorfmt, msg)
log.Printf("error: %s", msg)
}
func (ui *ui) echoerrf(format string, a ...interface{}) {
ui.echoerr(fmt.Sprintf(format, a...))
} }
type reg struct { type reg struct {
@@ -487,7 +541,7 @@ func (ui *ui) loadFile(nav *nav) {
if curr.IsDir() { if curr.IsDir() {
ui.dirPrev = nav.loadDir(curr.path) ui.dirPrev = nav.loadDir(curr.path)
} else if curr.Mode().IsRegular() { } else if curr.Mode().IsRegular() {
ui.regPrev = nav.loadReg(ui, curr.path) ui.regPrev = nav.loadReg(curr.path)
} }
} }
@@ -497,15 +551,17 @@ func (ui *ui) loadFileInfo(nav *nav) {
return return
} }
ui.msg = fmt.Sprintf("%v %4s %v", curr.Mode(), humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt)) ui.echof("%v %4s %v", curr.Mode(), humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt))
} }
func (ui *ui) drawPromptLine(nav *nav) { func (ui *ui) drawPromptLine(nav *nav) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
dir := nav.currDir() pwd := nav.currDir().path
nohome := strings.TrimPrefix(pwd, gUser.HomeDir)
pwd := strings.Replace(dir.path, gUser.HomeDir, "~", -1) if len(nohome) < len(pwd) {
pwd = "~/" + nohome
}
pwd = filepath.Clean(pwd) pwd = filepath.Clean(pwd)
var fname string var fname string
@@ -549,12 +605,27 @@ func (ui *ui) drawStatLine(nav *nav) {
ind := min(currDir.ind+1, tot) ind := min(currDir.ind+1, tot)
acc := string(ui.keyCount) + string(ui.keyAcc) acc := string(ui.keyCount) + string(ui.keyAcc)
ruler := fmt.Sprintf("%s %d/%d", acc, ind, tot) var progress string
if nav.copyTotal > 0 {
percentage := int((100 * float64(nav.copyBytes)) / float64(nav.copyTotal))
progress += fmt.Sprintf(" [%d%%]", percentage)
}
if nav.moveTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.moveCount, nav.moveTotal)
}
if nav.deleteTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.deleteCount, nav.deleteTotal)
}
ruler := fmt.Sprintf("%s%s %d/%d", acc, progress, ind, tot)
ui.msgWin.printRight(0, fg, bg, ruler) ui.msgWin.printRight(0, fg, bg, ruler)
} }
func (ui *ui) drawBox(nav *nav) { func (ui *ui) drawBox() {
fg, bg := termbox.ColorDefault, termbox.ColorDefault fg, bg := termbox.ColorDefault, termbox.ColorDefault
w, h := termbox.Size() w, h := termbox.Size()
@@ -602,7 +673,7 @@ func (ui *ui) draw(nav *nav) {
doff := len(nav.dirs) - length doff := len(nav.dirs) - length
for i := 0; i < length; i++ { for i := 0; i < length; i++ {
ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.selections, nav.saves, ui.colors) ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.selections, nav.saves, ui.colors, ui.icons)
} }
switch ui.cmdPrefix { switch ui.cmdPrefix {
@@ -628,7 +699,7 @@ func (ui *ui) draw(nav *nav) {
preview := ui.wins[len(ui.wins)-1] preview := ui.wins[len(ui.wins)-1]
if f.IsDir() { if f.IsDir() {
preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors) preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors, ui.icons)
} else if f.Mode().IsRegular() { } else if f.Mode().IsRegular() {
preview.printReg(ui.regPrev) preview.printReg(ui.regPrev)
} }
@@ -636,7 +707,7 @@ func (ui *ui) draw(nav *nav) {
} }
if gOpts.drawbox { if gOpts.drawbox {
ui.drawBox(nav) ui.drawBox()
} }
if ui.menuBuf != nil { if ui.menuBuf != nil {
@@ -742,7 +813,7 @@ func (ui *ui) pollEvent() termbox.Event {
ev.Key = val ev.Key = val
} else { } else {
ev.Key = termbox.KeyEsc ev.Key = termbox.KeyEsc
ui.printf("unknown key: %s", key) ui.echoerrf("unknown key: %s", key)
} }
} }
} }
@@ -794,34 +865,11 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
switch len(binds) { switch len(binds) {
case 0: case 0:
ui.printf("unknown mapping: %s", string(ui.keyAcc)) ui.echoerrf("unknown mapping: %s", string(ui.keyAcc))
ch <- draw ch <- draw
ui.keyAcc = nil ui.keyAcc = nil
ui.keyCount = nil ui.keyCount = nil
ui.menuBuf = nil ui.menuBuf = nil
case 1:
if ok {
if len(ui.keyCount) > 0 {
c, err := strconv.Atoi(string(ui.keyCount))
if err != nil {
log.Printf("converting command count: %s", err)
}
count = c
} else {
count = 1
}
expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok {
e.count = count
}
ch <- expr
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
} else {
ui.menuBuf = listBinds(binds)
ch <- draw
}
default: default:
if ok { if ok {
if len(ui.keyCount) > 0 { if len(ui.keyCount) > 0 {
@@ -830,8 +878,6 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
log.Printf("converting command count: %s", err) log.Printf("converting command count: %s", err)
} }
count = c count = c
} else {
count = 1
} }
expr := gOpts.keys[string(ui.keyAcc)] expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok { if e, ok := expr.(*callExpr); ok {
@@ -892,6 +938,14 @@ func (ui *ui) readExpr() <-chan expr {
return ch return ch
} }
func setColorMode() {
if gOpts.color256 {
termbox.SetOutputMode(termbox.Output256)
} else {
termbox.SetOutputMode(termbox.OutputNormal)
}
}
func (ui *ui) pause() { func (ui *ui) pause() {
termbox.Close() termbox.Close()
} }