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