Compare commits

63 Commits
Author SHA1 Message Date
Gokcehan 933b49d095 cleanup 2020-04-13 18:24:15 +03:00
Gokcehan c5d05b7683 add 'on-cd' to the documentation
Related #291
2020-04-13 17:58:03 +03:00
ath3 9c1836c18b Add possibility to execute commands when directory changes (on_chdir) (#291)
* Add possibility to execute commands when cwd changes (on_chdir)

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

* rename lf-complete.csh to lf.csh

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

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

* Reversed some sloppy new lines from previous commit

* Move delete operations to delete.go

* Simplify to use RemoveAll before

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

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

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

* mkdirAll if necessary

* updated TODO's

* rename with replace prompting

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

* renewing now (no set period is needed)

* documentation, keybidning change, load file info after renaming

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

* loadfileinfo after prompts too

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

* Revert "markclear"

This reverts commit 5e3a188618.

* Revert "Revert "markclear""

This reverts commit a7a3bfebbf.

* markclear with arguments

* docs

* reverted some whitepsace

* some inline comments

* additional error handling

* wrong argument case

* consider case when argument specified clears all marks

* code cleanup and removed readMarks from writeMarks

* indentation :/

* discussed changes implemnted

* return readMarks error in sync()

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

* documentation

* indentation

* indentation

* indentation

* save

* merge glob selects

* check if selected before toggling

* glob-unselect

* identation ...

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

Related #167
2019-05-18 18:20:58 +03:00
Gokcehan 80ab2e4fc4 cd if first argument is a directory
Related #167
2019-05-18 17:51:32 +03:00
Gokcehan f071a3ae70 do not cd when select on directory
Related #167
2019-05-17 21:48:19 +03:00
David Pedersen f3407b2d61 Remain in command mode after cmd-history-next (#168) 2019-05-17 18:52:58 +03:00
Gokcehan a5199960ed update documentation 2019-05-14 20:27:16 +03:00
Gokcehan e69a229578 allow movement commands in cmap
Related #68
2019-05-14 20:21:24 +03:00
David Pedersen e815adc6a6 Add Wrap Scroll functionality. Fixes #126 (#166) 2019-05-12 17:21:45 +03:00
Gokcehan 13fe1931cd replace godep with go modules
Related #155
2019-04-20 23:12:22 +03:00
Gokcehan 2c87b0dcfe fix hidden sort 2019-03-31 23:52:39 +03:00
Gokcehan b2b22fb674 disable hidden on windows 2019-03-31 23:39:41 +03:00
Gokcehan 45270e389e export id variable after initialization 2019-03-31 19:45:11 +03:00
Gokcehan fee016f406 cleanup 2019-03-27 23:03:19 +03:00
Gokcehan 29de45e466 cleanup 2019-03-27 22:11:34 +03:00
Gokcehan 791b704257 add 'errorfmt' option to format error messages
Related #154
2019-03-27 22:07:41 +03:00
Gokcehan e3bc11408f update example configuration 2019-03-20 21:45:09 +03:00
Gokcehan 6f35abb4ca quote file variables on windows 2019-03-17 20:16:19 +03:00
Gokcehan 0eedb71d6c export permanent env vars on startup
Related #134
2019-03-17 19:52:34 +03:00
Gokcehan 1eedd29546 add file completion to search
Related #150
2019-03-14 01:20:06 +03:00
Gokcehan 866a7e6a2b cleanup 2019-03-13 22:28:20 +03:00
33 changed files with 1212 additions and 454 deletions

No files matched your search

+2 -1
View File
@@ -1,6 +1,7 @@
language: go
install:
- go get github.com/nsf/termbox-go
- go get github.com/doronbehar/termbox-go
- go get gopkg.in/djherbis/times.v1
before_deploy:
- gen/xbuild.sh
deploy:
Generated
-21
View File
@@ -1,21 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
branch = "master"
name = "github.com/mattn/go-runewidth"
packages = ["."]
revision = "ce7b0b5c7b45a81508558cd1dba6bb1e4ddb51bb"
[[projects]]
branch = "master"
name = "github.com/nsf/termbox-go"
packages = ["."]
revision = "5c94acc5e6eb520f1bcd183974e01171cc4c23b3"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "8508b73787d4948edb76ccc25789c311a4ab84d4c8c0b96b267857e2e88d974e"
solver-name = "gps-cdcl"
solver-version = 1
-38
View File
@@ -1,38 +0,0 @@
# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
# name = "github.com/user/project"
# version = "1.0.0"
#
# [[constraint]]
# name = "github.com/user/project2"
# branch = "dev"
# source = "github.com/myfork/project2"
#
# [[override]]
# name = "github.com/x/y"
# version = "2.4.0"
#
# [prune]
# non-go = false
# go-tests = true
# unused-packages = true
[[constraint]]
branch = "master"
name = "github.com/mattn/go-runewidth"
[[constraint]]
branch = "master"
name = "github.com/nsf/termbox-go"
[prune]
go-tests = true
unused-packages = true
+39 -44
View File
@@ -8,7 +8,6 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
@@ -138,7 +137,14 @@ func (app *app) loop() {
if gSelect != "" {
go func() {
app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1}
stat, err := os.Stat(gSelect)
if err != nil {
app.ui.exprChan <- &callExpr{"echoerr", []string{err.Error()}, 1}
} else if stat.IsDir() {
app.ui.exprChan <- &callExpr{"cd", []string{gSelect}, 1}
} else {
app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1}
}
}()
}
@@ -173,12 +179,13 @@ func (app *app) loop() {
continue
}
log.Print("bye!")
if err := app.nav.writeMarks(); err != nil {
log.Printf("writing marks file: %s", err)
if app.nav.deleteTotal > 0 {
app.ui.echoerr("quit: delete operation in progress")
continue
}
log.Print("bye!")
if err := app.writeHistory(); err != nil {
log.Printf("writing history file: %s", err)
}
@@ -230,6 +237,21 @@ func (app *app) loop() {
app.nav.moveUpdate = 0
}
app.ui.draw(app.nav)
case n := <-app.nav.deleteCountChan:
app.nav.deleteCount += n
if app.nav.deleteUpdate++; app.nav.deleteUpdate >= 1000 {
app.nav.deleteUpdate = 0
app.ui.draw(app.nav)
}
case n := <-app.nav.deleteTotalChan:
app.nav.deleteTotal += n
if n < 0 {
app.nav.deleteCount += n
}
if app.nav.deleteTotal == 0 {
app.nav.deleteUpdate = 0
}
app.ui.draw(app.nav)
case d := <-app.nav.dirChan:
prev, ok := app.nav.dirCache[d.path]
if ok {
@@ -283,40 +305,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
}
selections := app.nav.currSelections()
currSelections := app.nav.currSelections()
envFiles := strings.Join(selections, gOpts.filesep)
os.Setenv("f", envFile)
os.Setenv("fs", envFiles)
if len(selections) == 0 {
os.Setenv("fx", envFile)
} else {
os.Setenv("fx", envFiles)
}
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
level, err := strconv.Atoi(envLevel)
if err != nil {
log.Printf("reading lf level: %s", err)
}
level++
os.Setenv("LF_LEVEL", strconv.Itoa(level))
exportFiles(currFile, currSelections)
}
func waitKey() error {
@@ -341,11 +338,12 @@ 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)
var out io.Reader
var err error
switch prefix {
case "$", "!":
cmd.Stdin = os.Stdin
@@ -355,6 +353,8 @@ func (app *app) runShell(s string, args []string, prefix string) {
app.ui.pause()
defer app.ui.resume()
defer app.nav.renew()
err = cmd.Run()
case "%":
stdin, err := cmd.StdinPipe()
if err != nil {
@@ -367,13 +367,8 @@ func (app *app) runShell(s string, args []string, prefix string) {
}
out = stdout
cmd.Stderr = cmd.Stdout
}
var err error
switch prefix {
case "$", "!":
err = cmd.Run()
case "%", "&":
fallthrough
case "&":
err = cmd.Start()
}
+2 -2
View File
@@ -10,7 +10,7 @@ import (
"strings"
"time"
"github.com/nsf/termbox-go"
"github.com/doronbehar/termbox-go"
)
func run() {
@@ -52,7 +52,7 @@ func readExpr() <-chan expr {
c, err := net.Dial(gSocketProt, gSocketPath)
for err != nil {
log.Printf(fmt.Sprintf("connecting server: %s", err))
log.Printf("connecting server: %s", err)
time.Sleep(duration)
duration *= 2
c, err = net.Dial(gSocketProt, gSocketPath)
+5 -5
View File
@@ -7,7 +7,7 @@ import (
"strconv"
"strings"
"github.com/nsf/termbox-go"
"github.com/doronbehar/termbox-go"
)
const gAnsiColorResetMask = termbox.AttrBold | termbox.AttrUnderline | termbox.AttrReverse
@@ -199,6 +199,10 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
var key string
switch {
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
@@ -207,10 +211,6 @@ func (cm colorMap) get(f *file) (termbox.Attribute, termbox.Attribute) {
key = "ow"
case f.IsDir():
key = "di"
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.Mode()&os.ModeNamedPipe != 0:
key = "pi"
case f.Mode()&os.ModeSocket != 0:
+1 -1
View File
@@ -3,7 +3,7 @@ package main
import (
"testing"
"github.com/nsf/termbox-go"
"github.com/doronbehar/termbox-go"
)
func TestApplyAnsiCodes(t *testing.T) {
+53 -4
View File
@@ -51,13 +51,17 @@ var (
"search-next",
"search-prev",
"mark-save",
"mark-remove",
"mark-load",
"rename",
"sync",
"echo",
"echomsg",
"echoerr",
"cd",
"select",
"glob-select",
"glob-unselect",
"source",
"push",
}
@@ -81,6 +85,9 @@ var (
"globsearch",
"noglobsearch",
"globsearch!",
"icons",
"noicons",
"icons!",
"hidden",
"nohidden",
"hidden!",
@@ -108,6 +115,9 @@ var (
"wrapscan",
"nowrapscan",
"wrapscan!",
"wrapscroll",
"nowrapscroll",
"wrapscroll!",
"number",
"nonumber",
"number!",
@@ -118,6 +128,7 @@ var (
"period",
"scrolloff",
"tabstop",
"errorfmt",
"filesep",
"ifs",
"previewer",
@@ -245,13 +256,13 @@ func matchFile(s string) (matches []string, longest string) {
name := f.Name()
if isRoot(s) || filepath.Base(s) != s {
name = filepath.Join(filepath.Dir(s), f.Name())
name = filepath.Join(filepath.Dir(unescape(s)), f.Name())
}
name = escape(name)
item := f.Name()
if f.Mode().IsDir() {
item += string(filepath.Separator)
item += escape(string(filepath.Separator))
}
matches = append(matches, item)
@@ -261,7 +272,7 @@ func matchFile(s string) (matches []string, longest string) {
if f.Mode().IsRegular() {
longest = name + " "
} else {
longest = name + string(filepath.Separator)
longest = name + escape(string(filepath.Separator))
}
}
}
@@ -321,6 +332,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)
@@ -333,7 +382,7 @@ func completeShell(acc []rune) (matches []string, longestAcc []rune) {
longestAcc = []rune(longest)
default:
matches, longest = matchFile(f[len(f)-1])
longestAcc = append(acc[:len(acc)-len(f[len(f)-1])], []rune(longest)...)
longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], []rune(longest)...)
}
return
+9 -16
View File
@@ -2,7 +2,7 @@ package main
import (
"strconv"
"strings"
"unicode"
)
var normMap map[rune]rune
@@ -14,19 +14,16 @@ func init() {
appendTransliterate(
"ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ",
"eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa",
true,
)
// Vietnamese
appendTransliterate(
"áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ",
"aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd",
true,
)
}
func appendTransliterate(base, norm string, uppercase bool) {
func appendTransliterate(base, norm string) {
normRunes := []rune(norm)
baseRunes := []rune(base)
@@ -36,24 +33,20 @@ func appendTransliterate(base, norm string, uppercase bool) {
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]
}
for i := 0; i < lenBase; i++ {
normMap[baseRunes[i]] = 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]
}
baseUpper := unicode.ToUpper(baseRunes[i])
normUpper := unicode.ToUpper(normRunes[i])
normMap[baseUpper] = normUpper
}
}
// Remove diacritics and make lowercase.
func removeDiacritics(baseString string) string {
var normalizedRunes []rune
for _, baseRune := range []rune(baseString) {
for _, baseRune := range baseString {
if normRune, ok := normMap[baseRune]; ok {
normalizedRunes = append(normalizedRunes, normRune)
} else {
+69 -17
View File
@@ -37,6 +37,7 @@ The following commands are provided by lf with default keybindings:
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
rename (default 'r')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
@@ -51,20 +52,23 @@ The following commands are provided by lf with default keybindings:
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default `"`)
The following commands are provided by lf without default keybindings:
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)
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
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default
keybindings:
@@ -102,6 +106,7 @@ The following options can be used to customize the behavior of lf:
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
icons boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
@@ -111,12 +116,14 @@ The following options can be used to customize the behavior of lf:
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
wrapscroll boolean (default off)
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)
@@ -167,6 +174,9 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info
map ss :set sortby size; set info size
map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~
The following keybindings to applications are provided by default:
@@ -213,14 +223,11 @@ The following command prefixes are used by lf:
% 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
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.
commands. These modes are mapped to the prefix keys above by default.
Syntax
@@ -534,7 +541,7 @@ 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.
File operations can be performed on the current selected file or alternatively
on multiple files by marking them first. When you 'copy' a file, lf doesn't
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.
@@ -582,7 +589,16 @@ 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.
'cmd-escape' to cancel the search. Alternatively, you can also map some other
commands with 'cmap' to accept the search and execute the command immediately
afterwards. Possible candidates are 'up', 'down' and their variants, 'updir',
and 'open' commands. For example, you can use arrow keys to finish the search
with the following mappings:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
@@ -622,6 +638,9 @@ You may want to use either file extensions or mime types from 'file' command:
esac
}}
You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
Following command is provided by default:
cmd open &$OPENER $f
@@ -674,6 +693,39 @@ pipe with a SIGPIPE when enough lines are read. When everything else fails, you
can make use of the height argument to only feed the first portion of the file
to a program for preview.
Changing Directory
lf changes the working directory of the process to the current directory so
that shell commands always work in the displayed directory. After quitting, it
returns to the original directory where it is first launched like all shell
programs. If you want to stay in the current directory after quitting, you can
use one of the example wrapper shell scripts provided in the repository.
There is a special command 'on-cd' that runs a shell command when it is defined
and the directory is changed. You can define it just as you would define any
other command:
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f$git\033[0m"
lf -remote "send $id set promptfmt \"$fmt\""
}}
This command runs whenever you change directory but not on startup. You can add
an extra call to make it run on startup as well:
cmd on-cd &{{ # ... }}
on-cd
Note that all shell commands are possible but `%` and `&` are usually more
appropriate as `$` and `!` causes flickers and pauses respectively.
Colorschemes
lf tries to automatically adapt its colors to the environment. On startup,
+75 -20
View File
@@ -40,6 +40,7 @@ The following commands are provided by lf with default keybindings:
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
rename (default 'r')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
@@ -54,20 +55,23 @@ The following commands are provided by lf with default keybindings:
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default '"')
The following commands are provided by lf without default keybindings:
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)
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
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
The following command line commands are provided by lf with default
keybindings:
@@ -105,6 +109,7 @@ The following options can be used to customize the behavior of lf:
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
icons boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
@@ -114,22 +119,24 @@ The following options can be used to customize the behavior of lf:
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
wrapscroll boolean (default off)
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)
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 ”)
info string (default '')
shellopts string (default '')
The following variables are exported for shell commands:
@@ -170,6 +177,9 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info
map ss :set sortby size; set info size
map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~
The following keybindings to applications are provided by default:
@@ -218,14 +228,12 @@ The following command prefixes are used by lf:
% 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
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.
default.
Syntax
@@ -557,7 +565,7 @@ as well as the log file and they do not preemptively finish the
corresponding file operation.
File operations can be performed on the current selected file or
alternatively on multiple files by marking them first. When you 'copy' a
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.
@@ -607,7 +615,16 @@ 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.
search or use 'cmd-escape' to cancel the search. Alternatively, you can also
map some other commands with 'cmap' to accept the search and execute the
command immediately afterwards. Possible candidates are 'up', 'down' and
their variants, 'updir', and 'open' commands. For example, you can use arrow
keys to finish the search with the following mappings:
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
Finding mechanism is implemented with commands 'find' (default 'f'),
'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default
@@ -649,6 +666,9 @@ command:
esac
}}
You may want to use 'setsid' before your opener command to have persistent
processes that continue to run after lf quits.
Following command is provided by default:
cmd open &$OPENER $f
@@ -704,6 +724,41 @@ everything else fails, you can make use of the height argument to only feed
the first portion of the file to a program for preview.
Changing Directory
lf changes the working directory of the process to the current directory so
that shell commands always work in the displayed directory. After quitting,
it returns to the original directory where it is first launched like all
shell programs. If you want to stay in the current directory after quitting,
you can use one of the example wrapper shell scripts provided in the
repository.
There is a special command 'on-cd' that runs a shell command when it is
defined and the directory is changed. You can define it just as you would
define any other command:
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\033[32;1m%u@%h\033[0m:\033[34;1m%w/\033[0m\033[1m%f$git\033[0m"
lf -remote "send $id set promptfmt \"$fmt\""
}}
This command runs whenever you change directory but not on startup. You can
add an extra call to make it run on startup as well:
cmd on-cd &{{ # ... }}
on-cd
Note that all shell commands are possible but '%' and '&' are usually more
appropriate as '$' and '!' causes flickers and pauses respectively.
Colorschemes
lf tries to automatically adapt its colors to the environment. On startup,
+12
View File
@@ -0,0 +1,12 @@
#
# For using these completions you must load it from .tcshrc
#
# source ~/.config/lf/lf.csh
#
set lf_args = "-command -cpuprofile -doc --help -last-dir-path -memprofile -remote -selection-path -server -version --version"
uncomplete lf
uncomplete lfcd
complete lf "C/-*/(${lf_args})/"
complete lfcd "C/-*/(${lf_args})/"
+29
View File
@@ -0,0 +1,29 @@
#compdef lf
# For using these completions you must:
# - rename this file to _lf
# - add the containing folder to $fpath in .zshrc, like this:
# '''
# fpath=(/path/to/folder/containing_lf $fpath)
# autoload -U compinit
# compinit
# '''
#
# zsh completions for 'lf'
# automatically generated with http://github.com/RobSis/zsh-completion-generator
local arguments
arguments=(
'-command[command to execute on client initialization]'
'-cpuprofile[path to the file to write the CPU profile]'
'-doc[show documentation]'
'-last-dir-path[path to the file to write the last dir on exit (to use for cd)]'
'-memprofile[path to the file to write the memory profile]'
'-remote[send remote command to server]'
'-selection-path[path to the file to write selected files on open (to use as open file dialog)]'
'-server[start server (automatic)]'
'-version[show version]'
'*:filename:_files'
)
_arguments -s $arguments
+6 -6
View File
@@ -5,11 +5,11 @@ rem You need to put this file to a folder in %PATH% variable.
:tmploop
set tmpfile="%tmp%\lf.%random%.tmp"
if exist "%tmpfile%" goto:tmploop
lf -last-dir-path="%tmpfile%" %*
if not exist "%tmpfile%" exit
set /p dir=<"%tmpfile%"
del /f "%tmpfile%"
if exist %tmpfile% goto:tmploop
lf -last-dir-path=%tmpfile% %*
if not exist %tmpfile% exit
set /p dir=<%tmpfile%
del /f %tmpfile%
if not exist "%dir%" exit
if "%dir%" == "%cd%" exit
cd "%dir%"
cd /d "%dir%"
+13
View File
@@ -0,0 +1,13 @@
# Change working dir in shell to last dir in lf on exit.
#
# You need to either copy the content of this file to your shell rc file
# (e.g. ~/.tcshrc) or source this file directly:
#
# setenv LF_HOME "${HOME}/.config/lf"
# [ -e "${LF_HOME}/lfcd.csh" ] && source "${LF_HOME}/lfcd.csh"
#
# You may also like to assign a key to this command:
#
# bindkey -c "^O" lfcd
#
alias lfcd 'set _=`mktemp` && lf -last-dir-path=$_ "\!*" && set _=`cat $_ && rm -f $_` && [ -d "$_" ] && cd "$_"'
+17 -13
View File
@@ -38,29 +38,33 @@ map O $mimeopen --ask $f
cmd open ${{
case $(file --mime-type $f -b) in
text/*) $EDITOR $fx;;
*) for f in $fx; do $OPENER $f > /dev/null 2> /dev/null & done;;
*) for f in $fx; do setsid $OPENER $f > /dev/null 2> /dev/null & done;;
esac
}}
# rename current file without overwrite
cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
map r push :rename<space>
# define a custom 'rename' command without prompt for overwrite
# cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1
# map r push :rename<space>
# make sure trash folder exists
%mkdir -p ~/.trash
# %mkdir -p ~/.trash
# move current file or selected files to trash folder
# (also see 'man mv' for backup/overwrite options)
cmd trash %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/)
+286 -81
View File
@@ -71,6 +71,12 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.globsearch = false
case "globsearch!":
gOpts.globsearch = !gOpts.globsearch
case "icons":
gOpts.icons = true
case "noicons":
gOpts.icons = false
case "icons!":
gOpts.icons = !gOpts.icons
case "hidden":
gOpts.sortType.option |= hiddenSort
app.nav.sort()
@@ -108,10 +114,18 @@ func (e *setExpr) eval(app *app, args []string) {
case "incsearch!":
gOpts.incsearch = !gOpts.incsearch
case "preview":
if len(gOpts.ratios) < 2 {
app.ui.echoerr("preview: 'ratios' should consist of at least two numbers before enabling 'preview'")
return
}
gOpts.preview = true
case "nopreview":
gOpts.preview = false
case "preview!":
if len(gOpts.ratios) < 2 {
app.ui.echoerr("preview: 'ratios' should consist of at least two numbers before enabling 'preview'")
return
}
gOpts.preview = !gOpts.preview
case "reverse":
gOpts.sortType.option |= reverseSort
@@ -143,6 +157,12 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.wrapscan = false
case "wrapscan!":
gOpts.wrapscan = !gOpts.wrapscan
case "wrapscroll":
gOpts.wrapscroll = true
case "nowrapscroll":
gOpts.wrapscroll = false
case "wrapscroll!":
gOpts.wrapscroll = !gOpts.wrapscroll
case "number":
gOpts.number = true
case "nonumber":
@@ -205,6 +225,8 @@ func (e *setExpr) eval(app *app, args []string) {
return
}
gOpts.tabstop = n
case "errorfmt":
gOpts.errorfmt = e.val
case "filesep":
gOpts.filesep = e.val
case "ifs":
@@ -216,10 +238,6 @@ func (e *setExpr) eval(app *app, args []string) {
case "shell":
gOpts.shell = e.val
case "sortby":
if e.val != "natural" && e.val != "name" && e.val != "size" && e.val != "time" {
app.ui.echoerr("sortby: value should either be 'natural', 'name', 'size' or 'time'")
return
}
switch e.val {
case "natural":
gOpts.sortType.method = naturalSort
@@ -229,6 +247,15 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.sortType.method = sizeSort
case "time":
gOpts.sortType.method = timeSort
case "ctime":
gOpts.sortType.method = ctimeSort
case "atime":
gOpts.sortType.method = atimeSort
case "ext":
gOpts.sortType.method = extSort
default:
app.ui.echoerr("sortby: value should either be 'natural', 'name', 'size', 'time', 'atime', 'ctime' or 'ext'")
return
}
app.nav.sort()
app.ui.sort()
@@ -259,8 +286,10 @@ func (e *setExpr) eval(app *app, args []string) {
case "info":
toks := strings.Split(e.val, ":")
for _, s := range toks {
if s != "" && s != "size" && s != "time" {
app.ui.echoerr("info: should consist of 'size' or 'time' separated with colon")
switch s {
case "", "size", "time", "atime", "ctime":
default:
app.ui.echoerr("info: should consist of 'size', 'time', 'atime' or 'ctime' separated with colon")
return
}
}
@@ -269,31 +298,42 @@ func (e *setExpr) eval(app *app, args []string) {
gOpts.shellopts = strings.Split(e.val, ":")
default:
app.ui.echoerrf("unknown option: %s", e.opt)
return
}
app.ui.loadFileInfo(app.nav)
}
func (e *mapExpr) eval(app *app, args []string) {
if e.expr == nil {
delete(gOpts.keys, e.keys)
return
} else {
gOpts.keys[e.keys] = e.expr
}
gOpts.keys[e.keys] = e.expr
app.ui.loadFileInfo(app.nav)
}
func (e *cmapExpr) eval(app *app, args []string) {
if e.cmd == "" {
delete(gOpts.cmdkeys, e.key)
return
} else {
gOpts.cmdkeys[e.key] = &callExpr{e.cmd, nil, 1}
}
gOpts.cmdkeys[e.key] = &callExpr{e.cmd, nil, 1}
app.ui.loadFileInfo(app.nav)
}
func (e *cmdExpr) eval(app *app, args []string) {
if e.expr == nil {
delete(gOpts.cmds, e.name)
return
} else {
gOpts.cmds[e.name] = e.expr
}
app.ui.loadFileInfo(app.nav)
}
func onChdir(app *app) {
if cmd, ok := gOpts.cmds["on-cd"]; ok {
cmd.eval(app, nil)
}
gOpts.cmds[e.name] = e.expr
}
func splitKeys(s string) (keys []string) {
@@ -362,6 +402,13 @@ func update(app *app) {
}
}
func normal(app *app) {
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
}
func insert(app *app, arg string) {
switch {
case gOpts.incsearch && (app.ui.cmdPrefix == "/" || app.ui.cmdPrefix == "?"):
@@ -395,10 +442,7 @@ func insert(app *app, arg string) {
}
}
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
normal(app)
case app.ui.cmdPrefix == "find-back: ":
app.nav.find = string(app.ui.cmdAccLeft) + arg + string(app.ui.cmdAccRight)
@@ -427,31 +471,41 @@ func insert(app *app, arg string) {
}
}
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 = ""
normal(app)
case strings.HasPrefix(app.ui.cmdPrefix, "delete"):
normal(app)
if arg == "y" {
if err := app.nav.del(); err != nil {
if err := app.nav.del(app.ui); 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)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
case strings.HasPrefix(app.ui.cmdPrefix, "replace") ||
strings.HasPrefix(app.ui.cmdPrefix, "create path"):
normal(app)
if arg == "y" {
if err := app.nav.rename(); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
case app.ui.cmdPrefix == "mark-save: ":
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
normal(app)
wd, err := os.Getwd()
if err != nil {
@@ -459,11 +513,14 @@ func insert(app *app, arg string) {
return
}
app.nav.marks[arg] = wd
if err := app.nav.writeMarks(); err != nil {
app.ui.echoerrf("mark-save: %s", err)
}
if err := remote("send sync"); err != nil {
app.ui.echoerrf("mark-save: %s", err)
}
case app.ui.cmdPrefix == "mark-load: ":
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
normal(app)
wd, err := os.Getwd()
if err != nil {
@@ -484,6 +541,20 @@ func insert(app *app, arg string) {
if wd != path {
app.nav.marks["'"] = wd
onChdir(app)
}
case app.ui.cmdPrefix == "mark-remove: ":
normal(app)
if err := app.nav.removeMark(arg); err != nil {
app.ui.echoerrf("mark-remove: %s", err)
return
}
if err := app.nav.writeMarks(); err != nil {
app.ui.echoerrf("mark-remove: %s", err)
return
}
if err := remote("send sync"); err != nil {
app.ui.echoerrf("mark-remove: %s", err)
}
default:
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...)
@@ -493,30 +564,51 @@ func insert(app *app, arg string) {
func (e *callExpr) eval(app *app, args []string) {
switch e.name {
case "up":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
app.nav.up(e.count)
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "half-up":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
app.nav.up(e.count * app.nav.height / 2)
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "page-up":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
app.nav.up(e.count * app.nav.height)
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "down":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
app.nav.down(e.count)
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "half-down":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
app.nav.down(e.count * app.nav.height / 2)
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "page-down":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
app.nav.down(e.count * app.nav.height)
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "updir":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
for i := 0; i < e.count; i++ {
if err := app.nav.updir(); err != nil {
app.ui.echoerrf("%s", err)
@@ -525,7 +617,11 @@ func (e *callExpr) eval(app *app, args []string) {
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
onChdir(app)
case "open":
if app.ui.cmdPrefix != "" && app.ui.cmdPrefix != ">" {
normal(app)
}
curr, err := app.nav.currFile()
if err != nil {
app.ui.echoerrf("opening: %s", err)
@@ -540,6 +636,7 @@ func (e *callExpr) eval(app *app, args []string) {
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
onChdir(app)
return
}
@@ -589,8 +686,10 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.loadFileInfo(app.nav)
case "invert":
app.nav.invert()
app.ui.loadFileInfo(app.nav)
case "unselect":
app.nav.unselect()
app.ui.loadFileInfo(app.nav)
case "copy":
if err := app.nav.save(true); err != nil {
app.ui.echoerrf("copy: %s", err)
@@ -599,7 +698,9 @@ func (e *callExpr) eval(app *app, args []string) {
app.nav.unselect()
if err := remote("send sync"); err != nil {
app.ui.echoerrf("copy: %s", err)
return
}
app.ui.loadFileInfo(app.nav)
case "cut":
if err := app.nav.save(false); err != nil {
app.ui.echoerrf("cut: %s", err)
@@ -608,7 +709,9 @@ func (e *callExpr) eval(app *app, args []string) {
app.nav.unselect()
if err := remote("send sync"); err != nil {
app.ui.echoerrf("cut: %s", err)
return
}
app.ui.loadFileInfo(app.nav)
case "paste":
if cmd, ok := gOpts.cmds["paste"]; ok {
cmd.eval(app, e.args)
@@ -616,20 +719,31 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.echoerrf("paste: %s", err)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
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)
return
}
} else {
if _, err := app.nav.currFileOrSelections(); err != nil {
fileOrSelections, err := app.nav.currFileOrSelections()
if err != nil {
app.ui.echoerrf("delete: %s", err)
return
}
app.ui.cmdPrefix = "delete?[y/N]: "
if selections := len(fileOrSelections); selections == 1 {
app.ui.cmdPrefix = "delete " + fileOrSelections[0] + " [y/N]? "
} else {
app.ui.cmdPrefix = "delete " + strconv.Itoa(selections) + " items [y/N]? "
}
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "clear":
if err := saveFiles(nil, false); err != nil {
app.ui.echoerrf("clear: %s", err)
@@ -637,18 +751,24 @@ func (e *callExpr) eval(app *app, args []string) {
}
if err := remote("send sync"); err != nil {
app.ui.echoerrf("clear: %s", err)
return
}
app.ui.loadFileInfo(app.nav)
case "draw":
case "redraw":
app.ui.sync()
app.ui.renew()
app.nav.height = app.ui.wins[0].h
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "load":
app.nav.renew()
case "reload":
if err := app.nav.reload(); err != nil {
app.ui.echoerrf("reload: %s", err)
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "read":
app.ui.cmdPrefix = ":"
case "shell":
@@ -734,6 +854,27 @@ func (e *callExpr) eval(app *app, args []string) {
case "mark-load":
app.ui.menuBuf = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-load: "
case "mark-remove":
app.ui.menuBuf = listMarks(app.nav.marks)
app.ui.cmdPrefix = "mark-remove: "
case "rename":
if cmd, ok := gOpts.cmds["rename"]; ok {
cmd.eval(app, e.args)
if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
} else {
curr, err := app.nav.currFile()
if err != nil {
app.ui.echoerrf("rename: %s:", err)
return
}
app.ui.cmdPrefix = "rename: "
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(curr.Name())...)
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
case "sync":
if err := app.nav.sync(); err != nil {
app.ui.echoerrf("sync: %s", err)
@@ -771,6 +912,7 @@ func (e *callExpr) eval(app *app, args []string) {
if wd != path {
app.nav.marks["'"] = wd
onChdir(app)
}
case "select":
if len(e.args) != 1 {
@@ -800,13 +942,35 @@ func (e *callExpr) eval(app *app, args []string) {
if wd != path {
app.nav.marks["'"] = wd
onChdir(app)
}
case "glob-select":
if len(e.args) != 1 {
app.ui.echoerr("glob-select: requires a pattern to match")
return
}
if err := app.nav.globSel(e.args[0], false); err != nil {
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFileInfo(app.nav)
case "glob-unselect":
if len(e.args) != 1 {
app.ui.echoerr("glob-unselect: requires a pattern to match")
return
}
if err := app.nav.globSel(e.args[0], true); err != nil {
app.ui.echoerrf("%s", err)
return
}
app.ui.loadFileInfo(app.nav)
case "source":
if len(e.args) != 1 {
app.ui.echoerr("source: requires an argument")
return
}
app.readFile(strings.Replace(e.args[0], "~", gUser.HomeDir, -1))
app.ui.loadFileInfo(app.nav)
case "push":
if len(e.args) != 1 {
app.ui.echoerr("push: requires an argument")
@@ -833,16 +997,18 @@ func (e *callExpr) eval(app *app, args []string) {
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 = ""
normal(app)
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 {
@@ -919,6 +1085,48 @@ func (e *callExpr) eval(app *app, args []string) {
if err := app.nav.searchPrev(); err != nil {
app.ui.echoerrf("search-back: %s: %s", err, app.nav.search)
} else {
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
case "rename: ":
app.ui.cmdPrefix = ""
if curr, err := app.nav.currFile(); err != nil {
app.ui.echoerrf("rename: %s", err)
} else {
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
return
}
oldPathTo := filepath.Join(wd, curr.Name())
newPathTo := filepath.Join(wd, s)
if oldPathTo == newPathTo {
return
}
app.nav.renameCache = []string{oldPathTo, newPathTo}
if dir, _ := filepath.Split(s); dir != "" {
if _, err := os.Stat(filepath.Join(wd, dir)); err != nil {
app.ui.cmdPrefix = "create path " + dir + "?[y/N]"
return
}
}
if _, err := os.Stat(newPathTo); err == nil { // file exists
app.ui.cmdPrefix = "replace " + s + "?[y/N]"
return
}
if err := app.nav.rename(); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
if err := remote("send load"); err != nil {
app.ui.echoerrf("rename: %s", err)
return
}
app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav)
}
@@ -936,7 +1144,7 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
app.ui.cmdPrefix = ":"
return
}
cmd := app.cmdHistory[len(app.cmdHistory)-app.cmdHistoryInd]
@@ -1006,8 +1214,8 @@ func (e *callExpr) eval(app *app, args []string) {
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]
app.ui.cmdYankBuf = []rune(string(app.ui.cmdAccLeft)[ind:])
app.ui.cmdAccLeft = []rune(string(app.ui.cmdAccLeft)[:ind])
update(app)
case "cmd-yank":
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdYankBuf...)
@@ -1022,34 +1230,31 @@ func (e *callExpr) eval(app *app, args []string) {
if app.cmd != nil {
app.cmd.Process.Kill()
}
app.ui.menuBuf = nil
app.ui.cmdAccLeft = nil
app.ui.cmdAccRight = nil
app.ui.cmdPrefix = ""
normal(app)
case "cmd-word":
if len(app.ui.cmdAccRight) == 0 {
return
}
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
ind := loc[3]
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(string(app.ui.cmdAccRight)[:ind])...)
app.ui.cmdAccRight = []rune(string(app.ui.cmdAccRight)[ind:])
case "cmd-word-back":
if len(app.ui.cmdAccLeft) == 0 {
return
}
locs := reWordBeg.FindAllStringIndex(string(app.ui.cmdAccLeft), -1)
locs := reWordBeg.FindAllStringSubmatchIndex(string(app.ui.cmdAccLeft), -1)
if locs == nil {
return
}
ind := locs[len(locs)-1][1] - 1
ind := locs[len(locs)-1][3]
old := app.ui.cmdAccRight
app.ui.cmdAccRight = append([]rune{}, app.ui.cmdAccLeft[ind:]...)
app.ui.cmdAccRight = append([]rune{}, []rune(string(app.ui.cmdAccLeft)[ind:])...)
app.ui.cmdAccRight = append(app.ui.cmdAccRight, old...)
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind]
app.ui.cmdAccLeft = []rune(string(app.ui.cmdAccLeft)[:ind])
case "cmd-capitalize-word":
if len(app.ui.cmdAccRight) == 0 {
return
@@ -1061,48 +1266,48 @@ func (e *callExpr) eval(app *app, args []string) {
return
}
app.ui.cmdAccRight[ind] = unicode.ToUpper(app.ui.cmdAccRight[ind])
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind = loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
ind = loc[3]
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(string(app.ui.cmdAccRight)[:ind])...)
app.ui.cmdAccRight = []rune(string(app.ui.cmdAccRight)[ind:])
update(app)
case "cmd-delete-word":
if len(app.ui.cmdAccRight) == 0 {
return
}
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
ind := loc[3]
app.ui.cmdAccRight = []rune(string(app.ui.cmdAccRight)[ind:])
update(app)
case "cmd-uppercase-word":
if len(app.ui.cmdAccRight) == 0 {
return
}
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
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:]
ind := loc[3]
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToUpper(string(app.ui.cmdAccRight)[:ind]))...)
app.ui.cmdAccRight = []rune(string(app.ui.cmdAccRight)[ind:])
update(app)
case "cmd-lowercase-word":
if len(app.ui.cmdAccRight) == 0 {
return
}
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
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:]
ind := loc[3]
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToLower(string(app.ui.cmdAccRight)[:ind]))...)
app.ui.cmdAccRight = []rune(string(app.ui.cmdAccRight)[ind:])
update(app)
case "cmd-transpose-word":
if len(app.ui.cmdAccLeft) == 0 {
@@ -1115,11 +1320,11 @@ func (e *callExpr) eval(app *app, args []string) {
}
if len(app.ui.cmdAccRight) > 0 {
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight))
if loc != nil {
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
ind := loc[3]
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(string(app.ui.cmdAccRight)[:ind])...)
app.ui.cmdAccRight = []rune(string(app.ui.cmdAccRight)[ind:])
}
}
@@ -1130,11 +1335,11 @@ func (e *callExpr) eval(app *app, args []string) {
var acc []rune
acc = append(acc, app.ui.cmdAccLeft[:beg1]...)
acc = append(acc, app.ui.cmdAccLeft[beg2:end2]...)
acc = append(acc, app.ui.cmdAccLeft[end1:beg2]...)
acc = append(acc, app.ui.cmdAccLeft[beg1:end1]...)
acc = append(acc, app.ui.cmdAccLeft[end2:]...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[:beg1])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[beg2:end2])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[end1:beg2])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[beg1:end1])...)
acc = append(acc, []rune(string(app.ui.cmdAccLeft)[end2:])...)
app.ui.cmdAccLeft = acc
update(app)
+41 -15
View File
@@ -67,8 +67,8 @@ var gEvalTests = []struct {
{
`echo "hello\zworld"`,
[]string{"echo", "helloworld", "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}, 1}},
[]string{"echo", `hello\zworld`, "\n"},
[]expr{&callExpr{"echo", []string{`hello\zworld`}, 1}},
},
{
@@ -90,7 +90,7 @@ var gEvalTests = []struct {
},
{
`echo hello\ world`,
"echo hello\\\tworld",
[]string{"echo", "hello\tworld", "\n"},
[]expr{&callExpr{"echo", []string{"hello\tworld"}, 1}},
},
@@ -101,10 +101,16 @@ var gEvalTests = []struct {
[]expr{&callExpr{"echo", []string{"hello\nworld"}, 1}},
},
{
`echo hello\\world`,
[]string{"echo", `hello\world`, "\n"},
[]expr{&callExpr{"echo", []string{`hello\world`}, 1}},
},
{
`echo hello\zworld`,
[]string{"echo", "helloworld", "\n"},
[]expr{&callExpr{"echo", []string{"helloworld"}, 1}},
[]string{"echo", "hellozworld", "\n"},
[]expr{&callExpr{"echo", []string{"hellozworld"}, 1}},
},
{
@@ -125,6 +131,18 @@ var gEvalTests = []struct {
[]expr{&setExpr{"hidden", ""}, &setExpr{"preview", ""}},
},
{
`set ifs ""`,
[]string{"set", "ifs", "", "\n"},
[]expr{&setExpr{"ifs", ""}},
},
{
`set ifs "\n"`,
[]string{"set", "ifs", "\n", "\n"},
[]expr{&setExpr{"ifs", "\n"}},
},
{
"set ratios 1:2:3",
[]string{"set", "ratios", "1:2:3", "\n"},
@@ -292,13 +310,17 @@ var gEvalTests = []struct {
cd ~
set hidden
}}`,
[]string{"cmd", "gohome", ":", "{{",
[]string{
"cmd", "gohome", ":", "{{",
"cd", "~", "\n",
"set", "hidden", "\n",
"}}", "\n"},
[]expr{&cmdExpr{"gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""}}},
"}}", "\n",
},
[]expr{&cmdExpr{
"gohome", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}},
}},
},
@@ -307,13 +329,17 @@ var gEvalTests = []struct {
cd ~
set hidden
}}`,
[]string{"map", "gh", ":", "{{",
[]string{
"map", "gh", ":", "{{",
"cd", "~", "\n",
"set", "hidden", "\n",
"}}", "\n"},
[]expr{&mapExpr{"gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""}}},
"}}", "\n",
},
[]expr{&mapExpr{
"gh", &listExpr{[]expr{
&callExpr{"cd", []string{"~"}, 1},
&setExpr{"hidden", ""},
}},
}},
},
+9
View File
@@ -0,0 +1,9 @@
module github.com/gokcehan/lf
go 1.12
require (
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05
github.com/mattn/go-runewidth v0.0.4
gopkg.in/djherbis/times.v1 v1.2.0
)
+10
View File
@@ -0,0 +1,10 @@
github.com/doronbehar/termbox-go v0.0.0-20190817171036-93860e161317 h1:mdOm+1RdYwVwC4Wjb53M5L96fRwWJ8gI7YXwwiCsHTk=
github.com/doronbehar/termbox-go v0.0.0-20190817171036-93860e161317/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20191006140624-aa2cdd26fb8c h1:qvLYQAhDCaMq+XiQ+t4YLaTJtUyHC1r20odd6ryKYIk=
github.com/doronbehar/termbox-go v0.0.0-20191006140624-aa2cdd26fb8c/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05 h1:pmXx7j8+mmkFJB2+qoB1C/Mz8SWvMlHTxSWOptJrr7E=
github.com/doronbehar/termbox-go v0.0.0-20191006141301-8c9470559e05/go.mod h1:cHYbFQiZNC8LPG6clYoLMKAl0xx7KR75RPsHtG/f1Hk=
github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
gopkg.in/djherbis/times.v1 v1.2.0 h1:UCvDKl1L/fmBygl2Y7hubXCnY7t4Yj46ZrBFNUipFbM=
gopkg.in/djherbis/times.v1 v1.2.0/go.mod h1:AQlg6unIsrsCEdQYhTzERy542dz6SFdQFZFv6mUY0P8=
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"log"
"os"
"path/filepath"
"strings"
)
type iconMap map[string]string
func parseIcons() iconMap {
if env := os.Getenv("LF_ICONS"); env != "" {
return parseIconsEnv(env)
}
defaultIcons := []string{
"tw=🗀",
"st=🗀",
"ow=🗀",
"di=🗀",
"fi=🗎",
}
return parseIconsEnv(strings.Join(defaultIcons, ":"))
}
func parseIconsEnv(env string) iconMap {
icons := make(iconMap)
entries := strings.Split(env, ":")
for _, entry := range entries {
if entry == "" {
continue
}
pair := strings.Split(entry, "=")
if len(pair) != 2 {
log.Printf("invalid $LF_ICONS entry: %s", entry)
return icons
}
key, val := pair[0], pair[1]
icons[key] = val
}
return icons
}
func (im iconMap) get(f *file) string {
var key string
switch {
case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0:
key = "tw"
case f.IsDir() && f.Mode()&os.ModeSticky != 0:
key = "st"
case f.IsDir() && f.Mode()&0002 != 0:
key = "ow"
case f.IsDir():
key = "di"
case f.linkState == working:
key = "ln"
case f.linkState == broken:
key = "or"
case f.Mode()&os.ModeNamedPipe != 0:
key = "pi"
case f.Mode()&os.ModeSocket != 0:
key = "so"
case f.Mode()&os.ModeCharDevice != 0:
key = "cd"
case f.Mode()&os.ModeDevice != 0:
key = "bd"
case f.Mode()&os.ModeSetuid != 0:
key = "su"
case f.Mode()&os.ModeSetgid != 0:
key = "sg"
case f.Mode().IsRegular() && f.Mode()&0111 != 0:
key = "ex"
default:
key = "*" + filepath.Ext(f.Name())
}
if val, ok := im[key]; ok {
return val
}
if val, ok := im["fi"]; ok {
return val
}
return " "
}
+64 -20
View File
@@ -47,6 +47,7 @@ The following commands are provided by lf with default keybindings:
redraw (default '<c-l>')
reload (default '<c-r>')
read (default ':')
rename (default 'r')
shell (default '$')
shell-pipe (default '%')
shell-wait (default '!')
@@ -61,22 +62,25 @@ The following commands are provided by lf with default keybindings:
search-prev (default 'N')
mark-save (default 'm')
mark-load (default "'")
mark-remove (default `"`)
.EE
.PP
The following commands are provided by lf without default keybindings:
.PP
.EX
draw draw the ui
load load modified files and directories
sync synchronize copied/cut files with server
echo print arguments to the message line
echomsg same as echo but logging
echoerr same as echomsg but red color
cd change working directory to the argument
select change current file selection to the argument
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)
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
glob-select select files that match the given glob
glob-unselect unselect files that match the given glob
source read the configuration file in the argument
push simulate key pushes given in the argument
delete remove the current file or selected file(s)
.EE
.PP
The following command line commands are provided by lf with default keybindings:
@@ -117,6 +121,7 @@ The following options can be used to customize the behavior of lf:
dirfirst boolean (default on)
drawbox boolean (default off)
globsearch boolean (default off)
icons boolean (default off)
hidden boolean (default off)
ignorecase boolean (default on)
ignoredia boolean (default off)
@@ -126,22 +131,24 @@ The following options can be used to customize the behavior of lf:
smartcase boolean (default on)
smartdia boolean (default off)
wrapscan boolean (default on)
wrapscroll boolean (default off)
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)
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 ”)
info string (default '')
shellopts string (default '')
.EE
.PP
The following variables are exported for shell commands:
@@ -190,6 +197,9 @@ The following additional keybindings are provided by default:
map sn :set sortby natural; set info
map ss :set sortby size; set info size
map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map gh cd ~
.EE
.PP
@@ -242,11 +252,9 @@ The following command prefixes are used by lf:
% 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.
The same evaluator is used for the command line and the configuration file for read and shell commands. The difference is that prefixes are not necessary in the command line. Instead, different modes are provided to read corresponding commands. These modes are mapped to the prefix keys above by default.
.SH SYNTAX
Characters from '#' to newline are comments and ignored:
.PP
@@ -532,7 +540,7 @@ Lastly, there is a 'conn' command to connect the server as a client. This should
.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 marking 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.
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
@@ -557,7 +565,14 @@ By default, lf does not assign 'delete' command to a key to protect new users. Y
.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.
Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. Alternatively, you can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. Possible candidates are 'up', 'down' and their variants, 'updir', and 'open' commands. For example, you can use arrow keys to finish the search with the following mappings:
.PP
.EX
cmap <up> up
cmap <down> down
cmap <left> updir
cmap <right> open
.EE
.PP
Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial.
.PP
@@ -586,6 +601,8 @@ You may want to use either file extensions or mime types from 'file' command:
}}
.EE
.PP
You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits.
.PP
Following command is provided by default:
.PP
.EX
@@ -621,6 +638,33 @@ Since this script is called for each file selection change it needs to be as eff
.EE
.PP
Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview.
.SH CHANGING DIRECTORY
lf changes the working directory of the process to the current directory so that shell commands always work in the displayed directory. After quitting, it returns to the original directory where it is first launched like all shell programs. If you want to stay in the current directory after quitting, you can use one of the example wrapper shell scripts provided in the repository.
.PP
There is a special command 'on-cd' that runs a shell command when it is defined and the directory is changed. You can define it just as you would define any other command:
.PP
.EX
cmd on-cd &{{
# display git repository status in your prompt
source /usr/share/git/completion/git-prompt.sh
GIT_PS1_SHOWDIRTYSTATE=auto
GIT_PS1_SHOWSTASHSTATE=auto
GIT_PS1_SHOWUNTRACKEDFILES=auto
GIT_PS1_SHOWUPSTREAM=auto
git=$(__git_ps1 " (%s)") || true
fmt="\e033[32;1m%u@%h\e033[0m:\e033[34;1m%w/\e033[0m\e033[1m%f$git\e033[0m"
lf -remote "send $id set promptfmt \e"$fmt\e""
}}
.EE
.PP
This command runs whenever you change directory but not on startup. You can add an extra call to make it run on startup as well:
.PP
.EX
cmd on-cd &{{ # ... }}
on-cd
.EE
.PP
Note that all shell commands are possible but `%` and `&` are usually more appropriate as `$` and `!` causes flickers and pauses respectively.
.SH COLORSCHEMES
lf tries to automatically adapt its colors to the environment. On startup, first '$LS_COLORS' environment variable is checked. This variable is used by GNU ls to configure its colors based on file types and extensions. The value of this variable is often set by GNU dircolors in a shell configuration file. dircolors program itself can be configured with a configuration file. dircolors supports 256 colors along with common attributes such as bold and underline.
.PP
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=lf
Comment=Launches the lf file manager
Icon=utilities-terminal
Terminal=true
Exec=lf
Categories=ConsoleOnly;System;FileTools;FileManager
MimeType=inode/directory;
+21
View File
@@ -9,6 +9,7 @@ import (
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
)
var (
@@ -42,6 +43,24 @@ func init() {
}
}
func exportEnvVars() {
os.Setenv("id", strconv.Itoa(gClientID))
os.Setenv("OPENER", envOpener)
os.Setenv("EDITOR", envEditor)
os.Setenv("PAGER", envPager)
os.Setenv("SHELL", envShell)
level, err := strconv.Atoi(envLevel)
if err != nil {
log.Printf("reading lf level: %s", err)
}
level++
os.Setenv("LF_LEVEL", strconv.Itoa(level))
}
func startServer() {
cmd := detachedCommand(os.Args[0], "-server")
if err := cmd.Start(); err != nil {
@@ -162,6 +181,8 @@ func main() {
os.Exit(2)
}
exportEnvVars()
run()
}
+16 -23
View File
@@ -41,22 +41,12 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune {
return nil
}
// This function is used to escape whitespaces with backlashes in a given
// string. If a whitespace is already escaped then it is not escaped again.
// This function is used to escape whitespaces and special characters with
// backlashes in a given string.
func escape(s string) string {
esc := false
buf := make([]rune, 0, len(s))
for _, r := range s {
if r == '\\' {
esc = true
continue
}
if esc {
esc = false
buf = append(buf, '\\', r)
continue
}
if unicode.IsSpace(r) {
if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
@@ -65,26 +55,29 @@ func escape(s string) string {
}
// This function is used to remove backlashes that are used to escape
// whitespaces in a given string.
// whitespaces and special characters in a given string.
func unescape(s string) string {
esc := false
buf := make([]rune, 0, len(s))
for _, r := range s {
if esc {
if !unicode.IsSpace(r) && r != '\\' && r != ';' && r != '#' {
buf = append(buf, '\\')
}
buf = append(buf, r)
esc = false
continue
}
if r == '\\' {
esc = true
continue
}
if esc {
esc = false
if unicode.IsSpace(r) {
buf = append(buf, r)
} else {
buf = append(buf, '\\', r)
}
continue
}
esc = false
buf = append(buf, r)
}
if esc {
buf = append(buf, '\\')
}
return string(buf)
}
+14 -3
View File
@@ -80,8 +80,13 @@ func TestEscape(t *testing.T) {
{"foo", "foo"},
{"foo bar", `foo\ bar`},
{"foo bar", `foo\ \ bar`},
{`foo\ bar`, `foo\ bar`},
{`foo\bar`, `foo\bar`},
{`foo\bar`, `foo\\bar`},
{`foo\ bar`, `foo\\\ bar`},
{`foo;bar`, `foo\;bar`},
{`foo#bar`, `foo\#bar`},
{`foo\tbar`, `foo\\tbar`},
{"foo\tbar", "foo\\\tbar"},
{`foo\`, `foo\\`},
}
for _, test := range tests {
@@ -98,9 +103,15 @@ func TestUnescape(t *testing.T) {
}{
{"", ""},
{"foo", "foo"},
{`foo\bar`, `foo\bar`},
{`foo\ bar`, "foo bar"},
{`foo\ \ bar`, "foo bar"},
{`foo\\bar`, `foo\bar`},
{`foo\\\ bar`, `foo\ bar`},
{`foo\;bar`, `foo;bar`},
{`foo\#bar`, `foo#bar`},
{`foo\\tbar`, `foo\tbar`},
{"foo\\\tbar", "foo\tbar"},
{`foo\`, `foo\`},
}
for _, test := range tests {
+200 -63
View File
@@ -13,6 +13,8 @@ import (
"strconv"
"strings"
"time"
times "gopkg.in/djherbis/times.v1"
)
type linkState byte
@@ -25,9 +27,12 @@ const (
type file struct {
os.FileInfo
linkState linkState
path string
dirCount int
linkState linkState
path string
dirCount int
accessTime time.Time
changeTime time.Time
ext string
}
func readdir(path string) ([]*file, error) {
@@ -62,11 +67,29 @@ func readdir(path string) ([]*file, error) {
}
}
ts := times.Get(lstat)
at := ts.AccessTime()
var ct time.Time
// from times docs: ChangeTime() panics unless HasChangeTime() is true
if ts.HasChangeTime() {
ct = ts.ChangeTime()
} else {
// fall back to ModTime if ChangeTime cannot be determined
ct = lstat.ModTime()
}
// returns an empty string if extension could not be determined
// i.e. directories, filenames without extensions
ext := filepath.Ext(fpath)
files = append(files, &file{
FileInfo: lstat,
linkState: linkState,
path: fpath,
dirCount: -1,
FileInfo: lstat,
linkState: linkState,
path: fpath,
dirCount: -1,
accessTime: at,
changeTime: ct,
ext: ext,
})
}
@@ -82,6 +105,7 @@ type dir struct {
files []*file // displayed files in directory including or excluding hidden ones
allFiles []*file // all files in directory including hidden ones (same array as files)
sortType sortType // sort method and options from last sort
noPerm bool // whether lf has no permission to open the directory
}
func newDir(path string) *dir {
@@ -97,6 +121,7 @@ func newDir(path string) *dir {
path: path,
files: files,
allFiles: files,
noPerm: os.IsPermission(err),
}
}
@@ -122,6 +147,34 @@ func (dir *dir) sort() {
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].ModTime().Before(dir.files[j].ModTime())
})
case atimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].accessTime.Before(dir.files[j].accessTime)
})
case ctimeSort:
sort.SliceStable(dir.files, func(i, j int) bool {
return dir.files[i].changeTime.Before(dir.files[j].changeTime)
})
case extSort:
sort.SliceStable(dir.files, func(i, j int) bool {
leftExt := strings.ToLower(dir.files[i].ext)
rightExt := strings.ToLower(dir.files[j].ext)
// if the extension could not be determined (directories, files without)
// use a zero byte so that these files can be ranked higher
if leftExt == "" {
leftExt = "\x00"
}
if rightExt == "" {
rightExt = "\x00"
}
// in order to also have natural sorting with the filenames
// combine the name with the ext but have the ext at the front
left := leftExt + strings.ToLower(dir.files[i].Name())
right := rightExt + strings.ToLower(dir.files[j].Name())
return left < right
})
}
if gOpts.sortType.option&reverseSort != 0 {
@@ -144,13 +197,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
}
@@ -188,32 +241,38 @@ func (dir *dir) sel(name string, height int) {
}
type nav struct {
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
dirs []*dir
copyBytes int64
copyTotal int64
copyUpdate int
moveCount int
moveTotal int
moveUpdate int
deleteCount int
deleteTotal int
deleteUpdate int
copyBytesChan chan int64
copyTotalChan chan int64
moveCountChan chan int
moveTotalChan chan int
deleteCountChan chan int
deleteTotalChan chan int
dirChan chan *dir
regChan chan *reg
dirCache map[string]*dir
regCache map[string]*reg
saves map[string]bool
marks map[string]string
renameCache []string
selections map[string]int
selectionInd int
height int
find string
findBack bool
search string
searchBack bool
searchInd int
searchPos int
}
func (nav *nav) loadDir(path string) *dir {
@@ -281,19 +340,22 @@ func newNav(height int) *nav {
}
nav := &nav{
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,
copyBytesChan: make(chan int64, 1024),
copyTotalChan: make(chan int64, 1024),
moveCountChan: make(chan int, 1024),
moveTotalChan: make(chan int, 1024),
deleteCountChan: make(chan int, 1024),
deleteTotalChan: 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),
renameCache: make([]string, 2),
selections: make(map[string]int),
selectionInd: 0,
height: height,
}
nav.getDirs(wd)
@@ -411,7 +473,7 @@ func (nav *nav) preview() {
nav.regChan <- reg
}
func (nav *nav) loadReg(ui *ui, path string) *reg {
func (nav *nav) loadReg(path string) *reg {
r, ok := nav.regCache[path]
if !ok {
go nav.preview()
@@ -445,6 +507,9 @@ func (nav *nav) up(dist int) {
dir := nav.currDir()
if dir.ind == 0 {
if gOpts.wrapscroll {
nav.bottom()
}
return
}
@@ -462,6 +527,9 @@ func (nav *nav) down(dist int) {
maxind := len(dir.files) - 1
if dir.ind >= maxind {
if gOpts.wrapscroll {
nav.top()
}
return
}
@@ -714,19 +782,61 @@ func (nav *nav) paste(ui *ui) error {
return nil
}
func (nav *nav) del() error {
func (nav *nav) del(ui *ui) error {
list, err := nav.currFileOrSelections()
if err != nil {
return err
}
for _, path := range list {
if err := os.RemoveAll(path); err != nil {
go func() {
echo := &callExpr{"echoerr", []string{""}, 1}
errCount := 0
nav.deleteTotalChan <- len(list)
for _, path := range list {
nav.deleteCountChan <- 1
if err := os.RemoveAll(path); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}
nav.deleteTotalChan <- -len(list)
if err := remote("send load"); err != nil {
errCount++
echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err)
ui.exprChan <- echo
}
}()
return nil
}
func (nav *nav) rename() error {
oldPath := nav.renameCache[0]
newPath := nav.renameCache[1]
dir, _ := filepath.Split(newPath)
os.MkdirAll(dir, os.ModePerm)
if _, err := os.Stat(newPath); err == nil { // file exists
if err := os.Remove(newPath); err != nil {
return err
}
}
if err := os.Rename(oldPath, newPath); err != nil {
return err
}
// TODO: change selection
if err := nav.sel(newPath); err != nil {
return err
}
return nil
}
@@ -741,7 +851,7 @@ func (nav *nav) sync() error {
nav.saves[f] = cp
}
return nil
return nav.readMarks()
}
func (nav *nav) cd(wd string) error {
@@ -762,6 +872,9 @@ func (nav *nav) cd(wd string) error {
}
func (nav *nav) sel(path string) error {
path = strings.Replace(path, "~", gUser.HomeDir, -1)
path = filepath.Clean(path)
lstat, err := os.Stat(path)
if err != nil {
return fmt.Errorf("select: %s", err)
@@ -785,6 +898,29 @@ func (nav *nav) sel(path string) error {
return nil
}
func (nav *nav) globSel(pattern string, invert bool) error {
curDir := nav.currDir()
anyMatches := false
for i := 0; i < len(curDir.files); i++ {
match, err := filepath.Match(pattern, curDir.files[i].Name())
if err != nil {
return fmt.Errorf("glob-select: %s", err)
}
if match {
anyMatches = true
fpath := filepath.Join(curDir.path, curDir.files[i].Name())
if _, ok := nav.selections[fpath]; ok == invert {
nav.toggleSelection(fpath)
}
}
}
if !anyMatches {
return fmt.Errorf("glob-select: pattern not found: %s", pattern)
}
return nil
}
func findMatch(name, pattern string) bool {
if gOpts.ignorecase {
lpattern := strings.ToLower(pattern)
@@ -942,7 +1078,16 @@ func (nav *nav) searchPrev() error {
return nil
}
func (nav *nav) removeMark(mark string) error {
if _, ok := nav.marks[mark]; ok {
delete(nav.marks, mark)
return nil
}
return fmt.Errorf("no such mark")
}
func (nav *nav) readMarks() error {
nav.marks = make(map[string]string)
f, err := os.Open(gMarksPath)
if os.IsNotExist(err) {
return nil
@@ -968,14 +1113,6 @@ func (nav *nav) readMarks() error {
}
func (nav *nav) writeMarks() error {
if len(nav.marks) == 0 {
return nil
}
if err := nav.readMarks(); err != nil {
return fmt.Errorf("reading marks file: %s", err)
}
if err := os.MkdirAll(filepath.Dir(gMarksPath), os.ModePerm); err != nil {
return fmt.Errorf("creating data directory: %s", err)
}
+18
View File
@@ -9,6 +9,9 @@ const (
nameSort
sizeSort
timeSort
atimeSort
ctimeSort
extSort
)
type sortOption byte
@@ -30,6 +33,7 @@ var gOpts struct {
dircounts bool
drawbox bool
globsearch bool
icons bool
ignorecase bool
incsearch bool
preview bool
@@ -37,12 +41,14 @@ var gOpts struct {
ignoredia bool
smartdia bool
wrapscan bool
wrapscroll bool
number bool
relativenumber bool
findlen int
period int
scrolloff int
tabstop int
errorfmt string
filesep string
ifs string
previewer string
@@ -64,6 +70,7 @@ func init() {
gOpts.dircounts = false
gOpts.drawbox = false
gOpts.globsearch = false
gOpts.icons = false
gOpts.ignorecase = true
gOpts.incsearch = false
gOpts.preview = true
@@ -71,11 +78,17 @@ func init() {
gOpts.ignoredia = false
gOpts.smartdia = false
gOpts.wrapscan = true
gOpts.wrapscroll = false
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
@@ -129,6 +142,8 @@ func init() {
gOpts.keys["N"] = &callExpr{"search-prev", nil, 1}
gOpts.keys["m"] = &callExpr{"mark-save", nil, 1}
gOpts.keys["'"] = &callExpr{"mark-load", nil, 1}
gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1}
gOpts.keys[`r`] = &callExpr{"rename", nil, 1}
gOpts.keys["<c-n>"] = &callExpr{"cmd-history-next", nil, 1}
gOpts.keys["<c-p>"] = &callExpr{"cmd-history-prev", nil, 1}
@@ -141,6 +156,9 @@ func init() {
gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}}
gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}}
gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}}
gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}}
gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}}
gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}}
gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1}
gOpts.cmdkeys = make(map[string]expr)
+19
View File
@@ -10,6 +10,7 @@ import (
"os/user"
"path/filepath"
"runtime"
"strings"
)
var (
@@ -131,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)
}
}
+27 -4
View File
@@ -1,6 +1,7 @@
package main
import (
"fmt"
"log"
"os"
"os/exec"
@@ -17,9 +18,7 @@ var (
envShell = os.Getenv("SHELL")
)
var (
envPathExt = os.Getenv("PATHEXT")
)
var envPathExt = os.Getenv("PATHEXT")
var (
gDefaultShell = "cmd"
@@ -36,7 +35,7 @@ var (
func init() {
if envOpener == "" {
envOpener = "start"
envOpener = `start ""`
}
if envEditor == "" {
@@ -114,3 +113,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 -21
View File
@@ -216,25 +216,24 @@ scan:
for !s.eof && s.chr != '"' {
if s.chr == '\\' {
s.next()
switch s.chr {
case '"', '\\':
switch {
case s.chr == '"' || s.chr == '\\':
buf = append(buf, s.chr)
case 'a':
case s.chr == 'a':
buf = append(buf, '\a')
case 'b':
case s.chr == 'b':
buf = append(buf, '\b')
case 'f':
case s.chr == 'f':
buf = append(buf, '\f')
case 'n':
case s.chr == 'n':
buf = append(buf, '\n')
case 'r':
case s.chr == 'r':
buf = append(buf, '\r')
case 't':
case s.chr == 't':
buf = append(buf, '\t')
case 'v':
case s.chr == 'v':
buf = append(buf, '\v')
}
if isDigit(s.chr) {
case isDigit(s.chr):
var oct []byte
for isDigit(s.chr) {
oct = append(oct, s.chr)
@@ -245,13 +244,15 @@ scan:
log.Printf("scanning: %s", err)
}
buf = append(buf, byte(n))
} else {
s.next()
continue
default:
buf = append(buf, '\\', s.chr)
}
} else {
buf = append(buf, s.chr)
s.next()
continue
}
buf = append(buf, s.chr)
s.next()
}
s.typ = tokenIdent
s.tok = string(buf)
@@ -293,12 +294,9 @@ scan:
for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' {
if s.chr == '\\' {
s.next()
if isSpace(s.chr) {
buf = append(buf, s.chr)
s.next()
} else {
s.next()
}
buf = append(buf, s.chr)
s.next()
continue
}
buf = append(buf, s.chr)
s.next()
+3 -2
View File
@@ -58,6 +58,7 @@ func listen(l net.Listener) {
func handleConn(c net.Conn) {
s := bufio.NewScanner(c)
Loop:
for s.Scan() {
log.Printf("listen: %s", s.Text())
word, rest := splitWord(s.Text())
@@ -71,7 +72,7 @@ func handleConn(c net.Conn) {
gCopyFile = false
default:
log.Printf("unexpected option to copy file(s): %s", s.Text())
break
break Loop
}
gFileList = nil
for s.Scan() && s.Text() != "" {
@@ -120,7 +121,7 @@ func handleConn(c net.Conn) {
c.Close()
}
gListener.Close()
break
break Loop
default:
log.Printf("listen: unexpected command: %s", word)
}
+33 -34
View File
@@ -15,8 +15,8 @@ import (
"unicode"
"unicode/utf8"
"github.com/doronbehar/termbox-go"
"github.com/mattn/go-runewidth"
"github.com/nsf/termbox-go"
)
const gEscapeCode = 27
@@ -190,8 +190,6 @@ func (win *win) printReg(reg *reg) {
for i, l := range reg.lines {
fg, bg = win.print(2, i, fg, bg, l)
}
return
}
func fileInfo(f *file, d *dir) string {
@@ -233,6 +231,10 @@ func fileInfo(f *file, d *dir) string {
}
case "time":
info = fmt.Sprintf("%s %12s", info, f.ModTime().Format("Jan _2 15:04"))
case "atime":
info = fmt.Sprintf("%s %12s", info, f.accessTime.Format("Jan _2 15:04"))
case "ctime":
info = fmt.Sprintf("%s %12s", info, f.changeTime.Format("Jan _2 15:04"))
default:
log.Printf("unknown info type: %s", s)
}
@@ -241,7 +243,7 @@ func fileInfo(f *file, d *dir) string {
return info
}
func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap) {
func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]bool, colors colorMap, icons iconMap) {
if win.w < 5 || dir == nil {
return
}
@@ -251,6 +253,11 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b
return
}
if dir.noPerm {
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "permission denied")
return
}
if len(dir.files) == 0 {
win.print(2, 0, termbox.AttrReverse, termbox.ColorDefault, "empty")
return
@@ -313,6 +320,11 @@ func (win *win) printDir(dir *dir, selections map[string]int, saves map[string]b
s = append(s, ' ')
if gOpts.icons {
s = append(s, []rune(icons.get(f))...)
s = append(s, ' ')
}
for _, r := range f.Name() {
s = append(s, r)
}
@@ -367,6 +379,7 @@ type ui struct {
keyAcc []rune
keyCount []rune
colors colorMap
icons iconMap
}
func getWidths(wtot int) []int {
@@ -448,6 +461,7 @@ func newUI() *ui {
keyChan: make(chan string, 1000),
evChan: evChan,
colors: parseColors(),
icons: parseIcons(),
}
}
@@ -499,7 +513,7 @@ func (ui *ui) echomsgf(format string, a ...interface{}) {
}
func (ui *ui) echoerr(msg string) {
ui.msg = fmt.Sprintf("\033[7;31;47m%s\033[0m", msg)
ui.msg = fmt.Sprintf(gOpts.errorfmt, msg)
log.Printf("error: %s", msg)
}
@@ -527,7 +541,7 @@ func (ui *ui) loadFile(nav *nav) {
if curr.IsDir() {
ui.dirPrev = nav.loadDir(curr.path)
} else if curr.Mode().IsRegular() {
ui.regPrev = nav.loadReg(ui, curr.path)
ui.regPrev = nav.loadReg(curr.path)
}
}
@@ -543,9 +557,11 @@ func (ui *ui) loadFileInfo(nav *nav) {
func (ui *ui) drawPromptLine(nav *nav) {
fg, bg := termbox.ColorDefault, termbox.ColorDefault
dir := nav.currDir()
pwd := strings.Replace(dir.path, gUser.HomeDir, "~", -1)
pwd := nav.currDir().path
nohome := strings.TrimPrefix(pwd, gUser.HomeDir)
if len(nohome) < len(pwd) {
pwd = "~/" + nohome
}
pwd = filepath.Clean(pwd)
var fname string
@@ -600,12 +616,16 @@ func (ui *ui) drawStatLine(nav *nav) {
progress += fmt.Sprintf(" [%d/%d]", nav.moveCount, nav.moveTotal)
}
if nav.deleteTotal > 0 {
progress += fmt.Sprintf(" [%d/%d]", nav.deleteCount, nav.deleteTotal)
}
ruler := fmt.Sprintf("%s%s %d/%d", acc, progress, ind, tot)
ui.msgWin.printRight(0, fg, bg, ruler)
}
func (ui *ui) drawBox(nav *nav) {
func (ui *ui) drawBox() {
fg, bg := termbox.ColorDefault, termbox.ColorDefault
w, h := termbox.Size()
@@ -653,7 +673,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.selections, nav.saves, ui.colors)
ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.selections, nav.saves, ui.colors, ui.icons)
}
switch ui.cmdPrefix {
@@ -679,7 +699,7 @@ func (ui *ui) draw(nav *nav) {
preview := ui.wins[len(ui.wins)-1]
if f.IsDir() {
preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors)
preview.printDir(ui.dirPrev, nav.selections, nav.saves, ui.colors, ui.icons)
} else if f.Mode().IsRegular() {
preview.printReg(ui.regPrev)
}
@@ -687,7 +707,7 @@ func (ui *ui) draw(nav *nav) {
}
if gOpts.drawbox {
ui.drawBox(nav)
ui.drawBox()
}
if ui.menuBuf != nil {
@@ -850,27 +870,6 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
case 1:
if ok {
if len(ui.keyCount) > 0 {
c, err := strconv.Atoi(string(ui.keyCount))
if err != nil {
log.Printf("converting command count: %s", err)
}
count = c
}
expr := gOpts.keys[string(ui.keyAcc)]
if e, ok := expr.(*callExpr); ok {
e.count = count
}
ch <- expr
ui.keyAcc = nil
ui.keyCount = nil
ui.menuBuf = nil
} else {
ui.menuBuf = listBinds(binds)
ch <- draw
}
default:
if ok {
if len(ui.keyCount) > 0 {