Compare commits

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

* fixed doc

* fixed typo

* added dummy function for delete for windows

* detacted the functionality from the OS

* now deletion works based on selections

* added effective selection

* delete no longer sends 'send sync'

* fixed typo

* fixed typo

* added DOC to effective selection

* added DOC to deleteFiles()

* fixed DOC typos

* added ability to overwrite :delete

* added ability to overwrite :delete
2018-12-29 20:14:20 +03:00
Gokcehan 3efdfd3bca update documentation 2018-12-03 15:46:17 +03:00
Gokcehan b101603a4a Revert "only draw ui when the output pauses in shell-pipe"
This reverts commit 8229d972b9.
2018-12-03 15:43:12 +03:00
martinlebeda c693b7eae4 add ignoredia and smartdia option for search and find without diacritics (#118) 2018-12-03 15:41:53 +03:00
Gokcehan 4ee6488a09 add 'incsearch' option for incremental searching
Related #68
2018-11-24 19:02:04 +03:00
Gokcehan 8229d972b9 only draw ui when the output pauses in shell-pipe 2018-11-08 20:00:54 +03:00
Gokcehan 6193885a55 remove notice from readme 2018-10-30 21:47:45 +03:00
Gokcehan 6b1748240c add notice to readme 2018-10-02 14:41:07 +03:00
Gokcehan 629a7f3297 update documentation 2018-08-29 19:28:22 +03:00
Gokcehan 5e67147204 check HOME and USER variables on startup
Related #108
2018-08-27 19:38:08 +03:00
Gokcehan 266a583adb use load instead of reload after shell-pipe
Related #109
2018-08-27 19:01:21 +03:00
Gokcehan b22384d634 keep index when selection is deleted
Related #109
2018-08-27 18:57:55 +03:00
Gokcehan 4ba3c3cda9 keep reverse direction in find and search 2018-08-23 01:55:50 +03:00
Gokcehan 4420e41c76 add 'anchorfind' option to control find start
Related #68
2018-08-23 01:37:07 +03:00
Gokcehan a59a5aa712 use zero value in findlen for arbitrary length
Related #68
2018-08-23 01:29:59 +03:00
Gokcehan 170e39b95e add 'findlen' option to control number of chars
Related #68
2018-08-22 20:57:47 +03:00
Gokcehan 011cca76d1 add find commands to find as you type
Related #68
2018-08-22 20:05:22 +03:00
Gokcehan 0b8de7c77e detach server on windows
Related #106
2018-08-01 00:21:55 +03:00
Gokcehan d3f9a3588f handle non-existent directories during reload 2018-07-30 20:56:57 +03:00
Gokcehan a0935fabcb handle removed directories during load 2018-07-30 18:41:14 +03:00
Gokcehan e82cbb820f export 'LF_LEVEL' variable for nested instances
Related #107
2018-07-28 16:52:54 +03:00
Gokcehan 9234bcd5b8 try to reconnect after sleep 2018-07-26 22:11:05 +03:00
Gokcehan 7dbb61f295 try to reconnect when server is not yet started
Related #106
2018-07-26 21:58:09 +03:00
Gokcehan 40002a7752 add 'quit' command to server protocol
Related #106
2018-07-22 20:44:56 +03:00
Gokcehan ffa913d943 update readme 2018-07-19 00:59:09 +03:00
Gokcehan abf2187271 save last directory as a mark
Related #76
2018-07-17 19:45:31 +03:00
Gokcehan ee7293e2f7 change system configuration path on unix 2018-07-13 22:46:37 +03:00
Gokcehan 95a9305f70 add marks and history file locations to doc 2018-07-12 21:47:19 +03:00
Gokcehan cdf4fcb810 write history to history file on quit
Related #81
2018-07-12 21:22:36 +03:00
Gokcehan 211bcd0444 write marks to marks file on quit
Related #76
2018-07-11 20:09:26 +03:00
Gokcehan 0d0f7451ac add 'mark-save' and 'mark-load' commands for marks
Related #76
2018-07-09 21:35:04 +03:00
Gokcehan a80900f41e rename mark to selection 2018-07-09 21:22:10 +03:00
Gokcehan 552182958a use pager variable for doc on windows 2018-07-08 14:27:35 +03:00
Gokcehan d86e9c991c add 'doc' command to view documentation
Related #100
2018-07-07 17:50:47 +03:00
Gokcehan e74a43bf0e cleanup 2018-07-07 17:34:04 +03:00
Gokcehan 9d4accbcde typo 2018-07-06 01:16:58 +03:00
Gokcehan db9d795cb0 cleanup 2018-07-06 01:12:20 +03:00
Gokcehan 2f3c52f9f2 update readme 2018-07-05 23:15:16 +03:00
Gokcehan 63892ee83c generate man page from the documentation 2018-07-05 23:09:53 +03:00
28 changed files with 2902 additions and 689 deletions

No files matched your search

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
+1 -4
View File
@@ -15,7 +15,7 @@
`lf` (as in "list files") is a terminal file manager written in Go.
It is heavily inspired by ranger with some missing and extra features.
Some of the missing features are deliberately omitted since they are better handled by external tools.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information.
See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts.
![multicol-screenshot](http://i.imgur.com/DaTUenu.png)
![singlecol-screenshot](http://i.imgur.com/p95xzUj.png)
@@ -38,7 +38,6 @@ See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information.
## May-Futures
- Bookmarks
- Mouse control
## Installation
@@ -53,8 +52,6 @@ See [packages](https://github.com/gokcehan/lf/wiki/Packages) for community maint
## Usage
See [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts.
After the installation `lf` command should start the application in the current directory.
Run `lf -help` to see command line options.
+157 -34
View File
@@ -7,7 +7,7 @@ import (
"log"
"os"
"os/exec"
"strconv"
"path/filepath"
"strings"
"time"
)
@@ -26,6 +26,7 @@ type app struct {
cmdIn io.WriteCloser
cmdOutBuf []byte
cmdHistory []cmdItem
cmdHistoryBeg int
cmdHistoryInd int
}
@@ -46,7 +47,7 @@ func (app *app) readFile(path string) {
f, err := os.Open(path)
if err != nil {
app.ui.printf("opening file: %s", err)
app.ui.echoerrf("opening file: %s", err)
return
}
defer f.Close()
@@ -58,10 +59,74 @@ func (app *app) readFile(path string) {
}
if p.err != nil {
app.ui.printf("%s", p.err)
app.ui.echoerrf("%s", p.err)
}
}
func (app *app) readHistory() error {
f, err := os.Open(gHistoryPath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("opening history file: %s", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), " ", 2)
app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]})
}
app.cmdHistoryBeg = len(app.cmdHistory)
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
return nil
}
func (app *app) writeHistory() error {
if len(app.cmdHistory) == 0 {
return nil
}
local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg)
copy(local, app.cmdHistory[app.cmdHistoryBeg:])
app.cmdHistory = nil
if err := app.readHistory(); err != nil {
return fmt.Errorf("reading history file: %s", err)
}
app.cmdHistory = append(app.cmdHistory, local...)
if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
f, err := os.Create(gHistoryPath)
if err != nil {
return fmt.Errorf("creating history file: %s", err)
}
defer f.Close()
if len(app.cmdHistory) > 1000 {
app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:]
}
for _, cmd := range app.cmdHistory {
_, err = f.WriteString(fmt.Sprintf("%s %s\n", cmd.prefix, cmd.value))
if err != nil {
return fmt.Errorf("writing history file: %s", err)
}
}
return nil
}
// This is the main event loop of the application. Expressions are read from
// the client and the server on separate goroutines and sent here over channels
// for evaluation. Similarly directories and regular files are also read in
@@ -70,11 +135,53 @@ func (app *app) loop() {
clientChan := app.ui.readExpr()
serverChan := readExpr()
if gSelect != "" {
go func() {
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 {
select {
case <-app.quitChan:
if app.nav.copyTotal > 0 {
app.ui.echoerr("quit: copy operation in progress")
continue
}
if app.nav.moveTotal > 0 {
app.ui.echoerr("quit: move operation in progress")
continue
}
log.Print("bye!")
if err := app.nav.writeMarks(); err != nil {
log.Printf("writing marks file: %s", err)
}
if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err)
}
if gLastDirPath != "" {
f, err := os.Create(gLastDirPath)
if err != nil {
@@ -91,10 +198,42 @@ func (app *app) loop() {
}
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 d := <-app.nav.dirChan:
prev, ok := app.nav.dirCache[d.path]
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
@@ -143,31 +282,15 @@ func (app *app) loop() {
}
}
func (app *app) exportVars() {
var envFile string
func (app *app) exportFiles() {
var currFile string
if f, err := app.nav.currFile(); err == nil {
envFile = f.path
currFile = f.path
}
marks := app.nav.currMarks()
currSelections := app.nav.currSelections()
envFiles := strings.Join(marks, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(marks) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
exportFiles(currFile, currSelections)
}
func waitKey() error {
@@ -192,7 +315,7 @@ func waitKey() error {
// ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) {
app.exportVars()
app.exportFiles()
cmd := shellCommand(s, args)
@@ -229,13 +352,13 @@ func (app *app) runShell(s string, args []string, prefix string) {
}
if err != nil {
app.ui.printf("running shell: %s", err)
app.ui.echoerrf("running shell: %s", err)
}
switch prefix {
case "!":
if err := waitKey(); err != nil {
app.ui.printf("waiting key: %s", err)
app.ui.echoerrf("waiting key: %s", err)
}
}
@@ -244,12 +367,12 @@ func (app *app) runShell(s string, args []string, prefix string) {
switch prefix {
case "%":
go func() {
app.cmd = cmd
app.cmdOutBuf = nil
app.ui.msg = ""
app.ui.cmdPrefix = ">"
app.cmd = cmd
app.cmdOutBuf = nil
app.ui.msg = ""
app.ui.cmdPrefix = ">"
go func() {
reader := bufio.NewReader(out)
for {
b, err := reader.ReadByte()
@@ -268,7 +391,7 @@ func (app *app) runShell(s string, args []string, prefix string) {
}
app.cmd = nil
app.ui.cmdPrefix = ""
app.ui.exprChan <- &callExpr{"reload", nil, 1}
app.ui.exprChan <- &callExpr{"load", nil, 1}
}()
}
}
+21 -14
View File
@@ -8,11 +8,19 @@ import (
"net"
"os"
"strings"
"time"
"github.com/nsf/termbox-go"
)
func run() {
if err := termbox.Init(); err != nil {
log.Fatalf("initializing termbox: %s", err)
}
defer termbox.Close()
setColorMode()
f, err := os.Create(gLogPath)
if err != nil {
panic(err)
@@ -23,19 +31,14 @@ func run() {
log.Print("hi!")
if err := termbox.Init(); err != nil {
log.Fatalf("initializing termbox: %s", err)
}
defer termbox.Close()
termbox.SetOutputMode(termbox.Output256)
app := newApp()
for _, path := range gConfigPaths {
if _, err := os.Stat(path); !os.IsNotExist(err) {
app.readFile(path)
}
if err := app.nav.readMarks(); err != nil {
app.ui.echoerrf("reading marks file: %s", err)
}
if err := app.readHistory(); err != nil {
app.ui.echoerrf("reading history file: %s", err)
}
app.loop()
@@ -45,10 +48,14 @@ func readExpr() <-chan expr {
ch := make(chan expr)
go func() {
duration := 1 * time.Second
c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil {
for err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err))
return
time.Sleep(duration)
duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath)
}
fmt.Fprintf(c, "conn %d\n", gClientID)
@@ -133,7 +140,7 @@ func loadFiles() (list []string, cp bool, err error) {
return
}
func sendRemote(cmd string) error {
func remote(cmd string) error {
c, err := net.Dial(gSocketProt, gSocketPath)
if err != nil {
return fmt.Errorf("dialing to send server: %s", err)
+11 -11
View File
@@ -51,25 +51,25 @@ func parseColors() colorMap {
return parseColorsBSD(env)
}
// default values from dircolors
// default values from dircolors with removed background colors
defaultColors := []string{
// "rs=0",
"di=01;34",
"ln=01;36",
// "mh=00",
"pi=40;33",
"pi=33", // "pi=40;33",
"so=01;35",
"do=01;35",
"bd=40;33;01",
"cd=40;33;01",
"or=40;31;01",
"bd=33;01", // "bd=40;33;01",
"cd=33;01", // "cd=40;33;01",
"or=31;01", // "or=40;31;01",
// "mi=00",
"su=37;41",
"sg=30;43",
"ca=30;41",
"tw=30;42",
"ow=34;42",
"st=37;44",
"su=01;32", // "su=37;41",
"sg=01;32", // "sg=30;43",
// "ca=30;41",
"tw=01;34", // "tw=30;42",
"ow=01;34", // "ow=34;42",
"st=01;34", // "st=37;44",
"ex=01;32",
}
+82 -2
View File
@@ -27,10 +27,11 @@ var (
"bottom",
"toggle",
"invert",
"unmark",
"unselect",
"copy",
"cut",
"paste",
"delete",
"clear",
"draw",
"redraw",
@@ -41,12 +42,20 @@ var (
"shell-pipe",
"shell-wait",
"shell-async",
"find",
"find-back",
"find-next",
"find-prev",
"search",
"search-back",
"search-next",
"search-prev",
"mark-save",
"mark-load",
"sync",
"echo",
"echomsg",
"echoerr",
"cd",
"select",
"source",
@@ -54,6 +63,12 @@ var (
}
gOptWords = []string{
"anchorfind",
"noanchorfind",
"anchorfind!",
"color256",
"nocolor256",
"color256!",
"dircounts",
"nodircounts",
"dircounts!",
@@ -72,6 +87,12 @@ var (
"ignorecase",
"noignorecase",
"ignorecase!",
"ignoredia",
"noignoredia",
"ignoredia!",
"incsearch",
"noincsearch",
"incsearch!",
"preview",
"nopreview",
"preview!",
@@ -81,12 +102,23 @@ var (
"smartcase",
"nosmartcase",
"smartcase!",
"smartdia",
"nosmartdia",
"smartdia!",
"wrapscan",
"nowrapscan",
"wrapscan!",
"number",
"nonumber",
"number!",
"relativenumber",
"norelativenumber",
"relativenumber!",
"findlen",
"period",
"scrolloff",
"tabstop",
"errorfmt",
"filesep",
"ifs",
"previewer",
@@ -188,8 +220,9 @@ func matchFile(s string) (matches []string, longest string) {
wd, err := os.Getwd()
if err != nil {
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))
@@ -254,6 +287,15 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
words = append(words, c)
}
sort.Strings(words)
j := 0
for i := 1; i < len(words); i++ {
if words[j] == words[i] {
continue
}
j++
words[i], words[j] = words[j], words[i]
}
words = words[:j+1]
matches, longest = matchWord(s, words)
longestAcc = []rune(longest)
case 2:
@@ -280,6 +322,44 @@ func completeCmd(acc []rune) (matches []string, longestAcc []rune) {
return
}
func completeFile(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
files, err := ioutil.ReadDir(wd)
if err != nil {
log.Printf("reading directory: %s", err)
}
var longest string
for _, f := range files {
if !strings.HasPrefix(f.Name(), s) {
continue
}
matches = append(matches, f.Name())
if longest != "" {
longest = matchLongest(longest, f.Name())
} else if s != "" {
longest = f.Name()
}
}
if longest == "" {
longest = s
}
longestAcc = []rune(longest)
return
}
func completeShell(acc []rune) (matches []string, longestAcc []rune) {
s := string(acc)
f := tokenize(s)
+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
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"strconv"
"strings"
)
var normMap map[rune]rune
func init() {
normMap = make(map[rune]rune)
// (not only) european
appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
true,
)
// Vietnamese
appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
true,
)
}
func appendTransliterate(base, norm string, uppercase bool) {
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, baseRune := range baseRunes {
normMap[baseRune] = normRunes[i]
}
if uppercase {
upperBase := strings.ToUpper(base)
upperNorm := strings.ToUpper(norm)
normRune := []rune(upperNorm)
for i, baseRune := range []rune(upperBase) {
normMap[baseRune] = normRune[i]
}
}
}
// Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string {
var normalizedRunes []rune
for _, baseRune := range []rune(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) + ", ")
}
}
+225 -124
View File
@@ -1,4 +1,5 @@
//go:generate gen/docstring.sh
//go:generate gen/man.sh
/*
lf is a terminal file manager.
@@ -6,114 +7,139 @@ lf is a terminal file manager.
Source code can be found in the repository at https://github.com/gokcehan/lf.
This documentation can either be read from terminal using 'lf -doc' or online
at https://godoc.org/github.com/gokcehan/lf.
at https://godoc.org/github.com/gokcehan/lf. You can also use 'doc' command
(default '<f-1>') inside lf to view the documentation in a pager.
You can run 'lf -help' to see descriptions of command line options.
Reference
The following commands are provided by lf with default keybindings:
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>')
open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
toggle (default '<space>')
invert (default 'v')
unmark (default 'u')
copy (default 'y')
cut (default 'd')
paste (default 'p')
clear (default 'c')
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
shell-async (default '&')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>')
open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
toggle (default '<space>')
invert (default 'v')
unselect (default 'u')
copy (default 'y')
cut (default 'd')
paste (default 'p')
clear (default 'c')
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
shell-async (default '&')
find (default 'f')
find-back (default 'F')
find-next (default ';')
find-prev (default ',')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
The following commands are provided by lf without default keybindings:
draw draw the ui
load load modified files and directories
sync synchronizes copied/cut files with server
echo prints its arguments to the message line
cd changes working directory to its argument
select changes current file selection to its argument
source reads the configuration file in its argument
push simulate key pushes given in its argument
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default
keybindings:
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
The following options can be used to customize the behavior of lf:
dircounts boolean (default off)
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
preview boolean (default on)
reverse boolean (default off)
smartcase boolean (default on)
wrapscan boolean (default on)
period integer (default 0)
scrolloff integer (default 0)
tabstop integer (default 8)
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 '')
anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off)
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
incsearch boolean (default off)
preview boolean (default on)
reverse boolean (default off)
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
number boolean (default off)
relativenumber boolean (default off)
findlen integer (default 1) (zero to prompt until single match)
period integer (default 0) (zero to disable periodic loading)
scrolloff integer (default 0)
tabstop integer (default 8)
errorfmt string (default "\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:
$f current file
$fs marked file(s) separated with 'filesep'
$fx current file or marked file(s) if any
$fs selected file(s) separated with 'filesep'
$fx current file or selected file(s) if any
$id id number of the client
The following variables are set to the corresponding values:
$LF_LEVEL current nesting level
The following default values are set to the environmental variables on unix
when they are not set or empty:
@@ -154,14 +180,25 @@ Configuration
Configuration files should be located at:
system-wide user-specific
unix /etc/lfrc ~/.config/lf/lfrc
os system-wide user-specific
unix /etc/lf/lfrc ~/.config/lf/lfrc
windows C:\ProgramData\lf\lfrc C:\Users\<user>\AppData\Local\lf\lfrc
Marks file should be located at:
unix ~/.local/share/lf/marks
windows C:\Users\<user>\AppData\Local\lf\marks
History file should be located at:
unix ~/.local/share/lf/history
windows C:\Users\<user>\AppData\Local\lf\history
You can configure the default values of following variables to change these
locations:
$XDG_CONFIG_HOME ~/.config
$XDG_DATA_HOME ~/.local/share
%ProgramData% C:\ProgramData
%LOCALAPPDATA% C:\Users\<user>\AppData\Local
@@ -195,7 +232,8 @@ Characters from '#' to newline are comments and ignored:
There are three special commands ('set', 'map', and 'cmd') and their variants
for configuration.
'set' is used to set an option which can be boolean, integer, or string:
Command 'set' is used to set an option which can be boolean, integer, or
string:
set hidden # boolean on
set nohidden # boolean off
@@ -205,16 +243,16 @@ for configuration.
set sortby 'time' # string value with single quotes (whitespaces)
set sortby "time" # string value with double quotes (backslash escapes)
'map' is used to bind a key to a command which can be builtin command, custom
command, or shell command:
Command 'map' is used to bind a key to a command which can be builtin command,
custom command, or shell command:
map gh cd ~ # builtin command
map D trash # custom command
map i $less $f # shell command
map U !du -sh # waiting shell command
'cmap' is used to bind a key to a command line command which can only be one of
the builtin commands:
Command 'cmap' is used to bind a key to a command line command which can only
be one of the builtin commands:
cmap <c-g> cmd-escape
@@ -223,7 +261,7 @@ You can delete an existing binding by leaving the expression empty:
map gh # deletes 'gh' mapping
cmap <c-g> # deletes '<c-g>' mapping
'cmd' is used to define a custom command
Command 'cmd' is used to define a custom command:
cmd usage $du -h -d1 | less
@@ -335,7 +373,7 @@ trash. A first attempt to write such a command may look like this:
fi
}}
We check '$fs' to see if there are any marked files. Otherwise we just delete
We check '$fs' to see if there are any selected files. Otherwise we just delete
the current file. Since this is such a common pattern, a separate '$fx'
variable is provided. We can use this variable to get rid of the conditional:
@@ -464,60 +502,111 @@ Setting the file selection is done with 'save' command:
Getting the file selection is similarly done with 'load' command:
resp=$(lf -remote 'load')
mode=$(echo "$resp" | sed -n '1p')
list=$(echo "$resp" | sed '1d')
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
# do something with $list
elif [ $mode = 'move' ]; then
# do something else with $list
fi
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
should not be needed for users.
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.
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.
cmd paste ${{
You can customize copy and move operations by defining a 'paste' command. This
is a special command that is called when it is defined instead of the builtin
implementation. You can use the following example as a starting point:
cmd paste %{{
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
cp -R -n $list .
cp -R $list .
elif [ $mode = 'move' ]; then
mv -n $list .
mv $list .
fi
lf -remote "$(printf 'save\nmove\n\n')"
lf -remote 'send load'
lf -remote 'send sync'
lf -remote 'send clear'
}}
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.
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.
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.
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
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:
cmd open $vi $fx
@@ -603,6 +692,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.
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
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
@@ -615,5 +711,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
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.
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
+229 -126
View File
@@ -1,4 +1,4 @@
// DO NOT EDIT! (AUTO-GENERATED)
// Code generated by gen/docstring.sh DO NOT EDIT.
package main
@@ -9,115 +9,140 @@ Source code can be found in the repository at
https://github.com/gokcehan/lf.
This documentation can either be read from terminal using 'lf -doc' or
online at https://godoc.org/github.com/gokcehan/lf.
online at https://godoc.org/github.com/gokcehan/lf. You can also use 'doc'
command (default '<f-1>') inside lf to view the documentation in a pager.
You can run 'lf -help' to see descriptions of command line options.
Reference
The following commands are provided by lf with default keybindings:
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>')
open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
toggle (default '<space>')
invert (default 'v')
unmark (default 'u')
copy (default 'y')
cut (default 'd')
paste (default 'p')
clear (default 'c')
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
shell-async (default '&')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>')
open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
toggle (default '<space>')
invert (default 'v')
unselect (default 'u')
copy (default 'y')
cut (default 'd')
paste (default 'p')
clear (default 'c')
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
shell-async (default '&')
find (default 'f')
find-back (default 'F')
find-next (default ';')
find-prev (default ',')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
The following commands are provided by lf without default keybindings:
draw draw the ui
load load modified files and directories
sync synchronizes copied/cut files with server
echo prints its arguments to the message line
cd changes working directory to its argument
select changes current file selection to its argument
source reads the configuration file in its argument
push simulate key pushes given in its argument
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default
keybindings:
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
The following options can be used to customize the behavior of lf:
dircounts boolean (default off)
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
preview boolean (default on)
reverse boolean (default off)
smartcase boolean (default on)
wrapscan boolean (default on)
period integer (default 0)
scrolloff integer (default 0)
tabstop integer (default 8)
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 '')
anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off)
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
incsearch boolean (default off)
preview boolean (default on)
reverse boolean (default off)
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
number boolean (default off)
relativenumber boolean (default off)
findlen integer (default 1) (zero to prompt until single match)
period integer (default 0) (zero to disable periodic loading)
scrolloff integer (default 0)
tabstop integer (default 8)
errorfmt string (default "\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:
$f current file
$fs marked file(s) separated with 'filesep'
$fx current file or marked file(s) if any
$fs selected file(s) separated with 'filesep'
$fx current file or selected file(s) if any
$id id number of the client
The following variables are set to the corresponding values:
$LF_LEVEL current nesting level
The following default values are set to the environmental variables on unix
when they are not set or empty:
@@ -159,14 +184,25 @@ Configuration
Configuration files should be located at:
system-wide user-specific
unix /etc/lfrc ~/.config/lf/lfrc
os system-wide user-specific
unix /etc/lf/lfrc ~/.config/lf/lfrc
windows C:\ProgramData\lf\lfrc C:\Users\<user>\AppData\Local\lf\lfrc
Marks file should be located at:
unix ~/.local/share/lf/marks
windows C:\Users\<user>\AppData\Local\lf\marks
History file should be located at:
unix ~/.local/share/lf/history
windows C:\Users\<user>\AppData\Local\lf\history
You can configure the default values of following variables to change these
locations:
$XDG_CONFIG_HOME ~/.config
$XDG_DATA_HOME ~/.local/share
%ProgramData% C:\ProgramData
%LOCALAPPDATA% C:\Users\<user>\AppData\Local
@@ -202,7 +238,8 @@ Characters from '#' to newline are comments and ignored:
There are three special commands ('set', 'map', and 'cmd') and their
variants for configuration.
'set' is used to set an option which can be boolean, integer, or string:
Command 'set' is used to set an option which can be boolean, integer, or
string:
set hidden # boolean on
set nohidden # boolean off
@@ -212,16 +249,16 @@ variants for configuration.
set sortby 'time' # string value with single quotes (whitespaces)
set sortby "time" # string value with double quotes (backslash escapes)
'map' is used to bind a key to a command which can be builtin command,
custom command, or shell command:
Command 'map' is used to bind a key to a command which can be builtin
command, custom command, or shell command:
map gh cd ~ # builtin command
map D trash # custom command
map i $less $f # shell command
map U !du -sh # waiting shell command
'cmap' is used to bind a key to a command line command which can only be one
of the builtin commands:
Command 'cmap' is used to bind a key to a command line command which can
only be one of the builtin commands:
cmap <c-g> cmd-escape
@@ -230,7 +267,7 @@ You can delete an existing binding by leaving the expression empty:
map gh # deletes 'gh' mapping
cmap <c-g> # deletes '<c-g>' mapping
'cmd' is used to define a custom command
Command 'cmd' is used to define a custom command:
cmd usage $du -h -d1 | less
@@ -348,7 +385,7 @@ this:
fi
}}
We check '$fs' to see if there are any marked files. Otherwise we just
We check '$fs' to see if there are any selected files. Otherwise we just
delete the current file. Since this is such a common pattern, a separate
'$fx' variable is provided. We can use this variable to get rid of the
conditional:
@@ -486,63 +523,116 @@ newline character. Setting the file selection is done with 'save' command:
Getting the file selection is similarly done with 'load' command:
resp=$(lf -remote 'load')
mode=$(echo "$resp" | sed -n '1p')
list=$(echo "$resp" | sed '1d')
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
# do something with $list
elif [ $mode = 'move' ]; then
# do something else with $list
fi
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
should not be needed for users.
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.
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.
cmd paste ${{
You can customize copy and move operations by defining a 'paste' command.
This is a special command that is called when it is defined instead of the
builtin implementation. You can use the following example as a starting
point:
cmd paste %{{
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
cp -R -n $list .
cp -R $list .
elif [ $mode = 'move' ]; then
mv -n $list .
mv $list .
fi
lf -remote "$(printf 'save\nmove\n\n')"
lf -remote 'send load'
lf -remote 'send sync'
lf -remote 'send clear'
}}
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.
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.
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.
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
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:
cmd open $vi $fx
@@ -634,6 +724,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. 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
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
@@ -647,4 +744,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
the system. You can 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.
`
+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'
+13 -12
View File
@@ -31,9 +31,6 @@ map X !$f
map o &mimeopen $f
map O $mimeopen --ask $f
# show documentation (overrides 'search-back' command)
map ? $lf -doc | $PAGER
# define a custom 'open' command
# This command is called when current file is not a directory. You may want to
# use either file extensions and/or mime types here. Below uses an editor for
@@ -50,20 +47,24 @@ cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
map r push :rename<space>
# make sure trash folder exists
%mkdir -p ~/.trash
# %mkdir -p ~/.trash
# move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options)
cmd trash %set -f; mv $fx ~/.trash
# delete current file or selected files (prompting)
cmd delete ${{
set -f
printf "$fx\n"
printf "delete?[y/n]"
read ans
[ $ans = "y" ] && rm -rf $fx
}}
# define a custom 'delete' command
# cmd delete ${{
# set -f
# printf "$fx\n"
# printf "delete?[y/n]"
# read ans
# [ $ans = "y" ] && rm -rf $fx
# }}
# use '<delete>' key for either 'trash' or 'delete' command
# map <delete> trash
# map <delete> delete
# extract the current file with the right command
# (xkcd link: https://xkcd.com/1168/)
+449 -75
View File
@@ -4,6 +4,7 @@ import (
"io"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"time"
@@ -13,6 +14,27 @@ import (
func (e *setExpr) eval(app *app, args []string) {
switch e.opt {
case "anchorfind":
gOpts.anchorfind = true
case "noanchorfind":
gOpts.anchorfind = false
case "anchorfind!":
gOpts.anchorfind = !gOpts.anchorfind
case "color256":
gOpts.color256 = true
setColorMode()
app.ui.pause()
app.ui.resume()
case "nocolor256":
gOpts.color256 = false
setColorMode()
app.ui.pause()
app.ui.resume()
case "color256!":
gOpts.color256 = !gOpts.color256
setColorMode()
app.ui.pause()
app.ui.resume()
case "dircounts":
gOpts.dircounts = true
case "nodircounts":
@@ -73,6 +95,18 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.ignorecase = false
case "ignorecase!":
gOpts.ignorecase = !gOpts.ignorecase
case "ignoredia":
gOpts.ignoredia = true
case "noignoredia":
gOpts.ignoredia = false
case "ignoredia!":
gOpts.ignoredia = !gOpts.ignoredia
case "incsearch":
gOpts.incsearch = true
case "noincsearch":
gOpts.incsearch = false
case "incsearch!":
gOpts.incsearch = !gOpts.incsearch
case "preview":
gOpts.preview = true
case "nopreview":
@@ -97,20 +131,49 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.smartcase = false
case "smartcase!":
gOpts.smartcase = !gOpts.smartcase
case "smartdia":
gOpts.smartdia = true
case "nosmartdia":
gOpts.smartdia = false
case "smartdia!":
gOpts.smartdia = !gOpts.smartdia
case "wrapscan":
gOpts.wrapscan = true
case "nowrapscan":
gOpts.wrapscan = false
case "wrapscan!":
gOpts.wrapscan = !gOpts.wrapscan
case "period":
case "number":
gOpts.number = true
case "nonumber":
gOpts.number = false
case "number!":
gOpts.number = !gOpts.number
case "relativenumber":
gOpts.relativenumber = true
case "norelativenumber":
gOpts.relativenumber = false
case "relativenumber!":
gOpts.relativenumber = !gOpts.relativenumber
case "findlen":
n, err := strconv.Atoi(e.val)
if err != nil {
app.ui.printf("period: %s", err)
app.ui.echoerrf("findlen: %s", err)
return
}
if n < 0 {
app.ui.print("period: value should be a non-negative number")
app.ui.echoerr("findlen: value should be a non-negative number")
return
}
gOpts.findlen = n
case "period":
n, err := strconv.Atoi(e.val)
if err != nil {
app.ui.echoerrf("period: %s", err)
return
}
if n < 0 {
app.ui.echoerr("period: value should be a non-negative number")
return
}
gOpts.period = n
@@ -123,25 +186,27 @@ func (e *setExpr) eval(app *app, args []string) {
case "scrolloff":
n, err := strconv.Atoi(e.val)
if err != nil {
app.ui.printf("scrolloff: %s", err)
app.ui.echoerrf("scrolloff: %s", err)
return
}
if n < 0 {
app.ui.print("scrolloff: value should be a non-negative number")
app.ui.echoerr("scrolloff: value should be a non-negative number")
return
}
gOpts.scrolloff = n
case "tabstop":
n, err := strconv.Atoi(e.val)
if err != nil {
app.ui.printf("tabstop: %s", err)
app.ui.echoerrf("tabstop: %s", err)
return
}
if n <= 0 {
app.ui.print("tabstop: value should be a positive number")
app.ui.echoerr("tabstop: value should be a positive number")
return
}
gOpts.tabstop = n
case "errorfmt":
gOpts.errorfmt = e.val
case "filesep":
gOpts.filesep = e.val
case "ifs":
@@ -154,7 +219,7 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.shell = e.val
case "sortby":
if e.val != "natural" && e.val != "name" && e.val != "size" && e.val != "time" {
app.ui.print("sortby: value should either be 'natural', 'name', 'size' or 'time'")
app.ui.echoerr("sortby: value should either be 'natural', 'name', 'size' or 'time'")
return
}
switch e.val {
@@ -177,17 +242,17 @@ func (e *setExpr) eval(app *app, args []string) {
for _, s := range toks {
n, err := strconv.Atoi(s)
if err != nil {
app.ui.printf("ratios: %s", err)
app.ui.echoerrf("ratios: %s", err)
return
}
if n <= 0 {
app.ui.print("ratios: value should be a positive number")
app.ui.echoerr("ratios: value should be a positive number")
return
}
rats = append(rats, n)
}
if gOpts.preview && len(rats) < 2 {
app.ui.print("ratios: should consist of at least two numbers when 'preview' is enabled")
app.ui.echoerr("ratios: should consist of at least two numbers when 'preview' is enabled")
return
}
gOpts.ratios = rats
@@ -197,7 +262,7 @@ func (e *setExpr) eval(app *app, args []string) {
toks := strings.Split(e.val, ":")
for _, s := range toks {
if s != "" && s != "size" && s != "time" {
app.ui.print("info: should consist of 'size' or 'time' separated with colon")
app.ui.echoerr("info: should consist of 'size' or 'time' separated with colon")
return
}
}
@@ -205,7 +270,7 @@ func (e *setExpr) eval(app *app, args []string) {
case "shellopts":
gOpts.shellopts = strings.Split(e.val, ":")
default:
app.ui.printf("unknown option: %s", e.opt)
app.ui.echoerrf("unknown option: %s", e.opt)
}
}
@@ -252,6 +317,181 @@ func splitKeys(s string) (keys []string) {
return
}
func update(app *app) {
switch {
case gOpts.incsearch && app.ui.cmdPrefix == "/":
app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight)
last := app.nav.currDir()
last.ind = app.nav.searchInd
last.pos = app.nav.searchPos
if app.nav.searchBack {
if err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
return
}
} else {
if err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search)
return
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case gOpts.incsearch && app.ui.cmdPrefix == "?":
app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight)
last := app.nav.currDir()
last.ind = app.nav.searchInd
last.pos = app.nav.searchPos
if app.nav.searchBack {
if err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
return
}
} else {
if err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search)
return
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
}
func insert(app *app, arg string) {
switch {
case gOpts.incsearch && (app.ui.cmdPrefix == "/" || app.ui.cmdPrefix == "?"):
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
update(app)
case app.ui.cmdPrefix == "find: ":
app.nav.find = string(app.ui.cmdAccLeft) + arg + string(app.ui.cmdAccRight)
if gOpts.findlen == 0 {
switch app.nav.findSingle() {
case 0:
app.ui.echoerrf("find: pattern not found: %s", app.nav.find)
case 1:
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
default:
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
return
}
} else {
if len(app.nav.find) < gOpts.findlen {
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
return
}
if !app.nav.findNext() {
app.ui.echoerrf("find: pattern not found: %s", app.nav.find)
} else {
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
}
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
case app.ui.cmdPrefix == "find-back: ":
app.nav.find = string(app.ui.cmdAccLeft) + arg + string(app.ui.cmdAccRight)
if gOpts.findlen == 0 {
switch app.nav.findSingle() {
case 0:
app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find)
case 1:
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
default:
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
return
}
} else {
if len(app.nav.find) < gOpts.findlen {
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
return
}
if !app.nav.findPrev() {
app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find)
} else {
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
}
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
case app.ui.cmdPrefix == "delete?[y/N]: ":
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
if arg == "y" {
if err := app.nav.del(); err != nil {
app.ui.echoerrf("delete: %s", err)
return
}
app.nav.unselect()
if err := remote("send load"); err != nil {
app.ui.echoerrf("delete: %s", err)
}
}
case app.ui.cmdPrefix == "mark-save: ":
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
return
}
app.nav.marks[arg] = wd
case app.ui.cmdPrefix == "mark-load: ":
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
path, ok := app.nav.marks[arg]
if !ok {
app.ui.echoerr("mark-load: no such mark")
return
}
if err := app.nav.cd(path); err != nil {
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
if wd != path {
app.nav.marks["'"] = wd
}
default:
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
}
}
func (e *callExpr) eval(app *app, args []string) {
switch e.name {
case "up":
@@ -281,7 +521,7 @@ func (e *callExpr) eval(app *app, args []string) {
case "updir":
for i := 0; i < e.count; i++ {
if err := app.nav.updir(); err != nil {
app.ui.printf("%s", err)
app.ui.echoerrf("%s", err)
return
}
}
@@ -290,14 +530,14 @@ func (e *callExpr) eval(app *app, args []string) {
case "open":
curr, err := app.nav.currFile()
if err != nil {
app.ui.printf("opening: %s", err)
app.ui.echoerrf("opening: %s", err)
return
}
if curr.IsDir() {
err := app.nav.open()
if err != nil {
app.ui.printf("opening directory: %s", err)
app.ui.echoerrf("opening directory: %s", err)
return
}
app.ui.loadFile(app.nav)
@@ -314,11 +554,8 @@ func (e *callExpr) eval(app *app, args []string) {
defer out.Close()
var path string
if len(app.nav.marks) != 0 {
marks := app.nav.currMarks()
path = strings.Join(marks, "\n")
} else if curr, err := app.nav.currFile(); err == nil {
path = curr.path
if list, err := app.nav.currFileOrSelections(); err == nil {
path = strings.Join(list, "\n")
} else {
return
}
@@ -354,46 +591,54 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.loadFileInfo(app.nav)
case "invert":
app.nav.invert()
case "unmark":
app.nav.unmark()
case "unselect":
app.nav.unselect()
case "copy":
if err := app.nav.save(true); err != nil {
app.ui.printf("copy: %s", err)
app.ui.echoerrf("copy: %s", err)
return
}
app.nav.unmark()
if err := sendRemote("send sync"); err != nil {
app.ui.printf("copy: %s", err)
app.nav.unselect()
if err := remote("send sync"); err != nil {
app.ui.echoerrf("copy: %s", err)
}
case "cut":
if err := app.nav.save(false); err != nil {
app.ui.printf("cut: %s", err)
app.ui.echoerrf("cut: %s", err)
return
}
app.nav.unmark()
if err := sendRemote("send sync"); err != nil {
app.ui.printf("cut: %s", err)
app.nav.unselect()
if err := remote("send sync"); err != nil {
app.ui.echoerrf("cut: %s", err)
}
case "paste":
if cmd, ok := gOpts.cmds["paste"]; ok {
cmd.eval(app, e.args)
} else if err := app.nav.paste(); err != nil {
app.ui.printf("paste: %s", err)
} else if err := app.nav.paste(app.ui); err != nil {
app.ui.echoerrf("paste: %s", err)
return
}
if err := sendRemote("send load"); err != nil {
app.ui.printf("paste: %s", err)
}
if err := sendRemote("send sync"); err != nil {
app.ui.printf("paste: %s", err)
case "delete":
if cmd, ok := gOpts.cmds["delete"]; ok {
cmd.eval(app, e.args)
app.nav.unselect()
if err := remote("send load"); err != nil {
app.ui.echoerrf("delete: %s", err)
}
} else {
if _, err := app.nav.currFileOrSelections(); err != nil {
app.ui.echoerrf("delete: %s", err)
return
}
app.ui.cmdPrefix = "delete?[y/N]: "
}
case "clear":
if err := saveFiles(nil, false); err != nil {
app.ui.printf("clear: %s", err)
app.ui.echoerrf("clear: %s", err)
return
}
if err := sendRemote("send sync"); err != nil {
app.ui.printf("clear: %s", err)
if err := remote("send sync"); err != nil {
app.ui.echoerrf("clear: %s", err)
}
case "draw":
case "redraw":
@@ -403,7 +648,9 @@ func (e *callExpr) eval(app *app, args []string) {
case "load":
app.nav.renew()
case "reload":
app.nav.reload()
if err := app.nav.reload(); err != nil {
app.ui.echoerrf("reload: %s", err)
}
case "read":
app.ui.cmdPrefix = ":"
case "shell":
@@ -414,65 +661,157 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.cmdPrefix = "!"
case "shell-async":
app.ui.cmdPrefix = "&"
case "find":
app.ui.cmdPrefix = "find: "
app.nav.findBack = false
case "find-back":
app.ui.cmdPrefix = "find-back: "
app.nav.findBack = true
case "find-next":
for i := 0; i < e.count; i++ {
if app.nav.findBack {
app.nav.findPrev()
} else {
app.nav.findNext()
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "find-prev":
for i := 0; i < e.count; i++ {
if app.nav.findBack {
app.nav.findNext()
} else {
app.nav.findPrev()
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "search":
app.ui.cmdPrefix = "/"
last := app.nav.currDir()
app.nav.searchInd = last.ind
app.nav.searchPos = last.pos
app.nav.searchBack = false
case "search-back":
app.ui.cmdPrefix = "?"
last := app.nav.currDir()
app.nav.searchInd = last.ind
app.nav.searchPos = last.pos
app.nav.searchBack = true
case "search-next":
for i := 0; i < e.count; i++ {
if err := app.nav.searchNext(); err != nil {
app.ui.printf("search: %s: %s", err, app.nav.search)
return
if app.nav.searchBack {
if err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
return
}
} else {
if err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search)
return
}
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "search-prev":
for i := 0; i < e.count; i++ {
if err := app.nav.searchPrev(); err != nil {
app.ui.printf("search: %s: %s", err, app.nav.search)
return
if app.nav.searchBack {
if err := app.nav.searchNext(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
return
}
} else {
if err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search: %s: %s", err, app.nav.search)
return
}
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "mark-save":
app.ui.cmdPrefix = "mark-save: "
case "mark-load":
app.ui.menuBuf = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-load: "
case "sync":
if err := app.nav.sync(); err != nil {
app.ui.printf("sync: %s", err)
app.ui.echoerrf("sync: %s", err)
}
case "echo":
app.ui.msg = strings.Join(e.args, " ")
app.ui.echo(strings.Join(e.args, " "))
case "echomsg":
app.ui.echomsg(strings.Join(e.args, " "))
case "echoerr":
app.ui.echoerr(strings.Join(e.args, " "))
case "cd":
path := "~"
if len(e.args) > 0 {
path = e.args[0]
}
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
if err := app.nav.cd(path); err != nil {
app.ui.printf("%s", err)
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
if !filepath.IsAbs(path) {
path = filepath.Join(wd, path)
} else {
path = filepath.Clean(path)
}
if wd != path {
app.nav.marks["'"] = wd
}
case "select":
if len(e.args) != 1 {
app.ui.print("select: requires an argument")
app.ui.echoerr("select: requires an argument")
return
}
if err := app.nav.find(e.args[0]); err != nil {
app.ui.printf("%s", err)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
if err := app.nav.sel(e.args[0]); err != nil {
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
path := filepath.Dir(e.args[0])
if !filepath.IsAbs(path) {
path = filepath.Join(wd, path)
} else {
path = filepath.Clean(path)
}
if wd != path {
app.nav.marks["'"] = wd
}
case "source":
if len(e.args) != 1 {
app.ui.print("source: requires an argument")
app.ui.echoerr("source: requires an argument")
return
}
app.readFile(strings.Replace(e.args[0], "~", gUser.HomeDir, -1))
case "push":
if len(e.args) != 1 {
app.ui.print("push: requires an argument")
app.ui.echoerr("push: requires an argument")
return
}
log.Println("pushing keys", e.args[0])
@@ -483,21 +822,34 @@ func (e *callExpr) eval(app *app, args []string) {
if len(e.args) == 0 {
return
}
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(e.args[0])...)
insert(app, e.args[0])
case "cmd-escape":
if app.ui.cmdPrefix == ">" {
return
}
if gOpts.incsearch && (app.ui.cmdPrefix == "/" || app.ui.cmdPrefix == "?") {
last := app.nav.currDir()
last.ind = app.nav.searchInd
last.pos = app.nav.searchPos
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
case "cmd-complete":
var matches []string
if app.ui.cmdPrefix == ":" {
switch app.ui.cmdPrefix {
case ":":
matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdAccLeft)
} else {
case "/", "?":
matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdAccLeft)
case "$", "%", "!", "&":
matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdAccLeft)
default:
return
}
app.ui.draw(app.nav)
if len(matches) > 1 {
@@ -516,57 +868,67 @@ func (e *callExpr) eval(app *app, args []string) {
switch app.ui.cmdPrefix {
case ":":
log.Printf("command: %s", s)
app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{":", s})
p := newParser(strings.NewReader(s))
for p.parse() {
p.expr.eval(app, nil)
}
if p.err != nil {
app.ui.printf("%s", p.err)
app.ui.echoerrf("%s", p.err)
}
app.cmdHistory = append(app.cmdHistory, cmdItem{app.ui.cmdPrefix, s})
app.ui.cmdPrefix = ""
case "$":
log.Printf("shell: %s", s)
app.runShell(s, nil, app.ui.cmdPrefix)
app.cmdHistory = append(app.cmdHistory, cmdItem{app.ui.cmdPrefix, s})
app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{"$", s})
app.runShell(s, nil, "$")
case "%":
log.Printf("shell-pipe: %s", s)
app.runShell(s, nil, app.ui.cmdPrefix)
app.cmdHistory = append(app.cmdHistory, cmdItem{app.ui.cmdPrefix, s})
app.cmdHistory = append(app.cmdHistory, cmdItem{"%", s})
app.runShell(s, nil, "%")
case ">":
io.WriteString(app.cmdIn, s+"\n")
app.cmdOutBuf = nil
case "!":
log.Printf("shell-wait: %s", s)
app.runShell(s, nil, app.ui.cmdPrefix)
app.cmdHistory = append(app.cmdHistory, cmdItem{app.ui.cmdPrefix, s})
app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{"!", s})
app.runShell(s, nil, "!")
case "&":
log.Printf("shell-async: %s", s)
app.runShell(s, nil, app.ui.cmdPrefix)
app.cmdHistory = append(app.cmdHistory, cmdItem{app.ui.cmdPrefix, s})
app.ui.cmdPrefix = ""
app.cmdHistory = append(app.cmdHistory, cmdItem{"&", s})
app.runShell(s, nil, "&")
case "/":
if gOpts.incsearch {
last := app.nav.currDir()
last.ind = app.nav.searchInd
last.pos = app.nav.searchPos
}
log.Printf("search: %s", s)
app.ui.cmdPrefix = ""
app.nav.search = s
if err := app.nav.searchNext(); err != nil {
app.ui.printf("search: %s: %s", err, app.nav.search)
app.ui.echoerrf("search: %s: %s", err, app.nav.search)
} else {
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
app.ui.cmdPrefix = ""
case "?":
if gOpts.incsearch {
last := app.nav.currDir()
last.ind = app.nav.searchInd
last.pos = app.nav.searchPos
}
log.Printf("search-back: %s", s)
app.ui.cmdPrefix = ""
app.nav.search = s
if err := app.nav.searchPrev(); err != nil {
app.ui.printf("search: %s: %s", err, app.nav.search)
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
} else {
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
app.ui.cmdPrefix = ""
default:
log.Printf("entering unknown execution prefix: %q", app.ui.cmdPrefix)
}
@@ -610,11 +972,13 @@ func (e *callExpr) eval(app *app, args []string) {
return
}
app.ui.cmdAccRight = app.ui.cmdAccRight[1:]
update(app)
case "cmd-delete-back":
if len(app.ui.cmdAccLeft) == 0 {
return
}
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1]
update(app)
case "cmd-left":
if len(app.ui.cmdAccLeft) == 0 {
return
@@ -639,23 +1003,28 @@ func (e *callExpr) eval(app *app, args []string) {
}
app.ui.cmdYankBuf = app.ui.cmdAccLeft
app.ui.cmdAccLeft = nil
update(app)
case "cmd-delete-end":
if len(app.ui.cmdAccRight) == 0 {
return
}
app.ui.cmdYankBuf = app.ui.cmdAccRight
app.ui.cmdAccRight = nil
update(app)
case "cmd-delete-unix-word":
ind := strings.LastIndex(strings.TrimRight(string(app.ui.cmdAccLeft), " "), " ") + 1
app.ui.cmdYankBuf = app.ui.cmdAccLeft[ind:]
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind]
update(app)
case "cmd-yank":
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdYankBuf...)
update(app)
case "cmd-transpose":
if len(app.ui.cmdAccLeft) < 2 {
return
}
app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1], app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-2] = app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-2], app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1]
update(app)
case "cmd-interrupt":
if app.cmd != nil {
app.cmd.Process.Kill()
@@ -706,6 +1075,7 @@ func (e *callExpr) eval(app *app, args []string) {
ind = loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
update(app)
case "cmd-delete-word":
if len(app.ui.cmdAccRight) == 0 {
return
@@ -716,6 +1086,7 @@ func (e *callExpr) eval(app *app, args []string) {
}
ind := loc[0] + 1
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
update(app)
case "cmd-uppercase-word":
if len(app.ui.cmdAccRight) == 0 {
return
@@ -727,6 +1098,7 @@ func (e *callExpr) eval(app *app, args []string) {
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToUpper(string(app.ui.cmdAccRight[:ind])))...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
update(app)
case "cmd-lowercase-word":
if len(app.ui.cmdAccRight) == 0 {
return
@@ -738,6 +1110,7 @@ func (e *callExpr) eval(app *app, args []string) {
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToLower(string(app.ui.cmdAccRight[:ind])))...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
update(app)
case "cmd-transpose-word":
if len(app.ui.cmdAccLeft) == 0 {
return
@@ -771,10 +1144,11 @@ func (e *callExpr) eval(app *app, args []string) {
acc = append(acc, app.ui.cmdAccLeft[end2:]...)
app.ui.cmdAccLeft = acc
update(app)
default:
cmd, ok := gOpts.cmds[e.name]
if !ok {
app.ui.printf("command not found: %s", e.name)
app.ui.echoerrf("command not found: %s", e.name)
return
}
cmd.eval(app, e.args)
+7 -7
View File
@@ -8,12 +8,12 @@
tmp=gen/docstring.go
echo "// DO NOT EDIT! (AUTO-GENERATED)" >> $tmp
echo >> $tmp
echo "package main" >> $tmp
echo >> $tmp
echo "var genDocString = \`" >> $tmp
go doc | tr "\`" "'" >> $tmp
echo "\`" >> $tmp
echo "// Code generated by gen/docstring.sh DO NOT EDIT." >> $tmp
echo >> $tmp
echo "package main" >> $tmp
echo >> $tmp
echo "var genDocString = \`" >> $tmp
go doc | tr "\`" "'" >> $tmp
echo "\`" >> $tmp
mv $tmp docstring.go
Executable
+69
View File
@@ -0,0 +1,69 @@
#!/bin/sh
# Generates `lf.1` man page using man macros with `go doc` output.
#
# This script is called in `doc.go` using `go generate` to generate a man page
# formatted with man macros from the documentation. A few additional sections
# such as `NAME` and `SYNOPSIS` are added to comply with man page conventions.
#
# Conversion logic implemented here from godoc output to man macros should not
# be considered compliant, as such it has inexact assumptions such as the use
# of spaces over tabs along with various corner cases that are not handled
# properly like character escaping. The intention here is to come up with
# something that can convert the current content in the documentation. For this
# reason, it is recommended to check the output after generation especially
# when the documentation is changed in a significant way.
out=lf.1
echo '.\" Code generated by gen/man.sh DO NOT EDIT.' > $out
cat << END >> $out
.TH LF 1
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
.SY lf
.OP \-cpuprofile path
.OP \-doc
.OP \-last-dir-path path
.OP \-memprofile path
.OP \-remote command
.OP \-selection-path path
.OP \-server
.OP \-version
.RI [ directory ]
.YS
.SH DESCRIPTION
END
go doc | awk '
BEGIN {
RS = ""
start = 1
}
# preformatted
/^ / {
gsub("\\\\", "\\e", $0)
print ".PP"
print ".EX"
print $0
print ".EE"
next
}
# heading
/^[^[:punct:]]*$/ {
print ".SH", toupper($0)
start = 1
next
}
# paragraph
{
gsub("\n", " ", $0)
gsub("\\\\", "\\e", $0)
if (start) { start = 0 } else { print ".PP" }
print $0
}
' >> $out
+8
View File
@@ -0,0 +1,8 @@
module github.com/gokcehan/lf
go 1.12
require (
github.com/mattn/go-runewidth v0.0.4
github.com/nsf/termbox-go v0.0.0-20190325093121-288510b9734e
)
+8
View File
@@ -0,0 +1,8 @@
github.com/mattn/go-runewidth v0.0.3 h1:a+kO+98RDGEfo6asOGMmpodZq4FNtnGP54yps8BzLR4=
github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/nsf/termbox-go v0.0.0-20180613055208-5c94acc5e6eb h1:YahEjAGkJtCrkqgVHhX6n8ZX+CZ3hDRL9fjLYugLfSs=
github.com/nsf/termbox-go v0.0.0-20180613055208-5c94acc5e6eb/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ=
github.com/nsf/termbox-go v0.0.0-20190325093121-288510b9734e h1:Vbib8wJAaMEF9jusI/kMSYMr/LtRzM7+F9MJgt/nH8k=
github.com/nsf/termbox-go v0.0.0-20190325093121-288510b9734e/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ=
+638
View File
@@ -0,0 +1,638 @@
.\" Code generated by gen/man.sh DO NOT EDIT.
.TH LF 1
.SH NAME
lf \- terminal file manager
.SH SYNOPSIS
.SY lf
.OP \-cpuprofile path
.OP \-doc
.OP \-last-dir-path path
.OP \-memprofile path
.OP \-remote command
.OP \-selection-path path
.OP \-server
.OP \-version
.RI [ directory ]
.YS
.SH DESCRIPTION
lf is a terminal file manager.
.PP
Source code can be found in the repository at https://github.com/gokcehan/lf.
.PP
This documentation can either be read from terminal using 'lf -doc' or online at https://godoc.org/github.com/gokcehan/lf. You can also use 'doc' command (default '<f-1>') inside lf to view the documentation in a pager.
.PP
You can run 'lf -help' to see descriptions of command line options.
.SH REFERENCE
The following commands are provided by lf with default keybindings:
.PP
.EX
up (default 'k' and '<up>')
half-up (default '<c-u>')
page-up (default '<c-b>' and '<pgup>')
down (default 'j' and '<down>')
half-down (default '<c-d>')
page-down (default '<c-f>' and '<pgdn>')
updir (default 'h' and '<left>')
open (default 'l' and '<right>')
quit (default 'q')
top (default 'gg' and '<home>')
bottom (default 'G' and '<end>')
toggle (default '<space>')
invert (default 'v')
unselect (default 'u')
copy (default 'y')
cut (default 'd')
paste (default 'p')
clear (default 'c')
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
shell-async (default '&')
find (default 'f')
find-back (default 'F')
find-next (default ';')
find-prev (default ',')
search (default '/')
search-back (default '?')
search-next (default 'n')
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
.EE
.PP
The following commands are provided by lf without default keybindings:
.PP
.EX
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
.EE
.PP
The following command line commands are provided by lf with default keybindings:
.PP
.EX
cmd-escape (default '<esc>')
cmd-complete (default '<tab>')
cmd-enter (default '<c-j>' and '<enter>')
cmd-history-next (default '<c-n>')
cmd-history-prev (default '<c-p>')
cmd-delete (default '<c-d>' and '<delete>')
cmd-delete-back (default '<bs>' and '<bs2>')
cmd-left (default '<c-b>' and '<left>')
cmd-right (default '<c-f>' and '<right>')
cmd-home (default '<c-a>' and '<home>')
cmd-end (default '<c-e>' and '<end>')
cmd-delete-home (default '<c-u>')
cmd-delete-end (default '<c-k>')
cmd-delete-unix-word (default '<c-w>')
cmd-yank (default '<c-y>')
cmd-transpose (default '<c-t>')
cmd-interrupt (default '<c-c>')
cmd-word (default '<a-f>')
cmd-word-back (default '<a-b>')
cmd-capitalize-word (default '<a-c>')
cmd-delete-word (default '<a-d>')
cmd-uppercase-word (default '<a-u>')
cmd-lowercase-word (default '<a-l>')
cmd-transpose-word (default '<a-t>')
.EE
.PP
The following options can be used to customize the behavior of lf:
.PP
.EX
anchorfind boolean (default on)
color256 boolean (default off)
dircounts boolean (default off)
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
incsearch boolean (default off)
preview boolean (default on)
reverse boolean (default off)
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
number boolean (default off)
relativenumber boolean (default off)
findlen integer (default 1) (zero to prompt until single match)
period integer (default 0) (zero to disable periodic loading)
scrolloff integer (default 0)
tabstop integer (default 8)
errorfmt string (default "\e033[7;31;47m%s\e033[0m")
filesep string (default "\en")
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
.PP
The following variables are exported for shell commands:
.PP
.EX
$f current file
$fs selected file(s) separated with 'filesep'
$fx current file or selected file(s) if any
$id id number of the client
.EE
.PP
The following variables are set to the corresponding values:
.PP
.EX
$LF_LEVEL current nesting level
.EE
.PP
The following default values are set to the environmental variables on unix when they are not set or empty:
.PP
.EX
$OPENER open # macos
$OPENER xdg-open # others
$EDITOR vi
$PAGER less
$SHELL sh
.EE
.PP
The following default values are set to the environmental variables on windows when they are not set or empty:
.PP
.EX
%OPENER% start
%EDITOR% notepad
%PAGER% more
%SHELL% cmd
.EE
.PP
The following additional keybindings are provided by default:
.PP
.EX
map zh set hidden!
map zr set reverse!
map zn set info
map zs set info size
map zt set info time
map za set info size:time
map sn :set sortby natural; set info
map ss :set sortby size; set info size
map st :set sortby time; set info time
map gh cd ~
.EE
.PP
The following keybindings to applications are provided by default:
.PP
.EX
map e $$EDITOR $f
map i $$PAGER $f
map w $$SHELL
.EE
.SH CONFIGURATION
Configuration files should be located at:
.PP
.EX
os system-wide user-specific
unix /etc/lf/lfrc ~/.config/lf/lfrc
windows C:\eProgramData\elf\elfrc C:\eUsers\e<user>\eAppData\eLocal\elf\elfrc
.EE
.PP
Marks file should be located at:
.PP
.EX
unix ~/.local/share/lf/marks
windows C:\eUsers\e<user>\eAppData\eLocal\elf\emarks
.EE
.PP
History file should be located at:
.PP
.EX
unix ~/.local/share/lf/history
windows C:\eUsers\e<user>\eAppData\eLocal\elf\ehistory
.EE
.PP
You can configure the default values of following variables to change these locations:
.PP
.EX
$XDG_CONFIG_HOME ~/.config
$XDG_DATA_HOME ~/.local/share
%ProgramData% C:\eProgramData
%LOCALAPPDATA% C:\eUsers\e<user>\eAppData\eLocal
.EE
.PP
A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example.
.SH PREFIXES
The following command prefixes are used by lf:
.PP
.EX
: read (default) builtin/custom command
$ shell shell command
% shell-pipe shell command running with the ui
! shell-wait shell command waiting for key press
& shell-async shell command running asynchronously
/ search search file in current directory
? search-back search file in the reverse order
.EE
.PP
The same evaluator is used for the command line and the configuration file for read and shell commands. The difference is that prefixes are not necessary in the command line. Instead, different modes are provided to read corresponding commands. These modes are mapped to the prefix keys above by default. Searching commands are only used from the command line.
.SH SYNTAX
Characters from '#' to newline are comments and ignored:
.PP
.EX
# comments start with '#'
.EE
.PP
There are three special commands ('set', 'map', and 'cmd') and their variants for configuration.
.PP
Command 'set' is used to set an option which can be boolean, integer, or string:
.PP
.EX
set hidden # boolean on
set nohidden # boolean off
set hidden! # boolean toggle
set scrolloff 10 # integer value
set sortby time # string value w/o quotes
set sortby 'time' # string value with single quotes (whitespaces)
set sortby "time" # string value with double quotes (backslash escapes)
.EE
.PP
Command 'map' is used to bind a key to a command which can be builtin command, custom command, or shell command:
.PP
.EX
map gh cd ~ # builtin command
map D trash # custom command
map i $less $f # shell command
map U !du -sh # waiting shell command
.EE
.PP
Command 'cmap' is used to bind a key to a command line command which can only be one of the builtin commands:
.PP
.EX
cmap <c-g> cmd-escape
.EE
.PP
You can delete an existing binding by leaving the expression empty:
.PP
.EX
map gh # deletes 'gh' mapping
cmap <c-g> # deletes '<c-g>' mapping
.EE
.PP
Command 'cmd' is used to define a custom command:
.PP
.EX
cmd usage $du -h -d1 | less
.EE
.PP
You can delete an existing command by leaving the expression empty:
.PP
.EX
cmd trash # deletes 'trash' command
.EE
.PP
If there is no prefix then ':' is assumed:
.PP
.EX
map zt set info time
.EE
.PP
An explicit ':' can be provided to group statements until a newline which is especially useful for 'map' and 'cmd' commands:
.PP
.EX
map st :set sortby time; set info time
.EE
.PP
If you need multiline you can wrap statements in '{{' and '}}' after the proper prefix.
.PP
.EX
map st :{{
set sortby time
set info time
}}
.EE
.SH KEY MAPPINGS
Regular keys are assigned to a command with the usual syntax:
.PP
.EX
map a down
.EE
.PP
Keys combined with the shift key simply use the uppercase letter:
.PP
.EX
map A down
.EE
.PP
Special keys are written in between '<' and '>' characters and always use lowercase letters:
.PP
.EX
map <enter> down
.EE
.PP
Angle brackets can be assigned with their special names:
.PP
.EX
map <lt> down
map <gt> down
.EE
.PP
Function keys are prefixed with 'f' character:
.PP
.EX
map <f-1> down
.EE
.PP
Keys combined with the control key are prefixed with 'c' character:
.PP
.EX
map <c-a> down
.EE
.PP
Keys combined with the alt key are assigned in two different ways depending on the behavior of your terminal. Older terminals (e.g. xterm) may set the 8th bit of a character when the alt key is pressed. On these terminals, you can use the corresponding byte for the mapping:
.PP
.EX
map á down
.EE
.PP
Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key when the alt key is pressed. lf uses the escape delaying mechanism to recognize alt keys in these terminals (delay is 100ms). On these terminals, keys combined with the alt key are prefixed with 'a' character:
.PP
.EX
map <a-a> down
.EE
.PP
Please note that, some key combinations are not possible due to the way terminals work (e.g. control and h combination sends a backspace key instead). The easiest way to find the name of a key combination is to press the key while lf is running and read the name of the key from the unknown mapping error.
.SH PUSH MAPPINGS
The usual way to map a key sequence is to assign it to a named or unnamed command. While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times. For this reason 'push' command is provided by lf. This command is used to simulate key pushes given as its arguments. You can 'map' a key to a 'push' command with an argument to create various keybindings.
.PP
This is mainly useful for two purposes. First, it can be used to map a command with a command count:
.PP
.EX
map <c-j> push 10j
.EE
.PP
Second, it can be used to avoid typing the name when a command takes arguments:
.PP
.EX
map r push :rename<space>
.EE
.PP
One thing to be careful is that since 'push' command works with keys instead of commands it is possible to accidentally create recursive bindings:
.PP
.EX
map j push 2j
.EE
.PP
These types of bindings create a deadlock when executed.
.SH SHELL COMMANDS
Regular shell commands are the most basic command type that is useful for many purposes. For example, we can write a shell command to move selected file(s) to trash. A first attempt to write such a command may look like this:
.PP
.EX
cmd trash ${{
mkdir -p ~/.trash
if [ -z "$fs" ]; then
mv "$f" ~/.trash
else
IFS="`printf '\en\et'`"; mv $fs ~/.trash
fi
}}
.EE
.PP
We check '$fs' to see if there are any selected files. Otherwise we just delete the current file. Since this is such a common pattern, a separate '$fx' variable is provided. We can use this variable to get rid of the conditional:
.PP
.EX
cmd trash ${{
mkdir -p ~/.trash
IFS="`printf '\en\et'`"; mv $fx ~/.trash
}}
.EE
.PP
The trash directory is checked each time the command is executed. We can move it outside of the command so it would only run once at startup:
.PP
.EX
${{ mkdir -p ~/.trash }}
.EE
.PP
.EX
cmd trash ${{ IFS="`printf '\en\et'`"; mv $fx ~/.trash }}
.EE
.PP
Since these are one liners, we can drop '{{' and '}}':
.PP
.EX
$mkdir -p ~/.trash
.EE
.PP
.EX
cmd trash $IFS="`printf '\en\et'`"; mv $fx ~/.trash
.EE
.PP
Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\en"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation.
.SH PIPING SHELL COMMANDS
Regular shell commands have some limitations in some cases. When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again. Also, even when there is no output or error, the ui still needs to be paused while the command is running. This can cause flickering on the screen for short commands and similar distractions for longer commands.
.PP
Instead of pausing the ui, piping shell commands connects stdin, stdout, and stderr of the command to the statline in the bottom of the ui. This can be useful for programs following the unix philosophy to give no output in the success case, and brief error messages or prompts in other cases.
.PP
For example, following rename command prompts for overwrite in the statline if there is an existing file with the given name:
.PP
.EX
cmd rename %mv -i $f $1
.EE
.PP
You can also output error messages in the command and it will show up in the statline. For example, an alternative rename command may look like this:
.PP
.EX
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
.EE
.PP
One thing to be careful is that although input is still line buffered, output and error are byte buffered and verbose commands will be very slow to display.
.SH WAITING SHELL COMMANDS
Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished. These can be useful to see the output of a program before the ui is resumed. Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline.
.SH ASYNCHRONOUS SHELL COMMANDS
Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish. Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui.
.SH REMOTE COMMANDS
One of the more advanced features in lf is remote commands. All clients connect to a server on startup. It is possible to send commands to all or any of the connected clients over the common server. This is used internally to notify file selection changes to other clients.
.PP
To use this feature, you need to use a client which supports communicating with a UNIX-domain socket. OpenBSD implementation of netcat (nc) is one such example. You can use it to send a command to the socket file:
.PP
.EX
echo 'send echo hello world' | nc -U /tmp/lf.${USER}.sock
.EE
.PP
Since such a client may not be available everywhere, lf comes bundled with a command line flag to be used as such. When using lf, you do not need to specify the address of the socket file. This is the recommended way of using remote commands since it is shorter and immune to socket file address changes:
.PP
.EX
lf -remote 'send echo hello world'
.EE
.PP
In this command 'send' is used to send the rest of the string as a command to all connected clients. You can optionally give it an id number to send a command to a single client:
.PP
.EX
lf -remote 'send 1000 echo hello world'
.EE
.PP
All clients have a unique id number but you may not be aware of the id number when you are writing a command. For this purpose, an '$id' variable is exported to the environment for shell commands. You can use it to send a remote command from a client to the server which in return sends a command back to itself. So now you can display a message in the current client by calling the following in a shell command:
.PP
.EX
lf -remote "send $id echo hello world"
.EE
.PP
Since lf does not have control flow syntax, remote commands are used for such needs. For example, you can configure the number of columns in the ui with respect to the terminal width as follows:
.PP
.EX
cmd recol %{{
w=$(tput cols)
if [ $w -le 80 ]; then
lf -remote "send $id set ratios 1:2"
elif [ $w -le 160 ]; then
lf -remote "send $id set ratios 1:2:3"
else
lf -remote "send $id set ratios 1:2:3:5"
fi
}}
.EE
.PP
Besides 'send' command, there are also two commands to get or set the current file selection. Two possible modes 'copy' and 'move' specify whether selected files are to be copied or moved. File names are separated by newline character. Setting the file selection is done with 'save' command:
.PP
.EX
lf -remote "$(printf 'save\encopy\enfoo.txt\enbar.txt\enbaz.txt\en')"
.EE
.PP
Getting the file selection is similarly done with 'load' command:
.PP
.EX
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
# do something with $list
elif [ $mode = 'move' ]; then
# do something else with $list
fi
.EE
.PP
There is a 'quit' command to close client connections and quit the server:
.PP
.EX
lf -remote 'quit'
.EE
.PP
Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users.
.SH FILE OPERATIONS
lf uses its own builtin copy and move operations by default. These are implemented as asynchronous operations and progress is shown in the bottom ruler. These commands do not overwrite existing files or directories with the same name. Instead, a suffix that is compatible with '--backup=numbered' option in GNU cp is added to the new files or directories. Only file modes are preserved and all other attributes are ignored including ownership, timestamps, context, links, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are followed. Moving is performed using the rename operation of the underlying OS. 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
File operations can be performed on the current selected file or alternatively on multiple files by selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to memory. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file.
.PP
You can customize copy and move operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. You can use the following example as a starting point:
.PP
.EX
cmd paste %{{
load=$(lf -remote 'load')
mode=$(echo "$load" | sed -n '1p')
list=$(echo "$load" | sed '1d')
if [ $mode = 'copy' ]; then
cp -R $list .
elif [ $mode = 'move' ]; then
mv $list .
fi
lf -remote 'send load'
lf -remote 'send clear'
}}
.EE
.PP
Some useful things to be considered are to use the backup ('--backup') and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls.
.PP
By default, lf does not assign 'delete' command to a key to protect new users. You can customize file deletion by defining a 'delete' command. You can also assign a key to this command if you like. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file.
.SH SEARCHING FILES
There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes.
.PP
Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search.
.PP
Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial.
.PP
Some options effect both searching and finding. You can disable 'wrapscan' option to prevent searches to wrap around at the end of the file list. You can disable 'ignorecase' option to match cases in the pattern and the filename. This option is already automatically overridden if the pattern contains upper case characters. You can disable 'smartcase' option to disable this behavior. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters.
.SH OPENING FILES
You can define a an 'open' command (default 'l' and '<right>') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command:
.PP
.EX
cmd open $vi $fx
.EE
.PP
It is possible to use different command types:
.PP
.EX
cmd open &xdg-open $f
.EE
.PP
You may want to use either file extensions or mime types from 'file' command:
.PP
.EX
cmd open ${{
case $(file --mime-type $f -b) in
text/*) vi $fx;;
*) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;;
esac
}}
.EE
.PP
Following command is provided by default:
.PP
.EX
cmd open &$OPENER $f
.EE
.PP
You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few.
.SH PREVIEWING FILES
lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files as text to name few. For coloring lf recognizes ansi escape codes.
.PP
In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. lf passes the current file name as the first argument and the height of the preview pane as the second argument when running this file. Output of the execution is printed in the preview pane. You may want to use the same script in your pager mapping as well if any:
.PP
.EX
set previewer ~/.config/lf/pv.sh
map i $~/.config/lf/pv.sh $f | less -R
.EE
.PP
Since this script is called for each file selection change it needs to be as efficient as possible and this responsibility is left to the user. You may use file extensions to determine the type of file more efficiently compared to obtaining mime types from 'file' command. Extensions can then be used to match cleanly within a conditional:
.PP
.EX
#!/bin/sh
.EE
.PP
.EX
case "$1" in
*.tar*) tar tf "$1";;
*.zip) unzip -l "$1";;
*.rar) unrar l "$1";;
*.7z) 7z l "$1";;
*.pdf) pdftotext "$1" -;;
*) highlight -O ansi "$1" || cat "$1";;
esac
.EE
.PP
Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview.
.SH COLORSCHEMES
lf tries to automatically adapt its colors to the environment. On startup, first '$LS_COLORS' environment variable is checked. This variable is used by GNU ls to configure its colors based on file types and extensions. The value of this variable is often set by GNU dircolors in a shell configuration file. dircolors program itself can be configured with a configuration file. dircolors supports 256 colors along with common attributes such as bold and underline.
.PP
If '$LS_COLORS' variable is not set, '$LSCOLORS' variable is checked instead. This variable is used by ls programs on unix systems such as Mac and BSDs. This variable has a simple syntax and supports 8 colors and bold attribute.
.PP
If both of these environment variables are not set, then lf fallbacks to its default colorscheme. Default lf colors are taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute.
.PP
You should also note that lf uses 8 color mode by default which uses sgr 3-bit color escapes (e.g. '\e033[34m'). If you want to use 256 colors, you need to enable 'color256' option which then makes lf use sgr 8-bit color escapes (e.g. '\e033[38;5;4m'). This option is intended to eliminate differences between default colors used by ls and lf since terminals may render 3-bit and 8-bit escapes differently even for the same color.
.PP
Keeping this mechanism in mind, you can configure lf colors in two different ways. First, you can configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other.
.PP
Second, you can set the values of environmental variables mentioned above for fine grained customization. This is useful to change colors used for different file types and extensions. '$LS_COLORS' is more powerful than '$LSCOLORS' and it can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results.
.PP
Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line.
+50 -17
View File
@@ -6,14 +6,15 @@ import (
"log"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
)
var (
envPath = os.Getenv("PATH")
envPath = os.Getenv("PATH")
envLevel = os.Getenv("LF_LEVEL")
)
var (
@@ -25,6 +26,8 @@ var (
gSocketPath string
gLogPath string
gServerLogPath string
gSelect string
gCommand string
gVersion string
)
@@ -34,10 +37,32 @@ func init() {
log.Printf("hostname: %s", err)
}
gHostname = h
if envLevel == "" {
envLevel = "0"
}
}
func exportEnvVars() {
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
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() {
cmd := exec.Command(os.Args[0], "-server")
cmd := detachedCommand(os.Args[0], "-server")
if err := cmd.Start(); err != nil {
log.Printf("starting server: %s", err)
}
@@ -99,6 +124,11 @@ func main() {
"",
"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()
gSocketProt = gDefaultSocketProt
@@ -115,26 +145,13 @@ func main() {
defer pprof.StopCPUProfile()
}
switch flag.NArg() {
case 0:
case 1:
dir := flag.Arg(0)
if err := os.Chdir(dir); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
default:
fmt.Fprintf(os.Stderr, "only single directory is allowed\n")
os.Exit(2)
}
switch {
case *showDoc:
fmt.Print(genDocString)
case *showVersion:
fmt.Println(gVersion)
case *remoteCmd != "":
if err := sendRemote(*remoteCmd); err != nil {
if err := remote(*remoteCmd); err != nil {
log.Fatalf("remote command: %s", err)
}
case *serverMode:
@@ -150,6 +167,22 @@ func main() {
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()
}
+4 -5
View File
@@ -133,11 +133,10 @@ func splitWord(s string) (word, rest string) {
return
}
// This function converts a size in bytes to a human readable form. For this
// purpose metric suffixes are used (e.g. 1K = 1000). For values less than 10
// the first significant digit is shown, otherwise it is hidden. Numbers are
// always rounded down. For these reasons this function always show somewhat
// smaller values but it should be fine for most human beings.
// This function converts a size in bytes to a human readable form using metric
// suffixes (e.g. 1K = 1000). For values less than 10 the first significant
// digit is shown, otherwise it is hidden. Numbers are always rounded down.
// This should be fine for most human beings.
func humanize(size int64) string {
if size < 1000 {
return fmt.Sprintf("%dB", size)
+389 -91
View File
@@ -144,13 +144,13 @@ func (dir *dir) sort() {
// files to the first non-hidden file in the list
if gOpts.sortType.option&hiddenSort == 0 {
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 dir.files[i].Name()[0] == '.'
return isHidden(dir.files[i])
})
for i, f := range dir.files {
if f.Name()[0] != '.' {
if !isHidden(f) {
dir.files = dir.files[i:]
return
}
@@ -166,7 +166,7 @@ func (dir *dir) name() string {
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 {
dir.ind, dir.pos = 0, 0
return
@@ -188,16 +188,32 @@ func (dir *dir) find(name string, height int) {
}
type nav struct {
dirs []*dir
dirChan chan *dir
regChan chan *reg
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
marks map[string]int
markInd int
height int
search string
dirs []*dir
copyBytes int64
copyTotal int64
copyUpdate int
moveCount int
moveTotal int
moveUpdate int
copyBytesChan chan int64
copyTotalChan chan int64
moveCountChan chan int
moveTotalChan chan int
dirChan chan *dir
regChan chan *reg
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
marks map[string]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 {
@@ -225,7 +241,7 @@ func (nav *nav) loadDir(path string) *dir {
d.loadTime = time.Now()
nd := newDir(path)
nd.sort()
nd.find(d.name(), nav.height)
nd.sel(d.name(), nav.height)
nav.dirChan <- nd
}()
case d.sortType != gOpts.sortType:
@@ -233,7 +249,7 @@ func (nav *nav) loadDir(path string) *dir {
d.loading = true
name := d.name()
d.sort()
d.find(name, nav.height)
d.sel(name, nav.height)
d.loading = false
nav.dirChan <- d
}()
@@ -247,7 +263,7 @@ func (nav *nav) getDirs(wd string) {
for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) {
dir := nav.loadDir(curr)
dir.find(base, nav.height)
dir.sel(base, nav.height)
dirs = append(dirs, dir)
}
@@ -265,14 +281,19 @@ func newNav(height int) *nav {
}
nav := &nav{
dirChan: make(chan *dir),
regChan: make(chan *reg),
dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
marks: make(map[string]int),
markInd: 0,
height: height,
copyBytesChan: make(chan int64, 1024),
copyTotalChan: make(chan int64, 1024),
moveCountChan: make(chan int, 1024),
moveTotalChan: make(chan int, 1024),
dirChan: make(chan *dir),
regChan: make(chan *reg),
dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
marks: make(map[string]string),
selections: make(map[string]int),
selectionInd: 0,
height: height,
}
nav.getDirs(wd)
@@ -286,6 +307,7 @@ func (nav *nav) renew() {
s, err := os.Stat(d.path)
if err != nil {
log.Printf("getting directory info: %s", err)
return
}
if d.loadTime.After(s.ModTime()) {
return
@@ -297,23 +319,23 @@ func (nav *nav) renew() {
}(d)
}
for m := range nav.marks {
for m := range nav.selections {
if _, err := os.Stat(m); os.IsNotExist(err) {
delete(nav.marks, m)
delete(nav.selections, m)
}
}
if len(nav.marks) == 0 {
nav.markInd = 0
if len(nav.selections) == 0 {
nav.selectionInd = 0
}
}
func (nav *nav) reload() {
func (nav *nav) reload() error {
nav.dirCache = make(map[string]*dir)
nav.regCache = make(map[string]*reg)
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
return fmt.Errorf("getting current directory: %s", err)
}
curr, err := nav.currFile()
@@ -322,12 +344,14 @@ func (nav *nav) reload() {
last := nav.dirs[len(nav.dirs)-1]
last.files = append(last.files, curr)
}
return nil
}
func (nav *nav) position() {
path := nav.currDir().path
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)
}
}
@@ -372,7 +396,7 @@ func (nav *nav) preview() {
for i := 0; i < nav.height && buf.Scan(); i++ {
for _, r := range buf.Text() {
if r == 0 {
reg.lines = []string{"\033[1mbinary\033[0m"}
reg.lines = []string{"\033[7mbinary\033[0m"}
nav.regChan <- reg
return
}
@@ -413,7 +437,7 @@ func (nav *nav) sort() {
for _, d := range nav.dirs {
name := d.name()
d.sort()
d.find(name, nav.height)
d.sel(name, nav.height)
}
}
@@ -504,15 +528,15 @@ func (nav *nav) bottom() {
dir.pos = min(dir.ind, nav.height-1)
}
func (nav *nav) toggleMark(path string) {
if _, ok := nav.marks[path]; ok {
delete(nav.marks, path)
if len(nav.marks) == 0 {
nav.markInd = 0
func (nav *nav) toggleSelection(path string) {
if _, ok := nav.selections[path]; ok {
delete(nav.selections, path)
if len(nav.selections) == 0 {
nav.selectionInd = 0
}
} else {
nav.marks[path] = nav.markInd
nav.markInd = nav.markInd + 1
nav.selections[path] = nav.selectionInd
nav.selectionInd++
}
}
@@ -522,7 +546,7 @@ func (nav *nav) toggle() {
return
}
nav.toggleMark(curr.path)
nav.toggleSelection(curr.path)
nav.down(1)
}
@@ -531,66 +555,178 @@ func (nav *nav) invert() {
last := nav.currDir()
for _, f := range last.files {
path := filepath.Join(last.path, f.Name())
nav.toggleMark(path)
nav.toggleSelection(path)
}
}
func (nav *nav) unmark() {
nav.marks = make(map[string]int)
nav.markInd = 0
func (nav *nav) unselect() {
nav.selections = make(map[string]int)
nav.selectionInd = 0
}
func (nav *nav) save(cp bool) error {
if len(nav.marks) == 0 {
curr, err := nav.currFile()
if err != nil {
return errors.New("no file selected")
}
list, err := nav.currFileOrSelections()
if err != nil {
return err
}
if err := saveFiles([]string{curr.path}, cp); err != nil {
return err
}
if err := saveFiles(list, cp); err != nil {
return err
}
nav.saves = make(map[string]bool)
nav.saves[curr.path] = cp
} else {
marks := nav.currMarks()
if err := saveFiles(marks, cp); err != nil {
return err
}
nav.saves = make(map[string]bool)
for f := range nav.marks {
nav.saves[f] = cp
}
nav.saves = make(map[string]bool)
for _, f := range list {
nav.saves[f] = cp
}
return nil
}
func (nav *nav) paste() error {
list, cp, err := loadFiles()
func (nav *nav) copyAsync(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
}
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 {
return err
}
if len(list) == 0 {
if len(srcs) == 0 {
return errors.New("no file in copy/cut buffer")
}
dir := nav.currDir()
dstDir := nav.currDir().path
cmd := pasteCommand(list, dir, cp)
if err := cmd.Run(); err != nil {
return fmt.Errorf("pasting files: %s", err)
if cp {
go nav.copyAsync(ui, srcs, dstDir)
} else {
go nav.moveAsync(ui, srcs, dstDir)
}
if err := saveFiles(nil, false); err != nil {
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() error {
list, err := nav.currFileOrSelections()
if err != nil {
return err
}
for _, path := range list {
if err := os.RemoveAll(path); err != nil {
return err
}
}
return nil
}
@@ -625,7 +761,7 @@ func (nav *nav) cd(wd string) error {
return nil
}
func (nav *nav) find(path string) error {
func (nav *nav) sel(path string) error {
lstat, err := os.Stat(path)
if err != nil {
return fmt.Errorf("select: %s", err)
@@ -643,13 +779,13 @@ func (nav *nav) find(path string) error {
if last.loading {
last.files = append(last.files, &file{FileInfo: lstat})
} else {
last.find(base, nav.height)
last.sel(base, nav.height)
}
return nil
}
func match(pattern, name string) (matched bool, err error) {
func findMatch(name, pattern string) bool {
if gOpts.ignorecase {
lpattern := strings.ToLower(pattern)
if !gOpts.smartcase || lpattern == pattern {
@@ -657,6 +793,95 @@ func match(pattern, name string) (matched bool, err error) {
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 {
return filepath.Match(pattern, name)
}
@@ -666,7 +891,7 @@ func match(pattern, name string) (matched bool, err error) {
func (nav *nav) searchNext() error {
last := nav.currDir()
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 {
return err
}
@@ -677,7 +902,7 @@ func (nav *nav) searchNext() error {
}
if gOpts.wrapscan {
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 {
return err
}
@@ -693,7 +918,7 @@ func (nav *nav) searchNext() error {
func (nav *nav) searchPrev() error {
last := nav.currDir()
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 {
return err
}
@@ -704,7 +929,7 @@ func (nav *nav) searchPrev() error {
}
if gOpts.wrapscan {
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 {
return err
}
@@ -717,6 +942,66 @@ func (nav *nav) searchPrev() error {
return nil
}
func (nav *nav) readMarks() error {
f, err := os.Open(gMarksPath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("opening marks file: %s", err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
toks := strings.SplitN(scanner.Text(), ":", 2)
if _, ok := nav.marks[toks[0]]; !ok {
nav.marks[toks[0]] = toks[1]
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading marks file: %s", err)
}
return nil
}
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 {
return fmt.Errorf("creating data directory: %s", err)
}
f, err := os.Create(gMarksPath)
if err != nil {
return fmt.Errorf("creating marks file: %s", err)
}
defer f.Close()
var keys []string
for k := range nav.marks {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
_, err = f.WriteString(fmt.Sprintf("%s:%s\n", k, nav.marks[k]))
if err != nil {
return fmt.Errorf("writing marks file: %s", err)
}
}
return nil
}
func (nav *nav) currDir() *dir {
return nav.dirs[len(nav.dirs)-1]
}
@@ -730,27 +1015,40 @@ func (nav *nav) currFile() (*file, error) {
return last.files[last.ind], nil
}
type indexedMarks struct {
type indexedSelections struct {
paths []string
indices []int
}
func (m indexedMarks) Len() int { return len(m.paths) }
func (m indexedSelections) Len() int { return len(m.paths) }
func (m indexedMarks) Swap(i, j int) {
func (m indexedSelections) Swap(i, j int) {
m.paths[i], m.paths[j] = m.paths[j], m.paths[i]
m.indices[i], m.indices[j] = m.indices[j], m.indices[i]
}
func (m indexedMarks) Less(i, j int) bool { return m.indices[i] < m.indices[j] }
func (m indexedSelections) Less(i, j int) bool { return m.indices[i] < m.indices[j] }
func (nav *nav) currMarks() []string {
paths := make([]string, 0, len(nav.marks))
indices := make([]int, 0, len(nav.marks))
for path, index := range nav.marks {
func (nav *nav) currSelections() []string {
paths := make([]string, 0, len(nav.selections))
indices := make([]int, 0, len(nav.selections))
for path, index := range nav.selections {
paths = append(paths, path)
indices = append(indices, index)
}
sort.Sort(indexedMarks{paths: paths, indices: indices})
sort.Sort(indexedSelections{paths: paths, indices: indices})
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
}
+50 -24
View File
@@ -25,43 +25,63 @@ type sortType struct {
}
var gOpts struct {
dircounts bool
drawbox bool
globsearch bool
ignorecase bool
preview bool
smartcase bool
wrapscan bool
period int
scrolloff int
tabstop int
filesep string
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
anchorfind bool
color256 bool
dircounts bool
drawbox bool
globsearch bool
ignorecase bool
incsearch bool
preview bool
smartcase bool
ignoredia bool
smartdia bool
wrapscan bool
number bool
relativenumber bool
findlen int
period int
scrolloff int
tabstop int
errorfmt string
filesep string
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() {
gOpts.anchorfind = true
gOpts.color256 = false
gOpts.dircounts = false
gOpts.drawbox = false
gOpts.globsearch = false
gOpts.ignorecase = true
gOpts.incsearch = false
gOpts.preview = true
gOpts.smartcase = true
gOpts.ignoredia = false
gOpts.smartdia = false
gOpts.wrapscan = true
gOpts.number = false
gOpts.relativenumber = false
gOpts.findlen = 1
gOpts.period = 0
gOpts.scrolloff = 0
gOpts.tabstop = 8
gOpts.errorfmt = "\033[7;31;47m%s\033[0m"
gOpts.filesep = "\n"
gOpts.ifs = ""
gOpts.previewer = ""
gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f\033[0m"
gOpts.shell = gDefaultShell
gOpts.timefmt = time.ANSIC
@@ -93,7 +113,7 @@ func init() {
gOpts.keys["<end>"] = &callExpr{"bottom", nil, 1}
gOpts.keys["<space>"] = &callExpr{"toggle", nil, 1}
gOpts.keys["v"] = &callExpr{"invert", nil, 1}
gOpts.keys["u"] = &callExpr{"unmark", nil, 1}
gOpts.keys["u"] = &callExpr{"unselect", nil, 1}
gOpts.keys["y"] = &callExpr{"copy", nil, 1}
gOpts.keys["d"] = &callExpr{"cut", nil, 1}
gOpts.keys["c"] = &callExpr{"clear", nil, 1}
@@ -105,10 +125,16 @@ func init() {
gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1}
gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1}
gOpts.keys["&"] = &callExpr{"shell-async", nil, 1}
gOpts.keys["f"] = &callExpr{"find", nil, 1}
gOpts.keys["F"] = &callExpr{"find-back", nil, 1}
gOpts.keys[";"] = &callExpr{"find-next", nil, 1}
gOpts.keys[","] = &callExpr{"find-prev", nil, 1}
gOpts.keys["/"] = &callExpr{"search", nil, 1}
gOpts.keys["?"] = &callExpr{"search-back", nil, 1}
gOpts.keys["n"] = &callExpr{"search-next", nil, 1}
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
+43 -26
View File
@@ -10,6 +10,7 @@ import (
"os/user"
"path/filepath"
"runtime"
"strings"
)
var (
@@ -28,6 +29,8 @@ var (
var (
gUser *user.User
gConfigPaths []string
gMarksPath string
gHistoryPath string
)
func init() {
@@ -54,6 +57,12 @@ func init() {
u, err := user.Current()
if err != nil {
log.Printf("user: %s", err)
if os.Getenv("HOME") == "" {
log.Print("$HOME variable is empty or not set")
}
if os.Getenv("USER") == "" {
log.Print("$USER variable is empty or not set")
}
}
gUser = u
@@ -63,13 +72,25 @@ func init() {
}
gConfigPaths = []string{
filepath.Join("/etc", "lfrc"),
filepath.Join("/etc", "lf", "lfrc"),
filepath.Join(config, "lf", "lfrc"),
}
data := os.Getenv("XDG_DATA_HOME")
if data == "" {
data = filepath.Join(gUser.HomeDir, ".local", "share")
}
gMarksPath = filepath.Join(data, "lf", "marks")
gHistoryPath = filepath.Join(data, "lf", "history")
gDefaultSocketPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.sock", gUser.Username))
}
func detachedCommand(name string, arg ...string) *exec.Cmd {
return exec.Command(name, arg...)
}
func pauseCommand() *exec.Cmd {
cmd := `echo
echo -n 'Press any key to continue'
@@ -94,36 +115,14 @@ func shellCommand(s string, args []string) *exec.Cmd {
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() {
gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`}
gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`}
gOpts.keys["i"] = &execExpr{"$", `$PAGER "$f"`}
gOpts.keys["w"] = &execExpr{"$", "$SHELL"}
gOpts.cmds["doc"] = &execExpr{"$", "lf -doc | $PAGER"}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
}
func moveCursor(y, x int) {
@@ -133,3 +132,21 @@ func moveCursor(y, x int) {
func isExecutable(f os.FileInfo) bool {
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)
}
}
+44 -29
View File
@@ -1,12 +1,14 @@
package main
import (
"fmt"
"log"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
"syscall"
)
var (
@@ -29,11 +31,13 @@ var (
var (
gUser *user.User
gConfigPaths []string
gMarksPath string
gHistoryPath string
)
func init() {
if envOpener == "" {
envOpener = "start"
envOpener = `start ""`
}
if envEditor == "" {
@@ -57,10 +61,21 @@ func init() {
// remove domain prefix
gUser.Username = strings.Split(gUser.Username, `\`)[1]
data := os.Getenv("LOCALAPPDATA")
gConfigPaths = []string{
filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"),
filepath.Join(os.Getenv("LOCALAPPDATA"), "lf", "lfrc"),
filepath.Join(data, "lf", "lfrc"),
}
gMarksPath = filepath.Join(data, "lf", "marks")
gHistoryPath = filepath.Join(data, "lf", "history")
}
func detachedCommand(name string, arg ...string) *exec.Cmd {
cmd := exec.Command(name, arg...)
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: 8}
return cmd
}
func pauseCommand() *exec.Cmd {
@@ -75,38 +90,14 @@ func shellCommand(s string, args []string) *exec.Cmd {
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() {
gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"}
gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"}
gOpts.keys["i"] = &execExpr{"!", "%PAGER% %f%"}
gOpts.keys["w"] = &execExpr{"$", "%SHELL%"}
gOpts.cmds["doc"] = &execExpr{"!", "lf -doc | %PAGER%"}
gOpts.keys["<f-1>"] = &callExpr{"doc", nil, 1}
}
func moveCursor(y, x int) {
@@ -124,3 +115,27 @@ func isExecutable(f os.FileInfo) bool {
}
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 -1
View File
@@ -13,6 +13,8 @@ var (
gCopyFile bool
gFileList []string
gConnList = make(map[int]net.Conn)
gQuitChan = make(chan bool, 1)
gListener net.Listener
)
func serve() {
@@ -32,6 +34,8 @@ func serve() {
}
defer l.Close()
gListener = l
listen(l)
}
@@ -39,7 +43,13 @@ func listen(l net.Listener) {
for {
c, err := l.Accept()
if err != nil {
log.Printf("accepting connection: %s", err)
select {
case <-gQuitChan:
log.Printf("bye!")
return
default:
log.Printf("accepting connection: %s", err)
}
}
go handleConn(c)
}
@@ -103,6 +113,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
default:
log.Printf("listen: unexpected command: %s", word)
}
+103 -28
View File
@@ -182,7 +182,7 @@ func (win *win) printReg(reg *reg) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault
if reg.loading {
fg = termbox.AttrBold
fg = termbox.AttrReverse
win.print(2, 0, fg, bg, "loading...")
return
}
@@ -241,22 +241,18 @@ func fileInfo(f *file, d *dir) string {
return info
}
func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool, colors colorMap) {
func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap) {
if win.w < 5 || dir == nil {
return
}
fg, bg := termbox.ColorDefault, termbox.ColorDefault
if dir.loading {
fg = termbox.AttrBold
win.print(2, 0, fg, bg, "loading...")
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "loading...")
return
}
if len(dir.files) == 0 {
fg = termbox.AttrBold
win.print(2, 0, fg, bg, "empty")
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "empty")
return
}
@@ -267,18 +263,45 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
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] {
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())
if _, ok := marks[path]; ok {
win.print(0, i, fg, termbox.ColorMagenta, " ")
if _, ok := selections[path]; ok {
win.print(lnwidth, i, fg, termbox.ColorMagenta, " ")
} else if cp, ok := saves[path]; ok {
if cp {
win.print(0, i, fg, termbox.ColorYellow, " ")
win.print(lnwidth, i, fg, termbox.ColorYellow, " ")
} else {
win.print(0, i, fg, termbox.ColorRed, " ")
win.print(lnwidth, i, fg, termbox.ColorRed, " ")
}
}
@@ -321,7 +344,7 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
s = append(s, ' ')
win.print(1, i, fg, bg, string(s))
win.print(lnwidth+1, i, fg, bg, string(s))
}
}
@@ -455,16 +478,33 @@ func (ui *ui) sort() {
}
name := ui.dirPrev.name()
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
log.Print(msg)
}
func (ui *ui) printf(format string, a ...interface{}) {
ui.print(fmt.Sprintf(format, a...))
func (ui *ui) echomsgf(format string, a ...interface{}) {
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 {
@@ -497,7 +537,7 @@ func (ui *ui) loadFileInfo(nav *nav) {
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) {
@@ -549,7 +589,18 @@ func (ui *ui) drawStatLine(nav *nav) {
ind := min(currDir.ind+1, tot)
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)
}
ruler := fmt.Sprintf("%s%s %d/%d", acc, progress, ind, tot)
ui.msgWin.printRight(0, fg, bg, ruler)
}
@@ -602,7 +653,7 @@ func (ui *ui) draw(nav *nav) {
doff := len(nav.dirs) - length
for i := 0; i < length; i++ {
ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.marks, nav.saves, ui.colors)
ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.selections, nav.saves, ui.colors)
}
switch ui.cmdPrefix {
@@ -628,7 +679,7 @@ func (ui *ui) draw(nav *nav) {
preview := ui.wins[len(ui.wins)-1]
if f.IsDir() {
preview.printDir(ui.dirPrev, nav.marks, nav.saves, ui.colors)
preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors)
} else if f.Mode().IsRegular() {
preview.printReg(ui.regPrev)
}
@@ -700,6 +751,26 @@ func listBinds(binds map[string]expr) *bytes.Buffer {
return b
}
func listMarks(marks map[string]string) *bytes.Buffer {
t := new(tabwriter.Writer)
b := new(bytes.Buffer)
var keys []string
for k := range marks {
keys = append(keys, k)
}
sort.Strings(keys)
t.Init(b, 0, gOpts.tabstop, 2, '\t', 0)
fmt.Fprintln(t, "mark\tpath")
for _, k := range keys {
fmt.Fprintf(t, "%s\t%s\n", k, marks[k])
}
t.Flush()
return b
}
func (ui *ui) pollEvent() termbox.Event {
select {
case key := <-ui.keyChan:
@@ -722,7 +793,7 @@ func (ui *ui) pollEvent() termbox.Event {
ev.Key = val
} else {
ev.Key = termbox.KeyEsc
ui.printf("unknown key: %s", key)
ui.echoerrf("unknown key: %s", key)
}
}
}
@@ -774,7 +845,7 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
switch len(binds) {
case 0:
ui.printf("unknown mapping: %s", string(ui.keyAcc))
ui.echoerrf("unknown mapping: %s", string(ui.keyAcc))
ch <- draw
ui.keyAcc = nil
ui.keyCount = nil
@@ -787,8 +858,6 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
log.Printf("converting command count: %s", err)
}
count = c
} else {
count = 1
}
expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok {
@@ -810,8 +879,6 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
log.Printf("converting command count: %s", err)
}
count = c
} else {
count = 1
}
expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok {
@@ -872,6 +939,14 @@ func (ui *ui) readExpr() <-chan expr {
return ch
}
func setColorMode() {
if gOpts.color256 {
termbox.SetOutputMode(termbox.Output256)
} else {
termbox.SetOutputMode(termbox.OutputNormal)
}
}
func (ui *ui) pause() {
termbox.Close()
}