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