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