Skip to content
Myr

Option to prioritize file name matches (#4192)

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

* 'pathname' is a new tiebreak option for prioritizing matches occurring in the file name of the path. * `--scheme=path` will automatically set `--tiebreak=pathname,length`. * fzf will automatically choose `path` scheme when the input is a TTY device, where fzf would start its built-in walker or run `$FZF_DEFAULT_COMMAND` which is usually a command for listing files. Close #4191

authored by Junegunn Choi · committed by GitHub · parent c71e4dd · Browse files · 7 files+127 added−28 removed
This commit

State

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

Diff stats

7 files+127 added−28 removed

  • other:+127 added−28 removed

7 files+127 added−28 removed

modified:man/man1/fzf.1+20 added-10 removed
19 unmodified lines
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN22THE SOFTWARE.23..24.TH fzf 1 "Jan 2025" "fzf 0.58.0" "fzf - a command-line fuzzy finder"24.TH fzf 1 "Jan 2025" "fzf 0.59.0" "fzf - a command-line fuzzy finder"2526.SH NAME27fzf - a command-line fuzzy finder28
46 unmodified lines
75.B path76.RS77Additional bonus point is only given to the characters after path separator.78You might want to choose this scheme over \fBdefault\fR if you have many files79with spaces in their paths.79with spaces in their paths. This also sets \fB\-\-tiebreak=pathname,length\fR,80to prioritize matches occurring in the tail element of a file path.81.RE82.RE8384.RS
5 unmodified lines
90\fB\-\-tiebreak=index\fR.91.RE92.RE9394.RS95fzf chooses \fBpath\fR scheme when the input is a TTY device, where fzf would96start its built-in walker or run \fB$FZF_DEFAULT_COMMAND\fR, and there is no97\fBreload\fR action bound to \fBstart\fR event. Otherwise, it chooses98\fBdefault\fR scheme.99.RE100101.TP102.BI "\-\-algo=" TYPE103Fuzzy matching algorithm (default: v2)104
42 unmodified lines
147Comma-separated list of sort criteria to apply when the scores are tied.148.br149150.br143.BR length " Prefers line with shorter length"151.BR length " Prefers line with shorter length"152.br145.BR chunk " Prefers line with shorter matched chunk (delimited by whitespaces)"153.BR chunk " Prefers line with shorter matched chunk (delimited by whitespaces)"154.br147.BR begin " Prefers line with matched substring closer to the beginning"155.BR pathname " Prefers line with matched substring in the file name of the path"156.br149.BR end " Prefers line with matched substring closer to the end"157.BR begin " Prefers line with matched substring closer to the beginning"158.br151.BR index " Prefers line that appeared earlier in the input stream"159.BR end " Prefers line with matched substring closer to the end"160.br161.BR index " Prefers line that appeared earlier in the input stream"162.br163164.br165- Each criterion should appear only once in the list166.br
970 unmodified lines
11371138.SH ENVIRONMENT VARIABLES1139.TP1140.B FZF_DEFAULT_COMMAND1131Default command to use when input is tty. On *nix systems, fzf runs the command1132with \fB$SHELL \-c\fR if \fBSHELL\fR is set, otherwise with \fBsh \-c\fR, so in1133this case make sure that the command is POSIX-compliant.1141Default command to use when input is a TTY device. On *nix systems, fzf runs1142the command with \fB$SHELL \-c\fR if \fBSHELL\fR is set, otherwise with \fBsh1143\-c\fR, so in this case make sure that the command is POSIX-compliant.1144.TP1145.B FZF_DEFAULT_OPTS1146Default options.1147.br
672 unmodified lines
modified:plugin/fzf.vim+1 added-1 removed
1079 unmodified lines
1080endfunction10811082function! s:cmd(bang, ...) abort1083 let args = copy(a:000)1084 let opts = { 'options': ['--multi'] }1084 let opts = { 'options': ['--multi', '--scheme', 'path'] }1085 if len(args) && isdirectory(expand(args[-1]))1086 let opts.dir = substitute(substitute(remove(args, -1), '\\\(["'']\)', '\1', 'g'), '[/\\]*$', '/', '')1087 if s:is_win && !&shellslash1088 let opts.dir = substitute(opts.dir, '/', '\\', 'g')
15 unmodified lines
modified:src/core.go+3 added
186 unmodified lines
187 case byEnd:188 forward = false189 case byBegin:190 forward = true191 case byPathname:192 withPos = true193 forward = false194 }195 }196197 nth := opts.Nth
282 unmodified lines
modified:src/options.go+62 added-17 removed
9 unmodified lines
10 "unicode"1112 "github.com/junegunn/fzf/src/algo"13 "github.com/junegunn/fzf/src/tui"14 "github.com/junegunn/fzf/src/util"1516 "github.com/junegunn/go-shellwords"17 "github.com/rivo/uniseg"18)
27 unmodified lines
46 --literal Do not normalize latin script letters47 --tail=NUM Maximum number of items to keep in memory48 --disabled Do not perform search49 --tiebreak=CRI[,..] Comma-separated list of sort criteria to apply49 when the scores are tied [length|chunk|begin|end|index]50 (default: length)50 when the scores are tied51 [length|chunk|pathname|begin|end|index] (default: length)5253 INPUT/OUTPUT54 --read0 Read input delimited by ASCII NUL characters55 --print0 Print output delimited by ASCII NUL characters
185 unmodified lines
241 byChunk242 byLength243 byBegin244 byEnd245 byPathname246)247248type heightSpec struct {249 size float64
404 unmodified lines
654 Fish: false,655 Man: false,656 Fuzzy: true,657 FuzzyAlgo: algo.FuzzyMatchV2,656 Scheme: "default",658 Scheme: "", // Unknown659 Extended: true,660 Phony: false,661 Case: CaseSmart,662 Normalize: true,
2 unmodified lines
665 Delimiter: Delimiter{},666 Sort: 1000,667 Track: trackDisabled,668 Tac: false,667 Criteria: []criterion{byScore, byLength},669 Criteria: []criterion{}, // Unknown670 Multi: 0,671 Ansi: false,672 Mouse: true,673 Theme: theme,
131 unmodified lines
805 }806 return nil, errors.New("invalid algorithm (expected: v1 or v2)")807}808807func processScheme(opts *Options) error {808 if !algo.Init(opts.Scheme) {809 return errors.New("invalid scoring scheme (expected: default|path|history)")810 }811 if opts.Scheme == "history" {812 opts.Criteria = []criterion{byScore}813 }814 return nil815}816809func parseBorder(str string, optional bool, allowLine bool) (tui.BorderShape, error) {810 switch str {811 case "line":812 if !allowLine {
215 unmodified lines
1028 }1029 return chords, nil1030}10311032func parseScheme(str string) (string, []criterion, error) {1033 str = strings.ToLower(str)1034 switch str {1035 case "history":1036 return str, []criterion{byScore}, nil1037 case "path":1038 return str, []criterion{byScore, byPathname, byLength}, nil1039 case "default":1040 return str, []criterion{byScore, byLength}, nil1041 }1042 return str, nil, errors.New("invalid scoring scheme: " + str + " (expected: default|path|history)")1043}10441045func parseTiebreak(str string) ([]criterion, error) {1046 criteria := []criterion{byScore}1047 hasIndex := false1048 hasChunk := false1049 hasLength := false1050 hasBegin := false1051 hasEnd := false1052 hasPathname := false1053 check := func(notExpected *bool, name string) error {1054 if *notExpected {1055 return errors.New("duplicate sort criteria: " + name)1056 }
13 unmodified lines
1070 if err := check(&hasChunk, "chunk"); err != nil {1071 return nil, err1072 }1073 criteria = append(criteria, byChunk)1074 case "pathname":1075 if err := check(&hasPathname, "pathname"); err != nil {1076 return nil, err1077 }1078 criteria = append(criteria, byPathname)1079 case "length":1080 if err := check(&hasLength, "length"); err != nil {1081 return nil, err1082 }
1188 unmodified lines
2271 str, err := nextString("scoring scheme required (default|path|history)")2272 if err != nil {2273 return err2274 }2264 opts.Scheme = strings.ToLower(str)2275 if opts.Scheme, opts.Criteria, err = parseScheme(str); err != nil {2276 return err2277 }2278 case "--expect":2279 str, err := nextString("key names required")2280 if err != nil {2281 return err
903 unmodified lines
3185 if err := opts.initProfiling(); err != nil {3186 return errors.New("failed to start pprof profiles: " + err.Error())3187 }31883176 return processScheme(opts)3189 algo.Init(opts.Scheme)31903191 return nil3192}31933194func parseShellWords(str string) ([]string, error) {3195 parser := shellwords.NewParser()
41 unmodified lines
3237 if err := parseOptions(&index, opts, args); err != nil {3238 return nil, err3239 }32403241 // 4. Change default scheme when built-in walker is used3242 if len(opts.Scheme) == 0 {3243 opts.Scheme = "default"3244 if len(opts.Criteria) == 0 {3245 // NOTE: Let's assume $FZF_DEFAULT_COMMAND generates a list of file paths.3246 // But it is possible that it is set to a command that doesn't generate3247 // file paths.3248 //3249 // In that case, you can either3250 // 1. explicitly set --scheme=default,3251 // 2. or replace $FZF_DEFAULT_COMMAND with an equivalent 'start:reload'3252 // binding, which is the new preferred way.3253 if !opts.hasReloadOnStart() && util.IsTty(os.Stdin) {3254 opts.Scheme = "path"3255 }3256 _, opts.Criteria, _ = parseScheme(opts.Scheme)3257 }3258 }32593226 // 4. Final validation of merged options3260 // 5. Final validation of merged options3261 if err := validateOptions(opts); err != nil {3262 return nil, err3263 }32643265 return opts, nil3266}32673268func (opts *Options) hasReloadOnStart() bool {3269 if actions, prs := opts.Keymap[tui.Start.AsEvent()]; prs {3270 for _, action := range actions {3271 if action.t == actReload || action.t == actReloadSync {3272 return true3273 }3274 }3275 }3276 return false3277}32783279func (opts *Options) extractReloadOnStart() string {3280 cmd := ""3281 if actions, prs := opts.Keymap[tui.Start.AsEvent()]; prs {3282 filtered := []*action{}
11 unmodified lines
modified:src/result.go+15 added
67 unmodified lines
68 val = util.AsUint16(e - b)69 }70 case byLength:71 val = item.TrimLength()72 case byPathname:73 if validOffsetFound {74 // lastDelim := strings.LastIndexByte(item.text.ToString(), '/')75 lastDelim := -176 s := item.text.ToString()77 for i := len(s) - 1; i >= 0; i-- {78 if s[i] == '/' || s[i] == '\\' {79 lastDelim = i80 break81 }82 }83 if lastDelim <= minBegin {84 val = util.AsUint16(minBegin - lastDelim)85 }86 }87 case byBegin, byEnd:88 if validOffsetFound {89 whitePrefixLen := 090 for idx := 0; idx < numChars; idx++ {
220 unmodified lines
modified:CHANGELOG.md+7 added
1CHANGELOG2=========340.59.05------6- Prioritizing file name matches (#4192)7 - Added a new tiebreak option `pathname` for prioritizing file name matches8 - `--scheme=path` now sets `--tiebreak=pathname,length`9 - fzf will automatically choose `path` scheme when the input is a TTY device, where fzf would start its built-in walker or run `$FZF_DEFAULT_COMMAND` which is usually a command for listing files.10110.58.012------13_Release highlights: https://junegunn.github.io/fzf/releases/0.58.0/_14
2427 unmodified lines
modified:README.md+19 added
81 unmodified lines
82 * [Supported commands](#supported-commands)83 * [Custom fuzzy completion](#custom-fuzzy-completion)84* [Vim plugin](#vim-plugin)85* [Advanced topics](#advanced-topics)86 * [Customizing for different types of input](#customizing-for-different-types-of-input)87 * [Performance](#performance)88 * [Executing external programs](#executing-external-programs)89 * [Turning into a different process](#turning-into-a-different-process)90 * [Reloading the candidate list](#reloading-the-candidate-list)
627 unmodified lines
718719Advanced topics720---------------721722### Customizing for different types of input723724Since fzf is a general-purpose text filter, its algorithm was designed to725"generally" work well with any kind of input. However, admittedly, there is no726true one-size-fits-all solution, and you may want to tweak the algorithm and727some of the settings depending on the type of the input. To make this process728easier, fzf provides a set of "scheme"s for some common input types.729730| Scheme | Description |731| :--- | :--- |732| `--scheme=default` | Generic scheme designed to work well with any kind of input |733| `--scheme=path` | Suitable for file paths |734| `--scheme=history` | Suitable for command history or any input where chronological ordering is important |735736(See `fzf --man` for the details)737738### Performance739740fzf is fast. Performance should not be a problem in most use cases. However,741you might want to be aware of the options that can affect performance.
1 unmodified line
743- `--ansi` tells fzf to extract and parse ANSI color codes in the input, and it744 makes the initial scanning slower. So it's not recommended that you add it745 to your `$FZF_DEFAULT_OPTS`.746- `--nth` makes fzf slower because it has to tokenize each line.747- A plain string `--delimiter` should be preferred over a regular expression748 delimiter.749- `--with-nth` makes fzf slower as fzf has to tokenize and reassemble each750 line.751752### Executing external programs
234 unmodified lines