Skip to content
Myr

Minor refactoring

Before adoption: this commit came in with the history the project adopted, so no landing records it.

- Slightly more efficient processing of Options - Do not return reference type arguments that are mutated inside the function - Use util.Constrain function when appropriate

authored by Junegunn Choi · committed by Junegunn Choi · parent 45108dd · Browse files · 3 files+88 added−48 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+88 added−48 removed

  • other:+88 added−48 removed

3 files+88 added−48 removed

modified:src/options_test.go+60 added-15 removed
94 unmodified lines
95 {96 opts := defaultOptions()97 words := []string{"--nth", "..", "-x"}98 parseOptions(opts, words)99 postProcessOptions(opts)100 if len(opts.Nth) != 0 {101 t.Errorf("nth should be empty: %s", opts.Nth)102 }103 }104 for _, words := range [][]string{[]string{"--nth", "..,3", "+x"}, []string{"--nth", "3,1..", "+x"}, []string{"--nth", "..-1,1", "+x"}} {105 {106 opts := defaultOptions()107 parseOptions(opts, words)108 postProcessOptions(opts)109 if len(opts.Nth) != 0 {110 t.Errorf("nth should be empty: %s", opts.Nth)111 }112 }113 {114 opts := defaultOptions()115 words = append(words, "-x")116 parseOptions(opts, words)117 postProcessOptions(opts)118 if len(opts.Nth) != 2 {119 t.Errorf("nth should not be empty: %s", opts.Nth)120 }121 }
111 unmodified lines
233 }234 keymap := defaultKeymap()235 execmap := make(map[int]string)236 check(actBeginningOfLine, keymap[curses.CtrlA])234 keymap, execmap, toggleSort :=235 parseKeymap(keymap, execmap, false,236 "ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+237 "f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+238 "alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};"+239 ",,:abort,::accept,X:execute:\nfoobar,Y:execute(baz)")237 parseKeymap(keymap, execmap,238 "ctrl-a:kill-line,ctrl-b:toggle-sort,c:page-up,alt-z:page-down,"+239 "f1:execute(ls {}),f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+240 "alt-a:execute@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};"+241 ",,:abort,::accept,X:execute:\nfoobar,Y:execute(baz)")240 if !toggleSort {241 t.Errorf("toggleSort not set")242 }242 check(actKillLine, keymap[curses.CtrlA])243 check(actToggleSort, keymap[curses.CtrlB])244 check(actPageUp, keymap[curses.AltZ+'c'])245 check(actAbort, keymap[curses.AltZ+','])
11 unmodified lines
257 checkString("echo (,),[,],/,:,@,%,{}", execmap[curses.AltB])258 checkString("\nfoobar,Y:execute(baz)", execmap[curses.AltZ+'X'])259260 for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {262 keymap, execmap, toggleSort =263 parseKeymap(keymap, execmap, false, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))261 parseKeymap(keymap, execmap, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))262 checkString("foobar", execmap[curses.AltZ+int([]rune(fmt.Sprintf("%d", idx%10))[0])])263 }264267 keymap, execmap, toggleSort = parseKeymap(keymap, execmap, false, "f1:abort")268 if toggleSort {269 t.Errorf("toggleSort set")270 }265 parseKeymap(keymap, execmap, "f1:abort")266 check(actAbort, keymap[curses.F1])267}268269func TestColorSpec(t *testing.T) {
52 unmodified lines
322 if newTheme.Prompt != 13 {323 t.Errorf("color should now be enabled and customized")324 }325}326327func TestDefaultCtrlNP(t *testing.T) {328 check := func(words []string, key int, expected actionType) {329 opts := defaultOptions()330 parseOptions(opts, words)331 postProcessOptions(opts)332 if opts.Keymap[key] != expected {333 t.Error()334 }335 }336 check([]string{}, curses.CtrlN, actDown)337 check([]string{}, curses.CtrlP, actUp)338339 check([]string{"--bind=ctrl-n:accept"}, curses.CtrlN, actAccept)340 check([]string{"--bind=ctrl-p:accept"}, curses.CtrlP, actAccept)341342 hist := "--history=/tmp/foo"343 check([]string{hist}, curses.CtrlN, actNextHistory)344 check([]string{hist}, curses.CtrlP, actPreviousHistory)345346 check([]string{hist, "--bind=ctrl-n:accept"}, curses.CtrlN, actAccept)347 check([]string{hist, "--bind=ctrl-n:accept"}, curses.CtrlP, actPreviousHistory)348349 check([]string{hist, "--bind=ctrl-p:accept"}, curses.CtrlN, actNextHistory)350 check([]string{hist, "--bind=ctrl-p:accept"}, curses.CtrlP, actAccept)351}352353func TestToggle(t *testing.T) {354 optsFor := func(words ...string) *Options {355 opts := defaultOptions()356 parseOptions(opts, words)357 postProcessOptions(opts)358 return opts359 }360361 opts := optsFor()362 if opts.ToggleSort {363 t.Error()364 }365366 opts = optsFor("--bind=a:toggle-sort")367 if !opts.ToggleSort {368 t.Error()369 }370371 opts = optsFor("--bind=a:toggle-sort", "--bind=a:up")372 if opts.ToggleSort {373 t.Error()374 }375}
modified:src/options.go+27 added-24 removed
161 unmodified lines
162 Exit0: false,163 Filter: nil,164 ToggleSort: false,165 Expect: make(map[int]string),166 Keymap: defaultKeymap(),166 Keymap: make(map[int]actionType),167 Execmap: make(map[int]string),168 PrintQuery: false,169 ReadZero: false,170 Sync: false,
312 unmodified lines
483 escapedColon = 0484 escapedComma = 1485)486487func parseKeymap(keymap map[int]actionType, execmap map[int]string, toggleSort bool, str string) (map[int]actionType, map[int]string, bool) {487func parseKeymap(keymap map[int]actionType, execmap map[int]string, str string) {488 if executeRegexp == nil {489 // Backreferences are not supported.490 // "~!@#$%^&*;/|".each_char.map { |c| Regexp.escape(c) }.map { |c| "#{c}[^#{c}]*#{c}" }.join('|')491 executeRegexp = regexp.MustCompile(
99 unmodified lines
591 case "next-history":592 keymap[key] = actNextHistory593 case "toggle-sort":594 keymap[key] = actToggleSort595 toggleSort = true595 default:596 if isExecuteAction(actLower) {597 var offset int598 if strings.HasPrefix(actLower, "execute-multi") {
12 unmodified lines
611 errorExit("unknown action: " + act)612 }613 }614 }616 return keymap, execmap, toggleSort615}616617func isExecuteAction(str string) bool {618 if !strings.HasPrefix(str, "execute") || len(str) < len("execute()") {
13 unmodified lines
632 }633 return false634}635638func checkToggleSort(keymap map[int]actionType, str string) map[int]actionType {636func parseToggleSort(keymap map[int]actionType, str string) {637 keys := parseKeyChords(str, "key name required")638 if len(keys) != 1 {639 errorExit("multiple keys specified")640 }641 keymap[firstKey(keys)] = actToggleSort644 return keymap642}643644func strLines(str string) []string {645 return strings.Split(strings.TrimSuffix(str, "\n"), "\n")
41 unmodified lines
687 return defaultMargin()688}689690func parseOptions(opts *Options, allArgs []string) {694 keymap := make(map[int]actionType)691 var historyMax int692 if opts.History == nil {693 historyMax = defaultHistoryMax694 } else {
41 unmodified lines
736 opts.Expect = parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required")737 case "--tiebreak":738 opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))739 case "--bind":744 keymap, opts.Execmap, opts.ToggleSort =745 parseKeymap(keymap, opts.Execmap, opts.ToggleSort, nextString(allArgs, &i, "bind expression required"))740 parseKeymap(opts.Keymap, opts.Execmap, nextString(allArgs, &i, "bind expression required"))741 case "--color":742 spec := optionalNextString(allArgs, &i)743 if len(spec) == 0 {744 opts.Theme = defaultTheme()745 } else {746 opts.Theme = parseTheme(opts.Theme, spec)747 }748 case "--toggle-sort":754 keymap = checkToggleSort(keymap, nextString(allArgs, &i, "key name required"))755 opts.ToggleSort = true749 parseToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))750 case "-d", "--delimiter":751 opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))752 case "-n", "--nth":753 opts.Nth = splitNth(nextString(allArgs, &i, "nth expression required"))
108 unmodified lines
862 opts.WithNth = splitNth(value)863 } else if match, _ := optString(arg, "-s", "--sort="); match {864 opts.Sort = 1 // Don't care865 } else if match, value := optString(arg, "--toggle-sort="); match {872 keymap = checkToggleSort(keymap, value)873 opts.ToggleSort = true866 parseToggleSort(opts.Keymap, value)867 } else if match, value := optString(arg, "--expect="); match {868 opts.Expect = parseKeyChords(value, "key names required")869 } else if match, value := optString(arg, "--tiebreak="); match {870 opts.Criteria = parseTiebreak(value)871 } else if match, value := optString(arg, "--color="); match {872 opts.Theme = parseTheme(opts.Theme, value)873 } else if match, value := optString(arg, "--bind="); match {881 keymap, opts.Execmap, opts.ToggleSort =882 parseKeymap(keymap, opts.Execmap, opts.ToggleSort, value)874 parseKeymap(opts.Keymap, opts.Execmap, value)875 } else if match, value := optString(arg, "--history="); match {876 setHistory(value)877 } else if match, value := optString(arg, "--history-size="); match {878 setHistoryMax(atoi(value))
17 unmodified lines
896897 if opts.Tabstop < 1 {898 errorExit("tab stop must be a positive integer")899 }900}901909 // Change default actions for CTRL-N / CTRL-P when --history is used902func postProcessOptions(opts *Options) {903 // Default actions for CTRL-N / CTRL-P when --history is set904 if opts.History != nil {911 if _, prs := keymap[curses.CtrlP]; !prs {912 keymap[curses.CtrlP] = actPreviousHistory905 if _, prs := opts.Keymap[curses.CtrlP]; !prs {906 opts.Keymap[curses.CtrlP] = actPreviousHistory907 }914 if _, prs := keymap[curses.CtrlN]; !prs {915 keymap[curses.CtrlN] = actNextHistory908 if _, prs := opts.Keymap[curses.CtrlN]; !prs {909 opts.Keymap[curses.CtrlN] = actNextHistory910 }911 }912919 // Override default key bindings920 for key, act := range keymap {921 opts.Keymap[key] = act913 // Extend the default key map914 keymap := defaultKeymap()915 for key, act := range opts.Keymap {916 if act == actToggleSort {917 opts.ToggleSort = true918 }919 keymap[key] = act920 }921 opts.Keymap = keymap922923 // If we're not using extended search mode, --nth option becomes irrelevant924 // if it contains the whole range925 if !opts.Extended || len(opts.Nth) == 1 {
11 unmodified lines
937 opts := defaultOptions()938939 // Options from Env var940 words, _ := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))941 if len(words) > 0 {942 parseOptions(opts, words)942 parseOptions(opts, words)943 }944945 // Options from command-line arguments946 parseOptions(opts, os.Args[1:])947948 postProcessOptions(opts)949 return opts950}
modified:src/terminal.go+1 added-9 removed
1120 unmodified lines
1121 height := t.maxItems()1122 diffpos := t.cy - t.offset11231124 t.cy = util.Constrain(t.cy, 0, count-1)11251126 if t.cy > t.offset+(height-1) {1127 // Ceil1128 t.offset = t.cy - (height - 1)1129 } else if t.offset > t.cy {1130 // Floor1131 t.offset = t.cy1132 }11331125 t.offset = util.Constrain(t.offset, t.cy-height+1, t.cy)1126 // Adjustment1127 if count-t.offset < height {1128 t.offset = util.Max(0, count-height)1129 t.cy = util.Constrain(t.offset+diffpos, 0, count-1)
36 unmodified lines