package main import ( "bytes" "fmt" "log" "os" "path/filepath" "reflect" "slices" "sort" "strconv" "strings" "text/tabwriter" "text/template" "time" "unicode" "unicode/utf8" "github.com/gdamore/tcell/v2" "github.com/mattn/go-runewidth" "golang.org/x/term" ) var gKeyVal = map[tcell.Key]string{ tcell.KeyEnter: "", tcell.KeyBackspace: "", tcell.KeyTab: "", tcell.KeyBacktab: "", tcell.KeyEsc: "", tcell.KeyBackspace2: "", tcell.KeyDelete: "", tcell.KeyInsert: "", tcell.KeyUp: "", tcell.KeyDown: "", tcell.KeyLeft: "", tcell.KeyRight: "", tcell.KeyHome: "", tcell.KeyEnd: "", tcell.KeyUpLeft: "", tcell.KeyUpRight: "", tcell.KeyDownLeft: "", tcell.KeyDownRight: "", tcell.KeyCenter: "
", tcell.KeyPgDn: "", tcell.KeyPgUp: "", tcell.KeyClear: "", tcell.KeyExit: "", tcell.KeyCancel: "", tcell.KeyPause: "", tcell.KeyPrint: "", tcell.KeyF1: "", tcell.KeyF2: "", tcell.KeyF3: "", tcell.KeyF4: "", tcell.KeyF5: "", tcell.KeyF6: "", tcell.KeyF7: "", tcell.KeyF8: "", tcell.KeyF9: "", tcell.KeyF10: "", tcell.KeyF11: "", tcell.KeyF12: "", tcell.KeyF13: "", tcell.KeyF14: "", tcell.KeyF15: "", tcell.KeyF16: "", tcell.KeyF17: "", tcell.KeyF18: "", tcell.KeyF19: "", tcell.KeyF20: "", tcell.KeyF21: "", tcell.KeyF22: "", tcell.KeyF23: "", tcell.KeyF24: "", tcell.KeyF25: "", tcell.KeyF26: "", tcell.KeyF27: "", tcell.KeyF28: "", tcell.KeyF29: "", tcell.KeyF30: "", tcell.KeyF31: "", tcell.KeyF32: "", tcell.KeyF33: "", tcell.KeyF34: "", tcell.KeyF35: "", tcell.KeyF36: "", tcell.KeyF37: "", tcell.KeyF38: "", tcell.KeyF39: "", tcell.KeyF40: "", tcell.KeyF41: "", tcell.KeyF42: "", tcell.KeyF43: "", tcell.KeyF44: "", tcell.KeyF45: "", tcell.KeyF46: "", tcell.KeyF47: "", tcell.KeyF48: "", tcell.KeyF49: "", tcell.KeyF50: "", tcell.KeyF51: "", tcell.KeyF52: "", tcell.KeyF53: "", tcell.KeyF54: "", tcell.KeyF55: "", tcell.KeyF56: "", tcell.KeyF57: "", tcell.KeyF58: "", tcell.KeyF59: "", tcell.KeyF60: "", tcell.KeyF61: "", tcell.KeyF62: "", tcell.KeyF63: "", tcell.KeyF64: "", tcell.KeyCtrlA: "", tcell.KeyCtrlB: "", tcell.KeyCtrlC: "", tcell.KeyCtrlD: "", tcell.KeyCtrlE: "", tcell.KeyCtrlF: "", tcell.KeyCtrlG: "", tcell.KeyCtrlJ: "", tcell.KeyCtrlK: "", tcell.KeyCtrlL: "", tcell.KeyCtrlN: "", tcell.KeyCtrlO: "", tcell.KeyCtrlP: "", tcell.KeyCtrlQ: "", tcell.KeyCtrlR: "", tcell.KeyCtrlS: "", tcell.KeyCtrlT: "", tcell.KeyCtrlU: "", tcell.KeyCtrlV: "", tcell.KeyCtrlW: "", tcell.KeyCtrlX: "", tcell.KeyCtrlY: "", tcell.KeyCtrlZ: "", tcell.KeyCtrlSpace: "", tcell.KeyCtrlUnderscore: "", tcell.KeyCtrlRightSq: "", tcell.KeyCtrlBackslash: "", tcell.KeyCtrlCarat: "", } var gValKey map[string]tcell.Key func init() { gValKey = make(map[string]tcell.Key, len(gKeyVal)) for k, v := range gKeyVal { gValKey[v] = k } } type win struct { w, h, x, y int } func newWin(w, h, x, y int) *win { return &win{w, h, x, y} } func (win *win) renew(w, h, x, y int) { win.w, win.h, win.x, win.y = w, h, x, y } func printLength(s string) int { ind := 0 off := 0 slen := len(s) for i := 0; i < slen; i++ { seq := readTermSequence(s[i:]) if seq != "" { i += len(seq) - 1 continue } r, w := utf8.DecodeRuneInString(s[i:]) i += w - 1 if r == '\t' { ind += gOpts.tabstop - (ind-off)%gOpts.tabstop } else { ind += runewidth.RuneWidth(r) } } return ind } func (win *win) print(screen tcell.Screen, x, y int, st tcell.Style, s string) tcell.Style { off := x var comb []rune slen := len(s) for i := 0; i < slen; i++ { seq := readTermSequence(s[i:]) if seq != "" { st = applyTermSequence(seq, st) i += len(seq) - 1 continue } r, w := utf8.DecodeRuneInString(s[i:]) for { rc, wc := utf8.DecodeRuneInString(s[i+w:]) if !unicode.Is(unicode.Mn, rc) { break } comb = append(comb, rc) i += wc } if x < win.w { screen.SetContent(win.x+x, win.y+y, r, comb, st) comb = nil } i += w - 1 if r == '\t' { ind := gOpts.tabstop - (x-off)%gOpts.tabstop for i := 0; i < ind && x+i < win.w; i++ { screen.SetContent(win.x+x+i, win.y+y, ' ', nil, st) } x += ind } else { x += runewidth.RuneWidth(r) } } return st } func (win *win) printf(screen tcell.Screen, x, y int, st tcell.Style, format string, a ...any) { win.print(screen, x, y, st, fmt.Sprintf(format, a...)) } func (win *win) printLine(screen tcell.Screen, x, y int, st tcell.Style, s string) { win.printf(screen, x, y, st, "%s%*s", s, win.w-printLength(s), "") } func (win *win) printRight(screen tcell.Screen, y int, st tcell.Style, s string) { win.print(screen, win.w-printLength(s), y, st, s) } func (win *win) printReg(screen tcell.Screen, reg *reg, previewLoading bool, sxs *sixelScreen) { switch { case reg.loading: if previewLoading { st := tcell.StyleDefault.Reverse(true) win.print(screen, 2, 0, st, "loading...") } case reg.sixel: sxs.printSixel(win, screen, reg) default: st := tcell.StyleDefault for i, l := range reg.lines { if i > win.h-1 { break } st = win.print(screen, 0, i, st, l) } } if !reg.sixel { sxs.lastFile = "" } } var gThisYear = time.Now().Year() func infotimefmt(t time.Time) string { if t.Year() == gThisYear { return t.Format(gOpts.infotimefmtnew) } return t.Format(gOpts.infotimefmtold) } func fileInfo(f *file, d *dir, userWidth, groupWidth, customWidth int) (string, string, int) { var info strings.Builder var custom string var off int for _, s := range getInfo(d.path) { switch s { case "size": if f.IsDir() && getDirCounts(d.path) { switch { case f.dirCount < -1: info.WriteString(" !") case f.dirCount < 0: info.WriteString(" ?") case f.dirCount < 10000: fmt.Fprintf(&info, " %5d", f.dirCount) default: info.WriteString(" 9999+") } continue } var sz string if f.IsDir() && f.dirSize < 0 { sz = "-" } else { sz = humanize(uint64(f.TotalSize())) } fmt.Fprintf(&info, " %5s", sz) case "time": fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.ModTime())) case "atime": fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.accessTime)) case "btime": fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.birthTime)) case "ctime": fmt.Fprintf(&info, " %*s", max(len(gOpts.infotimefmtnew), len(gOpts.infotimefmtold)), infotimefmt(f.changeTime)) case "perm": info.WriteString(" " + permString(f.Mode())) case "user": fmt.Fprintf(&info, " %-*s", userWidth, userName(f.FileInfo)) case "group": fmt.Fprintf(&info, " %-*s", groupWidth, groupName(f.FileInfo)) case "custom": // Prevent useless spacers, as `custom` allows empty values if customWidth < 1 { continue } // To allow for the usage of escape sequences, store `custom` // separately and print it later using the offset. off = info.Len() fmt.Fprintf(&info, " %*s", customWidth, "") custom = fmt.Sprintf(" %s%*s", f.customInfo, customWidth-printLength(f.customInfo), "") default: log.Printf("unknown info type: %s", s) } } return info.String(), custom, off } type dirContext struct { selections map[string]int clipboard clipboard tags map[string]string } type dirRole byte const ( Active dirRole = iota Parent Preview ) type dirStyle struct { colors styleMap icons iconMap role dirRole } func (win *win) printDir(ui *ui, dir *dir, context *dirContext, dirStyle *dirStyle) { if win.w < 5 || dir == nil { return } messageStyle := tcell.StyleDefault.Reverse(true) if dir.noPerm { win.print(ui.screen, 2, 0, messageStyle, "permission denied") return } fileslen := len(dir.files) if dir.loading && fileslen == 0 { win.print(ui.screen, 2, 0, messageStyle, "loading...") return } if fileslen == 0 { win.print(ui.screen, 2, 0, messageStyle, "empty") return } beg := max(dir.ind-dir.pos, 0) end := min(beg+win.h, fileslen) if beg > end { return } var lnwidth int if dirStyle.role == Active && (gOpts.number || gOpts.relativenumber) { lnwidth = 1 for j := 10; j <= fileslen; j *= 10 { lnwidth++ } if gOpts.number && gOpts.relativenumber { lnwidth = max(lnwidth, 2) } } var userWidth, groupWidth, customWidth int var fetchedCustom bool // Only fetch user/group/custom widths if configured to display them for _, s := range getInfo(dir.path) { switch s { case "user": userWidth = getUserWidth(dir, beg, end) case "group": groupWidth = getGroupWidth(dir, beg, end) case "custom": customWidth = getCustomWidth(dir, beg, end) fetchedCustom = true // Can have a length of 0 } if userWidth > 0 && groupWidth > 0 && fetchedCustom { break } } indOff, tagOff, nameOff := lnwidth, lnwidth, lnwidth+1 if !gOpts.mergeindicators { tagOff++ nameOff++ } visualSelections := dir.visualSelections() for i, f := range dir.files[beg:end] { st := dirStyle.colors.get(f) if lnwidth > 0 { var ln string if gOpts.number && !gOpts.relativenumber { ln = fmt.Sprintf("%*d", lnwidth, i+1+beg) } else if gOpts.relativenumber { switch { case i < dir.pos: ln = fmt.Sprintf("%*d", lnwidth, dir.pos-i) case i > dir.pos: ln = fmt.Sprintf("%*d", lnwidth, i-dir.pos) case gOpts.number: ln = fmt.Sprintf("%-*d", lnwidth, i+1+beg) default: ln = fmt.Sprintf("%*d", lnwidth, 0) } } win.print(ui.screen, 0, i, tcell.StyleDefault, fmt.Sprintf(optionToFmtstr(gOpts.numberfmt), ln)) } path := filepath.Join(dir.path, f.Name()) var fmtStr string if slices.Contains(visualSelections, path) { fmtStr = gOpts.visualfmt } else if _, ok := context.selections[path]; ok { fmtStr = gOpts.selectfmt } else if slices.Contains(context.clipboard.paths, path) { if context.clipboard.mode == clipboardCopy { fmtStr = gOpts.copyfmt } else { fmtStr = gOpts.cutfmt } } tag := " " if val, ok := context.tags[path]; ok && len(val) > 0 { tag = val } if fmtStr != "" { ind := " " if gOpts.mergeindicators { ind = tag } win.print(ui.screen, indOff, i, parseEscapeSequence(fmtStr), ind) } // make space for select marker, and leave another space at the end maxWidth := win.w - lnwidth - 2 // make extra space to separate windows if drawbox is not enabled if !gOpts.drawbox { maxWidth-- } var icon []rune var iconDef iconDef if gOpts.icons { iconDef = dirStyle.icons.get(f) icon = slices.Concat([]rune(iconDef.icon), []rune{' '}) } // subtract space for icon maxFilenameWidth := maxWidth - runeSliceWidth(icon) // subtract space for tag if not merged with selection marker if !gOpts.mergeindicators { maxFilenameWidth-- } info, custom, customOff := fileInfo(f, dir, userWidth, groupWidth, customWidth) infolen := len(info) showInfo := infolen > 0 && 2*infolen < maxWidth if showInfo { maxFilenameWidth -= infolen } filename := []rune(truncateFilename(f, maxFilenameWidth, gOpts.truncatepct, []rune(gOpts.truncatechar)[0])) for j := runeSliceWidth(filename); j < maxFilenameWidth; j++ { filename = append(filename, ' ') } if showInfo { filename = append(filename, []rune(info)...) customOff += nameOff + runeSliceWidth(icon) + maxFilenameWidth } if i == dir.pos { var cursorFmt string switch dirStyle.role { case Active: cursorFmt = optionToFmtstr(gOpts.cursoractivefmt) case Parent: cursorFmt = optionToFmtstr(gOpts.cursorparentfmt) case Preview: cursorFmt = optionToFmtstr(gOpts.cursorpreviewfmt) } // print tag separately as it can contain color escape sequences if !gOpts.mergeindicators || fmtStr == "" { win.print(ui.screen, tagOff, i, st, fmt.Sprintf(cursorFmt, tag)) } line := slices.Concat(icon, filename, []rune{' '}) win.print(ui.screen, nameOff, i, st, fmt.Sprintf(cursorFmt, string(line))) // print over the empty space we reserved for the custom info if showInfo && custom != "" { win.print(ui.screen, customOff, i, st, fmt.Sprintf(cursorFmt, stripTermSequence(custom))) } } else { if !gOpts.mergeindicators || fmtStr == "" { if tag == " " { win.print(ui.screen, tagOff, i, st, " ") } else { tagStr := fmt.Sprintf(optionToFmtstr(gOpts.tagfmt), tag) win.print(ui.screen, tagOff, i, tcell.StyleDefault, tagStr) } } if len(icon) > 0 { iconStyle := st if iconDef.hasStyle { iconStyle = iconDef.style } win.print(ui.screen, nameOff, i, iconStyle, string(icon)) } line := slices.Concat(filename, []rune{' '}) win.print(ui.screen, nameOff+runeSliceWidth(icon), i, st, string(line)) // print over the empty space we reserved for the custom info if showInfo && custom != "" { win.print(ui.screen, customOff, i, st, custom) } } } } func getUserWidth(dir *dir, beg, end int) int { maxw := 0 for _, f := range dir.files[beg:end] { maxw = max(len(userName(f.FileInfo)), maxw) } return maxw } func getGroupWidth(dir *dir, beg, end int) int { maxw := 0 for _, f := range dir.files[beg:end] { maxw = max(len(groupName(f.FileInfo)), maxw) } return maxw } func getCustomWidth(dir *dir, beg, end int) int { maxw := 0 for _, f := range dir.files[beg:end] { maxw = max(printLength(f.customInfo), maxw) } return maxw } func getWidths(wtot int) []int { rsum := 0 for _, r := range gOpts.ratios { rsum += r } wlen := len(gOpts.ratios) widths := make([]int, wlen) if gOpts.drawbox { wtot -= (wlen + 1) } wsum := 0 for i := range wlen - 1 { widths[i] = gOpts.ratios[i] * wtot / rsum wsum += widths[i] } widths[wlen-1] = wtot - wsum return widths } func getWins(screen tcell.Screen) []*win { wtot, htot := screen.Size() widths := getWidths(wtot) wacc := 0 wlen := len(widths) wins := make([]*win, 0, wlen) for i := range wlen { if gOpts.drawbox { wacc++ wins = append(wins, newWin(widths[i], max(htot-4, 0), wacc, 2)) } else { wins = append(wins, newWin(widths[i], max(htot-2, 0), wacc, 1)) } wacc += widths[i] } return wins } type menuSelect struct { x, y int s string } type ui struct { screen tcell.Screen sxScreen sixelScreen polling bool wins []*win promptWin *win msgWin *win menuWin *win msg string exprChan chan expr keyChan chan string tevChan chan tcell.Event evChan chan tcell.Event menu string menuSelect *menuSelect cmdPrefix string cmdAccLeft []rune cmdAccRight []rune cmdYankBuf []rune keyAcc []rune keyCount []rune styles styleMap icons iconMap ruler *template.Template rulerErr error currentFile string pasteEvent bool } func newUI(screen tcell.Screen) *ui { wtot, htot := screen.Size() ui := &ui{ screen: screen, polling: true, wins: getWins(screen), promptWin: newWin(wtot, 1, 0, 0), msgWin: newWin(wtot, 1, 0, htot-1), menuWin: newWin(wtot, 1, 0, htot-2), exprChan: make(chan expr, 1000), keyChan: make(chan string, 1000), tevChan: make(chan tcell.Event, 1000), evChan: make(chan tcell.Event, 1000), styles: parseStyles(), icons: parseIcons(), currentFile: "", sxScreen: sixelScreen{}, } ui.ruler, ui.rulerErr = parseRuler() go ui.pollEvents() return ui } func (ui *ui) winAt(x, y int) (int, *win) { for i := len(ui.wins) - 1; i >= 0; i-- { w := ui.wins[i] if x >= w.x && y >= w.y && y < w.y+w.h { return i, w } } return -1, nil } func (ui *ui) pollEvents() { var ev tcell.Event for { ev = ui.screen.PollEvent() if ev == nil { ui.polling = false return } ui.tevChan <- ev } } func (ui *ui) renew() { ui.wins = getWins(ui.screen) wtot, htot := ui.screen.Size() ui.promptWin.renew(wtot, 1, 0, 0) ui.msgWin.renew(wtot, 1, 0, htot-1) ui.menuWin.renew(wtot, 1, 0, htot-2) } func (ui *ui) echo(msg string) { ui.msg = msg } func (ui *ui) echomsg(msg string) { ui.echo(msg) log.Print(msg) } func (ui *ui) echoerr(msg string) { ui.echo(fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), msg)) log.Printf("error: %s", msg) } func (ui *ui) echoerrf(format string, a ...any) { ui.echoerr(fmt.Sprintf(format, a...)) } // This represents the preview for a regular file. // This can also be used to represent the preview of a directory if // `dirpreviews` is enabled. type reg struct { loading bool volatile bool loadTime time.Time path string lines []string sixel bool } func (ui *ui) loadFile(app *app, volatile bool) { curr := app.nav.currFile() if curr == nil { return } if curr.path != ui.currentFile { ui.currentFile = curr.path onSelect(app) } if volatile { app.nav.previewChan <- "" } if !gOpts.preview { return } if curr.isPreviewable() { app.nav.loadReg(curr.path, volatile) } else if curr.IsDir() { dir := app.nav.getDir(curr.path) app.nav.checkDir(dir) } } func (ui *ui) drawPromptLine(nav *nav) { st := tcell.StyleDefault dir := nav.currDir() pwd := dir.path if after, ok := strings.CutPrefix(pwd, gUser.HomeDir); ok { pwd = filepath.Join("~", after) } sep := string(filepath.Separator) var fname string if curr := nav.currFile(); curr != nil { fname = filepath.Base(curr.path) } var prompt string prompt = strings.ReplaceAll(gOpts.promptfmt, "%u", gUser.Username) prompt = strings.ReplaceAll(prompt, "%h", gHostname) prompt = strings.ReplaceAll(prompt, "%f", fname) if printLength(strings.ReplaceAll(strings.ReplaceAll(prompt, "%w", pwd), "%d", pwd)) > ui.promptWin.w { names := strings.Split(pwd, sep) for i := range names { if names[i] == "" { continue } r, _ := utf8.DecodeRuneInString(names[i]) names[i] = string(r) if printLength(strings.ReplaceAll(strings.ReplaceAll(prompt, "%w", strings.Join(names, sep)), "%d", strings.Join(names, sep))) <= ui.promptWin.w { break } } pwd = strings.Join(names, sep) } prompt = strings.ReplaceAll(prompt, "%w", pwd) if !strings.HasSuffix(pwd, sep) { pwd += sep } prompt = strings.ReplaceAll(prompt, "%d", pwd) if len(dir.filter) != 0 { prompt = strings.ReplaceAll(prompt, "%F", fmt.Sprint(dir.filter)) } else { prompt = strings.ReplaceAll(prompt, "%F", "") } // spacer avail := ui.promptWin.w - printLength(prompt) + 2 if avail > 0 { prompt = strings.Replace(prompt, "%S", strings.Repeat(" ", avail), 1) } prompt = strings.ReplaceAll(prompt, "%S", "") ui.promptWin.print(ui.screen, 0, 0, st, prompt) } func formatRulerOpt(name, val string) string { // handle escape character so it doesn't mess up the ruler val = strings.ReplaceAll(val, "\033", "\033[7m\\033\033[0m") // display name of builtin options for clarity if !strings.HasPrefix(name, "lf_user_") { return fmt.Sprintf("%s=%s", strings.TrimPrefix(name, "lf_"), val) } return val } func (ui *ui) drawStat(nav *nav) { if ui.msg != "" { ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, ui.msg) return } curr := nav.currFile() if curr == nil { return } if curr.err != nil { ui.echoerrf("stat: %s", curr.err) ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, ui.msg) return } statfmt := strings.ReplaceAll(gOpts.statfmt, "|", "\x1f") replace := func(s, val string) { if val == "" { val = "\x00" } statfmt = strings.ReplaceAll(statfmt, s, val) } if nav.isVisualMode() { replace("%m", "VISUAL") replace("%M", "VISUAL") } else { replace("%m", "") replace("%M", "NORMAL") } replace("%p", permString(curr.Mode())) replace("%c", linkCount(curr)) replace("%u", userName(curr)) replace("%g", groupName(curr)) replace("%s", humanize(uint64(curr.Size()))) replace("%S", fmt.Sprintf("%5s", humanize(uint64(curr.Size())))) replace("%t", curr.ModTime().Format(gOpts.timefmt)) replace("%l", curr.linkTarget) var fileInfo strings.Builder for section := range strings.SplitSeq(statfmt, "\x1f") { if !strings.Contains(section, "\x00") { fileInfo.WriteString(section) } } ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, fileInfo.String()) } func (ui *ui) drawRuler(nav *nav) { st := tcell.StyleDefault dir := nav.currDir() tot := len(dir.files) ind := min(dir.ind+1, tot) hid := len(dir.allFiles) - tot acc := string(ui.keyCount) + string(ui.keyAcc) var percentage string beg := max(dir.ind-dir.pos, 0) switch { case tot <= nav.height: percentage = "All" case beg == 0: percentage = "Top" case beg == tot-nav.height: percentage = "Bot" default: percentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height)) } numClipCopy := 0 numClipMove := 0 if nav.clipboard.mode == clipboardCopy { numClipCopy = len(nav.clipboard.paths) } else { numClipMove = len(nav.clipboard.paths) } currSelections := nav.currSelections() currVSelections := nav.currDir().visualSelections() progress := []string{} if nav.copyJobs > 0 { if nav.copyTotal == 0 { progress = append(progress, fmt.Sprintf("[0%%]")) } else { progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal)) } } if nav.moveTotal > 0 { progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal)) } if nav.deleteTotal > 0 { progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal)) } opts := getOptsMap() rulerfmt := strings.ReplaceAll(gOpts.rulerfmt, "|", "\x1f") rulerfmt = reRulerSub.ReplaceAllStringFunc(rulerfmt, func(s string) string { var result string switch s { case "%a": result = acc case "%p": result = strings.Join(progress, " ") case "%m": result = fmt.Sprintf("%.d", numClipMove) case "%c": result = fmt.Sprintf("%.d", numClipCopy) case "%s": result = fmt.Sprintf("%.d", len(currSelections)) case "%v": result = fmt.Sprintf("%.d", len(currVSelections)) case "%f": result = strings.Join(dir.filter, " ") case "%i": result = strconv.Itoa(ind) case "%t": result = strconv.Itoa(tot) case "%h": result = strconv.Itoa(hid) case "%P": result = percentage case "%d": result = diskFree(dir.path) default: s = strings.TrimSuffix(strings.TrimPrefix(s, "%{"), "}") if val, ok := opts[s]; ok { result = formatRulerOpt(s, val) } } if result == "" { return "\x00" } return result }) var ruler strings.Builder for section := range strings.SplitSeq(rulerfmt, "\x1f") { if !strings.Contains(section, "\x00") { ruler.WriteString(section) } } ui.msgWin.printRight(ui.screen, 0, st, ruler.String()) } func (ui *ui) drawRulerFile(nav *nav) { if ui.rulerErr != nil { err := fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), fmt.Errorf("parsing ruler: %w", ui.rulerErr)) ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, err) return } var stat *statData curr := nav.currFile() if curr != nil { if curr.err == nil { stat = &statData{ Path: curr.path, Name: curr.Name(), Size: uint64(curr.Size()), Permissions: permString(curr.Mode()), ModTime: curr.ModTime().Format(gOpts.timefmt), LinkCount: linkCount(curr), User: userName(curr), Group: groupName(curr), Target: curr.linkTarget, } } else { ui.echoerrf("stat: %s", curr.err) } } dir := nav.currDir() tot := len(dir.files) ind := min(dir.ind+1, tot) hid := len(dir.allFiles) - tot var linePercentage string if tot == 0 { linePercentage = "100%" } else { linePercentage = fmt.Sprintf("%d%%", ind*100/tot) } var scrollPercentage string beg := max(dir.ind-dir.pos, 0) switch { case tot <= nav.height: scrollPercentage = "All" case beg == 0: scrollPercentage = "Top" case beg == tot-nav.height: scrollPercentage = "Bot" default: scrollPercentage = fmt.Sprintf("%2d%%", beg*100/(tot-nav.height)) } var copiedPaths []string var cutPaths []string if nav.clipboard.mode == clipboardCopy { copiedPaths = nav.clipboard.paths } else { cutPaths = nav.clipboard.paths } currSelections := nav.currSelections() currVSelections := nav.currDir().visualSelections() progress := []string{} if nav.copyJobs > 0 { if nav.copyTotal == 0 { progress = append(progress, fmt.Sprintf("[0%%]")) } else { progress = append(progress, fmt.Sprintf("[%d%%]", nav.copyBytes*100/nav.copyTotal)) } } if nav.moveTotal > 0 { progress = append(progress, fmt.Sprintf("[%d/%d]", nav.moveCount, nav.moveTotal)) } if nav.deleteTotal > 0 { progress = append(progress, fmt.Sprintf("[%d/%d]", nav.deleteCount, nav.deleteTotal)) } mode := "NORMAL" if nav.isVisualMode() { mode = "VISUAL" } options := make(map[string]string) v := reflect.ValueOf(gOpts) t := v.Type() for i := range v.NumField() { name := t.Field(i).Name switch name { case "nkeys", "vkeys", "cmdkeys", "cmds", "user": continue default: options[name] = fieldToString(v.Field(i)) } } data := rulerData{ SPACER: "\x1f", Message: ui.msg, Keys: string(ui.keyCount) + string(ui.keyAcc), Progress: progress, Copy: copiedPaths, Cut: cutPaths, Select: currSelections, Visual: currVSelections, Index: ind, Total: tot, Hidden: hid, LinePercentage: linePercentage, ScrollPercentage: scrollPercentage, Filter: dir.filter, Mode: mode, Options: options, UserOptions: gOpts.user, Stat: stat, } left, right, err := renderRuler(ui.ruler, data, ui.msgWin.w) if err != nil { err := fmt.Sprintf(optionToFmtstr(gOpts.errorfmt), fmt.Errorf("rendering ruler: %w", err)) ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, err) return } ui.msgWin.print(ui.screen, 0, 0, tcell.StyleDefault, left) ui.msgWin.printRight(ui.screen, 0, tcell.StyleDefault, right) } func (ui *ui) drawPreview(nav *nav, context *dirContext) { curr := nav.currFile() if curr == nil { return } win := ui.wins[len(ui.wins)-1] ui.sxScreen.clearSixel(win, ui.screen, curr.path) if gOpts.preview { if curr.isPreviewable() { if reg, ok := nav.regCache[curr.path]; ok { win.printReg(ui.screen, reg, nav.previewLoading, &ui.sxScreen) } } else if curr.IsDir() { ui.sxScreen.lastFile = "" dir := nav.getDir(curr.path) dirStyle := &dirStyle{colors: ui.styles, icons: ui.icons, role: Preview} win.printDir(ui, dir, context, dirStyle) } } } func (ui *ui) drawBox() { st := parseEscapeSequence(gOpts.borderfmt) w, h := ui.screen.Size() for i := 1; i < w-1; i++ { ui.screen.SetContent(i, 1, tcell.RuneHLine, nil, st) ui.screen.SetContent(i, h-2, tcell.RuneHLine, nil, st) } for i := 2; i < h-2; i++ { ui.screen.SetContent(0, i, tcell.RuneVLine, nil, st) ui.screen.SetContent(w-1, i, tcell.RuneVLine, nil, st) } if gOpts.roundbox { ui.screen.SetContent(0, 1, '╭', nil, st) ui.screen.SetContent(w-1, 1, '╮', nil, st) ui.screen.SetContent(0, h-2, '╰', nil, st) ui.screen.SetContent(w-1, h-2, '╯', nil, st) } else { ui.screen.SetContent(0, 1, tcell.RuneULCorner, nil, st) ui.screen.SetContent(w-1, 1, tcell.RuneURCorner, nil, st) ui.screen.SetContent(0, h-2, tcell.RuneLLCorner, nil, st) ui.screen.SetContent(w-1, h-2, tcell.RuneLRCorner, nil, st) } wacc := 0 for wind := range len(ui.wins) - 1 { wacc += ui.wins[wind].w + 1 ui.screen.SetContent(wacc, 1, tcell.RuneTTee, nil, st) for i := 2; i < h-2; i++ { ui.screen.SetContent(wacc, i, tcell.RuneVLine, nil, st) } ui.screen.SetContent(wacc, h-2, tcell.RuneBTee, nil, st) } } func (ui *ui) drawMenu() { if ui.menu == "" { return } lines := strings.Split(ui.menu, "\n") lines = lines[:len(lines)-1] ui.menuWin.h = len(lines) ui.menuWin.y = ui.msgWin.y - ui.menuWin.h // clear sixel image if it overlaps with the menu ui.screen.LockRegion(ui.menuWin.x, ui.menuWin.y, ui.menuWin.w, ui.menuWin.h, false) ui.sxScreen.forceClear = true for i, line := range lines { var st tcell.Style if i == 0 { st = parseEscapeSequence(gOpts.menuheaderfmt) } else { st = parseEscapeSequence(gOpts.menufmt) } ui.menuWin.printLine(ui.screen, 0, i, st, line) } if ui.menuSelect != nil { st := parseEscapeSequence(gOpts.menuselectfmt) ui.menuWin.print(ui.screen, ui.menuSelect.x, ui.menuSelect.y, st, ui.menuSelect.s) } } func (ui *ui) dirOfWin(nav *nav, wind int) *dir { wins := len(ui.wins) if gOpts.preview { wins-- } ind := len(nav.dirPaths) - wins + wind if ind < 0 { return nil } return nav.getDir(nav.dirPaths[ind]) } func (ui *ui) draw(nav *nav) { st := tcell.StyleDefault context := dirContext{selections: nav.selections, clipboard: nav.clipboard, tags: nav.tags} ui.screen.Clear() ui.drawPromptLine(nav) wins := len(ui.wins) if gOpts.preview { wins-- } for i := range wins { role := Parent if i == wins-1 { role = Active } if dir := ui.dirOfWin(nav, i); dir != nil { ui.wins[i].printDir(ui, dir, &context, &dirStyle{colors: ui.styles, icons: ui.icons, role: role}) } } switch ui.cmdPrefix { case "": if gOpts.rulerfile { ui.drawRulerFile(nav) } else { ui.drawStat(nav) ui.drawRuler(nav) } ui.screen.HideCursor() case ">": maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth) left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix)-printLength(ui.msg)) ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+ui.msg) ui.msgWin.print(ui.screen, runeSliceWidth(prefix)+printLength(ui.msg), 0, st, string(left)+string(ui.cmdAccRight)) ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+printLength(ui.msg)+runeSliceWidth(left), ui.msgWin.y) default: maxWidth := ui.msgWin.w - 1 // leave space for cursor at the end prefix := runeSliceWidthRange([]rune(ui.cmdPrefix), 0, maxWidth) left := runeSliceWidthLastRange(ui.cmdAccLeft, maxWidth-runeSliceWidth(prefix)) ui.msgWin.printLine(ui.screen, 0, 0, st, string(prefix)+string(left)+string(ui.cmdAccRight)) ui.screen.ShowCursor(ui.msgWin.x+runeSliceWidth(prefix)+runeSliceWidth(left), ui.msgWin.y) } ui.drawPreview(nav, &context) if gOpts.drawbox { ui.drawBox() } ui.drawMenu() ui.screen.Show() } func findBinds(keys map[string]expr, prefix string) (binds map[string]expr, ok bool) { binds = make(map[string]expr) for key, expr := range keys { if !strings.HasPrefix(key, prefix) { continue } binds[key] = expr if key == prefix { ok = true } } return } func listBinds(binds map[string]map[string]expr) string { t := new(tabwriter.Writer) b := new(bytes.Buffer) // merge keys by command across modes m := make(map[string]map[string]string) for mode, keys := range binds { for key, expr := range keys { if _, ok := m[key]; !ok { m[key] = make(map[string]string) } m[key][expr.String()] += mode } } type entry struct { mode, key, cmd string } // collect normalized entries var entries []entry for key, cmds := range m { for cmd, modes := range cmds { tmp := []rune(modes) slices.Sort(tmp) entries = append(entries, entry{string(tmp), key, cmd}) } } sort.Slice(entries, func(i, j int) bool { if entries[i].key != entries[j].key { return entries[i].key < entries[j].key } return entries[i].mode < entries[j].mode }) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "mode\tkey\tcommand") for _, e := range entries { fmt.Fprintf(t, "%s\t%s\t%s\n", e.mode, e.key, e.cmd) } t.Flush() return b.String() } func listMatchingBinds(binds map[string]expr, prefix string) string { t := new(tabwriter.Writer) b := new(bytes.Buffer) keys := make([]string, 0, len(binds)) for k := range binds { keys = append(keys, k) } sort.Strings(keys) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "key\tcommand") for _, k := range keys { remain, _ := strings.CutPrefix(k, prefix) fmt.Fprintf(t, "%s\t%v\n", remain, binds[k]) } t.Flush() return b.String() } func listCmds(cmds map[string]expr) string { t := new(tabwriter.Writer) b := new(bytes.Buffer) keys := make([]string, 0, len(cmds)) for k := range cmds { keys = append(keys, k) } sort.Strings(keys) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "name\tcommand") for _, k := range keys { fmt.Fprintf(t, "%s\t%v\n", k, cmds[k]) } t.Flush() return b.String() } func listJumps(jumps []string, ind int) string { t := new(tabwriter.Writer) b := new(bytes.Buffer) maxlength := len(strconv.Itoa(max(ind, len(jumps)-1-ind))) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, " jump\tpath") // print jumps in order of most recent, Vim uses the opposite order for i := len(jumps) - 1; i >= 0; i-- { switch { case i < ind: fmt.Fprintf(t, " %*d\t%s\n", maxlength, ind-i, jumps[i]) case i > ind: fmt.Fprintf(t, " %*d\t%s\n", maxlength, i-ind, jumps[i]) default: fmt.Fprintf(t, "> %*d\t%s\n", maxlength, 0, jumps[i]) } } t.Flush() return b.String() } func listHistory(history []string) string { t := new(tabwriter.Writer) b := new(bytes.Buffer) maxlength := len(strconv.Itoa(len(history))) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "number\tcommand") for i, cmd := range history { fmt.Fprintf(t, "%*d\t%s\n", maxlength, i+1, cmd) } t.Flush() return b.String() } func listMarks(marks map[string]string) string { t := new(tabwriter.Writer) b := new(bytes.Buffer) keys := make([]string, 0, len(marks)) for k := range marks { keys = append(keys, k) } sort.Strings(keys) t.Init(b, 0, gOpts.tabstop, 2, '\t', 0) fmt.Fprintln(t, "mark\tpath") for _, k := range keys { fmt.Fprintf(t, "%s\t%s\n", k, marks[k]) } t.Flush() return b.String() } func listFilesInCurrDir(nav *nav) string { dir := nav.currDir() if dir.loading { log.Printf("listFilesInCurrDir(): %s is still loading, `files` isn't ready for remote query", dir.path) return "" } b := new(strings.Builder) for _, file := range dir.files { fmt.Fprintln(b, file.path) } return b.String() } func (ui *ui) pollEvent() tcell.Event { select { case val := <-ui.keyChan: var ch rune var mod tcell.ModMask k := tcell.KeyRune if key, ok := gValKey[val]; ok { return tcell.NewEventKey(key, ch, mod) } switch { case utf8.RuneCountInString(val) == 1: ch, _ = utf8.DecodeRuneInString(val) case val == "": ch = '<' case val == "": ch = '>' case val == "": ch = ' ' case reModKey.MatchString(val): matches := reModKey.FindStringSubmatch(val) switch matches[1] { case "c": mod = tcell.ModCtrl case "s": mod = tcell.ModShift case "a": mod = tcell.ModAlt } val = matches[2] if utf8.RuneCountInString(val) == 1 { ch, _ = utf8.DecodeRuneInString(val) break } else if key, ok := gValKey["<"+val+">"]; ok { k = key break } fallthrough default: k = tcell.KeyESC ui.echoerrf("unknown key: %s", val) } return tcell.NewEventKey(k, ch, mod) case ev := <-ui.tevChan: return ev } } func addSpecialKeyModifier(val string, mod tcell.ModMask) string { switch { case !strings.HasPrefix(val, "<"): return val case mod == tcell.ModCtrl && !strings.HasPrefix(val, "")...) case tev.Rune() == '>': ui.keyAcc = append(ui.keyAcc, []rune("")...) case tev.Rune() == ' ': ui.keyAcc = append(ui.keyAcc, []rune("")...) case tev.Modifiers() == tcell.ModAlt: ui.keyAcc = append(ui.keyAcc, '<', 'a', '-', tev.Rune(), '>') case unicode.IsDigit(tev.Rune()) && len(ui.keyAcc) == 0: ui.keyCount = append(ui.keyCount, tev.Rune()) default: ui.keyAcc = append(ui.keyAcc, tev.Rune()) } } else { val := gKeyVal[tev.Key()] val = addSpecialKeyModifier(val, tev.Modifiers()) if val == "" && len(ui.keyAcc) != 0 { ui.keyAcc = nil ui.keyCount = nil ui.menu = "" return draw } ui.keyAcc = append(ui.keyAcc, []rune(val)...) } if len(ui.keyAcc) == 0 { return draw } binds, ok := findBinds(keys, string(ui.keyAcc)) switch len(binds) { case 0: ui.echoerrf("unknown mapping: %s", string(ui.keyAcc)) ui.keyAcc = nil ui.keyCount = nil ui.menu = "" return draw default: if ok { if len(ui.keyCount) > 0 { c, err := strconv.Atoi(string(ui.keyCount)) if err != nil { log.Printf("converting command count: %s", err) } count = c } expr := keys[string(ui.keyAcc)] if count != 0 { switch e := expr.(type) { case *callExpr: expr = &callExpr{name: e.name, args: e.args, count: count} case *listExpr: expr = &listExpr{exprs: e.exprs, count: count} } } ui.keyAcc = nil ui.keyCount = nil ui.menu = "" return expr } if gOpts.showbinds { // mode and already typed keys are obvious here; no need to clutter the menu ui.menu = listMatchingBinds(binds, string(ui.keyAcc)) } return draw } case *tcell.EventMouse: if ui.cmdPrefix != "" { return nil } var button string switch tev.Buttons() { case tcell.Button1: button = "" case tcell.Button2: button = "" case tcell.Button3: button = "" case tcell.Button4: button = "" case tcell.Button5: button = "" case tcell.Button6: button = "" case tcell.Button7: button = "" case tcell.Button8: button = "" case tcell.WheelUp: button = "" case tcell.WheelDown: button = "" case tcell.WheelLeft: button = "" case tcell.WheelRight: button = "" case tcell.ButtonNone: return nil } if tev.Modifiers() == tcell.ModCtrl { button = "'}) if expr, ok := gOpts.cmdkeys[val]; ok { return expr } } else { return &callExpr{"cmd-insert", []string{string(tev.Rune())}, 1} } } else { val := gKeyVal[tev.Key()] val = addSpecialKeyModifier(val, tev.Modifiers()) if expr, ok := gOpts.cmdkeys[val]; ok { return expr } } } return nil } func (ui *ui) readEvent(ev tcell.Event, nav *nav) expr { if ev == nil { return nil } if _, ok := ev.(*tcell.EventKey); ok && ui.cmdPrefix != "" { return readCmdEvent(ev) } return ui.readNormalEvent(ev, nav) } func (ui *ui) readExpr() { go func() { for { ui.evChan <- ui.pollEvent() } }() } func (ui *ui) suspend() error { ui.sxScreen.forceClear = true return ui.screen.Suspend() } func (ui *ui) resume() error { err := ui.screen.Resume() if !ui.polling { go ui.pollEvents() ui.polling = true } return err } func (ui *ui) exportSizes() { w, h := ui.screen.Size() os.Setenv("lf_width", strconv.Itoa(w)) os.Setenv("lf_height", strconv.Itoa(h)) } func anyKey() { fmt.Fprint(os.Stderr, gOpts.waitmsg) defer fmt.Fprintln(os.Stderr) oldState, err := term.MakeRaw(int(os.Stdin.Fd())) if err != nil { panic(err) } defer func() { if err := term.Restore(int(os.Stdin.Fd()), oldState); err != nil { panic(err) } }() b := make([]byte, 8) if _, err := os.Stdin.Read(b); err != nil { log.Printf("Failed to read key press: %s", err) } } func listMatches(screen tcell.Screen, matches []compMatch, selectedInd int) (string, *menuSelect) { if len(matches) < 2 { return "", nil } wtot, _ := screen.Size() wcol := 0 for _, m := range matches { wcol = max(wcol, runeSliceWidth([]rune(m.name))) } wcol += gOpts.tabstop - wcol%gOpts.tabstop ncol := max(wtot/wcol, 1) var b strings.Builder b.WriteString("possible matches") for i, match := range matches { if i%ncol == 0 { b.WriteByte('\n') } w := runeSliceWidth([]rune(match.name)) fmt.Fprintf(&b, "%s%*s", match.name, wcol-w, "") } b.WriteByte('\n') var selection *menuSelect if selectedInd != -1 { selection = &menuSelect{selectedInd % ncol * wcol, selectedInd/ncol + 1, matches[selectedInd].name} } return b.String(), selection }