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