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