blob: e1c303a0ab8793b6e6da26cedbcc8a3dc494d680 [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++;
2178 c = byts[n];
2179 if (soundfold && sp->ts_twordlen == 0 && c == '*')
2180 // Inserting a vowel at the start of a word counts less,
2181 // see soundalike_score().
2182 newscore = 2 * SCORE_INS / 3;
2183 else
2184 newscore = SCORE_INS;
2185 if (c != fword[sp->ts_fidx]
2186 && TRY_DEEPER(su, stack, depth, newscore))
2187 {
2188 go_deeper(stack, depth, newscore);
2189#ifdef DEBUG_TRIEWALK
2190 sprintf(changename[depth], "%.*s-%s: insert %c",
2191 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2192 c);
2193#endif
2194 ++depth;
2195 sp = &stack[depth];
2196 tword[sp->ts_twordlen++] = c;
2197 sp->ts_arridx = idxs[n];
2198 if (has_mbyte)
2199 {
2200 fl = MB_BYTE2LEN(c);
2201 if (fl > 1)
2202 {
2203 // There are following bytes for the same character.
2204 // We must find all bytes before trying
2205 // delete/insert/swap/etc.
2206 sp->ts_tcharlen = fl;
2207 sp->ts_tcharidx = 1;
2208 sp->ts_isdiff = DIFF_INSERT;
2209 }
2210 }
2211 else
2212 fl = 1;
2213 if (fl == 1)
2214 {
2215 // If the previous character was the same, thus doubling a
2216 // character, give a bonus to the score. Also for
2217 // soundfold words (illogical but does give a better
2218 // score).
2219 if (sp->ts_twordlen >= 2
2220 && tword[sp->ts_twordlen - 2] == c)
2221 sp->ts_score -= SCORE_INS - SCORE_INSDUP;
2222 }
2223 }
2224 break;
2225
2226 case STATE_SWAP:
2227 // Swap two bytes in the bad word: "12" -> "21".
2228 // We change "fword" here, it's changed back afterwards at
2229 // STATE_UNSWAP.
2230 p = fword + sp->ts_fidx;
2231 c = *p;
2232 if (c == NUL)
2233 {
2234 // End of word, can't swap or replace.
2235 PROF_STORE(sp->ts_state)
2236 sp->ts_state = STATE_FINAL;
2237 break;
2238 }
2239
2240 // Don't swap if the first character is not a word character.
2241 // SWAP3 etc. also don't make sense then.
2242 if (!soundfold && !spell_iswordp(p, curwin))
2243 {
2244 PROF_STORE(sp->ts_state)
2245 sp->ts_state = STATE_REP_INI;
2246 break;
2247 }
2248
2249 if (has_mbyte)
2250 {
2251 n = MB_CPTR2LEN(p);
2252 c = mb_ptr2char(p);
2253 if (p[n] == NUL)
2254 c2 = NUL;
2255 else if (!soundfold && !spell_iswordp(p + n, curwin))
2256 c2 = c; // don't swap non-word char
2257 else
2258 c2 = mb_ptr2char(p + n);
2259 }
2260 else
2261 {
2262 if (p[1] == NUL)
2263 c2 = NUL;
2264 else if (!soundfold && !spell_iswordp(p + 1, curwin))
2265 c2 = c; // don't swap non-word char
2266 else
2267 c2 = p[1];
2268 }
2269
2270 // When the second character is NUL we can't swap.
2271 if (c2 == NUL)
2272 {
2273 PROF_STORE(sp->ts_state)
2274 sp->ts_state = STATE_REP_INI;
2275 break;
2276 }
2277
2278 // When characters are identical, swap won't do anything.
2279 // Also get here if the second char is not a word character.
2280 if (c == c2)
2281 {
2282 PROF_STORE(sp->ts_state)
2283 sp->ts_state = STATE_SWAP3;
2284 break;
2285 }
2286 if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
2287 {
2288 go_deeper(stack, depth, SCORE_SWAP);
2289#ifdef DEBUG_TRIEWALK
2290 sprintf(changename[depth], "%.*s-%s: swap %c and %c",
2291 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2292 c, c2);
2293#endif
2294 PROF_STORE(sp->ts_state)
2295 sp->ts_state = STATE_UNSWAP;
2296 ++depth;
2297 if (has_mbyte)
2298 {
2299 fl = mb_char2len(c2);
2300 mch_memmove(p, p + n, fl);
2301 mb_char2bytes(c, p + fl);
2302 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
2303 }
2304 else
2305 {
2306 p[0] = c2;
2307 p[1] = c;
2308 stack[depth].ts_fidxtry = sp->ts_fidx + 2;
2309 }
2310 }
2311 else
2312 {
2313 // If this swap doesn't work then SWAP3 won't either.
2314 PROF_STORE(sp->ts_state)
2315 sp->ts_state = STATE_REP_INI;
2316 }
2317 break;
2318
2319 case STATE_UNSWAP:
2320 // Undo the STATE_SWAP swap: "21" -> "12".
2321 p = fword + sp->ts_fidx;
2322 if (has_mbyte)
2323 {
Bram Moolenaar1614a142019-10-06 22:00:13 +02002324 n = mb_ptr2len(p);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002325 c = mb_ptr2char(p + n);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002326 mch_memmove(p + mb_ptr2len(p + n), p, n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002327 mb_char2bytes(c, p);
2328 }
2329 else
2330 {
2331 c = *p;
2332 *p = p[1];
2333 p[1] = c;
2334 }
2335 // FALLTHROUGH
2336
2337 case STATE_SWAP3:
2338 // Swap two bytes, skipping one: "123" -> "321". We change
2339 // "fword" here, it's changed back afterwards at STATE_UNSWAP3.
2340 p = fword + sp->ts_fidx;
2341 if (has_mbyte)
2342 {
2343 n = MB_CPTR2LEN(p);
2344 c = mb_ptr2char(p);
2345 fl = MB_CPTR2LEN(p + n);
2346 c2 = mb_ptr2char(p + n);
2347 if (!soundfold && !spell_iswordp(p + n + fl, curwin))
2348 c3 = c; // don't swap non-word char
2349 else
2350 c3 = mb_ptr2char(p + n + fl);
2351 }
2352 else
2353 {
2354 c = *p;
2355 c2 = p[1];
2356 if (!soundfold && !spell_iswordp(p + 2, curwin))
2357 c3 = c; // don't swap non-word char
2358 else
2359 c3 = p[2];
2360 }
2361
2362 // When characters are identical: "121" then SWAP3 result is
2363 // identical, ROT3L result is same as SWAP: "211", ROT3L result is
2364 // same as SWAP on next char: "112". Thus skip all swapping.
2365 // Also skip when c3 is NUL.
2366 // Also get here when the third character is not a word character.
2367 // Second character may any char: "a.b" -> "b.a"
2368 if (c == c3 || c3 == NUL)
2369 {
2370 PROF_STORE(sp->ts_state)
2371 sp->ts_state = STATE_REP_INI;
2372 break;
2373 }
2374 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
2375 {
2376 go_deeper(stack, depth, SCORE_SWAP3);
2377#ifdef DEBUG_TRIEWALK
2378 sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",
2379 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2380 c, c3);
2381#endif
2382 PROF_STORE(sp->ts_state)
2383 sp->ts_state = STATE_UNSWAP3;
2384 ++depth;
2385 if (has_mbyte)
2386 {
2387 tl = mb_char2len(c3);
2388 mch_memmove(p, p + n + fl, tl);
2389 mb_char2bytes(c2, p + tl);
2390 mb_char2bytes(c, p + fl + tl);
2391 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
2392 }
2393 else
2394 {
2395 p[0] = p[2];
2396 p[2] = c;
2397 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
2398 }
2399 }
2400 else
2401 {
2402 PROF_STORE(sp->ts_state)
2403 sp->ts_state = STATE_REP_INI;
2404 }
2405 break;
2406
2407 case STATE_UNSWAP3:
2408 // Undo STATE_SWAP3: "321" -> "123"
2409 p = fword + sp->ts_fidx;
2410 if (has_mbyte)
2411 {
Bram Moolenaar1614a142019-10-06 22:00:13 +02002412 n = mb_ptr2len(p);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002413 c2 = mb_ptr2char(p + n);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002414 fl = mb_ptr2len(p + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002415 c = mb_ptr2char(p + n + fl);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002416 tl = mb_ptr2len(p + n + fl);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002417 mch_memmove(p + fl + tl, p, n);
2418 mb_char2bytes(c, p);
2419 mb_char2bytes(c2, p + tl);
2420 p = p + tl;
2421 }
2422 else
2423 {
2424 c = *p;
2425 *p = p[2];
2426 p[2] = c;
2427 ++p;
2428 }
2429
2430 if (!soundfold && !spell_iswordp(p, curwin))
2431 {
2432 // Middle char is not a word char, skip the rotate. First and
2433 // third char were already checked at swap and swap3.
2434 PROF_STORE(sp->ts_state)
2435 sp->ts_state = STATE_REP_INI;
2436 break;
2437 }
2438
2439 // Rotate three characters left: "123" -> "231". We change
2440 // "fword" here, it's changed back afterwards at STATE_UNROT3L.
2441 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
2442 {
2443 go_deeper(stack, depth, SCORE_SWAP3);
2444#ifdef DEBUG_TRIEWALK
2445 p = fword + sp->ts_fidx;
2446 sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",
2447 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2448 p[0], p[1], p[2]);
2449#endif
2450 PROF_STORE(sp->ts_state)
2451 sp->ts_state = STATE_UNROT3L;
2452 ++depth;
2453 p = fword + sp->ts_fidx;
2454 if (has_mbyte)
2455 {
2456 n = MB_CPTR2LEN(p);
2457 c = mb_ptr2char(p);
2458 fl = MB_CPTR2LEN(p + n);
2459 fl += MB_CPTR2LEN(p + n + fl);
2460 mch_memmove(p, p + n, fl);
2461 mb_char2bytes(c, p + fl);
2462 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
2463 }
2464 else
2465 {
2466 c = *p;
2467 *p = p[1];
2468 p[1] = p[2];
2469 p[2] = c;
2470 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
2471 }
2472 }
2473 else
2474 {
2475 PROF_STORE(sp->ts_state)
2476 sp->ts_state = STATE_REP_INI;
2477 }
2478 break;
2479
2480 case STATE_UNROT3L:
2481 // Undo ROT3L: "231" -> "123"
2482 p = fword + sp->ts_fidx;
2483 if (has_mbyte)
2484 {
Bram Moolenaar1614a142019-10-06 22:00:13 +02002485 n = mb_ptr2len(p);
2486 n += mb_ptr2len(p + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002487 c = mb_ptr2char(p + n);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002488 tl = mb_ptr2len(p + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002489 mch_memmove(p + tl, p, n);
2490 mb_char2bytes(c, p);
2491 }
2492 else
2493 {
2494 c = p[2];
2495 p[2] = p[1];
2496 p[1] = *p;
2497 *p = c;
2498 }
2499
2500 // Rotate three bytes right: "123" -> "312". We change "fword"
2501 // here, it's changed back afterwards at STATE_UNROT3R.
2502 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
2503 {
2504 go_deeper(stack, depth, SCORE_SWAP3);
2505#ifdef DEBUG_TRIEWALK
2506 p = fword + sp->ts_fidx;
2507 sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",
2508 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2509 p[0], p[1], p[2]);
2510#endif
2511 PROF_STORE(sp->ts_state)
2512 sp->ts_state = STATE_UNROT3R;
2513 ++depth;
2514 p = fword + sp->ts_fidx;
2515 if (has_mbyte)
2516 {
2517 n = MB_CPTR2LEN(p);
2518 n += MB_CPTR2LEN(p + n);
2519 c = mb_ptr2char(p + n);
2520 tl = MB_CPTR2LEN(p + n);
2521 mch_memmove(p + tl, p, n);
2522 mb_char2bytes(c, p);
2523 stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
2524 }
2525 else
2526 {
2527 c = p[2];
2528 p[2] = p[1];
2529 p[1] = *p;
2530 *p = c;
2531 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
2532 }
2533 }
2534 else
2535 {
2536 PROF_STORE(sp->ts_state)
2537 sp->ts_state = STATE_REP_INI;
2538 }
2539 break;
2540
2541 case STATE_UNROT3R:
2542 // Undo ROT3R: "312" -> "123"
2543 p = fword + sp->ts_fidx;
2544 if (has_mbyte)
2545 {
2546 c = mb_ptr2char(p);
Bram Moolenaar1614a142019-10-06 22:00:13 +02002547 tl = mb_ptr2len(p);
2548 n = mb_ptr2len(p + tl);
2549 n += mb_ptr2len(p + tl + n);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002550 mch_memmove(p, p + tl, n);
2551 mb_char2bytes(c, p + n);
2552 }
2553 else
2554 {
2555 c = *p;
2556 *p = p[1];
2557 p[1] = p[2];
2558 p[2] = c;
2559 }
2560 // FALLTHROUGH
2561
2562 case STATE_REP_INI:
2563 // Check if matching with REP items from the .aff file would work.
2564 // Quickly skip if:
2565 // - there are no REP items and we are not in the soundfold trie
2566 // - the score is going to be too high anyway
2567 // - already applied a REP item or swapped here
2568 if ((lp->lp_replang == NULL && !soundfold)
2569 || sp->ts_score + SCORE_REP >= su->su_maxscore
2570 || sp->ts_fidx < sp->ts_fidxtry)
2571 {
2572 PROF_STORE(sp->ts_state)
2573 sp->ts_state = STATE_FINAL;
2574 break;
2575 }
2576
2577 // Use the first byte to quickly find the first entry that may
2578 // match. If the index is -1 there is none.
2579 if (soundfold)
2580 sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
2581 else
2582 sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];
2583
2584 if (sp->ts_curi < 0)
2585 {
2586 PROF_STORE(sp->ts_state)
2587 sp->ts_state = STATE_FINAL;
2588 break;
2589 }
2590
2591 PROF_STORE(sp->ts_state)
2592 sp->ts_state = STATE_REP;
2593 // FALLTHROUGH
2594
2595 case STATE_REP:
2596 // Try matching with REP items from the .aff file. For each match
2597 // replace the characters and check if the resulting word is
2598 // valid.
2599 p = fword + sp->ts_fidx;
2600
2601 if (soundfold)
2602 gap = &slang->sl_repsal;
2603 else
2604 gap = &lp->lp_replang->sl_rep;
2605 while (sp->ts_curi < gap->ga_len)
2606 {
2607 ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
2608 if (*ftp->ft_from != *p)
2609 {
2610 // past possible matching entries
2611 sp->ts_curi = gap->ga_len;
2612 break;
2613 }
2614 if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
2615 && TRY_DEEPER(su, stack, depth, SCORE_REP))
2616 {
2617 go_deeper(stack, depth, SCORE_REP);
2618#ifdef DEBUG_TRIEWALK
2619 sprintf(changename[depth], "%.*s-%s: replace %s with %s",
2620 sp->ts_twordlen, tword, fword + sp->ts_fidx,
2621 ftp->ft_from, ftp->ft_to);
2622#endif
2623 // Need to undo this afterwards.
2624 PROF_STORE(sp->ts_state)
2625 sp->ts_state = STATE_REP_UNDO;
2626
2627 // Change the "from" to the "to" string.
2628 ++depth;
2629 fl = (int)STRLEN(ftp->ft_from);
2630 tl = (int)STRLEN(ftp->ft_to);
2631 if (fl != tl)
2632 {
2633 STRMOVE(p + tl, p + fl);
2634 repextra += tl - fl;
2635 }
2636 mch_memmove(p, ftp->ft_to, tl);
2637 stack[depth].ts_fidxtry = sp->ts_fidx + tl;
2638 stack[depth].ts_tcharlen = 0;
2639 break;
2640 }
2641 }
2642
2643 if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
2644 {
2645 // No (more) matches.
2646 PROF_STORE(sp->ts_state)
2647 sp->ts_state = STATE_FINAL;
2648 }
2649
2650 break;
2651
2652 case STATE_REP_UNDO:
2653 // Undo a REP replacement and continue with the next one.
2654 if (soundfold)
2655 gap = &slang->sl_repsal;
2656 else
2657 gap = &lp->lp_replang->sl_rep;
2658 ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
2659 fl = (int)STRLEN(ftp->ft_from);
2660 tl = (int)STRLEN(ftp->ft_to);
2661 p = fword + sp->ts_fidx;
2662 if (fl != tl)
2663 {
2664 STRMOVE(p + fl, p + tl);
2665 repextra -= tl - fl;
2666 }
2667 mch_memmove(p, ftp->ft_from, fl);
2668 PROF_STORE(sp->ts_state)
2669 sp->ts_state = STATE_REP;
2670 break;
2671
2672 default:
2673 // Did all possible states at this level, go up one level.
2674 --depth;
2675
2676 if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
2677 {
2678 // Continue in or go back to the prefix tree.
2679 byts = pbyts;
2680 idxs = pidxs;
2681 }
2682
2683 // Don't check for CTRL-C too often, it takes time.
2684 if (--breakcheckcount == 0)
2685 {
2686 ui_breakcheck();
2687 breakcheckcount = 1000;
Bram Moolenaar06f15412022-01-29 10:51:59 +00002688#ifdef FEAT_RELTIME
Bram Moolenaar585ee072022-01-29 11:22:17 +00002689 if (spell_suggest_timeout > 0
2690 && profile_passed_limit(&time_limit))
Bram Moolenaar06f15412022-01-29 10:51:59 +00002691 got_int = TRUE;
2692#endif
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002693 }
2694 }
2695 }
2696}
2697
2698
2699/*
2700 * Go one level deeper in the tree.
2701 */
2702 static void
2703go_deeper(trystate_T *stack, int depth, int score_add)
2704{
2705 stack[depth + 1] = stack[depth];
2706 stack[depth + 1].ts_state = STATE_START;
2707 stack[depth + 1].ts_score = stack[depth].ts_score + score_add;
2708 stack[depth + 1].ts_curi = 1; // start just after length byte
2709 stack[depth + 1].ts_flags = 0;
2710}
2711
2712/*
2713 * "fword" is a good word with case folded. Find the matching keep-case
2714 * words and put it in "kword".
2715 * Theoretically there could be several keep-case words that result in the
2716 * same case-folded word, but we only find one...
2717 */
2718 static void
2719find_keepcap_word(slang_T *slang, char_u *fword, char_u *kword)
2720{
2721 char_u uword[MAXWLEN]; // "fword" in upper-case
2722 int depth;
2723 idx_T tryidx;
2724
2725 // The following arrays are used at each depth in the tree.
2726 idx_T arridx[MAXWLEN];
2727 int round[MAXWLEN];
2728 int fwordidx[MAXWLEN];
2729 int uwordidx[MAXWLEN];
2730 int kwordlen[MAXWLEN];
2731
2732 int flen, ulen;
2733 int l;
2734 int len;
2735 int c;
2736 idx_T lo, hi, m;
2737 char_u *p;
2738 char_u *byts = slang->sl_kbyts; // array with bytes of the words
2739 idx_T *idxs = slang->sl_kidxs; // array with indexes
2740
2741 if (byts == NULL)
2742 {
2743 // array is empty: "cannot happen"
2744 *kword = NUL;
2745 return;
2746 }
2747
2748 // Make an all-cap version of "fword".
2749 allcap_copy(fword, uword);
2750
2751 // Each character needs to be tried both case-folded and upper-case.
2752 // All this gets very complicated if we keep in mind that changing case
2753 // may change the byte length of a multi-byte character...
2754 depth = 0;
2755 arridx[0] = 0;
2756 round[0] = 0;
2757 fwordidx[0] = 0;
2758 uwordidx[0] = 0;
2759 kwordlen[0] = 0;
2760 while (depth >= 0)
2761 {
2762 if (fword[fwordidx[depth]] == NUL)
2763 {
2764 // We are at the end of "fword". If the tree allows a word to end
2765 // here we have found a match.
2766 if (byts[arridx[depth] + 1] == 0)
2767 {
2768 kword[kwordlen[depth]] = NUL;
2769 return;
2770 }
2771
2772 // kword is getting too long, continue one level up
2773 --depth;
2774 }
2775 else if (++round[depth] > 2)
2776 {
2777 // tried both fold-case and upper-case character, continue one
2778 // level up
2779 --depth;
2780 }
2781 else
2782 {
2783 // round[depth] == 1: Try using the folded-case character.
2784 // round[depth] == 2: Try using the upper-case character.
2785 if (has_mbyte)
2786 {
2787 flen = MB_CPTR2LEN(fword + fwordidx[depth]);
2788 ulen = MB_CPTR2LEN(uword + uwordidx[depth]);
2789 }
2790 else
2791 ulen = flen = 1;
2792 if (round[depth] == 1)
2793 {
2794 p = fword + fwordidx[depth];
2795 l = flen;
2796 }
2797 else
2798 {
2799 p = uword + uwordidx[depth];
2800 l = ulen;
2801 }
2802
2803 for (tryidx = arridx[depth]; l > 0; --l)
2804 {
2805 // Perform a binary search in the list of accepted bytes.
2806 len = byts[tryidx++];
2807 c = *p++;
2808 lo = tryidx;
2809 hi = tryidx + len - 1;
2810 while (lo < hi)
2811 {
2812 m = (lo + hi) / 2;
2813 if (byts[m] > c)
2814 hi = m - 1;
2815 else if (byts[m] < c)
2816 lo = m + 1;
2817 else
2818 {
2819 lo = hi = m;
2820 break;
2821 }
2822 }
2823
2824 // Stop if there is no matching byte.
2825 if (hi < lo || byts[lo] != c)
2826 break;
2827
2828 // Continue at the child (if there is one).
2829 tryidx = idxs[lo];
2830 }
2831
2832 if (l == 0)
2833 {
2834 // Found the matching char. Copy it to "kword" and go a
2835 // level deeper.
2836 if (round[depth] == 1)
2837 {
2838 STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth],
2839 flen);
2840 kwordlen[depth + 1] = kwordlen[depth] + flen;
2841 }
2842 else
2843 {
2844 STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth],
2845 ulen);
2846 kwordlen[depth + 1] = kwordlen[depth] + ulen;
2847 }
2848 fwordidx[depth + 1] = fwordidx[depth] + flen;
2849 uwordidx[depth + 1] = uwordidx[depth] + ulen;
2850
2851 ++depth;
2852 arridx[depth] = tryidx;
2853 round[depth] = 0;
2854 }
2855 }
2856 }
2857
2858 // Didn't find it: "cannot happen".
2859 *kword = NUL;
2860}
2861
2862/*
2863 * Compute the sound-a-like score for suggestions in su->su_ga and add them to
2864 * su->su_sga.
2865 */
2866 static void
2867score_comp_sal(suginfo_T *su)
2868{
2869 langp_T *lp;
2870 char_u badsound[MAXWLEN];
2871 int i;
2872 suggest_T *stp;
2873 suggest_T *sstp;
2874 int score;
2875 int lpi;
2876
2877 if (ga_grow(&su->su_sga, su->su_ga.ga_len) == FAIL)
2878 return;
2879
2880 // Use the sound-folding of the first language that supports it.
2881 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
2882 {
2883 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2884 if (lp->lp_slang->sl_sal.ga_len > 0)
2885 {
2886 // soundfold the bad word
2887 spell_soundfold(lp->lp_slang, su->su_fbadword, TRUE, badsound);
2888
2889 for (i = 0; i < su->su_ga.ga_len; ++i)
2890 {
2891 stp = &SUG(su->su_ga, i);
2892
2893 // Case-fold the suggested word, sound-fold it and compute the
2894 // sound-a-like score.
2895 score = stp_sal_score(stp, su, lp->lp_slang, badsound);
2896 if (score < SCORE_MAXMAX)
2897 {
2898 // Add the suggestion.
2899 sstp = &SUG(su->su_sga, su->su_sga.ga_len);
2900 sstp->st_word = vim_strsave(stp->st_word);
2901 if (sstp->st_word != NULL)
2902 {
2903 sstp->st_wordlen = stp->st_wordlen;
2904 sstp->st_score = score;
2905 sstp->st_altscore = 0;
2906 sstp->st_orglen = stp->st_orglen;
2907 ++su->su_sga.ga_len;
2908 }
2909 }
2910 }
2911 break;
2912 }
2913 }
2914}
2915
2916/*
2917 * Combine the list of suggestions in su->su_ga and su->su_sga.
2918 * They are entwined.
2919 */
2920 static void
2921score_combine(suginfo_T *su)
2922{
2923 int i;
2924 int j;
2925 garray_T ga;
2926 garray_T *gap;
2927 langp_T *lp;
2928 suggest_T *stp;
2929 char_u *p;
2930 char_u badsound[MAXWLEN];
2931 int round;
2932 int lpi;
2933 slang_T *slang = NULL;
2934
2935 // Add the alternate score to su_ga.
2936 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
2937 {
2938 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
2939 if (lp->lp_slang->sl_sal.ga_len > 0)
2940 {
2941 // soundfold the bad word
2942 slang = lp->lp_slang;
2943 spell_soundfold(slang, su->su_fbadword, TRUE, badsound);
2944
2945 for (i = 0; i < su->su_ga.ga_len; ++i)
2946 {
2947 stp = &SUG(su->su_ga, i);
2948 stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
2949 if (stp->st_altscore == SCORE_MAXMAX)
2950 stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
2951 else
2952 stp->st_score = (stp->st_score * 3
2953 + stp->st_altscore) / 4;
2954 stp->st_salscore = FALSE;
2955 }
2956 break;
2957 }
2958 }
2959
2960 if (slang == NULL) // Using "double" without sound folding.
2961 {
2962 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore,
2963 su->su_maxcount);
2964 return;
2965 }
2966
2967 // Add the alternate score to su_sga.
2968 for (i = 0; i < su->su_sga.ga_len; ++i)
2969 {
2970 stp = &SUG(su->su_sga, i);
2971 stp->st_altscore = spell_edit_score(slang,
2972 su->su_badword, stp->st_word);
2973 if (stp->st_score == SCORE_MAXMAX)
2974 stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
2975 else
2976 stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8;
2977 stp->st_salscore = TRUE;
2978 }
2979
2980 // Remove bad suggestions, sort the suggestions and truncate at "maxcount"
2981 // for both lists.
2982 check_suggestions(su, &su->su_ga);
2983 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
2984 check_suggestions(su, &su->su_sga);
2985 (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount);
2986
Bram Moolenaar04935fb2022-01-08 16:19:22 +00002987 ga_init2(&ga, sizeof(suginfo_T), 1);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02002988 if (ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len) == FAIL)
2989 return;
2990
2991 stp = &SUG(ga, 0);
2992 for (i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i)
2993 {
2994 // round 1: get a suggestion from su_ga
2995 // round 2: get a suggestion from su_sga
2996 for (round = 1; round <= 2; ++round)
2997 {
2998 gap = round == 1 ? &su->su_ga : &su->su_sga;
2999 if (i < gap->ga_len)
3000 {
3001 // Don't add a word if it's already there.
3002 p = SUG(*gap, i).st_word;
3003 for (j = 0; j < ga.ga_len; ++j)
3004 if (STRCMP(stp[j].st_word, p) == 0)
3005 break;
3006 if (j == ga.ga_len)
3007 stp[ga.ga_len++] = SUG(*gap, i);
3008 else
3009 vim_free(p);
3010 }
3011 }
3012 }
3013
3014 ga_clear(&su->su_ga);
3015 ga_clear(&su->su_sga);
3016
3017 // Truncate the list to the number of suggestions that will be displayed.
3018 if (ga.ga_len > su->su_maxcount)
3019 {
3020 for (i = su->su_maxcount; i < ga.ga_len; ++i)
3021 vim_free(stp[i].st_word);
3022 ga.ga_len = su->su_maxcount;
3023 }
3024
3025 su->su_ga = ga;
3026}
3027
3028/*
3029 * For the goodword in "stp" compute the soundalike score compared to the
3030 * badword.
3031 */
3032 static int
3033stp_sal_score(
3034 suggest_T *stp,
3035 suginfo_T *su,
3036 slang_T *slang,
3037 char_u *badsound) // sound-folded badword
3038{
3039 char_u *p;
3040 char_u *pbad;
3041 char_u *pgood;
3042 char_u badsound2[MAXWLEN];
3043 char_u fword[MAXWLEN];
3044 char_u goodsound[MAXWLEN];
3045 char_u goodword[MAXWLEN];
3046 int lendiff;
3047
3048 lendiff = (int)(su->su_badlen - stp->st_orglen);
3049 if (lendiff >= 0)
3050 pbad = badsound;
3051 else
3052 {
3053 // soundfold the bad word with more characters following
Bram Moolenaar4f135272021-06-11 19:07:40 +02003054 (void)spell_casefold(curwin,
3055 su->su_badptr, stp->st_orglen, fword, MAXWLEN);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003056
3057 // When joining two words the sound often changes a lot. E.g., "t he"
3058 // sounds like "t h" while "the" sounds like "@". Avoid that by
3059 // removing the space. Don't do it when the good word also contains a
3060 // space.
3061 if (VIM_ISWHITE(su->su_badptr[su->su_badlen])
3062 && *skiptowhite(stp->st_word) == NUL)
3063 for (p = fword; *(p = skiptowhite(p)) != NUL; )
3064 STRMOVE(p, p + 1);
3065
3066 spell_soundfold(slang, fword, TRUE, badsound2);
3067 pbad = badsound2;
3068 }
3069
3070 if (lendiff > 0 && stp->st_wordlen + lendiff < MAXWLEN)
3071 {
3072 // Add part of the bad word to the good word, so that we soundfold
3073 // what replaces the bad word.
3074 STRCPY(goodword, stp->st_word);
3075 vim_strncpy(goodword + stp->st_wordlen,
3076 su->su_badptr + su->su_badlen - lendiff, lendiff);
3077 pgood = goodword;
3078 }
3079 else
3080 pgood = stp->st_word;
3081
3082 // Sound-fold the word and compute the score for the difference.
3083 spell_soundfold(slang, pgood, FALSE, goodsound);
3084
3085 return soundalike_score(goodsound, pbad);
3086}
3087
3088// structure used to store soundfolded words that add_sound_suggest() has
3089// handled already.
3090typedef struct
3091{
3092 short sft_score; // lowest score used
3093 char_u sft_word[1]; // soundfolded word, actually longer
3094} sftword_T;
3095
3096static sftword_T dumsft;
kylo252ae6f1d82022-02-16 19:24:07 +00003097#define HIKEY2SFT(p) ((sftword_T *)((p) - (dumsft.sft_word - (char_u *)&dumsft)))
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003098#define HI2SFT(hi) HIKEY2SFT((hi)->hi_key)
3099
3100/*
3101 * Prepare for calling suggest_try_soundalike().
3102 */
3103 static void
3104suggest_try_soundalike_prep(void)
3105{
3106 langp_T *lp;
3107 int lpi;
3108 slang_T *slang;
3109
3110 // Do this for all languages that support sound folding and for which a
3111 // .sug file has been loaded.
3112 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
3113 {
3114 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
3115 slang = lp->lp_slang;
3116 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
3117 // prepare the hashtable used by add_sound_suggest()
3118 hash_init(&slang->sl_sounddone);
3119 }
3120}
3121
3122/*
3123 * Find suggestions by comparing the word in a sound-a-like form.
3124 * Note: This doesn't support postponed prefixes.
3125 */
3126 static void
3127suggest_try_soundalike(suginfo_T *su)
3128{
3129 char_u salword[MAXWLEN];
3130 langp_T *lp;
3131 int lpi;
3132 slang_T *slang;
3133
3134 // Do this for all languages that support sound folding and for which a
3135 // .sug file has been loaded.
3136 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
3137 {
3138 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
3139 slang = lp->lp_slang;
3140 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
3141 {
3142 // soundfold the bad word
3143 spell_soundfold(slang, su->su_fbadword, TRUE, salword);
3144
3145 // try all kinds of inserts/deletes/swaps/etc.
3146 // TODO: also soundfold the next words, so that we can try joining
3147 // and splitting
3148#ifdef SUGGEST_PROFILE
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003149 prof_init();
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003150#endif
3151 suggest_trie_walk(su, lp, salword, TRUE);
3152#ifdef SUGGEST_PROFILE
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003153 prof_report("soundalike");
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003154#endif
3155 }
3156 }
3157}
3158
3159/*
3160 * Finish up after calling suggest_try_soundalike().
3161 */
3162 static void
3163suggest_try_soundalike_finish(void)
3164{
3165 langp_T *lp;
3166 int lpi;
3167 slang_T *slang;
3168 int todo;
3169 hashitem_T *hi;
3170
3171 // Do this for all languages that support sound folding and for which a
3172 // .sug file has been loaded.
3173 for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
3174 {
3175 lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
3176 slang = lp->lp_slang;
3177 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
3178 {
3179 // Free the info about handled words.
3180 todo = (int)slang->sl_sounddone.ht_used;
Yegappan Lakshmanan14113fd2023-03-07 17:13:51 +00003181 FOR_ALL_HASHTAB_ITEMS(&slang->sl_sounddone, hi, todo)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003182 if (!HASHITEM_EMPTY(hi))
3183 {
3184 vim_free(HI2SFT(hi));
3185 --todo;
3186 }
3187
3188 // Clear the hashtable, it may also be used by another region.
3189 hash_clear(&slang->sl_sounddone);
3190 hash_init(&slang->sl_sounddone);
3191 }
3192 }
3193}
3194
3195/*
3196 * A match with a soundfolded word is found. Add the good word(s) that
3197 * produce this soundfolded word.
3198 */
3199 static void
3200add_sound_suggest(
3201 suginfo_T *su,
3202 char_u *goodword,
3203 int score, // soundfold score
3204 langp_T *lp)
3205{
3206 slang_T *slang = lp->lp_slang; // language for sound folding
3207 int sfwordnr;
3208 char_u *nrline;
3209 int orgnr;
3210 char_u theword[MAXWLEN];
3211 int i;
3212 int wlen;
3213 char_u *byts;
3214 idx_T *idxs;
3215 int n;
3216 int wordcount;
3217 int wc;
3218 int goodscore;
3219 hash_T hash;
3220 hashitem_T *hi;
3221 sftword_T *sft;
3222 int bc, gc;
3223 int limit;
3224
3225 // It's very well possible that the same soundfold word is found several
3226 // times with different scores. Since the following is quite slow only do
3227 // the words that have a better score than before. Use a hashtable to
3228 // remember the words that have been done.
3229 hash = hash_hash(goodword);
3230 hi = hash_lookup(&slang->sl_sounddone, goodword, hash);
3231 if (HASHITEM_EMPTY(hi))
3232 {
zeertzjq1b438a82023-02-01 13:11:15 +00003233 sft = alloc(offsetof(sftword_T, sft_word) + STRLEN(goodword) + 1);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003234 if (sft != NULL)
3235 {
3236 sft->sft_score = score;
3237 STRCPY(sft->sft_word, goodword);
3238 hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash);
3239 }
3240 }
3241 else
3242 {
3243 sft = HI2SFT(hi);
3244 if (score >= sft->sft_score)
3245 return;
3246 sft->sft_score = score;
3247 }
3248
3249 // Find the word nr in the soundfold tree.
3250 sfwordnr = soundfold_find(slang, goodword);
3251 if (sfwordnr < 0)
3252 {
3253 internal_error("add_sound_suggest()");
3254 return;
3255 }
3256
3257 // go over the list of good words that produce this soundfold word
3258 nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)(sfwordnr + 1), FALSE);
3259 orgnr = 0;
3260 while (*nrline != NUL)
3261 {
3262 // The wordnr was stored in a minimal nr of bytes as an offset to the
3263 // previous wordnr.
3264 orgnr += bytes2offset(&nrline);
3265
3266 byts = slang->sl_fbyts;
3267 idxs = slang->sl_fidxs;
3268
3269 // Lookup the word "orgnr" one of the two tries.
3270 n = 0;
3271 wordcount = 0;
3272 for (wlen = 0; wlen < MAXWLEN - 3; ++wlen)
3273 {
3274 i = 1;
3275 if (wordcount == orgnr && byts[n + 1] == NUL)
3276 break; // found end of word
3277
3278 if (byts[n + 1] == NUL)
3279 ++wordcount;
3280
3281 // skip over the NUL bytes
3282 for ( ; byts[n + i] == NUL; ++i)
3283 if (i > byts[n]) // safety check
3284 {
3285 STRCPY(theword + wlen, "BAD");
3286 wlen += 3;
3287 goto badword;
3288 }
3289
3290 // One of the siblings must have the word.
3291 for ( ; i < byts[n]; ++i)
3292 {
3293 wc = idxs[idxs[n + i]]; // nr of words under this byte
3294 if (wordcount + wc > orgnr)
3295 break;
3296 wordcount += wc;
3297 }
3298
3299 theword[wlen] = byts[n + i];
3300 n = idxs[n + i];
3301 }
3302badword:
3303 theword[wlen] = NUL;
3304
3305 // Go over the possible flags and regions.
3306 for (; i <= byts[n] && byts[n + i] == NUL; ++i)
3307 {
3308 char_u cword[MAXWLEN];
3309 char_u *p;
3310 int flags = (int)idxs[n + i];
3311
3312 // Skip words with the NOSUGGEST flag
3313 if (flags & WF_NOSUGGEST)
3314 continue;
3315
3316 if (flags & WF_KEEPCAP)
3317 {
3318 // Must find the word in the keep-case tree.
3319 find_keepcap_word(slang, theword, cword);
3320 p = cword;
3321 }
3322 else
3323 {
3324 flags |= su->su_badflags;
3325 if ((flags & WF_CAPMASK) != 0)
3326 {
3327 // Need to fix case according to "flags".
3328 make_case_word(theword, cword, flags);
3329 p = cword;
3330 }
3331 else
3332 p = theword;
3333 }
3334
3335 // Add the suggestion.
3336 if (sps_flags & SPS_DOUBLE)
3337 {
3338 // Add the suggestion if the score isn't too bad.
3339 if (score <= su->su_maxscore)
3340 add_suggestion(su, &su->su_sga, p, su->su_badlen,
3341 score, 0, FALSE, slang, FALSE);
3342 }
3343 else
3344 {
3345 // Add a penalty for words in another region.
3346 if ((flags & WF_REGION)
3347 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
3348 goodscore = SCORE_REGION;
3349 else
3350 goodscore = 0;
3351
3352 // Add a small penalty for changing the first letter from
3353 // lower to upper case. Helps for "tath" -> "Kath", which is
3354 // less common than "tath" -> "path". Don't do it when the
3355 // letter is the same, that has already been counted.
3356 gc = PTR2CHAR(p);
3357 if (SPELL_ISUPPER(gc))
3358 {
3359 bc = PTR2CHAR(su->su_badword);
3360 if (!SPELL_ISUPPER(bc)
3361 && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc))
3362 goodscore += SCORE_ICASE / 2;
3363 }
3364
3365 // Compute the score for the good word. This only does letter
3366 // insert/delete/swap/replace. REP items are not considered,
3367 // which may make the score a bit higher.
3368 // Use a limit for the score to make it work faster. Use
3369 // MAXSCORE(), because RESCORE() will change the score.
3370 // If the limit is very high then the iterative method is
3371 // inefficient, using an array is quicker.
3372 limit = MAXSCORE(su->su_sfmaxscore - goodscore, score);
3373 if (limit > SCORE_LIMITMAX)
3374 goodscore += spell_edit_score(slang, su->su_badword, p);
3375 else
3376 goodscore += spell_edit_score_limit(slang, su->su_badword,
3377 p, limit);
3378
3379 // When going over the limit don't bother to do the rest.
3380 if (goodscore < SCORE_MAXMAX)
3381 {
3382 // Give a bonus to words seen before.
3383 goodscore = score_wordcount_adj(slang, goodscore, p, FALSE);
3384
3385 // Add the suggestion if the score isn't too bad.
3386 goodscore = RESCORE(goodscore, score);
3387 if (goodscore <= su->su_sfmaxscore)
3388 add_suggestion(su, &su->su_ga, p, su->su_badlen,
3389 goodscore, score, TRUE, slang, TRUE);
3390 }
3391 }
3392 }
3393 // smsg("word %s (%d): %s (%d)", sftword, sftnr, theword, orgnr);
3394 }
3395}
3396
3397/*
3398 * Find word "word" in fold-case tree for "slang" and return the word number.
3399 */
3400 static int
3401soundfold_find(slang_T *slang, char_u *word)
3402{
3403 idx_T arridx = 0;
3404 int len;
3405 int wlen = 0;
3406 int c;
3407 char_u *ptr = word;
3408 char_u *byts;
3409 idx_T *idxs;
3410 int wordnr = 0;
3411
3412 byts = slang->sl_sbyts;
3413 idxs = slang->sl_sidxs;
3414
3415 for (;;)
3416 {
3417 // First byte is the number of possible bytes.
3418 len = byts[arridx++];
3419
3420 // If the first possible byte is a zero the word could end here.
3421 // If the word ends we found the word. If not skip the NUL bytes.
3422 c = ptr[wlen];
3423 if (byts[arridx] == NUL)
3424 {
3425 if (c == NUL)
3426 break;
3427
3428 // Skip over the zeros, there can be several.
3429 while (len > 0 && byts[arridx] == NUL)
3430 {
3431 ++arridx;
3432 --len;
3433 }
3434 if (len == 0)
3435 return -1; // no children, word should have ended here
3436 ++wordnr;
3437 }
3438
3439 // If the word ends we didn't find it.
3440 if (c == NUL)
3441 return -1;
3442
3443 // Perform a binary search in the list of accepted bytes.
3444 if (c == TAB) // <Tab> is handled like <Space>
3445 c = ' ';
3446 while (byts[arridx] < c)
3447 {
3448 // The word count is in the first idxs[] entry of the child.
3449 wordnr += idxs[idxs[arridx]];
3450 ++arridx;
3451 if (--len == 0) // end of the bytes, didn't find it
3452 return -1;
3453 }
3454 if (byts[arridx] != c) // didn't find the byte
3455 return -1;
3456
3457 // Continue at the child (if there is one).
3458 arridx = idxs[arridx];
3459 ++wlen;
3460
3461 // One space in the good word may stand for several spaces in the
3462 // checked word.
3463 if (c == ' ')
3464 while (ptr[wlen] == ' ' || ptr[wlen] == TAB)
3465 ++wlen;
3466 }
3467
3468 return wordnr;
3469}
3470
3471/*
3472 * Return TRUE if "c1" and "c2" are similar characters according to the MAP
3473 * lines in the .aff file.
3474 */
3475 static int
3476similar_chars(slang_T *slang, int c1, int c2)
3477{
3478 int m1, m2;
3479 char_u buf[MB_MAXBYTES + 1];
3480 hashitem_T *hi;
3481
3482 if (c1 >= 256)
3483 {
3484 buf[mb_char2bytes(c1, buf)] = 0;
3485 hi = hash_find(&slang->sl_map_hash, buf);
3486 if (HASHITEM_EMPTY(hi))
3487 m1 = 0;
3488 else
3489 m1 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
3490 }
3491 else
3492 m1 = slang->sl_map_array[c1];
3493 if (m1 == 0)
3494 return FALSE;
3495
3496
3497 if (c2 >= 256)
3498 {
3499 buf[mb_char2bytes(c2, buf)] = 0;
3500 hi = hash_find(&slang->sl_map_hash, buf);
3501 if (HASHITEM_EMPTY(hi))
3502 m2 = 0;
3503 else
3504 m2 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
3505 }
3506 else
3507 m2 = slang->sl_map_array[c2];
3508
3509 return m1 == m2;
3510}
3511
3512/*
3513 * Add a suggestion to the list of suggestions.
3514 * For a suggestion that is already in the list the lowest score is remembered.
3515 */
3516 static void
3517add_suggestion(
3518 suginfo_T *su,
3519 garray_T *gap, // either su_ga or su_sga
3520 char_u *goodword,
3521 int badlenarg, // len of bad word replaced with "goodword"
3522 int score,
3523 int altscore,
3524 int had_bonus, // value for st_had_bonus
3525 slang_T *slang, // language for sound folding
3526 int maxsf) // su_maxscore applies to soundfold score,
3527 // su_sfmaxscore to the total score.
3528{
3529 int goodlen; // len of goodword changed
3530 int badlen; // len of bad word changed
3531 suggest_T *stp;
3532 suggest_T new_sug;
3533 int i;
3534 char_u *pgood, *pbad;
3535
3536 // Minimize "badlen" for consistency. Avoids that changing "the the" to
3537 // "thee the" is added next to changing the first "the" the "thee".
3538 pgood = goodword + STRLEN(goodword);
3539 pbad = su->su_badptr + badlenarg;
3540 for (;;)
3541 {
3542 goodlen = (int)(pgood - goodword);
3543 badlen = (int)(pbad - su->su_badptr);
3544 if (goodlen <= 0 || badlen <= 0)
3545 break;
3546 MB_PTR_BACK(goodword, pgood);
3547 MB_PTR_BACK(su->su_badptr, pbad);
3548 if (has_mbyte)
3549 {
3550 if (mb_ptr2char(pgood) != mb_ptr2char(pbad))
3551 break;
3552 }
3553 else if (*pgood != *pbad)
3554 break;
3555 }
3556
3557 if (badlen == 0 && goodlen == 0)
3558 // goodword doesn't change anything; may happen for "the the" changing
3559 // the first "the" to itself.
3560 return;
3561
3562 if (gap->ga_len == 0)
3563 i = -1;
3564 else
3565 {
3566 // Check if the word is already there. Also check the length that is
3567 // being replaced "thes," -> "these" is a different suggestion from
3568 // "thes" -> "these".
3569 stp = &SUG(*gap, 0);
3570 for (i = gap->ga_len; --i >= 0; ++stp)
3571 if (stp->st_wordlen == goodlen
3572 && stp->st_orglen == badlen
3573 && STRNCMP(stp->st_word, goodword, goodlen) == 0)
3574 {
3575 // Found it. Remember the word with the lowest score.
3576 if (stp->st_slang == NULL)
3577 stp->st_slang = slang;
3578
3579 new_sug.st_score = score;
3580 new_sug.st_altscore = altscore;
3581 new_sug.st_had_bonus = had_bonus;
3582
3583 if (stp->st_had_bonus != had_bonus)
3584 {
3585 // Only one of the two had the soundalike score computed.
3586 // Need to do that for the other one now, otherwise the
3587 // scores can't be compared. This happens because
3588 // suggest_try_change() doesn't compute the soundalike
3589 // word to keep it fast, while some special methods set
3590 // the soundalike score to zero.
3591 if (had_bonus)
3592 rescore_one(su, stp);
3593 else
3594 {
3595 new_sug.st_word = stp->st_word;
3596 new_sug.st_wordlen = stp->st_wordlen;
3597 new_sug.st_slang = stp->st_slang;
3598 new_sug.st_orglen = badlen;
3599 rescore_one(su, &new_sug);
3600 }
3601 }
3602
3603 if (stp->st_score > new_sug.st_score)
3604 {
3605 stp->st_score = new_sug.st_score;
3606 stp->st_altscore = new_sug.st_altscore;
3607 stp->st_had_bonus = new_sug.st_had_bonus;
3608 }
3609 break;
3610 }
3611 }
3612
3613 if (i < 0 && ga_grow(gap, 1) == OK)
3614 {
3615 // Add a suggestion.
3616 stp = &SUG(*gap, gap->ga_len);
3617 stp->st_word = vim_strnsave(goodword, goodlen);
3618 if (stp->st_word != NULL)
3619 {
3620 stp->st_wordlen = goodlen;
3621 stp->st_score = score;
3622 stp->st_altscore = altscore;
3623 stp->st_had_bonus = had_bonus;
3624 stp->st_orglen = badlen;
3625 stp->st_slang = slang;
3626 ++gap->ga_len;
3627
3628 // If we have too many suggestions now, sort the list and keep
3629 // the best suggestions.
3630 if (gap->ga_len > SUG_MAX_COUNT(su))
3631 {
3632 if (maxsf)
3633 su->su_sfmaxscore = cleanup_suggestions(gap,
3634 su->su_sfmaxscore, SUG_CLEAN_COUNT(su));
3635 else
3636 su->su_maxscore = cleanup_suggestions(gap,
3637 su->su_maxscore, SUG_CLEAN_COUNT(su));
3638 }
3639 }
3640 }
3641}
3642
3643/*
3644 * Suggestions may in fact be flagged as errors. Esp. for banned words and
3645 * for split words, such as "the the". Remove these from the list here.
3646 */
3647 static void
3648check_suggestions(
3649 suginfo_T *su,
3650 garray_T *gap) // either su_ga or su_sga
3651{
3652 suggest_T *stp;
3653 int i;
3654 char_u longword[MAXWLEN + 1];
3655 int len;
3656 hlf_T attr;
3657
Bram Moolenaar9c2b0662020-09-01 19:56:15 +02003658 if (gap->ga_len == 0)
3659 return;
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003660 stp = &SUG(*gap, 0);
3661 for (i = gap->ga_len - 1; i >= 0; --i)
3662 {
3663 // Need to append what follows to check for "the the".
3664 vim_strncpy(longword, stp[i].st_word, MAXWLEN);
3665 len = stp[i].st_wordlen;
3666 vim_strncpy(longword + len, su->su_badptr + stp[i].st_orglen,
3667 MAXWLEN - len);
3668 attr = HLF_COUNT;
3669 (void)spell_check(curwin, longword, &attr, NULL, FALSE);
3670 if (attr != HLF_COUNT)
3671 {
3672 // Remove this entry.
3673 vim_free(stp[i].st_word);
3674 --gap->ga_len;
3675 if (i < gap->ga_len)
3676 mch_memmove(stp + i, stp + i + 1,
3677 sizeof(suggest_T) * (gap->ga_len - i));
3678 }
3679 }
3680}
3681
3682
3683/*
3684 * Add a word to be banned.
3685 */
3686 static void
3687add_banned(
3688 suginfo_T *su,
3689 char_u *word)
3690{
3691 char_u *s;
3692 hash_T hash;
3693 hashitem_T *hi;
3694
3695 hash = hash_hash(word);
3696 hi = hash_lookup(&su->su_banned, word, hash);
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003697 if (!HASHITEM_EMPTY(hi)) // already present
3698 return;
3699 s = vim_strsave(word);
3700 if (s != NULL)
3701 hash_add_item(&su->su_banned, hi, s, hash);
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003702}
3703
3704/*
3705 * Recompute the score for all suggestions if sound-folding is possible. This
3706 * is slow, thus only done for the final results.
3707 */
3708 static void
3709rescore_suggestions(suginfo_T *su)
3710{
3711 int i;
3712
3713 if (su->su_sallang != NULL)
3714 for (i = 0; i < su->su_ga.ga_len; ++i)
3715 rescore_one(su, &SUG(su->su_ga, i));
3716}
3717
3718/*
3719 * Recompute the score for one suggestion if sound-folding is possible.
3720 */
3721 static void
3722rescore_one(suginfo_T *su, suggest_T *stp)
3723{
3724 slang_T *slang = stp->st_slang;
3725 char_u sal_badword[MAXWLEN];
3726 char_u *p;
3727
3728 // Only rescore suggestions that have no sal score yet and do have a
3729 // language.
3730 if (slang != NULL && slang->sl_sal.ga_len > 0 && !stp->st_had_bonus)
3731 {
3732 if (slang == su->su_sallang)
3733 p = su->su_sal_badword;
3734 else
3735 {
3736 spell_soundfold(slang, su->su_fbadword, TRUE, sal_badword);
3737 p = sal_badword;
3738 }
3739
3740 stp->st_altscore = stp_sal_score(stp, su, slang, p);
3741 if (stp->st_altscore == SCORE_MAXMAX)
3742 stp->st_altscore = SCORE_BIG;
3743 stp->st_score = RESCORE(stp->st_score, stp->st_altscore);
3744 stp->st_had_bonus = TRUE;
3745 }
3746}
3747
3748static int sug_compare(const void *s1, const void *s2);
3749
3750/*
3751 * Function given to qsort() to sort the suggestions on st_score.
3752 * First on "st_score", then "st_altscore" then alphabetically.
3753 */
3754 static int
3755sug_compare(const void *s1, const void *s2)
3756{
3757 suggest_T *p1 = (suggest_T *)s1;
3758 suggest_T *p2 = (suggest_T *)s2;
3759 int n = p1->st_score - p2->st_score;
3760
3761 if (n == 0)
3762 {
3763 n = p1->st_altscore - p2->st_altscore;
3764 if (n == 0)
3765 n = STRICMP(p1->st_word, p2->st_word);
3766 }
3767 return n;
3768}
3769
3770/*
3771 * Cleanup the suggestions:
3772 * - Sort on score.
3773 * - Remove words that won't be displayed.
3774 * Returns the maximum score in the list or "maxscore" unmodified.
3775 */
3776 static int
3777cleanup_suggestions(
3778 garray_T *gap,
3779 int maxscore,
3780 int keep) // nr of suggestions to keep
3781{
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003782 if (gap->ga_len <= 0)
3783 return maxscore;
3784
3785 // Sort the list.
3786 qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T),
3787 sug_compare);
3788
3789 // Truncate the list to the number of suggestions that will be
3790 // displayed.
3791 if (gap->ga_len > keep)
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003792 {
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003793 int i;
3794 suggest_T *stp = &SUG(*gap, 0);
Bram Moolenaarbb65a562020-03-15 18:15:03 +01003795
Yegappan Lakshmanan6ec66662023-01-23 20:46:21 +00003796 for (i = keep; i < gap->ga_len; ++i)
3797 vim_free(stp[i].st_word);
3798 gap->ga_len = keep;
3799 if (keep >= 1)
3800 return stp[keep - 1].st_score;
Bram Moolenaar46a426c2019-09-27 12:41:56 +02003801 }
3802 return maxscore;
3803}
3804
3805/*
3806 * Compute a score for two sound-a-like words.
3807 * This permits up to two inserts/deletes/swaps/etc. to keep things fast.
3808 * Instead of a generic loop we write out the code. That keeps it fast by
3809 * avoiding checks that will not be possible.
3810 */
3811 static int
3812soundalike_score(
3813 char_u *goodstart, // sound-folded good word
3814 char_u *badstart) // sound-folded bad word
3815{
3816 char_u *goodsound = goodstart;
3817 char_u *badsound = badstart;
3818 int goodlen;
3819 int badlen;
3820 int n;
3821 char_u *pl, *ps;
3822 char_u *pl2, *ps2;
3823 int score = 0;
3824
3825 // Adding/inserting "*" at the start (word starts with vowel) shouldn't be
3826 // counted so much, vowels halfway the word aren't counted at all.
3827 if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound)
3828 {
3829 if ((badsound[0] == NUL && goodsound[1] == NUL)
3830 || (goodsound[0] == NUL && badsound[1] == NUL))
3831 // changing word with vowel to word without a sound
3832 return SCORE_DEL;
3833 if (badsound[0] == NUL || goodsound[0] == NUL)
3834 // more than two changes
3835 return SCORE_MAXMAX;
3836
3837 if (badsound[1] == goodsound[1]
3838 || (badsound[1] != NUL
3839 && goodsound[1] != NUL
3840 && badsound[2] == goodsound[2]))
3841 {
3842 // handle like a substitute
3843 }
3844 else
3845 {
3846 score = 2 * SCORE_DEL / 3;
3847 if (*badsound == '*')
3848 ++badsound;
3849 else
3850 ++goodsound;
3851 }
3852 }
3853
3854 goodlen = (int)STRLEN(goodsound);
3855 badlen = (int)STRLEN(badsound);
3856
3857 // Return quickly if the lengths are too different to be fixed by two
3858 // changes.
3859 n = goodlen - badlen;
3860 if (n < -2 || n > 2)
3861 return SCORE_MAXMAX;
3862
3863 if (n > 0)
3864 {
3865 pl = goodsound; // goodsound is longest
3866 ps = badsound;
3867 }
3868 else
3869 {
3870 pl = badsound; // badsound is longest
3871 ps = goodsound;
3872 }
3873
3874 // Skip over the identical part.
3875 while (*pl == *ps && *pl != NUL)
3876 {
3877 ++pl;
3878 ++ps;
3879 }
3880
3881 switch (n)
3882 {
3883 case -2:
3884 case 2:
3885 // Must delete two characters from "pl".
3886 ++pl; // first delete
3887 while (*pl == *ps)
3888 {
3889 ++pl;
3890 ++ps;
3891 }
3892 // strings must be equal after second delete
3893 if (STRCMP(pl + 1, ps) == 0)
3894 return score + SCORE_DEL * 2;
3895
3896 // Failed to compare.
3897 break;
3898
3899 case -1:
3900 case 1:
3901 // Minimal one delete from "pl" required.
3902
3903 // 1: delete
3904 pl2 = pl + 1;
3905 ps2 = ps;
3906 while (*pl2 == *ps2)
3907 {
3908 if (*pl2 == NUL) // reached the end
3909 return score + SCORE_DEL;
3910 ++pl2;
3911 ++ps2;
3912 }
3913
3914 // 2: delete then swap, then rest must be equal
3915 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3916 && STRCMP(pl2 + 2, ps2 + 2) == 0)
3917 return score + SCORE_DEL + SCORE_SWAP;
3918
3919 // 3: delete then substitute, then the rest must be equal
3920 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
3921 return score + SCORE_DEL + SCORE_SUBST;
3922
3923 // 4: first swap then delete
3924 if (pl[0] == ps[1] && pl[1] == ps[0])
3925 {
3926 pl2 = pl + 2; // swap, skip two chars
3927 ps2 = ps + 2;
3928 while (*pl2 == *ps2)
3929 {
3930 ++pl2;
3931 ++ps2;
3932 }
3933 // delete a char and then strings must be equal
3934 if (STRCMP(pl2 + 1, ps2) == 0)
3935 return score + SCORE_SWAP + SCORE_DEL;
3936 }
3937
3938 // 5: first substitute then delete
3939 pl2 = pl + 1; // substitute, skip one char
3940 ps2 = ps + 1;
3941 while (*pl2 == *ps2)
3942 {
3943 ++pl2;
3944 ++ps2;
3945 }
3946 // delete a char and then strings must be equal
3947 if (STRCMP(pl2 + 1, ps2) == 0)
3948 return score + SCORE_SUBST + SCORE_DEL;
3949
3950 // Failed to compare.
3951 break;
3952
3953 case 0:
3954 // Lengths are equal, thus changes must result in same length: An
3955 // insert is only possible in combination with a delete.
3956 // 1: check if for identical strings
3957 if (*pl == NUL)
3958 return score;
3959
3960 // 2: swap
3961 if (pl[0] == ps[1] && pl[1] == ps[0])
3962 {
3963 pl2 = pl + 2; // swap, skip two chars
3964 ps2 = ps + 2;
3965 while (*pl2 == *ps2)
3966 {
3967 if (*pl2 == NUL) // reached the end
3968 return score + SCORE_SWAP;
3969 ++pl2;
3970 ++ps2;
3971 }
3972 // 3: swap and swap again
3973 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3974 && STRCMP(pl2 + 2, ps2 + 2) == 0)
3975 return score + SCORE_SWAP + SCORE_SWAP;
3976
3977 // 4: swap and substitute
3978 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
3979 return score + SCORE_SWAP + SCORE_SUBST;
3980 }
3981
3982 // 5: substitute
3983 pl2 = pl + 1;
3984 ps2 = ps + 1;
3985 while (*pl2 == *ps2)
3986 {
3987 if (*pl2 == NUL) // reached the end
3988 return score + SCORE_SUBST;
3989 ++pl2;
3990 ++ps2;
3991 }
3992
3993 // 6: substitute and swap
3994 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
3995 && STRCMP(pl2 + 2, ps2 + 2) == 0)
3996 return score + SCORE_SUBST + SCORE_SWAP;
3997
3998 // 7: substitute and substitute
3999 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
4000 return score + SCORE_SUBST + SCORE_SUBST;
4001
4002 // 8: insert then delete
4003 pl2 = pl;
4004 ps2 = ps + 1;
4005 while (*pl2 == *ps2)
4006 {
4007 ++pl2;
4008 ++ps2;
4009 }
4010 if (STRCMP(pl2 + 1, ps2) == 0)
4011 return score + SCORE_INS + SCORE_DEL;
4012
4013 // 9: delete then insert
4014 pl2 = pl + 1;
4015 ps2 = ps;
4016 while (*pl2 == *ps2)
4017 {
4018 ++pl2;
4019 ++ps2;
4020 }
4021 if (STRCMP(pl2, ps2 + 1) == 0)
4022 return score + SCORE_INS + SCORE_DEL;
4023
4024 // Failed to compare.
4025 break;
4026 }
4027
4028 return SCORE_MAXMAX;
4029}
4030
4031/*
4032 * Compute the "edit distance" to turn "badword" into "goodword". The less
4033 * deletes/inserts/substitutes/swaps are required the lower the score.
4034 *
4035 * The algorithm is described by Du and Chang, 1992.
4036 * The implementation of the algorithm comes from Aspell editdist.cpp,
4037 * edit_distance(). It has been converted from C++ to C and modified to
4038 * support multi-byte characters.
4039 */
4040 static int
4041spell_edit_score(
4042 slang_T *slang,
4043 char_u *badword,
4044 char_u *goodword)
4045{
4046 int *cnt;
4047 int badlen, goodlen; // lengths including NUL
4048 int j, i;
4049 int t;
4050 int bc, gc;
4051 int pbc, pgc;
4052 char_u *p;
4053 int wbadword[MAXWLEN];
4054 int wgoodword[MAXWLEN];
4055
4056 if (has_mbyte)
4057 {
4058 // Get the characters from the multi-byte strings and put them in an
4059 // int array for easy access.
4060 for (p = badword, badlen = 0; *p != NUL; )
4061 wbadword[badlen++] = mb_cptr2char_adv(&p);
4062 wbadword[badlen++] = 0;
4063 for (p = goodword, goodlen = 0; *p != NUL; )
4064 wgoodword[goodlen++] = mb_cptr2char_adv(&p);
4065 wgoodword[goodlen++] = 0;
4066 }
4067 else
4068 {
4069 badlen = (int)STRLEN(badword) + 1;
4070 goodlen = (int)STRLEN(goodword) + 1;
4071 }
4072
4073 // We use "cnt" as an array: CNT(badword_idx, goodword_idx).
4074#define CNT(a, b) cnt[(a) + (b) * (badlen + 1)]
4075 cnt = ALLOC_MULT(int, (badlen + 1) * (goodlen + 1));
4076 if (cnt == NULL)
4077 return 0; // out of memory
4078
4079 CNT(0, 0) = 0;
4080 for (j = 1; j <= goodlen; ++j)
4081 CNT(0, j) = CNT(0, j - 1) + SCORE_INS;
4082
4083 for (i = 1; i <= badlen; ++i)
4084 {
4085 CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL;
4086 for (j = 1; j <= goodlen; ++j)
4087 {
4088 if (has_mbyte)
4089 {
4090 bc = wbadword[i - 1];
4091 gc = wgoodword[j - 1];
4092 }
4093 else
4094 {
4095 bc = badword[i - 1];
4096 gc = goodword[j - 1];
4097 }
4098 if (bc == gc)
4099 CNT(i, j) = CNT(i - 1, j - 1);
4100 else
4101 {
4102 // Use a better score when there is only a case difference.
4103 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
4104 CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1);
4105 else
4106 {
4107 // For a similar character use SCORE_SIMILAR.
4108 if (slang != NULL
4109 && slang->sl_has_map
4110 && similar_chars(slang, gc, bc))
4111 CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1);
4112 else
4113 CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1);
4114 }
4115
4116 if (i > 1 && j > 1)
4117 {
4118 if (has_mbyte)
4119 {
4120 pbc = wbadword[i - 2];
4121 pgc = wgoodword[j - 2];
4122 }
4123 else
4124 {
4125 pbc = badword[i - 2];
4126 pgc = goodword[j - 2];
4127 }
4128 if (bc == pgc && pbc == gc)
4129 {
4130 t = SCORE_SWAP + CNT(i - 2, j - 2);
4131 if (t < CNT(i, j))
4132 CNT(i, j) = t;
4133 }
4134 }
4135 t = SCORE_DEL + CNT(i - 1, j);
4136 if (t < CNT(i, j))
4137 CNT(i, j) = t;
4138 t = SCORE_INS + CNT(i, j - 1);
4139 if (t < CNT(i, j))
4140 CNT(i, j) = t;
4141 }
4142 }
4143 }
4144
4145 i = CNT(badlen - 1, goodlen - 1);
4146 vim_free(cnt);
4147 return i;
4148}
4149
4150typedef struct
4151{
4152 int badi;
4153 int goodi;
4154 int score;
4155} limitscore_T;
4156
4157/*
4158 * Like spell_edit_score(), but with a limit on the score to make it faster.
4159 * May return SCORE_MAXMAX when the score is higher than "limit".
4160 *
4161 * This uses a stack for the edits still to be tried.
4162 * The idea comes from Aspell leditdist.cpp. Rewritten in C and added support
4163 * for multi-byte characters.
4164 */
4165 static int
4166spell_edit_score_limit(
4167 slang_T *slang,
4168 char_u *badword,
4169 char_u *goodword,
4170 int limit)
4171{
4172 limitscore_T stack[10]; // allow for over 3 * 2 edits
4173 int stackidx;
4174 int bi, gi;
4175 int bi2, gi2;
4176 int bc, gc;
4177 int score;
4178 int score_off;
4179 int minscore;
4180 int round;
4181
4182 // Multi-byte characters require a bit more work, use a different function
4183 // to avoid testing "has_mbyte" quite often.
4184 if (has_mbyte)
4185 return spell_edit_score_limit_w(slang, badword, goodword, limit);
4186
4187 // The idea is to go from start to end over the words. So long as
4188 // characters are equal just continue, this always gives the lowest score.
4189 // When there is a difference try several alternatives. Each alternative
4190 // increases "score" for the edit distance. Some of the alternatives are
4191 // pushed unto a stack and tried later, some are tried right away. At the
4192 // end of the word the score for one alternative is known. The lowest
4193 // possible score is stored in "minscore".
4194 stackidx = 0;
4195 bi = 0;
4196 gi = 0;
4197 score = 0;
4198 minscore = limit + 1;
4199
4200 for (;;)
4201 {
4202 // Skip over an equal part, score remains the same.
4203 for (;;)
4204 {
4205 bc = badword[bi];
4206 gc = goodword[gi];
4207 if (bc != gc) // stop at a char that's different
4208 break;
4209 if (bc == NUL) // both words end
4210 {
4211 if (score < minscore)
4212 minscore = score;
4213 goto pop; // do next alternative
4214 }
4215 ++bi;
4216 ++gi;
4217 }
4218
4219 if (gc == NUL) // goodword ends, delete badword chars
4220 {
4221 do
4222 {
4223 if ((score += SCORE_DEL) >= minscore)
4224 goto pop; // do next alternative
4225 } while (badword[++bi] != NUL);
4226 minscore = score;
4227 }
4228 else if (bc == NUL) // badword ends, insert badword chars
4229 {
4230 do
4231 {
4232 if ((score += SCORE_INS) >= minscore)
4233 goto pop; // do next alternative
4234 } while (goodword[++gi] != NUL);
4235 minscore = score;
4236 }
4237 else // both words continue
4238 {
4239 // If not close to the limit, perform a change. Only try changes
4240 // that may lead to a lower score than "minscore".
4241 // round 0: try deleting a char from badword
4242 // round 1: try inserting a char in badword
4243 for (round = 0; round <= 1; ++round)
4244 {
4245 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
4246 if (score_off < minscore)
4247 {
4248 if (score_off + SCORE_EDIT_MIN >= minscore)
4249 {
4250 // Near the limit, rest of the words must match. We
4251 // can check that right now, no need to push an item
4252 // onto the stack.
4253 bi2 = bi + 1 - round;
4254 gi2 = gi + round;
4255 while (goodword[gi2] == badword[bi2])
4256 {
4257 if (goodword[gi2] == NUL)
4258 {
4259 minscore = score_off;
4260 break;
4261 }
4262 ++bi2;
4263 ++gi2;
4264 }
4265 }
4266 else
4267 {
4268 // try deleting/inserting a character later
4269 stack[stackidx].badi = bi + 1 - round;
4270 stack[stackidx].goodi = gi + round;
4271 stack[stackidx].score = score_off;
4272 ++stackidx;
4273 }
4274 }
4275 }
4276
4277 if (score + SCORE_SWAP < minscore)
4278 {
4279 // If swapping two characters makes a match then the
4280 // substitution is more expensive, thus there is no need to
4281 // try both.
4282 if (gc == badword[bi + 1] && bc == goodword[gi + 1])
4283 {
4284 // Swap two characters, that is: skip them.
4285 gi += 2;
4286 bi += 2;
4287 score += SCORE_SWAP;
4288 continue;
4289 }
4290 }
4291
4292 // Substitute one character for another which is the same
4293 // thing as deleting a character from both goodword and badword.
4294 // Use a better score when there is only a case difference.
4295 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
4296 score += SCORE_ICASE;
4297 else
4298 {
4299 // For a similar character use SCORE_SIMILAR.
4300 if (slang != NULL
4301 && slang->sl_has_map
4302 && similar_chars(slang, gc, bc))
4303 score += SCORE_SIMILAR;
4304 else
4305 score += SCORE_SUBST;
4306 }
4307
4308 if (score < minscore)
4309 {
4310 // Do the substitution.
4311 ++gi;
4312 ++bi;
4313 continue;
4314 }
4315 }
4316pop:
4317 // Get here to try the next alternative, pop it from the stack.
4318 if (stackidx == 0) // stack is empty, finished
4319 break;
4320
4321 // pop an item from the stack
4322 --stackidx;
4323 gi = stack[stackidx].goodi;
4324 bi = stack[stackidx].badi;
4325 score = stack[stackidx].score;
4326 }
4327
4328 // When the score goes over "limit" it may actually be much higher.
4329 // Return a very large number to avoid going below the limit when giving a
4330 // bonus.
4331 if (minscore > limit)
4332 return SCORE_MAXMAX;
4333 return minscore;
4334}
4335
4336/*
4337 * Multi-byte version of spell_edit_score_limit().
4338 * Keep it in sync with the above!
4339 */
4340 static int
4341spell_edit_score_limit_w(
4342 slang_T *slang,
4343 char_u *badword,
4344 char_u *goodword,
4345 int limit)
4346{
4347 limitscore_T stack[10]; // allow for over 3 * 2 edits
4348 int stackidx;
4349 int bi, gi;
4350 int bi2, gi2;
4351 int bc, gc;
4352 int score;
4353 int score_off;
4354 int minscore;
4355 int round;
4356 char_u *p;
4357 int wbadword[MAXWLEN];
4358 int wgoodword[MAXWLEN];
4359
4360 // Get the characters from the multi-byte strings and put them in an
4361 // int array for easy access.
4362 bi = 0;
4363 for (p = badword; *p != NUL; )
4364 wbadword[bi++] = mb_cptr2char_adv(&p);
4365 wbadword[bi++] = 0;
4366 gi = 0;
4367 for (p = goodword; *p != NUL; )
4368 wgoodword[gi++] = mb_cptr2char_adv(&p);
4369 wgoodword[gi++] = 0;
4370
4371 // The idea is to go from start to end over the words. So long as
4372 // characters are equal just continue, this always gives the lowest score.
4373 // When there is a difference try several alternatives. Each alternative
4374 // increases "score" for the edit distance. Some of the alternatives are
4375 // pushed unto a stack and tried later, some are tried right away. At the
4376 // end of the word the score for one alternative is known. The lowest
4377 // possible score is stored in "minscore".
4378 stackidx = 0;
4379 bi = 0;
4380 gi = 0;
4381 score = 0;
4382 minscore = limit + 1;
4383
4384 for (;;)
4385 {
4386 // Skip over an equal part, score remains the same.
4387 for (;;)
4388 {
4389 bc = wbadword[bi];
4390 gc = wgoodword[gi];
4391
4392 if (bc != gc) // stop at a char that's different
4393 break;
4394 if (bc == NUL) // both words end
4395 {
4396 if (score < minscore)
4397 minscore = score;
4398 goto pop; // do next alternative
4399 }
4400 ++bi;
4401 ++gi;
4402 }
4403
4404 if (gc == NUL) // goodword ends, delete badword chars
4405 {
4406 do
4407 {
4408 if ((score += SCORE_DEL) >= minscore)
4409 goto pop; // do next alternative
4410 } while (wbadword[++bi] != NUL);
4411 minscore = score;
4412 }
4413 else if (bc == NUL) // badword ends, insert badword chars
4414 {
4415 do
4416 {
4417 if ((score += SCORE_INS) >= minscore)
4418 goto pop; // do next alternative
4419 } while (wgoodword[++gi] != NUL);
4420 minscore = score;
4421 }
4422 else // both words continue
4423 {
4424 // If not close to the limit, perform a change. Only try changes
4425 // that may lead to a lower score than "minscore".
4426 // round 0: try deleting a char from badword
4427 // round 1: try inserting a char in badword
4428 for (round = 0; round <= 1; ++round)
4429 {
4430 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
4431 if (score_off < minscore)
4432 {
4433 if (score_off + SCORE_EDIT_MIN >= minscore)
4434 {
4435 // Near the limit, rest of the words must match. We
4436 // can check that right now, no need to push an item
4437 // onto the stack.
4438 bi2 = bi + 1 - round;
4439 gi2 = gi + round;
4440 while (wgoodword[gi2] == wbadword[bi2])
4441 {
4442 if (wgoodword[gi2] == NUL)
4443 {
4444 minscore = score_off;
4445 break;
4446 }
4447 ++bi2;
4448 ++gi2;
4449 }
4450 }
4451 else
4452 {
4453 // try deleting a character from badword later
4454 stack[stackidx].badi = bi + 1 - round;
4455 stack[stackidx].goodi = gi + round;
4456 stack[stackidx].score = score_off;
4457 ++stackidx;
4458 }
4459 }
4460 }
4461
4462 if (score + SCORE_SWAP < minscore)
4463 {
4464 // If swapping two characters makes a match then the
4465 // substitution is more expensive, thus there is no need to
4466 // try both.
4467 if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1])
4468 {
4469 // Swap two characters, that is: skip them.
4470 gi += 2;
4471 bi += 2;
4472 score += SCORE_SWAP;
4473 continue;
4474 }
4475 }
4476
4477 // Substitute one character for another which is the same
4478 // thing as deleting a character from both goodword and badword.
4479 // Use a better score when there is only a case difference.
4480 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
4481 score += SCORE_ICASE;
4482 else
4483 {
4484 // For a similar character use SCORE_SIMILAR.
4485 if (slang != NULL
4486 && slang->sl_has_map
4487 && similar_chars(slang, gc, bc))
4488 score += SCORE_SIMILAR;
4489 else
4490 score += SCORE_SUBST;
4491 }
4492
4493 if (score < minscore)
4494 {
4495 // Do the substitution.
4496 ++gi;
4497 ++bi;
4498 continue;
4499 }
4500 }
4501pop:
4502 // Get here to try the next alternative, pop it from the stack.
4503 if (stackidx == 0) // stack is empty, finished
4504 break;
4505
4506 // pop an item from the stack
4507 --stackidx;
4508 gi = stack[stackidx].goodi;
4509 bi = stack[stackidx].badi;
4510 score = stack[stackidx].score;
4511 }
4512
4513 // When the score goes over "limit" it may actually be much higher.
4514 // Return a very large number to avoid going below the limit when giving a
4515 // bonus.
4516 if (minscore > limit)
4517 return SCORE_MAXMAX;
4518 return minscore;
4519}
4520#endif // FEAT_SPELL