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