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