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