diff --git a/app.go b/app.go index d5e52552..23df125f 100644 --- a/app.go +++ b/app.go @@ -255,7 +255,7 @@ func (app *app) writeHistory() error { return nil } -// This is the main event loop of the application. Expressions are read from +// loop is the main event loop of the application. Expressions are read from // the client and the server on separate goroutines and sent here over channels // for evaluation. Similarly directories and regular files are also read in // separate goroutines and sent here for update. @@ -535,7 +535,7 @@ func (app *app) runCmdSync(cmd *exec.Cmd, pauseAfter bool) { app.nav.renew() } -// This function is used to run a shell command. Modes are as follows: +// runShell is used to run a shell command. Modes are as follows: // // Prefix Wait Async Stdin Stdout Stderr UI action // $ No No Yes Yes Yes Pause and then resume @@ -588,10 +588,10 @@ func (app *app) runShell(s string, args []string, prefix string) { return } - // Cmd.StdoutPipe cannot be used as it requires the output to be fully - // read before calling Cmd.Wait, however in this case Cmd.Wait should - // only wait for the command to finish executing regardless of whether - // the output has been fully read or not. + // [exec.Cmd.StdoutPipe] cannot be used as it requires the output to be fully + // read before calling [exec.Cmd.Wait], however in this case Cmd.Wait should + // only wait for the command to finish executing regardless of whether the + // output has been fully read or not. inReader, inWriter, err := os.Pipe() if err != nil { log.Printf("creating input pipe: %s", err) diff --git a/colors.go b/colors.go index 4871de62..0decf846 100644 --- a/colors.go +++ b/colors.go @@ -145,7 +145,7 @@ func (sm styleMap) parseFile(path string) { } } -// This function parses $LS_COLORS environment variable. +// parseGNU parses the $LS_COLORS environment variable. func (sm *styleMap) parseGNU(env string) { for entry := range strings.SplitSeq(env, ":") { if entry == "" { @@ -179,7 +179,7 @@ func (sm *styleMap) parsePair(pair []string) { sm.styles[key] = applySGR(val, tcell.StyleDefault) } -// This function parses $LSCOLORS environment variable. +// parseBSD parses the $LSCOLORS environment variable. func (sm styleMap) parseBSD(env string) { if len(env) != 22 { log.Printf("invalid $LSCOLORS variable: %s", env) diff --git a/misc.go b/misc.go index 68abb054..7eee655b 100644 --- a/misc.go +++ b/misc.go @@ -70,7 +70,8 @@ func runeSliceWidthRange(rs []rune, beg, end int) []rune { return rs[b:] } -// Returns the last runes of `rs` that take up at most `maxWidth` space. +// runeSliceWidthLastRange returns the last runes of `rs` that take up +// at most `maxWidth` space. func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune { lastWidth := 0 for i := len(rs) - 1; i >= 0; i-- { @@ -83,7 +84,7 @@ func runeSliceWidthLastRange(rs []rune, maxWidth int) []rune { return rs } -// This function is used to escape whitespaces and special characters with +// cmdEscape is used to escape whitespace and special characters with // backslashes in a given string. func cmdEscape(s string) string { buf := make([]rune, 0, len(s)) @@ -96,8 +97,8 @@ func cmdEscape(s string) string { return string(buf) } -// This function is used to remove backslashes that are used to escape -// whitespaces and special characters in a given string. +// cmdUnescape is used to remove backslashes that are used to escape +// whitespace and special characters in a given string. func cmdUnescape(s string) string { esc := false buf := make([]rune, 0, len(s)) @@ -123,8 +124,8 @@ func cmdUnescape(s string) string { return string(buf) } -// This function splits the given string by whitespaces. It is aware of escaped -// and quoted whitespaces so that they are not split unintentionally. +// tokenize splits the given string by whitespace. It is aware of escaped +// and quoted whitespace so that they are not split unintentionally. func tokenize(s string) []string { esc := false quote := false @@ -151,7 +152,7 @@ func tokenize(s string) []string { return append(toks, string(buf)) } -// This function splits the first word of a string delimited by whitespace from +// splitWord splits the first word of a string delimited by whitespace from // the rest. This is used to tokenize a string one by one without touching the // rest. Whitespace on the left side of both the word and the rest are trimmed. func splitWord(s string) (word, rest string) { @@ -168,8 +169,8 @@ func splitWord(s string) (word, rest string) { return } -// This function reads whitespace separated string arrays at each line. Single -// or double quotes can be used to escape whitespaces. Hash characters can be +// readArrays reads whitespace-separated string arrays on each line. Single +// or double quotes can be used to escape whitespace. Hash characters can be // used to add a comment until the end of line. Leading and trailing space is // trimmed. Empty lines are skipped. func readArrays(r io.Reader, minCols, maxCols int) ([][]string, error) { @@ -242,7 +243,7 @@ func readPairs(r io.Reader) ([][]string, error) { return readArrays(r, 2, 2) } -// This function converts a size in bytes to a human readable form using +// humanize converts a size in bytes to a human-readable form using // prefixes for either binary (1 KiB = 1024 B) or decimal (1 KB = 1000 B) // multiples. The output should be no more than 5 characters long. func humanize(size uint64) string { @@ -255,9 +256,8 @@ func humanize(size uint64) string { return fmt.Sprintf("%dB", size) } - // *Note*: due to [`FileSize.Size()`](https://pkg.go.dev/io/fs#FileInfo) - // being `int64`, the maximum possible representable value would be 8 EiB or - // 9.2 EB. + // Note: due to [fs.FileInfo.Size] being `int64`, the maximum + // possible representable value would be 8 EiB or 9.2 EB. prefixes := []string{ "K", // kibi (2^10) or kilo (10^3) "M", // mebi (2^20) or mega (10^6) @@ -290,8 +290,8 @@ func humanize(size uint64) string { return fmt.Sprintf("+999%s", prefixes[len(prefixes)-1]) } -// This function returns an ls(1)-style string representation of the given file -// mode, to avoid using Go's implementation, which slightly differs. +// permString returns an ls(1)-style string representation of the given file +// mode, to avoid using [fs.FileMode.String], which differs slightly. func permString(m os.FileMode) string { // re-use Perm()'s "-rwxrwxrwx" output and write type into b[0] b := []byte(m.Perm().String()) @@ -337,7 +337,7 @@ func permString(m os.FileMode) string { return string(b) } -// This function compares two strings for natural sorting which takes into +// naturalCmp compares two strings for natural sorting which takes into // account the values of numbers in strings. For example, '2' is ordered before // '10', and similarly 'foo2bar' ordered before 'foo10bar'. When comparing // numbers, if they have the same value then the length of the string is also @@ -389,8 +389,8 @@ func naturalCmp(s1, s2 string) int { } } -// This function returns the extension of a file with a leading dot -// it returns an empty string if extension could not be determined +// getFileExtension returns the extension of a file with a leading dot. +// It returns an empty string if extension could not be determined // i.e. directories, filenames without extensions func getFileExtension(file fs.FileInfo) string { if file.IsDir() { @@ -403,7 +403,7 @@ func getFileExtension(file fs.FileInfo) string { return filepath.Ext(file.Name()) } -// This function truncates a filename at a given position. +// truncateFilename truncates a filename at a given position. // The position is specified as percentage indicating where the truncation // character will appear (0 means left, 50 means middle, 100 means right). // The file extension is not affected by truncation, however it will be clipped @@ -433,8 +433,8 @@ func truncateFilename(file fs.FileInfo, maxWidth, truncatePct int, truncateChar return string(result) } -// This function deletes entries from a map if the key is either the given path -// or a subpath of it. +// deletePathRecursive deletes entries from a map if the key is either the given +// path or a subpath of it. // This is useful for clearing cached data when a directory is moved or deleted. func deletePathRecursive[T any](m map[string]T, path string) { delete(m, path) @@ -446,7 +446,7 @@ func deletePathRecursive[T any](m map[string]T, path string) { } } -// This function reads lines from a file to be displayed as a preview. +// readLines reads lines from a file to be displayed as a preview. // The number of lines to read is capped since files can be very large. // Lines are split on `\n` characters, and `\r` characters are discarded. // Sixel images are also detected and stored as separate lines. @@ -513,7 +513,7 @@ func readLines(reader io.ByteReader, maxLines int) (lines []string, binary bool, } } -// This function calculates the widths of windows as the result of applying the +// getWidths calculates the widths of windows as the result of applying the // `ratios` option to the screen width. One column is allocated for each divider // between windows. The `drawbox` option requires an additional two columns to // draw the left and right borders. diff --git a/nav.go b/nav.go index dd91ac45..0df10cda 100644 --- a/nav.go +++ b/nav.go @@ -23,12 +23,13 @@ import ( "github.com/djherbis/times" ) +// A linkState describes whether a file is a symlink and whether its target exists. type linkState byte const ( - notLink linkState = iota - working - broken + notLink linkState = iota // Not a symbolic link. + working // Symbolic link with an existing target. + broken // Symbolic link with a missing target. ) type file struct { @@ -43,7 +44,7 @@ type file struct { changeTime time.Time // time of last status (inode) change customInfo string // property defined via `addcustominfo` ext string // file extension (including the dot) - err error // potential error returned by `os.Lstat` + err error // potential error returned by [os.Lstat] } func newFile(path string) *file { @@ -80,7 +81,7 @@ func newFile(path string) *file { ts := times.Get(lstat) at := ts.AccessTime() - // from times docs: + // from [times.Timespec] docs: // ChangeTime() panics unless HasChangeTime() is true and // BirthTime() panics unless HasBirthTime() is true. @@ -429,11 +430,12 @@ func (dir *dir) boundPos(height int) { dir.pos = max(dir.pos, height-(len(dir.files)-dir.ind)) } +// clipboardMode controls the clipboard's behavior when pasting. type clipboardMode byte const ( - clipboardCopy = iota - clipboardCut + clipboardCopy clipboardMode = iota // Copy on paste. + clipboardCut // Move on paste. ) type clipboard struct { diff --git a/termseq.go b/termseq.go index 313d5147..72211a32 100644 --- a/termseq.go +++ b/termseq.go @@ -11,16 +11,17 @@ import ( "github.com/gdamore/tcell/v2" ) +// gEscapeCode is the byte that starts ANSI control sequences. const gEscapeCode byte = '\x1b' -// This function is used to remove style-related ANSI escape sequences from +// stripTermSequence is used to remove style-related ANSI escape sequences from // a given string. // -// *Note*: this function is based entirely on `printLength()` and strips only -// style-related sequences, `erase in line` and `OSC 8` sequences. Other codes -// (e.g., cursor moves), as well as broken escape sequences, aren't removed. -// This prevents mismatches between the two functions and avoids misalignment -// when rendering the UI. +// Note: this function is based on [printLength] and only strips style-related +// sequences, `erase in line`, and `OSC 8` sequences. Other codes (e.g. cursor +// moves), as well as broken escape sequences, are not removed. This prevents +// mismatches between the two functions and avoids misalignment when rendering +// the UI. func stripTermSequence(s string) string { var b strings.Builder slen := len(s) @@ -39,8 +40,9 @@ func stripTermSequence(s string) string { return b.String() } -// This function is used to extract and return a terminal sequence from a given -// string. If no supported sequence could be found, an empty string is returned. +// readTermSequence is used to extract and return a terminal sequence from a +// given string. If no supported sequence could be found, an empty string is +// returned. // // CSI (Control Sequence Introducer): // - SGR (Select Graphic Rendition) `m`, used for text styling @@ -85,8 +87,8 @@ func readTermSequence(s string) string { } } -// This function takes an escape sequence option (e.g. `\033[1m`) and outputs a -// complete format string (e.g. `\033[1m%s\033[0m`). +// optionToFmtstr takes an escape sequence option (e.g. `\033[1m`) and outputs +// a complete format string (e.g. `\033[1m%s\033[0m`). func optionToFmtstr(optstr string) string { if !strings.Contains(optstr, "%s") { return optstr + "%s\033[0m" @@ -95,8 +97,8 @@ func optionToFmtstr(optstr string) string { } } -// This function takes an escape sequence option (e.g. `\033[1m`) and converts -// it to a `tcell.Style` object. +// parseEscapeSequence takes an escape sequence option (e.g. `\033[1m`) and +// converts it to a [tcell.Style] object. // Legacy function that only accepts SGR. Kept for convenience. func parseEscapeSequence(s string) tcell.Style { s = strings.TrimPrefix(s, "\033[") @@ -106,8 +108,8 @@ func parseEscapeSequence(s string) tcell.Style { return applySGR(s, tcell.StyleDefault) } -// This function takes an escape sequence (e.g. `\033[1m`) and applies it -// to the given `tcell.Style` object. +// applyTermSequence takes an escape sequence (e.g. `\033[1m`) and applies it +// to the given [tcell.Style] object. // Accepts SGR and OSC sequences. func applyTermSequence(s string, st tcell.Style) tcell.Style { slen := len(s) @@ -133,6 +135,8 @@ func applyTermSequence(s string, st tcell.Style) tcell.Style { } } +// applySGR takes an SGR sequence and applies it to the given [tcell.Style] +// object. func applySGR(s string, st tcell.Style) tcell.Style { toks := strings.Split(s, ";") @@ -228,7 +232,10 @@ loop: return st } -// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda +// applyOSC takes an OSC sequence and applies it to the given [tcell.Style] +// object. +// It currently supports OSC 8 hyperlinks only, implemented as specified by +// https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda. func applyOSC(body string, st tcell.Style) tcell.Style { genAutoID := func(url string) string { sum := sha256.Sum256([]byte(url)) diff --git a/ui.go b/ui.go index 8779da34..6559f518 100644 --- a/ui.go +++ b/ui.go @@ -164,6 +164,10 @@ func (win *win) renew(w, h, x, y int) { win.w, win.h, win.x, win.y = w, h, x, y } +// printLength returns the display width of s in terminal cells. +// +// It ignores supported terminal control sequences (see [readTermSequence]) +// and accounts for tab expansions using the `tabstop` option. func printLength(s string) int { ind := 0 off := 0 @@ -342,12 +346,13 @@ type dirContext struct { tags map[string]string } +// dirRole describes what kind of directory pane is being drawn. type dirRole byte const ( - Active dirRole = iota - Parent - Preview + Active dirRole = iota // Current directory pane. + Parent // Parent or ancestor directory pane. + Preview // Preview pane when it shows a directory listing. ) type dirStyle struct { @@ -723,9 +728,12 @@ func (ui *ui) echoerrf(format string, a ...any) { ui.echoerr(fmt.Sprintf(format, a...)) } -// This represents the preview for a file. +// reg represents the preview for a file. // This can also be used to represent the preview of a directory if // `dirpreviews` is enabled. +// +// Note: the name `reg` is historical. It originally meant "regular" +// file preview, but `previewer` now also supports non-regular files. type reg struct { loading bool volatile bool @@ -1528,7 +1536,7 @@ func addSpecialKeyModifier(val string, mod tcell.ModMask) string { } } -// This function is used to read a normal event on the client side. For keys, +// readNormalEvent is used to read a normal event on the client side. For keys, // digits are interpreted as command counts but this is only done for digits // preceding any non-digit characters (e.g. "42y2k" as 42 times "y2k"). func (ui *ui) readNormalEvent(ev tcell.Event, nav *nav) expr {