Repository navigation
Expand file tree
/
Copy pathfzf.c
More file actions
3493 lines (3174 loc) · 111 KB
/
Copy pathfzf.c
File metadata and controls
3493 lines (3174 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
#include "fzf-private.h"
#include "fzf-simd-prefilter.h"
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
// UTF8PROC integration for Unicode support
#include "utf8proc-2.10.0/utf8proc.h"
#include "utf8_char_index.h"
#include "fzf-normalize.inc"
static FZF_THREAD_LOCAL bool fzf_allocation_failure;
FZF_THREAD_LOCAL bool fzf_simd_prefilter_allowed = true;
void fzf_clear_allocation_failure(void) {
fzf_allocation_failure = false;
}
bool fzf_allocation_failed(void) {
return fzf_allocation_failure;
}
static void fzf_mark_allocation_failure(void) {
fzf_allocation_failure = true;
}
// TODO(conni2461): UNICODE HEADER
#define UNICODE_MAXASCII 0x7f
/* Pattern parsing runs on the Emacs thread and on persistent scoring threads.
strtok stores its cursor in process-global state, so concurrent parses can
make one thread read another thread's freed pattern buffer. Use the native
reentrant tokenizer on each supported platform. */
static char *fzf_strtok_r(char *str, const char *delim, char **state) {
#ifdef _WIN32
return strtok_s(str, delim, state);
#else
return strtok_r(str, delim, state);
#endif
}
#define SFREE(x) \
if (x) { \
free(x); \
}
/* Helpers */
#define free_alloc(obj) \
if ((obj).allocated) { \
free((obj).data); \
}
#define gen_simple_slice(name, type) \
typedef struct { \
type *data; \
size_t size; \
} name##_slice_t; \
static name##_slice_t slice_##name(type *input, size_t from, size_t to) { \
return (name##_slice_t){.data = input + from, .size = to - from}; \
}
#define gen_slice(name, type) \
gen_simple_slice(name, type); \
static name##_slice_t slice_##name##_right(type *input, size_t to) { \
return slice_##name(input, 0, to); \
}
gen_slice(i16, int16_t);
gen_simple_slice(i32, int32_t);
gen_slice(str, const char);
#undef gen_slice
#undef gen_simple_slice
/* TODO(conni2461): additional types (utf8) */
typedef int32_t char_class;
typedef char byte;
typedef enum {
ScoreMatch = 16,
ScoreGapStart = -3,
ScoreGapExtention = -1,
BonusBoundary = ScoreMatch / 2,
BonusNonWord = ScoreMatch / 2,
BonusCamel123 = BonusBoundary + ScoreGapExtention,
BonusConsecutive = -(ScoreGapStart + ScoreGapExtention),
BonusFirstCharMultiplier = 2,
} score_t;
typedef enum {
CharWhite = 0,
CharNonWord,
CharDelimiter,
CharLower,
CharUpper,
CharLetter,
CharNumber
} char_types;
typedef struct {
int16_t boundary_white;
int16_t boundary_delimiter;
char_class initial_class;
bool path_delimiters_only;
} score_scheme_config_t;
static const score_scheme_config_t score_scheme_configs[] = {
[FZF_SCORE_SCHEME_DEFAULT] =
{BonusBoundary + 2, BonusBoundary + 1, CharWhite, false},
[FZF_SCORE_SCHEME_PATH] =
{BonusBoundary, BonusBoundary + 1, CharDelimiter, true},
[FZF_SCORE_SCHEME_HISTORY] =
{BonusBoundary, BonusBoundary, CharWhite, false},
};
static const score_scheme_config_t *score_scheme_config(
const fzf_slab_t *slab) {
fzf_score_scheme_t scheme = slab ? slab->score_scheme
: FZF_SCORE_SCHEME_DEFAULT;
if ((unsigned int)scheme > FZF_SCORE_SCHEME_HISTORY)
scheme = FZF_SCORE_SCHEME_DEFAULT;
return &score_scheme_configs[scheme];
}
static int32_t index_byte(fzf_string_t *string, char b) {
if (string->size == 0) return -1;
if (string->data[0] == b) return 0;
const char *match = memchr(
string->data + 1, (unsigned char)b, string->size - 1);
return match ? (int32_t)(match - string->data) : -1;
}
static bool fzf_unicode_is_space(utf8proc_int32_t cp) {
if ((cp >= 0x09 && cp <= 0x0d) || cp == 0x85)
return true;
utf8proc_category_t category = utf8proc_category(cp);
return category == UTF8PROC_CATEGORY_ZS ||
category == UTF8PROC_CATEGORY_ZL ||
category == UTF8PROC_CATEGORY_ZP;
}
/* Return a byte count. The anchored algorithms use byte slices even on the
UTF-8 path, so counting raw `isspace' bytes is both locale-dependent and
unsafe: in a UTF-8 locale a continuation byte such as 0xa0 can be classified
as whitespace and split a CJK codepoint. */
static size_t leading_whitespaces(fzf_string_t *str) {
size_t pos = 0;
while (pos < str->size) {
utf8proc_int32_t cp;
utf8proc_ssize_t width = utf8_iterate_lossy(
(const utf8proc_uint8_t *)str->data + pos,
(utf8proc_ssize_t)(str->size - pos), &cp);
if (!fzf_unicode_is_space(cp)) break;
pos += (size_t)width;
}
return pos;
}
static size_t trailing_whitespaces(fzf_string_t *str) {
size_t pos = 0;
size_t trailing = 0;
/* A string ending in an ASCII non-space (paths, identifiers -- the
common case for every `$'-anchored term) has no trailing whitespace;
answer without the full forward decode. */
if (str->size > 0) {
unsigned char last = (unsigned char)str->data[str->size - 1];
if (last < 0x80 && !((last >= 0x09 && last <= 0x0d) || last == 0x20))
return 0;
}
while (pos < str->size) {
utf8proc_int32_t cp;
utf8proc_ssize_t width = utf8_iterate_lossy(
(const utf8proc_uint8_t *)str->data + pos,
(utf8proc_ssize_t)(str->size - pos), &cp);
if (fzf_unicode_is_space(cp))
trailing += (size_t)width;
else
trailing = 0;
pos += (size_t)width;
}
return trailing;
}
static void copy_runes(fzf_string_t *src, fzf_i32_t *destination) {
for (size_t i = 0; i < src->size; i++) {
destination->data[i] = (int32_t)src->data[i];
}
}
static void copy_into_i16(i16_slice_t *src, fzf_i16_t *dest) {
for (size_t i = 0; i < src->size; i++) {
dest->data[i] = src->data[i];
}
}
// char* helpers
static char *trim_whitespace_left(char *str, size_t *len) {
for (size_t i = 0; i < *len; i++) {
if (str[0] == ' ') {
(*len)--;
str++;
} else {
break;
}
}
return str;
}
static bool has_prefix(const char *str, const char *prefix, size_t prefix_len) {
return strncmp(prefix, str, prefix_len) == 0;
}
static bool has_suffix(const char *str, size_t len, const char *suffix,
size_t suffix_len) {
return len >= suffix_len &&
strncmp(slice_str(str, len - suffix_len, len).data, suffix,
suffix_len) == 0;
}
static char *str_replace_char(char *str, char find, char replace) {
char *current_pos = strchr(str, find);
while (current_pos) {
*current_pos = replace;
current_pos = strchr(current_pos, find);
}
return str;
}
static char *str_replace(char *orig, char *rep, char *with) {
if (!orig || !rep || !with) {
return NULL;
}
char *result;
char *ins;
char *tmp;
size_t len_rep = strlen(rep);
size_t len_front = 0;
size_t len_orig = strlen(orig);
size_t len_with = strlen(with);
size_t count = 0;
if (len_rep == 0) {
return NULL;
}
ins = orig;
for (; (tmp = strstr(ins, rep)); ++count) {
ins = tmp + len_rep;
}
size_t result_len = len_orig;
if (len_with >= len_rep) {
size_t growth = len_with - len_rep;
if (growth && count > (SIZE_MAX - result_len - 1) / growth) {
return NULL;
}
result_len += growth * count;
} else {
size_t shrink = len_rep - len_with;
if (count > result_len / shrink) {
return NULL;
}
result_len -= shrink * count;
}
tmp = result = (char *)malloc(result_len + 1);
if (!result) {
return NULL;
}
while (count--) {
ins = strstr(orig, rep);
len_front = (size_t)(ins - orig);
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep;
len_orig -= len_front + len_rep;
}
strncpy(tmp, orig, len_orig);
tmp[len_orig] = 0;
return result;
}
static char *str_duplicate(const char *str, size_t size) {
if (size == SIZE_MAX) return NULL;
char *copy = malloc(size + 1);
if (!copy) return NULL;
memcpy(copy, str, size);
copy[size] = '\0';
return copy;
}
// UTF-8 aware lowercase conversion
static char *str_tolower(const char *str, size_t size) {
// Check if string is pure ASCII for fast path
if (is_ascii_utf8proc(str, size)) {
// Fast ASCII path
if (size == SIZE_MAX) return NULL;
char *lower_str = (char *)malloc(size + 1);
if (!lower_str) return NULL;
for (size_t i = 0; i < size; i++) {
lower_str[i] = (char)tolower((uint8_t)str[i]);
}
lower_str[size] = '\0';
return lower_str;
}
// UTF-8 path: need to handle multibyte characters
// Allocate worst case (each char could expand to 4 bytes)
if (size > (SIZE_MAX - 1) / 4) return NULL;
char *lower_str = (char *)malloc(size * 4 + 1);
if (!lower_str) return NULL;
size_t out_pos = 0;
size_t in_pos = 0;
while (in_pos < size) {
utf8proc_int32_t codepoint;
utf8proc_ssize_t bytes = utf8proc_iterate(
(const utf8proc_uint8_t*)(str + in_pos),
size - in_pos, &codepoint);
if (bytes <= 0) {
// Invalid UTF-8, copy byte as-is
lower_str[out_pos++] = str[in_pos++];
continue;
}
// Apply case folding
utf8proc_int32_t folded = utf8proc_case_fold(codepoint);
// Encode back to UTF-8
utf8proc_ssize_t out_bytes = utf8proc_encode_char(
folded, (utf8proc_uint8_t*)(lower_str + out_pos));
if (out_bytes > 0) {
out_pos += out_bytes;
} else {
// Encoding failed, copy original
memcpy(lower_str + out_pos, str + in_pos, bytes);
out_pos += bytes;
}
in_pos += bytes;
}
lower_str[out_pos] = '\0';
// Resize to actual size
char *result = (char *)realloc(lower_str, out_pos + 1);
return result ? result : lower_str;
}
static int16_t max16(int16_t a, int16_t b) {
return (a > b) ? a : b;
}
static size_t min64u(size_t a, size_t b) {
return (a < b) ? a : b;
}
fzf_position_t *fzf_pos_array(size_t len) {
if (len > SIZE_MAX / sizeof(uint32_t)) {
fzf_mark_allocation_failure();
return NULL;
}
fzf_position_t *pos = (fzf_position_t *)malloc(sizeof(fzf_position_t));
if (!pos) {
fzf_mark_allocation_failure();
return NULL;
}
pos->size = 0;
pos->cap = len;
if (len > 0) {
pos->data = (uint32_t *)malloc(len * sizeof(uint32_t));
if (!pos->data) {
free(pos);
fzf_mark_allocation_failure();
return NULL;
}
} else {
pos->data = NULL;
}
return pos;
}
static bool resize_pos(fzf_position_t *pos, size_t add_len, size_t comp) {
if (!pos) {
return true;
}
if (comp > SIZE_MAX - pos->size) {
fzf_mark_allocation_failure();
return false;
}
size_t needed = pos->size + comp;
if (needed <= pos->cap) return true;
size_t growth = add_len > 0 ? add_len : 1;
size_t new_cap = pos->cap;
if (growth > SIZE_MAX - new_cap)
new_cap = needed;
else
new_cap += growth;
if (new_cap < needed) new_cap = needed;
if (new_cap > SIZE_MAX / sizeof(uint32_t)) {
fzf_mark_allocation_failure();
return false;
}
uint32_t *new_data =
(uint32_t *)realloc(pos->data, sizeof(uint32_t) * new_cap);
if (!new_data) {
fzf_mark_allocation_failure();
return false;
}
pos->data = new_data;
pos->cap = new_cap;
return true;
}
static bool unsafe_append_pos(fzf_position_t *pos, size_t value) {
if (!resize_pos(pos, pos->cap, 1)) return false;
pos->data[pos->size] = value;
pos->size++;
return true;
}
static bool append_pos(fzf_position_t *pos, size_t value) {
return !pos || unsafe_append_pos(pos, value);
}
static bool insert_range(fzf_position_t *pos, size_t start, size_t end) {
if (!pos) {
return true;
}
if (end <= start) return true;
if (!resize_pos(pos, end - start, end - start)) return false;
for (size_t k = start; k < end; k++) {
pos->data[pos->size] = k;
pos->size++;
}
return true;
}
static fzf_i16_t alloc16(size_t *offset, fzf_slab_t *slab, size_t size) {
if (slab != NULL && *offset <= slab->I16.cap &&
size <= slab->I16.cap - *offset) {
i16_slice_t slice = slice_i16(slab->I16.data, *offset, (*offset) + size);
*offset = *offset + size;
return (fzf_i16_t){.data = slice.data,
.size = slice.size,
.cap = slice.size,
.allocated = false};
}
if (size > SIZE_MAX / sizeof(int16_t)) {
fzf_mark_allocation_failure();
return (fzf_i16_t){0};
}
int16_t *data = (int16_t *)malloc(size * sizeof(int16_t));
if (size > 0 && !data) {
fzf_mark_allocation_failure();
return (fzf_i16_t){0};
}
memset(data, 0, size * sizeof(int16_t));
return (fzf_i16_t){
.data = data, .size = size, .cap = size, .allocated = true};
}
static fzf_i32_t alloc32(size_t *offset, fzf_slab_t *slab, size_t size) {
if (slab != NULL && *offset <= slab->I32.cap &&
size <= slab->I32.cap - *offset) {
i32_slice_t slice = slice_i32(slab->I32.data, *offset, (*offset) + size);
*offset = *offset + size;
return (fzf_i32_t){.data = slice.data,
.size = slice.size,
.cap = slice.size,
.allocated = false};
}
if (size > SIZE_MAX / sizeof(int32_t)) {
fzf_mark_allocation_failure();
return (fzf_i32_t){0};
}
int32_t *data = (int32_t *)malloc(size * sizeof(int32_t));
if (size > 0 && !data) {
fzf_mark_allocation_failure();
return (fzf_i32_t){0};
}
memset(data, 0, size * sizeof(int32_t));
return (fzf_i32_t){
.data = data, .size = size, .cap = size, .allocated = true};
}
static bool score_scheme_delimiter(const score_scheme_config_t *config,
utf8proc_int32_t codepoint) {
if (codepoint == '/') return true;
/* Pinned fzf adds the host path separator alongside '/' only when they
differ. The test override exercises this Windows branch on POSIX without
defining _WIN32 and changing unrelated libc compatibility paths. */
#if defined(_WIN32) || defined(FZF_TEST_WINDOWS_PATH_SCORING)
if (config->path_delimiters_only && codepoint == '\\') return true;
#endif
return !config->path_delimiters_only &&
(codepoint == ',' || codepoint == ':' || codepoint == ';' ||
codepoint == '|');
}
static char_class char_class_of_ascii(char ch,
const score_scheme_config_t *config) {
unsigned char byte = (unsigned char)ch;
if (ch >= 'a' && ch <= 'z') {
return CharLower;
}
if (ch >= 'A' && ch <= 'Z') {
return CharUpper;
}
if (ch >= '0' && ch <= '9') {
return CharNumber;
}
if ((byte >= 0x09 && byte <= 0x0d) || byte == 0x20) {
return CharWhite;
}
if (score_scheme_delimiter(config, byte)) {
return CharDelimiter;
}
return CharNonWord;
}
// static char_class char_class_of_non_ascii(char ch) {
// return 0;
// }
static char_class char_class_of(char ch,
const score_scheme_config_t *config) {
return char_class_of_ascii(ch, config);
// if (ch <= 0x7f) {
// return char_class_of_ascii(ch);
// }
// return char_class_of_non_ascii(ch);
}
static bool char_class_is_word(char_class class) {
return class == CharLower || class == CharUpper || class == CharLetter ||
class == CharNumber;
}
static int16_t bonus_for(const score_scheme_config_t *config,
char_class prev_class, char_class class) {
if (class >= CharNonWord) {
if (prev_class == CharWhite) {
return config->boundary_white;
}
if (prev_class == CharDelimiter) {
return config->boundary_delimiter;
}
if (prev_class == CharNonWord) {
return BonusBoundary;
}
}
if ((prev_class == CharLower && class == CharUpper) ||
(prev_class != CharNumber && class == CharNumber)) {
return BonusCamel123;
}
if (class == CharNonWord || class == CharDelimiter) {
return BonusNonWord;
}
if (class == CharWhite) return config->boundary_white;
return 0;
}
static int16_t bonus_at(fzf_string_t *input, size_t idx,
const score_scheme_config_t *config) {
if (idx == 0) {
return config->boundary_white;
}
return bonus_for(config, char_class_of(input->data[idx - 1], config),
char_class_of(input->data[idx], config));
}
static utf8proc_int32_t fzf_normalize_codepoint(utf8proc_int32_t codepoint) {
if (codepoint < 0x00c0) return codepoint;
switch ((uint32_t)codepoint >> 8) {
#define FZF_NORMALIZED_SOURCE_PAGE(page) case page:
FZF_NORMALIZED_SOURCE_PAGES
#undef FZF_NORMALIZED_SOURCE_PAGE
#undef FZF_NORMALIZED_SOURCE_PAGES
break;
default:
return codepoint;
}
size_t lo = 0;
size_t hi = sizeof fzf_normalized_runes / sizeof fzf_normalized_runes[0];
while (lo < hi) {
size_t mid = lo + (hi - lo) / 2;
utf8proc_int32_t source = fzf_normalized_runes[mid].source;
if (source < codepoint)
lo = mid + 1;
else
hi = mid;
}
if (lo < sizeof fzf_normalized_runes / sizeof fzf_normalized_runes[0] &&
fzf_normalized_runes[lo].source == codepoint)
return fzf_normalized_runes[lo].target;
return codepoint;
}
static char normalize_rune(char r) {
return (char)fzf_normalize_codepoint((uint8_t)r);
}
/* fzf normalizes candidate text only when the lowercased query is already in
normalized form. A query that contains a foldable rune stays literal.
This preserves the directional contract: "e" matches "é", but "é" does
not match "e" or "ê". */
static bool pattern_can_normalize(const char *pattern, size_t byte_len) {
size_t offset = 0;
while (offset < byte_len) {
utf8proc_int32_t codepoint;
utf8proc_ssize_t width = utf8_iterate_lossy(
(const utf8proc_uint8_t *)pattern + offset,
(utf8proc_ssize_t)(byte_len - offset), &codepoint);
if (fzf_normalize_codepoint(codepoint) != codepoint) return false;
offset += (size_t)width;
}
return true;
}
static int32_t try_skip(fzf_string_t *input, bool case_sensitive, byte b,
int32_t from) {
str_slice_t slice = slice_str(input->data, (size_t)from, input->size);
fzf_string_t byte_array = {.data = slice.data, .size = slice.size};
int32_t idx = index_byte(&byte_array, b);
if (idx == 0) {
return from;
}
if (!case_sensitive && b >= 'a' && b <= 'z') {
if (idx > 0) {
str_slice_t tmp = slice_str_right(byte_array.data, (size_t)idx);
byte_array.data = tmp.data;
byte_array.size = tmp.size;
}
int32_t uidx = index_byte(&byte_array, b - (byte)32);
if (uidx >= 0) {
idx = uidx;
}
}
if (idx < 0) {
return -1;
}
return from + idx;
}
static bool is_ascii(const char *runes, size_t size) {
// TODO(conni2461): future use
/* for (size_t i = 0; i < size; i++) { */
/* if (runes[i] >= 256) { */
/* return false; */
/* } */
/* } */
return true;
}
static int32_t ascii_fuzzy_index(
fzf_string_t *input, fzf_string_t *pattern,
const fzf_ascii_query_plan_t *plan, bool case_sensitive) {
if (!is_ascii(pattern->data, pattern->size)) {
return -1;
}
#if FZF_HAVE_SIMD_PREFILTER
if (plan && plan->pattern_size == pattern->size &&
plan->case_sensitive == case_sensitive &&
pattern->size >= FZF_SIMD_FUZZY_MIN_PATTERN &&
input->size >= FZF_SIMD_FUZZY_MIN_TEXT) {
const char *first = fzf_ascii_plan_find_byte(
input->data, input->size, &plan->bytes[0], case_sensitive);
if (!first) return -1;
size_t first_index = (size_t)(first - input->data);
if (!fzf_ascii_plan_ordered_after_first(
input->data, input->size, plan, first_index))
return -1;
return first_index > 0 ? (int32_t)(first_index - 1) : 0;
}
#else
(void)plan;
#endif
int32_t first_idx = 0;
int32_t idx = 0;
for (size_t pidx = 0; pidx < pattern->size; pidx++) {
idx = try_skip(input, case_sensitive, pattern->data[pidx], idx);
if (idx < 0) {
return -1;
}
if (pidx == 0 && idx > 0) {
first_idx = idx - 1;
}
idx++;
}
return first_idx;
}
/* UTF-8 utility functions using utf8proc */
bool is_ascii_utf8proc(const char *text, size_t len) {
const unsigned char *ptr = (const unsigned char *)text;
/* fzf_has_match uses this check for every filter-only candidate. Inspect
eight bytes at a time so Unicode correctness does not add a byte-at-a-time
pre-pass to the overwhelmingly ASCII completion corpus. memcpy keeps the
load valid for unaligned strings. */
while (len >= sizeof(uint64_t)) {
uint64_t word;
memcpy(&word, ptr, sizeof(word));
if (word & UINT64_C(0x8080808080808080)) return false;
ptr += sizeof(word);
len -= sizeof(word);
}
while (len-- > 0)
if (*ptr++ & 0x80) return false;
return true;
}
static char_class char_class_of_codepoint(
utf8proc_int32_t codepoint, const score_scheme_config_t *config) {
const utf8proc_property_t *prop = utf8proc_get_property(codepoint);
switch (prop->category) {
case UTF8PROC_CATEGORY_LL: // Lowercase letter
return CharLower;
case UTF8PROC_CATEGORY_LU: // Uppercase letter
case UTF8PROC_CATEGORY_LT: // Titlecase letter
return CharUpper;
case UTF8PROC_CATEGORY_LO: // Other letter
case UTF8PROC_CATEGORY_LM: // Modifier letter
return CharLetter;
case UTF8PROC_CATEGORY_ND: // Decimal digit number
case UTF8PROC_CATEGORY_NL: // Letter number
case UTF8PROC_CATEGORY_NO: // Other number
return CharNumber;
default:
if (fzf_unicode_is_space(codepoint)) return CharWhite;
if (score_scheme_delimiter(config, codepoint)) return CharDelimiter;
return CharNonWord;
}
}
int32_t char_class_of_utf8proc(utf8proc_int32_t codepoint) {
return char_class_of_codepoint(codepoint,
&score_scheme_configs[FZF_SCORE_SCHEME_DEFAULT]);
}
utf8proc_int32_t utf8proc_case_fold(utf8proc_int32_t codepoint) {
return utf8proc_tolower(codepoint);
}
/* FuzzyMatchV2 follows fzf's unicode.IsUpper guard when it lowercases
candidate runes. This is intentionally narrower than Unicode ToLower:
titlecase letters and cased numbers can have lowercase mappings without
belonging to the Lu category. */
static utf8proc_int32_t v2_case_fold_candidate(
utf8proc_int32_t codepoint) {
return utf8proc_category(codepoint) == UTF8PROC_CATEGORY_LU
? utf8proc_case_fold(codepoint)
: codepoint;
}
/* Find the first byte of a fuzzy UTF-8 subsequence without narrowing an
input offset. Apply the same case-fold and pinned normalization map as
the scorer when NORMALIZE is true. The public compatibility wrapper below
still returns an int32_t, while internal callers can safely prefilter
size_t-bounded input. */
static bool utf8_fuzzy_index_size(fzf_string_t *input, const char *pattern,
size_t pattern_len, bool case_sensitive,
bool normalize,
bool v2_candidate_case,
size_t *first_idx_out,
size_t *input_char_count_out) {
*first_idx_out = 0;
if (input_char_count_out) *input_char_count_out = 0;
// Handle empty pattern
if (pattern_len == 0) {
if (input_char_count_out)
*input_char_count_out = utf8_strlen(input->data, input->size);
return true;
}
// Unified implementation for both ASCII and UTF-8
// This avoids the broken ascii_fuzzy_index function
const char *input_ptr = input->data;
const char *pattern_ptr = pattern;
size_t input_pos = 0;
size_t pattern_pos = 0;
size_t first_idx = 0;
size_t input_char_count = 0;
// Process each pattern character
while (pattern_pos < pattern_len && input_pos < input->size) {
utf8proc_int32_t pattern_cp, input_cp;
// Decode pattern character (handles both ASCII and UTF-8)
utf8proc_ssize_t pattern_bytes = utf8_iterate_lossy(
(const utf8proc_uint8_t*)(pattern_ptr + pattern_pos),
pattern_len - pattern_pos, &pattern_cp);
if (!case_sensitive) {
pattern_cp = utf8proc_case_fold(pattern_cp);
}
if (normalize) {
pattern_cp = fzf_normalize_codepoint(pattern_cp);
}
// Search for this pattern character starting from current position
bool found = false;
size_t search_pos = input_pos;
while (search_pos < input->size) {
utf8proc_ssize_t input_bytes = utf8_iterate_lossy(
(const utf8proc_uint8_t*)(input_ptr + search_pos),
input->size - search_pos, &input_cp);
input_char_count++;
utf8proc_int32_t input_cp_cmp = input_cp;
if (!case_sensitive) {
input_cp_cmp = v2_candidate_case
? v2_case_fold_candidate(input_cp)
: utf8proc_case_fold(input_cp);
}
if (normalize) {
input_cp_cmp = fzf_normalize_codepoint(input_cp_cmp);
}
if (input_cp_cmp == pattern_cp) {
// Found the character
if (pattern_pos == 0) {
// Store the byte position where the first match starts
first_idx = search_pos;
}
found = true;
input_pos = search_pos + input_bytes;
break;
}
search_pos += input_bytes;
input_pos = search_pos;
}
if (!found) {
if (input_char_count_out) *input_char_count_out = input_char_count;
return false; // Pattern character not found
}
pattern_pos += pattern_bytes;
}
/* Fuzzy v2 needs the full character count to size its DP arrays. Finish
that mandatory count here so a successful prefilter can reuse this decode
instead of making the char-map builder decode the candidate again. */
if (input_char_count_out) {
while (input_pos < input->size) {
utf8proc_int32_t input_cp;
utf8proc_ssize_t input_bytes = utf8_iterate_lossy(
(const utf8proc_uint8_t *)(input_ptr + input_pos),
input->size - input_pos, &input_cp);
input_pos += (size_t)input_bytes;
input_char_count++;
}
*input_char_count_out = input_char_count;
}
if (pattern_pos < pattern_len) return false;
*first_idx_out = first_idx;
return true;
}
int32_t utf8_fuzzy_index(fzf_string_t *input, const char *pattern,
size_t pattern_len, bool case_sensitive) {
size_t first_idx = 0;
if (!utf8_fuzzy_index_size(input, pattern, pattern_len, case_sensitive,
false, false, &first_idx, NULL) ||
first_idx > INT32_MAX)
return -1;
return (int32_t)first_idx;
}
/* UTF-8 helper functions */
// UTF-8 aware character comparison
static bool utf8_char_equal(utf8proc_int32_t cp1, utf8proc_int32_t cp2,
bool case_sensitive, bool normalize) {
if (!case_sensitive) {
cp1 = utf8proc_case_fold(cp1);
cp2 = utf8proc_case_fold(cp2);
}
if (normalize) {
cp1 = fzf_normalize_codepoint(cp1);
cp2 = fzf_normalize_codepoint(cp2);
}
return cp1 == cp2;
}
/* Return the byte offset of the UTF-8 character immediately before POS.
Callers validate the sequence with utf8proc_iterate after finding the
boundary, so malformed input remains a safe non-match. */
static size_t utf8_previous_char_start(const char *data, size_t pos) {
if (pos == 0) return 0;
pos--;
while (pos > 0 && ((uint8_t)data[pos] & 0xc0) == 0x80) pos--;
return pos;
}
/* Backward counterpart of `utf8_iterate_lossy': the byte offset and
codepoint of the unit a forward lossy pass decodes immediately before
POS (POS > 0). When the bytes between the previous lead-byte
boundary and POS are not one valid sequence, the previous unit is the
single (invalid) byte at POS-1, mirroring the forward policy. */
static size_t utf8_lossy_previous_char(const char *data, size_t pos,
utf8proc_int32_t *cp) {
size_t start = utf8_previous_char_start(data, pos);
utf8proc_ssize_t bytes = utf8proc_iterate(
(const utf8proc_uint8_t *)(data + start),
(utf8proc_ssize_t)(pos - start), cp);
if (bytes != (utf8proc_ssize_t)(pos - start) || bytes <= 0 || *cp < 0) {
*cp = 0xDC00 + (utf8proc_int32_t)(uint8_t)data[pos - 1];
return pos - 1;
}
return start;
}
// UTF-8 aware bonus calculation
static int32_t calculate_score(bool case_sensitive, bool normalize,
fzf_string_t *text, fzf_string_t *pattern,
size_t sidx, size_t eidx, fzf_position_t *pos,
fzf_slab_t *slab) {
const size_t M = pattern->size;
const score_scheme_config_t *config = score_scheme_config(slab);
size_t pidx = 0;
int32_t score = 0;
int32_t consecutive = 0;
bool in_gap = false;
int16_t first_bonus = 0;
if (!resize_pos(pos, M, M)) return 0;
int32_t prev_class = config->initial_class;
if (sidx > 0) {
prev_class = char_class_of(text->data[sidx - 1], config);
}
for (size_t idx = sidx; idx < eidx; idx++) {
char c = text->data[idx];
int32_t class = char_class_of(c, config);
if (!case_sensitive) {
/* TODO(conni2461): He does some unicode stuff here, investigate */
c = (char)tolower((uint8_t)c);
}
if (normalize) {
c = normalize_rune(c);
}
if (c == pattern->data[pidx]) {
if (!append_pos(pos, idx)) return 0;
score += ScoreMatch;
int16_t bonus = bonus_for(config, prev_class, class);
if (consecutive == 0) {
first_bonus = bonus;
} else {
if (bonus >= BonusBoundary && bonus > first_bonus) {
first_bonus = bonus;
}
bonus = max16(max16(bonus, first_bonus), BonusConsecutive);
}
if (pidx == 0) {
score += (int32_t)(bonus * BonusFirstCharMultiplier);
} else {
score += (int32_t)bonus;
}
in_gap = false;
consecutive++;
pidx++;
} else {
if (in_gap) {
score += ScoreGapExtention;
} else {
score += ScoreGapStart;
}
in_gap = true;
consecutive = 0;
first_bonus = 0;
}
prev_class = class;
}
return score;
}
// UTF-8 aware calculate_score