pax_global_header00006660000000000000000000000064143516567620014531gustar00rootroot0000000000000052 comment=b47cf6d5a525c39db268c2f7b77e2b7497843b17 lf-r28/000077500000000000000000000000001435165676200121075ustar00rootroot00000000000000lf-r28/.github/000077500000000000000000000000001435165676200134475ustar00rootroot00000000000000lf-r28/.github/workflows/000077500000000000000000000000001435165676200155045ustar00rootroot00000000000000lf-r28/.github/workflows/go.yml000066400000000000000000000016331435165676200166370ustar00rootroot00000000000000name: Go on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest] steps: - uses: actions/checkout@v2 with: fetch-depth: 1 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.17 - name: Build run: go build -v ./... - name: Test run: go test -v ./... - uses: dominikh/staticcheck-action@v1.2.0 with: version: "2022.1.3" install-go: false generate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: fetch-depth: 1 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.19 - name: Test `go fmt && go generate` on Go 1.19 creates no diffs run: go fmt && go generate && git diff --exit-code lf-r28/.github/workflows/release.yml000066400000000000000000000006571435165676200176570ustar00rootroot00000000000000name: Release on: push: tags: - '*' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.17 - name: Build run: gen/xbuild.sh - name: Release uses: softprops/action-gh-release@v1 with: files: dist/* env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} lf-r28/.gitignore000066400000000000000000000000351435165676200140750ustar00rootroot00000000000000lf lf.exe tags dist/ vendor/ lf-r28/LICENSE000066400000000000000000000020601435165676200131120ustar00rootroot00000000000000MIT License Copyright (c) 2016 Gökçehan Kara Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. lf-r28/README.md000066400000000000000000000065201435165676200133710ustar00rootroot00000000000000# LF [Google Groups](https://groups.google.com/forum/#!forum/lf-fm) | [Wiki](https://github.com/gokcehan/lf/wiki) | [#lf](https://web.libera.chat/#lf) (on Libera.Chat) | [#lf:matrix.org](https://matrix.to/#/#lf:matrix.org) (with IRC bridge) [![Go Report Card](https://goreportcard.com/badge/github.com/gokcehan/lf)](https://goreportcard.com/report/github.com/gokcehan/lf) [![Go Reference](https://pkg.go.dev/badge/github.com/gokcehan/lf.svg)](https://pkg.go.dev/github.com/gokcehan/lf) > This is a work in progress. Use at your own risk. `lf` (as in "list files") is a terminal file manager written in Go with a heavy inspiration from ranger file manager. See [faq](https://github.com/gokcehan/lf/wiki/FAQ) for more information and [tutorial](https://github.com/gokcehan/lf/wiki/Tutorial) for a gentle introduction with screencasts. ![multicol-screenshot](http://i.imgur.com/DaTUenu.png) ![singlecol-screenshot](http://i.imgur.com/p95xzUj.png) ## Features - Cross-platform (Linux, macOS, BSDs, Windows) - Single binary without any runtime dependencies - Fast startup and low memory footprint due to native code and static binaries - Asynchronous IO operations to avoid UI locking - Server/client architecture and remote commands to manage multiple instances - Extendable and configurable with shell commands - Customizable keybindings (vi and readline defaults) - A reasonable set of other features (see the [documentation](https://pkg.go.dev/github.com/gokcehan/lf)) ## Non-Features - Tabs or windows (better handled by window manager or terminal multiplexer) - Builtin pager/editor (better handled by your pager/editor of choice) ## Installation See [packages](https://github.com/gokcehan/lf/wiki/Packages) for community maintained packages. See [releases](https://github.com/gokcehan/lf/releases) for pre-built binaries. Building from the source requires [Go](https://go.dev/). On Unix (Go version < 1.17): ```bash env CGO_ENABLED=0 GO111MODULE=on go get -u -ldflags="-s -w" github.com/gokcehan/lf ``` On Unix (Go version >= 1.17): ```bash env CGO_ENABLED=0 go install -ldflags="-s -w" github.com/gokcehan/lf@latest ``` On Windows `cmd` (Go version < 1.17): ```cmd set CGO_ENABLED=0 set GO111MODULE=on go get -u -ldflags="-s -w" github.com/gokcehan/lf ``` On Windows `cmd` (Go version >= 1.17): ```cmd set CGO_ENABLED=0 go install -ldflags="-s -w" github.com/gokcehan/lf@latest ``` On Windows `powershell` (Go version < 1.17): ```powershell $env:CGO_ENABLED = '0' $env:GO111MODULE = 'on' go get -u -ldflags="-s -w" github.com/gokcehan/lf ``` On Windows `powershell` (Go version >= 1.17): ```powershell $env:CGO_ENABLED = '0' go install -ldflags="-s -w" github.com/gokcehan/lf@latest ``` ## Usage After the installation `lf` command should start the application in the current directory. Run `lf -help` to see command line options. Run `lf -doc` to see the [documentation](https://pkg.go.dev/github.com/gokcehan/lf). See [etc](etc) directory to integrate `lf` to your shell and/or editor. Example configuration files along with example colors and icons files can also be found in this directory. See [integrations](https://github.com/gokcehan/lf/wiki/Integrations) to integrate `lf` to other tools. See [tips](https://github.com/gokcehan/lf/wiki/Tips) for more examples. ## Contributing See [contributing](https://github.com/gokcehan/lf/wiki/Contributing) for guidelines. lf-r28/app.go000066400000000000000000000272461435165676200132310ustar00rootroot00000000000000package main import ( "bufio" "fmt" "io" "log" "os" "os/exec" "os/signal" "path/filepath" "strings" "syscall" "time" ) type cmdItem struct { prefix string value string } type app struct { ui *ui nav *nav ticker *time.Ticker quitChan chan struct{} cmd *exec.Cmd cmdIn io.WriteCloser cmdOutBuf []byte cmdHistory []cmdItem cmdHistoryBeg int cmdHistoryInd int menuCompActive bool menuComps []string menuCompInd int } func newApp(ui *ui, nav *nav) *app { quitChan := make(chan struct{}, 1) app := &app{ ui: ui, nav: nav, ticker: new(time.Ticker), quitChan: quitChan, } sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM) go func() { switch <-sigChan { case os.Interrupt: return case syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM: app.quit() os.Exit(3) return } }() return app } func (app *app) quit() { if gOpts.history { if err := app.writeHistory(); err != nil { log.Printf("writing history file: %s", err) } } if !gSingleMode { if err := remote(fmt.Sprintf("drop %d", gClientID)); err != nil { log.Printf("dropping connection: %s", err) } if gOpts.autoquit { if err := remote("quit"); err != nil { log.Printf("auto quitting server: %s", err) } } } } func (app *app) readFile(path string) { log.Printf("reading file: %s", path) f, err := os.Open(path) if err != nil { app.ui.echoerrf("opening file: %s", err) return } defer f.Close() p := newParser(f) for p.parse() { p.expr.eval(app, nil) } if p.err != nil { app.ui.echoerrf("%s", p.err) } } func loadFiles() (list []string, cp bool, err error) { files, err := os.Open(gFilesPath) if os.IsNotExist(err) { err = nil return } if err != nil { err = fmt.Errorf("opening file selections file: %s", err) return } defer files.Close() s := bufio.NewScanner(files) s.Scan() switch s.Text() { case "copy": cp = true case "move": cp = false default: err = fmt.Errorf("unexpected option to copy file(s): %s", s.Text()) return } for s.Scan() && s.Text() != "" { list = append(list, s.Text()) } if s.Err() != nil { err = fmt.Errorf("scanning file list: %s", s.Err()) return } log.Printf("loading files: %v", list) return } func saveFiles(list []string, cp bool) error { if err := os.MkdirAll(filepath.Dir(gFilesPath), os.ModePerm); err != nil { return fmt.Errorf("creating data directory: %s", err) } files, err := os.Create(gFilesPath) if err != nil { return fmt.Errorf("opening file selections file: %s", err) } defer files.Close() log.Printf("saving files: %v", list) if cp { fmt.Fprintln(files, "copy") } else { fmt.Fprintln(files, "move") } for _, f := range list { fmt.Fprintln(files, f) } return nil } func (app *app) readHistory() error { f, err := os.Open(gHistoryPath) if os.IsNotExist(err) { return nil } if err != nil { return fmt.Errorf("opening history file: %s", err) } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { toks := strings.SplitN(scanner.Text(), " ", 2) if toks[0] != ":" && toks[0] != "$" && toks[0] != "%" && toks[0] != "!" && toks[0] != "&" { continue } if len(toks) < 2 { continue } app.cmdHistory = append(app.cmdHistory, cmdItem{toks[0], toks[1]}) } app.cmdHistoryBeg = len(app.cmdHistory) if err := scanner.Err(); err != nil { return fmt.Errorf("reading history file: %s", err) } return nil } func (app *app) writeHistory() error { if len(app.cmdHistory) == 0 { return nil } local := make([]cmdItem, len(app.cmdHistory)-app.cmdHistoryBeg) copy(local, app.cmdHistory[app.cmdHistoryBeg:]) app.cmdHistory = nil if err := app.readHistory(); err != nil { return fmt.Errorf("reading history file: %s", err) } app.cmdHistory = append(app.cmdHistory, local...) if err := os.MkdirAll(filepath.Dir(gHistoryPath), os.ModePerm); err != nil { return fmt.Errorf("creating data directory: %s", err) } f, err := os.Create(gHistoryPath) if err != nil { return fmt.Errorf("creating history file: %s", err) } defer f.Close() if len(app.cmdHistory) > 1000 { app.cmdHistory = app.cmdHistory[len(app.cmdHistory)-1000:] } for _, cmd := range app.cmdHistory { _, err = f.WriteString(fmt.Sprintf("%s %s\n", cmd.prefix, cmd.value)) if err != nil { return fmt.Errorf("writing history file: %s", err) } } return nil } // This is the main event loop of the application. Expressions are read from // the client and the server on separate goroutines and sent here over channels // for evaluation. Similarly directories and regular files are also read in // separate goroutines and sent here for update. func (app *app) loop() { go app.nav.previewLoop(app.ui) go app.nav.dirPreviewLoop(app.ui) var serverChan <-chan expr if !gSingleMode { serverChan = readExpr() } app.ui.readExpr() if gConfigPath != "" { if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) { app.readFile(gConfigPath) } else { log.Printf("config file does not exist: %s", err) } } else { for _, path := range gConfigPaths { if _, err := os.Stat(path); !os.IsNotExist(err) { app.readFile(path) } } } for _, cmd := range gCommands { p := newParser(strings.NewReader(cmd)) for p.parse() { p.expr.eval(app, nil) } if p.err != nil { app.ui.echoerrf("%s", p.err) } } wd, err := os.Getwd() if err != nil { log.Printf("getting current directory: %s", err) } app.nav.getDirs(wd) app.nav.addJumpList() app.nav.init = true if gSelect != "" { go func() { lstat, err := os.Lstat(gSelect) if err != nil { app.ui.exprChan <- &callExpr{"echoerr", []string{err.Error()}, 1} } else if lstat.IsDir() { app.ui.exprChan <- &callExpr{"cd", []string{gSelect}, 1} } else { app.ui.exprChan <- &callExpr{"select", []string{gSelect}, 1} } }() } for { select { case <-app.quitChan: if app.nav.copyTotal > 0 { app.ui.echoerr("quit: copy operation in progress") continue } if app.nav.moveTotal > 0 { app.ui.echoerr("quit: move operation in progress") continue } if app.nav.deleteTotal > 0 { app.ui.echoerr("quit: delete operation in progress") continue } if cmd, ok := gOpts.cmds["on-quit"]; ok { cmd.eval(app, nil) } app.quit() app.nav.previewChan <- "" app.nav.dirPreviewChan <- nil log.Print("bye!") if gLastDirPath != "" { f, err := os.Create(gLastDirPath) if err != nil { log.Printf("opening last dir file: %s", err) } defer f.Close() _, err = f.WriteString(app.nav.currDir().path) if err != nil { log.Printf("writing last dir file: %s", err) } } return case n := <-app.nav.copyBytesChan: app.nav.copyBytes += n // n is usually 4096B so update roughly per 4096B x 1024 = 4MB copied if app.nav.copyUpdate++; app.nav.copyUpdate >= 1024 { app.nav.copyUpdate = 0 app.ui.draw(app.nav) } case n := <-app.nav.copyTotalChan: app.nav.copyTotal += n if n < 0 { app.nav.copyBytes += n } if app.nav.copyTotal == 0 { app.nav.copyUpdate = 0 } app.ui.draw(app.nav) case n := <-app.nav.moveCountChan: app.nav.moveCount += n if app.nav.moveUpdate++; app.nav.moveUpdate >= 1000 { app.nav.moveUpdate = 0 app.ui.draw(app.nav) } case n := <-app.nav.moveTotalChan: app.nav.moveTotal += n if n < 0 { app.nav.moveCount += n } if app.nav.moveTotal == 0 { app.nav.moveUpdate = 0 } app.ui.draw(app.nav) case n := <-app.nav.deleteCountChan: app.nav.deleteCount += n if app.nav.deleteUpdate++; app.nav.deleteUpdate >= 1000 { app.nav.deleteUpdate = 0 app.ui.draw(app.nav) } case n := <-app.nav.deleteTotalChan: app.nav.deleteTotal += n if n < 0 { app.nav.deleteCount += n } if app.nav.deleteTotal == 0 { app.nav.deleteUpdate = 0 } app.ui.draw(app.nav) case d := <-app.nav.dirChan: app.nav.checkDir(d) if gOpts.dircache { prev, ok := app.nav.dirCache[d.path] if ok { d.ind = prev.ind d.sel(prev.name(), app.nav.height) } app.nav.dirCache[d.path] = d } for i := range app.nav.dirs { if app.nav.dirs[i].path == d.path { app.nav.dirs[i] = d } } app.nav.position() curr, err := app.nav.currFile() if err == nil { if d.path == app.nav.currDir().path { app.ui.loadFile(app, true) if app.ui.msg == "" { app.ui.loadFileInfo(app.nav) } } if d.path == curr.path { app.ui.dirPrev = d } } app.ui.draw(app.nav) case r := <-app.nav.regChan: app.nav.checkReg(r) app.nav.regCache[r.path] = r curr, err := app.nav.currFile() if err == nil { if r.path == curr.path { app.ui.regPrev = r } } app.ui.draw(app.nav) case ev := <-app.ui.evChan: e := app.ui.readEvent(ev, app.nav) if e == nil { continue } e.eval(app, nil) loop: for { select { case ev := <-app.ui.evChan: e = app.ui.readEvent(ev, app.nav) if e == nil { continue } e.eval(app, nil) default: break loop } } app.ui.draw(app.nav) case e := <-app.ui.exprChan: e.eval(app, nil) app.ui.draw(app.nav) case e := <-serverChan: e.eval(app, nil) app.ui.draw(app.nav) case <-app.ticker.C: app.nav.renew() app.ui.loadFile(app, false) app.ui.draw(app.nav) } } } // This function is used to run a shell command. Modes are as follows: // // Prefix Wait Async Stdin Stdout Stderr UI action // $ No No Yes Yes Yes Pause and then resume // % No No Yes Yes Yes Statline for input/output // ! Yes No Yes Yes Yes Pause and then resume // & No Yes No No No Do nothing func (app *app) runShell(s string, args []string, prefix string) { app.nav.exportFiles() app.ui.exportSizes() exportOpts() cmd := shellCommand(s, args) var out io.Reader var err error switch prefix { case "$", "!": cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr app.nav.previewChan <- "" app.nav.dirPreviewChan <- nil if err := app.ui.suspend(); err != nil { log.Printf("suspend: %s", err) } defer func() { if err := app.ui.resume(); err != nil { app.quit() os.Exit(3) return } }() defer app.nav.renew() err = cmd.Run() case "%": shellSetPG(cmd) if app.ui.cmdPrefix == ">" { return } stdin, err := cmd.StdinPipe() if err != nil { log.Printf("writing stdin: %s", err) } app.cmdIn = stdin stdout, err := cmd.StdoutPipe() if err != nil { log.Printf("reading stdout: %s", err) } out = stdout cmd.Stderr = cmd.Stdout fallthrough case "&": shellSetPG(cmd) err = cmd.Start() } if err != nil { app.ui.echoerrf("running shell: %s", err) } switch prefix { case "!": anyKey() } app.ui.loadFile(app, true) switch prefix { case "%": normal(app) app.cmd = cmd app.cmdOutBuf = nil app.ui.msg = "" app.ui.cmdPrefix = ">" go func() { eol := false reader := bufio.NewReader(out) for { b, err := reader.ReadByte() if err == io.EOF { break } if eol { eol = false app.cmdOutBuf = nil } app.cmdOutBuf = append(app.cmdOutBuf, b) if b == '\n' || b == '\r' { eol = true } if reader.Buffered() > 0 { continue } app.ui.exprChan <- &callExpr{"echo", []string{string(app.cmdOutBuf)}, 1} } if err := cmd.Wait(); err != nil { log.Printf("running shell: %s", err) } app.cmd = nil app.ui.cmdPrefix = "" app.ui.exprChan <- &callExpr{"load", nil, 1} }() case "&": go func() { if err := cmd.Wait(); err != nil { log.Printf("running shell: %s", err) } }() } } lf-r28/client.go000066400000000000000000000044721435165676200137230ustar00rootroot00000000000000package main import ( "bufio" "fmt" "io" "io/ioutil" "log" "net" "os" "strings" "time" "github.com/gdamore/tcell/v2" ) func run() { var screen tcell.Screen var err error if screen, err = tcell.NewScreen(); err != nil { log.Fatalf("creating screen: %s", err) } else if err = screen.Init(); err != nil { log.Fatalf("initializing screen: %s", err) } if gOpts.mouse { screen.EnableMouse() } if gLogPath != "" { f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { panic(err) } defer f.Close() log.SetOutput(f) } else { log.SetOutput(ioutil.Discard) } log.Print("hi!") ui := newUI(screen) nav := newNav(ui.wins[0].h) app := newApp(ui, nav) if err := nav.sync(); err != nil { app.ui.echoerrf("sync: %s", err) } if err := app.nav.readMarks(); err != nil { app.ui.echoerrf("reading marks file: %s", err) } if err := app.nav.readTags(); err != nil { app.ui.echoerrf("reading tags file: %s", err) } if err := app.readHistory(); err != nil { app.ui.echoerrf("reading history file: %s", err) } app.loop() app.ui.screen.Fini() } func readExpr() <-chan expr { ch := make(chan expr) go func() { duration := 1 * time.Second c, err := net.Dial(gSocketProt, gSocketPath) for err != nil { log.Printf("connecting server: %s", err) time.Sleep(duration) duration *= 2 c, err = net.Dial(gSocketProt, gSocketPath) } fmt.Fprintf(c, "conn %d\n", gClientID) ch <- &callExpr{"sync", nil, 1} s := bufio.NewScanner(c) for s.Scan() { log.Printf("recv: %s", s.Text()) p := newParser(strings.NewReader(s.Text())) if p.parse() { ch <- p.expr } } c.Close() }() return ch } func remote(cmd string) error { c, err := net.Dial(gSocketProt, gSocketPath) if err != nil { return fmt.Errorf("dialing to send server: %s", err) } fmt.Fprintln(c, cmd) // XXX: Standard net.Conn interface does not include a CloseWrite method // but net.UnixConn and net.TCPConn implement it so the following should be // safe as long as we do not use other types of connections. We need // CloseWrite to notify the server that this is not a persistent connection // and it should be closed after the response. if v, ok := c.(interface { CloseWrite() error }); ok { v.CloseWrite() } io.Copy(os.Stdout, c) c.Close() return nil } lf-r28/colors.go000066400000000000000000000157121435165676200137450ustar00rootroot00000000000000package main import ( "log" "os" "path/filepath" "strconv" "strings" "github.com/gdamore/tcell/v2" ) type styleMap map[string]tcell.Style func parseStyles() styleMap { sm := make(styleMap) // Default values from dircolors // // no* NORMAL 00 // fi FILE 00 // rs* RESET 0 // di DIR 01;34 // ln LINK 01;36 // mh* MULTIHARDLINK 00 // pi FIFO 40;33 // so SOCK 01;35 // do* DOOR 01;35 // bd BLK 40;33;01 // cd CHR 40;33;01 // or ORPHAN 40;31;01 // mi* MISSING 00 // su SETUID 37;41 // sg SETGID 30;43 // ca* CAPABILITY 30;41 // tw STICKY_OTHER_WRITABLE 30;42 // ow OTHER_WRITABLE 34;42 // st STICKY 37;44 // ex EXEC 01;32 // // (Entries marked with * are not implemented in lf) // default values from dircolors with background colors removed defaultColors := []string{ "fi=00", "di=01;34", "ln=01;36", "pi=33", "so=01;35", "bd=33;01", "cd=33;01", "or=31;01", "su=01;32", "sg=01;32", "tw=01;34", "ow=01;34", "st=01;34", "ex=01;32", } sm.parseGNU(strings.Join(defaultColors, ":")) if env := os.Getenv("LSCOLORS"); env != "" { sm.parseBSD(env) } if env := os.Getenv("LS_COLORS"); env != "" { sm.parseGNU(env) } if env := os.Getenv("LF_COLORS"); env != "" { sm.parseGNU(env) } for _, path := range gColorsPaths { if _, err := os.Stat(path); !os.IsNotExist(err) { sm.parseFile(path) } } return sm } func applyAnsiCodes(s string, st tcell.Style) tcell.Style { toks := strings.Split(s, ";") var nums []int for _, tok := range toks { if tok == "" { nums = append(nums, 0) continue } n, err := strconv.Atoi(tok) if err != nil { log.Printf("converting escape code: %s", err) continue } nums = append(nums, n) } // ECMA-48 details the standard // TODO: should we support turning off attributes? // Probably because this is used for previewers too for i := 0; i < len(nums); i++ { n := nums[i] switch { case n == 0: st = tcell.StyleDefault case n == 1: st = st.Bold(true) case n == 2: st = st.Dim(true) case n == 3: st = st.Italic(true) case n == 4: st = st.Underline(true) case n == 5 || n == 6: st = st.Blink(true) case n == 7: st = st.Reverse(true) case n == 8: // TODO: tcell PR for proper conceal _, bg, _ := st.Decompose() st = st.Foreground(bg) case n == 9: st = st.StrikeThrough(true) case n >= 30 && n <= 37: st = st.Foreground(tcell.PaletteColor(n - 30)) case n >= 90 && n <= 97: st = st.Foreground(tcell.PaletteColor(n - 82)) case n == 38: if i+3 <= len(nums) && nums[i+1] == 5 { st = st.Foreground(tcell.PaletteColor(nums[i+2])) i += 2 } else if i+5 <= len(nums) && nums[i+1] == 2 { st = st.Foreground(tcell.NewRGBColor( int32(nums[i+2]), int32(nums[i+3]), int32(nums[i+4]))) i += 4 } else { log.Printf("unknown ansi code or incorrect form: %d", n) } case n >= 40 && n <= 47: st = st.Background(tcell.PaletteColor(n - 40)) case n >= 100 && n <= 107: st = st.Background(tcell.PaletteColor(n - 92)) case n == 48: if i+3 <= len(nums) && nums[i+1] == 5 { st = st.Background(tcell.PaletteColor(nums[i+2])) i += 2 } else if i+5 <= len(nums) && nums[i+1] == 2 { st = st.Background(tcell.NewRGBColor( int32(nums[i+2]), int32(nums[i+3]), int32(nums[i+4]))) i += 4 } else { log.Printf("unknown ansi code or incorrect form: %d", n) } default: log.Printf("unknown ansi code: %d", n) } } return st } func (sm styleMap) parseFile(path string) { log.Printf("reading file: %s", path) f, err := os.Open(path) if err != nil { log.Printf("opening colors file: %s", err) return } defer f.Close() pairs, err := readPairs(f) if err != nil { log.Printf("reading colors file: %s", err) return } for _, pair := range pairs { key, val := pair[0], pair[1] key = replaceTilde(key) if filepath.IsAbs(key) { key = filepath.Clean(key) } sm[key] = applyAnsiCodes(val, tcell.StyleDefault) } } // This function parses $LS_COLORS environment variable. func (sm styleMap) parseGNU(env string) { for _, entry := range strings.Split(env, ":") { if entry == "" { continue } pair := strings.Split(entry, "=") if len(pair) != 2 { log.Printf("invalid $LS_COLORS entry: %s", entry) return } key, val := pair[0], pair[1] key = replaceTilde(key) if filepath.IsAbs(key) { key = filepath.Clean(key) } sm[key] = applyAnsiCodes(val, tcell.StyleDefault) } } // This function parses $LSCOLORS environment variable. func (sm styleMap) parseBSD(env string) { if len(env) != 22 { log.Printf("invalid $LSCOLORS variable: %s", env) return } colorNames := []string{"di", "ln", "so", "pi", "ex", "bd", "cd", "su", "sg", "tw", "ow"} getStyle := func(r1, r2 byte) tcell.Style { st := tcell.StyleDefault switch { case r1 == 'x': st = st.Foreground(tcell.ColorDefault) case 'A' <= r1 && r1 <= 'H': st = st.Foreground(tcell.PaletteColor(int(r1 - 'A'))).Bold(true) case 'a' <= r1 && r1 <= 'h': st = st.Foreground(tcell.PaletteColor(int(r1 - 'a'))) default: log.Printf("invalid $LSCOLORS entry: %c", r1) return tcell.StyleDefault } switch { case r2 == 'x': st = st.Background(tcell.ColorDefault) case 'a' <= r2 && r2 <= 'h': st = st.Background(tcell.PaletteColor(int(r2 - 'a'))) default: log.Printf("invalid $LSCOLORS entry: %c", r2) return tcell.StyleDefault } return st } for i, key := range colorNames { sm[key] = getStyle(env[i*2], env[i*2+1]) } } func (sm styleMap) get(f *file) tcell.Style { if val, ok := sm[f.path]; ok { return val } if f.IsDir() { if val, ok := sm[f.Name()+"/"]; ok { return val } } var key string switch { case f.linkState == working: key = "ln" case f.linkState == broken: key = "or" case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0: key = "tw" case f.IsDir() && f.Mode()&0002 != 0: key = "ow" case f.IsDir() && f.Mode()&os.ModeSticky != 0: key = "st" case f.IsDir(): key = "di" case f.Mode()&os.ModeNamedPipe != 0: key = "pi" case f.Mode()&os.ModeSocket != 0: key = "so" case f.Mode()&os.ModeDevice != 0: key = "bd" case f.Mode()&os.ModeCharDevice != 0: key = "cd" case f.Mode()&os.ModeSetuid != 0: key = "su" case f.Mode()&os.ModeSetgid != 0: key = "sg" case f.Mode()&0111 != 0: key = "ex" } if val, ok := sm[key]; ok { return val } if val, ok := sm[f.Name()+"*"]; ok { return val } if val, ok := sm["*"+f.Name()]; ok { return val } if val, ok := sm[filepath.Base(f.Name())+".*"]; ok { return val } if val, ok := sm["*"+strings.ToLower(f.ext)]; ok { return val } if val, ok := sm["fi"]; ok { return val } return tcell.StyleDefault } lf-r28/colors_test.go000066400000000000000000000062441435165676200150040ustar00rootroot00000000000000package main import ( "testing" "github.com/gdamore/tcell/v2" ) func TestApplyAnsiCodes(t *testing.T) { none := tcell.StyleDefault tests := []struct { s string st tcell.Style stExp tcell.Style }{ {"", none, none}, {"", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none}, {"", none.Bold(true), none}, {"", none.Foreground(tcell.ColorMaroon).Bold(true), none}, {"0", none, none}, {"0", none.Foreground(tcell.ColorMaroon).Background(tcell.ColorMaroon), none}, {"0", none.Bold(true), none}, {"0", none.Foreground(tcell.ColorMaroon).Bold(true), none}, {"1", none, none.Bold(true)}, {"4", none, none.Underline(true)}, {"7", none, none.Reverse(true)}, {"1", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Bold(true)}, {"4", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Underline(true)}, {"7", none.Foreground(tcell.ColorMaroon), none.Foreground(tcell.ColorMaroon).Reverse(true)}, {"4", none.Bold(true), none.Bold(true).Underline(true)}, {"4", none.Foreground(tcell.ColorMaroon).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true).Underline(true)}, {"31", none, none.Foreground(tcell.ColorMaroon)}, {"31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)}, {"31", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)}, {"41", none, none.Background(tcell.ColorMaroon)}, {"41", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)}, {"1;31", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, {"1;31", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, {"38;5;0", none, none.Foreground(tcell.ColorBlack)}, {"38;5;1", none, none.Foreground(tcell.ColorMaroon)}, {"38;5;8", none, none.Foreground(tcell.ColorGray)}, {"38;5;16", none, none.Foreground(tcell.Color16)}, {"38;5;232", none, none.Foreground(tcell.Color232)}, {"38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon)}, {"38;5;1", none.Foreground(tcell.ColorGreen).Bold(true), none.Foreground(tcell.ColorMaroon).Bold(true)}, {"48;5;0", none, none.Background(tcell.ColorBlack)}, {"48;5;1", none, none.Background(tcell.ColorMaroon)}, {"48;5;8", none, none.Background(tcell.ColorGray)}, {"48;5;16", none, none.Background(tcell.Color16)}, {"48;5;232", none, none.Background(tcell.Color232)}, {"48;5;1", none.Background(tcell.ColorGreen), none.Background(tcell.ColorMaroon)}, {"1;38;5;1", none, none.Foreground(tcell.ColorMaroon).Bold(true)}, {"1;38;5;1", none.Foreground(tcell.ColorGreen), none.Foreground(tcell.ColorMaroon).Bold(true)}, {"38;2;5;102;8", none, none.Foreground(tcell.NewRGBColor(5, 102, 8))}, {"48;2;0;48;143", none, none.Background(tcell.NewRGBColor(0, 48, 143))}, // Fixes color construction issue: https://github.com/gokcehan/lf/pull/439#issuecomment-674409446 {"38;5;34;1", none, none.Foreground(tcell.Color34).Bold(true)}, } for _, test := range tests { if stGot := applyAnsiCodes(test.s, test.st); stGot != test.stExp { t.Errorf("at input '%s' with '%v' expected '%v' but got '%v'", test.s, test.st, test.stExp, stGot) } } } lf-r28/complete.go000066400000000000000000000177511435165676200142610ustar00rootroot00000000000000package main import ( "io/ioutil" "log" "os" "path/filepath" "sort" "strings" ) var ( gCmdWords = []string{ "set", "map", "cmap", "cmd", "quit", "up", "half-up", "page-up", "scroll-up", "down", "half-down", "page-down", "scroll-down", "updir", "open", "jump-next", "jump-prev", "top", "bottom", "high", "middle", "low", "toggle", "invert", "unselect", "glob-select", "glob-unselect", "calcdirsize", "copy", "cut", "paste", "clear", "sync", "draw", "redraw", "load", "reload", "echo", "echomsg", "echoerr", "cd", "select", "delete", "rename", "source", "push", "read", "shell", "shell-pipe", "shell-wait", "shell-async", "find", "find-back", "find-next", "find-prev", "search", "search-back", "search-next", "search-prev", "filter", "setfilter", "mark-save", "mark-load", "mark-remove", "tag", "tag-toggle", "cmd-escape", "cmd-complete", "cmd-menu-complete", "cmd-menu-complete-back", "cmd-menu-accept", "cmd-enter", "cmd-interrupt", "cmd-history-next", "cmd-history-prev", "cmd-left", "cmd-right", "cmd-home", "cmd-end", "cmd-delete", "cmd-delete-back", "cmd-delete-home", "cmd-delete-end", "cmd-delete-unix-word", "cmd-yank", "cmd-transpose", "cmd-transpose-word", "cmd-word", "cmd-word-back", "cmd-delete-word", "cmd-capitalize-word", "cmd-uppercase-word", "cmd-lowercase-word", } gOptWords = []string{ "anchorfind", "noanchorfind", "anchorfind!", "autoquit", "noautoquit", "autoquit!", "dircache", "nodircache", "dircache!", "dircounts", "nodircounts", "dircounts!", "dirfirst", "nodirfirst", "dirfirst!", "dironly", "nodironly", "dironly!", "dirpreviews", "nodirpreviews", "dirpreviews!", "drawbox", "nodrawbox", "drawbox!", "globsearch", "noglobsearch", "globsearch!", "hidden", "nohidden", "hidden!", "icons", "noicons", "icons!", "ignorecase", "noignorecase", "ignorecase!", "ignoredia", "noignoredia", "ignoredia!", "incsearch", "noincsearch", "incsearch!", "incfilter", "noincfilter", "incfilter!", "mouse", "nomouse", "mouse!", "number", "nonumber", "number!", "preview", "nopreview", "preview!", "relativenumber", "norelativenumber", "relativenumber!", "reverse", "noreverse", "reverse!", "smartcase", "nosmartcase", "smartcase!", "smartdia", "nosmartdia", "smartdia!", "waitmsg", "wrapscan", "nowrapscan", "wrapscan!", "wrapscroll", "nowrapscroll", "wrapscroll!", "findlen", "period", "scrolloff", "tabstop", "errorfmt", "filesep", "hiddenfiles", "history", "ifs", "info", "previewer", "cleaner", "promptfmt", "ratios", "selmode", "shell", "shellflag", "shellopts", "sortby", "timefmt", "tempmarks", "tagfmt", "infotimefmtnew", "infotimefmtold", "truncatechar", } ) func matchLongest(s1, s2 []rune) []rune { i := 0 for ; i < len(s1) && i < len(s2); i++ { if s1[i] != s2[i] { break } } return s1[:i] } func matchWord(s string, words []string) (matches []string, longest []rune) { for _, w := range words { if !strings.HasPrefix(w, s) { continue } matches = append(matches, w) if len(longest) != 0 { longest = matchLongest(longest, []rune(w)) } else if s != "" { longest = []rune(w + " ") } } if len(longest) == 0 { longest = []rune(s) } return } func matchExec(s string) (matches []string, longest []rune) { var words []string paths := strings.Split(envPath, string(filepath.ListSeparator)) for _, p := range paths { if _, err := os.Stat(p); os.IsNotExist(err) { continue } files, err := ioutil.ReadDir(p) if err != nil { log.Printf("reading path: %s", err) } for _, f := range files { if !strings.HasPrefix(f.Name(), s) { continue } f, err = os.Stat(filepath.Join(p, f.Name())) if err != nil { log.Printf("getting file information: %s", err) continue } if !f.Mode().IsRegular() || !isExecutable(f) { continue } log.Print(f.Name()) words = append(words, f.Name()) } } sort.Strings(words) if len(words) > 0 { uniq := words[:1] for i := 1; i < len(words); i++ { if words[i] != words[i-1] { uniq = append(uniq, words[i]) } } words = uniq } return matchWord(s, words) } func matchFile(s string) (matches []string, longest []rune) { dir := replaceTilde(s) if !filepath.IsAbs(dir) { wd, err := os.Getwd() if err != nil { log.Printf("getting current directory: %s", err) } else { dir = wd + string(filepath.Separator) + dir } } dir = filepath.Dir(unescape(dir)) files, err := ioutil.ReadDir(dir) if err != nil { log.Printf("reading directory: %s", err) } for _, f := range files { name := filepath.Join(dir, f.Name()) f, err := os.Lstat(name) if err != nil { log.Printf("getting file information: %s", err) continue } name = strings.ToLower(escape(f.Name())) _, last := filepath.Split(s) if !strings.HasPrefix(name, strings.ToLower(last)) { continue } name = f.Name() if isRoot(s) || filepath.Base(s) != s { name = filepath.Join(filepath.Dir(unescape(s)), f.Name()) } name = escape(name) item := f.Name() if f.Mode().IsDir() { item += escape(string(filepath.Separator)) } matches = append(matches, item) if longest != nil { longest = matchLongest(longest, []rune(name)) } else if s != "" { if f.Mode().IsRegular() { longest = []rune(name + " ") } else { longest = []rune(name + escape(string(filepath.Separator))) } } } if len(longest) < len([]rune(s)) { longest = []rune(s) } return } func matchCmd(s string) (matches []string, longest []rune) { words := gCmdWords for c := range gOpts.cmds { words = append(words, c) } sort.Strings(words) j := 0 for i := 1; i < len(words); i++ { if words[j] == words[i] { continue } j++ words[i], words[j] = words[j], words[i] } words = words[:j+1] matches, longest = matchWord(s, words) return } func completeCmd(acc []rune) (matches []string, longestAcc []rune) { s := string(acc) f := tokenize(s) var longest []rune switch len(f) { case 1: matches, longestAcc = matchCmd(s) case 2: switch f[0] { case "set": matches, longest = matchWord(f[1], gOptWords) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) case "map", "cmap", "cmd": longestAcc = acc default: matches, longest = matchFile(f[len(f)-1]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) } case 3: switch f[0] { case "map", "cmap": matches, longest = matchCmd(f[2]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) default: matches, longest = matchFile(f[len(f)-1]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) } default: switch f[0] { case "set", "map", "cmap", "cmd": longestAcc = acc default: matches, longest = matchFile(f[len(f)-1]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) } } return } func completeFile(acc []rune) (matches []string, longestAcc []rune) { s := string(acc) wd, err := os.Getwd() if err != nil { log.Printf("getting current directory: %s", err) } files, err := ioutil.ReadDir(wd) if err != nil { log.Printf("reading directory: %s", err) } for _, f := range files { if !strings.HasPrefix(strings.ToLower(f.Name()), strings.ToLower(s)) { continue } matches = append(matches, f.Name()) if longestAcc != nil { longestAcc = matchLongest(longestAcc, []rune(f.Name())) } else if s != "" { longestAcc = []rune(f.Name()) } } if len(longestAcc) < len(acc) { longestAcc = acc } return } func completeShell(acc []rune) (matches []string, longestAcc []rune) { s := string(acc) f := tokenize(s) var longest []rune switch len(f) { case 1: matches, longestAcc = matchExec(s) default: matches, longest = matchFile(f[len(f)-1]) longestAcc = append(acc[:len(acc)-len([]rune(f[len(f)-1]))], longest...) } return } lf-r28/complete_test.go000066400000000000000000000025241435165676200153100ustar00rootroot00000000000000package main import ( "reflect" "testing" ) func TestMatchLongest(t *testing.T) { tests := []struct { s1 string s2 string exp string }{ {"", "", ""}, {"", "foo", ""}, {"foo", "", ""}, {"foo", "bar", ""}, {"foo", "foobar", "foo"}, {"foo", "barfoo", ""}, {"foobar", "foobaz", "fooba"}, {"год", "гол", "го"}, } for _, test := range tests { if got := string(matchLongest([]rune(test.s1), []rune(test.s2))); got != test.exp { t.Errorf("at input '%s' and '%s' expected '%s' but got '%s'", test.s1, test.s2, test.exp, got) } } } func TestMatchWord(t *testing.T) { tests := []struct { s string words []string matches []string longest string }{ {"", nil, nil, ""}, {"", []string{"foo", "bar", "baz"}, []string{"foo", "bar", "baz"}, ""}, {"fo", []string{"foo", "bar", "baz"}, []string{"foo"}, "foo "}, {"ba", []string{"foo", "bar", "baz"}, []string{"bar", "baz"}, "ba"}, {"fo", []string{"bar", "baz"}, nil, "fo"}, } for _, test := range tests { m, l := matchWord(test.s, test.words) if !reflect.DeepEqual(m, test.matches) { t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.matches, m) } if ls := string(l); ls != test.longest { t.Errorf("at input '%s' with '%s' expected '%s' but got '%s'", test.s, test.words, test.longest, ls) } } } lf-r28/copy.go000066400000000000000000000050511435165676200134110ustar00rootroot00000000000000package main import ( "fmt" "io" "os" "path/filepath" ) func copySize(srcs []string) (int64, error) { var total int64 for _, src := range srcs { _, err := os.Lstat(src) if os.IsNotExist(err) { return total, fmt.Errorf("src does not exist: %q", src) } err = filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return fmt.Errorf("walk: %s", err) } total += info.Size() return nil }) if err != nil { return total, err } } return total, nil } func copyFile(src, dst string, info os.FileInfo, nums chan int64) error { buf := make([]byte, 4096) r, err := os.Open(src) if err != nil { return err } defer r.Close() w, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, info.Mode()) if err != nil { return err } for { n, err := r.Read(buf) if err != nil && err != io.EOF { w.Close() os.Remove(dst) return err } if n == 0 { break } if _, err := w.Write(buf[:n]); err != nil { return err } nums <- int64(n) } if err := w.Close(); err != nil { os.Remove(dst) return err } return nil } func copyAll(srcs []string, dstDir string) (nums chan int64, errs chan error) { nums = make(chan int64, 1024) errs = make(chan error, 1024) go func() { for _, src := range srcs { dst := filepath.Join(dstDir, filepath.Base(src)) _, err := os.Lstat(dst) if !os.IsNotExist(err) { var newPath string for i := 1; !os.IsNotExist(err); i++ { newPath = fmt.Sprintf("%s.~%d~", dst, i) _, err = os.Lstat(newPath) } dst = newPath } filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { errs <- fmt.Errorf("walk: %s", err) return nil } rel, err := filepath.Rel(src, path) if err != nil { errs <- fmt.Errorf("relative: %s", err) return nil } newPath := filepath.Join(dst, rel) if info.IsDir() { if err := os.MkdirAll(newPath, info.Mode()); err != nil { errs <- fmt.Errorf("mkdir: %s", err) } nums <- info.Size() } else if info.Mode()&os.ModeSymlink != 0 { /* Symlink */ if rlink, err := os.Readlink(path); err != nil { errs <- fmt.Errorf("symlink: %s", err) } else { if err := os.Symlink(rlink, newPath); err != nil { errs <- fmt.Errorf("symlink: %s", err) } } nums <- info.Size() } else { if err := copyFile(path, newPath, info, nums); err != nil { errs <- fmt.Errorf("copy: %s", err) } } return nil }) } close(errs) }() return nums, errs } lf-r28/diacritics.go000066400000000000000000000031431435165676200145550ustar00rootroot00000000000000package main import ( "strconv" "unicode" ) var normMap map[rune]rune func init() { normMap = make(map[rune]rune) // (not only) european appendTransliterate( "ěřůøĉĝĥĵŝŭèùÿėįųāēīūļķņģőűëïąćęłńśźżõșțčďĺľňŕšťýžéíñóúüåäöçîşûğăâđêôơưáàãảạ", "eruocghjsueuyeiuaeiulkngoueiacelnszzostcdllnrstyzeinouuaaocisugaadeoouaaaaa", ) // Vietnamese appendTransliterate( "áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ", "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd", ) } func appendTransliterate(base, norm string) { normRunes := []rune(norm) baseRunes := []rune(base) lenNorm := len(normRunes) lenBase := len(baseRunes) if lenNorm != lenBase { panic("Base and normalized strings have differend length: base=" + strconv.Itoa(lenBase) + ", norm=" + strconv.Itoa(lenNorm)) // programmer error in constant length } for i := 0; i < lenBase; i++ { normMap[baseRunes[i]] = normRunes[i] baseUpper := unicode.ToUpper(baseRunes[i]) normUpper := unicode.ToUpper(normRunes[i]) normMap[baseUpper] = normUpper } } // Remove diacritics and make lowercase. func removeDiacritics(baseString string) string { var normalizedRunes []rune for _, baseRune := range baseString { if normRune, ok := normMap[baseRune]; ok { normalizedRunes = append(normalizedRunes, normRune) } else { normalizedRunes = append(normalizedRunes, baseRune) } } return string(normalizedRunes) } lf-r28/diacritics_test.go000066400000000000000000000075531435165676200156250ustar00rootroot00000000000000package main import ( "strconv" "testing" ) // typical czech test sentence ;-) const baseTestString = "Příliš žluťoučký kůň příšerně úpěl ďábelské ódy" func TestRemoveDiacritics(t *testing.T) { testStr := baseTestString expStr := "Prilis zlutoucky kun priserne upel dabelske ody" checkRemoveDiacritics(testStr, expStr, t) // other accents (non comlete, but all I founded) testStr = "áéíóúýčďěňřšťžůåøĉĝĥĵŝŭšžõäöüàâçéèêëîïôùûüÿžščćđáéíóúąęėįųūčšžāēīūčšžļķņģáéíóúöüőűäöüëïąćęłńóśźżáàãâçéêíóõôăâîșțáäčďéíĺľňóôŕšťúýžáéíñóúüåäöâçîşûğăâđêôơưáàãảạ" expStr = "aeiouycdenrstzuaocghjsuszoaouaaceeeeiiouuuyzsccdaeiouaeeiuucszaeiucszlkngaeiouououaoueiacelnoszzaaaaceeioooaaistaacdeillnoorstuyzaeinouuaaoacisugaadeoouaaaaa" checkRemoveDiacritics(testStr, expStr, t) testStr = "ÁÉÍÓÚÝČĎĚŇŘŠŤŽŮÅØĈĜĤĴŜŬŠŽÕÄÖÜÀÂÇÉÈÊËÎÏÔÙÛÜŸŽŠČĆĐÁÉÍÓÚĄĘĖĮŲŪČŠŽĀĒĪŪČŠŽĻĶŅĢÁÉÍÓÚÖÜŐŰÄÖÜËÏĄĆĘŁŃÓŚŹŻÁÀÃÂÇÉÊÍÓÕÔĂÂÎȘȚÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽÁÉÍÑÓÚÜÅÄÖÂÇÎŞÛĞĂÂĐÊÔƠƯÁÀÃẢẠ" expStr = "AEIOUYCDENRSTZUAOCGHJSUSZOAOUAACEEEEIIOUUUYZSCCDAEIOUAEEIUUCSZAEIUCSZLKNGAEIOUOUOUAOUEIACELNOSZZAAAACEEIOOOAAISTAACDEILLNOORSTUYZAEINOUUAAOACISUGAADEOOUAAAAA" checkRemoveDiacritics(testStr, expStr, t) testStr = "áạàảãăắặằẳẵâấậầẩẫéẹèẻẽêếệềểễiíịìỉĩoóọòỏõôốộồổỗơớợờởỡúụùủũưứựừửữyýỵỳỷỹđ" expStr = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiioooooooooooooooooouuuuuuuuuuuyyyyyyd" checkRemoveDiacritics(testStr, expStr, t) testStr = "ÁẠÀẢÃĂẮẶẰẲẴÂẤẬẦẨẪÉẸÈẺẼÊẾỆỀỂỄÍỊÌỈĨÓỌÒỎÕÔỐỘỒỔỖƠỚỢỜỞỠÚỤÙỦŨƯỨỰỪỬỮÝỴỲỶỸĐ" expStr = "AAAAAAAAAAAAAAAAAEEEEEEEEEEEIIIIIOOOOOOOOOOOOOOOOOUUUUUUUUUUUYYYYYD" checkRemoveDiacritics(testStr, expStr, t) } func checkRemoveDiacritics(testStr string, expStr string, t *testing.T) { resultStr := removeDiacritics(testStr) if resultStr != expStr { t.Errorf("at input '%v' expected '%v' but got '%v'", testStr, expStr, resultStr) } } func TestSearchSettings(t *testing.T) { runSearch(t, true, false, true, true, "Veřejný", "vere", true) runSearch(t, true, false, true, false, baseTestString, "Zlutoucky", true) runSearch(t, true, false, true, false, baseTestString, "zlutoucky", true) runSearch(t, true, true, true, false, baseTestString, "Zlutoucky", false) runSearch(t, true, true, true, true, baseTestString, "zlutoucky", true) runSearch(t, false, false, true, false, baseTestString, "žlutoucky", true) runSearch(t, false, false, true, false, baseTestString, "Žlutoucky", false) runSearch(t, false, false, true, true, baseTestString, "žluťoučký", true) runSearch(t, false, false, true, false, baseTestString, "žluťoučký", true) runSearch(t, false, false, false, false, baseTestString, "žluťoučký", true) runSearch(t, false, false, false, false, baseTestString, "zlutoucky", false) runSearch(t, false, false, true, true, baseTestString, "zlutoucky", true) } func runSearch(t *testing.T, ignorecase, smartcase, ignorediacritics, smartdiacritics bool, base, pattern string, expected bool) { gOpts.ignorecase = ignorecase gOpts.smartcase = smartcase gOpts.ignoredia = ignorediacritics gOpts.smartdia = smartdiacritics matched, _ := searchMatch(base, pattern) if matched != expected { t.Errorf("False search for" + " ignorecase = " + strconv.FormatBool(gOpts.ignorecase) + ", " + " smartcase = " + strconv.FormatBool(gOpts.smartcase) + ", " + " ignoredia = " + strconv.FormatBool(gOpts.ignoredia) + ", " + " smartdia = " + strconv.FormatBool(gOpts.smartdia) + ", ") } } lf-r28/doc.go000066400000000000000000001645771435165676200132270ustar00rootroot00000000000000//go:generate gen/docstring.sh //go:generate gen/man.sh /* lf is a terminal file manager. Source code can be found in the repository at https://github.com/gokcehan/lf This documentation can either be read from terminal using 'lf -doc' or online at https://pkg.go.dev/github.com/gokcehan/lf You can also use 'doc' command (default '') inside lf to view the documentation in a pager. A man page with the same content is also available in the repository at https://github.com/gokcehan/lf/blob/master/lf.1 You can run 'lf -help' to see descriptions of command line options. # Quick Reference The following commands are provided by lf: quit (default 'q') up (default 'k' and '') half-up (default '') page-up (default '' and '') scroll-up (default '') down (default 'j' and '') half-down (default '') page-down (default '' and '') scroll-down (default '') updir (default 'h' and '') open (default 'l' and '') jump-next (default ']') jump-prev (default '[') top (default 'gg' and '') bottom (default 'G' and '') high (default 'H') middle (default 'M') low (default 'L') toggle invert (default 'v') unselect (default 'u') glob-select glob-unselect calcdirsize copy (default 'y') cut (default 'd') paste (default 'p') clear (default 'c') sync draw redraw (default '') load reload (default '') echo echomsg echoerr cd select delete (modal) rename (modal) (default 'r') source push read (modal) (default ':') shell (modal) (default '$') shell-pipe (modal) (default '%') shell-wait (modal) (default '!') shell-async (modal) (default '&') find (modal) (default 'f') find-back (modal) (default 'F') find-next (default ';') find-prev (default ',') search (modal) (default '/') search-back (modal) (default '?') search-next (default 'n') search-prev (default 'N') filter (modal) setfilter mark-save (modal) (default 'm') mark-load (modal) (default "'") mark-remove (modal) (default '"') tag tag-toggle (default 't') The following command line commands are provided by lf: cmd-escape (default '') cmd-complete (default '') cmd-menu-complete cmd-menu-complete-back cmd-menu-accept cmd-enter (default '' and '') cmd-interrupt (default '') cmd-history-next (default '') cmd-history-prev (default '') cmd-left (default '' and '') cmd-right (default '' and '') cmd-home (default '' and '') cmd-end (default '' and '') cmd-delete (default '' and '') cmd-delete-back (default '' and '') cmd-delete-home (default '') cmd-delete-end (default '') cmd-delete-unix-word (default '') cmd-yank (default '') cmd-transpose (default '') cmd-transpose-word (default '') cmd-word (default '') cmd-word-back (default '') cmd-delete-word (default '') cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') The following options can be used to customize the behavior of lf: anchorfind bool (default on) autoquit bool (default off) cleaner string (default '') dircache bool (default on) dircounts bool (default off) dirfirst bool (default on) dironly bool (default off) dirpreviews bool (default off) drawbox bool (default off) errorfmt string (default "\033[7;31;47m%s\033[0m") filesep string (default "\n") findlen int (default 1) globsearch bool (default off) hidden bool (default off) hiddenfiles []string (default '.*') history bool (default on) icons bool (default off) ifs string (default '') ignorecase bool (default on) ignoredia bool (default on) incfilter bool (default off) incsearch bool (default off) info []string (default '') infotimefmtnew string (default 'Jan _2 15:04') infotimefmtold string (default 'Jan _2 2006') mouse bool (default off) number bool (default off) period int (default 0) preview bool (default on) previewer string (default '') promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m") ratios []int (default '1:2:3') relativenumber bool (default off) reverse bool (default off) scrolloff int (default 0) selmode string (default 'all') shell string (default 'sh' for Unix and 'cmd' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows) shellopts []string (default '') smartcase bool (default on) smartdia bool (default off) sortby string (default 'natural') tabstop int (default 8) tagfmt string (default "\033[31m%s\033[0m") tempmarks string (default '') timefmt string (default 'Mon Jan _2 15:04:05 2006') truncatechar string (default '~') waitmsg string (default 'Press any key to continue') wrapscan bool (default on) wrapscroll bool (default off) user_{option} string (default none) The following environment variables are exported for shell commands: f fs fx id PWD OLDPWD LF_LEVEL OPENER EDITOR PAGER SHELL lf_{option} lf_user_{option} lf_width lf_height The following special shell commands are used to customize the behavior of lf when defined: open paste rename delete pre-cd on-cd on-select on-quit The following commands/keybindings are provided by default: Unix Windows cmd open &$OPENER "$f" cmd open &%OPENER% %f% map e $$EDITOR "$f" map e $%EDITOR% %f% map i $$PAGER "$f" map i !%PAGER% %f% map w $$SHELL map w $%SHELL% The following additional keybindings are provided by default: map zh set hidden! map zr set reverse! map zn set info map zs set info size map zt set info time map za set info size:time map sn :set sortby natural; set info map ss :set sortby size; set info size map st :set sortby time; set info time map sa :set sortby atime; set info atime map sc :set sortby ctime; set info ctime map se :set sortby ext; set info map gh cd ~ map :toggle; down If the 'mouse' option is enabled, mouse buttons have the following default effects: Left mouse button Click on a file or directory to select it. Right mouse button Enter a directory or open a file. Also works on the preview window. Scroll wheel Scroll up or down. # Configuration Configuration files should be located at: OS system-wide user-specific Unix /etc/lf/lfrc ~/.config/lf/lfrc Windows C:\ProgramData\lf\lfrc C:\Users\\AppData\Local\lf\lfrc Colors file should be located at: OS system-wide user-specific Unix /etc/lf/colors ~/.config/lf/colors Windows C:\ProgramData\lf\colors C:\Users\\AppData\Local\lf\colors Icons file should be located at: OS system-wide user-specific Unix /etc/lf/icons ~/.config/lf/icons Windows C:\ProgramData\lf\icons C:\Users\\AppData\Local\lf\icons Selection file should be located at: Unix ~/.local/share/lf/files Windows C:\Users\\AppData\Local\lf\files Marks file should be located at: Unix ~/.local/share/lf/marks Windows C:\Users\\AppData\Local\lf\marks Tags file should be located at: Unix ~/.local/share/lf/tags Windows C:\Users\\AppData\Local\lf\tags History file should be located at: Unix ~/.local/share/lf/history Windows C:\Users\\AppData\Local\lf\history You can configure the default values of following variables to change these locations: $XDG_CONFIG_HOME ~/.config $XDG_DATA_HOME ~/.local/share %ProgramData% C:\ProgramData %LOCALAPPDATA% C:\Users\\AppData\Local A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example # Commands This section shows information about builtin commands. Modal commands do not take any arguments, but instead change the operation mode to read their input conveniently, and so they are meant to be assigned to keybindings. quit (default 'q') Quit lf and return to the shell. up (default 'k' and '') half-up (default '') page-up (default '' and '') scroll-up (default '') down (default 'j' and '') half-down (default '') page-down (default '' and '') scroll-down (default '') Move/scroll the current file selection upwards/downwards by one/half a page/full page. updir (default 'h' and '') Change the current working directory to the parent directory. open (default 'l' and '') If the current file is a directory, then change the current directory to it, otherwise, execute the 'open' command. A default 'open' command is provided to call the default system opener asynchronously with the current file as the argument. A custom 'open' command can be defined to override this default. jump-next (default ']') jump-prev (default '[') Change the current working directory to the next/previous jumplist item. top (default 'gg' and '') bottom (default 'G' and '') Move the current file selection to the top/bottom of the directory. high (default 'H') middle (default 'M') low (default 'L') Move the current file selection to the high/middle/low of the screen. toggle Toggle the selection of the current file or files given as arguments. invert (default 'v') Reverse the selection of all files in the current directory (i.e. 'toggle' all files). Selections in other directories are not effected by this command. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories. unselect (default 'u') Remove the selection of all files in all directories. glob-select glob-unselect Select/unselect files that match the given glob. calcdirsize Calculate the total size for each of the selected directories. Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size. If the total size of a directory is not calculated, it will be shown as '-'. copy (default 'y') If there are no selections, save the path of the current file to the copy buffer, otherwise, copy the paths of selected files. cut (default 'd') If there are no selections, save the path of the current file to the cut buffer, otherwise, copy the paths of selected files. paste (default 'p') Copy/Move files in copy/cut buffer to the current working directory. A custom 'paste' command can be defined to override this default. clear (default 'c') Clear file paths in copy/cut buffer. sync Synchronize copied/cut files with server. This command is automatically called when required. draw Draw the screen. This command is automatically called when required. redraw (default '') Synchronize the terminal and redraw the screen. load Load modified files and directories. This command is automatically called when required. reload (default '') Flush the cache and reload all files and directories. echo Print given arguments to the message line at the bottom. echomsg Print given arguments to the message line at the bottom and also to the log file. echoerr Print given arguments to the message line at the bottom as 'errorfmt' and also to the log file. cd Change the working directory to the given argument. select Change the current file selection to the given argument. delete (modal) Remove the current file or selected file(s). A custom 'delete' command can be defined to override this default. rename (modal) (default 'r') Rename the current file using the builtin method. A custom 'rename' command can be defined to override this default. source Read the configuration file given in the argument. push Simulate key pushes given in the argument. read (modal) (default ':') Read a command to evaluate. shell (modal) (default '$') Read a shell command to execute. shell-pipe (modal) (default '%') Read a shell command to execute piping its standard I/O to the bottom statline. shell-wait (modal) (default '!') Read a shell command to execute and wait for a key press in the end. shell-async (modal) (default '&') Read a shell command to execute asynchronously without standard I/O. find (modal) (default 'f') find-back (modal) (default 'F') find-next (default ';') find-prev (default ',') Read key(s) to find the appropriate file name match in the forward/backward direction and jump to the next/previous match. search (default '/') search-back (default '?') search-next (default 'n') search-prev (default 'N') Read a pattern to search for a file name match in the forward/backward direction and jump to the next/previous match. filter (modal) setfilter Command 'filter' reads a pattern to filter out and only view files matching the pattern. Command 'setfilter' does the same but uses an argument to set the filter immediately. You can supply an argument to 'filter', in order to use that as the starting prompt. mark-save (modal) (default 'm') Save the current directory as a bookmark assigned to the given key. mark-load (modal) (default "'") Change the current directory to the bookmark assigned to the given key. A special bookmark "'" holds the previous directory after a 'mark-load', 'cd', or 'select' command. mark-remove (modal) (default '"') Remove a bookmark assigned to the given key. tag Tag a file with '*' or a single width character given in the argument. You can define a new tag clearing command by combining 'tag' with 'tag-toggle' (i.e. 'cmd tag-clear :tag; tag-toggle'). tag-toggle (default 't') Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag. # Command Line Commands The prompt character specifies which of the several command-line modes you are in. For example, the 'read' command takes you to the ':' mode. When the cursor is at the first character in ':' mode, pressing one of the keys '!', '$', '%', or '&' takes you to the corresponding mode. You can go back with 'cmd-delete-back' ('' by default). The command line commands should be mostly compatible with readline keybindings. A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters. cmd-escape (default '') Quit command line mode and return to normal mode. cmd-complete (default '') Autocomplete the current word. cmd-menu-complete cmd-menu-complete-back Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap cmd-menu-complete; cmap cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options. cmd-menu-accept Accept the currently selected match in menu completion and close the menu. cmd-enter (default '' and '') Execute the current line. cmd-interrupt (default '') Interrupt the current shell-pipe command and return to the normal mode. cmd-history-next (default '') cmd-history-prev (default '') Go to next/previous item in the history. cmd-left (default '' and '') cmd-right (default '' and '') Move the cursor to the left/right. cmd-home (default '' and '') cmd-end (default '' and '') Move the cursor to the beginning/end of line. cmd-delete (default '' and '') Delete the next character. cmd-delete-back (default '' and '') Delete the previous character. When at the beginning of a prompt, returns either to normal mode or to ':' mode. cmd-delete-home (default '') cmd-delete-end (default '') Delete everything up to the beginning/end of line. cmd-delete-unix-word (default '') Delete the previous unix word. cmd-yank (default '') Paste the buffer content containing the last deleted item. cmd-transpose (default '') cmd-transpose-word (default '') Transpose the positions of last two characters/words. cmd-word (default '') cmd-word-back (default '') Move the cursor by one word in forward/backward direction. cmd-delete-word (default '') Delete the next word in forward direction. cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') Capitalize/uppercase/lowercase the current word and jump to the next word. # Options This section shows information about options to customize the behavior. Character ':' is used as the separator for list options '[]int' and '[]string'. anchorfind bool (default on) When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position. autoquit bool (default off) Automatically quit server when there are no clients left connected. cleaner string (default '') (not called if empty) Set the path of a cleaner file. The file should be executable. This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Preview clearing is disabled when the value of this option is left empty. dircache bool (default on) Cache directory contents. dircounts bool (default off) When this option is enabled, directory sizes show the number of items inside instead of the total size of the directory, which needs to be calculated for each directory using 'calcdirsize'. This information needs to be calculated by reading the directory and counting the items inside. Therefore, this option is disabled by default for performance reasons. This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information. 999 items are counted per directory at most, and bigger directories are shown as '999+'. dirfirst bool (default on) Show directories first above regular files. dironly bool (default off) If enabled, directories will also be passed to the previewer script. This allows custom previews for directories. dirpreviews bool (default off) Show only directories. drawbox bool (default off) Draw boxes around panes with box drawing characters. errorfmt string (default "\033[7;31;47m%s\033[0m") Format string of error messages shown in the bottom message line. filesep string (default "\n") File separator used in environment variables 'fs' and 'fx'. findlen int (default 1) Number of characters prompted for the find command. When this value is set to 0, find command prompts until there is only a single match left. globsearch bool (default off) When this option is enabled, search command patterns are considered as globs, otherwise they are literals. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges. Otherwise, these characters are interpreted as they are. hidden bool (default off) Show hidden files. On Unix systems, hidden files are determined by the value of 'hiddenfiles'. On Windows, only files with hidden attributes are considered hidden files. hiddenfiles []string (default '.*') List of hidden file glob patterns. Patterns can be given as relative or absolute paths. Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. In addition, if a pattern starts with '!', then its matches are excluded from hidden files. history bool (default on) Save command history. icons bool (default off) Show icons before each item in the list. ifs string (default '') Sets 'IFS' variable in shell commands. It works by adding the assignment to the beginning of the command string as "IFS='...'; ...". The reason is that 'IFS' variable is not inherited by the shell for security reasons. This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells. This option has no effect when the value is left empty. This option does not have any effect on Windows. ignorecase bool (default on) Ignore case in sorting and search patterns. ignoredia bool (default on) Ignore diacritics in sorting and search patterns. incsearch bool (default off) Jump to the first match after each keystroke during searching. incfilter bool (default off) Apply filter pattern after each keystroke during filtering. info []string (default '') List of information shown for directory items at the right side of pane. Currently supported information types are 'size', 'time', 'atime', and 'ctime'. Information is only shown when the pane width is more than twice the width of information. infotimefmtnew string (default 'Jan _2 15:04') Format string of the file time shown in the info column when it matches this year. infotimefmtold string (default 'Jan _2 2006') Format string of the file time shown in the info column when it doesn't match this year. mouse bool (default off) Send mouse events as input. number bool (default off) Show the position number for directory items at the left side of pane. When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest. period int (default 0) Set the interval in seconds for periodic checks of directory updates. This works by periodically calling the 'load' command. Note that directories are already updated automatically in many cases. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. Periodic checks are disabled when the value of this option is set to zero. preview bool (default on) Show previews of files and directories at the right most pane. If the file has more lines than the preview pane, rest of the lines are not read. Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'. previewer string (default '') (not filtered if empty) Set the path of a previewer file to filter the content of regular files for previewing. The file should be executable. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. SIGPIPE signal is sent when enough lines are read. If the previewer returns a non-zero exit code, then the preview cache for the given file is disabled. This means that if the file is selected in the future, the previewer is called once again. Preview filtering is disabled and files are displayed as they are when the value of this option is left empty. promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m") Format string of the prompt shown in the top line. Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. '%S' may be used once and will provide a spacer so that the following parts are right aligned on the screen. Home folder is shown as '~' in the working directory expansion. Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen. ratios []int (default '1:2:3') List of ratios of pane widths. Number of items in the list determines the number of panes in the ui. When 'preview' option is enabled, the right most number is used for the width of preview pane. relativenumber bool (default off) Show the position number relative to the current line. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown. reverse bool (default off) Reverse the direction of sort. selmode string (default 'all') Selection mode for commands. When set to 'all' it will use the selected files from all directories. When set to 'dir' it will only use the selected files in the current directory. scrolloff int (default 0) Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling. The current line is kept in the middle when this option is set to a large value that is bigger than the half of number of lines. A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items. shell string (default 'sh' for Unix and 'cmd' for Windows) Shell executable to use for shell commands. Shell commands are executed as 'shell shellopts shellflag command -- arguments'. shellflag string (default '-c' for Unix and '/c' for Windows) Command line flag used to pass shell commands. shellopts []string (default '') List of shell options to pass to the shell executable. smartcase bool (default on) Override 'ignorecase' option when the pattern contains an uppercase character. This option has no effect when 'ignorecase' is disabled. smartdia bool (default off) Override 'ignoredia' option when the pattern contains a character with diacritic. This option has no effect when 'ignoredia' is disabled. sortby string (default 'natural') Sort type for directories. Currently supported sort types are 'natural', 'name', 'size', 'time', 'ctime', 'atime', and 'ext'. tabstop int (default 8) Number of space characters to show for horizontal tabulation (U+0009) character. tagfmt string (default "\033[31m%s\033[0m") Format string of the tags. tempmarks string (default '') Marks to be considered temporary (e.g. 'abc' refers to marks 'a', 'b', and 'c'). These marks are not synced to other clients and they are not saved in the bookmarks file. Note that the special bookmark "'" is always treated as temporary and it does not need to be specified. timefmt string (default 'Mon Jan _2 15:04:05 2006') Format string of the file modification time shown in the bottom line. truncatechar string (default '~') Truncate character shown at the end when the file name does not fit to the pane. waitmsg string (default 'Press any key to continue') String shown after commands of shell-wait type. wrapscan bool (default on) Searching can wrap around the file list. wrapscroll bool (default off) Scrolling can wrap around the file list. user_{option} string (default none) Any option that is prefixed with 'user_' is a user defined option and can be set to any string. Inside a user defined command the value will be provided in the `lf_user_{option}` environment variable. These options are not used by lf and are not persisted. # Environment Variables The following variables are exported for shell commands: These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f'). f Current file selection as a full path. fs Selected file(s) separated with the value of 'filesep' option as full path(s). fx Selected file(s) (i.e. 'fs') if there are any selected files, otherwise current file selection (i.e. 'f'). id Id of the running client. PWD Present working directory. OLDPWD Initial working directory. LF_LEVEL The value of this variable is set to the current nesting level when you run lf from a shell spawned inside lf. You can add the value of this variable to your shell prompt to make it clear that your shell runs inside lf. For example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] && PS1="$PS1""(lf level: $LF_LEVEL) "' in your shell configuration file (e.g. '~/.bashrc'). OPENER If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others. EDITOR If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on Unix, 'notepad' in Windows. PAGER If this variable is set in the environment, use the same value, otherwise set the value to 'less' on Unix, 'more' in Windows. SHELL If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on Unix, 'cmd' in Windows. lf_{option} Value of the {option}. lf_user_{option} Value of the user_{option}. lf_width lf_height Width/Height of the terminal. # Special Commands This section shows information about special shell commands. open This shell command can be defined to override the default 'open' command when the current file is not a directory. paste This shell command can be defined to override the default 'paste' command. rename This shell command can be defined to override the default 'rename' command. delete This shell command can be defined to override the default 'delete' command. pre-cd This shell command can be defined to be executed before changing a directory. on-cd This shell command can be defined to be executed after changing a directory. on-select This shell command can be defined to be executed after the selection changes. on-quit This shell command can be defined to be executed before quit. # Prefixes The following command prefixes are used by lf: : read (default) builtin/custom command $ shell shell command % shell-pipe shell command running with the ui ! shell-wait shell command waiting for key press & shell-async shell command running asynchronously 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. # Syntax Characters from '#' to newline are comments and ignored: # comments start with '#' There are four special commands ('set', 'map', 'cmap', and 'cmd') for configuration. Command 'set' is used to set an option which can be boolean, integer, or string: set hidden # boolean on set nohidden # boolean off set hidden! # boolean toggle set scrolloff 10 # integer value set sortby time # string value w/o quotes set sortby 'time' # string value with single quotes (whitespaces) set sortby "time" # string value with double quotes (backslash escapes) Command 'map' is used to bind a key to a command which can be builtin command, custom command, or shell command: map gh cd ~ # builtin command map D trash # custom command map i $less $f # shell command map U !du -csh * # waiting shell command Command 'cmap' is used to bind a key on the command line to a command line command or any other command: cmap cmd-escape cmap set incsearch! You can delete an existing binding by leaving the expression empty: map gh # deletes 'gh' mapping cmap # deletes '' mapping Command 'cmd' is used to define a custom command: cmd usage $du -h -d1 | less You can delete an existing command by leaving the expression empty: cmd trash # deletes 'trash' command If there is no prefix then ':' is assumed: map zt set info time An explicit ':' can be provided to group statements until a newline which is especially useful for 'map' and 'cmd' commands: map st :set sortby time; set info time If you need multiline you can wrap statements in '{{' and '}}' after the proper prefix. map st :{{ set sortby time set info time }} # Key Mappings Regular keys are assigned to a command with the usual syntax: map a down Keys combined with the shift key simply use the uppercase letter: map A down Special keys are written in between '<' and '>' characters and always use lowercase letters: map down Angle brackets can be assigned with their special names: map down map down Function keys are prefixed with 'f' character: map down Keys combined with the control key are prefixed with 'c' character: map down Keys combined with the alt key are assigned in two different ways depending on the behavior of your terminal. Older terminals (e.g. xterm) may set the 8th bit of a character when the alt key is pressed. On these terminals, you can use the corresponding byte for the mapping: map á down Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key when the alt key is pressed. lf uses the escape delaying mechanism to recognize alt keys in these terminals (delay is 100ms). On these terminals, keys combined with the alt key are prefixed with 'a' character: map down Please note that, some key combinations are not possible due to the way terminals work (e.g. control and h combination sends a backspace key instead). The easiest way to find the name of a key combination is to press the key while lf is running and read the name of the key from the unknown mapping error. Mouse buttons are prefixed with 'm' character: map down # primary map down # secondary map down # middle map down map down map down map down map down Mouse wheel events are also prefixed with 'm' character: map down map down map down map down # Push Mappings The usual way to map a key sequence is to assign it to a named or unnamed command. While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times. For this reason 'push' command is provided by lf. This command is used to simulate key pushes given as its arguments. You can 'map' a key to a 'push' command with an argument to create various keybindings. This is mainly useful for two purposes. First, it can be used to map a command with a command count: map push 10j Second, it can be used to avoid typing the name when a command takes arguments: map r push :rename One thing to be careful is that since 'push' command works with keys instead of commands it is possible to accidentally create recursive bindings: map j push 2j These types of bindings create a deadlock when executed. # Shell Commands Regular shell commands are the most basic command type that is useful for many purposes. For example, we can write a shell command to move selected file(s) to trash. A first attempt to write such a command may look like this: cmd trash ${{ mkdir -p ~/.trash if [ -z "$fs" ]; then mv "$f" ~/.trash else IFS="$(printf '\n\t')"; mv $fs ~/.trash fi }} We check '$fs' to see if there are any selected files. Otherwise we just delete the current file. Since this is such a common pattern, a separate '$fx' variable is provided. We can use this variable to get rid of the conditional: cmd trash ${{ mkdir -p ~/.trash IFS="$(printf '\n\t')"; mv $fx ~/.trash }} The trash directory is checked each time the command is executed. We can move it outside of the command so it would only run once at startup: ${{ mkdir -p ~/.trash }} cmd trash ${{ IFS="$(printf '\n\t')"; mv $fx ~/.trash }} Since these are one liners, we can drop '{{' and '}}': $mkdir -p ~/.trash cmd trash $IFS="$(printf '\n\t')"; mv $fx ~/.trash Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\n"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation. # Piping Shell Commands Regular shell commands have some limitations in some cases. When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again. Also, even when there is no output or error, the ui still needs to be paused while the command is running. This can cause flickering on the screen for short commands and similar distractions for longer commands. Instead of pausing the ui, piping shell commands connects stdin, stdout, and stderr of the command to the statline in the bottom of the ui. This can be useful for programs following the Unix philosophy to give no output in the success case, and brief error messages or prompts in other cases. For example, following rename command prompts for overwrite in the statline if there is an existing file with the given name: cmd rename %mv -i $f $1 You can also output error messages in the command and it will show up in the statline. For example, an alternative rename command may look like this: cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 Note that input is line buffered and output and error are byte buffered. # Waiting Shell Commands Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished. These can be useful to see the output of a program before the ui is resumed. Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline. # Asynchronous Shell Commands Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish. Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui. # Remote Commands One of the more advanced features in lf is remote commands. All clients connect to a server on startup. It is possible to send commands to all or any of the connected clients over the common server. This is used internally to notify file selection changes to other clients. To use this feature, you need to use a client which supports communicating with a Unix domain socket. OpenBSD implementation of netcat (nc) is one such example. You can use it to send a command to the socket file: echo 'send echo hello world' | nc -U ${XDG_RUNTIME_DIR:-/tmp}/lf.${USER}.sock Since such a client may not be available everywhere, lf comes bundled with a command line flag to be used as such. When using lf, you do not need to specify the address of the socket file. This is the recommended way of using remote commands since it is shorter and immune to socket file address changes: lf -remote 'send echo hello world' In this command 'send' is used to send the rest of the string as a command to all connected clients. You can optionally give it an id number to send a command to a single client: lf -remote 'send 1234 echo hello world' All clients have a unique id number but you may not be aware of the id number when you are writing a command. For this purpose, an '$id' variable is exported to the environment for shell commands. The value of this variable is set to the process id of the client. You can use it to send a remote command from a client to the server which in return sends a command back to itself. So now you can display a message in the current client by calling the following in a shell command: lf -remote "send $id echo hello world" Since lf does not have control flow syntax, remote commands are used for such needs. For example, you can configure the number of columns in the ui with respect to the terminal width as follows: cmd recol %{{ if [ $lf_width -le 80 ]; then lf -remote "send $id set ratios 1:2" elif [ $lf_width -le 160 ]; then lf -remote "send $id set ratios 1:2:3" else lf -remote "send $id set ratios 1:2:3:5" fi }} Besides 'send' command, there is a 'quit' command to quit the server when there are no connected clients left, and a 'quit!' command to force quit the server by closing client connections first: lf -remote 'quit' lf -remote 'quit!' Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users. # File Operations lf uses 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, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are not followed. Moving is performed using the rename operation of the underlying OS. For cross-device moving, lf falls back to copying and then deletes the original files if there are no errors. 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 selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to a file. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file. You can customize copy and move operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. You can use the following example as a starting point: cmd paste %{{ load=$(cat ~/.local/share/lf/files) mode=$(echo "$load" | sed -n '1p') list=$(echo "$load" | sed '1d') if [ $mode = 'copy' ]; then cp -R $list . elif [ $mode = 'move' ]; then mv $list . rm ~/.local/share/lf/files lf -remote 'send clear' fi }} Some useful things to be considered are to use the backup ('--backup') and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls. By default, lf does not assign 'delete' command to a key to protect new users. You can customize file deletion by defining a 'delete' command. You can also assign a key to this command if you like. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file. # Searching Files There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes. Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. You can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. For example, you can use the right arrow key to finish the search and open the selected file with the following mapping: cmap :cmd-enter; open Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial. Some options effect both searching and finding. You can disable 'wrapscan' option to prevent searches to wrap around at the end of the file list. You can disable 'ignorecase' option to match cases in the pattern and the filename. This option is already automatically overridden if the pattern contains upper case characters. You can disable 'smartcase' option to disable this behavior. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters. # Opening Files You can define a an 'open' command (default 'l' and '') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command: cmd open $vi $fx It is possible to use different command types: cmd open &xdg-open $f You may want to use either file extensions or mime types from 'file' command: cmd open ${{ case $(file --mime-type -Lb $f) in text/*) vi $fx;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; esac }} You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits. Regular shell commands (i.e. '$') drop to terminal which results in a flicker for commands that finishes immediately (e.g. 'xdg-open' in the above example). If you want to use asynchronous shell commands (i.e. '&') but also want to use the terminal when necessary (e.g. 'vi' in the above exxample), you can use a remote command: cmd open &{{ case $(file --mime-type -Lb $f) in text/*) lf -remote "send $id \$vi \$fx";; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; esac }} Note, asynchronous shell commands run in their own process group by default so they do not require the manual use of 'setsid'. Following command is provided by default: cmd open &$OPENER $f You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few. # Previewing Files lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files to name a few. For coloring lf recognizes ansi escape codes. In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Output of the execution is printed in the preview pane. You may also want to use the same script in your pager mapping as well: set previewer ~/.config/lf/pv.sh map i $~/.config/lf/pv.sh $f | less -R For 'less' pager, you may instead utilize 'LESSOPEN' mechanism so that useful information about the file such as the full path of the file can still be displayed in the statusline below: set previewer ~/.config/lf/pv.sh map i $LESSOPEN='| ~/.config/lf/pv.sh %s' less -R $f Since this script is called for each file selection change it needs to be as efficient as possible and this responsibility is left to the user. You may use file extensions to determine the type of file more efficiently compared to obtaining mime types from 'file' command. Extensions can then be used to match cleanly within a conditional: #!/bin/sh case "$1" in *.tar*) tar tf "$1";; *.zip) unzip -l "$1";; *.rar) unrar l "$1";; *.7z) 7z l "$1";; *.pdf) pdftotext "$1" -;; *) highlight -O ansi "$1";; esac 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. Note that some programs may not respond well to SIGPIPE to exit with a non-zero return code and avoid caching. You may add a trailing '|| true' command to avoid such errors: highlight -O ansi "$1" || true You may also use an existing preview filter as you like. Your system may already come with a preview filter named 'lesspipe'. These filters may have a mechanism to add user customizations as well. See the related documentations for more information. # 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 lfcd wrapper shell scripts provided in the repository at https://github.com/gokcehan/lf/tree/master/etc 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%d\033[0m\033[1m%f$git\033[0m" lf -remote "send $id set promptfmt \"$fmt\"" }} If you want to print escape sequences, you may redirect 'printf' output to '/dev/tty'. The following xterm specific escape sequence sets the terminal title to the working directory: cmd on-cd &{{ printf "\033]0; $PWD\007" > /dev/tty }} 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. There is also a 'pre-cd' command, that works like 'on-cd', but is run before the directory is actually changed. # Colors lf tries to automatically adapt its colors to the environment. It starts with a default colorscheme and updates colors using values of existing environment variables possibly by overwriting its previous values. Colors are set in the following order: 1. default 2. LSCOLORS (Mac/BSD ls) 3. LS_COLORS (GNU ls) 4. LF_COLORS (lf specific) 5. colors file (lf specific) Please refer to the corresponding man pages for more information about 'LSCOLORS' and 'LS_COLORS'. 'LF_COLORS' is provided with the same syntax as 'LS_COLORS' in case you want to configure colors only for lf but not ls. This can be useful since there are some differences between ls and lf, though one should expect the same behavior for common cases. Colors file is provided for easier configuration without environment variables. This file should consist of whitespace separated pairs with '#' character to start comments until the end of line. You can configure lf colors in two different ways. First, you can only configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. Second, you can set the values of environment variables or colors file mentioned above for fine grained customization. Note that 'LS_COLORS/LF_COLORS' are more powerful than 'LSCOLORS' and they can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line. It is worth noting that lf uses as many colors advertised by your terminal's entry in terminfo or infocmp databases on your system. If an entry is not present, it falls back to an internal database. If your terminal supports 24-bit colors but either does not have a database entry or does not advertise all capabilities, you can enable support by setting the '$COLORTERM' variable to 'truecolor' or ensuring '$TERM' is set to a value that ends with '-truecolor'. Default lf colors are mostly taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. Default dircolors entries with background colors are simplified to avoid confusion with current file selection in lf. Similarly, there are only file type matchings and extension matchings are left out for simplicity. Default values are as follows given with their matching order in lf: ln 01;36 or 31;01 tw 01;34 ow 01;34 st 01;34 di 01;34 pi 33 so 01;35 bd 33;01 cd 33;01 su 01;32 sg 01;32 ex 01;32 fi 00 Note that lf first tries matching file names and then falls back to file types. The full order of matchings from most specific to least are as follows: 1. Full Path (e.g. '~/.config/lf/lfrc') 2. Dir Name (e.g. '.git/') (only matches dirs with a trailing slash at the end) 3. File Type (e.g. 'ln') (except 'fi') 4. File Name (e.g. 'README*') 5. File Name (e.g. '*README') 6. Base Name (e.g. 'README.*') 7. Extension (e.g. '*.txt') 8. Default (i.e. 'fi') For example, given a regular text file '/path/to/README.txt', the following entries are checked in the configuration and the first one to match is used: 1. '/path/to/README.txt' 2. (skipped since the file is not a directory) 3. (skipped since the file is of type 'fi') 4. 'README.txt*' 5. '*README.txt' 6. 'README.*' 7. '*.txt' 8. 'fi' Given a regular directory '/path/to/example.d', the following entries are checked in the configuration and the first one to match is used: 1. '/path/to/example.d' 2. 'example.d/' 3. 'di' 4. 'example.d*' 5. '*example.d' 6. 'example.*' 7. '*.d' 8. 'fi' Note that glob-like patterns do not actually perform glob matching due to performance reasons. For example, you can set a variable as follows: export LF_COLORS="~/Documents=01;31:~/Downloads=01;31:~/.local/share=01;31:~/.config/lf/lfrc=31:.git/=01;32:.git*=32:*.gitignore=32:*Makefile=32:README.*=33:*.txt=34:*.md=34:ln=01;36:di=01;34:ex=01;32:" Having all entries on a single line can make it hard to read. You may instead divide it to multiple lines in between double quotes by escaping newlines with backslashes as follows: export LF_COLORS="\ ~/Documents=01;31:\ ~/Downloads=01;31:\ ~/.local/share=01;31:\ ~/.config/lf/lfrc=31:\ .git/=01;32:\ .git*=32:\ *.gitignore=32:\ *Makefile=32:\ README.*=33:\ *.txt=34:\ *.md=34:\ ln=01;36:\ di=01;34:\ ex=01;32:\ " Having such a long variable definition in a shell configuration file might be undesirable. You may instead use the colors file for configuration. A sample colors file can be found at https://github.com/gokcehan/lf/blob/master/etc/colors.example You may also see the wiki page for ansi escape codes https://en.wikipedia.org/wiki/ANSI_escape_code # Icons Icons are configured using 'LF_ICONS' environment variable or an icons file. The variable uses the same syntax as 'LS_COLORS/LF_COLORS'. Instead of colors, you should put a single characters as values of entries. Icons file should consist of whitespace separated pairs with '#' character to start comments until the end of line. Do not forget to enable 'icons' option to see the icons. Default values are as follows given with their matching order in lf: ln l or l tw t ow d st t di d pi p so s bd b cd c su u sg g ex x fi - A sample icons file can be found at https://github.com/gokcehan/lf/blob/master/etc/icons.example */ package main lf-r28/docstring.go000066400000000000000000001700341435165676200144370ustar00rootroot00000000000000// Code generated by gen/docstring.sh DO NOT EDIT. package main var genDocString = ` lf is a terminal file manager. Source code can be found in the repository at https://github.com/gokcehan/lf This documentation can either be read from terminal using 'lf -doc' or online at https://pkg.go.dev/github.com/gokcehan/lf You can also use 'doc' command (default '') inside lf to view the documentation in a pager. A man page with the same content is also available in the repository at https://github.com/gokcehan/lf/blob/master/lf.1 You can run 'lf -help' to see descriptions of command line options. # Quick Reference The following commands are provided by lf: quit (default 'q') up (default 'k' and '') half-up (default '') page-up (default '' and '') scroll-up (default '') down (default 'j' and '') half-down (default '') page-down (default '' and '') scroll-down (default '') updir (default 'h' and '') open (default 'l' and '') jump-next (default ']') jump-prev (default '[') top (default 'gg' and '') bottom (default 'G' and '') high (default 'H') middle (default 'M') low (default 'L') toggle invert (default 'v') unselect (default 'u') glob-select glob-unselect calcdirsize copy (default 'y') cut (default 'd') paste (default 'p') clear (default 'c') sync draw redraw (default '') load reload (default '') echo echomsg echoerr cd select delete (modal) rename (modal) (default 'r') source push read (modal) (default ':') shell (modal) (default '$') shell-pipe (modal) (default '%') shell-wait (modal) (default '!') shell-async (modal) (default '&') find (modal) (default 'f') find-back (modal) (default 'F') find-next (default ';') find-prev (default ',') search (modal) (default '/') search-back (modal) (default '?') search-next (default 'n') search-prev (default 'N') filter (modal) setfilter mark-save (modal) (default 'm') mark-load (modal) (default "'") mark-remove (modal) (default '"') tag tag-toggle (default 't') The following command line commands are provided by lf: cmd-escape (default '') cmd-complete (default '') cmd-menu-complete cmd-menu-complete-back cmd-menu-accept cmd-enter (default '' and '') cmd-interrupt (default '') cmd-history-next (default '') cmd-history-prev (default '') cmd-left (default '' and '') cmd-right (default '' and '') cmd-home (default '' and '') cmd-end (default '' and '') cmd-delete (default '' and '') cmd-delete-back (default '' and '') cmd-delete-home (default '') cmd-delete-end (default '') cmd-delete-unix-word (default '') cmd-yank (default '') cmd-transpose (default '') cmd-transpose-word (default '') cmd-word (default '') cmd-word-back (default '') cmd-delete-word (default '') cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') The following options can be used to customize the behavior of lf: anchorfind bool (default on) autoquit bool (default off) cleaner string (default '') dircache bool (default on) dircounts bool (default off) dirfirst bool (default on) dironly bool (default off) dirpreviews bool (default off) drawbox bool (default off) errorfmt string (default "\033[7;31;47m%s\033[0m") filesep string (default "\n") findlen int (default 1) globsearch bool (default off) hidden bool (default off) hiddenfiles []string (default '.*') history bool (default on) icons bool (default off) ifs string (default '') ignorecase bool (default on) ignoredia bool (default on) incfilter bool (default off) incsearch bool (default off) info []string (default '') infotimefmtnew string (default 'Jan _2 15:04') infotimefmtold string (default 'Jan _2 2006') mouse bool (default off) number bool (default off) period int (default 0) preview bool (default on) previewer string (default '') promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m") ratios []int (default '1:2:3') relativenumber bool (default off) reverse bool (default off) scrolloff int (default 0) selmode string (default 'all') shell string (default 'sh' for Unix and 'cmd' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows) shellopts []string (default '') smartcase bool (default on) smartdia bool (default off) sortby string (default 'natural') tabstop int (default 8) tagfmt string (default "\033[31m%s\033[0m") tempmarks string (default '') timefmt string (default 'Mon Jan _2 15:04:05 2006') truncatechar string (default '~') waitmsg string (default 'Press any key to continue') wrapscan bool (default on) wrapscroll bool (default off) user_{option} string (default none) The following environment variables are exported for shell commands: f fs fx id PWD OLDPWD LF_LEVEL OPENER EDITOR PAGER SHELL lf_{option} lf_user_{option} lf_width lf_height The following special shell commands are used to customize the behavior of lf when defined: open paste rename delete pre-cd on-cd on-select on-quit The following commands/keybindings are provided by default: Unix Windows cmd open &$OPENER "$f" cmd open &%OPENER% %f% map e $$EDITOR "$f" map e $%EDITOR% %f% map i $$PAGER "$f" map i !%PAGER% %f% map w $$SHELL map w $%SHELL% The following additional keybindings are provided by default: map zh set hidden! map zr set reverse! map zn set info map zs set info size map zt set info time map za set info size:time map sn :set sortby natural; set info map ss :set sortby size; set info size map st :set sortby time; set info time map sa :set sortby atime; set info atime map sc :set sortby ctime; set info ctime map se :set sortby ext; set info map gh cd ~ map :toggle; down If the 'mouse' option is enabled, mouse buttons have the following default effects: Left mouse button Click on a file or directory to select it. Right mouse button Enter a directory or open a file. Also works on the preview window. Scroll wheel Scroll up or down. # Configuration Configuration files should be located at: OS system-wide user-specific Unix /etc/lf/lfrc ~/.config/lf/lfrc Windows C:\ProgramData\lf\lfrc C:\Users\\AppData\Local\lf\lfrc Colors file should be located at: OS system-wide user-specific Unix /etc/lf/colors ~/.config/lf/colors Windows C:\ProgramData\lf\colors C:\Users\\AppData\Local\lf\colors Icons file should be located at: OS system-wide user-specific Unix /etc/lf/icons ~/.config/lf/icons Windows C:\ProgramData\lf\icons C:\Users\\AppData\Local\lf\icons Selection file should be located at: Unix ~/.local/share/lf/files Windows C:\Users\\AppData\Local\lf\files Marks file should be located at: Unix ~/.local/share/lf/marks Windows C:\Users\\AppData\Local\lf\marks Tags file should be located at: Unix ~/.local/share/lf/tags Windows C:\Users\\AppData\Local\lf\tags History file should be located at: Unix ~/.local/share/lf/history Windows C:\Users\\AppData\Local\lf\history You can configure the default values of following variables to change these locations: $XDG_CONFIG_HOME ~/.config $XDG_DATA_HOME ~/.local/share %ProgramData% C:\ProgramData %LOCALAPPDATA% C:\Users\\AppData\Local A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example # Commands This section shows information about builtin commands. Modal commands do not take any arguments, but instead change the operation mode to read their input conveniently, and so they are meant to be assigned to keybindings. quit (default 'q') Quit lf and return to the shell. up (default 'k' and '') half-up (default '') page-up (default '' and '') scroll-up (default '') down (default 'j' and '') half-down (default '') page-down (default '' and '') scroll-down (default '') Move/scroll the current file selection upwards/downwards by one/half a page/full page. updir (default 'h' and '') Change the current working directory to the parent directory. open (default 'l' and '') If the current file is a directory, then change the current directory to it, otherwise, execute the 'open' command. A default 'open' command is provided to call the default system opener asynchronously with the current file as the argument. A custom 'open' command can be defined to override this default. jump-next (default ']') jump-prev (default '[') Change the current working directory to the next/previous jumplist item. top (default 'gg' and '') bottom (default 'G' and '') Move the current file selection to the top/bottom of the directory. high (default 'H') middle (default 'M') low (default 'L') Move the current file selection to the high/middle/low of the screen. toggle Toggle the selection of the current file or files given as arguments. invert (default 'v') Reverse the selection of all files in the current directory (i.e. 'toggle' all files). Selections in other directories are not effected by this command. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories. unselect (default 'u') Remove the selection of all files in all directories. glob-select glob-unselect Select/unselect files that match the given glob. calcdirsize Calculate the total size for each of the selected directories. Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size. If the total size of a directory is not calculated, it will be shown as '-'. copy (default 'y') If there are no selections, save the path of the current file to the copy buffer, otherwise, copy the paths of selected files. cut (default 'd') If there are no selections, save the path of the current file to the cut buffer, otherwise, copy the paths of selected files. paste (default 'p') Copy/Move files in copy/cut buffer to the current working directory. A custom 'paste' command can be defined to override this default. clear (default 'c') Clear file paths in copy/cut buffer. sync Synchronize copied/cut files with server. This command is automatically called when required. draw Draw the screen. This command is automatically called when required. redraw (default '') Synchronize the terminal and redraw the screen. load Load modified files and directories. This command is automatically called when required. reload (default '') Flush the cache and reload all files and directories. echo Print given arguments to the message line at the bottom. echomsg Print given arguments to the message line at the bottom and also to the log file. echoerr Print given arguments to the message line at the bottom as 'errorfmt' and also to the log file. cd Change the working directory to the given argument. select Change the current file selection to the given argument. delete (modal) Remove the current file or selected file(s). A custom 'delete' command can be defined to override this default. rename (modal) (default 'r') Rename the current file using the builtin method. A custom 'rename' command can be defined to override this default. source Read the configuration file given in the argument. push Simulate key pushes given in the argument. read (modal) (default ':') Read a command to evaluate. shell (modal) (default '$') Read a shell command to execute. shell-pipe (modal) (default '%') Read a shell command to execute piping its standard I/O to the bottom statline. shell-wait (modal) (default '!') Read a shell command to execute and wait for a key press in the end. shell-async (modal) (default '&') Read a shell command to execute asynchronously without standard I/O. find (modal) (default 'f') find-back (modal) (default 'F') find-next (default ';') find-prev (default ',') Read key(s) to find the appropriate file name match in the forward/backward direction and jump to the next/previous match. search (default '/') search-back (default '?') search-next (default 'n') search-prev (default 'N') Read a pattern to search for a file name match in the forward/backward direction and jump to the next/previous match. filter (modal) setfilter Command 'filter' reads a pattern to filter out and only view files matching the pattern. Command 'setfilter' does the same but uses an argument to set the filter immediately. You can supply an argument to 'filter', in order to use that as the starting prompt. mark-save (modal) (default 'm') Save the current directory as a bookmark assigned to the given key. mark-load (modal) (default "'") Change the current directory to the bookmark assigned to the given key. A special bookmark "'" holds the previous directory after a 'mark-load', 'cd', or 'select' command. mark-remove (modal) (default '"') Remove a bookmark assigned to the given key. tag Tag a file with '*' or a single width character given in the argument. You can define a new tag clearing command by combining 'tag' with 'tag-toggle' (i.e. 'cmd tag-clear :tag; tag-toggle'). tag-toggle (default 't') Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag. # Command Line Commands The prompt character specifies which of the several command-line modes you are in. For example, the 'read' command takes you to the ':' mode. When the cursor is at the first character in ':' mode, pressing one of the keys '!', '$', '%', or '&' takes you to the corresponding mode. You can go back with 'cmd-delete-back' ('' by default). The command line commands should be mostly compatible with readline keybindings. A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters. cmd-escape (default '') Quit command line mode and return to normal mode. cmd-complete (default '') Autocomplete the current word. cmd-menu-complete cmd-menu-complete-back Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap cmd-menu-complete; cmap cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options. cmd-menu-accept Accept the currently selected match in menu completion and close the menu. cmd-enter (default '' and '') Execute the current line. cmd-interrupt (default '') Interrupt the current shell-pipe command and return to the normal mode. cmd-history-next (default '') cmd-history-prev (default '') Go to next/previous item in the history. cmd-left (default '' and '') cmd-right (default '' and '') Move the cursor to the left/right. cmd-home (default '' and '') cmd-end (default '' and '') Move the cursor to the beginning/end of line. cmd-delete (default '' and '') Delete the next character. cmd-delete-back (default '' and '') Delete the previous character. When at the beginning of a prompt, returns either to normal mode or to ':' mode. cmd-delete-home (default '') cmd-delete-end (default '') Delete everything up to the beginning/end of line. cmd-delete-unix-word (default '') Delete the previous unix word. cmd-yank (default '') Paste the buffer content containing the last deleted item. cmd-transpose (default '') cmd-transpose-word (default '') Transpose the positions of last two characters/words. cmd-word (default '') cmd-word-back (default '') Move the cursor by one word in forward/backward direction. cmd-delete-word (default '') Delete the next word in forward direction. cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') Capitalize/uppercase/lowercase the current word and jump to the next word. # Options This section shows information about options to customize the behavior. Character ':' is used as the separator for list options '[]int' and '[]string'. anchorfind bool (default on) When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position. autoquit bool (default off) Automatically quit server when there are no clients left connected. cleaner string (default '') (not called if empty) Set the path of a cleaner file. The file should be executable. This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Preview clearing is disabled when the value of this option is left empty. dircache bool (default on) Cache directory contents. dircounts bool (default off) When this option is enabled, directory sizes show the number of items inside instead of the total size of the directory, which needs to be calculated for each directory using 'calcdirsize'. This information needs to be calculated by reading the directory and counting the items inside. Therefore, this option is disabled by default for performance reasons. This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information. 999 items are counted per directory at most, and bigger directories are shown as '999+'. dirfirst bool (default on) Show directories first above regular files. dironly bool (default off) If enabled, directories will also be passed to the previewer script. This allows custom previews for directories. dirpreviews bool (default off) Show only directories. drawbox bool (default off) Draw boxes around panes with box drawing characters. errorfmt string (default "\033[7;31;47m%s\033[0m") Format string of error messages shown in the bottom message line. filesep string (default "\n") File separator used in environment variables 'fs' and 'fx'. findlen int (default 1) Number of characters prompted for the find command. When this value is set to 0, find command prompts until there is only a single match left. globsearch bool (default off) When this option is enabled, search command patterns are considered as globs, otherwise they are literals. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges. Otherwise, these characters are interpreted as they are. hidden bool (default off) Show hidden files. On Unix systems, hidden files are determined by the value of 'hiddenfiles'. On Windows, only files with hidden attributes are considered hidden files. hiddenfiles []string (default '.*') List of hidden file glob patterns. Patterns can be given as relative or absolute paths. Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. In addition, if a pattern starts with '!', then its matches are excluded from hidden files. history bool (default on) Save command history. icons bool (default off) Show icons before each item in the list. ifs string (default '') Sets 'IFS' variable in shell commands. It works by adding the assignment to the beginning of the command string as "IFS='...'; ...". The reason is that 'IFS' variable is not inherited by the shell for security reasons. This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells. This option has no effect when the value is left empty. This option does not have any effect on Windows. ignorecase bool (default on) Ignore case in sorting and search patterns. ignoredia bool (default on) Ignore diacritics in sorting and search patterns. incsearch bool (default off) Jump to the first match after each keystroke during searching. incfilter bool (default off) Apply filter pattern after each keystroke during filtering. info []string (default '') List of information shown for directory items at the right side of pane. Currently supported information types are 'size', 'time', 'atime', and 'ctime'. Information is only shown when the pane width is more than twice the width of information. infotimefmtnew string (default 'Jan _2 15:04') Format string of the file time shown in the info column when it matches this year. infotimefmtold string (default 'Jan _2 2006') Format string of the file time shown in the info column when it doesn't match this year. mouse bool (default off) Send mouse events as input. number bool (default off) Show the position number for directory items at the left side of pane. When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest. period int (default 0) Set the interval in seconds for periodic checks of directory updates. This works by periodically calling the 'load' command. Note that directories are already updated automatically in many cases. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. Periodic checks are disabled when the value of this option is set to zero. preview bool (default on) Show previews of files and directories at the right most pane. If the file has more lines than the preview pane, rest of the lines are not read. Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'. previewer string (default '') (not filtered if empty) Set the path of a previewer file to filter the content of regular files for previewing. The file should be executable. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. SIGPIPE signal is sent when enough lines are read. If the previewer returns a non-zero exit code, then the preview cache for the given file is disabled. This means that if the file is selected in the future, the previewer is called once again. Preview filtering is disabled and files are displayed as they are when the value of this option is left empty. promptfmt string (default "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m") Format string of the prompt shown in the top line. Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. '%S' may be used once and will provide a spacer so that the following parts are right aligned on the screen. Home folder is shown as '~' in the working directory expansion. Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen. ratios []int (default '1:2:3') List of ratios of pane widths. Number of items in the list determines the number of panes in the ui. When 'preview' option is enabled, the right most number is used for the width of preview pane. relativenumber bool (default off) Show the position number relative to the current line. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown. reverse bool (default off) Reverse the direction of sort. selmode string (default 'all') Selection mode for commands. When set to 'all' it will use the selected files from all directories. When set to 'dir' it will only use the selected files in the current directory. scrolloff int (default 0) Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling. The current line is kept in the middle when this option is set to a large value that is bigger than the half of number of lines. A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items. shell string (default 'sh' for Unix and 'cmd' for Windows) Shell executable to use for shell commands. Shell commands are executed as 'shell shellopts shellflag command -- arguments'. shellflag string (default '-c' for Unix and '/c' for Windows) Command line flag used to pass shell commands. shellopts []string (default '') List of shell options to pass to the shell executable. smartcase bool (default on) Override 'ignorecase' option when the pattern contains an uppercase character. This option has no effect when 'ignorecase' is disabled. smartdia bool (default off) Override 'ignoredia' option when the pattern contains a character with diacritic. This option has no effect when 'ignoredia' is disabled. sortby string (default 'natural') Sort type for directories. Currently supported sort types are 'natural', 'name', 'size', 'time', 'ctime', 'atime', and 'ext'. tabstop int (default 8) Number of space characters to show for horizontal tabulation (U+0009) character. tagfmt string (default "\033[31m%s\033[0m") Format string of the tags. tempmarks string (default '') Marks to be considered temporary (e.g. 'abc' refers to marks 'a', 'b', and 'c'). These marks are not synced to other clients and they are not saved in the bookmarks file. Note that the special bookmark "'" is always treated as temporary and it does not need to be specified. timefmt string (default 'Mon Jan _2 15:04:05 2006') Format string of the file modification time shown in the bottom line. truncatechar string (default '~') Truncate character shown at the end when the file name does not fit to the pane. waitmsg string (default 'Press any key to continue') String shown after commands of shell-wait type. wrapscan bool (default on) Searching can wrap around the file list. wrapscroll bool (default off) Scrolling can wrap around the file list. user_{option} string (default none) Any option that is prefixed with 'user_' is a user defined option and can be set to any string. Inside a user defined command the value will be provided in the 'lf_user_{option}' environment variable. These options are not used by lf and are not persisted. # Environment Variables The following variables are exported for shell commands: These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f'). f Current file selection as a full path. fs Selected file(s) separated with the value of 'filesep' option as full path(s). fx Selected file(s) (i.e. 'fs') if there are any selected files, otherwise current file selection (i.e. 'f'). id Id of the running client. PWD Present working directory. OLDPWD Initial working directory. LF_LEVEL The value of this variable is set to the current nesting level when you run lf from a shell spawned inside lf. You can add the value of this variable to your shell prompt to make it clear that your shell runs inside lf. For example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] && PS1="$PS1""(lf level: $LF_LEVEL) "' in your shell configuration file (e.g. '~/.bashrc'). OPENER If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others. EDITOR If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on Unix, 'notepad' in Windows. PAGER If this variable is set in the environment, use the same value, otherwise set the value to 'less' on Unix, 'more' in Windows. SHELL If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on Unix, 'cmd' in Windows. lf_{option} Value of the {option}. lf_user_{option} Value of the user_{option}. lf_width lf_height Width/Height of the terminal. # Special Commands This section shows information about special shell commands. open This shell command can be defined to override the default 'open' command when the current file is not a directory. paste This shell command can be defined to override the default 'paste' command. rename This shell command can be defined to override the default 'rename' command. delete This shell command can be defined to override the default 'delete' command. pre-cd This shell command can be defined to be executed before changing a directory. on-cd This shell command can be defined to be executed after changing a directory. on-select This shell command can be defined to be executed after the selection changes. on-quit This shell command can be defined to be executed before quit. # Prefixes The following command prefixes are used by lf: : read (default) builtin/custom command $ shell shell command % shell-pipe shell command running with the ui ! shell-wait shell command waiting for key press & shell-async shell command running asynchronously 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. # Syntax Characters from '#' to newline are comments and ignored: # comments start with '#' There are four special commands ('set', 'map', 'cmap', and 'cmd') for configuration. Command 'set' is used to set an option which can be boolean, integer, or string: set hidden # boolean on set nohidden # boolean off set hidden! # boolean toggle set scrolloff 10 # integer value set sortby time # string value w/o quotes set sortby 'time' # string value with single quotes (whitespaces) set sortby "time" # string value with double quotes (backslash escapes) Command 'map' is used to bind a key to a command which can be builtin command, custom command, or shell command: map gh cd ~ # builtin command map D trash # custom command map i $less $f # shell command map U !du -csh * # waiting shell command Command 'cmap' is used to bind a key on the command line to a command line command or any other command: cmap cmd-escape cmap set incsearch! You can delete an existing binding by leaving the expression empty: map gh # deletes 'gh' mapping cmap # deletes '' mapping Command 'cmd' is used to define a custom command: cmd usage $du -h -d1 | less You can delete an existing command by leaving the expression empty: cmd trash # deletes 'trash' command If there is no prefix then ':' is assumed: map zt set info time An explicit ':' can be provided to group statements until a newline which is especially useful for 'map' and 'cmd' commands: map st :set sortby time; set info time If you need multiline you can wrap statements in '{{' and '}}' after the proper prefix. map st :{{ set sortby time set info time }} # Key Mappings Regular keys are assigned to a command with the usual syntax: map a down Keys combined with the shift key simply use the uppercase letter: map A down Special keys are written in between '<' and '>' characters and always use lowercase letters: map down Angle brackets can be assigned with their special names: map down map down Function keys are prefixed with 'f' character: map down Keys combined with the control key are prefixed with 'c' character: map down Keys combined with the alt key are assigned in two different ways depending on the behavior of your terminal. Older terminals (e.g. xterm) may set the 8th bit of a character when the alt key is pressed. On these terminals, you can use the corresponding byte for the mapping: map á down Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key when the alt key is pressed. lf uses the escape delaying mechanism to recognize alt keys in these terminals (delay is 100ms). On these terminals, keys combined with the alt key are prefixed with 'a' character: map down Please note that, some key combinations are not possible due to the way terminals work (e.g. control and h combination sends a backspace key instead). The easiest way to find the name of a key combination is to press the key while lf is running and read the name of the key from the unknown mapping error. Mouse buttons are prefixed with 'm' character: map down # primary map down # secondary map down # middle map down map down map down map down map down Mouse wheel events are also prefixed with 'm' character: map down map down map down map down # Push Mappings The usual way to map a key sequence is to assign it to a named or unnamed command. While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times. For this reason 'push' command is provided by lf. This command is used to simulate key pushes given as its arguments. You can 'map' a key to a 'push' command with an argument to create various keybindings. This is mainly useful for two purposes. First, it can be used to map a command with a command count: map push 10j Second, it can be used to avoid typing the name when a command takes arguments: map r push :rename One thing to be careful is that since 'push' command works with keys instead of commands it is possible to accidentally create recursive bindings: map j push 2j These types of bindings create a deadlock when executed. # Shell Commands Regular shell commands are the most basic command type that is useful for many purposes. For example, we can write a shell command to move selected file(s) to trash. A first attempt to write such a command may look like this: cmd trash ${{ mkdir -p ~/.trash if [ -z "$fs" ]; then mv "$f" ~/.trash else IFS="$(printf '\n\t')"; mv $fs ~/.trash fi }} We check '$fs' to see if there are any selected files. Otherwise we just delete the current file. Since this is such a common pattern, a separate '$fx' variable is provided. We can use this variable to get rid of the conditional: cmd trash ${{ mkdir -p ~/.trash IFS="$(printf '\n\t')"; mv $fx ~/.trash }} The trash directory is checked each time the command is executed. We can move it outside of the command so it would only run once at startup: ${{ mkdir -p ~/.trash }} cmd trash ${{ IFS="$(printf '\n\t')"; mv $fx ~/.trash }} Since these are one liners, we can drop '{{' and '}}': $mkdir -p ~/.trash cmd trash $IFS="$(printf '\n\t')"; mv $fx ~/.trash Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\n"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation. # Piping Shell Commands Regular shell commands have some limitations in some cases. When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again. Also, even when there is no output or error, the ui still needs to be paused while the command is running. This can cause flickering on the screen for short commands and similar distractions for longer commands. Instead of pausing the ui, piping shell commands connects stdin, stdout, and stderr of the command to the statline in the bottom of the ui. This can be useful for programs following the Unix philosophy to give no output in the success case, and brief error messages or prompts in other cases. For example, following rename command prompts for overwrite in the statline if there is an existing file with the given name: cmd rename %mv -i $f $1 You can also output error messages in the command and it will show up in the statline. For example, an alternative rename command may look like this: cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 Note that input is line buffered and output and error are byte buffered. # Waiting Shell Commands Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished. These can be useful to see the output of a program before the ui is resumed. Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline. # Asynchronous Shell Commands Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish. Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui. # Remote Commands One of the more advanced features in lf is remote commands. All clients connect to a server on startup. It is possible to send commands to all or any of the connected clients over the common server. This is used internally to notify file selection changes to other clients. To use this feature, you need to use a client which supports communicating with a Unix domain socket. OpenBSD implementation of netcat (nc) is one such example. You can use it to send a command to the socket file: echo 'send echo hello world' | nc -U ${XDG_RUNTIME_DIR:-/tmp}/lf.${USER}.sock Since such a client may not be available everywhere, lf comes bundled with a command line flag to be used as such. When using lf, you do not need to specify the address of the socket file. This is the recommended way of using remote commands since it is shorter and immune to socket file address changes: lf -remote 'send echo hello world' In this command 'send' is used to send the rest of the string as a command to all connected clients. You can optionally give it an id number to send a command to a single client: lf -remote 'send 1234 echo hello world' All clients have a unique id number but you may not be aware of the id number when you are writing a command. For this purpose, an '$id' variable is exported to the environment for shell commands. The value of this variable is set to the process id of the client. You can use it to send a remote command from a client to the server which in return sends a command back to itself. So now you can display a message in the current client by calling the following in a shell command: lf -remote "send $id echo hello world" Since lf does not have control flow syntax, remote commands are used for such needs. For example, you can configure the number of columns in the ui with respect to the terminal width as follows: cmd recol %{{ if [ $lf_width -le 80 ]; then lf -remote "send $id set ratios 1:2" elif [ $lf_width -le 160 ]; then lf -remote "send $id set ratios 1:2:3" else lf -remote "send $id set ratios 1:2:3:5" fi }} Besides 'send' command, there is a 'quit' command to quit the server when there are no connected clients left, and a 'quit!' command to force quit the server by closing client connections first: lf -remote 'quit' lf -remote 'quit!' Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users. # File Operations lf uses 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, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are not followed. Moving is performed using the rename operation of the underlying OS. For cross-device moving, lf falls back to copying and then deletes the original files if there are no errors. 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 selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to a file. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file. You can customize copy and move operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. You can use the following example as a starting point: cmd paste %{{ load=$(cat ~/.local/share/lf/files) mode=$(echo "$load" | sed -n '1p') list=$(echo "$load" | sed '1d') if [ $mode = 'copy' ]; then cp -R $list . elif [ $mode = 'move' ]; then mv $list . rm ~/.local/share/lf/files lf -remote 'send clear' fi }} Some useful things to be considered are to use the backup ('--backup') and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls. By default, lf does not assign 'delete' command to a key to protect new users. You can customize file deletion by defining a 'delete' command. You can also assign a key to this command if you like. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file. # Searching Files There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes. Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. You can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. For example, you can use the right arrow key to finish the search and open the selected file with the following mapping: cmap :cmd-enter; open Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial. Some options effect both searching and finding. You can disable 'wrapscan' option to prevent searches to wrap around at the end of the file list. You can disable 'ignorecase' option to match cases in the pattern and the filename. This option is already automatically overridden if the pattern contains upper case characters. You can disable 'smartcase' option to disable this behavior. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters. # Opening Files You can define a an 'open' command (default 'l' and '') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command: cmd open $vi $fx It is possible to use different command types: cmd open &xdg-open $f You may want to use either file extensions or mime types from 'file' command: cmd open ${{ case $(file --mime-type -Lb $f) in text/*) vi $fx;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; esac }} You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits. Regular shell commands (i.e. '$') drop to terminal which results in a flicker for commands that finishes immediately (e.g. 'xdg-open' in the above example). If you want to use asynchronous shell commands (i.e. '&') but also want to use the terminal when necessary (e.g. 'vi' in the above exxample), you can use a remote command: cmd open &{{ case $(file --mime-type -Lb $f) in text/*) lf -remote "send $id \$vi \$fx";; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; esac }} Note, asynchronous shell commands run in their own process group by default so they do not require the manual use of 'setsid'. Following command is provided by default: cmd open &$OPENER $f You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few. # Previewing Files lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files to name a few. For coloring lf recognizes ansi escape codes. In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Output of the execution is printed in the preview pane. You may also want to use the same script in your pager mapping as well: set previewer ~/.config/lf/pv.sh map i $~/.config/lf/pv.sh $f | less -R For 'less' pager, you may instead utilize 'LESSOPEN' mechanism so that useful information about the file such as the full path of the file can still be displayed in the statusline below: set previewer ~/.config/lf/pv.sh map i $LESSOPEN='| ~/.config/lf/pv.sh %s' less -R $f Since this script is called for each file selection change it needs to be as efficient as possible and this responsibility is left to the user. You may use file extensions to determine the type of file more efficiently compared to obtaining mime types from 'file' command. Extensions can then be used to match cleanly within a conditional: #!/bin/sh case "$1" in *.tar*) tar tf "$1";; *.zip) unzip -l "$1";; *.rar) unrar l "$1";; *.7z) 7z l "$1";; *.pdf) pdftotext "$1" -;; *) highlight -O ansi "$1";; esac 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. Note that some programs may not respond well to SIGPIPE to exit with a non-zero return code and avoid caching. You may add a trailing '|| true' command to avoid such errors: highlight -O ansi "$1" || true You may also use an existing preview filter as you like. Your system may already come with a preview filter named 'lesspipe'. These filters may have a mechanism to add user customizations as well. See the related documentations for more information. # 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 lfcd wrapper shell scripts provided in the repository at https://github.com/gokcehan/lf/tree/master/etc 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%d\033[0m\033[1m%f$git\033[0m" lf -remote "send $id set promptfmt \"$fmt\"" }} If you want to print escape sequences, you may redirect 'printf' output to '/dev/tty'. The following xterm specific escape sequence sets the terminal title to the working directory: cmd on-cd &{{ printf "\033]0; $PWD\007" > /dev/tty }} 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. There is also a 'pre-cd' command, that works like 'on-cd', but is run before the directory is actually changed. # Colors lf tries to automatically adapt its colors to the environment. It starts with a default colorscheme and updates colors using values of existing environment variables possibly by overwriting its previous values. Colors are set in the following order: 1. default 2. LSCOLORS (Mac/BSD ls) 3. LS_COLORS (GNU ls) 4. LF_COLORS (lf specific) 5. colors file (lf specific) Please refer to the corresponding man pages for more information about 'LSCOLORS' and 'LS_COLORS'. 'LF_COLORS' is provided with the same syntax as 'LS_COLORS' in case you want to configure colors only for lf but not ls. This can be useful since there are some differences between ls and lf, though one should expect the same behavior for common cases. Colors file is provided for easier configuration without environment variables. This file should consist of whitespace separated pairs with '#' character to start comments until the end of line. You can configure lf colors in two different ways. First, you can only configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. Second, you can set the values of environment variables or colors file mentioned above for fine grained customization. Note that 'LS_COLORS/LF_COLORS' are more powerful than 'LSCOLORS' and they can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line. It is worth noting that lf uses as many colors advertised by your terminal's entry in terminfo or infocmp databases on your system. If an entry is not present, it falls back to an internal database. If your terminal supports 24-bit colors but either does not have a database entry or does not advertise all capabilities, you can enable support by setting the '$COLORTERM' variable to 'truecolor' or ensuring '$TERM' is set to a value that ends with '-truecolor'. Default lf colors are mostly taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. Default dircolors entries with background colors are simplified to avoid confusion with current file selection in lf. Similarly, there are only file type matchings and extension matchings are left out for simplicity. Default values are as follows given with their matching order in lf: ln 01;36 or 31;01 tw 01;34 ow 01;34 st 01;34 di 01;34 pi 33 so 01;35 bd 33;01 cd 33;01 su 01;32 sg 01;32 ex 01;32 fi 00 Note that lf first tries matching file names and then falls back to file types. The full order of matchings from most specific to least are as follows: 1. Full Path (e.g. '~/.config/lf/lfrc') 2. Dir Name (e.g. '.git/') (only matches dirs with a trailing slash at the end) 3. File Type (e.g. 'ln') (except 'fi') 4. File Name (e.g. 'README*') 5. File Name (e.g. '*README') 6. Base Name (e.g. 'README.*') 7. Extension (e.g. '*.txt') 8. Default (i.e. 'fi') For example, given a regular text file '/path/to/README.txt', the following entries are checked in the configuration and the first one to match is used: 1. '/path/to/README.txt' 2. (skipped since the file is not a directory) 3. (skipped since the file is of type 'fi') 4. 'README.txt*' 5. '*README.txt' 6. 'README.*' 7. '*.txt' 8. 'fi' Given a regular directory '/path/to/example.d', the following entries are checked in the configuration and the first one to match is used: 1. '/path/to/example.d' 2. 'example.d/' 3. 'di' 4. 'example.d*' 5. '*example.d' 6. 'example.*' 7. '*.d' 8. 'fi' Note that glob-like patterns do not actually perform glob matching due to performance reasons. For example, you can set a variable as follows: export LF_COLORS="~/Documents=01;31:~/Downloads=01;31:~/.local/share=01;31:~/.config/lf/lfrc=31:.git/=01;32:.git*=32:*.gitignore=32:*Makefile=32:README.*=33:*.txt=34:*.md=34:ln=01;36:di=01;34:ex=01;32:" Having all entries on a single line can make it hard to read. You may instead divide it to multiple lines in between double quotes by escaping newlines with backslashes as follows: export LF_COLORS="\ ~/Documents=01;31:\ ~/Downloads=01;31:\ ~/.local/share=01;31:\ ~/.config/lf/lfrc=31:\ .git/=01;32:\ .git*=32:\ *.gitignore=32:\ *Makefile=32:\ README.*=33:\ *.txt=34:\ *.md=34:\ ln=01;36:\ di=01;34:\ ex=01;32:\ " Having such a long variable definition in a shell configuration file might be undesirable. You may instead use the colors file for configuration. A sample colors file can be found at https://github.com/gokcehan/lf/blob/master/etc/colors.example You may also see the wiki page for ansi escape codes https://en.wikipedia.org/wiki/ANSI_escape_code # Icons Icons are configured using 'LF_ICONS' environment variable or an icons file. The variable uses the same syntax as 'LS_COLORS/LF_COLORS'. Instead of colors, you should put a single characters as values of entries. Icons file should consist of whitespace separated pairs with '#' character to start comments until the end of line. Do not forget to enable 'icons' option to see the icons. Default values are as follows given with their matching order in lf: ln l or l tw t ow d st t di d pi p so s bd b cd c su u sg g ex x fi - A sample icons file can be found at https://github.com/gokcehan/lf/blob/master/etc/icons.example ` lf-r28/etc/000077500000000000000000000000001435165676200126625ustar00rootroot00000000000000lf-r28/etc/colors.example000066400000000000000000000065041435165676200155450ustar00rootroot00000000000000# vim:ft=dircolors # (This is not a dircolors file but it helps to highlight colors and comments) # default values from dircolors # (entries with a leading # are not implemented in lf) # #no 00 # NORMAL # fi 00 # FILE # #rs 0 # RESET # di 01;34 # DIR # ln 01;36 # LINK # #mh 00 # MULTIHARDLINK # pi 40;33 # FIFO # so 01;35 # SOCK # #do 01;35 # DOOR # bd 40;33;01 # BLK # cd 40;33;01 # CHR # or 40;31;01 # ORPHAN # #mi 00 # MISSING # su 37;41 # SETUID # sg 30;43 # SETGID # #ca 30;41 # CAPABILITY # tw 30;42 # STICKY_OTHER_WRITABLE # ow 34;42 # OTHER_WRITABLE # st 37;44 # STICKY # ex 01;32 # EXEC # default values from lf (with matching order) # ln 01;36 # LINK # or 31;01 # ORPHAN # tw 01;34 # STICKY_OTHER_WRITABLE # ow 01;34 # OTHER_WRITABLE # st 01;34 # STICKY # di 01;34 # DIR # pi 33 # FIFO # so 01;35 # SOCK # bd 33;01 # BLK # cd 33;01 # CHR # su 01;32 # SETUID # sg 01;32 # SETGID # ex 01;32 # EXEC # fi 00 # FILE # file types (with matching order) ln 01;36 # LINK or 31;01 # ORPHAN tw 34 # STICKY_OTHER_WRITABLE ow 34 # OTHER_WRITABLE st 01;34 # STICKY di 01;34 # DIR pi 33 # FIFO so 01;35 # SOCK bd 33;01 # BLK cd 33;01 # CHR su 01;32 # SETUID sg 01;32 # SETGID ex 01;32 # EXEC fi 00 # FILE # archives or compressed (dircolors defaults) *.tar 01;31 *.tgz 01;31 *.arc 01;31 *.arj 01;31 *.taz 01;31 *.lha 01;31 *.lz4 01;31 *.lzh 01;31 *.lzma 01;31 *.tlz 01;31 *.txz 01;31 *.tzo 01;31 *.t7z 01;31 *.zip 01;31 *.z 01;31 *.dz 01;31 *.gz 01;31 *.lrz 01;31 *.lz 01;31 *.lzo 01;31 *.xz 01;31 *.zst 01;31 *.tzst 01;31 *.bz2 01;31 *.bz 01;31 *.tbz 01;31 *.tbz2 01;31 *.tz 01;31 *.deb 01;31 *.rpm 01;31 *.jar 01;31 *.war 01;31 *.ear 01;31 *.sar 01;31 *.rar 01;31 *.alz 01;31 *.ace 01;31 *.zoo 01;31 *.cpio 01;31 *.7z 01;31 *.rz 01;31 *.cab 01;31 *.wim 01;31 *.swm 01;31 *.dwm 01;31 *.esd 01;31 # image formats (dircolors defaults) *.jpg 01;35 *.jpeg 01;35 *.mjpg 01;35 *.mjpeg 01;35 *.gif 01;35 *.bmp 01;35 *.pbm 01;35 *.pgm 01;35 *.ppm 01;35 *.tga 01;35 *.xbm 01;35 *.xpm 01;35 *.tif 01;35 *.tiff 01;35 *.png 01;35 *.svg 01;35 *.svgz 01;35 *.mng 01;35 *.pcx 01;35 *.mov 01;35 *.mpg 01;35 *.mpeg 01;35 *.m2v 01;35 *.mkv 01;35 *.webm 01;35 *.ogm 01;35 *.mp4 01;35 *.m4v 01;35 *.mp4v 01;35 *.vob 01;35 *.qt 01;35 *.nuv 01;35 *.wmv 01;35 *.asf 01;35 *.rm 01;35 *.rmvb 01;35 *.flc 01;35 *.avi 01;35 *.fli 01;35 *.flv 01;35 *.gl 01;35 *.dl 01;35 *.xcf 01;35 *.xwd 01;35 *.yuv 01;35 *.cgm 01;35 *.emf 01;35 *.ogv 01;35 *.ogx 01;35 # audio formats (dircolors defaults) *.aac 00;36 *.au 00;36 *.flac 00;36 *.m4a 00;36 *.mid 00;36 *.midi 00;36 *.mka 00;36 *.mp3 00;36 *.mpc 00;36 *.ogg 00;36 *.ra 00;36 *.wav 00;36 *.oga 00;36 *.opus 00;36 *.spx 00;36 *.xspf 00;36 lf-r28/etc/icons.example000066400000000000000000000157531435165676200153650ustar00rootroot00000000000000# vim:ft=conf # These examples require Nerd Fonts or a compatible font to be used. # See https://www.nerdfonts.com for more information. # default values from lf (with matching order) # ln l # LINK # or l # ORPHAN # tw t # STICKY_OTHER_WRITABLE # ow d # OTHER_WRITABLE # st t # STICKY # di d # DIR # pi p # FIFO # so s # SOCK # bd b # BLK # cd c # CHR # su u # SETUID # sg g # SETGID # ex x # EXEC # fi - # FILE # file types (with matching order) ln  # LINK or  # ORPHAN tw t # STICKY_OTHER_WRITABLE ow  # OTHER_WRITABLE st t # STICKY di  # DIR pi p # FIFO so s # SOCK bd b # BLK cd c # CHR su u # SETUID sg g # SETGID ex  # EXEC fi  # FILE # file extensions (vim-devicons) *.styl  *.sass  *.scss  *.htm  *.html  *.slim  *.haml  *.ejs  *.css  *.less  *.md  *.mdx  *.markdown  *.rmd  *.json  *.webmanifest  *.js  *.mjs  *.jsx  *.rb  *.gemspec  *.rake  *.php  *.py  *.pyc  *.pyo  *.pyd  *.coffee  *.mustache  *.hbs  *.conf  *.ini  *.yml  *.yaml  *.toml  *.bat  *.mk  *.jpg  *.jpeg  *.bmp  *.png  *.webp  *.gif  *.ico  *.twig  *.cpp  *.c++  *.cxx  *.cc  *.cp  *.c  *.cs  *.h  *.hh  *.hpp  *.hxx  *.hs  *.lhs  *.nix  *.lua  *.java  *.sh  *.fish  *.bash  *.zsh  *.ksh  *.csh  *.awk  *.ps1  *.ml λ *.mli λ *.diff  *.db  *.sql  *.dump  *.clj  *.cljc  *.cljs  *.edn  *.scala  *.go  *.dart  *.xul  *.sln  *.suo  *.pl  *.pm  *.t  *.rss  '*.f#'  *.fsscript  *.fsx  *.fs  *.fsi  *.rs  *.rlib  *.d  *.erl  *.hrl  *.ex  *.exs  *.eex  *.leex  *.heex  *.vim  *.ai  *.psd  *.psb  *.ts  *.tsx  *.jl  *.pp  *.vue ﵂ *.elm  *.swift  *.xcplayground  *.tex ﭨ *.r ﳒ *.rproj 鉶 *.sol ﲹ *.pem  # file names (vim-devicons) (case-insensitive not supported in lf) *gruntfile.coffee  *gruntfile.js  *gruntfile.ls  *gulpfile.coffee  *gulpfile.js  *gulpfile.ls  *mix.lock  *dropbox  *.ds_store  *.gitconfig  *.gitignore  *.gitattributes  *.gitlab-ci.yml  *.bashrc  *.zshrc  *.zshenv  *.zprofile  *.vimrc  *.gvimrc  *_vimrc  *_gvimrc  *.bashprofile  *favicon.ico  *license  *node_modules  *react.jsx  *procfile  *dockerfile  *docker-compose.yml  *rakefile  *config.ru  *gemfile  *makefile  *cmakelists.txt  *robots.txt ﮧ # file names (case-sensitive adaptations) *Gruntfile.coffee  *Gruntfile.js  *Gruntfile.ls  *Gulpfile.coffee  *Gulpfile.js  *Gulpfile.ls  *Dropbox  *.DS_Store  *LICENSE  *React.jsx  *Procfile  *Dockerfile  *Docker-compose.yml  *Rakefile  *Gemfile  *Makefile  *CMakeLists.txt  # file patterns (vim-devicons) (patterns not supported in lf) # .*jquery.*\.js$  # .*angular.*\.js$  # .*backbone.*\.js$  # .*require.*\.js$  # .*materialize.*\.js$  # .*materialize.*\.css$  # .*mootools.*\.js$  # .*vimrc.*  # Vagrantfile$  # file patterns (file name adaptations) *jquery.min.js  *angular.min.js  *backbone.min.js  *require.min.js  *materialize.min.js  *materialize.min.css  *mootools.min.js  *vimrc  Vagrantfile  # archives or compressed (extensions from dircolors defaults) *.tar  *.tgz  *.arc  *.arj  *.taz  *.lha  *.lz4  *.lzh  *.lzma  *.tlz  *.txz  *.tzo  *.t7z  *.zip  *.z  *.dz  *.gz  *.lrz  *.lz  *.lzo  *.xz  *.zst  *.tzst  *.bz2  *.bz  *.tbz  *.tbz2  *.tz  *.deb  *.rpm  *.jar  *.war  *.ear  *.sar  *.rar  *.alz  *.ace  *.zoo  *.cpio  *.7z  *.rz  *.cab  *.wim  *.swm  *.dwm  *.esd  # image formats (extensions from dircolors defaults) *.jpg  *.jpeg  *.mjpg  *.mjpeg  *.gif  *.bmp  *.pbm  *.pgm  *.ppm  *.tga  *.xbm  *.xpm  *.tif  *.tiff  *.png  *.svg  *.svgz  *.mng  *.pcx  *.mov  *.mpg  *.mpeg  *.m2v  *.mkv  *.webm  *.ogm  *.mp4  *.m4v  *.mp4v  *.vob  *.qt  *.nuv  *.wmv  *.asf  *.rm  *.rmvb  *.flc  *.avi  *.fli  *.flv  *.gl  *.dl  *.xcf  *.xwd  *.yuv  *.cgm  *.emf  *.ogv  *.ogx  # audio formats (extensions from dircolors defaults) *.aac  *.au  *.flac  *.m4a  *.mid  *.midi  *.mka  *.mp3  *.mpc  *.ogg  *.ra  *.wav  *.oga  *.opus  *.spx  *.xspf  # other formats *.pdf  lf-r28/etc/lf.bash000066400000000000000000000012541435165676200141240ustar00rootroot00000000000000# Autocompletion for bash shell. # # You may put this file to a directory used by bash-completion: # # mkdir -p ~/.local/share/bash-completion/completions # ln -s "/path/to/lf.bash" ~/.local/share/bash-completion/completions # _lf () { local -a opts=( -command -config -cpuprofile -doc -last-dir-path -log -memprofile -remote -selection-path -server -single -version -help ) if [[ $2 == -* ]]; then COMPREPLY=( $(compgen -W "${opts[*]}" -- "$2") ) else COMPREPLY=( $(compgen -f -d -- "$2") ) fi } complete -o filenames -F _lf lf lfcd lf-r28/etc/lf.csh000066400000000000000000000007551435165676200137710ustar00rootroot00000000000000# Autocompletion for tcsh shell. # # You need to either copy the content of this file to your shell rc file # (e.g. ~/.tcshrc) or source this file directly: # # set LF_COMPLETE = "/path/to/lf.csh" # if ( -f "$LF_COMPLETE" ) then # source "$LF_COMPLETE" # endif # set LF_ARGS = "-command -config -cpuprofile -doc -last-dir-path -log -memprofile -remote -selection-path -server -single -version -help " complete lf "C/-*/(${LF_ARGS})/" complete lfcd "C/-*/(${LF_ARGS})/" lf-r28/etc/lf.fish000066400000000000000000000021561435165676200141420ustar00rootroot00000000000000# Autocompletion for fish shell. # # You may put this file to a directory in $fish_complete_path variable: # # mkdir -p ~/.config/fish/completions # ln -s "/path/to/lf.fish" ~/.config/fish/completions # complete -c lf -o command -r -d 'command to execute on client initialization' complete -c lf -o config -r -d 'path to the config file (instead of the usual paths)' complete -c lf -o cpuprofile -r -d 'path to the file to write the CPU profile' complete -c lf -o doc -d 'show documentation' complete -c lf -o last-dir-path -r -d 'path to the file to write the last dir on exit (to use for cd)' complete -c lf -o log -r -d 'path to the log file to write messages' complete -c lf -o memprofile -r -d 'path to the file to write the memory profile' complete -c lf -o remote -x -d 'send remote command to server' complete -c lf -o selection-path -r -d 'path to the file to write selected files on open (to use as open file dialog)' complete -c lf -o server -d 'start server (automatic)' complete -c lf -o single -d 'start a client without server' complete -c lf -o version -d 'show version' complete -c lf -o help -d 'show help' lf-r28/etc/lf.ps1000066400000000000000000000043051435165676200137120ustar00rootroot00000000000000# Autocompletion for powershell. # # You need to either copy the content of this file to $PROFILE or call this # script directly. # using namespace System.Management.Automation Register-ArgumentCompleter -Native -CommandName 'lf' -ScriptBlock { param($wordToComplete) $completions = @( [CompletionResult]::new('-command ', '-command', [CompletionResultType]::ParameterName, 'command to execute on client initialization') [CompletionResult]::new('-config ', '-config', [CompletionResultType]::ParameterName, 'path to the config file (instead of the usual paths)') [CompletionResult]::new('-cpuprofile ', '-cpuprofile', [CompletionResultType]::ParameterName, 'path to the file to write the CPU profile') [CompletionResult]::new('-doc', '-doc', [CompletionResultType]::ParameterName, 'show documentation') [CompletionResult]::new('-last-dir-path ', '-last-dir-path', [CompletionResultType]::ParameterName, 'path to the file to write the last dir on exit (to use for cd)') [CompletionResult]::new('-log ', '-log', [CompletionResultType]::ParameterName, 'path to the log file to write messages') [CompletionResult]::new('-memprofile ', '-memprofile', [CompletionResultType]::ParameterName, 'path to the file to write the memory profile') [CompletionResult]::new('-remote ', '-remote', [CompletionResultType]::ParameterName, 'send remote command to server') [CompletionResult]::new('-selection-path ', '-selection-path', [CompletionResultType]::ParameterName, 'path to the file to write selected files on open (to use as open file dialog)') [CompletionResult]::new('-server', '-server', [CompletionResultType]::ParameterName, 'start server (automatic)') [CompletionResult]::new('-single', '-single', [CompletionResultType]::ParameterName, 'start a client without server') [CompletionResult]::new('-version', '-version', [CompletionResultType]::ParameterName, 'show version') [CompletionResult]::new('-help', '-help', [CompletionResultType]::ParameterName, 'show help') ) if ($wordToComplete.StartsWith('-')) { $completions.Where{ $_.CompletionText -like "$wordToComplete*" } | Sort-Object -Property ListItemText } } lf-r28/etc/lf.vim000066400000000000000000000014451435165676200140040ustar00rootroot00000000000000" Use lf to select and open file(s) in vim (adapted from ranger). " " You need to either copy the content of this file to your ~/.vimrc or source " this file directly: " " let lfvim = "/path/to/lf.vim" " if filereadable(lfvim) " exec "source " . lfvim " endif " " You may also like to assign a key to this command: " " nnoremap l :LF " function! LF() let temp = tempname() exec 'silent !lf -selection-path=' . shellescape(temp) if !filereadable(temp) redraw! return endif let names = readfile(temp) if empty(names) redraw! return endif exec 'edit ' . fnameescape(names[0]) for name in names[1:] exec 'argadd ' . fnameescape(name) endfor redraw! endfunction command! -bar LF call LF() lf-r28/etc/lf.zsh000066400000000000000000000020101435165676200140020ustar00rootroot00000000000000#compdef lf # Autocompletion for zsh shell. # # You need to rename this file to _lf and add containing folder to $fpath in # ~/.zshrc file: # # fpath=(/path/to/directory/containing/the/file $fpath) # autoload -U compinit # compinit # local arguments arguments=( '-command[command to execute on client initialization]' '-config[path to the config file (instead of the usual paths)]' '-cpuprofile[path to the file to write the CPU profile]' '-doc[show documentation]' '-last-dir-path[path to the file to write the last dir on exit (to use for cd)]' '-log[path to the log file to write messages]' '-memprofile[path to the file to write the memory profile]' '-remote[send remote command to server]' '-selection-path[path to the file to write selected files on open (to use as open file dialog)]' '-server[start server (automatic)]' '-single[start a client without server]' '-version[show version]' '-help[show help]' '*:filename:_files' ) _arguments -s $arguments lf-r28/etc/lfcd.cmd000066400000000000000000000005731435165676200142640ustar00rootroot00000000000000@echo off rem Change working dir in cmd.exe to last dir in lf on exit. rem 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 not exist "%dir%" exit if "%dir%" == "%cd%" exit cd /d "%dir%" lf-r28/etc/lfcd.csh000066400000000000000000000010021435165676200142620ustar00rootroot00000000000000# Change working dir in tcsh to last dir in lf on exit (adapted from ranger). # # You need to either copy the content of this file to your shell rc file (e.g. # ~/.tcshrc) or source this file directly: # # setenv LF_HOME "${HOME}/.config/lf" # [ -e "${LF_HOME}/lfcd.csh" ] && source "${LF_HOME}/lfcd.csh" # # You may also like to assign a key to this command: # # bindkey -c "^O" lfcd # alias lfcd 'set _=`mktemp` && lf -last-dir-path=$_ "\!*" && set _=`cat $_ && rm -f $_` && [ -d "$_" ] && cd "$_"' lf-r28/etc/lfcd.fish000066400000000000000000000013351435165676200144470ustar00rootroot00000000000000# Change working dir in fish to last dir in lf on exit (adapted from ranger). # # You may put this file to a directory in $fish_function_path variable: # # mkdir -p ~/.config/fish/functions # ln -s "/path/to/lfcd.fish" ~/.config/fish/functions # # You may also like to assign a key to this command: # # bind \co 'set old_tty (stty -g); stty sane; lfcd; stty $old_tty; commandline -f repaint' # # You may put this in a function called fish_user_key_bindings. function lfcd set tmp (mktemp) lf -last-dir-path=$tmp $argv if test -f "$tmp" set dir (cat $tmp) rm -f $tmp if test -d "$dir" if test "$dir" != (pwd) cd $dir end end end end lf-r28/etc/lfcd.ps1000066400000000000000000000014551435165676200142240ustar00rootroot00000000000000# Change working dir in powershell to last dir in lf on exit. # # You need to put this file to a folder in $ENV:PATH variable. # # You may also like to assign a key to this command: # # Set-PSReadLineKeyHandler -Chord Ctrl+o -ScriptBlock { # [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() # [Microsoft.PowerShell.PSConsoleReadLine]::Insert('lfcd.ps1') # [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() # } # # You may put this in one of the profiles found in $PROFILE. # $tmp = [System.IO.Path]::GetTempFileName() lf -last-dir-path="$tmp" $args if (Test-Path -PathType Leaf "$tmp") { $dir = Get-Content "$tmp" Remove-Item -Force "$tmp" if (Test-Path -PathType Container "$dir") { if ("$dir" -ne "$pwd") { cd "$dir" } } } lf-r28/etc/lfcd.sh000066400000000000000000000013101435165676200141210ustar00rootroot00000000000000# Change working dir in shell to last dir in lf on exit (adapted from ranger). # # You need to either copy the content of this file to your shell rc file # (e.g. ~/.bashrc) or source this file directly: # # LFCD="/path/to/lfcd.sh" # if [ -f "$LFCD" ]; then # source "$LFCD" # fi # # You may also like to assign a key to this command: # # bind '"\C-o":"lfcd\C-m"' # bash # bindkey -s '^o' 'lfcd\n' # zsh # lfcd () { tmp="$(mktemp)" lf -last-dir-path="$tmp" "$@" if [ -f "$tmp" ]; then dir="$(cat "$tmp")" rm -f "$tmp" if [ -d "$dir" ]; then if [ "$dir" != "$(pwd)" ]; then cd "$dir" fi fi fi } lf-r28/etc/lfrc.cmd.example000066400000000000000000000022211435165676200157240ustar00rootroot00000000000000# interpreter for shell commands set shell cmd # Shell commands with multiline definitions and/or positional arguments and/or # quotes do not work in Windows. For anything but the simplest shell commands, # it is recommended to create separate script files and simply call them here # in commands or mappings. # change the editor used in default editor keybinding # There is no builtin terminal editor installed in Windows. The default editor # mapping uses 'notepad' which launches in a separate GUI window. You may # instead install a terminal editor of your choice and replace the default # editor keybinding accordingly. map e $vim %f% # change the pager used in default pager keybinding # The standard pager used in Windows is 'more' which is not a very capable # pager. You may instead install a pager of your choice and replace the default # pager keybinding accordingly. map i $less %f% # change the shell used in default shell keybinding map w $powershell # change 'doc' command to use a different pager cmd doc $lf -doc | less # leave some space at the top and the bottom of the screen set scrolloff 10 # use enter for shell commands map shell lf-r28/etc/lfrc.example000066400000000000000000000054031435165676200151670ustar00rootroot00000000000000# interpreter for shell commands set shell sh # set '-eu' options for shell commands # These options are used to have safer shell commands. Option '-e' is used to # exit on error and option '-u' is used to give error for unset variables. # Option '-f' disables pathname expansion which can be useful when $f, $fs, and # $fx variables contain names with '*' or '?' characters. However, this option # is used selectively within individual commands as it can be limiting at # times. set shellopts '-eu' # set internal field separator (IFS) to "\n" for shell commands # This is useful to automatically split file names in $fs and $fx properly # since default file separator used in these variables (i.e. 'filesep' option) # is newline. You need to consider the values of these options and create your # commands accordingly. set ifs "\n" # leave some space at the top and the bottom of the screen set scrolloff 10 # use enter for shell commands map shell # execute current file (must be executable) map x $$f map X !$f # dedicated keys for file opener actions map o &mimeopen $f map O $mimeopen --ask $f # define a custom 'open' command # This command is called when current file is not a directory. You may want to # use either file extensions and/or mime types here. Below uses an editor for # text files and a file opener for the rest. cmd open &{{ case $(file --mime-type -Lb $f) in text/*) lf -remote "send $id \$$EDITOR \$fx";; *) for f in $fx; do $OPENER $f > /dev/null 2> /dev/null & done;; esac }} # define a custom 'rename' command without prompt for overwrite # cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 # map r push :rename # make sure trash folder exists # %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 # define a custom 'delete' command # cmd delete ${{ # set -f # printf "$fx\n" # printf "delete?[y/n]" # read ans # [ "$ans" = "y" ] && rm -rf $fx # }} # use '' key for either 'trash' or 'delete' command # map trash # map delete # extract the current file with the right command # (xkcd link: https://xkcd.com/1168/) cmd extract ${{ set -f case $f in *.tar.bz|*.tar.bz2|*.tbz|*.tbz2) tar xjvf $f;; *.tar.gz|*.tgz) tar xzvf $f;; *.tar.xz|*.txz) tar xJvf $f;; *.zip) unzip $f;; *.rar) unrar x $f;; *.7z) 7z x $f;; esac }} # compress current file or selected files with tar and gunzip cmd tar ${{ set -f mkdir $1 cp -r $fx $1 tar czf $1.tar.gz $1 rm -rf $1 }} # compress current file or selected files with zip cmd zip ${{ set -f mkdir $1 cp -r $fx $1 zip -r $1.zip $1 rm -rf $1 }} lf-r28/etc/lfrc.ps1.example000066400000000000000000000026751435165676200157010ustar00rootroot00000000000000# interpreter for shell commands set shell powershell # Shell commands with multiline definitions and/or positional arguments and/or # quotes do not work in Windows. For anything but the simplest shell commands, # it is recommended to create separate script files and simply call them here # in commands or mappings. # # Also, the default keybindings are defined using cmd syntax (i.e. '%EDITOR%') # which does not work with powershell. Therefore, you need to override these # keybindings with explicit choices accordingly. # change the default open command to work in powerShell cmd open &start $Env:f # change the editor used in default editor keybinding # There is no builtin terminal editor installed in Windows. The default editor # mapping uses 'notepad' which launches in a separate GUI window. You may # instead install a terminal editor of your choice and replace the default # editor keybinding accordingly. map e $vim $Env:f # change the pager used in default pager keybinding # The standard pager used in Windows is 'more' which is not a very capable # pager. You may instead install a pager of your choice and replace the default # pager keybinding accordingly. map i $less $Env:f # change the shell used in default shell keybinding map w $powershell # change 'doc' command to use a different pager cmd doc $lf -doc | less # leave some space at the top and the bottom of the screen set scrolloff 10 # use enter for shell commands map shell lf-r28/eval.go000066400000000000000000001372601435165676200133760ustar00rootroot00000000000000package main import ( "io" "log" "os" "path/filepath" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/gdamore/tcell/v2" ) func (e *setExpr) eval(app *app, args []string) { switch e.opt { case "anchorfind": gOpts.anchorfind = true case "noanchorfind": gOpts.anchorfind = false case "anchorfind!": gOpts.anchorfind = !gOpts.anchorfind case "autoquit": gOpts.autoquit = true case "noautoquit": gOpts.autoquit = false case "autoquit!": gOpts.autoquit = !gOpts.autoquit case "dircache": gOpts.dircache = true case "nodircache": gOpts.dircache = false case "dircache!": gOpts.dircache = !gOpts.dircache case "dircounts": gOpts.dircounts = true case "nodircounts": gOpts.dircounts = false case "dircounts!": gOpts.dircounts = !gOpts.dircounts case "dironly": gOpts.dironly = true app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "dirpreviews": gOpts.dirpreviews = true case "nodirpreviews": gOpts.dirpreviews = false case "dirpreviews!": gOpts.dirpreviews = !gOpts.dirpreviews case "nodironly": gOpts.dironly = false app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "dironly!": gOpts.dironly = !gOpts.dironly app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "dirfirst": gOpts.sortType.option |= dirfirstSort app.nav.sort() app.ui.sort() case "nodirfirst": gOpts.sortType.option &= ^dirfirstSort app.nav.sort() app.ui.sort() case "dirfirst!": gOpts.sortType.option ^= dirfirstSort app.nav.sort() app.ui.sort() case "drawbox": gOpts.drawbox = true app.ui.renew() if app.nav.height != app.ui.wins[0].h { app.nav.height = app.ui.wins[0].h app.nav.regCache = make(map[string]*reg) } app.ui.loadFile(app, true) case "nodrawbox": gOpts.drawbox = false app.ui.renew() if app.nav.height != app.ui.wins[0].h { app.nav.height = app.ui.wins[0].h app.nav.regCache = make(map[string]*reg) } app.ui.loadFile(app, true) case "drawbox!": gOpts.drawbox = !gOpts.drawbox app.ui.renew() if app.nav.height != app.ui.wins[0].h { app.nav.height = app.ui.wins[0].h app.nav.regCache = make(map[string]*reg) } app.ui.loadFile(app, true) case "globsearch": gOpts.globsearch = true app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "noglobsearch": gOpts.globsearch = false app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "globsearch!": gOpts.globsearch = !gOpts.globsearch app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "hidden": gOpts.sortType.option |= hiddenSort app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "nohidden": gOpts.sortType.option &= ^hiddenSort app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "hidden!": gOpts.sortType.option ^= hiddenSort app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "history": gOpts.history = true case "nohistory": gOpts.history = false case "history!": gOpts.history = !gOpts.history case "icons": gOpts.icons = true case "noicons": gOpts.icons = false case "icons!": gOpts.icons = !gOpts.icons case "ignorecase": gOpts.ignorecase = true app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "noignorecase": gOpts.ignorecase = false app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "ignorecase!": gOpts.ignorecase = !gOpts.ignorecase app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "ignoredia": gOpts.ignoredia = true app.nav.sort() app.ui.sort() case "noignoredia": gOpts.ignoredia = false app.nav.sort() app.ui.sort() case "ignoredia!": gOpts.ignoredia = !gOpts.ignoredia app.nav.sort() app.ui.sort() case "incfilter": gOpts.incfilter = true case "noincfilter": gOpts.incfilter = false case "incfilter!": gOpts.incfilter = !gOpts.incfilter case "incsearch": gOpts.incsearch = true case "noincsearch": gOpts.incsearch = false case "incsearch!": gOpts.incsearch = !gOpts.incsearch case "mouse": if !gOpts.mouse { gOpts.mouse = true app.ui.screen.EnableMouse(tcell.MouseButtonEvents) } case "nomouse": if gOpts.mouse { gOpts.mouse = false app.ui.screen.DisableMouse() } case "mouse!": if gOpts.mouse { gOpts.mouse = false app.ui.screen.DisableMouse() } else { gOpts.mouse = true app.ui.screen.EnableMouse(tcell.MouseButtonEvents) } case "number": gOpts.number = true case "nonumber": gOpts.number = false case "number!": gOpts.number = !gOpts.number 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 "relativenumber": gOpts.relativenumber = true case "norelativenumber": gOpts.relativenumber = false case "relativenumber!": gOpts.relativenumber = !gOpts.relativenumber case "reverse": gOpts.sortType.option |= reverseSort app.nav.sort() app.ui.sort() case "noreverse": gOpts.sortType.option &= ^reverseSort app.nav.sort() app.ui.sort() case "reverse!": gOpts.sortType.option ^= reverseSort app.nav.sort() app.ui.sort() case "smartcase": gOpts.smartcase = true app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "nosmartcase": gOpts.smartcase = false app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "smartcase!": gOpts.smartcase = !gOpts.smartcase app.nav.sort() app.ui.sort() app.ui.loadFile(app, true) case "smartdia": gOpts.smartdia = true case "nosmartdia": gOpts.smartdia = false case "smartdia!": gOpts.smartdia = !gOpts.smartdia case "waitmsg": gOpts.waitmsg = e.val case "wrapscan": gOpts.wrapscan = true case "nowrapscan": 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 "findlen": n, err := strconv.Atoi(e.val) if err != nil { app.ui.echoerrf("findlen: %s", err) return } if n < 0 { app.ui.echoerr("findlen: value should be a non-negative number") return } gOpts.findlen = n case "period": n, err := strconv.Atoi(e.val) if err != nil { app.ui.echoerrf("period: %s", err) return } if n < 0 { app.ui.echoerr("period: value should be a non-negative number") return } gOpts.period = n if n == 0 { app.ticker.Stop() } else { app.ticker.Stop() app.ticker = time.NewTicker(time.Duration(gOpts.period) * time.Second) } case "scrolloff": n, err := strconv.Atoi(e.val) if err != nil { app.ui.echoerrf("scrolloff: %s", err) return } if n < 0 { app.ui.echoerr("scrolloff: value should be a non-negative number") return } gOpts.scrolloff = n case "tabstop": n, err := strconv.Atoi(e.val) if err != nil { app.ui.echoerrf("tabstop: %s", err) return } if n <= 0 { app.ui.echoerr("tabstop: value should be a positive number") return } gOpts.tabstop = n case "errorfmt": gOpts.errorfmt = e.val case "filesep": gOpts.filesep = e.val case "hiddenfiles": toks := strings.Split(e.val, ":") for _, s := range toks { if s == "" { app.ui.echoerr("hiddenfiles: glob should be non-empty") return } _, err := filepath.Match(s, "a") if err != nil { app.ui.echoerrf("hiddenfiles: %s", err) return } } gOpts.hiddenfiles = toks app.nav.sort() app.nav.position() app.ui.sort() app.ui.loadFile(app, true) case "ifs": gOpts.ifs = e.val case "info": if e.val == "" { gOpts.info = nil return } toks := strings.Split(e.val, ":") for _, s := range toks { switch s { case "size", "time", "atime", "ctime": default: app.ui.echoerr("info: should consist of 'size', 'time', 'atime' or 'ctime' separated with colon") return } } gOpts.info = toks case "previewer": gOpts.previewer = replaceTilde(e.val) case "cleaner": gOpts.cleaner = replaceTilde(e.val) case "promptfmt": gOpts.promptfmt = e.val case "ratios": toks := strings.Split(e.val, ":") var rats []int for _, s := range toks { n, err := strconv.Atoi(s) if err != nil { app.ui.echoerrf("ratios: %s", err) return } if n <= 0 { app.ui.echoerr("ratios: value should be a positive number") return } rats = append(rats, n) } if gOpts.preview && len(rats) < 2 { app.ui.echoerr("ratios: should consist of at least two numbers when 'preview' is enabled") return } gOpts.ratios = rats app.ui.wins = getWins(app.ui.screen) app.ui.loadFile(app, true) case "selmode": gOpts.selmode = e.val case "shell": gOpts.shell = e.val case "shellflag": gOpts.shellflag = e.val case "shellopts": if e.val == "" { gOpts.shellopts = nil return } gOpts.shellopts = strings.Split(e.val, ":") case "sortby": switch e.val { case "natural": gOpts.sortType.method = naturalSort case "name": gOpts.sortType.method = nameSort case "size": 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() case "tempmarks": if e.val != "" { gOpts.tempmarks = "'" + e.val } else { gOpts.tempmarks = "'" } case "tagfmt": gOpts.tagfmt = e.val case "timefmt": gOpts.timefmt = e.val case "infotimefmtnew": gOpts.infotimefmtnew = e.val case "infotimefmtold": gOpts.infotimefmtold = e.val case "truncatechar": if runeSliceWidth([]rune(e.val)) != 1 { app.ui.echoerr("truncatechar: value should be a single character") return } gOpts.truncatechar = e.val default: // any key with the prefix user_ is accepted as a user defined option if strings.HasPrefix(e.opt, "user_") { gOpts.user[e.opt[5:]] = e.val } else { 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) } else { gOpts.keys[e.keys] = e.expr } app.ui.loadFileInfo(app.nav) } func (e *cmapExpr) eval(app *app, args []string) { if e.expr == nil { delete(gOpts.cmdkeys, e.key) } else { gOpts.cmdkeys[e.key] = e.expr } app.ui.loadFileInfo(app.nav) } func (e *cmdExpr) eval(app *app, args []string) { if e.expr == nil { delete(gOpts.cmds, e.name) } else { gOpts.cmds[e.name] = e.expr } app.ui.loadFileInfo(app.nav) } func preChdir(app *app) { if cmd, ok := gOpts.cmds["pre-cd"]; ok { cmd.eval(app, nil) } } func onChdir(app *app) { app.nav.addJumpList() if cmd, ok := gOpts.cmds["on-cd"]; ok { cmd.eval(app, nil) } } func onSelect(app *app) { if cmd, ok := gOpts.cmds["on-select"]; ok { cmd.eval(app, nil) } } func splitKeys(s string) (keys []string) { for i := 0; i < len(s); { r, w := utf8.DecodeRuneInString(s[i:]) if r != '<' { keys = append(keys, s[i:i+w]) i += w } else { j := i + w for r != '>' && j < len(s) { r, w = utf8.DecodeRuneInString(s[j:]) j += w } keys = append(keys, s[i:j]) i = j } } return } func doComplete(app *app) (matches []string) { switch app.ui.cmdPrefix { case ":": matches, app.ui.cmdAccLeft = completeCmd(app.ui.cmdAccLeft) case "/", "?": matches, app.ui.cmdAccLeft = completeFile(app.ui.cmdAccLeft) case "$", "%", "!", "&": matches, app.ui.cmdAccLeft = completeShell(app.ui.cmdAccLeft) } return } func menuComplete(app *app, dir int) { if !app.menuCompActive { app.ui.cmdTmp = app.ui.cmdAccLeft app.menuComps = doComplete(app) if len(app.menuComps) > 1 { app.menuCompInd = -1 app.menuCompActive = true } } else { app.menuCompInd += dir if app.menuCompInd == len(app.menuComps) { app.menuCompInd = 0 } else if app.menuCompInd < 0 { app.menuCompInd = len(app.menuComps) - 1 } comp := app.menuComps[app.menuCompInd] toks := tokenize(string(app.ui.cmdTmp)) last := toks[len(toks)-1] if app.ui.cmdPrefix != "/" && app.ui.cmdPrefix != "?" { comp = escape(comp) _, last = filepath.Split(last) } ind := len(app.ui.cmdTmp) - len([]rune(last)) app.ui.cmdAccLeft = append(app.ui.cmdTmp[:ind], []rune(comp)...) } app.ui.menuBuf = listMatches(app.ui.screen, app.menuComps, app.menuCompInd) } func update(app *app) { app.ui.menuBuf = nil app.menuCompActive = false switch { case gOpts.incsearch && app.ui.cmdPrefix == "/": app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight) if app.nav.search == "" { return } dir := app.nav.currDir() old := dir.ind dir.ind = app.nav.searchInd dir.pos = app.nav.searchPos if _, err := app.nav.searchNext(); err != nil { app.ui.echoerrf("search: %s: %s", err, app.nav.search) } else if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case gOpts.incsearch && app.ui.cmdPrefix == "?": app.nav.search = string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight) if app.nav.search == "" { return } dir := app.nav.currDir() old := dir.ind dir.ind = app.nav.searchInd dir.pos = app.nav.searchPos if _, err := app.nav.searchPrev(); err != nil { app.ui.echoerrf("search: %s: %s", err, app.nav.search) } else if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case gOpts.incfilter && app.ui.cmdPrefix == "filter: ": filter := string(app.ui.cmdAccLeft) + string(app.ui.cmdAccRight) dir := app.nav.currDir() old := dir.ind if err := app.nav.setFilter(strings.Split(filter, " ")); err != nil { app.ui.echoerrf("filter: %s", err) } else if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } } func restartIncCmd(app *app) { if gOpts.incsearch && (app.ui.cmdPrefix == "/" || app.ui.cmdPrefix == "?") { dir := app.nav.currDir() app.nav.searchInd = dir.ind app.nav.searchPos = dir.pos update(app) } else if gOpts.incfilter && app.ui.cmdPrefix == "filter: " { dir := app.nav.currDir() app.nav.prevFilter = dir.filter update(app) } } func resetIncCmd(app *app) { if gOpts.incsearch && (app.ui.cmdPrefix == "/" || app.ui.cmdPrefix == "?") { dir := app.nav.currDir() dir.pos = app.nav.searchPos if dir.ind != app.nav.searchInd { dir.ind = app.nav.searchInd app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } else if gOpts.incfilter && app.ui.cmdPrefix == "filter: " { dir := app.nav.currDir() old := dir.ind app.nav.setFilter(app.nav.prevFilter) if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } } func normal(app *app) { resetIncCmd(app) app.cmdHistoryInd = 0 app.menuCompActive = false 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 == "?"): app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) update(app) case gOpts.incfilter && app.ui.cmdPrefix == "filter: ": app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) update(app) case app.ui.cmdPrefix == "find: ": app.nav.find = string(app.ui.cmdAccLeft) + arg + string(app.ui.cmdAccRight) if gOpts.findlen == 0 { switch app.nav.findSingle() { case 0: app.ui.echoerrf("find: pattern not found: %s", app.nav.find) case 1: app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) default: app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) return } } else { if len(app.nav.find) < gOpts.findlen { app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) return } if moved, found := app.nav.findNext(); !found { app.ui.echoerrf("find: pattern not found: %s", app.nav.find) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } normal(app) case app.ui.cmdPrefix == "find-back: ": app.nav.find = string(app.ui.cmdAccLeft) + arg + string(app.ui.cmdAccRight) if gOpts.findlen == 0 { switch app.nav.findSingle() { case 0: app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find) case 1: app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) default: app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) return } } else { if len(app.nav.find) < gOpts.findlen { app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) return } if moved, found := app.nav.findPrev(); !found { app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } normal(app) case strings.HasPrefix(app.ui.cmdPrefix, "delete"): normal(app) if arg == "y" { if err := app.nav.del(app); err != nil { app.ui.echoerrf("delete: %s", err) return } app.nav.unselect() if gSingleMode { app.nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { app.ui.echoerrf("delete: %s", err) return } } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case strings.HasPrefix(app.ui.cmdPrefix, "replace"): normal(app) if arg == "y" { if err := app.nav.rename(); err != nil { app.ui.echoerrf("rename: %s", err) return } if gSingleMode { app.nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { app.ui.echoerrf("rename: %s", err) return } } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case strings.HasPrefix(app.ui.cmdPrefix, "create"): normal(app) if arg == "y" { if err := os.MkdirAll(filepath.Dir(app.nav.renameNewPath), os.ModePerm); err != nil { app.ui.echoerrf("rename: %s", err) return } if err := app.nav.rename(); err != nil { app.ui.echoerrf("rename: %s", err) return } if gSingleMode { app.nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { app.ui.echoerrf("rename: %s", err) return } } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case app.ui.cmdPrefix == "mark-save: ": normal(app) app.nav.marks[arg] = app.nav.currDir().path if err := app.nav.writeMarks(); err != nil { app.ui.echoerrf("mark-save: %s", err) } if gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("mark-save: %s", err) } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("mark-save: %s", err) } } case app.ui.cmdPrefix == "mark-load: ": normal(app) wd, err := os.Getwd() if err != nil { log.Printf("getting current directory: %s", err) } path, ok := app.nav.marks[arg] if !ok { app.ui.echoerr("mark-load: no such mark") return } if wd != path { resetIncCmd(app) preChdir(app) } if err := app.nav.cd(path); err != nil { app.ui.echoerrf("%s", err) return } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) if wd != path { app.nav.marks["'"] = wd restartIncCmd(app) 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 gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("mark-remove: %s", err) } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("mark-remove: %s", err) } } case app.ui.cmdPrefix == ":" && len(app.ui.cmdAccLeft) == 0: switch arg { case "!", "$", "%", "&": app.ui.cmdPrefix = arg return } fallthrough default: app.ui.menuBuf = nil app.menuCompActive = false app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(arg)...) } } func (e *callExpr) eval(app *app, args []string) { switch e.name { case "up": if !app.nav.init { return } if app.nav.up(e.count) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "half-up": if !app.nav.init { return } if app.nav.up(e.count * app.nav.height / 2) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "page-up": if !app.nav.init { return } if app.nav.up(e.count * app.nav.height) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "scroll-up": if !app.nav.init { return } if app.nav.scrollUp(e.count) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "down": if !app.nav.init { return } if app.nav.down(e.count) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "half-down": if !app.nav.init { return } if app.nav.down(e.count * app.nav.height / 2) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "page-down": if !app.nav.init { return } if app.nav.down(e.count * app.nav.height) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "scroll-down": if !app.nav.init { return } if app.nav.scrollDown(e.count) { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "updir": if !app.nav.init { return } resetIncCmd(app) preChdir(app) for i := 0; i < e.count; i++ { if err := app.nav.updir(); err != nil { app.ui.echoerrf("%s", err) return } } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) restartIncCmd(app) onChdir(app) case "open": if !app.nav.init { return } curr, err := app.nav.currFile() if err != nil { app.ui.echoerrf("opening: %s", err) return } if curr.IsDir() { resetIncCmd(app) preChdir(app) err := app.nav.open() if err != nil { app.ui.echoerrf("opening directory: %s", err) return } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) restartIncCmd(app) onChdir(app) return } if gSelectionPath != "" { out, err := os.Create(gSelectionPath) if err != nil { log.Printf("opening selection file: %s", err) return } defer out.Close() var path string if list, err := app.nav.currFileOrSelections(); err == nil { path = strings.Join(list, "\n") } else { return } _, err = out.WriteString(path) if err != nil { log.Printf("writing selection file: %s", err) } app.quitChan <- struct{}{} return } if cmd, ok := gOpts.cmds["open"]; ok { cmd.eval(app, e.args) } case "jump-prev": resetIncCmd(app) preChdir(app) for i := 0; i < e.count; i++ { app.nav.cdJumpListPrev() } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) restartIncCmd(app) onChdir(app) case "jump-next": resetIncCmd(app) preChdir(app) for i := 0; i < e.count; i++ { app.nav.cdJumpListNext() } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) restartIncCmd(app) onChdir(app) case "quit": app.quitChan <- struct{}{} case "top": if !app.nav.init { return } if app.nav.top() { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "bottom": if !app.nav.init { return } if app.nav.bottom() { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "high": if !app.nav.init { return } if app.nav.high() { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "middle": if !app.nav.init { return } if app.nav.middle() { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "low": if !app.nav.init { return } if app.nav.low() { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "toggle": if !app.nav.init { return } if len(e.args) == 0 { app.nav.toggle() } else { dir := app.nav.currDir() for _, path := range e.args { path = replaceTilde(path) if !filepath.IsAbs(path) { path = filepath.Join(dir.path, path) } if _, err := os.Lstat(path); !os.IsNotExist(err) { app.nav.toggleSelection(path) } else { app.ui.echoerrf("toggle: %s", err) } } } case "tag-toggle": if !app.nav.init { return } tag := "*" if len(e.args) != 0 { tag = e.args[0] } if err := app.nav.tagToggle(tag); err != nil { app.ui.echoerrf("tag-toggle: %s", err) } else if err := app.nav.writeTags(); err != nil { app.ui.echoerrf("tag-toggle: %s", err) } if gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("tag-toggle: %s", err) } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("tag-toggle: %s", err) } } case "tag": if !app.nav.init { return } tag := "*" if len(e.args) != 0 { tag = e.args[0] } if err := app.nav.tag(tag); err != nil { app.ui.echoerrf("tag: %s", err) } else if err := app.nav.writeTags(); err != nil { app.ui.echoerrf("tag: %s", err) } if gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("tag: %s", err) } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("tag: %s", err) } } case "invert": if !app.nav.init { return } app.nav.invert() case "unselect": app.nav.unselect() case "calcdirsize": if !app.nav.init { return } err := app.nav.calcDirSize() if err != nil { app.ui.echoerrf("calcdirsize: %s", err) return } app.ui.loadFileInfo(app.nav) app.nav.sort() app.ui.sort() case "copy": if !app.nav.init { return } if err := app.nav.save(true); err != nil { app.ui.echoerrf("copy: %s", err) return } app.nav.unselect() if gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("copy: %s", err) return } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("copy: %s", err) return } } app.ui.loadFileInfo(app.nav) case "cut": if !app.nav.init { return } if err := app.nav.save(false); err != nil { app.ui.echoerrf("cut: %s", err) return } app.nav.unselect() if gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("cut: %s", err) return } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("cut: %s", err) return } } app.ui.loadFileInfo(app.nav) case "paste": if !app.nav.init { return } if cmd, ok := gOpts.cmds["paste"]; ok { cmd.eval(app, e.args) } else if err := app.nav.paste(app); err != nil { app.ui.echoerrf("paste: %s", err) return } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) case "delete": if !app.nav.init { return } if cmd, ok := gOpts.cmds["delete"]; ok { cmd.eval(app, e.args) app.nav.unselect() if gSingleMode { app.nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { app.ui.echoerrf("delete: %s", err) return } } } else { list, err := app.nav.currFileOrSelections() if err != nil { app.ui.echoerrf("delete: %s", err) return } if app.ui.cmdPrefix == ">" { return } normal(app) if len(list) == 1 { app.ui.cmdPrefix = "delete '" + list[0] + "' ? [y/N] " } else { app.ui.cmdPrefix = "delete " + strconv.Itoa(len(list)) + " items? [y/N] " } } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) case "clear": if !app.nav.init { return } if err := saveFiles(nil, false); err != nil { app.ui.echoerrf("clear: %s", err) return } if gSingleMode { if err := app.nav.sync(); err != nil { app.ui.echoerrf("clear: %s", err) return } } else { if err := remote("send sync"); err != nil { app.ui.echoerrf("clear: %s", err) return } } app.ui.loadFileInfo(app.nav) case "draw": case "redraw": if !app.nav.init { return } app.ui.renew() app.ui.screen.Sync() if app.nav.height != app.ui.wins[0].h { app.nav.height = app.ui.wins[0].h app.nav.regCache = make(map[string]*reg) } app.ui.loadFile(app, true) case "load": if !app.nav.init { return } app.nav.renew() app.ui.loadFile(app, true) case "reload": if !app.nav.init { return } if err := app.nav.reload(); err != nil { app.ui.echoerrf("reload: %s", err) } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) case "read": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = ":" app.ui.loadFileInfo(app.nav) case "shell": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "$" app.ui.loadFileInfo(app.nav) case "shell-pipe": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "%" app.ui.loadFileInfo(app.nav) case "shell-wait": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "!" app.ui.loadFileInfo(app.nav) case "shell-async": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "&" app.ui.loadFileInfo(app.nav) case "find": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "find: " app.nav.findBack = false app.ui.loadFileInfo(app.nav) case "find-back": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "find-back: " app.nav.findBack = true app.ui.loadFileInfo(app.nav) case "find-next": if !app.nav.init { return } dir := app.nav.currDir() old := dir.ind for i := 0; i < e.count; i++ { if app.nav.findBack { app.nav.findPrev() } else { app.nav.findNext() } } if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "find-prev": if !app.nav.init { return } dir := app.nav.currDir() old := dir.ind for i := 0; i < e.count; i++ { if app.nav.findBack { app.nav.findNext() } else { app.nav.findPrev() } } if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "search": if !app.nav.init { return } if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "/" dir := app.nav.currDir() app.nav.searchInd = dir.ind app.nav.searchPos = dir.pos app.nav.searchBack = false app.ui.loadFileInfo(app.nav) case "search-back": if !app.nav.init { return } if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "?" dir := app.nav.currDir() app.nav.searchInd = dir.ind app.nav.searchPos = dir.pos app.nav.searchBack = true app.ui.loadFileInfo(app.nav) case "search-next": if !app.nav.init { return } for i := 0; i < e.count; i++ { if app.nav.searchBack { if moved, err := app.nav.searchPrev(); err != nil { app.ui.echoerrf("search-back: %s: %s", err, app.nav.search) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } else { if moved, err := app.nav.searchNext(); err != nil { app.ui.echoerrf("search: %s: %s", err, app.nav.search) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } } case "search-prev": if !app.nav.init { return } for i := 0; i < e.count; i++ { if app.nav.searchBack { if moved, err := app.nav.searchNext(); err != nil { app.ui.echoerrf("search-back: %s: %s", err, app.nav.search) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } else { if moved, err := app.nav.searchPrev(); err != nil { app.ui.echoerrf("search: %s: %s", err, app.nav.search) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } } } case "filter": if !app.nav.init { return } if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "filter: " dir := app.nav.currDir() app.nav.prevFilter = dir.filter if len(e.args) == 0 { app.ui.cmdAccLeft = []rune(strings.Join(dir.filter, " ")) } else { app.ui.cmdAccLeft = []rune(strings.Join(e.args, " ")) } app.ui.loadFileInfo(app.nav) case "setfilter": if !app.nav.init { return } log.Printf("filter: %s", e.args) if err := app.nav.setFilter(e.args); err != nil { app.ui.echoerrf("filter: %s", err) } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) case "mark-save": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "mark-save: " case "mark-load": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.menuBuf = listMarks(app.nav.marks) app.ui.cmdPrefix = "mark-load: " case "mark-remove": if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.menuBuf = listMarks(app.nav.marks) app.ui.cmdPrefix = "mark-remove: " case "rename": if !app.nav.init { return } if cmd, ok := gOpts.cmds["rename"]; ok { cmd.eval(app, e.args) if gSingleMode { app.nav.renew() app.ui.loadFile(app, true) } else { 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 } if app.ui.cmdPrefix == ">" { return } normal(app) app.ui.cmdPrefix = "rename: " app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(curr.Name())...) } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) case "sync": if err := app.nav.sync(); err != nil { app.ui.echoerrf("sync: %s", err) } case "echo": app.ui.echo(strings.Join(e.args, " ")) case "echomsg": app.ui.echomsg(strings.Join(e.args, " ")) case "echoerr": app.ui.echoerr(strings.Join(e.args, " ")) case "cd": path := "~" if len(e.args) > 0 { path = e.args[0] } wd, err := os.Getwd() if err != nil { log.Printf("getting current directory: %s", err) } path = replaceTilde(path) if !filepath.IsAbs(path) { path = filepath.Join(wd, path) } else { path = filepath.Clean(path) } if wd != path { resetIncCmd(app) preChdir(app) } if err := app.nav.cd(path); err != nil { app.ui.echoerrf("%s", err) return } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) if wd != path { app.nav.marks["'"] = wd restartIncCmd(app) onChdir(app) } case "select": if !app.nav.init { return } if len(e.args) != 1 { app.ui.echoerr("select: requires an argument") return } wd, err := os.Getwd() if err != nil { log.Printf("getting current directory: %s", err) } path := filepath.Dir(replaceTilde(e.args[0])) if !filepath.IsAbs(path) { path = filepath.Join(wd, path) } else { path = filepath.Clean(path) } if wd != path { resetIncCmd(app) preChdir(app) } if err := app.nav.sel(e.args[0]); err != nil { app.ui.echoerrf("%s", err) return } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) if wd != path { app.nav.marks["'"] = wd restartIncCmd(app) onChdir(app) } case "glob-select": if !app.nav.init { return } 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 } case "glob-unselect": if !app.nav.init { return } 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 } case "source": if len(e.args) != 1 { app.ui.echoerr("source: requires an argument") return } app.readFile(replaceTilde(e.args[0])) app.ui.loadFileInfo(app.nav) case "push": if len(e.args) != 1 { app.ui.echoerr("push: requires an argument") return } log.Println("pushing keys", e.args[0]) for _, val := range splitKeys(e.args[0]) { app.ui.keyChan <- val } case "cmd-insert": if len(e.args) == 0 { return } insert(app, e.args[0]) case "cmd-escape": if app.ui.cmdPrefix == ">" { return } normal(app) case "cmd-complete": matches := doComplete(app) app.ui.menuBuf = listMatches(app.ui.screen, matches, -1) case "cmd-menu-complete": menuComplete(app, 1) case "cmd-menu-complete-back": menuComplete(app, -1) case "cmd-menu-accept": app.ui.menuBuf = nil app.menuCompActive = false case "cmd-enter": s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...)) if len(s) == 0 && app.ui.cmdPrefix != "filter: " { return } app.ui.menuBuf = nil app.menuCompActive = false app.ui.cmdAccLeft = nil app.ui.cmdAccRight = nil switch app.ui.cmdPrefix { case ":": log.Printf("command: %s", s) app.ui.cmdPrefix = "" app.cmdHistory = append(app.cmdHistory, cmdItem{":", s}) p := newParser(strings.NewReader(s)) for p.parse() { p.expr.eval(app, nil) } if p.err != nil { app.ui.echoerrf("%s", p.err) } case "$": log.Printf("shell: %s", s) app.ui.cmdPrefix = "" app.cmdHistory = append(app.cmdHistory, cmdItem{"$", s}) app.runShell(s, nil, "$") case "%": log.Printf("shell-pipe: %s", s) app.cmdHistory = append(app.cmdHistory, cmdItem{"%", s}) app.runShell(s, nil, "%") case ">": io.WriteString(app.cmdIn, s+"\n") app.cmdOutBuf = nil case "!": log.Printf("shell-wait: %s", s) app.ui.cmdPrefix = "" app.cmdHistory = append(app.cmdHistory, cmdItem{"!", s}) app.runShell(s, nil, "!") case "&": log.Printf("shell-async: %s", s) app.ui.cmdPrefix = "" app.cmdHistory = append(app.cmdHistory, cmdItem{"&", s}) app.runShell(s, nil, "&") case "/": dir := app.nav.currDir() old := dir.ind if gOpts.incsearch { dir.ind = app.nav.searchInd dir.pos = app.nav.searchPos } log.Printf("search: %s", s) app.ui.cmdPrefix = "" app.nav.search = s if _, err := app.nav.searchNext(); err != nil { app.ui.echoerrf("search: %s: %s", err, app.nav.search) } else if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "?": dir := app.nav.currDir() old := dir.ind if gOpts.incsearch { dir.ind = app.nav.searchInd dir.pos = app.nav.searchPos } log.Printf("search-back: %s", s) app.ui.cmdPrefix = "" app.nav.search = s if _, err := app.nav.searchPrev(); err != nil { app.ui.echoerrf("search-back: %s: %s", err, app.nav.search) } else if old != dir.ind { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "filter: ": log.Printf("filter: %s", s) app.ui.cmdPrefix = "" if err := app.nav.setFilter(strings.Split(s, " ")); err != nil { app.ui.echoerrf("filter: %s", err) } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) case "find: ": app.ui.cmdPrefix = "" if moved, found := app.nav.findNext(); !found { app.ui.echoerrf("find: pattern not found: %s", app.nav.find) } else if moved { app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } case "find-back: ": app.ui.cmdPrefix = "" if moved, found := app.nav.findPrev(); !found { app.ui.echoerrf("find-back: pattern not found: %s", app.nav.find) } else if moved { app.ui.loadFile(app, true) 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 } oldPath := filepath.Join(wd, curr.Name()) newPath := filepath.Clean(replaceTilde(s)) if !filepath.IsAbs(newPath) { newPath = filepath.Join(wd, newPath) } if oldPath == newPath { return } app.nav.renameOldPath = oldPath app.nav.renameNewPath = newPath newDir := filepath.Dir(newPath) if _, err := os.Stat(newDir); os.IsNotExist(err) { app.ui.cmdPrefix = "create '" + newDir + "' ? [y/N] " return } oldStat, err := os.Lstat(oldPath) if err != nil { app.ui.echoerrf("rename: %s", err) return } if newStat, err := os.Lstat(newPath); !os.IsNotExist(err) && !os.SameFile(oldStat, newStat) { app.ui.cmdPrefix = "replace '" + newPath + "' ? [y/N] " return } if err := app.nav.rename(); err != nil { app.ui.echoerrf("rename: %s", err) return } if gSingleMode { app.nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { app.ui.echoerrf("rename: %s", err) return } } app.ui.loadFile(app, true) app.ui.loadFileInfo(app.nav) } default: log.Printf("entering unknown execution prefix: %q", app.ui.cmdPrefix) } case "cmd-history-next": if app.ui.cmdPrefix == "" || app.ui.cmdPrefix == ">" { return } if app.cmdHistoryInd > 0 { app.cmdHistoryInd-- } if app.cmdHistoryInd == 0 { normal(app) app.ui.cmdPrefix = ":" return } historyInd := app.cmdHistoryInd cmd := app.cmdHistory[len(app.cmdHistory)-historyInd] normal(app) app.cmdHistoryInd = historyInd app.ui.cmdPrefix = cmd.prefix app.ui.cmdAccLeft = []rune(cmd.value) case "cmd-history-prev": if app.ui.cmdPrefix == ">" { return } if app.cmdHistoryInd == len(app.cmdHistory) { return } historyInd := app.cmdHistoryInd + 1 cmd := app.cmdHistory[len(app.cmdHistory)-historyInd] normal(app) app.cmdHistoryInd = historyInd app.ui.cmdPrefix = cmd.prefix app.ui.cmdAccLeft = []rune(cmd.value) case "cmd-delete": if len(app.ui.cmdAccRight) == 0 { return } app.ui.cmdAccRight = app.ui.cmdAccRight[1:] update(app) case "cmd-delete-back": if len(app.ui.cmdAccLeft) == 0 { switch app.ui.cmdPrefix { case "!", "$", "%", "&": app.ui.cmdPrefix = ":" case ">": // Don't mess with the program waiting for input default: normal(app) } return } app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] update(app) case "cmd-left": if len(app.ui.cmdAccLeft) == 0 { return } app.ui.cmdAccRight = append([]rune{app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1]}, app.ui.cmdAccRight...) app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] case "cmd-right": if len(app.ui.cmdAccRight) == 0 { return } app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[0]) app.ui.cmdAccRight = app.ui.cmdAccRight[1:] case "cmd-home": app.ui.cmdAccRight = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) app.ui.cmdAccLeft = nil case "cmd-end": app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) app.ui.cmdAccRight = nil case "cmd-delete-home": if len(app.ui.cmdAccLeft) == 0 { return } app.ui.cmdYankBuf = app.ui.cmdAccLeft app.ui.cmdAccLeft = nil update(app) case "cmd-delete-end": if len(app.ui.cmdAccRight) == 0 { return } app.ui.cmdYankBuf = app.ui.cmdAccRight app.ui.cmdAccRight = nil update(app) case "cmd-delete-unix-word": ind := strings.LastIndex(strings.TrimRight(string(app.ui.cmdAccLeft), " "), " ") + 1 app.ui.cmdYankBuf = []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...) update(app) case "cmd-transpose": if len(app.ui.cmdAccLeft) < 2 { return } app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1], app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-2] = app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-2], app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1] update(app) case "cmd-interrupt": if app.cmd != nil { err := shellKill(app.cmd) if err != nil { app.ui.echoerrf("kill: %s", err) } else { app.ui.echoerr("process interrupt") } } normal(app) case "cmd-word": if len(app.ui.cmdAccRight) == 0 { return } loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight)) if loc == nil { return } 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.FindAllStringSubmatchIndex(string(app.ui.cmdAccLeft), -1) if locs == nil { return } ind := locs[len(locs)-1][3] old := app.ui.cmdAccRight app.ui.cmdAccRight = append([]rune{}, []rune(string(app.ui.cmdAccLeft)[ind:])...) app.ui.cmdAccRight = append(app.ui.cmdAccRight, old...) app.ui.cmdAccLeft = []rune(string(app.ui.cmdAccLeft)[:ind]) case "cmd-capitalize-word": if len(app.ui.cmdAccRight) == 0 { return } ind := 0 for ; ind < len(app.ui.cmdAccRight) && unicode.IsSpace(app.ui.cmdAccRight[ind]); ind++ { } if ind >= len(app.ui.cmdAccRight) { return } app.ui.cmdAccRight[ind] = unicode.ToUpper(app.ui.cmdAccRight[ind]) loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight)) if loc == nil { return } 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.FindStringSubmatchIndex(string(app.ui.cmdAccRight)) if loc == nil { return } 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.FindStringSubmatchIndex(string(app.ui.cmdAccRight)) if loc == nil { return } 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.FindStringSubmatchIndex(string(app.ui.cmdAccRight)) if loc == nil { return } 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 { return } locs := reWord.FindAllStringIndex(string(app.ui.cmdAccLeft), -1) if len(locs) < 2 { return } if len(app.ui.cmdAccRight) > 0 { loc := reWordEnd.FindStringSubmatchIndex(string(app.ui.cmdAccRight)) if loc != nil { 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:]) } } locs = reWord.FindAllStringIndex(string(app.ui.cmdAccLeft), -1) beg1, end1 := locs[len(locs)-2][0], locs[len(locs)-2][1] beg2, end2 := locs[len(locs)-1][0], locs[len(locs)-1][1] var acc []rune 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) default: cmd, ok := gOpts.cmds[e.name] if !ok { app.ui.echoerrf("command not found: %s", e.name) return } cmd.eval(app, e.args) } } func (e *execExpr) eval(app *app, args []string) { switch e.prefix { case "$": log.Printf("shell: %s -- %s", e, args) app.runShell(e.value, args, e.prefix) case "%": log.Printf("shell-pipe: %s -- %s", e, args) app.runShell(e.value, args, e.prefix) case "!": log.Printf("shell-wait: %s -- %s", e, args) app.runShell(e.value, args, e.prefix) case "&": log.Printf("shell-async: %s -- %s", e, args) app.runShell(e.value, args, e.prefix) default: log.Printf("evaluating unknown execution prefix: %q", e.prefix) } } func (e *listExpr) eval(app *app, args []string) { for i := 0; i < e.count; i++ { for _, expr := range e.exprs { expr.eval(app, nil) } } } lf-r28/eval_test.go000066400000000000000000000244431435165676200144330ustar00rootroot00000000000000package main import ( "reflect" "strings" "testing" ) var gEvalTests = []struct { inp string toks []string exprs []expr }{ { "", []string{}, nil, }, { "# comments start with '#'", []string{}, nil, }, { "echo hello", []string{"echo", "hello", "\n"}, []expr{&callExpr{"echo", []string{"hello"}, 1}}, }, { "echo hello world", []string{"echo", "hello", "world", "\n"}, []expr{&callExpr{"echo", []string{"hello", "world"}, 1}}, }, { "echo 'hello world'", []string{"echo", "hello world", "\n"}, []expr{&callExpr{"echo", []string{"hello world"}, 1}}, }, { `echo "hello world"`, []string{"echo", "hello world", "\n"}, []expr{&callExpr{"echo", []string{"hello world"}, 1}}, }, { `echo "hello\"world"`, []string{"echo", `hello"world`, "\n"}, []expr{&callExpr{"echo", []string{`hello"world`}, 1}}, }, { `echo "hello\tworld"`, []string{"echo", "hello\tworld", "\n"}, []expr{&callExpr{"echo", []string{"hello\tworld"}, 1}}, }, { `echo "hello\nworld"`, []string{"echo", "hello\nworld", "\n"}, []expr{&callExpr{"echo", []string{"hello\nworld"}, 1}}, }, { `echo "hello\zworld"`, []string{"echo", `hello\zworld`, "\n"}, []expr{&callExpr{"echo", []string{`hello\zworld`}, 1}}, }, { `echo "hello\0world"`, []string{"echo", "hello\000world", "\n"}, []expr{&callExpr{"echo", []string{"hello\000world"}, 1}}, }, { `echo "hello\101world"`, []string{"echo", "hello\101world", "\n"}, []expr{&callExpr{"echo", []string{"hello\101world"}, 1}}, }, { `echo hello\ world`, []string{"echo", "hello world", "\n"}, []expr{&callExpr{"echo", []string{"hello world"}, 1}}, }, { "echo hello\\\tworld", []string{"echo", "hello\tworld", "\n"}, []expr{&callExpr{"echo", []string{"hello\tworld"}, 1}}, }, { "echo hello\\\nworld", []string{"echo", "hello\nworld", "\n"}, []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", "hellozworld", "\n"}, []expr{&callExpr{"echo", []string{"hellozworld"}, 1}}, }, { "set hidden # trailing comments are allowed", []string{"set", "hidden", "\n"}, []expr{&setExpr{"hidden", ""}}, }, { "set hidden; set preview", []string{"set", "hidden", ";", "set", "preview", "\n"}, []expr{&setExpr{"hidden", ""}, &setExpr{"preview", ""}}, }, { "set hidden\nset preview", []string{"set", "hidden", "\n", "set", "preview", "\n"}, []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"}, []expr{&setExpr{"ratios", "1:2:3"}}, }, { "set ratios 1:2:3;", []string{"set", "ratios", "1:2:3", ";"}, []expr{&setExpr{"ratios", "1:2:3"}}, }, { ":set ratios 1:2:3", []string{":", "set", "ratios", "1:2:3", "\n", "\n"}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}}, }, { ":set ratios 1:2:3\nset hidden", []string{":", "set", "ratios", "1:2:3", "\n", "\n", "set", "hidden", "\n"}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}, &setExpr{"hidden", ""}}, }, { ":set ratios 1:2:3;", []string{":", "set", "ratios", "1:2:3", ";", "\n"}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}}, }, { ":set ratios 1:2:3;\nset hidden", []string{":", "set", "ratios", "1:2:3", ";", "\n", "set", "hidden", "\n"}, []expr{&listExpr{[]expr{&setExpr{"ratios", "1:2:3"}}, 1}, &setExpr{"hidden", ""}}, }, { "set ratios 1:2:3\n set hidden", []string{"set", "ratios", "1:2:3", "\n", "set", "hidden", "\n"}, []expr{&setExpr{"ratios", "1:2:3"}, &setExpr{"hidden", ""}}, }, { "set ratios 1:2:3 \nset hidden", []string{"set", "ratios", "1:2:3", "\n", "set", "hidden", "\n"}, []expr{&setExpr{"ratios", "1:2:3"}, &setExpr{"hidden", ""}}, }, { "map gh cd ~", []string{"map", "gh", "cd", "~", "\n"}, []expr{&mapExpr{"gh", &callExpr{"cd", []string{"~"}, 1}}}, }, { "map gh cd ~;", []string{"map", "gh", "cd", "~", ";"}, []expr{&mapExpr{"gh", &callExpr{"cd", []string{"~"}, 1}}}, }, { "map gh :cd ~", []string{"map", "gh", ":", "cd", "~", "\n", "\n"}, []expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}, 1}}}, }, { "map gh :cd ~;", []string{"map", "gh", ":", "cd", "~", ";", "\n"}, []expr{&mapExpr{"gh", &listExpr{[]expr{&callExpr{"cd", []string{"~"}, 1}}, 1}}}, }, { "cmap cmd-escape", []string{"cmap", "", "cmd-escape", "\n"}, []expr{&cmapExpr{"", &callExpr{"cmd-escape", nil, 1}}}, }, { "cmd usage $du -h . | less", []string{"cmd", "usage", "$", "du -h . | less", "\n"}, []expr{&cmdExpr{"usage", &execExpr{"$", "du -h . | less"}}}, }, { "cmd 世界 $echo 世界", []string{"cmd", "世界", "$", "echo 世界", "\n"}, []expr{&cmdExpr{"世界", &execExpr{"$", "echo 世界"}}}, }, { "map u usage", []string{"map", "u", "usage", "\n"}, []expr{&mapExpr{"u", &callExpr{"usage", nil, 1}}}, }, { "map u usage;", []string{"map", "u", "usage", ";"}, []expr{&mapExpr{"u", &callExpr{"usage", nil, 1}}}, }, { "map u :usage", []string{"map", "u", ":", "usage", "\n", "\n"}, []expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}, 1}}}, }, { "map u :usage;", []string{"map", "u", ":", "usage", ";", "\n"}, []expr{&mapExpr{"u", &listExpr{[]expr{&callExpr{"usage", nil, 1}}, 1}}}, }, { "map r push :rename", []string{"map", "r", "push", ":rename", "\n"}, []expr{&mapExpr{"r", &callExpr{"push", []string{":rename"}, 1}}}, }, { "map r push :rename;", []string{"map", "r", "push", ":rename;", "\n"}, []expr{&mapExpr{"r", &callExpr{"push", []string{":rename;"}, 1}}}, }, { "map r push :rename # trailing comments are allowed after a space", []string{"map", "r", "push", ":rename", "\n"}, []expr{&mapExpr{"r", &callExpr{"push", []string{":rename"}, 1}}}, }, { "map r :push :rename", []string{"map", "r", ":", "push", ":rename", "\n", "\n"}, []expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename"}, 1}}, 1}}}, }, { "map r :push :rename ; set hidden", []string{"map", "r", ":", "push", ":rename", ";", "set", "hidden", "\n", "\n"}, []expr{&mapExpr{"r", &listExpr{[]expr{&callExpr{"push", []string{":rename"}, 1}, &setExpr{"hidden", ""}}, 1}}}, }, { "map u $du -h . | less", []string{"map", "u", "$", "du -h . | less", "\n"}, []expr{&mapExpr{"u", &execExpr{"$", "du -h . | less"}}}, }, { "cmd usage $du -h $1 | less", []string{"cmd", "usage", "$", "du -h $1 | less", "\n"}, []expr{&cmdExpr{"usage", &execExpr{"$", "du -h $1 | less"}}}, }, { "map u usage /", []string{"map", "u", "usage", "/", "\n"}, []expr{&mapExpr{"u", &callExpr{"usage", []string{"/"}, 1}}}, }, { "map ss :set sortby size; set info size", []string{"map", "ss", ":", "set", "sortby", "size", ";", "set", "info", "size", "\n", "\n"}, []expr{&mapExpr{"ss", &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}}}, }, { "map ss :set sortby size; set info size;", []string{"map", "ss", ":", "set", "sortby", "size", ";", "set", "info", "size", ";", "\n"}, []expr{&mapExpr{"ss", &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1}}}, }, { `cmd gohome :{{ cd ~ set hidden }}`, []string{ "cmd", "gohome", ":", "{{", "cd", "~", "\n", "set", "hidden", "\n", "}}", "\n", }, []expr{&cmdExpr{ "gohome", &listExpr{[]expr{ &callExpr{"cd", []string{"~"}, 1}, &setExpr{"hidden", ""}, }, 1}, }}, }, { `map gh :{{ cd ~ set hidden }}`, []string{ "map", "gh", ":", "{{", "cd", "~", "\n", "set", "hidden", "\n", "}}", "\n", }, []expr{&mapExpr{ "gh", &listExpr{[]expr{ &callExpr{"cd", []string{"~"}, 1}, &setExpr{"hidden", ""}, }, 1}, }}, }, { `map c ${{ mkdir foo cp $fs foo tar -czvf foo.tar.gz foo rm -rf foo }}`, []string{"map", "c", "$", "{{", ` mkdir foo cp $fs foo tar -czvf foo.tar.gz foo rm -rf foo `, "}}", "\n"}, []expr{&mapExpr{"c", &execExpr{"$", ` mkdir foo cp $fs foo tar -czvf foo.tar.gz foo rm -rf foo `}}}, }, { `cmd compress ${{ mkdir $1 cp $fs $1 tar -czvf $1.tar.gz $1 rm -rf $1 }}`, []string{"cmd", "compress", "$", "{{", ` mkdir $1 cp $fs $1 tar -czvf $1.tar.gz $1 rm -rf $1 `, "}}", "\n"}, []expr{&cmdExpr{"compress", &execExpr{"$", ` mkdir $1 cp $fs $1 tar -czvf $1.tar.gz $1 rm -rf $1 `}}}, }, } func TestScan(t *testing.T) { for _, test := range gEvalTests { s := newScanner(strings.NewReader(test.inp)) for _, tok := range test.toks { if s.scan(); s.tok != tok { t.Errorf("at input '%s' expected '%s' but scanned '%s'", test.inp, tok, s.tok) } } if s.scan() { t.Errorf("at input '%s' unexpected '%s'", test.inp, s.tok) } } } func TestParse(t *testing.T) { for _, test := range gEvalTests { p := newParser(strings.NewReader(test.inp)) for _, expr := range test.exprs { if p.parse(); !reflect.DeepEqual(p.expr, expr) { t.Errorf("at input '%s' expected '%s' but parsed '%s'", test.inp, expr, p.expr) } } if p.parse(); p.expr != nil { t.Errorf("at input '%s' unexpected '%s'", test.inp, p.expr) } } } func TestSplitKeys(t *testing.T) { inps := []struct { s string keys []string }{ {"", nil}, {"j", []string{"j"}}, {"jk", []string{"j", "k"}}, {"1j", []string{"1", "j"}}, {"42j", []string{"4", "2", "j"}}, {"", []string{""}}, {"j", []string{"j", ""}}, {"jk", []string{"j", "", "k"}}, {"1jk", []string{"1", "j", "", "k"}}, {"1j1k", []string{"1", "j", "", "1", "k"}}, {"<>", []string{"<>"}}, {"", []string{""}}, {">", []string{">", ""}}, {">>", []string{">", "", ">"}}, } for _, inp := range inps { if keys := splitKeys(inp.s); !reflect.DeepEqual(keys, inp.keys) { t.Errorf("at input '%s' expected '%v' but got '%v'", inp.s, inp.keys, keys) } } } lf-r28/gen/000077500000000000000000000000001435165676200126605ustar00rootroot00000000000000lf-r28/gen/build.sh000077500000000000000000000007531435165676200143230ustar00rootroot00000000000000#!/bin/sh # Builds a static stripped binary with version information. # # This script is used to build a binary for the current platform. Cgo is # disabled to make sure the binary is statically linked. Appropriate flags are # given to the go compiler to strip the binary. Current git tag is passed to # the compiler by default to be used as the version in the binary. [ -z $version ] && version=$(git describe --tags) CGO_ENABLED=0 go build -ldflags="-s -w -X main.gVersion=$version" "$@" lf-r28/gen/docstring.sh000077500000000000000000000015051435165676200152140ustar00rootroot00000000000000#!/bin/sh # Generates `docstring.go` having `genDocString` variable with `go doc` output. # # This script is called in `doc.go` using `go generate` to embed the # documentation inside the binary in order to show it on request with `-doc` # command line flag. Thus the same documentation is used for online and # terminal display. tmp=gen/docstring.go echo "// Code generated by gen/docstring.sh DO NOT EDIT." >> $tmp echo >> $tmp echo "package main" >> $tmp echo >> $tmp echo "var genDocString = \`" >> $tmp go doc | tr "\`" "'" >> $tmp echo "\`" >> $tmp mv $tmp docstring.go lf-r28/gen/man.sh000077500000000000000000000032511435165676200137730ustar00rootroot00000000000000#!/bin/sh # Generates `lf.1` man page using man macros with `go doc` output. # # This script is called in `doc.go` using `go generate` to generate a man page # formatted with man macros from the documentation. A few additional sections # such as `NAME` and `SYNOPSIS` are added to comply with man page conventions. # # Conversion logic implemented here from godoc output to man macros should not # be considered compliant, as such it has inexact assumptions such as the use # of spaces over tabs along with various corner cases that are not handled # properly like character escaping. The intention here is to come up with # something that can convert the current content in the documentation. For this # reason, it is recommended to check the output after generation especially # when the documentation is changed in a significant way. out=lf.1 echo '.\" Code generated by gen/man.sh DO NOT EDIT.' > $out cat << END >> $out .TH LF 1 .SH NAME lf \- terminal file manager .SH SYNOPSIS .SY lf .OP \-command command .OP \-config path .OP \-cpuprofile path .OP \-doc .OP \-last-dir-path path .OP \-log path .OP \-memprofile path .OP \-remote command .OP \-selection-path path .OP \-server .OP \-single .OP \-version .OP \-help .RI [ cd-or-select-path ] .YS .SH DESCRIPTION END go doc | awk ' BEGIN { RS = "" start = 1 } # preformatted /^ / { gsub("\\\\", "\\e", $0) print ".PP" print ".EX" print $0 print ".EE" next } # heading /^# *[^[:punct:]]*$/ { gsub(/# */, "", $0) print ".SH", toupper($0) start = 1 next } # paragraph { gsub("\n", " ", $0) gsub("\\\\", "\\e", $0) if (start) { start = 0 } else { print ".PP" } print $0 } ' >> $out lf-r28/gen/xbuild.sh000077500000000000000000000144741435165676200145200ustar00rootroot00000000000000#!/bin/sh # Generates cross builds for all supported platforms. # # This script is used to build binaries for all supported platforms. Cgo is # disabled to make sure binaries are statically linked. Appropriate flags are # given to the go compiler to strip binaries. Current git tag is passed to the # compiler by default to be used as the version in binaries. These are then # compressed in an archive form (`.zip` for windows and `.tar.gz` for the rest) # within a folder named `dist`. set -o verbose [ -z $version ] && version=$(git describe --tags) mkdir -p dist # https://golang.org/doc/install/source#environment CGO_ENABLED=0 GOOS=android GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=dragonfly GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-dragonfly-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=freebsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-386.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=freebsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=freebsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-freebsd-arm.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=illumos GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-illumos-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-386.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-arm64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=ppc64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-ppc64le.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=mips go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=mipsle go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mipsle.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=mips64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=mips64le go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-mips64le.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=linux GOARCH=s390x go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-linux-s390x.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=netbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-386.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=netbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=netbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-netbsd-arm.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=openbsd GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-386.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=openbsd GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=openbsd GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=openbsd GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-openbsd-arm64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=solaris GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-solaris-amd64.tar.gz lf --remove-files CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-386.zip lf.exe --move CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && zip dist/lf-windows-amd64.zip lf.exe --move # not supported # CGO_ENABLED=0 GOOS=aix GOARCH=ppc64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-aix-ppc64.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=android GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-386.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=android GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-amd64.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=android GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-android-arm.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-darwin-arm64.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=js GOARCH=wasm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-js-wasm.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=plan9 GOARCH=386 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-386.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=plan9 GOARCH=amd64 go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-amd64.tar.gz lf --remove-files # CGO_ENABLED=0 GOOS=plan9 GOARCH=arm go build -ldflags="-s -w -X main.gVersion=$version" && tar czf dist/lf-plan9-arm.tar.gz lf --remove-files lf-r28/go.mod000066400000000000000000000004521435165676200132160ustar00rootroot00000000000000module github.com/gokcehan/lf go 1.12 require ( github.com/gdamore/tcell/v2 v2.5.4-0.20221019011350-d3cbfcfb7aa3 github.com/mattn/go-runewidth v0.0.14 golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 github.com/djherbis/times v1.5.0 ) lf-r28/go.sum000066400000000000000000000073521435165676200132510ustar00rootroot00000000000000github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko= github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg= github.com/gdamore/tcell/v2 v2.5.4-0.20221019011350-d3cbfcfb7aa3 h1:e5DXSPPfOBDJY9Z0geFZjEDok0/cUEI5QlPeTmqPV4I= github.com/gdamore/tcell/v2 v2.5.4-0.20221019011350-d3cbfcfb7aa3/go.mod h1:XmCynGHvvGG7UFI6az9zzoEHBvZB1PGf5APwOJMFUyE= github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= github.com/djherbis/times v1.5.0 h1:79myA211VwPhFTqUk8xehWrsEO+zcIZj0zT8mXPVARU= github.com/djherbis/times v1.5.0/go.mod h1:5q7FDLvbNg1L/KaBmPcWlVR9NmoKo3+ucqUA3ijQhA0= lf-r28/icons.go000066400000000000000000000051111435165676200135470ustar00rootroot00000000000000package main import ( "log" "os" "path/filepath" "strings" ) type iconMap map[string]string func parseIcons() iconMap { im := make(iconMap) defaultIcons := []string{ "ln=l", "or=l", "tw=t", "ow=d", "st=t", "di=d", "pi=p", "so=s", "bd=b", "cd=c", "su=u", "sg=g", "ex=x", "fi=-", } im.parseEnv(strings.Join(defaultIcons, ":")) if env := os.Getenv("LF_ICONS"); env != "" { im.parseEnv(env) } for _, path := range gIconsPaths { if _, err := os.Stat(path); !os.IsNotExist(err) { im.parseFile(path) } } return im } func (im iconMap) parseFile(path string) { log.Printf("reading file: %s", path) f, err := os.Open(path) if err != nil { log.Printf("opening icons file: %s", err) return } defer f.Close() pairs, err := readPairs(f) if err != nil { log.Printf("reading icons file: %s", err) return } for _, pair := range pairs { key, val := pair[0], pair[1] key = replaceTilde(key) if filepath.IsAbs(key) { key = filepath.Clean(key) } im[key] = val } } func (im iconMap) parseEnv(env string) { for _, entry := range strings.Split(env, ":") { if entry == "" { continue } pair := strings.Split(entry, "=") if len(pair) != 2 { log.Printf("invalid $LF_ICONS entry: %s", entry) return } key, val := pair[0], pair[1] key = replaceTilde(key) if filepath.IsAbs(key) { key = filepath.Clean(key) } im[key] = val } } func (im iconMap) get(f *file) string { if val, ok := im[f.path]; ok { return val } if f.IsDir() { if val, ok := im[f.Name()+"/"]; ok { return val } } var key string switch { case f.linkState == working: key = "ln" case f.linkState == broken: key = "or" case f.IsDir() && f.Mode()&os.ModeSticky != 0 && f.Mode()&0002 != 0: key = "tw" case f.IsDir() && f.Mode()&0002 != 0: key = "ow" case f.IsDir() && f.Mode()&os.ModeSticky != 0: key = "st" case f.IsDir(): key = "di" case f.Mode()&os.ModeNamedPipe != 0: key = "pi" case f.Mode()&os.ModeSocket != 0: key = "so" case f.Mode()&os.ModeDevice != 0: key = "bd" case f.Mode()&os.ModeCharDevice != 0: key = "cd" case f.Mode()&os.ModeSetuid != 0: key = "su" case f.Mode()&os.ModeSetgid != 0: key = "sg" case f.Mode()&0111 != 0: key = "ex" } if val, ok := im[key]; ok { return val } if val, ok := im[f.Name()+"*"]; ok { return val } if val, ok := im["*"+f.Name()]; ok { return val } if val, ok := im[filepath.Base(f.Name())+".*"]; ok { return val } if val, ok := im["*"+strings.ToLower(f.ext)]; ok { return val } if val, ok := im["fi"]; ok { return val } return " " } lf-r28/lf.1000066400000000000000000001766321435165676200126110ustar00rootroot00000000000000.\" Code generated by gen/man.sh DO NOT EDIT. .TH LF 1 .SH NAME lf \- terminal file manager .SH SYNOPSIS .SY lf .OP \-command command .OP \-config path .OP \-cpuprofile path .OP \-doc .OP \-last-dir-path path .OP \-log path .OP \-memprofile path .OP \-remote command .OP \-selection-path path .OP \-server .OP \-single .OP \-version .OP \-help .RI [ cd-or-select-path ] .YS .SH DESCRIPTION lf is a terminal file manager. .PP Source code can be found in the repository at https://github.com/gokcehan/lf .PP This documentation can either be read from terminal using 'lf -doc' or online at https://pkg.go.dev/github.com/gokcehan/lf You can also use 'doc' command (default '') inside lf to view the documentation in a pager. A man page with the same content is also available in the repository at https://github.com/gokcehan/lf/blob/master/lf.1 .PP You can run 'lf -help' to see descriptions of command line options. .SH QUICK REFERENCE The following commands are provided by lf: .PP .EX quit (default 'q') up (default 'k' and '') half-up (default '') page-up (default '' and '') scroll-up (default '') down (default 'j' and '') half-down (default '') page-down (default '' and '') scroll-down (default '') updir (default 'h' and '') open (default 'l' and '') jump-next (default ']') jump-prev (default '[') top (default 'gg' and '') bottom (default 'G' and '') high (default 'H') middle (default 'M') low (default 'L') toggle invert (default 'v') unselect (default 'u') glob-select glob-unselect calcdirsize copy (default 'y') cut (default 'd') paste (default 'p') clear (default 'c') sync draw redraw (default '') load reload (default '') echo echomsg echoerr cd select delete (modal) rename (modal) (default 'r') source push read (modal) (default ':') shell (modal) (default '$') shell-pipe (modal) (default '%') shell-wait (modal) (default '!') shell-async (modal) (default '&') find (modal) (default 'f') find-back (modal) (default 'F') find-next (default ';') find-prev (default ',') search (modal) (default '/') search-back (modal) (default '?') search-next (default 'n') search-prev (default 'N') filter (modal) setfilter mark-save (modal) (default 'm') mark-load (modal) (default "'") mark-remove (modal) (default '"') tag tag-toggle (default 't') .EE .PP The following command line commands are provided by lf: .PP .EX cmd-escape (default '') cmd-complete (default '') cmd-menu-complete cmd-menu-complete-back cmd-menu-accept cmd-enter (default '' and '') cmd-interrupt (default '') cmd-history-next (default '') cmd-history-prev (default '') cmd-left (default '' and '') cmd-right (default '' and '') cmd-home (default '' and '') cmd-end (default '' and '') cmd-delete (default '' and '') cmd-delete-back (default '' and '') cmd-delete-home (default '') cmd-delete-end (default '') cmd-delete-unix-word (default '') cmd-yank (default '') cmd-transpose (default '') cmd-transpose-word (default '') cmd-word (default '') cmd-word-back (default '') cmd-delete-word (default '') cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') .EE .PP The following options can be used to customize the behavior of lf: .PP .EX anchorfind bool (default on) autoquit bool (default off) cleaner string (default '') dircache bool (default on) dircounts bool (default off) dirfirst bool (default on) dironly bool (default off) dirpreviews bool (default off) drawbox bool (default off) errorfmt string (default "\e033[7;31;47m%s\e033[0m") filesep string (default "\en") findlen int (default 1) globsearch bool (default off) hidden bool (default off) hiddenfiles []string (default '.*') history bool (default on) icons bool (default off) ifs string (default '') ignorecase bool (default on) ignoredia bool (default on) incfilter bool (default off) incsearch bool (default off) info []string (default '') infotimefmtnew string (default 'Jan _2 15:04') infotimefmtold string (default 'Jan _2 2006') mouse bool (default off) number bool (default off) period int (default 0) preview bool (default on) previewer string (default '') promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%d\e033[0m\e033[1m%f\e033[0m") ratios []int (default '1:2:3') relativenumber bool (default off) reverse bool (default off) scrolloff int (default 0) selmode string (default 'all') shell string (default 'sh' for Unix and 'cmd' for Windows) shellflag string (default '-c' for Unix and '/c' for Windows) shellopts []string (default '') smartcase bool (default on) smartdia bool (default off) sortby string (default 'natural') tabstop int (default 8) tagfmt string (default "\e033[31m%s\e033[0m") tempmarks string (default '') timefmt string (default 'Mon Jan _2 15:04:05 2006') truncatechar string (default '~') waitmsg string (default 'Press any key to continue') wrapscan bool (default on) wrapscroll bool (default off) user_{option} string (default none) .EE .PP The following environment variables are exported for shell commands: .PP .EX f fs fx id PWD OLDPWD LF_LEVEL OPENER EDITOR PAGER SHELL lf_{option} lf_user_{option} lf_width lf_height .EE .PP The following special shell commands are used to customize the behavior of lf when defined: .PP .EX open paste rename delete pre-cd on-cd on-select on-quit .EE .PP The following commands/keybindings are provided by default: .PP .EX Unix Windows cmd open &$OPENER "$f" cmd open &%OPENER% %f% map e $$EDITOR "$f" map e $%EDITOR% %f% map i $$PAGER "$f" map i !%PAGER% %f% map w $$SHELL map w $%SHELL% .EE .PP The following additional keybindings are provided by default: .PP .EX map zh set hidden! map zr set reverse! map zn set info map zs set info size map zt set info time map za set info size:time map sn :set sortby natural; set info map ss :set sortby size; set info size map st :set sortby time; set info time map sa :set sortby atime; set info atime map sc :set sortby ctime; set info ctime map se :set sortby ext; set info map gh cd ~ map :toggle; down .EE .PP If the 'mouse' option is enabled, mouse buttons have the following default effects: .PP .EX Left mouse button Click on a file or directory to select it. .EE .PP .EX Right mouse button Enter a directory or open a file. Also works on the preview window. .EE .PP .EX Scroll wheel Scroll up or down. .EE .SH CONFIGURATION Configuration files should be located at: .PP .EX OS system-wide user-specific Unix /etc/lf/lfrc ~/.config/lf/lfrc Windows C:\eProgramData\elf\elfrc C:\eUsers\e\eAppData\eLocal\elf\elfrc .EE .PP Colors file should be located at: .PP .EX OS system-wide user-specific Unix /etc/lf/colors ~/.config/lf/colors Windows C:\eProgramData\elf\ecolors C:\eUsers\e\eAppData\eLocal\elf\ecolors .EE .PP Icons file should be located at: .PP .EX OS system-wide user-specific Unix /etc/lf/icons ~/.config/lf/icons Windows C:\eProgramData\elf\eicons C:\eUsers\e\eAppData\eLocal\elf\eicons .EE .PP Selection file should be located at: .PP .EX Unix ~/.local/share/lf/files Windows C:\eUsers\e\eAppData\eLocal\elf\efiles .EE .PP Marks file should be located at: .PP .EX Unix ~/.local/share/lf/marks Windows C:\eUsers\e\eAppData\eLocal\elf\emarks .EE .PP Tags file should be located at: .PP .EX Unix ~/.local/share/lf/tags Windows C:\eUsers\e\eAppData\eLocal\elf\etags .EE .PP History file should be located at: .PP .EX Unix ~/.local/share/lf/history Windows C:\eUsers\e\eAppData\eLocal\elf\ehistory .EE .PP You can configure the default values of following variables to change these locations: .PP .EX $XDG_CONFIG_HOME ~/.config $XDG_DATA_HOME ~/.local/share %ProgramData% C:\eProgramData %LOCALAPPDATA% C:\eUsers\e\eAppData\eLocal .EE .PP A sample configuration file can be found at https://github.com/gokcehan/lf/blob/master/etc/lfrc.example .SH COMMANDS This section shows information about builtin commands. Modal commands do not take any arguments, but instead change the operation mode to read their input conveniently, and so they are meant to be assigned to keybindings. .PP .EX quit (default 'q') .EE .PP Quit lf and return to the shell. .PP .EX up (default 'k' and '') half-up (default '') page-up (default '' and '') scroll-up (default '') down (default 'j' and '') half-down (default '') page-down (default '' and '') scroll-down (default '') .EE .PP Move/scroll the current file selection upwards/downwards by one/half a page/full page. .PP .EX updir (default 'h' and '') .EE .PP Change the current working directory to the parent directory. .PP .EX open (default 'l' and '') .EE .PP If the current file is a directory, then change the current directory to it, otherwise, execute the 'open' command. A default 'open' command is provided to call the default system opener asynchronously with the current file as the argument. A custom 'open' command can be defined to override this default. .PP .EX jump-next (default ']') jump-prev (default '[') .EE .PP Change the current working directory to the next/previous jumplist item. .PP .EX top (default 'gg' and '') bottom (default 'G' and '') .EE .PP Move the current file selection to the top/bottom of the directory. .PP .EX high (default 'H') middle (default 'M') low (default 'L') .EE .PP Move the current file selection to the high/middle/low of the screen. .PP .EX toggle .EE .PP Toggle the selection of the current file or files given as arguments. .PP .EX invert (default 'v') .EE .PP Reverse the selection of all files in the current directory (i.e. 'toggle' all files). Selections in other directories are not effected by this command. You can define a new command to select all files in the directory by combining 'invert' with 'unselect' (i.e. 'cmd select-all :unselect; invert'), though this will also remove selections in other directories. .PP .EX unselect (default 'u') .EE .PP Remove the selection of all files in all directories. .PP .EX glob-select glob-unselect .EE .PP Select/unselect files that match the given glob. .PP .EX calcdirsize .EE .PP Calculate the total size for each of the selected directories. Option 'info' should include 'size' and option 'dircounts' should be disabled to show this size. If the total size of a directory is not calculated, it will be shown as '-'. .PP .EX copy (default 'y') .EE .PP If there are no selections, save the path of the current file to the copy buffer, otherwise, copy the paths of selected files. .PP .EX cut (default 'd') .EE .PP If there are no selections, save the path of the current file to the cut buffer, otherwise, copy the paths of selected files. .PP .EX paste (default 'p') .EE .PP Copy/Move files in copy/cut buffer to the current working directory. A custom 'paste' command can be defined to override this default. .PP .EX clear (default 'c') .EE .PP Clear file paths in copy/cut buffer. .PP .EX sync .EE .PP Synchronize copied/cut files with server. This command is automatically called when required. .PP .EX draw .EE .PP Draw the screen. This command is automatically called when required. .PP .EX redraw (default '') .EE .PP Synchronize the terminal and redraw the screen. .PP .EX load .EE .PP Load modified files and directories. This command is automatically called when required. .PP .EX reload (default '') .EE .PP Flush the cache and reload all files and directories. .PP .EX echo .EE .PP Print given arguments to the message line at the bottom. .PP .EX echomsg .EE .PP Print given arguments to the message line at the bottom and also to the log file. .PP .EX echoerr .EE .PP Print given arguments to the message line at the bottom as 'errorfmt' and also to the log file. .PP .EX cd .EE .PP Change the working directory to the given argument. .PP .EX select .EE .PP Change the current file selection to the given argument. .PP .EX delete (modal) .EE .PP Remove the current file or selected file(s). A custom 'delete' command can be defined to override this default. .PP .EX rename (modal) (default 'r') .EE .PP Rename the current file using the builtin method. A custom 'rename' command can be defined to override this default. .PP .EX source .EE .PP Read the configuration file given in the argument. .PP .EX push .EE .PP Simulate key pushes given in the argument. .PP .EX read (modal) (default ':') .EE .PP Read a command to evaluate. .PP .EX shell (modal) (default '$') .EE .PP Read a shell command to execute. .PP .EX shell-pipe (modal) (default '%') .EE .PP Read a shell command to execute piping its standard I/O to the bottom statline. .PP .EX shell-wait (modal) (default '!') .EE .PP Read a shell command to execute and wait for a key press in the end. .PP .EX shell-async (modal) (default '&') .EE .PP Read a shell command to execute asynchronously without standard I/O. .PP .EX find (modal) (default 'f') find-back (modal) (default 'F') find-next (default ';') find-prev (default ',') .EE .PP Read key(s) to find the appropriate file name match in the forward/backward direction and jump to the next/previous match. .PP .EX search (default '/') search-back (default '?') search-next (default 'n') search-prev (default 'N') .EE .PP Read a pattern to search for a file name match in the forward/backward direction and jump to the next/previous match. .PP .EX filter (modal) setfilter .EE .PP Command 'filter' reads a pattern to filter out and only view files matching the pattern. Command 'setfilter' does the same but uses an argument to set the filter immediately. You can supply an argument to 'filter', in order to use that as the starting prompt. .PP .EX mark-save (modal) (default 'm') .EE .PP Save the current directory as a bookmark assigned to the given key. .PP .EX mark-load (modal) (default "'") .EE .PP Change the current directory to the bookmark assigned to the given key. A special bookmark "'" holds the previous directory after a 'mark-load', 'cd', or 'select' command. .PP .EX mark-remove (modal) (default '"') .EE .PP Remove a bookmark assigned to the given key. .PP .EX tag .EE .PP Tag a file with '*' or a single width character given in the argument. You can define a new tag clearing command by combining 'tag' with 'tag-toggle' (i.e. 'cmd tag-clear :tag; tag-toggle'). .PP .EX tag-toggle (default 't') .EE .PP Tag a file with '*' or a single width character given in the argument if the file is untagged, otherwise remove the tag. .SH COMMAND LINE COMMANDS The prompt character specifies which of the several command-line modes you are in. For example, the 'read' command takes you to the ':' mode. .PP When the cursor is at the first character in ':' mode, pressing one of the keys '!', '$', '%', or '&' takes you to the corresponding mode. You can go back with 'cmd-delete-back' ('' by default). .PP The command line commands should be mostly compatible with readline keybindings. A character refers to a unicode code point, a word consists of letters and digits, and a unix word consists of any non-blank characters. .PP .EX cmd-escape (default '') .EE .PP Quit command line mode and return to normal mode. .PP .EX cmd-complete (default '') .EE .PP Autocomplete the current word. .PP .EX cmd-menu-complete cmd-menu-complete-back .EE .PP Autocomplete the current word with menu selection. You need to assign keys to these commands (e.g. 'cmap cmd-menu-complete; cmap cmd-menu-complete-back'). You can use the assigned keys assigned to display the menu and then cycle through completion options. .PP .EX cmd-menu-accept .EE .PP Accept the currently selected match in menu completion and close the menu. .PP .EX cmd-enter (default '' and '') .EE .PP Execute the current line. .PP .EX cmd-interrupt (default '') .EE .PP Interrupt the current shell-pipe command and return to the normal mode. .PP .EX cmd-history-next (default '') cmd-history-prev (default '') .EE .PP Go to next/previous item in the history. .PP .EX cmd-left (default '' and '') cmd-right (default '' and '') .EE .PP Move the cursor to the left/right. .PP .EX cmd-home (default '' and '') cmd-end (default '' and '') .EE .PP Move the cursor to the beginning/end of line. .PP .EX cmd-delete (default '' and '') .EE .PP Delete the next character. .PP .EX cmd-delete-back (default '' and '') .EE .PP Delete the previous character. When at the beginning of a prompt, returns either to normal mode or to ':' mode. .PP .EX cmd-delete-home (default '') cmd-delete-end (default '') .EE .PP Delete everything up to the beginning/end of line. .PP .EX cmd-delete-unix-word (default '') .EE .PP Delete the previous unix word. .PP .EX cmd-yank (default '') .EE .PP Paste the buffer content containing the last deleted item. .PP .EX cmd-transpose (default '') cmd-transpose-word (default '') .EE .PP Transpose the positions of last two characters/words. .PP .EX cmd-word (default '') cmd-word-back (default '') .EE .PP Move the cursor by one word in forward/backward direction. .PP .EX cmd-delete-word (default '') .EE .PP Delete the next word in forward direction. .PP .EX cmd-capitalize-word (default '') cmd-uppercase-word (default '') cmd-lowercase-word (default '') .EE .PP Capitalize/uppercase/lowercase the current word and jump to the next word. .SH OPTIONS This section shows information about options to customize the behavior. Character ':' is used as the separator for list options '[]int' and '[]string'. .PP .EX anchorfind bool (default on) .EE .PP When this option is enabled, find command starts matching patterns from the beginning of file names, otherwise, it can match at an arbitrary position. .PP .EX autoquit bool (default off) .EE .PP Automatically quit server when there are no clients left connected. .PP .EX cleaner string (default '') (not called if empty) .EE .PP Set the path of a cleaner file. The file should be executable. This file is called if previewing is enabled, the previewer is set, and the previously selected file had its preview cache disabled. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Preview clearing is disabled when the value of this option is left empty. .PP .EX dircache bool (default on) .EE .PP Cache directory contents. .PP .EX dircounts bool (default off) .EE .PP When this option is enabled, directory sizes show the number of items inside instead of the total size of the directory, which needs to be calculated for each directory using 'calcdirsize'. This information needs to be calculated by reading the directory and counting the items inside. Therefore, this option is disabled by default for performance reasons. This option only has an effect when 'info' has a 'size' field and the pane is wide enough to show the information. 999 items are counted per directory at most, and bigger directories are shown as '999+'. .PP .EX dirfirst bool (default on) .EE .PP Show directories first above regular files. .PP .EX dironly bool (default off) .EE .PP If enabled, directories will also be passed to the previewer script. This allows custom previews for directories. .PP .EX dirpreviews bool (default off) .EE .PP Show only directories. .PP .EX drawbox bool (default off) .EE .PP Draw boxes around panes with box drawing characters. .PP .EX errorfmt string (default "\e033[7;31;47m%s\e033[0m") .EE .PP Format string of error messages shown in the bottom message line. .PP .EX filesep string (default "\en") .EE .PP File separator used in environment variables 'fs' and 'fx'. .PP .EX findlen int (default 1) .EE .PP Number of characters prompted for the find command. When this value is set to 0, find command prompts until there is only a single match left. .PP .EX globsearch bool (default off) .EE .PP When this option is enabled, search command patterns are considered as globs, otherwise they are literals. With globbing, '*' matches any sequence, '?' matches any character, and '[...]' or '[^...] matches character sets or ranges. Otherwise, these characters are interpreted as they are. .PP .EX hidden bool (default off) .EE .PP Show hidden files. On Unix systems, hidden files are determined by the value of 'hiddenfiles'. On Windows, only files with hidden attributes are considered hidden files. .PP .EX hiddenfiles []string (default '.*') .EE .PP List of hidden file glob patterns. Patterns can be given as relative or absolute paths. Globbing supports the usual special characters, '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. In addition, if a pattern starts with '!', then its matches are excluded from hidden files. .PP .EX history bool (default on) .EE .PP Save command history. .PP .EX icons bool (default off) .EE .PP Show icons before each item in the list. .PP .EX ifs string (default '') .EE .PP Sets 'IFS' variable in shell commands. It works by adding the assignment to the beginning of the command string as "IFS='...'; ...". The reason is that 'IFS' variable is not inherited by the shell for security reasons. This method assumes a POSIX shell syntax and so it can fail for non-POSIX shells. This option has no effect when the value is left empty. This option does not have any effect on Windows. .PP .EX ignorecase bool (default on) .EE .PP Ignore case in sorting and search patterns. .PP .EX ignoredia bool (default on) .EE .PP Ignore diacritics in sorting and search patterns. .PP .EX incsearch bool (default off) .EE .PP Jump to the first match after each keystroke during searching. .PP .EX incfilter bool (default off) .EE .PP Apply filter pattern after each keystroke during filtering. .PP .EX info []string (default '') .EE .PP List of information shown for directory items at the right side of pane. Currently supported information types are 'size', 'time', 'atime', and 'ctime'. Information is only shown when the pane width is more than twice the width of information. .PP .EX infotimefmtnew string (default 'Jan _2 15:04') .EE .PP Format string of the file time shown in the info column when it matches this year. .PP .EX infotimefmtold string (default 'Jan _2 2006') .EE .PP Format string of the file time shown in the info column when it doesn't match this year. .PP .EX mouse bool (default off) .EE .PP Send mouse events as input. .PP .EX number bool (default off) .EE .PP Show the position number for directory items at the left side of pane. When 'relativenumber' option is enabled, only the current line shows the absolute position and relative positions are shown for the rest. .PP .EX period int (default 0) .EE .PP Set the interval in seconds for periodic checks of directory updates. This works by periodically calling the 'load' command. Note that directories are already updated automatically in many cases. This option can be useful when there is an external process changing the displayed directory and you are not doing anything in lf. Periodic checks are disabled when the value of this option is set to zero. .PP .EX preview bool (default on) .EE .PP Show previews of files and directories at the right most pane. If the file has more lines than the preview pane, rest of the lines are not read. Files containing the null character (U+0000) in the read portion are considered binary files and displayed as 'binary'. .PP .EX previewer string (default '') (not filtered if empty) .EE .PP Set the path of a previewer file to filter the content of regular files for previewing. The file should be executable. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. SIGPIPE signal is sent when enough lines are read. If the previewer returns a non-zero exit code, then the preview cache for the given file is disabled. This means that if the file is selected in the future, the previewer is called once again. Preview filtering is disabled and files are displayed as they are when the value of this option is left empty. .PP .EX promptfmt string (default "\e033[32;1m%u@%h\e033[0m:\e033[34;1m%d\e033[0m\e033[1m%f\e033[0m") .EE .PP Format string of the prompt shown in the top line. Special expansions are provided, '%u' as the user name, '%h' as the host name, '%w' as the working directory, '%d' as the working directory with a trailing path separator, '%f' as the file name, and '%F' as the current filter. '%S' may be used once and will provide a spacer so that the following parts are right aligned on the screen. Home folder is shown as '~' in the working directory expansion. Directory names are automatically shortened to a single character starting from the left most parent when the prompt does not fit to the screen. .PP .EX ratios []int (default '1:2:3') .EE .PP List of ratios of pane widths. Number of items in the list determines the number of panes in the ui. When 'preview' option is enabled, the right most number is used for the width of preview pane. .PP .EX relativenumber bool (default off) .EE .PP Show the position number relative to the current line. When 'number' is enabled, current line shows the absolute position, otherwise nothing is shown. .PP .EX reverse bool (default off) .EE .PP Reverse the direction of sort. .PP .EX selmode string (default 'all') .EE .PP Selection mode for commands. When set to 'all' it will use the selected files from all directories. When set to 'dir' it will only use the selected files in the current directory. .PP .EX scrolloff int (default 0) .EE .PP Minimum number of offset lines shown at all times in the top and the bottom of the screen when scrolling. The current line is kept in the middle when this option is set to a large value that is bigger than the half of number of lines. A smaller offset can be used when the current file is close to the beginning or end of the list to show the maximum number of items. .PP .EX shell string (default 'sh' for Unix and 'cmd' for Windows) .EE .PP Shell executable to use for shell commands. Shell commands are executed as 'shell shellopts shellflag command -- arguments'. .PP .EX shellflag string (default '-c' for Unix and '/c' for Windows) .EE .PP Command line flag used to pass shell commands. .PP .EX shellopts []string (default '') .EE .PP List of shell options to pass to the shell executable. .PP .EX smartcase bool (default on) .EE .PP Override 'ignorecase' option when the pattern contains an uppercase character. This option has no effect when 'ignorecase' is disabled. .PP .EX smartdia bool (default off) .EE .PP Override 'ignoredia' option when the pattern contains a character with diacritic. This option has no effect when 'ignoredia' is disabled. .PP .EX sortby string (default 'natural') .EE .PP Sort type for directories. Currently supported sort types are 'natural', 'name', 'size', 'time', 'ctime', 'atime', and 'ext'. .PP .EX tabstop int (default 8) .EE .PP Number of space characters to show for horizontal tabulation (U+0009) character. .PP .EX tagfmt string (default "\e033[31m%s\e033[0m") .EE .PP Format string of the tags. .PP .EX tempmarks string (default '') .EE .PP Marks to be considered temporary (e.g. 'abc' refers to marks 'a', 'b', and 'c'). These marks are not synced to other clients and they are not saved in the bookmarks file. Note that the special bookmark "'" is always treated as temporary and it does not need to be specified. .PP .EX timefmt string (default 'Mon Jan _2 15:04:05 2006') .EE .PP Format string of the file modification time shown in the bottom line. .PP .EX truncatechar string (default '~') .EE .PP Truncate character shown at the end when the file name does not fit to the pane. .PP .EX waitmsg string (default 'Press any key to continue') .EE .PP String shown after commands of shell-wait type. .PP .EX wrapscan bool (default on) .EE .PP Searching can wrap around the file list. .PP .EX wrapscroll bool (default off) .EE .PP Scrolling can wrap around the file list. .PP .EX user_{option} string (default none) .EE .PP Any option that is prefixed with 'user_' is a user defined option and can be set to any string. Inside a user defined command the value will be provided in the `lf_user_{option}` environment variable. These options are not used by lf and are not persisted. .SH ENVIRONMENT VARIABLES The following variables are exported for shell commands: These are referred with a '$' prefix on POSIX shells (e.g. '$f'), between '%' characters on Windows cmd (e.g. '%f%'), and with a '$env:' prefix on Windows powershell (e.g. '$env:f'). .PP .EX f .EE .PP Current file selection as a full path. .PP .EX fs .EE .PP Selected file(s) separated with the value of 'filesep' option as full path(s). .PP .EX fx .EE .PP Selected file(s) (i.e. 'fs') if there are any selected files, otherwise current file selection (i.e. 'f'). .PP .EX id .EE .PP Id of the running client. .PP .EX PWD .EE .PP Present working directory. .PP .EX OLDPWD .EE .PP Initial working directory. .PP .EX LF_LEVEL .EE .PP The value of this variable is set to the current nesting level when you run lf from a shell spawned inside lf. You can add the value of this variable to your shell prompt to make it clear that your shell runs inside lf. For example, with POSIX shells, you can use '[ -n "$LF_LEVEL" ] && PS1="$PS1""(lf level: $LF_LEVEL) "' in your shell configuration file (e.g. '~/.bashrc'). .PP .EX OPENER .EE .PP If this variable is set in the environment, use the same value, otherwise set the value to 'start' in Windows, 'open' in MacOS, 'xdg-open' in others. .PP .EX EDITOR .EE .PP If this variable is set in the environment, use the same value, otherwise set the value to 'vi' on Unix, 'notepad' in Windows. .PP .EX PAGER .EE .PP If this variable is set in the environment, use the same value, otherwise set the value to 'less' on Unix, 'more' in Windows. .PP .EX SHELL .EE .PP If this variable is set in the environment, use the same value, otherwise set the value to 'sh' on Unix, 'cmd' in Windows. .PP .EX lf_{option} .EE .PP Value of the {option}. .PP .EX lf_user_{option} .EE .PP Value of the user_{option}. .PP .EX lf_width lf_height .EE .PP Width/Height of the terminal. .SH SPECIAL COMMANDS This section shows information about special shell commands. .PP .EX open .EE .PP This shell command can be defined to override the default 'open' command when the current file is not a directory. .PP .EX paste .EE .PP This shell command can be defined to override the default 'paste' command. .PP .EX rename .EE .PP This shell command can be defined to override the default 'rename' command. .PP .EX delete .EE .PP This shell command can be defined to override the default 'delete' command. .PP .EX pre-cd .EE .PP This shell command can be defined to be executed before changing a directory. .PP .EX on-cd .EE .PP This shell command can be defined to be executed after changing a directory. .PP .EX on-select .EE .PP This shell command can be defined to be executed after the selection changes. .PP .EX on-quit .EE .PP This shell command can be defined to be executed before quit. .SH PREFIXES The following command prefixes are used by lf: .PP .EX : read (default) builtin/custom command $ shell shell command % shell-pipe shell command running with the ui ! shell-wait shell command waiting for key press & shell-async shell command running asynchronously .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. .SH SYNTAX Characters from '#' to newline are comments and ignored: .PP .EX # comments start with '#' .EE .PP There are four special commands ('set', 'map', 'cmap', and 'cmd') for configuration. .PP Command 'set' is used to set an option which can be boolean, integer, or string: .PP .EX set hidden # boolean on set nohidden # boolean off set hidden! # boolean toggle set scrolloff 10 # integer value set sortby time # string value w/o quotes set sortby 'time' # string value with single quotes (whitespaces) set sortby "time" # string value with double quotes (backslash escapes) .EE .PP Command 'map' is used to bind a key to a command which can be builtin command, custom command, or shell command: .PP .EX map gh cd ~ # builtin command map D trash # custom command map i $less $f # shell command map U !du -csh * # waiting shell command .EE .PP Command 'cmap' is used to bind a key on the command line to a command line command or any other command: .PP .EX cmap cmd-escape cmap set incsearch! .EE .PP You can delete an existing binding by leaving the expression empty: .PP .EX map gh # deletes 'gh' mapping cmap # deletes '' mapping .EE .PP Command 'cmd' is used to define a custom command: .PP .EX cmd usage $du -h -d1 | less .EE .PP You can delete an existing command by leaving the expression empty: .PP .EX cmd trash # deletes 'trash' command .EE .PP If there is no prefix then ':' is assumed: .PP .EX map zt set info time .EE .PP An explicit ':' can be provided to group statements until a newline which is especially useful for 'map' and 'cmd' commands: .PP .EX map st :set sortby time; set info time .EE .PP If you need multiline you can wrap statements in '{{' and '}}' after the proper prefix. .PP .EX map st :{{ set sortby time set info time }} .EE .SH KEY MAPPINGS Regular keys are assigned to a command with the usual syntax: .PP .EX map a down .EE .PP Keys combined with the shift key simply use the uppercase letter: .PP .EX map A down .EE .PP Special keys are written in between '<' and '>' characters and always use lowercase letters: .PP .EX map down .EE .PP Angle brackets can be assigned with their special names: .PP .EX map down map down .EE .PP Function keys are prefixed with 'f' character: .PP .EX map down .EE .PP Keys combined with the control key are prefixed with 'c' character: .PP .EX map down .EE .PP Keys combined with the alt key are assigned in two different ways depending on the behavior of your terminal. Older terminals (e.g. xterm) may set the 8th bit of a character when the alt key is pressed. On these terminals, you can use the corresponding byte for the mapping: .PP .EX map á down .EE .PP Newer terminals (e.g. gnome-terminal) may prefix the key with an escape key when the alt key is pressed. lf uses the escape delaying mechanism to recognize alt keys in these terminals (delay is 100ms). On these terminals, keys combined with the alt key are prefixed with 'a' character: .PP .EX map down .EE .PP Please note that, some key combinations are not possible due to the way terminals work (e.g. control and h combination sends a backspace key instead). The easiest way to find the name of a key combination is to press the key while lf is running and read the name of the key from the unknown mapping error. .PP Mouse buttons are prefixed with 'm' character: .PP .EX map down # primary map down # secondary map down # middle map down map down map down map down map down .EE .PP Mouse wheel events are also prefixed with 'm' character: .PP .EX map down map down map down map down .EE .SH PUSH MAPPINGS The usual way to map a key sequence is to assign it to a named or unnamed command. While this provides a clean way to remap builtin keys as well as other commands, it can be limiting at times. For this reason 'push' command is provided by lf. This command is used to simulate key pushes given as its arguments. You can 'map' a key to a 'push' command with an argument to create various keybindings. .PP This is mainly useful for two purposes. First, it can be used to map a command with a command count: .PP .EX map push 10j .EE .PP Second, it can be used to avoid typing the name when a command takes arguments: .PP .EX map r push :rename .EE .PP One thing to be careful is that since 'push' command works with keys instead of commands it is possible to accidentally create recursive bindings: .PP .EX map j push 2j .EE .PP These types of bindings create a deadlock when executed. .SH SHELL COMMANDS Regular shell commands are the most basic command type that is useful for many purposes. For example, we can write a shell command to move selected file(s) to trash. A first attempt to write such a command may look like this: .PP .EX cmd trash ${{ mkdir -p ~/.trash if [ -z "$fs" ]; then mv "$f" ~/.trash else IFS="$(printf '\en\et')"; mv $fs ~/.trash fi }} .EE .PP We check '$fs' to see if there are any selected files. Otherwise we just delete the current file. Since this is such a common pattern, a separate '$fx' variable is provided. We can use this variable to get rid of the conditional: .PP .EX cmd trash ${{ mkdir -p ~/.trash IFS="$(printf '\en\et')"; mv $fx ~/.trash }} .EE .PP The trash directory is checked each time the command is executed. We can move it outside of the command so it would only run once at startup: .PP .EX ${{ mkdir -p ~/.trash }} .EE .PP .EX cmd trash ${{ IFS="$(printf '\en\et')"; mv $fx ~/.trash }} .EE .PP Since these are one liners, we can drop '{{' and '}}': .PP .EX $mkdir -p ~/.trash .EE .PP .EX cmd trash $IFS="$(printf '\en\et')"; mv $fx ~/.trash .EE .PP Finally note that we set 'IFS' variable manually in these commands. Instead we could use the 'ifs' option to set it for all shell commands (i.e. 'set ifs "\en"'). This can be especially useful for interactive use (e.g. '$rm $f' or '$rm $fs' would simply work). This option is not set by default as it can behave unexpectedly for new users. However, use of this option is highly recommended and it is assumed in the rest of the documentation. .SH PIPING SHELL COMMANDS Regular shell commands have some limitations in some cases. When an output or error message is given and the command exits afterwards, the ui is immediately resumed and there is no way to see the message without dropping to shell again. Also, even when there is no output or error, the ui still needs to be paused while the command is running. This can cause flickering on the screen for short commands and similar distractions for longer commands. .PP Instead of pausing the ui, piping shell commands connects stdin, stdout, and stderr of the command to the statline in the bottom of the ui. This can be useful for programs following the Unix philosophy to give no output in the success case, and brief error messages or prompts in other cases. .PP For example, following rename command prompts for overwrite in the statline if there is an existing file with the given name: .PP .EX cmd rename %mv -i $f $1 .EE .PP You can also output error messages in the command and it will show up in the statline. For example, an alternative rename command may look like this: .PP .EX cmd rename %[ -e $1 ] && printf "file exists" || mv $f $1 .EE .PP Note that input is line buffered and output and error are byte buffered. .SH WAITING SHELL COMMANDS Waiting shell commands are similar to regular shell commands except that they wait for a key press when the command is finished. These can be useful to see the output of a program before the ui is resumed. Waiting shell commands are more appropriate than piping shell commands when the command is verbose and the output is best displayed as multiline. .SH ASYNCHRONOUS SHELL COMMANDS Asynchronous shell commands are used to start a command in the background and then resume operation without waiting for the command to finish. Stdin, stdout, and stderr of the command is neither connected to the terminal nor to the ui. .SH REMOTE COMMANDS One of the more advanced features in lf is remote commands. All clients connect to a server on startup. It is possible to send commands to all or any of the connected clients over the common server. This is used internally to notify file selection changes to other clients. .PP To use this feature, you need to use a client which supports communicating with a Unix domain socket. OpenBSD implementation of netcat (nc) is one such example. You can use it to send a command to the socket file: .PP .EX echo 'send echo hello world' | nc -U ${XDG_RUNTIME_DIR:-/tmp}/lf.${USER}.sock .EE .PP Since such a client may not be available everywhere, lf comes bundled with a command line flag to be used as such. When using lf, you do not need to specify the address of the socket file. This is the recommended way of using remote commands since it is shorter and immune to socket file address changes: .PP .EX lf -remote 'send echo hello world' .EE .PP In this command 'send' is used to send the rest of the string as a command to all connected clients. You can optionally give it an id number to send a command to a single client: .PP .EX lf -remote 'send 1234 echo hello world' .EE .PP All clients have a unique id number but you may not be aware of the id number when you are writing a command. For this purpose, an '$id' variable is exported to the environment for shell commands. The value of this variable is set to the process id of the client. You can use it to send a remote command from a client to the server which in return sends a command back to itself. So now you can display a message in the current client by calling the following in a shell command: .PP .EX lf -remote "send $id echo hello world" .EE .PP Since lf does not have control flow syntax, remote commands are used for such needs. For example, you can configure the number of columns in the ui with respect to the terminal width as follows: .PP .EX cmd recol %{{ if [ $lf_width -le 80 ]; then lf -remote "send $id set ratios 1:2" elif [ $lf_width -le 160 ]; then lf -remote "send $id set ratios 1:2:3" else lf -remote "send $id set ratios 1:2:3:5" fi }} .EE .PP Besides 'send' command, there is a 'quit' command to quit the server when there are no connected clients left, and a 'quit!' command to force quit the server by closing client connections first: .PP .EX lf -remote 'quit' lf -remote 'quit!' .EE .PP Lastly, there is a 'conn' command to connect the server as a client. This should not be needed for users. .SH FILE OPERATIONS lf uses its own builtin copy and move operations by default. These are implemented as asynchronous operations and progress is shown in the bottom ruler. These commands do not overwrite existing files or directories with the same name. Instead, a suffix that is compatible with '--backup=numbered' option in GNU cp is added to the new files or directories. Only file modes are preserved and all other attributes are ignored including ownership, timestamps, context, and xattr. Special files such as character and block devices, named pipes, and sockets are skipped and links are not followed. Moving is performed using the rename operation of the underlying OS. For cross-device moving, lf falls back to copying and then deletes the original files if there are no errors. Operation errors are shown in the message line as well as the log file and they do not preemptively finish the corresponding file operation. .PP File operations can be performed on the current selected file or alternatively on multiple files by selecting them first. When you 'copy' a file, lf doesn't actually copy the file on the disk, but only records its name to a file. The actual file copying takes place when you 'paste'. Similarly 'paste' after a 'cut' operation moves the file. .PP You can customize copy and move operations by defining a 'paste' command. This is a special command that is called when it is defined instead of the builtin implementation. You can use the following example as a starting point: .PP .EX cmd paste %{{ load=$(cat ~/.local/share/lf/files) mode=$(echo "$load" | sed -n '1p') list=$(echo "$load" | sed '1d') if [ $mode = 'copy' ]; then cp -R $list . elif [ $mode = 'move' ]; then mv $list . rm ~/.local/share/lf/files lf -remote 'send clear' fi }} .EE .PP Some useful things to be considered are to use the backup ('--backup') and/or preserve attributes ('-a') options with 'cp' and 'mv' commands if they support it (i.e. GNU implementation), change the command type to asynchronous, or use 'rsync' command with progress bar option for copying and feed the progress to the client periodically with remote 'echo' calls. .PP By default, lf does not assign 'delete' command to a key to protect new users. You can customize file deletion by defining a 'delete' command. You can also assign a key to this command if you like. An example command to move selected files to a trash folder and remove files completely after a prompt are provided in the example configuration file. .SH SEARCHING FILES There are two mechanisms implemented in lf to search a file in the current directory. Searching is the traditional method to move the selection to a file matching a given pattern. Finding is an alternative way to search for a pattern possibly using fewer keystrokes. .PP Searching mechanism is implemented with commands 'search' (default '/'), 'search-back' (default '?'), 'search-next' (default 'n'), and 'search-prev' (default 'N'). You can enable 'globsearch' option to match with a glob pattern. Globbing supports '*' to match any sequence, '?' to match any character, and '[...]' or '[^...] to match character sets or ranges. You can enable 'incsearch' option to jump to the current match at each keystroke while typing. In this mode, you can either use 'cmd-enter' to accept the search or use 'cmd-escape' to cancel the search. You can also map some other commands with 'cmap' to accept the search and execute the command immediately afterwards. For example, you can use the right arrow key to finish the search and open the selected file with the following mapping: .PP .EX cmap :cmd-enter; open .EE .PP Finding mechanism is implemented with commands 'find' (default 'f'), 'find-back' (default 'F'), 'find-next' (default ';'), 'find-prev' (default ','). You can disable 'anchorfind' option to match a pattern at an arbitrary position in the filename instead of the beginning. You can set the number of keys to match using 'findlen' option. If you set this value to zero, then the the keys are read until there is only a single match. Default values of these two options are set to jump to the first file with the given initial. .PP Some options effect both searching and finding. You can disable 'wrapscan' option to prevent searches to wrap around at the end of the file list. You can disable 'ignorecase' option to match cases in the pattern and the filename. This option is already automatically overridden if the pattern contains upper case characters. You can disable 'smartcase' option to disable this behavior. Two similar options 'ignoredia' and 'smartdia' are provided to control matching diacritics in latin letters. .SH OPENING FILES You can define a an 'open' command (default 'l' and '') to configure file opening. This command is only called when the current file is not a directory, otherwise the directory is entered instead. You can define it just as you would define any other command: .PP .EX cmd open $vi $fx .EE .PP It is possible to use different command types: .PP .EX cmd open &xdg-open $f .EE .PP You may want to use either file extensions or mime types from 'file' command: .PP .EX cmd open ${{ case $(file --mime-type -Lb $f) in text/*) vi $fx;; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; esac }} .EE .PP You may want to use 'setsid' before your opener command to have persistent processes that continue to run after lf quits. .PP Regular shell commands (i.e. '$') drop to terminal which results in a flicker for commands that finishes immediately (e.g. 'xdg-open' in the above example). If you want to use asynchronous shell commands (i.e. '&') but also want to use the terminal when necessary (e.g. 'vi' in the above exxample), you can use a remote command: .PP .EX cmd open &{{ case $(file --mime-type -Lb $f) in text/*) lf -remote "send $id \e$vi \e$fx";; *) for f in $fx; do xdg-open $f > /dev/null 2> /dev/null & done;; esac }} .EE .PP Note, asynchronous shell commands run in their own process group by default so they do not require the manual use of 'setsid'. .PP Following command is provided by default: .PP .EX cmd open &$OPENER $f .EE .PP You may also use any other existing file openers as you like. Possible options are 'libfile-mimeinfo-perl' (executable name is 'mimeopen'), 'rifle' (ranger's default file opener), or 'mimeo' to name a few. .SH PREVIEWING FILES lf previews files on the preview pane by printing the file until the end or the preview pane is filled. This output can be enhanced by providing a custom preview script for filtering. This can be used to highlight source codes, list contents of archive files or view pdf or image files to name a few. For coloring lf recognizes ansi escape codes. .PP In order to use this feature you need to set the value of 'previewer' option to the path of an executable file. Five arguments are passed to the file, (1) current file name, (2) width, (3) height, (4) horizontal position, and (5) vertical position of preview pane respectively. Output of the execution is printed in the preview pane. You may also want to use the same script in your pager mapping as well: .PP .EX set previewer ~/.config/lf/pv.sh map i $~/.config/lf/pv.sh $f | less -R .EE .PP For 'less' pager, you may instead utilize 'LESSOPEN' mechanism so that useful information about the file such as the full path of the file can still be displayed in the statusline below: .PP .EX set previewer ~/.config/lf/pv.sh map i $LESSOPEN='| ~/.config/lf/pv.sh %s' less -R $f .EE .PP Since this script is called for each file selection change it needs to be as efficient as possible and this responsibility is left to the user. You may use file extensions to determine the type of file more efficiently compared to obtaining mime types from 'file' command. Extensions can then be used to match cleanly within a conditional: .PP .EX #!/bin/sh .EE .PP .EX case "$1" in *.tar*) tar tf "$1";; *.zip) unzip -l "$1";; *.rar) unrar l "$1";; *.7z) 7z l "$1";; *.pdf) pdftotext "$1" -;; *) highlight -O ansi "$1";; esac .EE .PP Another important consideration for efficiency is the use of programs with short startup times for preview. For this reason, 'highlight' is recommended over 'pygmentize' for syntax highlighting. Besides, it is also important that the application is processing the file on the fly rather than first reading it to the memory and then do the processing afterwards. This is especially relevant for big files. lf automatically closes the previewer script output pipe with a SIGPIPE when enough lines are read. When everything else fails, you can make use of the height argument to only feed the first portion of the file to a program for preview. Note that some programs may not respond well to SIGPIPE to exit with a non-zero return code and avoid caching. You may add a trailing '|| true' command to avoid such errors: .PP .EX highlight -O ansi "$1" || true .EE .PP You may also use an existing preview filter as you like. Your system may already come with a preview filter named 'lesspipe'. These filters may have a mechanism to add user customizations as well. See the related documentations for more information. .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 lfcd wrapper shell scripts provided in the repository at https://github.com/gokcehan/lf/tree/master/etc .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%d\e033[0m\e033[1m%f$git\e033[0m" lf -remote "send $id set promptfmt \e"$fmt\e"" }} .EE .PP If you want to print escape sequences, you may redirect 'printf' output to '/dev/tty'. The following xterm specific escape sequence sets the terminal title to the working directory: .PP .EX cmd on-cd &{{ printf "\e033]0; $PWD\e007" > /dev/tty }} .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. .PP There is also a 'pre-cd' command, that works like 'on-cd', but is run before the directory is actually changed. .SH COLORS lf tries to automatically adapt its colors to the environment. It starts with a default colorscheme and updates colors using values of existing environment variables possibly by overwriting its previous values. Colors are set in the following order: .PP .EX 1. default 2. LSCOLORS (Mac/BSD ls) 3. LS_COLORS (GNU ls) 4. LF_COLORS (lf specific) 5. colors file (lf specific) .EE .PP Please refer to the corresponding man pages for more information about 'LSCOLORS' and 'LS_COLORS'. 'LF_COLORS' is provided with the same syntax as 'LS_COLORS' in case you want to configure colors only for lf but not ls. This can be useful since there are some differences between ls and lf, though one should expect the same behavior for common cases. Colors file is provided for easier configuration without environment variables. This file should consist of whitespace separated pairs with '#' character to start comments until the end of line. .PP You can configure lf colors in two different ways. First, you can only configure 8 basic colors used by your terminal and lf should pick up those colors automatically. Depending on your terminal, you should be able to select your colors from a 24-bit palette. This is the recommended approach as colors used by other programs will also match each other. .PP Second, you can set the values of environment variables or colors file mentioned above for fine grained customization. Note that 'LS_COLORS/LF_COLORS' are more powerful than 'LSCOLORS' and they can be used even when GNU programs are not installed on the system. You can combine this second method with the first method for best results. .PP Lastly, you may also want to configure the colors of the prompt line to match the rest of the colors. Colors of the prompt line can be configured using the 'promptfmt' option which can include hardcoded colors as ansi escapes. See the default value of this option to have an idea about how to color this line. .PP It is worth noting that lf uses as many colors advertised by your terminal's entry in terminfo or infocmp databases on your system. If an entry is not present, it falls back to an internal database. If your terminal supports 24-bit colors but either does not have a database entry or does not advertise all capabilities, you can enable support by setting the '$COLORTERM' variable to 'truecolor' or ensuring '$TERM' is set to a value that ends with '-truecolor'. .PP Default lf colors are mostly taken from GNU dircolors defaults. These defaults use 8 basic colors and bold attribute. Default dircolors entries with background colors are simplified to avoid confusion with current file selection in lf. Similarly, there are only file type matchings and extension matchings are left out for simplicity. Default values are as follows given with their matching order in lf: .PP .EX ln 01;36 or 31;01 tw 01;34 ow 01;34 st 01;34 di 01;34 pi 33 so 01;35 bd 33;01 cd 33;01 su 01;32 sg 01;32 ex 01;32 fi 00 .EE .PP Note that lf first tries matching file names and then falls back to file types. The full order of matchings from most specific to least are as follows: .PP .EX 1. Full Path (e.g. '~/.config/lf/lfrc') 2. Dir Name (e.g. '.git/') (only matches dirs with a trailing slash at the end) 3. File Type (e.g. 'ln') (except 'fi') 4. File Name (e.g. 'README*') 5. File Name (e.g. '*README') 6. Base Name (e.g. 'README.*') 7. Extension (e.g. '*.txt') 8. Default (i.e. 'fi') .EE .PP For example, given a regular text file '/path/to/README.txt', the following entries are checked in the configuration and the first one to match is used: .PP .EX 1. '/path/to/README.txt' 2. (skipped since the file is not a directory) 3. (skipped since the file is of type 'fi') 4. 'README.txt*' 5. '*README.txt' 6. 'README.*' 7. '*.txt' 8. 'fi' .EE .PP Given a regular directory '/path/to/example.d', the following entries are checked in the configuration and the first one to match is used: .PP .EX 1. '/path/to/example.d' 2. 'example.d/' 3. 'di' 4. 'example.d*' 5. '*example.d' 6. 'example.*' 7. '*.d' 8. 'fi' .EE .PP Note that glob-like patterns do not actually perform glob matching due to performance reasons. .PP For example, you can set a variable as follows: .PP .EX export LF_COLORS="~/Documents=01;31:~/Downloads=01;31:~/.local/share=01;31:~/.config/lf/lfrc=31:.git/=01;32:.git*=32:*.gitignore=32:*Makefile=32:README.*=33:*.txt=34:*.md=34:ln=01;36:di=01;34:ex=01;32:" .EE .PP Having all entries on a single line can make it hard to read. You may instead divide it to multiple lines in between double quotes by escaping newlines with backslashes as follows: .PP .EX export LF_COLORS="\e ~/Documents=01;31:\e ~/Downloads=01;31:\e ~/.local/share=01;31:\e ~/.config/lf/lfrc=31:\e .git/=01;32:\e .git*=32:\e *.gitignore=32:\e *Makefile=32:\e README.*=33:\e *.txt=34:\e *.md=34:\e ln=01;36:\e di=01;34:\e ex=01;32:\e " .EE .PP Having such a long variable definition in a shell configuration file might be undesirable. You may instead use the colors file for configuration. A sample colors file can be found at https://github.com/gokcehan/lf/blob/master/etc/colors.example You may also see the wiki page for ansi escape codes https://en.wikipedia.org/wiki/ANSI_escape_code .SH ICONS Icons are configured using 'LF_ICONS' environment variable or an icons file. The variable uses the same syntax as 'LS_COLORS/LF_COLORS'. Instead of colors, you should put a single characters as values of entries. Icons file should consist of whitespace separated pairs with '#' character to start comments until the end of line. Do not forget to enable 'icons' option to see the icons. Default values are as follows given with their matching order in lf: .PP .EX ln l or l tw t ow d st t di d pi p so s bd b cd c su u sg g ex x fi - .EE .PP A sample icons file can be found at https://github.com/gokcehan/lf/blob/master/etc/icons.example lf-r28/lf.desktop000066400000000000000000000003121435165676200140770ustar00rootroot00000000000000[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; lf-r28/main.go000066400000000000000000000151251435165676200133660ustar00rootroot00000000000000package main import ( "flag" "fmt" "log" "net" "os" "path/filepath" "reflect" "runtime" "runtime/pprof" "strconv" "strings" ) var ( envPath = os.Getenv("PATH") envLevel = os.Getenv("LF_LEVEL") ) type arrayFlag []string var ( gSingleMode bool gClientID int gHostname string gLastDirPath string gSelectionPath string gSocketProt string gSocketPath string gLogPath string gSelect string gConfigPath string gCommands arrayFlag gVersion string ) func (a *arrayFlag) Set(v string) error { *a = append(*a, v) return nil } func (a *arrayFlag) String() string { return strings.Join(*a, ", ") } func init() { h, err := os.Hostname() if err != nil { log.Printf("hostname: %s", err) } gHostname = h if envLevel == "" { envLevel = "0" } } func exportEnvVars() { os.Setenv("id", strconv.Itoa(gClientID)) os.Setenv("OPENER", envOpener) os.Setenv("EDITOR", envEditor) os.Setenv("PAGER", envPager) os.Setenv("SHELL", envShell) dir, err := os.Getwd() if err != nil { fmt.Fprintf(os.Stderr, "getting current directory: %s\n", err) } os.Setenv("OLDPWD", dir) level, err := strconv.Atoi(envLevel) if err != nil { log.Printf("reading lf level: %s", err) } level++ os.Setenv("LF_LEVEL", strconv.Itoa(level)) } // used by exportOpts below func fieldToString(field reflect.Value) string { kind := field.Kind() var value string switch kind { case reflect.Int: value = strconv.Itoa(int(field.Int())) case reflect.Bool: value = strconv.FormatBool(field.Bool()) case reflect.Slice: for i := 0; i < field.Len(); i++ { element := field.Index(i) if i == 0 { value = fieldToString(element) } else { value += ":" + fieldToString(element) } } default: value = field.String() } return value } func exportOpts() { e := reflect.ValueOf(&gOpts).Elem() for i := 0; i < e.NumField(); i++ { // Get name and prefix it with lf_ name := e.Type().Field(i).Name name = fmt.Sprintf("lf_%s", name) // Skip maps if name == "lf_keys" || name == "lf_cmdkeys" || name == "lf_cmds" { continue } // Get string representation of the value if name == "lf_sortType" { var sortby string switch gOpts.sortType.method { case naturalSort: sortby = "natural" case nameSort: sortby = "name" case sizeSort: sortby = "size" case timeSort: sortby = "time" case ctimeSort: sortby = "ctime" case atimeSort: sortby = "atime" case extSort: sortby = "ext" } os.Setenv("lf_sortby", sortby) reverse := strconv.FormatBool(gOpts.sortType.option&reverseSort != 0) os.Setenv("lf_reverse", reverse) hidden := strconv.FormatBool(gOpts.sortType.option&hiddenSort != 0) os.Setenv("lf_hidden", hidden) dirfirst := strconv.FormatBool(gOpts.sortType.option&dirfirstSort != 0) os.Setenv("lf_dirfirst", dirfirst) } else if name == "lf_user" { // set each user option for key, value := range gOpts.user { os.Setenv(name+"_"+key, value) } } else { field := e.Field(i) value := fieldToString(field) os.Setenv(name, value) } } } func startServer() { cmd := detachedCommand(os.Args[0], "-server") if err := cmd.Start(); err != nil { log.Printf("starting server: %s", err) } } func checkServer() { if gSocketProt == "unix" { if _, err := os.Stat(gSocketPath); os.IsNotExist(err) { startServer() } else if _, err := net.Dial(gSocketProt, gSocketPath); err != nil { os.Remove(gSocketPath) startServer() } } else { if _, err := net.Dial(gSocketProt, gSocketPath); err != nil { startServer() } } } func main() { flag.Usage = func() { f := flag.CommandLine.Output() fmt.Fprintln(f, "lf - Terminal file manager") fmt.Fprintln(f, "") fmt.Fprintf(f, "Usage: %s [options] [cd-or-select-path]\n\n", os.Args[0]) fmt.Fprintln(f, " cd-or-select-path") fmt.Fprintln(f, " set the initial dir or file selection to the given argument") fmt.Fprintln(f, "") fmt.Fprintln(f, "Options:") flag.PrintDefaults() } showDoc := flag.Bool( "doc", false, "show documentation") showVersion := flag.Bool( "version", false, "show version") serverMode := flag.Bool( "server", false, "start server (automatic)") singleMode := flag.Bool( "single", false, "start a client without server") remoteCmd := flag.String( "remote", "", "send remote command to server") cpuprofile := flag.String( "cpuprofile", "", "path to the file to write the CPU profile") memprofile := flag.String( "memprofile", "", "path to the file to write the memory profile") flag.StringVar(&gLastDirPath, "last-dir-path", "", "path to the file to write the last dir on exit (to use for cd)") flag.StringVar(&gSelectionPath, "selection-path", "", "path to the file to write selected files on open (to use as open file dialog)") flag.StringVar(&gConfigPath, "config", "", "path to the config file (instead of the usual paths)") flag.Var(&gCommands, "command", "command to execute on client initialization") flag.StringVar(&gLogPath, "log", "", "path to the log file to write messages") flag.Parse() gSocketProt = gDefaultSocketProt gSocketPath = gDefaultSocketPath if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatalf("could not create CPU profile: %s", err) } if err := pprof.StartCPUProfile(f); err != nil { log.Fatalf("could not start CPU profile: %s", err) } defer pprof.StopCPUProfile() } switch { case *showDoc: fmt.Print(genDocString) case *showVersion: fmt.Println(gVersion) case *remoteCmd != "": if err := remote(*remoteCmd); err != nil { log.Fatalf("remote command: %s", err) } case *serverMode: if gLogPath != "" && !filepath.IsAbs(gLogPath) { wd, err := os.Getwd() if err != nil { log.Fatalf("getting current directory: %s", err) } else { gLogPath = filepath.Join(wd, gLogPath) } } os.Chdir(gUser.HomeDir) serve() default: gSingleMode = *singleMode if !gSingleMode { checkServer() } gClientID = os.Getpid() switch flag.NArg() { case 0: _, err := os.Getwd() if err != nil { fmt.Fprintf(os.Stderr, "getting current directory: %s\n", err) os.Exit(2) } case 1: gSelect = flag.Arg(0) default: fmt.Fprintf(os.Stderr, "only single file or directory is allowed\n") os.Exit(2) } exportEnvVars() run() } if *memprofile != "" { f, err := os.Create(*memprofile) if err != nil { log.Fatal("could not create memory profile: ", err) } runtime.GC() if err := pprof.WriteHeapProfile(f); err != nil { log.Fatal("could not write memory profile: ", err) } f.Close() } } lf-r28/misc.go000066400000000000000000000145731435165676200134030ustar00rootroot00000000000000package main import ( "bufio" "fmt" "io" "path/filepath" "regexp" "strconv" "strings" "unicode" "github.com/mattn/go-runewidth" ) func isRoot(name string) bool { return filepath.Dir(name) == name } func replaceTilde(s string) string { if strings.HasPrefix(s, "~") { s = strings.Replace(s, "~", gUser.HomeDir, 1) } return s } func runeSliceWidth(rs []rune) int { w := 0 for _, r := range rs { w += runewidth.RuneWidth(r) } return w } func runeSliceWidthRange(rs []rune, beg, end int) []rune { curr := 0 b := 0 for i, r := range rs { w := runewidth.RuneWidth(r) switch { case curr == beg: b = i case curr < beg && curr+w > beg: b = i + 1 case curr == end: return rs[b:i] case curr > end: return rs[b : i-1] } curr += w } return nil } // This function is used to escape whitespaces and special characters with // backlashes in a given string. func escape(s string) string { buf := make([]rune, 0, len(s)) for _, r := range s { if unicode.IsSpace(r) || r == '\\' || r == ';' || r == '#' { buf = append(buf, '\\') } buf = append(buf, r) } return string(buf) } // This function is used to remove backlashes that are used to escape // 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 } esc = false buf = append(buf, r) } if esc { buf = append(buf, '\\') } return string(buf) } // This function splits the given string by whitespaces. It is aware of escaped // whitespaces so that they are not split unintentionally. func tokenize(s string) []string { esc := false var buf []rune var toks []string for _, r := range s { if r == '\\' { esc = true buf = append(buf, r) continue } if esc { esc = false buf = append(buf, r) continue } if !unicode.IsSpace(r) { buf = append(buf, r) } else { toks = append(toks, string(buf)) buf = nil } } toks = append(toks, string(buf)) return toks } // This function splits the first word of a string delimited by whitespace from // the rest. This is used to tokenize a string one by one without touching the // rest. Whitespace on the left side of both the word and the rest are trimmed. func splitWord(s string) (word, rest string) { s = strings.TrimLeftFunc(s, unicode.IsSpace) ind := len(s) for i, c := range s { if unicode.IsSpace(c) { ind = i break } } word = s[0:ind] rest = strings.TrimLeftFunc(s[ind:], unicode.IsSpace) return } // This function reads whitespace separated string pairs at each line. Single // or double quotes can be used to escape whitespaces. Hash characters can be // used to add a comment until the end of line. Leading and trailing space is // trimmed. Empty lines are skipped. func readPairs(r io.Reader) ([][]string, error) { var pairs [][]string s := bufio.NewScanner(r) for s.Scan() { line := s.Text() squote, dquote := false, false for i := 0; i < len(line); i++ { if line[i] == '\'' && !dquote { squote = !squote } else if line[i] == '"' && !squote { dquote = !dquote } if !squote && !dquote && line[i] == '#' { line = line[:i] break } } line = strings.TrimSpace(line) if line == "" { continue } squote, dquote = false, false pair := strings.FieldsFunc(line, func(r rune) bool { if r == '\'' && !dquote { squote = !squote } else if r == '"' && !squote { dquote = !dquote } return !squote && !dquote && unicode.IsSpace(r) }) if len(pair) != 2 { return nil, fmt.Errorf("expected pair but found: %s", s.Text()) } for i := 0; i < len(pair); i++ { squote, dquote = false, false buf := make([]rune, 0, len(pair[i])) for _, r := range pair[i] { if r == '\'' && !dquote { squote = !squote continue } if r == '"' && !squote { dquote = !dquote continue } buf = append(buf, r) } pair[i] = string(buf) } pairs = append(pairs, pair) } return pairs, nil } // This function converts a size in bytes to a human readable form using metric // suffixes (e.g. 1K = 1000). For values less than 10 the first significant // digit is shown, otherwise it is hidden. Numbers are always rounded down. // This should be fine for most human beings. func humanize(size int64) string { if size < 1000 { return fmt.Sprintf("%dB", size) } suffix := []string{ "K", // kilo "M", // mega "G", // giga "T", // tera "P", // peta "E", // exa "Z", // zeta "Y", // yotta } curr := float64(size) / 1000 for _, s := range suffix { if curr < 10 { return fmt.Sprintf("%.1f%s", curr-0.0499, s) } else if curr < 1000 { return fmt.Sprintf("%d%s", int(curr), s) } curr /= 1000 } return "" } // This function compares two strings for natural sorting which takes into // account values of numbers in strings. For example, '2' is less than '10', // and similarly 'foo2bar' is less than 'foo10bar', but 'bar2bar' is greater // than 'foo10bar'. func naturalLess(s1, s2 string) bool { lo1, lo2, hi1, hi2 := 0, 0, 0, 0 for { if hi1 >= len(s1) { return hi2 != len(s2) } if hi2 >= len(s2) { return false } isDigit1 := isDigit(s1[hi1]) isDigit2 := isDigit(s2[hi2]) for lo1 = hi1; hi1 < len(s1) && isDigit(s1[hi1]) == isDigit1; hi1++ { } for lo2 = hi2; hi2 < len(s2) && isDigit(s2[hi2]) == isDigit2; hi2++ { } if s1[lo1:hi1] == s2[lo2:hi2] { continue } if isDigit1 && isDigit2 { num1, err1 := strconv.Atoi(s1[lo1:hi1]) num2, err2 := strconv.Atoi(s2[lo2:hi2]) if err1 == nil && err2 == nil { return num1 < num2 } } return s1[lo1:hi1] < s2[lo2:hi2] } } var reAltKey = regexp.MustCompile(``) var reWord = regexp.MustCompile(`(\pL|\pN)+`) var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`) var reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`) func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b } // We don't need no generic code // We don't need no type control // No dark templates in compiler // Haskell leave them kids alone // Hey Bjarne leave them kids alone // All in all it's just another brick in the code // All in all you're just another brick in the code // // -- Pink Trolled -- lf-r28/misc_test.go000066400000000000000000000130051435165676200144270ustar00rootroot00000000000000package main import ( "os" "reflect" "strings" "testing" ) func TestIsRoot(t *testing.T) { sep := string(os.PathSeparator) if !isRoot(sep) { t.Errorf(`"%s" is root`, sep) } paths := []string{ "", "~", "foo", "foo/bar", "foo/bar", "/home", "/home/user", } for _, p := range paths { if isRoot(p) { t.Errorf("'%s' is not root", p) } } } func TestRuneSliceWidth(t *testing.T) { tests := []struct { rs []rune exp int }{ {[]rune{'a', 'b'}, 2}, {[]rune{'ı', 'ş'}, 2}, {[]rune{'世', '界'}, 4}, {[]rune{'世', 'a', '界', 'ı'}, 6}, } for _, test := range tests { if got := runeSliceWidth(test.rs); got != test.exp { t.Errorf("at input '%v' expected '%d' but got '%d'", test.rs, test.exp, got) } } } func TestRuneSliceWidthRange(t *testing.T) { tests := []struct { rs []rune beg int end int exp []rune }{ {[]rune{'a', 'b', 'c', 'd'}, 1, 3, []rune{'b', 'c'}}, {[]rune{'a', 'ı', 'b', 'ş'}, 1, 3, []rune{'ı', 'b'}}, {[]rune{'世', '界', '世', '界'}, 2, 6, []rune{'界', '世'}}, {[]rune{'世', '界', '世', '界'}, 3, 6, []rune{'世'}}, {[]rune{'世', '界', '世', '界'}, 2, 5, []rune{'界'}}, {[]rune{'世', '界', '世', '界'}, 3, 5, []rune{}}, {[]rune{'世', 'a', '界', 'ı'}, 2, 5, []rune{'a', '界'}}, {[]rune{'世', 'a', '界', 'ı'}, 2, 4, []rune{'a'}}, {[]rune{'世', 'a', '界', 'ı'}, 3, 5, []rune{'界'}}, {[]rune{'世', 'a', '界', 'ı'}, 3, 4, []rune{}}, } for _, test := range tests { if got := runeSliceWidthRange(test.rs, test.beg, test.end); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.rs, test.rs, got) } } } func TestEscape(t *testing.T) { tests := []struct { s string exp string }{ {"", ""}, {"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\tbar`, `foo\\tbar`}, {"foo\tbar", "foo\\\tbar"}, {`foo\`, `foo\\`}, } for _, test := range tests { if got := escape(test.s); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) } } } func TestUnescape(t *testing.T) { tests := []struct { s string exp string }{ {"", ""}, {"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\\tbar`, `foo\tbar`}, {"foo\\\tbar", "foo\tbar"}, {`foo\`, `foo\`}, } for _, test := range tests { if got := unescape(test.s); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) } } } func TestTokenize(t *testing.T) { tests := []struct { s string exp []string }{ {"", []string{""}}, {"foo", []string{"foo"}}, {"foo bar", []string{"foo", "bar"}}, {`:rename foo\ bar`, []string{":rename", `foo\ bar`}}, } for _, test := range tests { if got := tokenize(test.s); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) } } } func TestSplitWord(t *testing.T) { tests := []struct { s string word string rest string }{ {"", "", ""}, {"foo", "foo", ""}, {" foo", "foo", ""}, {"foo ", "foo", ""}, {" foo ", "foo", ""}, {"foo bar baz", "foo", "bar baz"}, {" foo bar baz", "foo", "bar baz"}, {"foo bar baz", "foo", "bar baz"}, {" foo bar baz", "foo", "bar baz"}, } for _, test := range tests { if w, r := splitWord(test.s); w != test.word || r != test.rest { t.Errorf("at input '%s' expected '%s' and '%s' but got '%s' and '%s'", test.s, test.word, test.rest, w, r) } } } func TestReadPairs(t *testing.T) { tests := []struct { s string exp [][]string }{ {"foo bar", [][]string{{"foo", "bar"}}}, {"foo bar ", [][]string{{"foo", "bar"}}}, {" foo bar", [][]string{{"foo", "bar"}}}, {" foo bar ", [][]string{{"foo", "bar"}}}, {"foo bar#baz", [][]string{{"foo", "bar"}}}, {"foo bar #baz", [][]string{{"foo", "bar"}}}, {`'foo#baz' bar`, [][]string{{"foo#baz", "bar"}}}, {`"foo#baz" bar`, [][]string{{"foo#baz", "bar"}}}, } for _, test := range tests { if got, _ := readPairs(strings.NewReader(test.s)); !reflect.DeepEqual(got, test.exp) { t.Errorf("at input '%v' expected '%v' but got '%v'", test.s, test.exp, got) } } } func TestHumanize(t *testing.T) { tests := []struct { i int64 exp string }{ {0, "0B"}, {9, "9B"}, {99, "99B"}, {999, "999B"}, {1000, "1.0K"}, {1023, "1.0K"}, {1025, "1.0K"}, {1049, "1.0K"}, {1050, "1.0K"}, {1099, "1.0K"}, {9999, "9.9K"}, {10000, "10K"}, {10100, "10K"}, {10500, "10K"}, {1000000, "1.0M"}, } for _, test := range tests { if got := humanize(test.i); got != test.exp { t.Errorf("at input '%d' expected '%s' but got '%s'", test.i, test.exp, got) } } } func TestNaturalLess(t *testing.T) { tests := []struct { s1 string s2 string exp bool }{ {"foo", "bar", false}, {"bar", "baz", true}, {"foo", "123", false}, {"foo1", "foobar", true}, {"foo1", "foo10", true}, {"foo2", "foo10", true}, {"foo1", "foo10bar", true}, {"foo2", "foo10bar", true}, {"foo1bar", "foo10bar", true}, {"foo2bar", "foo10bar", true}, {"foo1bar", "foo10", true}, {"foo2bar", "foo10", true}, } for _, test := range tests { if got := naturalLess(test.s1, test.s2); got != test.exp { t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got) } } } lf-r28/nav.go000066400000000000000000001165021435165676200132270ustar00rootroot00000000000000package main import ( "bufio" "errors" "fmt" "io" "log" "os" "os/exec" "path/filepath" "reflect" "sort" "strconv" "strings" "time" times "github.com/djherbis/times" ) type linkState byte const ( notLink linkState = iota working broken ) type file struct { os.FileInfo linkState linkState linkTarget string path string dirCount int dirSize int64 accessTime time.Time changeTime time.Time ext string } func (file *file) TotalSize() int64 { if file.IsDir() { if file.dirSize >= 0 { return file.dirSize } return 0 } return file.Size() } func readdir(path string) ([]*file, error) { f, err := os.Open(path) if err != nil { return nil, err } names, err := f.Readdirnames(-1) f.Close() files := make([]*file, 0, len(names)) for _, fname := range names { fpath := filepath.Join(path, fname) lstat, err := os.Lstat(fpath) if os.IsNotExist(err) { continue } if err != nil { log.Printf("getting file information: %s", err) continue } var linkState linkState var linkTarget string if lstat.Mode()&os.ModeSymlink != 0 { stat, err := os.Stat(fpath) if err == nil { linkState = working lstat = stat } else { linkState = broken } linkTarget, err = os.Readlink(fpath) if err != nil { log.Printf("reading link target: %s", err) } } 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) dirCount := -1 if lstat.IsDir() && gOpts.dircounts { d, err := os.Open(fpath) if err != nil { dirCount = -2 } else { names, err := d.Readdirnames(1000) d.Close() if names == nil && err != io.EOF { dirCount = -2 } else { dirCount = len(names) } } } files = append(files, &file{ FileInfo: lstat, linkState: linkState, linkTarget: linkTarget, path: fpath, dirCount: dirCount, dirSize: -1, accessTime: at, changeTime: ct, ext: ext, }) } return files, err } type dir struct { loading bool // directory is loading from disk loadTime time.Time // current loading or last load time ind int // index of current entry in files pos int // position of current entry in ui path string // full path of directory 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 dironly bool // dironly value from last sort hiddenfiles []string // hiddenfiles value from last sort filter []string // last filter for this directory ignorecase bool // ignorecase value from last sort ignoredia bool // ignoredia value from last sort noPerm bool // whether lf has no permission to open the directory lines []string // lines of text to display if directory previews are enabled } func newDir(path string) *dir { time := time.Now() files, err := readdir(path) if err != nil { log.Printf("reading directory: %s", err) } return &dir{ loading: gOpts.dirpreviews, // Directory is loaded after previewer function exits. loadTime: time, path: path, files: files, allFiles: files, noPerm: os.IsPermission(err), } } func normalize(s1, s2 string, ignorecase, ignoredia bool) (string, string) { if gOpts.ignorecase { s1 = strings.ToLower(s1) s2 = strings.ToLower(s2) } if gOpts.ignoredia { s1 = removeDiacritics(s1) s2 = removeDiacritics(s2) } return s1, s2 } func (dir *dir) sort() { dir.sortType = gOpts.sortType dir.dironly = gOpts.dironly dir.hiddenfiles = gOpts.hiddenfiles dir.ignorecase = gOpts.ignorecase dir.ignoredia = gOpts.ignoredia dir.files = dir.allFiles switch dir.sortType.method { case naturalSort: sort.SliceStable(dir.files, func(i, j int) bool { s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) return naturalLess(s1, s2) }) case nameSort: sort.SliceStable(dir.files, func(i, j int) bool { s1, s2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) return s1 < s2 }) case sizeSort: sort.SliceStable(dir.files, func(i, j int) bool { return dir.files[i].TotalSize() < dir.files[j].TotalSize() }) case timeSort: 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 { ext1, ext2 := normalize(dir.files[i].ext, dir.files[j].ext, dir.ignorecase, dir.ignoredia) // if the extension could not be determined (directories, files without) // use a zero byte so that these files can be ranked higher if ext1 == "" { ext1 = "\x00" } if ext2 == "" { ext2 = "\x00" } name1, name2 := normalize(dir.files[i].Name(), dir.files[j].Name(), dir.ignorecase, dir.ignoredia) // in order to also have natural sorting with the filenames // combine the name with the ext but have the ext at the front return ext1 < ext2 || ext1 == ext2 && name1 < name2 }) } if dir.sortType.option&reverseSort != 0 { for i, j := 0, len(dir.files)-1; i < j; i, j = i+1, j-1 { dir.files[i], dir.files[j] = dir.files[j], dir.files[i] } } if dir.sortType.option&dirfirstSort != 0 { sort.SliceStable(dir.files, func(i, j int) bool { if dir.files[i].IsDir() == dir.files[j].IsDir() { return i < j } return dir.files[i].IsDir() }) } // when dironly option is enabled, we move files to the beginning of our file // list and then set the beginning of displayed files to the first directory // in the list if dir.dironly { sort.SliceStable(dir.files, func(i, j int) bool { if !dir.files[i].IsDir() && !dir.files[j].IsDir() { return i < j } return !dir.files[i].IsDir() }) dir.files = func() []*file { for i, f := range dir.files { if f.IsDir() { return dir.files[i:] } } return dir.files[len(dir.files):] }() } // when hidden option is disabled, we move hidden files to the // beginning of our file list and then set the beginning of displayed // files to the first non-hidden file in the list if dir.sortType.option&hiddenSort == 0 { sort.SliceStable(dir.files, func(i, j int) bool { if isHidden(dir.files[i], dir.path, dir.hiddenfiles) && isHidden(dir.files[j], dir.path, dir.hiddenfiles) { return i < j } return isHidden(dir.files[i], dir.path, dir.hiddenfiles) }) for i, f := range dir.files { if !isHidden(f, dir.path, dir.hiddenfiles) { dir.files = dir.files[i:] break } } if len(dir.files) > 0 && isHidden(dir.files[len(dir.files)-1], dir.path, dir.hiddenfiles) { dir.files = dir.files[len(dir.files):] } } if len(dir.filter) != 0 { sort.SliceStable(dir.files, func(i, j int) bool { if isFiltered(dir.files[i], dir.filter) && isFiltered(dir.files[j], dir.filter) { return i < j } return isFiltered(dir.files[i], dir.filter) }) for i, f := range dir.files { if !isFiltered(f, dir.filter) { dir.files = dir.files[i:] break } } if len(dir.files) > 0 && isFiltered(dir.files[len(dir.files)-1], dir.filter) { dir.files = dir.files[len(dir.files):] } } dir.ind = max(dir.ind, 0) dir.ind = min(dir.ind, len(dir.files)-1) } func (dir *dir) name() string { if len(dir.files) == 0 { return "" } return dir.files[dir.ind].Name() } func (dir *dir) sel(name string, height int) { if len(dir.files) == 0 { dir.ind, dir.pos = 0, 0 return } dir.ind = max(dir.ind, 0) dir.ind = min(dir.ind, len(dir.files)-1) if dir.files[dir.ind].Name() != name { for i, f := range dir.files { if f.Name() == name { dir.ind = i break } } } edge := min(min(height/2, gOpts.scrolloff), len(dir.files)-dir.ind-1) dir.pos = min(dir.ind, height-edge-1) } type nav struct { init bool 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 previewChan chan string dirPreviewChan chan *dir dirChan chan *dir regChan chan *reg dirCache map[string]*dir regCache map[string]*reg saves map[string]bool marks map[string]string renameOldPath string renameNewPath string selections map[string]int tags map[string]string selectionInd int height int find string findBack bool search string searchBack bool searchInd int searchPos int prevFilter []string volatilePreview bool jumpList []string jumpListInd int } func (nav *nav) loadDirInternal(path string) *dir { d := &dir{ loading: true, loadTime: time.Now(), path: path, sortType: gOpts.sortType, hiddenfiles: gOpts.hiddenfiles, ignorecase: gOpts.ignorecase, ignoredia: gOpts.ignoredia, } go func() { d := newDir(path) d.sort() d.ind, d.pos = 0, 0 if gOpts.dirpreviews { nav.dirPreviewChan <- d } nav.dirChan <- d }() return d } func (nav *nav) loadDir(path string) *dir { if gOpts.dircache { d, ok := nav.dirCache[path] if !ok { d = nav.loadDirInternal(path) nav.dirCache[path] = d return d } nav.checkDir(d) return d } return nav.loadDirInternal(path) } func (nav *nav) checkDir(dir *dir) { s, err := os.Stat(dir.path) if err != nil { log.Printf("getting directory info: %s", err) return } switch { case s.ModTime().After(dir.loadTime): now := time.Now() // XXX: Linux builtin exFAT drivers are able to predict modifications in the future // https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504 if s.ModTime().After(now) { return } dir.loading = true dir.loadTime = now go func() { nd := newDir(dir.path) nd.filter = dir.filter nd.sort() if gOpts.dirpreviews { nav.dirPreviewChan <- nd } nav.dirChan <- nd }() case dir.sortType != gOpts.sortType || dir.dironly != gOpts.dironly || !reflect.DeepEqual(dir.hiddenfiles, gOpts.hiddenfiles) || dir.ignorecase != gOpts.ignorecase || dir.ignoredia != gOpts.ignoredia: dir.loading = true go func() { dir.sort() dir.loading = false nav.dirChan <- dir }() } } func (nav *nav) getDirs(wd string) { var dirs []*dir wd = filepath.Clean(wd) for curr, base := wd, ""; !isRoot(base); curr, base = filepath.Dir(curr), filepath.Base(curr) { dir := nav.loadDir(curr) dir.sel(base, nav.height) dirs = append(dirs, dir) } for i, j := 0, len(dirs)-1; i < j; i, j = i+1, j-1 { dirs[i], dirs[j] = dirs[j], dirs[i] } nav.dirs = dirs } 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), deleteCountChan: make(chan int, 1024), deleteTotalChan: make(chan int, 1024), previewChan: make(chan string, 1024), dirPreviewChan: make(chan *dir, 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), tags: make(map[string]string), selectionInd: 0, height: height, jumpList: make([]string, 0), jumpListInd: -1, } return nav } func (nav *nav) addJumpList() { currPath := nav.currDir().path if nav.jumpListInd >= 0 && nav.jumpListInd < len(nav.jumpList)-1 { if nav.jumpList[nav.jumpListInd] == currPath { // walking the jumpList return } nav.jumpList = nav.jumpList[:nav.jumpListInd+1] } if len(nav.jumpList) == 0 || nav.jumpList[len(nav.jumpList)-1] != currPath { nav.jumpList = append(nav.jumpList, currPath) } nav.jumpListInd = len(nav.jumpList) - 1 } func (nav *nav) cdJumpListPrev() { // currPath := nav.currDir().path if nav.jumpListInd > 0 { nav.jumpListInd -= 1 nav.cd(nav.jumpList[nav.jumpListInd]) } } func (nav *nav) cdJumpListNext() { if nav.jumpListInd < len(nav.jumpList)-1 { nav.jumpListInd += 1 nav.cd(nav.jumpList[nav.jumpListInd]) } } func (nav *nav) renew() { for _, d := range nav.dirs { nav.checkDir(d) } for m := range nav.selections { if _, err := os.Lstat(m); os.IsNotExist(err) { delete(nav.selections, m) } } if len(nav.selections) == 0 { nav.selectionInd = 0 } } func (nav *nav) reload() error { nav.dirCache = make(map[string]*dir) nav.regCache = make(map[string]*reg) wd, err := os.Getwd() if err != nil { return fmt.Errorf("getting current directory: %s", err) } curr, err := nav.currFile() nav.getDirs(wd) if err == nil { last := nav.dirs[len(nav.dirs)-1] last.files = append(last.files, curr) } return nil } func (nav *nav) position() { if !nav.init { return } path := nav.currDir().path for i := len(nav.dirs) - 2; i >= 0; i-- { nav.dirs[i].sel(filepath.Base(path), nav.height) path = filepath.Dir(path) } } func (nav *nav) exportFiles() { if !nav.init { return } var currFile string if curr, err := nav.currFile(); err == nil { currFile = curr.path } currSelections := nav.currSelections() exportFiles(currFile, currSelections, nav.currDir().path) } func (nav *nav) dirPreviewLoop(ui *ui) { var prevPath string for dir := range nav.dirPreviewChan { if dir == nil && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview { cmd := exec.Command(gOpts.cleaner, prevPath) if err := cmd.Run(); err != nil { log.Printf("cleaning preview: %s", err) } nav.volatilePreview = false } else if dir != nil { win := ui.wins[len(ui.wins)-1] nav.previewDir(dir, win) prevPath = dir.path } } } func (nav *nav) previewLoop(ui *ui) { var prev string for path := range nav.previewChan { clear := len(path) == 0 loop: for { select { case path = <-nav.previewChan: clear = clear || len(path) == 0 default: break loop } } win := ui.wins[len(ui.wins)-1] if clear && len(gOpts.previewer) != 0 && len(gOpts.cleaner) != 0 && nav.volatilePreview { nav.exportFiles() exportOpts() cmd := exec.Command(gOpts.cleaner, prev, strconv.Itoa(win.w), strconv.Itoa(win.h), strconv.Itoa(win.x), strconv.Itoa(win.y)) if err := cmd.Run(); err != nil { log.Printf("cleaning preview: %s", err) } nav.volatilePreview = false } if len(path) != 0 { nav.preview(path, win) prev = path } } } //lint:ignore U1000 This function is not used on Windows func matchPattern(pattern, name, path string) bool { s := name pattern = replaceTilde(pattern) if filepath.IsAbs(pattern) { s = filepath.Join(path, name) } // pattern errors are checked when 'hiddenfiles' option is set matched, _ := filepath.Match(pattern, s) return matched } func (nav *nav) previewDir(dir *dir, win *win) { defer func() { dir.loading = false nav.dirChan <- dir }() var reader io.Reader if len(gOpts.previewer) != 0 { nav.exportFiles() exportOpts() cmd := exec.Command(gOpts.previewer, dir.path, strconv.Itoa(win.w), strconv.Itoa(win.h), strconv.Itoa(win.x), strconv.Itoa(win.y)) out, err := cmd.StdoutPipe() if err != nil { log.Printf("previewing dir: %s", err) return } if err := cmd.Start(); err != nil { log.Printf("previewing dir: %s", err) out.Close() return } defer func() { if err := cmd.Wait(); err != nil { if e, ok := err.(*exec.ExitError); ok { if e.ExitCode() != 0 { nav.volatilePreview = true } } else { log.Printf("loading dir: %s", err) } } }() defer out.Close() reader = out buf := bufio.NewScanner(reader) for i := 0; i < win.h && buf.Scan(); i++ { for _, r := range buf.Text() { if r == 0 { dir.lines = []string{"\033[7mbinary\033[0m"} return } } dir.lines = append(dir.lines, buf.Text()) } if buf.Err() != nil { log.Printf("loading dir: %s", buf.Err()) } } } func (nav *nav) preview(path string, win *win) { reg := ®{loadTime: time.Now(), path: path} defer func() { nav.regChan <- reg }() var reader io.Reader if len(gOpts.previewer) != 0 { nav.exportFiles() exportOpts() cmd := exec.Command(gOpts.previewer, path, strconv.Itoa(win.w), strconv.Itoa(win.h), strconv.Itoa(win.x), strconv.Itoa(win.y)) out, err := cmd.StdoutPipe() if err != nil { log.Printf("previewing file: %s", err) return } if err := cmd.Start(); err != nil { log.Printf("previewing file: %s", err) out.Close() return } defer func() { if err := cmd.Wait(); err != nil { if e, ok := err.(*exec.ExitError); ok { if e.ExitCode() != 0 { reg.volatile = true nav.volatilePreview = true } } else { log.Printf("loading file: %s", err) } } }() defer out.Close() reader = out } else { f, err := os.Open(path) if err != nil { log.Printf("opening file: %s", err) return } defer f.Close() reader = f } buf := bufio.NewScanner(reader) for i := 0; i < win.h && buf.Scan(); i++ { for _, r := range buf.Text() { if r == 0 { reg.lines = []string{"\033[7mbinary\033[0m"} return } } reg.lines = append(reg.lines, buf.Text()) } if buf.Err() != nil { log.Printf("loading file: %s", buf.Err()) } } func (nav *nav) loadReg(path string, volatile bool) *reg { r, ok := nav.regCache[path] if !ok || (volatile && r.volatile) { r := ®{loading: true, loadTime: time.Now(), path: path, volatile: true} nav.regCache[path] = r nav.previewChan <- path return r } nav.checkReg(r) return r } func (nav *nav) checkReg(reg *reg) { s, err := os.Stat(reg.path) if err != nil { return } now := time.Now() // XXX: Linux builtin exFAT drivers are able to predict modifications in the future // https://bugs.launchpad.net/ubuntu/+source/ubuntu-meta/+bug/1872504 if s.ModTime().After(now) { return } if s.ModTime().After(reg.loadTime) { reg.loadTime = now nav.previewChan <- reg.path } } func (nav *nav) sort() { for _, d := range nav.dirs { name := d.name() d.sort() d.sel(name, nav.height) } } func (nav *nav) setFilter(filter []string) error { newfilter := []string{} for _, tok := range filter { _, err := filepath.Match(tok, "a") if err != nil { return err } if tok != "" { newfilter = append(newfilter, tok) } } dir := nav.currDir() dir.filter = newfilter // Apply filter, by sorting current dir (see nav.sort()) name := dir.name() dir.sort() dir.sel(name, nav.height) return nil } func (nav *nav) up(dist int) bool { dir := nav.currDir() old := dir.ind if dir.ind == 0 { if gOpts.wrapscroll { nav.bottom() } return old != dir.ind } dir.ind -= dist dir.ind = max(0, dir.ind) dir.pos -= dist edge := min(min(nav.height/2, gOpts.scrolloff), dir.ind) dir.pos = max(dir.pos, edge) return old != dir.ind } func (nav *nav) down(dist int) bool { dir := nav.currDir() old := dir.ind maxind := len(dir.files) - 1 if dir.ind >= maxind { if gOpts.wrapscroll { nav.top() } return old != dir.ind } dir.ind += dist dir.ind = min(maxind, dir.ind) dir.pos += dist edge := min(min(nav.height/2, gOpts.scrolloff), maxind-dir.ind) // use a smaller value when the height is even and scrolloff is maxed // in order to stay at the same row as much as possible while up/down edge = min(edge, nav.height/2+nav.height%2-1) dir.pos = min(dir.pos, nav.height-edge-1) dir.pos = min(dir.pos, maxind) return old != dir.ind } func (nav *nav) scrollUp(dist int) bool { dir := nav.currDir() // when reached top do nothing if istop := dir.ind == dir.pos; istop { return false } old := dir.ind minedge := min(nav.height/2, gOpts.scrolloff) dir.pos += dist // jump to ensure minedge when edge < minedge edge := nav.height - dir.pos delta := min(0, edge-minedge-1) dir.pos = min(dir.pos, nav.height-minedge-1) // update dir.ind accordingly dir.ind = dir.ind + delta dir.ind = min(dir.ind, dir.ind-(dir.pos-nav.height+1)) // prevent cursor disappearing downwards dir.pos = min(dir.pos, nav.height-1) return old != dir.ind } func (nav *nav) scrollDown(dist int) bool { dir := nav.currDir() maxind := len(dir.files) - 1 // reached bottom if dir.ind-dir.pos > maxind-nav.height { return false } old := dir.ind minedge := min(nav.height/2, gOpts.scrolloff) dir.pos -= dist // jump to ensure minedge when edge < minedge delta := min(0, dir.pos-minedge) dir.pos = max(dir.pos, minedge) // update dir.ind accordingly dir.ind = dir.ind - delta dir.ind = max(dir.ind, dir.ind-(dir.pos-minedge)) dir.ind = min(maxind, dir.ind) // prevent disappearing dir.pos = max(dir.pos, 0) return old != dir.ind } func (nav *nav) updir() error { if len(nav.dirs) <= 1 { return nil } dir := nav.currDir() nav.dirs = nav.dirs[:len(nav.dirs)-1] if err := os.Chdir(filepath.Dir(dir.path)); err != nil { return fmt.Errorf("updir: %s", err) } return nil } func (nav *nav) open() error { curr, err := nav.currFile() if err != nil { return fmt.Errorf("open: %s", err) } path := curr.path dir := nav.loadDir(path) nav.dirs = append(nav.dirs, dir) if err := os.Chdir(path); err != nil { return fmt.Errorf("open: %s", err) } return nil } func (nav *nav) top() bool { dir := nav.currDir() old := dir.ind dir.ind = 0 dir.pos = 0 return old != dir.ind } func (nav *nav) bottom() bool { dir := nav.currDir() old := dir.ind dir.ind = len(dir.files) - 1 dir.pos = min(dir.ind, nav.height-1) return old != dir.ind } func (nav *nav) high() bool { dir := nav.currDir() old := dir.ind beg := max(dir.ind-dir.pos, 0) offs := gOpts.scrolloff if beg == 0 { offs = 0 } dir.ind = beg + offs dir.pos = offs return old != dir.ind } func (nav *nav) middle() bool { dir := nav.currDir() old := dir.ind beg := max(dir.ind-dir.pos, 0) end := min(beg+nav.height, len(dir.files)) half := (end - beg) / 2 dir.ind = beg + half dir.pos = half return old != dir.ind } func (nav *nav) low() bool { dir := nav.currDir() old := dir.ind beg := max(dir.ind-dir.pos, 0) end := min(beg+nav.height, len(dir.files)) offs := gOpts.scrolloff if end == len(dir.files) { offs = 0 } dir.ind = end - 1 - offs dir.pos = end - beg - 1 - offs return old != dir.ind } func (nav *nav) toggleSelection(path string) { if _, ok := nav.selections[path]; ok { delete(nav.selections, path) if len(nav.selections) == 0 { nav.selectionInd = 0 } } else { nav.selections[path] = nav.selectionInd nav.selectionInd++ } } func (nav *nav) toggle() { curr, err := nav.currFile() if err != nil { return } nav.toggleSelection(curr.path) } func (nav *nav) tagToggleSelection(path string, tag string) { if _, ok := nav.tags[path]; ok { delete(nav.tags, path) } else { nav.tags[path] = tag } } func (nav *nav) tagToggle(tag string) error { list, err := nav.currFileOrSelections() if err != nil { return err } if printLength(tag) != 1 { return errors.New("tag should be single width character") } for _, path := range list { nav.tagToggleSelection(path, tag) } return nil } func (nav *nav) tag(tag string) error { list, err := nav.currFileOrSelections() if err != nil { return err } if printLength(tag) != 1 { return errors.New("tag should be single width character") } for _, path := range list { nav.tags[path] = tag } return nil } func (nav *nav) invert() { dir := nav.currDir() for _, f := range dir.files { path := filepath.Join(dir.path, f.Name()) nav.toggleSelection(path) } } func (nav *nav) unselect() { nav.selections = make(map[string]int) nav.selectionInd = 0 } func (nav *nav) save(cp bool) error { list, err := nav.currFileOrSelections() if err != nil { return err } if err := saveFiles(list, cp); err != nil { return err } nav.saves = make(map[string]bool) for _, f := range list { nav.saves[f] = cp } return nil } func (nav *nav) copyAsync(app *app, srcs []string, dstDir string) { echo := &callExpr{"echoerr", []string{""}, 1} _, err := os.Stat(dstDir) if os.IsNotExist(err) { echo.args[0] = err.Error() app.ui.exprChan <- echo return } total, err := copySize(srcs) if err != nil { echo.args[0] = err.Error() app.ui.exprChan <- echo return } nav.copyTotalChan <- total nums, errs := copyAll(srcs, dstDir) errCount := 0 loop: for { select { case n := <-nums: nav.copyBytesChan <- n case err, ok := <-errs: if !ok { break loop } errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } nav.copyTotalChan <- -total if gSingleMode { nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } if errCount == 0 { app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mCopied successfully\033[0m"}, 1} } } func (nav *nav) moveAsync(app *app, srcs []string, dstDir string) { echo := &callExpr{"echoerr", []string{""}, 1} _, err := os.Stat(dstDir) if os.IsNotExist(err) { echo.args[0] = err.Error() app.ui.exprChan <- echo return } nav.moveTotalChan <- len(srcs) errCount := 0 for _, src := range srcs { nav.moveCountChan <- 1 srcStat, err := os.Lstat(src) if err != nil { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo continue } dst := filepath.Join(dstDir, filepath.Base(src)) dstStat, err := os.Stat(dst) if os.SameFile(srcStat, dstStat) { errCount++ echo.args[0] = fmt.Sprintf("[%d] rename %s %s: source and destination are the same file", errCount, src, dst) app.ui.exprChan <- echo continue } else if !os.IsNotExist(err) { var newPath string for i := 1; !os.IsNotExist(err); i++ { newPath = fmt.Sprintf("%s.~%d~", dst, i) _, err = os.Lstat(newPath) } dst = newPath } if err := os.Rename(src, dst); err != nil { if errCrossDevice(err) { total, err := copySize([]string{src}) if err != nil { echo.args[0] = err.Error() app.ui.exprChan <- echo continue } nav.copyTotalChan <- total nums, errs := copyAll([]string{src}, dstDir) oldCount := errCount loop: for { select { case n := <-nums: nav.copyBytesChan <- n case err, ok := <-errs: if !ok { break loop } errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } nav.copyTotalChan <- -total if errCount == oldCount { if err := os.RemoveAll(src); err != nil { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } } else { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } } nav.moveTotalChan <- -len(srcs) if gSingleMode { nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } if errCount == 0 { app.ui.exprChan <- &callExpr{"echo", []string{"\033[0;32mMoved successfully\033[0m"}, 1} } } func (nav *nav) paste(app *app) error { srcs, cp, err := loadFiles() if err != nil { return err } if len(srcs) == 0 { return errors.New("no file in copy/cut buffer") } dstDir := nav.currDir().path if cp { go nav.copyAsync(app, srcs, dstDir) } else { go nav.moveAsync(app, srcs, dstDir) if err := saveFiles(nil, false); err != nil { return fmt.Errorf("clearing copy/cut buffer: %s", err) } if gSingleMode { if err := nav.sync(); err != nil { return fmt.Errorf("paste: %s", err) } } else { if err := remote("send sync"); err != nil { return fmt.Errorf("paste: %s", err) } } } return nil } func (nav *nav) del(app *app) error { list, err := nav.currFileOrSelections() if err != nil { return err } go func() { echo := &callExpr{"echoerr", []string{""}, 1} errCount := 0 nav.deleteTotalChan <- len(list) for _, path := range list { nav.deleteCountChan <- 1 if err := os.RemoveAll(path); err != nil { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } nav.deleteTotalChan <- -len(list) if gSingleMode { nav.renew() app.ui.loadFile(app, true) } else { if err := remote("send load"); err != nil { errCount++ echo.args[0] = fmt.Sprintf("[%d] %s", errCount, err) app.ui.exprChan <- echo } } }() return nil } func (nav *nav) rename() error { oldPath := nav.renameOldPath newPath := nav.renameNewPath if err := os.Rename(oldPath, newPath); err != nil { return err } lstat, err := os.Lstat(newPath) if err != nil { return err } dir := nav.loadDir(filepath.Dir(newPath)) if dir.loading { dir.files = append(dir.files, &file{FileInfo: lstat}) } dir.sel(lstat.Name(), nav.height) return nil } func (nav *nav) sync() error { list, cp, err := loadFiles() if err != nil { return err } nav.saves = make(map[string]bool) for _, f := range list { nav.saves[f] = cp } oldmarks := nav.marks errMarks := nav.readMarks() for _, ch := range gOpts.tempmarks { tmp := string(ch) if v, e := oldmarks[tmp]; e { nav.marks[tmp] = v } } err = nav.readTags() if errMarks != nil { return errMarks } return err } func (nav *nav) cd(wd string) error { wd = replaceTilde(wd) wd = filepath.Clean(wd) if !filepath.IsAbs(wd) { wd = filepath.Join(nav.currDir().path, wd) } if err := os.Chdir(wd); err != nil { return fmt.Errorf("cd: %s", err) } nav.getDirs(wd) nav.addJumpList() return nil } func (nav *nav) sel(path string) error { path = replaceTilde(path) path = filepath.Clean(path) lstat, err := os.Lstat(path) if err != nil { return fmt.Errorf("select: %s", err) } dir := filepath.Dir(path) if err := nav.cd(dir); err != nil { return fmt.Errorf("select: %s", err) } base := filepath.Base(path) last := nav.dirs[len(nav.dirs)-1] if last.loading { last.files = append(last.files, &file{FileInfo: lstat}) } last.sel(base, nav.height) return nil } func (nav *nav) globSel(pattern string, invert bool) error { dir := nav.currDir() anyMatched := false for i := 0; i < len(dir.files); i++ { matched, err := filepath.Match(pattern, dir.files[i].Name()) if err != nil { return fmt.Errorf("glob-select: %s", err) } if matched { anyMatched = true fpath := filepath.Join(dir.path, dir.files[i].Name()) if _, ok := nav.selections[fpath]; ok == invert { nav.toggleSelection(fpath) } } } if !anyMatched { 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) if !gOpts.smartcase || lpattern == pattern { pattern = lpattern name = strings.ToLower(name) } } if gOpts.ignoredia { lpattern := removeDiacritics(pattern) if !gOpts.smartdia || lpattern == pattern { pattern = lpattern name = removeDiacritics(name) } } if gOpts.anchorfind { return strings.HasPrefix(name, pattern) } return strings.Contains(name, pattern) } func (nav *nav) findSingle() int { count := 0 index := 0 dir := nav.currDir() for i := 0; i < len(dir.files); i++ { if findMatch(dir.files[i].Name(), nav.find) { count++ if count > 1 { return count } index = i } } if count == 1 { if index > dir.ind { nav.down(index - dir.ind) } else { nav.up(dir.ind - index) } } return count } func (nav *nav) findNext() (bool, bool) { dir := nav.currDir() for i := dir.ind + 1; i < len(dir.files); i++ { if findMatch(dir.files[i].Name(), nav.find) { return nav.down(i - dir.ind), true } } if gOpts.wrapscan { for i := 0; i < dir.ind; i++ { if findMatch(dir.files[i].Name(), nav.find) { return nav.up(dir.ind - i), true } } } return false, false } func (nav *nav) findPrev() (bool, bool) { dir := nav.currDir() for i := dir.ind - 1; i >= 0; i-- { if findMatch(dir.files[i].Name(), nav.find) { return nav.up(dir.ind - i), true } } if gOpts.wrapscan { for i := len(dir.files) - 1; i > dir.ind; i-- { if findMatch(dir.files[i].Name(), nav.find) { return nav.down(i - dir.ind), true } } } return false, false } func searchMatch(name, pattern string) (matched bool, err error) { if gOpts.ignorecase { lpattern := strings.ToLower(pattern) if !gOpts.smartcase || lpattern == pattern { pattern = lpattern name = strings.ToLower(name) } } if gOpts.ignoredia { lpattern := removeDiacritics(pattern) if !gOpts.smartdia || lpattern == pattern { pattern = lpattern name = removeDiacritics(name) } } if gOpts.globsearch { return filepath.Match(pattern, name) } return strings.Contains(name, pattern), nil } func (nav *nav) searchNext() (bool, error) { dir := nav.currDir() for i := dir.ind + 1; i < len(dir.files); i++ { if matched, err := searchMatch(dir.files[i].Name(), nav.search); err != nil { return false, err } else if matched { return nav.down(i - dir.ind), nil } } if gOpts.wrapscan { for i := 0; i < dir.ind; i++ { if matched, err := searchMatch(dir.files[i].Name(), nav.search); err != nil { return false, err } else if matched { return nav.up(dir.ind - i), nil } } } return false, nil } func (nav *nav) searchPrev() (bool, error) { dir := nav.currDir() for i := dir.ind - 1; i >= 0; i-- { if matched, err := searchMatch(dir.files[i].Name(), nav.search); err != nil { return false, err } else if matched { return nav.up(dir.ind - i), nil } } if gOpts.wrapscan { for i := len(dir.files) - 1; i > dir.ind; i-- { if matched, err := searchMatch(dir.files[i].Name(), nav.search); err != nil { return false, err } else if matched { return nav.down(i - dir.ind), nil } } } return false, nil } func isFiltered(f os.FileInfo, filter []string) bool { for _, pattern := range filter { matched, err := searchMatch(f.Name(), strings.TrimPrefix(pattern, "!")) if err != nil { log.Printf("Filter Error: %s", err) return false } if strings.HasPrefix(pattern, "!") && matched { return true } else if !strings.HasPrefix(pattern, "!") && !matched { return true } } return false } 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 } if err != nil { return fmt.Errorf("opening marks file: %s", err) } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { toks := strings.SplitN(scanner.Text(), ":", 2) if _, ok := nav.marks[toks[0]]; !ok { nav.marks[toks[0]] = toks[1] } } if err := scanner.Err(); err != nil { return fmt.Errorf("reading marks file: %s", err) } return nil } func (nav *nav) writeMarks() error { if err := os.MkdirAll(filepath.Dir(gMarksPath), os.ModePerm); err != nil { return fmt.Errorf("creating data directory: %s", err) } f, err := os.Create(gMarksPath) if err != nil { return fmt.Errorf("creating marks file: %s", err) } defer f.Close() var keys []string for k := range nav.marks { if !strings.Contains(gOpts.tempmarks, k) { keys = append(keys, k) } } sort.Strings(keys) for _, k := range keys { _, err = f.WriteString(fmt.Sprintf("%s:%s\n", k, nav.marks[k])) if err != nil { return fmt.Errorf("writing marks file: %s", err) } } return nil } func (nav *nav) readTags() error { nav.tags = make(map[string]string) f, err := os.Open(gTagsPath) if os.IsNotExist(err) { return nil } if err != nil { return fmt.Errorf("opening tags file: %s", err) } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { text := scanner.Text() ind := strings.LastIndex(text, ":") path := text[0:ind] mark := text[ind+1:] if _, ok := nav.tags[path]; !ok { nav.tags[path] = mark } } if err := scanner.Err(); err != nil { return fmt.Errorf("reading tags file: %s", err) } return nil } func (nav *nav) writeTags() error { if err := os.MkdirAll(filepath.Dir(gTagsPath), os.ModePerm); err != nil { return fmt.Errorf("creating data directory: %s", err) } f, err := os.Create(gTagsPath) if err != nil { return fmt.Errorf("creating tags file: %s", err) } defer f.Close() var keys []string for k := range nav.tags { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { _, err = f.WriteString(fmt.Sprintf("%s:%s\n", k, nav.tags[k])) if err != nil { return fmt.Errorf("writing tags file: %s", err) } } return nil } func (nav *nav) currDir() *dir { return nav.dirs[len(nav.dirs)-1] } func (nav *nav) currFile() (*file, error) { dir := nav.dirs[len(nav.dirs)-1] if len(dir.files) == 0 { return nil, fmt.Errorf("empty directory") } return dir.files[dir.ind], nil } type indexedSelections struct { paths []string indices []int } func (m indexedSelections) Len() int { return len(m.paths) } func (m indexedSelections) Swap(i, j int) { m.paths[i], m.paths[j] = m.paths[j], m.paths[i] m.indices[i], m.indices[j] = m.indices[j], m.indices[i] } func (m indexedSelections) Less(i, j int) bool { return m.indices[i] < m.indices[j] } func (nav *nav) currSelections() []string { currDirOnly := gOpts.selmode == "dir" currDirPath := "" if currDirOnly { // select only from this directory currDirPath = nav.currDir().path } paths := make([]string, 0, len(nav.selections)) indices := make([]int, 0, len(nav.selections)) for path, index := range nav.selections { if !currDirOnly || filepath.Dir(path) == currDirPath { paths = append(paths, path) indices = append(indices, index) } } sort.Sort(indexedSelections{paths: paths, indices: indices}) return paths } func (nav *nav) currFileOrSelections() (list []string, err error) { sel := nav.currSelections() if len(sel) == 0 { curr, err := nav.currFile() if err != nil { return nil, errors.New("no file selected") } return []string{curr.path}, nil } return sel, nil } func (nav *nav) calcDirSize() error { calc := func(f *file) error { if f.IsDir() { total, err := copySize([]string{f.path}) if err != nil { return err } f.dirSize = total } return nil } if len(nav.selections) == 0 { curr, err := nav.currFile() if err != nil { return errors.New("no file selected") } return calc(curr) } for sel := range nav.selections { lstat, err := os.Lstat(sel) if err != nil || !lstat.IsDir() { continue } path, name := filepath.Dir(sel), filepath.Base(sel) dir := nav.loadDir(path) for _, f := range dir.files { if f.Name() == name { err := calc(f) if err != nil { return err } break } } } return nil } lf-r28/opts.go000066400000000000000000000210031435165676200134170ustar00rootroot00000000000000package main import "time" type sortMethod byte const ( naturalSort sortMethod = iota nameSort sizeSort timeSort atimeSort ctimeSort extSort ) type sortOption byte const ( dirfirstSort sortOption = 1 << iota hiddenSort reverseSort ) type sortType struct { method sortMethod option sortOption } var gOpts struct { anchorfind bool autoquit bool dircache bool dircounts bool dironly bool dirpreviews bool drawbox bool globsearch bool icons bool ignorecase bool ignoredia bool incfilter bool incsearch bool mouse bool number bool preview bool relativenumber bool smartcase bool smartdia bool waitmsg string wrapscan bool wrapscroll bool findlen int period int scrolloff int tabstop int errorfmt string filesep string ifs string previewer string cleaner string promptfmt string selmode string shell string shellflag string timefmt string infotimefmtnew string infotimefmtold string truncatechar string ratios []int hiddenfiles []string history bool info []string shellopts []string keys map[string]expr cmdkeys map[string]expr cmds map[string]expr user map[string]string sortType sortType tempmarks string tagfmt string } func init() { gOpts.anchorfind = true gOpts.autoquit = false gOpts.dircache = true gOpts.dircounts = false gOpts.dironly = false gOpts.dirpreviews = false gOpts.drawbox = false gOpts.globsearch = false gOpts.icons = false gOpts.ignorecase = true gOpts.ignoredia = true gOpts.incfilter = false gOpts.incsearch = false gOpts.mouse = false gOpts.number = false gOpts.preview = true gOpts.relativenumber = false gOpts.smartcase = true gOpts.smartdia = false gOpts.waitmsg = "Press any key to continue" gOpts.wrapscan = true gOpts.wrapscroll = false gOpts.findlen = 1 gOpts.period = 0 gOpts.scrolloff = 0 gOpts.tabstop = 8 gOpts.errorfmt = "\033[7;31;47m%s\033[0m" gOpts.filesep = "\n" gOpts.ifs = "" gOpts.previewer = "" gOpts.cleaner = "" gOpts.promptfmt = "\033[32;1m%u@%h\033[0m:\033[34;1m%d\033[0m\033[1m%f\033[0m" gOpts.selmode = "all" gOpts.shell = gDefaultShell gOpts.shellflag = gDefaultShellFlag gOpts.timefmt = time.ANSIC gOpts.infotimefmtnew = "Jan _2 15:04" gOpts.infotimefmtold = "Jan _2 2006" gOpts.truncatechar = "~" gOpts.ratios = []int{1, 2, 3} gOpts.hiddenfiles = []string{".*"} gOpts.history = true gOpts.info = nil gOpts.shellopts = nil gOpts.sortType = sortType{naturalSort, dirfirstSort} gOpts.tempmarks = "'" gOpts.tagfmt = "\033[31m%s\033[0m" gOpts.keys = make(map[string]expr) gOpts.keys["k"] = &callExpr{"up", nil, 1} gOpts.keys[""] = &callExpr{"up", nil, 1} gOpts.keys[""] = &callExpr{"up", nil, 1} gOpts.keys[""] = &callExpr{"half-up", nil, 1} gOpts.keys[""] = &callExpr{"page-up", nil, 1} gOpts.keys[""] = &callExpr{"page-up", nil, 1} gOpts.keys[""] = &callExpr{"scroll-up", nil, 1} gOpts.keys["j"] = &callExpr{"down", nil, 1} gOpts.keys[""] = &callExpr{"down", nil, 1} gOpts.keys[""] = &callExpr{"down", nil, 1} gOpts.keys[""] = &callExpr{"half-down", nil, 1} gOpts.keys[""] = &callExpr{"page-down", nil, 1} gOpts.keys[""] = &callExpr{"page-down", nil, 1} gOpts.keys[""] = &callExpr{"scroll-down", nil, 1} gOpts.keys["h"] = &callExpr{"updir", nil, 1} gOpts.keys[""] = &callExpr{"updir", nil, 1} gOpts.keys["l"] = &callExpr{"open", nil, 1} gOpts.keys[""] = &callExpr{"open", nil, 1} gOpts.keys["q"] = &callExpr{"quit", nil, 1} gOpts.keys["gg"] = &callExpr{"top", nil, 1} gOpts.keys[""] = &callExpr{"top", nil, 1} gOpts.keys["G"] = &callExpr{"bottom", nil, 1} gOpts.keys[""] = &callExpr{"bottom", nil, 1} gOpts.keys["H"] = &callExpr{"high", nil, 1} gOpts.keys["M"] = &callExpr{"middle", nil, 1} gOpts.keys["L"] = &callExpr{"low", nil, 1} gOpts.keys["["] = &callExpr{"jump-prev", nil, 1} gOpts.keys["]"] = &callExpr{"jump-next", nil, 1} gOpts.keys[""] = &listExpr{[]expr{&callExpr{"toggle", nil, 1}, &callExpr{"down", nil, 1}}, 1} gOpts.keys["t"] = &callExpr{"tag-toggle", nil, 1} gOpts.keys["v"] = &callExpr{"invert", nil, 1} gOpts.keys["u"] = &callExpr{"unselect", nil, 1} gOpts.keys["y"] = &callExpr{"copy", nil, 1} gOpts.keys["d"] = &callExpr{"cut", nil, 1} gOpts.keys["c"] = &callExpr{"clear", nil, 1} gOpts.keys["p"] = &callExpr{"paste", nil, 1} gOpts.keys[""] = &callExpr{"redraw", nil, 1} gOpts.keys[""] = &callExpr{"reload", nil, 1} gOpts.keys[":"] = &callExpr{"read", nil, 1} gOpts.keys["$"] = &callExpr{"shell", nil, 1} gOpts.keys["%"] = &callExpr{"shell-pipe", nil, 1} gOpts.keys["!"] = &callExpr{"shell-wait", nil, 1} gOpts.keys["&"] = &callExpr{"shell-async", nil, 1} gOpts.keys["f"] = &callExpr{"find", nil, 1} gOpts.keys["F"] = &callExpr{"find-back", nil, 1} gOpts.keys[";"] = &callExpr{"find-next", nil, 1} gOpts.keys[","] = &callExpr{"find-prev", nil, 1} gOpts.keys["/"] = &callExpr{"search", nil, 1} gOpts.keys["?"] = &callExpr{"search-back", nil, 1} gOpts.keys["n"] = &callExpr{"search-next", nil, 1} gOpts.keys["N"] = &callExpr{"search-prev", nil, 1} gOpts.keys["m"] = &callExpr{"mark-save", nil, 1} gOpts.keys["'"] = &callExpr{"mark-load", nil, 1} gOpts.keys[`"`] = &callExpr{"mark-remove", nil, 1} gOpts.keys[`r`] = &callExpr{"rename", nil, 1} gOpts.keys[""] = &callExpr{"cmd-history-next", nil, 1} gOpts.keys[""] = &callExpr{"cmd-history-prev", nil, 1} gOpts.keys["zh"] = &setExpr{"hidden!", ""} gOpts.keys["zr"] = &setExpr{"reverse!", ""} gOpts.keys["zn"] = &setExpr{"info", ""} gOpts.keys["zs"] = &setExpr{"info", "size"} gOpts.keys["zt"] = &setExpr{"info", "time"} gOpts.keys["za"] = &setExpr{"info", "size:time"} gOpts.keys["sn"] = &listExpr{[]expr{&setExpr{"sortby", "natural"}, &setExpr{"info", ""}}, 1} gOpts.keys["ss"] = &listExpr{[]expr{&setExpr{"sortby", "size"}, &setExpr{"info", "size"}}, 1} gOpts.keys["st"] = &listExpr{[]expr{&setExpr{"sortby", "time"}, &setExpr{"info", "time"}}, 1} gOpts.keys["sa"] = &listExpr{[]expr{&setExpr{"sortby", "atime"}, &setExpr{"info", "atime"}}, 1} gOpts.keys["sc"] = &listExpr{[]expr{&setExpr{"sortby", "ctime"}, &setExpr{"info", "ctime"}}, 1} gOpts.keys["se"] = &listExpr{[]expr{&setExpr{"sortby", "ext"}, &setExpr{"info", ""}}, 1} gOpts.keys["gh"] = &callExpr{"cd", []string{"~"}, 1} gOpts.cmdkeys = make(map[string]expr) gOpts.cmdkeys[""] = &callExpr{"cmd-insert", []string{" "}, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-escape", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-complete", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-enter", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-enter", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-history-next", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-history-prev", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-back", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-back", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-left", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-left", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-right", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-right", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-home", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-home", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-end", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-end", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-home", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-end", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-unix-word", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-yank", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-transpose", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-interrupt", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-word", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-word-back", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-capitalize-word", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-word", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-uppercase-word", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-lowercase-word", nil, 1} gOpts.cmdkeys[""] = &callExpr{"cmd-transpose-word", nil, 1} gOpts.cmds = make(map[string]expr) gOpts.user = make(map[string]string) setDefaults() } lf-r28/os.go000066400000000000000000000113411435165676200130570ustar00rootroot00000000000000//go:build !windows package main import ( "fmt" "log" "os" "os/exec" "os/user" "path/filepath" "runtime" "strings" "syscall" "golang.org/x/sys/unix" ) var ( envOpener = os.Getenv("OPENER") envEditor = os.Getenv("EDITOR") envPager = os.Getenv("PAGER") envShell = os.Getenv("SHELL") ) var ( gDefaultShell = "sh" gDefaultShellFlag = "-c" gDefaultSocketProt = "unix" gDefaultSocketPath string ) var ( gUser *user.User gConfigPaths []string gColorsPaths []string gIconsPaths []string gFilesPath string gMarksPath string gTagsPath string gHistoryPath string ) func init() { if envOpener == "" { if runtime.GOOS == "darwin" { envOpener = "open" } else { envOpener = "xdg-open" } } if envEditor == "" { envEditor = "vi" } if envPager == "" { envPager = "less" } if envShell == "" { envShell = "sh" } u, err := user.Current() if err != nil { // When the user is not in /etc/passwd (for e.g. LDAP) and CGO_ENABLED=1 in go env, // the cgo implementation of user.Current() fails even when HOME and USER are set. log.Printf("user: %s", err) if os.Getenv("HOME") == "" { panic("$HOME variable is empty or not set") } if os.Getenv("USER") == "" { panic("$USER variable is empty or not set") } u = &user.User{ Username: os.Getenv("USER"), HomeDir: os.Getenv("HOME"), } } gUser = u config := os.Getenv("XDG_CONFIG_HOME") if config == "" { config = filepath.Join(gUser.HomeDir, ".config") } gConfigPaths = []string{ filepath.Join("/etc", "lf", "lfrc"), filepath.Join(config, "lf", "lfrc"), } gColorsPaths = []string{ filepath.Join("/etc", "lf", "colors"), filepath.Join(config, "lf", "colors"), } gIconsPaths = []string{ filepath.Join("/etc", "lf", "icons"), filepath.Join(config, "lf", "icons"), } data := os.Getenv("XDG_DATA_HOME") if data == "" { data = filepath.Join(gUser.HomeDir, ".local", "share") } gFilesPath = filepath.Join(data, "lf", "files") gMarksPath = filepath.Join(data, "lf", "marks") gTagsPath = filepath.Join(data, "lf", "tags") gHistoryPath = filepath.Join(data, "lf", "history") runtime := os.Getenv("XDG_RUNTIME_DIR") if runtime == "" { runtime = os.TempDir() } gDefaultSocketPath = filepath.Join(runtime, fmt.Sprintf("lf.%s.sock", gUser.Username)) } func detachedCommand(name string, arg ...string) *exec.Cmd { cmd := exec.Command(name, arg...) cmd.SysProcAttr = &unix.SysProcAttr{Setsid: true} return cmd } func shellCommand(s string, args []string) *exec.Cmd { if len(gOpts.ifs) != 0 { s = fmt.Sprintf("IFS='%s'; %s", gOpts.ifs, s) } args = append([]string{gOpts.shellflag, s, "--"}, args...) args = append(gOpts.shellopts, args...) return exec.Command(gOpts.shell, args...) } func shellSetPG(cmd *exec.Cmd) { cmd.SysProcAttr = &unix.SysProcAttr{Setpgid: true} } func shellKill(cmd *exec.Cmd) error { pgid, err := unix.Getpgid(cmd.Process.Pid) if err == nil && cmd.Process.Pid == pgid { // kill the process group err = unix.Kill(-pgid, 15) if err == nil { return nil } } return cmd.Process.Kill() } func setDefaults() { gOpts.cmds["open"] = &execExpr{"&", `$OPENER "$f"`} gOpts.keys["e"] = &execExpr{"$", `$EDITOR "$f"`} gOpts.keys["i"] = &execExpr{"$", `$PAGER "$f"`} gOpts.keys["w"] = &execExpr{"$", "$SHELL"} gOpts.cmds["doc"] = &execExpr{"$", "lf -doc | $PAGER"} gOpts.keys[""] = &callExpr{"doc", nil, 1} } func setUserUmask() { unix.Umask(0077) } func isExecutable(f os.FileInfo) bool { return f.Mode()&0111 != 0 } func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool { hidden := false for _, pattern := range hiddenfiles { matched := matchPattern(strings.TrimPrefix(pattern, "!"), f.Name(), path) if strings.HasPrefix(pattern, "!") && matched { hidden = false } else if matched { hidden = true } } return hidden } func userName(f os.FileInfo) string { if stat, ok := f.Sys().(*syscall.Stat_t); ok { if u, err := user.LookupId(fmt.Sprint(stat.Uid)); err == nil { return fmt.Sprintf("%v ", u.Username) } } return "" } func groupName(f os.FileInfo) string { if stat, ok := f.Sys().(*syscall.Stat_t); ok { if g, err := user.LookupGroupId(fmt.Sprint(stat.Gid)); err == nil { return fmt.Sprintf("%v ", g.Name) } } return "" } func linkCount(f os.FileInfo) string { if stat, ok := f.Sys().(*syscall.Stat_t); ok { return fmt.Sprintf("%v ", stat.Nlink) } return "" } func errCrossDevice(err error) bool { return err.(*os.LinkError).Err.(unix.Errno) == unix.EXDEV } func exportFiles(f string, fs []string, pwd string) { envFile := f envFiles := strings.Join(fs, gOpts.filesep) os.Setenv("f", envFile) os.Setenv("fs", envFiles) os.Setenv("PWD", pwd) if len(fs) == 0 { os.Setenv("fx", envFile) } else { os.Setenv("fx", envFiles) } } lf-r28/os_windows.go000066400000000000000000000072201435165676200146320ustar00rootroot00000000000000package main import ( "fmt" "log" "os" "os/exec" "os/user" "path/filepath" "strings" "golang.org/x/sys/windows" ) var ( envOpener = os.Getenv("OPENER") envEditor = os.Getenv("EDITOR") envPager = os.Getenv("PAGER") envShell = os.Getenv("SHELL") ) var envPathExt = os.Getenv("PATHEXT") var ( gDefaultShell = "cmd" gDefaultShellFlag = "/c" gDefaultSocketProt = "tcp" gDefaultSocketPath = "127.0.0.1:12345" ) var ( gUser *user.User gConfigPaths []string gColorsPaths []string gIconsPaths []string gFilesPath string gTagsPath string gMarksPath string gHistoryPath string ) func init() { if envOpener == "" { envOpener = `start ""` } if envEditor == "" { envEditor = "notepad" } if envPager == "" { envPager = "more" } if envShell == "" { envShell = "cmd" } u, err := user.Current() if err != nil { log.Printf("user: %s", err) } gUser = u // remove domain prefix gUser.Username = strings.Split(gUser.Username, `\`)[1] data := os.Getenv("LOCALAPPDATA") gConfigPaths = []string{ filepath.Join(os.Getenv("ProgramData"), "lf", "lfrc"), filepath.Join(data, "lf", "lfrc"), } gColorsPaths = []string{ filepath.Join(os.Getenv("ProgramData"), "lf", "colors"), filepath.Join(data, "lf", "colors"), } gIconsPaths = []string{ filepath.Join(os.Getenv("ProgramData"), "lf", "icons"), filepath.Join(data, "lf", "icons"), } gFilesPath = filepath.Join(data, "lf", "files") gMarksPath = filepath.Join(data, "lf", "marks") gTagsPath = filepath.Join(data, "lf", "tags") gHistoryPath = filepath.Join(data, "lf", "history") } func detachedCommand(name string, arg ...string) *exec.Cmd { cmd := exec.Command(name, arg...) cmd.SysProcAttr = &windows.SysProcAttr{CreationFlags: 8} return cmd } func shellCommand(s string, args []string) *exec.Cmd { args = append([]string{gOpts.shellflag, s}, args...) args = append(gOpts.shellopts, args...) return exec.Command(gOpts.shell, args...) } func shellSetPG(cmd *exec.Cmd) { } func shellKill(cmd *exec.Cmd) error { return cmd.Process.Kill() } func setDefaults() { gOpts.cmds["open"] = &execExpr{"&", "%OPENER% %f%"} gOpts.keys["e"] = &execExpr{"$", "%EDITOR% %f%"} gOpts.keys["i"] = &execExpr{"!", "%PAGER% %f%"} gOpts.keys["w"] = &execExpr{"$", "%SHELL%"} gOpts.cmds["doc"] = &execExpr{"!", "lf -doc | %PAGER%"} gOpts.keys[""] = &callExpr{"doc", nil, 1} } func setUserUmask() {} func isExecutable(f os.FileInfo) bool { exts := strings.Split(envPathExt, string(filepath.ListSeparator)) for _, e := range exts { if strings.HasSuffix(strings.ToLower(f.Name()), strings.ToLower(e)) { log.Print(f.Name(), e) return true } } return false } func isHidden(f os.FileInfo, path string, hiddenfiles []string) bool { ptr, err := windows.UTF16PtrFromString(filepath.Join(path, f.Name())) if err != nil { return false } attrs, err := windows.GetFileAttributes(ptr) if err != nil { return false } return attrs&windows.FILE_ATTRIBUTE_HIDDEN != 0 } func userName(f os.FileInfo) string { return "" } func groupName(f os.FileInfo) string { return "" } func linkCount(f os.FileInfo) string { return "" } func errCrossDevice(err error) bool { return err.(*os.LinkError).Err.(windows.Errno) == 17 } func exportFiles(f string, fs []string, pwd string) { envFile := fmt.Sprintf(`"%s"`, f) var quotedFiles []string for _, f := range fs { quotedFiles = append(quotedFiles, fmt.Sprintf(`"%s"`, f)) } envFiles := strings.Join(quotedFiles, gOpts.filesep) envPWD := fmt.Sprintf(`"%s"`, pwd) os.Setenv("f", envFile) os.Setenv("fs", envFiles) os.Setenv("PWD", envPWD) if len(fs) == 0 { os.Setenv("fx", envFile) } else { os.Setenv("fx", envFiles) } } lf-r28/parse.go000066400000000000000000000106271435165676200135560ustar00rootroot00000000000000package main // Grammar of the language used in the evaluator // // Expr = SetExpr // | MapExpr // | CMapExpr // | CmdExpr // | CallExpr // | ExecExpr // | ListExpr // // SetExpr = 'set' ';' // // MapExpr = 'map' Expr // // CMapExpr = 'cmap' Expr // // CmdExpr = 'cmd' Expr // // CallExpr = ';' // // ExecExpr = Prefix '\n' // | Prefix '{{' '}}' ';' // // Prefix = '$' | '%' | '!' | '&' // // ListExpr = ':' Expr ListRest '\n' // | ':' '{{' Expr ListRest '}}' ';' // // ListRest = Nil // | Expr ListExpr import ( "bytes" "fmt" "io" "strings" ) type expr interface { String() string eval(app *app, args []string) } type setExpr struct { opt string val string } func (e *setExpr) String() string { return fmt.Sprintf("set %s %s", e.opt, e.val) } type mapExpr struct { keys string expr expr } func (e *mapExpr) String() string { return fmt.Sprintf("map %s %s", e.keys, e.expr) } type cmapExpr struct { key string expr expr } func (e *cmapExpr) String() string { return fmt.Sprintf("cmap %s %s", e.key, e.expr) } type cmdExpr struct { name string expr expr } func (e *cmdExpr) String() string { return fmt.Sprintf("cmd %s %s", e.name, e.expr) } type callExpr struct { name string args []string count int } func (e *callExpr) String() string { return fmt.Sprintf("%s -- %s", e.name, e.args) } type execExpr struct { prefix string value string } func (e *execExpr) String() string { var buf bytes.Buffer buf.WriteString(e.prefix) buf.WriteString("{{ ") lines := strings.Split(e.value, "\n") for _, line := range lines { trimmed := strings.TrimSpace(line) if trimmed == "" { continue } buf.WriteString(trimmed) if len(lines) > 1 { buf.WriteString(" ...") } break } buf.WriteString(" }}") return buf.String() } type listExpr struct { exprs []expr count int } func (e *listExpr) String() string { var buf bytes.Buffer buf.WriteString(":{{ ") for _, expr := range e.exprs { buf.WriteString(expr.String()) buf.WriteString("; ") } buf.WriteString("}}") return buf.String() } type parser struct { scanner *scanner expr expr err error } func newParser(r io.Reader) *parser { scanner := newScanner(r) scanner.scan() return &parser{ scanner: scanner, } } func (p *parser) parseExpr() expr { s := p.scanner var result expr switch s.typ { case tokenEOF: return nil case tokenIdent: switch s.tok { case "set": var val string s.scan() if s.typ != tokenIdent { p.err = fmt.Errorf("expected identifier: %s", s.tok) } opt := s.tok s.scan() if s.typ != tokenSemicolon { val = s.tok s.scan() } s.scan() result = &setExpr{opt, val} case "map": var expr expr s.scan() keys := s.tok s.scan() if s.typ != tokenSemicolon { expr = p.parseExpr() } else { s.scan() } result = &mapExpr{keys, expr} case "cmap": var expr expr s.scan() key := s.tok s.scan() if s.typ != tokenSemicolon { expr = p.parseExpr() } else { s.scan() } result = &cmapExpr{key, expr} case "cmd": var expr expr s.scan() name := s.tok s.scan() if s.typ != tokenSemicolon { expr = p.parseExpr() } else { s.scan() } result = &cmdExpr{name, expr} default: name := s.tok var args []string for s.scan() && s.typ != tokenSemicolon { args = append(args, s.tok) } s.scan() result = &callExpr{name, args, 1} } case tokenColon: s.scan() var exprs []expr if s.typ == tokenLBraces { s.scan() for { e := p.parseExpr() if e == nil { return nil } exprs = append(exprs, e) if s.typ == tokenRBraces { break } } s.scan() } else { for { e := p.parseExpr() if e == nil { return nil } exprs = append(exprs, e) if s.tok == "\n" { break } } } s.scan() result = &listExpr{exprs, 1} case tokenPrefix: var expr string prefix := s.tok s.scan() if s.typ == tokenLBraces { s.scan() expr = s.tok s.scan() } else { expr = s.tok } s.scan() s.scan() result = &execExpr{prefix, expr} default: p.err = fmt.Errorf("unexpected token: %s", s.tok) } return result } func (p *parser) parse() bool { if p.expr = p.parseExpr(); p.expr == nil { return false } return true } lf-r28/scan.go000066400000000000000000000126101435165676200133620ustar00rootroot00000000000000package main import ( "io" "io/ioutil" "log" "strconv" ) type tokenType byte const ( tokenEOF tokenType = iota // no explicit keyword type tokenIdent // e.g. set, ratios, 1:2:3 tokenColon // : tokenPrefix // $, %, !, & tokenLBraces // {{ tokenRBraces // }} tokenCommand // in between a prefix to \n or between {{ and }} tokenSemicolon // ; // comments are stripped ) type scanner struct { buf []byte // input buffer off int // current offset in buf chr byte // current character in buf sem bool // insert semicolon nln bool // insert newline eof bool // buffer ended key bool // scanning keys blk bool // scanning block cmd bool // scanning command typ tokenType // scanned token type tok string // scanned token value // TODO: pos } func newScanner(r io.Reader) *scanner { buf, err := ioutil.ReadAll(r) if err != nil { log.Printf("scanning: %s", err) } var eof bool var chr byte if len(buf) == 0 { eof = true } else { eof = false chr = buf[0] } return &scanner{ buf: buf, eof: eof, chr: chr, } } func (s *scanner) next() { if s.off+1 < len(s.buf) { s.off++ s.chr = s.buf[s.off] return } s.off = len(s.buf) s.chr = 0 s.eof = true } func (s *scanner) peek() byte { if s.off+1 < len(s.buf) { return s.buf[s.off+1] } return 0 } func isSpace(b byte) bool { switch b { case '\t', '\n', '\v', '\f', '\r', ' ': return true } return false } func isDigit(b byte) bool { return '0' <= b && b <= '9' } func isPrefix(b byte) bool { switch b { case '$', '%', '!', '&': return true } return false } func (s *scanner) scan() bool { scan: switch { case s.eof: s.next() if s.sem { s.typ = tokenSemicolon s.tok = "\n" s.sem = false return true } if s.nln { s.typ = tokenSemicolon s.tok = "\n" s.nln = false return true } s.typ = tokenEOF s.tok = "EOF" return false case s.key: beg := s.off for !s.eof && !isSpace(s.chr) { s.next() } s.typ = tokenIdent s.tok = string(s.buf[beg:s.off]) s.key = false case s.blk: // return here by setting s.cmd to false // after scanning the command in the loop below if !s.cmd { s.next() s.next() s.typ = tokenRBraces s.tok = "}}" s.blk = false s.sem = true return true } beg := s.off for !s.eof { s.next() if s.chr == '}' { if !s.eof && s.peek() == '}' { s.typ = tokenCommand s.tok = string(s.buf[beg:s.off]) s.cmd = false return true } } } s.typ = tokenEOF s.tok = "EOF" return false case s.cmd: for !s.eof && isSpace(s.chr) { s.next() } if !s.eof && s.chr == '{' { if s.peek() == '{' { s.next() s.next() s.typ = tokenLBraces s.tok = "{{" s.blk = true return true } } beg := s.off for !s.eof && s.chr != '\n' { s.next() } s.typ = tokenCommand s.tok = string(s.buf[beg:s.off]) s.cmd = false s.sem = true case s.chr == '\n': if s.sem { s.typ = tokenSemicolon s.tok = "\n" s.sem = false return true } s.next() if s.nln { s.typ = tokenSemicolon s.tok = "\n" s.nln = false return true } goto scan case isSpace(s.chr): for !s.eof && isSpace(s.chr) && s.chr != '\n' { s.next() } goto scan case s.chr == ';': s.typ = tokenSemicolon s.tok = ";" s.sem = false s.next() case s.chr == '#': for !s.eof && s.chr != '\n' { s.next() } goto scan case s.chr == '"': s.next() var buf []byte for !s.eof && s.chr != '"' { if s.chr == '\\' { s.next() switch { case s.chr == '"' || s.chr == '\\': buf = append(buf, s.chr) case s.chr == 'a': buf = append(buf, '\a') case s.chr == 'b': buf = append(buf, '\b') case s.chr == 'f': buf = append(buf, '\f') case s.chr == 'n': buf = append(buf, '\n') case s.chr == 'r': buf = append(buf, '\r') case s.chr == 't': buf = append(buf, '\t') case s.chr == 'v': buf = append(buf, '\v') case isDigit(s.chr): var oct []byte for isDigit(s.chr) { oct = append(oct, s.chr) s.next() } n, err := strconv.ParseInt(string(oct), 8, 0) if err != nil { log.Printf("scanning: %s", err) } buf = append(buf, byte(n)) continue default: buf = append(buf, '\\', s.chr) } s.next() continue } buf = append(buf, s.chr) s.next() } s.typ = tokenIdent s.tok = string(buf) s.next() case s.chr == '\'': s.next() beg := s.off for !s.eof && s.chr != '\'' { s.next() } s.typ = tokenIdent s.tok = string(s.buf[beg:s.off]) s.next() case s.chr == ':': s.typ = tokenColon s.tok = ":" s.nln = true s.next() case s.chr == '{' && s.peek() == '{': s.next() s.next() s.typ = tokenLBraces s.tok = "{{" s.sem = false s.nln = false case s.chr == '}' && s.peek() == '}': s.next() s.next() s.typ = tokenRBraces s.tok = "}}" s.sem = true case isPrefix(s.chr): s.typ = tokenPrefix s.tok = string(s.chr) s.cmd = true s.next() default: var buf []byte for !s.eof && !isSpace(s.chr) && s.chr != ';' && s.chr != '#' { if s.chr == '\\' { s.next() buf = append(buf, s.chr) s.next() continue } buf = append(buf, s.chr) s.next() } s.typ = tokenIdent s.tok = string(buf) s.sem = true if s.tok == "push" { s.key = true for !s.eof && isSpace(s.chr) && s.chr != '\n' { s.next() } } } return true } lf-r28/server.go000066400000000000000000000050521435165676200137460ustar00rootroot00000000000000package main import ( "bufio" "fmt" "log" "net" "os" "strconv" ) var ( gConnList = make(map[int]net.Conn) gQuitChan = make(chan struct{}, 1) gListener net.Listener ) func serve() { if gLogPath != "" { f, err := os.OpenFile(gLogPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { panic(err) } defer f.Close() log.SetOutput(f) } log.Print("hi!") if gSocketProt == "unix" { setUserUmask() } l, err := net.Listen(gSocketProt, gSocketPath) if err != nil { log.Printf("listening socket: %s", err) return } defer l.Close() gListener = l listen(l) } func listen(l net.Listener) { for { c, err := l.Accept() if err != nil { select { case <-gQuitChan: log.Printf("bye!") return default: log.Printf("accepting connection: %s", err) } } go handleConn(c) } } func echoerr(c net.Conn, msg string) { fmt.Fprintln(c, msg) log.Print(msg) } func echoerrf(c net.Conn, format string, a ...interface{}) { echoerr(c, fmt.Sprintf(format, a...)) } func handleConn(c net.Conn) { s := bufio.NewScanner(c) Loop: for s.Scan() { log.Printf("listen: %s", s.Text()) word, rest := splitWord(s.Text()) switch word { case "conn": if rest != "" { word2, _ := splitWord(rest) id, err := strconv.Atoi(word2) if err != nil { echoerr(c, "listen: conn: client id should be a number") } else { gConnList[id] = c } } else { echoerr(c, "listen: conn: requires a client id") } case "drop": if rest != "" { word2, _ := splitWord(rest) id, err := strconv.Atoi(word2) if err != nil { echoerr(c, "listen: drop: client id should be a number") } else { delete(gConnList, id) } } else { echoerr(c, "listen: drop: requires a client id") } case "send": if rest != "" { word2, rest2 := splitWord(rest) id, err := strconv.Atoi(word2) if err != nil { for _, c := range gConnList { fmt.Fprintln(c, rest) } } else { if c2, ok := gConnList[id]; ok { fmt.Fprintln(c2, rest2) } else { echoerr(c, "listen: send: no such client id is connected") } } } case "quit": if len(gConnList) == 0 { gQuitChan <- struct{}{} gListener.Close() break Loop } case "quit!": gQuitChan <- struct{}{} for _, c := range gConnList { fmt.Fprintln(c, "echo server is quitting...") c.Close() } gListener.Close() break Loop default: echoerrf(c, "listen: unexpected command: %s", word) } } if s.Err() != nil { echoerrf(c, "listening: %s", s.Err()) } c.Close() } lf-r28/ui.go000066400000000000000000000741731435165676200130670ustar00rootroot00000000000000package main import ( "bytes" "fmt" "log" "os" "path/filepath" "sort" "strconv" "strings" "text/tabwriter" "time" "unicode" "unicode/utf8" "github.com/gdamore/tcell/v2" "github.com/mattn/go-runewidth" "golang.org/x/term" ) const gEscapeCode = 27 var gKeyVal = map[tcell.Key]string{ tcell.KeyEnter: "", tcell.KeyBackspace: "", tcell.KeyTab: "", tcell.KeyBacktab: "", tcell.KeyEsc: "", tcell.KeyBackspace2: "", tcell.KeyDelete: "", tcell.KeyInsert: "", tcell.KeyUp: "", tcell.KeyDown: "", tcell.KeyLeft: "", tcell.KeyRight: "", tcell.KeyHome: "", tcell.KeyEnd: "", tcell.KeyUpLeft: "", tcell.KeyUpRight: "", tcell.KeyDownLeft: "", tcell.KeyDownRight: "", tcell.KeyCenter: "
", tcell.KeyPgDn: "", tcell.KeyPgUp: "", tcell.KeyClear: "", tcell.KeyExit: "", tcell.KeyCancel: "", tcell.KeyPause: "", tcell.KeyPrint: "", tcell.KeyF1: "", tcell.KeyF2: "", tcell.KeyF3: "", tcell.KeyF4: "", tcell.KeyF5: "", tcell.KeyF6: "", tcell.KeyF7: "", tcell.KeyF8: "", tcell.KeyF9: "", tcell.KeyF10: "", tcell.KeyF11: "", tcell.KeyF12: "", tcell.KeyF13: "", tcell.KeyF14: "", tcell.KeyF15: "", tcell.KeyF16: "", tcell.KeyF17: "", tcell.KeyF18: "", tcell.KeyF19: "", tcell.KeyF20: "", tcell.KeyF21: "", tcell.KeyF22: "", tcell.KeyF23: "", tcell.KeyF24: "", tcell.KeyF25: "", tcell.KeyF26: "", tcell.KeyF27: "", tcell.KeyF28: "", tcell.KeyF29: "", tcell.KeyF30: "", tcell.KeyF31: "", tcell.KeyF32: "", tcell.KeyF33: "", tcell.KeyF34: "", tcell.KeyF35: "", tcell.KeyF36: "", tcell.KeyF37: "", tcell.KeyF38: "", tcell.KeyF39: "", tcell.KeyF40: "", tcell.KeyF41: "", tcell.KeyF42: "", tcell.KeyF43: "", tcell.KeyF44: "", tcell.KeyF45: "", tcell.KeyF46: "", tcell.KeyF47: "", tcell.KeyF48: "", tcell.KeyF49: "", tcell.KeyF50: "", tcell.KeyF51: "", tcell.KeyF52: "", tcell.KeyF53: "", tcell.KeyF54: "", tcell.KeyF55: "", tcell.KeyF56: "", tcell.KeyF57: "", tcell.KeyF58: "", tcell.KeyF59: "", tcell.KeyF60: "", tcell.KeyF61: "", tcell.KeyF62: "", tcell.KeyF63: "", tcell.KeyF64: "", tcell.KeyCtrlA: "", tcell.KeyCtrlB: "", tcell.KeyCtrlC: "", tcell.KeyCtrlD: "", tcell.KeyCtrlE: "", tcell.KeyCtrlF: "", tcell.KeyCtrlG: "", tcell.KeyCtrlJ: "", tcell.KeyCtrlK: "", tcell.KeyCtrlL: "", tcell.KeyCtrlN: "", tcell.KeyCtrlO: "", tcell.KeyCtrlP: "", tcell.KeyCtrlQ: "", tcell.KeyCtrlR: "", tcell.KeyCtrlS: "", tcell.KeyCtrlT: "", tcell.KeyCtrlU: "", tcell.KeyCtrlV: "", tcell.KeyCtrlW: "", tcell.KeyCtrlX: "", tcell.KeyCtrlY: "", tcell.KeyCtrlZ: "", tcell.KeyCtrlSpace: "", tcell.KeyCtrlUnderscore: "", tcell.KeyCtrlRightSq: "", tcell.KeyCtrlBackslash: "", tcell.KeyCtrlCarat: "", } var gValKey map[string]tcell.Key func init() { gValKey = make(map[string]tcell.Key) for k, v := range gKeyVal { gValKey[v] = k } } type win struct { w, h, x, y int } func newWin(w, h, x, y int) *win { return &win{w, h, x, y} } func (win *win) renew(w, h, x, y int) { win.w, win.h, win.x, win.y = w, h, x, y } func printLength(s string) int { ind := 0 off := 0 for i := 0; i < len(s); i++ { r, w := utf8.DecodeRuneInString(s[i:]) if r == gEscapeCode && i+1 < len(s) && s[i+1] == '[' { j := strings.IndexAny(s[i:min(len(s), i+64)], "mK") if j == -1 { continue } i += j continue } i += w - 1 if r == '\t' { ind += gOpts.tabstop - (ind-off)%gOpts.tabstop } else { ind += runewidth.RuneWidth(r) } } return ind } func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) tcell.Style { off := x var comb []rune for i := 0; i < len(s); i++ { r, w := utf8.DecodeRuneInString(s[i:]) if r == gEscapeCode && i+1 < len(s) && s[i+1] == '[' { j := strings.IndexAny(s[i:min(len(s), i+64)], "mK") if j == -1 { continue } if s[i+j] == 'm' { st = applyAnsiCodes(s[i+2:i+j], st) } i += j continue } for { rc, wc := utf8.DecodeRuneInString(s[i+w:]) if !unicode.Is(unicode.Mn, rc) { break } comb = append(comb, rc) i += wc } if x < win.w { screen.SetContent(win.x+x, win.y+y, r, comb, st) comb = nil } i += w - 1 if r == '\t' { s := gOpts.tabstop - (x-off)%gOpts.tabstop for i := 0; i < s && x+i < win.w; i++ { screen.SetContent(win.x+x+i, win.y+y, ' ', nil, st) } x += s } else { x += runewidth.RuneWidth(r) } } return st } func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...interface{}) { win.print(screen, x, y, st, fmt.Sprintf(format, a...)) } func (win *win) printLine(screen tcell.Screen, x, y int, st tcell.Style, s string) { win.printf(screen, x, y, st, "%s%*s", s, win.w-printLength(s), "") } func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string) { win.print(screen, win.w-printLength(s), y, st, s) } func (win *win) printReg(screen tcell.Screen, reg *reg) { if reg == nil { return } st := tcell.StyleDefault if reg.loading { st = st.Reverse(true) win.print(screen, 2, 0, st, "loading...") return } for i, l := range reg.lines { if i > win.h-1 { break } st = win.print(screen, 2, i, st, l) } } var gThisYear = time.Now().Year() func infotimefmt(t time.Time) string { if t.Year() == gThisYear { return t.Format(gOpts.infotimefmtnew) } return t.Format(gOpts.infotimefmtold) } func fileInfo(f *file, d *dir) string { var info string for _, s := range gOpts.info { switch s { case "size": if !(f.IsDir() && gOpts.dircounts) { var sz string if f.IsDir() && f.dirSize < 0 { sz = "-" } else { sz = humanize(f.TotalSize()) } info = fmt.Sprintf("%s %4s", info, sz) continue } switch { case f.dirCount < -1: info = fmt.Sprintf("%s !", info) case f.dirCount < 0: info = fmt.Sprintf("%s ?", info) case f.dirCount < 1000: info = fmt.Sprintf("%s %4d", info, f.dirCount) default: info = fmt.Sprintf("%s 999+", info) } case "time": info = fmt.Sprintf("%s %*s", info, max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime())) case "atime": info = fmt.Sprintf("%s %*s", info, max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime)) case "ctime": info = fmt.Sprintf("%s %*s", info, max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime)) default: log.Printf("unknown info type: %s", s) } } return info } type dirContext struct { selections map[string]int saves map[string]bool tags map[string]string } type dirStyle struct { colors styleMap icons iconMap previewing bool } // These colors are not currently customizeable const LineNumberColor = tcell.ColorOlive const SelectionColor = tcell.ColorPurple const YankColor = tcell.ColorOlive const CutColor = tcell.ColorMaroon func (win *win) printDir(screen tcell.Screen, dir *dir, context *dirContext, dirStyle *dirStyle) { if win.w < 5 || dir == nil { return } messageStyle := tcell.StyleDefault.Reverse(true) if dir.noPerm { win.print(screen, 2, 0, messageStyle, "permission denied") return } if (dir.loading && len(dir.files) == 0) || (dirStyle.previewing && dir.loading && gOpts.dirpreviews) { win.print(screen, 2, 0, messageStyle, "loading...") return } if dirStyle.previewing && gOpts.dirpreviews && len(gOpts.previewer) > 0 { // Print previewer result instead of default directory print operation. st := tcell.StyleDefault for i, l := range dir.lines { if i > win.h-1 { break } st = win.print(screen, 2, i, st, l) } return } if len(dir.files) == 0 { win.print(screen, 2, 0, messageStyle, "empty") return } beg := max(dir.ind-dir.pos, 0) end := min(beg+win.h, len(dir.files)) if beg > end { return } var lnwidth int var lnformat string if gOpts.number || gOpts.relativenumber { lnwidth = 1 if gOpts.number && gOpts.relativenumber { lnwidth++ } for j := 10; j < len(dir.files); j *= 10 { lnwidth++ } lnformat = fmt.Sprintf("%%%d.d ", lnwidth) } for i, f := range dir.files[beg:end] { st := dirStyle.colors.get(f) if lnwidth > 0 { var ln string if gOpts.number && (!gOpts.relativenumber) { ln = fmt.Sprintf(lnformat, i+1+beg) } else if gOpts.relativenumber { switch { case i < dir.pos: ln = fmt.Sprintf(lnformat, dir.pos-i) case i > dir.pos: ln = fmt.Sprintf(lnformat, i-dir.pos) case gOpts.number: ln = fmt.Sprintf(fmt.Sprintf("%%%d.d ", lnwidth-1), i+1+beg) default: ln = "" } } win.print(screen, 0, i, tcell.StyleDefault.Foreground(LineNumberColor), ln) } path := filepath.Join(dir.path, f.Name()) if _, ok := context.selections[path]; ok { win.print(screen, lnwidth, i, st.Background(SelectionColor), " ") } else if cp, ok := context.saves[path]; ok { if cp { win.print(screen, lnwidth, i, st.Background(YankColor), " ") } else { win.print(screen, lnwidth, i, st.Background(CutColor), " ") } } if i == dir.pos { st = st.Reverse(true) } var s []rune s = append(s, ' ') var iwidth int if gOpts.icons { s = append(s, []rune(dirStyle.icons.get(f))...) s = append(s, ' ') iwidth = 2 } for _, r := range f.Name() { s = append(s, r) } w := runeSliceWidth(s) if w > win.w-3 { s = runeSliceWidthRange(s, 0, win.w-4) s = append(s, []rune(gOpts.truncatechar)...) } else { for i := 0; i < win.w-3-w; i++ { s = append(s, ' ') } } info := fileInfo(f, dir) if len(info) > 0 && win.w-lnwidth-iwidth-2 > 2*len(info) { if win.w-2 > w+len(info) { s = runeSliceWidthRange(s, 0, win.w-3-len(info)-lnwidth) } else { s = runeSliceWidthRange(s, 0, win.w-4-len(info)-lnwidth) s = append(s, []rune(gOpts.truncatechar)...) } for _, r := range info { s = append(s, r) } } s = append(s, ' ') win.print(screen, lnwidth+1, i, st, string(s)) tag, ok := context.tags[path] if ok { if i == dir.pos { win.print(screen, lnwidth+1, i, st, tag) } else { win.print(screen, lnwidth+1, i, tcell.StyleDefault, fmt.Sprintf(gOpts.tagfmt, tag)) } } } } func getWidths(wtot int) []int { rsum := 0 for _, r := range gOpts.ratios { rsum += r } wlen := len(gOpts.ratios) widths := make([]int, wlen) wsum := 0 for i := 0; i < wlen-1; i++ { widths[i] = gOpts.ratios[i] * wtot / rsum wsum += widths[i] } widths[wlen-1] = wtot - wsum if gOpts.drawbox { widths[wlen-1]-- } return widths } func getWins(screen tcell.Screen) []*win { wtot, htot := screen.Size() var wins []*win widths := getWidths(wtot) wacc := 0 wlen := len(widths) for i := 0; i < wlen; i++ { if gOpts.drawbox { wins = append(wins, newWin(widths[i], htot-4, wacc+1, 2)) } else { wins = append(wins, newWin(widths[i], htot-2, wacc, 1)) } wacc += widths[i] } return wins } type ui struct { screen tcell.Screen polling bool wins []*win promptWin *win msgWin *win menuWin *win msg string regPrev *reg dirPrev *dir exprChan chan expr keyChan chan string tevChan chan tcell.Event evChan chan tcell.Event menuBuf *bytes.Buffer cmdPrefix string cmdAccLeft []rune cmdAccRight []rune cmdYankBuf []rune cmdTmp []rune keyAcc []rune keyCount []rune styles styleMap icons iconMap currentFile string } func newUI(screen tcell.Screen) *ui { wtot, htot := screen.Size() ui := &ui{ screen: screen, polling: true, wins: getWins(screen), promptWin: newWin(wtot, 1, 0, 0), msgWin: newWin(wtot, 1, 0, htot-1), menuWin: newWin(wtot, 1, 0, htot-2), exprChan: make(chan expr, 1000), keyChan: make(chan string, 1000), tevChan: make(chan tcell.Event, 1000), evChan: make(chan tcell.Event, 1000), styles: parseStyles(), icons: parseIcons(), currentFile: "", } go ui.pollEvents() return ui } func (ui *ui) winAt(x, y int) (int, *win) { for i := len(ui.wins) - 1; i >= 0; i-- { w := ui.wins[i] if x >= w.x && y >= w.y && y < w.y+w.h { return i, w } } return -1, nil } func (ui *ui) pollEvents() { var ev tcell.Event for { ev = ui.screen.PollEvent() if ev == nil { ui.polling = false return } ui.tevChan <- ev } } func (ui *ui) renew() { wtot, htot := ui.screen.Size() widths := getWidths(wtot) wacc := 0 wlen := len(widths) for i := 0; i < wlen; i++ { if gOpts.drawbox { ui.wins[i].renew(widths[i], htot-4, wacc+1, 2) } else { ui.wins[i].renew(widths[i], htot-2, wacc, 1) } wacc += widths[i] } ui.promptWin.renew(wtot, 1, 0, 0) ui.msgWin.renew(wtot, 1, 0, htot-1) ui.menuWin.renew(wtot, 1, 0, htot-2) } func (ui *ui) sort() { if ui.dirPrev == nil { return } name := ui.dirPrev.name() ui.dirPrev.sort() ui.dirPrev.sel(name, ui.wins[0].h) } func (ui *ui) echo(msg string) { ui.msg = msg } func (ui *ui) echof(format string, a ...interface{}) { ui.echo(fmt.Sprintf(format, a...)) } func (ui *ui) echomsg(msg string) { ui.msg = msg log.Print(msg) } func (ui *ui) echoerr(msg string) { ui.msg = fmt.Sprintf(gOpts.errorfmt, msg) log.Printf("error: %s", msg) } func (ui *ui) echoerrf(format string, a ...interface{}) { ui.echoerr(fmt.Sprintf(format, a...)) } type reg struct { loading bool volatile bool loadTime time.Time path string lines []string } func (ui *ui) loadFile(app *app, volatile bool) { if !app.nav.init { return } curr, err := app.nav.currFile() if err != nil { return } if curr.path == ui.currentFile { return } ui.currentFile = curr.path onSelect(app) if !gOpts.preview { return } if volatile { app.nav.previewChan <- "" } if curr.IsDir() { ui.dirPrev = app.nav.loadDir(curr.path) } else if curr.Mode().IsRegular() { ui.regPrev = app.nav.loadReg(curr.path, volatile) } } func (ui *ui) loadFileInfo(nav *nav) { if !nav.init { return } curr, err := nav.currFile() if err != nil { return } var linkTarget string if curr.linkTarget != "" { linkTarget = " -> " + curr.linkTarget } ui.echof("%v %v%v%v%4s %v%s", curr.Mode(), linkCount(curr), // optional userName(curr), // optional groupName(curr), // optional humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt), linkTarget) } func (ui *ui) drawPromptLine(nav *nav) { st := tcell.StyleDefault dir := nav.currDir() pwd := dir.path if strings.HasPrefix(pwd, gUser.HomeDir) { pwd = filepath.Join("~", strings.TrimPrefix(pwd, gUser.HomeDir)) } sep := string(filepath.Separator) var fname string curr, err := nav.currFile() if err == nil { fname = filepath.Base(curr.path) } var prompt string prompt = strings.Replace(gOpts.promptfmt, "%u", gUser.Username, -1) prompt = strings.Replace(prompt, "%h", gHostname, -1) prompt = strings.Replace(prompt, "%f", fname, -1) if printLength(strings.Replace(strings.Replace(prompt, "%w", pwd, -1), "%d", pwd, -1)) > ui.promptWin.w { names := strings.Split(pwd, sep) for i := range names { if names[i] == "" { continue } r, _ := utf8.DecodeRuneInString(names[i]) names[i] = string(r) if printLength(strings.Replace(strings.Replace(prompt, "%w", strings.Join(names, sep), -1), "%d", strings.Join(names, sep), -1)) <= ui.promptWin.w { break } } pwd = strings.Join(names, sep) } prompt = strings.Replace(prompt, "%w", pwd, -1) if !strings.HasSuffix(pwd, sep) { pwd += sep } prompt = strings.Replace(prompt, "%d", pwd, -1) if len(dir.filter) != 0 { prompt = strings.Replace(prompt, "%F", fmt.Sprint(dir.filter), -1) } else { prompt = strings.Replace(prompt, "%F", "", -1) } // spacer avail := ui.promptWin.w - printLength(prompt) + 2 if avail > 0 { prompt = strings.Replace(prompt, "%S", strings.Repeat(" ", avail), 1) } prompt = strings.Replace(prompt, "%S", "", -1) ui.promptWin.print(ui.screen, 0, 0, st, prompt) } func (ui *ui) drawStatLine(nav *nav) { st := tcell.StyleDefault dir := nav.currDir() ui.msgWin.print(ui.screen, 0, 0, st, ui.msg) tot := len(dir.files) ind := min(dir.ind+1, tot) acc := string(ui.keyCount) + string(ui.keyAcc) var selection string if len(nav.saves) > 0 { copy := 0 move := 0 for _, cp := range nav.saves { if cp { copy++ } else { move++ } } if copy > 0 { selection += fmt.Sprintf(" \033[33;7m %d \033[0m", copy) } if move > 0 { selection += fmt.Sprintf(" \033[31;7m %d \033[0m", move) } } currSelections := nav.currSelections() if len(currSelections) > 0 { selection += fmt.Sprintf(" \033[35;7m %d \033[0m", len(currSelections)) } if len(dir.filter) != 0 { selection += " \033[34;7m F \033[0m" } var progress string if nav.copyTotal > 0 { percentage := int((100 * float64(nav.copyBytes)) / float64(nav.copyTotal)) progress += fmt.Sprintf(" [%d%%]", percentage) } if nav.moveTotal > 0 { progress += fmt.Sprintf(" [%d/%d]", nav.moveCount, nav.moveTotal) } if nav.deleteTotal > 0 { progress += fmt.Sprintf(" [%d/%d]", nav.deleteCount, nav.deleteTotal) } ruler := fmt.Sprintf("%s%s%s %d/%d", acc, progress, selection, ind, tot) ui.msgWin.printRight(ui.screen, 0, st, ruler) } func (ui *ui) drawBox() { st := tcell.StyleDefault w, h := ui.screen.Size() for i := 1; i < w-1; i++ { ui.screen.SetContent(i, 1, '─', nil, st) ui.screen.SetContent(i, h-2, '─', nil, st) } for i := 2; i < h-2; i++ { ui.screen.SetContent(0, i, '│', nil, st) ui.screen.SetContent(w-1, i, '│', nil, st) } ui.screen.SetContent(0, 1, '┌', nil, st) ui.screen.SetContent(w-1, 1, '┐', nil, st) ui.screen.SetContent(0, h-2, '└', nil, st) ui.screen.SetContent(w-1, h-2, '┘', nil, st) wacc := 0 for wind := 0; wind < len(ui.wins)-1; wind++ { wacc += ui.wins[wind].w ui.screen.SetContent(wacc, 1, '┬', nil, st) for i := 2; i < h-2; i++ { ui.screen.SetContent(wacc, i, '│', nil, st) } ui.screen.SetContent(wacc, h-2, '┴', nil, st) } } func (ui *ui) dirOfWin(nav *nav, wind int) *dir { wins := len(ui.wins) if gOpts.preview { wins-- } ind := len(nav.dirs) - wins + wind if ind < 0 { return nil } return nav.dirs[ind] } func (ui *ui) draw(nav *nav) { st := tcell.StyleDefault context := dirContext{selections: nav.selections, saves: nav.saves, tags: nav.tags} wtot, htot := ui.screen.Size() for i := 0; i < wtot; i++ { for j := 0; j < htot; j++ { ui.screen.SetContent(i, j, ' ', nil, st) } } ui.drawPromptLine(nav) wins := len(ui.wins) if gOpts.preview { wins-- } for i := 0; i < wins; i++ { if dir := ui.dirOfWin(nav, i); dir != nil { ui.wins[i].printDir(ui.screen, dir, &context, &dirStyle{colors: ui.styles, icons: ui.icons, previewing: false}) } } switch ui.cmdPrefix { case "": ui.drawStatLine(nav) ui.screen.HideCursor() case ">": prefix := ui.cmdPrefix[:min(ui.msgWin.w-1, len(ui.cmdPrefix))] pos := min(runeSliceWidth(ui.cmdAccLeft), ui.msgWin.w-len(prefix)-1) left := ui.cmdAccLeft[runeSliceWidth(ui.cmdAccLeft)-pos:] right := ui.cmdAccRight ui.msgWin.printLine(ui.screen, 0, 0, st, prefix) ui.msgWin.print(ui.screen, len(prefix), 0, st, ui.msg) ui.msgWin.print(ui.screen, len(prefix)+printLength(ui.msg), 0, st, string(left)) ui.msgWin.print(ui.screen, len(prefix)+printLength(ui.msg)+runeSliceWidth(left), 0, st, string(right)) ui.screen.ShowCursor(ui.msgWin.x+len(prefix)+printLength(ui.msg)+runeSliceWidth(left), ui.msgWin.y) default: prefix := ui.cmdPrefix[:min(ui.msgWin.w-1, len(ui.cmdPrefix))] pos := min(runeSliceWidth(ui.cmdAccLeft), ui.msgWin.w-len(prefix)-1) left := ui.cmdAccLeft[runeSliceWidth(ui.cmdAccLeft)-pos:] right := ui.cmdAccRight ui.msgWin.printLine(ui.screen, 0, 0, st, prefix) ui.msgWin.print(ui.screen, len(prefix), 0, st, string(left)) ui.msgWin.print(ui.screen, len(prefix)+runeSliceWidth(left), 0, st, string(right)) ui.screen.ShowCursor(ui.msgWin.x+len(prefix)+runeSliceWidth(left), ui.msgWin.y) } if gOpts.preview { curr, err := nav.currFile() if err == nil { preview := ui.wins[len(ui.wins)-1] if curr.IsDir() { preview.printDir(ui.screen, ui.dirPrev, &context, &dirStyle{colors: ui.styles, icons: ui.icons, previewing: true}) } else if curr.Mode().IsRegular() { preview.printReg(ui.screen, ui.regPrev) } } } if gOpts.drawbox { ui.drawBox() } if ui.menuBuf != nil { lines := strings.Split(ui.menuBuf.String(), "\n") lines = lines[:len(lines)-1] ui.menuWin.h = len(lines) - 1 ui.menuWin.y = ui.wins[0].h - ui.menuWin.h if gOpts.drawbox { ui.menuWin.y += 2 } ui.menuWin.printLine(ui.screen, 0, 0, st.Bold(true), lines[0]) for i, line := range lines[1:] { ui.menuWin.printLine(ui.screen, 0, i+1, st, "") ui.menuWin.print(ui.screen, 0, i+1, st, line) } } ui.screen.Show() } func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) { binds = make(map[string]expr) for key, expr := range keys { if !strings.HasPrefix(key, prefix) { continue } binds[key] = expr if key == prefix { ok = true } } return } func listBinds(binds map[string]expr) *bytes.Buffer { t := new(tabwriter.Writer) b := new(bytes.Buffer) var keys []string for k := range binds { keys = append(keys, k) } sort.Strings(keys) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "keys\tcommand") for _, k := range keys { fmt.Fprintf(t, "%s\t%v\n", k, binds[k]) } t.Flush() return b } func listMarks(marks map[string]string) *bytes.Buffer { t := new(tabwriter.Writer) b := new(bytes.Buffer) var keys []string for k := range marks { keys = append(keys, k) } sort.Strings(keys) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "mark\tpath") for _, k := range keys { fmt.Fprintf(t, "%s\t%s\n", k, marks[k]) } t.Flush() return b } func (ui *ui) pollEvent() tcell.Event { select { case val := <-ui.keyChan: var ch rune var mod tcell.ModMask k := tcell.KeyRune if utf8.RuneCountInString(val) == 1 { ch, _ = utf8.DecodeRuneInString(val) } else { switch { case val == "": ch = '<' case val == "": ch = '>' case val == "": ch = ' ' case reAltKey.MatchString(val): match := reAltKey.FindStringSubmatch(val)[1] ch, _ = utf8.DecodeRuneInString(match) mod = tcell.ModMask(tcell.ModAlt) default: if key, ok := gValKey[val]; ok { k = key } else { k = tcell.KeyESC ui.echoerrf("unknown key: %s", val) } } } return tcell.NewEventKey(k, ch, mod) case ev := <-ui.tevChan: return ev } } // This function is used to read a normal event on the client side. For keys, // digits are interpreted as command counts but this is only done for digits // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k"). func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr { draw := &callExpr{"draw", nil, 1} count := 0 switch tev := ev.(type) { case *tcell.EventKey: // KeyRune is a regular character if tev.Key() == tcell.KeyRune { switch { case tev.Rune() == '<': ui.keyAcc = append(ui.keyAcc, []rune("")...) case tev.Rune() == '>': ui.keyAcc = append(ui.keyAcc, []rune("")...) case tev.Rune() == ' ': ui.keyAcc = append(ui.keyAcc, []rune("")...) case tev.Modifiers() == tcell.ModAlt: ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', tev.Rune(), '>') case unicode.IsDigit(tev.Rune()) && len(ui.keyAcc) == 0: ui.keyCount = append(ui.keyCount, tev.Rune()) default: ui.keyAcc = append(ui.keyAcc, tev.Rune()) } } else { val := gKeyVal[tev.Key()] if val == "" && string(ui.keyAcc) != "" { ui.keyAcc = nil ui.keyCount = nil ui.menuBuf = nil return draw } ui.keyAcc = append(ui.keyAcc, []rune(val)...) } if len(ui.keyAcc) == 0 { return draw } binds, ok := findBinds(gOpts.keys, string(ui.keyAcc)) switch len(binds) { case 0: ui.echoerrf("unknown mapping: %s", string(ui.keyAcc)) ui.keyAcc = nil ui.keyCount = nil ui.menuBuf = nil return draw default: 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 && count != 0 { expr = &callExpr{e.name, e.args, e.count} expr.(*callExpr).count = count } else if e, ok := expr.(*listExpr); ok && count != 0 { expr = &listExpr{e.exprs, e.count} expr.(*listExpr).count = count } ui.keyAcc = nil ui.keyCount = nil ui.menuBuf = nil return expr } ui.menuBuf = listBinds(binds) return draw } case *tcell.EventMouse: if ui.cmdPrefix != "" { return nil } var button string switch tev.Buttons() { case tcell.Button1: button = "" case tcell.Button2: button = "" case tcell.Button3: button = "" case tcell.Button4: button = "" case tcell.Button5: button = "" case tcell.Button6: button = "" case tcell.Button7: button = "" case tcell.Button8: button = "" case tcell.WheelUp: button = "" case tcell.WheelDown: button = "" case tcell.WheelLeft: button = "" case tcell.WheelRight: button = "" case tcell.ButtonNone: return nil } if expr, ok := gOpts.keys[button]; ok { return expr } if tev.Buttons() != tcell.Button1 && tev.Buttons() != tcell.Button2 { return nil } x, y := tev.Position() wind, w := ui.winAt(x, y) if wind == -1 { return nil } var dir *dir if gOpts.preview && wind == len(ui.wins)-1 { curr, err := nav.currFile() if err != nil { return nil } else if !curr.IsDir() || gOpts.dirpreviews { if tev.Buttons() != tcell.Button2 { return nil } return &callExpr{"open", nil, 1} } dir = ui.dirPrev } else { dir = ui.dirOfWin(nav, wind) if dir == nil { return nil } } var file *file ind := dir.ind - dir.pos + y - w.y if ind < len(dir.files) { file = dir.files[ind] } if file != nil { sel := &callExpr{"select", []string{file.path}, 1} if tev.Buttons() == tcell.Button1 { return sel } if file.IsDir() { return &callExpr{"cd", []string{file.path}, 1} } return &listExpr{[]expr{sel, &callExpr{"open", nil, 1}}, 1} } if tev.Buttons() == tcell.Button1 { return &callExpr{"cd", []string{dir.path}, 1} } case *tcell.EventResize: return &callExpr{"redraw", nil, 1} case *tcell.EventError: log.Printf("Got EventError: '%s' at %s", tev.Error(), tev.When()) case *tcell.EventInterrupt: log.Printf("Got EventInterrupt: at %s", tev.When()) } return nil } func readCmdEvent(ev tcell.Event) expr { switch tev := ev.(type) { case *tcell.EventKey: if tev.Key() == tcell.KeyRune { if tev.Modifiers() == tcell.ModMask(tcell.ModAlt) { val := string([]rune{'<', 'a', '-', tev.Rune(), '>'}) if expr, ok := gOpts.cmdkeys[val]; ok { return expr } } else { return &callExpr{"cmd-insert", []string{string(tev.Rune())}, 1} } } else { val := gKeyVal[tev.Key()] if expr, ok := gOpts.cmdkeys[val]; ok { return expr } } } return nil } func (ui *ui) readEvent(ev tcell.Event, nav *nav) expr { if ev == nil { return nil } if _, ok := ev.(*tcell.EventKey); ok && ui.cmdPrefix != "" { return readCmdEvent(ev) } return ui.readNormalEvent(ev, nav) } func (ui *ui) readExpr() { go func() { for { ui.evChan <- ui.pollEvent() } }() } func (ui *ui) suspend() error { return ui.screen.Suspend() } func (ui *ui) resume() error { err := ui.screen.Resume() if !ui.polling { go ui.pollEvents() ui.polling = true } return err } func (ui *ui) exportSizes() { w, h := ui.screen.Size() os.Setenv("lf_width", strconv.Itoa(w)) os.Setenv("lf_height", strconv.Itoa(h)) } func anyKey() { fmt.Print(gOpts.waitmsg) defer fmt.Print("\n") oldState, err := term.MakeRaw(int(os.Stdin.Fd())) if err != nil { panic(err) } defer term.Restore(int(os.Stdin.Fd()), oldState) b := make([]byte, 1) os.Stdin.Read(b) } func listMatches(screen tcell.Screen, matches []string, selectedInd int) *bytes.Buffer { if len(matches) < 2 { return nil } b := new(bytes.Buffer) wtot, _ := screen.Size() wcol := 0 for _, m := range matches { wcol = max(wcol, len(m)) } wcol += gOpts.tabstop - wcol%gOpts.tabstop ncol := wtot / wcol b.WriteString("possible matches\n") for i := 0; i < len(matches); { for j := 0; j < ncol && i < len(matches); i, j = i+1, j+1 { target := matches[i] if selectedInd == i { target = fmt.Sprintf("\033[7m%s\033[0m%*s", target, wcol-len(target), "") } else { target = fmt.Sprintf("%s%*s", target, wcol-len(target), "") } b.WriteString(target) } b.WriteByte('\n') } return b }