options.go
This file
Path
src/options.go
3,997 lines · 108.2 KiB · Go
Last changed by
Apply facing-line rule to input border as wellJunegunn Choibefore adoption7fe4831
History of this fileTake it
The walk stopped after 200 commits: lines older than 7a811f0 point at it.
Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1–6why, one step back1package fzf23import (4 "errors"5 "fmt"6 "maps"Add every(N) bind event and FZF_IDLE_TIME env var (#4797)Junegunn Choibefore adoptionfcc3c6a
line 7why, one step back7 "math"Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 8–68why, one step back8 "os"9 "regexp"10 "strconv"11 "strings"12 "time"1314 "github.com/junegunn/fzf/src/algo"15 "github.com/junegunn/fzf/src/tui"16 "github.com/junegunn/fzf/src/util"1718 "github.com/junegunn/go-shellwords"19 "github.com/rivo/uniseg"20)2122const Usage = `fzf is an interactive filter program for any kind of list.2324It implements a "fuzzy" matching algorithm, so you can quickly type in patterns25with omitted characters and still get the results you want.2627Project URL: https://github.com/junegunn/fzf28Author: Junegunn Choi <junegunn.c@gmail.com>2930* See man page for more information: fzf --man3132Usage: fzf [options]3334 SEARCH35 -e, --exact Enable exact-match36 +x, --no-extended Disable extended-search mode37 -i, --ignore-case Case-insensitive match38 +i, --no-ignore-case Case-sensitive match39 --smart-case Smart-case match (default)40 --scheme=SCHEME Scoring scheme [default|path|history]41 -n, --nth=N[,..] Comma-separated list of field index expressions42 for limiting search scope. Each can be a non-zero43 integer or a range expression ([BEGIN]..[END]).44 --with-nth=N[,..] Transform the presentation of each line using45 field index expressions46 --accept-nth=N[,..] Define which fields to print on accept47 -d, --delimiter=STR Field delimiter regex (default: AWK-style)48 +s, --no-sort Do not sort the result49 --literal Do not normalize latin script letters50 --tail=NUM Maximum number of items to keep in memory51 --disabled Do not perform search52 --tiebreak=CRI[,..] Comma-separated list of sort criteria to apply53 when the scores are tied54 [length|chunk|pathname|begin|end|index] (default: length)5556 INPUT/OUTPUT57 --read0 Read input delimited by ASCII NUL characters58 --print0 Print output delimited by ASCII NUL characters59 --ansi Enable processing of ANSI color codes60 --sync Synchronous search for multi-staged filtering6162 GLOBAL STYLE63 --style=PRESET Apply a style preset [default|minimal|full[:BORDER_STYLE]64 --color=COLSPEC Base scheme (dark|light|base16|bw) and/or custom colors65 --no-color Disable colors66 --no-bold Do not use bold text6768 DISPLAY MODEAllow adaptive height with negative valueJunegunn Choibefore adoptiond1cea64
line 69why, one step back69 --height=[~][-]HEIGHT[%] Display fzf window below the cursor with the givenFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 70–77why, one step back70 height instead of using fullscreen.71 A negative value is calculated as the terminal height72 minus the given value.73 If prefixed with '~', fzf will determine the height74 according to the input size.75 --min-height=HEIGHT[+] Minimum height when --height is given as a percentage.76 Add '+' to automatically increase the value77 according to the other layout options (default: 10+).Use floating pane instead of popup on tmux 3.7 or above (#4850) (#4852)Junegunn Choibefore adoption1e31e5d
line 78why, one step back78 --popup[=OPTS] Start fzf in a floating pane (requires tmux 3.3+ or Zellij 0.44+)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
line 79why, one step back79 [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]]Set --border-label as the title of the tmux floating pane (#4853)Junegunn Choibefore adoption77e6394
line 80why, one step back80 [,border-native] (default: center,50%)Support zellij floating pane via --popup (new name for --tmux) (#4145)Junegunn Choibefore adoption6f17d49
line 81why, one step back81 --tmux[=OPTS] Alias for --popupFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 82–87why, one step back8283 LAYOUT84 --layout=LAYOUT Choose layout: [default|reverse|reverse-list]85 --margin=MARGIN Screen margin (TRBL | TB,RL | T,RL,B | T,R,B,L)86 --padding=PADDING Padding inside border (TRBL | TB,RL | T,RL,B | T,R,B,L)87 --border[=STYLE] Draw border around the finderAdd dashed border styleJunegunn Choibefore adoption7782da6
line 88why, one step back88 [rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 89–104why, one step back89 top|bottom|left|right|line|none] (default: rounded)90 --border-label=LABEL Label to print on the border91 --border-label-pos=COL Position of the border label92 [POSITIVE_INTEGER: columns from left|93 NEGATIVE_INTEGER: columns from right][:bottom]94 (default: 0 or center)9596 LIST SECTION97 -m, --multi[=MAX] Enable multi-select with tab/shift-tab98 --highlight-line Highlight the whole current line99 --cycle Enable cyclic scroll100 --wrap[=MODE] Enable line wrap (char|word, default: char)101 --wrap-sign=STR Indicator for wrapped lines102 --no-multi-line Disable multi-line display of items when using --read0103 --raw Enable raw mode (show non-matching items)104 --track Track the current selection when the result is updatedReplace --track=NTH with --id-nth for cross-reload item identityJunegunn Choibefore adoptionb5f7221
line 105why, one step back105 --id-nth=N[,..] Define item identity fields for cross-reload operationsFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 106–130why, one step back106 --tac Reverse the order of the input107 --gap[=N] Render empty lines between each item108 --gap-line[=STR] Draw horizontal line on each gap using the string109 (default: '┈' or '-')110 --freeze-left=N Number of fields to freeze on the left111 --freeze-right=N Number of fields to freeze on the right112 --keep-right Keep the right end of the line visible on overflow113 --scroll-off=LINES Number of screen lines to keep above or below when114 scrolling to the top or to the bottom (default: 0)115 --no-hscroll Disable horizontal scroll116 --hscroll-off=COLS Number of screen columns to keep to the right of the117 highlighted substring (default: 10)118 --jump-labels=CHARS Label characters for jump mode119 --gutter=CHAR Character used for the gutter column (default: '▌')120 --gutter-raw=CHAR Character used for the gutter column in raw mode (default: '▖')121 --pointer=STR Pointer to the current line (default: '▌' or '>')122 --marker=STR Multi-select marker (default: '┃' or '>')123 --marker-multi-line=STR Multi-select marker for multi-line entries;124 3 elements for top, middle, and bottom (default: '╻┃╹')125 --ellipsis=STR Ellipsis to show when line is truncated (default: '··')126 --tabstop=SPACES Number of spaces for a tab character (default: 8)127 --scrollbar[=C1[C2]] Scrollbar character(s)128 (each for list section and preview window)129 --no-scrollbar Hide scrollbar130 --list-border[=STYLE] Draw border around the list sectionAdd dashed border styleJunegunn Choibefore adoption7782da6
line 131why, one step back131 [rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 132–150why, one step back132 top|bottom|left|right|none] (default: rounded)133 --list-label=LABEL Label to print on the list border134 --list-label-pos=COL Position of the list label135 [POSITIVE_INTEGER: columns from left|136 NEGATIVE_INTEGER: columns from right][:bottom]137 (default: 0 or center)138139 INPUT SECTION140 --no-input Disable and hide the input section141 --prompt=STR Input prompt (default: '> ')142 --info=STYLE Finder info style143 [default|right|hidden|inline[-right][:PREFIX]]144 --info-command=COMMAND Command to generate info line145 --separator=STR Draw horizontal separator on info line using the string146 (default: '─' or '-')147 --no-separator Hide info line separator148 --ghost=TEXT Ghost text to display when the input is empty149 --filepath-word Make word-wise movements respect path separators150 --input-border[=STYLE] Draw border around the input sectionAdd dashed border styleJunegunn Choibefore adoption7782da6
line 151why, one step back151 [rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 152–161why, one step back152 top|bottom|left|right|line|none] (default: rounded)153 --input-label=LABEL Label to print on the input border154 --input-label-pos=COL Position of the input label155 [POSITIVE_INTEGER: columns from left|156 NEGATIVE_INTEGER: columns from right][:bottom]157 (default: 0 or center)158159 PREVIEW WINDOW160 --preview=COMMAND Command to preview highlighted line ({})161 --preview-window=OPT Preview window layout (default: right:50%)Add --preview-window=next position (#4801)Junegunn Choibefore adoption677e854
line 162why, one step back162 [up|down|left|right|next][,SIZE[%]]Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 163–167why, one step back163 [,[no]wrap[-word]][,[no]cycle][,[no]follow][,[no]info]164 [,[no]hidden][,border-STYLE]165 [,+SCROLL[OFFSETS][/DENOM]][,~HEADER_LINES]166 [,default][,<SIZE_THRESHOLD(ALTERNATIVE_LAYOUT)]167 --preview-border[=STYLE] Short for --preview-window=border-STYLEAdd dashed border styleJunegunn Choibefore adoption7782da6
line 168why, one step back168 [rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 169–179why, one step back169 top|bottom|left|right|line|none] (default: rounded)170 --preview-label=LABEL171 --preview-label-pos=N Same as --border-label and --border-label-pos,172 but for preview window173 --preview-wrap-sign=STR Indicator for wrapped lines in the preview window174175 HEADER176 --header=STR String to print as header177 --header-lines=N The first N lines of the input are treated as header178 --header-first Print header before the prompt line179 --header-border[=STYLE] Draw border around the header sectionAdd dashed border styleJunegunn Choibefore adoption7782da6
line 180why, one step back180 [rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|Add --{header,header-lines,footer}-border=inlineJunegunn Choibefore adoptiond754cfa
line 181why, one step back181 top|bottom|left|right|line|inline|none] (default: rounded)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 182–184why, one step back182 --header-lines-border[=STYLE]183 Display header from --header-lines with a separate border.184 Pass 'none' to still separate it but without a border.Add --{header,header-lines,footer}-border=inlineJunegunn Choibefore adoptiond754cfa
line 185why, one step back185 Pass 'inline' to embed it inside the list frame.Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 186–194why, one step back186 --header-label=LABEL Label to print on the header border187 --header-label-pos=COL Position of the header label188 [POSITIVE_INTEGER: columns from left|189 NEGATIVE_INTEGER: columns from right][:bottom]190 (default: 0 or center)191192 FOOTER193 --footer=STR String to print as footer194 --footer-border[=STYLE] Draw border around the footer sectionAdd dashed border styleJunegunn Choibefore adoption7782da6
line 195why, one step back195 [rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|Add --{header,header-lines,footer}-border=inlineJunegunn Choibefore adoptiond754cfa
line 196why, one step back196 top|bottom|left|right|line|inline|none] (default: line)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 197–234why, one step back197 --footer-label=LABEL Label to print on the footer border198 --footer-label-pos=COL Position of the footer label199 [POSITIVE_INTEGER: columns from left|200 NEGATIVE_INTEGER: columns from right][:bottom]201 (default: 0 or center)202203 SCRIPTING204 -q, --query=STR Start the finder with the given query205 -1, --select-1 Automatically select the only match206 -0, --exit-0 Exit immediately when there's no match207 -f, --filter=STR Print matches for the initial query and exit208 --print-query Print query as the first line209 --expect=KEYS Comma-separated list of keys to complete fzf210211 KEY/EVENT BINDING212 --bind=BINDINGS Custom key/event bindings213214 ADVANCED215 --with-shell=STR Shell command and flags to start child processes with216 --listen[=[ADDR:]PORT] Start HTTP server to receive actions via TCP217 (To allow remote process execution, use --listen-unsafe)218 --listen=SOCKET_PATH Start HTTP server to receive actions via Unix domain socket219 (Path should end with .sock)220221 DIRECTORY TRAVERSAL (Only used when $FZF_DEFAULT_COMMAND is not set)222 --walker=OPTS [file][,dir][,follow][,hidden] (default: file,follow,hidden)223 --walker-root=DIR [...] List of directories to walk (default: .)224 --walker-skip=DIRS Comma-separated list of directory names to skip225 (default: .git,node_modules)226227 HISTORY228 --history=FILE File to store fzf search history (*not* shell command history)229 --history-size=N Maximum number of entries to keep in the file (default: 1000)230231 SHELL INTEGRATION232 --bash Print script to set up Bash shell integration233 --zsh Print script to set up Zsh shell integration234 --fish Print script to set up Fish shell integrationshell: nushell integration scripts (#4630)Simon Désaulniersbefore adoption290b18d
line 235why, one step back235 --nushell Print script to set up Nushell integrationFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 236–334why, one step back236237 HELP238 --version Display version information and exit239 --help Show this message240 --man Show man page241242 ENVIRONMENT VARIABLES243 FZF_DEFAULT_COMMAND Default command to use when input is tty244 FZF_DEFAULT_OPTS Default options (e.g. '--layout=reverse --info=inline')245 FZF_DEFAULT_OPTS_FILE Location of the file to read default options from246 FZF_API_KEY X-API-Key header for HTTP server (--listen)247248`249250// Can be changed by --style251var defaultBorderShape tui.BorderShape = tui.DefaultBorderShape252253const defaultInfoPrefix = " < "254255// Case denotes case-sensitivity of search256type Case int257258// Case-sensitivities259const (260 CaseSmart Case = iota261 CaseIgnore262 CaseRespect263)264265// Sort criteria266type criterion int267268const (269 byScore criterion = iota270 byChunk271 byLength272 byBegin273 byEnd274 byPathname275)276277type heightSpec struct {278 size float64279 percent bool280 auto bool281 inverse bool282 index int283}284285type sizeSpec struct {286 size float64287 percent bool288}289290func (s sizeSpec) String() string {291 if s.percent {292 return fmt.Sprintf("%d%%", int(s.size))293 }294 return fmt.Sprintf("%d", int(s.size))295}296297func defaultMargin() [4]sizeSpec {298 return [4]sizeSpec{}299}300301type trackOption struct {302 enabled bool303 index int32304}305306var (307 trackDisabled = trackOption{false, minItem.Index()}308 trackEnabled = trackOption{true, minItem.Index()}309)310311func (t trackOption) Disabled() bool {312 return !t.enabled313}314315func (t trackOption) Global() bool {316 return t.enabled && t.index == minItem.Index()317}318319func (t trackOption) Current() bool {320 return t.enabled && t.index != minItem.Index()321}322323func trackCurrent(index int32) trackOption {324 return trackOption{true, index}325}326327type windowPosition int328329const (330 posUp windowPosition = iota331 posDown332 posLeft333 posRight334 posCenterAdd --preview-window=next position (#4801)Junegunn Choibefore adoption677e854
line 335why, one step back335 posNext // adjacent to the input section, on the list sideFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 336–342why, one step back336)337338type tmuxOptions struct {339 width sizeSpec340 height sizeSpec341 position windowPosition342 index intSet --border-label as the title of the tmux floating pane (#4853)Junegunn Choibefore adoption77e6394
line 343why, one step back343 border boolFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 344–394why, one step back344}345346type layoutType int347348const (349 layoutDefault layoutType = iota350 layoutReverse351 layoutReverseList352)353354type infoStyle int355356const (357 infoDefault infoStyle = iota358 infoRight359 infoInline360 infoInlineRight361 infoHidden362)363364type labelOpts struct {365 label string366 column int367 bottom bool368}369370type previewOpts struct {371 command string372 position windowPosition373 size sizeSpec374 scroll string375 hidden bool376 wrap bool377 wrapWord bool378 cycle bool379 follow bool380 info bool381 border tui.BorderShape382 headerLines int383 threshold int384 alternative *previewOpts385}386387func (o *previewOpts) Visible() bool {388 return o.size.size > 0 || o.alternative != nil && o.alternative.size.size > 0389}390391func (o *previewOpts) Toggle() {392 o.hidden = !o.hidden393}394Add --preview-window=next position (#4801)Junegunn Choibefore adoption677e854
line 395why, one step back395func (o *previewOpts) Border(layout layoutType) tui.BorderShape {Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 396–406why, one step back396 shape := o.border397 if shape == tui.BorderLine {398 switch o.position {399 case posUp:400 shape = tui.BorderBottom401 case posDown:402 shape = tui.BorderTop403 case posLeft:404 shape = tui.BorderRight405 case posRight:406 shape = tui.BorderLeftAdd --preview-window=next position (#4801)Junegunn Choibefore adoption677e854
lines 407–412why, one step back407 case posNext:408 if layout == layoutReverse {409 shape = tui.BorderBottom410 } else {411 shape = tui.BorderTop412 }Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 413–429why, one step back413 }414 }415 return shape416}417418func defaultTmuxOptions(index int) *tmuxOptions {419 return &tmuxOptions{420 position: posCenter,421 width: sizeSpec{50, true},422 height: sizeSpec{50, true},423 index: index}424}425426func parseTmuxOptions(arg string, index int) (*tmuxOptions, error) {427 var err error428 opts := defaultTmuxOptions(index)429 tokens := splitRegexp.Split(arg, -1)Set --border-label as the title of the tmux floating pane (#4853)Junegunn Choibefore adoption77e6394
line 430why, one step back430 errorToReturn := errors.New("invalid popup option: " + arg + " (expected: [center|top|bottom|left|right][,SIZE[%]][,SIZE[%]][,border-native])")Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 431–435why, one step back431 if len(tokens) == 0 || len(tokens) > 4 {432 return nil, errorToReturn433 }434435 for i, token := range tokens {Set --border-label as the title of the tmux floating pane (#4853)Junegunn Choibefore adoption77e6394
lines 436–438why, one step back436 if token == "border-native" {437 tokens = append(tokens[:i], tokens[i+1:]...) // cut the 'border-native' option438 opts.border = trueFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 439–521why, one step back439 break440 }441 }442443 // Defaults to 'center'444 first := "center"445 if len(tokens) > 0 {446 first = tokens[0]447 }448449 switch first {450 case "top", "up":451 opts.position = posUp452 opts.width = sizeSpec{100, true}453 case "bottom", "down":454 opts.position = posDown455 opts.width = sizeSpec{100, true}456 case "left":457 opts.position = posLeft458 opts.height = sizeSpec{100, true}459 case "right":460 opts.position = posRight461 opts.height = sizeSpec{100, true}462 case "center":463 default:464 tokens = append([]string{"center"}, tokens...)465 }466467 // One size given468 var size1 sizeSpec469 if len(tokens) > 1 {470 if size1, err = parseSize(tokens[1], 100, "size"); err != nil {471 return nil, errorToReturn472 }473 }474475 // Two sizes given476 var size2 sizeSpec477 if len(tokens) == 3 {478 if size2, err = parseSize(tokens[2], 100, "size"); err != nil {479 return nil, errorToReturn480 }481 opts.width = size1482 opts.height = size2483 } else if len(tokens) == 2 {484 switch tokens[0] {485 case "top", "up":486 opts.height = size1487 case "bottom", "down":488 opts.height = size1489 case "left":490 opts.width = size1491 case "right":492 opts.width = size1493 case "center":494 opts.width = size1495 opts.height = size1496 }497 }498499 return opts, nil500}501502func parseLabelPosition(opts *labelOpts, arg string) error {503 opts.column = 0504 opts.bottom = false505 var err error506 for _, token := range splitRegexp.Split(strings.ToLower(arg), -1) {507 switch token {508 case "center":509 opts.column = 0510 case "bottom":511 opts.bottom = true512 case "top":513 opts.bottom = false514 default:515 opts.column, err = atoi(token)516 }517 }518 return err519}520521func (a previewOpts) aboveOrBelow() bool {Add --preview-window=next position (#4801)Junegunn Choibefore adoption677e854
line 522why, one step back522 return a.size.size > 0 && (a.position == posUp || a.position == posDown || a.position == posNext)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 523–588why, one step back523}524525type previewOptsCompare int526527const (528 previewOptsSame previewOptsCompare = iota529 previewOptsDifferentContentLayout530 previewOptsDifferentLayout531)532533func (o *previewOpts) compare(active *previewOpts, b *previewOpts) previewOptsCompare {534 a := o535536 sameThreshold := o.position == b.position && o.threshold == b.threshold537 // Alternative layout is being used538 if o.alternative == active {539 a = active540541 // If the other also has an alternative layout,542 if b.alternative != nil {543 // and if the same condition is the same, compare alt vs. alt.544 if sameThreshold {545 b = b.alternative546 } else {547 // If not, we pessimistically decide that the layouts may not be the same548 return previewOptsDifferentLayout549 }550 }551 } else if b.alternative != nil && !sameThreshold {552 // We may choose the other's alternative layout, so let's be conservative.553 return previewOptsDifferentLayout554 }555556 if !(a.size == b.size && a.position == b.position && a.border == b.border && a.hidden == b.hidden) {557 return previewOptsDifferentLayout558 }559560 if a.wrap == b.wrap && a.wrapWord == b.wrapWord && a.headerLines == b.headerLines && a.info == b.info && a.scroll == b.scroll {561 return previewOptsSame562 }563564 return previewOptsDifferentContentLayout565}566567func firstLine(s string) string {568 return strings.SplitN(s, "\n", 2)[0]569}570571type walkerOpts struct {572 file bool573 dir bool574 hidden bool575 follow bool576}577578// Options stores the values of command-line options579type Options struct {580 Input chan string581 Output chan string582 NoWinpty bool583 Tmux *tmuxOptions584 ForceTtyIn bool585 ProxyScript string586 Bash bool587 Zsh bool588 Fish boolshell: nushell integration scripts (#4630)Simon Désaulniersbefore adoption290b18d
line 589why, one step back589 Nushell boolFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 590–608why, one step back590 Man bool591 Fuzzy bool592 FuzzyAlgo algo.Algo593 Scheme string594 Extended bool595 Phony bool596 Inputless bool597 Case Case598 Normalize bool599 Nth []Range600 FreezeLeft int601 FreezeRight int602 WithNth func(Delimiter) func([]Token, int32) string603 WithNthExpr string604 AcceptNth func(Delimiter) func([]Token, int32) string605 Delimiter Delimiter606 Sort int607 Raw bool608 Track trackOptionReplace --track=NTH with --id-nth for cross-reload item identityJunegunn Choibefore adoptionb5f7221
line 609why, one step back609 IdNth []RangeFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 610–736why, one step back610 Tac bool611 Tail int612 Criteria []criterion613 Multi int614 Ansi bool615 Mouse bool616 BaseTheme *tui.ColorTheme617 Theme *tui.ColorTheme618 Black bool619 Bold bool620 Height heightSpec621 MinHeight int622 Layout layoutType623 Cycle bool624 Wrap bool625 WrapWord bool626 WrapSign *string627 PreviewWrapSign *string628 MultiLine bool629 CursorLine bool630 KeepRight bool631 Hscroll bool632 HscrollOff int633 ScrollOff int634 FileWord bool635 InfoStyle infoStyle636 InfoPrefix string637 InfoCommand string638 Ghost string639 Separator *string640 JumpLabels string641 Prompt string642 Gutter *string643 GutterRaw *string644 Pointer *string645 Marker *string646 MarkerMulti *[3]string647 Query string648 Select1 bool649 Exit0 bool650 Filter *string651 ToggleSort bool652 Expect map[tui.Event]string653 Keymap map[tui.Event][]*action654 Preview previewOpts655 PrintQuery bool656 ReadZero bool657 Printer func(string)658 PrintSep string659 Sync bool660 History *History661 Header []string662 HeaderLines int663 HeaderFirst bool664 Footer []string665 Gap int666 GapLine *string667 Ellipsis *string668 Scrollbar *string669 Margin [4]sizeSpec670 Padding [4]sizeSpec671 BorderShape tui.BorderShape672 ListBorderShape tui.BorderShape673 InputBorderShape tui.BorderShape674 HeaderBorderShape tui.BorderShape675 HeaderLinesShape tui.BorderShape676 FooterBorderShape tui.BorderShape677 InputLabel labelOpts678 HeaderLabel labelOpts679 FooterLabel labelOpts680 BorderLabel labelOpts681 ListLabel labelOpts682 PreviewLabel labelOpts683 Unicode bool684 Ambidouble bool685 Tabstop int686 WithShell string687 ListenAddr *listenAddress688 Unsafe bool689 ClearOnExit bool690 WalkerOpts walkerOpts691 WalkerRoot []string692 WalkerSkip []string693 Version bool694 Help bool695 Threads int696 Bench time.Duration697 CPUProfile string698 MEMProfile string699 BlockProfile string700 MutexProfile string701 TtyDefault string702}703704func filterNonEmpty(input []string) []string {705 output := make([]string, 0, len(input))706 for _, str := range input {707 if len(str) > 0 {708 output = append(output, str)709 }710 }711 return output712}713714func defaultPreviewOpts(command string) previewOpts {715 return previewOpts{716 command: command,717 position: posRight,718 size: sizeSpec{50, true},719 info: true,720 border: defaultBorderShape,721 }722}723724func defaultOptions() *Options {725 var theme, baseTheme *tui.ColorTheme726 if os.Getenv("NO_COLOR") != "" {727 theme = tui.NoColorTheme728 baseTheme = tui.NoColorTheme729 } else {730 theme = tui.EmptyTheme731 }732733 return &Options{734 Bash: false,735 Zsh: false,736 Fish: false,shell: nushell integration scripts (#4630)Simon Désaulniersbefore adoption290b18d
line 737why, one step back737 Nushell: false,Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 738–883why, one step back738 Man: false,739 Fuzzy: true,740 FuzzyAlgo: algo.FuzzyMatchV2,741 Scheme: "", // Unknown742 Extended: true,743 Phony: false,744 Inputless: false,745 Case: CaseSmart,746 Normalize: true,747 Nth: make([]Range, 0),748 Delimiter: Delimiter{},749 Sort: 1000,750 Track: trackDisabled,751 Tac: false,752 Criteria: []criterion{}, // Unknown753 Multi: 0,754 Ansi: false,755 Mouse: true,756 Theme: theme,757 BaseTheme: baseTheme,758 Black: false,759 Bold: true,760 MinHeight: -10,761 Layout: layoutDefault,762 Cycle: false,763 Wrap: false,764 WrapWord: false,765 MultiLine: true,766 KeepRight: false,767 Hscroll: true,768 HscrollOff: 10,769 ScrollOff: 3,770 FileWord: false,771 InfoStyle: infoDefault,772 Ghost: "",773 Separator: nil,774 JumpLabels: defaultJumpLabels,775 Prompt: "> ",776 Gutter: nil,777 GutterRaw: nil,778 Pointer: nil,779 Marker: nil,780 MarkerMulti: nil,781 Query: "",782 Select1: false,783 Exit0: false,784 Filter: nil,785 ToggleSort: false,786 Expect: make(map[tui.Event]string),787 Keymap: make(map[tui.Event][]*action),788 Preview: defaultPreviewOpts(""),789 PrintQuery: false,790 ReadZero: false,791 Printer: func(str string) { fmt.Println(str) },792 PrintSep: "\n",793 Sync: false,794 History: nil,795 Header: make([]string, 0),796 HeaderLines: 0,797 HeaderFirst: false,798 Footer: make([]string, 0),799 Gap: 0,800 Ellipsis: nil,801 Scrollbar: nil,802 Margin: defaultMargin(),803 Padding: defaultMargin(),804 Unicode: true,805 Ambidouble: os.Getenv("RUNEWIDTH_EASTASIAN") == "1",806 Tabstop: 8,807 BorderLabel: labelOpts{},808 PreviewLabel: labelOpts{},809 Unsafe: false,810 ClearOnExit: true,811 WalkerOpts: walkerOpts{file: true, hidden: true, follow: true},812 WalkerRoot: []string{"."},813 WalkerSkip: []string{".git", "node_modules"},814 TtyDefault: tui.DefaultTtyDevice,815 Help: false,816 Version: false}817}818819func isDir(path string) bool {820 stat, err := os.Stat(path)821 return err == nil && stat.IsDir()822}823824func atoi(str string) (int, error) {825 num, err := strconv.Atoi(str)826 if err != nil {827 return 0, errors.New("not a valid integer: " + str)828 }829 return num, nil830}831832func atof(str string) (float64, error) {833 num, err := strconv.ParseFloat(str, 64)834 if err != nil {835 return 0, errors.New("not a valid number: " + str)836 }837 return num, nil838}839840func splitNth(str string) ([]Range, error) {841 if match, _ := regexp.MatchString("^[0-9,-.]+$", str); !match {842 return nil, errors.New("invalid format: " + str)843 }844845 tokens := strings.Split(str, ",")846 ranges := make([]Range, len(tokens))847 for idx, s := range tokens {848 r, ok := ParseRange(&s)849 if !ok {850 return nil, errors.New("invalid format: " + str)851 }852 ranges[idx] = r853 }854 return ranges, nil855}856857func nthTransformer(str string) (func(Delimiter) func([]Token, int32) string, error) {858 // ^[0-9,-.]+$"859 if match, _ := regexp.MatchString("^[0-9,-.]+$", str); match {860 nth, err := splitNth(str)861 if err != nil {862 return nil, err863 }864 return func(Delimiter) func([]Token, int32) string {865 return func(tokens []Token, index int32) string {866 return JoinTokens(Transform(tokens, nth))867 }868 }, nil869 }870871 // {...} {...} ...872 placeholder := regexp.MustCompile("{[0-9,-.]+}|{n}")873 indexes := placeholder.FindAllStringIndex(str, -1)874 if indexes == nil {875 return nil, errors.New("template should include at least 1 placeholder: " + str)876 }877878 type NthParts struct {879 str string880 index bool881 nth []Range882 }883Fix nthTransformer parts slice preallocation (#4734)cuibefore adoption14e3995
line 884why, one step back884 parts := make([]NthParts, 0, len(indexes))Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 885–966why, one step back885 idx := 0886 for _, index := range indexes {887 if idx < index[0] {888 parts = append(parts, NthParts{str: str[idx:index[0]]})889 }890 expr := str[index[0]+1 : index[1]-1]891 if expr == "n" {892 parts = append(parts, NthParts{index: true})893 } else if nth, err := splitNth(expr); err == nil {894 parts = append(parts, NthParts{nth: nth})895 }896 idx = index[1]897 }898 if idx < len(str) {899 parts = append(parts, NthParts{str: str[idx:]})900 }901902 return func(delimiter Delimiter) func([]Token, int32) string {903 return func(tokens []Token, index int32) string {904 str := ""905 for _, holder := range parts {906 if holder.nth != nil {907 str += StripLastDelimiter(JoinTokens(Transform(tokens, holder.nth)), delimiter)908 } else if holder.index {909 if index >= 0 {910 str += strconv.Itoa(int(index))911 }912 } else {913 str += holder.str914 }915 }916 return str917 }918 }, nil919}920921func delimiterRegexp(str string) Delimiter {922 // Special handling of \t923 str = strings.ReplaceAll(str, "\\t", "\t")924925 // 1. Pattern is a single character926 if len([]rune(str)) == 1 {927 return Delimiter{str: &str}928 }929930 // 2. Pattern does not contain any special character931 if regexp.QuoteMeta(str) == str {932 return Delimiter{str: &str}933 }934935 rx, e := regexp.Compile(str)936 // 3. Pattern is not a valid regular expression937 if e != nil {938 return Delimiter{str: &str}939 }940941 // 4. Pattern as regular expression. Slow.942 return Delimiter{regex: rx}943}944945func isAlphabet(char uint8) bool {946 return char >= 'a' && char <= 'z'947}948949func isNumeric(char uint8) bool {950 return char >= '0' && char <= '9'951}952953func parseAlgo(str string) (algo.Algo, error) {954 switch str {955 case "v1":956 return algo.FuzzyMatchV1, nil957 case "v2":958 return algo.FuzzyMatchV2, nil959 }960 return nil, errors.New("invalid algorithm (expected: v1 or v2)")961}962963func parseBorder(str string, optional bool) (tui.BorderShape, error) {964 switch str {965 case "line":966 return tui.BorderLine, nilAdd --{header,header-lines,footer}-border=inlineJunegunn Choibefore adoptiond754cfa
lines 967–968why, one step back967 case "inline":968 return tui.BorderInline, nilFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 969–980why, one step back969 case "rounded":970 return tui.BorderRounded, nil971 case "sharp":972 return tui.BorderSharp, nil973 case "bold":974 return tui.BorderBold, nil975 case "block":976 return tui.BorderBlock, nil977 case "thinblock":978 return tui.BorderThinBlock, nil979 case "double":980 return tui.BorderDouble, nilAdd dashed border styleJunegunn Choibefore adoption7782da6
lines 981–982why, one step back981 case "dashed":982 return tui.BorderDashed, nilFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 983–1000why, one step back983 case "horizontal":984 return tui.BorderHorizontal, nil985 case "vertical":986 return tui.BorderVertical, nil987 case "top":988 return tui.BorderTop, nil989 case "bottom":990 return tui.BorderBottom, nil991 case "left":992 return tui.BorderLeft, nil993 case "right":994 return tui.BorderRight, nil995 case "none":996 return tui.BorderNone, nil997 }998 if optional && str == "" {999 return defaultBorderShape, nil1000 }Add dashed border styleJunegunn Choibefore adoption7782da6
line 1001why, one step back1001 return tui.BorderNone, errors.New("invalid border style (expected: rounded|sharp|bold|block|thinblock|double|dashed|horizontal|vertical|top|bottom|left|right|line|inline|none)")Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1002–1065why, one step back1002}10031004func parseKeyChords(str string, message string) (map[tui.Event]string, []tui.Event, error) {1005 if len(str) == 0 {1006 return nil, nil, errors.New(message)1007 }10081009 list := []tui.Event{}1010 str = regexp.MustCompile("(?i)(alt-),").ReplaceAllString(str, "$1"+string([]rune{escapedComma}))1011 tokens := strings.Split(str, ",")1012 if str == "," || strings.HasPrefix(str, ",,") || strings.HasSuffix(str, ",,") || strings.Contains(str, ",,,") {1013 tokens = append(tokens, ",")1014 }10151016 chords := make(map[tui.Event]string)1017 for _, key := range tokens {1018 if len(key) == 0 {1019 continue // ignore1020 }1021 key = strings.ReplaceAll(key, string([]rune{escapedComma}), ",")1022 lkey := strings.ToLower(key)1023 add := func(e tui.EventType) {1024 chords[e.AsEvent()] = key1025 list = append(list, e.AsEvent())1026 }1027 switch lkey {1028 case "up":1029 add(tui.Up)1030 case "down":1031 add(tui.Down)1032 case "left":1033 add(tui.Left)1034 case "right":1035 add(tui.Right)1036 case "enter", "return":1037 add(tui.Enter)1038 case "space":1039 evt := tui.Key(' ')1040 chords[evt] = key1041 list = append(list, evt)1042 case "backspace", "bspace", "bs":1043 add(tui.Backspace)1044 case "ctrl-space":1045 add(tui.CtrlSpace)1046 case "ctrl-^", "ctrl-6":1047 add(tui.CtrlCaret)1048 case "ctrl-/", "ctrl-_":1049 add(tui.CtrlSlash)1050 case "ctrl-\\":1051 add(tui.CtrlBackSlash)1052 case "ctrl-]":1053 add(tui.CtrlRightBracket)1054 case "change":1055 add(tui.Change)1056 case "backward-eof":1057 add(tui.BackwardEOF)1058 case "start":1059 add(tui.Start)1060 case "load":1061 add(tui.Load)1062 case "focus":1063 add(tui.Focus)1064 case "result":1065 add(tui.Result)Add result-final eventJunegunn Choibefore adoption5dd698b
lines 1066–1067why, one step back1066 case "result-final":1067 add(tui.ResultFinal)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1068–1271why, one step back1068 case "resize":1069 add(tui.Resize)1070 case "one":1071 add(tui.One)1072 case "zero":1073 add(tui.Zero)1074 case "jump":1075 add(tui.Jump)1076 case "jump-cancel":1077 add(tui.JumpCancel)1078 case "click-header":1079 add(tui.ClickHeader)1080 case "click-footer":1081 add(tui.ClickFooter)1082 case "multi":1083 add(tui.Multi)1084 case "alt-enter", "alt-return":1085 evt := tui.CtrlAltKey('m')1086 chords[evt] = key1087 list = append(list, evt)1088 case "alt-space":1089 evt := tui.AltKey(' ')1090 chords[evt] = key1091 list = append(list, evt)1092 case "alt-bs", "alt-bspace", "alt-backspace":1093 add(tui.AltBackspace)1094 case "ctrl-bs", "ctrl-bspace", "ctrl-backspace":1095 add(tui.CtrlBackspace)1096 case "ctrl-alt-bs", "ctrl-alt-bspace", "ctrl-alt-backspace":1097 add(tui.CtrlAltBackspace)1098 case "alt-up":1099 add(tui.AltUp)1100 case "alt-down":1101 add(tui.AltDown)1102 case "alt-left":1103 add(tui.AltLeft)1104 case "alt-right":1105 add(tui.AltRight)1106 case "alt-home":1107 add(tui.AltHome)1108 case "alt-end":1109 add(tui.AltEnd)1110 case "alt-delete":1111 add(tui.AltDelete)1112 case "alt-page-up":1113 add(tui.AltPageUp)1114 case "alt-page-down":1115 add(tui.AltPageDown)1116 case "tab":1117 add(tui.Tab)1118 case "btab", "shift-tab":1119 add(tui.ShiftTab)1120 case "esc":1121 add(tui.Esc)1122 case "delete", "del":1123 add(tui.Delete)1124 case "home":1125 add(tui.Home)1126 case "end":1127 add(tui.End)1128 case "insert":1129 add(tui.Insert)1130 case "pgup", "page-up":1131 add(tui.PageUp)1132 case "pgdn", "page-down":1133 add(tui.PageDown)1134 case "alt-shift-up", "shift-alt-up":1135 add(tui.AltShiftUp)1136 case "alt-shift-down", "shift-alt-down":1137 add(tui.AltShiftDown)1138 case "alt-shift-left", "shift-alt-left":1139 add(tui.AltShiftLeft)1140 case "alt-shift-right", "shift-alt-right":1141 add(tui.AltShiftRight)1142 case "alt-shift-home", "shift-alt-home":1143 add(tui.AltShiftHome)1144 case "alt-shift-end", "shift-alt-end":1145 add(tui.AltShiftEnd)1146 case "alt-shift-delete", "shift-alt-delete":1147 add(tui.AltShiftDelete)1148 case "alt-shift-page-up", "shift-alt-page-up":1149 add(tui.AltShiftPageUp)1150 case "alt-shift-page-down", "shift-alt-page-down":1151 add(tui.AltShiftPageDown)1152 case "ctrl-up":1153 add(tui.CtrlUp)1154 case "ctrl-down":1155 add(tui.CtrlDown)1156 case "ctrl-right":1157 add(tui.CtrlRight)1158 case "ctrl-left":1159 add(tui.CtrlLeft)1160 case "ctrl-home":1161 add(tui.CtrlHome)1162 case "ctrl-end":1163 add(tui.CtrlEnd)1164 case "ctrl-delete":1165 add(tui.CtrlDelete)1166 case "ctrl-page-up":1167 add(tui.CtrlPageUp)1168 case "ctrl-page-down":1169 add(tui.CtrlPageDown)1170 case "ctrl-alt-up", "alt-ctrl-up":1171 add(tui.CtrlAltUp)1172 case "ctrl-alt-down", "alt-ctrl-down":1173 add(tui.CtrlAltDown)1174 case "ctrl-alt-right", "alt-ctrl-right":1175 add(tui.CtrlAltRight)1176 case "ctrl-alt-left", "alt-ctrl-left":1177 add(tui.CtrlAltLeft)1178 case "ctrl-alt-home", "alt-ctrl-home":1179 add(tui.CtrlAltHome)1180 case "ctrl-alt-end", "alt-ctrl-end":1181 add(tui.CtrlAltEnd)1182 case "ctrl-alt-delete", "alt-ctrl-delete":1183 add(tui.CtrlAltDelete)1184 case "ctrl-alt-page-up", "alt-ctrl-page-up":1185 add(tui.CtrlAltPageUp)1186 case "ctrl-alt-page-down", "alt-ctrl-page-down":1187 add(tui.CtrlAltPageDown)1188 case "ctrl-shift-up", "shift-ctrl-up":1189 add(tui.CtrlShiftUp)1190 case "ctrl-shift-down", "shift-ctrl-down":1191 add(tui.CtrlShiftDown)1192 case "ctrl-shift-right", "shift-ctrl-right":1193 add(tui.CtrlShiftRight)1194 case "ctrl-shift-left", "shift-ctrl-left":1195 add(tui.CtrlShiftLeft)1196 case "ctrl-shift-home", "shift-ctrl-home":1197 add(tui.CtrlShiftHome)1198 case "ctrl-shift-end", "shift-ctrl-end":1199 add(tui.CtrlShiftEnd)1200 case "ctrl-shift-delete", "shift-ctrl-delete":1201 add(tui.CtrlShiftDelete)1202 case "ctrl-shift-page-up", "shift-ctrl-page-up":1203 add(tui.CtrlShiftPageUp)1204 case "ctrl-shift-page-down", "shift-ctrl-page-down":1205 add(tui.CtrlShiftPageDown)1206 case "ctrl-alt-shift-up":1207 add(tui.CtrlAltShiftUp)1208 case "ctrl-alt-shift-down":1209 add(tui.CtrlAltShiftDown)1210 case "ctrl-alt-shift-right":1211 add(tui.CtrlAltShiftRight)1212 case "ctrl-alt-shift-left":1213 add(tui.CtrlAltShiftLeft)1214 case "ctrl-alt-shift-home":1215 add(tui.CtrlAltShiftHome)1216 case "ctrl-alt-shift-end":1217 add(tui.CtrlAltShiftEnd)1218 case "ctrl-alt-shift-delete":1219 add(tui.CtrlAltShiftDelete)1220 case "ctrl-alt-shift-page-up":1221 add(tui.CtrlAltShiftPageUp)1222 case "ctrl-alt-shift-page-down":1223 add(tui.CtrlAltShiftPageDown)1224 case "shift-up":1225 add(tui.ShiftUp)1226 case "shift-down":1227 add(tui.ShiftDown)1228 case "shift-left":1229 add(tui.ShiftLeft)1230 case "shift-right":1231 add(tui.ShiftRight)1232 case "shift-home":1233 add(tui.ShiftHome)1234 case "shift-end":1235 add(tui.ShiftEnd)1236 case "shift-delete":1237 add(tui.ShiftDelete)1238 case "shift-page-up":1239 add(tui.ShiftPageUp)1240 case "shift-page-down":1241 add(tui.ShiftPageDown)1242 case "left-click":1243 add(tui.LeftClick)1244 case "right-click":1245 add(tui.RightClick)1246 case "shift-left-click":1247 add(tui.SLeftClick)1248 case "shift-right-click":1249 add(tui.SRightClick)1250 case "double-click":1251 add(tui.DoubleClick)1252 case "scroll-up":1253 add(tui.ScrollUp)1254 case "scroll-down":1255 add(tui.ScrollDown)1256 case "shift-scroll-up":1257 add(tui.SScrollUp)1258 case "shift-scroll-down":1259 add(tui.SScrollDown)1260 case "preview-scroll-up":1261 add(tui.PreviewScrollUp)1262 case "preview-scroll-down":1263 add(tui.PreviewScrollDown)1264 case "f10":1265 add(tui.F10)1266 case "f11":1267 add(tui.F11)1268 case "f12":1269 add(tui.F12)1270 default:1271 runes := []rune(key)Add every(N) bind event and FZF_IDLE_TIME env var (#4797)Junegunn Choibefore adoptionfcc3c6a
lines 1272–1279why, one step back1272 if strings.HasPrefix(lkey, "every(") && strings.HasSuffix(lkey, ")") {1273 evt, err := parseEveryEvent(key[6 : len(key)-1])1274 if err != nil {1275 return nil, list, err1276 }1277 chords[evt] = key1278 list = append(list, evt)1279 } else if len(key) == 10 && strings.HasPrefix(lkey, "ctrl-alt-") && isAlphabet(lkey[9]) {Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1280–1318why, one step back1280 r := rune(lkey[9])1281 evt := tui.CtrlAltKey(r)1282 if r == 'h' && !util.IsWindows() {1283 evt = tui.CtrlAltBackspace.AsEvent()1284 }1285 chords[evt] = key1286 list = append(list, evt)1287 } else if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {1288 evt := tui.EventType(tui.CtrlA.Int() + int(lkey[5]) - 'a')1289 r := rune(lkey[5])1290 if r == 'h' && !util.IsWindows() {1291 evt = tui.CtrlBackspace1292 }1293 add(evt)1294 } else if len(runes) == 5 && strings.HasPrefix(lkey, "alt-") {1295 r := runes[4]1296 switch r {1297 case escapedColon:1298 r = ':'1299 case escapedComma:1300 r = ','1301 case escapedPlus:1302 r = '+'1303 }1304 evt := tui.AltKey(r)1305 chords[evt] = key1306 list = append(list, evt)1307 } else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '9' {1308 add(tui.EventType(tui.F1.Int() + int(key[1]) - '1'))1309 } else if len(runes) == 1 {1310 evt := tui.Key(runes[0])1311 chords[evt] = key1312 list = append(list, evt)1313 } else {1314 return nil, list, errors.New("unsupported key: " + key)1315 }1316 }1317 }1318 return chords, list, nilAdd every(N) bind event and FZF_IDLE_TIME env var (#4797)Junegunn Choibefore adoptionfcc3c6a
lines 1319–1333why, one step back1319}13201321func parseEveryEvent(arg string) (tui.Event, error) {1322 secs, err := strconv.ParseFloat(strings.TrimSpace(arg), 64)1323 if err != nil || math.IsNaN(secs) || math.IsInf(secs, 0) || secs <= 0 {1324 return tui.Event{}, errors.New("every() requires a positive number of seconds")1325 }1326 if secs < 0.01 {1327 secs = 0.011328 }1329 ms := math.Round(secs * 1000)1330 if ms > math.MaxInt32 {1331 return tui.Event{}, errors.New("every() interval is too large")1332 }1333 return tui.Event{Type: tui.Every, Char: rune(int32(ms))}, nilFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1334–1608why, one step back1334}13351336func parseScheme(str string) (string, []criterion, error) {1337 str = strings.ToLower(str)1338 switch str {1339 case "history":1340 return str, []criterion{byScore}, nil1341 case "path":1342 return str, []criterion{byScore, byPathname, byLength}, nil1343 case "default":1344 return str, []criterion{byScore, byLength}, nil1345 }1346 return str, nil, errors.New("invalid scoring scheme: " + str + " (expected: default|path|history)")1347}13481349func parseTiebreak(str string) ([]criterion, error) {1350 criteria := []criterion{byScore}1351 hasIndex := false1352 hasChunk := false1353 hasLength := false1354 hasBegin := false1355 hasEnd := false1356 hasPathname := false1357 check := func(notExpected *bool, name string) error {1358 if *notExpected {1359 return errors.New("duplicate sort criteria: " + name)1360 }1361 if hasIndex {1362 return errors.New("index should be the last criterion")1363 }1364 *notExpected = true1365 return nil1366 }1367 for _, str := range strings.Split(strings.ToLower(str), ",") {1368 switch str {1369 case "index":1370 if err := check(&hasIndex, "index"); err != nil {1371 return nil, err1372 }1373 case "chunk":1374 if err := check(&hasChunk, "chunk"); err != nil {1375 return nil, err1376 }1377 criteria = append(criteria, byChunk)1378 case "pathname":1379 if err := check(&hasPathname, "pathname"); err != nil {1380 return nil, err1381 }1382 criteria = append(criteria, byPathname)1383 case "length":1384 if err := check(&hasLength, "length"); err != nil {1385 return nil, err1386 }1387 criteria = append(criteria, byLength)1388 case "begin":1389 if err := check(&hasBegin, "begin"); err != nil {1390 return nil, err1391 }1392 criteria = append(criteria, byBegin)1393 case "end":1394 if err := check(&hasEnd, "end"); err != nil {1395 return nil, err1396 }1397 criteria = append(criteria, byEnd)1398 default:1399 return nil, errors.New("invalid sort criterion: " + str)1400 }1401 }1402 if len(criteria) > 4 {1403 return nil, errors.New("at most 3 tiebreaks are allowed: " + str)1404 }1405 return criteria, nil1406}14071408func dupeTheme(theme *tui.ColorTheme) *tui.ColorTheme {1409 dupe := *theme1410 return &dupe1411}14121413func parseTheme(defaultTheme *tui.ColorTheme, str string) (*tui.ColorTheme, *tui.ColorTheme, error) {1414 var err error1415 var baseTheme *tui.ColorTheme1416 theme := dupeTheme(defaultTheme)1417 rrggbb := regexp.MustCompile("^#[0-9a-fA-F]{6}$")1418 comma := regexp.MustCompile(`[\s,]+`)1419 for _, str := range comma.Split(strings.ToLower(str), -1) {1420 str = strings.TrimSpace(str)1421 if len(str) == 0 {1422 continue1423 }1424 switch str {1425 case "dark":1426 baseTheme = tui.Dark2561427 theme = dupeTheme(tui.Dark256)1428 case "light":1429 baseTheme = tui.Light2561430 theme = dupeTheme(tui.Light256)1431 case "base16", "16":1432 baseTheme = tui.Default161433 theme = dupeTheme(tui.Default16)1434 case "bw", "no":1435 baseTheme = tui.NoColorTheme1436 theme = dupeTheme(tui.NoColorTheme)1437 default:1438 fail := func() {1439 // Let the code proceed to simplify the error handling1440 err = errors.New("invalid color specification: " + str)1441 }1442 // Color is disabled1443 if theme == nil {1444 continue1445 }14461447 components := strings.Split(str, ":")1448 if len(components) < 2 {1449 fail()1450 }14511452 mergeAttr := func(cattr *tui.ColorAttr) {1453 for _, component := range components[1:] {1454 switch component {1455 case "regular":1456 cattr.Attr = tui.AttrRegular1457 case "bold", "strong":1458 cattr.Attr |= tui.Bold1459 case "dim":1460 cattr.Attr |= tui.Dim1461 case "strip":1462 cattr.Attr |= tui.Strip1463 case "italic":1464 cattr.Attr |= tui.Italic1465 case "underline":1466 cattr.Attr |= tui.Underline1467 case "underline-double":1468 cattr.Attr |= tui.Underline | tui.UlStyleDouble1469 case "underline-curly":1470 cattr.Attr |= tui.Underline | tui.UlStyleCurly1471 case "underline-dotted":1472 cattr.Attr |= tui.Underline | tui.UlStyleDotted1473 case "underline-dashed":1474 cattr.Attr |= tui.Underline | tui.UlStyleDashed1475 case "blink":1476 cattr.Attr |= tui.Blink1477 case "reverse":1478 cattr.Attr |= tui.Reverse1479 case "strikethrough":1480 cattr.Attr |= tui.StrikeThrough1481 case "black":1482 cattr.Color = tui.Color(0)1483 case "red":1484 cattr.Color = tui.Color(1)1485 case "green":1486 cattr.Color = tui.Color(2)1487 case "yellow":1488 cattr.Color = tui.Color(3)1489 case "blue":1490 cattr.Color = tui.Color(4)1491 case "magenta":1492 cattr.Color = tui.Color(5)1493 case "cyan":1494 cattr.Color = tui.Color(6)1495 case "white":1496 cattr.Color = tui.Color(7)1497 case "bright-black", "gray", "grey":1498 cattr.Color = tui.Color(8)1499 case "bright-red":1500 cattr.Color = tui.Color(9)1501 case "bright-green":1502 cattr.Color = tui.Color(10)1503 case "bright-yellow":1504 cattr.Color = tui.Color(11)1505 case "bright-blue":1506 cattr.Color = tui.Color(12)1507 case "bright-magenta":1508 cattr.Color = tui.Color(13)1509 case "bright-cyan":1510 cattr.Color = tui.Color(14)1511 case "bright-white":1512 cattr.Color = tui.Color(15)1513 case "":1514 default:1515 if rrggbb.MatchString(component) {1516 cattr.Color = tui.HexToColor(component)1517 } else {1518 ansi32, err := strconv.Atoi(component)1519 if err != nil || ansi32 < -1 || ansi32 > 255 {1520 fail()1521 }1522 cattr.Color = tui.Color(ansi32)1523 }1524 }1525 }1526 }1527 switch components[0] {1528 case "query", "input", "input-fg":1529 mergeAttr(&theme.Input)1530 case "ghost":1531 mergeAttr(&theme.Ghost)1532 case "disabled":1533 mergeAttr(&theme.Disabled)1534 case "fg":1535 mergeAttr(&theme.Fg)1536 case "bg":1537 mergeAttr(&theme.Bg)1538 case "list-fg":1539 mergeAttr(&theme.ListFg)1540 case "list-bg":1541 mergeAttr(&theme.ListBg)1542 case "preview-fg":1543 mergeAttr(&theme.PreviewFg)1544 case "preview-bg":1545 mergeAttr(&theme.PreviewBg)1546 case "current-fg", "fg+":1547 mergeAttr(&theme.Current)1548 case "current-bg", "bg+":1549 mergeAttr(&theme.DarkBg)1550 case "alt-bg":1551 mergeAttr(&theme.AltBg)1552 case "selected-fg":1553 mergeAttr(&theme.SelectedFg)1554 case "selected-bg":1555 mergeAttr(&theme.SelectedBg)1556 case "nth":1557 mergeAttr(&theme.Nth)1558 case "nomatch":1559 mergeAttr(&theme.Nomatch)1560 case "gutter":1561 mergeAttr(&theme.Gutter)1562 case "alt-gutter":1563 mergeAttr(&theme.AltGutter)1564 case "hl":1565 mergeAttr(&theme.Match)1566 case "current-hl", "hl+":1567 mergeAttr(&theme.CurrentMatch)1568 case "selected-hl":1569 mergeAttr(&theme.SelectedMatch)1570 case "border":1571 mergeAttr(&theme.Border)1572 case "preview-border":1573 mergeAttr(&theme.PreviewBorder)1574 case "separator":1575 mergeAttr(&theme.Separator)1576 case "scrollbar":1577 mergeAttr(&theme.Scrollbar)1578 case "preview-scrollbar":1579 mergeAttr(&theme.PreviewScrollbar)1580 case "label":1581 mergeAttr(&theme.BorderLabel)1582 case "list-label":1583 mergeAttr(&theme.ListLabel)1584 case "list-border":1585 mergeAttr(&theme.ListBorder)1586 case "preview-label":1587 mergeAttr(&theme.PreviewLabel)1588 case "prompt":1589 mergeAttr(&theme.Prompt)1590 case "input-bg":1591 mergeAttr(&theme.InputBg)1592 case "input-border":1593 mergeAttr(&theme.InputBorder)1594 case "input-label":1595 mergeAttr(&theme.InputLabel)1596 case "header-border":1597 mergeAttr(&theme.HeaderBorder)1598 case "header-label":1599 mergeAttr(&theme.HeaderLabel)1600 case "footer-border":1601 mergeAttr(&theme.FooterBorder)1602 case "footer-label":1603 mergeAttr(&theme.FooterLabel)1604 case "spinner":1605 mergeAttr(&theme.Spinner)1606 case "info":1607 mergeAttr(&theme.Info)1608 case "pointer":Rename internal variables to match user-facing namesJunegunn Choibefore adoptionf783582
line 1609why, one step back1609 mergeAttr(&theme.Pointer)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1610–1654why, one step back1610 case "marker":1611 mergeAttr(&theme.Marker)1612 case "header", "header-fg":1613 mergeAttr(&theme.Header)1614 case "header-bg":1615 mergeAttr(&theme.HeaderBg)1616 case "footer", "footer-fg":1617 mergeAttr(&theme.Footer)1618 case "footer-bg":1619 mergeAttr(&theme.FooterBg)1620 case "gap-line":1621 mergeAttr(&theme.GapLine)1622 default:1623 fail()1624 }1625 }1626 }1627 return baseTheme, theme, err1628}16291630func parseWalkerOpts(str string) (walkerOpts, error) {1631 opts := walkerOpts{}1632 for _, str := range strings.Split(strings.ToLower(str), ",") {1633 switch str {1634 case "file":1635 opts.file = true1636 case "dir":1637 opts.dir = true1638 case "hidden":1639 opts.hidden = true1640 case "follow":1641 opts.follow = true1642 case "":1643 // Ignored1644 default:1645 return opts, errors.New("invalid walker option: " + str)1646 }1647 }1648 if !opts.file && !opts.dir {1649 return opts, errors.New("at least one of 'file' or 'dir' should be specified")1650 }1651 return opts, nil1652}16531654var (Add field-based tracking across reloads (--track=NTH)Junegunn Choibefore adoption9f42285
line 1655why, one step back1655 argActionRegexp *regexp.RegexpFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1656–1673why, one step back1656 splitRegexp *regexp.Regexp1657 actionNameRegexp *regexp.Regexp1658)16591660func firstKey(keymap map[tui.Event]string) tui.Event {1661 for k := range keymap {1662 return k1663 }1664 return tui.EventType(0).AsEvent()1665}16661667const (1668 escapedColon = 01669 escapedComma = 11670 escapedPlus = 21671)16721673func init() {Add field-based tracking across reloads (--track=NTH)Junegunn Choibefore adoption9f42285
line 1674why, one step back1674 argActionRegexp = regexp.MustCompile(Replace --track=NTH with --id-nth for cross-reload item identityJunegunn Choibefore adoptionb5f7221
line 1675why, one step back1675 `(?si)[:+](become|execute(?:-multi|-silent)?|reload(?:-sync)?|preview|(?:change|bg-transform|transform)-(?:query|prompt|(?:border|list|preview|input|header|footer)-label|header-lines|header|footer|search|with-nth|nth|pointer|ghost)|bg-transform|transform|change-(?:preview-window|preview|multi)|(?:re|un|toggle-)bind|pos|put|print|search|trigger)`)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1676–1683why, one step back1676 splitRegexp = regexp.MustCompile("[,:]+")1677 actionNameRegexp = regexp.MustCompile("(?i)^[a-z-]+")1678}16791680func maskActionContents(action string) string {1681 masked := ""1682Loop:1683 for len(action) > 0 {Add field-based tracking across reloads (--track=NTH)Junegunn Choibefore adoption9f42285
line 1684why, one step back1684 loc := argActionRegexp.FindStringIndex(action)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1685–1737why, one step back1685 if loc == nil {1686 masked += action1687 break1688 }1689 masked += action[:loc[1]]1690 action = action[loc[1]:]1691 if len(action) == 0 {1692 break1693 }1694 cs := string(action[0])1695 var ce string1696 switch action[0] {1697 case ':':1698 masked += strings.Repeat(" ", len(action))1699 break Loop1700 case '(':1701 ce = ")"1702 case '{':1703 ce = "}"1704 case '[':1705 ce = "]"1706 case '<':1707 ce = ">"1708 case '~', '!', '@', '#', '$', '%', '^', '&', '*', ';', '/', '|':1709 ce = string(cs)1710 default:1711 continue1712 }1713 cs = regexp.QuoteMeta(cs)1714 ce = regexp.QuoteMeta(ce)17151716 // @$ or @+1717 loc = regexp.MustCompile(fmt.Sprintf(`(?s)^%s.*?(%s[+,]|%s$)`, cs, ce, ce)).FindStringIndex(action)1718 if loc == nil {1719 masked += action1720 break1721 }1722 // Keep + or , at the end1723 lastChar := action[loc[1]-1]1724 if lastChar == '+' || lastChar == ',' {1725 loc[1]--1726 }1727 masked += strings.Repeat(" ", loc[1])1728 action = action[loc[1]:]1729 }1730 masked = strings.ReplaceAll(masked, ",,,", string([]rune{',', escapedComma, ','}))1731 masked = strings.ReplaceAll(masked, ",:,", string([]rune{',', escapedColon, ','}))1732 masked = strings.ReplaceAll(masked, "::", string([]rune{escapedColon, ':'}))1733 masked = strings.ReplaceAll(masked, ",:", string([]rune{escapedComma, ':'}))1734 masked = strings.ReplaceAll(masked, "+:", string([]rune{escapedPlus, ':'}))1735 return masked1736}1737Allow bare put action in transform outputJunegunn Choibefore adoptionae78a5c
line 1738why, one step back1738func parseSingleActionList(str string, putAllowed bool) ([]*action, error) {Add field-based tracking across reloads (--track=NTH)Junegunn Choibefore adoption9f42285
line 1739why, one step back1739 // We prepend a colon to satisfy argActionRegexp and remove it laterFix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
line 1740why, one step back1740 masked := maskActionContents(":" + str)[1:]Allow bare put action in transform outputJunegunn Choibefore adoptionae78a5c
line 1741why, one step back1741 return parseActionList(masked, str, []*action{}, putAllowed)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1742–1960why, one step back1742}17431744func parseActionList(masked string, original string, prevActions []*action, putAllowed bool) ([]*action, error) {1745 maskedStrings := strings.Split(masked, "+")1746 originalStrings := make([]string, len(maskedStrings))1747 idx := 01748 for i, maskedString := range maskedStrings {1749 originalStrings[i] = original[idx : idx+len(maskedString)]1750 idx += len(maskedString) + 11751 }1752 actions := make([]*action, 0, len(maskedStrings))1753 appendAction := func(types ...actionType) {1754 actions = append(actions, toActions(types...)...)1755 }1756 prevSpec := ""1757 for specIndex, spec := range originalStrings {1758 spec = prevSpec + spec1759 specLower := strings.ToLower(spec)1760 switch specLower {1761 case "ignore":1762 appendAction(actIgnore)1763 case "beginning-of-line":1764 appendAction(actBeginningOfLine)1765 case "abort":1766 appendAction(actAbort)1767 case "accept":1768 appendAction(actAccept)1769 case "accept-non-empty":1770 appendAction(actAcceptNonEmpty)1771 case "accept-or-print-query":1772 appendAction(actAcceptOrPrintQuery)1773 case "print-query":1774 appendAction(actPrintQuery)1775 case "refresh-preview":1776 appendAction(actRefreshPreview)1777 case "replace-query":1778 appendAction(actReplaceQuery)1779 case "backward-char":1780 appendAction(actBackwardChar)1781 case "backward-delete-char":1782 appendAction(actBackwardDeleteChar)1783 case "backward-delete-char/eof":1784 appendAction(actBackwardDeleteCharEof)1785 case "backward-word":1786 appendAction(actBackwardWord)1787 case "backward-subword":1788 appendAction(actBackwardSubWord)1789 case "clear-screen":1790 appendAction(actClearScreen)1791 case "delete-char":1792 appendAction(actDeleteChar)1793 case "delete-char/eof":1794 appendAction(actDeleteCharEof)1795 case "deselect":1796 appendAction(actDeselect)1797 case "end-of-line":1798 appendAction(actEndOfLine)1799 case "cancel":1800 appendAction(actCancel)1801 case "clear-query":1802 appendAction(actClearQuery)1803 case "clear-multi", "clear-selection":1804 appendAction(actClearSelection)1805 case "forward-char":1806 appendAction(actForwardChar)1807 case "forward-word":1808 appendAction(actForwardWord)1809 case "forward-subword":1810 appendAction(actForwardSubWord)1811 case "jump":1812 appendAction(actJump)1813 case "jump-accept":1814 appendAction(actJumpAccept)1815 case "kill-line":1816 appendAction(actKillLine)1817 case "kill-word":1818 appendAction(actKillWord)1819 case "kill-subword":1820 appendAction(actKillSubWord)1821 case "unix-line-discard", "line-discard":1822 appendAction(actUnixLineDiscard)1823 case "unix-word-rubout", "word-rubout":1824 appendAction(actUnixWordRubout)1825 case "yank":1826 appendAction(actYank)1827 case "backward-kill-word":1828 appendAction(actBackwardKillWord)1829 case "backward-kill-subword":1830 appendAction(actBackwardKillSubWord)1831 case "toggle-down":1832 appendAction(actToggle, actDown)1833 case "toggle-up":1834 appendAction(actToggle, actUp)1835 case "toggle-in":1836 appendAction(actToggleIn)1837 case "toggle-out":1838 appendAction(actToggleOut)1839 case "toggle-all":1840 appendAction(actToggleAll)1841 case "toggle-search":1842 appendAction(actToggleSearch)1843 case "toggle-track":1844 appendAction(actToggleTrack)1845 case "toggle-track-current":1846 appendAction(actToggleTrackCurrent)1847 case "toggle-input":1848 appendAction(actToggleInput)1849 case "hide-input":1850 appendAction(actHideInput)1851 case "show-input":1852 appendAction(actShowInput)1853 case "toggle-header":1854 appendAction(actToggleHeader)1855 case "toggle-wrap":1856 appendAction(actToggleWrap)1857 case "toggle-wrap-word":1858 appendAction(actToggleWrapWord)1859 case "toggle-multi-line":1860 appendAction(actToggleMultiLine)1861 case "toggle-hscroll":1862 appendAction(actToggleHscroll)1863 case "toggle-raw":1864 appendAction(actToggleRaw)1865 case "enable-raw":1866 appendAction(actEnableRaw)1867 case "disable-raw":1868 appendAction(actDisableRaw)1869 case "show-header":1870 appendAction(actShowHeader)1871 case "hide-header":1872 appendAction(actHideHeader)1873 case "track", "track-current":1874 appendAction(actTrackCurrent)1875 case "untrack-current":1876 appendAction(actUntrackCurrent)1877 case "select":1878 appendAction(actSelect)1879 case "select-all":1880 appendAction(actSelectAll)1881 case "deselect-all":1882 appendAction(actDeselectAll)1883 case "close":1884 appendAction(actClose)1885 case "toggle":1886 appendAction(actToggle)1887 case "down":1888 appendAction(actDown)1889 case "down-match":1890 appendAction(actDownMatch)1891 case "up":1892 appendAction(actUp)1893 case "up-match":1894 appendAction(actUpMatch)1895 case "first", "top":1896 appendAction(actFirst)1897 case "last":1898 appendAction(actLast)1899 case "best":1900 appendAction(actBest)1901 case "page-up":1902 appendAction(actPageUp)1903 case "page-down":1904 appendAction(actPageDown)1905 case "half-page-up":1906 appendAction(actHalfPageUp)1907 case "half-page-down":1908 appendAction(actHalfPageDown)1909 case "prev-history", "previous-history":1910 appendAction(actPrevHistory)1911 case "next-history":1912 appendAction(actNextHistory)1913 case "up-selected", "prev-selected":1914 appendAction(actPrevSelected)1915 case "down-selected", "next-selected":1916 appendAction(actNextSelected)1917 case "show-preview":1918 appendAction(actShowPreview)1919 case "hide-preview":1920 appendAction(actHidePreview)1921 case "toggle-preview":1922 appendAction(actTogglePreview)1923 case "toggle-preview-wrap":1924 appendAction(actTogglePreviewWrap)1925 case "toggle-preview-wrap-word":1926 appendAction(actTogglePreviewWrapWord)1927 case "toggle-sort":1928 appendAction(actToggleSort)1929 case "offset-up":1930 appendAction(actOffsetUp)1931 case "offset-down":1932 appendAction(actOffsetDown)1933 case "offset-middle":1934 appendAction(actOffsetMiddle)1935 case "preview-top":1936 appendAction(actPreviewTop)1937 case "preview-bottom":1938 appendAction(actPreviewBottom)1939 case "preview-up":1940 appendAction(actPreviewUp)1941 case "preview-down":1942 appendAction(actPreviewDown)1943 case "preview-page-up":1944 appendAction(actPreviewPageUp)1945 case "preview-page-down":1946 appendAction(actPreviewPageDown)1947 case "preview-half-page-up":1948 appendAction(actPreviewHalfPageUp)1949 case "preview-half-page-down":1950 appendAction(actPreviewHalfPageDown)1951 case "enable-search":1952 appendAction(actEnableSearch)1953 case "disable-search":1954 appendAction(actDisableSearch)1955 case "put":1956 if putAllowed {1957 appendAction(actChar)1958 } else {1959 return nil, errors.New("unable to put non-printable character")1960 }Add 'wait' action to block until search completion (#4825)Junegunn Choibefore adoption8ec443b
lines 1961–1962why, one step back1961 case "wait":1962 appendAction(actWait)Fix --no-sort jumpiness by merging results in index orderJunegunn Choibefore adoption7a811f0
lines 1963–2048why, one step back1963 case "bell":1964 appendAction(actBell)1965 case "exclude":1966 appendAction(actExclude)1967 case "exclude-multi":1968 appendAction(actExcludeMulti)1969 case "bg-cancel":1970 appendAction(actBgCancel)1971 default:1972 t := isExecuteAction(specLower)1973 if t == actIgnore {1974 if specIndex == 0 && specLower == "" {1975 actions = append(prevActions, actions...)1976 } else if specLower == "change-multi" {1977 appendAction(actChangeMulti)1978 } else {1979 return nil, errors.New("unknown action: " + spec)1980 }1981 } else {1982 offset := len(actionNameRegexp.FindString(spec))1983 var actionArg string1984 if spec[offset] == ':' {1985 if specIndex == len(originalStrings)-1 {1986 actionArg = spec[offset+1:]1987 actions = append(actions, &action{t: t, a: actionArg})1988 } else {1989 prevSpec = spec + "+"1990 continue1991 }1992 } else {1993 actionArg = spec[offset+1 : len(spec)-1]1994 actions = append(actions, &action{t: t, a: actionArg})1995 }1996 switch t {1997 case actUnbind, actRebind, actToggleBind:1998 if _, _, err := parseKeyChords(actionArg, spec[0:offset]+" target required"); err != nil {1999 return nil, err2000 }The first 2,000 of 3,997 lines.