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