robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 57int idx ;///< used for stable sort 58listitem_T * item ; 59int score ; 60list_T * lmatchpos ; 61char * pat ; 62char * itemstr ; 63bool itemstr_allocated ; 64int 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 , 76int * const outScore ,uint32_t * const matches ,const int maxMatches ) 77FUNC_ATTR_NONNULL_ALL 78{ 79bool complete = false; 80int numMatches = 0 ; 81int pat_chars = 0 ; 82 83* outScore = 0 ; 84 85char * const save_pat = xstrdup (pat_arg ); 86char * pat = save_pat ; 87char * p = pat ; 88 89// Try matching each word in "pat_arg" in "str" 90while (true) { 91if (matchseq ) { 92complete = true; 93 }else { 94// Extract one word from the pattern (separated by space) 95p = skipwhite (p ); 96if (* p == NUL ) { 97break ; 98 } 99pat = p ; 100while (* p != NUL && !ascii_iswhite (utf_ptr2char (p ))) { 101MB_PTR_ADV (p ); 102 } 103if (* p == NUL ) {// processed all the words 104complete = true; 105 } 106* p = NUL ; 107 } 108// match_positions() always writes pat_chars entries, 109// so bail if they won't fit. 110pat_chars = mb_charlen (pat ); 111if (pat_chars > maxMatches ) { 112pat_chars = maxMatches ; 113 } 114if (numMatches > maxMatches - pat_chars ) { 115numMatches = 0 ; 116* outScore = FUZZY_SCORE_NONE ; 117break ; 118 } 119 120int score = FUZZY_SCORE_NONE ; 121if (has_match (pat ,str )) { 122score_t fzy_score = match_positions (pat ,str ,matches + numMatches ); 123if (fzy_score != (score_t )SCORE_MIN ) { 124score = (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 132if (score == FUZZY_SCORE_NONE ) { 133numMatches = 0 ; 134* outScore = FUZZY_SCORE_NONE ; 135break ; 136 } 137 138if (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 146numMatches += pat_chars ; 147 148if (complete || numMatches >=maxMatches ) { 149break ; 150 } 151 152// try matching the next word 153p ++ ; 154 } 155 156xfree (save_pat ); 157return 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 ) 163FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_PURE 164{ 165const int v1 = ((const fuzzyItem_T * )s1 )-> score ; 166const int v2 = ((const fuzzyItem_T * )s2 )-> score ; 167 168if (v1 == v2 ) { 169const char * const pat = ((const fuzzyItem_T * )s1 )-> pat ; 170const size_t patlen = strlen (pat ); 171int startpos = ((const fuzzyItem_T * )s1 )-> startpos ; 172const bool exact_match1 = startpos >=0 173&& strncmp (pat , ((fuzzyItem_T * )s1 )-> itemstr + startpos ,patlen )== 0 ; 174startpos = ((const fuzzyItem_T * )s2 )-> startpos ; 175const bool exact_match2 = startpos >=0 176&& strncmp (pat , ((fuzzyItem_T * )s2 )-> itemstr + startpos ,patlen )== 0 ; 177 178if (exact_match1 == exact_match2 ) { 179const int idx1 = ((const fuzzyItem_T * )s1 )-> idx ; 180const int idx2 = ((const fuzzyItem_T * )s2 )-> idx ; 181return idx1 == idx2 ?0 :idx1 > idx2 ?1 :-1 ; 182 }else if (exact_match2 ) { 183return 1 ; 184 } 185return -1 ; 186 }else { 187return 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 , 201const char * const key ,Callback * const item_cb , 202const bool retmatchpos ,list_T * const fmatchlist , 203const int max_matches ) 204FUNC_ATTR_NONNULL_ARG (2 ,5 ,7 ) 205{ 206int len = tv_list_len (l ); 207if (len == 0 ) { 208return ; 209 } 210if (max_matches > 0 && len > max_matches ) { 211len = max_matches ; 212 } 213 214fuzzyItem_T * const items = xcalloc ((size_t )len ,sizeof (fuzzyItem_T )); 215int match_count = 0 ; 216uint32_t matches [FUZZY_MATCH_MAX_LEN ]; 217 218// For all the string items in items, get the fuzzy matching score 219TV_LIST_ITER (l ,li , { 220if (max_matches > 0 && match_count >=max_matches ) { 221break ; 222 } 223 224char * itemstr = NULL ; 225bool itemstr_allocate = false; 226typval_T rettv ; 227 228rettv .v_type = VAR_UNKNOWN ; 229const typval_T * const tv = TV_LIST_ITEM_TV (li ); 230if (tv -> v_type == VAR_STRING ) {// list of strings 231itemstr = 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. 236if (key != NULL ) { 237itemstr = tv_dict_get_string (tv -> vval .v_dict ,key , false); 238 }else { 239typval_T argv [2 ]; 240 241// Invoke the supplied callback (if any) to get the dict item 242tv -> vval .v_dict -> dv_refcount ++ ; 243argv [0 ].v_type = VAR_DICT ; 244argv [0 ].vval .v_dict = tv -> vval .v_dict ; 245argv [1 ].v_type = VAR_UNKNOWN ; 246if (callback_call (item_cb ,1 ,argv ,& rettv )) { 247if (rettv .v_type == VAR_STRING ) { 248itemstr = rettv .vval .v_string ; 249itemstr_allocate = true; 250 } 251 } 252tv_dict_unref (tv -> vval .v_dict ); 253 } 254 } 255 256int score ; 257if (itemstr != NULL 258&& fuzzy_match (itemstr ,str ,matchseq ,& score ,matches ,FUZZY_MATCH_MAX_LEN )) { 259char * itemstr_copy = itemstr_allocate ?xstrdup (itemstr ) :itemstr ; 260list_T * match_positions = NULL ; 261 262// Copy the list of matching positions in itemstr to a list, if 263// "retmatchpos" is set. 264if (retmatchpos ) { 265match_positions = tv_list_alloc (kListLenMayKnow ); 266// Fill position information 267int j = 0 ; 268const char * p = str ; 269while (* p != NUL && j < FUZZY_MATCH_MAX_LEN ) { 270if (!ascii_iswhite (utf_ptr2char (p ))|| matchseq ) { 271tv_list_append_number (match_positions ,matches [j ]); 272j ++ ; 273 } 274MB_PTR_ADV (p ); 275 } 276 } 277items [match_count ].idx = match_count ; 278items [match_count ].item = li ; 279items [match_count ].score = score ; 280items [match_count ].pat = str ; 281items [match_count ].startpos = (int )matches [0 ]; 282items [match_count ].itemstr = itemstr_copy ; 283items [match_count ].itemstr_allocated = itemstr_allocate ; 284items [match_count ].lmatchpos = match_positions ; 285 286match_count ++ ; 287 } 288tv_clear (& rettv ); 289 }); 290 291if (match_count > 0 ) { 292// Sort the list by the descending order of the match score 293qsort (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]]] 302list_T * retlist ; 303if (retmatchpos ) { 304const listitem_T * const li = tv_list_find (fmatchlist ,0 ); 305assert (li != NULL && TV_LIST_ITEM_TV (li )-> vval .v_list != NULL ); 306retlist = TV_LIST_ITEM_TV (li )-> vval .v_list ; 307 }else { 308retlist = fmatchlist ; 309 } 310 311// Copy the matching strings to the return list 312for (int i = 0 ;i < match_count ;i ++ ) { 313tv_list_append_tv (retlist ,TV_LIST_ITEM_TV (items [i ].item )); 314 } 315 316// next copy the list of matching positions 317if (retmatchpos ) { 318const listitem_T * li = tv_list_find (fmatchlist ,-2 ); 319assert (li != NULL && TV_LIST_ITEM_TV (li )-> vval .v_list != NULL ); 320retlist = TV_LIST_ITEM_TV (li )-> vval .v_list ; 321 322for (int i = 0 ;i < match_count ;i ++ ) { 323assert (items [i ].lmatchpos != NULL ); 324tv_list_append_list (retlist ,items [i ].lmatchpos ); 325items [i ].lmatchpos = NULL ; 326 } 327 328// copy the matching scores 329li = tv_list_find (fmatchlist ,-1 ); 330assert (li != NULL && TV_LIST_ITEM_TV (li )-> vval .v_list != NULL ); 331retlist = TV_LIST_ITEM_TV (li )-> vval .v_list ; 332for (int i = 0 ;i < match_count ;i ++ ) { 333tv_list_append_number (retlist ,items [i ].score ); 334 } 335 } 336 } 337 338for (int i = 0 ;i < match_count ;i ++ ) { 339if (items [i ].itemstr_allocated ) { 340xfree (items [i ].itemstr ); 341 } 342assert (items [i ].lmatchpos == NULL ); 343 } 344xfree (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 , 350const bool retmatchpos ) 351FUNC_ATTR_NONNULL_ALL 352{ 353// validate and get the arguments 354if (argvars [0 ].v_type != VAR_LIST || argvars [0 ].vval .v_list == NULL ) { 355semsg (_ (e_listarg ),retmatchpos ?"matchfuzzypos()" :"matchfuzzy()" ); 356return ; 357 } 358if (argvars [1 ].v_type != VAR_STRING || argvars [1 ].vval .v_string == NULL ) { 359semsg (_ (e_invarg2 ),tv_get_string (& argvars [1 ])); 360return ; 361 } 362 363Callback cb = CALLBACK_NONE ; 364const char * key = NULL ; 365bool matchseq = false; 366int max_matches = 0 ; 367if (argvars [2 ].v_type != VAR_UNKNOWN ) { 368if (tv_check_for_nonnull_dict_arg (argvars ,2 )== FAIL ) { 369return ; 370 } 371 372// To search a dict, either a callback function or a key can be 373// specified. 374dict_T * const d = argvars [2 ].vval .v_dict ; 375const dictitem_T * di ; 376if ((di = tv_dict_find (d ,"key" ,-1 ))!= NULL ) { 377if (di -> di_tv .v_type != VAR_STRING || di -> di_tv .vval .v_string == NULL 378|| * di -> di_tv .vval .v_string == NUL ) { 379semsg (_ (e_invargNval ),"key" ,tv_get_string (& di -> di_tv )); 380return ; 381 } 382key = tv_get_string (& di -> di_tv ); 383 }else if (!tv_dict_get_callback (d ,"text_cb" ,-1 ,& cb )) { 384semsg (_ (e_invargval ),"text_cb" ); 385return ; 386 } 387 388if ((di = tv_dict_find (d ,"limit" ,-1 ))!= NULL ) { 389if (di -> di_tv .v_type != VAR_NUMBER ) { 390semsg (_ (e_invargval ),"limit" ); 391return ; 392 } 393max_matches = (int )tv_get_number_chk (& di -> di_tv ,NULL ); 394 } 395 396if (tv_dict_has_key (d ,"matchseq" )) { 397matchseq = true; 398 } 399 } 400 401// get the fuzzy matches 402tv_list_alloc_ret (rettv ,retmatchpos ?3 :kListLenUnknown ); 403if (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. 408tv_list_append_list (rettv -> vval .v_list ,tv_list_alloc (kListLenUnknown )); 409tv_list_append_list (rettv -> vval .v_list ,tv_list_alloc (kListLenUnknown )); 410tv_list_append_list (rettv -> vval .v_list ,tv_list_alloc (kListLenUnknown )); 411 } 412 413fuzzy_match_in_list (argvars [0 ].vval .v_list , (char * )tv_get_string (& argvars [1 ]), 414matchseq ,key ,& cb ,retmatchpos ,rettv -> vval .v_list ,max_matches ); 415 416callback_free (& cb ); 417} 418 419/// "matchfuzzy()" function 420void f_matchfuzzy (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 421{ 422do_fuzzymatch (argvars ,rettv , false); 423} 424 425/// "matchfuzzypos()" function 426void f_matchfuzzypos (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 427{ 428do_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 ) 433FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 434{ 435const int v1 = ((fuzmatch_str_T * )s1 )-> score ; 436const int v2 = ((fuzmatch_str_T * )s2 )-> score ; 437const int idx1 = ((fuzmatch_str_T * )s1 )-> idx ; 438const int idx2 = ((fuzmatch_str_T * )s2 )-> idx ; 439 440if (v1 == v2 ) { 441return idx1 == idx2 ?0 :idx1 > idx2 ?1 :-1 ; 442 }else { 443return 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 ) 449FUNC_ATTR_NONNULL_ALL 450{ 451// Sort the list by the descending order of the match score 452qsort (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 ) 458FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 459{ 460const int v1 = ((fuzmatch_str_T * )s1 )-> score ; 461const int v2 = ((fuzmatch_str_T * )s2 )-> score ; 462const int idx1 = ((fuzmatch_str_T * )s1 )-> idx ; 463const int idx2 = ((fuzmatch_str_T * )s2 )-> idx ; 464const char * const str1 = ((fuzmatch_str_T * )s1 )-> str ; 465const char * const str2 = ((fuzmatch_str_T * )s2 )-> str ; 466 467if (* str1 != '<' && * str2 == '<' ) { 468return -1 ; 469 } 470if (* str1 == '<' && * str2 != '<' ) { 471return 1 ; 472 } 473if (v1 == v2 ) { 474return idx1 == idx2 ?0 :idx1 > idx2 ?1 :-1 ; 475 } 476return 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 ) 482FUNC_ATTR_NONNULL_ALL 483{ 484// Sort the list by the descending order of the match score 485qsort (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 ) 491FUNC_ATTR_WARN_UNUSED_RESULT 492{ 493if (str == NULL || pat == NULL ) { 494return 0 ; 495 } 496 497int score = FUZZY_SCORE_NONE ; 498uint32_t matchpos [FUZZY_MATCH_MAX_LEN ]; 499fuzzy_match (str ,pat , true,& score ,matchpos ,ARRAY_SIZE (matchpos )); 500 501return 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{ 508if (str == NULL || pat == NULL ) { 509return NULL ; 510 } 511 512garray_T * match_positions = xmalloc (sizeof (garray_T )); 513ga_init (match_positions ,sizeof (uint32_t ),10 ); 514 515int score = FUZZY_SCORE_NONE ; 516uint32_t matches [FUZZY_MATCH_MAX_LEN ]; 517if (!fuzzy_match (str ,pat , false,& score ,matches ,FUZZY_MATCH_MAX_LEN ) 518|| score == FUZZY_SCORE_NONE ) { 519ga_clear (match_positions ); 520xfree (match_positions ); 521return NULL ; 522 } 523 524int j = 0 ; 525for (const char * p = pat ;* p != NUL ;MB_PTR_ADV (p )) { 526if (!ascii_iswhite (utf_ptr2char (p ))) { 527GA_APPEND (uint32_t ,match_positions ,matches [j ]); 528j ++ ; 529 } 530 } 531 532return 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{ 547char * str = * ptr ; 548char * strBegin = str ; 549char * end = NULL ; 550char * start = NULL ; 551bool found = false; 552 553if (str == NULL || pat == NULL ) { 554return found ; 555 } 556char * line_end = find_line_end (str ); 557 558while (str < line_end ) { 559// Skip non-word characters 560start = find_word_start (str ); 561if (* start == NUL ) { 562break ; 563 } 564end = find_word_end (start ); 565 566// Extract the word from start to end 567char save_end = * end ; 568* end = NUL ; 569 570// Perform fuzzy match 571* score = fuzzy_match_str (start ,pat ); 572* end = save_end ; 573 574if (* score != FUZZY_SCORE_NONE ) { 575* len = (int )(end - start ); 576found = true; 577* ptr = start ; 578if (current_pos ) { 579current_pos -> col += (int )(end - strBegin ); 580 } 581break ; 582 } 583 584// Move to the end of the current word for the next iteration 585str = end ; 586// Ensure we continue searching after the current word 587while (* str != NUL && !vim_iswordp (str )) { 588MB_PTR_ADV (str ); 589 } 590 } 591 592if (!found ) { 593* ptr = line_end ; 594 } 595 596return 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 , 606int * len ,char ** ptr ,int * score ) 607{ 608pos_T current_pos = * pos ; 609pos_T circly_end ; 610bool found_new_match = false; 611bool looped_around = false; 612 613bool whole_line = ctrl_x_mode_whole_line (); 614 615if (buf == curbuf ) { 616circly_end = * start_pos ; 617 }else { 618circly_end .lnum = buf -> b_ml .ml_line_count ; 619circly_end .col = 0 ; 620circly_end .coladd = 0 ; 621 } 622 623if (whole_line && start_pos -> lnum != pos -> lnum ) { 624current_pos .lnum += dir ; 625 } 626 627while (true) { 628// Check if looped around and back to start position 629if (looped_around && (whole_line ?current_pos .lnum == circly_end .lnum 630 :equalpos (current_pos ,circly_end ))) { 631break ; 632 } 633 634// Ensure current_pos is valid 635if (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 ); 638if (!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 644if (* ptr != NULL && ** ptr != NUL ) { 645if (!whole_line ) { 646// Try to find a fuzzy match in the current line starting 647// from current position 648found_new_match = fuzzy_match_str_in_line (ptr ,pattern , 649len ,& current_pos ,score ); 650if (found_new_match ) { 651* pos = current_pos ; 652break ; 653 }else if (looped_around && current_pos .lnum == circly_end .lnum ) { 654break ; 655 } 656 }else { 657char * line = * ptr ; 658char * p = skipwhite (line ); 659if (fuzzy_match_str (p ,pattern )!= FUZZY_SCORE_NONE ) { 660found_new_match = true; 661* pos = current_pos ; 662* ptr = p ; 663* len = ml_get_buf_len (buf ,current_pos .lnum )- (int )(p - line ); 664break ; 665 } 666 } 667 } 668 } 669 670// Move to the next line or previous line based on direction 671if (dir == FORWARD ) { 672if (++ current_pos .lnum > buf -> b_ml .ml_line_count ) { 673if (p_ws ) { 674current_pos .lnum = 1 ; 675looped_around = true; 676 }else { 677break ; 678 } 679 } 680 }else { 681if (-- current_pos .lnum < 1 ) { 682if (p_ws ) { 683current_pos .lnum = buf -> b_ml .ml_line_count ; 684looped_around = true; 685 }else { 686break ; 687 } 688 } 689 } 690current_pos .col = 0 ; 691 } 692 693return 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{ 699if (fuzmatch == NULL ) { 700return ; 701 } 702for (int i = 0 ;i < count ;i ++ ) { 703xfree (fuzmatch [i ].str ); 704 } 705xfree (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 , 711const int count ,const bool funcsort ) 712FUNC_ATTR_NONNULL_ARG (2 ) 713{ 714if (count <=0 ) { 715 gototheend ; 716 } 717 718* matches = xmalloc ((size_t )count * sizeof (char * )); 719 720// Sort the list by the descending order of the match score 721if (funcsort ) { 722fuzzy_match_func_sort (fuzmatch ,count ); 723 }else { 724fuzzy_match_str_sort (fuzmatch ,count ); 725 } 726 727for (int i = 0 ;i < count ;i ++ ) { 728 (* matches )[i ]= fuzmatch [i ].str ; 729 } 730 731theend : 732xfree (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{ 751if (!needle || !haystack || !* needle ) { 752return FAIL ; 753 } 754 755const char * n_ptr = needle ; 756const char * h_ptr = haystack ; 757 758while (* n_ptr ) { 759const int n_char = utf_ptr2char (n_ptr ); 760const int n_upper = mb_toupper (n_char ); 761bool found = false; 762 763while (* h_ptr ) { 764const int h_char = utf_ptr2char (h_ptr ); 765if (h_char == n_char || h_char == n_upper ) { 766found = true; 767h_ptr += utfc_ptr2len (h_ptr ); 768break ; 769 } 770h_ptr += utfc_ptr2len (h_ptr ); 771 } 772 773if (!found ) { 774return FAIL ; 775 } 776 777n_ptr += utfc_ptr2len (n_ptr ); 778 } 779 780return OK ; 781} 782 783struct match_struct { 784int needle_len ; 785int haystack_len ; 786int lower_needle [MATCH_MAX_LEN ];///< stores codepoints 787int lower_haystack [MATCH_MAX_LEN ];///< stores codepoints 788score_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{ 797if (ASCII_ISALNUM (c )|| vim_iswordc (c )) { 798if (IS_PATH_SEP (last_c )) { 799return SCORE_MATCH_SLASH ; 800 } 801if (IS_WORD_SEP (last_c )) { 802return SCORE_MATCH_WORD ; 803 } 804if (IS_DOT (last_c )) { 805return SCORE_MATCH_DOT ; 806 } 807if (mb_isupper (c )&& mb_islower (last_c )) { 808return SCORE_MATCH_CAPITAL ; 809 } 810 } 811return 0 ; 812} 813 814static void setup_match_struct (match_struct * const match ,const char * const needle , 815const char * const haystack ) 816{ 817int i = 0 ; 818const char * p = needle ; 819while (* p != NUL && i < MATCH_MAX_LEN ) { 820const int c = utf_ptr2char (p ); 821match -> lower_needle [i ++ ]= mb_tolower (c ); 822MB_PTR_ADV (p ); 823 } 824match -> needle_len = i ; 825 826i = 0 ; 827p = haystack ; 828int prev_c = '/' ; 829while (* p != NUL && i < MATCH_MAX_LEN ) { 830const int c = utf_ptr2char (p ); 831match -> lower_haystack [i ]= mb_tolower (c ); 832match -> match_bonus [i ]= compute_bonus_codepoint (prev_c ,c ); 833prev_c = c ; 834MB_PTR_ADV (p ); 835i ++ ; 836 } 837match -> haystack_len = i ; 838} 839 840static inline void match_row (const match_struct * match ,int row ,score_t * curr_D ,score_t * curr_M , 841const score_t * last_D ,const score_t * last_M ) 842{ 843int n = match -> needle_len ; 844int m = match -> haystack_len ; 845int i = row ; 846 847const int * lower_needle = match -> lower_needle ; 848const int * lower_haystack = match -> lower_haystack ; 849const score_t * match_bonus = match -> match_bonus ; 850 851score_t prev_score = (score_t )SCORE_MIN ; 852score_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 855score_t prev_M = (score_t )SCORE_MIN ,prev_D = (score_t )SCORE_MIN ; 856 857for (int j = 0 ;j < m ;j ++ ) { 858if (lower_needle [i ]== lower_haystack [j ]) { 859score_t score = (score_t )SCORE_MIN ; 860if (!i ) { 861score = (j * SCORE_GAP_LEADING )+ match_bonus [j ]; 862 }else if (j ) {// i > 0 && j > 0 863score = MAX (prev_M + match_bonus [j ], 864// consecutive match, doesn't stack with match_bonus 865prev_D + SCORE_MATCH_CONSECUTIVE ); 866 } 867prev_D = last_D [j ]; 868prev_M = last_M [j ]; 869curr_D [j ]= score ; 870curr_M [j ]= prev_score = MAX (score ,prev_score + gap_score ); 871 }else { 872prev_D = last_D [j ]; 873prev_M = last_M [j ]; 874curr_D [j ]= (score_t )SCORE_MIN ; 875curr_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 , 881uint32_t * const positions ) 882{ 883if (!needle || !haystack || !* needle ) { 884return (score_t )SCORE_MIN ; 885 } 886 887match_struct match ; 888setup_match_struct (& match ,needle ,haystack ); 889 890int n = match .needle_len ; 891int m = match .haystack_len ; 892 893if (m > MATCH_MAX_LEN || n > m ) { 894// Unreasonably large candidate: return no score 895return (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. 902bool equal = true; 903for (int i = 0 ;i < n ;i ++ ) { 904if (match .lower_needle [i ]!= match .lower_haystack [i ]) { 905equal = false; 906break ; 907 } 908 } 909if (equal ) { 910if (positions ) { 911for (int i = 0 ;i < n ;i ++ ) { 912positions [i ]= (uint32_t )i ; 913 } 914 } 915return (score_t )SCORE_MAX ; 916 } 917 } 918 919// ensure n * MATCH_MAX_LEN * 2 won't overflow 920if ((size_t )n > (SIZE_MAX /sizeof (score_t )) /MATCH_MAX_LEN /2 ) { 921return (score_t )SCORE_MIN ; 922 } 923 924// Allocate for both D and M matrices in one contiguous block 925score_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. 929score_t (* D )[MATCH_MAX_LEN ]= (score_t (* )[MATCH_MAX_LEN ])(block ); 930score_t (* M )[MATCH_MAX_LEN ]= (score_t (* )[MATCH_MAX_LEN ])(block 931+ MATCH_MAX_LEN * (size_t )n ); 932 933match_row (& match ,0 ,D [0 ],M [0 ],D [0 ],M [0 ]); 934for (int i = 1 ;i < n ;i ++ ) { 935match_row (& match ,i ,D [i ],M [i ],D [i - 1 ],M [i - 1 ]); 936 } 937 938// backtrace to find the positions of optimal matching 939if (positions ) { 940int match_required = 0 ; 941for (int i = n - 1 ,j = m - 1 ;i >=0 ;i -- ) { 942for (;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. 949if (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 954match_required = i && j 955&& M [i ][j ]== D [i - 1 ][j - 1 ]+ SCORE_MATCH_CONSECUTIVE ; 956positions [i ]= (uint32_t )(j -- ); 957break ; 958 } 959 } 960 } 961 } 962 963score_t result = M [n - 1 ][m - 1 ]; 964 965xfree (block ); 966return result ; 967}