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