Skip to content
Myr

options.go

This file

Path

src/options.go

1,567 lines · 41.7 KiB · Go

Last changed by

Fix handling of arrow keys with alt and/or shift modifierJunegunn Choibefore adoption3fe8eee

History of this file

Take it

1package fzf23import (4	"fmt"5	"os"6	"regexp"7	"strconv"8	"strings"9	"unicode"10	"unicode/utf8"1112	"github.com/junegunn/fzf/src/algo"13	"github.com/junegunn/fzf/src/tui"1415	"github.com/mattn/go-runewidth"16	"github.com/mattn/go-shellwords"17)1819const usage = `usage: fzf [options]2021  Search22    -x, --extended        Extended-search mode23                          (enabled by default; +x or --no-extended to disable)24    -e, --exact           Enable Exact-match25    --algo=TYPE           Fuzzy matching algorithm: [v1|v2] (default: v2)26    -i                    Case-insensitive match (default: smart-case match)27    +i                    Case-sensitive match28    --literal             Do not normalize latin script letters before matching29    -n, --nth=N[,..]      Comma-separated list of field index expressions30                          for limiting search scope. Each can be a non-zero31                          integer or a range expression ([BEGIN]..[END]).32    --with-nth=N[,..]     Transform the presentation of each line using33                          field index expressions34    -d, --delimiter=STR   Field delimiter regex (default: AWK-style)35    +s, --no-sort         Do not sort the result36    --tac                 Reverse the order of the input37    --phony               Do not perform search38    --tiebreak=CRI[,..]   Comma-separated list of sort criteria to apply39                          when the scores are tied [length|begin|end|index]40                          (default: length)4142  Interface43    -m, --multi[=MAX]     Enable multi-select with tab/shift-tab44    --no-mouse            Disable mouse45    --bind=KEYBINDS       Custom key bindings. Refer to the man page.46    --cycle               Enable cyclic scroll47    --keep-right          Keep the right end of the line visible on overflow48    --no-hscroll          Disable horizontal scroll49    --hscroll-off=COL     Number of screen columns to keep to the right of the50                          highlighted substring (default: 10)51    --filepath-word       Make word-wise movements respect path separators52    --jump-labels=CHARS   Label characters for jump and jump-accept5354  Layout55    --height=HEIGHT[%]    Display fzf window below the cursor with the given56                          height instead of using fullscreen57    --min-height=HEIGHT   Minimum height when --height is given in percent58                          (default: 10)59    --layout=LAYOUT       Choose layout: [default|reverse|reverse-list]60    --border[=STYLE]      Draw border around the finder61                          [rounded|sharp|horizontal|vertical|62                           top|bottom|left|right] (default: rounded)63    --margin=MARGIN       Screen margin (TRBL | TB,RL | T,RL,B | T,R,B,L)64    --padding=PADDING     Padding inside border (TRBL | TB,RL | T,RL,B | T,R,B,L)65    --info=STYLE          Finder info style [default|inline|hidden]66    --prompt=STR          Input prompt (default: '> ')67    --pointer=STR         Pointer to the current line (default: '>')68    --marker=STR          Multi-select marker (default: '>')69    --header=STR          String to print as header70    --header-lines=N      The first N lines of the input are treated as header7172  Display73    --ansi                Enable processing of ANSI color codes74    --tabstop=SPACES      Number of spaces for a tab character (default: 8)75    --color=COLSPEC       Base scheme (dark|light|16|bw) and/or custom colors76    --no-bold             Do not use bold text7778  History79    --history=FILE        History file80    --history-size=N      Maximum number of history entries (default: 1000)8182  Preview83    --preview=COMMAND     Command to preview highlighted line ({})84    --preview-window=OPT  Preview window layout (default: right:50%)85                          [up|down|left|right][:SIZE[%]]86                          [:[no]wrap][:[no]cycle][:[no]hidden]87                          [:rounded|sharp|noborder]88                          [:+SCROLL[-OFFSET]]89                          [:default]9091  Scripting92    -q, --query=STR       Start the finder with the given query93    -1, --select-1        Automatically select the only match94    -0, --exit-0          Exit immediately when there's no match95    -f, --filter=STR      Filter mode. Do not start interactive finder.96    --print-query         Print query as the first line97    --expect=KEYS         Comma-separated list of keys to complete fzf98    --read0               Read input delimited by ASCII NUL characters99    --print0              Print output delimited by ASCII NUL characters100    --sync                Synchronous search for multi-staged filtering101    --version             Display version information and exit102103  Environment variables104    FZF_DEFAULT_COMMAND   Default command to use when input is tty105    FZF_DEFAULT_OPTS      Default options106                          (e.g. '--layout=reverse --inline-info')107108`109110// Case denotes case-sensitivity of search111type Case int112113// Case-sensitivities114const (115	CaseSmart Case = iota116	CaseIgnore117	CaseRespect118)119120// Sort criteria121type criterion int122123const (124	byScore criterion = iota125	byLength126	byBegin127	byEnd128)129130type sizeSpec struct {131	size    float64132	percent bool133}134135func defaultMargin() [4]sizeSpec {136	return [4]sizeSpec{}137}138139type windowPosition int140141const (142	posUp windowPosition = iota143	posDown144	posLeft145	posRight146)147148type layoutType int149150const (151	layoutDefault layoutType = iota152	layoutReverse153	layoutReverseList154)155156type infoStyle int157158const (159	infoDefault infoStyle = iota160	infoInline161	infoHidden162)163164type previewOpts struct {165	command  string166	position windowPosition167	size     sizeSpec168	scroll   string169	hidden   bool170	wrap     bool171	cycle    bool172	border   tui.BorderShape173}174175// Options stores the values of command-line options176type Options struct {177	Fuzzy       bool178	FuzzyAlgo   algo.Algo179	Extended    bool180	Phony       bool181	Case        Case182	Normalize   bool183	Nth         []Range184	WithNth     []Range185	Delimiter   Delimiter186	Sort        int187	Tac         bool188	Criteria    []criterion189	Multi       int190	Ansi        bool191	Mouse       bool192	Theme       *tui.ColorTheme193	Black       bool194	Bold        bool195	Height      sizeSpec196	MinHeight   int197	Layout      layoutType198	Cycle       bool199	KeepRight   bool200	Hscroll     bool201	HscrollOff  int202	FileWord    bool203	InfoStyle   infoStyle204	JumpLabels  string205	Prompt      string206	Pointer     string207	Marker      string208	Query       string209	Select1     bool210	Exit0       bool211	Filter      *string212	ToggleSort  bool213	Expect      map[int]string214	Keymap      map[int][]action215	Preview     previewOpts216	PrintQuery  bool217	ReadZero    bool218	Printer     func(string)219	PrintSep    string220	Sync        bool221	History     *History222	Header      []string223	HeaderLines int224	Margin      [4]sizeSpec225	Padding     [4]sizeSpec226	BorderShape tui.BorderShape227	Unicode     bool228	Tabstop     int229	ClearOnExit bool230	Version     bool231}232233func defaultPreviewOpts(command string) previewOpts {234	return previewOpts{command, posRight, sizeSpec{50, true}, "", false, false, false, tui.BorderRounded}235}236237func defaultOptions() *Options {238	return &Options{239		Fuzzy:       true,240		FuzzyAlgo:   algo.FuzzyMatchV2,241		Extended:    true,242		Phony:       false,243		Case:        CaseSmart,244		Normalize:   true,245		Nth:         make([]Range, 0),246		WithNth:     make([]Range, 0),247		Delimiter:   Delimiter{},248		Sort:        1000,249		Tac:         false,250		Criteria:    []criterion{byScore, byLength},251		Multi:       0,252		Ansi:        false,253		Mouse:       true,254		Theme:       tui.EmptyTheme(),255		Black:       false,256		Bold:        true,257		MinHeight:   10,258		Layout:      layoutDefault,259		Cycle:       false,260		KeepRight:   false,261		Hscroll:     true,262		HscrollOff:  10,263		FileWord:    false,264		InfoStyle:   infoDefault,265		JumpLabels:  defaultJumpLabels,266		Prompt:      "> ",267		Pointer:     ">",268		Marker:      ">",269		Query:       "",270		Select1:     false,271		Exit0:       false,272		Filter:      nil,273		ToggleSort:  false,274		Expect:      make(map[int]string),275		Keymap:      make(map[int][]action),276		Preview:     defaultPreviewOpts(""),277		PrintQuery:  false,278		ReadZero:    false,279		Printer:     func(str string) { fmt.Println(str) },280		PrintSep:    "\n",281		Sync:        false,282		History:     nil,283		Header:      make([]string, 0),284		HeaderLines: 0,285		Margin:      defaultMargin(),286		Padding:     defaultMargin(),287		Unicode:     true,288		Tabstop:     8,289		ClearOnExit: true,290		Version:     false}291}292293func help(code int) {294	os.Stdout.WriteString(usage)295	os.Exit(code)296}297298func errorExit(msg string) {299	os.Stderr.WriteString(msg + "\n")300	os.Exit(exitError)301}302303func optString(arg string, prefixes ...string) (bool, string) {304	for _, prefix := range prefixes {305		if strings.HasPrefix(arg, prefix) {306			return true, arg[len(prefix):]307		}308	}309	return false, ""310}311312func nextString(args []string, i *int, message string) string {313	if len(args) > *i+1 {314		*i++315	} else {316		errorExit(message)317	}318	return args[*i]319}320321func optionalNextString(args []string, i *int) (bool, string) {322	if len(args) > *i+1 && !strings.HasPrefix(args[*i+1], "-") && !strings.HasPrefix(args[*i+1], "+") {323		*i++324		return true, args[*i]325	}326	return false, ""327}328329func atoi(str string) int {330	num, err := strconv.Atoi(str)331	if err != nil {332		errorExit("not a valid integer: " + str)333	}334	return num335}336337func atof(str string) float64 {338	num, err := strconv.ParseFloat(str, 64)339	if err != nil {340		errorExit("not a valid number: " + str)341	}342	return num343}344345func nextInt(args []string, i *int, message string) int {346	if len(args) > *i+1 {347		*i++348	} else {349		errorExit(message)350	}351	return atoi(args[*i])352}353354func optionalNumeric(args []string, i *int, defaultValue int) int {355	if len(args) > *i+1 {356		if strings.IndexAny(args[*i+1], "0123456789") == 0 {357			*i++358			return atoi(args[*i])359		}360	}361	return defaultValue362}363364func splitNth(str string) []Range {365	if match, _ := regexp.MatchString("^[0-9,-.]+$", str); !match {366		errorExit("invalid format: " + str)367	}368369	tokens := strings.Split(str, ",")370	ranges := make([]Range, len(tokens))371	for idx, s := range tokens {372		r, ok := ParseRange(&s)373		if !ok {374			errorExit("invalid format: " + str)375		}376		ranges[idx] = r377	}378	return ranges379}380381func delimiterRegexp(str string) Delimiter {382	// Special handling of \t383	str = strings.Replace(str, "\\t", "\t", -1)384385	// 1. Pattern does not contain any special character386	if regexp.QuoteMeta(str) == str {387		return Delimiter{str: &str}388	}389390	rx, e := regexp.Compile(str)391	// 2. Pattern is not a valid regular expression392	if e != nil {393		return Delimiter{str: &str}394	}395396	// 3. Pattern as regular expression. Slow.397	return Delimiter{regex: rx}398}399400func isAlphabet(char uint8) bool {401	return char >= 'a' && char <= 'z'402}403404func isNumeric(char uint8) bool {405	return char >= '0' && char <= '9'406}407408func parseAlgo(str string) algo.Algo {409	switch str {410	case "v1":411		return algo.FuzzyMatchV1412	case "v2":413		return algo.FuzzyMatchV2414	default:415		errorExit("invalid algorithm (expected: v1 or v2)")416	}417	return algo.FuzzyMatchV2418}419420func parseBorder(str string, optional bool) tui.BorderShape {421	switch str {422	case "rounded":423		return tui.BorderRounded424	case "sharp":425		return tui.BorderSharp426	case "horizontal":427		return tui.BorderHorizontal428	case "vertical":429		return tui.BorderVertical430	case "top":431		return tui.BorderTop432	case "bottom":433		return tui.BorderBottom434	case "left":435		return tui.BorderLeft436	case "right":437		return tui.BorderRight438	default:439		if optional && str == "" {440			return tui.BorderRounded441		}442		errorExit("invalid border style (expected: rounded|sharp|horizontal|vertical|top|bottom|left|right)")443	}444	return tui.BorderNone445}446447func parseKeyChords(str string, message string) map[int]string {448	if len(str) == 0 {449		errorExit(message)450	}451452	tokens := strings.Split(str, ",")453	if str == "," || strings.HasPrefix(str, ",,") || strings.HasSuffix(str, ",,") || strings.Contains(str, ",,,") {454		tokens = append(tokens, ",")455	}456457	chords := make(map[int]string)458	for _, key := range tokens {459		if len(key) == 0 {460			continue // ignore461		}462		lkey := strings.ToLower(key)463		chord := 0464		switch lkey {465		case "up":466			chord = tui.Up467		case "down":468			chord = tui.Down469		case "left":470			chord = tui.Left471		case "right":472			chord = tui.Right473		case "enter", "return":474			chord = tui.CtrlM475		case "space":476			chord = tui.AltZ + int(' ')477		case "bspace", "bs":478			chord = tui.BSpace479		case "ctrl-space":480			chord = tui.CtrlSpace481		case "ctrl-^", "ctrl-6":482			chord = tui.CtrlCaret483		case "ctrl-/", "ctrl-_":484			chord = tui.CtrlSlash485		case "ctrl-\\":486			chord = tui.CtrlBackSlash487		case "ctrl-]":488			chord = tui.CtrlRightBracket489		case "change":490			chord = tui.Change491		case "backward-eof":492			chord = tui.BackwardEOF493		case "alt-enter", "alt-return":494			chord = tui.CtrlAltM495		case "alt-space":496			chord = tui.AltSpace497		case "alt-/":498			chord = tui.AltSlash499		case "alt-bs", "alt-bspace":500			chord = tui.AltBS501		case "alt-up":502			chord = tui.AltUp503		case "alt-down":504			chord = tui.AltDown505		case "alt-left":506			chord = tui.AltLeft507		case "alt-right":508			chord = tui.AltRight509		case "tab":510			chord = tui.Tab511		case "btab", "shift-tab":512			chord = tui.BTab513		case "esc":514			chord = tui.ESC515		case "del":516			chord = tui.Del517		case "home":518			chord = tui.Home519		case "end":520			chord = tui.End521		case "insert":522			chord = tui.Insert523		case "pgup", "page-up":524			chord = tui.PgUp525		case "pgdn", "page-down":526			chord = tui.PgDn527		case "alt-shift-up", "shift-alt-up":528			chord = tui.AltSUp529		case "alt-shift-down", "shift-alt-down":530			chord = tui.AltSDown531		case "alt-shift-left", "shift-alt-left":532			chord = tui.AltSLeft533		case "alt-shift-right", "shift-alt-right":534			chord = tui.AltSRight535		case "shift-up":536			chord = tui.SUp537		case "shift-down":538			chord = tui.SDown539		case "shift-left":540			chord = tui.SLeft541		case "shift-right":542			chord = tui.SRight543		case "left-click":544			chord = tui.LeftClick545		case "right-click":546			chord = tui.RightClick547		case "double-click":548			chord = tui.DoubleClick549		case "f10":550			chord = tui.F10551		case "f11":552			chord = tui.F11553		case "f12":554			chord = tui.F12555		default:556			if len(key) == 10 && strings.HasPrefix(lkey, "ctrl-alt-") && isAlphabet(lkey[9]) {557				chord = tui.CtrlAltA + int(lkey[9]) - 'a'558			} else if len(key) == 6 && strings.HasPrefix(lkey, "ctrl-") && isAlphabet(lkey[5]) {559				chord = tui.CtrlA + int(lkey[5]) - 'a'560			} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isAlphabet(lkey[4]) {561				chord = tui.AltA + int(lkey[4]) - 'a'562			} else if len(key) == 5 && strings.HasPrefix(lkey, "alt-") && isNumeric(lkey[4]) {563				chord = tui.Alt0 + int(lkey[4]) - '0'564			} else if len(key) == 2 && strings.HasPrefix(lkey, "f") && key[1] >= '1' && key[1] <= '9' {565				chord = tui.F1 + int(key[1]) - '1'566			} else if utf8.RuneCountInString(key) == 1 {567				chord = tui.AltZ + int([]rune(key)[0])568			} else {569				errorExit("unsupported key: " + key)570			}571		}572		if chord > 0 {573			chords[chord] = key574		}575	}576	return chords577}578579func parseTiebreak(str string) []criterion {580	criteria := []criterion{byScore}581	hasIndex := false582	hasLength := false583	hasBegin := false584	hasEnd := false585	check := func(notExpected *bool, name string) {586		if *notExpected {587			errorExit("duplicate sort criteria: " + name)588		}589		if hasIndex {590			errorExit("index should be the last criterion")591		}592		*notExpected = true593	}594	for _, str := range strings.Split(strings.ToLower(str), ",") {595		switch str {596		case "index":597			check(&hasIndex, "index")598		case "length":599			check(&hasLength, "length")600			criteria = append(criteria, byLength)601		case "begin":602			check(&hasBegin, "begin")603			criteria = append(criteria, byBegin)604		case "end":605			check(&hasEnd, "end")606			criteria = append(criteria, byEnd)607		default:608			errorExit("invalid sort criterion: " + str)609		}610	}611	return criteria612}613614func dupeTheme(theme *tui.ColorTheme) *tui.ColorTheme {615	dupe := *theme616	return &dupe617}618619func parseTheme(defaultTheme *tui.ColorTheme, str string) *tui.ColorTheme {620	theme := dupeTheme(defaultTheme)621	rrggbb := regexp.MustCompile("^#[0-9a-fA-F]{6}$")622	for _, str := range strings.Split(strings.ToLower(str), ",") {623		switch str {624		case "dark":625			theme = dupeTheme(tui.Dark256)626		case "light":627			theme = dupeTheme(tui.Light256)628		case "16":629			theme = dupeTheme(tui.Default16)630		case "bw", "no":631			theme = tui.NoColorTheme()632		default:633			fail := func() {634				errorExit("invalid color specification: " + str)635			}636			// Color is disabled637			if theme == nil {638				continue639			}640641			components := strings.Split(str, ":")642			if len(components) < 2 {643				fail()644			}645646			cattr := tui.NewColorAttr()647			for _, component := range components[1:] {648				switch component {649				case "regular":650					cattr.Attr = tui.AttrRegular651				case "bold", "strong":652					cattr.Attr |= tui.Bold653				case "dim":654					cattr.Attr |= tui.Dim655				case "italic":656					cattr.Attr |= tui.Italic657				case "underline":658					cattr.Attr |= tui.Underline659				case "blink":660					cattr.Attr |= tui.Blink661				case "reverse":662					cattr.Attr |= tui.Reverse663				case "":664				default:665					if rrggbb.MatchString(component) {666						cattr.Color = tui.HexToColor(component)667					} else {668						ansi32, err := strconv.Atoi(component)669						if err != nil || ansi32 < -1 || ansi32 > 255 {670							fail()671						}672						cattr.Color = tui.Color(ansi32)673					}674				}675			}676			switch components[0] {677			case "input":678				theme.Input = cattr679			case "fg":680				theme.Fg = cattr681			case "bg":682				theme.Bg = cattr683			case "preview-fg":684				theme.PreviewFg = cattr685			case "preview-bg":686				theme.PreviewBg = cattr687			case "fg+":688				theme.Current = cattr689			case "bg+":690				theme.DarkBg = cattr691			case "gutter":692				theme.Gutter = cattr693			case "hl":694				theme.Match = cattr695			case "hl+":696				theme.CurrentMatch = cattr697			case "border":698				theme.Border = cattr699			case "prompt":700				theme.Prompt = cattr701			case "spinner":702				theme.Spinner = cattr703			case "info":704				theme.Info = cattr705			case "pointer":706				theme.Cursor = cattr707			case "marker":708				theme.Selected = cattr709			case "header":710				theme.Header = cattr711			default:712				fail()713			}714		}715	}716	return theme717}718719var executeRegexp *regexp.Regexp720721func firstKey(keymap map[int]string) int {722	for k := range keymap {723		return k724	}725	return 0726}727728const (729	escapedColon = 0730	escapedComma = 1731	escapedPlus  = 2732)733734func init() {735	// Backreferences are not supported.736	// "~!@#$%^&*;/|".each_char.map { |c| Regexp.escape(c) }.map { |c| "#{c}[^#{c}]*#{c}" }.join('|')737	executeRegexp = regexp.MustCompile(738		`(?si)[:+](execute(?:-multi|-silent)?|reload|preview):.+|[:+](execute(?:-multi|-silent)?|reload|preview)(\([^)]*\)|\[[^\]]*\]|~[^~]*~|![^!]*!|@[^@]*@|\#[^\#]*\#|\$[^\$]*\$|%[^%]*%|\^[^\^]*\^|&[^&]*&|\*[^\*]*\*|;[^;]*;|/[^/]*/|\|[^\|]*\|)`)739}740741func parseKeymap(keymap map[int][]action, str string) {742	masked := executeRegexp.ReplaceAllStringFunc(str, func(src string) string {743		symbol := ":"744		if strings.HasPrefix(src, "+") {745			symbol = "+"746		}747		prefix := symbol + "execute"748		if strings.HasPrefix(src[1:], "reload") {749			prefix = symbol + "reload"750		} else if strings.HasPrefix(src[1:], "preview") {751			prefix = symbol + "preview"752		} else if src[len(prefix)] == '-' {753			c := src[len(prefix)+1]754			if c == 's' || c == 'S' {755				prefix += "-silent"756			} else {757				prefix += "-multi"758			}759		}760		return prefix + "(" + strings.Repeat(" ", len(src)-len(prefix)-2) + ")"761	})762	masked = strings.Replace(masked, "::", string([]rune{escapedColon, ':'}), -1)763	masked = strings.Replace(masked, ",:", string([]rune{escapedComma, ':'}), -1)764	masked = strings.Replace(masked, "+:", string([]rune{escapedPlus, ':'}), -1)765766	idx := 0767	for _, pairStr := range strings.Split(masked, ",") {768		origPairStr := str[idx : idx+len(pairStr)]769		idx += len(pairStr) + 1770771		pair := strings.SplitN(pairStr, ":", 2)772		if len(pair) < 2 {773			errorExit("bind action not specified: " + origPairStr)774		}775		var key int776		if len(pair[0]) == 1 && pair[0][0] == escapedColon {777			key = ':' + tui.AltZ778		} else if len(pair[0]) == 1 && pair[0][0] == escapedComma {779			key = ',' + tui.AltZ780		} else if len(pair[0]) == 1 && pair[0][0] == escapedPlus {781			key = '+' + tui.AltZ782		} else {783			keys := parseKeyChords(pair[0], "key name required")784			key = firstKey(keys)785		}786787		idx2 := len(pair[0]) + 1788		specs := strings.Split(pair[1], "+")789		actions := make([]action, 0, len(specs))790		appendAction := func(types ...actionType) {791			actions = append(actions, toActions(types...)...)792		}793		prevSpec := ""794		for specIndex, maskedSpec := range specs {795			spec := origPairStr[idx2 : idx2+len(maskedSpec)]796			idx2 += len(maskedSpec) + 1797			spec = prevSpec + spec798			specLower := strings.ToLower(spec)799			switch specLower {800			case "ignore":801				appendAction(actIgnore)802			case "beginning-of-line":803				appendAction(actBeginningOfLine)804			case "abort":805				appendAction(actAbort)806			case "accept":807				appendAction(actAccept)808			case "accept-non-empty":809				appendAction(actAcceptNonEmpty)810			case "print-query":811				appendAction(actPrintQuery)812			case "refresh-preview":813				appendAction(actRefreshPreview)814			case "replace-query":815				appendAction(actReplaceQuery)816			case "backward-char":817				appendAction(actBackwardChar)818			case "backward-delete-char":819				appendAction(actBackwardDeleteChar)820			case "backward-delete-char/eof":821				appendAction(actBackwardDeleteCharEOF)822			case "backward-word":823				appendAction(actBackwardWord)824			case "clear-screen":825				appendAction(actClearScreen)826			case "delete-char":827				appendAction(actDeleteChar)828			case "delete-char/eof":829				appendAction(actDeleteCharEOF)830			case "end-of-line":831				appendAction(actEndOfLine)832			case "cancel":833				appendAction(actCancel)834			case "clear-query":835				appendAction(actClearQuery)836			case "clear-selection":837				appendAction(actClearSelection)838			case "forward-char":839				appendAction(actForwardChar)840			case "forward-word":841				appendAction(actForwardWord)842			case "jump":843				appendAction(actJump)844			case "jump-accept":845				appendAction(actJumpAccept)846			case "kill-line":847				appendAction(actKillLine)848			case "kill-word":849				appendAction(actKillWord)850			case "unix-line-discard", "line-discard":851				appendAction(actUnixLineDiscard)852			case "unix-word-rubout", "word-rubout":853				appendAction(actUnixWordRubout)854			case "yank":855				appendAction(actYank)856			case "backward-kill-word":857				appendAction(actBackwardKillWord)858			case "toggle-down":859				appendAction(actToggle, actDown)860			case "toggle-up":861				appendAction(actToggle, actUp)862			case "toggle-in":863				appendAction(actToggleIn)864			case "toggle-out":865				appendAction(actToggleOut)866			case "toggle-all":867				appendAction(actToggleAll)868			case "select-all":869				appendAction(actSelectAll)870			case "deselect-all":871				appendAction(actDeselectAll)872			case "toggle":873				appendAction(actToggle)874			case "down":875				appendAction(actDown)876			case "up":877				appendAction(actUp)878			case "top":879				appendAction(actTop)880			case "page-up":881				appendAction(actPageUp)882			case "page-down":883				appendAction(actPageDown)884			case "half-page-up":885				appendAction(actHalfPageUp)886			case "half-page-down":887				appendAction(actHalfPageDown)888			case "previous-history":889				appendAction(actPreviousHistory)890			case "next-history":891				appendAction(actNextHistory)892			case "toggle-preview":893				appendAction(actTogglePreview)894			case "toggle-preview-wrap":895				appendAction(actTogglePreviewWrap)896			case "toggle-sort":897				appendAction(actToggleSort)898			case "preview-up":899				appendAction(actPreviewUp)900			case "preview-down":901				appendAction(actPreviewDown)902			case "preview-page-up":903				appendAction(actPreviewPageUp)904			case "preview-page-down":905				appendAction(actPreviewPageDown)906			case "preview-half-page-up":907				appendAction(actPreviewHalfPageUp)908			case "preview-half-page-down":909				appendAction(actPreviewHalfPageDown)910			default:911				t := isExecuteAction(specLower)912				if t == actIgnore {913					if specIndex == 0 && specLower == "" {914						actions = append(keymap[key], actions...)915					} else {916						errorExit("unknown action: " + spec)917					}918				} else {919					var offset int920					switch t {921					case actReload:922						offset = len("reload")923					case actPreview:924						offset = len("preview")925					case actExecuteSilent:926						offset = len("execute-silent")927					case actExecuteMulti:928						offset = len("execute-multi")929					default:930						offset = len("execute")931					}932					if spec[offset] == ':' {933						if specIndex == len(specs)-1 {934							actions = append(actions, action{t: t, a: spec[offset+1:]})935						} else {936							prevSpec = spec + "+"937							continue938						}939					} else {940						actions = append(actions, action{t: t, a: spec[offset+1 : len(spec)-1]})941					}942				}943			}944			prevSpec = ""945		}946		keymap[key] = actions947	}948}949950func isExecuteAction(str string) actionType {951	matches := executeRegexp.FindAllStringSubmatch(":"+str, -1)952	if matches == nil || len(matches) != 1 {953		return actIgnore954	}955	prefix := matches[0][1]956	if len(prefix) == 0 {957		prefix = matches[0][2]958	}959	switch prefix {960	case "reload":961		return actReload962	case "preview":963		return actPreview964	case "execute":965		return actExecute966	case "execute-silent":967		return actExecuteSilent968	case "execute-multi":969		return actExecuteMulti970	}971	return actIgnore972}973974func parseToggleSort(keymap map[int][]action, str string) {975	keys := parseKeyChords(str, "key name required")976	if len(keys) != 1 {977		errorExit("multiple keys specified")978	}979	keymap[firstKey(keys)] = toActions(actToggleSort)980}981982func strLines(str string) []string {983	return strings.Split(strings.TrimSuffix(str, "\n"), "\n")984}985986func parseSize(str string, maxPercent float64, label string) sizeSpec {987	var val float64988	percent := strings.HasSuffix(str, "%")989	if percent {990		val = atof(str[:len(str)-1])991		if val < 0 {992			errorExit(label + " must be non-negative")993		}994		if val > maxPercent {995			errorExit(fmt.Sprintf("%s too large (max: %d%%)", label, int(maxPercent)))996		}997	} else {998		if strings.Contains(str, ".") {999			errorExit(label + " (without %) must be a non-negative integer")1000		}10011002		val = float64(atoi(str))1003		if val < 0 {1004			errorExit(label + " must be non-negative")1005		}1006	}1007	return sizeSpec{val, percent}1008}10091010func parseHeight(str string) sizeSpec {1011	size := parseSize(str, 100, "height")1012	return size1013}10141015func parseLayout(str string) layoutType {1016	switch str {1017	case "default":1018		return layoutDefault1019	case "reverse":1020		return layoutReverse1021	case "reverse-list":1022		return layoutReverseList1023	default:1024		errorExit("invalid layout (expected: default / reverse / reverse-list)")1025	}1026	return layoutDefault1027}10281029func parseInfoStyle(str string) infoStyle {1030	switch str {1031	case "default":1032		return infoDefault1033	case "inline":1034		return infoInline1035	case "hidden":1036		return infoHidden1037	default:1038		errorExit("invalid info style (expected: default / inline / hidden)")1039	}1040	return infoDefault1041}10421043func parsePreviewWindow(opts *previewOpts, input string) {1044	tokens := strings.Split(input, ":")1045	sizeRegex := regexp.MustCompile("^[0-9]+%?$")1046	offsetRegex := regexp.MustCompile("^\\+([0-9]+|{-?[0-9]+})(-[0-9]+|-/[1-9][0-9]*)?$")1047	for _, token := range tokens {1048		switch token {1049		case "":1050		case "default":1051			*opts = defaultPreviewOpts(opts.command)1052		case "hidden":1053			opts.hidden = true1054		case "nohidden":1055			opts.hidden = false1056		case "wrap":1057			opts.wrap = true1058		case "nowrap":1059			opts.wrap = false1060		case "cycle":1061			opts.cycle = true1062		case "nocycle":1063			opts.cycle = false1064		case "up", "top":1065			opts.position = posUp1066		case "down", "bottom":1067			opts.position = posDown1068		case "left":1069			opts.position = posLeft1070		case "right":1071			opts.position = posRight1072		case "rounded", "border":1073			opts.border = tui.BorderRounded1074		case "sharp":1075			opts.border = tui.BorderSharp1076		case "noborder":1077			opts.border = tui.BorderNone1078		default:1079			if sizeRegex.MatchString(token) {1080				opts.size = parseSize(token, 99, "window size")1081			} else if offsetRegex.MatchString(token) {1082				opts.scroll = token[1:]1083			} else {1084				errorExit("invalid preview window option: " + token)1085			}1086		}1087	}1088}10891090func parseMargin(opt string, margin string) [4]sizeSpec {1091	margins := strings.Split(margin, ",")1092	checked := func(str string) sizeSpec {1093		return parseSize(str, 49, opt)1094	}1095	switch len(margins) {1096	case 1:1097		m := checked(margins[0])1098		return [4]sizeSpec{m, m, m, m}1099	case 2:1100		tb := checked(margins[0])1101		rl := checked(margins[1])1102		return [4]sizeSpec{tb, rl, tb, rl}1103	case 3:1104		t := checked(margins[0])1105		rl := checked(margins[1])1106		b := checked(margins[2])1107		return [4]sizeSpec{t, rl, b, rl}1108	case 4:1109		return [4]sizeSpec{1110			checked(margins[0]), checked(margins[1]),1111			checked(margins[2]), checked(margins[3])}1112	default:1113		errorExit("invalid " + opt + ": " + margin)1114	}1115	return defaultMargin()1116}11171118func parseOptions(opts *Options, allArgs []string) {1119	var historyMax int1120	if opts.History == nil {1121		historyMax = defaultHistoryMax1122	} else {1123		historyMax = opts.History.maxSize1124	}1125	setHistory := func(path string) {1126		h, e := NewHistory(path, historyMax)1127		if e != nil {1128			errorExit(e.Error())1129		}1130		opts.History = h1131	}1132	setHistoryMax := func(max int) {1133		historyMax = max1134		if historyMax < 1 {1135			errorExit("history max must be a positive integer")1136		}1137		if opts.History != nil {1138			opts.History.maxSize = historyMax1139		}1140	}1141	validateJumpLabels := false1142	validatePointer := false1143	validateMarker := false1144	for i := 0; i < len(allArgs); i++ {1145		arg := allArgs[i]1146		switch arg {1147		case "-h", "--help":1148			help(exitOk)1149		case "-x", "--extended":1150			opts.Extended = true1151		case "-e", "--exact":1152			opts.Fuzzy = false1153		case "--extended-exact":1154			// Note that we now don't have --no-extended-exact1155			opts.Fuzzy = false1156			opts.Extended = true1157		case "+x", "--no-extended":1158			opts.Extended = false1159		case "+e", "--no-exact":1160			opts.Fuzzy = true1161		case "-q", "--query":1162			opts.Query = nextString(allArgs, &i, "query string required")1163		case "-f", "--filter":1164			filter := nextString(allArgs, &i, "query string required")1165			opts.Filter = &filter1166		case "--literal":1167			opts.Normalize = false1168		case "--no-literal":1169			opts.Normalize = true1170		case "--algo":1171			opts.FuzzyAlgo = parseAlgo(nextString(allArgs, &i, "algorithm required (v1|v2)"))1172		case "--expect":1173			for k, v := range parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required") {1174				opts.Expect[k] = v1175			}1176		case "--no-expect":1177			opts.Expect = make(map[int]string)1178		case "--no-phony":1179			opts.Phony = false1180		case "--phony":1181			opts.Phony = true1182		case "--tiebreak":1183			opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))1184		case "--bind":1185			parseKeymap(opts.Keymap, nextString(allArgs, &i, "bind expression required"))1186		case "--color":1187			_, spec := optionalNextString(allArgs, &i)1188			if len(spec) == 0 {1189				opts.Theme = tui.EmptyTheme()1190			} else {1191				opts.Theme = parseTheme(opts.Theme, spec)1192			}1193		case "--toggle-sort":1194			parseToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))1195		case "-d", "--delimiter":1196			opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))1197		case "-n", "--nth":1198			opts.Nth = splitNth(nextString(allArgs, &i, "nth expression required"))1199		case "--with-nth":1200			opts.WithNth = splitNth(nextString(allArgs, &i, "nth expression required"))1201		case "-s", "--sort":1202			opts.Sort = optionalNumeric(allArgs, &i, 1)1203		case "+s", "--no-sort":1204			opts.Sort = 01205		case "--tac":1206			opts.Tac = true1207		case "--no-tac":1208			opts.Tac = false1209		case "-i":1210			opts.Case = CaseIgnore1211		case "+i":1212			opts.Case = CaseRespect1213		case "-m", "--multi":1214			opts.Multi = optionalNumeric(allArgs, &i, maxMulti)1215		case "+m", "--no-multi":1216			opts.Multi = 01217		case "--ansi":1218			opts.Ansi = true1219		case "--no-ansi":1220			opts.Ansi = false1221		case "--no-mouse":1222			opts.Mouse = false1223		case "+c", "--no-color":1224			opts.Theme = tui.NoColorTheme()1225		case "+2", "--no-256":1226			opts.Theme = tui.Default161227		case "--black":1228			opts.Black = true1229		case "--no-black":1230			opts.Black = false1231		case "--bold":1232			opts.Bold = true1233		case "--no-bold":1234			opts.Bold = false1235		case "--layout":1236			opts.Layout = parseLayout(1237				nextString(allArgs, &i, "layout required (default / reverse / reverse-list)"))1238		case "--reverse":1239			opts.Layout = layoutReverse1240		case "--no-reverse":1241			opts.Layout = layoutDefault1242		case "--cycle":1243			opts.Cycle = true1244		case "--no-cycle":1245			opts.Cycle = false1246		case "--keep-right":1247			opts.KeepRight = true1248		case "--no-keep-right":1249			opts.KeepRight = false1250		case "--hscroll":1251			opts.Hscroll = true1252		case "--no-hscroll":1253			opts.Hscroll = false1254		case "--hscroll-off":1255			opts.HscrollOff = nextInt(allArgs, &i, "hscroll offset required")1256		case "--filepath-word":1257			opts.FileWord = true1258		case "--no-filepath-word":1259			opts.FileWord = false1260		case "--info":1261			opts.InfoStyle = parseInfoStyle(1262				nextString(allArgs, &i, "info style required"))1263		case "--no-info":1264			opts.InfoStyle = infoHidden1265		case "--inline-info":1266			opts.InfoStyle = infoInline1267		case "--no-inline-info":1268			opts.InfoStyle = infoDefault1269		case "--jump-labels":1270			opts.JumpLabels = nextString(allArgs, &i, "label characters required")1271			validateJumpLabels = true1272		case "-1", "--select-1":1273			opts.Select1 = true1274		case "+1", "--no-select-1":1275			opts.Select1 = false1276		case "-0", "--exit-0":1277			opts.Exit0 = true1278		case "+0", "--no-exit-0":1279			opts.Exit0 = false1280		case "--read0":1281			opts.ReadZero = true1282		case "--no-read0":1283			opts.ReadZero = false1284		case "--print0":1285			opts.Printer = func(str string) { fmt.Print(str, "\x00") }1286			opts.PrintSep = "\x00"1287		case "--no-print0":1288			opts.Printer = func(str string) { fmt.Println(str) }1289			opts.PrintSep = "\n"1290		case "--print-query":1291			opts.PrintQuery = true1292		case "--no-print-query":1293			opts.PrintQuery = false1294		case "--prompt":1295			opts.Prompt = nextString(allArgs, &i, "prompt string required")1296		case "--pointer":1297			opts.Pointer = nextString(allArgs, &i, "pointer sign string required")1298			validatePointer = true1299		case "--marker":1300			opts.Marker = nextString(allArgs, &i, "selected sign string required")1301			validateMarker = true1302		case "--sync":1303			opts.Sync = true1304		case "--no-sync":1305			opts.Sync = false1306		case "--async":1307			opts.Sync = false1308		case "--no-history":1309			opts.History = nil1310		case "--history":1311			setHistory(nextString(allArgs, &i, "history file path required"))1312		case "--history-size":1313			setHistoryMax(nextInt(allArgs, &i, "history max size required"))1314		case "--no-header":1315			opts.Header = []string{}1316		case "--no-header-lines":1317			opts.HeaderLines = 01318		case "--header":1319			opts.Header = strLines(nextString(allArgs, &i, "header string required"))1320		case "--header-lines":1321			opts.HeaderLines = atoi(1322				nextString(allArgs, &i, "number of header lines required"))1323		case "--preview":1324			opts.Preview.command = nextString(allArgs, &i, "preview command required")1325		case "--no-preview":1326			opts.Preview.command = ""1327		case "--preview-window":1328			parsePreviewWindow(&opts.Preview,1329				nextString(allArgs, &i, "preview window layout required: [up|down|left|right][:SIZE[%]][:rounded|sharp|noborder][:wrap][:cycle][:hidden][:+SCROLL[-OFFSET]][:default]"))1330		case "--height":1331			opts.Height = parseHeight(nextString(allArgs, &i, "height required: HEIGHT[%]"))1332		case "--min-height":1333			opts.MinHeight = nextInt(allArgs, &i, "height required: HEIGHT")1334		case "--no-height":1335			opts.Height = sizeSpec{}1336		case "--no-margin":1337			opts.Margin = defaultMargin()1338		case "--no-padding":1339			opts.Padding = defaultMargin()1340		case "--no-border":1341			opts.BorderShape = tui.BorderNone1342		case "--border":1343			hasArg, arg := optionalNextString(allArgs, &i)1344			opts.BorderShape = parseBorder(arg, !hasArg)1345		case "--no-unicode":1346			opts.Unicode = false1347		case "--unicode":1348			opts.Unicode = true1349		case "--margin":1350			opts.Margin = parseMargin(1351				"margin",1352				nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))1353		case "--padding":1354			opts.Padding = parseMargin(1355				"padding",1356				nextString(allArgs, &i, "padding required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))1357		case "--tabstop":1358			opts.Tabstop = nextInt(allArgs, &i, "tab stop required")1359		case "--clear":1360			opts.ClearOnExit = true1361		case "--no-clear":1362			opts.ClearOnExit = false1363		case "--version":1364			opts.Version = true1365		default:1366			if match, value := optString(arg, "--algo="); match {1367				opts.FuzzyAlgo = parseAlgo(value)1368			} else if match, value := optString(arg, "-q", "--query="); match {1369				opts.Query = value1370			} else if match, value := optString(arg, "-f", "--filter="); match {1371				opts.Filter = &value1372			} else if match, value := optString(arg, "-d", "--delimiter="); match {1373				opts.Delimiter = delimiterRegexp(value)1374			} else if match, value := optString(arg, "--border="); match {1375				opts.BorderShape = parseBorder(value, false)1376			} else if match, value := optString(arg, "--prompt="); match {1377				opts.Prompt = value1378			} else if match, value := optString(arg, "--pointer="); match {1379				opts.Pointer = value1380				validatePointer = true1381			} else if match, value := optString(arg, "--marker="); match {1382				opts.Marker = value1383				validateMarker = true1384			} else if match, value := optString(arg, "-n", "--nth="); match {1385				opts.Nth = splitNth(value)1386			} else if match, value := optString(arg, "--with-nth="); match {1387				opts.WithNth = splitNth(value)1388			} else if match, _ := optString(arg, "-s", "--sort="); match {1389				opts.Sort = 1 // Don't care1390			} else if match, value := optString(arg, "-m", "--multi="); match {1391				opts.Multi = atoi(value)1392			} else if match, value := optString(arg, "--height="); match {1393				opts.Height = parseHeight(value)1394			} else if match, value := optString(arg, "--min-height="); match {1395				opts.MinHeight = atoi(value)1396			} else if match, value := optString(arg, "--layout="); match {1397				opts.Layout = parseLayout(value)1398			} else if match, value := optString(arg, "--info="); match {1399				opts.InfoStyle = parseInfoStyle(value)1400			} else if match, value := optString(arg, "--toggle-sort="); match {1401				parseToggleSort(opts.Keymap, value)1402			} else if match, value := optString(arg, "--expect="); match {1403				for k, v := range parseKeyChords(value, "key names required") {1404					opts.Expect[k] = v1405				}1406			} else if match, value := optString(arg, "--tiebreak="); match {1407				opts.Criteria = parseTiebreak(value)1408			} else if match, value := optString(arg, "--color="); match {1409				opts.Theme = parseTheme(opts.Theme, value)1410			} else if match, value := optString(arg, "--bind="); match {1411				parseKeymap(opts.Keymap, value)1412			} else if match, value := optString(arg, "--history="); match {1413				setHistory(value)1414			} else if match, value := optString(arg, "--history-size="); match {1415				setHistoryMax(atoi(value))1416			} else if match, value := optString(arg, "--header="); match {1417				opts.Header = strLines(value)1418			} else if match, value := optString(arg, "--header-lines="); match {1419				opts.HeaderLines = atoi(value)1420			} else if match, value := optString(arg, "--preview="); match {1421				opts.Preview.command = value1422			} else if match, value := optString(arg, "--preview-window="); match {1423				parsePreviewWindow(&opts.Preview, value)1424			} else if match, value := optString(arg, "--margin="); match {1425				opts.Margin = parseMargin("margin", value)1426			} else if match, value := optString(arg, "--padding="); match {1427				opts.Padding = parseMargin("padding", value)1428			} else if match, value := optString(arg, "--tabstop="); match {1429				opts.Tabstop = atoi(value)1430			} else if match, value := optString(arg, "--hscroll-off="); match {1431				opts.HscrollOff = atoi(value)1432			} else if match, value := optString(arg, "--jump-labels="); match {1433				opts.JumpLabels = value1434				validateJumpLabels = true1435			} else {1436				errorExit("unknown option: " + arg)1437			}1438		}1439	}14401441	if opts.HeaderLines < 0 {1442		errorExit("header lines must be a non-negative integer")1443	}14441445	if opts.HscrollOff < 0 {1446		errorExit("hscroll offset must be a non-negative integer")1447	}14481449	if opts.Tabstop < 1 {1450		errorExit("tab stop must be a positive integer")1451	}14521453	if len(opts.JumpLabels) == 0 {1454		errorExit("empty jump labels")1455	}14561457	if validateJumpLabels {1458		for _, r := range opts.JumpLabels {1459			if r < 32 || r > 126 {1460				errorExit("non-ascii jump labels are not allowed")1461			}1462		}1463	}14641465	if validatePointer {1466		if err := validateSign(opts.Pointer, "pointer"); err != nil {1467			errorExit(err.Error())1468		}1469	}14701471	if validateMarker {1472		if err := validateSign(opts.Marker, "marker"); err != nil {1473			errorExit(err.Error())1474		}1475	}1476}14771478func validateSign(sign string, signOptName string) error {1479	if sign == "" {1480		return fmt.Errorf("%v cannot be empty", signOptName)1481	}1482	widthSum := 01483	for _, r := range sign {1484		if !unicode.IsGraphic(r) {1485			return fmt.Errorf("invalid character in %v", signOptName)1486		}1487		widthSum += runewidth.RuneWidth(r)1488		if widthSum > 2 {1489			return fmt.Errorf("%v display width should be up to 2", signOptName)1490		}1491	}1492	return nil1493}14941495func postProcessOptions(opts *Options) {1496	if !tui.IsLightRendererSupported() && opts.Height.size > 0 {1497		errorExit("--height option is currently not supported on this platform")1498	}1499	// Default actions for CTRL-N / CTRL-P when --history is set1500	if opts.History != nil {1501		if _, prs := opts.Keymap[tui.CtrlP]; !prs {1502			opts.Keymap[tui.CtrlP] = toActions(actPreviousHistory)1503		}1504		if _, prs := opts.Keymap[tui.CtrlN]; !prs {1505			opts.Keymap[tui.CtrlN] = toActions(actNextHistory)1506		}1507	}15081509	// Extend the default key map1510	keymap := defaultKeymap()1511	for key, actions := range opts.Keymap {1512		for _, act := range actions {1513			if act.t == actToggleSort {1514				opts.ToggleSort = true1515			}1516		}1517		keymap[key] = actions1518	}1519	opts.Keymap = keymap15201521	// If we're not using extended search mode, --nth option becomes irrelevant1522	// if it contains the whole range1523	if !opts.Extended || len(opts.Nth) == 1 {1524		for _, r := range opts.Nth {1525			if r.begin == rangeEllipsis && r.end == rangeEllipsis {1526				opts.Nth = make([]Range, 0)1527				return1528			}1529		}1530	}15311532	if opts.Bold {1533		theme := opts.Theme1534		boldify := func(c tui.ColorAttr) tui.ColorAttr {1535			dup := c1536			if !theme.Colored {1537				dup.Attr |= tui.Bold1538			} else if (c.Attr & tui.AttrRegular) == 0 {1539				dup.Attr |= tui.Bold1540			}1541			return dup1542		}1543		theme.Current = boldify(theme.Current)1544		theme.CurrentMatch = boldify(theme.CurrentMatch)1545		theme.Prompt = boldify(theme.Prompt)1546		theme.Input = boldify(theme.Input)1547		theme.Cursor = boldify(theme.Cursor)1548		theme.Spinner = boldify(theme.Spinner)1549	}1550}15511552// ParseOptions parses command-line options1553func ParseOptions() *Options {1554	opts := defaultOptions()15551556	// Options from Env var1557	words, _ := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))1558	if len(words) > 0 {1559		parseOptions(opts, words)1560	}15611562	// Options from command-line arguments1563	parseOptions(opts, os.Args[1:])15641565	postProcessOptions(opts)1566	return opts1567}