blob: ecc0a7403d6ab968923ed217969db908352476b0 [file] [log] [blame]
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * spellsuggest.c: functions for spelling suggestions
12 */
13
14#include "vim.h"
15
16#if defined(FEAT_SPELL) || defined(PROTO)
17
18/*
19 * Use this to adjust the score after finding suggestions, based on the
20 * suggested word sounding like the bad word. This is much faster than doing
21 * it for every possible suggestion.
22 * Disadvantage: When "the" is typed as "hte" it sounds quite different ("@"
23 * vs "ht") and goes down in the list.
24 * Used when 'spellsuggest' is set to "best".
25 */
kylo252ae6f1d82022-02-16 19:24:07 +000026#define RESCORE(word_score, sound_score) ((3 * (word_score) + (sound_score)) / 4)
Bram Moolenaar46a426c2019-09-27 12:41:56 +020027
28/*
29 * Do the opposite: based on a maximum end score and a known sound score,
30 * compute the maximum word score that can be used.
31 */
kylo252ae6f1d82022-02-16 19:24:07 +000032#define MAXSCORE(word_score, sound_score) ((4 * (word_score) - (sound_score)) / 3)
Bram Moolenaar46a426c2019-09-27 12:41:56 +020033
34// only used for su_badflags
35#define WF_MIXCAP 0x20 // mix of upper and lower case: macaRONI
36
37/*
38 * Information used when looking for suggestions.
39 */
40typedef struct suginfo_S
41{
42 garray_T su_ga; // suggestions, contains "suggest_T"
43 int su_maxcount; // max. number of suggestions displayed
44 int su_maxscore; // maximum score for adding to su_ga
45 int su_sfmaxscore; // idem, for when doing soundfold words
46 garray_T su_sga; // like su_ga, sound-folded scoring
47 char_u *su_badptr; // start of bad word in line
48 int su_badlen; // length of detected bad word in line
49 int su_badflags; // caps flags for bad word
50 char_u su_badword[MAXWLEN]; // bad word truncated at su_badlen
51 char_u su_fbadword[MAXWLEN]; // su_badword case-folded
52 char_u su_sal_badword[MAXWLEN]; // su_badword soundfolded
53 hashtab_T su_banned; // table with banned words
54 slang_T *su_sallang; // default language for sound folding
55} suginfo_T;
56
57// One word suggestion. Used in "si_ga".
58typedef struct suggest_S
59{
60 char_u *st_word; // suggested word, allocated string
61 int st_wordlen; // STRLEN(st_word)
62 int st_orglen; // length of replaced text
63 int st_score; // lower is better
64 int st_altscore; // used when st_score compares equal
65 int st_salscore; // st_score is for soundalike
66 int st_had_bonus; // bonus already included in score
67 slang_T *st_slang; // language used for sound folding
68} suggest_T;
69
70#define SUG(ga, i) (((suggest_T *)(ga).ga_data)[i])
71
72// TRUE if a word appears in the list of banned words.
kylo252ae6f1d82022-02-16 19:24:07 +000073#define WAS_BANNED(su, word) (!HASHITEM_EMPTY(hash_find(&(su)->su_banned, word)))
Bram Moolenaar46a426c2019-09-27 12:41:56 +020074
75// Number of suggestions kept when cleaning up. We need to keep more than
76// what is displayed, because when rescore_suggestions() is called the score
77// may change and wrong suggestions may be removed later.
78#define SUG_CLEAN_COUNT(su) ((su)->su_maxcount < 130 ? 150 : (su)->su_maxcount + 20)
79
80// Threshold for sorting and cleaning up suggestions. Don't want to keep lots
81// of suggestions that are not going to be displayed.
82#define SUG_MAX_COUNT(su) (SUG_CLEAN_COUNT(su) + 50)
83
84// score for various changes
85#define SCORE_SPLIT 149 // split bad word
86#define SCORE_SPLIT_NO 249 // split bad word with NOSPLITSUGS
87#define SCORE_ICASE 52 // slightly different case
88#define SCORE_REGION 200 // word is for different region
89#define SCORE_RARE 180 // rare word
90#define SCORE_SWAP 75 // swap two characters
91#define SCORE_SWAP3 110 // swap two characters in three
92#define SCORE_REP 65 // REP replacement
93#define SCORE_SUBST 93 // substitute a character
94#define SCORE_SIMILAR 33 // substitute a similar character
95#define SCORE_SUBCOMP 33 // substitute a composing character
96#define SCORE_DEL 94 // delete a character
97#define SCORE_DELDUP 66 // delete a duplicated character
98#define SCORE_DELCOMP 28 // delete a composing character
99#define SCORE_INS 96 // insert a character
100#define SCORE_INSDUP 67 // insert a duplicate character
101#define SCORE_INSCOMP 30 // insert a composing character
102#define SCORE_NONWORD 103 // change non-word to word char
103
104#define SCORE_FILE 30 // suggestion from a file
105#define SCORE_MAXINIT 350 // Initial maximum score: higher == slower.
106 // 350 allows for about three changes.
107
108#define SCORE_COMMON1 30 // subtracted for words seen before
109#define SCORE_COMMON2 40 // subtracted for words often seen
110#define SCORE_COMMON3 50 // subtracted for words very often seen
111#define SCORE_THRES2 10 // word count threshold for COMMON2
112#define SCORE_THRES3 100 // word count threshold for COMMON3
113
114// When trying changed soundfold words it becomes slow when trying more than
Dominique Pelleaf4a61a2021-12-27 17:21:41 +0000115// two changes. With less than two changes it's slightly faster but we miss a
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200116// few good suggestions. In rare cases we need to try three of four changes.
117#define SCORE_SFMAX1 200 // maximum score for first try
118#define SCORE_SFMAX2 300 // maximum score for second try
119#define SCORE_SFMAX3 400 // maximum score for third try
120
kylo252ae6f1d82022-02-16 19:24:07 +0000121#define SCORE_BIG (SCORE_INS * 3) // big difference
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200122#define SCORE_MAXMAX 999999 // accept any score
123#define SCORE_LIMITMAX 350 // for spell_edit_score_limit()
124
125// for spell_edit_score_limit() we need to know the minimum value of
126// SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS
127#define SCORE_EDIT_MIN SCORE_SIMILAR
128
129/*
130 * For finding suggestions: At each node in the tree these states are tried:
131 */
132typedef enum
133{
134 STATE_START = 0, // At start of node check for NUL bytes (goodword
135 // ends); if badword ends there is a match, otherwise
136 // try splitting word.
137 STATE_NOPREFIX, // try without prefix
138 STATE_SPLITUNDO, // Undo splitting.
139 STATE_ENDNUL, // Past NUL bytes at start of the node.
140 STATE_PLAIN, // Use each byte of the node.
141 STATE_DEL, // Delete a byte from the bad word.
142 STATE_INS_PREP, // Prepare for inserting bytes.
143 STATE_INS, // Insert a byte in the bad word.
144 STATE_SWAP, // Swap two bytes.
145 STATE_UNSWAP, // Undo swap two characters.
146 STATE_SWAP3, // Swap two characters over three.
147 STATE_UNSWAP3, // Undo Swap two characters over three.
148 STATE_UNROT3L, // Undo rotate three characters left
149 STATE_UNROT3R, // Undo rotate three characters right
150 STATE_REP_INI, // Prepare for using REP items.
151 STATE_REP, // Use matching REP items from the .aff file.
152 STATE_REP_UNDO, // Undo a REP item replacement.
153 STATE_FINAL // End of this node.
154} state_T;
155
156/*
157 * Struct to keep the state at each level in suggest_try_change().
158 */
159typedef struct trystate_S
160{
161 state_T ts_state; // state at this level, STATE_
162 int ts_score; // score
163 idx_T ts_arridx; // index in tree array, start of node
164 short ts_curi; // index in list of child nodes
165 char_u ts_fidx; // index in fword[], case-folded bad word
166 char_u ts_fidxtry; // ts_fidx at which bytes may be changed
167 char_u ts_twordlen; // valid length of tword[]
168 char_u ts_prefixdepth; // stack depth for end of prefix or
169 // PFD_PREFIXTREE or PFD_NOPREFIX
170 char_u ts_flags; // TSF_ flags
171 char_u ts_tcharlen; // number of bytes in tword character
172 char_u ts_tcharidx; // current byte index in tword character
173 char_u ts_isdiff; // DIFF_ values
174 char_u ts_fcharstart; // index in fword where badword char started
175 char_u ts_prewordlen; // length of word in "preword[]"
176 char_u ts_splitoff; // index in "tword" after last split
177 char_u ts_splitfidx; // "ts_fidx" at word split
178 char_u ts_complen; // nr of compound words used
179 char_u ts_compsplit; // index for "compflags" where word was spit
180 char_u ts_save_badflags; // su_badflags saved here
181 char_u ts_delidx; // index in fword for char that was deleted,
182 // valid when "ts_flags" has TSF_DIDDEL
183} trystate_T;
184
185// values for ts_isdiff
186#define DIFF_NONE 0 // no different byte (yet)
187#define DIFF_YES 1 // different byte found
188#define DIFF_INSERT 2 // inserting character
189
190// values for ts_flags
191#define TSF_PREFIXOK 1 // already checked that prefix is OK
192#define TSF_DIDSPLIT 2 // tried split at this point
193#define TSF_DIDDEL 4 // did a delete, "ts_delidx" has index
194
195// special values ts_prefixdepth
196#define PFD_NOPREFIX 0xff // not using prefixes
197#define PFD_PREFIXTREE 0xfe // walking through the prefix tree
198#define PFD_NOTSPECIAL 0xfd // highest value that's not special
199
Bram Moolenaar585ee072022-01-29 11:22:17 +0000200static long spell_suggest_timeout = 5000;
201
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200202static void spell_find_suggest(char_u *badptr, int badlen, suginfo_T *su, int maxcount, int banbadword, int need_cap, int interactive);
203#ifdef FEAT_EVAL
204static void spell_suggest_expr(suginfo_T *su, char_u *expr);
205#endif
206static void spell_suggest_file(suginfo_T *su, char_u *fname);
207static void spell_suggest_intern(suginfo_T *su, int interactive);
208static void spell_find_cleanup(suginfo_T *su);
209static void suggest_try_special(suginfo_T *su);
210static void suggest_try_change(suginfo_T *su);
211static void suggest_trie_walk(suginfo_T *su, langp_T *lp, char_u *fword, int soundfold);
212static void go_deeper(trystate_T *stack, int depth, int score_add);
213static void find_keepcap_word(slang_T *slang, char_u *fword, char_u *kword);
214static void score_comp_sal(suginfo_T *su);
215static void score_combine(suginfo_T *su);
216static int stp_sal_score(suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *badsound);
217static void suggest_try_soundalike_prep(void);
218static void suggest_try_soundalike(suginfo_T *su);
219static void suggest_try_soundalike_finish(void);
220static void add_sound_suggest(suginfo_T *su, char_u *goodword, int score, langp_T *lp);
221static int soundfold_find(slang_T *slang, char_u *word);
222static int similar_chars(slang_T *slang, int c1, int c2);
223static void add_suggestion(suginfo_T *su, garray_T *gap, char_u *goodword, int badlen, int score, int altscore, int had_bonus, slang_T *slang, int maxsf);
224static void check_suggestions(suginfo_T *su, garray_T *gap);
225static void add_banned(suginfo_T *su, char_u *word);
226static void rescore_suggestions(suginfo_T *su);
227static void rescore_one(suginfo_T *su, suggest_T *stp);
228static int cleanup_suggestions(garray_T *gap, int maxscore, int keep);
229static int soundalike_score(char_u *goodsound, char_u *badsound);
230static int spell_edit_score(slang_T *slang, char_u *badword, char_u *goodword);
231static int spell_edit_score_limit(slang_T *slang, char_u *badword, char_u *goodword, int limit);
232static int spell_edit_score_limit_w(slang_T *slang, char_u *badword, char_u *goodword, int limit);
233
234/*
235 * Return TRUE when the sequence of flags in "compflags" plus "flag" can
236 * possibly form a valid compounded word. This also checks the COMPOUNDRULE
237 * lines if they don't contain wildcards.
238 */
239 static int
240can_be_compound(
241 trystate_T *sp,
242 slang_T *slang,
243 char_u *compflags,
244 int flag)
245{
246 // If the flag doesn't appear in sl_compstartflags or sl_compallflags
247 // then it can't possibly compound.
248 if (!byte_in_str(sp->ts_complen == sp->ts_compsplit
249 ? slang->sl_compstartflags : slang->sl_compallflags, flag))
250 return FALSE;
251
252 // If there are no wildcards, we can check if the flags collected so far
253 // possibly can form a match with COMPOUNDRULE patterns. This only
254 // makes sense when we have two or more words.
255 if (slang->sl_comprules != NULL && sp->ts_complen > sp->ts_compsplit)
256 {
257 int v;
258
259 compflags[sp->ts_complen] = flag;
260 compflags[sp->ts_complen + 1] = NUL;
261 v = match_compoundrule(slang, compflags + sp->ts_compsplit);
262 compflags[sp->ts_complen] = NUL;
263 return v;
264 }
265
266 return TRUE;
267}
268
269/*
270 * Adjust the score of common words.
271 */
272 static int
273score_wordcount_adj(
274 slang_T *slang,
275 int score,
276 char_u *word,
277 int split) // word was split, less bonus
278{
279 hashitem_T *hi;
280 wordcount_T *wc;
281 int bonus;
282 int newscore;
283
284 hi = hash_find(&slang->sl_wordcount, word);
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +0000285 if (HASHITEM_EMPTY(hi))
286 return score;
287
288 wc = HI2WC(hi);
289 if (wc->wc_count < SCORE_THRES2)
290 bonus = SCORE_COMMON1;
291 else if (wc->wc_count < SCORE_THRES3)
292 bonus = SCORE_COMMON2;
293 else
294 bonus = SCORE_COMMON3;
295 if (split)
296 newscore = score - bonus / 2;
297 else
298 newscore = score - bonus;
299 if (newscore < 0)
300 return 0;
301 return newscore;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200302}
303
304/*
305 * Like captype() but for a KEEPCAP word add ONECAP if the word starts with a
306 * capital. So that make_case_word() can turn WOrd into Word.
307 * Add ALLCAP for "WOrD".
308 */
309 static int
310badword_captype(char_u *word, char_u *end)
311{
312 int flags = captype(word, end);
313 int c;
314 int l, u;
315 int first;
316 char_u *p;
317
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +0000318 if (!(flags & WF_KEEPCAP))
319 return flags;
320
321 // Count the number of UPPER and lower case letters.
322 l = u = 0;
323 first = FALSE;
324 for (p = word; p < end; MB_PTR_ADV(p))
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200325 {
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +0000326 c = PTR2CHAR(p);
327 if (SPELL_ISUPPER(c))
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200328 {
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +0000329 ++u;
330 if (p == word)
331 first = TRUE;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200332 }
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +0000333 else
334 ++l;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200335 }
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +0000336
337 // If there are more UPPER than lower case letters suggest an
338 // ALLCAP word. Otherwise, if the first letter is UPPER then
339 // suggest ONECAP. Exception: "ALl" most likely should be "All",
340 // require three upper case letters.
341 if (u > l && u > 2)
342 flags |= WF_ALLCAP;
343 else if (first)
344 flags |= WF_ONECAP;
345
346 if (u >= 2 && l >= 2) // maCARONI maCAroni
347 flags |= WF_MIXCAP;
348
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200349 return flags;
350}
351
352/*
353 * Opposite of offset2bytes().
354 * "pp" points to the bytes and is advanced over it.
355 * Returns the offset.
356 */
357 static int
358bytes2offset(char_u **pp)
359{
360 char_u *p = *pp;
361 int nr;
362 int c;
363
364 c = *p++;
365 if ((c & 0x80) == 0x00) // 1 byte
366 {
367 nr = c - 1;
368 }
369 else if ((c & 0xc0) == 0x80) // 2 bytes
370 {
371 nr = (c & 0x3f) - 1;
372 nr = nr * 255 + (*p++ - 1);
373 }
374 else if ((c & 0xe0) == 0xc0) // 3 bytes
375 {
376 nr = (c & 0x1f) - 1;
377 nr = nr * 255 + (*p++ - 1);
378 nr = nr * 255 + (*p++ - 1);
379 }
380 else // 4 bytes
381 {
382 nr = (c & 0x0f) - 1;
383 nr = nr * 255 + (*p++ - 1);
384 nr = nr * 255 + (*p++ - 1);
385 nr = nr * 255 + (*p++ - 1);
386 }
387
388 *pp = p;
389 return nr;
390}
391
392// values for sps_flags
393#define SPS_BEST 1
394#define SPS_FAST 2
395#define SPS_DOUBLE 4
396
397static int sps_flags = SPS_BEST; // flags from 'spellsuggest'
398static int sps_limit = 9999; // max nr of suggestions given
399
400/*
401 * Check the 'spellsuggest' option. Return FAIL if it's wrong.
402 * Sets "sps_flags" and "sps_limit".
403 */
404 int
405spell_check_sps(void)
406{
407 char_u *p;
408 char_u *s;
409 char_u buf[MAXPATHL];
410 int f;
411
412 sps_flags = 0;
413 sps_limit = 9999;
414
415 for (p = p_sps; *p != NUL; )
416 {
417 copy_option_part(&p, buf, MAXPATHL, ",");
418
419 f = 0;
420 if (VIM_ISDIGIT(*buf))
421 {
422 s = buf;
423 sps_limit = getdigits(&s);
424 if (*s != NUL && !VIM_ISDIGIT(*s))
425 f = -1;
426 }
Yee Cheng Chin900894b2023-09-29 20:42:32 +0200427 // Note: Keep this in sync with p_sps_values.
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200428 else if (STRCMP(buf, "best") == 0)
429 f = SPS_BEST;
430 else if (STRCMP(buf, "fast") == 0)
431 f = SPS_FAST;
432 else if (STRCMP(buf, "double") == 0)
433 f = SPS_DOUBLE;
434 else if (STRNCMP(buf, "expr:", 5) != 0
Bram Moolenaar585ee072022-01-29 11:22:17 +0000435 && STRNCMP(buf, "file:", 5) != 0
436 && (STRNCMP(buf, "timeout:", 8) != 0
437 || (!VIM_ISDIGIT(buf[8])
438 && !(buf[8] == '-' && VIM_ISDIGIT(buf[9])))))
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200439 f = -1;
440
441 if (f == -1 || (sps_flags != 0 && f != 0))
442 {
443 sps_flags = SPS_BEST;
444 sps_limit = 9999;
445 return FAIL;
446 }
447 if (f != 0)
448 sps_flags = f;
449 }
450
451 if (sps_flags == 0)
452 sps_flags = SPS_BEST;
453
454 return OK;
455}
456
457/*
458 * "z=": Find badly spelled word under or after the cursor.
459 * Give suggestions for the properly spelled word.
460 * In Visual mode use the highlighted word as the bad word.
461 * When "count" is non-zero use that suggestion.
462 */
463 void
464spell_suggest(int count)
465{
466 char_u *line;
467 pos_T prev_cursor = curwin->w_cursor;
468 char_u wcopy[MAXWLEN + 2];
469 char_u *p;
470 int i;
471 int c;
472 suginfo_T sug;
473 suggest_T *stp;
474 int mouse_used;
475 int need_cap;
476 int limit;
477 int selected = count;
478 int badlen = 0;
479 int msg_scroll_save = msg_scroll;
Bram Moolenaar152e79e2020-06-10 15:32:08 +0200480 int wo_spell_save = curwin->w_p_spell;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200481
Bram Moolenaar152e79e2020-06-10 15:32:08 +0200482 if (!curwin->w_p_spell)
483 {
Yegappan Lakshmananaf936912023-02-20 12:16:39 +0000484 parse_spelllang(curwin);
Bram Moolenaar152e79e2020-06-10 15:32:08 +0200485 curwin->w_p_spell = TRUE;
486 }
487
488 if (*curwin->w_s->b_p_spl == NUL)
489 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000490 emsg(_(e_spell_checking_is_not_possible));
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200491 return;
Bram Moolenaar152e79e2020-06-10 15:32:08 +0200492 }
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200493
494 if (VIsual_active)
495 {
496 // Use the Visually selected text as the bad word. But reject
497 // a multi-line selection.
498 if (curwin->w_cursor.lnum != VIsual.lnum)
499 {
500 vim_beep(BO_SPELL);
501 return;
502 }
503 badlen = (int)curwin->w_cursor.col - (int)VIsual.col;
504 if (badlen < 0)
505 badlen = -badlen;
506 else
507 curwin->w_cursor.col = VIsual.col;
508 ++badlen;
509 end_visual_mode();
Bram Moolenaar5c686172022-03-13 20:12:25 +0000510 // make sure we don't include the NUL at the end of the line
511 line = ml_get_curline();
Bram Moolenaar6e2e2cc2022-03-14 19:24:46 +0000512 if (badlen > (int)STRLEN(line) - (int)curwin->w_cursor.col)
Yegappan Lakshmanan5cffa8d2022-03-16 13:33:53 +0000513 badlen = (int)STRLEN(line) - (int)curwin->w_cursor.col;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200514 }
515 // Find the start of the badly spelled word.
516 else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0
517 || curwin->w_cursor.col > prev_cursor.col)
518 {
519 // No bad word or it starts after the cursor: use the word under the
520 // cursor.
521 curwin->w_cursor = prev_cursor;
522 line = ml_get_curline();
523 p = line + curwin->w_cursor.col;
524 // Backup to before start of word.
525 while (p > line && spell_iswordp_nmw(p, curwin))
526 MB_PTR_BACK(line, p);
527 // Forward to start of word.
528 while (*p != NUL && !spell_iswordp_nmw(p, curwin))
529 MB_PTR_ADV(p);
530
531 if (!spell_iswordp_nmw(p, curwin)) // No word found.
532 {
533 beep_flush();
534 return;
535 }
536 curwin->w_cursor.col = (colnr_T)(p - line);
537 }
538
539 // Get the word and its length.
540
541 // Figure out if the word should be capitalised.
Luuk van Baal2ac64972023-05-25 17:14:42 +0100542 need_cap = check_need_cap(curwin, curwin->w_cursor.lnum,
543 curwin->w_cursor.col);
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200544
545 // Make a copy of current line since autocommands may free the line.
546 line = vim_strsave(ml_get_curline());
547 if (line == NULL)
548 goto skip;
549
550 // Get the list of suggestions. Limit to 'lines' - 2 or the number in
551 // 'spellsuggest', whatever is smaller.
552 if (sps_limit > (int)Rows - 2)
553 limit = (int)Rows - 2;
554 else
555 limit = sps_limit;
556 spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
557 TRUE, need_cap, TRUE);
558
559 if (sug.su_ga.ga_len == 0)
560 msg(_("Sorry, no suggestions"));
561 else if (count > 0)
562 {
563 if (count > sug.su_ga.ga_len)
Bram Moolenaar6c52f822019-12-25 14:13:03 +0100564 smsg(_("Sorry, only %ld suggestions"), (long)sug.su_ga.ga_len);
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200565 }
566 else
567 {
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200568#ifdef FEAT_RIGHTLEFT
569 // When 'rightleft' is set the list is drawn right-left.
570 cmdmsg_rl = curwin->w_p_rl;
571 if (cmdmsg_rl)
572 msg_col = Columns - 1;
573#endif
574
575 // List the suggestions.
576 msg_start();
577 msg_row = Rows - 1; // for when 'cmdheight' > 1
578 lines_left = Rows; // avoid more prompt
579 vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"),
580 sug.su_badlen, sug.su_badptr);
581#ifdef FEAT_RIGHTLEFT
582 if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0)
583 {
584 // And now the rabbit from the high hat: Avoid showing the
585 // untranslated message rightleft.
586 vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC",
587 sug.su_badlen, sug.su_badptr);
588 }
589#endif
590 msg_puts((char *)IObuff);
591 msg_clr_eos();
592 msg_putchar('\n');
593
594 msg_scroll = TRUE;
595 for (i = 0; i < sug.su_ga.ga_len; ++i)
596 {
Bram Moolenaar1eead4c2022-07-30 11:39:57 +0100597 int el;
598
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200599 stp = &SUG(sug.su_ga, i);
600
601 // The suggested word may replace only part of the bad word, add
Bram Moolenaar1eead4c2022-07-30 11:39:57 +0100602 // the not replaced part. But only when it's not getting too long.
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200603 vim_strncpy(wcopy, stp->st_word, MAXWLEN);
Bram Moolenaar1eead4c2022-07-30 11:39:57 +0100604 el = sug.su_badlen - stp->st_orglen;
605 if (el > 0 && stp->st_wordlen + el <= MAXWLEN)
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200606 vim_strncpy(wcopy + stp->st_wordlen,
Bram Moolenaar1eead4c2022-07-30 11:39:57 +0100607 sug.su_badptr + stp->st_orglen, el);
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200608 vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1);
609#ifdef FEAT_RIGHTLEFT
610 if (cmdmsg_rl)
611 rl_mirror(IObuff);
612#endif
613 msg_puts((char *)IObuff);
614
615 vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy);
616 msg_puts((char *)IObuff);
617
618 // The word may replace more than "su_badlen".
619 if (sug.su_badlen < stp->st_orglen)
620 {
621 vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""),
622 stp->st_orglen, sug.su_badptr);
623 msg_puts((char *)IObuff);
624 }
625
626 if (p_verbose > 0)
627 {
628 // Add the score.
629 if (sps_flags & (SPS_DOUBLE | SPS_BEST))
630 vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)",
631 stp->st_salscore ? "s " : "",
632 stp->st_score, stp->st_altscore);
633 else
634 vim_snprintf((char *)IObuff, IOSIZE, " (%d)",
635 stp->st_score);
636#ifdef FEAT_RIGHTLEFT
637 if (cmdmsg_rl)
638 // Mirror the numbers, but keep the leading space.
639 rl_mirror(IObuff + 1);
640#endif
641 msg_advance(30);
642 msg_puts((char *)IObuff);
643 }
644 msg_putchar('\n');
645 }
646
647#ifdef FEAT_RIGHTLEFT
648 cmdmsg_rl = FALSE;
649 msg_col = 0;
650#endif
651 // Ask for choice.
652 selected = prompt_for_number(&mouse_used);
653 if (mouse_used)
654 selected -= lines_left;
655 lines_left = Rows; // avoid more prompt
656 // don't delay for 'smd' in normal_cmd()
657 msg_scroll = msg_scroll_save;
658 }
659
660 if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)
661 {
662 // Save the from and to text for :spellrepall.
Bram Moolenaar6c52f822019-12-25 14:13:03 +0100663 VIM_CLEAR(repl_from);
664 VIM_CLEAR(repl_to);
665
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200666 stp = &SUG(sug.su_ga, selected - 1);
667 if (sug.su_badlen > stp->st_orglen)
668 {
669 // Replacing less than "su_badlen", append the remainder to
670 // repl_to.
671 repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);
672 vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word,
673 sug.su_badlen - stp->st_orglen,
674 sug.su_badptr + stp->st_orglen);
675 repl_to = vim_strsave(IObuff);
676 }
677 else
678 {
679 // Replacing su_badlen or more, use the whole word.
680 repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);
681 repl_to = vim_strsave(stp->st_word);
682 }
683
684 // Replace the word.
685 p = alloc(STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1);
686 if (p != NULL)
687 {
LemonBoyb7a70122022-05-13 12:41:50 +0100688 int len_diff = stp->st_wordlen - stp->st_orglen;
689
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200690 c = (int)(sug.su_badptr - line);
691 mch_memmove(p, line, c);
692 STRCPY(p + c, stp->st_word);
693 STRCAT(p, sug.su_badptr + stp->st_orglen);
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200694
695 // For redo we use a change-word command.
696 ResetRedobuff();
697 AppendToRedobuff((char_u *)"ciw");
698 AppendToRedobuffLit(p + c,
699 stp->st_wordlen + sug.su_badlen - stp->st_orglen);
700 AppendCharToRedobuff(ESC);
701
Bram Moolenaar6b949612020-06-29 23:18:42 +0200702 // "p" may be freed here
703 ml_replace(curwin->w_cursor.lnum, p, FALSE);
704 curwin->w_cursor.col = c;
705
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200706 changed_bytes(curwin->w_cursor.lnum, c);
Martin Tournoijba43e762022-10-13 22:12:15 +0100707#if defined(FEAT_PROP_POPUP)
LemonBoyb7a70122022-05-13 12:41:50 +0100708 if (curbuf->b_has_textprop && len_diff != 0)
709 adjust_prop_columns(curwin->w_cursor.lnum, c, len_diff,
710 APC_SUBSTITUTE);
Martin Tournoijba43e762022-10-13 22:12:15 +0100711#endif
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200712 }
713 }
714 else
715 curwin->w_cursor = prev_cursor;
716
717 spell_find_cleanup(&sug);
718skip:
719 vim_free(line);
Bram Moolenaar152e79e2020-06-10 15:32:08 +0200720 curwin->w_p_spell = wo_spell_save;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200721}
722
723/*
724 * Find spell suggestions for "word". Return them in the growarray "*gap" as
725 * a list of allocated strings.
726 */
727 void
728spell_suggest_list(
729 garray_T *gap,
730 char_u *word,
731 int maxcount, // maximum nr of suggestions
732 int need_cap, // 'spellcapcheck' matched
733 int interactive)
734{
735 suginfo_T sug;
736 int i;
737 suggest_T *stp;
738 char_u *wcopy;
739
740 spell_find_suggest(word, 0, &sug, maxcount, FALSE, need_cap, interactive);
741
742 // Make room in "gap".
743 ga_init2(gap, sizeof(char_u *), sug.su_ga.ga_len + 1);
744 if (ga_grow(gap, sug.su_ga.ga_len) == OK)
745 {
746 for (i = 0; i < sug.su_ga.ga_len; ++i)
747 {
748 stp = &SUG(sug.su_ga, i);
749
750 // The suggested word may replace only part of "word", add the not
751 // replaced part.
752 wcopy = alloc(stp->st_wordlen
753 + (unsigned)STRLEN(sug.su_badptr + stp->st_orglen) + 1);
754 if (wcopy == NULL)
755 break;
756 STRCPY(wcopy, stp->st_word);
757 STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen);
758 ((char_u **)gap->ga_data)[gap->ga_len++] = wcopy;
759 }
760 }
761
762 spell_find_cleanup(&sug);
763}
764
765/*
766 * Find spell suggestions for the word at the start of "badptr".
767 * Return the suggestions in "su->su_ga".
768 * The maximum number of suggestions is "maxcount".
769 * Note: does use info for the current window.
770 * This is based on the mechanisms of Aspell, but completely reimplemented.
771 */
772 static void
773spell_find_suggest(
774 char_u *badptr,
775 int badlen, // length of bad word or 0 if unknown
776 suginfo_T *su,
777 int maxcount,
778 int banbadword, // don't include badword in suggestions
779 int need_cap, // word should start with capital
780 int interactive)
781{
782 hlf_T attr = HLF_COUNT;
783 char_u buf[MAXPATHL];
784 char_u *p;
785 int do_combine = FALSE;
786 char_u *sps_copy;
787#ifdef FEAT_EVAL
788 static int expr_busy = FALSE;
789#endif
790 int c;
791 int i;
792 langp_T *lp;
Bram Moolenaar77a849c2021-01-20 21:42:33 +0100793 int did_intern = FALSE;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200794
795 // Set the info in "*su".
Bram Moolenaara80faa82020-04-12 19:37:17 +0200796 CLEAR_POINTER(su);
Bram Moolenaar04935fb2022-01-08 16:19:22 +0000797 ga_init2(&su->su_ga, sizeof(suggest_T), 10);
798 ga_init2(&su->su_sga, sizeof(suggest_T), 10);
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200799 if (*badptr == NUL)
800 return;
801 hash_init(&su->su_banned);
802
803 su->su_badptr = badptr;
804 if (badlen != 0)
805 su->su_badlen = badlen;
806 else
807 su->su_badlen = spell_check(curwin, su->su_badptr, &attr, NULL, FALSE);
808 su->su_maxcount = maxcount;
809 su->su_maxscore = SCORE_MAXINIT;
810
811 if (su->su_badlen >= MAXWLEN)
812 su->su_badlen = MAXWLEN - 1; // just in case
813 vim_strncpy(su->su_badword, su->su_badptr, su->su_badlen);
Bram Moolenaar4f135272021-06-11 19:07:40 +0200814 (void)spell_casefold(curwin, su->su_badptr, su->su_badlen,
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200815 su->su_fbadword, MAXWLEN);
816 // TODO: make this work if the case-folded text is longer than the original
817 // text. Currently an illegal byte causes wrong pointer computations.
818 su->su_fbadword[su->su_badlen] = NUL;
819
820 // get caps flags for bad word
821 su->su_badflags = badword_captype(su->su_badptr,
822 su->su_badptr + su->su_badlen);
823 if (need_cap)
824 su->su_badflags |= WF_ONECAP;
825
826 // Find the default language for sound folding. We simply use the first
827 // one in 'spelllang' that supports sound folding. That's good for when
828 // using multiple files for one language, it's not that bad when mixing
829 // languages (e.g., "pl,en").
830 for (i = 0; i < curbuf->b_s.b_langp.ga_len; ++i)
831 {
832 lp = LANGP_ENTRY(curbuf->b_s.b_langp, i);
833 if (lp->lp_sallang != NULL)
834 {
835 su->su_sallang = lp->lp_sallang;
836 break;
837 }
838 }
839
840 // Soundfold the bad word with the default sound folding, so that we don't
841 // have to do this many times.
842 if (su->su_sallang != NULL)
843 spell_soundfold(su->su_sallang, su->su_fbadword, TRUE,
844 su->su_sal_badword);
845
846 // If the word is not capitalised and spell_check() doesn't consider the
847 // word to be bad then it might need to be capitalised. Add a suggestion
848 // for that.
849 c = PTR2CHAR(su->su_badptr);
850 if (!SPELL_ISUPPER(c) && attr == HLF_COUNT)
851 {
852 make_case_word(su->su_badword, buf, WF_ONECAP);
853 add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE,
854 0, TRUE, su->su_sallang, FALSE);
855 }
856
857 // Ban the bad word itself. It may appear in another region.
858 if (banbadword)
859 add_banned(su, su->su_badword);
860
861 // Make a copy of 'spellsuggest', because the expression may change it.
862 sps_copy = vim_strsave(p_sps);
863 if (sps_copy == NULL)
864 return;
Bram Moolenaar585ee072022-01-29 11:22:17 +0000865 spell_suggest_timeout = 5000;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200866
867 // Loop over the items in 'spellsuggest'.
868 for (p = sps_copy; *p != NUL; )
869 {
870 copy_option_part(&p, buf, MAXPATHL, ",");
871
872 if (STRNCMP(buf, "expr:", 5) == 0)
873 {
874#ifdef FEAT_EVAL
875 // Evaluate an expression. Skip this when called recursively,
876 // when using spellsuggest() in the expression.
877 if (!expr_busy)
878 {
879 expr_busy = TRUE;
880 spell_suggest_expr(su, buf + 5);
881 expr_busy = FALSE;
882 }
883#endif
884 }
885 else if (STRNCMP(buf, "file:", 5) == 0)
886 // Use list of suggestions in a file.
887 spell_suggest_file(su, buf + 5);
Bram Moolenaar585ee072022-01-29 11:22:17 +0000888 else if (STRNCMP(buf, "timeout:", 8) == 0)
889 // Limit the time searching for suggestions.
890 spell_suggest_timeout = atol((char *)buf + 8);
Bram Moolenaar77a849c2021-01-20 21:42:33 +0100891 else if (!did_intern)
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200892 {
Bram Moolenaar77a849c2021-01-20 21:42:33 +0100893 // Use internal method once.
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200894 spell_suggest_intern(su, interactive);
895 if (sps_flags & SPS_DOUBLE)
896 do_combine = TRUE;
Bram Moolenaar77a849c2021-01-20 21:42:33 +0100897 did_intern = TRUE;
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200898 }
899 }
900
901 vim_free(sps_copy);
902
903 if (do_combine)
904 // Combine the two list of suggestions. This must be done last,
905 // because sorting changes the order again.
906 score_combine(su);
907}
908
909#ifdef FEAT_EVAL
910/*
911 * Find suggestions by evaluating expression "expr".
912 */
913 static void
914spell_suggest_expr(suginfo_T *su, char_u *expr)
915{
916 list_T *list;
917 listitem_T *li;
918 int score;
919 char_u *p;
920
921 // The work is split up in a few parts to avoid having to export
922 // suginfo_T.
923 // First evaluate the expression and get the resulting list.
924 list = eval_spell_expr(su->su_badword, expr);
925 if (list != NULL)
926 {
927 // Loop over the items in the list.
Bram Moolenaaraeea7212020-04-02 18:50:46 +0200928 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200929 if (li->li_tv.v_type == VAR_LIST)
930 {
931 // Get the word and the score from the items.
932 score = get_spellword(li->li_tv.vval.v_list, &p);
933 if (score >= 0 && score <= su->su_maxscore)
934 add_suggestion(su, &su->su_ga, p, su->su_badlen,
935 score, 0, TRUE, su->su_sallang, FALSE);
936 }
937 list_unref(list);
938 }
939
940 // Remove bogus suggestions, sort and truncate at "maxcount".
941 check_suggestions(su, &su->su_ga);
942 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
943}
944#endif
945
946/*
947 * Find suggestions in file "fname". Used for "file:" in 'spellsuggest'.
948 */
949 static void
950spell_suggest_file(suginfo_T *su, char_u *fname)
951{
952 FILE *fd;
953 char_u line[MAXWLEN * 2];
954 char_u *p;
955 int len;
956 char_u cword[MAXWLEN];
957
958 // Open the file.
959 fd = mch_fopen((char *)fname, "r");
960 if (fd == NULL)
961 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +0000962 semsg(_(e_cant_open_file_str), fname);
Bram Moolenaar46a426c2019-09-27 12:41:56 +0200963 return;
964 }
965
966 // Read it line by line.
967 while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int)
968 {
969 line_breakcheck();
970
971 p = vim_strchr(line, '/');
972 if (p == NULL)
973 continue; // No Tab found, just skip the line.
974 *p++ = NUL;
975 if (STRICMP(su->su_badword, line) == 0)
976 {
977 // Match! Isolate the good word, until CR or NL.
978 for (len = 0; p[len] >= ' '; ++len)
979 ;
980 p[len] = NUL;
981
982 // If the suggestion doesn't have specific case duplicate the case
983 // of the bad word.
984 if (captype(p, NULL) == 0)
985 {
986 make_case_word(p, cword, su->su_badflags);
987 p = cword;
988 }
989
990 add_suggestion(su, &su->su_ga, p, su->su_badlen,
991 SCORE_FILE, 0, TRUE, su->su_sallang, FALSE);
992 }
993 }
994
995 fclose(fd);
996
997 // Remove bogus suggestions, sort and truncate at "maxcount".
998 check_suggestions(su, &su->su_ga);
999 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
1000}
1001
1002/*
1003 * Find suggestions for the internal method indicated by "sps_flags".
1004 */
1005 static void
1006spell_suggest_intern(suginfo_T *su, int interactive)
1007{
1008 // Load the .sug file(s) that are available and not done yet.
1009 suggest_load_files();
1010
1011 // 1. Try special cases, such as repeating a word: "the the" -> "the".
1012 //
1013 // Set a maximum score to limit the combination of operations that is
1014 // tried.
1015 suggest_try_special(su);
1016
1017 // 2. Try inserting/deleting/swapping/changing a letter, use REP entries
1018 // from the .aff file and inserting a space (split the word).
1019 suggest_try_change(su);
1020
1021 // For the resulting top-scorers compute the sound-a-like score.
1022 if (sps_flags & SPS_DOUBLE)
1023 score_comp_sal(su);
1024
1025 // 3. Try finding sound-a-like words.
1026 if ((sps_flags & SPS_FAST) == 0)
1027 {
1028 if (sps_flags & SPS_BEST)
1029 // Adjust the word score for the suggestions found so far for how
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001030 // they sound like.
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001031 rescore_suggestions(su);
1032
1033 // While going through the soundfold tree "su_maxscore" is the score
1034 // for the soundfold word, limits the changes that are being tried,
1035 // and "su_sfmaxscore" the rescored score, which is set by
1036 // cleanup_suggestions().
1037 // First find words with a small edit distance, because this is much
1038 // faster and often already finds the top-N suggestions. If we didn't
1039 // find many suggestions try again with a higher edit distance.
1040 // "sl_sounddone" is used to avoid doing the same word twice.
1041 suggest_try_soundalike_prep();
1042 su->su_maxscore = SCORE_SFMAX1;
1043 su->su_sfmaxscore = SCORE_MAXINIT * 3;
1044 suggest_try_soundalike(su);
1045 if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
1046 {
1047 // We didn't find enough matches, try again, allowing more
1048 // changes to the soundfold word.
1049 su->su_maxscore = SCORE_SFMAX2;
1050 suggest_try_soundalike(su);
1051 if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
1052 {
1053 // Still didn't find enough matches, try again, allowing even
1054 // more changes to the soundfold word.
1055 su->su_maxscore = SCORE_SFMAX3;
1056 suggest_try_soundalike(su);
1057 }
1058 }
1059 su->su_maxscore = su->su_sfmaxscore;
1060 suggest_try_soundalike_finish();
1061 }
1062
1063 // When CTRL-C was hit while searching do show the results. Only clear
1064 // got_int when using a command, not for spellsuggest().
1065 ui_breakcheck();
1066 if (interactive && got_int)
1067 {
1068 (void)vgetc();
1069 got_int = FALSE;
1070 }
1071
1072 if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0)
1073 {
1074 if (sps_flags & SPS_BEST)
1075 // Adjust the word score for how it sounds like.
1076 rescore_suggestions(su);
1077
1078 // Remove bogus suggestions, sort and truncate at "maxcount".
1079 check_suggestions(su, &su->su_ga);
1080 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
1081 }
1082}
1083
1084/*
1085 * Free the info put in "*su" by spell_find_suggest().
1086 */
1087 static void
1088spell_find_cleanup(suginfo_T *su)
1089{
1090 int i;
1091
1092 // Free the suggestions.
1093 for (i = 0; i < su->su_ga.ga_len; ++i)
1094 vim_free(SUG(su->su_ga, i).st_word);
1095 ga_clear(&su->su_ga);
1096 for (i = 0; i < su->su_sga.ga_len; ++i)
1097 vim_free(SUG(su->su_sga, i).st_word);
1098 ga_clear(&su->su_sga);
1099
1100 // Free the banned words.
1101 hash_clear_all(&su->su_banned, 0);
1102}
1103
1104/*
1105 * Try finding suggestions by recognizing specific situations.
1106 */
1107 static void
1108suggest_try_special(suginfo_T *su)
1109{
1110 char_u *p;
1111 size_t len;
1112 int c;
1113 char_u word[MAXWLEN];
1114
1115 // Recognize a word that is repeated: "the the".
1116 p = skiptowhite(su->su_fbadword);
1117 len = p - su->su_fbadword;
1118 p = skipwhite(p);
1119 if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0)
1120 {
1121 // Include badflags: if the badword is onecap or allcap
1122 // use that for the goodword too: "The the" -> "The".
1123 c = su->su_fbadword[len];
1124 su->su_fbadword[len] = NUL;
1125 make_case_word(su->su_fbadword, word, su->su_badflags);
1126 su->su_fbadword[len] = c;
1127
1128 // Give a soundalike score of 0, compute the score as if deleting one
1129 // character.
1130 add_suggestion(su, &su->su_ga, word, su->su_badlen,
1131 RESCORE(SCORE_REP, 0), 0, TRUE, su->su_sallang, FALSE);
1132 }
1133}
1134
1135/*
1136 * Change the 0 to 1 to measure how much time is spent in each state.
1137 * Output is dumped in "suggestprof".
1138 */
1139#if 0
1140# define SUGGEST_PROFILE
1141proftime_T current;
1142proftime_T total;
1143proftime_T times[STATE_FINAL + 1];
1144long counts[STATE_FINAL + 1];
1145
1146 static void
1147prof_init(void)
1148{
1149 for (int i = 0; i <= STATE_FINAL; ++i)
1150 {
1151 profile_zero(&times[i]);
1152 counts[i] = 0;
1153 }
1154 profile_start(&current);
1155 profile_start(&total);
1156}
1157
1158// call before changing state
1159 static void
1160prof_store(state_T state)
1161{
1162 profile_end(&current);
1163 profile_add(&times[state], &current);
1164 ++counts[state];
1165 profile_start(&current);
1166}
1167# define PROF_STORE(state) prof_store(state);
1168
1169 static void
1170prof_report(char *name)
1171{
1172 FILE *fd = fopen("suggestprof", "a");
1173
1174 profile_end(&total);
1175 fprintf(fd, "-----------------------\n");
1176 fprintf(fd, "%s: %s\n", name, profile_msg(&total));
1177 for (int i = 0; i <= STATE_FINAL; ++i)
1178 fprintf(fd, "%d: %s (%ld)\n", i, profile_msg(&times[i]), counts[i]);
1179 fclose(fd);
1180}
1181#else
1182# define PROF_STORE(state)
1183#endif
1184
1185/*
1186 * Try finding suggestions by adding/removing/swapping letters.
1187 */
1188 static void
1189suggest_try_change(suginfo_T *su)
1190{
1191 char_u fword[MAXWLEN]; // copy of the bad word, case-folded
1192 int n;
1193 char_u *p;
1194 int lpi;
1195 langp_T *lp;
1196
1197 // We make a copy of the case-folded bad word, so that we can modify it
1198 // to find matches (esp. REP items). Append some more text, changing
1199 // chars after the bad word may help.
1200 STRCPY(fword, su->su_fbadword);
1201 n = (int)STRLEN(fword);
1202 p = su->su_badptr + su->su_badlen;
Bram Moolenaar4f135272021-06-11 19:07:40 +02001203 (void)spell_casefold(curwin, p, (int)STRLEN(p), fword + n, MAXWLEN - n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001204
Bram Moolenaare275ba42021-10-06 13:41:07 +01001205 // Make sure the resulting text is not longer than the original text.
1206 n = (int)STRLEN(su->su_badptr);
1207 if (n < MAXWLEN)
1208 fword[n] = NUL;
1209
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001210 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
1211 {
1212 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
1213
1214 // If reloading a spell file fails it's still in the list but
1215 // everything has been cleared.
1216 if (lp->lp_slang->sl_fbyts == NULL)
1217 continue;
1218
1219 // Try it for this language. Will add possible suggestions.
1220#ifdef SUGGEST_PROFILE
1221 prof_init();
1222#endif
1223 suggest_trie_walk(su, lp, fword, FALSE);
1224#ifdef SUGGEST_PROFILE
1225 prof_report("try_change");
1226#endif
1227 }
1228}
1229
1230// Check the maximum score, if we go over it we won't try this change.
1231#define TRY_DEEPER(su, stack, depth, add) \
kylo252ae6f1d82022-02-16 19:24:07 +00001232 ((depth) < MAXWLEN - 1 && (stack)[depth].ts_score + (add) < (su)->su_maxscore)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001233
1234/*
1235 * Try finding suggestions by adding/removing/swapping letters.
1236 *
1237 * This uses a state machine. At each node in the tree we try various
1238 * operations. When trying if an operation works "depth" is increased and the
1239 * stack[] is used to store info. This allows combinations, thus insert one
1240 * character, replace one and delete another. The number of changes is
1241 * limited by su->su_maxscore.
1242 *
1243 * After implementing this I noticed an article by Kemal Oflazer that
1244 * describes something similar: "Error-tolerant Finite State Recognition with
1245 * Applications to Morphological Analysis and Spelling Correction" (1996).
1246 * The implementation in the article is simplified and requires a stack of
1247 * unknown depth. The implementation here only needs a stack depth equal to
1248 * the length of the word.
1249 *
1250 * This is also used for the sound-folded word, "soundfold" is TRUE then.
1251 * The mechanism is the same, but we find a match with a sound-folded word
1252 * that comes from one or more original words. Each of these words may be
1253 * added, this is done by add_sound_suggest().
1254 * Don't use:
1255 * the prefix tree or the keep-case tree
1256 * "su->su_badlen"
1257 * anything to do with upper and lower case
1258 * anything to do with word or non-word characters ("spell_iswordp()")
1259 * banned words
1260 * word flags (rare, region, compounding)
1261 * word splitting for now
1262 * "similar_chars()"
1263 * use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep"
1264 */
1265 static void
1266suggest_trie_walk(
1267 suginfo_T *su,
1268 langp_T *lp,
1269 char_u *fword,
1270 int soundfold)
1271{
1272 char_u tword[MAXWLEN]; // good word collected so far
1273 trystate_T stack[MAXWLEN];
1274 char_u preword[MAXWLEN * 3]; // word found with proper case;
1275 // concatenation of prefix compound
1276 // words and split word. NUL terminated
1277 // when going deeper but not when coming
1278 // back.
1279 char_u compflags[MAXWLEN]; // compound flags, one for each word
1280 trystate_T *sp;
1281 int newscore;
1282 int score;
1283 char_u *byts, *fbyts, *pbyts;
1284 idx_T *idxs, *fidxs, *pidxs;
1285 int depth;
1286 int c, c2, c3;
1287 int n = 0;
1288 int flags;
1289 garray_T *gap;
1290 idx_T arridx;
1291 int len;
1292 char_u *p;
1293 fromto_T *ftp;
1294 int fl = 0, tl;
1295 int repextra = 0; // extra bytes in fword[] from REP item
1296 slang_T *slang = lp->lp_slang;
1297 int fword_ends;
1298 int goodword_ends;
1299#ifdef DEBUG_TRIEWALK
1300 // Stores the name of the change made at each level.
1301 char_u changename[MAXWLEN][80];
1302#endif
1303 int breakcheckcount = 1000;
Bram Moolenaar06f15412022-01-29 10:51:59 +00001304#ifdef FEAT_RELTIME
1305 proftime_T time_limit;
1306#endif
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001307 int compound_ok;
1308
1309 // Go through the whole case-fold tree, try changes at each node.
1310 // "tword[]" contains the word collected from nodes in the tree.
1311 // "fword[]" the word we are trying to match with (initially the bad
1312 // word).
1313 depth = 0;
1314 sp = &stack[0];
Bram Moolenaara80faa82020-04-12 19:37:17 +02001315 CLEAR_POINTER(sp);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001316 sp->ts_curi = 1;
1317
1318 if (soundfold)
1319 {
1320 // Going through the soundfold tree.
1321 byts = fbyts = slang->sl_sbyts;
1322 idxs = fidxs = slang->sl_sidxs;
1323 pbyts = NULL;
1324 pidxs = NULL;
1325 sp->ts_prefixdepth = PFD_NOPREFIX;
1326 sp->ts_state = STATE_START;
1327 }
1328 else
1329 {
1330 // When there are postponed prefixes we need to use these first. At
1331 // the end of the prefix we continue in the case-fold tree.
1332 fbyts = slang->sl_fbyts;
1333 fidxs = slang->sl_fidxs;
1334 pbyts = slang->sl_pbyts;
1335 pidxs = slang->sl_pidxs;
1336 if (pbyts != NULL)
1337 {
1338 byts = pbyts;
1339 idxs = pidxs;
1340 sp->ts_prefixdepth = PFD_PREFIXTREE;
1341 sp->ts_state = STATE_NOPREFIX; // try without prefix first
1342 }
1343 else
1344 {
1345 byts = fbyts;
1346 idxs = fidxs;
1347 sp->ts_prefixdepth = PFD_NOPREFIX;
1348 sp->ts_state = STATE_START;
1349 }
1350 }
Bram Moolenaar06f15412022-01-29 10:51:59 +00001351#ifdef FEAT_RELTIME
Bram Moolenaar585ee072022-01-29 11:22:17 +00001352 // The loop may take an indefinite amount of time. Break out after some
1353 // time.
1354 if (spell_suggest_timeout > 0)
1355 profile_setlimit(spell_suggest_timeout, &time_limit);
Bram Moolenaar06f15412022-01-29 10:51:59 +00001356#endif
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001357
1358 // Loop to find all suggestions. At each round we either:
1359 // - For the current state try one operation, advance "ts_curi",
1360 // increase "depth".
1361 // - When a state is done go to the next, set "ts_state".
1362 // - When all states are tried decrease "depth".
1363 while (depth >= 0 && !got_int)
1364 {
1365 sp = &stack[depth];
1366 switch (sp->ts_state)
1367 {
1368 case STATE_START:
1369 case STATE_NOPREFIX:
1370 // Start of node: Deal with NUL bytes, which means
1371 // tword[] may end here.
1372 arridx = sp->ts_arridx; // current node in the tree
1373 len = byts[arridx]; // bytes in this node
1374 arridx += sp->ts_curi; // index of current byte
1375
1376 if (sp->ts_prefixdepth == PFD_PREFIXTREE)
1377 {
1378 // Skip over the NUL bytes, we use them later.
1379 for (n = 0; n < len && byts[arridx + n] == 0; ++n)
1380 ;
1381 sp->ts_curi += n;
1382
1383 // Always past NUL bytes now.
1384 n = (int)sp->ts_state;
1385 PROF_STORE(sp->ts_state)
1386 sp->ts_state = STATE_ENDNUL;
1387 sp->ts_save_badflags = su->su_badflags;
1388
1389 // At end of a prefix or at start of prefixtree: check for
1390 // following word.
Bram Moolenaar6970e1e2022-01-30 12:10:39 +00001391 if (depth < MAXWLEN - 1
Bram Moolenaar06f15412022-01-29 10:51:59 +00001392 && (byts[arridx] == 0 || n == (int)STATE_NOPREFIX))
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001393 {
1394 // Set su->su_badflags to the caps type at this position.
1395 // Use the caps type until here for the prefix itself.
1396 if (has_mbyte)
1397 n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
1398 else
1399 n = sp->ts_fidx;
1400 flags = badword_captype(su->su_badptr, su->su_badptr + n);
1401 su->su_badflags = badword_captype(su->su_badptr + n,
1402 su->su_badptr + su->su_badlen);
1403#ifdef DEBUG_TRIEWALK
1404 sprintf(changename[depth], "prefix");
1405#endif
1406 go_deeper(stack, depth, 0);
1407 ++depth;
1408 sp = &stack[depth];
1409 sp->ts_prefixdepth = depth - 1;
1410 byts = fbyts;
1411 idxs = fidxs;
1412 sp->ts_arridx = 0;
1413
1414 // Move the prefix to preword[] with the right case
1415 // and make find_keepcap_word() works.
1416 tword[sp->ts_twordlen] = NUL;
1417 make_case_word(tword + sp->ts_splitoff,
1418 preword + sp->ts_prewordlen, flags);
1419 sp->ts_prewordlen = (char_u)STRLEN(preword);
1420 sp->ts_splitoff = sp->ts_twordlen;
1421 }
1422 break;
1423 }
1424
1425 if (sp->ts_curi > len || byts[arridx] != 0)
1426 {
1427 // Past bytes in node and/or past NUL bytes.
1428 PROF_STORE(sp->ts_state)
1429 sp->ts_state = STATE_ENDNUL;
1430 sp->ts_save_badflags = su->su_badflags;
1431 break;
1432 }
1433
1434 // End of word in tree.
1435 ++sp->ts_curi; // eat one NUL byte
1436
1437 flags = (int)idxs[arridx];
1438
1439 // Skip words with the NOSUGGEST flag.
1440 if (flags & WF_NOSUGGEST)
1441 break;
1442
1443 fword_ends = (fword[sp->ts_fidx] == NUL
1444 || (soundfold
1445 ? VIM_ISWHITE(fword[sp->ts_fidx])
1446 : !spell_iswordp(fword + sp->ts_fidx, curwin)));
1447 tword[sp->ts_twordlen] = NUL;
1448
1449 if (sp->ts_prefixdepth <= PFD_NOTSPECIAL
Bram Moolenaar11b66002020-07-01 13:15:24 +02001450 && (sp->ts_flags & TSF_PREFIXOK) == 0
1451 && pbyts != NULL)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001452 {
1453 // There was a prefix before the word. Check that the prefix
1454 // can be used with this word.
1455 // Count the length of the NULs in the prefix. If there are
1456 // none this must be the first try without a prefix.
1457 n = stack[sp->ts_prefixdepth].ts_arridx;
1458 len = pbyts[n++];
1459 for (c = 0; c < len && pbyts[n + c] == 0; ++c)
1460 ;
1461 if (c > 0)
1462 {
1463 c = valid_word_prefix(c, n, flags,
1464 tword + sp->ts_splitoff, slang, FALSE);
1465 if (c == 0)
1466 break;
1467
1468 // Use the WF_RARE flag for a rare prefix.
1469 if (c & WF_RAREPFX)
1470 flags |= WF_RARE;
1471
1472 // Tricky: when checking for both prefix and compounding
1473 // we run into the prefix flag first.
1474 // Remember that it's OK, so that we accept the prefix
1475 // when arriving at a compound flag.
1476 sp->ts_flags |= TSF_PREFIXOK;
1477 }
1478 }
1479
1480 // Check NEEDCOMPOUND: can't use word without compounding. Do try
1481 // appending another compound word below.
1482 if (sp->ts_complen == sp->ts_compsplit && fword_ends
1483 && (flags & WF_NEEDCOMP))
1484 goodword_ends = FALSE;
1485 else
1486 goodword_ends = TRUE;
1487
1488 p = NULL;
1489 compound_ok = TRUE;
1490 if (sp->ts_complen > sp->ts_compsplit)
1491 {
1492 if (slang->sl_nobreak)
1493 {
1494 // There was a word before this word. When there was no
1495 // change in this word (it was correct) add the first word
1496 // as a suggestion. If this word was corrected too, we
1497 // need to check if a correct word follows.
1498 if (sp->ts_fidx - sp->ts_splitfidx
1499 == sp->ts_twordlen - sp->ts_splitoff
1500 && STRNCMP(fword + sp->ts_splitfidx,
1501 tword + sp->ts_splitoff,
1502 sp->ts_fidx - sp->ts_splitfidx) == 0)
1503 {
1504 preword[sp->ts_prewordlen] = NUL;
1505 newscore = score_wordcount_adj(slang, sp->ts_score,
1506 preword + sp->ts_prewordlen,
1507 sp->ts_prewordlen > 0);
1508 // Add the suggestion if the score isn't too bad.
1509 if (newscore <= su->su_maxscore)
1510 add_suggestion(su, &su->su_ga, preword,
1511 sp->ts_splitfidx - repextra,
1512 newscore, 0, FALSE,
1513 lp->lp_sallang, FALSE);
1514 break;
1515 }
1516 }
1517 else
1518 {
1519 // There was a compound word before this word. If this
1520 // word does not support compounding then give up
1521 // (splitting is tried for the word without compound
1522 // flag).
1523 if (((unsigned)flags >> 24) == 0
1524 || sp->ts_twordlen - sp->ts_splitoff
1525 < slang->sl_compminlen)
1526 break;
1527 // For multi-byte chars check character length against
1528 // COMPOUNDMIN.
1529 if (has_mbyte
1530 && slang->sl_compminlen > 0
1531 && mb_charlen(tword + sp->ts_splitoff)
1532 < slang->sl_compminlen)
1533 break;
1534
1535 compflags[sp->ts_complen] = ((unsigned)flags >> 24);
1536 compflags[sp->ts_complen + 1] = NUL;
1537 vim_strncpy(preword + sp->ts_prewordlen,
1538 tword + sp->ts_splitoff,
1539 sp->ts_twordlen - sp->ts_splitoff);
1540
1541 // Verify CHECKCOMPOUNDPATTERN rules.
1542 if (match_checkcompoundpattern(preword, sp->ts_prewordlen,
1543 &slang->sl_comppat))
1544 compound_ok = FALSE;
1545
1546 if (compound_ok)
1547 {
1548 p = preword;
1549 while (*skiptowhite(p) != NUL)
1550 p = skipwhite(skiptowhite(p));
1551 if (fword_ends && !can_compound(slang, p,
1552 compflags + sp->ts_compsplit))
1553 // Compound is not allowed. But it may still be
1554 // possible if we add another (short) word.
1555 compound_ok = FALSE;
1556 }
1557
1558 // Get pointer to last char of previous word.
1559 p = preword + sp->ts_prewordlen;
1560 MB_PTR_BACK(preword, p);
1561 }
1562 }
1563
1564 // Form the word with proper case in preword.
1565 // If there is a word from a previous split, append.
1566 // For the soundfold tree don't change the case, simply append.
1567 if (soundfold)
1568 STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
1569 else if (flags & WF_KEEPCAP)
1570 // Must find the word in the keep-case tree.
1571 find_keepcap_word(slang, tword + sp->ts_splitoff,
1572 preword + sp->ts_prewordlen);
1573 else
1574 {
1575 // Include badflags: If the badword is onecap or allcap
1576 // use that for the goodword too. But if the badword is
1577 // allcap and it's only one char long use onecap.
1578 c = su->su_badflags;
1579 if ((c & WF_ALLCAP)
1580 && su->su_badlen == (*mb_ptr2len)(su->su_badptr))
1581 c = WF_ONECAP;
1582 c |= flags;
1583
1584 // When appending a compound word after a word character don't
1585 // use Onecap.
1586 if (p != NULL && spell_iswordp_nmw(p, curwin))
1587 c &= ~WF_ONECAP;
1588 make_case_word(tword + sp->ts_splitoff,
1589 preword + sp->ts_prewordlen, c);
1590 }
1591
1592 if (!soundfold)
1593 {
1594 // Don't use a banned word. It may appear again as a good
1595 // word, thus remember it.
1596 if (flags & WF_BANNED)
1597 {
1598 add_banned(su, preword + sp->ts_prewordlen);
1599 break;
1600 }
1601 if ((sp->ts_complen == sp->ts_compsplit
1602 && WAS_BANNED(su, preword + sp->ts_prewordlen))
1603 || WAS_BANNED(su, preword))
1604 {
1605 if (slang->sl_compprog == NULL)
1606 break;
1607 // the word so far was banned but we may try compounding
1608 goodword_ends = FALSE;
1609 }
1610 }
1611
1612 newscore = 0;
1613 if (!soundfold) // soundfold words don't have flags
1614 {
1615 if ((flags & WF_REGION)
1616 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
1617 newscore += SCORE_REGION;
1618 if (flags & WF_RARE)
1619 newscore += SCORE_RARE;
1620
1621 if (!spell_valid_case(su->su_badflags,
1622 captype(preword + sp->ts_prewordlen, NULL)))
1623 newscore += SCORE_ICASE;
1624 }
1625
1626 // TODO: how about splitting in the soundfold tree?
1627 if (fword_ends
1628 && goodword_ends
1629 && sp->ts_fidx >= sp->ts_fidxtry
1630 && compound_ok)
1631 {
1632 // The badword also ends: add suggestions.
1633#ifdef DEBUG_TRIEWALK
1634 if (soundfold && STRCMP(preword, "smwrd") == 0)
1635 {
1636 int j;
1637
1638 // print the stack of changes that brought us here
1639 smsg("------ %s -------", fword);
1640 for (j = 0; j < depth; ++j)
1641 smsg("%s", changename[j]);
1642 }
1643#endif
1644 if (soundfold)
1645 {
1646 // For soundfolded words we need to find the original
1647 // words, the edit distance and then add them.
1648 add_sound_suggest(su, preword, sp->ts_score, lp);
1649 }
1650 else if (sp->ts_fidx > 0)
1651 {
1652 // Give a penalty when changing non-word char to word
1653 // char, e.g., "thes," -> "these".
1654 p = fword + sp->ts_fidx;
1655 MB_PTR_BACK(fword, p);
Bram Moolenaar15d98902021-11-04 15:46:05 +00001656 if (!spell_iswordp(p, curwin) && *preword != NUL)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001657 {
1658 p = preword + STRLEN(preword);
1659 MB_PTR_BACK(preword, p);
1660 if (spell_iswordp(p, curwin))
1661 newscore += SCORE_NONWORD;
1662 }
1663
1664 // Give a bonus to words seen before.
1665 score = score_wordcount_adj(slang,
1666 sp->ts_score + newscore,
1667 preword + sp->ts_prewordlen,
1668 sp->ts_prewordlen > 0);
1669
1670 // Add the suggestion if the score isn't too bad.
1671 if (score <= su->su_maxscore)
1672 {
1673 add_suggestion(su, &su->su_ga, preword,
1674 sp->ts_fidx - repextra,
1675 score, 0, FALSE, lp->lp_sallang, FALSE);
1676
1677 if (su->su_badflags & WF_MIXCAP)
1678 {
1679 // We really don't know if the word should be
1680 // upper or lower case, add both.
1681 c = captype(preword, NULL);
1682 if (c == 0 || c == WF_ALLCAP)
1683 {
1684 make_case_word(tword + sp->ts_splitoff,
1685 preword + sp->ts_prewordlen,
1686 c == 0 ? WF_ALLCAP : 0);
1687
1688 add_suggestion(su, &su->su_ga, preword,
1689 sp->ts_fidx - repextra,
1690 score + SCORE_ICASE, 0, FALSE,
1691 lp->lp_sallang, FALSE);
1692 }
1693 }
1694 }
1695 }
1696 }
1697
1698 // Try word split and/or compounding.
1699 if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
1700 // Don't split halfway a character.
1701 && (!has_mbyte || sp->ts_tcharlen == 0))
1702 {
1703 int try_compound;
1704 int try_split;
1705
1706 // If past the end of the bad word don't try a split.
1707 // Otherwise try changing the next word. E.g., find
1708 // suggestions for "the the" where the second "the" is
1709 // different. It's done like a split.
1710 // TODO: word split for soundfold words
1711 try_split = (sp->ts_fidx - repextra < su->su_badlen)
1712 && !soundfold;
1713
1714 // Get here in several situations:
1715 // 1. The word in the tree ends:
1716 // If the word allows compounding try that. Otherwise try
1717 // a split by inserting a space. For both check that a
1718 // valid words starts at fword[sp->ts_fidx].
1719 // For NOBREAK do like compounding to be able to check if
1720 // the next word is valid.
1721 // 2. The badword does end, but it was due to a change (e.g.,
1722 // a swap). No need to split, but do check that the
1723 // following word is valid.
1724 // 3. The badword and the word in the tree end. It may still
1725 // be possible to compound another (short) word.
1726 try_compound = FALSE;
1727 if (!soundfold
1728 && !slang->sl_nocompoundsugs
1729 && slang->sl_compprog != NULL
1730 && ((unsigned)flags >> 24) != 0
1731 && sp->ts_twordlen - sp->ts_splitoff
1732 >= slang->sl_compminlen
1733 && (!has_mbyte
1734 || slang->sl_compminlen == 0
1735 || mb_charlen(tword + sp->ts_splitoff)
1736 >= slang->sl_compminlen)
1737 && (slang->sl_compsylmax < MAXWLEN
1738 || sp->ts_complen + 1 - sp->ts_compsplit
1739 < slang->sl_compmax)
1740 && (can_be_compound(sp, slang,
1741 compflags, ((unsigned)flags >> 24))))
1742
1743 {
1744 try_compound = TRUE;
1745 compflags[sp->ts_complen] = ((unsigned)flags >> 24);
1746 compflags[sp->ts_complen + 1] = NUL;
1747 }
1748
1749 // For NOBREAK we never try splitting, it won't make any word
1750 // valid.
1751 if (slang->sl_nobreak && !slang->sl_nocompoundsugs)
1752 try_compound = TRUE;
1753
1754 // If we could add a compound word, and it's also possible to
1755 // split at this point, do the split first and set
1756 // TSF_DIDSPLIT to avoid doing it again.
1757 else if (!fword_ends
1758 && try_compound
1759 && (sp->ts_flags & TSF_DIDSPLIT) == 0)
1760 {
1761 try_compound = FALSE;
1762 sp->ts_flags |= TSF_DIDSPLIT;
1763 --sp->ts_curi; // do the same NUL again
1764 compflags[sp->ts_complen] = NUL;
1765 }
1766 else
1767 sp->ts_flags &= ~TSF_DIDSPLIT;
1768
1769 if (try_split || try_compound)
1770 {
1771 if (!try_compound && (!fword_ends || !goodword_ends))
1772 {
1773 // If we're going to split need to check that the
1774 // words so far are valid for compounding. If there
1775 // is only one word it must not have the NEEDCOMPOUND
1776 // flag.
1777 if (sp->ts_complen == sp->ts_compsplit
1778 && (flags & WF_NEEDCOMP))
1779 break;
1780 p = preword;
1781 while (*skiptowhite(p) != NUL)
1782 p = skipwhite(skiptowhite(p));
1783 if (sp->ts_complen > sp->ts_compsplit
1784 && !can_compound(slang, p,
1785 compflags + sp->ts_compsplit))
1786 break;
1787
1788 if (slang->sl_nosplitsugs)
1789 newscore += SCORE_SPLIT_NO;
1790 else
1791 newscore += SCORE_SPLIT;
1792
1793 // Give a bonus to words seen before.
1794 newscore = score_wordcount_adj(slang, newscore,
1795 preword + sp->ts_prewordlen, TRUE);
1796 }
1797
1798 if (TRY_DEEPER(su, stack, depth, newscore))
1799 {
1800 go_deeper(stack, depth, newscore);
1801#ifdef DEBUG_TRIEWALK
1802 if (!try_compound && !fword_ends)
1803 sprintf(changename[depth], "%.*s-%s: split",
1804 sp->ts_twordlen, tword, fword + sp->ts_fidx);
1805 else
1806 sprintf(changename[depth], "%.*s-%s: compound",
1807 sp->ts_twordlen, tword, fword + sp->ts_fidx);
1808#endif
1809 // Save things to be restored at STATE_SPLITUNDO.
1810 sp->ts_save_badflags = su->su_badflags;
1811 PROF_STORE(sp->ts_state)
1812 sp->ts_state = STATE_SPLITUNDO;
1813
1814 ++depth;
1815 sp = &stack[depth];
1816
1817 // Append a space to preword when splitting.
1818 if (!try_compound && !fword_ends)
1819 STRCAT(preword, " ");
1820 sp->ts_prewordlen = (char_u)STRLEN(preword);
1821 sp->ts_splitoff = sp->ts_twordlen;
1822 sp->ts_splitfidx = sp->ts_fidx;
1823
1824 // If the badword has a non-word character at this
1825 // position skip it. That means replacing the
1826 // non-word character with a space. Always skip a
1827 // character when the word ends. But only when the
1828 // good word can end.
1829 if (((!try_compound && !spell_iswordp_nmw(fword
1830 + sp->ts_fidx,
1831 curwin))
1832 || fword_ends)
1833 && fword[sp->ts_fidx] != NUL
1834 && goodword_ends)
1835 {
1836 int l;
1837
Bram Moolenaar1614a142019-10-06 22:00:13 +02001838 l = mb_ptr2len(fword + sp->ts_fidx);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001839 if (fword_ends)
1840 {
1841 // Copy the skipped character to preword.
1842 mch_memmove(preword + sp->ts_prewordlen,
1843 fword + sp->ts_fidx, l);
1844 sp->ts_prewordlen += l;
1845 preword[sp->ts_prewordlen] = NUL;
1846 }
1847 else
1848 sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
1849 sp->ts_fidx += l;
1850 }
1851
1852 // When compounding include compound flag in
1853 // compflags[] (already set above). When splitting we
1854 // may start compounding over again.
1855 if (try_compound)
1856 ++sp->ts_complen;
1857 else
1858 sp->ts_compsplit = sp->ts_complen;
1859 sp->ts_prefixdepth = PFD_NOPREFIX;
1860
1861 // set su->su_badflags to the caps type at this
1862 // position
1863 if (has_mbyte)
1864 n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
1865 else
1866 n = sp->ts_fidx;
1867 su->su_badflags = badword_captype(su->su_badptr + n,
1868 su->su_badptr + su->su_badlen);
1869
1870 // Restart at top of the tree.
1871 sp->ts_arridx = 0;
1872
1873 // If there are postponed prefixes, try these too.
1874 if (pbyts != NULL)
1875 {
1876 byts = pbyts;
1877 idxs = pidxs;
1878 sp->ts_prefixdepth = PFD_PREFIXTREE;
1879 PROF_STORE(sp->ts_state)
1880 sp->ts_state = STATE_NOPREFIX;
1881 }
1882 }
1883 }
1884 }
1885 break;
1886
1887 case STATE_SPLITUNDO:
1888 // Undo the changes done for word split or compound word.
1889 su->su_badflags = sp->ts_save_badflags;
1890
1891 // Continue looking for NUL bytes.
1892 PROF_STORE(sp->ts_state)
1893 sp->ts_state = STATE_START;
1894
1895 // In case we went into the prefix tree.
1896 byts = fbyts;
1897 idxs = fidxs;
1898 break;
1899
1900 case STATE_ENDNUL:
1901 // Past the NUL bytes in the node.
1902 su->su_badflags = sp->ts_save_badflags;
1903 if (fword[sp->ts_fidx] == NUL && sp->ts_tcharlen == 0)
1904 {
1905 // The badword ends, can't use STATE_PLAIN.
1906 PROF_STORE(sp->ts_state)
1907 sp->ts_state = STATE_DEL;
1908 break;
1909 }
1910 PROF_STORE(sp->ts_state)
1911 sp->ts_state = STATE_PLAIN;
1912 // FALLTHROUGH
1913
1914 case STATE_PLAIN:
1915 // Go over all possible bytes at this node, add each to tword[]
1916 // and use child node. "ts_curi" is the index.
1917 arridx = sp->ts_arridx;
1918 if (sp->ts_curi > byts[arridx])
1919 {
1920 // Done all bytes at this node, do next state. When still at
1921 // already changed bytes skip the other tricks.
1922 PROF_STORE(sp->ts_state)
1923 if (sp->ts_fidx >= sp->ts_fidxtry)
1924 sp->ts_state = STATE_DEL;
1925 else
1926 sp->ts_state = STATE_FINAL;
1927 }
1928 else
1929 {
1930 arridx += sp->ts_curi++;
1931 c = byts[arridx];
1932
1933 // Normal byte, go one level deeper. If it's not equal to the
1934 // byte in the bad word adjust the score. But don't even try
1935 // when the byte was already changed. And don't try when we
1936 // just deleted this byte, accepting it is always cheaper than
1937 // delete + substitute.
1938 if (c == fword[sp->ts_fidx]
1939 || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE))
1940 newscore = 0;
1941 else
1942 newscore = SCORE_SUBST;
1943 if ((newscore == 0
1944 || (sp->ts_fidx >= sp->ts_fidxtry
1945 && ((sp->ts_flags & TSF_DIDDEL) == 0
1946 || c != fword[sp->ts_delidx])))
1947 && TRY_DEEPER(su, stack, depth, newscore))
1948 {
1949 go_deeper(stack, depth, newscore);
1950#ifdef DEBUG_TRIEWALK
1951 if (newscore > 0)
1952 sprintf(changename[depth], "%.*s-%s: subst %c to %c",
1953 sp->ts_twordlen, tword, fword + sp->ts_fidx,
1954 fword[sp->ts_fidx], c);
1955 else
1956 sprintf(changename[depth], "%.*s-%s: accept %c",
1957 sp->ts_twordlen, tword, fword + sp->ts_fidx,
1958 fword[sp->ts_fidx]);
1959#endif
1960 ++depth;
1961 sp = &stack[depth];
Bram Moolenaar6d24b4f2022-05-23 12:01:50 +01001962 if (fword[sp->ts_fidx] != NUL)
1963 ++sp->ts_fidx;
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001964 tword[sp->ts_twordlen++] = c;
1965 sp->ts_arridx = idxs[arridx];
1966 if (newscore == SCORE_SUBST)
1967 sp->ts_isdiff = DIFF_YES;
1968 if (has_mbyte)
1969 {
1970 // Multi-byte characters are a bit complicated to
1971 // handle: They differ when any of the bytes differ
1972 // and then their length may also differ.
1973 if (sp->ts_tcharlen == 0)
1974 {
1975 // First byte.
1976 sp->ts_tcharidx = 0;
1977 sp->ts_tcharlen = MB_BYTE2LEN(c);
1978 sp->ts_fcharstart = sp->ts_fidx - 1;
1979 sp->ts_isdiff = (newscore != 0)
1980 ? DIFF_YES : DIFF_NONE;
1981 }
Bram Moolenaar156d3912022-06-18 14:09:08 +01001982 else if (sp->ts_isdiff == DIFF_INSERT
1983 && sp->ts_fidx > 0)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001984 // When inserting trail bytes don't advance in the
1985 // bad word.
1986 --sp->ts_fidx;
1987 if (++sp->ts_tcharidx == sp->ts_tcharlen)
1988 {
1989 // Last byte of character.
1990 if (sp->ts_isdiff == DIFF_YES)
1991 {
1992 // Correct ts_fidx for the byte length of the
1993 // character (we didn't check that before).
1994 sp->ts_fidx = sp->ts_fcharstart
Bram Moolenaar1614a142019-10-06 22:00:13 +02001995 + mb_ptr2len(
Bram Moolenaar46a426c2019-09-27 12:41:56 +02001996 fword + sp->ts_fcharstart);
1997 // For changing a composing character adjust
1998 // the score from SCORE_SUBST to
1999 // SCORE_SUBCOMP.
2000 if (enc_utf8
2001 && utf_iscomposing(
2002 utf_ptr2char(tword
2003 + sp->ts_twordlen
2004 - sp->ts_tcharlen))
2005 && utf_iscomposing(
2006 utf_ptr2char(fword
2007 + sp->ts_fcharstart)))
2008 sp->ts_score -=
2009 SCORE_SUBST - SCORE_SUBCOMP;
2010
2011 // For a similar character adjust score from
2012 // SCORE_SUBST to SCORE_SIMILAR.
2013 else if (!soundfold
2014 && slang->sl_has_map
2015 && similar_chars(slang,
2016 mb_ptr2char(tword
2017 + sp->ts_twordlen
2018 - sp->ts_tcharlen),
2019 mb_ptr2char(fword
2020 + sp->ts_fcharstart)))
2021 sp->ts_score -=
2022 SCORE_SUBST - SCORE_SIMILAR;
2023 }
2024 else if (sp->ts_isdiff == DIFF_INSERT
2025 && sp->ts_twordlen > sp->ts_tcharlen)
2026 {
2027 p = tword + sp->ts_twordlen - sp->ts_tcharlen;
2028 c = mb_ptr2char(p);
2029 if (enc_utf8 && utf_iscomposing(c))
2030 {
2031 // Inserting a composing char doesn't
2032 // count that much.
2033 sp->ts_score -= SCORE_INS - SCORE_INSCOMP;
2034 }
2035 else
2036 {
2037 // If the previous character was the same,
2038 // thus doubling a character, give a bonus
2039 // to the score. Also for the soundfold
2040 // tree (might seem illogical but does
2041 // give better scores).
2042 MB_PTR_BACK(tword, p);
2043 if (c == mb_ptr2char(p))
2044 sp->ts_score -= SCORE_INS
2045 - SCORE_INSDUP;
2046 }
2047 }
2048
2049 // Starting a new char, reset the length.
2050 sp->ts_tcharlen = 0;
2051 }
2052 }
2053 else
2054 {
2055 // If we found a similar char adjust the score.
2056 // We do this after calling go_deeper() because
2057 // it's slow.
2058 if (newscore != 0
2059 && !soundfold
2060 && slang->sl_has_map
2061 && similar_chars(slang,
2062 c, fword[sp->ts_fidx - 1]))
2063 sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
2064 }
2065 }
2066 }
2067 break;
2068
2069 case STATE_DEL:
2070 // When past the first byte of a multi-byte char don't try
2071 // delete/insert/swap a character.
2072 if (has_mbyte && sp->ts_tcharlen > 0)
2073 {
2074 PROF_STORE(sp->ts_state)
2075 sp->ts_state = STATE_FINAL;
2076 break;
2077 }
2078 // Try skipping one character in the bad word (delete it).
2079 PROF_STORE(sp->ts_state)
2080 sp->ts_state = STATE_INS_PREP;
2081 sp->ts_curi = 1;
2082 if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')
2083 // Deleting a vowel at the start of a word counts less, see
2084 // soundalike_score().
2085 newscore = 2 * SCORE_DEL / 3;
2086 else
2087 newscore = SCORE_DEL;
2088 if (fword[sp->ts_fidx] != NUL
2089 && TRY_DEEPER(su, stack, depth, newscore))
2090 {
2091 go_deeper(stack, depth, newscore);
2092#ifdef DEBUG_TRIEWALK
2093 sprintf(changename[depth], "%.*s-%s: delete %c",
2094 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2095 fword[sp->ts_fidx]);
2096#endif
2097 ++depth;
2098
2099 // Remember what character we deleted, so that we can avoid
2100 // inserting it again.
2101 stack[depth].ts_flags |= TSF_DIDDEL;
2102 stack[depth].ts_delidx = sp->ts_fidx;
2103
2104 // Advance over the character in fword[]. Give a bonus to the
2105 // score if the same character is following "nn" -> "n". It's
2106 // a bit illogical for soundfold tree but it does give better
2107 // results.
2108 if (has_mbyte)
2109 {
2110 c = mb_ptr2char(fword + sp->ts_fidx);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002111 stack[depth].ts_fidx += mb_ptr2len(fword + sp->ts_fidx);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002112 if (enc_utf8 && utf_iscomposing(c))
2113 stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
2114 else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))
2115 stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
2116 }
2117 else
2118 {
2119 ++stack[depth].ts_fidx;
2120 if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])
2121 stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
2122 }
2123 break;
2124 }
2125 // FALLTHROUGH
2126
2127 case STATE_INS_PREP:
2128 if (sp->ts_flags & TSF_DIDDEL)
2129 {
2130 // If we just deleted a byte then inserting won't make sense,
2131 // a substitute is always cheaper.
2132 PROF_STORE(sp->ts_state)
2133 sp->ts_state = STATE_SWAP;
2134 break;
2135 }
2136
2137 // skip over NUL bytes
2138 n = sp->ts_arridx;
2139 for (;;)
2140 {
2141 if (sp->ts_curi > byts[n])
2142 {
2143 // Only NUL bytes at this node, go to next state.
2144 PROF_STORE(sp->ts_state)
2145 sp->ts_state = STATE_SWAP;
2146 break;
2147 }
2148 if (byts[n + sp->ts_curi] != NUL)
2149 {
2150 // Found a byte to insert.
2151 PROF_STORE(sp->ts_state)
2152 sp->ts_state = STATE_INS;
2153 break;
2154 }
2155 ++sp->ts_curi;
2156 }
2157 break;
2158
2159 // FALLTHROUGH
2160
2161 case STATE_INS:
2162 // Insert one byte. Repeat this for each possible byte at this
2163 // node.
2164 n = sp->ts_arridx;
2165 if (sp->ts_curi > byts[n])
2166 {
2167 // Done all bytes at this node, go to next state.
2168 PROF_STORE(sp->ts_state)
2169 sp->ts_state = STATE_SWAP;
2170 break;
2171 }
2172
2173 // Do one more byte at this node, but:
2174 // - Skip NUL bytes.
2175 // - Skip the byte if it's equal to the byte in the word,
2176 // accepting that byte is always better.
2177 n += sp->ts_curi++;
Christian Brabandt0fb375a2023-11-29 10:23:39 +01002178
2179 // break out, if we would be accessing byts buffer out of bounds
2180 if (byts == slang->sl_fbyts && n >= slang->sl_fbyts_len)
2181 {
2182 got_int = TRUE;
2183 break;
2184 }
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002185 c = byts[n];
2186 if (soundfold && sp->ts_twordlen == 0 && c == '*')
2187 // Inserting a vowel at the start of a word counts less,
2188 // see soundalike_score().
2189 newscore = 2 * SCORE_INS / 3;
2190 else
2191 newscore = SCORE_INS;
2192 if (c != fword[sp->ts_fidx]
2193 && TRY_DEEPER(su, stack, depth, newscore))
2194 {
2195 go_deeper(stack, depth, newscore);
2196#ifdef DEBUG_TRIEWALK
2197 sprintf(changename[depth], "%.*s-%s: insert %c",
2198 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2199 c);
2200#endif
2201 ++depth;
2202 sp = &stack[depth];
2203 tword[sp->ts_twordlen++] = c;
2204 sp->ts_arridx = idxs[n];
2205 if (has_mbyte)
2206 {
2207 fl = MB_BYTE2LEN(c);
2208 if (fl > 1)
2209 {
2210 // There are following bytes for the same character.
2211 // We must find all bytes before trying
2212 // delete/insert/swap/etc.
2213 sp->ts_tcharlen = fl;
2214 sp->ts_tcharidx = 1;
2215 sp->ts_isdiff = DIFF_INSERT;
2216 }
2217 }
2218 else
2219 fl = 1;
2220 if (fl == 1)
2221 {
2222 // If the previous character was the same, thus doubling a
2223 // character, give a bonus to the score. Also for
2224 // soundfold words (illogical but does give a better
2225 // score).
2226 if (sp->ts_twordlen >= 2
2227 && tword[sp->ts_twordlen - 2] == c)
2228 sp->ts_score -= SCORE_INS - SCORE_INSDUP;
2229 }
2230 }
2231 break;
2232
2233 case STATE_SWAP:
2234 // Swap two bytes in the bad word: "12" -> "21".
2235 // We change "fword" here, it's changed back afterwards at
2236 // STATE_UNSWAP.
2237 p = fword + sp->ts_fidx;
2238 c = *p;
2239 if (c == NUL)
2240 {
2241 // End of word, can't swap or replace.
2242 PROF_STORE(sp->ts_state)
2243 sp->ts_state = STATE_FINAL;
2244 break;
2245 }
2246
2247 // Don't swap if the first character is not a word character.
2248 // SWAP3 etc. also don't make sense then.
2249 if (!soundfold && !spell_iswordp(p, curwin))
2250 {
2251 PROF_STORE(sp->ts_state)
2252 sp->ts_state = STATE_REP_INI;
2253 break;
2254 }
2255
2256 if (has_mbyte)
2257 {
2258 n = MB_CPTR2LEN(p);
2259 c = mb_ptr2char(p);
2260 if (p[n] == NUL)
2261 c2 = NUL;
2262 else if (!soundfold && !spell_iswordp(p + n, curwin))
2263 c2 = c; // don't swap non-word char
2264 else
2265 c2 = mb_ptr2char(p + n);
2266 }
2267 else
2268 {
2269 if (p[1] == NUL)
2270 c2 = NUL;
2271 else if (!soundfold && !spell_iswordp(p + 1, curwin))
2272 c2 = c; // don't swap non-word char
2273 else
2274 c2 = p[1];
2275 }
2276
2277 // When the second character is NUL we can't swap.
2278 if (c2 == NUL)
2279 {
2280 PROF_STORE(sp->ts_state)
2281 sp->ts_state = STATE_REP_INI;
2282 break;
2283 }
2284
2285 // When characters are identical, swap won't do anything.
2286 // Also get here if the second char is not a word character.
2287 if (c == c2)
2288 {
2289 PROF_STORE(sp->ts_state)
2290 sp->ts_state = STATE_SWAP3;
2291 break;
2292 }
2293 if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
2294 {
2295 go_deeper(stack, depth, SCORE_SWAP);
2296#ifdef DEBUG_TRIEWALK
2297 sprintf(changename[depth], "%.*s-%s: swap %c and %c",
2298 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2299 c, c2);
2300#endif
2301 PROF_STORE(sp->ts_state)
2302 sp->ts_state = STATE_UNSWAP;
2303 ++depth;
2304 if (has_mbyte)
2305 {
2306 fl = mb_char2len(c2);
2307 mch_memmove(p, p + n, fl);
2308 mb_char2bytes(c, p + fl);
2309 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
2310 }
2311 else
2312 {
2313 p[0] = c2;
2314 p[1] = c;
2315 stack[depth].ts_fidxtry = sp->ts_fidx + 2;
2316 }
2317 }
2318 else
2319 {
2320 // If this swap doesn't work then SWAP3 won't either.
2321 PROF_STORE(sp->ts_state)
2322 sp->ts_state = STATE_REP_INI;
2323 }
2324 break;
2325
2326 case STATE_UNSWAP:
2327 // Undo the STATE_SWAP swap: "21" -> "12".
2328 p = fword + sp->ts_fidx;
2329 if (has_mbyte)
2330 {
Bram Moolenaar1614a142019-10-06 22:00:13 +02002331 n = mb_ptr2len(p);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002332 c = mb_ptr2char(p + n);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002333 mch_memmove(p + mb_ptr2len(p + n), p, n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002334 mb_char2bytes(c, p);
2335 }
2336 else
2337 {
2338 c = *p;
2339 *p = p[1];
2340 p[1] = c;
2341 }
2342 // FALLTHROUGH
2343
2344 case STATE_SWAP3:
2345 // Swap two bytes, skipping one: "123" -> "321". We change
2346 // "fword" here, it's changed back afterwards at STATE_UNSWAP3.
2347 p = fword + sp->ts_fidx;
2348 if (has_mbyte)
2349 {
2350 n = MB_CPTR2LEN(p);
2351 c = mb_ptr2char(p);
2352 fl = MB_CPTR2LEN(p + n);
2353 c2 = mb_ptr2char(p + n);
2354 if (!soundfold && !spell_iswordp(p + n + fl, curwin))
2355 c3 = c; // don't swap non-word char
2356 else
2357 c3 = mb_ptr2char(p + n + fl);
2358 }
2359 else
2360 {
2361 c = *p;
2362 c2 = p[1];
2363 if (!soundfold && !spell_iswordp(p + 2, curwin))
2364 c3 = c; // don't swap non-word char
2365 else
2366 c3 = p[2];
2367 }
2368
2369 // When characters are identical: "121" then SWAP3 result is
2370 // identical, ROT3L result is same as SWAP: "211", ROT3L result is
2371 // same as SWAP on next char: "112". Thus skip all swapping.
2372 // Also skip when c3 is NUL.
2373 // Also get here when the third character is not a word character.
2374 // Second character may any char: "a.b" -> "b.a"
2375 if (c == c3 || c3 == NUL)
2376 {
2377 PROF_STORE(sp->ts_state)
2378 sp->ts_state = STATE_REP_INI;
2379 break;
2380 }
2381 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
2382 {
2383 go_deeper(stack, depth, SCORE_SWAP3);
2384#ifdef DEBUG_TRIEWALK
2385 sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",
2386 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2387 c, c3);
2388#endif
2389 PROF_STORE(sp->ts_state)
2390 sp->ts_state = STATE_UNSWAP3;
2391 ++depth;
2392 if (has_mbyte)
2393 {
2394 tl = mb_char2len(c3);
2395 mch_memmove(p, p + n + fl, tl);
2396 mb_char2bytes(c2, p + tl);
2397 mb_char2bytes(c, p + fl + tl);
2398 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
2399 }
2400 else
2401 {
2402 p[0] = p[2];
2403 p[2] = c;
2404 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
2405 }
2406 }
2407 else
2408 {
2409 PROF_STORE(sp->ts_state)
2410 sp->ts_state = STATE_REP_INI;
2411 }
2412 break;
2413
2414 case STATE_UNSWAP3:
2415 // Undo STATE_SWAP3: "321" -> "123"
2416 p = fword + sp->ts_fidx;
2417 if (has_mbyte)
2418 {
Bram Moolenaar1614a142019-10-06 22:00:13 +02002419 n = mb_ptr2len(p);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002420 c2 = mb_ptr2char(p + n);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002421 fl = mb_ptr2len(p + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002422 c = mb_ptr2char(p + n + fl);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002423 tl = mb_ptr2len(p + n + fl);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002424 mch_memmove(p + fl + tl, p, n);
2425 mb_char2bytes(c, p);
2426 mb_char2bytes(c2, p + tl);
2427 p = p + tl;
2428 }
2429 else
2430 {
2431 c = *p;
2432 *p = p[2];
2433 p[2] = c;
2434 ++p;
2435 }
2436
2437 if (!soundfold && !spell_iswordp(p, curwin))
2438 {
2439 // Middle char is not a word char, skip the rotate. First and
2440 // third char were already checked at swap and swap3.
2441 PROF_STORE(sp->ts_state)
2442 sp->ts_state = STATE_REP_INI;
2443 break;
2444 }
2445
2446 // Rotate three characters left: "123" -> "231". We change
2447 // "fword" here, it's changed back afterwards at STATE_UNROT3L.
2448 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
2449 {
2450 go_deeper(stack, depth, SCORE_SWAP3);
2451#ifdef DEBUG_TRIEWALK
2452 p = fword + sp->ts_fidx;
2453 sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",
2454 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2455 p[0], p[1], p[2]);
2456#endif
2457 PROF_STORE(sp->ts_state)
2458 sp->ts_state = STATE_UNROT3L;
2459 ++depth;
2460 p = fword + sp->ts_fidx;
2461 if (has_mbyte)
2462 {
2463 n = MB_CPTR2LEN(p);
2464 c = mb_ptr2char(p);
2465 fl = MB_CPTR2LEN(p + n);
2466 fl += MB_CPTR2LEN(p + n + fl);
2467 mch_memmove(p, p + n, fl);
2468 mb_char2bytes(c, p + fl);
2469 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
2470 }
2471 else
2472 {
2473 c = *p;
2474 *p = p[1];
2475 p[1] = p[2];
2476 p[2] = c;
2477 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
2478 }
2479 }
2480 else
2481 {
2482 PROF_STORE(sp->ts_state)
2483 sp->ts_state = STATE_REP_INI;
2484 }
2485 break;
2486
2487 case STATE_UNROT3L:
2488 // Undo ROT3L: "231" -> "123"
2489 p = fword + sp->ts_fidx;
2490 if (has_mbyte)
2491 {
Bram Moolenaar1614a142019-10-06 22:00:13 +02002492 n = mb_ptr2len(p);
2493 n += mb_ptr2len(p + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002494 c = mb_ptr2char(p + n);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002495 tl = mb_ptr2len(p + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002496 mch_memmove(p + tl, p, n);
2497 mb_char2bytes(c, p);
2498 }
2499 else
2500 {
2501 c = p[2];
2502 p[2] = p[1];
2503 p[1] = *p;
2504 *p = c;
2505 }
2506
2507 // Rotate three bytes right: "123" -> "312". We change "fword"
2508 // here, it's changed back afterwards at STATE_UNROT3R.
2509 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
2510 {
2511 go_deeper(stack, depth, SCORE_SWAP3);
2512#ifdef DEBUG_TRIEWALK
2513 p = fword + sp->ts_fidx;
2514 sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",
2515 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2516 p[0], p[1], p[2]);
2517#endif
2518 PROF_STORE(sp->ts_state)
2519 sp->ts_state = STATE_UNROT3R;
2520 ++depth;
2521 p = fword + sp->ts_fidx;
2522 if (has_mbyte)
2523 {
2524 n = MB_CPTR2LEN(p);
2525 n += MB_CPTR2LEN(p + n);
2526 c = mb_ptr2char(p + n);
2527 tl = MB_CPTR2LEN(p + n);
2528 mch_memmove(p + tl, p, n);
2529 mb_char2bytes(c, p);
2530 stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
2531 }
2532 else
2533 {
2534 c = p[2];
2535 p[2] = p[1];
2536 p[1] = *p;
2537 *p = c;
2538 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
2539 }
2540 }
2541 else
2542 {
2543 PROF_STORE(sp->ts_state)
2544 sp->ts_state = STATE_REP_INI;
2545 }
2546 break;
2547
2548 case STATE_UNROT3R:
2549 // Undo ROT3R: "312" -> "123"
2550 p = fword + sp->ts_fidx;
2551 if (has_mbyte)
2552 {
2553 c = mb_ptr2char(p);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002554 tl = mb_ptr2len(p);
2555 n = mb_ptr2len(p + tl);
2556 n += mb_ptr2len(p + tl + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002557 mch_memmove(p, p + tl, n);
2558 mb_char2bytes(c, p + n);
2559 }
2560 else
2561 {
2562 c = *p;
2563 *p = p[1];
2564 p[1] = p[2];
2565 p[2] = c;
2566 }
2567 // FALLTHROUGH
2568
2569 case STATE_REP_INI:
2570 // Check if matching with REP items from the .aff file would work.
2571 // Quickly skip if:
2572 // - there are no REP items and we are not in the soundfold trie
2573 // - the score is going to be too high anyway
2574 // - already applied a REP item or swapped here
2575 if ((lp->lp_replang == NULL && !soundfold)
2576 || sp->ts_score + SCORE_REP >= su->su_maxscore
2577 || sp->ts_fidx < sp->ts_fidxtry)
2578 {
2579 PROF_STORE(sp->ts_state)
2580 sp->ts_state = STATE_FINAL;
2581 break;
2582 }
2583
2584 // Use the first byte to quickly find the first entry that may
2585 // match. If the index is -1 there is none.
2586 if (soundfold)
2587 sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
2588 else
2589 sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];
2590
2591 if (sp->ts_curi < 0)
2592 {
2593 PROF_STORE(sp->ts_state)
2594 sp->ts_state = STATE_FINAL;
2595 break;
2596 }
2597
2598 PROF_STORE(sp->ts_state)
2599 sp->ts_state = STATE_REP;
2600 // FALLTHROUGH
2601
2602 case STATE_REP:
2603 // Try matching with REP items from the .aff file. For each match
2604 // replace the characters and check if the resulting word is
2605 // valid.
2606 p = fword + sp->ts_fidx;
2607
2608 if (soundfold)
2609 gap = &slang->sl_repsal;
2610 else
2611 gap = &lp->lp_replang->sl_rep;
2612 while (sp->ts_curi < gap->ga_len)
2613 {
2614 ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
2615 if (*ftp->ft_from != *p)
2616 {
2617 // past possible matching entries
2618 sp->ts_curi = gap->ga_len;
2619 break;
2620 }
2621 if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
2622 && TRY_DEEPER(su, stack, depth, SCORE_REP))
2623 {
2624 go_deeper(stack, depth, SCORE_REP);
2625#ifdef DEBUG_TRIEWALK
2626 sprintf(changename[depth], "%.*s-%s: replace %s with %s",
2627 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2628 ftp->ft_from, ftp->ft_to);
2629#endif
2630 // Need to undo this afterwards.
2631 PROF_STORE(sp->ts_state)
2632 sp->ts_state = STATE_REP_UNDO;
2633
2634 // Change the "from" to the "to" string.
2635 ++depth;
2636 fl = (int)STRLEN(ftp->ft_from);
2637 tl = (int)STRLEN(ftp->ft_to);
2638 if (fl != tl)
2639 {
2640 STRMOVE(p + tl, p + fl);
2641 repextra += tl - fl;
2642 }
2643 mch_memmove(p, ftp->ft_to, tl);
2644 stack[depth].ts_fidxtry = sp->ts_fidx + tl;
2645 stack[depth].ts_tcharlen = 0;
2646 break;
2647 }
2648 }
2649
2650 if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
2651 {
2652 // No (more) matches.
2653 PROF_STORE(sp->ts_state)
2654 sp->ts_state = STATE_FINAL;
2655 }
2656
2657 break;
2658
2659 case STATE_REP_UNDO:
2660 // Undo a REP replacement and continue with the next one.
2661 if (soundfold)
2662 gap = &slang->sl_repsal;
2663 else
2664 gap = &lp->lp_replang->sl_rep;
2665 ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
2666 fl = (int)STRLEN(ftp->ft_from);
2667 tl = (int)STRLEN(ftp->ft_to);
2668 p = fword + sp->ts_fidx;
2669 if (fl != tl)
2670 {
2671 STRMOVE(p + fl, p + tl);
2672 repextra -= tl - fl;
2673 }
2674 mch_memmove(p, ftp->ft_from, fl);
2675 PROF_STORE(sp->ts_state)
2676 sp->ts_state = STATE_REP;
2677 break;
2678
2679 default:
2680 // Did all possible states at this level, go up one level.
2681 --depth;
2682
2683 if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
2684 {
2685 // Continue in or go back to the prefix tree.
2686 byts = pbyts;
2687 idxs = pidxs;
2688 }
2689
2690 // Don't check for CTRL-C too often, it takes time.
2691 if (--breakcheckcount == 0)
2692 {
2693 ui_breakcheck();
2694 breakcheckcount = 1000;
Bram Moolenaar06f15412022-01-29 10:51:59 +00002695#ifdef FEAT_RELTIME
Bram Moolenaar585ee072022-01-29 11:22:17 +00002696 if (spell_suggest_timeout > 0
2697 && profile_passed_limit(&time_limit))
Bram Moolenaar06f15412022-01-29 10:51:59 +00002698 got_int = TRUE;
2699#endif
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002700 }
2701 }
2702 }
2703}
2704
2705
2706/*
2707 * Go one level deeper in the tree.
2708 */
2709 static void
2710go_deeper(trystate_T *stack, int depth, int score_add)
2711{
2712 stack[depth + 1] = stack[depth];
2713 stack[depth + 1].ts_state = STATE_START;
2714 stack[depth + 1].ts_score = stack[depth].ts_score + score_add;
2715 stack[depth + 1].ts_curi = 1; // start just after length byte
2716 stack[depth + 1].ts_flags = 0;
2717}
2718
2719/*
2720 * "fword" is a good word with case folded. Find the matching keep-case
2721 * words and put it in "kword".
2722 * Theoretically there could be several keep-case words that result in the
2723 * same case-folded word, but we only find one...
2724 */
2725 static void
2726find_keepcap_word(slang_T *slang, char_u *fword, char_u *kword)
2727{
2728 char_u uword[MAXWLEN]; // "fword" in upper-case
2729 int depth;
2730 idx_T tryidx;
2731
2732 // The following arrays are used at each depth in the tree.
2733 idx_T arridx[MAXWLEN];
2734 int round[MAXWLEN];
2735 int fwordidx[MAXWLEN];
2736 int uwordidx[MAXWLEN];
2737 int kwordlen[MAXWLEN];
2738
2739 int flen, ulen;
2740 int l;
2741 int len;
2742 int c;
2743 idx_T lo, hi, m;
2744 char_u *p;
2745 char_u *byts = slang->sl_kbyts; // array with bytes of the words
2746 idx_T *idxs = slang->sl_kidxs; // array with indexes
2747
2748 if (byts == NULL)
2749 {
2750 // array is empty: "cannot happen"
2751 *kword = NUL;
2752 return;
2753 }
2754
2755 // Make an all-cap version of "fword".
2756 allcap_copy(fword, uword);
2757
2758 // Each character needs to be tried both case-folded and upper-case.
2759 // All this gets very complicated if we keep in mind that changing case
2760 // may change the byte length of a multi-byte character...
2761 depth = 0;
2762 arridx[0] = 0;
2763 round[0] = 0;
2764 fwordidx[0] = 0;
2765 uwordidx[0] = 0;
2766 kwordlen[0] = 0;
2767 while (depth >= 0)
2768 {
2769 if (fword[fwordidx[depth]] == NUL)
2770 {
2771 // We are at the end of "fword". If the tree allows a word to end
2772 // here we have found a match.
2773 if (byts[arridx[depth] + 1] == 0)
2774 {
2775 kword[kwordlen[depth]] = NUL;
2776 return;
2777 }
2778
2779 // kword is getting too long, continue one level up
2780 --depth;
2781 }
2782 else if (++round[depth] > 2)
2783 {
2784 // tried both fold-case and upper-case character, continue one
2785 // level up
2786 --depth;
2787 }
2788 else
2789 {
2790 // round[depth] == 1: Try using the folded-case character.
2791 // round[depth] == 2: Try using the upper-case character.
2792 if (has_mbyte)
2793 {
2794 flen = MB_CPTR2LEN(fword + fwordidx[depth]);
2795 ulen = MB_CPTR2LEN(uword + uwordidx[depth]);
2796 }
2797 else
2798 ulen = flen = 1;
2799 if (round[depth] == 1)
2800 {
2801 p = fword + fwordidx[depth];
2802 l = flen;
2803 }
2804 else
2805 {
2806 p = uword + uwordidx[depth];
2807 l = ulen;
2808 }
2809
2810 for (tryidx = arridx[depth]; l > 0; --l)
2811 {
2812 // Perform a binary search in the list of accepted bytes.
2813 len = byts[tryidx++];
2814 c = *p++;
2815 lo = tryidx;
2816 hi = tryidx + len - 1;
2817 while (lo < hi)
2818 {
2819 m = (lo + hi) / 2;
2820 if (byts[m] > c)
2821 hi = m - 1;
2822 else if (byts[m] < c)
2823 lo = m + 1;
2824 else
2825 {
2826 lo = hi = m;
2827 break;
2828 }
2829 }
2830
2831 // Stop if there is no matching byte.
2832 if (hi < lo || byts[lo] != c)
2833 break;
2834
2835 // Continue at the child (if there is one).
2836 tryidx = idxs[lo];
2837 }
2838
2839 if (l == 0)
2840 {
2841 // Found the matching char. Copy it to "kword" and go a
2842 // level deeper.
2843 if (round[depth] == 1)
2844 {
2845 STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth],
2846 flen);
2847 kwordlen[depth + 1] = kwordlen[depth] + flen;
2848 }
2849 else
2850 {
2851 STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth],
2852 ulen);
2853 kwordlen[depth + 1] = kwordlen[depth] + ulen;
2854 }
2855 fwordidx[depth + 1] = fwordidx[depth] + flen;
2856 uwordidx[depth + 1] = uwordidx[depth] + ulen;
2857
2858 ++depth;
2859 arridx[depth] = tryidx;
2860 round[depth] = 0;
2861 }
2862 }
2863 }
2864
2865 // Didn't find it: "cannot happen".
2866 *kword = NUL;
2867}
2868
2869/*
2870 * Compute the sound-a-like score for suggestions in su->su_ga and add them to
2871 * su->su_sga.
2872 */
2873 static void
2874score_comp_sal(suginfo_T *su)
2875{
2876 langp_T *lp;
2877 char_u badsound[MAXWLEN];
2878 int i;
2879 suggest_T *stp;
2880 suggest_T *sstp;
2881 int score;
2882 int lpi;
2883
2884 if (ga_grow(&su->su_sga, su->su_ga.ga_len) == FAIL)
2885 return;
2886
2887 // Use the sound-folding of the first language that supports it.
2888 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
2889 {
2890 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2891 if (lp->lp_slang->sl_sal.ga_len > 0)
2892 {
2893 // soundfold the bad word
2894 spell_soundfold(lp->lp_slang, su->su_fbadword, TRUE, badsound);
2895
2896 for (i = 0; i < su->su_ga.ga_len; ++i)
2897 {
2898 stp = &SUG(su->su_ga, i);
2899
2900 // Case-fold the suggested word, sound-fold it and compute the
2901 // sound-a-like score.
2902 score = stp_sal_score(stp, su, lp->lp_slang, badsound);
2903 if (score < SCORE_MAXMAX)
2904 {
2905 // Add the suggestion.
2906 sstp = &SUG(su->su_sga, su->su_sga.ga_len);
2907 sstp->st_word = vim_strsave(stp->st_word);
2908 if (sstp->st_word != NULL)
2909 {
2910 sstp->st_wordlen = stp->st_wordlen;
2911 sstp->st_score = score;
2912 sstp->st_altscore = 0;
2913 sstp->st_orglen = stp->st_orglen;
2914 ++su->su_sga.ga_len;
2915 }
2916 }
2917 }
2918 break;
2919 }
2920 }
2921}
2922
2923/*
2924 * Combine the list of suggestions in su->su_ga and su->su_sga.
2925 * They are entwined.
2926 */
2927 static void
2928score_combine(suginfo_T *su)
2929{
2930 int i;
2931 int j;
2932 garray_T ga;
2933 garray_T *gap;
2934 langp_T *lp;
2935 suggest_T *stp;
2936 char_u *p;
2937 char_u badsound[MAXWLEN];
2938 int round;
2939 int lpi;
2940 slang_T *slang = NULL;
2941
2942 // Add the alternate score to su_ga.
2943 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
2944 {
2945 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2946 if (lp->lp_slang->sl_sal.ga_len > 0)
2947 {
2948 // soundfold the bad word
2949 slang = lp->lp_slang;
2950 spell_soundfold(slang, su->su_fbadword, TRUE, badsound);
2951
2952 for (i = 0; i < su->su_ga.ga_len; ++i)
2953 {
2954 stp = &SUG(su->su_ga, i);
2955 stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
2956 if (stp->st_altscore == SCORE_MAXMAX)
2957 stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
2958 else
2959 stp->st_score = (stp->st_score * 3
2960 + stp->st_altscore) / 4;
2961 stp->st_salscore = FALSE;
2962 }
2963 break;
2964 }
2965 }
2966
2967 if (slang == NULL) // Using "double" without sound folding.
2968 {
2969 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore,
2970 su->su_maxcount);
2971 return;
2972 }
2973
2974 // Add the alternate score to su_sga.
2975 for (i = 0; i < su->su_sga.ga_len; ++i)
2976 {
2977 stp = &SUG(su->su_sga, i);
2978 stp->st_altscore = spell_edit_score(slang,
2979 su->su_badword, stp->st_word);
2980 if (stp->st_score == SCORE_MAXMAX)
2981 stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
2982 else
2983 stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8;
2984 stp->st_salscore = TRUE;
2985 }
2986
2987 // Remove bad suggestions, sort the suggestions and truncate at "maxcount"
2988 // for both lists.
2989 check_suggestions(su, &su->su_ga);
2990 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
2991 check_suggestions(su, &su->su_sga);
2992 (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount);
2993
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002994 ga_init2(&ga, sizeof(suginfo_T), 1);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002995 if (ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len) == FAIL)
2996 return;
2997
2998 stp = &SUG(ga, 0);
2999 for (i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i)
3000 {
3001 // round 1: get a suggestion from su_ga
3002 // round 2: get a suggestion from su_sga
3003 for (round = 1; round <= 2; ++round)
3004 {
3005 gap = round == 1 ? &su->su_ga : &su->su_sga;
3006 if (i < gap->ga_len)
3007 {
3008 // Don't add a word if it's already there.
3009 p = SUG(*gap, i).st_word;
3010 for (j = 0; j < ga.ga_len; ++j)
3011 if (STRCMP(stp[j].st_word, p) == 0)
3012 break;
3013 if (j == ga.ga_len)
3014 stp[ga.ga_len++] = SUG(*gap, i);
3015 else
3016 vim_free(p);
3017 }
3018 }
3019 }
3020
3021 ga_clear(&su->su_ga);
3022 ga_clear(&su->su_sga);
3023
3024 // Truncate the list to the number of suggestions that will be displayed.
3025 if (ga.ga_len > su->su_maxcount)
3026 {
3027 for (i = su->su_maxcount; i < ga.ga_len; ++i)
3028 vim_free(stp[i].st_word);
3029 ga.ga_len = su->su_maxcount;
3030 }
3031
3032 su->su_ga = ga;
3033}
3034
3035/*
3036 * For the goodword in "stp" compute the soundalike score compared to the
3037 * badword.
3038 */
3039 static int
3040stp_sal_score(
3041 suggest_T *stp,
3042 suginfo_T *su,
3043 slang_T *slang,
3044 char_u *badsound) // sound-folded badword
3045{
3046 char_u *p;
3047 char_u *pbad;
3048 char_u *pgood;
3049 char_u badsound2[MAXWLEN];
3050 char_u fword[MAXWLEN];
3051 char_u goodsound[MAXWLEN];
3052 char_u goodword[MAXWLEN];
3053 int lendiff;
3054
3055 lendiff = (int)(su->su_badlen - stp->st_orglen);
3056 if (lendiff >= 0)
3057 pbad = badsound;
3058 else
3059 {
3060 // soundfold the bad word with more characters following
Bram Moolenaar4f135272021-06-11 19:07:40 +02003061 (void)spell_casefold(curwin,
3062 su->su_badptr, stp->st_orglen, fword, MAXWLEN);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003063
3064 // When joining two words the sound often changes a lot. E.g., "t he"
3065 // sounds like "t h" while "the" sounds like "@". Avoid that by
3066 // removing the space. Don't do it when the good word also contains a
3067 // space.
3068 if (VIM_ISWHITE(su->su_badptr[su->su_badlen])
3069 && *skiptowhite(stp->st_word) == NUL)
3070 for (p = fword; *(p = skiptowhite(p)) != NUL; )
3071 STRMOVE(p, p + 1);
3072
3073 spell_soundfold(slang, fword, TRUE, badsound2);
3074 pbad = badsound2;
3075 }
3076
3077 if (lendiff > 0 && stp->st_wordlen + lendiff < MAXWLEN)
3078 {
3079 // Add part of the bad word to the good word, so that we soundfold
3080 // what replaces the bad word.
3081 STRCPY(goodword, stp->st_word);
3082 vim_strncpy(goodword + stp->st_wordlen,
3083 su->su_badptr + su->su_badlen - lendiff, lendiff);
3084 pgood = goodword;
3085 }
3086 else
3087 pgood = stp->st_word;
3088
3089 // Sound-fold the word and compute the score for the difference.
3090 spell_soundfold(slang, pgood, FALSE, goodsound);
3091
3092 return soundalike_score(goodsound, pbad);
3093}
3094
3095// structure used to store soundfolded words that add_sound_suggest() has
3096// handled already.
3097typedef struct
3098{
3099 short sft_score; // lowest score used
3100 char_u sft_word[1]; // soundfolded word, actually longer
3101} sftword_T;
3102
3103static sftword_T dumsft;
kylo252ae6f1d82022-02-16 19:24:07 +00003104#define HIKEY2SFT(p) ((sftword_T *)((p) - (dumsft.sft_word - (char_u *)&dumsft)))
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003105#define HI2SFT(hi) HIKEY2SFT((hi)->hi_key)
3106
3107/*
3108 * Prepare for calling suggest_try_soundalike().
3109 */
3110 static void
3111suggest_try_soundalike_prep(void)
3112{
3113 langp_T *lp;
3114 int lpi;
3115 slang_T *slang;
3116
3117 // Do this for all languages that support sound folding and for which a
3118 // .sug file has been loaded.
3119 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
3120 {
3121 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
3122 slang = lp->lp_slang;
3123 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
3124 // prepare the hashtable used by add_sound_suggest()
3125 hash_init(&slang->sl_sounddone);
3126 }
3127}
3128
3129/*
3130 * Find suggestions by comparing the word in a sound-a-like form.
3131 * Note: This doesn't support postponed prefixes.
3132 */
3133 static void
3134suggest_try_soundalike(suginfo_T *su)
3135{
3136 char_u salword[MAXWLEN];
3137 langp_T *lp;
3138 int lpi;
3139 slang_T *slang;
3140
3141 // Do this for all languages that support sound folding and for which a
3142 // .sug file has been loaded.
3143 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
3144 {
3145 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
3146 slang = lp->lp_slang;
3147 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
3148 {
3149 // soundfold the bad word
3150 spell_soundfold(slang, su->su_fbadword, TRUE, salword);
3151
3152 // try all kinds of inserts/deletes/swaps/etc.
3153 // TODO: also soundfold the next words, so that we can try joining
3154 // and splitting
3155#ifdef SUGGEST_PROFILE
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003156 prof_init();
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003157#endif
3158 suggest_trie_walk(su, lp, salword, TRUE);
3159#ifdef SUGGEST_PROFILE
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003160 prof_report("soundalike");
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003161#endif
3162 }
3163 }
3164}
3165
3166/*
3167 * Finish up after calling suggest_try_soundalike().
3168 */
3169 static void
3170suggest_try_soundalike_finish(void)
3171{
3172 langp_T *lp;
3173 int lpi;
3174 slang_T *slang;
3175 int todo;
3176 hashitem_T *hi;
3177
3178 // Do this for all languages that support sound folding and for which a
3179 // .sug file has been loaded.
3180 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
3181 {
3182 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
3183 slang = lp->lp_slang;
3184 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
3185 {
3186 // Free the info about handled words.
3187 todo = (int)slang->sl_sounddone.ht_used;
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00003188 FOR_ALL_HASHTAB_ITEMS(&slang->sl_sounddone, hi, todo)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003189 if (!HASHITEM_EMPTY(hi))
3190 {
3191 vim_free(HI2SFT(hi));
3192 --todo;
3193 }
3194
3195 // Clear the hashtable, it may also be used by another region.
3196 hash_clear(&slang->sl_sounddone);
3197 hash_init(&slang->sl_sounddone);
3198 }
3199 }
3200}
3201
3202/*
3203 * A match with a soundfolded word is found. Add the good word(s) that
3204 * produce this soundfolded word.
3205 */
3206 static void
3207add_sound_suggest(
3208 suginfo_T *su,
3209 char_u *goodword,
3210 int score, // soundfold score
3211 langp_T *lp)
3212{
3213 slang_T *slang = lp->lp_slang; // language for sound folding
3214 int sfwordnr;
3215 char_u *nrline;
3216 int orgnr;
3217 char_u theword[MAXWLEN];
3218 int i;
3219 int wlen;
3220 char_u *byts;
3221 idx_T *idxs;
3222 int n;
3223 int wordcount;
3224 int wc;
3225 int goodscore;
3226 hash_T hash;
3227 hashitem_T *hi;
3228 sftword_T *sft;
3229 int bc, gc;
3230 int limit;
3231
3232 // It's very well possible that the same soundfold word is found several
3233 // times with different scores. Since the following is quite slow only do
3234 // the words that have a better score than before. Use a hashtable to
3235 // remember the words that have been done.
3236 hash = hash_hash(goodword);
3237 hi = hash_lookup(&slang->sl_sounddone, goodword, hash);
3238 if (HASHITEM_EMPTY(hi))
3239 {
zeertzjq1b438a82023-02-01 13:11:15 +00003240 sft = alloc(offsetof(sftword_T, sft_word) + STRLEN(goodword) + 1);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003241 if (sft != NULL)
3242 {
3243 sft->sft_score = score;
3244 STRCPY(sft->sft_word, goodword);
3245 hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash);
3246 }
3247 }
3248 else
3249 {
3250 sft = HI2SFT(hi);
3251 if (score >= sft->sft_score)
3252 return;
3253 sft->sft_score = score;
3254 }
3255
3256 // Find the word nr in the soundfold tree.
3257 sfwordnr = soundfold_find(slang, goodword);
3258 if (sfwordnr < 0)
3259 {
3260 internal_error("add_sound_suggest()");
3261 return;
3262 }
3263
3264 // go over the list of good words that produce this soundfold word
3265 nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)(sfwordnr + 1), FALSE);
3266 orgnr = 0;
3267 while (*nrline != NUL)
3268 {
3269 // The wordnr was stored in a minimal nr of bytes as an offset to the
3270 // previous wordnr.
3271 orgnr += bytes2offset(&nrline);
3272
3273 byts = slang->sl_fbyts;
3274 idxs = slang->sl_fidxs;
3275
3276 // Lookup the word "orgnr" one of the two tries.
3277 n = 0;
3278 wordcount = 0;
3279 for (wlen = 0; wlen < MAXWLEN - 3; ++wlen)
3280 {
3281 i = 1;
3282 if (wordcount == orgnr && byts[n + 1] == NUL)
3283 break; // found end of word
3284
3285 if (byts[n + 1] == NUL)
3286 ++wordcount;
3287
3288 // skip over the NUL bytes
3289 for ( ; byts[n + i] == NUL; ++i)
3290 if (i > byts[n]) // safety check
3291 {
3292 STRCPY(theword + wlen, "BAD");
3293 wlen += 3;
3294 goto badword;
3295 }
3296
3297 // One of the siblings must have the word.
3298 for ( ; i < byts[n]; ++i)
3299 {
3300 wc = idxs[idxs[n + i]]; // nr of words under this byte
3301 if (wordcount + wc > orgnr)
3302 break;
3303 wordcount += wc;
3304 }
3305
3306 theword[wlen] = byts[n + i];
3307 n = idxs[n + i];
3308 }
3309badword:
3310 theword[wlen] = NUL;
3311
3312 // Go over the possible flags and regions.
3313 for (; i <= byts[n] && byts[n + i] == NUL; ++i)
3314 {
3315 char_u cword[MAXWLEN];
3316 char_u *p;
3317 int flags = (int)idxs[n + i];
3318
3319 // Skip words with the NOSUGGEST flag
3320 if (flags & WF_NOSUGGEST)
3321 continue;
3322
3323 if (flags & WF_KEEPCAP)
3324 {
3325 // Must find the word in the keep-case tree.
3326 find_keepcap_word(slang, theword, cword);
3327 p = cword;
3328 }
3329 else
3330 {
3331 flags |= su->su_badflags;
3332 if ((flags & WF_CAPMASK) != 0)
3333 {
3334 // Need to fix case according to "flags".
3335 make_case_word(theword, cword, flags);
3336 p = cword;
3337 }
3338 else
3339 p = theword;
3340 }
3341
3342 // Add the suggestion.
3343 if (sps_flags & SPS_DOUBLE)
3344 {
3345 // Add the suggestion if the score isn't too bad.
3346 if (score <= su->su_maxscore)
3347 add_suggestion(su, &su->su_sga, p, su->su_badlen,
3348 score, 0, FALSE, slang, FALSE);
3349 }
3350 else
3351 {
3352 // Add a penalty for words in another region.
3353 if ((flags & WF_REGION)
3354 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
3355 goodscore = SCORE_REGION;
3356 else
3357 goodscore = 0;
3358
3359 // Add a small penalty for changing the first letter from
3360 // lower to upper case. Helps for "tath" -> "Kath", which is
3361 // less common than "tath" -> "path". Don't do it when the
3362 // letter is the same, that has already been counted.
3363 gc = PTR2CHAR(p);
3364 if (SPELL_ISUPPER(gc))
3365 {
3366 bc = PTR2CHAR(su->su_badword);
3367 if (!SPELL_ISUPPER(bc)
3368 && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc))
3369 goodscore += SCORE_ICASE / 2;
3370 }
3371
3372 // Compute the score for the good word. This only does letter
3373 // insert/delete/swap/replace. REP items are not considered,
3374 // which may make the score a bit higher.
3375 // Use a limit for the score to make it work faster. Use
3376 // MAXSCORE(), because RESCORE() will change the score.
3377 // If the limit is very high then the iterative method is
3378 // inefficient, using an array is quicker.
3379 limit = MAXSCORE(su->su_sfmaxscore - goodscore, score);
3380 if (limit > SCORE_LIMITMAX)
3381 goodscore += spell_edit_score(slang, su->su_badword, p);
3382 else
3383 goodscore += spell_edit_score_limit(slang, su->su_badword,
3384 p, limit);
3385
3386 // When going over the limit don't bother to do the rest.
3387 if (goodscore < SCORE_MAXMAX)
3388 {
3389 // Give a bonus to words seen before.
3390 goodscore = score_wordcount_adj(slang, goodscore, p, FALSE);
3391
3392 // Add the suggestion if the score isn't too bad.
3393 goodscore = RESCORE(goodscore, score);
3394 if (goodscore <= su->su_sfmaxscore)
3395 add_suggestion(su, &su->su_ga, p, su->su_badlen,
3396 goodscore, score, TRUE, slang, TRUE);
3397 }
3398 }
3399 }
3400 // smsg("word %s (%d): %s (%d)", sftword, sftnr, theword, orgnr);
3401 }
3402}
3403
3404/*
3405 * Find word "word" in fold-case tree for "slang" and return the word number.
3406 */
3407 static int
3408soundfold_find(slang_T *slang, char_u *word)
3409{
3410 idx_T arridx = 0;
3411 int len;
3412 int wlen = 0;
3413 int c;
3414 char_u *ptr = word;
3415 char_u *byts;
3416 idx_T *idxs;
3417 int wordnr = 0;
3418
3419 byts = slang->sl_sbyts;
3420 idxs = slang->sl_sidxs;
3421
3422 for (;;)
3423 {
3424 // First byte is the number of possible bytes.
3425 len = byts[arridx++];
3426
3427 // If the first possible byte is a zero the word could end here.
3428 // If the word ends we found the word. If not skip the NUL bytes.
3429 c = ptr[wlen];
3430 if (byts[arridx] == NUL)
3431 {
3432 if (c == NUL)
3433 break;
3434
3435 // Skip over the zeros, there can be several.
3436 while (len > 0 && byts[arridx] == NUL)
3437 {
3438 ++arridx;
3439 --len;
3440 }
3441 if (len == 0)
3442 return -1; // no children, word should have ended here
3443 ++wordnr;
3444 }
3445
3446 // If the word ends we didn't find it.
3447 if (c == NUL)
3448 return -1;
3449
3450 // Perform a binary search in the list of accepted bytes.
3451 if (c == TAB) // <Tab> is handled like <Space>
3452 c = ' ';
3453 while (byts[arridx] < c)
3454 {
3455 // The word count is in the first idxs[] entry of the child.
3456 wordnr += idxs[idxs[arridx]];
3457 ++arridx;
3458 if (--len == 0) // end of the bytes, didn't find it
3459 return -1;
3460 }
3461 if (byts[arridx] != c) // didn't find the byte
3462 return -1;
3463
3464 // Continue at the child (if there is one).
3465 arridx = idxs[arridx];
3466 ++wlen;
3467
3468 // One space in the good word may stand for several spaces in the
3469 // checked word.
3470 if (c == ' ')
3471 while (ptr[wlen] == ' ' || ptr[wlen] == TAB)
3472 ++wlen;
3473 }
3474
3475 return wordnr;
3476}
3477
3478/*
3479 * Return TRUE if "c1" and "c2" are similar characters according to the MAP
3480 * lines in the .aff file.
3481 */
3482 static int
3483similar_chars(slang_T *slang, int c1, int c2)
3484{
3485 int m1, m2;
3486 char_u buf[MB_MAXBYTES + 1];
3487 hashitem_T *hi;
3488
3489 if (c1 >= 256)
3490 {
3491 buf[mb_char2bytes(c1, buf)] = 0;
3492 hi = hash_find(&slang->sl_map_hash, buf);
3493 if (HASHITEM_EMPTY(hi))
3494 m1 = 0;
3495 else
3496 m1 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
3497 }
3498 else
3499 m1 = slang->sl_map_array[c1];
3500 if (m1 == 0)
3501 return FALSE;
3502
3503
3504 if (c2 >= 256)
3505 {
3506 buf[mb_char2bytes(c2, buf)] = 0;
3507 hi = hash_find(&slang->sl_map_hash, buf);
3508 if (HASHITEM_EMPTY(hi))
3509 m2 = 0;
3510 else
3511 m2 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
3512 }
3513 else
3514 m2 = slang->sl_map_array[c2];
3515
3516 return m1 == m2;
3517}
3518
3519/*
3520 * Add a suggestion to the list of suggestions.
3521 * For a suggestion that is already in the list the lowest score is remembered.
3522 */
3523 static void
3524add_suggestion(
3525 suginfo_T *su,
3526 garray_T *gap, // either su_ga or su_sga
3527 char_u *goodword,
3528 int badlenarg, // len of bad word replaced with "goodword"
3529 int score,
3530 int altscore,
3531 int had_bonus, // value for st_had_bonus
3532 slang_T *slang, // language for sound folding
3533 int maxsf) // su_maxscore applies to soundfold score,
3534 // su_sfmaxscore to the total score.
3535{
3536 int goodlen; // len of goodword changed
3537 int badlen; // len of bad word changed
3538 suggest_T *stp;
3539 suggest_T new_sug;
3540 int i;
3541 char_u *pgood, *pbad;
3542
3543 // Minimize "badlen" for consistency. Avoids that changing "the the" to
3544 // "thee the" is added next to changing the first "the" the "thee".
3545 pgood = goodword + STRLEN(goodword);
3546 pbad = su->su_badptr + badlenarg;
3547 for (;;)
3548 {
3549 goodlen = (int)(pgood - goodword);
3550 badlen = (int)(pbad - su->su_badptr);
3551 if (goodlen <= 0 || badlen <= 0)
3552 break;
3553 MB_PTR_BACK(goodword, pgood);
3554 MB_PTR_BACK(su->su_badptr, pbad);
3555 if (has_mbyte)
3556 {
3557 if (mb_ptr2char(pgood) != mb_ptr2char(pbad))
3558 break;
3559 }
3560 else if (*pgood != *pbad)
3561 break;
3562 }
3563
3564 if (badlen == 0 && goodlen == 0)
3565 // goodword doesn't change anything; may happen for "the the" changing
3566 // the first "the" to itself.
3567 return;
3568
3569 if (gap->ga_len == 0)
3570 i = -1;
3571 else
3572 {
3573 // Check if the word is already there. Also check the length that is
3574 // being replaced "thes," -> "these" is a different suggestion from
3575 // "thes" -> "these".
3576 stp = &SUG(*gap, 0);
3577 for (i = gap->ga_len; --i >= 0; ++stp)
3578 if (stp->st_wordlen == goodlen
3579 && stp->st_orglen == badlen
3580 && STRNCMP(stp->st_word, goodword, goodlen) == 0)
3581 {
3582 // Found it. Remember the word with the lowest score.
3583 if (stp->st_slang == NULL)
3584 stp->st_slang = slang;
3585
3586 new_sug.st_score = score;
3587 new_sug.st_altscore = altscore;
3588 new_sug.st_had_bonus = had_bonus;
3589
3590 if (stp->st_had_bonus != had_bonus)
3591 {
3592 // Only one of the two had the soundalike score computed.
3593 // Need to do that for the other one now, otherwise the
3594 // scores can't be compared. This happens because
3595 // suggest_try_change() doesn't compute the soundalike
3596 // word to keep it fast, while some special methods set
3597 // the soundalike score to zero.
3598 if (had_bonus)
3599 rescore_one(su, stp);
3600 else
3601 {
3602 new_sug.st_word = stp->st_word;
3603 new_sug.st_wordlen = stp->st_wordlen;
3604 new_sug.st_slang = stp->st_slang;
3605 new_sug.st_orglen = badlen;
3606 rescore_one(su, &new_sug);
3607 }
3608 }
3609
3610 if (stp->st_score > new_sug.st_score)
3611 {
3612 stp->st_score = new_sug.st_score;
3613 stp->st_altscore = new_sug.st_altscore;
3614 stp->st_had_bonus = new_sug.st_had_bonus;
3615 }
3616 break;
3617 }
3618 }
3619
3620 if (i < 0 && ga_grow(gap, 1) == OK)
3621 {
3622 // Add a suggestion.
3623 stp = &SUG(*gap, gap->ga_len);
3624 stp->st_word = vim_strnsave(goodword, goodlen);
3625 if (stp->st_word != NULL)
3626 {
3627 stp->st_wordlen = goodlen;
3628 stp->st_score = score;
3629 stp->st_altscore = altscore;
3630 stp->st_had_bonus = had_bonus;
3631 stp->st_orglen = badlen;
3632 stp->st_slang = slang;
3633 ++gap->ga_len;
3634
3635 // If we have too many suggestions now, sort the list and keep
3636 // the best suggestions.
3637 if (gap->ga_len > SUG_MAX_COUNT(su))
3638 {
3639 if (maxsf)
3640 su->su_sfmaxscore = cleanup_suggestions(gap,
3641 su->su_sfmaxscore, SUG_CLEAN_COUNT(su));
3642 else
3643 su->su_maxscore = cleanup_suggestions(gap,
3644 su->su_maxscore, SUG_CLEAN_COUNT(su));
3645 }
3646 }
3647 }
3648}
3649
3650/*
3651 * Suggestions may in fact be flagged as errors. Esp. for banned words and
3652 * for split words, such as "the the". Remove these from the list here.
3653 */
3654 static void
3655check_suggestions(
3656 suginfo_T *su,
3657 garray_T *gap) // either su_ga or su_sga
3658{
3659 suggest_T *stp;
3660 int i;
3661 char_u longword[MAXWLEN + 1];
3662 int len;
3663 hlf_T attr;
3664
Bram Moolenaar9c2b0662020-09-01 19:56:15 +02003665 if (gap->ga_len == 0)
3666 return;
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003667 stp = &SUG(*gap, 0);
3668 for (i = gap->ga_len - 1; i >= 0; --i)
3669 {
3670 // Need to append what follows to check for "the the".
3671 vim_strncpy(longword, stp[i].st_word, MAXWLEN);
3672 len = stp[i].st_wordlen;
3673 vim_strncpy(longword + len, su->su_badptr + stp[i].st_orglen,
3674 MAXWLEN - len);
3675 attr = HLF_COUNT;
3676 (void)spell_check(curwin, longword, &attr, NULL, FALSE);
3677 if (attr != HLF_COUNT)
3678 {
3679 // Remove this entry.
3680 vim_free(stp[i].st_word);
3681 --gap->ga_len;
3682 if (i < gap->ga_len)
3683 mch_memmove(stp + i, stp + i + 1,
3684 sizeof(suggest_T) * (gap->ga_len - i));
3685 }
3686 }
3687}
3688
3689
3690/*
3691 * Add a word to be banned.
3692 */
3693 static void
3694add_banned(
3695 suginfo_T *su,
3696 char_u *word)
3697{
3698 char_u *s;
3699 hash_T hash;
3700 hashitem_T *hi;
3701
3702 hash = hash_hash(word);
3703 hi = hash_lookup(&su->su_banned, word, hash);
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003704 if (!HASHITEM_EMPTY(hi)) // already present
3705 return;
3706 s = vim_strsave(word);
3707 if (s != NULL)
3708 hash_add_item(&su->su_banned, hi, s, hash);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003709}
3710
3711/*
3712 * Recompute the score for all suggestions if sound-folding is possible. This
3713 * is slow, thus only done for the final results.
3714 */
3715 static void
3716rescore_suggestions(suginfo_T *su)
3717{
3718 int i;
3719
3720 if (su->su_sallang != NULL)
3721 for (i = 0; i < su->su_ga.ga_len; ++i)
3722 rescore_one(su, &SUG(su->su_ga, i));
3723}
3724
3725/*
3726 * Recompute the score for one suggestion if sound-folding is possible.
3727 */
3728 static void
3729rescore_one(suginfo_T *su, suggest_T *stp)
3730{
3731 slang_T *slang = stp->st_slang;
3732 char_u sal_badword[MAXWLEN];
3733 char_u *p;
3734
3735 // Only rescore suggestions that have no sal score yet and do have a
3736 // language.
3737 if (slang != NULL && slang->sl_sal.ga_len > 0 && !stp->st_had_bonus)
3738 {
3739 if (slang == su->su_sallang)
3740 p = su->su_sal_badword;
3741 else
3742 {
3743 spell_soundfold(slang, su->su_fbadword, TRUE, sal_badword);
3744 p = sal_badword;
3745 }
3746
3747 stp->st_altscore = stp_sal_score(stp, su, slang, p);
3748 if (stp->st_altscore == SCORE_MAXMAX)
3749 stp->st_altscore = SCORE_BIG;
3750 stp->st_score = RESCORE(stp->st_score, stp->st_altscore);
3751 stp->st_had_bonus = TRUE;
3752 }
3753}
3754
3755static int sug_compare(const void *s1, const void *s2);
3756
3757/*
3758 * Function given to qsort() to sort the suggestions on st_score.
3759 * First on "st_score", then "st_altscore" then alphabetically.
3760 */
3761 static int
3762sug_compare(const void *s1, const void *s2)
3763{
3764 suggest_T *p1 = (suggest_T *)s1;
3765 suggest_T *p2 = (suggest_T *)s2;
3766 int n = p1->st_score - p2->st_score;
3767
3768 if (n == 0)
3769 {
3770 n = p1->st_altscore - p2->st_altscore;
3771 if (n == 0)
3772 n = STRICMP(p1->st_word, p2->st_word);
3773 }
3774 return n;
3775}
3776
3777/*
3778 * Cleanup the suggestions:
3779 * - Sort on score.
3780 * - Remove words that won't be displayed.
3781 * Returns the maximum score in the list or "maxscore" unmodified.
3782 */
3783 static int
3784cleanup_suggestions(
3785 garray_T *gap,
3786 int maxscore,
3787 int keep) // nr of suggestions to keep
3788{
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003789 if (gap->ga_len <= 0)
3790 return maxscore;
3791
3792 // Sort the list.
3793 qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T),
3794 sug_compare);
3795
3796 // Truncate the list to the number of suggestions that will be
3797 // displayed.
3798 if (gap->ga_len > keep)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003799 {
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003800 int i;
3801 suggest_T *stp = &SUG(*gap, 0);
Bram Moolenaarbb65a562020-03-15 18:15:03 +01003802
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003803 for (i = keep; i < gap->ga_len; ++i)
3804 vim_free(stp[i].st_word);
3805 gap->ga_len = keep;
3806 if (keep >= 1)
3807 return stp[keep - 1].st_score;
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003808 }
3809 return maxscore;
3810}
3811
3812/*
3813 * Compute a score for two sound-a-like words.
3814 * This permits up to two inserts/deletes/swaps/etc. to keep things fast.
3815 * Instead of a generic loop we write out the code. That keeps it fast by
3816 * avoiding checks that will not be possible.
3817 */
3818 static int
3819soundalike_score(
3820 char_u *goodstart, // sound-folded good word
3821 char_u *badstart) // sound-folded bad word
3822{
3823 char_u *goodsound = goodstart;
3824 char_u *badsound = badstart;
3825 int goodlen;
3826 int badlen;
3827 int n;
3828 char_u *pl, *ps;
3829 char_u *pl2, *ps2;
3830 int score = 0;
3831
3832 // Adding/inserting "*" at the start (word starts with vowel) shouldn't be
3833 // counted so much, vowels halfway the word aren't counted at all.
3834 if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound)
3835 {
3836 if ((badsound[0] == NUL && goodsound[1] == NUL)
3837 || (goodsound[0] == NUL && badsound[1] == NUL))
3838 // changing word with vowel to word without a sound
3839 return SCORE_DEL;
3840 if (badsound[0] == NUL || goodsound[0] == NUL)
3841 // more than two changes
3842 return SCORE_MAXMAX;
3843
3844 if (badsound[1] == goodsound[1]
3845 || (badsound[1] != NUL
3846 && goodsound[1] != NUL
3847 && badsound[2] == goodsound[2]))
3848 {
3849 // handle like a substitute
3850 }
3851 else
3852 {
3853 score = 2 * SCORE_DEL / 3;
3854 if (*badsound == '*')
3855 ++badsound;
3856 else
3857 ++goodsound;
3858 }
3859 }
3860
3861 goodlen = (int)STRLEN(goodsound);
3862 badlen = (int)STRLEN(badsound);
3863
3864 // Return quickly if the lengths are too different to be fixed by two
3865 // changes.
3866 n = goodlen - badlen;
3867 if (n < -2 || n > 2)
3868 return SCORE_MAXMAX;
3869
3870 if (n > 0)
3871 {
3872 pl = goodsound; // goodsound is longest
3873 ps = badsound;
3874 }
3875 else
3876 {
3877 pl = badsound; // badsound is longest
3878 ps = goodsound;
3879 }
3880
3881 // Skip over the identical part.
3882 while (*pl == *ps && *pl != NUL)
3883 {
3884 ++pl;
3885 ++ps;
3886 }
3887
3888 switch (n)
3889 {
3890 case -2:
3891 case 2:
3892 // Must delete two characters from "pl".
3893 ++pl; // first delete
3894 while (*pl == *ps)
3895 {
3896 ++pl;
3897 ++ps;
3898 }
3899 // strings must be equal after second delete
3900 if (STRCMP(pl + 1, ps) == 0)
3901 return score + SCORE_DEL * 2;
3902
3903 // Failed to compare.
3904 break;
3905
3906 case -1:
3907 case 1:
3908 // Minimal one delete from "pl" required.
3909
3910 // 1: delete
3911 pl2 = pl + 1;
3912 ps2 = ps;
3913 while (*pl2 == *ps2)
3914 {
3915 if (*pl2 == NUL) // reached the end
3916 return score + SCORE_DEL;
3917 ++pl2;
3918 ++ps2;
3919 }
3920
3921 // 2: delete then swap, then rest must be equal
3922 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3923 && STRCMP(pl2 + 2, ps2 + 2) == 0)
3924 return score + SCORE_DEL + SCORE_SWAP;
3925
3926 // 3: delete then substitute, then the rest must be equal
3927 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
3928 return score + SCORE_DEL + SCORE_SUBST;
3929
3930 // 4: first swap then delete
3931 if (pl[0] == ps[1] && pl[1] == ps[0])
3932 {
3933 pl2 = pl + 2; // swap, skip two chars
3934 ps2 = ps + 2;
3935 while (*pl2 == *ps2)
3936 {
3937 ++pl2;
3938 ++ps2;
3939 }
3940 // delete a char and then strings must be equal
3941 if (STRCMP(pl2 + 1, ps2) == 0)
3942 return score + SCORE_SWAP + SCORE_DEL;
3943 }
3944
3945 // 5: first substitute then delete
3946 pl2 = pl + 1; // substitute, skip one char
3947 ps2 = ps + 1;
3948 while (*pl2 == *ps2)
3949 {
3950 ++pl2;
3951 ++ps2;
3952 }
3953 // delete a char and then strings must be equal
3954 if (STRCMP(pl2 + 1, ps2) == 0)
3955 return score + SCORE_SUBST + SCORE_DEL;
3956
3957 // Failed to compare.
3958 break;
3959
3960 case 0:
3961 // Lengths are equal, thus changes must result in same length: An
3962 // insert is only possible in combination with a delete.
3963 // 1: check if for identical strings
3964 if (*pl == NUL)
3965 return score;
3966
3967 // 2: swap
3968 if (pl[0] == ps[1] && pl[1] == ps[0])
3969 {
3970 pl2 = pl + 2; // swap, skip two chars
3971 ps2 = ps + 2;
3972 while (*pl2 == *ps2)
3973 {
3974 if (*pl2 == NUL) // reached the end
3975 return score + SCORE_SWAP;
3976 ++pl2;
3977 ++ps2;
3978 }
3979 // 3: swap and swap again
3980 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3981 && STRCMP(pl2 + 2, ps2 + 2) == 0)
3982 return score + SCORE_SWAP + SCORE_SWAP;
3983
3984 // 4: swap and substitute
3985 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
3986 return score + SCORE_SWAP + SCORE_SUBST;
3987 }
3988
3989 // 5: substitute
3990 pl2 = pl + 1;
3991 ps2 = ps + 1;
3992 while (*pl2 == *ps2)
3993 {
3994 if (*pl2 == NUL) // reached the end
3995 return score + SCORE_SUBST;
3996 ++pl2;
3997 ++ps2;
3998 }
3999
4000 // 6: substitute and swap
4001 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
4002 && STRCMP(pl2 + 2, ps2 + 2) == 0)
4003 return score + SCORE_SUBST + SCORE_SWAP;
4004
4005 // 7: substitute and substitute
4006 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
4007 return score + SCORE_SUBST + SCORE_SUBST;
4008
4009 // 8: insert then delete
4010 pl2 = pl;
4011 ps2 = ps + 1;
4012 while (*pl2 == *ps2)
4013 {
4014 ++pl2;
4015 ++ps2;
4016 }
4017 if (STRCMP(pl2 + 1, ps2) == 0)
4018 return score + SCORE_INS + SCORE_DEL;
4019
4020 // 9: delete then insert
4021 pl2 = pl + 1;
4022 ps2 = ps;
4023 while (*pl2 == *ps2)
4024 {
4025 ++pl2;
4026 ++ps2;
4027 }
4028 if (STRCMP(pl2, ps2 + 1) == 0)
4029 return score + SCORE_INS + SCORE_DEL;
4030
4031 // Failed to compare.
4032 break;
4033 }
4034
4035 return SCORE_MAXMAX;
4036}
4037
4038/*
4039 * Compute the "edit distance" to turn "badword" into "goodword". The less
4040 * deletes/inserts/substitutes/swaps are required the lower the score.
4041 *
4042 * The algorithm is described by Du and Chang, 1992.
4043 * The implementation of the algorithm comes from Aspell editdist.cpp,
4044 * edit_distance(). It has been converted from C++ to C and modified to
4045 * support multi-byte characters.
4046 */
4047 static int
4048spell_edit_score(
4049 slang_T *slang,
4050 char_u *badword,
4051 char_u *goodword)
4052{
4053 int *cnt;
4054 int badlen, goodlen; // lengths including NUL
4055 int j, i;
4056 int t;
4057 int bc, gc;
4058 int pbc, pgc;
4059 char_u *p;
4060 int wbadword[MAXWLEN];
4061 int wgoodword[MAXWLEN];
4062
4063 if (has_mbyte)
4064 {
4065 // Get the characters from the multi-byte strings and put them in an
4066 // int array for easy access.
4067 for (p = badword, badlen = 0; *p != NUL; )
4068 wbadword[badlen++] = mb_cptr2char_adv(&p);
4069 wbadword[badlen++] = 0;
4070 for (p = goodword, goodlen = 0; *p != NUL; )
4071 wgoodword[goodlen++] = mb_cptr2char_adv(&p);
4072 wgoodword[goodlen++] = 0;
4073 }
4074 else
4075 {
4076 badlen = (int)STRLEN(badword) + 1;
4077 goodlen = (int)STRLEN(goodword) + 1;
4078 }
4079
4080 // We use "cnt" as an array: CNT(badword_idx, goodword_idx).
4081#define CNT(a, b) cnt[(a) + (b) * (badlen + 1)]
4082 cnt = ALLOC_MULT(int, (badlen + 1) * (goodlen + 1));
4083 if (cnt == NULL)
4084 return 0; // out of memory
4085
4086 CNT(0, 0) = 0;
4087 for (j = 1; j <= goodlen; ++j)
4088 CNT(0, j) = CNT(0, j - 1) + SCORE_INS;
4089
4090 for (i = 1; i <= badlen; ++i)
4091 {
4092 CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL;
4093 for (j = 1; j <= goodlen; ++j)
4094 {
4095 if (has_mbyte)
4096 {
4097 bc = wbadword[i - 1];
4098 gc = wgoodword[j - 1];
4099 }
4100 else
4101 {
4102 bc = badword[i - 1];
4103 gc = goodword[j - 1];
4104 }
4105 if (bc == gc)
4106 CNT(i, j) = CNT(i - 1, j - 1);
4107 else
4108 {
4109 // Use a better score when there is only a case difference.
4110 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
4111 CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1);
4112 else
4113 {
4114 // For a similar character use SCORE_SIMILAR.
4115 if (slang != NULL
4116 && slang->sl_has_map
4117 && similar_chars(slang, gc, bc))
4118 CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1);
4119 else
4120 CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1);
4121 }
4122
4123 if (i > 1 && j > 1)
4124 {
4125 if (has_mbyte)
4126 {
4127 pbc = wbadword[i - 2];
4128 pgc = wgoodword[j - 2];
4129 }
4130 else
4131 {
4132 pbc = badword[i - 2];
4133 pgc = goodword[j - 2];
4134 }
4135 if (bc == pgc && pbc == gc)
4136 {
4137 t = SCORE_SWAP + CNT(i - 2, j - 2);
4138 if (t < CNT(i, j))
4139 CNT(i, j) = t;
4140 }
4141 }
4142 t = SCORE_DEL + CNT(i - 1, j);
4143 if (t < CNT(i, j))
4144 CNT(i, j) = t;
4145 t = SCORE_INS + CNT(i, j - 1);
4146 if (t < CNT(i, j))
4147 CNT(i, j) = t;
4148 }
4149 }
4150 }
4151
4152 i = CNT(badlen - 1, goodlen - 1);
4153 vim_free(cnt);
4154 return i;
4155}
4156
4157typedef struct
4158{
4159 int badi;
4160 int goodi;
4161 int score;
4162} limitscore_T;
4163
4164/*
4165 * Like spell_edit_score(), but with a limit on the score to make it faster.
4166 * May return SCORE_MAXMAX when the score is higher than "limit".
4167 *
4168 * This uses a stack for the edits still to be tried.
4169 * The idea comes from Aspell leditdist.cpp. Rewritten in C and added support
4170 * for multi-byte characters.
4171 */
4172 static int
4173spell_edit_score_limit(
4174 slang_T *slang,
4175 char_u *badword,
4176 char_u *goodword,
4177 int limit)
4178{
4179 limitscore_T stack[10]; // allow for over 3 * 2 edits
4180 int stackidx;
4181 int bi, gi;
4182 int bi2, gi2;
4183 int bc, gc;
4184 int score;
4185 int score_off;
4186 int minscore;
4187 int round;
4188
4189 // Multi-byte characters require a bit more work, use a different function
4190 // to avoid testing "has_mbyte" quite often.
4191 if (has_mbyte)
4192 return spell_edit_score_limit_w(slang, badword, goodword, limit);
4193
4194 // The idea is to go from start to end over the words. So long as
4195 // characters are equal just continue, this always gives the lowest score.
4196 // When there is a difference try several alternatives. Each alternative
4197 // increases "score" for the edit distance. Some of the alternatives are
4198 // pushed unto a stack and tried later, some are tried right away. At the
4199 // end of the word the score for one alternative is known. The lowest
4200 // possible score is stored in "minscore".
4201 stackidx = 0;
4202 bi = 0;
4203 gi = 0;
4204 score = 0;
4205 minscore = limit + 1;
4206
4207 for (;;)
4208 {
4209 // Skip over an equal part, score remains the same.
4210 for (;;)
4211 {
4212 bc = badword[bi];
4213 gc = goodword[gi];
4214 if (bc != gc) // stop at a char that's different
4215 break;
4216 if (bc == NUL) // both words end
4217 {
4218 if (score < minscore)
4219 minscore = score;
4220 goto pop; // do next alternative
4221 }
4222 ++bi;
4223 ++gi;
4224 }
4225
4226 if (gc == NUL) // goodword ends, delete badword chars
4227 {
4228 do
4229 {
4230 if ((score += SCORE_DEL) >= minscore)
4231 goto pop; // do next alternative
4232 } while (badword[++bi] != NUL);
4233 minscore = score;
4234 }
4235 else if (bc == NUL) // badword ends, insert badword chars
4236 {
4237 do
4238 {
4239 if ((score += SCORE_INS) >= minscore)
4240 goto pop; // do next alternative
4241 } while (goodword[++gi] != NUL);
4242 minscore = score;
4243 }
4244 else // both words continue
4245 {
4246 // If not close to the limit, perform a change. Only try changes
4247 // that may lead to a lower score than "minscore".
4248 // round 0: try deleting a char from badword
4249 // round 1: try inserting a char in badword
4250 for (round = 0; round <= 1; ++round)
4251 {
4252 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
4253 if (score_off < minscore)
4254 {
4255 if (score_off + SCORE_EDIT_MIN >= minscore)
4256 {
4257 // Near the limit, rest of the words must match. We
4258 // can check that right now, no need to push an item
4259 // onto the stack.
4260 bi2 = bi + 1 - round;
4261 gi2 = gi + round;
4262 while (goodword[gi2] == badword[bi2])
4263 {
4264 if (goodword[gi2] == NUL)
4265 {
4266 minscore = score_off;
4267 break;
4268 }
4269 ++bi2;
4270 ++gi2;
4271 }
4272 }
4273 else
4274 {
4275 // try deleting/inserting a character later
4276 stack[stackidx].badi = bi + 1 - round;
4277 stack[stackidx].goodi = gi + round;
4278 stack[stackidx].score = score_off;
4279 ++stackidx;
4280 }
4281 }
4282 }
4283
4284 if (score + SCORE_SWAP < minscore)
4285 {
4286 // If swapping two characters makes a match then the
4287 // substitution is more expensive, thus there is no need to
4288 // try both.
4289 if (gc == badword[bi + 1] && bc == goodword[gi + 1])
4290 {
4291 // Swap two characters, that is: skip them.
4292 gi += 2;
4293 bi += 2;
4294 score += SCORE_SWAP;
4295 continue;
4296 }
4297 }
4298
4299 // Substitute one character for another which is the same
4300 // thing as deleting a character from both goodword and badword.
4301 // Use a better score when there is only a case difference.
4302 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
4303 score += SCORE_ICASE;
4304 else
4305 {
4306 // For a similar character use SCORE_SIMILAR.
4307 if (slang != NULL
4308 && slang->sl_has_map
4309 && similar_chars(slang, gc, bc))
4310 score += SCORE_SIMILAR;
4311 else
4312 score += SCORE_SUBST;
4313 }
4314
4315 if (score < minscore)
4316 {
4317 // Do the substitution.
4318 ++gi;
4319 ++bi;
4320 continue;
4321 }
4322 }
4323pop:
4324 // Get here to try the next alternative, pop it from the stack.
4325 if (stackidx == 0) // stack is empty, finished
4326 break;
4327
4328 // pop an item from the stack
4329 --stackidx;
4330 gi = stack[stackidx].goodi;
4331 bi = stack[stackidx].badi;
4332 score = stack[stackidx].score;
4333 }
4334
4335 // When the score goes over "limit" it may actually be much higher.
4336 // Return a very large number to avoid going below the limit when giving a
4337 // bonus.
4338 if (minscore > limit)
4339 return SCORE_MAXMAX;
4340 return minscore;
4341}
4342
4343/*
4344 * Multi-byte version of spell_edit_score_limit().
4345 * Keep it in sync with the above!
4346 */
4347 static int
4348spell_edit_score_limit_w(
4349 slang_T *slang,
4350 char_u *badword,
4351 char_u *goodword,
4352 int limit)
4353{
4354 limitscore_T stack[10]; // allow for over 3 * 2 edits
4355 int stackidx;
4356 int bi, gi;
4357 int bi2, gi2;
4358 int bc, gc;
4359 int score;
4360 int score_off;
4361 int minscore;
4362 int round;
4363 char_u *p;
4364 int wbadword[MAXWLEN];
4365 int wgoodword[MAXWLEN];
4366
4367 // Get the characters from the multi-byte strings and put them in an
4368 // int array for easy access.
4369 bi = 0;
4370 for (p = badword; *p != NUL; )
4371 wbadword[bi++] = mb_cptr2char_adv(&p);
4372 wbadword[bi++] = 0;
4373 gi = 0;
4374 for (p = goodword; *p != NUL; )
4375 wgoodword[gi++] = mb_cptr2char_adv(&p);
4376 wgoodword[gi++] = 0;
4377
4378 // The idea is to go from start to end over the words. So long as
4379 // characters are equal just continue, this always gives the lowest score.
4380 // When there is a difference try several alternatives. Each alternative
4381 // increases "score" for the edit distance. Some of the alternatives are
4382 // pushed unto a stack and tried later, some are tried right away. At the
4383 // end of the word the score for one alternative is known. The lowest
4384 // possible score is stored in "minscore".
4385 stackidx = 0;
4386 bi = 0;
4387 gi = 0;
4388 score = 0;
4389 minscore = limit + 1;
4390
4391 for (;;)
4392 {
4393 // Skip over an equal part, score remains the same.
4394 for (;;)
4395 {
4396 bc = wbadword[bi];
4397 gc = wgoodword[gi];
4398
4399 if (bc != gc) // stop at a char that's different
4400 break;
4401 if (bc == NUL) // both words end
4402 {
4403 if (score < minscore)
4404 minscore = score;
4405 goto pop; // do next alternative
4406 }
4407 ++bi;
4408 ++gi;
4409 }
4410
4411 if (gc == NUL) // goodword ends, delete badword chars
4412 {
4413 do
4414 {
4415 if ((score += SCORE_DEL) >= minscore)
4416 goto pop; // do next alternative
4417 } while (wbadword[++bi] != NUL);
4418 minscore = score;
4419 }
4420 else if (bc == NUL) // badword ends, insert badword chars
4421 {
4422 do
4423 {
4424 if ((score += SCORE_INS) >= minscore)
4425 goto pop; // do next alternative
4426 } while (wgoodword[++gi] != NUL);
4427 minscore = score;
4428 }
4429 else // both words continue
4430 {
4431 // If not close to the limit, perform a change. Only try changes
4432 // that may lead to a lower score than "minscore".
4433 // round 0: try deleting a char from badword
4434 // round 1: try inserting a char in badword
4435 for (round = 0; round <= 1; ++round)
4436 {
4437 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
4438 if (score_off < minscore)
4439 {
4440 if (score_off + SCORE_EDIT_MIN >= minscore)
4441 {
4442 // Near the limit, rest of the words must match. We
4443 // can check that right now, no need to push an item
4444 // onto the stack.
4445 bi2 = bi + 1 - round;
4446 gi2 = gi + round;
4447 while (wgoodword[gi2] == wbadword[bi2])
4448 {
4449 if (wgoodword[gi2] == NUL)
4450 {
4451 minscore = score_off;
4452 break;
4453 }
4454 ++bi2;
4455 ++gi2;
4456 }
4457 }
4458 else
4459 {
4460 // try deleting a character from badword later
4461 stack[stackidx].badi = bi + 1 - round;
4462 stack[stackidx].goodi = gi + round;
4463 stack[stackidx].score = score_off;
4464 ++stackidx;
4465 }
4466 }
4467 }
4468
4469 if (score + SCORE_SWAP < minscore)
4470 {
4471 // If swapping two characters makes a match then the
4472 // substitution is more expensive, thus there is no need to
4473 // try both.
4474 if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1])
4475 {
4476 // Swap two characters, that is: skip them.
4477 gi += 2;
4478 bi += 2;
4479 score += SCORE_SWAP;
4480 continue;
4481 }
4482 }
4483
4484 // Substitute one character for another which is the same
4485 // thing as deleting a character from both goodword and badword.
4486 // Use a better score when there is only a case difference.
4487 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
4488 score += SCORE_ICASE;
4489 else
4490 {
4491 // For a similar character use SCORE_SIMILAR.
4492 if (slang != NULL
4493 && slang->sl_has_map
4494 && similar_chars(slang, gc, bc))
4495 score += SCORE_SIMILAR;
4496 else
4497 score += SCORE_SUBST;
4498 }
4499
4500 if (score < minscore)
4501 {
4502 // Do the substitution.
4503 ++gi;
4504 ++bi;
4505 continue;
4506 }
4507 }
4508pop:
4509 // Get here to try the next alternative, pop it from the stack.
4510 if (stackidx == 0) // stack is empty, finished
4511 break;
4512
4513 // pop an item from the stack
4514 --stackidx;
4515 gi = stack[stackidx].goodi;
4516 bi = stack[stackidx].badi;
4517 score = stack[stackidx].score;
4518 }
4519
4520 // When the score goes over "limit" it may actually be much higher.
4521 // Return a very large number to avoid going below the limit when giving a
4522 // bonus.
4523 if (minscore > limit)
4524 return SCORE_MAXMAX;
4525 return minscore;
4526}
4527#endif // FEAT_SPELL