robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
121.4 KiB3708 linesraw
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 {
74  garray_T su_ga;                  ///< suggestions, contains "suggest_T"
75  int su_maxcount;                 ///< max. number of suggestions displayed
76  int su_maxscore;                 ///< maximum score for adding to su_ga
77  int su_sfmaxscore;               ///< idem, for when doing soundfold words
78  garray_T su_sga;                 ///< like su_ga, sound-folded scoring
79  char *su_badptr;                 ///< start of bad word in line
80  int su_badlen;                   ///< length of detected bad word in line
81  int su_badflags;                 ///< caps flags for bad word
82  char su_badword[MAXWLEN];        ///< bad word truncated at su_badlen
83  char su_fbadword[MAXWLEN];       ///< su_badword case-folded
84  char su_sal_badword[MAXWLEN];    ///< su_badword soundfolded
85  hashtab_T su_banned;             ///< table with banned words
86  slang_T *su_sallang;             ///< default language for sound folding
87} suginfo_T;
88
89/// One word suggestion.  Used in "si_ga".
90typedef struct {
91  char *st_word;      ///< suggested word, allocated string
92  int st_wordlen;     ///< strlen(st_word)
93  int st_orglen;      ///< length of replaced text
94  int st_score;       ///< lower is better
95  int st_altscore;    ///< used when st_score compares equal
96  bool st_salscore;   ///< st_score is for soundalike
97  bool st_had_bonus;  ///< bonus already included in score
98  slang_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 {
118  SCORE_SPLIT = 149,     // split bad word
119  SCORE_SPLIT_NO = 249,  // split bad word with NOSPLITSUGS
120  SCORE_ICASE = 52,      // slightly different case
121  SCORE_REGION = 200,    // word is for different region
122  SCORE_RARE = 180,      // rare word
123  SCORE_SWAP = 75,       // swap two characters
124  SCORE_SWAP3 = 110,     // swap two characters in three
125  SCORE_REP = 65,        // REP replacement
126  SCORE_SUBST = 93,      // substitute a character
127  SCORE_SIMILAR = 33,    // substitute a similar character
128  SCORE_SUBCOMP = 33,    // substitute a composing character
129  SCORE_DEL = 94,        // delete a character
130  SCORE_DELDUP = 66,     // delete a duplicated character
131  SCORE_DELCOMP = 28,    // delete a composing character
132  SCORE_INS = 96,        // insert a character
133  SCORE_INSDUP = 67,     // insert a duplicate character
134  SCORE_INSCOMP = 30,    // insert a composing character
135  SCORE_NONWORD = 103,   // change non-word to word char
136};
137
138enum {
139  SCORE_FILE = 30,      // suggestion from a file
140  SCORE_MAXINIT = 350,  // Initial maximum score: higher == slower.
141                        // 350 allows for about three changes.
142};
143
144enum {
145  SCORE_COMMON1 = 30,  // subtracted for words seen before
146  SCORE_COMMON2 = 40,  // subtracted for words often seen
147  SCORE_COMMON3 = 50,  // subtracted for words very often seen
148  SCORE_THRES2 = 10,   // word count threshold for COMMON2
149  SCORE_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 {
156  SCORE_SFMAX1 = 200,  // maximum score for first try
157  SCORE_SFMAX2 = 300,  // maximum score for second try
158  SCORE_SFMAX3 = 400,  // maximum score for third try
159};
160
161#define SCORE_BIG       (SCORE_INS * 3)  // big difference
162enum {
163  SCORE_MAXMAX = 999999,  // accept any score
164  SCORE_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 {
173  STATE_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.
176  STATE_NOPREFIX,   ///< try without prefix
177  STATE_SPLITUNDO,  ///< Undo splitting.
178  STATE_ENDNUL,     ///< Past NUL bytes at start of the node.
179  STATE_PLAIN,      ///< Use each byte of the node.
180  STATE_DEL,        ///< Delete a byte from the bad word.
181  STATE_INS_PREP,   ///< Prepare for inserting bytes.
182  STATE_INS,        ///< Insert a byte in the bad word.
183  STATE_SWAP,       ///< Swap two bytes.
184  STATE_UNSWAP,     ///< Undo swap two characters.
185  STATE_SWAP3,      ///< Swap two characters over three.
186  STATE_UNSWAP3,    ///< Undo Swap two characters over three.
187  STATE_UNROT3L,    ///< Undo rotate three characters left
188  STATE_UNROT3R,    ///< Undo rotate three characters right
189  STATE_REP_INI,    ///< Prepare for using REP items.
190  STATE_REP,        ///< Use matching REP items from the .aff file.
191  STATE_REP_UNDO,   ///< Undo a REP item replacement.
192  STATE_FINAL,      ///< End of this node.
193} state_T;
194
195/// Struct to keep the state at each level in suggest_try_change().
196typedef struct {
197  state_T ts_state;          ///< state at this level, STATE_
198  int ts_score;              ///< score
199  idx_T ts_arridx;           ///< index in tree array, start of node
200  int16_t ts_curi;           ///< index in list of child nodes
201  uint8_t ts_fidx;           ///< index in fword[], case-folded bad word
202  uint8_t ts_fidxtry;        ///< ts_fidx at which bytes may be changed
203  uint8_t ts_twordlen;       ///< valid length of tword[]
204  uint8_t ts_prefixdepth;    ///< stack depth for end of prefix or
205                             ///< PFD_PREFIXTREE or PFD_NOPREFIX
206  uint8_t ts_flags;          ///< TSF_ flags
207  uint8_t ts_tcharlen;       ///< number of bytes in tword character
208  uint8_t ts_tcharidx;       ///< current byte index in tword character
209  uint8_t ts_isdiff;         ///< DIFF_ values
210  uint8_t ts_fcharstart;     ///< index in fword where badword char started
211  uint8_t ts_prewordlen;     ///< length of word in "preword[]"
212  uint8_t ts_splitoff;       ///< index in "tword" after last split
213  uint8_t ts_splitfidx;      ///< "ts_fidx" at word split
214  uint8_t ts_complen;        ///< nr of compound words used
215  uint8_t ts_compsplit;      ///< index for "compflags" where word was spit
216  uint8_t ts_save_badflags;  ///< su_badflags saved here
217  uint8_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 {
223  DIFF_NONE = 0,    // no different byte (yet)
224  DIFF_YES = 1,     // different byte found
225  DIFF_INSERT = 2,  // inserting character
226};
227
228// values for ts_flags
229enum {
230  TSF_PREFIXOK = 1,  // already checked that prefix is OK
231  TSF_DIDSPLIT = 2,  // tried split at this point
232  TSF_DIDDEL = 4,    // did a delete, "ts_delidx" has index
233};
234
235// special values ts_prefixdepth
236enum {
237  PFD_NOPREFIX = 0xff,    // not using prefixes
238  PFD_PREFIXTREE = 0xfe,  // walking through the prefix tree
239  PFD_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.
253  if (!byte_in_str(sp->ts_complen == sp->ts_compsplit
254                   ? slang->sl_compstartflags : slang->sl_compallflags, flag)) {
255    return 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.
261  if (slang->sl_comprules != NULL && sp->ts_complen > sp->ts_compsplit) {
262    compflags[sp->ts_complen] = (uint8_t)flag;
263    compflags[sp->ts_complen + 1] = NUL;
264    bool v = match_compoundrule(slang, compflags + sp->ts_compsplit);
265    compflags[sp->ts_complen] = NUL;
266    return v;
267  }
268
269  return 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{
277  int bonus;
278
279  hashitem_T *hi = hash_find(&slang->sl_wordcount, word);
280  if (HASHITEM_EMPTY(hi)) {
281    return score;
282  }
283
284  wordcount_T *wc = HI2WC(hi);
285  if (wc->wc_count < SCORE_THRES2) {
286    bonus = SCORE_COMMON1;
287  } else if (wc->wc_count < SCORE_THRES3) {
288    bonus = SCORE_COMMON2;
289  } else {
290    bonus = SCORE_COMMON3;
291  }
292  int newscore = split ? score - bonus / 2
293                       : score - bonus;
294  if (newscore < 0) {
295    return 0;
296  }
297  return 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)
304  FUNC_ATTR_NONNULL_ALL
305{
306  int flags = captype(word, end);
307
308  if (!(flags & WF_KEEPCAP)) {
309    return flags;
310  }
311
312  // Count the number of UPPER and lower case letters.
313  int l = 0;
314  int u = 0;
315  bool first = false;
316  for (char *p = word; p < end; MB_PTR_ADV(p)) {
317    int c = utf_ptr2char(p);
318    if (SPELL_ISUPPER(c)) {
319      u++;
320      if (p == word) {
321        first = true;
322      }
323    } else {
324      l++;
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.
332  if (u > l && u > 2) {
333    flags |= WF_ALLCAP;
334  } else if (first) {
335    flags |= WF_ONECAP;
336  }
337
338  if (u >= 2 && l >= 2) {     // maCARONI maCAroni
339    flags |= WF_MIXCAP;
340  }
341
342  return 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{
351  uint8_t *p = (uint8_t *)(*pp);
352  int nr;
353
354  int c = *p++;
355  if ((c & 0x80) == 0x00) {             // 1 byte
356    nr = c - 1;
357  } else if ((c & 0xc0) == 0x80) {      // 2 bytes
358    nr = (c & 0x3f) - 1;
359    nr = nr * 255 + (*p++ - 1);
360  } else if ((c & 0xe0) == 0xc0) {      // 3 bytes
361    nr = (c & 0x1f) - 1;
362    nr = nr * 255 + (*p++ - 1);
363    nr = nr * 255 + (*p++ - 1);
364  } else {                              // 4 bytes
365    nr = (c & 0x0f) - 1;
366    nr = nr * 255 + (*p++ - 1);
367    nr = nr * 255 + (*p++ - 1);
368    nr = nr * 255 + (*p++ - 1);
369  }
370
371  *pp = (char *)p;
372  return nr;
373}
374
375// values for sps_flags
376enum {
377  SPS_BEST = 1,
378  SPS_FAST = 2,
379  SPS_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{
389  int flags = 0;
390  int limit = 9999;
391
392  const char *key, *val;
393  size_t keylen, vallen;
394  for (const char *p = p_sps; option_next_keyval(&p, &key, &keylen, &val, &vallen);) {
395    int f = 0;
396    if (val == NULL) {
397      // A bare number is the suggestion limit.
398      if (keylen > 0 && ascii_isdigit((uint8_t)(*key))) {
399        char *s = (char *)key;
400        limit = getdigits_int(&s, true, 0);
401        if (s != key + keylen) {  // trailing non-digits
402          f = -1;
403        }
404      } else if (option_slice_eq(key, keylen, "best")) {
405        f = SPS_BEST;
406      } else if (option_slice_eq(key, keylen, "fast")) {
407        f = SPS_FAST;
408      } else if (option_slice_eq(key, keylen, "double")) {
409        f = SPS_DOUBLE;
410      } else {
411        f = -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.
417      const char *v = val;
418      size_t vl = vallen;
419      if (vl > 0 && *v == '-') {
420        v++;
421        vl--;
422      }
423      if (vl == 0 || !ascii_isdigit((uint8_t)(*v))) {
424        f = -1;
425      }
426    } else {
427      f = -1;
428    }
429
430    if (f == -1 || (flags != 0 && f != 0)) {
431      return FAIL;
432    }
433    if (f != 0) {
434      flags = f;
435    }
436  }
437
438  if (flags == 0) {
439    flags = SPS_BEST;
440  }
441  sps_flags = flags;
442  sps_limit = limit;
443
444  return 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{
450  typval_T items_tv;
451  tv_list_alloc_ret(&items_tv, sug->su_ga.ga_len);
452
453  for (int i = 0; i < sug->su_ga.ga_len; i++) {
454    suggest_T *stp = &SUG(sug->su_ga, i);
455
456    dict_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".
460    int el = sug->su_badlen - stp->st_orglen;
461    if (el > 0) {
462      char *word = xmallocz((size_t)stp->st_wordlen + (size_t)el);
463      memcpy(word, stp->st_word, (size_t)stp->st_wordlen);
464      memcpy(word + stp->st_wordlen, sug->su_badptr + stp->st_orglen, (size_t)el);
465      tv_dict_add_allocated_str(d, S_LEN("word"), word);
466    } else {
467      tv_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`.
472    if (sug->su_badlen < stp->st_orglen) {
473      char *extra = xstrnsave(sug->su_badptr, (size_t)stp->st_orglen);
474      tv_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.
479    tv_dict_add_nr(d, S_LEN("score"), stp->st_score);
480    if (sps_flags & (SPS_DOUBLE | SPS_BEST)) {
481      tv_dict_add_nr(d, S_LEN("altscore"), stp->st_altscore);
482      tv_dict_add_bool(d, S_LEN("salscore"),
483                       stp->st_salscore ? kBoolVarTrue : kBoolVarFalse);
484    }
485
486    typval_T item = { .v_type = VAR_DICT, .vval.v_dict = d };
487    tv_list_append_tv(items_tv.vval.v_list, &item);
488  }
489
490  typval_T bad_tv = { .v_type = VAR_STRING,
491                      .vval.v_string = xstrnsave(sug->su_badptr, (size_t)sug->su_badlen) };
492  typval_T lua_args[] = { items_tv, bad_tv, { .v_type = VAR_UNKNOWN } };
493  nlua_call_typval("vim._core.spell", "select_suggest", lua_args, NULL);
494
495  tv_clear(&items_tv);
496  tv_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{
505  int badlen = 0;
506  int msg_scroll_save = msg_scroll;
507  const int wo_spell_save = curwin->w_p_spell;
508
509  if (!curwin->w_p_spell) {
510    parse_spelllang(curwin);
511    curwin->w_p_spell = true;
512  }
513  // Autocommands may have changed the buffer and made the cursor invalid
514  check_cursor(curwin);
515  pos_T prev_cursor = curwin->w_cursor;
516
517  if (*curwin->w_s->b_p_spl == NUL) {
518    emsg(_(e_no_spell));
519    goto skip;
520  }
521
522  if (Visual.active) {
523    // Use the Visually selected text as the bad word.  But reject
524    // a multi-line selection.
525    if (curwin->w_cursor.lnum != Visual.start.lnum) {
526      vim_beep(kOptBoFlagSpell);
527      goto skip;
528    }
529    badlen = (int)curwin->w_cursor.col - (int)Visual.start.col;
530    if (badlen < 0) {
531      badlen = -badlen;
532    } else {
533      curwin->w_cursor.col = Visual.start.col;
534    }
535    badlen++;
536    end_visual_mode();
537    // make sure we don't include the NUL at the end of the line
538    badlen = 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.
544    curwin->w_cursor = prev_cursor;
545    char *curline = get_cursor_line_ptr();
546    char *p = curline + curwin->w_cursor.col;
547    // Backup to before start of word.
548    while (p > curline && spell_iswordp_nmw(p, curwin)) {
549      MB_PTR_BACK(curline, p);
550    }
551    // Forward to start of word.
552    while (*p != NUL && !spell_iswordp_nmw(p, curwin)) {
553      MB_PTR_ADV(p);
554    }
555
556    if (!spell_iswordp_nmw(p, curwin)) {                // No word found.
557      beep_flush();
558      goto skip;
559    }
560    curwin->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.
566  int 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.
569  char *line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len());
570  spell_suggest_timeout = 5000;
571
572  // Get the list of suggestions.  Limit to 'lines' - 2 or the number in
573  // 'spellsuggest', whatever is smaller.
574  suginfo_T sug;
575  int limit = MIN(sps_limit, Rows - 2);
576  spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
577                     true, need_cap, true);
578
579  int selected = count;
580  if (GA_EMPTY(&sug.su_ga)) {
581    msg_ext_set_kind("wmsg");
582    msg(_("No suggestions"), 0);
583  } else if (count > 0) {
584    if (count > sug.su_ga.ga_len) {
585      msg_ext_set_kind("wmsg");
586      smsg(0, _("Only %" PRId64 " suggestions"), (int64_t)sug.su_ga.ga_len);
587    }
588  } else {
589    // Hand off to (async) vim.ui.select().
590    curwin->w_p_spell = wo_spell_save;
591    select_spell_suggestion(&sug);
592
593    lines_left = Rows;                  // avoid more prompt
594    // don't delay for 'smd' in normal_cmd()
595    msg_scroll = msg_scroll_save;
596
597    spell_find_cleanup(&sug);
598    xfree(line);
599    return;
600  }
601
602  if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK) {
603    // Save the from and to text for :spellrepall.
604    XFREE_CLEAR(repl_from);
605    XFREE_CLEAR(repl_to);
606
607    suggest_T *stp = &SUG(sug.su_ga, selected - 1);
608    if (sug.su_badlen > stp->st_orglen) {
609      // Replacing less than "su_badlen", append the remainder to
610      // repl_to.
611      repl_from = xstrnsave(sug.su_badptr, (size_t)sug.su_badlen);
612      vim_snprintf(IObuff, IOSIZE, "%s%.*s", stp->st_word,
613                   sug.su_badlen - stp->st_orglen,
614                   sug.su_badptr + stp->st_orglen);
615      repl_to = xstrdup(IObuff);
616    } else {
617      // Replacing su_badlen or more, use the whole word.
618      repl_from = xstrnsave(sug.su_badptr, (size_t)stp->st_orglen);
619      repl_to = xstrdup(stp->st_word);
620    }
621
622    // Replace the word.
623    char *p = xmalloc(strlen(line) - (size_t)stp->st_orglen + (size_t)stp->st_wordlen + 1);
624    int c = (int)(sug.su_badptr - line);
625    memmove(p, line, (size_t)c);
626    STRCPY(p + c, stp->st_word);
627    strcat(p, sug.su_badptr + stp->st_orglen);
628
629    // For redo we use a change-word command.
630    prep_redo(false, false, (CmdSpec){ .op = 'c', .cmd = 'i', .cmd2 = 'w' });
631    redo_append_lit(p + c, stp->st_wordlen + sug.su_badlen - stp->st_orglen);
632    redo_append_char(ESC);
633
634    // "p" may be freed here
635    ml_replace(curwin->w_cursor.lnum, p, false);
636    curwin->w_cursor.col = c;
637
638    inserted_bytes(curwin->w_cursor.lnum, c, stp->st_orglen, stp->st_wordlen);
639  } else {
640    curwin->w_cursor = prev_cursor;
641  }
642
643  spell_find_cleanup(&sug);
644  xfree(line);
645skip:
646  curwin->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{
656  suginfo_T sug;
657
658  spell_find_suggest(word, 0, &sug, maxcount, false, need_cap, interactive);
659
660  // Make room in "gap".
661  ga_init(gap, sizeof(char *), sug.su_ga.ga_len + 1);
662  ga_grow(gap, sug.su_ga.ga_len);
663  for (int i = 0; i < sug.su_ga.ga_len; i++) {
664    suggest_T *stp = &SUG(sug.su_ga, i);
665
666    // The suggested word may replace only part of "word", add the not
667    // replaced part.
668    char *wcopy = xmalloc((size_t)stp->st_wordlen + strlen(sug.su_badptr + stp->st_orglen) + 1);
669    STRCPY(wcopy, stp->st_word);
670    STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen);
671    ((char **)gap->ga_data)[gap->ga_len++] = wcopy;
672  }
673
674  spell_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,
687                               bool banbadword, bool need_cap, bool interactive)
688{
689  hlf_T attr = HLF_COUNT;
690  char buf[MAXPATHL];
691  bool do_combine = false;
692  static bool expr_busy = false;
693  bool did_intern = false;
694
695  // Set the info in "*su".
696  CLEAR_POINTER(su);
697  ga_init(&su->su_ga, (int)sizeof(suggest_T), 10);
698  ga_init(&su->su_sga, (int)sizeof(suggest_T), 10);
699  if (*badptr == NUL) {
700    return;
701  }
702  hash_init(&su->su_banned);
703
704  su->su_badptr = badptr;
705  if (badlen != 0) {
706    su->su_badlen = badlen;
707  } else {
708    size_t tmplen = spell_check(curwin, su->su_badptr, &attr, NULL, false);
709    assert(tmplen <= INT_MAX);
710    su->su_badlen = (int)tmplen;
711  }
712  su->su_maxcount = maxcount;
713  su->su_maxscore = SCORE_MAXINIT;
714  su->su_badlen = MIN(su->su_badlen, MAXWLEN - 1);  // just in case
715  xmemcpyz(su->su_badword, su->su_badptr, (size_t)su->su_badlen);
716  spell_casefold(curwin, su->su_badptr, su->su_badlen, su->su_fbadword,
717                 MAXWLEN);
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.
722  su->su_fbadword[su->su_badlen] = NUL;
723
724  // get caps flags for bad word
725  su->su_badflags = badword_captype(su->su_badptr,
726                                    su->su_badptr + su->su_badlen);
727  if (need_cap) {
728    su->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").
735  for (int i = 0; i < curbuf->b_s.b_langp.ga_len; i++) {
736    langp_T *lp = LANGP_ENTRY(curbuf->b_s.b_langp, i);
737    if (lp->lp_sallang != NULL) {
738      su->su_sallang = lp->lp_sallang;
739      break;
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.
745  if (su->su_sallang != NULL) {
746    spell_soundfold(su->su_sallang, su->su_fbadword, true,
747                    su->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.
753  int c = utf_ptr2char(su->su_badptr);
754  if (!SPELL_ISUPPER(c) && attr == HLF_COUNT) {
755    make_case_word(su->su_badword, buf, WF_ONECAP);
756    add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE,
757                   0, true, su->su_sallang, false);
758  }
759
760  // Ban the bad word itself.  It may appear in another region.
761  if (banbadword) {
762    add_banned(su, su->su_badword);
763  }
764
765  // Make a copy of 'spellsuggest', because the expression may change it.
766  char *sps_copy = xstrdup(p_sps);
767
768  // Loop over the items in 'spellsuggest'.
769  for (char *p = sps_copy; *p != NUL;) {
770    copy_option_part(&p, buf, MAXPATHL, ",");
771
772    if (strncmp(buf, "expr:", 5) == 0) {
773      // Evaluate an expression.  Skip this when called recursively,
774      // when using spellsuggest() in the expression.
775      if (!expr_busy) {
776        expr_busy = true;
777        spell_suggest_expr(su, buf + 5);
778        expr_busy = false;
779      }
780    } else if (strncmp(buf, "file:", 5) == 0) {
781      // Use list of suggestions in a file.
782      spell_suggest_file(su, buf + 5);
783    } else if (strncmp(buf, "timeout:", 8) == 0) {
784      // Limit the time searching for suggestions.
785      spell_suggest_timeout = atoi(buf + 8);
786    } else if (!did_intern) {
787      // Use internal method once.
788      spell_suggest_intern(su, interactive);
789      if (sps_flags & SPS_DOUBLE) {
790        do_combine = true;
791      }
792      did_intern = true;
793    }
794  }
795
796  xfree(sps_copy);
797
798  if (do_combine) {
799    // Combine the two list of suggestions.  This must be done last,
800    // because sorting changes the order again.
801    score_combine(su);
802  }
803}
804
805/// Find suggestions by evaluating expression "expr".
806static void spell_suggest_expr(suginfo_T *su, char *expr)
807{
808  const 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.
813  list_T *const list = eval_spell_expr(su->su_badword, expr);
814  if (list != NULL) {
815    // Loop over the items in the list.
816    TV_LIST_ITER(list, li, {
817      if (TV_LIST_ITEM_TV(li)->v_type == VAR_LIST) {
818        // Get the word and the score from the items.
819        int score = get_spellword(TV_LIST_ITEM_TV(li)->vval.v_list, &p);
820        if (score >= 0 && score <= su->su_maxscore) {
821          add_suggestion(su, &su->su_ga, p, su->su_badlen,
822                         score, 0, true, su->su_sallang, false);
823        }
824      }
825    });
826    tv_list_unref(list);
827  }
828
829  // Remove bogus suggestions, sort and truncate at "maxcount".
830  check_suggestions(su, &su->su_ga);
831  cleanup_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{
837  char line[MAXWLEN * 2];
838  int len;
839  char cword[MAXWLEN];
840
841  // Open the file.
842  FILE *fd = os_fopen(fname, "r");
843  if (fd == NULL) {
844    semsg(_(e_notopen), fname);
845    return;
846  }
847
848  // Read it line by line.
849  while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int) {
850    line_breakcheck();
851
852    char *p = vim_strchr(line, '/');
853    if (p == NULL) {
854      continue;             // No Tab found, just skip the line.
855    }
856    *p++ = NUL;
857    if (STRICMP(su->su_badword, line) == 0) {
858      // Match!  Isolate the good word, until CR or NL.
859      for (len = 0; (uint8_t)p[len] >= ' '; len++) {}
860      p[len] = NUL;
861
862      // If the suggestion doesn't have specific case duplicate the case
863      // of the bad word.
864      if (captype(p, NULL) == 0) {
865        make_case_word(p, cword, su->su_badflags);
866        p = cword;
867      }
868
869      add_suggestion(su, &su->su_ga, p, su->su_badlen,
870                     SCORE_FILE, 0, true, su->su_sallang, false);
871    }
872  }
873
874  fclose(fd);
875
876  // Remove bogus suggestions, sort and truncate at "maxcount".
877  check_suggestions(su, &su->su_ga);
878  cleanup_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.
885  suggest_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.
891  suggest_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).
895  suggest_try_change(su);
896
897  // For the resulting top-scorers compute the sound-a-like score.
898  if (sps_flags & SPS_DOUBLE) {
899    score_comp_sal(su);
900  }
901
902  // 3. Try finding sound-a-like words.
903  if ((sps_flags & SPS_FAST) == 0) {
904    if (sps_flags & SPS_BEST) {
905      // Adjust the word score for the suggestions found so far for how
906      // they sounds like.
907      rescore_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.
918    suggest_try_soundalike_prep();
919    su->su_maxscore = SCORE_SFMAX1;
920    su->su_sfmaxscore = SCORE_MAXINIT * 3;
921    suggest_try_soundalike(su);
922    if (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.
925      su->su_maxscore = SCORE_SFMAX2;
926      suggest_try_soundalike(su);
927      if (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.
930        su->su_maxscore = SCORE_SFMAX3;
931        suggest_try_soundalike(su);
932      }
933    }
934    su->su_maxscore = su->su_sfmaxscore;
935    suggest_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().
940  os_breakcheck();
941  if (interactive && got_int) {
942    vgetc();
943    got_int = false;
944  }
945
946  if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0) {
947    if (sps_flags & SPS_BEST) {
948      // Adjust the word score for how it sounds like.
949      rescore_suggestions(su);
950    }
951
952    // Remove bogus suggestions, sort and truncate at "maxcount".
953    check_suggestions(su, &su->su_ga);
954    cleanup_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.
963  GA_DEEP_CLEAR(&su->su_ga, suggest_T, FREE_SUG_WORD);
964  GA_DEEP_CLEAR(&su->su_sga, suggest_T, FREE_SUG_WORD);
965
966  // Free the banned words.
967  hash_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{
973  char word[MAXWLEN];
974
975  // Recognize a word that is repeated: "the the".
976  char *p = skiptowhite(su->su_fbadword);
977  size_t len = (size_t)(p - su->su_fbadword);
978  p = skipwhite(p);
979  if (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".
982    char c = su->su_fbadword[len];
983    su->su_fbadword[len] = NUL;
984    make_case_word(su->su_fbadword, word, su->su_badflags);
985    su->su_fbadword[len] = c;
986
987    // Give a soundalike score of 0, compute the score as if deleting one
988    // character.
989    add_suggestion(su, &su->su_ga, word, su->su_badlen,
990                   RESCORE(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{
1005  for (int i = 0; i <= STATE_FINAL; i++) {
1006    profile_zero(&times[i]);
1007    counts[i] = 0;
1008  }
1009  profile_start(&current);
1010  profile_start(&total);
1011}
1012
1013/// call before changing state
1014static void prof_store(state_T state)
1015{
1016  profile_end(&current);
1017  profile_add(&times[state], &current);
1018  counts[state]++;
1019  profile_start(&current);
1020}
1021# define PROF_STORE(state) prof_store(state);
1022
1023static void prof_report(char *name)
1024{
1025  FILE *fd = fopen("suggestprof", "a");
1026
1027  profile_end(&total);
1028  fprintf(fd, "-----------------------\n");
1029  fprintf(fd, "%s: %s\n", name, profile_msg(&total));
1030  for (int i = 0; i <= STATE_FINAL; i++) {
1031    fprintf(fd, "%d: %s ("%" PRId64)\n", i, profile_msg(&times[i]), counts[i]);
1032  }
1033  fclose(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{
1042  char 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.
1047  STRCPY(fword, su->su_fbadword);
1048  int n = (int)strlen(fword);
1049  char *p = su->su_badptr + su->su_badlen;
1050  spell_casefold(curwin, p, (int)strlen(p), fword + n, MAXWLEN - n);
1051
1052  // Make sure the resulting text is not longer than the original text.
1053  n = (int)strlen(su->su_badptr);
1054  if (n < MAXWLEN) {
1055    fword[n] = NUL;
1056  }
1057
1058  for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
1059    langp_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.
1063    if (lp->lp_slang->sl_fbyts == NULL) {
1064      continue;
1065    }
1066
1067    // Try it for this language.  Will add possible suggestions.
1068#ifdef SUGGEST_PROFILE
1069    prof_init();
1070#endif
1071    suggest_trie_walk(su, lp, fword, false);
1072#ifdef SUGGEST_PROFILE
1073    prof_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{
1113  char tword[MAXWLEN];            // good word collected so far
1114  trystate_T stack[MAXWLEN];
1115  char 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.
1120  uint8_t compflags[MAXWLEN];        // compound flags, one for each word
1121  uint8_t *byts, *fbyts, *pbyts;
1122  idx_T *idxs, *fidxs, *pidxs;
1123  int c, c2, c3;
1124  int n = 0;
1125  idx_T arridx;
1126  int fl = 0;
1127  int tl;
1128  int repextra = 0;                 // extra bytes in fword[] from REP item
1129  slang_T *slang = lp->lp_slang;
1130  bool goodword_ends;
1131#ifdef DEBUG_TRIEWALK
1132  // Stores the name of the change made at each level.
1133  uint8_t changename[MAXWLEN][80];
1134#endif
1135  int 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).
1141  int depth = 0;
1142  trystate_T *sp = &stack[0];
1143  CLEAR_POINTER(sp);
1144  sp->ts_curi = 1;
1145
1146  if (soundfold) {
1147    // Going through the soundfold tree.
1148    byts = fbyts = slang->sl_sbyts;
1149    idxs = fidxs = slang->sl_sidxs;
1150    pbyts = NULL;
1151    pidxs = NULL;
1152    sp->ts_prefixdepth = PFD_NOPREFIX;
1153    sp->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.
1157    fbyts = slang->sl_fbyts;
1158    fidxs = slang->sl_fidxs;
1159    pbyts = slang->sl_pbyts;
1160    pidxs = slang->sl_pidxs;
1161    if (pbyts != NULL) {
1162      byts = pbyts;
1163      idxs = pidxs;
1164      sp->ts_prefixdepth = PFD_PREFIXTREE;
1165      sp->ts_state = STATE_NOPREFIX;            // try without prefix first
1166    } else {
1167      byts = fbyts;
1168      idxs = fidxs;
1169      sp->ts_prefixdepth = PFD_NOPREFIX;
1170      sp->ts_state = STATE_START;
1171    }
1172  }
1173
1174  // The loop may take an indefinite amount of time. Break out after some
1175  // time.
1176  proftime_T time_limit = 0;
1177  if (spell_suggest_timeout > 0) {
1178    time_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".
1186  while (depth >= 0 && !got_int) {
1187    sp = &stack[depth];
1188    switch (sp->ts_state) {
1189    case STATE_START:
1190    case STATE_NOPREFIX:
1191      // Start of node: Deal with NUL bytes, which means
1192      // tword[] may end here.
1193      arridx = sp->ts_arridx;               // current node in the tree
1194      int len = byts[arridx];                   // bytes in this node
1195      arridx += sp->ts_curi;                // index of current byte
1196
1197      if (sp->ts_prefixdepth == PFD_PREFIXTREE) {
1198        // Skip over the NUL bytes, we use them later.
1199        for (n = 0; n < len && byts[arridx + n] == 0; n++) {}
1200        sp->ts_curi = (int16_t)(sp->ts_curi + n);
1201
1202        // Always past NUL bytes now.
1203        n = (int)sp->ts_state;
1204        PROF_STORE(sp->ts_state)
1205        sp->ts_state = STATE_ENDNUL;
1206        sp->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.
1210        if (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.
1213          n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
1214          int flags = badword_captype(su->su_badptr, su->su_badptr + n);
1215          su->su_badflags = badword_captype(su->su_badptr + n,
1216                                            su->su_badptr + su->su_badlen);
1217#ifdef DEBUG_TRIEWALK
1218          sprintf(changename[depth], "prefix");  // NOLINT(runtime/printf)
1219#endif
1220          go_deeper(stack, depth, 0);
1221          depth++;
1222          sp = &stack[depth];
1223          sp->ts_prefixdepth = (uint8_t)(depth - 1);
1224          byts = fbyts;
1225          idxs = fidxs;
1226          sp->ts_arridx = 0;
1227
1228          // Move the prefix to preword[] with the right case
1229          // and make find_keepcap_word() works.
1230          tword[sp->ts_twordlen] = NUL;
1231          make_case_word(tword + sp->ts_splitoff,
1232                         preword + sp->ts_prewordlen, flags);
1233          sp->ts_prewordlen = (uint8_t)strlen(preword);
1234          sp->ts_splitoff = sp->ts_twordlen;
1235        }
1236        break;
1237      }
1238
1239      if (sp->ts_curi > len || byts[arridx] != 0) {
1240        // Past bytes in node and/or past NUL bytes.
1241        PROF_STORE(sp->ts_state)
1242        sp->ts_state = STATE_ENDNUL;
1243        sp->ts_save_badflags = (uint8_t)su->su_badflags;
1244        break;
1245      }
1246
1247      // End of word in tree.
1248      sp->ts_curi++;                    // eat one NUL byte
1249
1250      int flags = (int)idxs[arridx];
1251
1252      // Skip words with the NOSUGGEST flag.
1253      if (flags & WF_NOSUGGEST) {
1254        break;
1255      }
1256
1257      bool fword_ends = (fword[sp->ts_fidx] == NUL
1258                         || (soundfold
1259                             ? ascii_iswhite(fword[sp->ts_fidx])
1260                             : !spell_iswordp(fword + sp->ts_fidx, curwin)));
1261      tword[sp->ts_twordlen] = NUL;
1262
1263      if (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.
1270        n = stack[sp->ts_prefixdepth].ts_arridx;
1271        len = pbyts[n++];
1272        for (c = 0; c < len && pbyts[n + c] == 0; c++) {}
1273        if (c > 0) {
1274          c = valid_word_prefix(c, n, flags,
1275                                tword + sp->ts_splitoff, slang, false);
1276          if (c == 0) {
1277            break;
1278          }
1279
1280          // Use the WF_RARE flag for a rare prefix.
1281          if (c & WF_RAREPFX) {
1282            flags |= 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.
1289          sp->ts_flags |= TSF_PREFIXOK;
1290        }
1291      }
1292
1293      // Check NEEDCOMPOUND: can't use word without compounding.  Do try
1294      // appending another compound word below.
1295      if (sp->ts_complen == sp->ts_compsplit && fword_ends
1296          && (flags & WF_NEEDCOMP)) {
1297        goodword_ends = false;
1298      } else {
1299        goodword_ends = true;
1300      }
1301
1302      char *p = NULL;
1303      bool compound_ok = true;
1304      if (sp->ts_complen > sp->ts_compsplit) {
1305        if (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.
1310          if (sp->ts_fidx - sp->ts_splitfidx
1311              == sp->ts_twordlen - sp->ts_splitoff
1312              && strncmp(fword + sp->ts_splitfidx,
1313                         tword + sp->ts_splitoff,
1314                         (size_t)(sp->ts_fidx - sp->ts_splitfidx)) == 0) {
1315            preword[sp->ts_prewordlen] = NUL;
1316            int newscore = score_wordcount_adj(slang, sp->ts_score,
1317                                               preword + sp->ts_prewordlen,
1318                                               sp->ts_prewordlen > 0);
1319            // Add the suggestion if the score isn't too bad.
1320            if (newscore <= su->su_maxscore) {
1321              add_suggestion(su, &su->su_ga, preword,
1322                             sp->ts_splitfidx - repextra,
1323                             newscore, 0, false,
1324                             lp->lp_sallang, false);
1325            }
1326            break;
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).
1333          if (((unsigned)flags >> 24) == 0
1334              || sp->ts_twordlen - sp->ts_splitoff
1335              < slang->sl_compminlen) {
1336            break;
1337          }
1338          // For multi-byte chars check character length against
1339          // COMPOUNDMIN.
1340          if (slang->sl_compminlen > 0
1341              && mb_charlen(tword + sp->ts_splitoff)
1342              < slang->sl_compminlen) {
1343            break;
1344          }
1345
1346          compflags[sp->ts_complen] = (uint8_t)((unsigned)flags >> 24);
1347          compflags[sp->ts_complen + 1] = NUL;
1348          xmemcpyz(preword + sp->ts_prewordlen,
1349                   tword + sp->ts_splitoff,
1350                   (size_t)(sp->ts_twordlen - sp->ts_splitoff));
1351
1352          // Verify CHECKCOMPOUNDPATTERN  rules.
1353          if (match_checkcompoundpattern(preword,  sp->ts_prewordlen,
1354                                         &slang->sl_comppat)) {
1355            compound_ok = false;
1356          }
1357
1358          if (compound_ok) {
1359            p = preword;
1360            while (*skiptowhite(p) != NUL) {
1361              p = skipwhite(skiptowhite(p));
1362            }
1363            if (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.
1366              compound_ok = false;
1367            }
1368          }
1369
1370          // Get pointer to last char of previous word.
1371          p = preword + sp->ts_prewordlen;
1372          MB_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.
1379      if (soundfold) {
1380        STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
1381      } else if (flags & WF_KEEPCAP) {
1382        // Must find the word in the keep-case tree.
1383        find_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.
1388        c = su->su_badflags;
1389        if ((c & WF_ALLCAP) && su->su_badlen == utfc_ptr2len(su->su_badptr)) {
1390          c = WF_ONECAP;
1391        }
1392        c |= flags;
1393
1394        // When appending a compound word after a word character don't
1395        // use Onecap.
1396        if (p != NULL && spell_iswordp_nmw(p, curwin)) {
1397          c &= ~WF_ONECAP;
1398        }
1399        make_case_word(tword + sp->ts_splitoff,
1400                       preword + sp->ts_prewordlen, c);
1401      }
1402
1403      if (!soundfold) {
1404        // Don't use a banned word.  It may appear again as a good
1405        // word, thus remember it.
1406        if (flags & WF_BANNED) {
1407          add_banned(su, preword + sp->ts_prewordlen);
1408          break;
1409        }
1410        if ((sp->ts_complen == sp->ts_compsplit
1411             && WAS_BANNED(su, preword + sp->ts_prewordlen))
1412            || WAS_BANNED(su, preword)) {
1413          if (slang->sl_compprog == NULL) {
1414            break;
1415          }
1416          // the word so far was banned but we may try compounding
1417          goodword_ends = false;
1418        }
1419      }
1420
1421      int newscore = 0;
1422      if (!soundfold) {         // soundfold words don't have flags
1423        if ((flags & WF_REGION)
1424            && (((unsigned)flags >> 16) & (unsigned)lp->lp_region) == 0) {
1425          newscore += SCORE_REGION;
1426        }
1427        if (flags & WF_RARE) {
1428          newscore += SCORE_RARE;
1429        }
1430
1431        if (!spell_valid_case(su->su_badflags,
1432                              captype(preword + sp->ts_prewordlen, NULL))) {
1433          newscore += SCORE_ICASE;
1434        }
1435      }
1436
1437      // TODO(vim): how about splitting in the soundfold tree?
1438      if (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
1444        if (soundfold && strcmp(preword, "smwrd") == 0) {
1445          int j;
1446
1447          // print the stack of changes that brought us here
1448          smsg(0, "------ %s -------", fword);
1449          for (j = 0; j < depth; j++) {
1450            smsg(0, "%s", changename[j]);
1451          }
1452        }
1453#endif
1454        if (soundfold) {
1455          // For soundfolded words we need to find the original
1456          // words, the edit distance and then add them.
1457          add_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".
1461          p = fword + sp->ts_fidx;
1462          MB_PTR_BACK(fword, p);
1463          if (!spell_iswordp(p, curwin) && *preword != NUL) {
1464            p = preword + strlen(preword);
1465            MB_PTR_BACK(preword, p);
1466            if (spell_iswordp(p, curwin)) {
1467              newscore += SCORE_NONWORD;
1468            }
1469          }
1470
1471          // Give a bonus to words seen before.
1472          int score = score_wordcount_adj(slang,
1473                                          sp->ts_score + newscore,
1474                                          preword + sp->ts_prewordlen,
1475                                          sp->ts_prewordlen > 0);
1476
1477          // Add the suggestion if the score isn't too bad.
1478          if (score <= su->su_maxscore) {
1479            add_suggestion(su, &su->su_ga, preword,
1480                           sp->ts_fidx - repextra,
1481                           score, 0, false, lp->lp_sallang, false);
1482
1483            if (su->su_badflags & WF_MIXCAP) {
1484              // We really don't know if the word should be
1485              // upper or lower case, add both.
1486              c = captype(preword, NULL);
1487              if (c == 0 || c == WF_ALLCAP) {
1488                make_case_word(tword + sp->ts_splitoff,
1489                               preword + sp->ts_prewordlen,
1490                               c == 0 ? WF_ALLCAP : 0);
1491
1492                add_suggestion(su, &su->su_ga, preword,
1493                               sp->ts_fidx - repextra,
1494                               score + SCORE_ICASE, 0, false,
1495                               lp->lp_sallang, false);
1496              }
1497            }
1498          }
1499        }
1500      }
1501
1502      // Try word split and/or compounding.
1503      if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
1504          // Don't split in the middle of a character
1505          && (sp->ts_tcharlen == 0)) {
1506        bool try_compound;
1507        int 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
1514        try_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.
1529        try_compound = false;
1530        if (!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)))) {
1543          try_compound = true;
1544          compflags[sp->ts_complen] = (uint8_t)((unsigned)flags >> 24);
1545          compflags[sp->ts_complen + 1] = NUL;
1546        }
1547
1548        // For NOBREAK we never try splitting, it won't make any word
1549        // valid.
1550        if (slang->sl_nobreak && !slang->sl_nocompoundsugs) {
1551          try_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.
1558          try_compound = false;
1559          sp->ts_flags |= TSF_DIDSPLIT;
1560          sp->ts_curi--;                    // do the same NUL again
1561          compflags[sp->ts_complen] = NUL;
1562        } else {
1563          sp->ts_flags &= (uint8_t) ~TSF_DIDSPLIT;
1564        }
1565
1566        if (try_split || try_compound) {
1567          if (!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.
1572            if (sp->ts_complen == sp->ts_compsplit
1573                && (flags & WF_NEEDCOMP)) {
1574              break;
1575            }
1576            p = preword;
1577            while (*skiptowhite(p) != NUL) {
1578              p = skipwhite(skiptowhite(p));
1579            }
1580            if (sp->ts_complen > sp->ts_compsplit
1581                && !can_compound(slang, p, compflags + sp->ts_compsplit)) {
1582              break;
1583            }
1584
1585            if (slang->sl_nosplitsugs) {
1586              newscore += SCORE_SPLIT_NO;
1587            } else {
1588              newscore += SCORE_SPLIT;
1589            }
1590
1591            // Give a bonus to words seen before.
1592            newscore = score_wordcount_adj(slang, newscore,
1593                                           preword + sp->ts_prewordlen, true);
1594          }
1595
1596          if (TRY_DEEPER(su, stack, depth, newscore)) {
1597            go_deeper(stack, depth, newscore);
1598#ifdef DEBUG_TRIEWALK
1599            if (!try_compound && !fword_ends) {
1600              sprintf(changename[depth], "%.*s-%s: split",  // NOLINT(runtime/printf)
1601                      sp->ts_twordlen, tword, fword + sp->ts_fidx);
1602            } else {
1603              sprintf(changename[depth], "%.*s-%s: compound",  // NOLINT(runtime/printf)
1604                      sp->ts_twordlen, tword, fword + sp->ts_fidx);
1605            }
1606#endif
1607            // Save things to be restored at STATE_SPLITUNDO.
1608            sp->ts_save_badflags = (uint8_t)su->su_badflags;
1609            PROF_STORE(sp->ts_state)
1610            sp->ts_state = STATE_SPLITUNDO;
1611
1612            depth++;
1613            sp = &stack[depth];
1614
1615            // Append a space to preword when splitting.
1616            if (!try_compound && !fword_ends) {
1617              strcat(preword, " ");
1618            }
1619            sp->ts_prewordlen = (uint8_t)strlen(preword);
1620            sp->ts_splitoff = sp->ts_twordlen;
1621            sp->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.
1628            if (((!try_compound && !spell_iswordp_nmw(fword
1629                                                      + sp->ts_fidx,
1630                                                      curwin))
1631                 || fword_ends)
1632                && fword[sp->ts_fidx] != NUL
1633                && goodword_ends) {
1634              int l;
1635
1636              l = utfc_ptr2len(fword + sp->ts_fidx);
1637              if (fword_ends) {
1638                // Copy the skipped character to preword.
1639                memmove(preword + sp->ts_prewordlen, fword + sp->ts_fidx, (size_t)l);
1640                sp->ts_prewordlen = (uint8_t)(sp->ts_prewordlen + l);
1641                preword[sp->ts_prewordlen] = NUL;
1642              } else {
1643                sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
1644              }
1645              sp->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.
1651            if (try_compound) {
1652              sp->ts_complen++;
1653            } else {
1654              sp->ts_compsplit = sp->ts_complen;
1655            }
1656            sp->ts_prefixdepth = PFD_NOPREFIX;
1657
1658            // set su->su_badflags to the caps type at this
1659            // position
1660            n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
1661            su->su_badflags = badword_captype(su->su_badptr + n,
1662                                              su->su_badptr + su->su_badlen);
1663
1664            // Restart at top of the tree.
1665            sp->ts_arridx = 0;
1666
1667            // If there are postponed prefixes, try these too.
1668            if (pbyts != NULL) {
1669              byts = pbyts;
1670              idxs = pidxs;
1671              sp->ts_prefixdepth = PFD_PREFIXTREE;
1672              PROF_STORE(sp->ts_state)
1673              sp->ts_state = STATE_NOPREFIX;
1674            }
1675          }
1676        }
1677      }
1678      break;
1679
1680    case STATE_SPLITUNDO:
1681      // Undo the changes done for word split or compound word.
1682      su->su_badflags = sp->ts_save_badflags;
1683
1684      // Continue looking for NUL bytes.
1685      PROF_STORE(sp->ts_state)
1686      sp->ts_state = STATE_START;
1687
1688      // In case we went into the prefix tree.
1689      byts = fbyts;
1690      idxs = fidxs;
1691      break;
1692
1693    case STATE_ENDNUL:
1694      // Past the NUL bytes in the node.
1695      su->su_badflags = sp->ts_save_badflags;
1696      if (fword[sp->ts_fidx] == NUL
1697          && sp->ts_tcharlen == 0) {
1698        // The badword ends, can't use STATE_PLAIN.
1699        PROF_STORE(sp->ts_state)
1700        sp->ts_state = STATE_DEL;
1701        break;
1702      }
1703      PROF_STORE(sp->ts_state)
1704      sp->ts_state = STATE_PLAIN;
1705      FALLTHROUGH;
1706
1707    case 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.
1710      arridx = sp->ts_arridx;
1711      if (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.
1714        PROF_STORE(sp->ts_state)
1715        sp->ts_state = sp->ts_fidx >= sp->ts_fidxtry ? STATE_DEL
1716                                                     : STATE_FINAL;
1717      } else {
1718        arridx += sp->ts_curi++;
1719        c = 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.
1726        if (c == (uint8_t)fword[sp->ts_fidx]
1727            || (sp->ts_tcharlen > 0
1728                && sp->ts_isdiff != DIFF_NONE)) {
1729          newscore = 0;
1730        } else {
1731          newscore = SCORE_SUBST;
1732        }
1733        if ((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)) {
1738          go_deeper(stack, depth, newscore);
1739#ifdef DEBUG_TRIEWALK
1740          if (newscore > 0) {
1741            sprintf(changename[depth], "%.*s-%s: subst %c to %c",  // NOLINT(runtime/printf)
1742                    sp->ts_twordlen, tword, fword + sp->ts_fidx,
1743                    fword[sp->ts_fidx], c);
1744          } else {
1745            sprintf(changename[depth], "%.*s-%s: accept %c",  // NOLINT(runtime/printf)
1746                    sp->ts_twordlen, tword, fword + sp->ts_fidx,
1747                    fword[sp->ts_fidx]);
1748          }
1749#endif
1750          depth++;
1751          sp = &stack[depth];
1752          if (fword[sp->ts_fidx] != NUL) {
1753            sp->ts_fidx++;
1754          }
1755          tword[sp->ts_twordlen++] = (char)c;
1756          sp->ts_arridx = idxs[arridx];
1757          if (newscore == SCORE_SUBST) {
1758            sp->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.
1763          if (sp->ts_tcharlen == 0) {
1764            // First byte.
1765            sp->ts_tcharidx = 0;
1766            sp->ts_tcharlen = MB_BYTE2LEN(c);
1767            sp->ts_fcharstart = (uint8_t)(sp->ts_fidx - 1);
1768            sp->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.
1773            sp->ts_fidx--;
1774          }
1775          if (++sp->ts_tcharidx == sp->ts_tcharlen) {
1776            // Last byte of character.
1777            if (sp->ts_isdiff == DIFF_YES) {
1778              // Correct ts_fidx for the byte length of the
1779              // character (we didn't check that before).
1780              sp->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.
1786              if (utf_iscomposing_legacy(utf_ptr2char(tword + sp->ts_twordlen - sp->ts_tcharlen))
1787                  && utf_iscomposing_legacy(utf_ptr2char(fword + sp->ts_fcharstart))) {
1788                sp->ts_score -= SCORE_SUBST - SCORE_SUBCOMP;
1789              } else if (!soundfold
1790                         && slang->sl_has_map
1791                         && similar_chars(slang,
1792                                          utf_ptr2char(tword + sp->ts_twordlen -
1793                                                       sp->ts_tcharlen),
1794                                          utf_ptr2char(fword + sp->ts_fcharstart))) {
1795                // For a similar character adjust score from
1796                // SCORE_SUBST to SCORE_SIMILAR.
1797                sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
1798              }
1799            } else if (sp->ts_isdiff == DIFF_INSERT
1800                       && sp->ts_twordlen > sp->ts_tcharlen) {
1801              p = tword + sp->ts_twordlen - sp->ts_tcharlen;
1802              c = utf_ptr2char(p);
1803              if (utf_iscomposing_legacy(c)) {
1804                // Inserting a composing char doesn't
1805                // count that much.
1806                sp->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).
1813                MB_PTR_BACK(tword, p);
1814                if (c == utf_ptr2char(p)) {
1815                  sp->ts_score -= SCORE_INS - SCORE_INSDUP;
1816                }
1817              }
1818            }
1819
1820            // Starting a new char, reset the length.
1821            sp->ts_tcharlen = 0;
1822          }
1823        }
1824      }
1825      break;
1826
1827    case STATE_DEL:
1828      // When past the first byte of a multi-byte char don't try
1829      // delete/insert/swap a character.
1830      if (sp->ts_tcharlen > 0) {
1831        PROF_STORE(sp->ts_state)
1832        sp->ts_state = STATE_FINAL;
1833        break;
1834      }
1835      // Try skipping one character in the bad word (delete it).
1836      PROF_STORE(sp->ts_state)
1837      sp->ts_state = STATE_INS_PREP;
1838      sp->ts_curi = 1;
1839      if (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().
1842        newscore = 2 * SCORE_DEL / 3;
1843      } else {
1844        newscore = SCORE_DEL;
1845      }
1846      if (fword[sp->ts_fidx] != NUL
1847          && TRY_DEEPER(su, stack, depth, newscore)) {
1848        go_deeper(stack, depth, newscore);
1849#ifdef DEBUG_TRIEWALK
1850        sprintf(changename[depth], "%.*s-%s: delete %c",  // NOLINT(runtime/printf)
1851                sp->ts_twordlen, tword, fword + sp->ts_fidx,
1852                fword[sp->ts_fidx]);
1853#endif
1854        depth++;
1855
1856        // Remember what character we deleted, so that we can avoid
1857        // inserting it again.
1858        stack[depth].ts_flags |= TSF_DIDDEL;
1859        stack[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.
1865        c = utf_ptr2char(fword + sp->ts_fidx);
1866        stack[depth].ts_fidx =
1867          (uint8_t)(stack[depth].ts_fidx + utfc_ptr2len(fword + sp->ts_fidx));
1868        if (utf_iscomposing_legacy(c)) {
1869          stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
1870        } else if (c == utf_ptr2char(fword + stack[depth].ts_fidx)) {
1871          stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
1872        }
1873
1874        break;
1875      }
1876      FALLTHROUGH;
1877
1878    case STATE_INS_PREP:
1879      if (sp->ts_flags & TSF_DIDDEL) {
1880        // If we just deleted a byte then inserting won't make sense,
1881        // a substitute is always cheaper.
1882        PROF_STORE(sp->ts_state)
1883        sp->ts_state = STATE_SWAP;
1884        break;
1885      }
1886
1887      // skip over NUL bytes
1888      n = sp->ts_arridx;
1889      while (true) {
1890        if (sp->ts_curi > byts[n]) {
1891          // Only NUL bytes at this node, go to next state.
1892          PROF_STORE(sp->ts_state)
1893          sp->ts_state = STATE_SWAP;
1894          break;
1895        }
1896        if (byts[n + sp->ts_curi] != NUL) {
1897          // Found a byte to insert.
1898          PROF_STORE(sp->ts_state)
1899          sp->ts_state = STATE_INS;
1900          break;
1901        }
1902        sp->ts_curi++;
1903      }
1904      break;
1905
1906    case STATE_INS:
1907      // Insert one byte.  Repeat this for each possible byte at this
1908      // node.
1909      n = sp->ts_arridx;
1910      if (sp->ts_curi > byts[n]) {
1911        // Done all bytes at this node, go to next state.
1912        PROF_STORE(sp->ts_state)
1913        sp->ts_state = STATE_SWAP;
1914        break;
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.
1921      n += sp->ts_curi++;
1922
1923      // break out, if we would be accessing byts buffer out of bounds
1924      if (byts == slang->sl_fbyts && n >= slang->sl_fbyts_len) {
1925        got_int = true;
1926        break;
1927      }
1928      c = byts[n];
1929      if (soundfold && sp->ts_twordlen == 0 && c == '*') {
1930        // Inserting a vowel at the start of a word counts less,
1931        // see soundalike_score().
1932        newscore = 2 * SCORE_INS / 3;
1933      } else {
1934        newscore = SCORE_INS;
1935      }
1936      if (c != (uint8_t)fword[sp->ts_fidx]
1937          && TRY_DEEPER(su, stack, depth, newscore)) {
1938        go_deeper(stack, depth, newscore);
1939#ifdef DEBUG_TRIEWALK
1940        sprintf(changename[depth], "%.*s-%s: insert %c",  // NOLINT(runtime/printf)
1941                sp->ts_twordlen, tword, fword + sp->ts_fidx,
1942                c);
1943#endif
1944        depth++;
1945        sp = &stack[depth];
1946        tword[sp->ts_twordlen++] = (char)c;
1947        sp->ts_arridx = idxs[n];
1948        fl = MB_BYTE2LEN(c);
1949        if (fl > 1) {
1950          // There are following bytes for the same character.
1951          // We must find all bytes before trying
1952          // delete/insert/swap/etc.
1953          sp->ts_tcharlen = (uint8_t)fl;
1954          sp->ts_tcharidx = 1;
1955          sp->ts_isdiff = DIFF_INSERT;
1956        }
1957        if (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).
1962          if (sp->ts_twordlen >= 2
1963              && (uint8_t)tword[sp->ts_twordlen - 2] == c) {
1964            sp->ts_score -= SCORE_INS - SCORE_INSDUP;
1965          }
1966        }
1967      }
1968      break;
1969
1970    case 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.
1974      p = fword + sp->ts_fidx;
1975      c = (uint8_t)(*p);
1976      if (c == NUL) {
1977        // End of word, can't swap or replace.
1978        PROF_STORE(sp->ts_state)
1979        sp->ts_state = STATE_FINAL;
1980        break;
1981      }
1982
1983      // Don't swap if the first character is not a word character.
1984      // SWAP3 etc. also don't make sense then.
1985      if (!soundfold && !spell_iswordp(p, curwin)) {
1986        PROF_STORE(sp->ts_state)
1987        sp->ts_state = STATE_REP_INI;
1988        break;
1989      }
1990
1991      n = utf_ptr2len(p);
1992      c = utf_ptr2char(p);
1993      if (p[n] == NUL) {
1994        c2 = NUL;
1995      } else if (!soundfold && !spell_iswordp(p + n, curwin)) {
1996        c2 = c;  // don't swap non-word char
1997      } else {
1998        c2 = utf_ptr2char(p + n);
1999      }
2000
2001      // When the second character is NUL we can't swap.
2002      if (c2 == NUL) {
2003        PROF_STORE(sp->ts_state)
2004        sp->ts_state = STATE_REP_INI;
2005        break;
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.
2010      if (c == c2) {
2011        PROF_STORE(sp->ts_state)
2012        sp->ts_state = STATE_SWAP3;
2013        break;
2014      }
2015      if (TRY_DEEPER(su, stack, depth, SCORE_SWAP)) {
2016        go_deeper(stack, depth, SCORE_SWAP);
2017#ifdef DEBUG_TRIEWALK
2018        snprintf(changename[depth], sizeof(changename[0]),
2019                 "%.*s-%s: swap %c and %c",
2020                 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2021                 c, c2);
2022#endif
2023        PROF_STORE(sp->ts_state)
2024        sp->ts_state = STATE_UNSWAP;
2025        depth++;
2026        fl = utf_char2len(c2);
2027        memmove(p, p + n, (size_t)fl);
2028        utf_char2bytes(c, p + fl);
2029        stack[depth].ts_fidxtry = (uint8_t)(sp->ts_fidx + n + fl);
2030      } else {
2031        // If this swap doesn't work then SWAP3 won't either.
2032        PROF_STORE(sp->ts_state)
2033        sp->ts_state = STATE_REP_INI;
2034      }
2035      break;
2036
2037    case STATE_UNSWAP:
2038      // Undo the STATE_SWAP swap: "21" -> "12".
2039      p = fword + sp->ts_fidx;
2040      n = utfc_ptr2len(p);
2041      c = utf_ptr2char(p + n);
2042      memmove(p + utfc_ptr2len(p + n), p, (size_t)n);
2043      utf_char2bytes(c, p);
2044
2045      FALLTHROUGH;
2046
2047    case STATE_SWAP3:
2048      // Swap two bytes, skipping one: "123" -> "321".  We change
2049      // "fword" here, it's changed back afterwards at STATE_UNSWAP3.
2050      p = fword + sp->ts_fidx;
2051      n = utf_ptr2len(p);
2052      c = utf_ptr2char(p);
2053      fl = utf_ptr2len(p + n);
2054      c2 = utf_ptr2char(p + n);
2055      if (!soundfold && !spell_iswordp(p + n + fl, curwin)) {
2056        c3 = c;  // don't swap non-word char
2057      } else {
2058        c3 = 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"
2067      if (c == c3 || c3 == NUL) {
2068        PROF_STORE(sp->ts_state)
2069        sp->ts_state = STATE_REP_INI;
2070        break;
2071      }
2072      if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) {
2073        go_deeper(stack, depth, SCORE_SWAP3);
2074#ifdef DEBUG_TRIEWALK
2075        sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",  // NOLINT(runtime/printf)
2076                sp->ts_twordlen, tword, fword + sp->ts_fidx,
2077                c, c3);
2078#endif
2079        PROF_STORE(sp->ts_state)
2080        sp->ts_state = STATE_UNSWAP3;
2081        depth++;
2082        tl = utf_char2len(c3);
2083        memmove(p, p + n + fl, (size_t)tl);
2084        utf_char2bytes(c2, p + tl);
2085        utf_char2bytes(c, p + fl + tl);
2086        stack[depth].ts_fidxtry = (uint8_t)(sp->ts_fidx + n + fl + tl);
2087      } else {
2088        PROF_STORE(sp->ts_state)
2089        sp->ts_state = STATE_REP_INI;
2090      }
2091      break;
2092
2093    case STATE_UNSWAP3:
2094      // Undo STATE_SWAP3: "321" -> "123"
2095      p = fword + sp->ts_fidx;
2096      n = utfc_ptr2len(p);
2097      c2 = utf_ptr2char(p + n);
2098      fl = utfc_ptr2len(p + n);
2099      c = utf_ptr2char(p + n + fl);
2100      tl = utfc_ptr2len(p + n + fl);
2101      memmove(p + fl + tl, p, (size_t)n);
2102      utf_char2bytes(c, p);
2103      utf_char2bytes(c2, p + tl);
2104      p = p + tl;
2105
2106      if (!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.
2109        PROF_STORE(sp->ts_state)
2110        sp->ts_state = STATE_REP_INI;
2111        break;
2112      }
2113
2114      // Rotate three characters left: "123" -> "231".  We change
2115      // "fword" here, it's changed back afterwards at STATE_UNROT3L.
2116      if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) {
2117        go_deeper(stack, depth, SCORE_SWAP3);
2118#ifdef DEBUG_TRIEWALK
2119        p = fword + sp->ts_fidx;
2120        sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",  // NOLINT(runtime/printf)
2121                sp->ts_twordlen, tword, fword + sp->ts_fidx,
2122                p[0], p[1], p[2]);
2123#endif
2124        PROF_STORE(sp->ts_state)
2125        sp->ts_state = STATE_UNROT3L;
2126        depth++;
2127        p = fword + sp->ts_fidx;
2128        n = utf_ptr2len(p);
2129        c = utf_ptr2char(p);
2130        fl = utf_ptr2len(p + n);
2131        fl += utf_ptr2len(p + n + fl);
2132        memmove(p, p + n, (size_t)fl);
2133        utf_char2bytes(c, p + fl);
2134        stack[depth].ts_fidxtry = (uint8_t)(sp->ts_fidx + n + fl);
2135      } else {
2136        PROF_STORE(sp->ts_state)
2137        sp->ts_state = STATE_REP_INI;
2138      }
2139      break;
2140
2141    case STATE_UNROT3L:
2142      // Undo ROT3L: "231" -> "123"
2143      p = fword + sp->ts_fidx;
2144      n = utfc_ptr2len(p);
2145      n += utfc_ptr2len(p + n);
2146      c = utf_ptr2char(p + n);
2147      tl = utfc_ptr2len(p + n);
2148      memmove(p + tl, p, (size_t)n);
2149      utf_char2bytes(c, p);
2150
2151      // Rotate three bytes right: "123" -> "312".  We change "fword"
2152      // here, it's changed back afterwards at STATE_UNROT3R.
2153      if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3)) {
2154        go_deeper(stack, depth, SCORE_SWAP3);
2155#ifdef DEBUG_TRIEWALK
2156        p = fword + sp->ts_fidx;
2157        sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",  // NOLINT(runtime/printf)
2158                sp->ts_twordlen, tword, fword + sp->ts_fidx,
2159                p[0], p[1], p[2]);
2160#endif
2161        PROF_STORE(sp->ts_state)
2162        sp->ts_state = STATE_UNROT3R;
2163        depth++;
2164        p = fword + sp->ts_fidx;
2165        n = utf_ptr2len(p);
2166        n += utf_ptr2len(p + n);
2167        c = utf_ptr2char(p + n);
2168        tl = utf_ptr2len(p + n);
2169        memmove(p + tl, p, (size_t)n);
2170        utf_char2bytes(c, p);
2171        stack[depth].ts_fidxtry = (uint8_t)(sp->ts_fidx + n + tl);
2172      } else {
2173        PROF_STORE(sp->ts_state)
2174        sp->ts_state = STATE_REP_INI;
2175      }
2176      break;
2177
2178    case STATE_UNROT3R:
2179      // Undo ROT3R: "312" -> "123"
2180      p = fword + sp->ts_fidx;
2181      c = utf_ptr2char(p);
2182      tl = utfc_ptr2len(p);
2183      n = utfc_ptr2len(p + tl);
2184      n += utfc_ptr2len(p + tl + n);
2185      memmove(p, p + tl, (size_t)n);
2186      utf_char2bytes(c, p + n);
2187
2188      FALLTHROUGH;
2189
2190    case 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
2196      if ((lp->lp_replang == NULL && !soundfold)
2197          || sp->ts_score + SCORE_REP >= su->su_maxscore
2198          || sp->ts_fidx < sp->ts_fidxtry) {
2199        PROF_STORE(sp->ts_state)
2200        sp->ts_state = STATE_FINAL;
2201        break;
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.
2206      if (soundfold) {
2207        sp->ts_curi = slang->sl_repsal_first[(uint8_t)fword[sp->ts_fidx]];
2208      } else {
2209        sp->ts_curi = lp->lp_replang->sl_rep_first[(uint8_t)fword[sp->ts_fidx]];
2210      }
2211
2212      if (sp->ts_curi < 0) {
2213        PROF_STORE(sp->ts_state)
2214        sp->ts_state = STATE_FINAL;
2215        break;
2216      }
2217
2218      PROF_STORE(sp->ts_state)
2219      sp->ts_state = STATE_REP;
2220      FALLTHROUGH;
2221
2222    case 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.
2226      p = fword + sp->ts_fidx;
2227
2228      garray_T *gap = soundfold ? &slang->sl_repsal
2229                                : &lp->lp_replang->sl_rep;
2230      while (sp->ts_curi < gap->ga_len) {
2231        fromto_T *ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
2232        if (*ftp->ft_from != *p) {
2233          // past possible matching entries
2234          sp->ts_curi = (int16_t)gap->ga_len;
2235          break;
2236        }
2237        if (strncmp(ftp->ft_from, p, strlen(ftp->ft_from)) == 0
2238            && TRY_DEEPER(su, stack, depth, SCORE_REP)) {
2239          go_deeper(stack, depth, SCORE_REP);
2240#ifdef DEBUG_TRIEWALK
2241          sprintf(changename[depth], "%.*s-%s: replace %s with %s",  // NOLINT(runtime/printf)
2242                  sp->ts_twordlen, tword, fword + sp->ts_fidx,
2243                  ftp->ft_from, ftp->ft_to);
2244#endif
2245          // Need to undo this afterwards.
2246          PROF_STORE(sp->ts_state)
2247          sp->ts_state = STATE_REP_UNDO;
2248
2249          // Change the "from" to the "to" string.
2250          depth++;
2251          fl = (int)strlen(ftp->ft_from);
2252          tl = (int)strlen(ftp->ft_to);
2253          if (fl != tl) {
2254            STRMOVE(p + tl, p + fl);
2255            repextra += tl - fl;
2256          }
2257          memmove(p, ftp->ft_to, (size_t)tl);
2258          stack[depth].ts_fidxtry = (uint8_t)(sp->ts_fidx + tl);
2259          stack[depth].ts_tcharlen = 0;
2260          break;
2261        }
2262      }
2263
2264      if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP) {
2265        // No (more) matches.
2266        PROF_STORE(sp->ts_state)
2267        sp->ts_state = STATE_FINAL;
2268      }
2269
2270      break;
2271
2272    case STATE_REP_UNDO:
2273      // Undo a REP replacement and continue with the next one.
2274      if (soundfold) {
2275        gap = &slang->sl_repsal;
2276      } else {
2277        gap = &lp->lp_replang->sl_rep;
2278      }
2279      fromto_T *ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
2280      fl = (int)strlen(ftp->ft_from);
2281      tl = (int)strlen(ftp->ft_to);
2282      p = fword + sp->ts_fidx;
2283      if (fl != tl) {
2284        STRMOVE(p + fl, p + tl);
2285        repextra -= tl - fl;
2286      }
2287      memmove(p, ftp->ft_from, (size_t)fl);
2288      PROF_STORE(sp->ts_state)
2289      sp->ts_state = STATE_REP;
2290      break;
2291
2292    default:
2293      // Did all possible states at this level, go up one level.
2294      depth--;
2295
2296      if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE) {
2297        // Continue in or go back to the prefix tree.
2298        byts = pbyts;
2299        idxs = pidxs;
2300      }
2301
2302      // Don't check for CTRL-C too often, it takes time.
2303      if (--breakcheckcount == 0) {
2304        os_breakcheck();
2305        breakcheckcount = 1000;
2306        if (spell_suggest_timeout > 0 && profile_passed_limit(time_limit)) {
2307          got_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{
2317  stack[depth + 1] = stack[depth];
2318  stack[depth + 1].ts_state = STATE_START;
2319  stack[depth + 1].ts_score = stack[depth].ts_score + score_add;
2320  stack[depth + 1].ts_curi = 1;         // start just after length byte
2321  stack[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{
2330  char uword[MAXWLEN];                // "fword" in upper-case
2331  idx_T tryidx;
2332
2333  // The following arrays are used at each depth in the tree.
2334  idx_T arridx[MAXWLEN];
2335  int round[MAXWLEN];
2336  int fwordidx[MAXWLEN];
2337  int uwordidx[MAXWLEN];
2338  int kwordlen[MAXWLEN];
2339
2340  int l;
2341  char *p;
2342  uint8_t *byts = slang->sl_kbyts;      // array with bytes of the words
2343  idx_T *idxs = slang->sl_kidxs;      // array with indexes
2344
2345  if (byts == NULL) {
2346    // array is empty: "cannot happen"
2347    *kword = NUL;
2348    return;
2349  }
2350
2351  // Make an all-cap version of "fword".
2352  allcap_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...
2357  int depth = 0;
2358  arridx[0] = 0;
2359  round[0] = 0;
2360  fwordidx[0] = 0;
2361  uwordidx[0] = 0;
2362  kwordlen[0] = 0;
2363  while (depth >= 0) {
2364    if (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.
2367      if (byts[arridx[depth] + 1] == 0) {
2368        kword[kwordlen[depth]] = NUL;
2369        return;
2370      }
2371
2372      // kword is getting too long, continue one level up
2373      depth--;
2374    } else if (++round[depth] > 2) {
2375      // tried both fold-case and upper-case character, continue one
2376      // level up
2377      depth--;
2378    } else {
2379      // round[depth] == 1: Try using the folded-case character.
2380      // round[depth] == 2: Try using the upper-case character.
2381      int flen = utf_ptr2len(fword + fwordidx[depth]);
2382      int ulen = utf_ptr2len(uword + uwordidx[depth]);
2383      if (round[depth] == 1) {
2384        p = fword + fwordidx[depth];
2385        l = flen;
2386      } else {
2387        p = uword + uwordidx[depth];
2388        l = ulen;
2389      }
2390
2391      for (tryidx = arridx[depth]; l > 0; l--) {
2392        // Perform a binary search in the list of accepted bytes.
2393        int len = byts[tryidx++];
2394        int c = (uint8_t)(*p++);
2395        idx_T lo = tryidx;
2396        idx_T hi = tryidx + len - 1;
2397        while (lo < hi) {
2398          idx_T m = (lo + hi) / 2;
2399          if (byts[m] > c) {
2400            hi = m - 1;
2401          } else if (byts[m] < c) {
2402            lo = m + 1;
2403          } else {
2404            lo = hi = m;
2405            break;
2406          }
2407        }
2408
2409        // Stop if there is no matching byte.
2410        if (hi < lo || byts[lo] != c) {
2411          break;
2412        }
2413
2414        // Continue at the child (if there is one).
2415        tryidx = idxs[lo];
2416      }
2417
2418      if (l == 0) {
2419        // Found the matching char.  Copy it to "kword" and go a
2420        // level deeper.
2421        if (round[depth] == 1) {
2422          strncpy(kword + kwordlen[depth],  // NOLINT(runtime/printf)
2423                  fword + fwordidx[depth],
2424                  (size_t)flen);
2425          kwordlen[depth + 1] = kwordlen[depth] + flen;
2426        } else {
2427          strncpy(kword + kwordlen[depth],  // NOLINT(runtime/printf)
2428                  uword + uwordidx[depth],
2429                  (size_t)ulen);
2430          kwordlen[depth + 1] = kwordlen[depth] + ulen;
2431        }
2432        fwordidx[depth + 1] = fwordidx[depth] + flen;
2433        uwordidx[depth + 1] = uwordidx[depth] + ulen;
2434
2435        depth++;
2436        arridx[depth] = tryidx;
2437        round[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{
2450  char badsound[MAXWLEN];
2451
2452  ga_grow(&su->su_sga, su->su_ga.ga_len);
2453
2454  // Use the sound-folding of the first language that supports it.
2455  for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
2456    langp_T *lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2457    if (!GA_EMPTY(&lp->lp_slang->sl_sal)) {
2458      // soundfold the bad word
2459      spell_soundfold(lp->lp_slang, su->su_fbadword, true, badsound);
2460
2461      for (int i = 0; i < su->su_ga.ga_len; i++) {
2462        suggest_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.
2466        int score = stp_sal_score(stp, su, lp->lp_slang, badsound);
2467        if (score < SCORE_MAXMAX) {
2468          // Add the suggestion.
2469          suggest_T *sstp = &SUG(su->su_sga, su->su_sga.ga_len);
2470          sstp->st_word = xstrdup(stp->st_word);
2471          sstp->st_wordlen = stp->st_wordlen;
2472          sstp->st_score = score;
2473          sstp->st_altscore = 0;
2474          sstp->st_orglen = stp->st_orglen;
2475          su->su_sga.ga_len++;
2476        }
2477      }
2478      break;
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{
2487  garray_T ga;
2488  char *p;
2489  char badsound[MAXWLEN];
2490  slang_T *slang = NULL;
2491
2492  // Add the alternate score to su_ga.
2493  for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
2494    langp_T *lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2495    if (!GA_EMPTY(&lp->lp_slang->sl_sal)) {
2496      // soundfold the bad word
2497      slang = lp->lp_slang;
2498      spell_soundfold(slang, su->su_fbadword, true, badsound);
2499
2500      for (int i = 0; i < su->su_ga.ga_len; i++) {
2501        suggest_T *stp = &SUG(su->su_ga, i);
2502        stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
2503        if (stp->st_altscore == SCORE_MAXMAX) {
2504          stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
2505        } else {
2506          stp->st_score = (stp->st_score * 3 + stp->st_altscore) / 4;
2507        }
2508        stp->st_salscore = false;
2509      }
2510      break;
2511    }
2512  }
2513
2514  if (slang == NULL) {  // Using "double" without sound folding.
2515    cleanup_suggestions(&su->su_ga, su->su_maxscore,
2516                        su->su_maxcount);
2517    return;
2518  }
2519
2520  // Add the alternate score to su_sga.
2521  for (int i = 0; i < su->su_sga.ga_len; i++) {
2522    suggest_T *stp = &SUG(su->su_sga, i);
2523    stp->st_altscore = spell_edit_score(slang, su->su_badword, stp->st_word);
2524    if (stp->st_score == SCORE_MAXMAX) {
2525      stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
2526    } else {
2527      stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8;
2528    }
2529    stp->st_salscore = true;
2530  }
2531
2532  // Remove bad suggestions, sort the suggestions and truncate at "maxcount"
2533  // for both lists.
2534  check_suggestions(su, &su->su_ga);
2535  cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
2536  check_suggestions(su, &su->su_sga);
2537  cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount);
2538
2539  ga_init(&ga, (int)sizeof(suginfo_T), 1);
2540  ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len);
2541
2542  suggest_T *stp = &SUG(ga, 0);
2543  for (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
2546    for (int round = 1; round <= 2; round++) {
2547      garray_T *gap = round == 1 ? &su->su_ga : &su->su_sga;
2548      if (i < gap->ga_len) {
2549        // Don't add a word if it's already there.
2550        p = SUG(*gap, i).st_word;
2551        int j;
2552        for (j = 0; j < ga.ga_len; j++) {
2553          if (strcmp(stp[j].st_word, p) == 0) {
2554            break;
2555          }
2556        }
2557        if (j == ga.ga_len) {
2558          stp[ga.ga_len++] = SUG(*gap, i);
2559        } else {
2560          xfree(p);
2561        }
2562      }
2563    }
2564  }
2565
2566  ga_clear(&su->su_ga);
2567  ga_clear(&su->su_sga);
2568
2569  // Truncate the list to the number of suggestions that will be displayed.
2570  if (ga.ga_len > su->su_maxcount) {
2571    for (int i = su->su_maxcount; i < ga.ga_len; i++) {
2572      xfree(stp[i].st_word);
2573    }
2574    ga.ga_len = su->su_maxcount;
2575  }
2576
2577  su->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{
2586  char *pbad;
2587  char *pgood;
2588  char badsound2[MAXWLEN];
2589  char fword[MAXWLEN];
2590  char goodsound[MAXWLEN];
2591  char goodword[MAXWLEN];
2592
2593  int lendiff = su->su_badlen - stp->st_orglen;
2594  if (lendiff >= 0) {
2595    pbad = badsound;
2596  } else {
2597    // soundfold the bad word with more characters following
2598    spell_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.
2604    if (ascii_iswhite(su->su_badptr[su->su_badlen])
2605        && *skiptowhite(stp->st_word) == NUL) {
2606      for (char *p = fword; *(p = skiptowhite(p)) != NUL;) {
2607        STRMOVE(p, p + 1);
2608      }
2609    }
2610
2611    spell_soundfold(slang, fword, true, badsound2);
2612    pbad = badsound2;
2613  }
2614
2615  if (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.
2618    STRCPY(goodword, stp->st_word);
2619    xmemcpyz(goodword + stp->st_wordlen,
2620             su->su_badptr + su->su_badlen - lendiff, (size_t)lendiff);
2621    pgood = goodword;
2622  } else {
2623    pgood = stp->st_word;
2624  }
2625
2626  // Sound-fold the word and compute the score for the difference.
2627  spell_soundfold(slang, pgood, false, goodsound);
2628
2629  return soundalike_score(goodsound, pbad);
2630}
2631
2632/// structure used to store soundfolded words that add_sound_suggest() has
2633/// handled already.
2634typedef struct {
2635  int16_t sft_score;   ///< lowest score used
2636  uint8_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.
2647  for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
2648    langp_T *lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2649    slang_T *slang = lp->lp_slang;
2650    if (!GA_EMPTY(&slang->sl_sal) && slang->sl_sbyts != NULL) {
2651      // prepare the hashtable used by add_sound_suggest()
2652      hash_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{
2661  char salword[MAXWLEN];
2662
2663  // Do this for all languages that support sound folding and for which a
2664  // .sug file has been loaded.
2665  for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
2666    langp_T *lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2667    slang_T *slang = lp->lp_slang;
2668    if (!GA_EMPTY(&slang->sl_sal) && slang->sl_sbyts != NULL) {
2669      // soundfold the bad word
2670      spell_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
2676      prof_init();
2677#endif
2678      suggest_trie_walk(su, lp, salword, true);
2679#ifdef SUGGEST_PROFILE
2680      prof_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.
2691  for (int lpi = 0; lpi < curwin->w_s->b_langp.ga_len; lpi++) {
2692    langp_T *lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2693    slang_T *slang = lp->lp_slang;
2694    if (!GA_EMPTY(&slang->sl_sal) && slang->sl_sbyts != NULL) {
2695      // Free the info about handled words.
2696      int todo = (int)slang->sl_sounddone.ht_used;
2697      for (hashitem_T *hi = slang->sl_sounddone.ht_array; todo > 0; hi++) {
2698        if (!HASHITEM_EMPTY(hi)) {
2699          xfree(HI2SFT(hi));
2700          todo--;
2701        }
2702      }
2703
2704      // Clear the hashtable, it may also be used by another region.
2705      hash_clear(&slang->sl_sounddone);
2706      hash_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{
2717  slang_T *slang = lp->lp_slang;    // language for sound folding
2718  char theword[MAXWLEN];
2719  int i;
2720  int wlen;
2721  uint8_t *byts;
2722  int wc;
2723  int goodscore;
2724  sftword_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.
2730  hash_T hash = hash_hash(goodword);
2731  const size_t goodword_len = strlen(goodword);
2732  hashitem_T *hi = hash_lookup(&slang->sl_sounddone, goodword, goodword_len, hash);
2733  if (HASHITEM_EMPTY(hi)) {
2734    sft = xmalloc(offsetof(sftword_T, sft_word) + goodword_len + 1);
2735    sft->sft_score = (int16_t)score;
2736    memcpy(sft->sft_word, goodword, goodword_len + 1);
2737    hash_add_item(&slang->sl_sounddone, hi, (char *)sft->sft_word, hash);
2738  } else {
2739    sft = HI2SFT(hi);
2740    if (score >= sft->sft_score) {
2741      return;
2742    }
2743    sft->sft_score = (int16_t)score;
2744  }
2745
2746  // Find the word nr in the soundfold tree.
2747  int sfwordnr = soundfold_find(slang, goodword);
2748  if (sfwordnr < 0) {
2749    internal_error("add_sound_suggest()");
2750    return;
2751  }
2752
2753  // Go over the list of good words that produce this soundfold word
2754  char *nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)sfwordnr + 1);
2755  int orgnr = 0;
2756  while (*nrline != NUL) {
2757    // The wordnr was stored in a minimal nr of bytes as an offset to the
2758    // previous wordnr.
2759    orgnr += bytes2offset(&nrline);
2760
2761    byts = slang->sl_fbyts;
2762    idx_T *idxs = slang->sl_fidxs;
2763
2764    // Lookup the word "orgnr" one of the two tries.
2765    int n = 0;
2766    int wordcount = 0;
2767    for (wlen = 0; wlen < MAXWLEN - 3; wlen++) {
2768      i = 1;
2769      if (wordcount == orgnr && byts[n + 1] == NUL) {
2770        break;          // found end of word
2771      }
2772      if (byts[n + 1] == NUL) {
2773        wordcount++;
2774      }
2775
2776      // skip over the NUL bytes
2777      for (; byts[n + i] == NUL; i++) {
2778        if (i > byts[n]) {              // safety check
2779          STRCPY(theword + wlen, "BAD");
2780          wlen += 3;
2781          goto badword;
2782        }
2783      }
2784
2785      // One of the siblings must have the word.
2786      for (; i < byts[n]; i++) {
2787        wc = idxs[idxs[n + i]];         // nr of words under this byte
2788        if (wordcount + wc > orgnr) {
2789          break;
2790        }
2791        wordcount += wc;
2792      }
2793
2794      theword[wlen] = (char)byts[n + i];
2795      n = idxs[n + i];
2796    }
2797badword:
2798    theword[wlen] = NUL;
2799
2800    // Go over the possible flags and regions.
2801    for (; i <= byts[n] && byts[n + i] == NUL; i++) {
2802      char cword[MAXWLEN];
2803      char *p;
2804      int flags = (int)idxs[n + i];
2805
2806      // Skip words with the NOSUGGEST flag
2807      if (flags & WF_NOSUGGEST) {
2808        continue;
2809      }
2810
2811      if (flags & WF_KEEPCAP) {
2812        // Must find the word in the keep-case tree.
2813        find_keepcap_word(slang, theword, cword);
2814        p = cword;
2815      } else {
2816        flags |= su->su_badflags;
2817        if ((flags & WF_CAPMASK) != 0) {
2818          // Need to fix case according to "flags".
2819          make_case_word(theword, cword, flags);
2820          p = cword;
2821        } else {
2822          p = theword;
2823        }
2824      }
2825
2826      // Add the suggestion.
2827      if (sps_flags & SPS_DOUBLE) {
2828        // Add the suggestion if the score isn't too bad.
2829        if (score <= su->su_maxscore) {
2830          add_suggestion(su, &su->su_sga, p, su->su_badlen,
2831                         score, 0, false, slang, false);
2832        }
2833      } else {
2834        // Add a penalty for words in another region.
2835        if ((flags & WF_REGION)
2836            && (((unsigned)flags >> 16) & (unsigned)lp->lp_region) == 0) {
2837          goodscore = SCORE_REGION;
2838        } else {
2839          goodscore = 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.
2846        int gc = utf_ptr2char(p);
2847        if (SPELL_ISUPPER(gc)) {
2848          int bc = utf_ptr2char(su->su_badword);
2849          if (!SPELL_ISUPPER(bc)
2850              && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc)) {
2851            goodscore += 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.
2862        int limit = MAXSCORE(su->su_sfmaxscore - goodscore, score);
2863        if (limit > SCORE_LIMITMAX) {
2864          goodscore += spell_edit_score(slang, su->su_badword, p);
2865        } else {
2866          goodscore += 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.
2870        if (goodscore < SCORE_MAXMAX) {
2871          // Give a bonus to words seen before.
2872          goodscore = score_wordcount_adj(slang, goodscore, p, false);
2873
2874          // Add the suggestion if the score isn't too bad.
2875          goodscore = RESCORE(goodscore, score);
2876          if (goodscore <= su->su_sfmaxscore) {
2877            add_suggestion(su, &su->su_ga, p, su->su_badlen,
2878                           goodscore, 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{
2889  idx_T arridx = 0;
2890  int wlen = 0;
2891  uint8_t *ptr = (uint8_t *)word;
2892  int wordnr = 0;
2893
2894  uint8_t *byts = slang->sl_sbyts;
2895  idx_T *idxs = slang->sl_sidxs;
2896
2897  while (true) {
2898    // First byte is the number of possible bytes.
2899    int 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.
2903    int c = ptr[wlen];
2904    if (byts[arridx] == NUL) {
2905      if (c == NUL) {
2906        break;
2907      }
2908
2909      // Skip over the zeros, there can be several.
2910      while (len > 0 && byts[arridx] == NUL) {
2911        arridx++;
2912        len--;
2913      }
2914      if (len == 0) {
2915        return -1;            // no children, word should have ended here
2916      }
2917      wordnr++;
2918    }
2919
2920    // If the word ends we didn't find it.
2921    if (c == NUL) {
2922      return -1;
2923    }
2924
2925    // Perform a binary search in the list of accepted bytes.
2926    if (c == TAB) {         // <Tab> is handled like <Space>
2927      c = ' ';
2928    }
2929    while (byts[arridx] < c) {
2930      // The word count is in the first idxs[] entry of the child.
2931      wordnr += idxs[idxs[arridx]];
2932      arridx++;
2933      if (--len == 0) {         // end of the bytes, didn't find it
2934        return -1;
2935      }
2936    }
2937    if (byts[arridx] != c) {    // didn't find the byte
2938      return -1;
2939    }
2940
2941    // Continue at the child (if there is one).
2942    arridx = idxs[arridx];
2943    wlen++;
2944
2945    // One space in the good word may stand for several spaces in the
2946    // checked word.
2947    if (c == ' ') {
2948      while (ptr[wlen] == ' ' || ptr[wlen] == TAB) {
2949        wlen++;
2950      }
2951    }
2952  }
2953
2954  return 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{
2961  int m1, m2;
2962  char buf[MB_MAXCHAR + 1];
2963
2964  if (c1 >= 256) {
2965    buf[utf_char2bytes(c1, buf)] = 0;
2966    hashitem_T *hi = hash_find(&slang->sl_map_hash, buf);
2967    if (HASHITEM_EMPTY(hi)) {
2968      m1 = 0;
2969    } else {
2970      m1 = utf_ptr2char(hi->hi_key + strlen(hi->hi_key) + 1);
2971    }
2972  } else {
2973    m1 = slang->sl_map_array[c1];
2974  }
2975  if (m1 == 0) {
2976    return false;
2977  }
2978
2979  if (c2 >= 256) {
2980    buf[utf_char2bytes(c2, buf)] = 0;
2981    hashitem_T *hi = hash_find(&slang->sl_map_hash, buf);
2982    if (HASHITEM_EMPTY(hi)) {
2983      m2 = 0;
2984    } else {
2985      m2 = utf_ptr2char(hi->hi_key + strlen(hi->hi_key) + 1);
2986    }
2987  } else {
2988    m2 = slang->sl_map_array[c2];
2989  }
2990
2991  return 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,
3003                           int score, int altscore, bool had_bonus, slang_T *slang, bool maxsf)
3004{
3005  int goodlen;                  // len of goodword changed
3006  int badlen;                   // len of bad word changed
3007  suggest_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".
3011  const char *pgood = goodword + strlen(goodword);
3012  char *pbad = su->su_badptr + badlenarg;
3013  while (true) {
3014    goodlen = (int)(pgood - goodword);
3015    badlen = (int)(pbad - su->su_badptr);
3016    if (goodlen <= 0 || badlen <= 0) {
3017      break;
3018    }
3019    MB_PTR_BACK(goodword, pgood);
3020    MB_PTR_BACK(su->su_badptr, pbad);
3021    if (utf_ptr2char(pgood) != utf_ptr2char(pbad)) {
3022      break;
3023    }
3024  }
3025
3026  if (badlen == 0 && goodlen == 0) {
3027    // goodword doesn't change anything; may happen for "the the" changing
3028    // the first "the" to itself.
3029    return;
3030  }
3031
3032  int i;
3033  if (GA_EMPTY(gap)) {
3034    i = -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".
3039    suggest_T *stp = &SUG(*gap, 0);
3040    for (i = gap->ga_len; --i >= 0; stp++) {
3041      if (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.
3045        if (stp->st_slang == NULL) {
3046          stp->st_slang = slang;
3047        }
3048
3049        new_sug.st_score = score;
3050        new_sug.st_altscore = altscore;
3051        new_sug.st_had_bonus = had_bonus;
3052
3053        if (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.
3060          if (had_bonus) {
3061            rescore_one(su, stp);
3062          } else {
3063            new_sug.st_word = stp->st_word;
3064            new_sug.st_wordlen = stp->st_wordlen;
3065            new_sug.st_slang = stp->st_slang;
3066            new_sug.st_orglen = badlen;
3067            rescore_one(su, &new_sug);
3068          }
3069        }
3070
3071        if (stp->st_score > new_sug.st_score) {
3072          stp->st_score = new_sug.st_score;
3073          stp->st_altscore = new_sug.st_altscore;
3074          stp->st_had_bonus = new_sug.st_had_bonus;
3075        }
3076        break;
3077      }
3078    }
3079  }
3080
3081  if (i < 0) {
3082    // Add a suggestion.
3083    suggest_T *stp = GA_APPEND_VIA_PTR(suggest_T, gap);
3084    stp->st_word = xmemdupz(goodword, (size_t)goodlen);
3085    stp->st_wordlen = goodlen;
3086    stp->st_score = score;
3087    stp->st_altscore = altscore;
3088    stp->st_had_bonus = had_bonus;
3089    stp->st_orglen = badlen;
3090    stp->st_slang = slang;
3091
3092    // If we have too many suggestions now, sort the list and keep
3093    // the best suggestions.
3094    if (gap->ga_len > SUG_MAX_COUNT(su)) {
3095      if (maxsf) {
3096        su->su_sfmaxscore = cleanup_suggestions(gap, su->su_sfmaxscore, SUG_CLEAN_COUNT(su));
3097      } else {
3098        su->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{
3110  char longword[MAXWLEN + 1];
3111
3112  if (gap->ga_len == 0) {
3113    return;
3114  }
3115  suggest_T *stp = &SUG(*gap, 0);
3116  for (int i = gap->ga_len - 1; i >= 0; i--) {
3117    // Need to append what follows to check for "the the".
3118    xstrlcpy(longword, stp[i].st_word, MAXWLEN + 1);
3119    int len = stp[i].st_wordlen;
3120    xstrlcpy(longword + len, su->su_badptr + stp[i].st_orglen, MAXWLEN + 1 - (size_t)len);
3121    hlf_T attr = HLF_COUNT;
3122    spell_check(curwin, longword, &attr, NULL, false);
3123    if (attr != HLF_COUNT) {
3124      // Remove this entry.
3125      xfree(stp[i].st_word);
3126      gap->ga_len--;
3127      if (i < gap->ga_len) {
3128        memmove(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{
3137  hash_T hash = hash_hash(word);
3138  const size_t word_len = strlen(word);
3139  hashitem_T *hi = hash_lookup(&su->su_banned, word, word_len, hash);
3140  if (!HASHITEM_EMPTY(hi)) {  // already present
3141    return;
3142  }
3143  char *s = xmemdupz(word, word_len);
3144  hash_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{
3151  if (su->su_sallang != NULL) {
3152    for (int i = 0; i < su->su_ga.ga_len; i++) {
3153      rescore_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{
3161  slang_T *slang = stp->st_slang;
3162  char sal_badword[MAXWLEN];
3163
3164  // Only rescore suggestions that have no sal score yet and do have a
3165  // language.
3166  if (slang != NULL && !GA_EMPTY(&slang->sl_sal) && !stp->st_had_bonus) {
3167    char *p;
3168    if (slang == su->su_sallang) {
3169      p = su->su_sal_badword;
3170    } else {
3171      spell_soundfold(slang, su->su_fbadword, true, sal_badword);
3172      p = sal_badword;
3173    }
3174
3175    stp->st_altscore = stp_sal_score(stp, su, slang, p);
3176    if (stp->st_altscore == SCORE_MAXMAX) {
3177      stp->st_altscore = SCORE_BIG;
3178    }
3179    stp->st_score = RESCORE(stp->st_score, stp->st_altscore);
3180    stp->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{
3188  suggest_T *p1 = (suggest_T *)s1;
3189  suggest_T *p2 = (suggest_T *)s2;
3190  int n = p1->st_score == p2->st_score ? 0 : p1->st_score > p2->st_score ? 1 : -1;
3191
3192  if (n == 0) {
3193    n = p1->st_altscore == p2->st_altscore ? 0 : p1->st_altscore > p2->st_altscore ? 1 : -1;
3194    if (n == 0) {
3195      n = STRICMP(p1->st_word, p2->st_word);
3196    }
3197  }
3198  return 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)
3209  FUNC_ATTR_NONNULL_ALL
3210{
3211  if (gap->ga_len <= 0) {
3212    return maxscore;
3213  }
3214
3215  // Sort the list.
3216  qsort(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.
3219  if (gap->ga_len > keep) {
3220    suggest_T *const stp = &SUG(*gap, 0);
3221
3222    for (int i = keep; i < gap->ga_len; i++) {
3223      xfree(stp[i].st_word);
3224    }
3225    gap->ga_len = keep;
3226    if (keep >= 1) {
3227      return stp[keep - 1].st_score;
3228    }
3229  }
3230  return 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{
3242  char *goodsound = goodstart;
3243  char *badsound = badstart;
3244  int 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.
3248  if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound) {
3249    if ((badsound[0] == NUL && goodsound[1] == NUL)
3250        || (goodsound[0] == NUL && badsound[1] == NUL)) {
3251      // changing word with vowel to word without a sound
3252      return SCORE_DEL;
3253    }
3254    if (badsound[0] == NUL || goodsound[0] == NUL) {
3255      // more than two changes
3256      return SCORE_MAXMAX;
3257    }
3258
3259    if (badsound[1] == goodsound[1]
3260        || (badsound[1] != NUL
3261            && goodsound[1] != NUL
3262            && badsound[2] == goodsound[2])) {
3263      // handle like a substitute
3264    } else {
3265      score = 2 * SCORE_DEL / 3;
3266      if (*badsound == '*') {
3267        badsound++;
3268      } else {
3269        goodsound++;
3270      }
3271    }
3272  }
3273
3274  int goodlen = (int)strlen(goodsound);
3275  int badlen = (int)strlen(badsound);
3276
3277  // Return quickly if the lengths are too different to be fixed by two
3278  // changes.
3279  int n = goodlen - badlen;
3280  if (n < -2 || n > 2) {
3281    return SCORE_MAXMAX;
3282  }
3283
3284  // n > 0 : goodsound is longest
3285  // n <= 0 : badsound is longest
3286  char *pl = n > 0 ? goodsound : badsound;
3287  char *ps = n > 0 ? badsound : goodsound;
3288
3289  // Skip over the identical part.
3290  while (*pl == *ps && *pl != NUL) {
3291    pl++;
3292    ps++;
3293  }
3294
3295  char *pl2, *ps2;
3296
3297  switch (n) {
3298  case -2:
3299  case 2:
3300    // Must delete two characters from "pl".
3301    pl++;               // first delete
3302    while (*pl == *ps) {
3303      pl++;
3304      ps++;
3305    }
3306    // strings must be equal after second delete
3307    if (strcmp(pl + 1, ps) == 0) {
3308      return score + SCORE_DEL * 2;
3309    }
3310
3311    // Failed to compare.
3312    break;
3313
3314  case -1:
3315  case 1:
3316    // Minimal one delete from "pl" required.
3317
3318    // 1: delete
3319    pl2 = pl + 1;
3320    ps2 = ps;
3321    while (*pl2 == *ps2) {
3322      if (*pl2 == NUL) {                // reached the end
3323        return score + SCORE_DEL;
3324      }
3325      pl2++;
3326      ps2++;
3327    }
3328
3329    // 2: delete then swap, then rest must be equal
3330    if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3331        && strcmp(pl2 + 2, ps2 + 2) == 0) {
3332      return score + SCORE_DEL + SCORE_SWAP;
3333    }
3334
3335    // 3: delete then substitute, then the rest must be equal
3336    if (strcmp(pl2 + 1, ps2 + 1) == 0) {
3337      return score + SCORE_DEL + SCORE_SUBST;
3338    }
3339
3340    // 4: first swap then delete
3341    if (pl[0] == ps[1] && pl[1] == ps[0]) {
3342      pl2 = pl + 2;                 // swap, skip two chars
3343      ps2 = ps + 2;
3344      while (*pl2 == *ps2) {
3345        pl2++;
3346        ps2++;
3347      }
3348      // delete a char and then strings must be equal
3349      if (strcmp(pl2 + 1, ps2) == 0) {
3350        return score + SCORE_SWAP + SCORE_DEL;
3351      }
3352    }
3353
3354    // 5: first substitute then delete
3355    pl2 = pl + 1;                   // substitute, skip one char
3356    ps2 = ps + 1;
3357    while (*pl2 == *ps2) {
3358      pl2++;
3359      ps2++;
3360    }
3361    // delete a char and then strings must be equal
3362    if (strcmp(pl2 + 1, ps2) == 0) {
3363      return score + SCORE_SUBST + SCORE_DEL;
3364    }
3365
3366    // Failed to compare.
3367    break;
3368
3369  case 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
3373    if (*pl == NUL) {
3374      return score;
3375    }
3376
3377    // 2: swap
3378    if (pl[0] == ps[1] && pl[1] == ps[0]) {
3379      pl2 = pl + 2;                 // swap, skip two chars
3380      ps2 = ps + 2;
3381      while (*pl2 == *ps2) {
3382        if (*pl2 == NUL) {              // reached the end
3383          return score + SCORE_SWAP;
3384        }
3385        pl2++;
3386        ps2++;
3387      }
3388      // 3: swap and swap again
3389      if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3390          && strcmp(pl2 + 2, ps2 + 2) == 0) {
3391        return score + SCORE_SWAP + SCORE_SWAP;
3392      }
3393
3394      // 4: swap and substitute
3395      if (strcmp(pl2 + 1, ps2 + 1) == 0) {
3396        return score + SCORE_SWAP + SCORE_SUBST;
3397      }
3398    }
3399
3400    // 5: substitute
3401    pl2 = pl + 1;
3402    ps2 = ps + 1;
3403    while (*pl2 == *ps2) {
3404      if (*pl2 == NUL) {                // reached the end
3405        return score + SCORE_SUBST;
3406      }
3407      pl2++;
3408      ps2++;
3409    }
3410
3411    // 6: substitute and swap
3412    if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3413        && strcmp(pl2 + 2, ps2 + 2) == 0) {
3414      return score + SCORE_SUBST + SCORE_SWAP;
3415    }
3416
3417    // 7: substitute and substitute
3418    if (strcmp(pl2 + 1, ps2 + 1) == 0) {
3419      return score + SCORE_SUBST + SCORE_SUBST;
3420    }
3421
3422    // 8: insert then delete
3423    pl2 = pl;
3424    ps2 = ps + 1;
3425    while (*pl2 == *ps2) {
3426      pl2++;
3427      ps2++;
3428    }
3429    if (strcmp(pl2 + 1, ps2) == 0) {
3430      return score + SCORE_INS + SCORE_DEL;
3431    }
3432
3433    // 9: delete then insert
3434    pl2 = pl + 1;
3435    ps2 = ps;
3436    while (*pl2 == *ps2) {
3437      pl2++;
3438      ps2++;
3439    }
3440    if (strcmp(pl2, ps2 + 1) == 0) {
3441      return score + SCORE_INS + SCORE_DEL;
3442    }
3443
3444    // Failed to compare.
3445    break;
3446  }
3447
3448  return 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{
3460  int wbadword[MAXWLEN];
3461  int wgoodword[MAXWLEN];
3462
3463  // Lengths with NUL.
3464  int badlen;
3465  int goodlen;
3466  {
3467    // Get the characters from the multi-byte strings and put them in an
3468    // int array for easy access.
3469    badlen = 0;
3470    for (const char *p = badword; *p != NUL;) {
3471      wbadword[badlen++] = mb_cptr2char_adv(&p);
3472    }
3473    wbadword[badlen++] = 0;
3474    goodlen = 0;
3475    for (const char *p = goodword; *p != NUL;) {
3476      wgoodword[goodlen++] = mb_cptr2char_adv(&p);
3477    }
3478    wgoodword[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)]
3483  int *cnt = xmalloc(sizeof(int) * ((size_t)badlen + 1) * ((size_t)goodlen + 1));
3484
3485  CNT(0, 0) = 0;
3486  for (int j = 1; j <= goodlen; j++) {
3487    CNT(0, j) = CNT(0, j - 1) + SCORE_INS;
3488  }
3489
3490  for (int i = 1; i <= badlen; i++) {
3491    CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL;
3492    for (int j = 1; j <= goodlen; j++) {
3493      int bc = wbadword[i - 1];
3494      int gc = wgoodword[j - 1];
3495      if (bc == gc) {
3496        CNT(i, j) = CNT(i - 1, j - 1);
3497      } else {
3498        // Use a better score when there is only a case difference.
3499        if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) {
3500          CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1);
3501        } else {
3502          // For a similar character use SCORE_SIMILAR.
3503          if (slang != NULL
3504              && slang->sl_has_map
3505              && similar_chars(slang, gc, bc)) {
3506            CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1);
3507          } else {
3508            CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1);
3509          }
3510        }
3511
3512        if (i > 1 && j > 1) {
3513          int pbc = wbadword[i - 2];
3514          int pgc = wgoodword[j - 2];
3515          if (bc == pgc && pbc == gc) {
3516            int t = SCORE_SWAP + CNT(i - 2, j - 2);
3517            CNT(i, j) = MIN(CNT(i, j), t);
3518          }
3519        }
3520        int t = SCORE_DEL + CNT(i - 1, j);
3521        CNT(i, j) = MIN(CNT(i, j), t);
3522        t = SCORE_INS + CNT(i, j - 1);
3523        CNT(i, j) = MIN(CNT(i, j), t);
3524      }
3525    }
3526  }
3527
3528  int i = CNT(badlen - 1, goodlen - 1);
3529  xfree(cnt);
3530  return i;
3531}
3532
3533typedef struct {
3534  int badi;
3535  int goodi;
3536  int 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{
3547  return 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,
3553                                    int limit)
3554{
3555  limitscore_T stack[10];               // allow for over 3 * 2 edits
3556  int bc, gc;
3557  int score_off;
3558  int wbadword[MAXWLEN];
3559  int wgoodword[MAXWLEN];
3560
3561  // Get the characters from the multi-byte strings and put them in an
3562  // int array for easy access.
3563  int bi = 0;
3564  for (const char *p = badword; *p != NUL;) {
3565    wbadword[bi++] = mb_cptr2char_adv(&p);
3566  }
3567  wbadword[bi++] = 0;
3568  int gi = 0;
3569  for (const char *p = goodword; *p != NUL;) {
3570    wgoodword[gi++] = mb_cptr2char_adv(&p);
3571  }
3572  wgoodword[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".
3581  int stackidx = 0;
3582  bi = 0;
3583  gi = 0;
3584  int score = 0;
3585  int minscore = limit + 1;
3586
3587  while (true) {
3588    // Skip over an equal part, score remains the same.
3589    while (true) {
3590      bc = wbadword[bi];
3591      gc = wgoodword[gi];
3592
3593      if (bc != gc) {           // stop at a char that's different
3594        break;
3595      }
3596      if (bc == NUL) {          // both words end
3597        if (score < minscore) {
3598          minscore = score;
3599        }
3600        goto pop;               // do next alternative
3601      }
3602      bi++;
3603      gi++;
3604    }
3605
3606    if (gc == NUL) {      // goodword ends, delete badword chars
3607      do {
3608        if ((score += SCORE_DEL) >= minscore) {
3609          goto pop;                 // do next alternative
3610        }
3611      } while (wbadword[++bi] != NUL);
3612      minscore = score;
3613    } else if (bc == NUL) {   // badword ends, insert badword chars
3614      do {
3615        if ((score += SCORE_INS) >= minscore) {
3616          goto pop;                 // do next alternative
3617        }
3618      } while (wgoodword[++gi] != NUL);
3619      minscore = 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
3625      for (int round = 0; round <= 1; round++) {
3626        score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
3627        if (score_off < minscore) {
3628          if (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.
3632            int bi2 = bi + 1 - round;
3633            int gi2 = gi + round;
3634            while (wgoodword[gi2] == wbadword[bi2]) {
3635              if (wgoodword[gi2] == NUL) {
3636                minscore = score_off;
3637                break;
3638              }
3639              bi2++;
3640              gi2++;
3641            }
3642          } else {
3643            // try deleting a character from badword later
3644            stack[stackidx].badi = bi + 1 - round;
3645            stack[stackidx].goodi = gi + round;
3646            stack[stackidx].score = score_off;
3647            stackidx++;
3648          }
3649        }
3650      }
3651
3652      if (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.
3656        if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1]) {
3657          // Swap two characters, that is: skip them.
3658          gi += 2;
3659          bi += 2;
3660          score += SCORE_SWAP;
3661          continue;
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.
3668      if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc)) {
3669        score += SCORE_ICASE;
3670      } else {
3671        // For a similar character use SCORE_SIMILAR.
3672        if (slang != NULL
3673            && slang->sl_has_map
3674            && similar_chars(slang, gc, bc)) {
3675          score += SCORE_SIMILAR;
3676        } else {
3677          score += SCORE_SUBST;
3678        }
3679      }
3680
3681      if (score < minscore) {
3682        // Do the substitution.
3683        gi++;
3684        bi++;
3685        continue;
3686      }
3687    }
3688pop:
3689    // Get here to try the next alternative, pop it from the stack.
3690    if (stackidx == 0) {                // stack is empty, finished
3691      break;
3692    }
3693
3694    // pop an item from the stack
3695    stackidx--;
3696    gi = stack[stackidx].goodi;
3697    bi = stack[stackidx].badi;
3698    score = 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.
3704  if (minscore > limit) {
3705    return SCORE_MAXMAX;
3706  }
3707  return minscore;
3708}