robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
29.2 KiB967 linesraw
1// fuzzy.c: fuzzy matching algorithm and related functions
2//
3// Portions of this file are adapted from fzy (https://github.com/jhawthorn/fzy)
4// Original code:
5//   Copyright (c) 2014 John Hawthorn
6//   Licensed under the MIT License.
7//
8// Permission is hereby granted, free of charge, to any person obtaining a copy
9// of this software and associated documentation files (the "Software"), to deal
10// in the Software without restriction, including without limitation the rights
11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12// copies of the Software, and to permit persons to whom the Software is
13// furnished to do so, subject to the following conditions:
14//
15// The above copyright notice and this permission notice shall be included in
16// all copies or substantial portions of the Software.
17//
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24// THE SOFTWARE.
25
26#include <assert.h>
27#include <limits.h>
28#include <math.h>
29#include <stdbool.h>
30#include <stdint.h>
31#include <stdlib.h>
32#include <string.h>
33
34#include "nvim/ascii_defs.h"
35#include "nvim/charset.h"
36#include "nvim/errors.h"
37#include "nvim/eval.h"
38#include "nvim/eval/typval.h"
39#include "nvim/fuzzy.h"
40#include "nvim/garray.h"
41#include "nvim/garray_defs.h"
42#include "nvim/globals.h"
43#include "nvim/insexpand.h"
44#include "nvim/macros_defs.h"
45#include "nvim/mbyte.h"
46#include "nvim/memline.h"
47#include "nvim/memory.h"
48#include "nvim/message.h"
49
50typedef double score_t;
51
52#define SCORE_MAX INFINITY
53#define SCORE_MIN (-INFINITY)
54#define SCORE_SCALE 1000
55
56typedef struct {
57  int idx;  ///< used for stable sort
58  listitem_T *item;
59  int score;
60  list_T *lmatchpos;
61  char *pat;
62  char *itemstr;
63  bool itemstr_allocated;
64  int startpos;
65} fuzzyItem_T;
66
67typedef struct match_struct match_struct;
68
69#include "fuzzy.c.generated.h"
70
71/// fuzzy_match()
72///
73/// @return true if "pat_arg" matches "str". Also returns the match score in
74/// "outScore" and the matching character positions in "matches".
75bool fuzzy_match(char *const str, const char *const pat_arg, const bool matchseq,
76                 int *const outScore, uint32_t *const matches, const int maxMatches)
77  FUNC_ATTR_NONNULL_ALL
78{
79  bool complete = false;
80  int numMatches = 0;
81  int pat_chars = 0;
82
83  *outScore = 0;
84
85  char *const save_pat = xstrdup(pat_arg);
86  char *pat = save_pat;
87  char *p = pat;
88
89  // Try matching each word in "pat_arg" in "str"
90  while (true) {
91    if (matchseq) {
92      complete = true;
93    } else {
94      // Extract one word from the pattern (separated by space)
95      p = skipwhite(p);
96      if (*p == NUL) {
97        break;
98      }
99      pat = p;
100      while (*p != NUL && !ascii_iswhite(utf_ptr2char(p))) {
101        MB_PTR_ADV(p);
102      }
103      if (*p == NUL) {  // processed all the words
104        complete = true;
105      }
106      *p = NUL;
107    }
108    // match_positions() always writes pat_chars entries,
109    // so bail if they won't fit.
110    pat_chars = mb_charlen(pat);
111    if (pat_chars > maxMatches) {
112      pat_chars = maxMatches;
113    }
114    if (numMatches > maxMatches - pat_chars) {
115      numMatches = 0;
116      *outScore = FUZZY_SCORE_NONE;
117      break;
118    }
119
120    int score = FUZZY_SCORE_NONE;
121    if (has_match(pat, str)) {
122      score_t fzy_score = match_positions(pat, str, matches + numMatches);
123      if (fzy_score != (score_t)SCORE_MIN) {
124        score = (fzy_score == (score_t)SCORE_MAX)
125                ? INT_MAX
126                : ((fzy_score < 0)
127                   ? (int)ceil(fzy_score * SCORE_SCALE - 0.5)
128                   : (int)floor(fzy_score * SCORE_SCALE + 0.5));
129      }
130    }
131
132    if (score == FUZZY_SCORE_NONE) {
133      numMatches = 0;
134      *outScore = FUZZY_SCORE_NONE;
135      break;
136    }
137
138    if (score > 0 && *outScore > INT_MAX - score) {
139      *outScore = INT_MAX;
140    } else if (score < 0 && *outScore < INT_MIN + 1 - score) {
141      *outScore = INT_MIN + 1;
142    } else {
143      *outScore += score;
144    }
145
146    numMatches += pat_chars;
147
148    if (complete || numMatches >= maxMatches) {
149      break;
150    }
151
152    // try matching the next word
153    p++;
154  }
155
156  xfree(save_pat);
157  return numMatches != 0;
158}
159
160/// Sort the fuzzy matches in the descending order of the match score.
161/// For items with same score, retain the order using the index (stable sort)
162static int fuzzy_match_item_compare(const void *const s1, const void *const s2)
163  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE
164{
165  const int v1 = ((const fuzzyItem_T *)s1)->score;
166  const int v2 = ((const fuzzyItem_T *)s2)->score;
167
168  if (v1 == v2) {
169    const char *const pat = ((const fuzzyItem_T *)s1)->pat;
170    const size_t patlen = strlen(pat);
171    int startpos = ((const fuzzyItem_T *)s1)->startpos;
172    const bool exact_match1 = startpos >= 0
173                              && strncmp(pat, ((fuzzyItem_T *)s1)->itemstr + startpos, patlen) == 0;
174    startpos = ((const fuzzyItem_T *)s2)->startpos;
175    const bool exact_match2 = startpos >= 0
176                              && strncmp(pat, ((fuzzyItem_T *)s2)->itemstr + startpos, patlen) == 0;
177
178    if (exact_match1 == exact_match2) {
179      const int idx1 = ((const fuzzyItem_T *)s1)->idx;
180      const int idx2 = ((const fuzzyItem_T *)s2)->idx;
181      return idx1 == idx2 ? 0 : idx1 > idx2 ? 1 : -1;
182    } else if (exact_match2) {
183      return 1;
184    }
185    return -1;
186  } else {
187    return v1 > v2 ? -1 : 1;
188  }
189}
190
191/// Fuzzy search the string "str" in a list of "items" and return the matching
192/// strings in "fmatchlist".
193/// If "matchseq" is true, then for multi-word search strings, match all the
194/// words in sequence.
195/// If "items" is a list of strings, then search for "str" in the list.
196/// If "items" is a list of dicts, then either use "key" to lookup the string
197/// for each item or use "item_cb" Funcref function to get the string.
198/// If "retmatchpos" is true, then return a list of positions where "str"
199/// matches for each item.
200static void fuzzy_match_in_list(list_T *const l, char *const str, const bool matchseq,
201                                const char *const key, Callback *const item_cb,
202                                const bool retmatchpos, list_T *const fmatchlist,
203                                const int max_matches)
204  FUNC_ATTR_NONNULL_ARG(2, 5, 7)
205{
206  int len = tv_list_len(l);
207  if (len == 0) {
208    return;
209  }
210  if (max_matches > 0 && len > max_matches) {
211    len = max_matches;
212  }
213
214  fuzzyItem_T *const items = xcalloc((size_t)len, sizeof(fuzzyItem_T));
215  int match_count = 0;
216  uint32_t matches[FUZZY_MATCH_MAX_LEN];
217
218  // For all the string items in items, get the fuzzy matching score
219  TV_LIST_ITER(l, li, {
220    if (max_matches > 0 && match_count >= max_matches) {
221      break;
222    }
223
224    char *itemstr = NULL;
225    bool itemstr_allocate = false;
226    typval_T rettv;
227
228    rettv.v_type = VAR_UNKNOWN;
229    const typval_T *const tv = TV_LIST_ITEM_TV(li);
230    if (tv->v_type == VAR_STRING) {  // list of strings
231      itemstr = tv->vval.v_string;
232    } else if (tv->v_type == VAR_DICT
233               && (key != NULL || item_cb->type != kCallbackNone)) {
234      // For a dict, either use the specified key to lookup the string or
235      // use the specified callback function to get the string.
236      if (key != NULL) {
237        itemstr = tv_dict_get_string(tv->vval.v_dict, key, false);
238      } else {
239        typval_T argv[2];
240
241        // Invoke the supplied callback (if any) to get the dict item
242        tv->vval.v_dict->dv_refcount++;
243        argv[0].v_type = VAR_DICT;
244        argv[0].vval.v_dict = tv->vval.v_dict;
245        argv[1].v_type = VAR_UNKNOWN;
246        if (callback_call(item_cb, 1, argv, &rettv)) {
247          if (rettv.v_type == VAR_STRING) {
248            itemstr = rettv.vval.v_string;
249            itemstr_allocate = true;
250          }
251        }
252        tv_dict_unref(tv->vval.v_dict);
253      }
254    }
255
256    int score;
257    if (itemstr != NULL
258        && fuzzy_match(itemstr, str, matchseq, &score, matches, FUZZY_MATCH_MAX_LEN)) {
259      char *itemstr_copy = itemstr_allocate ? xstrdup(itemstr) : itemstr;
260      list_T *match_positions = NULL;
261
262      // Copy the list of matching positions in itemstr to a list, if
263      // "retmatchpos" is set.
264      if (retmatchpos) {
265        match_positions = tv_list_alloc(kListLenMayKnow);
266        // Fill position information
267        int j = 0;
268        const char *p = str;
269        while (*p != NUL && j < FUZZY_MATCH_MAX_LEN) {
270          if (!ascii_iswhite(utf_ptr2char(p)) || matchseq) {
271            tv_list_append_number(match_positions, matches[j]);
272            j++;
273          }
274          MB_PTR_ADV(p);
275        }
276      }
277      items[match_count].idx = match_count;
278      items[match_count].item = li;
279      items[match_count].score = score;
280      items[match_count].pat = str;
281      items[match_count].startpos = (int)matches[0];
282      items[match_count].itemstr = itemstr_copy;
283      items[match_count].itemstr_allocated = itemstr_allocate;
284      items[match_count].lmatchpos = match_positions;
285
286      match_count++;
287    }
288    tv_clear(&rettv);
289  });
290
291  if (match_count > 0) {
292    // Sort the list by the descending order of the match score
293    qsort(items, (size_t)match_count, sizeof(fuzzyItem_T), fuzzy_match_item_compare);
294
295    // For matchfuzzy(), return a list of matched strings.
296    //          ['str1', 'str2', 'str3']
297    // For matchfuzzypos(), return a list with three items.
298    // The first item is a list of matched strings. The second item
299    // is a list of lists where each list item is a list of matched
300    // character positions. The third item is a list of matching scores.
301    //      [['str1', 'str2', 'str3'], [[1, 3], [1, 3], [1, 3]]]
302    list_T *retlist;
303    if (retmatchpos) {
304      const listitem_T *const li = tv_list_find(fmatchlist, 0);
305      assert(li != NULL && TV_LIST_ITEM_TV(li)->vval.v_list != NULL);
306      retlist = TV_LIST_ITEM_TV(li)->vval.v_list;
307    } else {
308      retlist = fmatchlist;
309    }
310
311    // Copy the matching strings to the return list
312    for (int i = 0; i < match_count; i++) {
313      tv_list_append_tv(retlist, TV_LIST_ITEM_TV(items[i].item));
314    }
315
316    // next copy the list of matching positions
317    if (retmatchpos) {
318      const listitem_T *li = tv_list_find(fmatchlist, -2);
319      assert(li != NULL && TV_LIST_ITEM_TV(li)->vval.v_list != NULL);
320      retlist = TV_LIST_ITEM_TV(li)->vval.v_list;
321
322      for (int i = 0; i < match_count; i++) {
323        assert(items[i].lmatchpos != NULL);
324        tv_list_append_list(retlist, items[i].lmatchpos);
325        items[i].lmatchpos = NULL;
326      }
327
328      // copy the matching scores
329      li = tv_list_find(fmatchlist, -1);
330      assert(li != NULL && TV_LIST_ITEM_TV(li)->vval.v_list != NULL);
331      retlist = TV_LIST_ITEM_TV(li)->vval.v_list;
332      for (int i = 0; i < match_count; i++) {
333        tv_list_append_number(retlist, items[i].score);
334      }
335    }
336  }
337
338  for (int i = 0; i < match_count; i++) {
339    if (items[i].itemstr_allocated) {
340      xfree(items[i].itemstr);
341    }
342    assert(items[i].lmatchpos == NULL);
343  }
344  xfree(items);
345}
346
347/// Do fuzzy matching. Returns the list of matched strings in "rettv".
348/// If "retmatchpos" is true, also returns the matching character positions.
349static void do_fuzzymatch(const typval_T *const argvars, typval_T *const rettv,
350                          const bool retmatchpos)
351  FUNC_ATTR_NONNULL_ALL
352{
353  // validate and get the arguments
354  if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL) {
355    semsg(_(e_listarg), retmatchpos ? "matchfuzzypos()" : "matchfuzzy()");
356    return;
357  }
358  if (argvars[1].v_type != VAR_STRING || argvars[1].vval.v_string == NULL) {
359    semsg(_(e_invarg2), tv_get_string(&argvars[1]));
360    return;
361  }
362
363  Callback cb = CALLBACK_NONE;
364  const char *key = NULL;
365  bool matchseq = false;
366  int max_matches = 0;
367  if (argvars[2].v_type != VAR_UNKNOWN) {
368    if (tv_check_for_nonnull_dict_arg(argvars, 2) == FAIL) {
369      return;
370    }
371
372    // To search a dict, either a callback function or a key can be
373    // specified.
374    dict_T *const d = argvars[2].vval.v_dict;
375    const dictitem_T *di;
376    if ((di = tv_dict_find(d, "key", -1)) != NULL) {
377      if (di->di_tv.v_type != VAR_STRING || di->di_tv.vval.v_string == NULL
378          || *di->di_tv.vval.v_string == NUL) {
379        semsg(_(e_invargNval), "key", tv_get_string(&di->di_tv));
380        return;
381      }
382      key = tv_get_string(&di->di_tv);
383    } else if (!tv_dict_get_callback(d, "text_cb", -1, &cb)) {
384      semsg(_(e_invargval), "text_cb");
385      return;
386    }
387
388    if ((di = tv_dict_find(d, "limit", -1)) != NULL) {
389      if (di->di_tv.v_type != VAR_NUMBER) {
390        semsg(_(e_invargval), "limit");
391        return;
392      }
393      max_matches = (int)tv_get_number_chk(&di->di_tv, NULL);
394    }
395
396    if (tv_dict_has_key(d, "matchseq")) {
397      matchseq = true;
398    }
399  }
400
401  // get the fuzzy matches
402  tv_list_alloc_ret(rettv, retmatchpos ? 3 : kListLenUnknown);
403  if (retmatchpos) {
404    // For matchfuzzypos(), a list with three items are returned. First
405    // item is a list of matching strings, the second item is a list of
406    // lists with matching positions within each string and the third item
407    // is the list of scores of the matches.
408    tv_list_append_list(rettv->vval.v_list, tv_list_alloc(kListLenUnknown));
409    tv_list_append_list(rettv->vval.v_list, tv_list_alloc(kListLenUnknown));
410    tv_list_append_list(rettv->vval.v_list, tv_list_alloc(kListLenUnknown));
411  }
412
413  fuzzy_match_in_list(argvars[0].vval.v_list, (char *)tv_get_string(&argvars[1]),
414                      matchseq, key, &cb, retmatchpos, rettv->vval.v_list, max_matches);
415
416  callback_free(&cb);
417}
418
419/// "matchfuzzy()" function
420void f_matchfuzzy(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
421{
422  do_fuzzymatch(argvars, rettv, false);
423}
424
425/// "matchfuzzypos()" function
426void f_matchfuzzypos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
427{
428  do_fuzzymatch(argvars, rettv, true);
429}
430
431/// Same as fuzzy_match_item_compare() except for use with a string match
432static int fuzzy_match_str_compare(const void *const s1, const void *const s2)
433  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
434{
435  const int v1 = ((fuzmatch_str_T *)s1)->score;
436  const int v2 = ((fuzmatch_str_T *)s2)->score;
437  const int idx1 = ((fuzmatch_str_T *)s1)->idx;
438  const int idx2 = ((fuzmatch_str_T *)s2)->idx;
439
440  if (v1 == v2) {
441    return idx1 == idx2 ? 0 : idx1 > idx2 ? 1 : -1;
442  } else {
443    return v1 > v2 ? -1 : 1;
444  }
445}
446
447/// Sort fuzzy matches by score
448static void fuzzy_match_str_sort(fuzmatch_str_T *const fm, const int sz)
449  FUNC_ATTR_NONNULL_ALL
450{
451  // Sort the list by the descending order of the match score
452  qsort(fm, (size_t)sz, sizeof(fuzmatch_str_T), fuzzy_match_str_compare);
453}
454
455/// Same as fuzzy_match_item_compare() except for use with a function name
456/// string match. <SNR> functions should be sorted to the end.
457static int fuzzy_match_func_compare(const void *const s1, const void *const s2)
458  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
459{
460  const int v1 = ((fuzmatch_str_T *)s1)->score;
461  const int v2 = ((fuzmatch_str_T *)s2)->score;
462  const int idx1 = ((fuzmatch_str_T *)s1)->idx;
463  const int idx2 = ((fuzmatch_str_T *)s2)->idx;
464  const char *const str1 = ((fuzmatch_str_T *)s1)->str;
465  const char *const str2 = ((fuzmatch_str_T *)s2)->str;
466
467  if (*str1 != '<' && *str2 == '<') {
468    return -1;
469  }
470  if (*str1 == '<' && *str2 != '<') {
471    return 1;
472  }
473  if (v1 == v2) {
474    return idx1 == idx2 ? 0 : idx1 > idx2 ? 1 : -1;
475  }
476  return v1 > v2 ? -1 : 1;
477}
478
479/// Sort fuzzy matches of function names by score.
480/// <SNR> functions should be sorted to the end.
481static void fuzzy_match_func_sort(fuzmatch_str_T *const fm, const int sz)
482  FUNC_ATTR_NONNULL_ALL
483{
484  // Sort the list by the descending order of the match score
485  qsort(fm, (size_t)sz, sizeof(fuzmatch_str_T), fuzzy_match_func_compare);
486}
487
488/// Fuzzy match "pat" in "str".
489/// @returns 0 if there is no match. Otherwise, returns the match score.
490int fuzzy_match_str(char *const str, const char *const pat)
491  FUNC_ATTR_WARN_UNUSED_RESULT
492{
493  if (str == NULL || pat == NULL) {
494    return 0;
495  }
496
497  int score = FUZZY_SCORE_NONE;
498  uint32_t matchpos[FUZZY_MATCH_MAX_LEN];
499  fuzzy_match(str, pat, true, &score, matchpos, ARRAY_SIZE(matchpos));
500
501  return score;
502}
503
504/// Fuzzy match the position of string "pat" in string "str".
505/// @returns a dynamic array of matching positions. If there is no match, returns NULL.
506garray_T *fuzzy_match_str_with_pos(char *const str, const char *const pat)
507{
508  if (str == NULL || pat == NULL) {
509    return NULL;
510  }
511
512  garray_T *match_positions = xmalloc(sizeof(garray_T));
513  ga_init(match_positions, sizeof(uint32_t), 10);
514
515  int score = FUZZY_SCORE_NONE;
516  uint32_t matches[FUZZY_MATCH_MAX_LEN];
517  if (!fuzzy_match(str, pat, false, &score, matches, FUZZY_MATCH_MAX_LEN)
518      || score == FUZZY_SCORE_NONE) {
519    ga_clear(match_positions);
520    xfree(match_positions);
521    return NULL;
522  }
523
524  int j = 0;
525  for (const char *p = pat; *p != NUL; MB_PTR_ADV(p)) {
526    if (!ascii_iswhite(utf_ptr2char(p))) {
527      GA_APPEND(uint32_t, match_positions, matches[j]);
528      j++;
529    }
530  }
531
532  return match_positions;
533}
534
535/// This function splits the line pointed to by `*ptr` into words and performs
536/// a fuzzy match for the pattern `pat` on each word. It iterates through the
537/// line, moving `*ptr` to the start of each word during the process.
538///
539/// If a match is found:
540/// - `*ptr` points to the start of the matched word.
541/// - `*len` is set to the length of the matched word.
542/// - `*score` contains the match score.
543///
544/// If no match is found, `*ptr` is updated to the end of the line.
545bool fuzzy_match_str_in_line(char **ptr, char *pat, int *len, pos_T *current_pos, int *score)
546{
547  char *str = *ptr;
548  char *strBegin = str;
549  char *end = NULL;
550  char *start = NULL;
551  bool found = false;
552
553  if (str == NULL || pat == NULL) {
554    return found;
555  }
556  char *line_end = find_line_end(str);
557
558  while (str < line_end) {
559    // Skip non-word characters
560    start = find_word_start(str);
561    if (*start == NUL) {
562      break;
563    }
564    end = find_word_end(start);
565
566    // Extract the word from start to end
567    char save_end = *end;
568    *end = NUL;
569
570    // Perform fuzzy match
571    *score = fuzzy_match_str(start, pat);
572    *end = save_end;
573
574    if (*score != FUZZY_SCORE_NONE) {
575      *len = (int)(end - start);
576      found = true;
577      *ptr = start;
578      if (current_pos) {
579        current_pos->col += (int)(end - strBegin);
580      }
581      break;
582    }
583
584    // Move to the end of the current word for the next iteration
585    str = end;
586    // Ensure we continue searching after the current word
587    while (*str != NUL && !vim_iswordp(str)) {
588      MB_PTR_ADV(str);
589    }
590  }
591
592  if (!found) {
593    *ptr = line_end;
594  }
595
596  return found;
597}
598
599/// Search for the next fuzzy match in the specified buffer.
600/// This function attempts to find the next occurrence of the given pattern
601/// in the buffer, starting from the current position. It handles line wrapping
602/// and direction of search.
603///
604/// Return true if a match is found, otherwise false.
605bool search_for_fuzzy_match(buf_T *buf, pos_T *pos, char *pattern, int dir, pos_T *start_pos,
606                            int *len, char **ptr, int *score)
607{
608  pos_T current_pos = *pos;
609  pos_T circly_end;
610  bool found_new_match = false;
611  bool looped_around = false;
612
613  bool whole_line = ctrl_x_mode_whole_line();
614
615  if (buf == curbuf) {
616    circly_end = *start_pos;
617  } else {
618    circly_end.lnum = buf->b_ml.ml_line_count;
619    circly_end.col = 0;
620    circly_end.coladd = 0;
621  }
622
623  if (whole_line && start_pos->lnum != pos->lnum) {
624    current_pos.lnum += dir;
625  }
626
627  while (true) {
628    // Check if looped around and back to start position
629    if (looped_around && (whole_line ? current_pos.lnum == circly_end.lnum
630                                     : equalpos(current_pos, circly_end))) {
631      break;
632    }
633
634    // Ensure current_pos is valid
635    if (current_pos.lnum >= 1 && current_pos.lnum <= buf->b_ml.ml_line_count) {
636      // Get the current line buffer
637      *ptr = ml_get_buf(buf, current_pos.lnum);
638      if (!whole_line) {
639        *ptr += current_pos.col;
640      }
641
642      // If ptr is end of line is reached, move to next line
643      // or previous line based on direction
644      if (*ptr != NULL && **ptr != NUL) {
645        if (!whole_line) {
646          // Try to find a fuzzy match in the current line starting
647          // from current position
648          found_new_match = fuzzy_match_str_in_line(ptr, pattern,
649                                                    len, &current_pos, score);
650          if (found_new_match) {
651            *pos = current_pos;
652            break;
653          } else if (looped_around && current_pos.lnum == circly_end.lnum) {
654            break;
655          }
656        } else {
657          char *line = *ptr;
658          char *p = skipwhite(line);
659          if (fuzzy_match_str(p, pattern) != FUZZY_SCORE_NONE) {
660            found_new_match = true;
661            *pos = current_pos;
662            *ptr = p;
663            *len = ml_get_buf_len(buf, current_pos.lnum) - (int)(p - line);
664            break;
665          }
666        }
667      }
668    }
669
670    // Move to the next line or previous line based on direction
671    if (dir == FORWARD) {
672      if (++current_pos.lnum > buf->b_ml.ml_line_count) {
673        if (p_ws) {
674          current_pos.lnum = 1;
675          looped_around = true;
676        } else {
677          break;
678        }
679      }
680    } else {
681      if (--current_pos.lnum < 1) {
682        if (p_ws) {
683          current_pos.lnum = buf->b_ml.ml_line_count;
684          looped_around = true;
685        } else {
686          break;
687        }
688      }
689    }
690    current_pos.col = 0;
691  }
692
693  return found_new_match;
694}
695
696/// Free an array of fuzzy string matches "fuzmatch[count]".
697void fuzmatch_str_free(fuzmatch_str_T *const fuzmatch, int count)
698{
699  if (fuzmatch == NULL) {
700    return;
701  }
702  for (int i = 0; i < count; i++) {
703    xfree(fuzmatch[i].str);
704  }
705  xfree(fuzmatch);
706}
707
708/// Copy a list of fuzzy matches into a string list after sorting the matches by
709/// the fuzzy score. Frees the memory allocated for "fuzmatch".
710void fuzzymatches_to_strmatches(fuzmatch_str_T *const fuzmatch, char ***const matches,
711                                const int count, const bool funcsort)
712  FUNC_ATTR_NONNULL_ARG(2)
713{
714  if (count <= 0) {
715    goto theend;
716  }
717
718  *matches = xmalloc((size_t)count * sizeof(char *));
719
720  // Sort the list by the descending order of the match score
721  if (funcsort) {
722    fuzzy_match_func_sort(fuzmatch, count);
723  } else {
724    fuzzy_match_str_sort(fuzmatch, count);
725  }
726
727  for (int i = 0; i < count; i++) {
728    (*matches)[i] = fuzmatch[i].str;
729  }
730
731theend:
732  xfree(fuzmatch);
733}
734
735/// Fuzzy match algorithm ported from https://github.com/jhawthorn/fzy.
736/// This implementation extends the original by supporting multibyte characters.
737
738#define MATCH_MAX_LEN FUZZY_MATCH_MAX_LEN
739
740#define SCORE_GAP_LEADING -0.005
741#define SCORE_GAP_TRAILING -0.005
742#define SCORE_GAP_INNER -0.01
743#define SCORE_MATCH_CONSECUTIVE 1.0
744#define SCORE_MATCH_SLASH 0.9
745#define SCORE_MATCH_WORD 0.8
746#define SCORE_MATCH_CAPITAL 0.7
747#define SCORE_MATCH_DOT 0.6
748
749static int has_match(const char *const needle, const char *const haystack)
750{
751  if (!needle || !haystack || !*needle) {
752    return FAIL;
753  }
754
755  const char *n_ptr = needle;
756  const char *h_ptr = haystack;
757
758  while (*n_ptr) {
759    const int n_char = utf_ptr2char(n_ptr);
760    const int n_upper = mb_toupper(n_char);
761    bool found = false;
762
763    while (*h_ptr) {
764      const int h_char = utf_ptr2char(h_ptr);
765      if (h_char == n_char || h_char == n_upper) {
766        found = true;
767        h_ptr += utfc_ptr2len(h_ptr);
768        break;
769      }
770      h_ptr += utfc_ptr2len(h_ptr);
771    }
772
773    if (!found) {
774      return FAIL;
775    }
776
777    n_ptr += utfc_ptr2len(n_ptr);
778  }
779
780  return OK;
781}
782
783struct match_struct {
784  int needle_len;
785  int haystack_len;
786  int lower_needle[MATCH_MAX_LEN];    ///< stores codepoints
787  int lower_haystack[MATCH_MAX_LEN];  ///< stores codepoints
788  score_t match_bonus[MATCH_MAX_LEN];
789};
790
791#define IS_WORD_SEP(c) ((c) == '-' || (c) == '_' || (c) == ' ')
792#define IS_PATH_SEP(c) ((c) == '/')
793#define IS_DOT(c)      ((c) == '.')
794
795static score_t compute_bonus_codepoint(int last_c, int c)
796{
797  if (ASCII_ISALNUM(c) || vim_iswordc(c)) {
798    if (IS_PATH_SEP(last_c)) {
799      return SCORE_MATCH_SLASH;
800    }
801    if (IS_WORD_SEP(last_c)) {
802      return SCORE_MATCH_WORD;
803    }
804    if (IS_DOT(last_c)) {
805      return SCORE_MATCH_DOT;
806    }
807    if (mb_isupper(c) && mb_islower(last_c)) {
808      return SCORE_MATCH_CAPITAL;
809    }
810  }
811  return 0;
812}
813
814static void setup_match_struct(match_struct *const match, const char *const needle,
815                               const char *const haystack)
816{
817  int i = 0;
818  const char *p = needle;
819  while (*p != NUL && i < MATCH_MAX_LEN) {
820    const int c = utf_ptr2char(p);
821    match->lower_needle[i++] = mb_tolower(c);
822    MB_PTR_ADV(p);
823  }
824  match->needle_len = i;
825
826  i = 0;
827  p = haystack;
828  int prev_c = '/';
829  while (*p != NUL && i < MATCH_MAX_LEN) {
830    const int c = utf_ptr2char(p);
831    match->lower_haystack[i] = mb_tolower(c);
832    match->match_bonus[i] = compute_bonus_codepoint(prev_c, c);
833    prev_c = c;
834    MB_PTR_ADV(p);
835    i++;
836  }
837  match->haystack_len = i;
838}
839
840static inline void match_row(const match_struct *match, int row, score_t *curr_D, score_t *curr_M,
841                             const score_t *last_D, const score_t *last_M)
842{
843  int n = match->needle_len;
844  int m = match->haystack_len;
845  int i = row;
846
847  const int *lower_needle = match->lower_needle;
848  const int *lower_haystack = match->lower_haystack;
849  const score_t *match_bonus = match->match_bonus;
850
851  score_t prev_score = (score_t)SCORE_MIN;
852  score_t gap_score = i == n - 1 ? SCORE_GAP_TRAILING : SCORE_GAP_INNER;
853
854  // These will not be used with this value, but not all compilers see it
855  score_t prev_M = (score_t)SCORE_MIN, prev_D = (score_t)SCORE_MIN;
856
857  for (int j = 0; j < m; j++) {
858    if (lower_needle[i] == lower_haystack[j]) {
859      score_t score = (score_t)SCORE_MIN;
860      if (!i) {
861        score = (j * SCORE_GAP_LEADING) + match_bonus[j];
862      } else if (j) {  // i > 0 && j > 0
863        score = MAX(prev_M + match_bonus[j],
864                    // consecutive match, doesn't stack with match_bonus
865                    prev_D + SCORE_MATCH_CONSECUTIVE);
866      }
867      prev_D = last_D[j];
868      prev_M = last_M[j];
869      curr_D[j] = score;
870      curr_M[j] = prev_score = MAX(score, prev_score + gap_score);
871    } else {
872      prev_D = last_D[j];
873      prev_M = last_M[j];
874      curr_D[j] = (score_t)SCORE_MIN;
875      curr_M[j] = prev_score = prev_score + gap_score;
876    }
877  }
878}
879
880static score_t match_positions(const char *const needle, const char *const haystack,
881                               uint32_t *const positions)
882{
883  if (!needle || !haystack || !*needle) {
884    return (score_t)SCORE_MIN;
885  }
886
887  match_struct match;
888  setup_match_struct(&match, needle, haystack);
889
890  int n = match.needle_len;
891  int m = match.haystack_len;
892
893  if (m > MATCH_MAX_LEN || n > m) {
894    // Unreasonably large candidate: return no score
895    return (score_t)SCORE_MIN;
896  } else if (n == m) {
897    // Since this method can only be called with a haystack which
898    // matches needle. If the lengths of the strings are equal the
899    // strings themselves must also be equal (ignoring case).
900    // After truncation to MATCH_MAX_LEN n == m can also happen for
901    // unequal strings, so check before taking the shortcut.
902    bool equal = true;
903    for (int i = 0; i < n; i++) {
904      if (match.lower_needle[i] != match.lower_haystack[i]) {
905        equal = false;
906        break;
907      }
908    }
909    if (equal) {
910      if (positions) {
911        for (int i = 0; i < n; i++) {
912          positions[i] = (uint32_t)i;
913        }
914      }
915      return (score_t)SCORE_MAX;
916    }
917  }
918
919  // ensure n * MATCH_MAX_LEN * 2 won't overflow
920  if ((size_t)n > (SIZE_MAX / sizeof(score_t)) / MATCH_MAX_LEN / 2) {
921    return (score_t)SCORE_MIN;
922  }
923
924  // Allocate for both D and M matrices in one contiguous block
925  score_t *block = (score_t *)xmalloc(sizeof(score_t) * MATCH_MAX_LEN * (size_t)n * 2);
926
927  // D[][] Stores the best score for this position ending with a match.
928  // M[][] Stores the best possible score at this position.
929  score_t(*D)[MATCH_MAX_LEN] = (score_t(*)[MATCH_MAX_LEN])(block);
930  score_t(*M)[MATCH_MAX_LEN] = (score_t(*)[MATCH_MAX_LEN])(block
931                                                           + MATCH_MAX_LEN * (size_t)n);
932
933  match_row(&match, 0, D[0], M[0], D[0], M[0]);
934  for (int i = 1; i < n; i++) {
935    match_row(&match, i, D[i], M[i], D[i - 1], M[i - 1]);
936  }
937
938  // backtrace to find the positions of optimal matching
939  if (positions) {
940    int match_required = 0;
941    for (int i = n - 1, j = m - 1; i >= 0; i--) {
942      for (; j >= 0; j--) {
943        // There may be multiple paths which result in
944        // the optimal weight.
945        //
946        // For simplicity, we will pick the first one
947        // we encounter, the latest in the candidate
948        // string.
949        if (D[i][j] != (score_t)SCORE_MIN
950            && (match_required || D[i][j] == M[i][j])) {
951          // If this score was determined using
952          // SCORE_MATCH_CONSECUTIVE, the
953          // previous character MUST be a match
954          match_required = i && j
955                           && M[i][j] == D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE;
956          positions[i] = (uint32_t)(j--);
957          break;
958        }
959      }
960    }
961  }
962
963  score_t result = M[n - 1][m - 1];
964
965  xfree(block);
966  return result;
967}