This commit is contained in:
Gokcehan committed 2018-05-20 20:30:41 +03:00
1 parent 03b9fe0c5e
commit a85e0da9b0
12 files changed
+435 -428

No files matched your search

+11 -9
View File
@@ -49,6 +49,7 @@ func (app *app) readFile(path string) {
defer f.Close() defer f.Close()
p := newParser(f) p := newParser(f)
for p.parse() { for p.parse() {
p.expr.eval(app, nil) p.expr.eval(app, nil)
} }
@@ -58,9 +59,10 @@ func (app *app) readFile(path string) {
} }
} }
// This is the main event loop of the application. There are two channels to // This is the main event loop of the application. Expressions are read from
// read expressions from client and server. Reading and evaluation are done on // the client and the server on separate goroutines and sent here over channels
// separate goroutines. // for evaluation. Similarly directories and regular files are also read in
// separate goroutines and sent here for update.
func (app *app) loop() { func (app *app) loop() {
clientChan := app.ui.readExpr() clientChan := app.ui.readExpr()
serverChan := readExpr() serverChan := readExpr()
@@ -170,13 +172,13 @@ func waitKey() error {
return nil return nil
} }
// This function is used to run a command in shell. Following modes are used: // This function is used to run a shell command. Modes are as follows:
// //
// Prefix Wait Async Stdin Stdout Stderr UI action // Prefix Wait Async Stdin Stdout Stderr UI action
// $ No No Yes Yes Yes Pause and then resume // $ No No Yes Yes Yes Pause and then resume
// % No No Yes Yes Yes Use statline for input/output // % No No Yes Yes Yes Statline for input/output
// ! Yes No Yes Yes Yes Pause and then resume // ! Yes No Yes Yes Yes Pause and then resume
// & No Yes No No No Do nothing // & No Yes No No No Do nothing
func (app *app) runShell(s string, args []string, prefix string) { func (app *app) runShell(s string, args []string, prefix string) {
app.exportVars() app.exportVars()
+3 -3
View File
@@ -13,13 +13,13 @@ import (
) )
func run() { func run() {
logFile, err := os.Create(gLogPath) f, err := os.Create(gLogPath)
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer os.Remove(gLogPath) defer os.Remove(gLogPath)
defer logFile.Close() defer f.Close()
log.SetOutput(logFile) log.SetOutput(f)
log.Print("hi!") log.Print("hi!")
+50 -42
View File
@@ -108,13 +108,15 @@ func matchLongest(s1, s2 string) string {
func matchWord(s string, words []string) (matches []string, longest string) { func matchWord(s string, words []string) (matches []string, longest string) {
for _, w := range words { for _, w := range words {
if strings.HasPrefix(w, s) { if !strings.HasPrefix(w, s) {
matches = append(matches, w) continue
if longest != "" { }
longest = matchLongest(longest, w)
} else if s != "" { matches = append(matches, w)
longest = w + " " if longest != "" {
} longest = matchLongest(longest, w)
} else if s != "" {
longest = w + " "
} }
} }
@@ -135,25 +137,27 @@ func matchExec(s string) (matches []string, longest string) {
continue continue
} }
fi, err := ioutil.ReadDir(p) files, err := ioutil.ReadDir(p)
if err != nil { if err != nil {
log.Printf("reading path: %s", err) log.Printf("reading path: %s", err)
} }
for _, f := range fi { for _, f := range files {
if strings.HasPrefix(f.Name(), s) { if !strings.HasPrefix(f.Name(), s) {
f, err = os.Stat(filepath.Join(p, f.Name())) continue
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
if !f.Mode().IsRegular() || f.Mode()&0111 == 0 {
continue
}
words = append(words, f.Name())
} }
f, err = os.Stat(filepath.Join(p, f.Name()))
if err != nil {
log.Printf("getting file information: %s", err)
continue
}
if !f.Mode().IsRegular() || f.Mode()&0111 == 0 {
continue
}
words = append(words, f.Name())
} }
} }
@@ -185,12 +189,12 @@ func matchFile(s string) (matches []string, longest string) {
dir = unescape(filepath.Dir(dir)) dir = unescape(filepath.Dir(dir))
fi, err := ioutil.ReadDir(dir) files, err := ioutil.ReadDir(dir)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} }
for _, f := range fi { for _, f := range files {
f, err := os.Stat(filepath.Join(dir, f.Name())) f, err := os.Stat(filepath.Join(dir, f.Name()))
if err != nil { if err != nil {
log.Printf("getting file information: %s", err) log.Printf("getting file information: %s", err)
@@ -198,25 +202,29 @@ func matchFile(s string) (matches []string, longest string) {
} }
_, last := filepath.Split(s) _, last := filepath.Split(s)
if strings.HasPrefix(escape(f.Name()), last) { if !strings.HasPrefix(escape(f.Name()), last) {
name := f.Name() continue
if isRoot(s) || filepath.Base(s) != s { }
name = filepath.Join(filepath.Dir(s), f.Name())
} name := f.Name()
name = escape(name) if isRoot(s) || filepath.Base(s) != s {
item := f.Name() name = filepath.Join(filepath.Dir(s), f.Name())
if f.Mode().IsDir() { }
item += string(filepath.Separator) name = escape(name)
}
matches = append(matches, item) item := f.Name()
if longest != "" { if f.Mode().IsDir() {
longest = matchLongest(longest, name) item += string(filepath.Separator)
} else if s != "" { }
if f.Mode().IsRegular() { matches = append(matches, item)
longest = name + " "
} else { if longest != "" {
longest = name + string(filepath.Separator) longest = matchLongest(longest, name)
} } else if s != "" {
if f.Mode().IsRegular() {
longest = name + " "
} else {
longest = name + string(filepath.Separator)
} }
} }
} }
+5 -4
View File
@@ -161,10 +161,11 @@ The following command prefixes are used by lf:
/ search search file in current directory / search search file in current directory
? search-back search file in the reverse order ? search-back search file in the reverse order
The same evaluator is used for the command line and the configuration file. The The same evaluator is used for the command line and the configuration file for
difference is that prefixes are not necessary in the command line. Instead read and shell commands. The difference is that prefixes are not necessary in
different modes are provided to read corresponding commands. Note that by the command line. Instead, different modes are provided to read corresponding
default these modes are mapped to the prefix keys above. commands. These modes are mapped to the prefix keys above by default. Searching
commands are only used from the command line.
Syntax Syntax
+5 -4
View File
@@ -168,10 +168,11 @@ The following command prefixes are used by lf:
/ search search file in current directory / search search file in current directory
? search-back search file in the reverse order ? search-back search file in the reverse order
The same evaluator is used for the command line and the configuration file. The same evaluator is used for the command line and the configuration file
The difference is that prefixes are not necessary in the command line. for read and shell commands. The difference is that prefixes are not
Instead different modes are provided to read corresponding commands. Note necessary in the command line. Instead, different modes are provided to read
that by default these modes are mapped to the prefix keys above. corresponding commands. These modes are mapped to the prefix keys above by
default. Searching commands are only used from the command line.
Syntax Syntax
+128 -108
View File
@@ -209,14 +209,14 @@ func (e *cmdExpr) eval(app *app, args []string) {
func splitKeys(s string) (keys []string) { func splitKeys(s string) (keys []string) {
for i := 0; i < len(s); { for i := 0; i < len(s); {
c, w := utf8.DecodeRuneInString(s[i:]) r, w := utf8.DecodeRuneInString(s[i:])
if c != '<' { if r != '<' {
keys = append(keys, s[i:i+w]) keys = append(keys, s[i:i+w])
i += w i += w
} else { } else {
j := i + w j := i + w
for c != '>' && j < len(s) { for r != '>' && j < len(s) {
c, w = utf8.DecodeRuneInString(s[j:]) r, w = utf8.DecodeRuneInString(s[j:])
j += w j += w
} }
keys = append(keys, s[i:j]) keys = append(keys, s[i:j])
@@ -437,16 +437,19 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.loadFile(app.nav) app.ui.loadFile(app.nav)
app.ui.loadFileInfo(app.nav) app.ui.loadFileInfo(app.nav)
case "push": case "push":
if len(e.args) > 0 { if len(e.args) != 1 {
log.Println("pushing keys", e.args[0]) app.ui.print("push: requires an argument")
for _, key := range splitKeys(e.args[0]) { return
app.ui.keyChan <- key }
} log.Println("pushing keys", e.args[0])
for _, key := range splitKeys(e.args[0]) {
app.ui.keyChan <- key
} }
case "cmd-insert": case "cmd-insert":
if len(e.args) > 0 { if len(e.args) == 0 {
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(e.args[0])...) return
} }
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(e.args[0])...)
case "cmd-escape": case "cmd-escape":
if app.ui.cmdPrefix == ">" { if app.ui.cmdPrefix == ">" {
return return
@@ -560,23 +563,27 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
app.ui.menuBuf = nil app.ui.menuBuf = nil
case "cmd-delete": case "cmd-delete":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
app.ui.cmdAccRight = app.ui.cmdAccRight[1:] return
} }
app.ui.cmdAccRight = app.ui.cmdAccRight[1:]
case "cmd-delete-back": case "cmd-delete-back":
if len(app.ui.cmdAccLeft) > 0 { if len(app.ui.cmdAccLeft) == 0 {
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1] return
} }
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1]
case "cmd-left": case "cmd-left":
if len(app.ui.cmdAccLeft) > 0 { if len(app.ui.cmdAccLeft) == 0 {
app.ui.cmdAccRight = append([]rune{app.ui.cmdAccLeft[len(app.ui.cmdAccLeft)-1]}, app.ui.cmdAccRight...) return
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:len(app.ui.cmdAccLeft)-1]
} }
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": case "cmd-right":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[0]) return
app.ui.cmdAccRight = app.ui.cmdAccRight[1:]
} }
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[0])
app.ui.cmdAccRight = app.ui.cmdAccRight[1:]
case "cmd-home": case "cmd-home":
app.ui.cmdAccRight = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) app.ui.cmdAccRight = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...)
app.ui.cmdAccLeft = nil app.ui.cmdAccLeft = nil
@@ -584,25 +591,28 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight...)
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
case "cmd-delete-home": case "cmd-delete-home":
if len(app.ui.cmdAccLeft) > 0 { if len(app.ui.cmdAccLeft) == 0 {
app.ui.cmdBuf = app.ui.cmdAccLeft return
app.ui.cmdAccLeft = nil
} }
app.ui.cmdYankBuf = app.ui.cmdAccLeft
app.ui.cmdAccLeft = nil
case "cmd-delete-end": case "cmd-delete-end":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
app.ui.cmdBuf = app.ui.cmdAccRight return
app.ui.cmdAccRight = nil
} }
app.ui.cmdYankBuf = app.ui.cmdAccRight
app.ui.cmdAccRight = nil
case "cmd-delete-unix-word": case "cmd-delete-unix-word":
ind := strings.LastIndex(strings.TrimRight(string(app.ui.cmdAccLeft), " "), " ") + 1 ind := strings.LastIndex(strings.TrimRight(string(app.ui.cmdAccLeft), " "), " ") + 1
app.ui.cmdBuf = app.ui.cmdAccLeft[ind:] app.ui.cmdYankBuf = app.ui.cmdAccLeft[ind:]
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind] app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind]
case "cmd-yank": case "cmd-yank":
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdBuf...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdYankBuf...)
case "cmd-transpose": case "cmd-transpose":
if len(app.ui.cmdAccLeft) > 1 { if len(app.ui.cmdAccLeft) < 2 {
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] 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]
case "cmd-interrupt": case "cmd-interrupt":
if app.cmd != nil { if app.cmd != nil {
app.cmd.Process.Kill() app.cmd.Process.Kill()
@@ -612,100 +622,110 @@ func (e *callExpr) eval(app *app, args []string) {
app.ui.cmdAccRight = nil app.ui.cmdAccRight = nil
app.ui.cmdPrefix = "" app.ui.cmdPrefix = ""
case "cmd-word": case "cmd-word":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight)) return
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
} }
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
case "cmd-word-back": case "cmd-word-back":
if len(app.ui.cmdAccLeft) > 0 { if len(app.ui.cmdAccLeft) == 0 {
locs := reWordBeg.FindAllStringIndex(string(app.ui.cmdAccLeft), -1) return
if locs == nil {
return
}
ind := locs[len(locs)-1][1] - 1
app.ui.cmdAccRight = append(app.ui.cmdAccLeft[ind:], app.ui.cmdAccRight...)
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind]
} }
locs := reWordBeg.FindAllStringIndex(string(app.ui.cmdAccLeft), -1)
if locs == nil {
return
}
ind := locs[len(locs)-1][1] - 1
app.ui.cmdAccRight = append(app.ui.cmdAccLeft[ind:], app.ui.cmdAccRight...)
app.ui.cmdAccLeft = app.ui.cmdAccLeft[:ind]
case "cmd-capitalize-word": case "cmd-capitalize-word":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
ind := 0 return
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.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind = loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
} }
ind := 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.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind = loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
case "cmd-delete-word": case "cmd-delete-word":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight)) return
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
} }
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
case "cmd-uppercase-word": case "cmd-uppercase-word":
if len(app.ui.cmdAccRight) > 0 { if len(app.ui.cmdAccRight) == 0 {
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight)) return
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToUpper(string(app.ui.cmdAccRight[:ind])))...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
} }
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToUpper(string(app.ui.cmdAccRight[:ind])))...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
case "cmd-lowercase-word": case "cmd-lowercase-word":
if len(app.ui.cmdAccRight) == 0 {
return
}
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToLower(string(app.ui.cmdAccRight[:ind])))...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
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 { if len(app.ui.cmdAccRight) > 0 {
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight)) loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
if loc == nil { if loc != nil {
return
}
ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, []rune(strings.ToLower(string(app.ui.cmdAccRight[:ind])))...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:]
}
case "cmd-transpose-word":
if len(app.ui.cmdAccLeft) > 0 {
locs := reWord.FindAllStringIndex(string(app.ui.cmdAccLeft), -1)
if len(locs) < 2 {
return
}
if len(app.ui.cmdAccRight) > 0 {
loc := reWordEnd.FindStringIndex(string(app.ui.cmdAccRight))
ind := loc[0] + 1 ind := loc[0] + 1
app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...) app.ui.cmdAccLeft = append(app.ui.cmdAccLeft, app.ui.cmdAccRight[:ind]...)
app.ui.cmdAccRight = app.ui.cmdAccRight[ind:] app.ui.cmdAccRight = 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, app.ui.cmdAccLeft[:beg1]...)
acc = append(acc, app.ui.cmdAccLeft[beg2:end2]...)
acc = append(acc, app.ui.cmdAccLeft[end1:beg2]...)
acc = append(acc, app.ui.cmdAccLeft[beg1:end1]...)
acc = append(acc, app.ui.cmdAccLeft[end2:]...)
app.ui.cmdAccLeft = acc
} }
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, app.ui.cmdAccLeft[:beg1]...)
acc = append(acc, app.ui.cmdAccLeft[beg2:end2]...)
acc = append(acc, app.ui.cmdAccLeft[end1:beg2]...)
acc = append(acc, app.ui.cmdAccLeft[beg1:end1]...)
acc = append(acc, app.ui.cmdAccLeft[end2:]...)
app.ui.cmdAccLeft = acc
default: default:
cmd, ok := gOpts.cmds[e.name] cmd, ok := gOpts.cmds[e.name]
if !ok { if !ok {
+3 -1
View File
@@ -195,6 +195,8 @@ func naturalLess(s1, s2 string) bool {
return len(parts1) < len(parts2) return len(parts1) < len(parts2)
} }
var reAltKey = regexp.MustCompile(`<a-(.)>`)
var reWord = regexp.MustCompile(`(\pL|\pN)+`) var reWord = regexp.MustCompile(`(\pL|\pN)+`)
var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`) var reWordBeg = regexp.MustCompile(`([^\pL\pN]|^)(\pL|\pN)`)
var reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`) var reWordEnd = regexp.MustCompile(`(\pL|\pN)([^\pL\pN]|$)`)
@@ -214,7 +216,7 @@ func max(a, b int) int {
} }
// We don't need no generic code // We don't need no generic code
// We don't need no thought control // We don't need no type control
// No dark templates in compiler // No dark templates in compiler
// Haskell leave them kids alone // Haskell leave them kids alone
// Hey Bjarne leave them kids alone // Hey Bjarne leave them kids alone
+108 -134
View File
@@ -27,21 +27,7 @@ type file struct {
os.FileInfo os.FileInfo
linkState linkState linkState linkState
path string path string
count int dirCount int
}
type filesSortable struct {
files []*file
less func(i, j int) bool
}
func (f filesSortable) Len() int { return len(f.files) }
func (f filesSortable) Swap(i, j int) { f.files[i], f.files[j] = f.files[j], f.files[i] }
func (f filesSortable) Less(i, j int) bool { return f.less(i, j) }
// TODO: Replace with `sort.SliceStable` once available
func sortFilesStable(files []*file, less func(i, j int) bool) {
sort.Stable(filesSortable{files: files, less: less})
} }
func readdir(path string) ([]*file, error) { func readdir(path string) ([]*file, error) {
@@ -49,61 +35,59 @@ func readdir(path string) ([]*file, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
names, err := f.Readdirnames(-1) names, err := f.Readdirnames(-1)
f.Close() f.Close()
fi := make([]*file, 0, len(names)) files := make([]*file, 0, len(names))
for _, filename := range names { for _, fname := range names {
fpath := filepath.Join(path, filename) fpath := filepath.Join(path, fname)
lstat, lerr := os.Lstat(fpath) lstat, err := os.Lstat(fpath)
if os.IsNotExist(lerr) { if os.IsNotExist(err) {
continue continue
} }
if lerr != nil { if err != nil {
return fi, lerr return files, err
} }
var linkState linkState var linkState linkState
if lstat.Mode()&os.ModeSymlink != 0 { if lstat.Mode()&os.ModeSymlink != 0 {
stat, serr := os.Stat(fpath) stat, err := os.Stat(fpath)
if serr == nil { if err == nil {
linkState = working linkState = working
lstat = stat lstat = stat
} else { } else {
linkState = broken linkState = broken
log.Printf("getting link destination info: %s", serr)
} }
} }
fi = append(fi, &file{ files = append(files, &file{
FileInfo: lstat, FileInfo: lstat,
linkState: linkState, linkState: linkState,
path: fpath, path: fpath,
count: -1, dirCount: -1,
}) })
} }
return fi, err return files, err
} }
type dir struct { type dir struct {
loading bool // directory is loading from disk loading bool // directory is loading from disk
loadTime time.Time // current loading or last load time loadTime time.Time // current loading or last load time
ind int // index of current entry in fi ind int // index of current entry in files
pos int // position of current entry in ui pos int // position of current entry in ui
path string // full path of directory path string // full path of directory
fi []*file // displayed files in directory including or excluding hidden ones files []*file // displayed files in directory including or excluding hidden ones
all []*file // all files in directory including hidden ones (same array as fi) allFiles []*file // all files in directory including hidden ones (same array as files)
sortType sortType // sort method and options from last sort sortType sortType // sort method and options from last sort
} }
func newDir(path string) *dir { func newDir(path string) *dir {
time := time.Now() time := time.Now()
fi, err := readdir(path) files, err := readdir(path)
if err != nil { if err != nil {
log.Printf("reading directory: %s", err) log.Printf("reading directory: %s", err)
} }
@@ -111,57 +95,47 @@ func newDir(path string) *dir {
return &dir{ return &dir{
loadTime: time, loadTime: time,
path: path, path: path,
fi: fi, files: files,
all: fi, allFiles: files,
} }
} }
func (dir *dir) renew() {
fi, err := readdir(dir.path)
if err != nil {
log.Printf("reading directory: %s", err)
}
dir.fi = fi
dir.all = fi
}
func (dir *dir) sort() { func (dir *dir) sort() {
dir.sortType = gOpts.sortType dir.sortType = gOpts.sortType
dir.fi = dir.all dir.files = dir.allFiles
switch gOpts.sortType.method { switch gOpts.sortType.method {
case naturalSort: case naturalSort:
sortFilesStable(dir.fi, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
return naturalLess(strings.ToLower(dir.fi[i].Name()), strings.ToLower(dir.fi[j].Name())) return naturalLess(strings.ToLower(dir.files[i].Name()), strings.ToLower(dir.files[j].Name()))
}) })
case nameSort: case nameSort:
sortFilesStable(dir.fi, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
return strings.ToLower(dir.fi[i].Name()) < strings.ToLower(dir.fi[j].Name()) return strings.ToLower(dir.files[i].Name()) < strings.ToLower(dir.files[j].Name())
}) })
case sizeSort: case sizeSort:
sortFilesStable(dir.fi, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
return dir.fi[i].Size() < dir.fi[j].Size() return dir.files[i].Size() < dir.files[j].Size()
}) })
case timeSort: case timeSort:
sortFilesStable(dir.fi, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
return dir.fi[i].ModTime().Before(dir.fi[j].ModTime()) return dir.files[i].ModTime().Before(dir.files[j].ModTime())
}) })
} }
if gOpts.sortType.option&reverseSort != 0 { if gOpts.sortType.option&reverseSort != 0 {
for i, j := 0, len(dir.fi)-1; i < j; i, j = i+1, j-1 { for i, j := 0, len(dir.files)-1; i < j; i, j = i+1, j-1 {
dir.fi[i], dir.fi[j] = dir.fi[j], dir.fi[i] dir.files[i], dir.files[j] = dir.files[j], dir.files[i]
} }
} }
if gOpts.sortType.option&dirfirstSort != 0 { if gOpts.sortType.option&dirfirstSort != 0 {
sortFilesStable(dir.fi, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if dir.fi[i].IsDir() == dir.fi[j].IsDir() { if dir.files[i].IsDir() == dir.files[j].IsDir() {
return i < j return i < j
} }
return dir.fi[i].IsDir() return dir.files[i].IsDir()
}) })
} }
@@ -169,39 +143,39 @@ func (dir *dir) sort() {
// beginning of our file list and then set the beginning of displayed // beginning of our file list and then set the beginning of displayed
// files to the first non-hidden file in the list // files to the first non-hidden file in the list
if gOpts.sortType.option&hiddenSort == 0 { if gOpts.sortType.option&hiddenSort == 0 {
sortFilesStable(dir.fi, func(i, j int) bool { sort.SliceStable(dir.files, func(i, j int) bool {
if dir.fi[i].Name()[0] == '.' && dir.fi[j].Name()[0] == '.' { if dir.files[i].Name()[0] == '.' && dir.files[j].Name()[0] == '.' {
return i < j return i < j
} }
return dir.fi[i].Name()[0] == '.' return dir.files[i].Name()[0] == '.'
}) })
for i, f := range dir.fi { for i, f := range dir.files {
if f.Name()[0] != '.' { if f.Name()[0] != '.' {
dir.fi = dir.fi[i:] dir.files = dir.files[i:]
return return
} }
} }
dir.fi = dir.fi[len(dir.fi):] dir.files = dir.files[len(dir.files):]
} }
} }
func (dir *dir) name() string { func (dir *dir) name() string {
if len(dir.fi) == 0 { if len(dir.files) == 0 {
return "" return ""
} }
return dir.fi[dir.ind].Name() return dir.files[dir.ind].Name()
} }
func (dir *dir) find(name string, height int) { func (dir *dir) find(name string, height int) {
if len(dir.fi) == 0 { if len(dir.files) == 0 {
dir.ind, dir.pos = 0, 0 dir.ind, dir.pos = 0, 0
return return
} }
dir.ind = min(dir.ind, len(dir.fi)-1) dir.ind = min(dir.ind, len(dir.files)-1)
if dir.fi[dir.ind].Name() != name { if dir.files[dir.ind].Name() != name {
for i, f := range dir.fi { for i, f := range dir.files {
if f.Name() == name { if f.Name() == name {
dir.ind = i dir.ind = i
break break
@@ -209,7 +183,7 @@ func (dir *dir) find(name string, height int) {
} }
} }
edge := min(min(height/2, gOpts.scrolloff), len(dir.fi)-dir.ind-1) edge := min(min(height/2, gOpts.scrolloff), len(dir.files)-dir.ind-1)
dir.pos = min(dir.ind, height-edge-1) dir.pos = min(dir.ind, height-edge-1)
} }
@@ -226,34 +200,32 @@ type nav struct {
search string search string
} }
func newNav(height int) *nav { func (nav *nav) loadDir(path string) *dir {
wd, err := os.Getwd() d, ok := nav.dirCache[path]
if err != nil { if !ok {
log.Printf("getting current directory: %s", err) go func() {
d := newDir(path)
d.sort()
d.ind, d.pos = 0, 0
nav.dirChan <- d
}()
d := &dir{loading: true, path: path, sortType: gOpts.sortType}
nav.dirCache[path] = d
return d
} }
nav := &nav{ if d.sortType != gOpts.sortType {
dirChan: make(chan *dir), go func() {
regChan: make(chan *reg), d.loading = true
dirCache: make(map[string]*dir), name := d.name()
regCache: make(map[string]*reg), d.sort()
marks: make(map[string]int), d.find(name, nav.height)
saves: make(map[string]bool), d.loading = false
markInd: 0, nav.dirChan <- d
height: height, }()
} }
nav.getDirs(wd) return d
return nav
}
func (nav *nav) position() {
path := nav.currDir().path
for i := len(nav.dirs) - 2; i >= 0; i-- {
nav.dirs[i].find(filepath.Base(path), nav.height)
path = filepath.Dir(path)
}
} }
func (nav *nav) getDirs(wd string) { func (nav *nav) getDirs(wd string) {
@@ -272,6 +244,28 @@ func (nav *nav) getDirs(wd string) {
nav.dirs = dirs nav.dirs = dirs
} }
func newNav(height int) *nav {
wd, err := os.Getwd()
if err != nil {
log.Printf("getting current directory: %s", err)
}
nav := &nav{
dirChan: make(chan *dir),
regChan: make(chan *reg),
dirCache: make(map[string]*dir),
regCache: make(map[string]*reg),
saves: make(map[string]bool),
marks: make(map[string]int),
markInd: 0,
height: height,
}
nav.getDirs(wd)
return nav
}
func (nav *nav) renew() { func (nav *nav) renew() {
nav.dirCache = make(map[string]*dir) nav.dirCache = make(map[string]*dir)
for _, d := range nav.dirs { for _, d := range nav.dirs {
@@ -317,36 +311,16 @@ func (nav *nav) reload() {
nav.getDirs(wd) nav.getDirs(wd)
if err == nil { if err == nil {
last := nav.dirs[len(nav.dirs)-1] last := nav.dirs[len(nav.dirs)-1]
last.fi = append(last.fi, curr) last.files = append(last.files, curr)
} }
} }
func (nav *nav) loadDir(path string) *dir { func (nav *nav) position() {
d, ok := nav.dirCache[path] path := nav.currDir().path
if !ok { for i := len(nav.dirs) - 2; i >= 0; i-- {
go func() { nav.dirs[i].find(filepath.Base(path), nav.height)
d := newDir(path) path = filepath.Dir(path)
d.sort()
d.ind, d.pos = 0, 0
nav.dirChan <- d
}()
d := &dir{loading: true, path: path, sortType: gOpts.sortType}
nav.dirCache[path] = d
return d
} }
if d.sortType != gOpts.sortType {
go func() {
d.loading = true
name := d.name()
d.sort()
d.find(name, nav.height)
d.loading = false
nav.dirChan <- d
}()
}
return d
} }
func (nav *nav) preview() { func (nav *nav) preview() {
@@ -441,7 +415,7 @@ func (nav *nav) up(dist int) {
func (nav *nav) down(dist int) { func (nav *nav) down(dist int) {
dir := nav.currDir() dir := nav.currDir()
maxind := len(dir.fi) - 1 maxind := len(dir.files) - 1
if dir.ind >= maxind { if dir.ind >= maxind {
return return
@@ -506,7 +480,7 @@ func (nav *nav) top() {
func (nav *nav) bottom() { func (nav *nav) bottom() {
dir := nav.currDir() dir := nav.currDir()
dir.ind = len(dir.fi) - 1 dir.ind = len(dir.files) - 1
dir.pos = min(dir.ind, nav.height-1) dir.pos = min(dir.ind, nav.height-1)
} }
@@ -535,7 +509,7 @@ func (nav *nav) toggle() {
func (nav *nav) invert() { func (nav *nav) invert() {
last := nav.currDir() last := nav.currDir()
for _, f := range last.fi { for _, f := range last.files {
path := filepath.Join(last.path, f.Name()) path := filepath.Join(last.path, f.Name())
nav.toggleMark(path) nav.toggleMark(path)
} }
@@ -647,7 +621,7 @@ func (nav *nav) find(path string) error {
last := nav.dirs[len(nav.dirs)-1] last := nav.dirs[len(nav.dirs)-1]
if last.loading { if last.loading {
last.fi = append(last.fi, &file{FileInfo: lstat}) last.files = append(last.files, &file{FileInfo: lstat})
} else { } else {
last.find(base, nav.height) last.find(base, nav.height)
} }
@@ -671,8 +645,8 @@ func match(pattern, name string) (matched bool, err error) {
func (nav *nav) searchNext() error { func (nav *nav) searchNext() error {
last := nav.currDir() last := nav.currDir()
for i := last.ind + 1; i < len(last.fi); i++ { for i := last.ind + 1; i < len(last.files); i++ {
matched, err := match(nav.search, last.fi[i].Name()) matched, err := match(nav.search, last.files[i].Name())
if err != nil { if err != nil {
return err return err
} }
@@ -683,7 +657,7 @@ func (nav *nav) searchNext() error {
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := 0; i < last.ind; i++ { for i := 0; i < last.ind; i++ {
matched, err := match(nav.search, last.fi[i].Name()) matched, err := match(nav.search, last.files[i].Name())
if err != nil { if err != nil {
return err return err
} }
@@ -699,7 +673,7 @@ func (nav *nav) searchNext() error {
func (nav *nav) searchPrev() error { func (nav *nav) searchPrev() error {
last := nav.currDir() last := nav.currDir()
for i := last.ind - 1; i >= 0; i-- { for i := last.ind - 1; i >= 0; i-- {
matched, err := match(nav.search, last.fi[i].Name()) matched, err := match(nav.search, last.files[i].Name())
if err != nil { if err != nil {
return err return err
} }
@@ -709,8 +683,8 @@ func (nav *nav) searchPrev() error {
} }
} }
if gOpts.wrapscan { if gOpts.wrapscan {
for i := len(last.fi) - 1; i > last.ind; i-- { for i := len(last.files) - 1; i > last.ind; i-- {
matched, err := match(nav.search, last.fi[i].Name()) matched, err := match(nav.search, last.files[i].Name())
if err != nil { if err != nil {
return err return err
} }
@@ -730,10 +704,10 @@ func (nav *nav) currDir() *dir {
func (nav *nav) currFile() (*file, error) { func (nav *nav) currFile() (*file, error) {
last := nav.dirs[len(nav.dirs)-1] last := nav.dirs[len(nav.dirs)-1]
if len(last.fi) == 0 { if len(last.files) == 0 {
return nil, fmt.Errorf("empty directory") return nil, fmt.Errorf("empty directory")
} }
return last.fi[last.ind], nil return last.files[last.ind], nil
} }
type indexedMarks struct { type indexedMarks struct {
+13 -12
View File
@@ -47,15 +47,15 @@ func init() {
} }
func pauseCommand() *exec.Cmd { func pauseCommand() *exec.Cmd {
c := `echo cmd := `echo
echo -n 'Press any key to continue' echo -n 'Press any key to continue'
old=$(stty -g) old=$(stty -g)
stty raw -echo stty raw -echo
eval "ignore=\$(dd bs=1 count=1 2> /dev/null)" eval "ignore=\$(dd bs=1 count=1 2> /dev/null)"
stty $old stty $old
echo` echo`
return exec.Command(gOpts.shell, "-c", c) return exec.Command(gOpts.shell, "-c", cmd)
} }
func shellCommand(s string, args []string) *exec.Cmd { func shellCommand(s string, args []string) *exec.Cmd {
@@ -80,10 +80,11 @@ func putCommand(list []string, dir *dir, copy bool) *exec.Cmd {
} }
// XXX: POSIX standard states that -i flag shall do nothing when the // XXX: POSIX standard states that -i flag shall do nothing when the
// response is not affirmative. Since this command is run with a nil stdin, // response is not affirmative. Since this command is run with a nil
// it should not give an affirmative answer and in return this command // stdin, it should not give an affirmative answer and in return this
// should not overwrite existing files. Our intention here is to use the // command should not overwrite existing files. Our intention here is
// standard -i flag in place of non-standard -n flag to avoid overwrites. // to use the standard -i flag in place of non-standard -n flag to
// avoid overwrites.
args = append(args, "-i") args = append(args, "-i")
args = append(args, list...) args = append(args, list...)
+1 -1
View File
@@ -23,7 +23,7 @@ package main
// ExecExpr = Prefix <value> '\n' // ExecExpr = Prefix <value> '\n'
// | Prefix '{{' <value> '}}' ';' // | Prefix '{{' <value> '}}' ';'
// //
// Prefix = '$' | '!' | '&' | '/' | '?' // Prefix = '$' | '%' | '!' | '&'
// //
// ListExpr = ':' Expr ListRest '\n' // ListExpr = ':' Expr ListRest '\n'
// | ':' '{{' Expr ListRest '}}' ';' // | ':' '{{' Expr ListRest '}}' ';'
+3 -3
View File
@@ -16,12 +16,12 @@ var (
) )
func serve() { func serve() {
logFile, err := os.Create(gServerLogPath) f, err := os.Create(gServerLogPath)
if err != nil { if err != nil {
panic(err) panic(err)
} }
defer logFile.Close() defer f.Close()
log.SetOutput(logFile) log.SetOutput(f)
log.Print("hi!") log.Print("hi!")
+105 -107
View File
@@ -7,7 +7,6 @@ import (
"log" "log"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -22,63 +21,63 @@ import (
const gEscapeCode = 27 const gEscapeCode = 27
var gKeyVal = map[termbox.Key][]rune{ var gKeyVal = map[termbox.Key]string{
termbox.KeyF1: {'<', 'f', '-', '1', '>'}, termbox.KeyF1: "<f-1>",
termbox.KeyF2: {'<', 'f', '-', '2', '>'}, termbox.KeyF2: "<f-2>",
termbox.KeyF3: {'<', 'f', '-', '3', '>'}, termbox.KeyF3: "<f-3>",
termbox.KeyF4: {'<', 'f', '-', '4', '>'}, termbox.KeyF4: "<f-4>",
termbox.KeyF5: {'<', 'f', '-', '5', '>'}, termbox.KeyF5: "<f-5>",
termbox.KeyF6: {'<', 'f', '-', '6', '>'}, termbox.KeyF6: "<f-6>",
termbox.KeyF7: {'<', 'f', '-', '7', '>'}, termbox.KeyF7: "<f-7>",
termbox.KeyF8: {'<', 'f', '-', '8', '>'}, termbox.KeyF8: "<f-8>",
termbox.KeyF9: {'<', 'f', '-', '9', '>'}, termbox.KeyF9: "<f-9>",
termbox.KeyF10: {'<', 'f', '-', '1', '0', '>'}, termbox.KeyF10: "<f-10>",
termbox.KeyF11: {'<', 'f', '-', '1', '1', '>'}, termbox.KeyF11: "<f-11>",
termbox.KeyF12: {'<', 'f', '-', '1', '2', '>'}, termbox.KeyF12: "<f-12>",
termbox.KeyInsert: {'<', 'i', 'n', 's', 'e', 'r', 't', '>'}, termbox.KeyInsert: "<insert>",
termbox.KeyDelete: {'<', 'd', 'e', 'l', 'e', 't', 'e', '>'}, termbox.KeyDelete: "<delete>",
termbox.KeyHome: {'<', 'h', 'o', 'm', 'e', '>'}, termbox.KeyHome: "<home>",
termbox.KeyEnd: {'<', 'e', 'n', 'd', '>'}, termbox.KeyEnd: "<end>",
termbox.KeyPgup: {'<', 'p', 'g', 'u', 'p', '>'}, termbox.KeyPgup: "<pgup>",
termbox.KeyPgdn: {'<', 'p', 'g', 'd', 'n', '>'}, termbox.KeyPgdn: "<pgdn>",
termbox.KeyArrowUp: {'<', 'u', 'p', '>'}, termbox.KeyArrowUp: "<up>",
termbox.KeyArrowDown: {'<', 'd', 'o', 'w', 'n', '>'}, termbox.KeyArrowDown: "<down>",
termbox.KeyArrowLeft: {'<', 'l', 'e', 'f', 't', '>'}, termbox.KeyArrowLeft: "<left>",
termbox.KeyArrowRight: {'<', 'r', 'i', 'g', 'h', 't', '>'}, termbox.KeyArrowRight: "<right>",
termbox.KeyCtrlSpace: {'<', 'c', '-', 's', 'p', 'a', 'c', 'e', '>'}, termbox.KeyCtrlSpace: "<c-space>",
termbox.KeyCtrlA: {'<', 'c', '-', 'a', '>'}, termbox.KeyCtrlA: "<c-a>",
termbox.KeyCtrlB: {'<', 'c', '-', 'b', '>'}, termbox.KeyCtrlB: "<c-b>",
termbox.KeyCtrlC: {'<', 'c', '-', 'c', '>'}, termbox.KeyCtrlC: "<c-c>",
termbox.KeyCtrlD: {'<', 'c', '-', 'd', '>'}, termbox.KeyCtrlD: "<c-d>",
termbox.KeyCtrlE: {'<', 'c', '-', 'e', '>'}, termbox.KeyCtrlE: "<c-e>",
termbox.KeyCtrlF: {'<', 'c', '-', 'f', '>'}, termbox.KeyCtrlF: "<c-f>",
termbox.KeyCtrlG: {'<', 'c', '-', 'g', '>'}, termbox.KeyCtrlG: "<c-g>",
termbox.KeyBackspace: {'<', 'b', 's', '>'}, termbox.KeyBackspace: "<bs>",
termbox.KeyTab: {'<', 't', 'a', 'b', '>'}, termbox.KeyTab: "<tab>",
termbox.KeyCtrlJ: {'<', 'c', '-', 'j', '>'}, termbox.KeyCtrlJ: "<c-j>",
termbox.KeyCtrlK: {'<', 'c', '-', 'k', '>'}, termbox.KeyCtrlK: "<c-k>",
termbox.KeyCtrlL: {'<', 'c', '-', 'l', '>'}, termbox.KeyCtrlL: "<c-l>",
termbox.KeyEnter: {'<', 'e', 'n', 't', 'e', 'r', '>'}, termbox.KeyEnter: "<enter>",
termbox.KeyCtrlN: {'<', 'c', '-', 'n', '>'}, termbox.KeyCtrlN: "<c-n>",
termbox.KeyCtrlO: {'<', 'c', '-', 'o', '>'}, termbox.KeyCtrlO: "<c-o>",
termbox.KeyCtrlP: {'<', 'c', '-', 'p', '>'}, termbox.KeyCtrlP: "<c-p>",
termbox.KeyCtrlQ: {'<', 'c', '-', 'q', '>'}, termbox.KeyCtrlQ: "<c-q>",
termbox.KeyCtrlR: {'<', 'c', '-', 'r', '>'}, termbox.KeyCtrlR: "<c-r>",
termbox.KeyCtrlS: {'<', 'c', '-', 's', '>'}, termbox.KeyCtrlS: "<c-s>",
termbox.KeyCtrlT: {'<', 'c', '-', 't', '>'}, termbox.KeyCtrlT: "<c-t>",
termbox.KeyCtrlU: {'<', 'c', '-', 'u', '>'}, termbox.KeyCtrlU: "<c-u>",
termbox.KeyCtrlV: {'<', 'c', '-', 'v', '>'}, termbox.KeyCtrlV: "<c-v>",
termbox.KeyCtrlW: {'<', 'c', '-', 'w', '>'}, termbox.KeyCtrlW: "<c-w>",
termbox.KeyCtrlX: {'<', 'c', '-', 'x', '>'}, termbox.KeyCtrlX: "<c-x>",
termbox.KeyCtrlY: {'<', 'c', '-', 'y', '>'}, termbox.KeyCtrlY: "<c-y>",
termbox.KeyCtrlZ: {'<', 'c', '-', 'z', '>'}, termbox.KeyCtrlZ: "<c-z>",
termbox.KeyEsc: {'<', 'e', 's', 'c', '>'}, termbox.KeyEsc: "<esc>",
termbox.KeyCtrlBackslash: {'<', 'c', '-', '\\', '>'}, termbox.KeyCtrlBackslash: "<c-\\>",
termbox.KeyCtrlRsqBracket: {'<', 'c', '-', ']', '>'}, termbox.KeyCtrlRsqBracket: "<c-]>",
termbox.KeyCtrl6: {'<', 'c', '-', '6', '>'}, termbox.KeyCtrl6: "<c-6>",
termbox.KeyCtrlSlash: {'<', 'c', '-', '/', '>'}, termbox.KeyCtrlSlash: "<c-/>",
termbox.KeySpace: {'<', 's', 'p', 'a', 'c', 'e', '>'}, termbox.KeySpace: "<space>",
termbox.KeyBackspace2: {'<', 'b', 's', '2', '>'}, termbox.KeyBackspace2: "<bs2>",
} }
var gValKey map[string]termbox.Key var gValKey map[string]termbox.Key
@@ -86,7 +85,7 @@ var gValKey map[string]termbox.Key
func init() { func init() {
gValKey = make(map[string]termbox.Key) gValKey = make(map[string]termbox.Key)
for k, v := range gKeyVal { for k, v := range gKeyVal {
gValKey[string(v)] = k gValKey[v] = k
} }
} }
@@ -202,27 +201,27 @@ func fileInfo(f *file, d *dir) string {
continue continue
} }
if f.count == -1 { if f.dirCount == -1 {
d, err := os.Open(path) d, err := os.Open(path)
if err != nil { if err != nil {
f.count = -2 f.dirCount = -2
} }
names, err := d.Readdirnames(1000) names, err := d.Readdirnames(1000)
d.Close() d.Close()
if names == nil && err != io.EOF { if names == nil && err != io.EOF {
f.count = -2 f.dirCount = -2
} else { } else {
f.count = len(names) f.dirCount = len(names)
} }
} }
switch { switch {
case f.count < 0: case f.dirCount < 0:
info = fmt.Sprintf("%s ?", info) info = fmt.Sprintf("%s ?", info)
case f.count < 1000: case f.dirCount < 1000:
info = fmt.Sprintf("%s %4d", info, f.count) info = fmt.Sprintf("%s %4d", info, f.dirCount)
default: default:
info = fmt.Sprintf("%s 999+", info) info = fmt.Sprintf("%s 999+", info)
} }
@@ -249,20 +248,20 @@ func (win *win) printDir(dir *dir, marks map[string]int, saves map[string]bool,
return return
} }
if len(dir.fi) == 0 { if len(dir.files) == 0 {
fg = termbox.AttrBold fg = termbox.AttrBold
win.print(2, 0, fg, bg, "empty") win.print(2, 0, fg, bg, "empty")
return return
} }
beg := max(dir.ind-dir.pos, 0) beg := max(dir.ind-dir.pos, 0)
end := min(beg+win.h, len(dir.fi)) end := min(beg+win.h, len(dir.files))
if beg > end { if beg > end {
return return
} }
for i, f := range dir.fi[beg:end] { for i, f := range dir.files[beg:end] {
fg, bg = colors.get(f) fg, bg = colors.get(f)
path := filepath.Join(dir.path, f.Name()) path := filepath.Join(dir.path, f.Name())
@@ -335,7 +334,7 @@ type ui struct {
cmdPrefix string cmdPrefix string
cmdAccLeft []rune cmdAccLeft []rune
cmdAccRight []rune cmdAccRight []rune
cmdBuf []rune cmdYankBuf []rune
keyAcc []rune keyAcc []rune
keyCount []rune keyCount []rune
colors colorMap colors colorMap
@@ -343,8 +342,8 @@ type ui struct {
func getWidths(wtot int) []int { func getWidths(wtot int) []int {
rsum := 0 rsum := 0
for _, rat := range gOpts.ratios { for _, r := range gOpts.ratios {
rsum += rat rsum += r
} }
wlen := len(gOpts.ratios) wlen := len(gOpts.ratios)
@@ -538,7 +537,7 @@ func (ui *ui) drawStatLine(nav *nav) {
ui.msgWin.print(0, 0, fg, bg, ui.msg) ui.msgWin.print(0, 0, fg, bg, ui.msg)
tot := len(currDir.fi) tot := len(currDir.files)
ind := min(currDir.ind+1, tot) ind := min(currDir.ind+1, tot)
acc := string(ui.keyCount) + string(ui.keyAcc) acc := string(ui.keyCount) + string(ui.keyAcc)
@@ -662,11 +661,12 @@ func (ui *ui) draw(nav *nav) {
func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) { func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) {
binds = make(map[string]expr) binds = make(map[string]expr)
for key, expr := range keys { for key, expr := range keys {
if strings.HasPrefix(key, prefix) { if !strings.HasPrefix(key, prefix) {
binds[key] = expr continue
if key == prefix { }
ok = true binds[key] = expr
} if key == prefix {
ok = true
} }
} }
return return
@@ -692,8 +692,6 @@ func listBinds(binds map[string]expr) *bytes.Buffer {
return b return b
} }
var altKey = regexp.MustCompile(`<a-(.)>`)
func (ui *ui) pollEvent() termbox.Event { func (ui *ui) pollEvent() termbox.Event {
select { select {
case key := <-ui.keyChan: case key := <-ui.keyChan:
@@ -707,8 +705,8 @@ func (ui *ui) pollEvent() termbox.Event {
ev.Ch = '<' ev.Ch = '<'
case key == "<gt>": case key == "<gt>":
ev.Ch = '>' ev.Ch = '>'
case altKey.MatchString(key): case reAltKey.MatchString(key):
match := altKey.FindStringSubmatch(key)[1] match := reAltKey.FindStringSubmatch(key)[1]
ev.Ch, _ = utf8.DecodeRuneInString(match) ev.Ch, _ = utf8.DecodeRuneInString(match)
ev.Mod = termbox.ModAlt ev.Mod = termbox.ModAlt
default: default:
@@ -727,24 +725,9 @@ func (ui *ui) pollEvent() termbox.Event {
} }
} }
func readCmdEvent(ch chan<- expr, ev termbox.Event) { // This function is used to read a normal event on the client side. For keys,
if ev.Ch != 0 { // digits are interpreted as command counts but this is only done for digits
if ev.Mod == termbox.ModAlt { // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k").
val := []rune{'<', 'a', '-', ev.Ch, '>'}
if expr, ok := gOpts.cmdkeys[string(val)]; ok {
ch <- expr
}
} else {
ch <- &callExpr{"cmd-insert", []string{string(ev.Ch)}, 1}
}
} else {
val := gKeyVal[ev.Key]
if expr, ok := gOpts.cmdkeys[string(val)]; ok {
ch <- expr
}
}
}
func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) { func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
draw := &callExpr{"draw", nil, 1} draw := &callExpr{"draw", nil, 1}
count := 1 count := 1
@@ -754,9 +737,9 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
if ev.Ch != 0 { if ev.Ch != 0 {
switch { switch {
case ev.Ch == '<': case ev.Ch == '<':
ui.keyAcc = append(ui.keyAcc, '<', 'l', 't', '>') ui.keyAcc = append(ui.keyAcc, []rune("<lt>")...)
case ev.Ch == '>': case ev.Ch == '>':
ui.keyAcc = append(ui.keyAcc, '<', 'g', 't', '>') ui.keyAcc = append(ui.keyAcc, []rune("<gt>")...)
case ev.Mod == termbox.ModAlt: case ev.Mod == termbox.ModAlt:
ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', ev.Ch, '>') ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', ev.Ch, '>')
case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0: case unicode.IsDigit(ev.Ch) && len(ui.keyAcc) == 0:
@@ -766,12 +749,12 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
} }
} else { } else {
val := gKeyVal[ev.Key] val := gKeyVal[ev.Key]
if string(val) == "<esc>" { if val == "<esc>" {
ch <- draw ch <- draw
ui.keyAcc = nil ui.keyAcc = nil
ui.keyCount = nil ui.keyCount = nil
} }
ui.keyAcc = append(ui.keyAcc, val...) ui.keyAcc = append(ui.keyAcc, []rune(val)...)
} }
if len(ui.keyAcc) == 0 { if len(ui.keyAcc) == 0 {
@@ -843,9 +826,24 @@ func (ui *ui) readEvent(ch chan<- expr, ev termbox.Event) {
} }
} }
// This function is used to read expressions on the client side. Digits are func readCmdEvent(ch chan<- expr, ev termbox.Event) {
// interpreted as command counts but this is only done for digits preceding any if ev.Ch != 0 {
// non-digit characters (e.g. "42y2k" as 42 times "y2k"). if ev.Mod == termbox.ModAlt {
val := string([]rune{'<', 'a', '-', ev.Ch, '>'})
if expr, ok := gOpts.cmdkeys[val]; ok {
ch <- expr
}
} else {
ch <- &callExpr{"cmd-insert", []string{string(ev.Ch)}, 1}
}
} else {
val := gKeyVal[ev.Key]
if expr, ok := gOpts.cmdkeys[val]; ok {
ch <- expr
}
}
}
func (ui *ui) readExpr() <-chan expr { func (ui *ui) readExpr() <-chan expr {
ch := make(chan expr) ch := make(chan expr)