chore: import official kitty sources from upstream

Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
BlackAngelTV committed 2026-11-04 11:35:59 +01:00
commit 3d174c45a4
1134 files changed
+433629

No files matched your search

+209
View File
@@ -0,0 +1,209 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package subseq
import (
"fmt"
"slices"
"strings"
"github.com/kovidgoyal/go-parallel"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
const (
LEVEL1 = "/"
LEVEL2 = "-_0123456789"
LEVEL3 = "."
)
type resolved_options_type struct {
level1, level2, level3 []rune
}
type Options struct {
Level1, Level2, Level3 string
NumberOfThreads int
}
type Match struct {
Positions []int
Score float64
idx int
Text string
}
func level_factor_for(current_lcase, last_lcase, current_cased, last_cased rune, opts *resolved_options_type) int {
switch {
case slices.Contains(opts.level1, last_lcase):
return 90
case slices.Contains(opts.level2, last_lcase):
return 80
case last_lcase == last_cased && current_lcase != current_cased: // camelCase
return 80
case slices.Contains(opts.level3, last_lcase):
return 70
default:
return 0
}
}
type workspace_type struct {
positions [][]int // positions of each needle char in haystack
level_factors []int
best []float64 // highest score of a match ending at each position of each needle char, flattened
prev []int // index into the positions of the previous needle char for that match
max_score_per_char float64
}
func (w *workspace_type) initialize(haystack_sz, needle_sz int) {
if cap(w.positions) < needle_sz {
w.positions = make([][]int, needle_sz)
} else {
w.positions = w.positions[:needle_sz]
}
if cap(w.level_factors) < haystack_sz {
w.level_factors = make([]int, 2*haystack_sz)
} else {
w.level_factors = w.level_factors[:haystack_sz]
}
for i, s := range w.positions {
if cap(s) < haystack_sz {
w.positions[i] = make([]int, 0, 2*haystack_sz)
} else {
w.positions[i] = w.positions[i][:0]
}
}
}
func (w *workspace_type) char_score(pos, distance int) float64 {
if w.level_factors[pos] > 0 {
return (100.0 * w.max_score_per_char) / float64(w.level_factors[pos]) // at a special location
}
return (0.75 * w.max_score_per_char) / float64(distance)
}
func has_atleast_one_match(w *workspace_type) (found bool) {
p := -1
for i := range len(w.positions) {
if len(w.positions[i]) == 0 { // all chars of needle not in haystack
return false
}
found = false
for _, pos := range w.positions[i] {
if pos > p {
p = pos
found = true
break
}
}
if !found { // chars of needle not present in sequence in haystack
return false
}
}
return true
}
func score_item(item string, idx int, needle []rune, opts *resolved_options_type, w *workspace_type) *Match {
ans := &Match{idx: idx, Text: item, Positions: make([]int, len(needle))}
haystack := []rune(strings.ToLower(item))
orig_haystack := []rune(item)
w.initialize(len(orig_haystack), len(needle))
for i := range len(haystack) {
level_factor_calculated := false
for j := range len(needle) {
if needle[j] == haystack[i] {
if !level_factor_calculated {
level_factor_calculated = true
if i > 0 {
w.level_factors[i] = level_factor_for(haystack[i], haystack[i-1], orig_haystack[i], orig_haystack[i-1], opts)
}
}
w.positions[j] = append(w.positions[j], i)
}
}
}
w.max_score_per_char = (1.0/float64(len(orig_haystack)) + 1.0/float64(len(needle))) / 2.0
if !has_atleast_one_match(w) {
return ans
}
// Find the highest scoring monotonic positions one needle char at a time
n := 0
for _, positions := range w.positions {
n += len(positions)
}
if cap(w.best) < n {
w.best, w.prev = make([]float64, 2*n), make([]int, 2*n)
}
for k, pos := range w.positions[0] {
w.best[k] = w.char_score(pos, pos+1)
}
off := 0 // offset of the entries for the previous needle char in best
for j := 1; j < len(w.positions); j++ {
prev_positions, next_off := w.positions[j-1], off+len(w.positions[j-1])
for k, pos := range w.positions[j] {
score, from := 0.0, 0
for i := 0; i < len(prev_positions) && prev_positions[i] < pos; i++ {
s := w.best[off+i]
if s == 0 { // no match ends here, all scores are > 0
continue
}
if distance := pos - prev_positions[i]; distance < 2 {
s += w.max_score_per_char // consecutive chars
} else {
s += w.char_score(pos, distance)
}
if s > score {
score, from = s, i
}
}
w.best[next_off+k], w.prev[next_off+k] = score, from
}
off = next_off
}
last, k := len(w.positions)-1, 0
for i := range len(w.positions[last]) {
if w.best[off+i] > ans.Score {
ans.Score, k = w.best[off+i], i
}
}
for j := last; j > 0; j-- {
ans.Positions[j] = w.positions[j][k]
k = w.prev[off+k]
off -= len(w.positions[j-1])
}
ans.Positions[0] = w.positions[0][k]
if ans.Score > 0 {
adjust := utils.RuneOffsetsToByteOffsets(item)
for i := range ans.Positions {
ans.Positions[i] = adjust(ans.Positions[i])
}
}
return ans
}
func ScoreItems(query string, items []string, opts Options) []*Match {
ans := make([]*Match, len(items))
nr := []rune(strings.ToLower(query))
if opts.Level1 == "" {
opts.Level1 = LEVEL1
}
if opts.Level2 == "" {
opts.Level2 = LEVEL2
}
if opts.Level3 == "" {
opts.Level3 = LEVEL3
}
ropts := resolved_options_type{
level1: []rune(opts.Level1), level2: []rune(opts.Level2), level3: []rune(opts.Level3),
}
parallel.Run_in_parallel_over_range(opts.NumberOfThreads, func(start, limit int) {
w := workspace_type{}
for i := start; i < limit; i++ {
ans[i] = score_item(items[i], i, nr, &ropts, &w)
}
}, 0, len(items))
return ans
}
+203
View File
@@ -0,0 +1,203 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package subseq
import (
"fmt"
"github.com/kovidgoyal/kitty/tools/utils"
"math/rand"
"slices"
"strconv"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestSubseq(t *testing.T) {
var positions [][]int
sort_by_score := false
simple := func(items, query string, expected ...string) {
matches := ScoreItems(query, utils.Splitlines(items), Options{})
if sort_by_score {
matches = utils.StableSort(matches, func(a, b *Match) int {
if b.Score < a.Score {
return -1
}
if b.Score > a.Score {
return 1
}
return 0
})
}
actual := make([]string, 0, len(matches))
actual_positions := make([][]int, 0, len(matches))
for _, m := range matches {
if m.Score > 0 {
actual = append(actual, m.Text)
actual_positions = append(actual_positions, m.Positions)
}
}
if expected == nil {
expected = []string{}
}
if diff := cmp.Diff(expected, actual); diff != "" {
t.Fatalf("Failed for items: %v\nMatches: %#v\n%s", utils.Splitlines(items), matches, diff)
}
if positions != nil {
if diff := cmp.Diff(positions, actual_positions); diff != "" {
t.Fatalf("Failed positions for items: %v\n%s", utils.Splitlines(items), diff)
}
positions = nil
}
}
simple("test\nxyz", "te", "test")
simple("abc\nxyz", "ba")
simple("abc\n123", "abc", "abc")
simple("test\nxyz", "Te", "test")
simple("test\nxyz", "XY", "xyz")
simple("test\nXYZ", "xy", "XYZ")
simple("test\nXYZ", "mn")
positions = [][]int{{0, 2}, {0, 1}}
simple("abc\nac", "ac", "abc", "ac")
positions = [][]int{{0}}
simple("abc\nv", "a", "abc")
positions = [][]int{{len("汉"), 7}}
simple("汉a字b\nxyz", "ab", "汉a字b")
sort_by_score = true
// Match at start
simple("archer\nelementary", "e", "elementary", "archer")
// Match at level factor
simple("xxxy\nxx/y", "y", "xx/y", "xxxy")
// CamelCase
simple("xxxy\nxxxY", "y", "xxxY", "xxxy")
// Total length
simple("xxxya\nxxxy", "y", "xxxy", "xxxya")
// Distance
simple("abbc\nabc", "ac", "abc", "abbc")
// Extreme chars
simple("xxa\naxx", "a", "axx", "xxa")
// Highest score
positions = [][]int{{3}}
simple("xa/a", "a", "xa/a")
sort_by_score = false
items := make([]string, 256)
for i := range items {
items[i] = strconv.Itoa(i)
}
expected := make([]string, 0, len(items))
for _, x := range items {
if strings.ContainsRune(x, rune('2')) {
expected = append(expected, x)
}
}
simple(strings.Join(items, "\n"), "2", expected...)
}
var theme_names = []string{
"1984 Dark", "Adwaita darker", "Aquarium Light", "Atelier Plateau Dark", "Ayu Mirage", "Base2Tone Heath Dark",
"Base2Tone Sea Dark", "Base4Tone_Modern_W Dark", "Bluloco Dark", "C64", "Catppuccin-Latte", "Chalkboard",
"Copland OS", "Darkside", "Doom Vibrant", "Earthsong", "Everforest Light Hard", "Flexoki (Dark)",
"GitHub Dark Colorblind", "GitHub Light High Contrast", "Gnome-ish gray-on-black", "Gruvbox Light Soft",
"Gruvbox Material Light Medium", "HardHacker", "IC Green PPL", "Kanagawa_dragon", "Kibble", "Linh", "Mayukai",
"Modus Vivendi", "N0tch2k", "Nord", "One Half Dark", "Pastel EGA", "Red Alert", "Ryoccino", "Selenized White",
"Serendipity Sunset", "Soft Server", "Solarized Dark Higher Contrast", "Sonokai Sushia", "Spring", "Teerb",
"Tokyo Night", "Tomorrow", "Tomorrow Night Eighties", "Ubuntu", "Wez", "Yorumi Kraken", "ferra", "pink lavender",
"zenbones_light",
}
func score_positions(w *workspace_type, positions []int) (ans float64) {
for i, pos := range positions {
distance := pos + 1
if i > 0 {
distance = pos - positions[i-1]
if distance < 2 {
ans += w.max_score_per_char
continue
}
}
if w.level_factors[pos] > 0 {
ans += (100.0 * w.max_score_per_char) / float64(w.level_factors[pos])
} else {
ans += (0.75 * w.max_score_per_char) / float64(distance)
}
}
return
}
// Try every monotonic set of positions for the item last scored with w
func brute_force(w *workspace_type) (best float64) {
positions := make([]int, len(w.positions))
var recurse func(j int)
recurse = func(j int) {
if j == len(positions) {
best = max(best, score_positions(w, positions))
return
}
for _, pos := range w.positions[j] {
if j == 0 || pos > positions[j-1] {
positions[j] = pos
recurse(j + 1)
}
}
}
recurse(0)
return
}
func TestSubseqBruteForce(t *testing.T) {
opts := resolved_options_type{level1: []rune(" "), level2: []rune(LEVEL2), level3: []rune(LEVEL3)}
w := workspace_type{}
r := rand.New(rand.NewSource(1))
for range 200 {
name := []rune(strings.ToLower(theme_names[r.Intn(len(theme_names))]))
idx := r.Perm(len(name))[:1+r.Intn(min(6, len(name)))]
slices.Sort(idx)
needle := make([]rune, len(idx))
for i, x := range idx {
needle[i] = name[x]
}
for _, item := range theme_names {
m := score_item(item, 0, needle, &opts, &w)
if expected := brute_force(&w); m.Score != expected {
t.Fatalf("Score for %#v in %#v: %v != %v", string(needle), item, m.Score, expected)
}
if m.Score > 0 {
ok := score_positions(&w, m.Positions) == m.Score
for i, pos := range m.Positions {
ok = ok && strings.ToLower(item)[pos] == byte(needle[i]) && (i == 0 || pos > m.Positions[i-1])
}
if !ok {
t.Fatalf("Positions for %#v in %#v: %v do not give the score %v", string(needle), item, m.Positions, m.Score)
}
}
}
}
// the old code tried every combination of positions here, which never finishes
m := ScoreItems(strings.Repeat("a", 100), []string{strings.Repeat("a", 200)}, Options{})[0]
expected := make([]int, 100)
for i := range expected {
expected[i] = i
}
if diff := cmp.Diff(expected, m.Positions); diff != "" {
t.Fatalf("Failed positions for long needle:\n%s", diff)
}
}
func BenchmarkScoreItems(b *testing.B) {
for _, query := range []string{"dark", "tokyo night", "solarized dark higher contrast"} {
b.Run(query, func(b *testing.B) {
for b.Loop() {
for i := range len(query) { // as if typed one char at a time
ScoreItems(query[:i+1], theme_names, Options{Level1: " "})
}
}
})
}
}