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