Skip to content
Myr

result.go

This file

Path

src/result.go

436 lines · 10.2 KiB · Go

Last changed by

Fix --tiebreak=pathname with non-ASCII textJunegunn Choibefore adoptionb395cfb

History of this file

Take it

1package fzf23import (4	"math"5	"slices"6	"sort"7	"unicode"89	"github.com/junegunn/fzf/src/tui"10	"github.com/junegunn/fzf/src/util"11)1213// Offset holds two 32-bit integers denoting the offsets of a matched substring14type Offset [2]int321516type colorOffset struct {17	offset [2]int3218	color  tui.ColorPair19	match  bool20	url    *url21}2223func (co colorOffset) IsFullBgMarker(at int32) bool {24	return at == co.offset[0] && at == co.offset[1] && co.color.Attr()&tui.FullBg > 025}2627type Result struct {28	item   *Item29	points [4]uint1630}3132func buildResult(item *Item, offsets []Offset, score int) Result {33	if len(offsets) > 1 {34		slices.SortFunc(offsets, compareOffsets)35	}3637	minBegin := math.MaxUint1638	minEnd := math.MaxUint1639	maxEnd := 040	validOffsetFound := false41	for _, offset := range offsets {42		b, e := int(offset[0]), int(offset[1])43		if b < e {44			minBegin = min(b, minBegin)45			minEnd = min(e, minEnd)46			maxEnd = max(e, maxEnd)47			validOffsetFound = true48		}49	}5051	return buildResultFromBounds(item, score, minBegin, minEnd, maxEnd, validOffsetFound)52}5354// buildResultFromBounds builds a Result from pre-computed offset bounds.55func buildResultFromBounds(item *Item, score int, minBegin, minEnd, maxEnd int, validOffsetFound bool) Result {56	result := Result{item: item}57	numChars := item.text.Length()5859	for idx, criterion := range sortCriteria {60		val := uint16(math.MaxUint16)61		switch criterion {62		case byScore:63			// Higher is better64			val = math.MaxUint16 - util.AsUint16(score)65		case byChunk:66			if validOffsetFound {67				b := minBegin68				e := maxEnd69				for ; b >= 1; b-- {70					if unicode.IsSpace(item.text.Get(b - 1)) {71						break72					}73				}74				for ; e < numChars; e++ {75					if unicode.IsSpace(item.text.Get(e)) {76						break77					}78				}79				val = util.AsUint16(e - b)80			}81		case byLength:82			val = item.TrimLength()83		case byPathname:84			if validOffsetFound {85				// Rune index, to be comparable with minBegin86				lastDelim := -187				for i := numChars - 1; i >= 0; i-- {88					if r := item.text.Get(i); r == '/' || r == '\\' {89						lastDelim = i90						break91					}92				}93				if lastDelim <= minBegin {94					val = util.AsUint16(minBegin - lastDelim)95				}96			}97		case byBegin, byEnd:98			if validOffsetFound {99				whitePrefixLen := 0100				for idx := range numChars {101					r := item.text.Get(idx)102					whitePrefixLen = idx103					if idx == minBegin || !unicode.IsSpace(r) {104						break105					}106				}107				if criterion == byBegin {108					val = util.AsUint16(minEnd - whitePrefixLen)109				} else {110					val = util.AsUint16(math.MaxUint16 - math.MaxUint16*(maxEnd-whitePrefixLen)/(int(item.TrimLength())+1))111				}112			}113		}114		result.points[3-idx] = val115	}116117	return result118}119120// Sort criteria to use. Never changes once fzf is started.121var sortCriteria []criterion122123// Index returns ordinal index of the Item124func (result *Result) Index() int32 {125	return result.item.Index()126}127128func minRank() Result {129	return Result{item: &minItem, points: [4]uint16{math.MaxUint16, 0, 0, 0}}130}131132func (result *Result) colorOffsets(matchOffsets []Offset, nthOffsets []Offset, theme *tui.ColorTheme, colBase tui.ColorPair, colMatch tui.ColorPair, attrNth tui.Attr, nthOverlay tui.Attr, hidden bool) []colorOffset {133	itemColors := result.item.Colors()134135	// No ANSI codes136	if len(itemColors) == 0 && len(nthOffsets) == 0 {137		offsets := make([]colorOffset, len(matchOffsets))138		for i, off := range matchOffsets {139			offsets[i] = colorOffset{offset: [2]int32{off[0], off[1]}, color: colMatch, match: true}140		}141		return offsets142	}143144	// Find max column145	var maxCol int32146	for _, off := range append(matchOffsets, nthOffsets...) {147		if off[1] > maxCol {148			maxCol = off[1]149		}150	}151	for _, ansi := range itemColors {152		if ansi.offset[1] > maxCol {153			maxCol = ansi.offset[1]154		}155	}156157	type cellInfo struct {158		index int159		color bool160		match bool161		nth   bool162		fbg   tui.Color163	}164165	cols := make([]cellInfo, maxCol+1)166	for idx := range cols {167		cols[idx].fbg = -1168	}169	for colorIndex, ansi := range itemColors {170		if ansi.offset[0] == ansi.offset[1] && ansi.color.attr&tui.FullBg > 0 {171			cols[ansi.offset[0]].fbg = ansi.color.lbg172		} else {173			for i := ansi.offset[0]; i < ansi.offset[1]; i++ {174				cols[i] = cellInfo{colorIndex, true, false, false, cols[i].fbg}175			}176		}177	}178179	for _, off := range matchOffsets {180		for i := off[0]; i < off[1]; i++ {181			cols[i].match = true182		}183	}184185	for _, off := range nthOffsets {186		for i := off[0]; i < off[1]; i++ {187			cols[i].nth = true188		}189	}190191	// slices.SortFunc(offsets, compareOffsets)192193	// Merge offsets194	// ------------  ----  --  ----195	//   ++++++++      ++++++++++196	// --++++++++--  --++++++++++---197	curr := cellInfo{0, false, false, false, -1}198	start := 0199	ansiToColorPair := func(ansi ansiOffset, base tui.ColorPair) tui.ColorPair {200		if !theme.Colored {201			// Ignore ANSI colors but keep the attributes. Retain the base202			// colors (e.g. an overridden input-bg or list-bg) instead of203			// resetting to the terminal default.204			return tui.NewColorPair(base.Fg(), base.Bg(), ansi.color.attr).MergeAttr(base)205		}206		// fd --color always | fzf --ansi --delimiter / --nth -1 --color fg:dim:strip,nth:regular207		if base.ShouldStripColors() {208			return base209		}210		fg := ansi.color.fg211		bg := ansi.color.bg212		if fg == -1 {213			fg = colBase.Fg()214		}215		if bg == -1 {216			bg = colBase.Bg()217		}218		return tui.NewColorPair(fg, bg, ansi.color.attr).WithUl(ansi.color.ul).MergeAttr(base)219	}220	fgAttr := tui.ColNormal.Attr()221	nthAttrFinal := fgAttr.Merge(attrNth).Merge(nthOverlay)222	nthBase := colBase.WithNewAttr(nthAttrFinal)223224	var colors []colorOffset225	add := func(idx int) {226		if curr.fbg >= 0 {227			colors = append(colors, colorOffset{228				offset: [2]int32{int32(start), int32(start)},229				color:  tui.NewColorPair(-1, curr.fbg, tui.FullBg),230				match:  false,231				url:    nil})232		}233		if (curr.color || curr.nth || curr.match) && idx > start {234			if curr.match {235				var color tui.ColorPair236				if curr.nth {237					color = nthBase.Merge(colMatch)238				} else {239					color = colBase.Merge(colMatch)240				}241				var url *url242				if curr.color {243					ansi := itemColors[curr.index]244					url = ansi.color.url245					origColor := ansiToColorPair(ansi, colMatch)246					// hl or hl+ only sets the foreground color, so colMatch is the247					// combination of either [hl and bg] or [hl+ and bg+].248					//249					// If the original text already has background color, and the250					// foreground color of colMatch is -1, we shouldn't only apply the251					// background color of colMatch.252					// e.g. echo -e "\x1b[32;7mfoo\x1b[mbar" | fzf --ansi --color bg+:1,hl+:-1:underline253					//      echo -e "\x1b[42mfoo\x1b[mbar" | fzf --ansi --color bg+:1,hl+:-1:underline254					if color.Fg().IsDefault() && origColor.HasBg() {255						color = origColor256						if curr.nth {257							color = color.WithAttr((attrNth &^ tui.AttrRegular).Merge(nthOverlay))258						}259					} else {260						color = origColor.MergeNonDefault(color)261					}262				}263				colors = append(colors, colorOffset{264					offset: [2]int32{int32(start), int32(idx)}, color: color, match: true, url: url})265			} else if curr.color {266				ansi := itemColors[curr.index]267				base := colBase268				if curr.nth {269					base = nthBase270				}271				if hidden {272					base = base.WithFg(theme.Nomatch)273				}274				color := ansiToColorPair(ansi, base)275				colors = append(colors, colorOffset{276					offset: [2]int32{int32(start), int32(idx)},277					color:  color,278					match:  false,279					url:    ansi.color.url})280			} else {281				color := nthBase282				if hidden {283					color = color.WithFg(theme.Nomatch)284				}285				colors = append(colors, colorOffset{286					offset: [2]int32{int32(start), int32(idx)},287					color:  color,288					match:  false,289					url:    nil})290			}291		}292	}293	for idx, col := range cols {294		if col != curr {295			add(idx)296			start = idx297			curr = col298		}299	}300	add(int(maxCol))301	return colors302}303304func compareOffsets(a, b Offset) int {305	if a[0] < b[0] {306		return -1307	}308	if a[0] > b[0] {309		return 1310	}311	if a[1] < b[1] {312		return -1313	}314	if a[1] > b[1] {315		return 1316	}317	return 0318}319320// ByRelevance is for sorting Items321type ByRelevance []Result322323func (a ByRelevance) Len() int {324	return len(a)325}326327func (a ByRelevance) Swap(i, j int) {328	a[i], a[j] = a[j], a[i]329}330331func (a ByRelevance) Less(i, j int) bool {332	return compareRanks(a[i], a[j], false)333}334335// ByRelevanceTac is for sorting Items336type ByRelevanceTac []Result337338func (a ByRelevanceTac) Len() int {339	return len(a)340}341342func (a ByRelevanceTac) Swap(i, j int) {343	a[i], a[j] = a[j], a[i]344}345346func (a ByRelevanceTac) Less(i, j int) bool {347	return compareRanks(a[i], a[j], true)348}349350// radixSortResults sorts Results by their points key using LSD radix sort.351// O(n) time complexity vs O(n log n) for comparison sort.352// The sort is stable, so equal-key items maintain original (item-index) order.353// For tac mode, runs of equal keys are reversed after sorting.354func radixSortResults(a []Result, tac bool, scratch []Result) []Result {355	n := len(a)356	if n < 128 {357		if tac {358			sort.Sort(ByRelevanceTac(a))359		} else {360			sort.Sort(ByRelevance(a))361		}362		return scratch[:0]363	}364365	if cap(scratch) < n {366		scratch = make([]Result, n)367	}368	buf := scratch[:n]369	src, dst := a, buf370	scattered := 0371372	// OR of all keys: a byte position that is zero here is zero in every key,373	// so its pass is a no-op and can be skipped without a histogram scan.374	// With the common two-criteria setup the low 32 bits are always zero.375	var keyOR uint64376	for i := range src {377		keyOR |= sortKey(&src[i])378	}379380	for pass := range 8 {381		shift := uint(pass) * 8382383		if byte(keyOR>>shift) == 0 {384			continue385		}386387		var count [256]int388		for i := range src {389			count[byte(sortKey(&src[i])>>shift)]++390		}391392		// Skip if all items have the same byte value at this position393		if count[byte(sortKey(&src[0])>>shift)] == n {394			continue395		}396397		var offset [256]int398		for i := 1; i < 256; i++ {399			offset[i] = offset[i-1] + count[i-1]400		}401402		for i := range src {403			b := byte(sortKey(&src[i]) >> shift)404			dst[offset[b]] = src[i]405			offset[b]++406		}407408		src, dst = dst, src409		scattered++410	}411412	// If odd number of scatters, data is in buf, copy back to a413	if scattered%2 == 1 {414		copy(a, src)415	}416417	// Handle tac: reverse runs of equal keys so equal-key items418	// are in reverse item-index order419	if tac {420		i := 0421		for i < n {422			ki := sortKey(&a[i])423			j := i + 1424			for j < n && sortKey(&a[j]) == ki {425				j++426			}427			if j-i > 1 {428				for l, r := i, j-1; l < r; l, r = l+1, r-1 {429					a[l], a[r] = a[r], a[l]430				}431			}432			i = j433		}434	}435	return scratch436}