robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// spellsuggest.c: functions for spelling suggestions 2 3#include <assert.h> 4#include <inttypes.h> 5#include <limits.h> 6#include <stdbool.h> 7#include <stddef.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <string.h> 11 12#include "nvim/ascii_defs.h" 13#include "nvim/buffer_defs.h" 14#include "nvim/change.h" 15#include "nvim/charset.h" 16#include "nvim/cursor.h" 17#include "nvim/dialog.h" 18#include "nvim/errors.h" 19#include "nvim/eval/typval.h" 20#include "nvim/eval/typval_defs.h" 21#include "nvim/eval/vars.h" 22#include "nvim/fileio.h" 23#include "nvim/garray.h" 24#include "nvim/garray_defs.h" 25#include "nvim/gettext_defs.h" 26#include "nvim/globals.h" 27#include "nvim/hashtab.h" 28#include "nvim/hashtab_defs.h" 29#include "nvim/highlight_defs.h" 30#include "nvim/input.h" 31#include "nvim/lua/executor.h" 32#include "nvim/macros_defs.h" 33#include "nvim/mbyte.h" 34#include "nvim/mbyte_defs.h" 35#include "nvim/memline.h" 36#include "nvim/memory.h" 37#include "nvim/message.h" 38#include "nvim/normal.h" 39#include "nvim/option.h" 40#include "nvim/option_vars.h" 41#include "nvim/os/fs.h" 42#include "nvim/os/input.h" 43#include "nvim/os/os_defs.h" 44#include "nvim/pos_defs.h" 45#include "nvim/profile.h" 46#include "nvim/spell.h" 47#include "nvim/spell_defs.h" 48#include "nvim/spellfile.h" 49#include "nvim/spellsuggest.h" 50#include "nvim/strings.h" 51#include "nvim/types_defs.h" 52#include "nvim/ui.h" 53#include "nvim/ui_defs.h" 54#include "nvim/undo.h" 55#include "nvim/vim_defs.h" 56 57// Use this to adjust the score after finding suggestions, based on the 58// suggested word sounding like the bad word. This is much faster than doing 59// it for every possible suggestion. 60// Disadvantage: When "the" is typed as "hte" it sounds quite different ("@" 61// vs "ht") and goes down in the list. 62// Used when 'spellsuggest' is set to "best". 63#define RESCORE (word_score ,sound_score ) ((3 * (word_score) + (sound_score)) / 4) 64 65// Do the opposite: based on a maximum end score and a known sound score, 66// compute the maximum word score that can be used. 67#define MAXSCORE (word_score ,sound_score ) ((4 * (word_score) - (sound_score)) / 3) 68 69// only used for su_badflags 70#define WF_MIXCAP 0x20 // mix of upper and lower case: macaRONI 71 72/// Information used when looking for suggestions. 73typedef struct { 74garray_T su_ga ;///< suggestions, contains "suggest_T" 75int su_maxcount ;///< max. number of suggestions displayed 76int su_maxscore ;///< maximum score for adding to su_ga 77int su_sfmaxscore ;///< idem, for when doing soundfold words 78garray_T su_sga ;///< like su_ga, sound-folded scoring 79char * su_badptr ;///< start of bad word in line 80int su_badlen ;///< length of detected bad word in line 81int su_badflags ;///< caps flags for bad word 82char su_badword [MAXWLEN ];///< bad word truncated at su_badlen 83char su_fbadword [MAXWLEN ];///< su_badword case-folded 84char su_sal_badword [MAXWLEN ];///< su_badword soundfolded 85hashtab_T su_banned ;///< table with banned words 86slang_T * su_sallang ;///< default language for sound folding 87}suginfo_T ; 88 89/// One word suggestion. Used in "si_ga". 90typedef struct { 91char * st_word ;///< suggested word, allocated string 92int st_wordlen ;///< strlen(st_word) 93int st_orglen ;///< length of replaced text 94int st_score ;///< lower is better 95int st_altscore ;///< used when st_score compares equal 96bool st_salscore ;///< st_score is for soundalike 97bool st_had_bonus ;///< bonus already included in score 98slang_T * st_slang ;///< language used for sound folding 99}suggest_T ; 100 101#define SUG (ga ,i ) (((suggest_T *)(ga).ga_data)[i]) 102 103// True if a word appears in the list of banned words. 104#define WAS_BANNED (su ,word ) (!HASHITEM_EMPTY(hash_find(&(su)->su_banned, word))) 105 106// Number of suggestions kept when cleaning up. We need to keep more than 107// what is displayed, because when rescore_suggestions() is called the score 108// may change and wrong suggestions may be removed later. 109#define SUG_CLEAN_COUNT (su ) ((su)->su_maxcount < \ 110 130 ? 150 : (su)->su_maxcount + 20) 111 112// Threshold for sorting and cleaning up suggestions. Don't want to keep lots 113// of suggestions that are not going to be displayed. 114#define SUG_MAX_COUNT (su ) (SUG_CLEAN_COUNT(su) + 50) 115 116// score for various changes 117enum { 118SCORE_SPLIT = 149 ,// split bad word 119SCORE_SPLIT_NO = 249 ,// split bad word with NOSPLITSUGS 120SCORE_ICASE = 52 ,// slightly different case 121SCORE_REGION = 200 ,// word is for different region 122SCORE_RARE = 180 ,// rare word 123SCORE_SWAP = 75 ,// swap two characters 124SCORE_SWAP3 = 110 ,// swap two characters in three 125SCORE_REP = 65 ,// REP replacement 126SCORE_SUBST = 93 ,// substitute a character 127SCORE_SIMILAR = 33 ,// substitute a similar character 128SCORE_SUBCOMP = 33 ,// substitute a composing character 129SCORE_DEL = 94 ,// delete a character 130SCORE_DELDUP = 66 ,// delete a duplicated character 131SCORE_DELCOMP = 28 ,// delete a composing character 132SCORE_INS = 96 ,// insert a character 133SCORE_INSDUP = 67 ,// insert a duplicate character 134SCORE_INSCOMP = 30 ,// insert a composing character 135SCORE_NONWORD = 103 ,// change non-word to word char 136}; 137 138enum { 139SCORE_FILE = 30 ,// suggestion from a file 140SCORE_MAXINIT = 350 ,// Initial maximum score: higher == slower. 141// 350 allows for about three changes. 142}; 143 144enum { 145SCORE_COMMON1 = 30 ,// subtracted for words seen before 146SCORE_COMMON2 = 40 ,// subtracted for words often seen 147SCORE_COMMON3 = 50 ,// subtracted for words very often seen 148SCORE_THRES2 = 10 ,// word count threshold for COMMON2 149SCORE_THRES3 = 100 ,// word count threshold for COMMON3 150}; 151 152// When trying changed soundfold words it becomes slow when trying more than 153// two changes. With less than two changes it's slightly faster but we miss a 154// few good suggestions. In rare cases we need to try three of four changes. 155enum { 156SCORE_SFMAX1 = 200 ,// maximum score for first try 157SCORE_SFMAX2 = 300 ,// maximum score for second try 158SCORE_SFMAX3 = 400 ,// maximum score for third try 159}; 160 161#define SCORE_BIG (SCORE_INS * 3) // big difference 162enum { 163SCORE_MAXMAX = 999999 ,// accept any score 164SCORE_LIMITMAX = 350 ,// for spell_edit_score_limit() 165}; 166 167// for spell_edit_score_limit() we need to know the minimum value of 168// SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS 169#define SCORE_EDIT_MIN SCORE_SIMILAR 170 171/// For finding suggestions: At each node in the tree these states are tried: 172typedef enum { 173STATE_START = 0 ,///< At start of node check for NUL bytes (goodword 174///< ends); if badword ends there is a match, otherwise 175///< try splitting word. 176STATE_NOPREFIX ,///< try without prefix 177STATE_SPLITUNDO ,///< Undo splitting. 178STATE_ENDNUL ,///< Past NUL bytes at start of the node. 179STATE_PLAIN ,///< Use each byte of the node. 180STATE_DEL ,///< Delete a byte from the bad word. 181STATE_INS_PREP ,///< Prepare for inserting bytes. 182STATE_INS ,///< Insert a byte in the bad word. 183STATE_SWAP ,///< Swap two bytes. 184STATE_UNSWAP ,///< Undo swap two characters. 185STATE_SWAP3 ,///< Swap two characters over three. 186STATE_UNSWAP3 ,///< Undo Swap two characters over three. 187STATE_UNROT3L ,///< Undo rotate three characters left 188STATE_UNROT3R ,///< Undo rotate three characters right 189STATE_REP_INI ,///< Prepare for using REP items. 190STATE_REP ,///< Use matching REP items from the .aff file. 191STATE_REP_UNDO ,///< Undo a REP item replacement. 192STATE_FINAL ,///< End of this node. 193}state_T ; 194 195/// Struct to keep the state at each level in suggest_try_change(). 196typedef struct { 197state_T ts_state ;///< state at this level, STATE_ 198int ts_score ;///< score 199idx_T ts_arridx ;///< index in tree array, start of node 200int16_t ts_curi ;///< index in list of child nodes 201uint8_t ts_fidx ;///< index in fword[], case-folded bad word 202uint8_t ts_fidxtry ;///< ts_fidx at which bytes may be changed 203uint8_t ts_twordlen ;///< valid length of tword[] 204uint8_t ts_prefixdepth ;///< stack depth for end of prefix or 205///< PFD_PREFIXTREE or PFD_NOPREFIX 206uint8_t ts_flags ;///< TSF_ flags 207uint8_t ts_tcharlen ;///< number of bytes in tword character 208uint8_t ts_tcharidx ;///< current byte index in tword character 209uint8_t ts_isdiff ;///< DIFF_ values 210uint8_t ts_fcharstart ;///< index in fword where badword char started 211uint8_t ts_prewordlen ;///< length of word in "preword[]" 212uint8_t ts_splitoff ;///< index in "tword" after last split 213uint8_t ts_splitfidx ;///< "ts_fidx" at word split 214uint8_t ts_complen ;///< nr of compound words used 215uint8_t ts_compsplit ;///< index for "compflags" where word was spit 216uint8_t ts_save_badflags ;///< su_badflags saved here 217uint8_t ts_delidx ;///< index in fword for char that was deleted, 218///< valid when "ts_flags" has TSF_DIDDEL 219}trystate_T ; 220 221// values for ts_isdiff 222enum { 223DIFF_NONE = 0 ,// no different byte (yet) 224DIFF_YES = 1 ,// different byte found 225DIFF_INSERT = 2 ,// inserting character 226}; 227 228// values for ts_flags 229enum { 230TSF_PREFIXOK = 1 ,// already checked that prefix is OK 231TSF_DIDSPLIT = 2 ,// tried split at this point 232TSF_DIDDEL = 4 ,// did a delete, "ts_delidx" has index 233}; 234 235// special values ts_prefixdepth 236enum { 237PFD_NOPREFIX = 0xff ,// not using prefixes 238PFD_PREFIXTREE = 0xfe ,// walking through the prefix tree 239PFD_NOTSPECIAL = 0xfd ,// highest value that's not special 240}; 241 242static int spell_suggest_timeout = 5000 ; 243 244#include "spellsuggest.c.generated.h" 245 246/// Returns true when the sequence of flags in "compflags" plus "flag" can 247/// possibly form a valid compounded word. This also checks the COMPOUNDRULE 248/// lines if they don't contain wildcards. 249static bool can_be_compound (trystate_T * sp ,slang_T * slang ,uint8_t * compflags ,int flag ) 250{ 251// If the flag doesn't appear in sl_compstartflags or sl_compallflags 252// then it can't possibly compound. 253if (!byte_in_str (sp -> ts_complen == sp -> ts_compsplit 254 ?slang -> sl_compstartflags :slang -> sl_compallflags ,flag )) { 255return false; 256 } 257 258// If there are no wildcards, we can check if the flags collected so far 259// possibly can form a match with COMPOUNDRULE patterns. This only 260// makes sense when we have two or more words. 261if (slang -> sl_comprules != NULL && sp -> ts_complen > sp -> ts_compsplit ) { 262compflags [sp -> ts_complen ]= (uint8_t )flag ; 263compflags [sp -> ts_complen + 1 ]= NUL ; 264bool v = match_compoundrule (slang ,compflags + sp -> ts_compsplit ); 265compflags [sp -> ts_complen ]= NUL ; 266return v ; 267 } 268 269return true; 270} 271 272/// Adjust the score of common words. 273/// 274/// @param split word was split, less bonus 275static int score_wordcount_adj (slang_T * slang ,int score ,char * word ,bool split ) 276{ 277int bonus ; 278 279hashitem_T * hi = hash_find (& slang -> sl_wordcount ,word ); 280if (HASHITEM_EMPTY (hi )) { 281return score ; 282 } 283 284wordcount_T * wc = HI2WC (hi ); 285if (wc -> wc_count < SCORE_THRES2 ) { 286bonus = SCORE_COMMON1 ; 287 }else if (wc -> wc_count < SCORE_THRES3 ) { 288bonus = SCORE_COMMON2 ; 289 }else { 290bonus = SCORE_COMMON3 ; 291 } 292int newscore = split ?score - bonus /2 293 :score - bonus ; 294if (newscore < 0 ) { 295return 0 ; 296 } 297return newscore ; 298} 299 300/// Like captype() but for a KEEPCAP word add ONECAP if the word starts with a 301/// capital. So that make_case_word() can turn WOrd into Word. 302/// Add ALLCAP for "WOrD". 303static int badword_captype (char * word ,char * end ) 304FUNC_ATTR_NONNULL_ALL 305{ 306int flags = captype (word ,end ); 307 308if (!(flags & WF_KEEPCAP )) { 309return flags ; 310 } 311 312// Count the number of UPPER and lower case letters. 313int l = 0 ; 314int u = 0 ; 315bool first = false; 316for (char * p = word ;p < end ;MB_PTR_ADV (p )) { 317int c = utf_ptr2char (p ); 318if (SPELL_ISUPPER (c )) { 319u ++ ; 320if (p == word ) { 321first = true; 322 } 323 }else { 324l ++ ; 325 } 326 } 327 328// If there are more UPPER than lower case letters suggest an 329// ALLCAP word. Otherwise, if the first letter is UPPER then 330// suggest ONECAP. Exception: "ALl" most likely should be "All", 331// require three upper case letters. 332if (u > l && u > 2 ) { 333flags |=WF_ALLCAP ; 334 }else if (first ) { 335flags |=WF_ONECAP ; 336 } 337 338if (u >=2 && l >=2 ) {// maCARONI maCAroni 339flags |=WF_MIXCAP ; 340 } 341 342return flags ; 343} 344 345/// Opposite of offset2bytes(). 346/// "pp" points to the bytes and is advanced over it. 347/// 348/// @return the offset. 349static int bytes2offset (char ** pp ) 350{ 351uint8_t * p = (uint8_t * )(* pp ); 352int nr ; 353 354int c = * p ++ ; 355if ((c & 0x80 )== 0x00 ) {// 1 byte 356nr = c - 1 ; 357 }else if ((c & 0xc0 )== 0x80 ) {// 2 bytes 358nr = (c & 0x3f )- 1 ; 359nr = nr * 255 + (* p ++ - 1 ); 360 }else if ((c & 0xe0 )== 0xc0 ) {// 3 bytes 361nr = (c & 0x1f )- 1 ; 362nr = nr * 255 + (* p ++ - 1 ); 363nr = nr * 255 + (* p ++ - 1 ); 364 }else {// 4 bytes 365nr = (c & 0x0f )- 1 ; 366nr = nr * 255 + (* p ++ - 1 ); 367nr = nr * 255 + (* p ++ - 1 ); 368nr = nr * 255 + (* p ++ - 1 ); 369 } 370 371* pp = (char * )p ; 372return nr ; 373} 374 375// values for sps_flags 376enum { 377SPS_BEST = 1 , 378SPS_FAST = 2 , 379SPS_DOUBLE = 4 , 380}; 381 382static int sps_flags = SPS_BEST ;///< flags from 'spellsuggest' 383static int sps_limit = 9999 ;///< max nr of suggestions given 384 385/// Check the 'spellsuggest' option. Return FAIL if it's wrong. 386/// Updates "sps_flags" and "sps_limit" only when the value is valid. 387int spell_check_sps (void ) 388{ 389int flags = 0 ; 390int limit = 9999 ; 391 392const char * key ,* val ; 393size_t keylen ,vallen ; 394for (const char * p = p_sps ;option_next_keyval (& p ,& key ,& keylen ,& val ,& vallen );) { 395int f = 0 ; 396if (val == NULL ) { 397// A bare number is the suggestion limit. 398if (keylen > 0 && ascii_isdigit ((uint8_t )(* key ))) { 399char * s = (char * )key ; 400limit = getdigits_int (& s , true,0 ); 401if (s != key + keylen ) {// trailing non-digits 402f = -1 ; 403 } 404 }else if (option_slice_eq (key ,keylen ,"best" )) { 405f = SPS_BEST ; 406 }else if (option_slice_eq (key ,keylen ,"fast" )) { 407f = SPS_FAST ; 408 }else if (option_slice_eq (key ,keylen ,"double" )) { 409f = SPS_DOUBLE ; 410 }else { 411f = -1 ; 412 } 413 }else if (option_slice_eq (key ,keylen ,"expr" )|| option_slice_eq (key ,keylen ,"file" )) { 414// Value is an expression/filename, consumed later in spell_find_suggest(). 415 }else if (option_slice_eq (key ,keylen ,"timeout" )) { 416// Optional leading '-', then at least one digit. 417const char * v = val ; 418size_t vl = vallen ; 419if (vl > 0 && * v == '-' ) { 420v ++ ; 421vl -- ; 422 } 423if (vl == 0 || !ascii_isdigit ((uint8_t )(* v ))) { 424f = -1 ; 425 } 426 }else { 427f = -1 ; 428 } 429 430if (f == -1 || (flags != 0 && f != 0 )) { 431return FAIL ; 432 } 433if (f != 0 ) { 434flags = f ; 435 } 436 } 437 438if (flags == 0 ) { 439flags = SPS_BEST ; 440 } 441sps_flags = flags ; 442sps_limit = limit ; 443 444return OK ; 445} 446 447/// Let the user pick a spell suggestion. Delegates to (async) `vim.ui.select()`. 448static void select_spell_suggestion (suginfo_T * sug ) 449{ 450typval_T items_tv ; 451tv_list_alloc_ret (& items_tv ,sug -> su_ga .ga_len ); 452 453for (int i = 0 ;i < sug -> su_ga .ga_len ;i ++ ) { 454suggest_T * stp = & SUG (sug -> su_ga ,i ); 455 456dict_T * d = tv_dict_alloc (); 457 458// The suggested word may replace only part of the bad word; append the 459// unreplaced tail to form the user-visible "word". 460int el = sug -> su_badlen - stp -> st_orglen ; 461if (el > 0 ) { 462char * word = xmallocz ((size_t )stp -> st_wordlen + (size_t )el ); 463memcpy (word ,stp -> st_word , (size_t )stp -> st_wordlen ); 464memcpy (word + stp -> st_wordlen ,sug -> su_badptr + stp -> st_orglen , (size_t )el ); 465tv_dict_add_allocated_str (d ,S_LEN ("word" ),word ); 466 }else { 467tv_dict_add_str (d ,S_LEN ("word" ),stp -> st_word ); 468 } 469 470// The suggestion may replace MORE than su_badlen of the bad text; 471// capture that wider span as `extra`. 472if (sug -> su_badlen < stp -> st_orglen ) { 473char * extra = xstrnsave (sug -> su_badptr , (size_t )stp -> st_orglen ); 474tv_dict_add_allocated_str (d ,S_LEN ("extra" ),extra ); 475 } 476 477// Pass raw scoring data; Lua decides whether/how to render. 478// `altscore`/`salscore` are only meaningful with SPS_DOUBLE|SPS_BEST. 479tv_dict_add_nr (d ,S_LEN ("score" ),stp -> st_score ); 480if (sps_flags & (SPS_DOUBLE |SPS_BEST )) { 481tv_dict_add_nr (d ,S_LEN ("altscore" ),stp -> st_altscore ); 482tv_dict_add_bool (d ,S_LEN ("salscore" ), 483stp -> st_salscore ?kBoolVarTrue :kBoolVarFalse ); 484 } 485 486typval_T item = { .v_type = VAR_DICT , .vval .v_dict = d }; 487tv_list_append_tv (items_tv .vval .v_list ,& item ); 488 } 489 490typval_T bad_tv = { .v_type = VAR_STRING , 491 .vval .v_string = xstrnsave (sug -> su_badptr , (size_t )sug -> su_badlen ) }; 492typval_T lua_args []= {items_tv ,bad_tv , { .v_type = VAR_UNKNOWN } }; 493nlua_call_typval ("vim._core.spell" ,"select_suggest" ,lua_args ,NULL ); 494 495tv_clear (& items_tv ); 496tv_clear (& bad_tv ); 497} 498 499/// "z=": Find badly spelled word under or after the cursor. 500/// Give suggestions for the properly spelled word. 501/// In Visual mode use the highlighted word as the bad word. 502/// When "count" is non-zero use that suggestion. 503void spell_suggest (int count ) 504{ 505int badlen = 0 ; 506int msg_scroll_save = msg_scroll ; 507const int wo_spell_save = curwin -> w_p_spell ; 508 509if (!curwin -> w_p_spell ) { 510parse_spelllang (curwin ); 511curwin -> w_p_spell = true; 512 } 513// Autocommands may have changed the buffer and made the cursor invalid 514check_cursor (curwin ); 515pos_T prev_cursor = curwin -> w_cursor ; 516 517if (* curwin -> w_s -> b_p_spl == NUL ) { 518emsg (_ (e_no_spell )); 519 gotoskip ; 520 } 521 522if (Visual .active ) { 523// Use the Visually selected text as the bad word. But reject 524// a multi-line selection. 525if (curwin -> w_cursor .lnum != Visual .start .lnum ) { 526vim_beep (kOptBoFlagSpell ); 527 gotoskip ; 528 } 529badlen = (int )curwin -> w_cursor .col - (int )Visual .start .col ; 530if (badlen < 0 ) { 531badlen = - badlen ; 532 }else { 533curwin -> w_cursor .col = Visual .start .col ; 534 } 535badlen ++ ; 536end_visual_mode (); 537// make sure we don't include the NUL at the end of the line 538badlen = MIN (badlen ,get_cursor_line_len ()- curwin -> w_cursor .col ); 539// Find the start of the badly spelled word. 540 }else if (spell_move_to (curwin ,FORWARD ,SMT_ALL , true,NULL )== 0 541|| curwin -> w_cursor .col > prev_cursor .col ) { 542// No bad word or it starts after the cursor: use the word under the 543// cursor. 544curwin -> w_cursor = prev_cursor ; 545char * curline = get_cursor_line_ptr (); 546char * p = curline + curwin -> w_cursor .col ; 547// Backup to before start of word. 548while (p > curline && spell_iswordp_nmw (p ,curwin )) { 549MB_PTR_BACK (curline ,p ); 550 } 551// Forward to start of word. 552while (* p != NUL && !spell_iswordp_nmw (p ,curwin )) { 553MB_PTR_ADV (p ); 554 } 555 556if (!spell_iswordp_nmw (p ,curwin )) {// No word found. 557beep_flush (); 558 gotoskip ; 559 } 560curwin -> w_cursor .col = (colnr_T )(p - curline ); 561 } 562 563// Get the word and its length. 564 565// Figure out if the word should be capitalised. 566int need_cap = check_need_cap (curwin ,curwin -> w_cursor .lnum ,curwin -> w_cursor .col ); 567 568// Make a copy of current line since autocommands may free the line. 569char * line = xstrnsave (get_cursor_line_ptr (), (size_t )get_cursor_line_len ()); 570spell_suggest_timeout = 5000 ; 571 572// Get the list of suggestions. Limit to 'lines' - 2 or the number in 573// 'spellsuggest', whatever is smaller. 574suginfo_T sug ; 575int limit = MIN (sps_limit ,Rows - 2 ); 576spell_find_suggest (line + curwin -> w_cursor .col ,badlen ,& sug ,limit , 577 true,need_cap , true); 578 579int selected = count ; 580if (GA_EMPTY (& sug .su_ga )) { 581msg_ext_set_kind ("wmsg" ); 582msg (_ ("No suggestions" ),0 ); 583 }else if (count > 0 ) { 584if (count > sug .su_ga .ga_len ) { 585msg_ext_set_kind ("wmsg" ); 586smsg (0 ,_ ("Only %" PRId64 " suggestions" ), (int64_t )sug .su_ga .ga_len ); 587 } 588 }else { 589// Hand off to (async) vim.ui.select(). 590curwin -> w_p_spell = wo_spell_save ; 591select_spell_suggestion (& sug ); 592 593lines_left = Rows ;// avoid more prompt 594// don't delay for 'smd' in normal_cmd() 595msg_scroll = msg_scroll_save ; 596 597spell_find_cleanup (& sug ); 598xfree (line ); 599return ; 600 } 601 602if (selected > 0 && selected <=sug .su_ga .ga_len && u_save_cursor ()== OK ) { 603// Save the from and to text for :spellrepall. 604XFREE_CLEAR (repl_from ); 605XFREE_CLEAR (repl_to ); 606 607suggest_T * stp = & SUG (sug .su_ga ,selected - 1 ); 608if (sug .su_badlen > stp -> st_orglen ) { 609// Replacing less than "su_badlen", append the remainder to 610// repl_to. 611repl_from = xstrnsave (sug .su_badptr , (size_t )sug .su_badlen ); 612vim_snprintf (IObuff ,IOSIZE ,"%s%.*s" ,stp -> st_word , 613sug .su_badlen - stp -> st_orglen , 614sug .su_badptr + stp -> st_orglen ); 615repl_to = xstrdup (IObuff ); 616 }else { 617// Replacing su_badlen or more, use the whole word. 618repl_from = xstrnsave (sug .su_badptr , (size_t )stp -> st_orglen ); 619repl_to = xstrdup (stp -> st_word ); 620 } 621 622// Replace the word. 623char * p = xmalloc (strlen (line )- (size_t )stp -> st_orglen + (size_t )stp -> st_wordlen + 1 ); 624int c = (int )(sug .su_badptr - line ); 625memmove (p ,line , (size_t )c ); 626STRCPY (p + c ,stp -> st_word ); 627strcat (p ,sug .su_badptr + stp -> st_orglen ); 628 629// For redo we use a change-word command. 630prep_redo (false, false, (CmdSpec ){ .op = 'c' , .cmd = 'i' , .cmd2 = 'w' }); 631redo_append_lit (p + c ,stp -> st_wordlen + sug .su_badlen - stp -> st_orglen ); 632redo_append_char (ESC ); 633 634// "p" may be freed here 635ml_replace (curwin -> w_cursor .lnum ,p , false); 636curwin -> w_cursor .col = c ; 637 638inserted_bytes (curwin -> w_cursor .lnum ,c ,stp -> st_orglen ,stp -> st_wordlen ); 639 }else { 640curwin -> w_cursor = prev_cursor ; 641 } 642 643spell_find_cleanup (& sug ); 644xfree (line ); 645skip : 646curwin -> w_p_spell = wo_spell_save ; 647} 648 649/// Find spell suggestions for "word". Return them in the growarray "*gap" as 650/// a list of allocated strings. 651/// 652/// @param maxcount maximum nr of suggestions 653/// @param need_cap 'spellcapcheck' matched 654void spell_suggest_list (garray_T * gap ,char * word ,int maxcount ,bool need_cap ,bool interactive ) 655{ 656suginfo_T sug ; 657 658spell_find_suggest (word ,0 ,& sug ,maxcount , false,need_cap ,interactive ); 659 660// Make room in "gap". 661ga_init (gap ,sizeof (char * ),sug .su_ga .ga_len + 1 ); 662ga_grow (gap ,sug .su_ga .ga_len ); 663for (int i = 0 ;i < sug .su_ga .ga_len ;i ++ ) { 664suggest_T * stp = & SUG (sug .su_ga ,i ); 665 666// The suggested word may replace only part of "word", add the not 667// replaced part. 668char * wcopy = xmalloc ((size_t )stp -> st_wordlen + strlen (sug .su_badptr + stp -> st_orglen )+ 1 ); 669STRCPY (wcopy ,stp -> st_word ); 670STRCPY (wcopy + stp -> st_wordlen ,sug .su_badptr + stp -> st_orglen ); 671 ((char ** )gap -> ga_data )[gap -> ga_len ++ ]= wcopy ; 672 } 673 674spell_find_cleanup (& sug ); 675} 676 677/// Find spell suggestions for the word at the start of "badptr". 678/// Return the suggestions in "su->su_ga". 679/// The maximum number of suggestions is "maxcount". 680/// Note: does use info for the current window. 681/// This is based on the mechanisms of Aspell, but completely reimplemented. 682/// 683/// @param badlen length of bad word or 0 if unknown 684/// @param banbadword don't include badword in suggestions 685/// @param need_cap word should start with capital 686static void spell_find_suggest (char * badptr ,int badlen ,suginfo_T * su ,int maxcount , 687bool banbadword ,bool need_cap ,bool interactive ) 688{ 689hlf_T attr = HLF_COUNT ; 690char buf [MAXPATHL ]; 691bool do_combine = false; 692static bool expr_busy = false; 693bool did_intern = false; 694 695// Set the info in "*su". 696CLEAR_POINTER (su ); 697ga_init (& su -> su_ga , (int )sizeof (suggest_T ),10 ); 698ga_init (& su -> su_sga , (int )sizeof (suggest_T ),10 ); 699if (* badptr == NUL ) { 700return ; 701 } 702hash_init (& su -> su_banned ); 703 704su -> su_badptr = badptr ; 705if (badlen != 0 ) { 706su -> su_badlen = badlen ; 707 }else { 708size_t tmplen = spell_check (curwin ,su -> su_badptr ,& attr ,NULL , false); 709assert (tmplen <=INT_MAX ); 710su -> su_badlen = (int )tmplen ; 711 } 712su -> su_maxcount = maxcount ; 713su -> su_maxscore = SCORE_MAXINIT ; 714su -> su_badlen = MIN (su -> su_badlen ,MAXWLEN - 1 );// just in case 715xmemcpyz (su -> su_badword ,su -> su_badptr , (size_t )su -> su_badlen ); 716spell_casefold (curwin ,su -> su_badptr ,su -> su_badlen ,su -> su_fbadword , 717MAXWLEN ); 718 719// TODO(vim): make this work if the case-folded text is longer than the 720// original text. Currently an illegal byte causes wrong pointer 721// computations. 722su -> su_fbadword [su -> su_badlen ]= NUL ; 723 724// get caps flags for bad word 725su -> su_badflags = badword_captype (su -> su_badptr , 726su -> su_badptr + su -> su_badlen ); 727if (need_cap ) { 728su -> su_badflags |=WF_ONECAP ; 729 } 730 731// Find the default language for sound folding. We simply use the first 732// one in 'spelllang' that supports sound folding. That's good for when 733// using multiple files for one language, it's not that bad when mixing 734// languages (e.g., "pl,en"). 735for (int i = 0 ;i < curbuf -> b_s .b_langp .ga_len ;i ++ ) { 736langp_T * lp = LANGP_ENTRY (curbuf -> b_s .b_langp ,i ); 737if (lp -> lp_sallang != NULL ) { 738su -> su_sallang = lp -> lp_sallang ; 739break ; 740 } 741 } 742 743// Soundfold the bad word with the default sound folding, so that we don't 744// have to do this many times. 745if (su -> su_sallang != NULL ) { 746spell_soundfold (su -> su_sallang ,su -> su_fbadword , true, 747su -> su_sal_badword ); 748 } 749 750// If the word is not capitalised and spell_check() doesn't consider the 751// word to be bad then it might need to be capitalised. Add a suggestion 752// for that. 753int c = utf_ptr2char (su -> su_badptr ); 754if (!SPELL_ISUPPER (c )&& attr == HLF_COUNT ) { 755make_case_word (su -> su_badword ,buf ,WF_ONECAP ); 756add_suggestion (su ,& su -> su_ga ,buf ,su -> su_badlen ,SCORE_ICASE , 7570 , true,su -> su_sallang , false); 758 } 759 760// Ban the bad word itself. It may appear in another region. 761if (banbadword ) { 762add_banned (su ,su -> su_badword ); 763 } 764 765// Make a copy of 'spellsuggest', because the expression may change it. 766char * sps_copy = xstrdup (p_sps ); 767 768// Loop over the items in 'spellsuggest'. 769for (char * p = sps_copy ;* p != NUL ;) { 770copy_option_part (& p ,buf ,MAXPATHL ,"," ); 771 772if (strncmp (buf ,"expr:" ,5 )== 0 ) { 773// Evaluate an expression. Skip this when called recursively, 774// when using spellsuggest() in the expression. 775if (!expr_busy ) { 776expr_busy = true; 777spell_suggest_expr (su ,buf + 5 ); 778expr_busy = false; 779 } 780 }else if (strncmp (buf ,"file:" ,5 )== 0 ) { 781// Use list of suggestions in a file. 782spell_suggest_file (su ,buf + 5 ); 783 }else if (strncmp (buf ,"timeout:" ,8 )== 0 ) { 784// Limit the time searching for suggestions. 785spell_suggest_timeout = atoi (buf + 8 ); 786 }else if (!did_intern ) { 787// Use internal method once. 788spell_suggest_intern (su ,interactive ); 789if (sps_flags & SPS_DOUBLE ) { 790do_combine = true; 791 } 792did_intern = true; 793 } 794 } 795 796xfree (sps_copy ); 797 798if (do_combine ) { 799// Combine the two list of suggestions. This must be done last, 800// because sorting changes the order again. 801score_combine (su ); 802 } 803} 804 805/// Find suggestions by evaluating expression "expr". 806static void spell_suggest_expr (suginfo_T * su ,char * expr ) 807{ 808const char * p ; 809 810// The work is split up in a few parts to avoid having to export 811// suginfo_T. 812// First evaluate the expression and get the resulting list. 813list_T * const list = eval_spell_expr (su -> su_badword ,expr ); 814if (list != NULL ) { 815// Loop over the items in the list. 816TV_LIST_ITER (list ,li , { 817if (TV_LIST_ITEM_TV (li )-> v_type == VAR_LIST ) { 818// Get the word and the score from the items. 819int score = get_spellword (TV_LIST_ITEM_TV (li )-> vval .v_list ,& p ); 820if (score >=0 && score <=su -> su_maxscore ) { 821add_suggestion (su ,& su -> su_ga ,p ,su -> su_badlen , 822score ,0 , true,su -> su_sallang , false); 823 } 824 } 825 }); 826tv_list_unref (list ); 827 } 828 829// Remove bogus suggestions, sort and truncate at "maxcount". 830check_suggestions (su ,& su -> su_ga ); 831cleanup_suggestions (& su -> su_ga ,su -> su_maxscore ,su -> su_maxcount ); 832} 833 834/// Find suggestions in file "fname". Used for "file:" in 'spellsuggest'. 835static void spell_suggest_file (suginfo_T * su ,char * fname ) 836{ 837char line [MAXWLEN * 2 ]; 838int len ; 839char cword [MAXWLEN ]; 840 841// Open the file. 842FILE * fd = os_fopen (fname ,"r" ); 843if (fd == NULL ) { 844semsg (_ (e_notopen ),fname ); 845return ; 846 } 847 848// Read it line by line. 849while (!vim_fgets (line ,MAXWLEN * 2 ,fd )&& !got_int ) { 850line_breakcheck (); 851 852char * p = vim_strchr (line ,'/' ); 853if (p == NULL ) { 854continue ;// No Tab found, just skip the line. 855 } 856* p ++ = NUL ; 857if (STRICMP (su -> su_badword ,line )== 0 ) { 858// Match! Isolate the good word, until CR or NL. 859for (len = 0 ; (uint8_t )p [len ] >=' ' ;len ++ ) {} 860p [len ]= NUL ; 861 862// If the suggestion doesn't have specific case duplicate the case 863// of the bad word. 864if (captype (p ,NULL )== 0 ) { 865make_case_word (p ,cword ,su -> su_badflags ); 866p = cword ; 867 } 868 869add_suggestion (su ,& su -> su_ga ,p ,su -> su_badlen , 870SCORE_FILE ,0 , true,su -> su_sallang , false); 871 } 872 } 873 874fclose (fd ); 875 876// Remove bogus suggestions, sort and truncate at "maxcount". 877check_suggestions (su ,& su -> su_ga ); 878cleanup_suggestions (& su -> su_ga ,su -> su_maxscore ,su -> su_maxcount ); 879} 880 881/// Find suggestions for the internal method indicated by "sps_flags". 882static void spell_suggest_intern (suginfo_T * su ,bool interactive ) 883{ 884// Load the .sug file(s) that are available and not done yet. 885suggest_load_files (); 886 887// 1. Try special cases, such as repeating a word: "the the" -> "the". 888// 889// Set a maximum score to limit the combination of operations that is 890// tried. 891suggest_try_special (su ); 892 893// 2. Try inserting/deleting/swapping/changing a letter, use REP entries 894// from the .aff file and inserting a space (split the word). 895suggest_try_change (su ); 896 897// For the resulting top-scorers compute the sound-a-like score. 898if (sps_flags & SPS_DOUBLE ) { 899score_comp_sal (su ); 900 } 901 902// 3. Try finding sound-a-like words. 903if ((sps_flags & SPS_FAST )== 0 ) { 904if (sps_flags & SPS_BEST ) { 905// Adjust the word score for the suggestions found so far for how 906// they sounds like. 907rescore_suggestions (su ); 908 } 909 910// While going through the soundfold tree "su_maxscore" is the score 911// for the soundfold word, limits the changes that are being tried, 912// and "su_sfmaxscore" the rescored score, which is set by 913// cleanup_suggestions(). 914// First find words with a small edit distance, because this is much 915// faster and often already finds the top-N suggestions. If we didn't 916// find many suggestions try again with a higher edit distance. 917// "sl_sounddone" is used to avoid doing the same word twice. 918suggest_try_soundalike_prep (); 919su -> su_maxscore = SCORE_SFMAX1 ; 920su -> su_sfmaxscore = SCORE_MAXINIT * 3 ; 921suggest_try_soundalike (su ); 922if (su -> su_ga .ga_len < SUG_CLEAN_COUNT (su )) { 923// We didn't find enough matches, try again, allowing more 924// changes to the soundfold word. 925su -> su_maxscore = SCORE_SFMAX2 ; 926suggest_try_soundalike (su ); 927if (su -> su_ga .ga_len < SUG_CLEAN_COUNT (su )) { 928// Still didn't find enough matches, try again, allowing even 929// more changes to the soundfold word. 930su -> su_maxscore = SCORE_SFMAX3 ; 931suggest_try_soundalike (su ); 932 } 933 } 934su -> su_maxscore = su -> su_sfmaxscore ; 935suggest_try_soundalike_finish (); 936 } 937 938// When CTRL-C was hit while searching do show the results. Only clear 939// got_int when using a command, not for spellsuggest(). 940os_breakcheck (); 941if (interactive && got_int ) { 942vgetc (); 943got_int = false; 944 } 945 946if ((sps_flags & SPS_DOUBLE )== 0 && su -> su_ga .ga_len != 0 ) { 947if (sps_flags & SPS_BEST ) { 948// Adjust the word score for how it sounds like. 949rescore_suggestions (su ); 950 } 951 952// Remove bogus suggestions, sort and truncate at "maxcount". 953check_suggestions (su ,& su -> su_ga ); 954cleanup_suggestions (& su -> su_ga ,su -> su_maxscore ,su -> su_maxcount ); 955 } 956} 957 958/// Free the info put in "*su" by spell_find_suggest(). 959static void spell_find_cleanup (suginfo_T * su ) 960{ 961#define FREE_SUG_WORD (sug ) xfree((sug)->st_word) 962// Free the suggestions. 963GA_DEEP_CLEAR (& su -> su_ga ,suggest_T ,FREE_SUG_WORD ); 964GA_DEEP_CLEAR (& su -> su_sga ,suggest_T ,FREE_SUG_WORD ); 965 966// Free the banned words. 967hash_clear_all (& su -> su_banned ,0 ); 968} 969 970/// Try finding suggestions by recognizing specific situations. 971static void suggest_try_special (suginfo_T * su ) 972{ 973char word [MAXWLEN ]; 974 975// Recognize a word that is repeated: "the the". 976char * p = skiptowhite (su -> su_fbadword ); 977size_t len = (size_t )(p - su -> su_fbadword ); 978p = skipwhite (p ); 979if (strlen (p )== len && strncmp (su -> su_fbadword ,p ,len )== 0 ) { 980// Include badflags: if the badword is onecap or allcap 981// use that for the goodword too: "The the" -> "The". 982char c = su -> su_fbadword [len ]; 983su -> su_fbadword [len ]= NUL ; 984make_case_word (su -> su_fbadword ,word ,su -> su_badflags ); 985su -> su_fbadword [len ]= c ; 986 987// Give a soundalike score of 0, compute the score as if deleting one 988// character. 989add_suggestion (su ,& su -> su_ga ,word ,su -> su_badlen , 990RESCORE (SCORE_REP ,0 ),0 , true,su -> su_sallang , false); 991 } 992} 993 994// Measure how much time is spent in each state. 995// Output is dumped in "suggestprof". 996 997#ifdef SUGGEST_PROFILE 998proftime_T current ; 999proftime_T total ; 1000proftime_T times [STATE_FINAL + 1 ]; 1001long counts [STATE_FINAL + 1 ]; 1002 1003static void prof_init (void ) 1004{ 1005for (int i = 0 ;i <=STATE_FINAL ;i ++ ) { 1006profile_zero (& times [i ]); 1007counts [i ]= 0 ; 1008 } 1009profile_start (& current ); 1010profile_start (& total ); 1011} 1012 1013/// call before changing state 1014static void prof_store (state_T state ) 1015{ 1016profile_end (& current ); 1017profile_add (& times [state ],& current ); 1018counts [state ]++ ; 1019profile_start (& current ); 1020} 1021# define PROF_STORE (state ) prof_store(state); 1022 1023static void prof_report (char * name ) 1024{ 1025FILE * fd = fopen ("suggestprof" ,"a" ); 1026 1027profile_end (& total ); 1028fprintf (fd ,"-----------------------\n" ); 1029fprintf (fd ,"%s: %s\n" ,name ,profile_msg (& total )); 1030for (int i = 0 ;i <=STATE_FINAL ;i ++ ) { 1031fprintf (fd ,"%d: %s (" %" PRId64)\n" ,i ,profile_msg (& times [i ]),counts [i ]); 1032 } 1033fclose (fd ); 1034} 1035#else 1036# define PROF_STORE (state ) 1037#endif 1038 1039/// Try finding suggestions by adding/removing/swapping letters. 1040static void suggest_try_change (suginfo_T * su ) 1041{ 1042char fword [MAXWLEN ];// copy of the bad word, case-folded 1043 1044// We make a copy of the case-folded bad word, so that we can modify it 1045// to find matches (esp. REP items). Append some more text, changing 1046// chars after the bad word may help. 1047STRCPY (fword ,su -> su_fbadword ); 1048int n = (int )strlen (fword ); 1049char * p = su -> su_badptr + su -> su_badlen ; 1050spell_casefold (curwin ,p , (int )strlen (p ),fword + n ,MAXWLEN - n ); 1051 1052// Make sure the resulting text is not longer than the original text. 1053n = (int )strlen (su -> su_badptr ); 1054if (n < MAXWLEN ) { 1055fword [n ]= NUL ; 1056 } 1057 1058for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 1059langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 1060 1061// If reloading a spell file fails it's still in the list but 1062// everything has been cleared. 1063if (lp -> lp_slang -> sl_fbyts == NULL ) { 1064continue ; 1065 } 1066 1067// Try it for this language. Will add possible suggestions. 1068#ifdef SUGGEST_PROFILE 1069prof_init (); 1070#endif 1071suggest_trie_walk (su ,lp ,fword , false); 1072#ifdef SUGGEST_PROFILE 1073prof_report ("try_change" ); 1074#endif 1075 } 1076} 1077 1078// Check the maximum score, if we go over it we won't try this change. 1079#define TRY_DEEPER (su ,stack ,depth ,add ) \ 1080 ((depth) < MAXWLEN - 1 && (stack)[depth].ts_score + (add) < (su)->su_maxscore) 1081 1082/// Try finding suggestions by adding/removing/swapping letters. 1083/// 1084/// This uses a state machine. At each node in the tree we try various 1085/// operations. When trying if an operation works "depth" is increased and the 1086/// stack[] is used to store info. This allows combinations, thus insert one 1087/// character, replace one and delete another. The number of changes is 1088/// limited by su->su_maxscore. 1089/// 1090/// After implementing this I noticed an article by Kemal Oflazer that 1091/// describes something similar: "Error-tolerant Finite State Recognition with 1092/// Applications to Morphological Analysis and Spelling Correction" (1996). 1093/// The implementation in the article is simplified and requires a stack of 1094/// unknown depth. The implementation here only needs a stack depth equal to 1095/// the length of the word. 1096/// 1097/// This is also used for the sound-folded word, "soundfold" is true then. 1098/// The mechanism is the same, but we find a match with a sound-folded word 1099/// that comes from one or more original words. Each of these words may be 1100/// added, this is done by add_sound_suggest(). 1101/// Don't use: 1102/// the prefix tree or the keep-case tree 1103/// "su->su_badlen" 1104/// anything to do with upper and lower case 1105/// anything to do with word or non-word characters ("spell_iswordp()") 1106/// banned words 1107/// word flags (rare, region, compounding) 1108/// word splitting for now 1109/// "similar_chars()" 1110/// use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep" 1111static void suggest_trie_walk (suginfo_T * su ,langp_T * lp ,char * fword ,bool soundfold ) 1112{ 1113char tword [MAXWLEN ];// good word collected so far 1114trystate_T stack [MAXWLEN ]; 1115char preword [MAXWLEN * 3 ]= {0 };// word found with proper case; 1116// concatenation of prefix compound 1117// words and split word. NUL terminated 1118// when going deeper but not when coming 1119// back. 1120uint8_t compflags [MAXWLEN ];// compound flags, one for each word 1121uint8_t * byts ,* fbyts ,* pbyts ; 1122idx_T * idxs ,* fidxs ,* pidxs ; 1123int c ,c2 ,c3 ; 1124int n = 0 ; 1125idx_T arridx ; 1126int fl = 0 ; 1127int tl ; 1128int repextra = 0 ;// extra bytes in fword[] from REP item 1129slang_T * slang = lp -> lp_slang ; 1130bool goodword_ends ; 1131#ifdef DEBUG_TRIEWALK 1132// Stores the name of the change made at each level. 1133uint8_t changename [MAXWLEN ][80 ]; 1134#endif 1135int breakcheckcount = 1000 ; 1136 1137// Go through the whole case-fold tree, try changes at each node. 1138// "tword[]" contains the word collected from nodes in the tree. 1139// "fword[]" the word we are trying to match with (initially the bad 1140// word). 1141int depth = 0 ; 1142trystate_T * sp = & stack [0 ]; 1143CLEAR_POINTER (sp ); 1144sp -> ts_curi = 1 ; 1145 1146if (soundfold ) { 1147// Going through the soundfold tree. 1148byts = fbyts = slang -> sl_sbyts ; 1149idxs = fidxs = slang -> sl_sidxs ; 1150pbyts = NULL ; 1151pidxs = NULL ; 1152sp -> ts_prefixdepth = PFD_NOPREFIX ; 1153sp -> ts_state = STATE_START ; 1154 }else { 1155// When there are postponed prefixes we need to use these first. At 1156// the end of the prefix we continue in the case-fold tree. 1157fbyts = slang -> sl_fbyts ; 1158fidxs = slang -> sl_fidxs ; 1159pbyts = slang -> sl_pbyts ; 1160pidxs = slang -> sl_pidxs ; 1161if (pbyts != NULL ) { 1162byts = pbyts ; 1163idxs = pidxs ; 1164sp -> ts_prefixdepth = PFD_PREFIXTREE ; 1165sp -> ts_state = STATE_NOPREFIX ;// try without prefix first 1166 }else { 1167byts = fbyts ; 1168idxs = fidxs ; 1169sp -> ts_prefixdepth = PFD_NOPREFIX ; 1170sp -> ts_state = STATE_START ; 1171 } 1172 } 1173 1174// The loop may take an indefinite amount of time. Break out after some 1175// time. 1176proftime_T time_limit = 0 ; 1177if (spell_suggest_timeout > 0 ) { 1178time_limit = profile_setlimit (spell_suggest_timeout ); 1179 } 1180 1181// Loop to find all suggestions. At each round we either: 1182// - For the current state try one operation, advance "ts_curi", 1183// increase "depth". 1184// - When a state is done go to the next, set "ts_state". 1185// - When all states are tried decrease "depth". 1186while (depth >=0 && !got_int ) { 1187sp = & stack [depth ]; 1188switch (sp -> ts_state ) { 1189case STATE_START : 1190case STATE_NOPREFIX : 1191// Start of node: Deal with NUL bytes, which means 1192// tword[] may end here. 1193arridx = sp -> ts_arridx ;// current node in the tree 1194int len = byts [arridx ];// bytes in this node 1195arridx += sp -> ts_curi ;// index of current byte 1196 1197if (sp -> ts_prefixdepth == PFD_PREFIXTREE ) { 1198// Skip over the NUL bytes, we use them later. 1199for (n = 0 ;n < len && byts [arridx + n ]== 0 ;n ++ ) {} 1200sp -> ts_curi = (int16_t )(sp -> ts_curi + n ); 1201 1202// Always past NUL bytes now. 1203n = (int )sp -> ts_state ; 1204PROF_STORE (sp -> ts_state ) 1205sp -> ts_state = STATE_ENDNUL ; 1206sp -> ts_save_badflags = (uint8_t )su -> su_badflags ; 1207 1208// At end of a prefix or at start of prefixtree: check for 1209// following word. 1210if (depth < MAXWLEN - 1 && (byts [arridx ]== 0 || n == STATE_NOPREFIX )) { 1211// Set su->su_badflags to the caps type at this position. 1212// Use the caps type until here for the prefix itself. 1213n = nofold_len (fword ,sp -> ts_fidx ,su -> su_badptr ); 1214int flags = badword_captype (su -> su_badptr ,su -> su_badptr + n ); 1215su -> su_badflags = badword_captype (su -> su_badptr + n , 1216su -> su_badptr + su -> su_badlen ); 1217#ifdef DEBUG_TRIEWALK 1218sprintf (changename [depth ],"prefix" );// NOLINT(runtime/printf) 1219#endif 1220go_deeper (stack ,depth ,0 ); 1221depth ++ ; 1222sp = & stack [depth ]; 1223sp -> ts_prefixdepth = (uint8_t )(depth - 1 ); 1224byts = fbyts ; 1225idxs = fidxs ; 1226sp -> ts_arridx = 0 ; 1227 1228// Move the prefix to preword[] with the right case 1229// and make find_keepcap_word() works. 1230tword [sp -> ts_twordlen ]= NUL ; 1231make_case_word (tword + sp -> ts_splitoff , 1232preword + sp -> ts_prewordlen ,flags ); 1233sp -> ts_prewordlen = (uint8_t )strlen (preword ); 1234sp -> ts_splitoff = sp -> ts_twordlen ; 1235 } 1236break ; 1237 } 1238 1239if (sp -> ts_curi > len || byts [arridx ]!= 0 ) { 1240// Past bytes in node and/or past NUL bytes. 1241PROF_STORE (sp -> ts_state ) 1242sp -> ts_state = STATE_ENDNUL ; 1243sp -> ts_save_badflags = (uint8_t )su -> su_badflags ; 1244break ; 1245 } 1246 1247// End of word in tree. 1248sp -> ts_curi ++ ;// eat one NUL byte 1249 1250int flags = (int )idxs [arridx ]; 1251 1252// Skip words with the NOSUGGEST flag. 1253if (flags & WF_NOSUGGEST ) { 1254break ; 1255 } 1256 1257bool fword_ends = (fword [sp -> ts_fidx ]== NUL 1258|| (soundfold 1259 ?ascii_iswhite (fword [sp -> ts_fidx ]) 1260 : !spell_iswordp (fword + sp -> ts_fidx ,curwin ))); 1261tword [sp -> ts_twordlen ]= NUL ; 1262 1263if (sp -> ts_prefixdepth <=PFD_NOTSPECIAL 1264&& (sp -> ts_flags & TSF_PREFIXOK )== 0 1265&& pbyts != NULL ) { 1266// There was a prefix before the word. Check that the prefix 1267// can be used with this word. 1268// Count the length of the NULs in the prefix. If there are 1269// none this must be the first try without a prefix. 1270n = stack [sp -> ts_prefixdepth ].ts_arridx ; 1271len = pbyts [n ++ ]; 1272for (c = 0 ;c < len && pbyts [n + c ]== 0 ;c ++ ) {} 1273if (c > 0 ) { 1274c = valid_word_prefix (c ,n ,flags , 1275tword + sp -> ts_splitoff ,slang , false); 1276if (c == 0 ) { 1277break ; 1278 } 1279 1280// Use the WF_RARE flag for a rare prefix. 1281if (c & WF_RAREPFX ) { 1282flags |=WF_RARE ; 1283 } 1284 1285// Tricky: when checking for both prefix and compounding 1286// we run into the prefix flag first. 1287// Remember that it's OK, so that we accept the prefix 1288// when arriving at a compound flag. 1289sp -> ts_flags |=TSF_PREFIXOK ; 1290 } 1291 } 1292 1293// Check NEEDCOMPOUND: can't use word without compounding. Do try 1294// appending another compound word below. 1295if (sp -> ts_complen == sp -> ts_compsplit && fword_ends 1296&& (flags & WF_NEEDCOMP )) { 1297goodword_ends = false; 1298 }else { 1299goodword_ends = true; 1300 } 1301 1302char * p = NULL ; 1303bool compound_ok = true; 1304if (sp -> ts_complen > sp -> ts_compsplit ) { 1305if (slang -> sl_nobreak ) { 1306// There was a word before this word. When there was no 1307// change in this word (it was correct) add the first word 1308// as a suggestion. If this word was corrected too, we 1309// need to check if a correct word follows. 1310if (sp -> ts_fidx - sp -> ts_splitfidx 1311== sp -> ts_twordlen - sp -> ts_splitoff 1312&& strncmp (fword + sp -> ts_splitfidx , 1313tword + sp -> ts_splitoff , 1314 (size_t )(sp -> ts_fidx - sp -> ts_splitfidx ))== 0 ) { 1315preword [sp -> ts_prewordlen ]= NUL ; 1316int newscore = score_wordcount_adj (slang ,sp -> ts_score , 1317preword + sp -> ts_prewordlen , 1318sp -> ts_prewordlen > 0 ); 1319// Add the suggestion if the score isn't too bad. 1320if (newscore <=su -> su_maxscore ) { 1321add_suggestion (su ,& su -> su_ga ,preword , 1322sp -> ts_splitfidx - repextra , 1323newscore ,0 , false, 1324lp -> lp_sallang , false); 1325 } 1326break ; 1327 } 1328 }else { 1329// There was a compound word before this word. If this 1330// word does not support compounding then give up 1331// (splitting is tried for the word without compound 1332// flag). 1333if (((unsigned )flags >>24 )== 0 1334|| sp -> ts_twordlen - sp -> ts_splitoff 1335< slang -> sl_compminlen ) { 1336break ; 1337 } 1338// For multi-byte chars check character length against 1339// COMPOUNDMIN. 1340if (slang -> sl_compminlen > 0 1341&& mb_charlen (tword + sp -> ts_splitoff ) 1342< slang -> sl_compminlen ) { 1343break ; 1344 } 1345 1346compflags [sp -> ts_complen ]= (uint8_t )((unsigned )flags >>24 ); 1347compflags [sp -> ts_complen + 1 ]= NUL ; 1348xmemcpyz (preword + sp -> ts_prewordlen , 1349tword + sp -> ts_splitoff , 1350 (size_t )(sp -> ts_twordlen - sp -> ts_splitoff )); 1351 1352// Verify CHECKCOMPOUNDPATTERN rules. 1353if (match_checkcompoundpattern (preword ,sp -> ts_prewordlen , 1354& slang -> sl_comppat )) { 1355compound_ok = false; 1356 } 1357 1358if (compound_ok ) { 1359p = preword ; 1360while (* skiptowhite (p )!= NUL ) { 1361p = skipwhite (skiptowhite (p )); 1362 } 1363if (fword_ends && !can_compound (slang ,p ,compflags + sp -> ts_compsplit )) { 1364// Compound is not allowed. But it may still be 1365// possible if we add another (short) word. 1366compound_ok = false; 1367 } 1368 } 1369 1370// Get pointer to last char of previous word. 1371p = preword + sp -> ts_prewordlen ; 1372MB_PTR_BACK (preword ,p ); 1373 } 1374 } 1375 1376// Form the word with proper case in preword. 1377// If there is a word from a previous split, append. 1378// For the soundfold tree don't change the case, simply append. 1379if (soundfold ) { 1380STRCPY (preword + sp -> ts_prewordlen ,tword + sp -> ts_splitoff ); 1381 }else if (flags & WF_KEEPCAP ) { 1382// Must find the word in the keep-case tree. 1383find_keepcap_word (slang ,tword + sp -> ts_splitoff ,preword + sp -> ts_prewordlen ); 1384 }else { 1385// Include badflags: If the badword is onecap or allcap 1386// use that for the goodword too. But if the badword is 1387// allcap and it's only one char long use onecap. 1388c = su -> su_badflags ; 1389if ((c & WF_ALLCAP )&& su -> su_badlen == utfc_ptr2len (su -> su_badptr )) { 1390c = WF_ONECAP ; 1391 } 1392c |=flags ; 1393 1394// When appending a compound word after a word character don't 1395// use Onecap. 1396if (p != NULL && spell_iswordp_nmw (p ,curwin )) { 1397c &= ~WF_ONECAP ; 1398 } 1399make_case_word (tword + sp -> ts_splitoff , 1400preword + sp -> ts_prewordlen ,c ); 1401 } 1402 1403if (!soundfold ) { 1404// Don't use a banned word. It may appear again as a good 1405// word, thus remember it. 1406if (flags & WF_BANNED ) { 1407add_banned (su ,preword + sp -> ts_prewordlen ); 1408break ; 1409 } 1410if ((sp -> ts_complen == sp -> ts_compsplit 1411&& WAS_BANNED (su ,preword + sp -> ts_prewordlen )) 1412|| WAS_BANNED (su ,preword )) { 1413if (slang -> sl_compprog == NULL ) { 1414break ; 1415 } 1416// the word so far was banned but we may try compounding 1417goodword_ends = false; 1418 } 1419 } 1420 1421int newscore = 0 ; 1422if (!soundfold ) {// soundfold words don't have flags 1423if ((flags & WF_REGION ) 1424&& (((unsigned )flags >>16 )& (unsigned )lp -> lp_region )== 0 ) { 1425newscore += SCORE_REGION ; 1426 } 1427if (flags & WF_RARE ) { 1428newscore += SCORE_RARE ; 1429 } 1430 1431if (!spell_valid_case (su -> su_badflags , 1432captype (preword + sp -> ts_prewordlen ,NULL ))) { 1433newscore += SCORE_ICASE ; 1434 } 1435 } 1436 1437// TODO(vim): how about splitting in the soundfold tree? 1438if (fword_ends 1439&& goodword_ends 1440&& sp -> ts_fidx >=sp -> ts_fidxtry 1441&& compound_ok ) { 1442// The badword also ends: add suggestions. 1443#ifdef DEBUG_TRIEWALK 1444if (soundfold && strcmp (preword ,"smwrd" )== 0 ) { 1445int j ; 1446 1447// print the stack of changes that brought us here 1448smsg (0 ,"------ %s -------" ,fword ); 1449for (j = 0 ;j < depth ;j ++ ) { 1450smsg (0 ,"%s" ,changename [j ]); 1451 } 1452 } 1453#endif 1454if (soundfold ) { 1455// For soundfolded words we need to find the original 1456// words, the edit distance and then add them. 1457add_sound_suggest (su ,preword ,sp -> ts_score ,lp ); 1458 }else if (sp -> ts_fidx > 0 ) { 1459// Give a penalty when changing non-word char to word 1460// char, e.g., "thes," -> "these". 1461p = fword + sp -> ts_fidx ; 1462MB_PTR_BACK (fword ,p ); 1463if (!spell_iswordp (p ,curwin )&& * preword != NUL ) { 1464p = preword + strlen (preword ); 1465MB_PTR_BACK (preword ,p ); 1466if (spell_iswordp (p ,curwin )) { 1467newscore += SCORE_NONWORD ; 1468 } 1469 } 1470 1471// Give a bonus to words seen before. 1472int score = score_wordcount_adj (slang , 1473sp -> ts_score + newscore , 1474preword + sp -> ts_prewordlen , 1475sp -> ts_prewordlen > 0 ); 1476 1477// Add the suggestion if the score isn't too bad. 1478if (score <=su -> su_maxscore ) { 1479add_suggestion (su ,& su -> su_ga ,preword , 1480sp -> ts_fidx - repextra , 1481score ,0 , false,lp -> lp_sallang , false); 1482 1483if (su -> su_badflags & WF_MIXCAP ) { 1484// We really don't know if the word should be 1485// upper or lower case, add both. 1486c = captype (preword ,NULL ); 1487if (c == 0 || c == WF_ALLCAP ) { 1488make_case_word (tword + sp -> ts_splitoff , 1489preword + sp -> ts_prewordlen , 1490c == 0 ?WF_ALLCAP :0 ); 1491 1492add_suggestion (su ,& su -> su_ga ,preword , 1493sp -> ts_fidx - repextra , 1494score + SCORE_ICASE ,0 , false, 1495lp -> lp_sallang , false); 1496 } 1497 } 1498 } 1499 } 1500 } 1501 1502// Try word split and/or compounding. 1503if ((sp -> ts_fidx >=sp -> ts_fidxtry || fword_ends ) 1504// Don't split in the middle of a character 1505&& (sp -> ts_tcharlen == 0 )) { 1506bool try_compound ; 1507int try_split ; 1508 1509// If past the end of the bad word don't try a split. 1510// Otherwise try changing the next word. E.g., find 1511// suggestions for "the the" where the second "the" is 1512// different. It's done like a split. 1513// TODO(vim): word split for soundfold words 1514try_split = (sp -> ts_fidx - repextra < su -> su_badlen ) 1515&& !soundfold ; 1516 1517// Get here in several situations: 1518// 1. The word in the tree ends: 1519// If the word allows compounding try that. Otherwise try 1520// a split by inserting a space. For both check that a 1521// valid words starts at fword[sp->ts_fidx]. 1522// For NOBREAK do like compounding to be able to check if 1523// the next word is valid. 1524// 2. The badword does end, but it was due to a change (e.g., 1525// a swap). No need to split, but do check that the 1526// following word is valid. 1527// 3. The badword and the word in the tree end. It may still 1528// be possible to compound another (short) word. 1529try_compound = false; 1530if (!soundfold 1531&& !slang -> sl_nocompoundsugs 1532&& slang -> sl_compprog != NULL 1533&& ((unsigned )flags >>24 )!= 0 1534&& sp -> ts_twordlen - sp -> ts_splitoff 1535 >=slang -> sl_compminlen 1536&& (slang -> sl_compminlen == 0 1537|| mb_charlen (tword + sp -> ts_splitoff ) 1538 >=slang -> sl_compminlen ) 1539&& (slang -> sl_compsylmax < MAXWLEN 1540|| sp -> ts_complen + 1 - sp -> ts_compsplit 1541< slang -> sl_compmax ) 1542&& (can_be_compound (sp ,slang ,compflags , (int )((unsigned )flags >>24 )))) { 1543try_compound = true; 1544compflags [sp -> ts_complen ]= (uint8_t )((unsigned )flags >>24 ); 1545compflags [sp -> ts_complen + 1 ]= NUL ; 1546 } 1547 1548// For NOBREAK we never try splitting, it won't make any word 1549// valid. 1550if (slang -> sl_nobreak && !slang -> sl_nocompoundsugs ) { 1551try_compound = true; 1552 }else if (!fword_ends 1553&& try_compound 1554&& (sp -> ts_flags & TSF_DIDSPLIT )== 0 ) { 1555// If we could add a compound word, and it's also possible to 1556// split at this point, do the split first and set 1557// TSF_DIDSPLIT to avoid doing it again. 1558try_compound = false; 1559sp -> ts_flags |=TSF_DIDSPLIT ; 1560sp -> ts_curi -- ;// do the same NUL again 1561compflags [sp -> ts_complen ]= NUL ; 1562 }else { 1563sp -> ts_flags &= (uint8_t ) ~TSF_DIDSPLIT ; 1564 } 1565 1566if (try_split || try_compound ) { 1567if (!try_compound && (!fword_ends || !goodword_ends )) { 1568// If we're going to split need to check that the 1569// words so far are valid for compounding. If there 1570// is only one word it must not have the NEEDCOMPOUND 1571// flag. 1572if (sp -> ts_complen == sp -> ts_compsplit 1573&& (flags & WF_NEEDCOMP )) { 1574break ; 1575 } 1576p = preword ; 1577while (* skiptowhite (p )!= NUL ) { 1578p = skipwhite (skiptowhite (p )); 1579 } 1580if (sp -> ts_complen > sp -> ts_compsplit 1581&& !can_compound (slang ,p ,compflags + sp -> ts_compsplit )) { 1582break ; 1583 } 1584 1585if (slang -> sl_nosplitsugs ) { 1586newscore += SCORE_SPLIT_NO ; 1587 }else { 1588newscore += SCORE_SPLIT ; 1589 } 1590 1591// Give a bonus to words seen before. 1592newscore = score_wordcount_adj (slang ,newscore , 1593preword + sp -> ts_prewordlen , true); 1594 } 1595 1596if (TRY_DEEPER (su ,stack ,depth ,newscore )) { 1597go_deeper (stack ,depth ,newscore ); 1598#ifdef DEBUG_TRIEWALK 1599if (!try_compound && !fword_ends ) { 1600sprintf (changename [depth ],"%.*s-%s: split" ,// NOLINT(runtime/printf) 1601sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx ); 1602 }else { 1603sprintf (changename [depth ],"%.*s-%s: compound" ,// NOLINT(runtime/printf) 1604sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx ); 1605 } 1606#endif 1607// Save things to be restored at STATE_SPLITUNDO. 1608sp -> ts_save_badflags = (uint8_t )su -> su_badflags ; 1609PROF_STORE (sp -> ts_state ) 1610sp -> ts_state = STATE_SPLITUNDO ; 1611 1612depth ++ ; 1613sp = & stack [depth ]; 1614 1615// Append a space to preword when splitting. 1616if (!try_compound && !fword_ends ) { 1617strcat (preword ," " ); 1618 } 1619sp -> ts_prewordlen = (uint8_t )strlen (preword ); 1620sp -> ts_splitoff = sp -> ts_twordlen ; 1621sp -> ts_splitfidx = sp -> ts_fidx ; 1622 1623// If the badword has a non-word character at this 1624// position skip it. That means replacing the 1625// non-word character with a space. Always skip a 1626// character when the word ends. But only when the 1627// good word can end. 1628if (((!try_compound && !spell_iswordp_nmw (fword 1629+ sp -> ts_fidx , 1630curwin )) 1631|| fword_ends ) 1632&& fword [sp -> ts_fidx ]!= NUL 1633&& goodword_ends ) { 1634int l ; 1635 1636l = utfc_ptr2len (fword + sp -> ts_fidx ); 1637if (fword_ends ) { 1638// Copy the skipped character to preword. 1639memmove (preword + sp -> ts_prewordlen ,fword + sp -> ts_fidx , (size_t )l ); 1640sp -> ts_prewordlen = (uint8_t )(sp -> ts_prewordlen + l ); 1641preword [sp -> ts_prewordlen ]= NUL ; 1642 }else { 1643sp -> ts_score -= SCORE_SPLIT - SCORE_SUBST ; 1644 } 1645sp -> ts_fidx = (uint8_t )(sp -> ts_fidx + l ); 1646 } 1647 1648// When compounding include compound flag in 1649// compflags[] (already set above). When splitting we 1650// may start compounding over again. 1651if (try_compound ) { 1652sp -> ts_complen ++ ; 1653 }else { 1654sp -> ts_compsplit = sp -> ts_complen ; 1655 } 1656sp -> ts_prefixdepth = PFD_NOPREFIX ; 1657 1658// set su->su_badflags to the caps type at this 1659// position 1660n = nofold_len (fword ,sp -> ts_fidx ,su -> su_badptr ); 1661su -> su_badflags = badword_captype (su -> su_badptr + n , 1662su -> su_badptr + su -> su_badlen ); 1663 1664// Restart at top of the tree. 1665sp -> ts_arridx = 0 ; 1666 1667// If there are postponed prefixes, try these too. 1668if (pbyts != NULL ) { 1669byts = pbyts ; 1670idxs = pidxs ; 1671sp -> ts_prefixdepth = PFD_PREFIXTREE ; 1672PROF_STORE (sp -> ts_state ) 1673sp -> ts_state = STATE_NOPREFIX ; 1674 } 1675 } 1676 } 1677 } 1678break ; 1679 1680case STATE_SPLITUNDO : 1681// Undo the changes done for word split or compound word. 1682su -> su_badflags = sp -> ts_save_badflags ; 1683 1684// Continue looking for NUL bytes. 1685PROF_STORE (sp -> ts_state ) 1686sp -> ts_state = STATE_START ; 1687 1688// In case we went into the prefix tree. 1689byts = fbyts ; 1690idxs = fidxs ; 1691break ; 1692 1693case STATE_ENDNUL : 1694// Past the NUL bytes in the node. 1695su -> su_badflags = sp -> ts_save_badflags ; 1696if (fword [sp -> ts_fidx ]== NUL 1697&& sp -> ts_tcharlen == 0 ) { 1698// The badword ends, can't use STATE_PLAIN. 1699PROF_STORE (sp -> ts_state ) 1700sp -> ts_state = STATE_DEL ; 1701break ; 1702 } 1703PROF_STORE (sp -> ts_state ) 1704sp -> ts_state = STATE_PLAIN ; 1705FALLTHROUGH ; 1706 1707case STATE_PLAIN : 1708// Go over all possible bytes at this node, add each to tword[] 1709// and use child node. "ts_curi" is the index. 1710arridx = sp -> ts_arridx ; 1711if (sp -> ts_curi > byts [arridx ]) { 1712// Done all bytes at this node, do next state. When still at 1713// already changed bytes skip the other tricks. 1714PROF_STORE (sp -> ts_state ) 1715sp -> ts_state = sp -> ts_fidx >=sp -> ts_fidxtry ?STATE_DEL 1716 :STATE_FINAL ; 1717 }else { 1718arridx += sp -> ts_curi ++ ; 1719c = byts [arridx ]; 1720 1721// Normal byte, go one level deeper. If it's not equal to the 1722// byte in the bad word adjust the score. But don't even try 1723// when the byte was already changed. And don't try when we 1724// just deleted this byte, accepting it is always cheaper than 1725// delete + substitute. 1726if (c == (uint8_t )fword [sp -> ts_fidx ] 1727|| (sp -> ts_tcharlen > 0 1728&& sp -> ts_isdiff != DIFF_NONE )) { 1729newscore = 0 ; 1730 }else { 1731newscore = SCORE_SUBST ; 1732 } 1733if ((newscore == 0 1734|| (sp -> ts_fidx >=sp -> ts_fidxtry 1735&& ((sp -> ts_flags & TSF_DIDDEL )== 0 1736|| c != (uint8_t )fword [sp -> ts_delidx ]))) 1737&& TRY_DEEPER (su ,stack ,depth ,newscore )) { 1738go_deeper (stack ,depth ,newscore ); 1739#ifdef DEBUG_TRIEWALK 1740if (newscore > 0 ) { 1741sprintf (changename [depth ],"%.*s-%s: subst %c to %c" ,// NOLINT(runtime/printf) 1742sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 1743fword [sp -> ts_fidx ],c ); 1744 }else { 1745sprintf (changename [depth ],"%.*s-%s: accept %c" ,// NOLINT(runtime/printf) 1746sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 1747fword [sp -> ts_fidx ]); 1748 } 1749#endif 1750depth ++ ; 1751sp = & stack [depth ]; 1752if (fword [sp -> ts_fidx ]!= NUL ) { 1753sp -> ts_fidx ++ ; 1754 } 1755tword [sp -> ts_twordlen ++ ]= (char )c ; 1756sp -> ts_arridx = idxs [arridx ]; 1757if (newscore == SCORE_SUBST ) { 1758sp -> ts_isdiff = DIFF_YES ; 1759 } 1760// Multi-byte characters are a bit complicated to 1761// handle: They differ when any of the bytes differ 1762// and then their length may also differ. 1763if (sp -> ts_tcharlen == 0 ) { 1764// First byte. 1765sp -> ts_tcharidx = 0 ; 1766sp -> ts_tcharlen = MB_BYTE2LEN (c ); 1767sp -> ts_fcharstart = (uint8_t )(sp -> ts_fidx - 1 ); 1768sp -> ts_isdiff = (newscore != 0 ) 1769 ?DIFF_YES :DIFF_NONE ; 1770 }else if (sp -> ts_isdiff == DIFF_INSERT && sp -> ts_fidx > 0 ) { 1771// When inserting trail bytes don't advance in the 1772// bad word. 1773sp -> ts_fidx -- ; 1774 } 1775if (++ sp -> ts_tcharidx == sp -> ts_tcharlen ) { 1776// Last byte of character. 1777if (sp -> ts_isdiff == DIFF_YES ) { 1778// Correct ts_fidx for the byte length of the 1779// character (we didn't check that before). 1780sp -> ts_fidx = (uint8_t )(sp -> ts_fcharstart 1781+ utfc_ptr2len (fword + sp -> ts_fcharstart )); 1782 1783// For changing a composing character adjust 1784// the score from SCORE_SUBST to 1785// SCORE_SUBCOMP. 1786if (utf_iscomposing_legacy (utf_ptr2char (tword + sp -> ts_twordlen - sp -> ts_tcharlen )) 1787&& utf_iscomposing_legacy (utf_ptr2char (fword + sp -> ts_fcharstart ))) { 1788sp -> ts_score -= SCORE_SUBST - SCORE_SUBCOMP ; 1789 }else if (!soundfold 1790&& slang -> sl_has_map 1791&& similar_chars (slang , 1792utf_ptr2char (tword + sp -> ts_twordlen - 1793sp -> ts_tcharlen ), 1794utf_ptr2char (fword + sp -> ts_fcharstart ))) { 1795// For a similar character adjust score from 1796// SCORE_SUBST to SCORE_SIMILAR. 1797sp -> ts_score -= SCORE_SUBST - SCORE_SIMILAR ; 1798 } 1799 }else if (sp -> ts_isdiff == DIFF_INSERT 1800&& sp -> ts_twordlen > sp -> ts_tcharlen ) { 1801p = tword + sp -> ts_twordlen - sp -> ts_tcharlen ; 1802c = utf_ptr2char (p ); 1803if (utf_iscomposing_legacy (c )) { 1804// Inserting a composing char doesn't 1805// count that much. 1806sp -> ts_score -= SCORE_INS - SCORE_INSCOMP ; 1807 }else { 1808// If the previous character was the same, 1809// thus doubling a character, give a bonus 1810// to the score. Also for the soundfold 1811// tree (might seem illogical but does 1812// give better scores). 1813MB_PTR_BACK (tword ,p ); 1814if (c == utf_ptr2char (p )) { 1815sp -> ts_score -= SCORE_INS - SCORE_INSDUP ; 1816 } 1817 } 1818 } 1819 1820// Starting a new char, reset the length. 1821sp -> ts_tcharlen = 0 ; 1822 } 1823 } 1824 } 1825break ; 1826 1827case STATE_DEL : 1828// When past the first byte of a multi-byte char don't try 1829// delete/insert/swap a character. 1830if (sp -> ts_tcharlen > 0 ) { 1831PROF_STORE (sp -> ts_state ) 1832sp -> ts_state = STATE_FINAL ; 1833break ; 1834 } 1835// Try skipping one character in the bad word (delete it). 1836PROF_STORE (sp -> ts_state ) 1837sp -> ts_state = STATE_INS_PREP ; 1838sp -> ts_curi = 1 ; 1839if (soundfold && sp -> ts_fidx == 0 && fword [sp -> ts_fidx ]== '*' ) { 1840// Deleting a vowel at the start of a word counts less, see 1841// soundalike_score(). 1842newscore = 2 * SCORE_DEL /3 ; 1843 }else { 1844newscore = SCORE_DEL ; 1845 } 1846if (fword [sp -> ts_fidx ]!= NUL 1847&& TRY_DEEPER (su ,stack ,depth ,newscore )) { 1848go_deeper (stack ,depth ,newscore ); 1849#ifdef DEBUG_TRIEWALK 1850sprintf (changename [depth ],"%.*s-%s: delete %c" ,// NOLINT(runtime/printf) 1851sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 1852fword [sp -> ts_fidx ]); 1853#endif 1854depth ++ ; 1855 1856// Remember what character we deleted, so that we can avoid 1857// inserting it again. 1858stack [depth ].ts_flags |=TSF_DIDDEL ; 1859stack [depth ].ts_delidx = sp -> ts_fidx ; 1860 1861// Advance over the character in fword[]. Give a bonus to the 1862// score if the same character is following "nn" -> "n". It's 1863// a bit illogical for soundfold tree but it does give better 1864// results. 1865c = utf_ptr2char (fword + sp -> ts_fidx ); 1866stack [depth ].ts_fidx = 1867 (uint8_t )(stack [depth ].ts_fidx + utfc_ptr2len (fword + sp -> ts_fidx )); 1868if (utf_iscomposing_legacy (c )) { 1869stack [depth ].ts_score -= SCORE_DEL - SCORE_DELCOMP ; 1870 }else if (c == utf_ptr2char (fword + stack [depth ].ts_fidx )) { 1871stack [depth ].ts_score -= SCORE_DEL - SCORE_DELDUP ; 1872 } 1873 1874break ; 1875 } 1876FALLTHROUGH ; 1877 1878case STATE_INS_PREP : 1879if (sp -> ts_flags & TSF_DIDDEL ) { 1880// If we just deleted a byte then inserting won't make sense, 1881// a substitute is always cheaper. 1882PROF_STORE (sp -> ts_state ) 1883sp -> ts_state = STATE_SWAP ; 1884break ; 1885 } 1886 1887// skip over NUL bytes 1888n = sp -> ts_arridx ; 1889while (true) { 1890if (sp -> ts_curi > byts [n ]) { 1891// Only NUL bytes at this node, go to next state. 1892PROF_STORE (sp -> ts_state ) 1893sp -> ts_state = STATE_SWAP ; 1894break ; 1895 } 1896if (byts [n + sp -> ts_curi ]!= NUL ) { 1897// Found a byte to insert. 1898PROF_STORE (sp -> ts_state ) 1899sp -> ts_state = STATE_INS ; 1900break ; 1901 } 1902sp -> ts_curi ++ ; 1903 } 1904break ; 1905 1906case STATE_INS : 1907// Insert one byte. Repeat this for each possible byte at this 1908// node. 1909n = sp -> ts_arridx ; 1910if (sp -> ts_curi > byts [n ]) { 1911// Done all bytes at this node, go to next state. 1912PROF_STORE (sp -> ts_state ) 1913sp -> ts_state = STATE_SWAP ; 1914break ; 1915 } 1916 1917// Do one more byte at this node, but: 1918// - Skip NUL bytes. 1919// - Skip the byte if it's equal to the byte in the word, 1920// accepting that byte is always better. 1921n += sp -> ts_curi ++ ; 1922 1923// break out, if we would be accessing byts buffer out of bounds 1924if (byts == slang -> sl_fbyts && n >=slang -> sl_fbyts_len ) { 1925got_int = true; 1926break ; 1927 } 1928c = byts [n ]; 1929if (soundfold && sp -> ts_twordlen == 0 && c == '*' ) { 1930// Inserting a vowel at the start of a word counts less, 1931// see soundalike_score(). 1932newscore = 2 * SCORE_INS /3 ; 1933 }else { 1934newscore = SCORE_INS ; 1935 } 1936if (c != (uint8_t )fword [sp -> ts_fidx ] 1937&& TRY_DEEPER (su ,stack ,depth ,newscore )) { 1938go_deeper (stack ,depth ,newscore ); 1939#ifdef DEBUG_TRIEWALK 1940sprintf (changename [depth ],"%.*s-%s: insert %c" ,// NOLINT(runtime/printf) 1941sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 1942c ); 1943#endif 1944depth ++ ; 1945sp = & stack [depth ]; 1946tword [sp -> ts_twordlen ++ ]= (char )c ; 1947sp -> ts_arridx = idxs [n ]; 1948fl = MB_BYTE2LEN (c ); 1949if (fl > 1 ) { 1950// There are following bytes for the same character. 1951// We must find all bytes before trying 1952// delete/insert/swap/etc. 1953sp -> ts_tcharlen = (uint8_t )fl ; 1954sp -> ts_tcharidx = 1 ; 1955sp -> ts_isdiff = DIFF_INSERT ; 1956 } 1957if (fl == 1 ) { 1958// If the previous character was the same, thus doubling a 1959// character, give a bonus to the score. Also for 1960// soundfold words (illogical but does give a better 1961// score). 1962if (sp -> ts_twordlen >=2 1963&& (uint8_t )tword [sp -> ts_twordlen - 2 ]== c ) { 1964sp -> ts_score -= SCORE_INS - SCORE_INSDUP ; 1965 } 1966 } 1967 } 1968break ; 1969 1970case STATE_SWAP : 1971// Swap two bytes in the bad word: "12" -> "21". 1972// We change "fword" here, it's changed back afterwards at 1973// STATE_UNSWAP. 1974p = fword + sp -> ts_fidx ; 1975c = (uint8_t )(* p ); 1976if (c == NUL ) { 1977// End of word, can't swap or replace. 1978PROF_STORE (sp -> ts_state ) 1979sp -> ts_state = STATE_FINAL ; 1980break ; 1981 } 1982 1983// Don't swap if the first character is not a word character. 1984// SWAP3 etc. also don't make sense then. 1985if (!soundfold && !spell_iswordp (p ,curwin )) { 1986PROF_STORE (sp -> ts_state ) 1987sp -> ts_state = STATE_REP_INI ; 1988break ; 1989 } 1990 1991n = utf_ptr2len (p ); 1992c = utf_ptr2char (p ); 1993if (p [n ]== NUL ) { 1994c2 = NUL ; 1995 }else if (!soundfold && !spell_iswordp (p + n ,curwin )) { 1996c2 = c ;// don't swap non-word char 1997 }else { 1998c2 = utf_ptr2char (p + n ); 1999 } 2000 2001// When the second character is NUL we can't swap. 2002if (c2 == NUL ) { 2003PROF_STORE (sp -> ts_state ) 2004sp -> ts_state = STATE_REP_INI ; 2005break ; 2006 } 2007 2008// When characters are identical, swap won't do anything. 2009// Also get here if the second char is not a word character. 2010if (c == c2 ) { 2011PROF_STORE (sp -> ts_state ) 2012sp -> ts_state = STATE_SWAP3 ; 2013break ; 2014 } 2015if (TRY_DEEPER (su ,stack ,depth ,SCORE_SWAP )) { 2016go_deeper (stack ,depth ,SCORE_SWAP ); 2017#ifdef DEBUG_TRIEWALK 2018snprintf (changename [depth ],sizeof (changename [0 ]), 2019"%.*s-%s: swap %c and %c" , 2020sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 2021c ,c2 ); 2022#endif 2023PROF_STORE (sp -> ts_state ) 2024sp -> ts_state = STATE_UNSWAP ; 2025depth ++ ; 2026fl = utf_char2len (c2 ); 2027memmove (p ,p + n , (size_t )fl ); 2028utf_char2bytes (c ,p + fl ); 2029stack [depth ].ts_fidxtry = (uint8_t )(sp -> ts_fidx + n + fl ); 2030 }else { 2031// If this swap doesn't work then SWAP3 won't either. 2032PROF_STORE (sp -> ts_state ) 2033sp -> ts_state = STATE_REP_INI ; 2034 } 2035break ; 2036 2037case STATE_UNSWAP : 2038// Undo the STATE_SWAP swap: "21" -> "12". 2039p = fword + sp -> ts_fidx ; 2040n = utfc_ptr2len (p ); 2041c = utf_ptr2char (p + n ); 2042memmove (p + utfc_ptr2len (p + n ),p , (size_t )n ); 2043utf_char2bytes (c ,p ); 2044 2045FALLTHROUGH ; 2046 2047case STATE_SWAP3 : 2048// Swap two bytes, skipping one: "123" -> "321". We change 2049// "fword" here, it's changed back afterwards at STATE_UNSWAP3. 2050p = fword + sp -> ts_fidx ; 2051n = utf_ptr2len (p ); 2052c = utf_ptr2char (p ); 2053fl = utf_ptr2len (p + n ); 2054c2 = utf_ptr2char (p + n ); 2055if (!soundfold && !spell_iswordp (p + n + fl ,curwin )) { 2056c3 = c ;// don't swap non-word char 2057 }else { 2058c3 = utf_ptr2char (p + n + fl ); 2059 } 2060 2061// When characters are identical: "121" then SWAP3 result is 2062// identical, ROT3L result is same as SWAP: "211", ROT3L result is 2063// same as SWAP on next char: "112". Thus skip all swapping. 2064// Also skip when c3 is NUL. 2065// Also get here when the third character is not a word character. 2066// Second character may any char: "a.b" -> "b.a" 2067if (c == c3 || c3 == NUL ) { 2068PROF_STORE (sp -> ts_state ) 2069sp -> ts_state = STATE_REP_INI ; 2070break ; 2071 } 2072if (TRY_DEEPER (su ,stack ,depth ,SCORE_SWAP3 )) { 2073go_deeper (stack ,depth ,SCORE_SWAP3 ); 2074#ifdef DEBUG_TRIEWALK 2075sprintf (changename [depth ],"%.*s-%s: swap3 %c and %c" ,// NOLINT(runtime/printf) 2076sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 2077c ,c3 ); 2078#endif 2079PROF_STORE (sp -> ts_state ) 2080sp -> ts_state = STATE_UNSWAP3 ; 2081depth ++ ; 2082tl = utf_char2len (c3 ); 2083memmove (p ,p + n + fl , (size_t )tl ); 2084utf_char2bytes (c2 ,p + tl ); 2085utf_char2bytes (c ,p + fl + tl ); 2086stack [depth ].ts_fidxtry = (uint8_t )(sp -> ts_fidx + n + fl + tl ); 2087 }else { 2088PROF_STORE (sp -> ts_state ) 2089sp -> ts_state = STATE_REP_INI ; 2090 } 2091break ; 2092 2093case STATE_UNSWAP3 : 2094// Undo STATE_SWAP3: "321" -> "123" 2095p = fword + sp -> ts_fidx ; 2096n = utfc_ptr2len (p ); 2097c2 = utf_ptr2char (p + n ); 2098fl = utfc_ptr2len (p + n ); 2099c = utf_ptr2char (p + n + fl ); 2100tl = utfc_ptr2len (p + n + fl ); 2101memmove (p + fl + tl ,p , (size_t )n ); 2102utf_char2bytes (c ,p ); 2103utf_char2bytes (c2 ,p + tl ); 2104p = p + tl ; 2105 2106if (!soundfold && !spell_iswordp (p ,curwin )) { 2107// Middle char is not a word char, skip the rotate. First and 2108// third char were already checked at swap and swap3. 2109PROF_STORE (sp -> ts_state ) 2110sp -> ts_state = STATE_REP_INI ; 2111break ; 2112 } 2113 2114// Rotate three characters left: "123" -> "231". We change 2115// "fword" here, it's changed back afterwards at STATE_UNROT3L. 2116if (TRY_DEEPER (su ,stack ,depth ,SCORE_SWAP3 )) { 2117go_deeper (stack ,depth ,SCORE_SWAP3 ); 2118#ifdef DEBUG_TRIEWALK 2119p = fword + sp -> ts_fidx ; 2120sprintf (changename [depth ],"%.*s-%s: rotate left %c%c%c" ,// NOLINT(runtime/printf) 2121sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 2122p [0 ],p [1 ],p [2 ]); 2123#endif 2124PROF_STORE (sp -> ts_state ) 2125sp -> ts_state = STATE_UNROT3L ; 2126depth ++ ; 2127p = fword + sp -> ts_fidx ; 2128n = utf_ptr2len (p ); 2129c = utf_ptr2char (p ); 2130fl = utf_ptr2len (p + n ); 2131fl += utf_ptr2len (p + n + fl ); 2132memmove (p ,p + n , (size_t )fl ); 2133utf_char2bytes (c ,p + fl ); 2134stack [depth ].ts_fidxtry = (uint8_t )(sp -> ts_fidx + n + fl ); 2135 }else { 2136PROF_STORE (sp -> ts_state ) 2137sp -> ts_state = STATE_REP_INI ; 2138 } 2139break ; 2140 2141case STATE_UNROT3L : 2142// Undo ROT3L: "231" -> "123" 2143p = fword + sp -> ts_fidx ; 2144n = utfc_ptr2len (p ); 2145n += utfc_ptr2len (p + n ); 2146c = utf_ptr2char (p + n ); 2147tl = utfc_ptr2len (p + n ); 2148memmove (p + tl ,p , (size_t )n ); 2149utf_char2bytes (c ,p ); 2150 2151// Rotate three bytes right: "123" -> "312". We change "fword" 2152// here, it's changed back afterwards at STATE_UNROT3R. 2153if (TRY_DEEPER (su ,stack ,depth ,SCORE_SWAP3 )) { 2154go_deeper (stack ,depth ,SCORE_SWAP3 ); 2155#ifdef DEBUG_TRIEWALK 2156p = fword + sp -> ts_fidx ; 2157sprintf (changename [depth ],"%.*s-%s: rotate right %c%c%c" ,// NOLINT(runtime/printf) 2158sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 2159p [0 ],p [1 ],p [2 ]); 2160#endif 2161PROF_STORE (sp -> ts_state ) 2162sp -> ts_state = STATE_UNROT3R ; 2163depth ++ ; 2164p = fword + sp -> ts_fidx ; 2165n = utf_ptr2len (p ); 2166n += utf_ptr2len (p + n ); 2167c = utf_ptr2char (p + n ); 2168tl = utf_ptr2len (p + n ); 2169memmove (p + tl ,p , (size_t )n ); 2170utf_char2bytes (c ,p ); 2171stack [depth ].ts_fidxtry = (uint8_t )(sp -> ts_fidx + n + tl ); 2172 }else { 2173PROF_STORE (sp -> ts_state ) 2174sp -> ts_state = STATE_REP_INI ; 2175 } 2176break ; 2177 2178case STATE_UNROT3R : 2179// Undo ROT3R: "312" -> "123" 2180p = fword + sp -> ts_fidx ; 2181c = utf_ptr2char (p ); 2182tl = utfc_ptr2len (p ); 2183n = utfc_ptr2len (p + tl ); 2184n += utfc_ptr2len (p + tl + n ); 2185memmove (p ,p + tl , (size_t )n ); 2186utf_char2bytes (c ,p + n ); 2187 2188FALLTHROUGH ; 2189 2190case STATE_REP_INI : 2191// Check if matching with REP items from the .aff file would work. 2192// Quickly skip if: 2193// - there are no REP items and we are not in the soundfold trie 2194// - the score is going to be too high anyway 2195// - already applied a REP item or swapped here 2196if ((lp -> lp_replang == NULL && !soundfold ) 2197|| sp -> ts_score + SCORE_REP >=su -> su_maxscore 2198|| sp -> ts_fidx < sp -> ts_fidxtry ) { 2199PROF_STORE (sp -> ts_state ) 2200sp -> ts_state = STATE_FINAL ; 2201break ; 2202 } 2203 2204// Use the first byte to quickly find the first entry that may 2205// match. If the index is -1 there is none. 2206if (soundfold ) { 2207sp -> ts_curi = slang -> sl_repsal_first [(uint8_t )fword [sp -> ts_fidx ]]; 2208 }else { 2209sp -> ts_curi = lp -> lp_replang -> sl_rep_first [(uint8_t )fword [sp -> ts_fidx ]]; 2210 } 2211 2212if (sp -> ts_curi < 0 ) { 2213PROF_STORE (sp -> ts_state ) 2214sp -> ts_state = STATE_FINAL ; 2215break ; 2216 } 2217 2218PROF_STORE (sp -> ts_state ) 2219sp -> ts_state = STATE_REP ; 2220FALLTHROUGH ; 2221 2222case STATE_REP : 2223// Try matching with REP items from the .aff file. For each match 2224// replace the characters and check if the resulting word is 2225// valid. 2226p = fword + sp -> ts_fidx ; 2227 2228garray_T * gap = soundfold ?& slang -> sl_repsal 2229 :& lp -> lp_replang -> sl_rep ; 2230while (sp -> ts_curi < gap -> ga_len ) { 2231fromto_T * ftp = (fromto_T * )gap -> ga_data + sp -> ts_curi ++ ; 2232if (* ftp -> ft_from != * p ) { 2233// past possible matching entries 2234sp -> ts_curi = (int16_t )gap -> ga_len ; 2235break ; 2236 } 2237if (strncmp (ftp -> ft_from ,p ,strlen (ftp -> ft_from ))== 0 2238&& TRY_DEEPER (su ,stack ,depth ,SCORE_REP )) { 2239go_deeper (stack ,depth ,SCORE_REP ); 2240#ifdef DEBUG_TRIEWALK 2241sprintf (changename [depth ],"%.*s-%s: replace %s with %s" ,// NOLINT(runtime/printf) 2242sp -> ts_twordlen ,tword ,fword + sp -> ts_fidx , 2243ftp -> ft_from ,ftp -> ft_to ); 2244#endif 2245// Need to undo this afterwards. 2246PROF_STORE (sp -> ts_state ) 2247sp -> ts_state = STATE_REP_UNDO ; 2248 2249// Change the "from" to the "to" string. 2250depth ++ ; 2251fl = (int )strlen (ftp -> ft_from ); 2252tl = (int )strlen (ftp -> ft_to ); 2253if (fl != tl ) { 2254STRMOVE (p + tl ,p + fl ); 2255repextra += tl - fl ; 2256 } 2257memmove (p ,ftp -> ft_to , (size_t )tl ); 2258stack [depth ].ts_fidxtry = (uint8_t )(sp -> ts_fidx + tl ); 2259stack [depth ].ts_tcharlen = 0 ; 2260break ; 2261 } 2262 } 2263 2264if (sp -> ts_curi >=gap -> ga_len && sp -> ts_state == STATE_REP ) { 2265// No (more) matches. 2266PROF_STORE (sp -> ts_state ) 2267sp -> ts_state = STATE_FINAL ; 2268 } 2269 2270break ; 2271 2272case STATE_REP_UNDO : 2273// Undo a REP replacement and continue with the next one. 2274if (soundfold ) { 2275gap = & slang -> sl_repsal ; 2276 }else { 2277gap = & lp -> lp_replang -> sl_rep ; 2278 } 2279fromto_T * ftp = (fromto_T * )gap -> ga_data + sp -> ts_curi - 1 ; 2280fl = (int )strlen (ftp -> ft_from ); 2281tl = (int )strlen (ftp -> ft_to ); 2282p = fword + sp -> ts_fidx ; 2283if (fl != tl ) { 2284STRMOVE (p + fl ,p + tl ); 2285repextra -= tl - fl ; 2286 } 2287memmove (p ,ftp -> ft_from , (size_t )fl ); 2288PROF_STORE (sp -> ts_state ) 2289sp -> ts_state = STATE_REP ; 2290break ; 2291 2292default : 2293// Did all possible states at this level, go up one level. 2294depth -- ; 2295 2296if (depth >=0 && stack [depth ].ts_prefixdepth == PFD_PREFIXTREE ) { 2297// Continue in or go back to the prefix tree. 2298byts = pbyts ; 2299idxs = pidxs ; 2300 } 2301 2302// Don't check for CTRL-C too often, it takes time. 2303if (-- breakcheckcount == 0 ) { 2304os_breakcheck (); 2305breakcheckcount = 1000 ; 2306if (spell_suggest_timeout > 0 && profile_passed_limit (time_limit )) { 2307got_int = true; 2308 } 2309 } 2310 } 2311 } 2312} 2313 2314/// Go one level deeper in the tree. 2315static void go_deeper (trystate_T * stack ,int depth ,int score_add ) 2316{ 2317stack [depth + 1 ]= stack [depth ]; 2318stack [depth + 1 ].ts_state = STATE_START ; 2319stack [depth + 1 ].ts_score = stack [depth ].ts_score + score_add ; 2320stack [depth + 1 ].ts_curi = 1 ;// start just after length byte 2321stack [depth + 1 ].ts_flags = 0 ; 2322} 2323 2324/// "fword" is a good word with case folded. Find the matching keep-case 2325/// words and put it in "kword". 2326/// Theoretically there could be several keep-case words that result in the 2327/// same case-folded word, but we only find one... 2328static void find_keepcap_word (slang_T * slang ,char * fword ,char * kword ) 2329{ 2330char uword [MAXWLEN ];// "fword" in upper-case 2331idx_T tryidx ; 2332 2333// The following arrays are used at each depth in the tree. 2334idx_T arridx [MAXWLEN ]; 2335int round [MAXWLEN ]; 2336int fwordidx [MAXWLEN ]; 2337int uwordidx [MAXWLEN ]; 2338int kwordlen [MAXWLEN ]; 2339 2340int l ; 2341char * p ; 2342uint8_t * byts = slang -> sl_kbyts ;// array with bytes of the words 2343idx_T * idxs = slang -> sl_kidxs ;// array with indexes 2344 2345if (byts == NULL ) { 2346// array is empty: "cannot happen" 2347* kword = NUL ; 2348return ; 2349 } 2350 2351// Make an all-cap version of "fword". 2352allcap_copy (fword ,uword ); 2353 2354// Each character needs to be tried both case-folded and upper-case. 2355// All this gets very complicated if we keep in mind that changing case 2356// may change the byte length of a multi-byte character... 2357int depth = 0 ; 2358arridx [0 ]= 0 ; 2359round [0 ]= 0 ; 2360fwordidx [0 ]= 0 ; 2361uwordidx [0 ]= 0 ; 2362kwordlen [0 ]= 0 ; 2363while (depth >=0 ) { 2364if (fword [fwordidx [depth ]]== NUL ) { 2365// We are at the end of "fword". If the tree allows a word to end 2366// here we have found a match. 2367if (byts [arridx [depth ]+ 1 ]== 0 ) { 2368kword [kwordlen [depth ]]= NUL ; 2369return ; 2370 } 2371 2372// kword is getting too long, continue one level up 2373depth -- ; 2374 }else if (++ round [depth ]> 2 ) { 2375// tried both fold-case and upper-case character, continue one 2376// level up 2377depth -- ; 2378 }else { 2379// round[depth] == 1: Try using the folded-case character. 2380// round[depth] == 2: Try using the upper-case character. 2381int flen = utf_ptr2len (fword + fwordidx [depth ]); 2382int ulen = utf_ptr2len (uword + uwordidx [depth ]); 2383if (round [depth ]== 1 ) { 2384p = fword + fwordidx [depth ]; 2385l = flen ; 2386 }else { 2387p = uword + uwordidx [depth ]; 2388l = ulen ; 2389 } 2390 2391for (tryidx = arridx [depth ];l > 0 ;l -- ) { 2392// Perform a binary search in the list of accepted bytes. 2393int len = byts [tryidx ++ ]; 2394int c = (uint8_t )(* p ++ ); 2395idx_T lo = tryidx ; 2396idx_T hi = tryidx + len - 1 ; 2397while (lo < hi ) { 2398idx_T m = (lo + hi ) /2 ; 2399if (byts [m ]> c ) { 2400hi = m - 1 ; 2401 }else if (byts [m ]< c ) { 2402lo = m + 1 ; 2403 }else { 2404lo = hi = m ; 2405break ; 2406 } 2407 } 2408 2409// Stop if there is no matching byte. 2410if (hi < lo || byts [lo ]!= c ) { 2411break ; 2412 } 2413 2414// Continue at the child (if there is one). 2415tryidx = idxs [lo ]; 2416 } 2417 2418if (l == 0 ) { 2419// Found the matching char. Copy it to "kword" and go a 2420// level deeper. 2421if (round [depth ]== 1 ) { 2422strncpy (kword + kwordlen [depth ],// NOLINT(runtime/printf) 2423fword + fwordidx [depth ], 2424 (size_t )flen ); 2425kwordlen [depth + 1 ]= kwordlen [depth ]+ flen ; 2426 }else { 2427strncpy (kword + kwordlen [depth ],// NOLINT(runtime/printf) 2428uword + uwordidx [depth ], 2429 (size_t )ulen ); 2430kwordlen [depth + 1 ]= kwordlen [depth ]+ ulen ; 2431 } 2432fwordidx [depth + 1 ]= fwordidx [depth ]+ flen ; 2433uwordidx [depth + 1 ]= uwordidx [depth ]+ ulen ; 2434 2435depth ++ ; 2436arridx [depth ]= tryidx ; 2437round [depth ]= 0 ; 2438 } 2439 } 2440 } 2441 2442// Didn't find it: "cannot happen". 2443* kword = NUL ; 2444} 2445 2446/// Compute the sound-a-like score for suggestions in su->su_ga and add them to 2447/// su->su_sga. 2448static void score_comp_sal (suginfo_T * su ) 2449{ 2450char badsound [MAXWLEN ]; 2451 2452ga_grow (& su -> su_sga ,su -> su_ga .ga_len ); 2453 2454// Use the sound-folding of the first language that supports it. 2455for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 2456langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 2457if (!GA_EMPTY (& lp -> lp_slang -> sl_sal )) { 2458// soundfold the bad word 2459spell_soundfold (lp -> lp_slang ,su -> su_fbadword , true,badsound ); 2460 2461for (int i = 0 ;i < su -> su_ga .ga_len ;i ++ ) { 2462suggest_T * stp = & SUG (su -> su_ga ,i ); 2463 2464// Case-fold the suggested word, sound-fold it and compute the 2465// sound-a-like score. 2466int score = stp_sal_score (stp ,su ,lp -> lp_slang ,badsound ); 2467if (score < SCORE_MAXMAX ) { 2468// Add the suggestion. 2469suggest_T * sstp = & SUG (su -> su_sga ,su -> su_sga .ga_len ); 2470sstp -> st_word = xstrdup (stp -> st_word ); 2471sstp -> st_wordlen = stp -> st_wordlen ; 2472sstp -> st_score = score ; 2473sstp -> st_altscore = 0 ; 2474sstp -> st_orglen = stp -> st_orglen ; 2475su -> su_sga .ga_len ++ ; 2476 } 2477 } 2478break ; 2479 } 2480 } 2481} 2482 2483/// Combine the list of suggestions in su->su_ga and su->su_sga. 2484/// They are entwined. 2485static void score_combine (suginfo_T * su ) 2486{ 2487garray_T ga ; 2488char * p ; 2489char badsound [MAXWLEN ]; 2490slang_T * slang = NULL ; 2491 2492// Add the alternate score to su_ga. 2493for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 2494langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 2495if (!GA_EMPTY (& lp -> lp_slang -> sl_sal )) { 2496// soundfold the bad word 2497slang = lp -> lp_slang ; 2498spell_soundfold (slang ,su -> su_fbadword , true,badsound ); 2499 2500for (int i = 0 ;i < su -> su_ga .ga_len ;i ++ ) { 2501suggest_T * stp = & SUG (su -> su_ga ,i ); 2502stp -> st_altscore = stp_sal_score (stp ,su ,slang ,badsound ); 2503if (stp -> st_altscore == SCORE_MAXMAX ) { 2504stp -> st_score = (stp -> st_score * 3 + SCORE_BIG ) /4 ; 2505 }else { 2506stp -> st_score = (stp -> st_score * 3 + stp -> st_altscore ) /4 ; 2507 } 2508stp -> st_salscore = false; 2509 } 2510break ; 2511 } 2512 } 2513 2514if (slang == NULL ) {// Using "double" without sound folding. 2515cleanup_suggestions (& su -> su_ga ,su -> su_maxscore , 2516su -> su_maxcount ); 2517return ; 2518 } 2519 2520// Add the alternate score to su_sga. 2521for (int i = 0 ;i < su -> su_sga .ga_len ;i ++ ) { 2522suggest_T * stp = & SUG (su -> su_sga ,i ); 2523stp -> st_altscore = spell_edit_score (slang ,su -> su_badword ,stp -> st_word ); 2524if (stp -> st_score == SCORE_MAXMAX ) { 2525stp -> st_score = (SCORE_BIG * 7 + stp -> st_altscore ) /8 ; 2526 }else { 2527stp -> st_score = (stp -> st_score * 7 + stp -> st_altscore ) /8 ; 2528 } 2529stp -> st_salscore = true; 2530 } 2531 2532// Remove bad suggestions, sort the suggestions and truncate at "maxcount" 2533// for both lists. 2534check_suggestions (su ,& su -> su_ga ); 2535cleanup_suggestions (& su -> su_ga ,su -> su_maxscore ,su -> su_maxcount ); 2536check_suggestions (su ,& su -> su_sga ); 2537cleanup_suggestions (& su -> su_sga ,su -> su_maxscore ,su -> su_maxcount ); 2538 2539ga_init (& ga , (int )sizeof (suginfo_T ),1 ); 2540ga_grow (& ga ,su -> su_ga .ga_len + su -> su_sga .ga_len ); 2541 2542suggest_T * stp = & SUG (ga ,0 ); 2543for (int i = 0 ;i < su -> su_ga .ga_len || i < su -> su_sga .ga_len ;i ++ ) { 2544// round 1: get a suggestion from su_ga 2545// round 2: get a suggestion from su_sga 2546for (int round = 1 ;round <=2 ;round ++ ) { 2547garray_T * gap = round == 1 ?& su -> su_ga :& su -> su_sga ; 2548if (i < gap -> ga_len ) { 2549// Don't add a word if it's already there. 2550p = SUG (* gap ,i ).st_word ; 2551int j ; 2552for (j = 0 ;j < ga .ga_len ;j ++ ) { 2553if (strcmp (stp [j ].st_word ,p )== 0 ) { 2554break ; 2555 } 2556 } 2557if (j == ga .ga_len ) { 2558stp [ga .ga_len ++ ]= SUG (* gap ,i ); 2559 }else { 2560xfree (p ); 2561 } 2562 } 2563 } 2564 } 2565 2566ga_clear (& su -> su_ga ); 2567ga_clear (& su -> su_sga ); 2568 2569// Truncate the list to the number of suggestions that will be displayed. 2570if (ga .ga_len > su -> su_maxcount ) { 2571for (int i = su -> su_maxcount ;i < ga .ga_len ;i ++ ) { 2572xfree (stp [i ].st_word ); 2573 } 2574ga .ga_len = su -> su_maxcount ; 2575 } 2576 2577su -> su_ga = ga ; 2578} 2579 2580/// For the goodword in "stp" compute the soundalike score compared to the 2581/// badword. 2582/// 2583/// @param badsound sound-folded badword 2584static int stp_sal_score (suggest_T * stp ,suginfo_T * su ,slang_T * slang ,char * badsound ) 2585{ 2586char * pbad ; 2587char * pgood ; 2588char badsound2 [MAXWLEN ]; 2589char fword [MAXWLEN ]; 2590char goodsound [MAXWLEN ]; 2591char goodword [MAXWLEN ]; 2592 2593int lendiff = su -> su_badlen - stp -> st_orglen ; 2594if (lendiff >=0 ) { 2595pbad = badsound ; 2596 }else { 2597// soundfold the bad word with more characters following 2598spell_casefold (curwin ,su -> su_badptr ,stp -> st_orglen ,fword ,MAXWLEN ); 2599 2600// When joining two words the sound often changes a lot. E.g., "t he" 2601// sounds like "t h" while "the" sounds like "@". Avoid that by 2602// removing the space. Don't do it when the good word also contains a 2603// space. 2604if (ascii_iswhite (su -> su_badptr [su -> su_badlen ]) 2605&& * skiptowhite (stp -> st_word )== NUL ) { 2606for (char * p = fword ;* (p = skiptowhite (p ))!= NUL ;) { 2607STRMOVE (p ,p + 1 ); 2608 } 2609 } 2610 2611spell_soundfold (slang ,fword , true,badsound2 ); 2612pbad = badsound2 ; 2613 } 2614 2615if (lendiff > 0 && stp -> st_wordlen + lendiff < MAXWLEN ) { 2616// Add part of the bad word to the good word, so that we soundfold 2617// what replaces the bad word. 2618STRCPY (goodword ,stp -> st_word ); 2619xmemcpyz (goodword + stp -> st_wordlen , 2620su -> su_badptr + su -> su_badlen - lendiff , (size_t )lendiff ); 2621pgood = goodword ; 2622 }else { 2623pgood = stp -> st_word ; 2624 } 2625 2626// Sound-fold the word and compute the score for the difference. 2627spell_soundfold (slang ,pgood , false,goodsound ); 2628 2629return soundalike_score (goodsound ,pbad ); 2630} 2631 2632/// structure used to store soundfolded words that add_sound_suggest() has 2633/// handled already. 2634typedef struct { 2635int16_t sft_score ;///< lowest score used 2636uint8_t sft_word [];///< soundfolded word 2637}sftword_T ; 2638 2639#define HIKEY2SFT (p ) ((sftword_T *)((p) - offsetof(sftword_T, sft_word))) 2640#define HI2SFT (hi ) HIKEY2SFT((hi)->hi_key) 2641 2642/// Prepare for calling suggest_try_soundalike(). 2643static void suggest_try_soundalike_prep (void ) 2644{ 2645// Do this for all languages that support sound folding and for which a 2646// .sug file has been loaded. 2647for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 2648langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 2649slang_T * slang = lp -> lp_slang ; 2650if (!GA_EMPTY (& slang -> sl_sal )&& slang -> sl_sbyts != NULL ) { 2651// prepare the hashtable used by add_sound_suggest() 2652hash_init (& slang -> sl_sounddone ); 2653 } 2654 } 2655} 2656 2657/// Find suggestions by comparing the word in a sound-a-like form. 2658/// Note: This doesn't support postponed prefixes. 2659static void suggest_try_soundalike (suginfo_T * su ) 2660{ 2661char salword [MAXWLEN ]; 2662 2663// Do this for all languages that support sound folding and for which a 2664// .sug file has been loaded. 2665for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 2666langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 2667slang_T * slang = lp -> lp_slang ; 2668if (!GA_EMPTY (& slang -> sl_sal )&& slang -> sl_sbyts != NULL ) { 2669// soundfold the bad word 2670spell_soundfold (slang ,su -> su_fbadword , true,salword ); 2671 2672// try all kinds of inserts/deletes/swaps/etc. 2673// TODO(vim): also soundfold the next words, so that we can try joining 2674// and splitting 2675#ifdef SUGGEST_PROFILE 2676prof_init (); 2677#endif 2678suggest_trie_walk (su ,lp ,salword , true); 2679#ifdef SUGGEST_PROFILE 2680prof_report ("soundalike" ); 2681#endif 2682 } 2683 } 2684} 2685 2686/// Finish up after calling suggest_try_soundalike(). 2687static void suggest_try_soundalike_finish (void ) 2688{ 2689// Do this for all languages that support sound folding and for which a 2690// .sug file has been loaded. 2691for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 2692langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 2693slang_T * slang = lp -> lp_slang ; 2694if (!GA_EMPTY (& slang -> sl_sal )&& slang -> sl_sbyts != NULL ) { 2695// Free the info about handled words. 2696int todo = (int )slang -> sl_sounddone .ht_used ; 2697for (hashitem_T * hi = slang -> sl_sounddone .ht_array ;todo > 0 ;hi ++ ) { 2698if (!HASHITEM_EMPTY (hi )) { 2699xfree (HI2SFT (hi )); 2700todo -- ; 2701 } 2702 } 2703 2704// Clear the hashtable, it may also be used by another region. 2705hash_clear (& slang -> sl_sounddone ); 2706hash_init (& slang -> sl_sounddone ); 2707 } 2708 } 2709} 2710 2711/// A match with a soundfolded word is found. Add the good word(s) that 2712/// produce this soundfolded word. 2713/// 2714/// @param score soundfold score 2715static void add_sound_suggest (suginfo_T * su ,char * goodword ,int score ,langp_T * lp ) 2716{ 2717slang_T * slang = lp -> lp_slang ;// language for sound folding 2718char theword [MAXWLEN ]; 2719int i ; 2720int wlen ; 2721uint8_t * byts ; 2722int wc ; 2723int goodscore ; 2724sftword_T * sft ; 2725 2726// It's very well possible that the same soundfold word is found several 2727// times with different scores. Since the following is quite slow only do 2728// the words that have a better score than before. Use a hashtable to 2729// remember the words that have been done. 2730hash_T hash = hash_hash (goodword ); 2731const size_t goodword_len = strlen (goodword ); 2732hashitem_T * hi = hash_lookup (& slang -> sl_sounddone ,goodword ,goodword_len ,hash ); 2733if (HASHITEM_EMPTY (hi )) { 2734sft = xmalloc (offsetof(sftword_T ,sft_word )+ goodword_len + 1 ); 2735sft -> sft_score = (int16_t )score ; 2736memcpy (sft -> sft_word ,goodword ,goodword_len + 1 ); 2737hash_add_item (& slang -> sl_sounddone ,hi , (char * )sft -> sft_word ,hash ); 2738 }else { 2739sft = HI2SFT (hi ); 2740if (score >=sft -> sft_score ) { 2741return ; 2742 } 2743sft -> sft_score = (int16_t )score ; 2744 } 2745 2746// Find the word nr in the soundfold tree. 2747int sfwordnr = soundfold_find (slang ,goodword ); 2748if (sfwordnr < 0 ) { 2749internal_error ("add_sound_suggest()" ); 2750return ; 2751 } 2752 2753// Go over the list of good words that produce this soundfold word 2754char * nrline = ml_get_buf (slang -> sl_sugbuf , (linenr_T )sfwordnr + 1 ); 2755int orgnr = 0 ; 2756while (* nrline != NUL ) { 2757// The wordnr was stored in a minimal nr of bytes as an offset to the 2758// previous wordnr. 2759orgnr += bytes2offset (& nrline ); 2760 2761byts = slang -> sl_fbyts ; 2762idx_T * idxs = slang -> sl_fidxs ; 2763 2764// Lookup the word "orgnr" one of the two tries. 2765int n = 0 ; 2766int wordcount = 0 ; 2767for (wlen = 0 ;wlen < MAXWLEN - 3 ;wlen ++ ) { 2768i = 1 ; 2769if (wordcount == orgnr && byts [n + 1 ]== NUL ) { 2770break ;// found end of word 2771 } 2772if (byts [n + 1 ]== NUL ) { 2773wordcount ++ ; 2774 } 2775 2776// skip over the NUL bytes 2777for (;byts [n + i ]== NUL ;i ++ ) { 2778if (i > byts [n ]) {// safety check 2779STRCPY (theword + wlen ,"BAD" ); 2780wlen += 3 ; 2781 gotobadword ; 2782 } 2783 } 2784 2785// One of the siblings must have the word. 2786for (;i < byts [n ];i ++ ) { 2787wc = idxs [idxs [n + i ]];// nr of words under this byte 2788if (wordcount + wc > orgnr ) { 2789break ; 2790 } 2791wordcount += wc ; 2792 } 2793 2794theword [wlen ]= (char )byts [n + i ]; 2795n = idxs [n + i ]; 2796 } 2797badword : 2798theword [wlen ]= NUL ; 2799 2800// Go over the possible flags and regions. 2801for (;i <=byts [n ]&& byts [n + i ]== NUL ;i ++ ) { 2802char cword [MAXWLEN ]; 2803char * p ; 2804int flags = (int )idxs [n + i ]; 2805 2806// Skip words with the NOSUGGEST flag 2807if (flags & WF_NOSUGGEST ) { 2808continue ; 2809 } 2810 2811if (flags & WF_KEEPCAP ) { 2812// Must find the word in the keep-case tree. 2813find_keepcap_word (slang ,theword ,cword ); 2814p = cword ; 2815 }else { 2816flags |=su -> su_badflags ; 2817if ((flags & WF_CAPMASK )!= 0 ) { 2818// Need to fix case according to "flags". 2819make_case_word (theword ,cword ,flags ); 2820p = cword ; 2821 }else { 2822p = theword ; 2823 } 2824 } 2825 2826// Add the suggestion. 2827if (sps_flags & SPS_DOUBLE ) { 2828// Add the suggestion if the score isn't too bad. 2829if (score <=su -> su_maxscore ) { 2830add_suggestion (su ,& su -> su_sga ,p ,su -> su_badlen , 2831score ,0 , false,slang , false); 2832 } 2833 }else { 2834// Add a penalty for words in another region. 2835if ((flags & WF_REGION ) 2836&& (((unsigned )flags >>16 )& (unsigned )lp -> lp_region )== 0 ) { 2837goodscore = SCORE_REGION ; 2838 }else { 2839goodscore = 0 ; 2840 } 2841 2842// Add a small penalty for changing the first letter from 2843// lower to upper case. Helps for "tath" -> "Kath", which is 2844// less common than "tath" -> "path". Don't do it when the 2845// letter is the same, that has already been counted. 2846int gc = utf_ptr2char (p ); 2847if (SPELL_ISUPPER (gc )) { 2848int bc = utf_ptr2char (su -> su_badword ); 2849if (!SPELL_ISUPPER (bc ) 2850&& SPELL_TOFOLD (bc )!= SPELL_TOFOLD (gc )) { 2851goodscore += SCORE_ICASE /2 ; 2852 } 2853 } 2854 2855// Compute the score for the good word. This only does letter 2856// insert/delete/swap/replace. REP items are not considered, 2857// which may make the score a bit higher. 2858// Use a limit for the score to make it work faster. Use 2859// MAXSCORE(), because RESCORE() will change the score. 2860// If the limit is very high then the iterative method is 2861// inefficient, using an array is quicker. 2862int limit = MAXSCORE (su -> su_sfmaxscore - goodscore ,score ); 2863if (limit > SCORE_LIMITMAX ) { 2864goodscore += spell_edit_score (slang ,su -> su_badword ,p ); 2865 }else { 2866goodscore += spell_edit_score_limit (slang ,su -> su_badword ,p ,limit ); 2867 } 2868 2869// When going over the limit don't bother to do the rest. 2870if (goodscore < SCORE_MAXMAX ) { 2871// Give a bonus to words seen before. 2872goodscore = score_wordcount_adj (slang ,goodscore ,p , false); 2873 2874// Add the suggestion if the score isn't too bad. 2875goodscore = RESCORE (goodscore ,score ); 2876if (goodscore <=su -> su_sfmaxscore ) { 2877add_suggestion (su ,& su -> su_ga ,p ,su -> su_badlen , 2878goodscore ,score , true,slang , true); 2879 } 2880 } 2881 } 2882 } 2883 } 2884} 2885 2886/// Find word "word" in fold-case tree for "slang" and return the word number. 2887static int soundfold_find (slang_T * slang ,char * word ) 2888{ 2889idx_T arridx = 0 ; 2890int wlen = 0 ; 2891uint8_t * ptr = (uint8_t * )word ; 2892int wordnr = 0 ; 2893 2894uint8_t * byts = slang -> sl_sbyts ; 2895idx_T * idxs = slang -> sl_sidxs ; 2896 2897while (true) { 2898// First byte is the number of possible bytes. 2899int len = byts [arridx ++ ]; 2900 2901// If the first possible byte is a zero the word could end here. 2902// If the word ends we found the word. If not skip the NUL bytes. 2903int c = ptr [wlen ]; 2904if (byts [arridx ]== NUL ) { 2905if (c == NUL ) { 2906break ; 2907 } 2908 2909// Skip over the zeros, there can be several. 2910while (len > 0 && byts [arridx ]== NUL ) { 2911arridx ++ ; 2912len -- ; 2913 } 2914if (len == 0 ) { 2915return -1 ;// no children, word should have ended here 2916 } 2917wordnr ++ ; 2918 } 2919 2920// If the word ends we didn't find it. 2921if (c == NUL ) { 2922return -1 ; 2923 } 2924 2925// Perform a binary search in the list of accepted bytes. 2926if (c == TAB ) {// <Tab> is handled like <Space> 2927c = ' ' ; 2928 } 2929while (byts [arridx ]< c ) { 2930// The word count is in the first idxs[] entry of the child. 2931wordnr += idxs [idxs [arridx ]]; 2932arridx ++ ; 2933if (-- len == 0 ) {// end of the bytes, didn't find it 2934return -1 ; 2935 } 2936 } 2937if (byts [arridx ]!= c ) {// didn't find the byte 2938return -1 ; 2939 } 2940 2941// Continue at the child (if there is one). 2942arridx = idxs [arridx ]; 2943wlen ++ ; 2944 2945// One space in the good word may stand for several spaces in the 2946// checked word. 2947if (c == ' ' ) { 2948while (ptr [wlen ]== ' ' || ptr [wlen ]== TAB ) { 2949wlen ++ ; 2950 } 2951 } 2952 } 2953 2954return wordnr ; 2955} 2956 2957/// Returns true if "c1" and "c2" are similar characters according to the MAP 2958/// lines in the .aff file. 2959static bool similar_chars (slang_T * slang ,int c1 ,int c2 ) 2960{ 2961int m1 ,m2 ; 2962char buf [MB_MAXCHAR + 1 ]; 2963 2964if (c1 >=256 ) { 2965buf [utf_char2bytes (c1 ,buf )]= 0 ; 2966hashitem_T * hi = hash_find (& slang -> sl_map_hash ,buf ); 2967if (HASHITEM_EMPTY (hi )) { 2968m1 = 0 ; 2969 }else { 2970m1 = utf_ptr2char (hi -> hi_key + strlen (hi -> hi_key )+ 1 ); 2971 } 2972 }else { 2973m1 = slang -> sl_map_array [c1 ]; 2974 } 2975if (m1 == 0 ) { 2976return false; 2977 } 2978 2979if (c2 >=256 ) { 2980buf [utf_char2bytes (c2 ,buf )]= 0 ; 2981hashitem_T * hi = hash_find (& slang -> sl_map_hash ,buf ); 2982if (HASHITEM_EMPTY (hi )) { 2983m2 = 0 ; 2984 }else { 2985m2 = utf_ptr2char (hi -> hi_key + strlen (hi -> hi_key )+ 1 ); 2986 } 2987 }else { 2988m2 = slang -> sl_map_array [c2 ]; 2989 } 2990 2991return m1 == m2 ; 2992} 2993 2994/// Adds a suggestion to the list of suggestions. 2995/// For a suggestion that is already in the list the lowest score is remembered. 2996/// 2997/// @param gap either su_ga or su_sga 2998/// @param badlenarg len of bad word replaced with "goodword" 2999/// @param had_bonus value for st_had_bonus 3000/// @param slang language for sound folding 3001/// @param maxsf su_maxscore applies to soundfold score, su_sfmaxscore to the total score. 3002static void add_suggestion (suginfo_T * su ,garray_T * gap ,const char * goodword ,int badlenarg , 3003int score ,int altscore ,bool had_bonus ,slang_T * slang ,bool maxsf ) 3004{ 3005int goodlen ;// len of goodword changed 3006int badlen ;// len of bad word changed 3007suggest_T new_sug ; 3008 3009// Minimize "badlen" for consistency. Avoids that changing "the the" to 3010// "thee the" is added next to changing the first "the" the "thee". 3011const char * pgood = goodword + strlen (goodword ); 3012char * pbad = su -> su_badptr + badlenarg ; 3013while (true) { 3014goodlen = (int )(pgood - goodword ); 3015badlen = (int )(pbad - su -> su_badptr ); 3016if (goodlen <=0 || badlen <=0 ) { 3017break ; 3018 } 3019MB_PTR_BACK (goodword ,pgood ); 3020MB_PTR_BACK (su -> su_badptr ,pbad ); 3021if (utf_ptr2char (pgood )!= utf_ptr2char (pbad )) { 3022break ; 3023 } 3024 } 3025 3026if (badlen == 0 && goodlen == 0 ) { 3027// goodword doesn't change anything; may happen for "the the" changing 3028// the first "the" to itself. 3029return ; 3030 } 3031 3032int i ; 3033if (GA_EMPTY (gap )) { 3034i = -1 ; 3035 }else { 3036// Check if the word is already there. Also check the length that is 3037// being replaced "thes," -> "these" is a different suggestion from 3038// "thes" -> "these". 3039suggest_T * stp = & SUG (* gap ,0 ); 3040for (i = gap -> ga_len ;-- i >=0 ;stp ++ ) { 3041if (stp -> st_wordlen == goodlen 3042&& stp -> st_orglen == badlen 3043&& strncmp (stp -> st_word ,goodword , (size_t )goodlen )== 0 ) { 3044// Found it. Remember the word with the lowest score. 3045if (stp -> st_slang == NULL ) { 3046stp -> st_slang = slang ; 3047 } 3048 3049new_sug .st_score = score ; 3050new_sug .st_altscore = altscore ; 3051new_sug .st_had_bonus = had_bonus ; 3052 3053if (stp -> st_had_bonus != had_bonus ) { 3054// Only one of the two had the soundalike score computed. 3055// Need to do that for the other one now, otherwise the 3056// scores can't be compared. This happens because 3057// suggest_try_change() doesn't compute the soundalike 3058// word to keep it fast, while some special methods set 3059// the soundalike score to zero. 3060if (had_bonus ) { 3061rescore_one (su ,stp ); 3062 }else { 3063new_sug .st_word = stp -> st_word ; 3064new_sug .st_wordlen = stp -> st_wordlen ; 3065new_sug .st_slang = stp -> st_slang ; 3066new_sug .st_orglen = badlen ; 3067rescore_one (su ,& new_sug ); 3068 } 3069 } 3070 3071if (stp -> st_score > new_sug .st_score ) { 3072stp -> st_score = new_sug .st_score ; 3073stp -> st_altscore = new_sug .st_altscore ; 3074stp -> st_had_bonus = new_sug .st_had_bonus ; 3075 } 3076break ; 3077 } 3078 } 3079 } 3080 3081if (i < 0 ) { 3082// Add a suggestion. 3083suggest_T * stp = GA_APPEND_VIA_PTR (suggest_T ,gap ); 3084stp -> st_word = xmemdupz (goodword , (size_t )goodlen ); 3085stp -> st_wordlen = goodlen ; 3086stp -> st_score = score ; 3087stp -> st_altscore = altscore ; 3088stp -> st_had_bonus = had_bonus ; 3089stp -> st_orglen = badlen ; 3090stp -> st_slang = slang ; 3091 3092// If we have too many suggestions now, sort the list and keep 3093// the best suggestions. 3094if (gap -> ga_len > SUG_MAX_COUNT (su )) { 3095if (maxsf ) { 3096su -> su_sfmaxscore = cleanup_suggestions (gap ,su -> su_sfmaxscore ,SUG_CLEAN_COUNT (su )); 3097 }else { 3098su -> su_maxscore = cleanup_suggestions (gap ,su -> su_maxscore ,SUG_CLEAN_COUNT (su )); 3099 } 3100 } 3101 } 3102} 3103 3104/// Suggestions may in fact be flagged as errors. Esp. for banned words and 3105/// for split words, such as "the the". Remove these from the list here. 3106/// 3107/// @param gap either su_ga or su_sga 3108static void check_suggestions (suginfo_T * su ,garray_T * gap ) 3109{ 3110char longword [MAXWLEN + 1 ]; 3111 3112if (gap -> ga_len == 0 ) { 3113return ; 3114 } 3115suggest_T * stp = & SUG (* gap ,0 ); 3116for (int i = gap -> ga_len - 1 ;i >=0 ;i -- ) { 3117// Need to append what follows to check for "the the". 3118xstrlcpy (longword ,stp [i ].st_word ,MAXWLEN + 1 ); 3119int len = stp [i ].st_wordlen ; 3120xstrlcpy (longword + len ,su -> su_badptr + stp [i ].st_orglen ,MAXWLEN + 1 - (size_t )len ); 3121hlf_T attr = HLF_COUNT ; 3122spell_check (curwin ,longword ,& attr ,NULL , false); 3123if (attr != HLF_COUNT ) { 3124// Remove this entry. 3125xfree (stp [i ].st_word ); 3126gap -> ga_len -- ; 3127if (i < gap -> ga_len ) { 3128memmove (stp + i ,stp + i + 1 ,sizeof (suggest_T )* (size_t )(gap -> ga_len - i )); 3129 } 3130 } 3131 } 3132} 3133 3134/// Add a word to be banned. 3135static void add_banned (suginfo_T * su ,char * word ) 3136{ 3137hash_T hash = hash_hash (word ); 3138const size_t word_len = strlen (word ); 3139hashitem_T * hi = hash_lookup (& su -> su_banned ,word ,word_len ,hash ); 3140if (!HASHITEM_EMPTY (hi )) {// already present 3141return ; 3142 } 3143char * s = xmemdupz (word ,word_len ); 3144hash_add_item (& su -> su_banned ,hi ,s ,hash ); 3145} 3146 3147/// Recompute the score for all suggestions if sound-folding is possible. This 3148/// is slow, thus only done for the final results. 3149static void rescore_suggestions (suginfo_T * su ) 3150{ 3151if (su -> su_sallang != NULL ) { 3152for (int i = 0 ;i < su -> su_ga .ga_len ;i ++ ) { 3153rescore_one (su ,& SUG (su -> su_ga ,i )); 3154 } 3155 } 3156} 3157 3158/// Recompute the score for one suggestion if sound-folding is possible. 3159static void rescore_one (suginfo_T * su ,suggest_T * stp ) 3160{ 3161slang_T * slang = stp -> st_slang ; 3162char sal_badword [MAXWLEN ]; 3163 3164// Only rescore suggestions that have no sal score yet and do have a 3165// language. 3166if (slang != NULL && !GA_EMPTY (& slang -> sl_sal )&& !stp -> st_had_bonus ) { 3167char * p ; 3168if (slang == su -> su_sallang ) { 3169p = su -> su_sal_badword ; 3170 }else { 3171spell_soundfold (slang ,su -> su_fbadword , true,sal_badword ); 3172p = sal_badword ; 3173 } 3174 3175stp -> st_altscore = stp_sal_score (stp ,su ,slang ,p ); 3176if (stp -> st_altscore == SCORE_MAXMAX ) { 3177stp -> st_altscore = SCORE_BIG ; 3178 } 3179stp -> st_score = RESCORE (stp -> st_score ,stp -> st_altscore ); 3180stp -> st_had_bonus = true; 3181 } 3182} 3183 3184/// Function given to qsort() to sort the suggestions on st_score. 3185/// First on "st_score", then "st_altscore" then alphabetically. 3186static int sug_compare (const void * s1 ,const void * s2 ) 3187{ 3188suggest_T * p1 = (suggest_T * )s1 ; 3189suggest_T * p2 = (suggest_T * )s2 ; 3190int n = p1 -> st_score == p2 -> st_score ?0 :p1 -> st_score > p2 -> st_score ?1 :-1 ; 3191 3192if (n == 0 ) { 3193n = p1 -> st_altscore == p2 -> st_altscore ?0 :p1 -> st_altscore > p2 -> st_altscore ?1 :-1 ; 3194if (n == 0 ) { 3195n = STRICMP (p1 -> st_word ,p2 -> st_word ); 3196 } 3197 } 3198return n ; 3199} 3200 3201/// Cleanup the suggestions: 3202/// - Sort on score. 3203/// - Remove words that won't be displayed. 3204/// 3205/// @param keep nr of suggestions to keep 3206/// 3207/// @return the maximum score in the list or "maxscore" unmodified. 3208static int cleanup_suggestions (garray_T * gap ,int maxscore ,int keep ) 3209FUNC_ATTR_NONNULL_ALL 3210{ 3211if (gap -> ga_len <=0 ) { 3212return maxscore ; 3213 } 3214 3215// Sort the list. 3216qsort (gap -> ga_data , (size_t )gap -> ga_len ,sizeof (suggest_T ),sug_compare ); 3217 3218// Truncate the list to the number of suggestions that will be displayed. 3219if (gap -> ga_len > keep ) { 3220suggest_T * const stp = & SUG (* gap ,0 ); 3221 3222for (int i = keep ;i < gap -> ga_len ;i ++ ) { 3223xfree (stp [i ].st_word ); 3224 } 3225gap -> ga_len = keep ; 3226if (keep >=1 ) { 3227return stp [keep - 1 ].st_score ; 3228 } 3229 } 3230return maxscore ; 3231} 3232 3233/// Compute a score for two sound-a-like words. 3234/// This permits up to two inserts/deletes/swaps/etc. to keep things fast. 3235/// Instead of a generic loop we write out the code. That keeps it fast by 3236/// avoiding checks that will not be possible. 3237/// 3238/// @param goodstart sound-folded good word 3239/// @param badstart sound-folded bad word 3240static int soundalike_score (char * goodstart ,char * badstart ) 3241{ 3242char * goodsound = goodstart ; 3243char * badsound = badstart ; 3244int score = 0 ; 3245 3246// Adding/inserting "*" at the start (word starts with vowel) shouldn't be 3247// counted so much, vowels in the middle of the word aren't counted at all. 3248if ((* badsound == '*' || * goodsound == '*' )&& * badsound != * goodsound ) { 3249if ((badsound [0 ]== NUL && goodsound [1 ]== NUL ) 3250|| (goodsound [0 ]== NUL && badsound [1 ]== NUL )) { 3251// changing word with vowel to word without a sound 3252return SCORE_DEL ; 3253 } 3254if (badsound [0 ]== NUL || goodsound [0 ]== NUL ) { 3255// more than two changes 3256return SCORE_MAXMAX ; 3257 } 3258 3259if (badsound [1 ]== goodsound [1 ] 3260|| (badsound [1 ]!= NUL 3261&& goodsound [1 ]!= NUL 3262&& badsound [2 ]== goodsound [2 ])) { 3263// handle like a substitute 3264 }else { 3265score = 2 * SCORE_DEL /3 ; 3266if (* badsound == '*' ) { 3267badsound ++ ; 3268 }else { 3269goodsound ++ ; 3270 } 3271 } 3272 } 3273 3274int goodlen = (int )strlen (goodsound ); 3275int badlen = (int )strlen (badsound ); 3276 3277// Return quickly if the lengths are too different to be fixed by two 3278// changes. 3279int n = goodlen - badlen ; 3280if (n < -2 || n > 2 ) { 3281return SCORE_MAXMAX ; 3282 } 3283 3284// n > 0 : goodsound is longest 3285// n <= 0 : badsound is longest 3286char * pl = n > 0 ?goodsound :badsound ; 3287char * ps = n > 0 ?badsound :goodsound ; 3288 3289// Skip over the identical part. 3290while (* pl == * ps && * pl != NUL ) { 3291pl ++ ; 3292ps ++ ; 3293 } 3294 3295char * pl2 ,* ps2 ; 3296 3297switch (n ) { 3298case -2 : 3299case 2 : 3300// Must delete two characters from "pl". 3301pl ++ ;// first delete 3302while (* pl == * ps ) { 3303pl ++ ; 3304ps ++ ; 3305 } 3306// strings must be equal after second delete 3307if (strcmp (pl + 1 ,ps )== 0 ) { 3308return score + SCORE_DEL * 2 ; 3309 } 3310 3311// Failed to compare. 3312break ; 3313 3314case -1 : 3315case 1 : 3316// Minimal one delete from "pl" required. 3317 3318// 1: delete 3319pl2 = pl + 1 ; 3320ps2 = ps ; 3321while (* pl2 == * ps2 ) { 3322if (* pl2 == NUL ) {// reached the end 3323return score + SCORE_DEL ; 3324 } 3325pl2 ++ ; 3326ps2 ++ ; 3327 } 3328 3329// 2: delete then swap, then rest must be equal 3330if (pl2 [0 ]== ps2 [1 ]&& pl2 [1 ]== ps2 [0 ] 3331&& strcmp (pl2 + 2 ,ps2 + 2 )== 0 ) { 3332return score + SCORE_DEL + SCORE_SWAP ; 3333 } 3334 3335// 3: delete then substitute, then the rest must be equal 3336if (strcmp (pl2 + 1 ,ps2 + 1 )== 0 ) { 3337return score + SCORE_DEL + SCORE_SUBST ; 3338 } 3339 3340// 4: first swap then delete 3341if (pl [0 ]== ps [1 ]&& pl [1 ]== ps [0 ]) { 3342pl2 = pl + 2 ;// swap, skip two chars 3343ps2 = ps + 2 ; 3344while (* pl2 == * ps2 ) { 3345pl2 ++ ; 3346ps2 ++ ; 3347 } 3348// delete a char and then strings must be equal 3349if (strcmp (pl2 + 1 ,ps2 )== 0 ) { 3350return score + SCORE_SWAP + SCORE_DEL ; 3351 } 3352 } 3353 3354// 5: first substitute then delete 3355pl2 = pl + 1 ;// substitute, skip one char 3356ps2 = ps + 1 ; 3357while (* pl2 == * ps2 ) { 3358pl2 ++ ; 3359ps2 ++ ; 3360 } 3361// delete a char and then strings must be equal 3362if (strcmp (pl2 + 1 ,ps2 )== 0 ) { 3363return score + SCORE_SUBST + SCORE_DEL ; 3364 } 3365 3366// Failed to compare. 3367break ; 3368 3369case 0 : 3370// Lengths are equal, thus changes must result in same length: An 3371// insert is only possible in combination with a delete. 3372// 1: check if for identical strings 3373if (* pl == NUL ) { 3374return score ; 3375 } 3376 3377// 2: swap 3378if (pl [0 ]== ps [1 ]&& pl [1 ]== ps [0 ]) { 3379pl2 = pl + 2 ;// swap, skip two chars 3380ps2 = ps + 2 ; 3381while (* pl2 == * ps2 ) { 3382if (* pl2 == NUL ) {// reached the end 3383return score + SCORE_SWAP ; 3384 } 3385pl2 ++ ; 3386ps2 ++ ; 3387 } 3388// 3: swap and swap again 3389if (pl2 [0 ]== ps2 [1 ]&& pl2 [1 ]== ps2 [0 ] 3390&& strcmp (pl2 + 2 ,ps2 + 2 )== 0 ) { 3391return score + SCORE_SWAP + SCORE_SWAP ; 3392 } 3393 3394// 4: swap and substitute 3395if (strcmp (pl2 + 1 ,ps2 + 1 )== 0 ) { 3396return score + SCORE_SWAP + SCORE_SUBST ; 3397 } 3398 } 3399 3400// 5: substitute 3401pl2 = pl + 1 ; 3402ps2 = ps + 1 ; 3403while (* pl2 == * ps2 ) { 3404if (* pl2 == NUL ) {// reached the end 3405return score + SCORE_SUBST ; 3406 } 3407pl2 ++ ; 3408ps2 ++ ; 3409 } 3410 3411// 6: substitute and swap 3412if (pl2 [0 ]== ps2 [1 ]&& pl2 [1 ]== ps2 [0 ] 3413&& strcmp (pl2 + 2 ,ps2 + 2 )== 0 ) { 3414return score + SCORE_SUBST + SCORE_SWAP ; 3415 } 3416 3417// 7: substitute and substitute 3418if (strcmp (pl2 + 1 ,ps2 + 1 )== 0 ) { 3419return score + SCORE_SUBST + SCORE_SUBST ; 3420 } 3421 3422// 8: insert then delete 3423pl2 = pl ; 3424ps2 = ps + 1 ; 3425while (* pl2 == * ps2 ) { 3426pl2 ++ ; 3427ps2 ++ ; 3428 } 3429if (strcmp (pl2 + 1 ,ps2 )== 0 ) { 3430return score + SCORE_INS + SCORE_DEL ; 3431 } 3432 3433// 9: delete then insert 3434pl2 = pl + 1 ; 3435ps2 = ps ; 3436while (* pl2 == * ps2 ) { 3437pl2 ++ ; 3438ps2 ++ ; 3439 } 3440if (strcmp (pl2 ,ps2 + 1 )== 0 ) { 3441return score + SCORE_INS + SCORE_DEL ; 3442 } 3443 3444// Failed to compare. 3445break ; 3446 } 3447 3448return SCORE_MAXMAX ; 3449} 3450 3451/// Compute the "edit distance" to turn "badword" into "goodword". The less 3452/// deletes/inserts/substitutes/swaps are required the lower the score. 3453/// 3454/// The algorithm is described by Du and Chang, 1992. 3455/// The implementation of the algorithm comes from Aspell editdist.cpp, 3456/// edit_distance(). It has been converted from C++ to C and modified to 3457/// support multi-byte characters. 3458static int spell_edit_score (slang_T * slang ,const char * badword ,const char * goodword ) 3459{ 3460int wbadword [MAXWLEN ]; 3461int wgoodword [MAXWLEN ]; 3462 3463// Lengths with NUL. 3464int badlen ; 3465int goodlen ; 3466 { 3467// Get the characters from the multi-byte strings and put them in an 3468// int array for easy access. 3469badlen = 0 ; 3470for (const char * p = badword ;* p != NUL ;) { 3471wbadword [badlen ++ ]= mb_cptr2char_adv (& p ); 3472 } 3473wbadword [badlen ++ ]= 0 ; 3474goodlen = 0 ; 3475for (const char * p = goodword ;* p != NUL ;) { 3476wgoodword [goodlen ++ ]= mb_cptr2char_adv (& p ); 3477 } 3478wgoodword [goodlen ++ ]= 0 ; 3479 } 3480 3481// We use "cnt" as an array: CNT(badword_idx, goodword_idx). 3482#define CNT (a ,b ) cnt[(a) + (b) * (badlen + 1)] 3483int * cnt = xmalloc (sizeof (int )* ((size_t )badlen + 1 )* ((size_t )goodlen + 1 )); 3484 3485CNT (0 ,0 )= 0 ; 3486for (int j = 1 ;j <=goodlen ;j ++ ) { 3487CNT (0 ,j )= CNT (0 ,j - 1 )+ SCORE_INS ; 3488 } 3489 3490for (int i = 1 ;i <=badlen ;i ++ ) { 3491CNT (i ,0 )= CNT (i - 1 ,0 )+ SCORE_DEL ; 3492for (int j = 1 ;j <=goodlen ;j ++ ) { 3493int bc = wbadword [i - 1 ]; 3494int gc = wgoodword [j - 1 ]; 3495if (bc == gc ) { 3496CNT (i ,j )= CNT (i - 1 ,j - 1 ); 3497 }else { 3498// Use a better score when there is only a case difference. 3499if (SPELL_TOFOLD (bc )== SPELL_TOFOLD (gc )) { 3500CNT (i ,j )= SCORE_ICASE + CNT (i - 1 ,j - 1 ); 3501 }else { 3502// For a similar character use SCORE_SIMILAR. 3503if (slang != NULL 3504&& slang -> sl_has_map 3505&& similar_chars (slang ,gc ,bc )) { 3506CNT (i ,j )= SCORE_SIMILAR + CNT (i - 1 ,j - 1 ); 3507 }else { 3508CNT (i ,j )= SCORE_SUBST + CNT (i - 1 ,j - 1 ); 3509 } 3510 } 3511 3512if (i > 1 && j > 1 ) { 3513int pbc = wbadword [i - 2 ]; 3514int pgc = wgoodword [j - 2 ]; 3515if (bc == pgc && pbc == gc ) { 3516int t = SCORE_SWAP + CNT (i - 2 ,j - 2 ); 3517CNT (i ,j )= MIN (CNT (i ,j ),t ); 3518 } 3519 } 3520int t = SCORE_DEL + CNT (i - 1 ,j ); 3521CNT (i ,j )= MIN (CNT (i ,j ),t ); 3522t = SCORE_INS + CNT (i ,j - 1 ); 3523CNT (i ,j )= MIN (CNT (i ,j ),t ); 3524 } 3525 } 3526 } 3527 3528int i = CNT (badlen - 1 ,goodlen - 1 ); 3529xfree (cnt ); 3530return i ; 3531} 3532 3533typedef struct { 3534int badi ; 3535int goodi ; 3536int score ; 3537}limitscore_T ; 3538 3539/// Like spell_edit_score(), but with a limit on the score to make it faster. 3540/// May return SCORE_MAXMAX when the score is higher than "limit". 3541/// 3542/// This uses a stack for the edits still to be tried. 3543/// The idea comes from Aspell leditdist.cpp. Rewritten in C and added support 3544/// for multi-byte characters. 3545static int spell_edit_score_limit (slang_T * slang ,char * badword ,char * goodword ,int limit ) 3546{ 3547return spell_edit_score_limit_w (slang ,badword ,goodword ,limit ); 3548} 3549 3550/// Multi-byte version of spell_edit_score_limit(). 3551/// Keep it in sync with the above! 3552static int spell_edit_score_limit_w (slang_T * slang ,const char * badword ,const char * goodword , 3553int limit ) 3554{ 3555limitscore_T stack [10 ];// allow for over 3 * 2 edits 3556int bc ,gc ; 3557int score_off ; 3558int wbadword [MAXWLEN ]; 3559int wgoodword [MAXWLEN ]; 3560 3561// Get the characters from the multi-byte strings and put them in an 3562// int array for easy access. 3563int bi = 0 ; 3564for (const char * p = badword ;* p != NUL ;) { 3565wbadword [bi ++ ]= mb_cptr2char_adv (& p ); 3566 } 3567wbadword [bi ++ ]= 0 ; 3568int gi = 0 ; 3569for (const char * p = goodword ;* p != NUL ;) { 3570wgoodword [gi ++ ]= mb_cptr2char_adv (& p ); 3571 } 3572wgoodword [gi ++ ]= 0 ; 3573 3574// The idea is to go from start to end over the words. So long as 3575// characters are equal just continue, this always gives the lowest score. 3576// When there is a difference try several alternatives. Each alternative 3577// increases "score" for the edit distance. Some of the alternatives are 3578// pushed unto a stack and tried later, some are tried right away. At the 3579// end of the word the score for one alternative is known. The lowest 3580// possible score is stored in "minscore". 3581int stackidx = 0 ; 3582bi = 0 ; 3583gi = 0 ; 3584int score = 0 ; 3585int minscore = limit + 1 ; 3586 3587while (true) { 3588// Skip over an equal part, score remains the same. 3589while (true) { 3590bc = wbadword [bi ]; 3591gc = wgoodword [gi ]; 3592 3593if (bc != gc ) {// stop at a char that's different 3594break ; 3595 } 3596if (bc == NUL ) {// both words end 3597if (score < minscore ) { 3598minscore = score ; 3599 } 3600 gotopop ;// do next alternative 3601 } 3602bi ++ ; 3603gi ++ ; 3604 } 3605 3606if (gc == NUL ) {// goodword ends, delete badword chars 3607do { 3608if ((score += SCORE_DEL ) >=minscore ) { 3609 gotopop ;// do next alternative 3610 } 3611 }while (wbadword [++ bi ]!= NUL ); 3612minscore = score ; 3613 }else if (bc == NUL ) {// badword ends, insert badword chars 3614do { 3615if ((score += SCORE_INS ) >=minscore ) { 3616 gotopop ;// do next alternative 3617 } 3618 }while (wgoodword [++ gi ]!= NUL ); 3619minscore = score ; 3620 }else {// both words continue 3621// If not close to the limit, perform a change. Only try changes 3622// that may lead to a lower score than "minscore". 3623// round 0: try deleting a char from badword 3624// round 1: try inserting a char in badword 3625for (int round = 0 ;round <=1 ;round ++ ) { 3626score_off = score + (round == 0 ?SCORE_DEL :SCORE_INS ); 3627if (score_off < minscore ) { 3628if (score_off + SCORE_EDIT_MIN >=minscore ) { 3629// Near the limit, rest of the words must match. We 3630// can check that right now, no need to push an item 3631// onto the stack. 3632int bi2 = bi + 1 - round ; 3633int gi2 = gi + round ; 3634while (wgoodword [gi2 ]== wbadword [bi2 ]) { 3635if (wgoodword [gi2 ]== NUL ) { 3636minscore = score_off ; 3637break ; 3638 } 3639bi2 ++ ; 3640gi2 ++ ; 3641 } 3642 }else { 3643// try deleting a character from badword later 3644stack [stackidx ].badi = bi + 1 - round ; 3645stack [stackidx ].goodi = gi + round ; 3646stack [stackidx ].score = score_off ; 3647stackidx ++ ; 3648 } 3649 } 3650 } 3651 3652if (score + SCORE_SWAP < minscore ) { 3653// If swapping two characters makes a match then the 3654// substitution is more expensive, thus there is no need to 3655// try both. 3656if (gc == wbadword [bi + 1 ]&& bc == wgoodword [gi + 1 ]) { 3657// Swap two characters, that is: skip them. 3658gi += 2 ; 3659bi += 2 ; 3660score += SCORE_SWAP ; 3661continue ; 3662 } 3663 } 3664 3665// Substitute one character for another which is the same 3666// thing as deleting a character from both goodword and badword. 3667// Use a better score when there is only a case difference. 3668if (SPELL_TOFOLD (bc )== SPELL_TOFOLD (gc )) { 3669score += SCORE_ICASE ; 3670 }else { 3671// For a similar character use SCORE_SIMILAR. 3672if (slang != NULL 3673&& slang -> sl_has_map 3674&& similar_chars (slang ,gc ,bc )) { 3675score += SCORE_SIMILAR ; 3676 }else { 3677score += SCORE_SUBST ; 3678 } 3679 } 3680 3681if (score < minscore ) { 3682// Do the substitution. 3683gi ++ ; 3684bi ++ ; 3685continue ; 3686 } 3687 } 3688pop : 3689// Get here to try the next alternative, pop it from the stack. 3690if (stackidx == 0 ) {// stack is empty, finished 3691break ; 3692 } 3693 3694// pop an item from the stack 3695stackidx -- ; 3696gi = stack [stackidx ].goodi ; 3697bi = stack [stackidx ].badi ; 3698score = stack [stackidx ].score ; 3699 } 3700 3701// When the score goes over "limit" it may actually be much higher. 3702// Return a very large number to avoid going below the limit when giving a 3703// bonus. 3704if (minscore > limit ) { 3705return SCORE_MAXMAX ; 3706 } 3707return minscore ; 3708}