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