diff --git a/app.go b/app.go index fe574f56..e38b483c 100644 --- a/app.go +++ b/app.go @@ -9,55 +9,59 @@ import ( ) type cmdItem struct { - pref string - s string + prefix string + value string } type app struct { - ui *ui - nav *nav - quit chan bool - cmdHist []cmdItem - cmdHind int + ui *ui + nav *nav + quitChan chan bool + cmdHist []cmdItem + cmdHistInd int } func newApp() *app { ui := newUI() nav := newNav(ui.wins[0].h) - quit := make(chan bool, 1) return &app{ - ui: ui, - nav: nav, - quit: quit, + ui: ui, + nav: nav, + quitChan: make(chan bool, 1), } } -func waitKey() error { - // TODO: this should be done with termbox somehow +func (app *app) readFile(path string) { + log.Printf("reading file: %s", path) - cmd := pauseCommand() + f, err := os.Open(path) + if err != nil { + app.ui.printf("opening file: %s", err) + return + } + defer f.Close() - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - - if err := cmd.Run(); err != nil { - return fmt.Errorf("waiting key: %s", err) + p := newParser(f) + for p.parse() { + p.expr.eval(app, nil) } - return nil + if p.err != nil { + app.ui.printf("%s", p.err) + } } // This is the main event loop of the application. There are two channels to // read expressions from client and server. Reading and evaluation are done on // separate goroutines. -func (app *app) handleInp(serverChan <-chan expr) { +func (app *app) loop() { clientChan := app.ui.readExpr() + serverChan := readExpr() for { select { - case <-app.quit: + case <-app.quitChan: log.Print("bye!") if gLastDirPath != "" { @@ -91,7 +95,7 @@ func (app *app) handleInp(serverChan <-chan expr) { func (app *app) exportVars() { var envFile string if f, err := app.nav.currFile(); err == nil { - envFile = f.Path + envFile = f.path } marks := app.nav.currMarks() @@ -110,6 +114,20 @@ func (app *app) exportVars() { os.Setenv("id", strconv.Itoa(gClientID)) } +func waitKey() error { + cmd := pauseCommand() + + cmd.Stdin = os.Stdin + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + + if err := cmd.Run(); err != nil { + return fmt.Errorf("waiting key: %s", err) + } + + return nil +} + // This function is used to run a command in shell. Following modes are used: // // Prefix Wait Async Stdin/Stdout/Stderr UI action @@ -141,16 +159,12 @@ func (app *app) runShell(s string, args []string, wait bool, async bool) { } if err != nil { - msg := fmt.Sprintf("running shell: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("running shell: %s", err) } if wait { if err := waitKey(); err != nil { - msg := fmt.Sprintf("waiting shell: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("waiting shell: %s", err) } } diff --git a/client.go b/client.go index dc427bb4..1b9093de 100644 --- a/client.go +++ b/client.go @@ -12,7 +12,7 @@ import ( "github.com/nsf/termbox-go" ) -func client() { +func run() { logFile, err := os.Create(gLogPath) if err != nil { panic(err) @@ -30,58 +30,27 @@ func client() { app := newApp() - app.ui.loadFile(app.nav) - - var serverChan <-chan expr - - c, err := net.Dial(gSocketProt, gSocketPath) - if err != nil { - msg := fmt.Sprintf("connecting server: %s", err) - app.ui.message = msg - log.Printf(msg) - } else { - serverChan = readExpr(c) + if _, err := os.Stat(gConfigPath); !os.IsNotExist(err) { + app.readFile(gConfigPath) } - if err := app.nav.sync(); err != nil { - msg := fmt.Sprintf("sync: %s", err) - app.ui.message = msg - log.Printf(msg) - } - - if _, err := os.Stat(gConfigPath); err == nil { - log.Printf("reading configuration file: %s", gConfigPath) - - rcFile, err := os.Open(gConfigPath) - if err != nil { - msg := fmt.Sprintf("opening configuration file: %s", err) - app.ui.message = msg - log.Printf(msg) - } - defer rcFile.Close() - - p := newParser(rcFile) - for p.parse() { - p.expr.eval(app, nil) - } - - if p.err != nil { - app.ui.message = p.err.Error() - log.Print(p.err) - } - } - - app.ui.draw(app.nav) - - app.handleInp(serverChan) + app.loop() } -func readExpr(c net.Conn) <-chan expr { +func readExpr() <-chan expr { ch := make(chan expr) go func() { + c, err := net.Dial(gSocketProt, gSocketPath) + if err != nil { + log.Printf(fmt.Sprintf("connecting server: %s", err)) + return + } + fmt.Fprintf(c, "conn %d\n", gClientID) + ch <- &callExpr{"sync", nil} + s := bufio.NewScanner(c) for s.Scan() { log.Printf("recv: %s", s.Text()) diff --git a/comp.go b/comp.go index bfc16672..e49690d1 100644 --- a/comp.go +++ b/comp.go @@ -23,8 +23,15 @@ var ( "updir", "open", "quit", - "bot", "top", + "bot", + "toggle", + "invert", + "yank", + "delete", + "put", + "clear", + "renew", "read", "read-shell", "read-shell-wait", @@ -33,16 +40,9 @@ var ( "search-back", "search-next", "search-prev", - "toggle", - "invert", - "yank", - "delete", - "put", - "clear", - "redraw", - "renew", "sync", "echo", + "redraw", "cd", "push", } diff --git a/doc.go b/doc.go index 175ec3a3..f41358e5 100644 --- a/doc.go +++ b/doc.go @@ -21,8 +21,15 @@ The following commands are provided by lf with default keybindings: updir (default 'h' and '') open (default 'l' and '') quit (default 'q') - bot (default 'G') top (default 'gg') + bot (default 'G') + toggle (default '') + invert (default 'v') + yank (default 'y') + delete (default 'd') + put (default 'p') + clear (default 'c') + renew (default '') read (default ':') read-shell (default '$') read-shell-wait (default '!') @@ -31,13 +38,6 @@ The following commands are provided by lf with default keybindings: search-back (default '?') search-next (default 'n') search-prev (default 'N') - toggle (default '') - invert (default 'v') - yank (default 'y') - clear (default 'c') - delete (default 'd') - put (default 'p') - renew (default '') The following commands are provided by lf without default keybindings: @@ -61,8 +61,8 @@ keybindings: cmd-right (default '' and '') cmd-beg (default '' and '') cmd-end (default '' and '') - cmd-delete-end (default '') cmd-delete-beg (default '') + cmd-delete-end (default '') cmd-delete-word (default '') cmd-put (default '') cmd-transpose (default '') diff --git a/docstring.go b/docstring.go index b14da8dd..abb56407 100644 --- a/docstring.go +++ b/docstring.go @@ -25,8 +25,15 @@ The following commands are provided by lf with default keybindings: updir (default 'h' and '') open (default 'l' and '') quit (default 'q') - bot (default 'G') top (default 'gg') + bot (default 'G') + toggle (default '') + invert (default 'v') + yank (default 'y') + delete (default 'd') + put (default 'p') + clear (default 'c') + renew (default '') read (default ':') read-shell (default '$') read-shell-wait (default '!') @@ -35,13 +42,6 @@ The following commands are provided by lf with default keybindings: search-back (default '?') search-next (default 'n') search-prev (default 'N') - toggle (default '') - invert (default 'v') - yank (default 'y') - clear (default 'c') - delete (default 'd') - put (default 'p') - renew (default '') The following commands are provided by lf without default keybindings: @@ -65,8 +65,8 @@ keybindings: cmd-right (default '' and '') cmd-beg (default '' and '') cmd-end (default '' and '') - cmd-delete-end (default '') cmd-delete-beg (default '') + cmd-delete-end (default '') cmd-delete-word (default '') cmd-put (default '') cmd-transpose (default '') diff --git a/eval.go b/eval.go index 1371c404..6b651c3c 100644 --- a/eval.go +++ b/eval.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "log" "os" "strconv" @@ -77,15 +76,11 @@ func (e *setExpr) eval(app *app, args []string) { case "scrolloff": n, err := strconv.Atoi(e.val) if err != nil { - msg := fmt.Sprintf("scrolloff: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("scrolloff: %s", err) return } if n < 0 { - msg := "scrolloff: value should be a non-negative number" - app.ui.message = msg - log.Print(msg) + app.ui.print("scrolloff: value should be a non-negative number") return } max := app.ui.wins[0].h / 2 @@ -96,15 +91,11 @@ func (e *setExpr) eval(app *app, args []string) { case "tabstop": n, err := strconv.Atoi(e.val) if err != nil { - msg := fmt.Sprintf("tabstop: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("tabstop: %s", err) return } if n <= 0 { - msg := "tabstop: value should be a positive number" - app.ui.message = msg - log.Print(msg) + app.ui.print("tabstop: value should be a positive number") return } gOpts.tabstop = n @@ -118,9 +109,7 @@ func (e *setExpr) eval(app *app, args []string) { gOpts.shell = e.val case "sortby": if e.val != "natural" && e.val != "name" && e.val != "size" && e.val != "time" { - msg := "sortby should either be 'natural', 'name', 'size' or 'time'" - app.ui.message = msg - log.Print(msg) + app.ui.print("sortby should either be 'natural', 'name', 'size' or 'time'") return } gOpts.sortby = e.val @@ -133,9 +122,7 @@ func (e *setExpr) eval(app *app, args []string) { for _, s := range toks { i, err := strconv.Atoi(s) if err != nil { - msg := fmt.Sprintf("ratios: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("ratios: %s", err) return } rats = append(rats, i) @@ -147,17 +134,13 @@ func (e *setExpr) eval(app *app, args []string) { toks := strings.Split(e.val, ":") for _, s := range toks { if s != "" && s != "size" && s != "time" { - msg := "info should consist of 'size' or 'time' separated with colon" - app.ui.message = msg - log.Print(msg) + app.ui.print("info should consist of 'size' or 'time' separated with colon") return } } gOpts.info = toks default: - msg := fmt.Sprintf("unknown option: %s", e.opt) - app.ui.message = msg - log.Print(msg) + app.ui.printf("unknown option: %s", e.opt) } } @@ -205,7 +188,6 @@ func splitKeys(s string) (keys []string) { } func (e *callExpr) eval(app *app, args []string) { - // TODO: check for extra toks in each case switch e.name { case "up": app.nav.up(1) @@ -233,8 +215,7 @@ func (e *callExpr) eval(app *app, args []string) { app.ui.loadFileInfo(app.nav) case "updir": if err := app.nav.updir(); err != nil { - app.ui.message = err.Error() - log.Print(err) + app.ui.printf("%s", err) return } app.ui.loadFile(app.nav) @@ -242,18 +223,14 @@ func (e *callExpr) eval(app *app, args []string) { case "open": curr, err := app.nav.currFile() if err != nil { - msg := fmt.Sprintf("opening: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("opening: %s", err) return } if curr.IsDir() { - app.nav.open() + err := app.nav.open() if err != nil { - msg := fmt.Sprintf("opening directory: %s", err) - app.ui.message = msg - log.Print(msg) + app.ui.printf("opening directory: %s", err) return } app.ui.loadFile(app.nav) @@ -274,7 +251,7 @@ func (e *callExpr) eval(app *app, args []string) { marks := app.nav.currMarks() path = strings.Join(marks, "\n") } else if curr, err := app.nav.currFile(); err == nil { - path = curr.Path + path = curr.path } else { return } @@ -284,7 +261,7 @@ func (e *callExpr) eval(app *app, args []string) { log.Printf("writing selection file: %s", err) } - app.quit <- true + app.quitChan <- true return } @@ -293,43 +270,13 @@ func (e *callExpr) eval(app *app, args []string) { cmd.eval(app, e.args) } case "quit": - app.quit <- true - case "bot": - app.nav.bot() - app.ui.loadFile(app.nav) - app.ui.loadFileInfo(app.nav) + app.quitChan <- true case "top": app.nav.top() app.ui.loadFile(app.nav) app.ui.loadFileInfo(app.nav) - case "read": - app.ui.cmdpref = ":" - case "read-shell": - app.ui.cmdpref = "$" - case "read-shell-wait": - app.ui.cmdpref = "!" - case "read-shell-async": - app.ui.cmdpref = "&" - case "search": - app.ui.cmdpref = "/" - case "search-back": - app.ui.cmdpref = "?" - case "search-next": - if err := app.nav.searchNext(); err != nil { - msg := fmt.Sprintf("search: %s: %s", err, app.nav.search) - app.ui.message = msg - log.Printf(msg) - return - } - app.ui.loadFile(app.nav) - app.ui.loadFileInfo(app.nav) - case "search-prev": - if err := app.nav.searchPrev(); err != nil { - msg := fmt.Sprintf("search: %s: %s", err, app.nav.search) - app.ui.message = msg - log.Printf(msg) - return - } + case "bot": + app.nav.bot() app.ui.loadFile(app.nav) app.ui.loadFileInfo(app.nav) case "toggle": @@ -340,80 +287,88 @@ func (e *callExpr) eval(app *app, args []string) { app.nav.invert() case "yank": if err := app.nav.save(true); err != nil { - msg := fmt.Sprintf("yank: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("yank: %s", err) return } app.nav.marks = make(map[string]int) if err := sendRemote("send sync"); err != nil { - msg := fmt.Sprintf("yank: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("yank: %s", err) } case "delete": if err := app.nav.save(false); err != nil { - msg := fmt.Sprintf("delete: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("delete: %s", err) return } app.nav.marks = make(map[string]int) if err := sendRemote("send sync"); err != nil { - msg := fmt.Sprintf("delete: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("delete: %s", err) } case "put": if cmd, ok := gOpts.cmds["put"]; ok { cmd.eval(app, e.args) } else if err := app.nav.put(); err != nil { - msg := fmt.Sprintf("put: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("put: %s", err) return } app.nav.renew(app.nav.height) if err := sendRemote("send sync"); err != nil { - msg := fmt.Sprintf("put: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("put: %s", err) } case "clear": if err := saveFiles(nil, false); err != nil { - msg := fmt.Sprintf("clear: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("clear: %s", err) return } if err := sendRemote("send sync"); err != nil { - msg := fmt.Sprintf("clear: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("clear: %s", err) } - case "redraw": - app.ui.sync() - app.ui.renew() case "renew": app.ui.sync() app.ui.renew() app.nav.renew(app.ui.wins[0].h) + case "read": + app.ui.cmdPrefix = ":" + case "read-shell": + app.ui.cmdPrefix = "$" + case "read-shell-wait": + app.ui.cmdPrefix = "!" + case "read-shell-async": + app.ui.cmdPrefix = "&" + case "search": + app.ui.cmdPrefix = "/" + case "search-back": + app.ui.cmdPrefix = "?" + case "search-next": + if err := app.nav.searchNext(); err != nil { + app.ui.printf("search: %s: %s", err, app.nav.search) + return + } + app.ui.loadFile(app.nav) + app.ui.loadFileInfo(app.nav) + case "search-prev": + if err := app.nav.searchPrev(); err != nil { + app.ui.printf("search: %s: %s", err, app.nav.search) + return + } + app.ui.loadFile(app.nav) + app.ui.loadFileInfo(app.nav) case "sync": if err := app.nav.sync(); err != nil { - msg := fmt.Sprintf("sync: %s", err) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("sync: %s", err) } case "echo": - app.ui.message = strings.Join(e.args, " ") + app.ui.msg = strings.Join(e.args, " ") + case "redraw": + app.ui.sync() + app.ui.renew() + app.ui.loadFile(app.nav) case "cd": path := "~" if len(e.args) > 0 { path = e.args[0] } if err := app.nav.cd(path); err != nil { - app.ui.message = err.Error() - log.Print(err) + app.ui.printf("%s", err) return } app.ui.loadFile(app.nav) @@ -422,40 +377,40 @@ func (e *callExpr) eval(app *app, args []string) { if len(e.args) > 0 { log.Println("pushing keys", e.args[0]) for _, key := range splitKeys(e.args[0]) { - app.ui.keychan <- key + app.ui.keyChan <- key } } case "cmd-insert": if len(e.args) > 0 { - app.ui.cmdlacc = append(app.ui.cmdlacc, []rune(e.args[0])...) + app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(e.args[0])...) } case "cmd-escape": - app.ui.menubuf = nil - app.ui.cmdlacc = nil - app.ui.cmdracc = nil - app.ui.cmdpref = "" + app.ui.menuBuf = nil + app.ui.cmdAccLeft = nil + app.ui.cmdAccRight = nil + app.ui.cmdPrefix = "" case "cmd-comp": var matches []string - if app.ui.cmdpref == ":" { - matches, app.ui.cmdlacc = compCmd(app.ui.cmdlacc) + if app.ui.cmdPrefix == ":" { + matches, app.ui.cmdAccLeft = compCmd(app.ui.cmdAccLeft) } else { - matches, app.ui.cmdlacc = compShell(app.ui.cmdlacc) + matches, app.ui.cmdAccLeft = compShell(app.ui.cmdAccLeft) } app.ui.draw(app.nav) if len(matches) > 1 { - app.ui.menubuf = listMatches(matches) + app.ui.menuBuf = listMatches(matches) } else { - app.ui.menubuf = nil + app.ui.menuBuf = nil } case "cmd-enter": - s := string(append(app.ui.cmdlacc, app.ui.cmdracc...)) + s := string(append(app.ui.cmdAccLeft, app.ui.cmdAccRight...)) if len(s) == 0 { return } - app.ui.menubuf = nil - app.ui.cmdlacc = nil - app.ui.cmdracc = nil - switch app.ui.cmdpref { + app.ui.menuBuf = nil + app.ui.cmdAccLeft = nil + app.ui.cmdAccRight = nil + switch app.ui.cmdPrefix { case ":": log.Printf("command: %s", s) p := newParser(strings.NewReader(s)) @@ -463,8 +418,7 @@ func (e *callExpr) eval(app *app, args []string) { p.expr.eval(app, nil) } if p.err != nil { - app.ui.message = p.err.Error() - log.Print(p.err) + app.ui.printf("%s", p.err) } case "$": log.Printf("shell: %s", s) @@ -479,9 +433,7 @@ func (e *callExpr) eval(app *app, args []string) { log.Printf("search: %s", s) app.nav.search = s if err := app.nav.searchNext(); err != nil { - msg := fmt.Sprintf("search: %s: %s", err, app.nav.search) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("search: %s: %s", err, app.nav.search) } else { app.ui.loadFile(app.nav) app.ui.loadFileInfo(app.nav) @@ -490,94 +442,90 @@ func (e *callExpr) eval(app *app, args []string) { log.Printf("search-back: %s", s) app.nav.search = s if err := app.nav.searchPrev(); err != nil { - msg := fmt.Sprintf("search: %s: %s", err, app.nav.search) - app.ui.message = msg - log.Printf(msg) + app.ui.printf("search: %s: %s", err, app.nav.search) } else { app.ui.loadFile(app.nav) app.ui.loadFileInfo(app.nav) } default: - log.Printf("entering unknown execution prefix: %q", app.ui.cmdpref) + log.Printf("entering unknown execution prefix: %q", app.ui.cmdPrefix) } - app.cmdHist = append(app.cmdHist, cmdItem{app.ui.cmdpref, s}) - app.ui.cmdpref = "" - case "cmd-hist-prev": - if app.cmdHind == len(app.cmdHist) { - return - } - app.cmdHind++ - cmd := app.cmdHist[len(app.cmdHist)-app.cmdHind] - app.ui.cmdpref = cmd.pref - app.ui.cmdlacc = []rune(cmd.s) - app.ui.cmdracc = nil - app.ui.menubuf = nil + app.cmdHist = append(app.cmdHist, cmdItem{app.ui.cmdPrefix, s}) + app.ui.cmdPrefix = "" case "cmd-hist-next": - if app.cmdHind > 0 { - app.cmdHind-- + if app.cmdHistInd > 0 { + app.cmdHistInd-- } - if app.cmdHind == 0 { - app.ui.menubuf = nil - app.ui.cmdlacc = nil - app.ui.cmdracc = nil - app.ui.cmdpref = "" + if app.cmdHistInd == 0 { + app.ui.menuBuf = nil + app.ui.cmdAccLeft = nil + app.ui.cmdAccRight = nil + app.ui.cmdPrefix = "" return } - cmd := app.cmdHist[len(app.cmdHist)-app.cmdHind] - app.ui.cmdpref = cmd.pref - app.ui.cmdlacc = []rune(cmd.s) - app.ui.cmdracc = nil - app.ui.menubuf = nil - case "cmd-delete-back": - if len(app.ui.cmdlacc) > 0 { - app.ui.cmdlacc = app.ui.cmdlacc[:len(app.ui.cmdlacc)-1] + cmd := app.cmdHist[len(app.cmdHist)-app.cmdHistInd] + app.ui.cmdPrefix = cmd.prefix + app.ui.cmdAccLeft = []rune(cmd.value) + app.ui.cmdAccRight = nil + app.ui.menuBuf = nil + case "cmd-hist-prev": + if app.cmdHistInd == len(app.cmdHist) { + return } + app.cmdHistInd++ + cmd := app.cmdHist[len(app.cmdHist)-app.cmdHistInd] + app.ui.cmdPrefix = cmd.prefix + app.ui.cmdAccLeft = []rune(cmd.value) + app.ui.cmdAccRight = nil + app.ui.menuBuf = nil case "cmd-delete": - if len(app.ui.cmdracc) > 0 { - app.ui.cmdracc = app.ui.cmdracc[1:] + if len(app.ui.cmdAccRight) > 0 { + app.ui.cmdAccRight = app.ui.cmdAccRight[1:] + } + case "cmd-delete-back": + if len(app.ui.cmdAccLeft) > 0 { + app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] } case "cmd-left": - if len(app.ui.cmdlacc) > 0 { - app.ui.cmdracc = append([]rune{app.ui.cmdlacc[len(app.ui.cmdlacc)-1]}, app.ui.cmdracc...) - app.ui.cmdlacc = app.ui.cmdlacc[:len(app.ui.cmdlacc)-1] + if len(app.ui.cmdAccLeft) > 0 { + 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.cmdracc) > 0 { - app.ui.cmdlacc = append(app.ui.cmdlacc, app.ui.cmdracc[0]) - app.ui.cmdracc = app.ui.cmdracc[1:] + if len(app.ui.cmdAccRight) > 0 { + app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[0]) + app.ui.cmdAccRight = app.ui.cmdAccRight[1:] } case "cmd-beg": - app.ui.cmdracc = append(app.ui.cmdlacc, app.ui.cmdracc...) - app.ui.cmdlacc = nil + app.ui.cmdAccRight = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) + app.ui.cmdAccLeft = nil case "cmd-end": - app.ui.cmdlacc = append(app.ui.cmdlacc, app.ui.cmdracc...) - app.ui.cmdracc = nil - case "cmd-delete-end": - if len(app.ui.cmdracc) > 0 { - app.ui.cmdbuf = app.ui.cmdracc - app.ui.cmdracc = nil - } + app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) + app.ui.cmdAccRight = nil case "cmd-delete-beg": - if len(app.ui.cmdlacc) > 0 { - app.ui.cmdbuf = app.ui.cmdlacc - app.ui.cmdlacc = nil + if len(app.ui.cmdAccLeft) > 0 { + app.ui.cmdBuf = app.ui.cmdAccLeft + app.ui.cmdAccLeft = nil + } + case "cmd-delete-end": + if len(app.ui.cmdAccRight) > 0 { + app.ui.cmdBuf = app.ui.cmdAccRight + app.ui.cmdAccRight = nil } case "cmd-delete-word": - ind := strings.LastIndex(strings.TrimRight(string(app.ui.cmdlacc), " "), " ") + 1 - app.ui.cmdbuf = app.ui.cmdlacc[ind:] - app.ui.cmdlacc = app.ui.cmdlacc[:ind] + ind := strings.LastIndex(strings.TrimRight(string(app.ui.cmdAccLeft), " "), " ") + 1 + app.ui.cmdBuf = app.ui.cmdAccLeft[ind:] + app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind] case "cmd-put": - app.ui.cmdlacc = append(app.ui.cmdlacc, app.ui.cmdbuf...) + app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdBuf...) case "cmd-transpose": - if len(app.ui.cmdlacc) > 1 { - app.ui.cmdlacc[len(app.ui.cmdlacc)-1], app.ui.cmdlacc[len(app.ui.cmdlacc)-2] = app.ui.cmdlacc[len(app.ui.cmdlacc)-2], app.ui.cmdlacc[len(app.ui.cmdlacc)-1] + if len(app.ui.cmdAccLeft) > 1 { + 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] } default: cmd, ok := gOpts.cmds[e.name] if !ok { - msg := fmt.Sprintf("command not found: %s", e.name) - app.ui.message = msg - log.Print(msg) + app.ui.printf("command not found: %s", e.name) return } cmd.eval(app, e.args) @@ -585,16 +533,16 @@ func (e *callExpr) eval(app *app, args []string) { } func (e *execExpr) eval(app *app, args []string) { - switch e.pref { + switch e.prefix { case "$": log.Printf("shell: %s -- %s", e, args) - app.runShell(e.expr, args, false, false) + app.runShell(e.value, args, false, false) case "!": log.Printf("shell-wait: %s -- %s", e, args) - app.runShell(e.expr, args, true, false) + app.runShell(e.value, args, true, false) case "&": log.Printf("shell-async: %s -- %s", e, args) - app.runShell(e.expr, args, false, true) + app.runShell(e.value, args, false, true) case "/": log.Printf("search: %s -- %s", e, args) // TODO: implement @@ -602,7 +550,7 @@ func (e *execExpr) eval(app *app, args []string) { log.Printf("search-back: %s -- %s", e, args) // TODO: implement default: - log.Printf("evaluating unknown execution prefix: %q", e.pref) + log.Printf("evaluating unknown execution prefix: %q", e.prefix) } } diff --git a/main.go b/main.go index 5b61254e..292440b3 100644 --- a/main.go +++ b/main.go @@ -26,12 +26,11 @@ var ( ) func init() { - var err error - - gHostname, err = os.Hostname() + h, err := os.Hostname() if err != nil { log.Printf("hostname: %s", err) } + gHostname = h } func startServer() { @@ -42,18 +41,52 @@ func startServer() { } func main() { - showDoc := flag.Bool("doc", false, "show documentation") - remoteCmd := flag.String("remote", "", "send remote command to server") - serverMode := flag.Bool("server", false, "start server (automatic)") - cpuprofile := flag.String("cpuprofile", "", "path to the file to write the cpu 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)") + showDoc := flag.Bool( + "doc", + false, + "show documentation") + + remoteCmd := flag.String( + "remote", + "", + "send remote command to server") + + serverMode := flag.Bool( + "server", + false, + "start server (automatic)") + + cpuprofile := flag.String( + "cpuprofile", + "", + "path to the file to write the cpu 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.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 flag.NArg() { case 0: case 1: @@ -67,33 +100,17 @@ func main() { os.Exit(2) } - if *showDoc { + switch { + case *showDoc: fmt.Print(genDocString) - return - } - - if *remoteCmd != "" { + case *remoteCmd != "": if err := sendRemote(*remoteCmd); err != nil { log.Fatalf("remote command: %s", err) } - return - } - - 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() - } - - if *serverMode { + case *serverMode: gServerLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.server.log", gUser.Username)) serve() - } else { + default: // TODO: check if the socket is working if _, err := os.Stat(gSocketPath); os.IsNotExist(err) { startServer() @@ -101,11 +118,11 @@ func main() { gClientID = 1000 gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID)) - for _, err := os.Stat(gLogPath); err == nil; _, err = os.Stat(gLogPath) { + for _, err := os.Stat(gLogPath); !os.IsNotExist(err); _, err = os.Stat(gLogPath) { gClientID++ gLogPath = filepath.Join(os.TempDir(), fmt.Sprintf("lf.%s.%d.log", gUser.Username, gClientID)) } - client() + run() } } diff --git a/misc.go b/misc.go index 20b822cd..eb17858e 100644 --- a/misc.go +++ b/misc.go @@ -21,7 +21,7 @@ func runeSliceWidth(rs []rune) int { return w } -func runeSliceWidthRange(rs []rune, beg int, end int) []rune { +func runeSliceWidthRange(rs []rune, beg, end int) []rune { curr := 0 b := 0 for i, r := range rs { diff --git a/nav.go b/nav.go index 193a921e..96c86f94 100644 --- a/nav.go +++ b/nav.go @@ -20,9 +20,9 @@ const ( type file struct { os.FileInfo - LinkState linkState - Path string - Count int + linkState linkState + path string + count int } type filesSortable struct { @@ -39,51 +39,6 @@ func sortFilesStable(files []*file, less func(i, j int) bool) { sort.Stable(filesSortable{files: files, less: less}) } -func getFilesSorted(path string) []*file { - fi, err := readdir(path) - if err != nil { - log.Printf("reading directory: %s", err) - } - - switch gOpts.sortby { - case "natural": - sortFilesStable(fi, func(i, j int) bool { - return naturalLess(strings.ToLower(fi[i].Name()), strings.ToLower(fi[j].Name())) - }) - case "name": - sortFilesStable(fi, func(i, j int) bool { - return strings.ToLower(fi[i].Name()) < strings.ToLower(fi[j].Name()) - }) - case "size": - sortFilesStable(fi, func(i, j int) bool { - return fi[i].Size() < fi[j].Size() - }) - case "time": - sortFilesStable(fi, func(i, j int) bool { - return fi[i].ModTime().Before(fi[j].ModTime()) - }) - default: - log.Printf("unknown sorting type: %s", gOpts.sortby) - } - - if gOpts.reverse { - for i, j := 0, len(fi)-1; i < j; i, j = i+1, j-1 { - fi[i], fi[j] = fi[j], fi[i] - } - } - - if gOpts.dirfirst { - sortFilesStable(fi, func(i, j int) bool { - if fi[i].IsDir() == fi[j].IsDir() { - return i < j - } - return fi[i].IsDir() - }) - } - - return fi -} - func readdir(path string) ([]*file, error) { f, err := os.Open(path) if err != nil { @@ -124,11 +79,12 @@ func readdir(path string) ([]*file, error) { fi = append(fi, &file{ FileInfo: lstat, - LinkState: linkState, - Path: fpath, - Count: -1, + linkState: linkState, + path: fpath, + count: -1, }) } + return fi, err } @@ -139,45 +95,28 @@ type dir struct { fi []*file } -func newDir(path string, height int) *dir { +func newDir(path string) *dir { fi, err := readdir(path) if err != nil { log.Printf("reading directory: %s", err) } - dir := &dir{ + return &dir{ path: path, fi: fi, } - - dir.sort(height) - - return dir } -func (dir *dir) renew(height int) { - var name string - if len(dir.fi) != 0 { - name = dir.fi[dir.ind].Name() - } - +func (dir *dir) renew() { fi, err := readdir(dir.path) if err != nil { log.Printf("reading directory: %s", err) } dir.fi = fi - - dir.sort(height) - - dir.find(dir.ind, dir.pos, height, name) } -func (dir *dir) sort(height int) { - if len(dir.fi) != 0 && dir.ind < len(dir.fi) { - defer dir.find(dir.ind, dir.pos, height, dir.fi[dir.ind].Name()) - } - +func (dir *dir) sort() { switch gOpts.sortby { case "natural": sortFilesStable(dir.fi, func(i, j int) bool { @@ -215,35 +154,39 @@ func (dir *dir) sort(height int) { } } -func (dir *dir) find(ind, pos, height int, name string) { +func (dir *dir) name() string { + if len(dir.fi) == 0 { + return "" + } + return dir.fi[dir.ind].Name() +} + +func (dir *dir) find(name string, height int) { if len(dir.fi) == 0 { dir.ind, dir.pos = 0, 0 return } - ind = max(0, min(ind, len(dir.fi)-1)) + dir.ind = max(0, min(dir.ind, len(dir.fi)-1)) - if dir.fi[ind].Name() != name { + if dir.fi[dir.ind].Name() != name { for i, f := range dir.fi { if f.Name() == name { - ind = i + dir.ind = i break } } - edge := min(gOpts.scrolloff, len(dir.fi)-ind-1) - pos = min(ind, height-edge-1) + edge := min(gOpts.scrolloff, len(dir.fi)-dir.ind-1) + dir.pos = min(dir.ind, height-edge-1) } - - dir.ind = ind - dir.pos = pos } type nav struct { dirs []*dir dirCache map[string]*dir - marks map[string]int saves map[string]bool + marks map[string]int markInd int height int search string @@ -294,7 +237,10 @@ func (nav *nav) getDirs(wd string) { func (nav *nav) renew(height int) { nav.height = height for _, d := range nav.dirs { - d.renew(nav.height) + name := d.name() + d.renew() + d.sort() + d.find(name, height) } for m := range nav.marks { @@ -310,7 +256,8 @@ func (nav *nav) renew(height int) { func (nav *nav) load(path string) *dir { dir, ok := nav.dirCache[path] if !ok { - dir = newDir(path, nav.height) + dir = newDir(path) + dir.sort() dir.ind, dir.pos = 0, 0 nav.dirCache[path] = dir } @@ -319,7 +266,9 @@ func (nav *nav) load(path string) *dir { func (nav *nav) sort() { for _, d := range nav.dirs { - d.sort(nav.height) + name := d.name() + d.sort() + d.find(name, nav.height) } } @@ -383,7 +332,7 @@ func (nav *nav) open() error { return fmt.Errorf("open: %s", err) } - path := curr.Path + path := curr.path dir := nav.load(path) @@ -396,6 +345,13 @@ func (nav *nav) open() error { return nil } +func (nav *nav) top() { + dir := nav.currDir() + + dir.ind = 0 + dir.pos = 0 +} + func (nav *nav) bot() { dir := nav.currDir() @@ -403,11 +359,101 @@ func (nav *nav) bot() { dir.pos = min(dir.ind, nav.height-1) } -func (nav *nav) top() { +func (nav *nav) toggleMark(path string) { + if _, ok := nav.marks[path]; ok { + delete(nav.marks, path) + if len(nav.marks) == 0 { + nav.markInd = 0 + } + } else { + nav.marks[path] = nav.markInd + nav.markInd = nav.markInd + 1 + } +} + +func (nav *nav) toggle() { + curr, err := nav.currFile() + if err != nil { + return + } + + nav.toggleMark(curr.path) + + nav.down(1) +} + +func (nav *nav) invert() { + last := nav.currDir() + for _, f := range last.fi { + path := filepath.Join(last.path, f.Name()) + nav.toggleMark(path) + } +} + +func (nav *nav) save(copy bool) error { + if len(nav.marks) == 0 { + curr, err := nav.currFile() + if err != nil { + return errors.New("no file selected") + } + + if err := saveFiles([]string{curr.path}, copy); err != nil { + return err + } + + nav.saves = make(map[string]bool) + nav.saves[curr.path] = copy + } else { + marks := nav.currMarks() + + if err := saveFiles(marks, copy); err != nil { + return err + } + + nav.saves = make(map[string]bool) + for f := range nav.marks { + nav.saves[f] = copy + } + } + + return nil +} + +func (nav *nav) put() error { + list, copy, err := loadFiles() + if err != nil { + return err + } + + if len(list) == 0 { + return errors.New("no file in yank/delete buffer") + } + dir := nav.currDir() - dir.ind = 0 - dir.pos = 0 + cmd := putCommand(list, dir, copy) + + if err := cmd.Run(); err != nil { + return fmt.Errorf("putting files: %s", err) + } + + saveFiles(nil, false) + + return nil +} + +func (nav *nav) sync() error { + list, copy, err := loadFiles() + if err != nil { + return err + } + + nav.saves = make(map[string]bool) + for _, f := range list { + nav.saves[f] = copy + } + + return nil } func (nav *nav) cd(wd string) error { @@ -495,109 +541,6 @@ func (nav *nav) searchPrev() error { return nil } -func (nav *nav) toggleMark(path string) { - if _, ok := nav.marks[path]; ok { - delete(nav.marks, path) - if len(nav.marks) == 0 { - nav.markInd = 0 - } - } else { - nav.marks[path] = nav.markInd - nav.markInd = nav.markInd + 1 - } -} - -func (nav *nav) toggle() { - curr, err := nav.currFile() - if err != nil { - return - } - - nav.toggleMark(curr.Path) - - nav.down(1) -} - -func (nav *nav) invert() { - last := nav.currDir() - for _, f := range last.fi { - path := filepath.Join(last.path, f.Name()) - nav.toggleMark(path) - } -} - -func (nav *nav) save(copy bool) error { - if len(nav.marks) == 0 { - curr, err := nav.currFile() - if err != nil { - return errors.New("no file selected") - } - - if err := saveFiles([]string{curr.Path}, copy); err != nil { - return err - } - - nav.saves = make(map[string]bool) - nav.saves[curr.Path] = copy - } else { - var fs []string - for f := range nav.marks { - fs = append(fs, f) - } - - if err := saveFiles(fs, copy); err != nil { - return err - } - - nav.saves = make(map[string]bool) - for f := range nav.marks { - nav.saves[f] = copy - } - } - - return nil -} - -func (nav *nav) put() error { - list, copy, err := loadFiles() - if err != nil { - return err - } - - if len(list) == 0 { - return errors.New("no file in yank/delete buffer") - } - - dir := nav.currDir() - - cmd := putCommand(list, dir, copy) - - if err := cmd.Run(); err != nil { - // TODO: add name of external command to message - return fmt.Errorf("putting files: %s", err) - } - - // TODO: async? - - saveFiles(nil, false) - - return nil -} - -func (nav *nav) sync() error { - list, copy, err := loadFiles() - if err != nil { - return err - } - - nav.saves = make(map[string]bool) - for _, f := range list { - nav.saves[f] = copy - } - - return nil -} - func (nav *nav) currDir() *dir { return nav.dirs[len(nav.dirs)-1] } diff --git a/opts.go b/opts.go index 51dba7c6..c1e38511 100644 --- a/opts.go +++ b/opts.go @@ -61,18 +61,8 @@ func init() { gOpts.keys["l"] = &callExpr{"open", nil} gOpts.keys[""] = &callExpr{"open", nil} gOpts.keys["q"] = &callExpr{"quit", nil} - gOpts.keys["G"] = &callExpr{"bot", nil} gOpts.keys["gg"] = &callExpr{"top", nil} - gOpts.keys[":"] = &callExpr{"read", nil} - gOpts.keys["$"] = &callExpr{"read-shell", nil} - gOpts.keys["!"] = &callExpr{"read-shell-wait", nil} - gOpts.keys["&"] = &callExpr{"read-shell-async", nil} - gOpts.keys[""] = &callExpr{"cmd-hist-next", nil} - gOpts.keys[""] = &callExpr{"cmd-hist-prev", nil} - gOpts.keys["/"] = &callExpr{"search", nil} - gOpts.keys["?"] = &callExpr{"search-back", nil} - gOpts.keys["n"] = &callExpr{"search-next", nil} - gOpts.keys["N"] = &callExpr{"search-prev", nil} + gOpts.keys["G"] = &callExpr{"bot", nil} gOpts.keys[""] = &callExpr{"toggle", nil} gOpts.keys["v"] = &callExpr{"invert", nil} gOpts.keys["y"] = &callExpr{"yank", nil} @@ -80,21 +70,31 @@ func init() { gOpts.keys["c"] = &callExpr{"clear", nil} gOpts.keys["p"] = &callExpr{"put", nil} gOpts.keys[""] = &callExpr{"renew", nil} + gOpts.keys[":"] = &callExpr{"read", nil} + gOpts.keys["$"] = &callExpr{"read-shell", nil} + gOpts.keys["!"] = &callExpr{"read-shell-wait", nil} + gOpts.keys["&"] = &callExpr{"read-shell-async", nil} + gOpts.keys["/"] = &callExpr{"search", nil} + gOpts.keys["?"] = &callExpr{"search-back", nil} + gOpts.keys["n"] = &callExpr{"search-next", nil} + gOpts.keys["N"] = &callExpr{"search-prev", nil} + gOpts.keys[""] = &callExpr{"cmd-hist-next", nil} + gOpts.keys[""] = &callExpr{"cmd-hist-prev", nil} gOpts.cmdkeys = make(map[string]expr) // TODO: rest of the keys - gOpts.cmdkeys[""] = &callExpr{"cmd-escape", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-insert", []string{" "}} + gOpts.cmdkeys[""] = &callExpr{"cmd-escape", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-comp", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-enter", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-enter", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-hist-next", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-hist-prev", nil} - gOpts.cmdkeys[""] = &callExpr{"cmd-delete-back", nil} - gOpts.cmdkeys[""] = &callExpr{"cmd-delete-back", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-delete", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-delete", nil} + gOpts.cmdkeys[""] = &callExpr{"cmd-delete-back", nil} + gOpts.cmdkeys[""] = &callExpr{"cmd-delete-back", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-left", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-left", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-right", nil} @@ -103,8 +103,8 @@ func init() { gOpts.cmdkeys[""] = &callExpr{"cmd-beg", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-end", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-end", nil} - gOpts.cmdkeys[""] = &callExpr{"cmd-delete-end", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-beg", nil} + gOpts.cmdkeys[""] = &callExpr{"cmd-delete-end", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-delete-word", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-put", nil} gOpts.cmdkeys[""] = &callExpr{"cmd-transpose", nil} diff --git a/os.go b/os.go index 01b8a624..162349f7 100644 --- a/os.go +++ b/os.go @@ -23,12 +23,11 @@ var ( ) func init() { - var err error - - gUser, err = user.Current() + u, err := user.Current() if err != nil { log.Printf("user: %s", err) } + gUser = u config := os.Getenv("XDG_CONFIG_HOME") if config == "" { diff --git a/os_windows.go b/os_windows.go index 186158d4..b39d778d 100644 --- a/os_windows.go +++ b/os_windows.go @@ -21,12 +21,11 @@ var ( ) func init() { - var err error - - gUser, err = user.Current() + u, err := user.Current() if err != nil { log.Printf("user: %s", err) } + gUser = u // remove domain prefix gUser.Username = strings.Split(gUser.Username, `\`)[1] diff --git a/parse.go b/parse.go index 9e4c9ba2..e402c593 100644 --- a/parse.go +++ b/parse.go @@ -12,24 +12,24 @@ package main // // SetExpr = 'set' ';' // -// MapExpr = 'map' Expr ';' +// MapExpr = 'map' Expr // // CMapExpr = 'cmap' ';' // -// CmdExpr = 'cmd' Expr ';' +// CmdExpr = 'cmd' Expr // // CallExpr = ';' // -// ExecExpr = Prefix '\n' -// | Prefix '{{' '}}' ';' +// ExecExpr = Prefix '\n' +// | Prefix '{{' '}}' ';' // // Prefix = '$' | '!' | '&' | '/' | '?' // -// ListExpr = ':' ListRest '\n' -// | ':' '{{' ListRest '}}' ';' +// ListExpr = ':' Expr ListRest '\n' +// | ':' '{{' Expr ListRest '}}' ';' // // ListRest = Nil -// | Expr ListRest +// | Expr ListExpr import ( "bytes" @@ -40,9 +40,7 @@ import ( type expr interface { String() string - eval(app *app, args []string) - // TODO: add a bind method to avoid passing args in eval } type setExpr struct { @@ -81,17 +79,17 @@ type callExpr struct { func (e *callExpr) String() string { return fmt.Sprintf("%s -- %s", e.name, e.args) } type execExpr struct { - pref string - expr string + prefix string + value string } func (e *execExpr) String() string { var buf bytes.Buffer - buf.WriteString(e.pref) + buf.WriteString(e.prefix) buf.WriteString("{{ ") - lines := strings.Split(e.expr, "\n") + lines := strings.Split(e.value, "\n") for _, line := range lines { trimmed := strings.TrimSpace(line) @@ -270,7 +268,7 @@ func (p *parser) parseExpr() expr { case tokenPrefix: var expr string - pref := s.tok + prefix := s.tok s.scan() if s.typ == tokenLBraces { @@ -284,7 +282,7 @@ func (p *parser) parseExpr() expr { s.scan() s.scan() - result = &execExpr{pref, expr} + result = &execExpr{prefix, expr} default: p.err = fmt.Errorf("unexpected token: %s", s.tok) } diff --git a/scan.go b/scan.go index 6dbecedc..0d6a85c6 100644 --- a/scan.go +++ b/scan.go @@ -217,7 +217,6 @@ scan: for !s.eof && s.chr != '"' { if s.chr == '\\' { s.next() - // TODO: octal escape switch s.chr { case '"', '\\': buf = append(buf, s.chr) diff --git a/server.go b/server.go index c2765a6e..7c842bae 100644 --- a/server.go +++ b/server.go @@ -12,7 +12,7 @@ import ( var ( gCopyFile bool gFileList []string - gConnList map[int]net.Conn + gConnList map[int]net.Conn = make(map[int]net.Conn) ) func serve() { @@ -32,8 +32,6 @@ func serve() { } defer l.Close() - gConnList = make(map[int]net.Conn) - listen(l) } diff --git a/ui.go b/ui.go index 0b47fc73..9a8063e2 100644 --- a/ui.go +++ b/ui.go @@ -113,10 +113,7 @@ func init() { } type win struct { - w int - h int - x int - y int + w, h, x, y int } func newWin(w, h, x, y int) *win { @@ -124,10 +121,7 @@ func newWin(w, h, x, y int) *win { } func (win *win) renew(w, h, x, y int) { - win.w = w - win.h = h - win.x = x - win.y = y + win.w, win.h, win.x, win.y = w, h, x, y } func (win *win) print(x, y int, fg, bg termbox.Attribute, s string) { @@ -209,11 +203,25 @@ func (win *win) printl(x, y int, fg, bg termbox.Attribute, s string) { win.printf(x, y, fg, bg, "%s%*s", s, win.w-len(s), "") } -func (win *win) printd(dir *dir, marks map[string]int, saves map[string]bool) { +func (win *win) printReg(reg []string) { + fg, bg := termbox.ColorDefault, termbox.ColorDefault + + for i, l := range reg { + win.print(2, i, fg, bg, l) + } + + return +} + +func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool) { if win.w < 3 { return } + if dir == nil { + return + } + fg, bg := termbox.ColorDefault, termbox.ColorDefault if len(dir.fi) == 0 { @@ -229,12 +237,12 @@ func (win *win) printd(dir *dir, marks map[string]int, saves map[string]bool) { for i, f := range dir.fi[beg:end] { switch { - case f.LinkState == working: + case f.linkState == working: fg = termbox.ColorCyan if f.Mode().IsDir() { fg |= termbox.AttrBold } - case f.LinkState == broken: + case f.linkState == broken: fg = termbox.ColorMagenta case f.Mode().IsRegular(): if f.Mode()&0111 != 0 { @@ -295,7 +303,7 @@ func (win *win) printd(dir *dir, marks map[string]int, saves map[string]bool) { continue } - if f.Count == -1 { + if f.count == -1 { d, err := os.Open(path) if err != nil { log.Printf("opening dir to read count: %s", err) @@ -310,9 +318,9 @@ func (win *win) printd(dir *dir, marks map[string]int, saves map[string]bool) { continue } - f.Count = len(names) + f.count = len(names) } - info = fmt.Sprintf("%s %d", info, f.Count) + info = fmt.Sprintf("%s %d", info, f.count) case "time": info = fmt.Sprintf("%s %12s", info, f.ModTime().Format("Jan _2 15:04")) default: @@ -333,33 +341,23 @@ func (win *win) printd(dir *dir, marks map[string]int, saves map[string]bool) { } } -func (win *win) printr(reg []string) { - fg, bg := termbox.ColorDefault, termbox.ColorDefault - - for i, l := range reg { - win.print(2, i, fg, bg, l) - } - - return -} - type ui struct { - wins []*win - pwdwin *win - msgwin *win - menuwin *win - message string - regprev []string - dirprev *dir - keychan chan string - evschan chan termbox.Event - menubuf *bytes.Buffer - cmdpref string - cmdlacc []rune - cmdracc []rune - cmdbuf []rune - keyacc []rune - keycnt []rune + wins []*win + pwdWin *win + msgWin *win + menuWin *win + msg string + regPrev []string + dirPrev *dir + keyChan chan string + evChan chan termbox.Event + menuBuf *bytes.Buffer + cmdPrefix string + cmdAccLeft []rune + cmdAccRight []rune + cmdBuf []rune + keyAcc []rune + keyCount []rune } func getWidths(wtot int) []int { @@ -401,22 +399,21 @@ func getWins() []*win { func newUI() *ui { wtot, htot := termbox.Size() - key := make(chan string, 1000) - evs := make(chan termbox.Event) + evChan := make(chan termbox.Event) go func() { for { - evs <- termbox.PollEvent() + evChan <- termbox.PollEvent() } }() return &ui{ wins: getWins(), - pwdwin: newWin(wtot, 1, 0, 0), - msgwin: newWin(wtot, 1, 0, htot-1), - menuwin: newWin(wtot, 1, 0, htot-2), - keychan: key, - evschan: evs, + pwdWin: newWin(wtot, 1, 0, 0), + msgWin: newWin(wtot, 1, 0, htot-1), + menuWin: newWin(wtot, 1, 0, htot-2), + keyChan: make(chan string, 1000), + evChan: evChan, } } @@ -432,16 +429,16 @@ func (ui *ui) renew() { wacc += widths[i] } - ui.msgwin.renew(wtot, 1, 0, htot-1) + ui.msgWin.renew(wtot, 1, 0, htot-1) } -func (ui *ui) loadFileInfo(nav *nav) { - curr, err := nav.currFile() - if err != nil { - return - } +func (ui *ui) print(msg string) { + ui.msg = msg + log.Print(msg) +} - ui.message = fmt.Sprintf("%v %4s %v", curr.Mode(), humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt)) +func (ui *ui) printf(format string, a ...interface{}) { + ui.print(fmt.Sprintf(format, a...)) } func (ui *ui) loadFile(nav *nav) { @@ -455,64 +452,65 @@ func (ui *ui) loadFile(nav *nav) { } if curr.IsDir() { - dir := nav.load(curr.Path) - ui.dirprev = dir + dir := nav.load(curr.path) + ui.dirPrev = dir } else if curr.Mode().IsRegular() { var reader io.Reader if len(gOpts.previewer) != 0 { - cmd := exec.Command(gOpts.previewer, curr.Path, strconv.Itoa(nav.height)) + cmd := exec.Command(gOpts.previewer, curr.path, strconv.Itoa(nav.height)) out, err := cmd.StdoutPipe() if err != nil { - msg := fmt.Sprintf("previewing file: %s", err) - ui.message = msg - log.Print(msg) + ui.printf("previewing file: %s", err) } if err := cmd.Start(); err != nil { - msg := fmt.Sprintf("previewing file: %s", err) - ui.message = msg - log.Print(msg) + ui.printf("previewing file: %s", err) } defer cmd.Wait() defer out.Close() reader = out } else { - f, err := os.Open(curr.Path) + f, err := os.Open(curr.path) if err != nil { - msg := fmt.Sprintf("opening file: %s", err) - ui.message = msg - log.Print(msg) + ui.printf("opening file: %s", err) } defer f.Close() reader = f } - ui.regprev = nil + ui.regPrev = nil buf := bufio.NewScanner(reader) for i := 0; i < nav.height && buf.Scan(); i++ { for _, r := range buf.Text() { if r == 0 { - ui.regprev = []string{"\033[1mbinary\033[0m"} + ui.regPrev = []string{"\033[1mbinary\033[0m"} return } } - ui.regprev = append(ui.regprev, buf.Text()) + ui.regPrev = append(ui.regPrev, buf.Text()) } if buf.Err() != nil { - msg := fmt.Sprintf("loading file: %s", buf.Err()) - ui.message = msg - log.Print(msg) + ui.printf("loading file: %s", buf.Err()) } } } +func (ui *ui) loadFileInfo(nav *nav) { + curr, err := nav.currFile() + if err != nil { + return + } + + ui.msg = fmt.Sprintf("%v %4s %v", curr.Mode(), humanize(curr.Size()), curr.ModTime().Format(gOpts.timefmt)) +} + func (ui *ui) draw(nav *nav) { fg, bg := termbox.ColorDefault, termbox.ColorDefault @@ -523,9 +521,9 @@ func (ui *ui) draw(nav *nav) { path := strings.Replace(dir.path, gUser.HomeDir, "~", -1) path = filepath.Clean(path) - ui.pwdwin.printf(0, 0, termbox.AttrBold|termbox.ColorGreen, bg, "%s@%s", gUser.Username, gHostname) - ui.pwdwin.printf(len(gUser.Username)+len(gHostname)+1, 0, fg, bg, ":") - ui.pwdwin.printf(len(gUser.Username)+len(gHostname)+2, 0, termbox.AttrBold|termbox.ColorBlue, bg, "%s", path) + ui.pwdWin.printf(0, 0, termbox.AttrBold|termbox.ColorGreen, bg, "%s@%s", gUser.Username, gHostname) + ui.pwdWin.printf(len(gUser.Username)+len(gHostname)+1, 0, fg, bg, ":") + ui.pwdWin.printf(len(gUser.Username)+len(gHostname)+2, 0, termbox.AttrBold|termbox.ColorBlue, bg, "%s", path) length := min(len(ui.wins), len(nav.dirs)) woff := len(ui.wins) - length @@ -537,16 +535,16 @@ func (ui *ui) draw(nav *nav) { doff := len(nav.dirs) - length for i := 0; i < length; i++ { - ui.wins[woff+i].printd(nav.dirs[doff+i], nav.marks, nav.saves) + ui.wins[woff+i].printDir(nav.dirs[doff+i], nav.marks, nav.saves) } - if ui.cmdpref != "" { - ui.msgwin.printl(0, 0, fg, bg, ui.cmdpref) - ui.msgwin.print(len(ui.cmdpref), 0, fg, bg, string(ui.cmdlacc)) - ui.msgwin.print(len(ui.cmdpref)+runeSliceWidth(ui.cmdlacc), 0, fg, bg, string(ui.cmdracc)) - termbox.SetCursor(ui.msgwin.x+len(ui.cmdpref)+runeSliceWidth(ui.cmdlacc), ui.msgwin.y) + if ui.cmdPrefix != "" { + ui.msgWin.printl(0, 0, fg, bg, ui.cmdPrefix) + ui.msgWin.print(len(ui.cmdPrefix), 0, fg, bg, string(ui.cmdAccLeft)) + ui.msgWin.print(len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), 0, fg, bg, string(ui.cmdAccRight)) + termbox.SetCursor(ui.msgWin.x+len(ui.cmdPrefix)+runeSliceWidth(ui.cmdAccLeft), ui.msgWin.y) } else { - ui.msgwin.print(0, 0, fg, bg, ui.message) + ui.msgWin.print(0, 0, fg, bg, ui.msg) termbox.HideCursor() } @@ -556,31 +554,31 @@ func (ui *ui) draw(nav *nav) { preview := ui.wins[len(ui.wins)-1] if f.IsDir() { - preview.printd(ui.dirprev, nav.marks, nav.saves) + preview.printDir(ui.dirPrev, nav.marks, nav.saves) } else if f.Mode().IsRegular() { - preview.printr(ui.regprev) + preview.printReg(ui.regPrev) } } } - if ui.menubuf != nil { - lines := strings.Split(ui.menubuf.String(), "\n") + 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 + ui.menuWin.h = len(lines) - 1 + ui.menuWin.y = ui.wins[0].h - ui.menuWin.h - ui.menuwin.printl(0, 0, termbox.AttrBold, termbox.AttrBold, lines[0]) + ui.menuWin.printl(0, 0, termbox.AttrBold, termbox.AttrBold, lines[0]) for i, line := range lines[1:] { - ui.menuwin.printl(0, i+1, fg, bg, "") - ui.menuwin.print(0, i+1, fg, bg, line) + ui.menuWin.printl(0, i+1, fg, bg, "") + ui.menuWin.print(0, i+1, fg, bg, line) } } termbox.Flush() - if ui.cmdpref == "" { + if ui.cmdPrefix == "" { // leave the cursor at the beginning of the current file for screen readers moveCursor(ui.wins[woff+length-1].y+nav.dirs[doff+length-1].pos+1, ui.wins[woff+length-1].x+1) } @@ -621,7 +619,7 @@ func listBinds(binds map[string]expr) *bytes.Buffer { func (ui *ui) pollEvent() termbox.Event { select { - case key := <-ui.keychan: + case key := <-ui.keyChan: ev := termbox.Event{Type: termbox.EventKey} if len(key) == 1 { @@ -637,15 +635,13 @@ func (ui *ui) pollEvent() termbox.Event { ev.Key = val } else { ev.Key = termbox.KeyEsc - msg := fmt.Sprintf("unknown key: %s", key) - ui.message = msg - log.Print(msg) + ui.printf("unknown key: %s", key) } } } return ev - case ev := <-ui.evschan: + case ev := <-ui.evChan: return ev } } @@ -675,36 +671,36 @@ func (ui *ui) readEvent(ch chan<- multiExpr, ev termbox.Event) { if ev.Ch != 0 { switch { case ev.Ch == '<': - ui.keyacc = append(ui.keyacc, '<', 'l', 't', '>') + ui.keyAcc = append(ui.keyAcc, '<', 'l', 't', '>') case ev.Ch == '>': - ui.keyacc = append(ui.keyacc, '<', 'g', 't', '>') - case unicode.IsDigit(ev.Ch) && len(ui.keyacc) == 0: - ui.keycnt = append(ui.keycnt, ev.Ch) + ui.keyAcc = append(ui.keyAcc, '<', 'g', 't', '>') + case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0: + ui.keyCount = append(ui.keyCount, ev.Ch) default: - ui.keyacc = append(ui.keyacc, ev.Ch) + ui.keyAcc = append(ui.keyAcc, ev.Ch) } } else { val := gKeyVal[ev.Key] if string(val) == "" { ch <- multiExpr{redraw, 1} - ui.keyacc = nil - ui.keycnt = nil + ui.keyAcc = nil + ui.keyCount = nil } - ui.keyacc = append(ui.keyacc, val...) + ui.keyAcc = append(ui.keyAcc, val...) } - binds, ok := findBinds(gOpts.keys, string(ui.keyacc)) + binds, ok := findBinds(gOpts.keys, string(ui.keyAcc)) switch len(binds) { case 0: - ui.message = fmt.Sprintf("unknown mapping: %s", string(ui.keyacc)) + ui.printf("unknown mapping: %s", string(ui.keyAcc)) ch <- multiExpr{redraw, 1} - ui.keyacc = nil - ui.keycnt = nil + ui.keyAcc = nil + ui.keyCount = nil case 1: if ok { - if len(ui.keycnt) > 0 { - c, err := strconv.Atoi(string(ui.keycnt)) + if len(ui.keyCount) > 0 { + c, err := strconv.Atoi(string(ui.keyCount)) if err != nil { log.Printf("converting command count: %s", err) } @@ -712,22 +708,22 @@ func (ui *ui) readEvent(ch chan<- multiExpr, ev termbox.Event) { } else { count = 1 } - expr := gOpts.keys[string(ui.keyacc)] + expr := gOpts.keys[string(ui.keyAcc)] ch <- multiExpr{expr, count} - ui.keyacc = nil - ui.keycnt = nil + ui.keyAcc = nil + ui.keyCount = nil } - if len(ui.keyacc) > 0 { - ui.menubuf = listBinds(binds) + if len(ui.keyAcc) > 0 { + ui.menuBuf = listBinds(binds) ch <- multiExpr{redraw, 1} - } else if ui.menubuf != nil { - ui.menubuf = nil + } else if ui.menuBuf != nil { + ui.menuBuf = nil } default: if ok { // TODO: use a delay - if len(ui.keycnt) > 0 { - c, err := strconv.Atoi(string(ui.keycnt)) + if len(ui.keyCount) > 0 { + c, err := strconv.Atoi(string(ui.keyCount)) if err != nil { log.Printf("converting command count: %s", err) } @@ -735,16 +731,16 @@ func (ui *ui) readEvent(ch chan<- multiExpr, ev termbox.Event) { } else { count = 1 } - expr := gOpts.keys[string(ui.keyacc)] + expr := gOpts.keys[string(ui.keyAcc)] ch <- multiExpr{expr, count} - ui.keyacc = nil - ui.keycnt = nil + ui.keyAcc = nil + ui.keyCount = nil } - if len(ui.keyacc) > 0 { - ui.menubuf = listBinds(binds) + if len(ui.keyAcc) > 0 { + ui.menuBuf = listBinds(binds) ch <- multiExpr{redraw, 1} } else { - ui.menubuf = nil + ui.menuBuf = nil } } case termbox.EventResize: @@ -761,10 +757,12 @@ func (ui *ui) readExpr() <-chan multiExpr { ch := make(chan multiExpr) go func() { + ch <- multiExpr{&callExpr{"redraw", nil}, 1} + for { ev := ui.pollEvent() - if ui.cmdpref != "" && ev.Type == termbox.EventKey { + if ui.cmdPrefix != "" && ev.Type == termbox.EventKey { readCmdEvent(ch, ev) continue }