Merge branch 'vim-with-runtime' into feat/persistent-undo
[vim_extended.git] / src / spell.c
blobd346d08dd37c20cb82cdbb3748e15b91102cbd2c
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * spell.c: code for spell checking
13 * The spell checking mechanism uses a tree (aka trie). Each node in the tree
14 * has a list of bytes that can appear (siblings). For each byte there is a
15 * pointer to the node with the byte that follows in the word (child).
17 * A NUL byte is used where the word may end. The bytes are sorted, so that
18 * binary searching can be used and the NUL bytes are at the start. The
19 * number of possible bytes is stored before the list of bytes.
21 * The tree uses two arrays: "byts" stores the characters, "idxs" stores
22 * either the next index or flags. The tree starts at index 0. For example,
23 * to lookup "vi" this sequence is followed:
24 * i = 0
25 * len = byts[i]
26 * n = where "v" appears in byts[i + 1] to byts[i + len]
27 * i = idxs[n]
28 * len = byts[i]
29 * n = where "i" appears in byts[i + 1] to byts[i + len]
30 * i = idxs[n]
31 * len = byts[i]
32 * find that byts[i + 1] is 0, idxs[i + 1] has flags for "vi".
34 * There are two word trees: one with case-folded words and one with words in
35 * original case. The second one is only used for keep-case words and is
36 * usually small.
38 * There is one additional tree for when not all prefixes are applied when
39 * generating the .spl file. This tree stores all the possible prefixes, as
40 * if they were words. At each word (prefix) end the prefix nr is stored, the
41 * following word must support this prefix nr. And the condition nr is
42 * stored, used to lookup the condition that the word must match with.
44 * Thanks to Olaf Seibert for providing an example implementation of this tree
45 * and the compression mechanism.
46 * LZ trie ideas:
47 * http://www.irb.hr/hr/home/ristov/papers/RistovLZtrieRevision1.pdf
48 * More papers: http://www-igm.univ-mlv.fr/~laporte/publi_en.html
50 * Matching involves checking the caps type: Onecap ALLCAP KeepCap.
52 * Why doesn't Vim use aspell/ispell/myspell/etc.?
53 * See ":help develop-spell".
56 /* Use SPELL_PRINTTREE for debugging: dump the word tree after adding a word.
57 * Only use it for small word lists! */
58 #if 0
59 # define SPELL_PRINTTREE
60 #endif
62 /* Use DEBUG_TRIEWALK to print the changes made in suggest_trie_walk() for a
63 * specific word. */
64 #if 0
65 # define DEBUG_TRIEWALK
66 #endif
69 * Use this to adjust the score after finding suggestions, based on the
70 * suggested word sounding like the bad word. This is much faster than doing
71 * it for every possible suggestion.
72 * Disadvantage: When "the" is typed as "hte" it sounds quite different ("@"
73 * vs "ht") and goes down in the list.
74 * Used when 'spellsuggest' is set to "best".
76 #define RESCORE(word_score, sound_score) ((3 * word_score + sound_score) / 4)
79 * Do the opposite: based on a maximum end score and a known sound score,
80 * compute the maximum word score that can be used.
82 #define MAXSCORE(word_score, sound_score) ((4 * word_score - sound_score) / 3)
85 * Vim spell file format: <HEADER>
86 * <SECTIONS>
87 * <LWORDTREE>
88 * <KWORDTREE>
89 * <PREFIXTREE>
91 * <HEADER>: <fileID> <versionnr>
93 * <fileID> 8 bytes "VIMspell"
94 * <versionnr> 1 byte VIMSPELLVERSION
97 * Sections make it possible to add information to the .spl file without
98 * making it incompatible with previous versions. There are two kinds of
99 * sections:
100 * 1. Not essential for correct spell checking. E.g. for making suggestions.
101 * These are skipped when not supported.
102 * 2. Optional information, but essential for spell checking when present.
103 * E.g. conditions for affixes. When this section is present but not
104 * supported an error message is given.
106 * <SECTIONS>: <section> ... <sectionend>
108 * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
110 * <sectionID> 1 byte number from 0 to 254 identifying the section
112 * <sectionflags> 1 byte SNF_REQUIRED: this section is required for correct
113 * spell checking
115 * <sectionlen> 4 bytes length of section contents, MSB first
117 * <sectionend> 1 byte SN_END
120 * sectionID == SN_INFO: <infotext>
121 * <infotext> N bytes free format text with spell file info (version,
122 * website, etc)
124 * sectionID == SN_REGION: <regionname> ...
125 * <regionname> 2 bytes Up to 8 region names: ca, au, etc. Lower case.
126 * First <regionname> is region 1.
128 * sectionID == SN_CHARFLAGS: <charflagslen> <charflags>
129 * <folcharslen> <folchars>
130 * <charflagslen> 1 byte Number of bytes in <charflags> (should be 128).
131 * <charflags> N bytes List of flags (first one is for character 128):
132 * 0x01 word character CF_WORD
133 * 0x02 upper-case character CF_UPPER
134 * <folcharslen> 2 bytes Number of bytes in <folchars>.
135 * <folchars> N bytes Folded characters, first one is for character 128.
137 * sectionID == SN_MIDWORD: <midword>
138 * <midword> N bytes Characters that are word characters only when used
139 * in the middle of a word.
141 * sectionID == SN_PREFCOND: <prefcondcnt> <prefcond> ...
142 * <prefcondcnt> 2 bytes Number of <prefcond> items following.
143 * <prefcond> : <condlen> <condstr>
144 * <condlen> 1 byte Length of <condstr>.
145 * <condstr> N bytes Condition for the prefix.
147 * sectionID == SN_REP: <repcount> <rep> ...
148 * <repcount> 2 bytes number of <rep> items, MSB first.
149 * <rep> : <repfromlen> <repfrom> <reptolen> <repto>
150 * <repfromlen> 1 byte length of <repfrom>
151 * <repfrom> N bytes "from" part of replacement
152 * <reptolen> 1 byte length of <repto>
153 * <repto> N bytes "to" part of replacement
155 * sectionID == SN_REPSAL: <repcount> <rep> ...
156 * just like SN_REP but for soundfolded words
158 * sectionID == SN_SAL: <salflags> <salcount> <sal> ...
159 * <salflags> 1 byte flags for soundsalike conversion:
160 * SAL_F0LLOWUP
161 * SAL_COLLAPSE
162 * SAL_REM_ACCENTS
163 * <salcount> 2 bytes number of <sal> items following
164 * <sal> : <salfromlen> <salfrom> <saltolen> <salto>
165 * <salfromlen> 1 byte length of <salfrom>
166 * <salfrom> N bytes "from" part of soundsalike
167 * <saltolen> 1 byte length of <salto>
168 * <salto> N bytes "to" part of soundsalike
170 * sectionID == SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
171 * <sofofromlen> 2 bytes length of <sofofrom>
172 * <sofofrom> N bytes "from" part of soundfold
173 * <sofotolen> 2 bytes length of <sofoto>
174 * <sofoto> N bytes "to" part of soundfold
176 * sectionID == SN_SUGFILE: <timestamp>
177 * <timestamp> 8 bytes time in seconds that must match with .sug file
179 * sectionID == SN_NOSPLITSUGS: nothing
181 * sectionID == SN_WORDS: <word> ...
182 * <word> N bytes NUL terminated common word
184 * sectionID == SN_MAP: <mapstr>
185 * <mapstr> N bytes String with sequences of similar characters,
186 * separated by slashes.
188 * sectionID == SN_COMPOUND: <compmax> <compminlen> <compsylmax> <compoptions>
189 * <comppatcount> <comppattern> ... <compflags>
190 * <compmax> 1 byte Maximum nr of words in compound word.
191 * <compminlen> 1 byte Minimal word length for compounding.
192 * <compsylmax> 1 byte Maximum nr of syllables in compound word.
193 * <compoptions> 2 bytes COMP_ flags.
194 * <comppatcount> 2 bytes number of <comppattern> following
195 * <compflags> N bytes Flags from COMPOUNDRULE items, separated by
196 * slashes.
198 * <comppattern>: <comppatlen> <comppattext>
199 * <comppatlen> 1 byte length of <comppattext>
200 * <comppattext> N bytes end or begin chars from CHECKCOMPOUNDPATTERN
202 * sectionID == SN_NOBREAK: (empty, its presence is what matters)
204 * sectionID == SN_SYLLABLE: <syllable>
205 * <syllable> N bytes String from SYLLABLE item.
207 * <LWORDTREE>: <wordtree>
209 * <KWORDTREE>: <wordtree>
211 * <PREFIXTREE>: <wordtree>
214 * <wordtree>: <nodecount> <nodedata> ...
216 * <nodecount> 4 bytes Number of nodes following. MSB first.
218 * <nodedata>: <siblingcount> <sibling> ...
220 * <siblingcount> 1 byte Number of siblings in this node. The siblings
221 * follow in sorted order.
223 * <sibling>: <byte> [ <nodeidx> <xbyte>
224 * | <flags> [<flags2>] [<region>] [<affixID>]
225 * | [<pflags>] <affixID> <prefcondnr> ]
227 * <byte> 1 byte Byte value of the sibling. Special cases:
228 * BY_NOFLAGS: End of word without flags and for all
229 * regions.
230 * For PREFIXTREE <affixID> and
231 * <prefcondnr> follow.
232 * BY_FLAGS: End of word, <flags> follow.
233 * For PREFIXTREE <pflags>, <affixID>
234 * and <prefcondnr> follow.
235 * BY_FLAGS2: End of word, <flags> and <flags2>
236 * follow. Not used in PREFIXTREE.
237 * BY_INDEX: Child of sibling is shared, <nodeidx>
238 * and <xbyte> follow.
240 * <nodeidx> 3 bytes Index of child for this sibling, MSB first.
242 * <xbyte> 1 byte byte value of the sibling.
244 * <flags> 1 byte bitmask of:
245 * WF_ALLCAP word must have only capitals
246 * WF_ONECAP first char of word must be capital
247 * WF_KEEPCAP keep-case word
248 * WF_FIXCAP keep-case word, all caps not allowed
249 * WF_RARE rare word
250 * WF_BANNED bad word
251 * WF_REGION <region> follows
252 * WF_AFX <affixID> follows
254 * <flags2> 1 byte Bitmask of:
255 * WF_HAS_AFF >> 8 word includes affix
256 * WF_NEEDCOMP >> 8 word only valid in compound
257 * WF_NOSUGGEST >> 8 word not used for suggestions
258 * WF_COMPROOT >> 8 word already a compound
259 * WF_NOCOMPBEF >> 8 no compounding before this word
260 * WF_NOCOMPAFT >> 8 no compounding after this word
262 * <pflags> 1 byte bitmask of:
263 * WFP_RARE rare prefix
264 * WFP_NC non-combining prefix
265 * WFP_UP letter after prefix made upper case
267 * <region> 1 byte Bitmask for regions in which word is valid. When
268 * omitted it's valid in all regions.
269 * Lowest bit is for region 1.
271 * <affixID> 1 byte ID of affix that can be used with this word. In
272 * PREFIXTREE used for the required prefix ID.
274 * <prefcondnr> 2 bytes Prefix condition number, index in <prefcond> list
275 * from HEADER.
277 * All text characters are in 'encoding', but stored as single bytes.
281 * Vim .sug file format: <SUGHEADER>
282 * <SUGWORDTREE>
283 * <SUGTABLE>
285 * <SUGHEADER>: <fileID> <versionnr> <timestamp>
287 * <fileID> 6 bytes "VIMsug"
288 * <versionnr> 1 byte VIMSUGVERSION
289 * <timestamp> 8 bytes timestamp that must match with .spl file
292 * <SUGWORDTREE>: <wordtree> (see above, no flags or region used)
295 * <SUGTABLE>: <sugwcount> <sugline> ...
297 * <sugwcount> 4 bytes number of <sugline> following
299 * <sugline>: <sugnr> ... NUL
301 * <sugnr>: X bytes word number that results in this soundfolded word,
302 * stored as an offset to the previous number in as
303 * few bytes as possible, see offset2bytes())
306 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
307 # include "vimio.h" /* for lseek(), must be before vim.h */
308 #endif
310 #include "vim.h"
312 #if defined(FEAT_SPELL) || defined(PROTO)
314 #ifndef UNIX /* it's in os_unix.h for Unix */
315 # include <time.h> /* for time_t */
316 #endif
318 #define MAXWLEN 250 /* Assume max. word len is this many bytes.
319 Some places assume a word length fits in a
320 byte, thus it can't be above 255. */
322 /* Type used for indexes in the word tree need to be at least 4 bytes. If int
323 * is 8 bytes we could use something smaller, but what? */
324 #if SIZEOF_INT > 3
325 typedef int idx_T;
326 #else
327 typedef long idx_T;
328 #endif
330 /* Flags used for a word. Only the lowest byte can be used, the region byte
331 * comes above it. */
332 #define WF_REGION 0x01 /* region byte follows */
333 #define WF_ONECAP 0x02 /* word with one capital (or all capitals) */
334 #define WF_ALLCAP 0x04 /* word must be all capitals */
335 #define WF_RARE 0x08 /* rare word */
336 #define WF_BANNED 0x10 /* bad word */
337 #define WF_AFX 0x20 /* affix ID follows */
338 #define WF_FIXCAP 0x40 /* keep-case word, allcap not allowed */
339 #define WF_KEEPCAP 0x80 /* keep-case word */
341 /* for <flags2>, shifted up one byte to be used in wn_flags */
342 #define WF_HAS_AFF 0x0100 /* word includes affix */
343 #define WF_NEEDCOMP 0x0200 /* word only valid in compound */
344 #define WF_NOSUGGEST 0x0400 /* word not to be suggested */
345 #define WF_COMPROOT 0x0800 /* already compounded word, COMPOUNDROOT */
346 #define WF_NOCOMPBEF 0x1000 /* no compounding before this word */
347 #define WF_NOCOMPAFT 0x2000 /* no compounding after this word */
349 /* only used for su_badflags */
350 #define WF_MIXCAP 0x20 /* mix of upper and lower case: macaRONI */
352 #define WF_CAPMASK (WF_ONECAP | WF_ALLCAP | WF_KEEPCAP | WF_FIXCAP)
354 /* flags for <pflags> */
355 #define WFP_RARE 0x01 /* rare prefix */
356 #define WFP_NC 0x02 /* prefix is not combining */
357 #define WFP_UP 0x04 /* to-upper prefix */
358 #define WFP_COMPPERMIT 0x08 /* prefix with COMPOUNDPERMITFLAG */
359 #define WFP_COMPFORBID 0x10 /* prefix with COMPOUNDFORBIDFLAG */
361 /* Flags for postponed prefixes in "sl_pidxs". Must be above affixID (one
362 * byte) and prefcondnr (two bytes). */
363 #define WF_RAREPFX (WFP_RARE << 24) /* rare postponed prefix */
364 #define WF_PFX_NC (WFP_NC << 24) /* non-combining postponed prefix */
365 #define WF_PFX_UP (WFP_UP << 24) /* to-upper postponed prefix */
366 #define WF_PFX_COMPPERMIT (WFP_COMPPERMIT << 24) /* postponed prefix with
367 * COMPOUNDPERMITFLAG */
368 #define WF_PFX_COMPFORBID (WFP_COMPFORBID << 24) /* postponed prefix with
369 * COMPOUNDFORBIDFLAG */
372 /* flags for <compoptions> */
373 #define COMP_CHECKDUP 1 /* CHECKCOMPOUNDDUP */
374 #define COMP_CHECKREP 2 /* CHECKCOMPOUNDREP */
375 #define COMP_CHECKCASE 4 /* CHECKCOMPOUNDCASE */
376 #define COMP_CHECKTRIPLE 8 /* CHECKCOMPOUNDTRIPLE */
378 /* Special byte values for <byte>. Some are only used in the tree for
379 * postponed prefixes, some only in the other trees. This is a bit messy... */
380 #define BY_NOFLAGS 0 /* end of word without flags or region; for
381 * postponed prefix: no <pflags> */
382 #define BY_INDEX 1 /* child is shared, index follows */
383 #define BY_FLAGS 2 /* end of word, <flags> byte follows; for
384 * postponed prefix: <pflags> follows */
385 #define BY_FLAGS2 3 /* end of word, <flags> and <flags2> bytes
386 * follow; never used in prefix tree */
387 #define BY_SPECIAL BY_FLAGS2 /* highest special byte value */
389 /* Info from "REP", "REPSAL" and "SAL" entries in ".aff" file used in si_rep,
390 * si_repsal, sl_rep, and si_sal. Not for sl_sal!
391 * One replacement: from "ft_from" to "ft_to". */
392 typedef struct fromto_S
394 char_u *ft_from;
395 char_u *ft_to;
396 } fromto_T;
398 /* Info from "SAL" entries in ".aff" file used in sl_sal.
399 * The info is split for quick processing by spell_soundfold().
400 * Note that "sm_oneof" and "sm_rules" point into sm_lead. */
401 typedef struct salitem_S
403 char_u *sm_lead; /* leading letters */
404 int sm_leadlen; /* length of "sm_lead" */
405 char_u *sm_oneof; /* letters from () or NULL */
406 char_u *sm_rules; /* rules like ^, $, priority */
407 char_u *sm_to; /* replacement. */
408 #ifdef FEAT_MBYTE
409 int *sm_lead_w; /* wide character copy of "sm_lead" */
410 int *sm_oneof_w; /* wide character copy of "sm_oneof" */
411 int *sm_to_w; /* wide character copy of "sm_to" */
412 #endif
413 } salitem_T;
415 #ifdef FEAT_MBYTE
416 typedef int salfirst_T;
417 #else
418 typedef short salfirst_T;
419 #endif
421 /* Values for SP_*ERROR are negative, positive values are used by
422 * read_cnt_string(). */
423 #define SP_TRUNCERROR -1 /* spell file truncated error */
424 #define SP_FORMERROR -2 /* format error in spell file */
425 #define SP_OTHERERROR -3 /* other error while reading spell file */
428 * Structure used to store words and other info for one language, loaded from
429 * a .spl file.
430 * The main access is through the tree in "sl_fbyts/sl_fidxs", storing the
431 * case-folded words. "sl_kbyts/sl_kidxs" is for keep-case words.
433 * The "byts" array stores the possible bytes in each tree node, preceded by
434 * the number of possible bytes, sorted on byte value:
435 * <len> <byte1> <byte2> ...
436 * The "idxs" array stores the index of the child node corresponding to the
437 * byte in "byts".
438 * Exception: when the byte is zero, the word may end here and "idxs" holds
439 * the flags, region mask and affixID for the word. There may be several
440 * zeros in sequence for alternative flag/region/affixID combinations.
442 typedef struct slang_S slang_T;
443 struct slang_S
445 slang_T *sl_next; /* next language */
446 char_u *sl_name; /* language name "en", "en.rare", "nl", etc. */
447 char_u *sl_fname; /* name of .spl file */
448 int sl_add; /* TRUE if it's a .add file. */
450 char_u *sl_fbyts; /* case-folded word bytes */
451 idx_T *sl_fidxs; /* case-folded word indexes */
452 char_u *sl_kbyts; /* keep-case word bytes */
453 idx_T *sl_kidxs; /* keep-case word indexes */
454 char_u *sl_pbyts; /* prefix tree word bytes */
455 idx_T *sl_pidxs; /* prefix tree word indexes */
457 char_u *sl_info; /* infotext string or NULL */
459 char_u sl_regions[17]; /* table with up to 8 region names plus NUL */
461 char_u *sl_midword; /* MIDWORD string or NULL */
463 hashtab_T sl_wordcount; /* hashtable with word count, wordcount_T */
465 int sl_compmax; /* COMPOUNDWORDMAX (default: MAXWLEN) */
466 int sl_compminlen; /* COMPOUNDMIN (default: 0) */
467 int sl_compsylmax; /* COMPOUNDSYLMAX (default: MAXWLEN) */
468 int sl_compoptions; /* COMP_* flags */
469 garray_T sl_comppat; /* CHECKCOMPOUNDPATTERN items */
470 regprog_T *sl_compprog; /* COMPOUNDRULE turned into a regexp progrm
471 * (NULL when no compounding) */
472 char_u *sl_comprules; /* all COMPOUNDRULE concatenated (or NULL) */
473 char_u *sl_compstartflags; /* flags for first compound word */
474 char_u *sl_compallflags; /* all flags for compound words */
475 char_u sl_nobreak; /* When TRUE: no spaces between words */
476 char_u *sl_syllable; /* SYLLABLE repeatable chars or NULL */
477 garray_T sl_syl_items; /* syllable items */
479 int sl_prefixcnt; /* number of items in "sl_prefprog" */
480 regprog_T **sl_prefprog; /* table with regprogs for prefixes */
482 garray_T sl_rep; /* list of fromto_T entries from REP lines */
483 short sl_rep_first[256]; /* indexes where byte first appears, -1 if
484 there is none */
485 garray_T sl_sal; /* list of salitem_T entries from SAL lines */
486 salfirst_T sl_sal_first[256]; /* indexes where byte first appears, -1 if
487 there is none */
488 int sl_followup; /* SAL followup */
489 int sl_collapse; /* SAL collapse_result */
490 int sl_rem_accents; /* SAL remove_accents */
491 int sl_sofo; /* SOFOFROM and SOFOTO instead of SAL items:
492 * "sl_sal_first" maps chars, when has_mbyte
493 * "sl_sal" is a list of wide char lists. */
494 garray_T sl_repsal; /* list of fromto_T entries from REPSAL lines */
495 short sl_repsal_first[256]; /* sl_rep_first for REPSAL lines */
496 int sl_nosplitsugs; /* don't suggest splitting a word */
498 /* Info from the .sug file. Loaded on demand. */
499 time_t sl_sugtime; /* timestamp for .sug file */
500 char_u *sl_sbyts; /* soundfolded word bytes */
501 idx_T *sl_sidxs; /* soundfolded word indexes */
502 buf_T *sl_sugbuf; /* buffer with word number table */
503 int sl_sugloaded; /* TRUE when .sug file was loaded or failed to
504 load */
506 int sl_has_map; /* TRUE if there is a MAP line */
507 #ifdef FEAT_MBYTE
508 hashtab_T sl_map_hash; /* MAP for multi-byte chars */
509 int sl_map_array[256]; /* MAP for first 256 chars */
510 #else
511 char_u sl_map_array[256]; /* MAP for first 256 chars */
512 #endif
513 hashtab_T sl_sounddone; /* table with soundfolded words that have
514 handled, see add_sound_suggest() */
517 /* First language that is loaded, start of the linked list of loaded
518 * languages. */
519 static slang_T *first_lang = NULL;
521 /* Flags used in .spl file for soundsalike flags. */
522 #define SAL_F0LLOWUP 1
523 #define SAL_COLLAPSE 2
524 #define SAL_REM_ACCENTS 4
527 * Structure used in "b_langp", filled from 'spelllang'.
529 typedef struct langp_S
531 slang_T *lp_slang; /* info for this language */
532 slang_T *lp_sallang; /* language used for sound folding or NULL */
533 slang_T *lp_replang; /* language used for REP items or NULL */
534 int lp_region; /* bitmask for region or REGION_ALL */
535 } langp_T;
537 #define LANGP_ENTRY(ga, i) (((langp_T *)(ga).ga_data) + (i))
539 #define REGION_ALL 0xff /* word valid in all regions */
541 #define VIMSPELLMAGIC "VIMspell" /* string at start of Vim spell file */
542 #define VIMSPELLMAGICL 8
543 #define VIMSPELLVERSION 50
545 #define VIMSUGMAGIC "VIMsug" /* string at start of Vim .sug file */
546 #define VIMSUGMAGICL 6
547 #define VIMSUGVERSION 1
549 /* Section IDs. Only renumber them when VIMSPELLVERSION changes! */
550 #define SN_REGION 0 /* <regionname> section */
551 #define SN_CHARFLAGS 1 /* charflags section */
552 #define SN_MIDWORD 2 /* <midword> section */
553 #define SN_PREFCOND 3 /* <prefcond> section */
554 #define SN_REP 4 /* REP items section */
555 #define SN_SAL 5 /* SAL items section */
556 #define SN_SOFO 6 /* soundfolding section */
557 #define SN_MAP 7 /* MAP items section */
558 #define SN_COMPOUND 8 /* compound words section */
559 #define SN_SYLLABLE 9 /* syllable section */
560 #define SN_NOBREAK 10 /* NOBREAK section */
561 #define SN_SUGFILE 11 /* timestamp for .sug file */
562 #define SN_REPSAL 12 /* REPSAL items section */
563 #define SN_WORDS 13 /* common words */
564 #define SN_NOSPLITSUGS 14 /* don't split word for suggestions */
565 #define SN_INFO 15 /* info section */
566 #define SN_END 255 /* end of sections */
568 #define SNF_REQUIRED 1 /* <sectionflags>: required section */
570 /* Result values. Lower number is accepted over higher one. */
571 #define SP_BANNED -1
572 #define SP_OK 0
573 #define SP_RARE 1
574 #define SP_LOCAL 2
575 #define SP_BAD 3
577 /* file used for "zG" and "zW" */
578 static char_u *int_wordlist = NULL;
580 typedef struct wordcount_S
582 short_u wc_count; /* nr of times word was seen */
583 char_u wc_word[1]; /* word, actually longer */
584 } wordcount_T;
586 static wordcount_T dumwc;
587 #define WC_KEY_OFF (unsigned)(dumwc.wc_word - (char_u *)&dumwc)
588 #define HI2WC(hi) ((wordcount_T *)((hi)->hi_key - WC_KEY_OFF))
589 #define MAXWORDCOUNT 0xffff
592 * Information used when looking for suggestions.
594 typedef struct suginfo_S
596 garray_T su_ga; /* suggestions, contains "suggest_T" */
597 int su_maxcount; /* max. number of suggestions displayed */
598 int su_maxscore; /* maximum score for adding to su_ga */
599 int su_sfmaxscore; /* idem, for when doing soundfold words */
600 garray_T su_sga; /* like su_ga, sound-folded scoring */
601 char_u *su_badptr; /* start of bad word in line */
602 int su_badlen; /* length of detected bad word in line */
603 int su_badflags; /* caps flags for bad word */
604 char_u su_badword[MAXWLEN]; /* bad word truncated at su_badlen */
605 char_u su_fbadword[MAXWLEN]; /* su_badword case-folded */
606 char_u su_sal_badword[MAXWLEN]; /* su_badword soundfolded */
607 hashtab_T su_banned; /* table with banned words */
608 slang_T *su_sallang; /* default language for sound folding */
609 } suginfo_T;
611 /* One word suggestion. Used in "si_ga". */
612 typedef struct suggest_S
614 char_u *st_word; /* suggested word, allocated string */
615 int st_wordlen; /* STRLEN(st_word) */
616 int st_orglen; /* length of replaced text */
617 int st_score; /* lower is better */
618 int st_altscore; /* used when st_score compares equal */
619 int st_salscore; /* st_score is for soundalike */
620 int st_had_bonus; /* bonus already included in score */
621 slang_T *st_slang; /* language used for sound folding */
622 } suggest_T;
624 #define SUG(ga, i) (((suggest_T *)(ga).ga_data)[i])
626 /* TRUE if a word appears in the list of banned words. */
627 #define WAS_BANNED(su, word) (!HASHITEM_EMPTY(hash_find(&su->su_banned, word)))
629 /* Number of suggestions kept when cleaning up. We need to keep more than
630 * what is displayed, because when rescore_suggestions() is called the score
631 * may change and wrong suggestions may be removed later. */
632 #define SUG_CLEAN_COUNT(su) ((su)->su_maxcount < 130 ? 150 : (su)->su_maxcount + 20)
634 /* Threshold for sorting and cleaning up suggestions. Don't want to keep lots
635 * of suggestions that are not going to be displayed. */
636 #define SUG_MAX_COUNT(su) (SUG_CLEAN_COUNT(su) + 50)
638 /* score for various changes */
639 #define SCORE_SPLIT 149 /* split bad word */
640 #define SCORE_SPLIT_NO 249 /* split bad word with NOSPLITSUGS */
641 #define SCORE_ICASE 52 /* slightly different case */
642 #define SCORE_REGION 200 /* word is for different region */
643 #define SCORE_RARE 180 /* rare word */
644 #define SCORE_SWAP 75 /* swap two characters */
645 #define SCORE_SWAP3 110 /* swap two characters in three */
646 #define SCORE_REP 65 /* REP replacement */
647 #define SCORE_SUBST 93 /* substitute a character */
648 #define SCORE_SIMILAR 33 /* substitute a similar character */
649 #define SCORE_SUBCOMP 33 /* substitute a composing character */
650 #define SCORE_DEL 94 /* delete a character */
651 #define SCORE_DELDUP 66 /* delete a duplicated character */
652 #define SCORE_DELCOMP 28 /* delete a composing character */
653 #define SCORE_INS 96 /* insert a character */
654 #define SCORE_INSDUP 67 /* insert a duplicate character */
655 #define SCORE_INSCOMP 30 /* insert a composing character */
656 #define SCORE_NONWORD 103 /* change non-word to word char */
658 #define SCORE_FILE 30 /* suggestion from a file */
659 #define SCORE_MAXINIT 350 /* Initial maximum score: higher == slower.
660 * 350 allows for about three changes. */
662 #define SCORE_COMMON1 30 /* subtracted for words seen before */
663 #define SCORE_COMMON2 40 /* subtracted for words often seen */
664 #define SCORE_COMMON3 50 /* subtracted for words very often seen */
665 #define SCORE_THRES2 10 /* word count threshold for COMMON2 */
666 #define SCORE_THRES3 100 /* word count threshold for COMMON3 */
668 /* When trying changed soundfold words it becomes slow when trying more than
669 * two changes. With less then two changes it's slightly faster but we miss a
670 * few good suggestions. In rare cases we need to try three of four changes.
672 #define SCORE_SFMAX1 200 /* maximum score for first try */
673 #define SCORE_SFMAX2 300 /* maximum score for second try */
674 #define SCORE_SFMAX3 400 /* maximum score for third try */
676 #define SCORE_BIG SCORE_INS * 3 /* big difference */
677 #define SCORE_MAXMAX 999999 /* accept any score */
678 #define SCORE_LIMITMAX 350 /* for spell_edit_score_limit() */
680 /* for spell_edit_score_limit() we need to know the minimum value of
681 * SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS */
682 #define SCORE_EDIT_MIN SCORE_SIMILAR
685 * Structure to store info for word matching.
687 typedef struct matchinf_S
689 langp_T *mi_lp; /* info for language and region */
691 /* pointers to original text to be checked */
692 char_u *mi_word; /* start of word being checked */
693 char_u *mi_end; /* end of matching word so far */
694 char_u *mi_fend; /* next char to be added to mi_fword */
695 char_u *mi_cend; /* char after what was used for
696 mi_capflags */
698 /* case-folded text */
699 char_u mi_fword[MAXWLEN + 1]; /* mi_word case-folded */
700 int mi_fwordlen; /* nr of valid bytes in mi_fword */
702 /* for when checking word after a prefix */
703 int mi_prefarridx; /* index in sl_pidxs with list of
704 affixID/condition */
705 int mi_prefcnt; /* number of entries at mi_prefarridx */
706 int mi_prefixlen; /* byte length of prefix */
707 #ifdef FEAT_MBYTE
708 int mi_cprefixlen; /* byte length of prefix in original
709 case */
710 #else
711 # define mi_cprefixlen mi_prefixlen /* it's the same value */
712 #endif
714 /* for when checking a compound word */
715 int mi_compoff; /* start of following word offset */
716 char_u mi_compflags[MAXWLEN]; /* flags for compound words used */
717 int mi_complen; /* nr of compound words used */
718 int mi_compextra; /* nr of COMPOUNDROOT words */
720 /* others */
721 int mi_result; /* result so far: SP_BAD, SP_OK, etc. */
722 int mi_capflags; /* WF_ONECAP WF_ALLCAP WF_KEEPCAP */
723 buf_T *mi_buf; /* buffer being checked */
725 /* for NOBREAK */
726 int mi_result2; /* "mi_resul" without following word */
727 char_u *mi_end2; /* "mi_end" without following word */
728 } matchinf_T;
731 * The tables used for recognizing word characters according to spelling.
732 * These are only used for the first 256 characters of 'encoding'.
734 typedef struct spelltab_S
736 char_u st_isw[256]; /* flags: is word char */
737 char_u st_isu[256]; /* flags: is uppercase char */
738 char_u st_fold[256]; /* chars: folded case */
739 char_u st_upper[256]; /* chars: upper case */
740 } spelltab_T;
742 static spelltab_T spelltab;
743 static int did_set_spelltab;
745 #define CF_WORD 0x01
746 #define CF_UPPER 0x02
748 static void clear_spell_chartab __ARGS((spelltab_T *sp));
749 static int set_spell_finish __ARGS((spelltab_T *new_st));
750 static int spell_iswordp __ARGS((char_u *p, buf_T *buf));
751 static int spell_iswordp_nmw __ARGS((char_u *p));
752 #ifdef FEAT_MBYTE
753 static int spell_mb_isword_class __ARGS((int cl));
754 static int spell_iswordp_w __ARGS((int *p, buf_T *buf));
755 #endif
756 static int write_spell_prefcond __ARGS((FILE *fd, garray_T *gap));
759 * For finding suggestions: At each node in the tree these states are tried:
761 typedef enum
763 STATE_START = 0, /* At start of node check for NUL bytes (goodword
764 * ends); if badword ends there is a match, otherwise
765 * try splitting word. */
766 STATE_NOPREFIX, /* try without prefix */
767 STATE_SPLITUNDO, /* Undo splitting. */
768 STATE_ENDNUL, /* Past NUL bytes at start of the node. */
769 STATE_PLAIN, /* Use each byte of the node. */
770 STATE_DEL, /* Delete a byte from the bad word. */
771 STATE_INS_PREP, /* Prepare for inserting bytes. */
772 STATE_INS, /* Insert a byte in the bad word. */
773 STATE_SWAP, /* Swap two bytes. */
774 STATE_UNSWAP, /* Undo swap two characters. */
775 STATE_SWAP3, /* Swap two characters over three. */
776 STATE_UNSWAP3, /* Undo Swap two characters over three. */
777 STATE_UNROT3L, /* Undo rotate three characters left */
778 STATE_UNROT3R, /* Undo rotate three characters right */
779 STATE_REP_INI, /* Prepare for using REP items. */
780 STATE_REP, /* Use matching REP items from the .aff file. */
781 STATE_REP_UNDO, /* Undo a REP item replacement. */
782 STATE_FINAL /* End of this node. */
783 } state_T;
786 * Struct to keep the state at each level in suggest_try_change().
788 typedef struct trystate_S
790 state_T ts_state; /* state at this level, STATE_ */
791 int ts_score; /* score */
792 idx_T ts_arridx; /* index in tree array, start of node */
793 short ts_curi; /* index in list of child nodes */
794 char_u ts_fidx; /* index in fword[], case-folded bad word */
795 char_u ts_fidxtry; /* ts_fidx at which bytes may be changed */
796 char_u ts_twordlen; /* valid length of tword[] */
797 char_u ts_prefixdepth; /* stack depth for end of prefix or
798 * PFD_PREFIXTREE or PFD_NOPREFIX */
799 char_u ts_flags; /* TSF_ flags */
800 #ifdef FEAT_MBYTE
801 char_u ts_tcharlen; /* number of bytes in tword character */
802 char_u ts_tcharidx; /* current byte index in tword character */
803 char_u ts_isdiff; /* DIFF_ values */
804 char_u ts_fcharstart; /* index in fword where badword char started */
805 #endif
806 char_u ts_prewordlen; /* length of word in "preword[]" */
807 char_u ts_splitoff; /* index in "tword" after last split */
808 char_u ts_splitfidx; /* "ts_fidx" at word split */
809 char_u ts_complen; /* nr of compound words used */
810 char_u ts_compsplit; /* index for "compflags" where word was spit */
811 char_u ts_save_badflags; /* su_badflags saved here */
812 char_u ts_delidx; /* index in fword for char that was deleted,
813 valid when "ts_flags" has TSF_DIDDEL */
814 } trystate_T;
816 /* values for ts_isdiff */
817 #define DIFF_NONE 0 /* no different byte (yet) */
818 #define DIFF_YES 1 /* different byte found */
819 #define DIFF_INSERT 2 /* inserting character */
821 /* values for ts_flags */
822 #define TSF_PREFIXOK 1 /* already checked that prefix is OK */
823 #define TSF_DIDSPLIT 2 /* tried split at this point */
824 #define TSF_DIDDEL 4 /* did a delete, "ts_delidx" has index */
826 /* special values ts_prefixdepth */
827 #define PFD_NOPREFIX 0xff /* not using prefixes */
828 #define PFD_PREFIXTREE 0xfe /* walking through the prefix tree */
829 #define PFD_NOTSPECIAL 0xfd /* highest value that's not special */
831 /* mode values for find_word */
832 #define FIND_FOLDWORD 0 /* find word case-folded */
833 #define FIND_KEEPWORD 1 /* find keep-case word */
834 #define FIND_PREFIX 2 /* find word after prefix */
835 #define FIND_COMPOUND 3 /* find case-folded compound word */
836 #define FIND_KEEPCOMPOUND 4 /* find keep-case compound word */
838 static slang_T *slang_alloc __ARGS((char_u *lang));
839 static void slang_free __ARGS((slang_T *lp));
840 static void slang_clear __ARGS((slang_T *lp));
841 static void slang_clear_sug __ARGS((slang_T *lp));
842 static void find_word __ARGS((matchinf_T *mip, int mode));
843 static int match_checkcompoundpattern __ARGS((char_u *ptr, int wlen, garray_T *gap));
844 static int can_compound __ARGS((slang_T *slang, char_u *word, char_u *flags));
845 static int can_be_compound __ARGS((trystate_T *sp, slang_T *slang, char_u *compflags, int flag));
846 static int match_compoundrule __ARGS((slang_T *slang, char_u *compflags));
847 static int valid_word_prefix __ARGS((int totprefcnt, int arridx, int flags, char_u *word, slang_T *slang, int cond_req));
848 static void find_prefix __ARGS((matchinf_T *mip, int mode));
849 static int fold_more __ARGS((matchinf_T *mip));
850 static int spell_valid_case __ARGS((int wordflags, int treeflags));
851 static int no_spell_checking __ARGS((win_T *wp));
852 static void spell_load_lang __ARGS((char_u *lang));
853 static char_u *spell_enc __ARGS((void));
854 static void int_wordlist_spl __ARGS((char_u *fname));
855 static void spell_load_cb __ARGS((char_u *fname, void *cookie));
856 static slang_T *spell_load_file __ARGS((char_u *fname, char_u *lang, slang_T *old_lp, int silent));
857 static time_t get8c __ARGS((FILE *fd));
858 static char_u *read_cnt_string __ARGS((FILE *fd, int cnt_bytes, int *lenp));
859 static char_u *read_string __ARGS((FILE *fd, int cnt));
860 static int read_region_section __ARGS((FILE *fd, slang_T *slang, int len));
861 static int read_charflags_section __ARGS((FILE *fd));
862 static int read_prefcond_section __ARGS((FILE *fd, slang_T *lp));
863 static int read_rep_section __ARGS((FILE *fd, garray_T *gap, short *first));
864 static int read_sal_section __ARGS((FILE *fd, slang_T *slang));
865 static int read_words_section __ARGS((FILE *fd, slang_T *lp, int len));
866 static void count_common_word __ARGS((slang_T *lp, char_u *word, int len, int count));
867 static int score_wordcount_adj __ARGS((slang_T *slang, int score, char_u *word, int split));
868 static int read_sofo_section __ARGS((FILE *fd, slang_T *slang));
869 static int read_compound __ARGS((FILE *fd, slang_T *slang, int len));
870 static int byte_in_str __ARGS((char_u *str, int byte));
871 static int init_syl_tab __ARGS((slang_T *slang));
872 static int count_syllables __ARGS((slang_T *slang, char_u *word));
873 static int set_sofo __ARGS((slang_T *lp, char_u *from, char_u *to));
874 static void set_sal_first __ARGS((slang_T *lp));
875 #ifdef FEAT_MBYTE
876 static int *mb_str2wide __ARGS((char_u *s));
877 #endif
878 static int spell_read_tree __ARGS((FILE *fd, char_u **bytsp, idx_T **idxsp, int prefixtree, int prefixcnt));
879 static idx_T read_tree_node __ARGS((FILE *fd, char_u *byts, idx_T *idxs, int maxidx, int startidx, int prefixtree, int maxprefcondnr));
880 static void clear_midword __ARGS((buf_T *buf));
881 static void use_midword __ARGS((slang_T *lp, buf_T *buf));
882 static int find_region __ARGS((char_u *rp, char_u *region));
883 static int captype __ARGS((char_u *word, char_u *end));
884 static int badword_captype __ARGS((char_u *word, char_u *end));
885 static void spell_reload_one __ARGS((char_u *fname, int added_word));
886 static void set_spell_charflags __ARGS((char_u *flags, int cnt, char_u *upp));
887 static int set_spell_chartab __ARGS((char_u *fol, char_u *low, char_u *upp));
888 static int spell_casefold __ARGS((char_u *p, int len, char_u *buf, int buflen));
889 static int check_need_cap __ARGS((linenr_T lnum, colnr_T col));
890 static void spell_find_suggest __ARGS((char_u *badptr, int badlen, suginfo_T *su, int maxcount, int banbadword, int need_cap, int interactive));
891 #ifdef FEAT_EVAL
892 static void spell_suggest_expr __ARGS((suginfo_T *su, char_u *expr));
893 #endif
894 static void spell_suggest_file __ARGS((suginfo_T *su, char_u *fname));
895 static void spell_suggest_intern __ARGS((suginfo_T *su, int interactive));
896 static void suggest_load_files __ARGS((void));
897 static void tree_count_words __ARGS((char_u *byts, idx_T *idxs));
898 static void spell_find_cleanup __ARGS((suginfo_T *su));
899 static void onecap_copy __ARGS((char_u *word, char_u *wcopy, int upper));
900 static void allcap_copy __ARGS((char_u *word, char_u *wcopy));
901 static void suggest_try_special __ARGS((suginfo_T *su));
902 static void suggest_try_change __ARGS((suginfo_T *su));
903 static void suggest_trie_walk __ARGS((suginfo_T *su, langp_T *lp, char_u *fword, int soundfold));
904 static void go_deeper __ARGS((trystate_T *stack, int depth, int score_add));
905 #ifdef FEAT_MBYTE
906 static int nofold_len __ARGS((char_u *fword, int flen, char_u *word));
907 #endif
908 static void find_keepcap_word __ARGS((slang_T *slang, char_u *fword, char_u *kword));
909 static void score_comp_sal __ARGS((suginfo_T *su));
910 static void score_combine __ARGS((suginfo_T *su));
911 static int stp_sal_score __ARGS((suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *badsound));
912 static void suggest_try_soundalike_prep __ARGS((void));
913 static void suggest_try_soundalike __ARGS((suginfo_T *su));
914 static void suggest_try_soundalike_finish __ARGS((void));
915 static void add_sound_suggest __ARGS((suginfo_T *su, char_u *goodword, int score, langp_T *lp));
916 static int soundfold_find __ARGS((slang_T *slang, char_u *word));
917 static void make_case_word __ARGS((char_u *fword, char_u *cword, int flags));
918 static void set_map_str __ARGS((slang_T *lp, char_u *map));
919 static int similar_chars __ARGS((slang_T *slang, int c1, int c2));
920 static void add_suggestion __ARGS((suginfo_T *su, garray_T *gap, char_u *goodword, int badlen, int score, int altscore, int had_bonus, slang_T *slang, int maxsf));
921 static void check_suggestions __ARGS((suginfo_T *su, garray_T *gap));
922 static void add_banned __ARGS((suginfo_T *su, char_u *word));
923 static void rescore_suggestions __ARGS((suginfo_T *su));
924 static void rescore_one __ARGS((suginfo_T *su, suggest_T *stp));
925 static int cleanup_suggestions __ARGS((garray_T *gap, int maxscore, int keep));
926 static void spell_soundfold __ARGS((slang_T *slang, char_u *inword, int folded, char_u *res));
927 static void spell_soundfold_sofo __ARGS((slang_T *slang, char_u *inword, char_u *res));
928 static void spell_soundfold_sal __ARGS((slang_T *slang, char_u *inword, char_u *res));
929 #ifdef FEAT_MBYTE
930 static void spell_soundfold_wsal __ARGS((slang_T *slang, char_u *inword, char_u *res));
931 #endif
932 static int soundalike_score __ARGS((char_u *goodsound, char_u *badsound));
933 static int spell_edit_score __ARGS((slang_T *slang, char_u *badword, char_u *goodword));
934 static int spell_edit_score_limit __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit));
935 #ifdef FEAT_MBYTE
936 static int spell_edit_score_limit_w __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit));
937 #endif
938 static void dump_word __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T lnum));
939 static linenr_T dump_prefixes __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T startlnum));
940 static buf_T *open_spellbuf __ARGS((void));
941 static void close_spellbuf __ARGS((buf_T *buf));
944 * Use our own character-case definitions, because the current locale may
945 * differ from what the .spl file uses.
946 * These must not be called with negative number!
948 #ifndef FEAT_MBYTE
949 /* Non-multi-byte implementation. */
950 # define SPELL_TOFOLD(c) ((c) < 256 ? (int)spelltab.st_fold[c] : (c))
951 # define SPELL_TOUPPER(c) ((c) < 256 ? (int)spelltab.st_upper[c] : (c))
952 # define SPELL_ISUPPER(c) ((c) < 256 ? spelltab.st_isu[c] : FALSE)
953 #else
954 # if defined(HAVE_WCHAR_H)
955 # include <wchar.h> /* for towupper() and towlower() */
956 # endif
957 /* Multi-byte implementation. For Unicode we can call utf_*(), but don't do
958 * that for ASCII, because we don't want to use 'casemap' here. Otherwise use
959 * the "w" library function for characters above 255 if available. */
960 # ifdef HAVE_TOWLOWER
961 # define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \
962 : (c) < 256 ? (int)spelltab.st_fold[c] : (int)towlower(c))
963 # else
964 # define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \
965 : (c) < 256 ? (int)spelltab.st_fold[c] : (c))
966 # endif
968 # ifdef HAVE_TOWUPPER
969 # define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \
970 : (c) < 256 ? (int)spelltab.st_upper[c] : (int)towupper(c))
971 # else
972 # define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \
973 : (c) < 256 ? (int)spelltab.st_upper[c] : (c))
974 # endif
976 # ifdef HAVE_ISWUPPER
977 # define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \
978 : (c) < 256 ? spelltab.st_isu[c] : iswupper(c))
979 # else
980 # define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \
981 : (c) < 256 ? spelltab.st_isu[c] : (FALSE))
982 # endif
983 #endif
986 static char *e_format = N_("E759: Format error in spell file");
987 static char *e_spell_trunc = N_("E758: Truncated spell file");
988 static char *e_afftrailing = N_("Trailing text in %s line %d: %s");
989 static char *e_affname = N_("Affix name too long in %s line %d: %s");
990 static char *e_affform = N_("E761: Format error in affix file FOL, LOW or UPP");
991 static char *e_affrange = N_("E762: Character in FOL, LOW or UPP is out of range");
992 static char *msg_compressing = N_("Compressing word tree...");
994 /* Remember what "z?" replaced. */
995 static char_u *repl_from = NULL;
996 static char_u *repl_to = NULL;
999 * Main spell-checking function.
1000 * "ptr" points to a character that could be the start of a word.
1001 * "*attrp" is set to the highlight index for a badly spelled word. For a
1002 * non-word or when it's OK it remains unchanged.
1003 * This must only be called when 'spelllang' is not empty.
1005 * "capcol" is used to check for a Capitalised word after the end of a
1006 * sentence. If it's zero then perform the check. Return the column where to
1007 * check next, or -1 when no sentence end was found. If it's NULL then don't
1008 * worry.
1010 * Returns the length of the word in bytes, also when it's OK, so that the
1011 * caller can skip over the word.
1014 spell_check(wp, ptr, attrp, capcol, docount)
1015 win_T *wp; /* current window */
1016 char_u *ptr;
1017 hlf_T *attrp;
1018 int *capcol; /* column to check for Capital */
1019 int docount; /* count good words */
1021 matchinf_T mi; /* Most things are put in "mi" so that it can
1022 be passed to functions quickly. */
1023 int nrlen = 0; /* found a number first */
1024 int c;
1025 int wrongcaplen = 0;
1026 int lpi;
1027 int count_word = docount;
1029 /* A word never starts at a space or a control character. Return quickly
1030 * then, skipping over the character. */
1031 if (*ptr <= ' ')
1032 return 1;
1034 /* Return here when loading language files failed. */
1035 if (wp->w_buffer->b_langp.ga_len == 0)
1036 return 1;
1038 vim_memset(&mi, 0, sizeof(matchinf_T));
1040 /* A number is always OK. Also skip hexadecimal numbers 0xFF99 and
1041 * 0X99FF. But always do check spelling to find "3GPP" and "11
1042 * julifeest". */
1043 if (*ptr >= '0' && *ptr <= '9')
1045 if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X'))
1046 mi.mi_end = skiphex(ptr + 2);
1047 else
1048 mi.mi_end = skipdigits(ptr);
1049 nrlen = (int)(mi.mi_end - ptr);
1052 /* Find the normal end of the word (until the next non-word character). */
1053 mi.mi_word = ptr;
1054 mi.mi_fend = ptr;
1055 if (spell_iswordp(mi.mi_fend, wp->w_buffer))
1059 mb_ptr_adv(mi.mi_fend);
1060 } while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp->w_buffer));
1062 if (capcol != NULL && *capcol == 0 && wp->w_buffer->b_cap_prog != NULL)
1064 /* Check word starting with capital letter. */
1065 c = PTR2CHAR(ptr);
1066 if (!SPELL_ISUPPER(c))
1067 wrongcaplen = (int)(mi.mi_fend - ptr);
1070 if (capcol != NULL)
1071 *capcol = -1;
1073 /* We always use the characters up to the next non-word character,
1074 * also for bad words. */
1075 mi.mi_end = mi.mi_fend;
1077 /* Check caps type later. */
1078 mi.mi_buf = wp->w_buffer;
1080 /* case-fold the word with one non-word character, so that we can check
1081 * for the word end. */
1082 if (*mi.mi_fend != NUL)
1083 mb_ptr_adv(mi.mi_fend);
1085 (void)spell_casefold(ptr, (int)(mi.mi_fend - ptr), mi.mi_fword,
1086 MAXWLEN + 1);
1087 mi.mi_fwordlen = (int)STRLEN(mi.mi_fword);
1089 /* The word is bad unless we recognize it. */
1090 mi.mi_result = SP_BAD;
1091 mi.mi_result2 = SP_BAD;
1094 * Loop over the languages specified in 'spelllang'.
1095 * We check them all, because a word may be matched longer in another
1096 * language.
1098 for (lpi = 0; lpi < wp->w_buffer->b_langp.ga_len; ++lpi)
1100 mi.mi_lp = LANGP_ENTRY(wp->w_buffer->b_langp, lpi);
1102 /* If reloading fails the language is still in the list but everything
1103 * has been cleared. */
1104 if (mi.mi_lp->lp_slang->sl_fidxs == NULL)
1105 continue;
1107 /* Check for a matching word in case-folded words. */
1108 find_word(&mi, FIND_FOLDWORD);
1110 /* Check for a matching word in keep-case words. */
1111 find_word(&mi, FIND_KEEPWORD);
1113 /* Check for matching prefixes. */
1114 find_prefix(&mi, FIND_FOLDWORD);
1116 /* For a NOBREAK language, may want to use a word without a following
1117 * word as a backup. */
1118 if (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD
1119 && mi.mi_result2 != SP_BAD)
1121 mi.mi_result = mi.mi_result2;
1122 mi.mi_end = mi.mi_end2;
1125 /* Count the word in the first language where it's found to be OK. */
1126 if (count_word && mi.mi_result == SP_OK)
1128 count_common_word(mi.mi_lp->lp_slang, ptr,
1129 (int)(mi.mi_end - ptr), 1);
1130 count_word = FALSE;
1134 if (mi.mi_result != SP_OK)
1136 /* If we found a number skip over it. Allows for "42nd". Do flag
1137 * rare and local words, e.g., "3GPP". */
1138 if (nrlen > 0)
1140 if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)
1141 return nrlen;
1144 /* When we are at a non-word character there is no error, just
1145 * skip over the character (try looking for a word after it). */
1146 else if (!spell_iswordp_nmw(ptr))
1148 if (capcol != NULL && wp->w_buffer->b_cap_prog != NULL)
1150 regmatch_T regmatch;
1152 /* Check for end of sentence. */
1153 regmatch.regprog = wp->w_buffer->b_cap_prog;
1154 regmatch.rm_ic = FALSE;
1155 if (vim_regexec(&regmatch, ptr, 0))
1156 *capcol = (int)(regmatch.endp[0] - ptr);
1159 #ifdef FEAT_MBYTE
1160 if (has_mbyte)
1161 return (*mb_ptr2len)(ptr);
1162 #endif
1163 return 1;
1165 else if (mi.mi_end == ptr)
1166 /* Always include at least one character. Required for when there
1167 * is a mixup in "midword". */
1168 mb_ptr_adv(mi.mi_end);
1169 else if (mi.mi_result == SP_BAD
1170 && LANGP_ENTRY(wp->w_buffer->b_langp, 0)->lp_slang->sl_nobreak)
1172 char_u *p, *fp;
1173 int save_result = mi.mi_result;
1175 /* First language in 'spelllang' is NOBREAK. Find first position
1176 * at which any word would be valid. */
1177 mi.mi_lp = LANGP_ENTRY(wp->w_buffer->b_langp, 0);
1178 if (mi.mi_lp->lp_slang->sl_fidxs != NULL)
1180 p = mi.mi_word;
1181 fp = mi.mi_fword;
1182 for (;;)
1184 mb_ptr_adv(p);
1185 mb_ptr_adv(fp);
1186 if (p >= mi.mi_end)
1187 break;
1188 mi.mi_compoff = (int)(fp - mi.mi_fword);
1189 find_word(&mi, FIND_COMPOUND);
1190 if (mi.mi_result != SP_BAD)
1192 mi.mi_end = p;
1193 break;
1196 mi.mi_result = save_result;
1200 if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)
1201 *attrp = HLF_SPB;
1202 else if (mi.mi_result == SP_RARE)
1203 *attrp = HLF_SPR;
1204 else
1205 *attrp = HLF_SPL;
1208 if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE))
1210 /* Report SpellCap only when the word isn't badly spelled. */
1211 *attrp = HLF_SPC;
1212 return wrongcaplen;
1215 return (int)(mi.mi_end - ptr);
1219 * Check if the word at "mip->mi_word" is in the tree.
1220 * When "mode" is FIND_FOLDWORD check in fold-case word tree.
1221 * When "mode" is FIND_KEEPWORD check in keep-case word tree.
1222 * When "mode" is FIND_PREFIX check for word after prefix in fold-case word
1223 * tree.
1225 * For a match mip->mi_result is updated.
1227 static void
1228 find_word(mip, mode)
1229 matchinf_T *mip;
1230 int mode;
1232 idx_T arridx = 0;
1233 int endlen[MAXWLEN]; /* length at possible word endings */
1234 idx_T endidx[MAXWLEN]; /* possible word endings */
1235 int endidxcnt = 0;
1236 int len;
1237 int wlen = 0;
1238 int flen;
1239 int c;
1240 char_u *ptr;
1241 idx_T lo, hi, m;
1242 #ifdef FEAT_MBYTE
1243 char_u *s;
1244 #endif
1245 char_u *p;
1246 int res = SP_BAD;
1247 slang_T *slang = mip->mi_lp->lp_slang;
1248 unsigned flags;
1249 char_u *byts;
1250 idx_T *idxs;
1251 int word_ends;
1252 int prefix_found;
1253 int nobreak_result;
1255 if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND)
1257 /* Check for word with matching case in keep-case tree. */
1258 ptr = mip->mi_word;
1259 flen = 9999; /* no case folding, always enough bytes */
1260 byts = slang->sl_kbyts;
1261 idxs = slang->sl_kidxs;
1263 if (mode == FIND_KEEPCOMPOUND)
1264 /* Skip over the previously found word(s). */
1265 wlen += mip->mi_compoff;
1267 else
1269 /* Check for case-folded in case-folded tree. */
1270 ptr = mip->mi_fword;
1271 flen = mip->mi_fwordlen; /* available case-folded bytes */
1272 byts = slang->sl_fbyts;
1273 idxs = slang->sl_fidxs;
1275 if (mode == FIND_PREFIX)
1277 /* Skip over the prefix. */
1278 wlen = mip->mi_prefixlen;
1279 flen -= mip->mi_prefixlen;
1281 else if (mode == FIND_COMPOUND)
1283 /* Skip over the previously found word(s). */
1284 wlen = mip->mi_compoff;
1285 flen -= mip->mi_compoff;
1290 if (byts == NULL)
1291 return; /* array is empty */
1294 * Repeat advancing in the tree until:
1295 * - there is a byte that doesn't match,
1296 * - we reach the end of the tree,
1297 * - or we reach the end of the line.
1299 for (;;)
1301 if (flen <= 0 && *mip->mi_fend != NUL)
1302 flen = fold_more(mip);
1304 len = byts[arridx++];
1306 /* If the first possible byte is a zero the word could end here.
1307 * Remember this index, we first check for the longest word. */
1308 if (byts[arridx] == 0)
1310 if (endidxcnt == MAXWLEN)
1312 /* Must be a corrupted spell file. */
1313 EMSG(_(e_format));
1314 return;
1316 endlen[endidxcnt] = wlen;
1317 endidx[endidxcnt++] = arridx++;
1318 --len;
1320 /* Skip over the zeros, there can be several flag/region
1321 * combinations. */
1322 while (len > 0 && byts[arridx] == 0)
1324 ++arridx;
1325 --len;
1327 if (len == 0)
1328 break; /* no children, word must end here */
1331 /* Stop looking at end of the line. */
1332 if (ptr[wlen] == NUL)
1333 break;
1335 /* Perform a binary search in the list of accepted bytes. */
1336 c = ptr[wlen];
1337 if (c == TAB) /* <Tab> is handled like <Space> */
1338 c = ' ';
1339 lo = arridx;
1340 hi = arridx + len - 1;
1341 while (lo < hi)
1343 m = (lo + hi) / 2;
1344 if (byts[m] > c)
1345 hi = m - 1;
1346 else if (byts[m] < c)
1347 lo = m + 1;
1348 else
1350 lo = hi = m;
1351 break;
1355 /* Stop if there is no matching byte. */
1356 if (hi < lo || byts[lo] != c)
1357 break;
1359 /* Continue at the child (if there is one). */
1360 arridx = idxs[lo];
1361 ++wlen;
1362 --flen;
1364 /* One space in the good word may stand for several spaces in the
1365 * checked word. */
1366 if (c == ' ')
1368 for (;;)
1370 if (flen <= 0 && *mip->mi_fend != NUL)
1371 flen = fold_more(mip);
1372 if (ptr[wlen] != ' ' && ptr[wlen] != TAB)
1373 break;
1374 ++wlen;
1375 --flen;
1381 * Verify that one of the possible endings is valid. Try the longest
1382 * first.
1384 while (endidxcnt > 0)
1386 --endidxcnt;
1387 arridx = endidx[endidxcnt];
1388 wlen = endlen[endidxcnt];
1390 #ifdef FEAT_MBYTE
1391 if ((*mb_head_off)(ptr, ptr + wlen) > 0)
1392 continue; /* not at first byte of character */
1393 #endif
1394 if (spell_iswordp(ptr + wlen, mip->mi_buf))
1396 if (slang->sl_compprog == NULL && !slang->sl_nobreak)
1397 continue; /* next char is a word character */
1398 word_ends = FALSE;
1400 else
1401 word_ends = TRUE;
1402 /* The prefix flag is before compound flags. Once a valid prefix flag
1403 * has been found we try compound flags. */
1404 prefix_found = FALSE;
1406 #ifdef FEAT_MBYTE
1407 if (mode != FIND_KEEPWORD && has_mbyte)
1409 /* Compute byte length in original word, length may change
1410 * when folding case. This can be slow, take a shortcut when the
1411 * case-folded word is equal to the keep-case word. */
1412 p = mip->mi_word;
1413 if (STRNCMP(ptr, p, wlen) != 0)
1415 for (s = ptr; s < ptr + wlen; mb_ptr_adv(s))
1416 mb_ptr_adv(p);
1417 wlen = (int)(p - mip->mi_word);
1420 #endif
1422 /* Check flags and region. For FIND_PREFIX check the condition and
1423 * prefix ID.
1424 * Repeat this if there are more flags/region alternatives until there
1425 * is a match. */
1426 res = SP_BAD;
1427 for (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0;
1428 --len, ++arridx)
1430 flags = idxs[arridx];
1432 /* For the fold-case tree check that the case of the checked word
1433 * matches with what the word in the tree requires.
1434 * For keep-case tree the case is always right. For prefixes we
1435 * don't bother to check. */
1436 if (mode == FIND_FOLDWORD)
1438 if (mip->mi_cend != mip->mi_word + wlen)
1440 /* mi_capflags was set for a different word length, need
1441 * to do it again. */
1442 mip->mi_cend = mip->mi_word + wlen;
1443 mip->mi_capflags = captype(mip->mi_word, mip->mi_cend);
1446 if (mip->mi_capflags == WF_KEEPCAP
1447 || !spell_valid_case(mip->mi_capflags, flags))
1448 continue;
1451 /* When mode is FIND_PREFIX the word must support the prefix:
1452 * check the prefix ID and the condition. Do that for the list at
1453 * mip->mi_prefarridx that find_prefix() filled. */
1454 else if (mode == FIND_PREFIX && !prefix_found)
1456 c = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx,
1457 flags,
1458 mip->mi_word + mip->mi_cprefixlen, slang,
1459 FALSE);
1460 if (c == 0)
1461 continue;
1463 /* Use the WF_RARE flag for a rare prefix. */
1464 if (c & WF_RAREPFX)
1465 flags |= WF_RARE;
1466 prefix_found = TRUE;
1469 if (slang->sl_nobreak)
1471 if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND)
1472 && (flags & WF_BANNED) == 0)
1474 /* NOBREAK: found a valid following word. That's all we
1475 * need to know, so return. */
1476 mip->mi_result = SP_OK;
1477 break;
1481 else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND
1482 || !word_ends))
1484 /* If there is no compound flag or the word is shorter than
1485 * COMPOUNDMIN reject it quickly.
1486 * Makes you wonder why someone puts a compound flag on a word
1487 * that's too short... Myspell compatibility requires this
1488 * anyway. */
1489 if (((unsigned)flags >> 24) == 0
1490 || wlen - mip->mi_compoff < slang->sl_compminlen)
1491 continue;
1492 #ifdef FEAT_MBYTE
1493 /* For multi-byte chars check character length against
1494 * COMPOUNDMIN. */
1495 if (has_mbyte
1496 && slang->sl_compminlen > 0
1497 && mb_charlen_len(mip->mi_word + mip->mi_compoff,
1498 wlen - mip->mi_compoff) < slang->sl_compminlen)
1499 continue;
1500 #endif
1502 /* Limit the number of compound words to COMPOUNDWORDMAX if no
1503 * maximum for syllables is specified. */
1504 if (!word_ends && mip->mi_complen + mip->mi_compextra + 2
1505 > slang->sl_compmax
1506 && slang->sl_compsylmax == MAXWLEN)
1507 continue;
1509 /* Don't allow compounding on a side where an affix was added,
1510 * unless COMPOUNDPERMITFLAG was used. */
1511 if (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF))
1512 continue;
1513 if (!word_ends && (flags & WF_NOCOMPAFT))
1514 continue;
1516 /* Quickly check if compounding is possible with this flag. */
1517 if (!byte_in_str(mip->mi_complen == 0
1518 ? slang->sl_compstartflags
1519 : slang->sl_compallflags,
1520 ((unsigned)flags >> 24)))
1521 continue;
1523 /* If there is a match with a CHECKCOMPOUNDPATTERN rule
1524 * discard the compound word. */
1525 if (match_checkcompoundpattern(ptr, wlen, &slang->sl_comppat))
1526 continue;
1528 if (mode == FIND_COMPOUND)
1530 int capflags;
1532 /* Need to check the caps type of the appended compound
1533 * word. */
1534 #ifdef FEAT_MBYTE
1535 if (has_mbyte && STRNCMP(ptr, mip->mi_word,
1536 mip->mi_compoff) != 0)
1538 /* case folding may have changed the length */
1539 p = mip->mi_word;
1540 for (s = ptr; s < ptr + mip->mi_compoff; mb_ptr_adv(s))
1541 mb_ptr_adv(p);
1543 else
1544 #endif
1545 p = mip->mi_word + mip->mi_compoff;
1546 capflags = captype(p, mip->mi_word + wlen);
1547 if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP
1548 && (flags & WF_FIXCAP) != 0))
1549 continue;
1551 if (capflags != WF_ALLCAP)
1553 /* When the character before the word is a word
1554 * character we do not accept a Onecap word. We do
1555 * accept a no-caps word, even when the dictionary
1556 * word specifies ONECAP. */
1557 mb_ptr_back(mip->mi_word, p);
1558 if (spell_iswordp_nmw(p)
1559 ? capflags == WF_ONECAP
1560 : (flags & WF_ONECAP) != 0
1561 && capflags != WF_ONECAP)
1562 continue;
1566 /* If the word ends the sequence of compound flags of the
1567 * words must match with one of the COMPOUNDRULE items and
1568 * the number of syllables must not be too large. */
1569 mip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24);
1570 mip->mi_compflags[mip->mi_complen + 1] = NUL;
1571 if (word_ends)
1573 char_u fword[MAXWLEN];
1575 if (slang->sl_compsylmax < MAXWLEN)
1577 /* "fword" is only needed for checking syllables. */
1578 if (ptr == mip->mi_word)
1579 (void)spell_casefold(ptr, wlen, fword, MAXWLEN);
1580 else
1581 vim_strncpy(fword, ptr, endlen[endidxcnt]);
1583 if (!can_compound(slang, fword, mip->mi_compflags))
1584 continue;
1586 else if (slang->sl_comprules != NULL
1587 && !match_compoundrule(slang, mip->mi_compflags))
1588 /* The compound flags collected so far do not match any
1589 * COMPOUNDRULE, discard the compounded word. */
1590 continue;
1593 /* Check NEEDCOMPOUND: can't use word without compounding. */
1594 else if (flags & WF_NEEDCOMP)
1595 continue;
1597 nobreak_result = SP_OK;
1599 if (!word_ends)
1601 int save_result = mip->mi_result;
1602 char_u *save_end = mip->mi_end;
1603 langp_T *save_lp = mip->mi_lp;
1604 int lpi;
1606 /* Check that a valid word follows. If there is one and we
1607 * are compounding, it will set "mi_result", thus we are
1608 * always finished here. For NOBREAK we only check that a
1609 * valid word follows.
1610 * Recursive! */
1611 if (slang->sl_nobreak)
1612 mip->mi_result = SP_BAD;
1614 /* Find following word in case-folded tree. */
1615 mip->mi_compoff = endlen[endidxcnt];
1616 #ifdef FEAT_MBYTE
1617 if (has_mbyte && mode == FIND_KEEPWORD)
1619 /* Compute byte length in case-folded word from "wlen":
1620 * byte length in keep-case word. Length may change when
1621 * folding case. This can be slow, take a shortcut when
1622 * the case-folded word is equal to the keep-case word. */
1623 p = mip->mi_fword;
1624 if (STRNCMP(ptr, p, wlen) != 0)
1626 for (s = ptr; s < ptr + wlen; mb_ptr_adv(s))
1627 mb_ptr_adv(p);
1628 mip->mi_compoff = (int)(p - mip->mi_fword);
1631 #endif
1632 c = mip->mi_compoff;
1633 ++mip->mi_complen;
1634 if (flags & WF_COMPROOT)
1635 ++mip->mi_compextra;
1637 /* For NOBREAK we need to try all NOBREAK languages, at least
1638 * to find the ".add" file(s). */
1639 for (lpi = 0; lpi < mip->mi_buf->b_langp.ga_len; ++lpi)
1641 if (slang->sl_nobreak)
1643 mip->mi_lp = LANGP_ENTRY(mip->mi_buf->b_langp, lpi);
1644 if (mip->mi_lp->lp_slang->sl_fidxs == NULL
1645 || !mip->mi_lp->lp_slang->sl_nobreak)
1646 continue;
1649 find_word(mip, FIND_COMPOUND);
1651 /* When NOBREAK any word that matches is OK. Otherwise we
1652 * need to find the longest match, thus try with keep-case
1653 * and prefix too. */
1654 if (!slang->sl_nobreak || mip->mi_result == SP_BAD)
1656 /* Find following word in keep-case tree. */
1657 mip->mi_compoff = wlen;
1658 find_word(mip, FIND_KEEPCOMPOUND);
1660 #if 0 /* Disabled, a prefix must not appear halfway a compound word,
1661 unless the COMPOUNDPERMITFLAG is used and then it can't be a
1662 postponed prefix. */
1663 if (!slang->sl_nobreak || mip->mi_result == SP_BAD)
1665 /* Check for following word with prefix. */
1666 mip->mi_compoff = c;
1667 find_prefix(mip, FIND_COMPOUND);
1669 #endif
1672 if (!slang->sl_nobreak)
1673 break;
1675 --mip->mi_complen;
1676 if (flags & WF_COMPROOT)
1677 --mip->mi_compextra;
1678 mip->mi_lp = save_lp;
1680 if (slang->sl_nobreak)
1682 nobreak_result = mip->mi_result;
1683 mip->mi_result = save_result;
1684 mip->mi_end = save_end;
1686 else
1688 if (mip->mi_result == SP_OK)
1689 break;
1690 continue;
1694 if (flags & WF_BANNED)
1695 res = SP_BANNED;
1696 else if (flags & WF_REGION)
1698 /* Check region. */
1699 if ((mip->mi_lp->lp_region & (flags >> 16)) != 0)
1700 res = SP_OK;
1701 else
1702 res = SP_LOCAL;
1704 else if (flags & WF_RARE)
1705 res = SP_RARE;
1706 else
1707 res = SP_OK;
1709 /* Always use the longest match and the best result. For NOBREAK
1710 * we separately keep the longest match without a following good
1711 * word as a fall-back. */
1712 if (nobreak_result == SP_BAD)
1714 if (mip->mi_result2 > res)
1716 mip->mi_result2 = res;
1717 mip->mi_end2 = mip->mi_word + wlen;
1719 else if (mip->mi_result2 == res
1720 && mip->mi_end2 < mip->mi_word + wlen)
1721 mip->mi_end2 = mip->mi_word + wlen;
1723 else if (mip->mi_result > res)
1725 mip->mi_result = res;
1726 mip->mi_end = mip->mi_word + wlen;
1728 else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen)
1729 mip->mi_end = mip->mi_word + wlen;
1731 if (mip->mi_result == SP_OK)
1732 break;
1735 if (mip->mi_result == SP_OK)
1736 break;
1741 * Return TRUE if there is a match between the word ptr[wlen] and
1742 * CHECKCOMPOUNDPATTERN rules, assuming that we will concatenate with another
1743 * word.
1744 * A match means that the first part of CHECKCOMPOUNDPATTERN matches at the
1745 * end of ptr[wlen] and the second part matches after it.
1747 static int
1748 match_checkcompoundpattern(ptr, wlen, gap)
1749 char_u *ptr;
1750 int wlen;
1751 garray_T *gap; /* &sl_comppat */
1753 int i;
1754 char_u *p;
1755 int len;
1757 for (i = 0; i + 1 < gap->ga_len; i += 2)
1759 p = ((char_u **)gap->ga_data)[i + 1];
1760 if (STRNCMP(ptr + wlen, p, STRLEN(p)) == 0)
1762 /* Second part matches at start of following compound word, now
1763 * check if first part matches at end of previous word. */
1764 p = ((char_u **)gap->ga_data)[i];
1765 len = (int)STRLEN(p);
1766 if (len <= wlen && STRNCMP(ptr + wlen - len, p, len) == 0)
1767 return TRUE;
1770 return FALSE;
1774 * Return TRUE if "flags" is a valid sequence of compound flags and "word"
1775 * does not have too many syllables.
1777 static int
1778 can_compound(slang, word, flags)
1779 slang_T *slang;
1780 char_u *word;
1781 char_u *flags;
1783 regmatch_T regmatch;
1784 #ifdef FEAT_MBYTE
1785 char_u uflags[MAXWLEN * 2];
1786 int i;
1787 #endif
1788 char_u *p;
1790 if (slang->sl_compprog == NULL)
1791 return FALSE;
1792 #ifdef FEAT_MBYTE
1793 if (enc_utf8)
1795 /* Need to convert the single byte flags to utf8 characters. */
1796 p = uflags;
1797 for (i = 0; flags[i] != NUL; ++i)
1798 p += mb_char2bytes(flags[i], p);
1799 *p = NUL;
1800 p = uflags;
1802 else
1803 #endif
1804 p = flags;
1805 regmatch.regprog = slang->sl_compprog;
1806 regmatch.rm_ic = FALSE;
1807 if (!vim_regexec(&regmatch, p, 0))
1808 return FALSE;
1810 /* Count the number of syllables. This may be slow, do it last. If there
1811 * are too many syllables AND the number of compound words is above
1812 * COMPOUNDWORDMAX then compounding is not allowed. */
1813 if (slang->sl_compsylmax < MAXWLEN
1814 && count_syllables(slang, word) > slang->sl_compsylmax)
1815 return (int)STRLEN(flags) < slang->sl_compmax;
1816 return TRUE;
1820 * Return TRUE when the sequence of flags in "compflags" plus "flag" can
1821 * possibly form a valid compounded word. This also checks the COMPOUNDRULE
1822 * lines if they don't contain wildcards.
1824 static int
1825 can_be_compound(sp, slang, compflags, flag)
1826 trystate_T *sp;
1827 slang_T *slang;
1828 char_u *compflags;
1829 int flag;
1831 /* If the flag doesn't appear in sl_compstartflags or sl_compallflags
1832 * then it can't possibly compound. */
1833 if (!byte_in_str(sp->ts_complen == sp->ts_compsplit
1834 ? slang->sl_compstartflags : slang->sl_compallflags, flag))
1835 return FALSE;
1837 /* If there are no wildcards, we can check if the flags collected so far
1838 * possibly can form a match with COMPOUNDRULE patterns. This only
1839 * makes sense when we have two or more words. */
1840 if (slang->sl_comprules != NULL && sp->ts_complen > sp->ts_compsplit)
1842 int v;
1844 compflags[sp->ts_complen] = flag;
1845 compflags[sp->ts_complen + 1] = NUL;
1846 v = match_compoundrule(slang, compflags + sp->ts_compsplit);
1847 compflags[sp->ts_complen] = NUL;
1848 return v;
1851 return TRUE;
1856 * Return TRUE if the compound flags in compflags[] match the start of any
1857 * compound rule. This is used to stop trying a compound if the flags
1858 * collected so far can't possibly match any compound rule.
1859 * Caller must check that slang->sl_comprules is not NULL.
1861 static int
1862 match_compoundrule(slang, compflags)
1863 slang_T *slang;
1864 char_u *compflags;
1866 char_u *p;
1867 int i;
1868 int c;
1870 /* loop over all the COMPOUNDRULE entries */
1871 for (p = slang->sl_comprules; *p != NUL; ++p)
1873 /* loop over the flags in the compound word we have made, match
1874 * them against the current rule entry */
1875 for (i = 0; ; ++i)
1877 c = compflags[i];
1878 if (c == NUL)
1879 /* found a rule that matches for the flags we have so far */
1880 return TRUE;
1881 if (*p == '/' || *p == NUL)
1882 break; /* end of rule, it's too short */
1883 if (*p == '[')
1885 int match = FALSE;
1887 /* compare against all the flags in [] */
1888 ++p;
1889 while (*p != ']' && *p != NUL)
1890 if (*p++ == c)
1891 match = TRUE;
1892 if (!match)
1893 break; /* none matches */
1895 else if (*p != c)
1896 break; /* flag of word doesn't match flag in pattern */
1897 ++p;
1900 /* Skip to the next "/", where the next pattern starts. */
1901 p = vim_strchr(p, '/');
1902 if (p == NULL)
1903 break;
1906 /* Checked all the rules and none of them match the flags, so there
1907 * can't possibly be a compound starting with these flags. */
1908 return FALSE;
1912 * Return non-zero if the prefix indicated by "arridx" matches with the prefix
1913 * ID in "flags" for the word "word".
1914 * The WF_RAREPFX flag is included in the return value for a rare prefix.
1916 static int
1917 valid_word_prefix(totprefcnt, arridx, flags, word, slang, cond_req)
1918 int totprefcnt; /* nr of prefix IDs */
1919 int arridx; /* idx in sl_pidxs[] */
1920 int flags;
1921 char_u *word;
1922 slang_T *slang;
1923 int cond_req; /* only use prefixes with a condition */
1925 int prefcnt;
1926 int pidx;
1927 regprog_T *rp;
1928 regmatch_T regmatch;
1929 int prefid;
1931 prefid = (unsigned)flags >> 24;
1932 for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt)
1934 pidx = slang->sl_pidxs[arridx + prefcnt];
1936 /* Check the prefix ID. */
1937 if (prefid != (pidx & 0xff))
1938 continue;
1940 /* Check if the prefix doesn't combine and the word already has a
1941 * suffix. */
1942 if ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC))
1943 continue;
1945 /* Check the condition, if there is one. The condition index is
1946 * stored in the two bytes above the prefix ID byte. */
1947 rp = slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff];
1948 if (rp != NULL)
1950 regmatch.regprog = rp;
1951 regmatch.rm_ic = FALSE;
1952 if (!vim_regexec(&regmatch, word, 0))
1953 continue;
1955 else if (cond_req)
1956 continue;
1958 /* It's a match! Return the WF_ flags. */
1959 return pidx;
1961 return 0;
1965 * Check if the word at "mip->mi_word" has a matching prefix.
1966 * If it does, then check the following word.
1968 * If "mode" is "FIND_COMPOUND" then do the same after another word, find a
1969 * prefix in a compound word.
1971 * For a match mip->mi_result is updated.
1973 static void
1974 find_prefix(mip, mode)
1975 matchinf_T *mip;
1976 int mode;
1978 idx_T arridx = 0;
1979 int len;
1980 int wlen = 0;
1981 int flen;
1982 int c;
1983 char_u *ptr;
1984 idx_T lo, hi, m;
1985 slang_T *slang = mip->mi_lp->lp_slang;
1986 char_u *byts;
1987 idx_T *idxs;
1989 byts = slang->sl_pbyts;
1990 if (byts == NULL)
1991 return; /* array is empty */
1993 /* We use the case-folded word here, since prefixes are always
1994 * case-folded. */
1995 ptr = mip->mi_fword;
1996 flen = mip->mi_fwordlen; /* available case-folded bytes */
1997 if (mode == FIND_COMPOUND)
1999 /* Skip over the previously found word(s). */
2000 ptr += mip->mi_compoff;
2001 flen -= mip->mi_compoff;
2003 idxs = slang->sl_pidxs;
2006 * Repeat advancing in the tree until:
2007 * - there is a byte that doesn't match,
2008 * - we reach the end of the tree,
2009 * - or we reach the end of the line.
2011 for (;;)
2013 if (flen == 0 && *mip->mi_fend != NUL)
2014 flen = fold_more(mip);
2016 len = byts[arridx++];
2018 /* If the first possible byte is a zero the prefix could end here.
2019 * Check if the following word matches and supports the prefix. */
2020 if (byts[arridx] == 0)
2022 /* There can be several prefixes with different conditions. We
2023 * try them all, since we don't know which one will give the
2024 * longest match. The word is the same each time, pass the list
2025 * of possible prefixes to find_word(). */
2026 mip->mi_prefarridx = arridx;
2027 mip->mi_prefcnt = len;
2028 while (len > 0 && byts[arridx] == 0)
2030 ++arridx;
2031 --len;
2033 mip->mi_prefcnt -= len;
2035 /* Find the word that comes after the prefix. */
2036 mip->mi_prefixlen = wlen;
2037 if (mode == FIND_COMPOUND)
2038 /* Skip over the previously found word(s). */
2039 mip->mi_prefixlen += mip->mi_compoff;
2041 #ifdef FEAT_MBYTE
2042 if (has_mbyte)
2044 /* Case-folded length may differ from original length. */
2045 mip->mi_cprefixlen = nofold_len(mip->mi_fword,
2046 mip->mi_prefixlen, mip->mi_word);
2048 else
2049 mip->mi_cprefixlen = mip->mi_prefixlen;
2050 #endif
2051 find_word(mip, FIND_PREFIX);
2054 if (len == 0)
2055 break; /* no children, word must end here */
2058 /* Stop looking at end of the line. */
2059 if (ptr[wlen] == NUL)
2060 break;
2062 /* Perform a binary search in the list of accepted bytes. */
2063 c = ptr[wlen];
2064 lo = arridx;
2065 hi = arridx + len - 1;
2066 while (lo < hi)
2068 m = (lo + hi) / 2;
2069 if (byts[m] > c)
2070 hi = m - 1;
2071 else if (byts[m] < c)
2072 lo = m + 1;
2073 else
2075 lo = hi = m;
2076 break;
2080 /* Stop if there is no matching byte. */
2081 if (hi < lo || byts[lo] != c)
2082 break;
2084 /* Continue at the child (if there is one). */
2085 arridx = idxs[lo];
2086 ++wlen;
2087 --flen;
2092 * Need to fold at least one more character. Do until next non-word character
2093 * for efficiency. Include the non-word character too.
2094 * Return the length of the folded chars in bytes.
2096 static int
2097 fold_more(mip)
2098 matchinf_T *mip;
2100 int flen;
2101 char_u *p;
2103 p = mip->mi_fend;
2106 mb_ptr_adv(mip->mi_fend);
2107 } while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_buf));
2109 /* Include the non-word character so that we can check for the word end. */
2110 if (*mip->mi_fend != NUL)
2111 mb_ptr_adv(mip->mi_fend);
2113 (void)spell_casefold(p, (int)(mip->mi_fend - p),
2114 mip->mi_fword + mip->mi_fwordlen,
2115 MAXWLEN - mip->mi_fwordlen);
2116 flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen);
2117 mip->mi_fwordlen += flen;
2118 return flen;
2122 * Check case flags for a word. Return TRUE if the word has the requested
2123 * case.
2125 static int
2126 spell_valid_case(wordflags, treeflags)
2127 int wordflags; /* flags for the checked word. */
2128 int treeflags; /* flags for the word in the spell tree */
2130 return ((wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0)
2131 || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0
2132 && ((treeflags & WF_ONECAP) == 0
2133 || (wordflags & WF_ONECAP) != 0)));
2137 * Return TRUE if spell checking is not enabled.
2139 static int
2140 no_spell_checking(wp)
2141 win_T *wp;
2143 if (!wp->w_p_spell || *wp->w_buffer->b_p_spl == NUL
2144 || wp->w_buffer->b_langp.ga_len == 0)
2146 EMSG(_("E756: Spell checking is not enabled"));
2147 return TRUE;
2149 return FALSE;
2153 * Move to next spell error.
2154 * "curline" is FALSE for "[s", "]s", "[S" and "]S".
2155 * "curline" is TRUE to find word under/after cursor in the same line.
2156 * For Insert mode completion "dir" is BACKWARD and "curline" is TRUE: move
2157 * to after badly spelled word before the cursor.
2158 * Return 0 if not found, length of the badly spelled word otherwise.
2161 spell_move_to(wp, dir, allwords, curline, attrp)
2162 win_T *wp;
2163 int dir; /* FORWARD or BACKWARD */
2164 int allwords; /* TRUE for "[s"/"]s", FALSE for "[S"/"]S" */
2165 int curline;
2166 hlf_T *attrp; /* return: attributes of bad word or NULL
2167 (only when "dir" is FORWARD) */
2169 linenr_T lnum;
2170 pos_T found_pos;
2171 int found_len = 0;
2172 char_u *line;
2173 char_u *p;
2174 char_u *endp;
2175 hlf_T attr;
2176 int len;
2177 # ifdef FEAT_SYN_HL
2178 int has_syntax = syntax_present(wp->w_buffer);
2179 # endif
2180 int col;
2181 int can_spell;
2182 char_u *buf = NULL;
2183 int buflen = 0;
2184 int skip = 0;
2185 int capcol = -1;
2186 int found_one = FALSE;
2187 int wrapped = FALSE;
2189 if (no_spell_checking(wp))
2190 return 0;
2193 * Start looking for bad word at the start of the line, because we can't
2194 * start halfway a word, we don't know where it starts or ends.
2196 * When searching backwards, we continue in the line to find the last
2197 * bad word (in the cursor line: before the cursor).
2199 * We concatenate the start of the next line, so that wrapped words work
2200 * (e.g. "et<line-break>cetera"). Doesn't work when searching backwards
2201 * though...
2203 lnum = wp->w_cursor.lnum;
2204 clearpos(&found_pos);
2206 while (!got_int)
2208 line = ml_get_buf(wp->w_buffer, lnum, FALSE);
2210 len = (int)STRLEN(line);
2211 if (buflen < len + MAXWLEN + 2)
2213 vim_free(buf);
2214 buflen = len + MAXWLEN + 2;
2215 buf = alloc(buflen);
2216 if (buf == NULL)
2217 break;
2220 /* In first line check first word for Capital. */
2221 if (lnum == 1)
2222 capcol = 0;
2224 /* For checking first word with a capital skip white space. */
2225 if (capcol == 0)
2226 capcol = (int)(skipwhite(line) - line);
2227 else if (curline && wp == curwin)
2229 /* For spellbadword(): check if first word needs a capital. */
2230 col = (int)(skipwhite(line) - line);
2231 if (check_need_cap(lnum, col))
2232 capcol = col;
2234 /* Need to get the line again, may have looked at the previous
2235 * one. */
2236 line = ml_get_buf(wp->w_buffer, lnum, FALSE);
2239 /* Copy the line into "buf" and append the start of the next line if
2240 * possible. */
2241 STRCPY(buf, line);
2242 if (lnum < wp->w_buffer->b_ml.ml_line_count)
2243 spell_cat_line(buf + STRLEN(buf),
2244 ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN);
2246 p = buf + skip;
2247 endp = buf + len;
2248 while (p < endp)
2250 /* When searching backward don't search after the cursor. Unless
2251 * we wrapped around the end of the buffer. */
2252 if (dir == BACKWARD
2253 && lnum == wp->w_cursor.lnum
2254 && !wrapped
2255 && (colnr_T)(p - buf) >= wp->w_cursor.col)
2256 break;
2258 /* start of word */
2259 attr = HLF_COUNT;
2260 len = spell_check(wp, p, &attr, &capcol, FALSE);
2262 if (attr != HLF_COUNT)
2264 /* We found a bad word. Check the attribute. */
2265 if (allwords || attr == HLF_SPB)
2267 /* When searching forward only accept a bad word after
2268 * the cursor. */
2269 if (dir == BACKWARD
2270 || lnum != wp->w_cursor.lnum
2271 || (lnum == wp->w_cursor.lnum
2272 && (wrapped
2273 || (colnr_T)(curline ? p - buf + len
2274 : p - buf)
2275 > wp->w_cursor.col)))
2277 # ifdef FEAT_SYN_HL
2278 if (has_syntax)
2280 col = (int)(p - buf);
2281 (void)syn_get_id(wp, lnum, (colnr_T)col,
2282 FALSE, &can_spell, FALSE);
2283 if (!can_spell)
2284 attr = HLF_COUNT;
2286 else
2287 #endif
2288 can_spell = TRUE;
2290 if (can_spell)
2292 found_one = TRUE;
2293 found_pos.lnum = lnum;
2294 found_pos.col = (int)(p - buf);
2295 #ifdef FEAT_VIRTUALEDIT
2296 found_pos.coladd = 0;
2297 #endif
2298 if (dir == FORWARD)
2300 /* No need to search further. */
2301 wp->w_cursor = found_pos;
2302 vim_free(buf);
2303 if (attrp != NULL)
2304 *attrp = attr;
2305 return len;
2307 else if (curline)
2308 /* Insert mode completion: put cursor after
2309 * the bad word. */
2310 found_pos.col += len;
2311 found_len = len;
2314 else
2315 found_one = TRUE;
2319 /* advance to character after the word */
2320 p += len;
2321 capcol -= len;
2324 if (dir == BACKWARD && found_pos.lnum != 0)
2326 /* Use the last match in the line (before the cursor). */
2327 wp->w_cursor = found_pos;
2328 vim_free(buf);
2329 return found_len;
2332 if (curline)
2333 break; /* only check cursor line */
2335 /* Advance to next line. */
2336 if (dir == BACKWARD)
2338 /* If we are back at the starting line and searched it again there
2339 * is no match, give up. */
2340 if (lnum == wp->w_cursor.lnum && wrapped)
2341 break;
2343 if (lnum > 1)
2344 --lnum;
2345 else if (!p_ws)
2346 break; /* at first line and 'nowrapscan' */
2347 else
2349 /* Wrap around to the end of the buffer. May search the
2350 * starting line again and accept the last match. */
2351 lnum = wp->w_buffer->b_ml.ml_line_count;
2352 wrapped = TRUE;
2353 if (!shortmess(SHM_SEARCH))
2354 give_warning((char_u *)_(top_bot_msg), TRUE);
2356 capcol = -1;
2358 else
2360 if (lnum < wp->w_buffer->b_ml.ml_line_count)
2361 ++lnum;
2362 else if (!p_ws)
2363 break; /* at first line and 'nowrapscan' */
2364 else
2366 /* Wrap around to the start of the buffer. May search the
2367 * starting line again and accept the first match. */
2368 lnum = 1;
2369 wrapped = TRUE;
2370 if (!shortmess(SHM_SEARCH))
2371 give_warning((char_u *)_(bot_top_msg), TRUE);
2374 /* If we are back at the starting line and there is no match then
2375 * give up. */
2376 if (lnum == wp->w_cursor.lnum && (!found_one || wrapped))
2377 break;
2379 /* Skip the characters at the start of the next line that were
2380 * included in a match crossing line boundaries. */
2381 if (attr == HLF_COUNT)
2382 skip = (int)(p - endp);
2383 else
2384 skip = 0;
2386 /* Capcol skips over the inserted space. */
2387 --capcol;
2389 /* But after empty line check first word in next line */
2390 if (*skipwhite(line) == NUL)
2391 capcol = 0;
2394 line_breakcheck();
2397 vim_free(buf);
2398 return 0;
2402 * For spell checking: concatenate the start of the following line "line" into
2403 * "buf", blanking-out special characters. Copy less then "maxlen" bytes.
2404 * Keep the blanks at the start of the next line, this is used in win_line()
2405 * to skip those bytes if the word was OK.
2407 void
2408 spell_cat_line(buf, line, maxlen)
2409 char_u *buf;
2410 char_u *line;
2411 int maxlen;
2413 char_u *p;
2414 int n;
2416 p = skipwhite(line);
2417 while (vim_strchr((char_u *)"*#/\"\t", *p) != NULL)
2418 p = skipwhite(p + 1);
2420 if (*p != NUL)
2422 /* Only worth concatenating if there is something else than spaces to
2423 * concatenate. */
2424 n = (int)(p - line) + 1;
2425 if (n < maxlen - 1)
2427 vim_memset(buf, ' ', n);
2428 vim_strncpy(buf + n, p, maxlen - 1 - n);
2434 * Structure used for the cookie argument of do_in_runtimepath().
2436 typedef struct spelload_S
2438 char_u sl_lang[MAXWLEN + 1]; /* language name */
2439 slang_T *sl_slang; /* resulting slang_T struct */
2440 int sl_nobreak; /* NOBREAK language found */
2441 } spelload_T;
2444 * Load word list(s) for "lang" from Vim spell file(s).
2445 * "lang" must be the language without the region: e.g., "en".
2447 static void
2448 spell_load_lang(lang)
2449 char_u *lang;
2451 char_u fname_enc[85];
2452 int r;
2453 spelload_T sl;
2454 #ifdef FEAT_AUTOCMD
2455 int round;
2456 #endif
2458 /* Copy the language name to pass it to spell_load_cb() as a cookie.
2459 * It's truncated when an error is detected. */
2460 STRCPY(sl.sl_lang, lang);
2461 sl.sl_slang = NULL;
2462 sl.sl_nobreak = FALSE;
2464 #ifdef FEAT_AUTOCMD
2465 /* We may retry when no spell file is found for the language, an
2466 * autocommand may load it then. */
2467 for (round = 1; round <= 2; ++round)
2468 #endif
2471 * Find the first spell file for "lang" in 'runtimepath' and load it.
2473 vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,
2474 "spell/%s.%s.spl", lang, spell_enc());
2475 r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl);
2477 if (r == FAIL && *sl.sl_lang != NUL)
2479 /* Try loading the ASCII version. */
2480 vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,
2481 "spell/%s.ascii.spl", lang);
2482 r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl);
2484 #ifdef FEAT_AUTOCMD
2485 if (r == FAIL && *sl.sl_lang != NUL && round == 1
2486 && apply_autocmds(EVENT_SPELLFILEMISSING, lang,
2487 curbuf->b_fname, FALSE, curbuf))
2488 continue;
2489 break;
2490 #endif
2492 #ifdef FEAT_AUTOCMD
2493 break;
2494 #endif
2497 if (r == FAIL)
2499 smsg((char_u *)_("Warning: Cannot find word list \"%s.%s.spl\" or \"%s.ascii.spl\""),
2500 lang, spell_enc(), lang);
2502 else if (sl.sl_slang != NULL)
2504 /* At least one file was loaded, now load ALL the additions. */
2505 STRCPY(fname_enc + STRLEN(fname_enc) - 3, "add.spl");
2506 do_in_runtimepath(fname_enc, TRUE, spell_load_cb, &sl);
2511 * Return the encoding used for spell checking: Use 'encoding', except that we
2512 * use "latin1" for "latin9". And limit to 60 characters (just in case).
2514 static char_u *
2515 spell_enc()
2518 #ifdef FEAT_MBYTE
2519 if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0)
2520 return p_enc;
2521 #endif
2522 return (char_u *)"latin1";
2526 * Get the name of the .spl file for the internal wordlist into
2527 * "fname[MAXPATHL]".
2529 static void
2530 int_wordlist_spl(fname)
2531 char_u *fname;
2533 vim_snprintf((char *)fname, MAXPATHL, "%s.%s.spl",
2534 int_wordlist, spell_enc());
2538 * Allocate a new slang_T for language "lang". "lang" can be NULL.
2539 * Caller must fill "sl_next".
2541 static slang_T *
2542 slang_alloc(lang)
2543 char_u *lang;
2545 slang_T *lp;
2547 lp = (slang_T *)alloc_clear(sizeof(slang_T));
2548 if (lp != NULL)
2550 if (lang != NULL)
2551 lp->sl_name = vim_strsave(lang);
2552 ga_init2(&lp->sl_rep, sizeof(fromto_T), 10);
2553 ga_init2(&lp->sl_repsal, sizeof(fromto_T), 10);
2554 lp->sl_compmax = MAXWLEN;
2555 lp->sl_compsylmax = MAXWLEN;
2556 hash_init(&lp->sl_wordcount);
2559 return lp;
2563 * Free the contents of an slang_T and the structure itself.
2565 static void
2566 slang_free(lp)
2567 slang_T *lp;
2569 vim_free(lp->sl_name);
2570 vim_free(lp->sl_fname);
2571 slang_clear(lp);
2572 vim_free(lp);
2576 * Clear an slang_T so that the file can be reloaded.
2578 static void
2579 slang_clear(lp)
2580 slang_T *lp;
2582 garray_T *gap;
2583 fromto_T *ftp;
2584 salitem_T *smp;
2585 int i;
2586 int round;
2588 vim_free(lp->sl_fbyts);
2589 lp->sl_fbyts = NULL;
2590 vim_free(lp->sl_kbyts);
2591 lp->sl_kbyts = NULL;
2592 vim_free(lp->sl_pbyts);
2593 lp->sl_pbyts = NULL;
2595 vim_free(lp->sl_fidxs);
2596 lp->sl_fidxs = NULL;
2597 vim_free(lp->sl_kidxs);
2598 lp->sl_kidxs = NULL;
2599 vim_free(lp->sl_pidxs);
2600 lp->sl_pidxs = NULL;
2602 for (round = 1; round <= 2; ++round)
2604 gap = round == 1 ? &lp->sl_rep : &lp->sl_repsal;
2605 while (gap->ga_len > 0)
2607 ftp = &((fromto_T *)gap->ga_data)[--gap->ga_len];
2608 vim_free(ftp->ft_from);
2609 vim_free(ftp->ft_to);
2611 ga_clear(gap);
2614 gap = &lp->sl_sal;
2615 if (lp->sl_sofo)
2617 /* "ga_len" is set to 1 without adding an item for latin1 */
2618 if (gap->ga_data != NULL)
2619 /* SOFOFROM and SOFOTO items: free lists of wide characters. */
2620 for (i = 0; i < gap->ga_len; ++i)
2621 vim_free(((int **)gap->ga_data)[i]);
2623 else
2624 /* SAL items: free salitem_T items */
2625 while (gap->ga_len > 0)
2627 smp = &((salitem_T *)gap->ga_data)[--gap->ga_len];
2628 vim_free(smp->sm_lead);
2629 /* Don't free sm_oneof and sm_rules, they point into sm_lead. */
2630 vim_free(smp->sm_to);
2631 #ifdef FEAT_MBYTE
2632 vim_free(smp->sm_lead_w);
2633 vim_free(smp->sm_oneof_w);
2634 vim_free(smp->sm_to_w);
2635 #endif
2637 ga_clear(gap);
2639 for (i = 0; i < lp->sl_prefixcnt; ++i)
2640 vim_free(lp->sl_prefprog[i]);
2641 lp->sl_prefixcnt = 0;
2642 vim_free(lp->sl_prefprog);
2643 lp->sl_prefprog = NULL;
2645 vim_free(lp->sl_info);
2646 lp->sl_info = NULL;
2648 vim_free(lp->sl_midword);
2649 lp->sl_midword = NULL;
2651 vim_free(lp->sl_compprog);
2652 vim_free(lp->sl_comprules);
2653 vim_free(lp->sl_compstartflags);
2654 vim_free(lp->sl_compallflags);
2655 lp->sl_compprog = NULL;
2656 lp->sl_comprules = NULL;
2657 lp->sl_compstartflags = NULL;
2658 lp->sl_compallflags = NULL;
2660 vim_free(lp->sl_syllable);
2661 lp->sl_syllable = NULL;
2662 ga_clear(&lp->sl_syl_items);
2664 ga_clear_strings(&lp->sl_comppat);
2666 hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF);
2667 hash_init(&lp->sl_wordcount);
2669 #ifdef FEAT_MBYTE
2670 hash_clear_all(&lp->sl_map_hash, 0);
2671 #endif
2673 /* Clear info from .sug file. */
2674 slang_clear_sug(lp);
2676 lp->sl_compmax = MAXWLEN;
2677 lp->sl_compminlen = 0;
2678 lp->sl_compsylmax = MAXWLEN;
2679 lp->sl_regions[0] = NUL;
2683 * Clear the info from the .sug file in "lp".
2685 static void
2686 slang_clear_sug(lp)
2687 slang_T *lp;
2689 vim_free(lp->sl_sbyts);
2690 lp->sl_sbyts = NULL;
2691 vim_free(lp->sl_sidxs);
2692 lp->sl_sidxs = NULL;
2693 close_spellbuf(lp->sl_sugbuf);
2694 lp->sl_sugbuf = NULL;
2695 lp->sl_sugloaded = FALSE;
2696 lp->sl_sugtime = 0;
2700 * Load one spell file and store the info into a slang_T.
2701 * Invoked through do_in_runtimepath().
2703 static void
2704 spell_load_cb(fname, cookie)
2705 char_u *fname;
2706 void *cookie;
2708 spelload_T *slp = (spelload_T *)cookie;
2709 slang_T *slang;
2711 slang = spell_load_file(fname, slp->sl_lang, NULL, FALSE);
2712 if (slang != NULL)
2714 /* When a previously loaded file has NOBREAK also use it for the
2715 * ".add" files. */
2716 if (slp->sl_nobreak && slang->sl_add)
2717 slang->sl_nobreak = TRUE;
2718 else if (slang->sl_nobreak)
2719 slp->sl_nobreak = TRUE;
2721 slp->sl_slang = slang;
2726 * Load one spell file and store the info into a slang_T.
2728 * This is invoked in three ways:
2729 * - From spell_load_cb() to load a spell file for the first time. "lang" is
2730 * the language name, "old_lp" is NULL. Will allocate an slang_T.
2731 * - To reload a spell file that was changed. "lang" is NULL and "old_lp"
2732 * points to the existing slang_T.
2733 * - Just after writing a .spl file; it's read back to produce the .sug file.
2734 * "old_lp" is NULL and "lang" is NULL. Will allocate an slang_T.
2736 * Returns the slang_T the spell file was loaded into. NULL for error.
2738 static slang_T *
2739 spell_load_file(fname, lang, old_lp, silent)
2740 char_u *fname;
2741 char_u *lang;
2742 slang_T *old_lp;
2743 int silent; /* no error if file doesn't exist */
2745 FILE *fd;
2746 char_u buf[VIMSPELLMAGICL];
2747 char_u *p;
2748 int i;
2749 int n;
2750 int len;
2751 char_u *save_sourcing_name = sourcing_name;
2752 linenr_T save_sourcing_lnum = sourcing_lnum;
2753 slang_T *lp = NULL;
2754 int c = 0;
2755 int res;
2757 fd = mch_fopen((char *)fname, "r");
2758 if (fd == NULL)
2760 if (!silent)
2761 EMSG2(_(e_notopen), fname);
2762 else if (p_verbose > 2)
2764 verbose_enter();
2765 smsg((char_u *)e_notopen, fname);
2766 verbose_leave();
2768 goto endFAIL;
2770 if (p_verbose > 2)
2772 verbose_enter();
2773 smsg((char_u *)_("Reading spell file \"%s\""), fname);
2774 verbose_leave();
2777 if (old_lp == NULL)
2779 lp = slang_alloc(lang);
2780 if (lp == NULL)
2781 goto endFAIL;
2783 /* Remember the file name, used to reload the file when it's updated. */
2784 lp->sl_fname = vim_strsave(fname);
2785 if (lp->sl_fname == NULL)
2786 goto endFAIL;
2788 /* Check for .add.spl. */
2789 lp->sl_add = strstr((char *)gettail(fname), ".add.") != NULL;
2791 else
2792 lp = old_lp;
2794 /* Set sourcing_name, so that error messages mention the file name. */
2795 sourcing_name = fname;
2796 sourcing_lnum = 0;
2799 * <HEADER>: <fileID>
2801 for (i = 0; i < VIMSPELLMAGICL; ++i)
2802 buf[i] = getc(fd); /* <fileID> */
2803 if (STRNCMP(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0)
2805 EMSG(_("E757: This does not look like a spell file"));
2806 goto endFAIL;
2808 c = getc(fd); /* <versionnr> */
2809 if (c < VIMSPELLVERSION)
2811 EMSG(_("E771: Old spell file, needs to be updated"));
2812 goto endFAIL;
2814 else if (c > VIMSPELLVERSION)
2816 EMSG(_("E772: Spell file is for newer version of Vim"));
2817 goto endFAIL;
2822 * <SECTIONS>: <section> ... <sectionend>
2823 * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
2825 for (;;)
2827 n = getc(fd); /* <sectionID> or <sectionend> */
2828 if (n == SN_END)
2829 break;
2830 c = getc(fd); /* <sectionflags> */
2831 len = get4c(fd); /* <sectionlen> */
2832 if (len < 0)
2833 goto truncerr;
2835 res = 0;
2836 switch (n)
2838 case SN_INFO:
2839 lp->sl_info = read_string(fd, len); /* <infotext> */
2840 if (lp->sl_info == NULL)
2841 goto endFAIL;
2842 break;
2844 case SN_REGION:
2845 res = read_region_section(fd, lp, len);
2846 break;
2848 case SN_CHARFLAGS:
2849 res = read_charflags_section(fd);
2850 break;
2852 case SN_MIDWORD:
2853 lp->sl_midword = read_string(fd, len); /* <midword> */
2854 if (lp->sl_midword == NULL)
2855 goto endFAIL;
2856 break;
2858 case SN_PREFCOND:
2859 res = read_prefcond_section(fd, lp);
2860 break;
2862 case SN_REP:
2863 res = read_rep_section(fd, &lp->sl_rep, lp->sl_rep_first);
2864 break;
2866 case SN_REPSAL:
2867 res = read_rep_section(fd, &lp->sl_repsal, lp->sl_repsal_first);
2868 break;
2870 case SN_SAL:
2871 res = read_sal_section(fd, lp);
2872 break;
2874 case SN_SOFO:
2875 res = read_sofo_section(fd, lp);
2876 break;
2878 case SN_MAP:
2879 p = read_string(fd, len); /* <mapstr> */
2880 if (p == NULL)
2881 goto endFAIL;
2882 set_map_str(lp, p);
2883 vim_free(p);
2884 break;
2886 case SN_WORDS:
2887 res = read_words_section(fd, lp, len);
2888 break;
2890 case SN_SUGFILE:
2891 lp->sl_sugtime = get8c(fd); /* <timestamp> */
2892 break;
2894 case SN_NOSPLITSUGS:
2895 lp->sl_nosplitsugs = TRUE; /* <timestamp> */
2896 break;
2898 case SN_COMPOUND:
2899 res = read_compound(fd, lp, len);
2900 break;
2902 case SN_NOBREAK:
2903 lp->sl_nobreak = TRUE;
2904 break;
2906 case SN_SYLLABLE:
2907 lp->sl_syllable = read_string(fd, len); /* <syllable> */
2908 if (lp->sl_syllable == NULL)
2909 goto endFAIL;
2910 if (init_syl_tab(lp) == FAIL)
2911 goto endFAIL;
2912 break;
2914 default:
2915 /* Unsupported section. When it's required give an error
2916 * message. When it's not required skip the contents. */
2917 if (c & SNF_REQUIRED)
2919 EMSG(_("E770: Unsupported section in spell file"));
2920 goto endFAIL;
2922 while (--len >= 0)
2923 if (getc(fd) < 0)
2924 goto truncerr;
2925 break;
2927 someerror:
2928 if (res == SP_FORMERROR)
2930 EMSG(_(e_format));
2931 goto endFAIL;
2933 if (res == SP_TRUNCERROR)
2935 truncerr:
2936 EMSG(_(e_spell_trunc));
2937 goto endFAIL;
2939 if (res == SP_OTHERERROR)
2940 goto endFAIL;
2943 /* <LWORDTREE> */
2944 res = spell_read_tree(fd, &lp->sl_fbyts, &lp->sl_fidxs, FALSE, 0);
2945 if (res != 0)
2946 goto someerror;
2948 /* <KWORDTREE> */
2949 res = spell_read_tree(fd, &lp->sl_kbyts, &lp->sl_kidxs, FALSE, 0);
2950 if (res != 0)
2951 goto someerror;
2953 /* <PREFIXTREE> */
2954 res = spell_read_tree(fd, &lp->sl_pbyts, &lp->sl_pidxs, TRUE,
2955 lp->sl_prefixcnt);
2956 if (res != 0)
2957 goto someerror;
2959 /* For a new file link it in the list of spell files. */
2960 if (old_lp == NULL && lang != NULL)
2962 lp->sl_next = first_lang;
2963 first_lang = lp;
2966 goto endOK;
2968 endFAIL:
2969 if (lang != NULL)
2970 /* truncating the name signals the error to spell_load_lang() */
2971 *lang = NUL;
2972 if (lp != NULL && old_lp == NULL)
2973 slang_free(lp);
2974 lp = NULL;
2976 endOK:
2977 if (fd != NULL)
2978 fclose(fd);
2979 sourcing_name = save_sourcing_name;
2980 sourcing_lnum = save_sourcing_lnum;
2982 return lp;
2986 * Read 2 bytes from "fd" and turn them into an int, MSB first.
2989 get2c(fd)
2990 FILE *fd;
2992 long n;
2994 n = getc(fd);
2995 n = (n << 8) + getc(fd);
2996 return n;
3000 * Read 3 bytes from "fd" and turn them into an int, MSB first.
3003 get3c(fd)
3004 FILE *fd;
3006 long n;
3008 n = getc(fd);
3009 n = (n << 8) + getc(fd);
3010 n = (n << 8) + getc(fd);
3011 return n;
3015 * Read 4 bytes from "fd" and turn them into an int, MSB first.
3018 get4c(fd)
3019 FILE *fd;
3021 long n;
3023 n = getc(fd);
3024 n = (n << 8) + getc(fd);
3025 n = (n << 8) + getc(fd);
3026 n = (n << 8) + getc(fd);
3027 return n;
3031 * Read 8 bytes from "fd" and turn them into a time_t, MSB first.
3033 static time_t
3034 get8c(fd)
3035 FILE *fd;
3037 time_t n = 0;
3038 int i;
3040 for (i = 0; i < 8; ++i)
3041 n = (n << 8) + getc(fd);
3042 return n;
3046 * Read a length field from "fd" in "cnt_bytes" bytes.
3047 * Allocate memory, read the string into it and add a NUL at the end.
3048 * Returns NULL when the count is zero.
3049 * Sets "*cntp" to SP_*ERROR when there is an error, length of the result
3050 * otherwise.
3052 static char_u *
3053 read_cnt_string(fd, cnt_bytes, cntp)
3054 FILE *fd;
3055 int cnt_bytes;
3056 int *cntp;
3058 int cnt = 0;
3059 int i;
3060 char_u *str;
3062 /* read the length bytes, MSB first */
3063 for (i = 0; i < cnt_bytes; ++i)
3064 cnt = (cnt << 8) + getc(fd);
3065 if (cnt < 0)
3067 *cntp = SP_TRUNCERROR;
3068 return NULL;
3070 *cntp = cnt;
3071 if (cnt == 0)
3072 return NULL; /* nothing to read, return NULL */
3074 str = read_string(fd, cnt);
3075 if (str == NULL)
3076 *cntp = SP_OTHERERROR;
3077 return str;
3081 * Read a string of length "cnt" from "fd" into allocated memory.
3082 * Returns NULL when out of memory or unable to read that many bytes.
3084 static char_u *
3085 read_string(fd, cnt)
3086 FILE *fd;
3087 int cnt;
3089 char_u *str;
3090 int i;
3091 int c;
3093 /* allocate memory */
3094 str = alloc((unsigned)cnt + 1);
3095 if (str != NULL)
3097 /* Read the string. Quit when running into the EOF. */
3098 for (i = 0; i < cnt; ++i)
3100 c = getc(fd);
3101 if (c == EOF)
3103 vim_free(str);
3104 return NULL;
3106 str[i] = c;
3108 str[i] = NUL;
3110 return str;
3114 * Read SN_REGION: <regionname> ...
3115 * Return SP_*ERROR flags.
3117 static int
3118 read_region_section(fd, lp, len)
3119 FILE *fd;
3120 slang_T *lp;
3121 int len;
3123 int i;
3125 if (len > 16)
3126 return SP_FORMERROR;
3127 for (i = 0; i < len; ++i)
3128 lp->sl_regions[i] = getc(fd); /* <regionname> */
3129 lp->sl_regions[len] = NUL;
3130 return 0;
3134 * Read SN_CHARFLAGS section: <charflagslen> <charflags>
3135 * <folcharslen> <folchars>
3136 * Return SP_*ERROR flags.
3138 static int
3139 read_charflags_section(fd)
3140 FILE *fd;
3142 char_u *flags;
3143 char_u *fol;
3144 int flagslen, follen;
3146 /* <charflagslen> <charflags> */
3147 flags = read_cnt_string(fd, 1, &flagslen);
3148 if (flagslen < 0)
3149 return flagslen;
3151 /* <folcharslen> <folchars> */
3152 fol = read_cnt_string(fd, 2, &follen);
3153 if (follen < 0)
3155 vim_free(flags);
3156 return follen;
3159 /* Set the word-char flags and fill SPELL_ISUPPER() table. */
3160 if (flags != NULL && fol != NULL)
3161 set_spell_charflags(flags, flagslen, fol);
3163 vim_free(flags);
3164 vim_free(fol);
3166 /* When <charflagslen> is zero then <fcharlen> must also be zero. */
3167 if ((flags == NULL) != (fol == NULL))
3168 return SP_FORMERROR;
3169 return 0;
3173 * Read SN_PREFCOND section.
3174 * Return SP_*ERROR flags.
3176 static int
3177 read_prefcond_section(fd, lp)
3178 FILE *fd;
3179 slang_T *lp;
3181 int cnt;
3182 int i;
3183 int n;
3184 char_u *p;
3185 char_u buf[MAXWLEN + 1];
3187 /* <prefcondcnt> <prefcond> ... */
3188 cnt = get2c(fd); /* <prefcondcnt> */
3189 if (cnt <= 0)
3190 return SP_FORMERROR;
3192 lp->sl_prefprog = (regprog_T **)alloc_clear(
3193 (unsigned)sizeof(regprog_T *) * cnt);
3194 if (lp->sl_prefprog == NULL)
3195 return SP_OTHERERROR;
3196 lp->sl_prefixcnt = cnt;
3198 for (i = 0; i < cnt; ++i)
3200 /* <prefcond> : <condlen> <condstr> */
3201 n = getc(fd); /* <condlen> */
3202 if (n < 0 || n >= MAXWLEN)
3203 return SP_FORMERROR;
3205 /* When <condlen> is zero we have an empty condition. Otherwise
3206 * compile the regexp program used to check for the condition. */
3207 if (n > 0)
3209 buf[0] = '^'; /* always match at one position only */
3210 p = buf + 1;
3211 while (n-- > 0)
3212 *p++ = getc(fd); /* <condstr> */
3213 *p = NUL;
3214 lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC + RE_STRING);
3217 return 0;
3221 * Read REP or REPSAL items section from "fd": <repcount> <rep> ...
3222 * Return SP_*ERROR flags.
3224 static int
3225 read_rep_section(fd, gap, first)
3226 FILE *fd;
3227 garray_T *gap;
3228 short *first;
3230 int cnt;
3231 fromto_T *ftp;
3232 int i;
3234 cnt = get2c(fd); /* <repcount> */
3235 if (cnt < 0)
3236 return SP_TRUNCERROR;
3238 if (ga_grow(gap, cnt) == FAIL)
3239 return SP_OTHERERROR;
3241 /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */
3242 for (; gap->ga_len < cnt; ++gap->ga_len)
3244 ftp = &((fromto_T *)gap->ga_data)[gap->ga_len];
3245 ftp->ft_from = read_cnt_string(fd, 1, &i);
3246 if (i < 0)
3247 return i;
3248 if (i == 0)
3249 return SP_FORMERROR;
3250 ftp->ft_to = read_cnt_string(fd, 1, &i);
3251 if (i <= 0)
3253 vim_free(ftp->ft_from);
3254 if (i < 0)
3255 return i;
3256 return SP_FORMERROR;
3260 /* Fill the first-index table. */
3261 for (i = 0; i < 256; ++i)
3262 first[i] = -1;
3263 for (i = 0; i < gap->ga_len; ++i)
3265 ftp = &((fromto_T *)gap->ga_data)[i];
3266 if (first[*ftp->ft_from] == -1)
3267 first[*ftp->ft_from] = i;
3269 return 0;
3273 * Read SN_SAL section: <salflags> <salcount> <sal> ...
3274 * Return SP_*ERROR flags.
3276 static int
3277 read_sal_section(fd, slang)
3278 FILE *fd;
3279 slang_T *slang;
3281 int i;
3282 int cnt;
3283 garray_T *gap;
3284 salitem_T *smp;
3285 int ccnt;
3286 char_u *p;
3287 int c = NUL;
3289 slang->sl_sofo = FALSE;
3291 i = getc(fd); /* <salflags> */
3292 if (i & SAL_F0LLOWUP)
3293 slang->sl_followup = TRUE;
3294 if (i & SAL_COLLAPSE)
3295 slang->sl_collapse = TRUE;
3296 if (i & SAL_REM_ACCENTS)
3297 slang->sl_rem_accents = TRUE;
3299 cnt = get2c(fd); /* <salcount> */
3300 if (cnt < 0)
3301 return SP_TRUNCERROR;
3303 gap = &slang->sl_sal;
3304 ga_init2(gap, sizeof(salitem_T), 10);
3305 if (ga_grow(gap, cnt + 1) == FAIL)
3306 return SP_OTHERERROR;
3308 /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */
3309 for (; gap->ga_len < cnt; ++gap->ga_len)
3311 smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
3312 ccnt = getc(fd); /* <salfromlen> */
3313 if (ccnt < 0)
3314 return SP_TRUNCERROR;
3315 if ((p = alloc(ccnt + 2)) == NULL)
3316 return SP_OTHERERROR;
3317 smp->sm_lead = p;
3319 /* Read up to the first special char into sm_lead. */
3320 for (i = 0; i < ccnt; ++i)
3322 c = getc(fd); /* <salfrom> */
3323 if (vim_strchr((char_u *)"0123456789(-<^$", c) != NULL)
3324 break;
3325 *p++ = c;
3327 smp->sm_leadlen = (int)(p - smp->sm_lead);
3328 *p++ = NUL;
3330 /* Put (abc) chars in sm_oneof, if any. */
3331 if (c == '(')
3333 smp->sm_oneof = p;
3334 for (++i; i < ccnt; ++i)
3336 c = getc(fd); /* <salfrom> */
3337 if (c == ')')
3338 break;
3339 *p++ = c;
3341 *p++ = NUL;
3342 if (++i < ccnt)
3343 c = getc(fd);
3345 else
3346 smp->sm_oneof = NULL;
3348 /* Any following chars go in sm_rules. */
3349 smp->sm_rules = p;
3350 if (i < ccnt)
3351 /* store the char we got while checking for end of sm_lead */
3352 *p++ = c;
3353 for (++i; i < ccnt; ++i)
3354 *p++ = getc(fd); /* <salfrom> */
3355 *p++ = NUL;
3357 /* <saltolen> <salto> */
3358 smp->sm_to = read_cnt_string(fd, 1, &ccnt);
3359 if (ccnt < 0)
3361 vim_free(smp->sm_lead);
3362 return ccnt;
3365 #ifdef FEAT_MBYTE
3366 if (has_mbyte)
3368 /* convert the multi-byte strings to wide char strings */
3369 smp->sm_lead_w = mb_str2wide(smp->sm_lead);
3370 smp->sm_leadlen = mb_charlen(smp->sm_lead);
3371 if (smp->sm_oneof == NULL)
3372 smp->sm_oneof_w = NULL;
3373 else
3374 smp->sm_oneof_w = mb_str2wide(smp->sm_oneof);
3375 if (smp->sm_to == NULL)
3376 smp->sm_to_w = NULL;
3377 else
3378 smp->sm_to_w = mb_str2wide(smp->sm_to);
3379 if (smp->sm_lead_w == NULL
3380 || (smp->sm_oneof_w == NULL && smp->sm_oneof != NULL)
3381 || (smp->sm_to_w == NULL && smp->sm_to != NULL))
3383 vim_free(smp->sm_lead);
3384 vim_free(smp->sm_to);
3385 vim_free(smp->sm_lead_w);
3386 vim_free(smp->sm_oneof_w);
3387 vim_free(smp->sm_to_w);
3388 return SP_OTHERERROR;
3391 #endif
3394 if (gap->ga_len > 0)
3396 /* Add one extra entry to mark the end with an empty sm_lead. Avoids
3397 * that we need to check the index every time. */
3398 smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
3399 if ((p = alloc(1)) == NULL)
3400 return SP_OTHERERROR;
3401 p[0] = NUL;
3402 smp->sm_lead = p;
3403 smp->sm_leadlen = 0;
3404 smp->sm_oneof = NULL;
3405 smp->sm_rules = p;
3406 smp->sm_to = NULL;
3407 #ifdef FEAT_MBYTE
3408 if (has_mbyte)
3410 smp->sm_lead_w = mb_str2wide(smp->sm_lead);
3411 smp->sm_leadlen = 0;
3412 smp->sm_oneof_w = NULL;
3413 smp->sm_to_w = NULL;
3415 #endif
3416 ++gap->ga_len;
3419 /* Fill the first-index table. */
3420 set_sal_first(slang);
3422 return 0;
3426 * Read SN_WORDS: <word> ...
3427 * Return SP_*ERROR flags.
3429 static int
3430 read_words_section(fd, lp, len)
3431 FILE *fd;
3432 slang_T *lp;
3433 int len;
3435 int done = 0;
3436 int i;
3437 int c;
3438 char_u word[MAXWLEN];
3440 while (done < len)
3442 /* Read one word at a time. */
3443 for (i = 0; ; ++i)
3445 c = getc(fd);
3446 if (c == EOF)
3447 return SP_TRUNCERROR;
3448 word[i] = c;
3449 if (word[i] == NUL)
3450 break;
3451 if (i == MAXWLEN - 1)
3452 return SP_FORMERROR;
3455 /* Init the count to 10. */
3456 count_common_word(lp, word, -1, 10);
3457 done += i + 1;
3459 return 0;
3463 * Add a word to the hashtable of common words.
3464 * If it's already there then the counter is increased.
3466 static void
3467 count_common_word(lp, word, len, count)
3468 slang_T *lp;
3469 char_u *word;
3470 int len; /* word length, -1 for upto NUL */
3471 int count; /* 1 to count once, 10 to init */
3473 hash_T hash;
3474 hashitem_T *hi;
3475 wordcount_T *wc;
3476 char_u buf[MAXWLEN];
3477 char_u *p;
3479 if (len == -1)
3480 p = word;
3481 else
3483 vim_strncpy(buf, word, len);
3484 p = buf;
3487 hash = hash_hash(p);
3488 hi = hash_lookup(&lp->sl_wordcount, p, hash);
3489 if (HASHITEM_EMPTY(hi))
3491 wc = (wordcount_T *)alloc((unsigned)(sizeof(wordcount_T) + STRLEN(p)));
3492 if (wc == NULL)
3493 return;
3494 STRCPY(wc->wc_word, p);
3495 wc->wc_count = count;
3496 hash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash);
3498 else
3500 wc = HI2WC(hi);
3501 if ((wc->wc_count += count) < (unsigned)count) /* check for overflow */
3502 wc->wc_count = MAXWORDCOUNT;
3507 * Adjust the score of common words.
3509 static int
3510 score_wordcount_adj(slang, score, word, split)
3511 slang_T *slang;
3512 int score;
3513 char_u *word;
3514 int split; /* word was split, less bonus */
3516 hashitem_T *hi;
3517 wordcount_T *wc;
3518 int bonus;
3519 int newscore;
3521 hi = hash_find(&slang->sl_wordcount, word);
3522 if (!HASHITEM_EMPTY(hi))
3524 wc = HI2WC(hi);
3525 if (wc->wc_count < SCORE_THRES2)
3526 bonus = SCORE_COMMON1;
3527 else if (wc->wc_count < SCORE_THRES3)
3528 bonus = SCORE_COMMON2;
3529 else
3530 bonus = SCORE_COMMON3;
3531 if (split)
3532 newscore = score - bonus / 2;
3533 else
3534 newscore = score - bonus;
3535 if (newscore < 0)
3536 return 0;
3537 return newscore;
3539 return score;
3543 * SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
3544 * Return SP_*ERROR flags.
3546 static int
3547 read_sofo_section(fd, slang)
3548 FILE *fd;
3549 slang_T *slang;
3551 int cnt;
3552 char_u *from, *to;
3553 int res;
3555 slang->sl_sofo = TRUE;
3557 /* <sofofromlen> <sofofrom> */
3558 from = read_cnt_string(fd, 2, &cnt);
3559 if (cnt < 0)
3560 return cnt;
3562 /* <sofotolen> <sofoto> */
3563 to = read_cnt_string(fd, 2, &cnt);
3564 if (cnt < 0)
3566 vim_free(from);
3567 return cnt;
3570 /* Store the info in slang->sl_sal and/or slang->sl_sal_first. */
3571 if (from != NULL && to != NULL)
3572 res = set_sofo(slang, from, to);
3573 else if (from != NULL || to != NULL)
3574 res = SP_FORMERROR; /* only one of two strings is an error */
3575 else
3576 res = 0;
3578 vim_free(from);
3579 vim_free(to);
3580 return res;
3584 * Read the compound section from the .spl file:
3585 * <compmax> <compminlen> <compsylmax> <compoptions> <compflags>
3586 * Returns SP_*ERROR flags.
3588 static int
3589 read_compound(fd, slang, len)
3590 FILE *fd;
3591 slang_T *slang;
3592 int len;
3594 int todo = len;
3595 int c;
3596 int atstart;
3597 char_u *pat;
3598 char_u *pp;
3599 char_u *cp;
3600 char_u *ap;
3601 char_u *crp;
3602 int cnt;
3603 garray_T *gap;
3605 if (todo < 2)
3606 return SP_FORMERROR; /* need at least two bytes */
3608 --todo;
3609 c = getc(fd); /* <compmax> */
3610 if (c < 2)
3611 c = MAXWLEN;
3612 slang->sl_compmax = c;
3614 --todo;
3615 c = getc(fd); /* <compminlen> */
3616 if (c < 1)
3617 c = 0;
3618 slang->sl_compminlen = c;
3620 --todo;
3621 c = getc(fd); /* <compsylmax> */
3622 if (c < 1)
3623 c = MAXWLEN;
3624 slang->sl_compsylmax = c;
3626 c = getc(fd); /* <compoptions> */
3627 if (c != 0)
3628 ungetc(c, fd); /* be backwards compatible with Vim 7.0b */
3629 else
3631 --todo;
3632 c = getc(fd); /* only use the lower byte for now */
3633 --todo;
3634 slang->sl_compoptions = c;
3636 gap = &slang->sl_comppat;
3637 c = get2c(fd); /* <comppatcount> */
3638 todo -= 2;
3639 ga_init2(gap, sizeof(char_u *), c);
3640 if (ga_grow(gap, c) == OK)
3641 while (--c >= 0)
3643 ((char_u **)(gap->ga_data))[gap->ga_len++] =
3644 read_cnt_string(fd, 1, &cnt);
3645 /* <comppatlen> <comppattext> */
3646 if (cnt < 0)
3647 return cnt;
3648 todo -= cnt + 1;
3651 if (todo < 0)
3652 return SP_FORMERROR;
3654 /* Turn the COMPOUNDRULE items into a regexp pattern:
3655 * "a[bc]/a*b+" -> "^\(a[bc]\|a*b\+\)$".
3656 * Inserting backslashes may double the length, "^\(\)$<Nul>" is 7 bytes.
3657 * Conversion to utf-8 may double the size. */
3658 c = todo * 2 + 7;
3659 #ifdef FEAT_MBYTE
3660 if (enc_utf8)
3661 c += todo * 2;
3662 #endif
3663 pat = alloc((unsigned)c);
3664 if (pat == NULL)
3665 return SP_OTHERERROR;
3667 /* We also need a list of all flags that can appear at the start and one
3668 * for all flags. */
3669 cp = alloc(todo + 1);
3670 if (cp == NULL)
3672 vim_free(pat);
3673 return SP_OTHERERROR;
3675 slang->sl_compstartflags = cp;
3676 *cp = NUL;
3678 ap = alloc(todo + 1);
3679 if (ap == NULL)
3681 vim_free(pat);
3682 return SP_OTHERERROR;
3684 slang->sl_compallflags = ap;
3685 *ap = NUL;
3687 /* And a list of all patterns in their original form, for checking whether
3688 * compounding may work in match_compoundrule(). This is freed when we
3689 * encounter a wildcard, the check doesn't work then. */
3690 crp = alloc(todo + 1);
3691 slang->sl_comprules = crp;
3693 pp = pat;
3694 *pp++ = '^';
3695 *pp++ = '\\';
3696 *pp++ = '(';
3698 atstart = 1;
3699 while (todo-- > 0)
3701 c = getc(fd); /* <compflags> */
3702 if (c == EOF)
3704 vim_free(pat);
3705 return SP_TRUNCERROR;
3708 /* Add all flags to "sl_compallflags". */
3709 if (vim_strchr((char_u *)"+*[]/", c) == NULL
3710 && !byte_in_str(slang->sl_compallflags, c))
3712 *ap++ = c;
3713 *ap = NUL;
3716 if (atstart != 0)
3718 /* At start of item: copy flags to "sl_compstartflags". For a
3719 * [abc] item set "atstart" to 2 and copy up to the ']'. */
3720 if (c == '[')
3721 atstart = 2;
3722 else if (c == ']')
3723 atstart = 0;
3724 else
3726 if (!byte_in_str(slang->sl_compstartflags, c))
3728 *cp++ = c;
3729 *cp = NUL;
3731 if (atstart == 1)
3732 atstart = 0;
3736 /* Copy flag to "sl_comprules", unless we run into a wildcard. */
3737 if (crp != NULL)
3739 if (c == '+' || c == '*')
3741 vim_free(slang->sl_comprules);
3742 slang->sl_comprules = NULL;
3743 crp = NULL;
3745 else
3746 *crp++ = c;
3749 if (c == '/') /* slash separates two items */
3751 *pp++ = '\\';
3752 *pp++ = '|';
3753 atstart = 1;
3755 else /* normal char, "[abc]" and '*' are copied as-is */
3757 if (c == '+' || c == '~')
3758 *pp++ = '\\'; /* "a+" becomes "a\+" */
3759 #ifdef FEAT_MBYTE
3760 if (enc_utf8)
3761 pp += mb_char2bytes(c, pp);
3762 else
3763 #endif
3764 *pp++ = c;
3768 *pp++ = '\\';
3769 *pp++ = ')';
3770 *pp++ = '$';
3771 *pp = NUL;
3773 if (crp != NULL)
3774 *crp = NUL;
3776 slang->sl_compprog = vim_regcomp(pat, RE_MAGIC + RE_STRING + RE_STRICT);
3777 vim_free(pat);
3778 if (slang->sl_compprog == NULL)
3779 return SP_FORMERROR;
3781 return 0;
3785 * Return TRUE if byte "n" appears in "str".
3786 * Like strchr() but independent of locale.
3788 static int
3789 byte_in_str(str, n)
3790 char_u *str;
3791 int n;
3793 char_u *p;
3795 for (p = str; *p != NUL; ++p)
3796 if (*p == n)
3797 return TRUE;
3798 return FALSE;
3801 #define SY_MAXLEN 30
3802 typedef struct syl_item_S
3804 char_u sy_chars[SY_MAXLEN]; /* the sequence of chars */
3805 int sy_len;
3806 } syl_item_T;
3809 * Truncate "slang->sl_syllable" at the first slash and put the following items
3810 * in "slang->sl_syl_items".
3812 static int
3813 init_syl_tab(slang)
3814 slang_T *slang;
3816 char_u *p;
3817 char_u *s;
3818 int l;
3819 syl_item_T *syl;
3821 ga_init2(&slang->sl_syl_items, sizeof(syl_item_T), 4);
3822 p = vim_strchr(slang->sl_syllable, '/');
3823 while (p != NULL)
3825 *p++ = NUL;
3826 if (*p == NUL) /* trailing slash */
3827 break;
3828 s = p;
3829 p = vim_strchr(p, '/');
3830 if (p == NULL)
3831 l = (int)STRLEN(s);
3832 else
3833 l = (int)(p - s);
3834 if (l >= SY_MAXLEN)
3835 return SP_FORMERROR;
3836 if (ga_grow(&slang->sl_syl_items, 1) == FAIL)
3837 return SP_OTHERERROR;
3838 syl = ((syl_item_T *)slang->sl_syl_items.ga_data)
3839 + slang->sl_syl_items.ga_len++;
3840 vim_strncpy(syl->sy_chars, s, l);
3841 syl->sy_len = l;
3843 return OK;
3847 * Count the number of syllables in "word".
3848 * When "word" contains spaces the syllables after the last space are counted.
3849 * Returns zero if syllables are not defines.
3851 static int
3852 count_syllables(slang, word)
3853 slang_T *slang;
3854 char_u *word;
3856 int cnt = 0;
3857 int skip = FALSE;
3858 char_u *p;
3859 int len;
3860 int i;
3861 syl_item_T *syl;
3862 int c;
3864 if (slang->sl_syllable == NULL)
3865 return 0;
3867 for (p = word; *p != NUL; p += len)
3869 /* When running into a space reset counter. */
3870 if (*p == ' ')
3872 len = 1;
3873 cnt = 0;
3874 continue;
3877 /* Find longest match of syllable items. */
3878 len = 0;
3879 for (i = 0; i < slang->sl_syl_items.ga_len; ++i)
3881 syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i;
3882 if (syl->sy_len > len
3883 && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0)
3884 len = syl->sy_len;
3886 if (len != 0) /* found a match, count syllable */
3888 ++cnt;
3889 skip = FALSE;
3891 else
3893 /* No recognized syllable item, at least a syllable char then? */
3894 #ifdef FEAT_MBYTE
3895 c = mb_ptr2char(p);
3896 len = (*mb_ptr2len)(p);
3897 #else
3898 c = *p;
3899 len = 1;
3900 #endif
3901 if (vim_strchr(slang->sl_syllable, c) == NULL)
3902 skip = FALSE; /* No, search for next syllable */
3903 else if (!skip)
3905 ++cnt; /* Yes, count it */
3906 skip = TRUE; /* don't count following syllable chars */
3910 return cnt;
3914 * Set the SOFOFROM and SOFOTO items in language "lp".
3915 * Returns SP_*ERROR flags when there is something wrong.
3917 static int
3918 set_sofo(lp, from, to)
3919 slang_T *lp;
3920 char_u *from;
3921 char_u *to;
3923 int i;
3925 #ifdef FEAT_MBYTE
3926 garray_T *gap;
3927 char_u *s;
3928 char_u *p;
3929 int c;
3930 int *inp;
3932 if (has_mbyte)
3934 /* Use "sl_sal" as an array with 256 pointers to a list of wide
3935 * characters. The index is the low byte of the character.
3936 * The list contains from-to pairs with a terminating NUL.
3937 * sl_sal_first[] is used for latin1 "from" characters. */
3938 gap = &lp->sl_sal;
3939 ga_init2(gap, sizeof(int *), 1);
3940 if (ga_grow(gap, 256) == FAIL)
3941 return SP_OTHERERROR;
3942 vim_memset(gap->ga_data, 0, sizeof(int *) * 256);
3943 gap->ga_len = 256;
3945 /* First count the number of items for each list. Temporarily use
3946 * sl_sal_first[] for this. */
3947 for (p = from, s = to; *p != NUL && *s != NUL; )
3949 c = mb_cptr2char_adv(&p);
3950 mb_cptr_adv(s);
3951 if (c >= 256)
3952 ++lp->sl_sal_first[c & 0xff];
3954 if (*p != NUL || *s != NUL) /* lengths differ */
3955 return SP_FORMERROR;
3957 /* Allocate the lists. */
3958 for (i = 0; i < 256; ++i)
3959 if (lp->sl_sal_first[i] > 0)
3961 p = alloc(sizeof(int) * (lp->sl_sal_first[i] * 2 + 1));
3962 if (p == NULL)
3963 return SP_OTHERERROR;
3964 ((int **)gap->ga_data)[i] = (int *)p;
3965 *(int *)p = 0;
3968 /* Put the characters up to 255 in sl_sal_first[] the rest in a sl_sal
3969 * list. */
3970 vim_memset(lp->sl_sal_first, 0, sizeof(salfirst_T) * 256);
3971 for (p = from, s = to; *p != NUL && *s != NUL; )
3973 c = mb_cptr2char_adv(&p);
3974 i = mb_cptr2char_adv(&s);
3975 if (c >= 256)
3977 /* Append the from-to chars at the end of the list with
3978 * the low byte. */
3979 inp = ((int **)gap->ga_data)[c & 0xff];
3980 while (*inp != 0)
3981 ++inp;
3982 *inp++ = c; /* from char */
3983 *inp++ = i; /* to char */
3984 *inp++ = NUL; /* NUL at the end */
3986 else
3987 /* mapping byte to char is done in sl_sal_first[] */
3988 lp->sl_sal_first[c] = i;
3991 else
3992 #endif
3994 /* mapping bytes to bytes is done in sl_sal_first[] */
3995 if (STRLEN(from) != STRLEN(to))
3996 return SP_FORMERROR;
3998 for (i = 0; to[i] != NUL; ++i)
3999 lp->sl_sal_first[from[i]] = to[i];
4000 lp->sl_sal.ga_len = 1; /* indicates we have soundfolding */
4003 return 0;
4007 * Fill the first-index table for "lp".
4009 static void
4010 set_sal_first(lp)
4011 slang_T *lp;
4013 salfirst_T *sfirst;
4014 int i;
4015 salitem_T *smp;
4016 int c;
4017 garray_T *gap = &lp->sl_sal;
4019 sfirst = lp->sl_sal_first;
4020 for (i = 0; i < 256; ++i)
4021 sfirst[i] = -1;
4022 smp = (salitem_T *)gap->ga_data;
4023 for (i = 0; i < gap->ga_len; ++i)
4025 #ifdef FEAT_MBYTE
4026 if (has_mbyte)
4027 /* Use the lowest byte of the first character. For latin1 it's
4028 * the character, for other encodings it should differ for most
4029 * characters. */
4030 c = *smp[i].sm_lead_w & 0xff;
4031 else
4032 #endif
4033 c = *smp[i].sm_lead;
4034 if (sfirst[c] == -1)
4036 sfirst[c] = i;
4037 #ifdef FEAT_MBYTE
4038 if (has_mbyte)
4040 int n;
4042 /* Make sure all entries with this byte are following each
4043 * other. Move the ones that are in the wrong position. Do
4044 * keep the same ordering! */
4045 while (i + 1 < gap->ga_len
4046 && (*smp[i + 1].sm_lead_w & 0xff) == c)
4047 /* Skip over entry with same index byte. */
4048 ++i;
4050 for (n = 1; i + n < gap->ga_len; ++n)
4051 if ((*smp[i + n].sm_lead_w & 0xff) == c)
4053 salitem_T tsal;
4055 /* Move entry with same index byte after the entries
4056 * we already found. */
4057 ++i;
4058 --n;
4059 tsal = smp[i + n];
4060 mch_memmove(smp + i + 1, smp + i,
4061 sizeof(salitem_T) * n);
4062 smp[i] = tsal;
4065 #endif
4070 #ifdef FEAT_MBYTE
4072 * Turn a multi-byte string into a wide character string.
4073 * Return it in allocated memory (NULL for out-of-memory)
4075 static int *
4076 mb_str2wide(s)
4077 char_u *s;
4079 int *res;
4080 char_u *p;
4081 int i = 0;
4083 res = (int *)alloc(sizeof(int) * (mb_charlen(s) + 1));
4084 if (res != NULL)
4086 for (p = s; *p != NUL; )
4087 res[i++] = mb_ptr2char_adv(&p);
4088 res[i] = NUL;
4090 return res;
4092 #endif
4095 * Read a tree from the .spl or .sug file.
4096 * Allocates the memory and stores pointers in "bytsp" and "idxsp".
4097 * This is skipped when the tree has zero length.
4098 * Returns zero when OK, SP_ value for an error.
4100 static int
4101 spell_read_tree(fd, bytsp, idxsp, prefixtree, prefixcnt)
4102 FILE *fd;
4103 char_u **bytsp;
4104 idx_T **idxsp;
4105 int prefixtree; /* TRUE for the prefix tree */
4106 int prefixcnt; /* when "prefixtree" is TRUE: prefix count */
4108 int len;
4109 int idx;
4110 char_u *bp;
4111 idx_T *ip;
4113 /* The tree size was computed when writing the file, so that we can
4114 * allocate it as one long block. <nodecount> */
4115 len = get4c(fd);
4116 if (len < 0)
4117 return SP_TRUNCERROR;
4118 if (len > 0)
4120 /* Allocate the byte array. */
4121 bp = lalloc((long_u)len, TRUE);
4122 if (bp == NULL)
4123 return SP_OTHERERROR;
4124 *bytsp = bp;
4126 /* Allocate the index array. */
4127 ip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE);
4128 if (ip == NULL)
4129 return SP_OTHERERROR;
4130 *idxsp = ip;
4132 /* Recursively read the tree and store it in the array. */
4133 idx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt);
4134 if (idx < 0)
4135 return idx;
4137 return 0;
4141 * Read one row of siblings from the spell file and store it in the byte array
4142 * "byts" and index array "idxs". Recursively read the children.
4144 * NOTE: The code here must match put_node()!
4146 * Returns the index (>= 0) following the siblings.
4147 * Returns SP_TRUNCERROR if the file is shorter than expected.
4148 * Returns SP_FORMERROR if there is a format error.
4150 static idx_T
4151 read_tree_node(fd, byts, idxs, maxidx, startidx, prefixtree, maxprefcondnr)
4152 FILE *fd;
4153 char_u *byts;
4154 idx_T *idxs;
4155 int maxidx; /* size of arrays */
4156 idx_T startidx; /* current index in "byts" and "idxs" */
4157 int prefixtree; /* TRUE for reading PREFIXTREE */
4158 int maxprefcondnr; /* maximum for <prefcondnr> */
4160 int len;
4161 int i;
4162 int n;
4163 idx_T idx = startidx;
4164 int c;
4165 int c2;
4166 #define SHARED_MASK 0x8000000
4168 len = getc(fd); /* <siblingcount> */
4169 if (len <= 0)
4170 return SP_TRUNCERROR;
4172 if (startidx + len >= maxidx)
4173 return SP_FORMERROR;
4174 byts[idx++] = len;
4176 /* Read the byte values, flag/region bytes and shared indexes. */
4177 for (i = 1; i <= len; ++i)
4179 c = getc(fd); /* <byte> */
4180 if (c < 0)
4181 return SP_TRUNCERROR;
4182 if (c <= BY_SPECIAL)
4184 if (c == BY_NOFLAGS && !prefixtree)
4186 /* No flags, all regions. */
4187 idxs[idx] = 0;
4188 c = 0;
4190 else if (c != BY_INDEX)
4192 if (prefixtree)
4194 /* Read the optional pflags byte, the prefix ID and the
4195 * condition nr. In idxs[] store the prefix ID in the low
4196 * byte, the condition index shifted up 8 bits, the flags
4197 * shifted up 24 bits. */
4198 if (c == BY_FLAGS)
4199 c = getc(fd) << 24; /* <pflags> */
4200 else
4201 c = 0;
4203 c |= getc(fd); /* <affixID> */
4205 n = get2c(fd); /* <prefcondnr> */
4206 if (n >= maxprefcondnr)
4207 return SP_FORMERROR;
4208 c |= (n << 8);
4210 else /* c must be BY_FLAGS or BY_FLAGS2 */
4212 /* Read flags and optional region and prefix ID. In
4213 * idxs[] the flags go in the low two bytes, region above
4214 * that and prefix ID above the region. */
4215 c2 = c;
4216 c = getc(fd); /* <flags> */
4217 if (c2 == BY_FLAGS2)
4218 c = (getc(fd) << 8) + c; /* <flags2> */
4219 if (c & WF_REGION)
4220 c = (getc(fd) << 16) + c; /* <region> */
4221 if (c & WF_AFX)
4222 c = (getc(fd) << 24) + c; /* <affixID> */
4225 idxs[idx] = c;
4226 c = 0;
4228 else /* c == BY_INDEX */
4230 /* <nodeidx> */
4231 n = get3c(fd);
4232 if (n < 0 || n >= maxidx)
4233 return SP_FORMERROR;
4234 idxs[idx] = n + SHARED_MASK;
4235 c = getc(fd); /* <xbyte> */
4238 byts[idx++] = c;
4241 /* Recursively read the children for non-shared siblings.
4242 * Skip the end-of-word ones (zero byte value) and the shared ones (and
4243 * remove SHARED_MASK) */
4244 for (i = 1; i <= len; ++i)
4245 if (byts[startidx + i] != 0)
4247 if (idxs[startidx + i] & SHARED_MASK)
4248 idxs[startidx + i] &= ~SHARED_MASK;
4249 else
4251 idxs[startidx + i] = idx;
4252 idx = read_tree_node(fd, byts, idxs, maxidx, idx,
4253 prefixtree, maxprefcondnr);
4254 if (idx < 0)
4255 break;
4259 return idx;
4263 * Parse 'spelllang' and set buf->b_langp accordingly.
4264 * Returns NULL if it's OK, an error message otherwise.
4266 char_u *
4267 did_set_spelllang(buf)
4268 buf_T *buf;
4270 garray_T ga;
4271 char_u *splp;
4272 char_u *region;
4273 char_u region_cp[3];
4274 int filename;
4275 int region_mask;
4276 slang_T *slang;
4277 int c;
4278 char_u lang[MAXWLEN + 1];
4279 char_u spf_name[MAXPATHL];
4280 int len;
4281 char_u *p;
4282 int round;
4283 char_u *spf;
4284 char_u *use_region = NULL;
4285 int dont_use_region = FALSE;
4286 int nobreak = FALSE;
4287 int i, j;
4288 langp_T *lp, *lp2;
4289 static int recursive = FALSE;
4290 char_u *ret_msg = NULL;
4291 char_u *spl_copy;
4293 /* We don't want to do this recursively. May happen when a language is
4294 * not available and the SpellFileMissing autocommand opens a new buffer
4295 * in which 'spell' is set. */
4296 if (recursive)
4297 return NULL;
4298 recursive = TRUE;
4300 ga_init2(&ga, sizeof(langp_T), 2);
4301 clear_midword(buf);
4303 /* Make a copy of 'spellang', the SpellFileMissing autocommands may change
4304 * it under our fingers. */
4305 spl_copy = vim_strsave(buf->b_p_spl);
4306 if (spl_copy == NULL)
4307 goto theend;
4309 /* loop over comma separated language names. */
4310 for (splp = spl_copy; *splp != NUL; )
4312 /* Get one language name. */
4313 copy_option_part(&splp, lang, MAXWLEN, ",");
4315 region = NULL;
4316 len = (int)STRLEN(lang);
4318 /* If the name ends in ".spl" use it as the name of the spell file.
4319 * If there is a region name let "region" point to it and remove it
4320 * from the name. */
4321 if (len > 4 && fnamecmp(lang + len - 4, ".spl") == 0)
4323 filename = TRUE;
4325 /* Locate a region and remove it from the file name. */
4326 p = vim_strchr(gettail(lang), '_');
4327 if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2])
4328 && !ASCII_ISALPHA(p[3]))
4330 vim_strncpy(region_cp, p + 1, 2);
4331 mch_memmove(p, p + 3, len - (p - lang) - 2);
4332 len -= 3;
4333 region = region_cp;
4335 else
4336 dont_use_region = TRUE;
4338 /* Check if we loaded this language before. */
4339 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4340 if (fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME)
4341 break;
4343 else
4345 filename = FALSE;
4346 if (len > 3 && lang[len - 3] == '_')
4348 region = lang + len - 2;
4349 len -= 3;
4350 lang[len] = NUL;
4352 else
4353 dont_use_region = TRUE;
4355 /* Check if we loaded this language before. */
4356 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4357 if (STRICMP(lang, slang->sl_name) == 0)
4358 break;
4361 if (region != NULL)
4363 /* If the region differs from what was used before then don't
4364 * use it for 'spellfile'. */
4365 if (use_region != NULL && STRCMP(region, use_region) != 0)
4366 dont_use_region = TRUE;
4367 use_region = region;
4370 /* If not found try loading the language now. */
4371 if (slang == NULL)
4373 if (filename)
4374 (void)spell_load_file(lang, lang, NULL, FALSE);
4375 else
4377 spell_load_lang(lang);
4378 #ifdef FEAT_AUTOCMD
4379 /* SpellFileMissing autocommands may do anything, including
4380 * destroying the buffer we are using... */
4381 if (!buf_valid(buf))
4383 ret_msg = (char_u *)"E797: SpellFileMissing autocommand deleted buffer";
4384 goto theend;
4386 #endif
4391 * Loop over the languages, there can be several files for "lang".
4393 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4394 if (filename ? fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME
4395 : STRICMP(lang, slang->sl_name) == 0)
4397 region_mask = REGION_ALL;
4398 if (!filename && region != NULL)
4400 /* find region in sl_regions */
4401 c = find_region(slang->sl_regions, region);
4402 if (c == REGION_ALL)
4404 if (slang->sl_add)
4406 if (*slang->sl_regions != NUL)
4407 /* This addition file is for other regions. */
4408 region_mask = 0;
4410 else
4411 /* This is probably an error. Give a warning and
4412 * accept the words anyway. */
4413 smsg((char_u *)
4414 _("Warning: region %s not supported"),
4415 region);
4417 else
4418 region_mask = 1 << c;
4421 if (region_mask != 0)
4423 if (ga_grow(&ga, 1) == FAIL)
4425 ga_clear(&ga);
4426 ret_msg = e_outofmem;
4427 goto theend;
4429 LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;
4430 LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
4431 ++ga.ga_len;
4432 use_midword(slang, buf);
4433 if (slang->sl_nobreak)
4434 nobreak = TRUE;
4439 /* round 0: load int_wordlist, if possible.
4440 * round 1: load first name in 'spellfile'.
4441 * round 2: load second name in 'spellfile.
4442 * etc. */
4443 spf = buf->b_p_spf;
4444 for (round = 0; round == 0 || *spf != NUL; ++round)
4446 if (round == 0)
4448 /* Internal wordlist, if there is one. */
4449 if (int_wordlist == NULL)
4450 continue;
4451 int_wordlist_spl(spf_name);
4453 else
4455 /* One entry in 'spellfile'. */
4456 copy_option_part(&spf, spf_name, MAXPATHL - 5, ",");
4457 STRCAT(spf_name, ".spl");
4459 /* If it was already found above then skip it. */
4460 for (c = 0; c < ga.ga_len; ++c)
4462 p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname;
4463 if (p != NULL && fullpathcmp(spf_name, p, FALSE) == FPC_SAME)
4464 break;
4466 if (c < ga.ga_len)
4467 continue;
4470 /* Check if it was loaded already. */
4471 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4472 if (fullpathcmp(spf_name, slang->sl_fname, FALSE) == FPC_SAME)
4473 break;
4474 if (slang == NULL)
4476 /* Not loaded, try loading it now. The language name includes the
4477 * region name, the region is ignored otherwise. for int_wordlist
4478 * use an arbitrary name. */
4479 if (round == 0)
4480 STRCPY(lang, "internal wordlist");
4481 else
4483 vim_strncpy(lang, gettail(spf_name), MAXWLEN);
4484 p = vim_strchr(lang, '.');
4485 if (p != NULL)
4486 *p = NUL; /* truncate at ".encoding.add" */
4488 slang = spell_load_file(spf_name, lang, NULL, TRUE);
4490 /* If one of the languages has NOBREAK we assume the addition
4491 * files also have this. */
4492 if (slang != NULL && nobreak)
4493 slang->sl_nobreak = TRUE;
4495 if (slang != NULL && ga_grow(&ga, 1) == OK)
4497 region_mask = REGION_ALL;
4498 if (use_region != NULL && !dont_use_region)
4500 /* find region in sl_regions */
4501 c = find_region(slang->sl_regions, use_region);
4502 if (c != REGION_ALL)
4503 region_mask = 1 << c;
4504 else if (*slang->sl_regions != NUL)
4505 /* This spell file is for other regions. */
4506 region_mask = 0;
4509 if (region_mask != 0)
4511 LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;
4512 LANGP_ENTRY(ga, ga.ga_len)->lp_sallang = NULL;
4513 LANGP_ENTRY(ga, ga.ga_len)->lp_replang = NULL;
4514 LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
4515 ++ga.ga_len;
4516 use_midword(slang, buf);
4521 /* Everything is fine, store the new b_langp value. */
4522 ga_clear(&buf->b_langp);
4523 buf->b_langp = ga;
4525 /* For each language figure out what language to use for sound folding and
4526 * REP items. If the language doesn't support it itself use another one
4527 * with the same name. E.g. for "en-math" use "en". */
4528 for (i = 0; i < ga.ga_len; ++i)
4530 lp = LANGP_ENTRY(ga, i);
4532 /* sound folding */
4533 if (lp->lp_slang->sl_sal.ga_len > 0)
4534 /* language does sound folding itself */
4535 lp->lp_sallang = lp->lp_slang;
4536 else
4537 /* find first similar language that does sound folding */
4538 for (j = 0; j < ga.ga_len; ++j)
4540 lp2 = LANGP_ENTRY(ga, j);
4541 if (lp2->lp_slang->sl_sal.ga_len > 0
4542 && STRNCMP(lp->lp_slang->sl_name,
4543 lp2->lp_slang->sl_name, 2) == 0)
4545 lp->lp_sallang = lp2->lp_slang;
4546 break;
4550 /* REP items */
4551 if (lp->lp_slang->sl_rep.ga_len > 0)
4552 /* language has REP items itself */
4553 lp->lp_replang = lp->lp_slang;
4554 else
4555 /* find first similar language that has REP items */
4556 for (j = 0; j < ga.ga_len; ++j)
4558 lp2 = LANGP_ENTRY(ga, j);
4559 if (lp2->lp_slang->sl_rep.ga_len > 0
4560 && STRNCMP(lp->lp_slang->sl_name,
4561 lp2->lp_slang->sl_name, 2) == 0)
4563 lp->lp_replang = lp2->lp_slang;
4564 break;
4569 theend:
4570 vim_free(spl_copy);
4571 recursive = FALSE;
4572 return ret_msg;
4576 * Clear the midword characters for buffer "buf".
4578 static void
4579 clear_midword(buf)
4580 buf_T *buf;
4582 vim_memset(buf->b_spell_ismw, 0, 256);
4583 #ifdef FEAT_MBYTE
4584 vim_free(buf->b_spell_ismw_mb);
4585 buf->b_spell_ismw_mb = NULL;
4586 #endif
4590 * Use the "sl_midword" field of language "lp" for buffer "buf".
4591 * They add up to any currently used midword characters.
4593 static void
4594 use_midword(lp, buf)
4595 slang_T *lp;
4596 buf_T *buf;
4598 char_u *p;
4600 if (lp->sl_midword == NULL) /* there aren't any */
4601 return;
4603 for (p = lp->sl_midword; *p != NUL; )
4604 #ifdef FEAT_MBYTE
4605 if (has_mbyte)
4607 int c, l, n;
4608 char_u *bp;
4610 c = mb_ptr2char(p);
4611 l = (*mb_ptr2len)(p);
4612 if (c < 256 && l <= 2)
4613 buf->b_spell_ismw[c] = TRUE;
4614 else if (buf->b_spell_ismw_mb == NULL)
4615 /* First multi-byte char in "b_spell_ismw_mb". */
4616 buf->b_spell_ismw_mb = vim_strnsave(p, l);
4617 else
4619 /* Append multi-byte chars to "b_spell_ismw_mb". */
4620 n = (int)STRLEN(buf->b_spell_ismw_mb);
4621 bp = vim_strnsave(buf->b_spell_ismw_mb, n + l);
4622 if (bp != NULL)
4624 vim_free(buf->b_spell_ismw_mb);
4625 buf->b_spell_ismw_mb = bp;
4626 vim_strncpy(bp + n, p, l);
4629 p += l;
4631 else
4632 #endif
4633 buf->b_spell_ismw[*p++] = TRUE;
4637 * Find the region "region[2]" in "rp" (points to "sl_regions").
4638 * Each region is simply stored as the two characters of it's name.
4639 * Returns the index if found (first is 0), REGION_ALL if not found.
4641 static int
4642 find_region(rp, region)
4643 char_u *rp;
4644 char_u *region;
4646 int i;
4648 for (i = 0; ; i += 2)
4650 if (rp[i] == NUL)
4651 return REGION_ALL;
4652 if (rp[i] == region[0] && rp[i + 1] == region[1])
4653 break;
4655 return i / 2;
4659 * Return case type of word:
4660 * w word 0
4661 * Word WF_ONECAP
4662 * W WORD WF_ALLCAP
4663 * WoRd wOrd WF_KEEPCAP
4665 static int
4666 captype(word, end)
4667 char_u *word;
4668 char_u *end; /* When NULL use up to NUL byte. */
4670 char_u *p;
4671 int c;
4672 int firstcap;
4673 int allcap;
4674 int past_second = FALSE; /* past second word char */
4676 /* find first letter */
4677 for (p = word; !spell_iswordp_nmw(p); mb_ptr_adv(p))
4678 if (end == NULL ? *p == NUL : p >= end)
4679 return 0; /* only non-word characters, illegal word */
4680 #ifdef FEAT_MBYTE
4681 if (has_mbyte)
4682 c = mb_ptr2char_adv(&p);
4683 else
4684 #endif
4685 c = *p++;
4686 firstcap = allcap = SPELL_ISUPPER(c);
4689 * Need to check all letters to find a word with mixed upper/lower.
4690 * But a word with an upper char only at start is a ONECAP.
4692 for ( ; end == NULL ? *p != NUL : p < end; mb_ptr_adv(p))
4693 if (spell_iswordp_nmw(p))
4695 c = PTR2CHAR(p);
4696 if (!SPELL_ISUPPER(c))
4698 /* UUl -> KEEPCAP */
4699 if (past_second && allcap)
4700 return WF_KEEPCAP;
4701 allcap = FALSE;
4703 else if (!allcap)
4704 /* UlU -> KEEPCAP */
4705 return WF_KEEPCAP;
4706 past_second = TRUE;
4709 if (allcap)
4710 return WF_ALLCAP;
4711 if (firstcap)
4712 return WF_ONECAP;
4713 return 0;
4717 * Like captype() but for a KEEPCAP word add ONECAP if the word starts with a
4718 * capital. So that make_case_word() can turn WOrd into Word.
4719 * Add ALLCAP for "WOrD".
4721 static int
4722 badword_captype(word, end)
4723 char_u *word;
4724 char_u *end;
4726 int flags = captype(word, end);
4727 int c;
4728 int l, u;
4729 int first;
4730 char_u *p;
4732 if (flags & WF_KEEPCAP)
4734 /* Count the number of UPPER and lower case letters. */
4735 l = u = 0;
4736 first = FALSE;
4737 for (p = word; p < end; mb_ptr_adv(p))
4739 c = PTR2CHAR(p);
4740 if (SPELL_ISUPPER(c))
4742 ++u;
4743 if (p == word)
4744 first = TRUE;
4746 else
4747 ++l;
4750 /* If there are more UPPER than lower case letters suggest an
4751 * ALLCAP word. Otherwise, if the first letter is UPPER then
4752 * suggest ONECAP. Exception: "ALl" most likely should be "All",
4753 * require three upper case letters. */
4754 if (u > l && u > 2)
4755 flags |= WF_ALLCAP;
4756 else if (first)
4757 flags |= WF_ONECAP;
4759 if (u >= 2 && l >= 2) /* maCARONI maCAroni */
4760 flags |= WF_MIXCAP;
4762 return flags;
4765 # if defined(FEAT_MBYTE) || defined(EXITFREE) || defined(PROTO)
4767 * Free all languages.
4769 void
4770 spell_free_all()
4772 slang_T *slang;
4773 buf_T *buf;
4774 char_u fname[MAXPATHL];
4776 /* Go through all buffers and handle 'spelllang'. */
4777 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
4778 ga_clear(&buf->b_langp);
4780 while (first_lang != NULL)
4782 slang = first_lang;
4783 first_lang = slang->sl_next;
4784 slang_free(slang);
4787 if (int_wordlist != NULL)
4789 /* Delete the internal wordlist and its .spl file */
4790 mch_remove(int_wordlist);
4791 int_wordlist_spl(fname);
4792 mch_remove(fname);
4793 vim_free(int_wordlist);
4794 int_wordlist = NULL;
4797 init_spell_chartab();
4799 vim_free(repl_to);
4800 repl_to = NULL;
4801 vim_free(repl_from);
4802 repl_from = NULL;
4804 # endif
4806 # if defined(FEAT_MBYTE) || defined(PROTO)
4808 * Clear all spelling tables and reload them.
4809 * Used after 'encoding' is set and when ":mkspell" was used.
4811 void
4812 spell_reload()
4814 buf_T *buf;
4815 win_T *wp;
4817 /* Initialize the table for spell_iswordp(). */
4818 init_spell_chartab();
4820 /* Unload all allocated memory. */
4821 spell_free_all();
4823 /* Go through all buffers and handle 'spelllang'. */
4824 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
4826 /* Only load the wordlists when 'spelllang' is set and there is a
4827 * window for this buffer in which 'spell' is set. */
4828 if (*buf->b_p_spl != NUL)
4830 FOR_ALL_WINDOWS(wp)
4831 if (wp->w_buffer == buf && wp->w_p_spell)
4833 (void)did_set_spelllang(buf);
4834 # ifdef FEAT_WINDOWS
4835 break;
4836 # endif
4841 # endif
4844 * Reload the spell file "fname" if it's loaded.
4846 static void
4847 spell_reload_one(fname, added_word)
4848 char_u *fname;
4849 int added_word; /* invoked through "zg" */
4851 slang_T *slang;
4852 int didit = FALSE;
4854 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4856 if (fullpathcmp(fname, slang->sl_fname, FALSE) == FPC_SAME)
4858 slang_clear(slang);
4859 if (spell_load_file(fname, NULL, slang, FALSE) == NULL)
4860 /* reloading failed, clear the language */
4861 slang_clear(slang);
4862 redraw_all_later(SOME_VALID);
4863 didit = TRUE;
4867 /* When "zg" was used and the file wasn't loaded yet, should redo
4868 * 'spelllang' to load it now. */
4869 if (added_word && !didit)
4870 did_set_spelllang(curbuf);
4875 * Functions for ":mkspell".
4878 #define MAXLINELEN 500 /* Maximum length in bytes of a line in a .aff
4879 and .dic file. */
4881 * Main structure to store the contents of a ".aff" file.
4883 typedef struct afffile_S
4885 char_u *af_enc; /* "SET", normalized, alloc'ed string or NULL */
4886 int af_flagtype; /* AFT_CHAR, AFT_LONG, AFT_NUM or AFT_CAPLONG */
4887 unsigned af_rare; /* RARE ID for rare word */
4888 unsigned af_keepcase; /* KEEPCASE ID for keep-case word */
4889 unsigned af_bad; /* BAD ID for banned word */
4890 unsigned af_needaffix; /* NEEDAFFIX ID */
4891 unsigned af_circumfix; /* CIRCUMFIX ID */
4892 unsigned af_needcomp; /* NEEDCOMPOUND ID */
4893 unsigned af_comproot; /* COMPOUNDROOT ID */
4894 unsigned af_compforbid; /* COMPOUNDFORBIDFLAG ID */
4895 unsigned af_comppermit; /* COMPOUNDPERMITFLAG ID */
4896 unsigned af_nosuggest; /* NOSUGGEST ID */
4897 int af_pfxpostpone; /* postpone prefixes without chop string and
4898 without flags */
4899 hashtab_T af_pref; /* hashtable for prefixes, affheader_T */
4900 hashtab_T af_suff; /* hashtable for suffixes, affheader_T */
4901 hashtab_T af_comp; /* hashtable for compound flags, compitem_T */
4902 } afffile_T;
4904 #define AFT_CHAR 0 /* flags are one character */
4905 #define AFT_LONG 1 /* flags are two characters */
4906 #define AFT_CAPLONG 2 /* flags are one or two characters */
4907 #define AFT_NUM 3 /* flags are numbers, comma separated */
4909 typedef struct affentry_S affentry_T;
4910 /* Affix entry from ".aff" file. Used for prefixes and suffixes. */
4911 struct affentry_S
4913 affentry_T *ae_next; /* next affix with same name/number */
4914 char_u *ae_chop; /* text to chop off basic word (can be NULL) */
4915 char_u *ae_add; /* text to add to basic word (can be NULL) */
4916 char_u *ae_flags; /* flags on the affix (can be NULL) */
4917 char_u *ae_cond; /* condition (NULL for ".") */
4918 regprog_T *ae_prog; /* regexp program for ae_cond or NULL */
4919 char ae_compforbid; /* COMPOUNDFORBIDFLAG found */
4920 char ae_comppermit; /* COMPOUNDPERMITFLAG found */
4923 #ifdef FEAT_MBYTE
4924 # define AH_KEY_LEN 17 /* 2 x 8 bytes + NUL */
4925 #else
4926 # define AH_KEY_LEN 7 /* 6 digits + NUL */
4927 #endif
4929 /* Affix header from ".aff" file. Used for af_pref and af_suff. */
4930 typedef struct affheader_S
4932 char_u ah_key[AH_KEY_LEN]; /* key for hashtab == name of affix */
4933 unsigned ah_flag; /* affix name as number, uses "af_flagtype" */
4934 int ah_newID; /* prefix ID after renumbering; 0 if not used */
4935 int ah_combine; /* suffix may combine with prefix */
4936 int ah_follows; /* another affix block should be following */
4937 affentry_T *ah_first; /* first affix entry */
4938 } affheader_T;
4940 #define HI2AH(hi) ((affheader_T *)(hi)->hi_key)
4942 /* Flag used in compound items. */
4943 typedef struct compitem_S
4945 char_u ci_key[AH_KEY_LEN]; /* key for hashtab == name of compound */
4946 unsigned ci_flag; /* affix name as number, uses "af_flagtype" */
4947 int ci_newID; /* affix ID after renumbering. */
4948 } compitem_T;
4950 #define HI2CI(hi) ((compitem_T *)(hi)->hi_key)
4953 * Structure that is used to store the items in the word tree. This avoids
4954 * the need to keep track of each allocated thing, everything is freed all at
4955 * once after ":mkspell" is done.
4956 * Note: "sb_next" must be just before "sb_data" to make sure the alignment of
4957 * "sb_data" is correct for systems where pointers must be aligned on
4958 * pointer-size boundaries and sizeof(pointer) > sizeof(int) (e.g., Sparc).
4960 #define SBLOCKSIZE 16000 /* size of sb_data */
4961 typedef struct sblock_S sblock_T;
4962 struct sblock_S
4964 int sb_used; /* nr of bytes already in use */
4965 sblock_T *sb_next; /* next block in list */
4966 char_u sb_data[1]; /* data, actually longer */
4970 * A node in the tree.
4972 typedef struct wordnode_S wordnode_T;
4973 struct wordnode_S
4975 union /* shared to save space */
4977 char_u hashkey[6]; /* the hash key, only used while compressing */
4978 int index; /* index in written nodes (valid after first
4979 round) */
4980 } wn_u1;
4981 union /* shared to save space */
4983 wordnode_T *next; /* next node with same hash key */
4984 wordnode_T *wnode; /* parent node that will write this node */
4985 } wn_u2;
4986 wordnode_T *wn_child; /* child (next byte in word) */
4987 wordnode_T *wn_sibling; /* next sibling (alternate byte in word,
4988 always sorted) */
4989 int wn_refs; /* Nr. of references to this node. Only
4990 relevant for first node in a list of
4991 siblings, in following siblings it is
4992 always one. */
4993 char_u wn_byte; /* Byte for this node. NUL for word end */
4995 /* Info for when "wn_byte" is NUL.
4996 * In PREFIXTREE "wn_region" is used for the prefcondnr.
4997 * In the soundfolded word tree "wn_flags" has the MSW of the wordnr and
4998 * "wn_region" the LSW of the wordnr. */
4999 char_u wn_affixID; /* supported/required prefix ID or 0 */
5000 short_u wn_flags; /* WF_ flags */
5001 short wn_region; /* region mask */
5003 #ifdef SPELL_PRINTTREE
5004 int wn_nr; /* sequence nr for printing */
5005 #endif
5008 #define WN_MASK 0xffff /* mask relevant bits of "wn_flags" */
5010 #define HI2WN(hi) (wordnode_T *)((hi)->hi_key)
5013 * Info used while reading the spell files.
5015 typedef struct spellinfo_S
5017 wordnode_T *si_foldroot; /* tree with case-folded words */
5018 long si_foldwcount; /* nr of words in si_foldroot */
5020 wordnode_T *si_keeproot; /* tree with keep-case words */
5021 long si_keepwcount; /* nr of words in si_keeproot */
5023 wordnode_T *si_prefroot; /* tree with postponed prefixes */
5025 long si_sugtree; /* creating the soundfolding trie */
5027 sblock_T *si_blocks; /* memory blocks used */
5028 long si_blocks_cnt; /* memory blocks allocated */
5029 long si_compress_cnt; /* words to add before lowering
5030 compression limit */
5031 wordnode_T *si_first_free; /* List of nodes that have been freed during
5032 compression, linked by "wn_child" field. */
5033 long si_free_count; /* number of nodes in si_first_free */
5034 #ifdef SPELL_PRINTTREE
5035 int si_wordnode_nr; /* sequence nr for nodes */
5036 #endif
5037 buf_T *si_spellbuf; /* buffer used to store soundfold word table */
5039 int si_ascii; /* handling only ASCII words */
5040 int si_add; /* addition file */
5041 int si_clear_chartab; /* when TRUE clear char tables */
5042 int si_region; /* region mask */
5043 vimconv_T si_conv; /* for conversion to 'encoding' */
5044 int si_memtot; /* runtime memory used */
5045 int si_verbose; /* verbose messages */
5046 int si_msg_count; /* number of words added since last message */
5047 char_u *si_info; /* info text chars or NULL */
5048 int si_region_count; /* number of regions supported (1 when there
5049 are no regions) */
5050 char_u si_region_name[16]; /* region names; used only if
5051 * si_region_count > 1) */
5053 garray_T si_rep; /* list of fromto_T entries from REP lines */
5054 garray_T si_repsal; /* list of fromto_T entries from REPSAL lines */
5055 garray_T si_sal; /* list of fromto_T entries from SAL lines */
5056 char_u *si_sofofr; /* SOFOFROM text */
5057 char_u *si_sofoto; /* SOFOTO text */
5058 int si_nosugfile; /* NOSUGFILE item found */
5059 int si_nosplitsugs; /* NOSPLITSUGS item found */
5060 int si_followup; /* soundsalike: ? */
5061 int si_collapse; /* soundsalike: ? */
5062 hashtab_T si_commonwords; /* hashtable for common words */
5063 time_t si_sugtime; /* timestamp for .sug file */
5064 int si_rem_accents; /* soundsalike: remove accents */
5065 garray_T si_map; /* MAP info concatenated */
5066 char_u *si_midword; /* MIDWORD chars or NULL */
5067 int si_compmax; /* max nr of words for compounding */
5068 int si_compminlen; /* minimal length for compounding */
5069 int si_compsylmax; /* max nr of syllables for compounding */
5070 int si_compoptions; /* COMP_ flags */
5071 garray_T si_comppat; /* CHECKCOMPOUNDPATTERN items, each stored as
5072 a string */
5073 char_u *si_compflags; /* flags used for compounding */
5074 char_u si_nobreak; /* NOBREAK */
5075 char_u *si_syllable; /* syllable string */
5076 garray_T si_prefcond; /* table with conditions for postponed
5077 * prefixes, each stored as a string */
5078 int si_newprefID; /* current value for ah_newID */
5079 int si_newcompID; /* current value for compound ID */
5080 } spellinfo_T;
5082 static afffile_T *spell_read_aff __ARGS((spellinfo_T *spin, char_u *fname));
5083 static int is_aff_rule __ARGS((char_u **items, int itemcnt, char *rulename, int mincount));
5084 static void aff_process_flags __ARGS((afffile_T *affile, affentry_T *entry));
5085 static int spell_info_item __ARGS((char_u *s));
5086 static unsigned affitem2flag __ARGS((int flagtype, char_u *item, char_u *fname, int lnum));
5087 static unsigned get_affitem __ARGS((int flagtype, char_u **pp));
5088 static void process_compflags __ARGS((spellinfo_T *spin, afffile_T *aff, char_u *compflags));
5089 static void check_renumber __ARGS((spellinfo_T *spin));
5090 static int flag_in_afflist __ARGS((int flagtype, char_u *afflist, unsigned flag));
5091 static void aff_check_number __ARGS((int spinval, int affval, char *name));
5092 static void aff_check_string __ARGS((char_u *spinval, char_u *affval, char *name));
5093 static int str_equal __ARGS((char_u *s1, char_u *s2));
5094 static void add_fromto __ARGS((spellinfo_T *spin, garray_T *gap, char_u *from, char_u *to));
5095 static int sal_to_bool __ARGS((char_u *s));
5096 static int has_non_ascii __ARGS((char_u *s));
5097 static void spell_free_aff __ARGS((afffile_T *aff));
5098 static int spell_read_dic __ARGS((spellinfo_T *spin, char_u *fname, afffile_T *affile));
5099 static int get_affix_flags __ARGS((afffile_T *affile, char_u *afflist));
5100 static int get_pfxlist __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist));
5101 static void get_compflags __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist));
5102 static int store_aff_word __ARGS((spellinfo_T *spin, char_u *word, char_u *afflist, afffile_T *affile, hashtab_T *ht, hashtab_T *xht, int condit, int flags, char_u *pfxlist, int pfxlen));
5103 static int spell_read_wordfile __ARGS((spellinfo_T *spin, char_u *fname));
5104 static void *getroom __ARGS((spellinfo_T *spin, size_t len, int align));
5105 static char_u *getroom_save __ARGS((spellinfo_T *spin, char_u *s));
5106 static void free_blocks __ARGS((sblock_T *bl));
5107 static wordnode_T *wordtree_alloc __ARGS((spellinfo_T *spin));
5108 static int store_word __ARGS((spellinfo_T *spin, char_u *word, int flags, int region, char_u *pfxlist, int need_affix));
5109 static int tree_add_word __ARGS((spellinfo_T *spin, char_u *word, wordnode_T *tree, int flags, int region, int affixID));
5110 static wordnode_T *get_wordnode __ARGS((spellinfo_T *spin));
5111 static int deref_wordnode __ARGS((spellinfo_T *spin, wordnode_T *node));
5112 static void free_wordnode __ARGS((spellinfo_T *spin, wordnode_T *n));
5113 static void wordtree_compress __ARGS((spellinfo_T *spin, wordnode_T *root));
5114 static int node_compress __ARGS((spellinfo_T *spin, wordnode_T *node, hashtab_T *ht, int *tot));
5115 static int node_equal __ARGS((wordnode_T *n1, wordnode_T *n2));
5116 static void put_sugtime __ARGS((spellinfo_T *spin, FILE *fd));
5117 static int write_vim_spell __ARGS((spellinfo_T *spin, char_u *fname));
5118 static void clear_node __ARGS((wordnode_T *node));
5119 static int put_node __ARGS((FILE *fd, wordnode_T *node, int idx, int regionmask, int prefixtree));
5120 static void spell_make_sugfile __ARGS((spellinfo_T *spin, char_u *wfname));
5121 static int sug_filltree __ARGS((spellinfo_T *spin, slang_T *slang));
5122 static int sug_maketable __ARGS((spellinfo_T *spin));
5123 static int sug_filltable __ARGS((spellinfo_T *spin, wordnode_T *node, int startwordnr, garray_T *gap));
5124 static int offset2bytes __ARGS((int nr, char_u *buf));
5125 static int bytes2offset __ARGS((char_u **pp));
5126 static void sug_write __ARGS((spellinfo_T *spin, char_u *fname));
5127 static void mkspell __ARGS((int fcount, char_u **fnames, int ascii, int overwrite, int added_word));
5128 static void spell_message __ARGS((spellinfo_T *spin, char_u *str));
5129 static void init_spellfile __ARGS((void));
5131 /* In the postponed prefixes tree wn_flags is used to store the WFP_ flags,
5132 * but it must be negative to indicate the prefix tree to tree_add_word().
5133 * Use a negative number with the lower 8 bits zero. */
5134 #define PFX_FLAGS -256
5136 /* flags for "condit" argument of store_aff_word() */
5137 #define CONDIT_COMB 1 /* affix must combine */
5138 #define CONDIT_CFIX 2 /* affix must have CIRCUMFIX flag */
5139 #define CONDIT_SUF 4 /* add a suffix for matching flags */
5140 #define CONDIT_AFF 8 /* word already has an affix */
5143 * Tunable parameters for when the tree is compressed. See 'mkspellmem'.
5145 static long compress_start = 30000; /* memory / SBLOCKSIZE */
5146 static long compress_inc = 100; /* memory / SBLOCKSIZE */
5147 static long compress_added = 500000; /* word count */
5149 #ifdef SPELL_PRINTTREE
5151 * For debugging the tree code: print the current tree in a (more or less)
5152 * readable format, so that we can see what happens when adding a word and/or
5153 * compressing the tree.
5154 * Based on code from Olaf Seibert.
5156 #define PRINTLINESIZE 1000
5157 #define PRINTWIDTH 6
5159 #define PRINTSOME(l, depth, fmt, a1, a2) vim_snprintf(l + depth * PRINTWIDTH, \
5160 PRINTLINESIZE - PRINTWIDTH * depth, fmt, a1, a2)
5162 static char line1[PRINTLINESIZE];
5163 static char line2[PRINTLINESIZE];
5164 static char line3[PRINTLINESIZE];
5166 static void
5167 spell_clear_flags(wordnode_T *node)
5169 wordnode_T *np;
5171 for (np = node; np != NULL; np = np->wn_sibling)
5173 np->wn_u1.index = FALSE;
5174 spell_clear_flags(np->wn_child);
5178 static void
5179 spell_print_node(wordnode_T *node, int depth)
5181 if (node->wn_u1.index)
5183 /* Done this node before, print the reference. */
5184 PRINTSOME(line1, depth, "(%d)", node->wn_nr, 0);
5185 PRINTSOME(line2, depth, " ", 0, 0);
5186 PRINTSOME(line3, depth, " ", 0, 0);
5187 msg(line1);
5188 msg(line2);
5189 msg(line3);
5191 else
5193 node->wn_u1.index = TRUE;
5195 if (node->wn_byte != NUL)
5197 if (node->wn_child != NULL)
5198 PRINTSOME(line1, depth, " %c -> ", node->wn_byte, 0);
5199 else
5200 /* Cannot happen? */
5201 PRINTSOME(line1, depth, " %c ???", node->wn_byte, 0);
5203 else
5204 PRINTSOME(line1, depth, " $ ", 0, 0);
5206 PRINTSOME(line2, depth, "%d/%d ", node->wn_nr, node->wn_refs);
5208 if (node->wn_sibling != NULL)
5209 PRINTSOME(line3, depth, " | ", 0, 0);
5210 else
5211 PRINTSOME(line3, depth, " ", 0, 0);
5213 if (node->wn_byte == NUL)
5215 msg(line1);
5216 msg(line2);
5217 msg(line3);
5220 /* do the children */
5221 if (node->wn_byte != NUL && node->wn_child != NULL)
5222 spell_print_node(node->wn_child, depth + 1);
5224 /* do the siblings */
5225 if (node->wn_sibling != NULL)
5227 /* get rid of all parent details except | */
5228 STRCPY(line1, line3);
5229 STRCPY(line2, line3);
5230 spell_print_node(node->wn_sibling, depth);
5235 static void
5236 spell_print_tree(wordnode_T *root)
5238 if (root != NULL)
5240 /* Clear the "wn_u1.index" fields, used to remember what has been
5241 * done. */
5242 spell_clear_flags(root);
5244 /* Recursively print the tree. */
5245 spell_print_node(root, 0);
5248 #endif /* SPELL_PRINTTREE */
5251 * Read the affix file "fname".
5252 * Returns an afffile_T, NULL for complete failure.
5254 static afffile_T *
5255 spell_read_aff(spin, fname)
5256 spellinfo_T *spin;
5257 char_u *fname;
5259 FILE *fd;
5260 afffile_T *aff;
5261 char_u rline[MAXLINELEN];
5262 char_u *line;
5263 char_u *pc = NULL;
5264 #define MAXITEMCNT 30
5265 char_u *(items[MAXITEMCNT]);
5266 int itemcnt;
5267 char_u *p;
5268 int lnum = 0;
5269 affheader_T *cur_aff = NULL;
5270 int did_postpone_prefix = FALSE;
5271 int aff_todo = 0;
5272 hashtab_T *tp;
5273 char_u *low = NULL;
5274 char_u *fol = NULL;
5275 char_u *upp = NULL;
5276 int do_rep;
5277 int do_repsal;
5278 int do_sal;
5279 int do_mapline;
5280 int found_map = FALSE;
5281 hashitem_T *hi;
5282 int l;
5283 int compminlen = 0; /* COMPOUNDMIN value */
5284 int compsylmax = 0; /* COMPOUNDSYLMAX value */
5285 int compoptions = 0; /* COMP_ flags */
5286 int compmax = 0; /* COMPOUNDWORDMAX value */
5287 char_u *compflags = NULL; /* COMPOUNDFLAG and COMPOUNDRULE
5288 concatenated */
5289 char_u *midword = NULL; /* MIDWORD value */
5290 char_u *syllable = NULL; /* SYLLABLE value */
5291 char_u *sofofrom = NULL; /* SOFOFROM value */
5292 char_u *sofoto = NULL; /* SOFOTO value */
5295 * Open the file.
5297 fd = mch_fopen((char *)fname, "r");
5298 if (fd == NULL)
5300 EMSG2(_(e_notopen), fname);
5301 return NULL;
5304 vim_snprintf((char *)IObuff, IOSIZE, _("Reading affix file %s ..."), fname);
5305 spell_message(spin, IObuff);
5307 /* Only do REP lines when not done in another .aff file already. */
5308 do_rep = spin->si_rep.ga_len == 0;
5310 /* Only do REPSAL lines when not done in another .aff file already. */
5311 do_repsal = spin->si_repsal.ga_len == 0;
5313 /* Only do SAL lines when not done in another .aff file already. */
5314 do_sal = spin->si_sal.ga_len == 0;
5316 /* Only do MAP lines when not done in another .aff file already. */
5317 do_mapline = spin->si_map.ga_len == 0;
5320 * Allocate and init the afffile_T structure.
5322 aff = (afffile_T *)getroom(spin, sizeof(afffile_T), TRUE);
5323 if (aff == NULL)
5325 fclose(fd);
5326 return NULL;
5328 hash_init(&aff->af_pref);
5329 hash_init(&aff->af_suff);
5330 hash_init(&aff->af_comp);
5333 * Read all the lines in the file one by one.
5335 while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
5337 line_breakcheck();
5338 ++lnum;
5340 /* Skip comment lines. */
5341 if (*rline == '#')
5342 continue;
5344 /* Convert from "SET" to 'encoding' when needed. */
5345 vim_free(pc);
5346 #ifdef FEAT_MBYTE
5347 if (spin->si_conv.vc_type != CONV_NONE)
5349 pc = string_convert(&spin->si_conv, rline, NULL);
5350 if (pc == NULL)
5352 smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
5353 fname, lnum, rline);
5354 continue;
5356 line = pc;
5358 else
5359 #endif
5361 pc = NULL;
5362 line = rline;
5365 /* Split the line up in white separated items. Put a NUL after each
5366 * item. */
5367 itemcnt = 0;
5368 for (p = line; ; )
5370 while (*p != NUL && *p <= ' ') /* skip white space and CR/NL */
5371 ++p;
5372 if (*p == NUL)
5373 break;
5374 if (itemcnt == MAXITEMCNT) /* too many items */
5375 break;
5376 items[itemcnt++] = p;
5377 /* A few items have arbitrary text argument, don't split them. */
5378 if (itemcnt == 2 && spell_info_item(items[0]))
5379 while (*p >= ' ' || *p == TAB) /* skip until CR/NL */
5380 ++p;
5381 else
5382 while (*p > ' ') /* skip until white space or CR/NL */
5383 ++p;
5384 if (*p == NUL)
5385 break;
5386 *p++ = NUL;
5389 /* Handle non-empty lines. */
5390 if (itemcnt > 0)
5392 if (is_aff_rule(items, itemcnt, "SET", 2) && aff->af_enc == NULL)
5394 #ifdef FEAT_MBYTE
5395 /* Setup for conversion from "ENC" to 'encoding'. */
5396 aff->af_enc = enc_canonize(items[1]);
5397 if (aff->af_enc != NULL && !spin->si_ascii
5398 && convert_setup(&spin->si_conv, aff->af_enc,
5399 p_enc) == FAIL)
5400 smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
5401 fname, aff->af_enc, p_enc);
5402 spin->si_conv.vc_fail = TRUE;
5403 #else
5404 smsg((char_u *)_("Conversion in %s not supported"), fname);
5405 #endif
5407 else if (is_aff_rule(items, itemcnt, "FLAG", 2)
5408 && aff->af_flagtype == AFT_CHAR)
5410 if (STRCMP(items[1], "long") == 0)
5411 aff->af_flagtype = AFT_LONG;
5412 else if (STRCMP(items[1], "num") == 0)
5413 aff->af_flagtype = AFT_NUM;
5414 else if (STRCMP(items[1], "caplong") == 0)
5415 aff->af_flagtype = AFT_CAPLONG;
5416 else
5417 smsg((char_u *)_("Invalid value for FLAG in %s line %d: %s"),
5418 fname, lnum, items[1]);
5419 if (aff->af_rare != 0
5420 || aff->af_keepcase != 0
5421 || aff->af_bad != 0
5422 || aff->af_needaffix != 0
5423 || aff->af_circumfix != 0
5424 || aff->af_needcomp != 0
5425 || aff->af_comproot != 0
5426 || aff->af_nosuggest != 0
5427 || compflags != NULL
5428 || aff->af_suff.ht_used > 0
5429 || aff->af_pref.ht_used > 0)
5430 smsg((char_u *)_("FLAG after using flags in %s line %d: %s"),
5431 fname, lnum, items[1]);
5433 else if (spell_info_item(items[0]))
5435 p = (char_u *)getroom(spin,
5436 (spin->si_info == NULL ? 0 : STRLEN(spin->si_info))
5437 + STRLEN(items[0])
5438 + STRLEN(items[1]) + 3, FALSE);
5439 if (p != NULL)
5441 if (spin->si_info != NULL)
5443 STRCPY(p, spin->si_info);
5444 STRCAT(p, "\n");
5446 STRCAT(p, items[0]);
5447 STRCAT(p, " ");
5448 STRCAT(p, items[1]);
5449 spin->si_info = p;
5452 else if (is_aff_rule(items, itemcnt, "MIDWORD", 2)
5453 && midword == NULL)
5455 midword = getroom_save(spin, items[1]);
5457 else if (is_aff_rule(items, itemcnt, "TRY", 2))
5459 /* ignored, we look in the tree for what chars may appear */
5461 /* TODO: remove "RAR" later */
5462 else if ((is_aff_rule(items, itemcnt, "RAR", 2)
5463 || is_aff_rule(items, itemcnt, "RARE", 2))
5464 && aff->af_rare == 0)
5466 aff->af_rare = affitem2flag(aff->af_flagtype, items[1],
5467 fname, lnum);
5469 /* TODO: remove "KEP" later */
5470 else if ((is_aff_rule(items, itemcnt, "KEP", 2)
5471 || is_aff_rule(items, itemcnt, "KEEPCASE", 2))
5472 && aff->af_keepcase == 0)
5474 aff->af_keepcase = affitem2flag(aff->af_flagtype, items[1],
5475 fname, lnum);
5477 else if ((is_aff_rule(items, itemcnt, "BAD", 2)
5478 || is_aff_rule(items, itemcnt, "FORBIDDENWORD", 2))
5479 && aff->af_bad == 0)
5481 aff->af_bad = affitem2flag(aff->af_flagtype, items[1],
5482 fname, lnum);
5484 else if (is_aff_rule(items, itemcnt, "NEEDAFFIX", 2)
5485 && aff->af_needaffix == 0)
5487 aff->af_needaffix = affitem2flag(aff->af_flagtype, items[1],
5488 fname, lnum);
5490 else if (is_aff_rule(items, itemcnt, "CIRCUMFIX", 2)
5491 && aff->af_circumfix == 0)
5493 aff->af_circumfix = affitem2flag(aff->af_flagtype, items[1],
5494 fname, lnum);
5496 else if (is_aff_rule(items, itemcnt, "NOSUGGEST", 2)
5497 && aff->af_nosuggest == 0)
5499 aff->af_nosuggest = affitem2flag(aff->af_flagtype, items[1],
5500 fname, lnum);
5502 else if ((is_aff_rule(items, itemcnt, "NEEDCOMPOUND", 2)
5503 || is_aff_rule(items, itemcnt, "ONLYINCOMPOUND", 2))
5504 && aff->af_needcomp == 0)
5506 aff->af_needcomp = affitem2flag(aff->af_flagtype, items[1],
5507 fname, lnum);
5509 else if (is_aff_rule(items, itemcnt, "COMPOUNDROOT", 2)
5510 && aff->af_comproot == 0)
5512 aff->af_comproot = affitem2flag(aff->af_flagtype, items[1],
5513 fname, lnum);
5515 else if (is_aff_rule(items, itemcnt, "COMPOUNDFORBIDFLAG", 2)
5516 && aff->af_compforbid == 0)
5518 aff->af_compforbid = affitem2flag(aff->af_flagtype, items[1],
5519 fname, lnum);
5520 if (aff->af_pref.ht_used > 0)
5521 smsg((char_u *)_("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d"),
5522 fname, lnum);
5524 else if (is_aff_rule(items, itemcnt, "COMPOUNDPERMITFLAG", 2)
5525 && aff->af_comppermit == 0)
5527 aff->af_comppermit = affitem2flag(aff->af_flagtype, items[1],
5528 fname, lnum);
5529 if (aff->af_pref.ht_used > 0)
5530 smsg((char_u *)_("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d"),
5531 fname, lnum);
5533 else if (is_aff_rule(items, itemcnt, "COMPOUNDFLAG", 2)
5534 && compflags == NULL)
5536 /* Turn flag "c" into COMPOUNDRULE compatible string "c+",
5537 * "Na" into "Na+", "1234" into "1234+". */
5538 p = getroom(spin, STRLEN(items[1]) + 2, FALSE);
5539 if (p != NULL)
5541 STRCPY(p, items[1]);
5542 STRCAT(p, "+");
5543 compflags = p;
5546 else if (is_aff_rule(items, itemcnt, "COMPOUNDRULES", 2))
5548 /* We don't use the count, but do check that it's a number and
5549 * not COMPOUNDRULE mistyped. */
5550 if (atoi((char *)items[1]) == 0)
5551 smsg((char_u *)_("Wrong COMPOUNDRULES value in %s line %d: %s"),
5552 fname, lnum, items[1]);
5554 else if (is_aff_rule(items, itemcnt, "COMPOUNDRULE", 2))
5556 /* Concatenate this string to previously defined ones, using a
5557 * slash to separate them. */
5558 l = (int)STRLEN(items[1]) + 1;
5559 if (compflags != NULL)
5560 l += (int)STRLEN(compflags) + 1;
5561 p = getroom(spin, l, FALSE);
5562 if (p != NULL)
5564 if (compflags != NULL)
5566 STRCPY(p, compflags);
5567 STRCAT(p, "/");
5569 STRCAT(p, items[1]);
5570 compflags = p;
5573 else if (is_aff_rule(items, itemcnt, "COMPOUNDWORDMAX", 2)
5574 && compmax == 0)
5576 compmax = atoi((char *)items[1]);
5577 if (compmax == 0)
5578 smsg((char_u *)_("Wrong COMPOUNDWORDMAX value in %s line %d: %s"),
5579 fname, lnum, items[1]);
5581 else if (is_aff_rule(items, itemcnt, "COMPOUNDMIN", 2)
5582 && compminlen == 0)
5584 compminlen = atoi((char *)items[1]);
5585 if (compminlen == 0)
5586 smsg((char_u *)_("Wrong COMPOUNDMIN value in %s line %d: %s"),
5587 fname, lnum, items[1]);
5589 else if (is_aff_rule(items, itemcnt, "COMPOUNDSYLMAX", 2)
5590 && compsylmax == 0)
5592 compsylmax = atoi((char *)items[1]);
5593 if (compsylmax == 0)
5594 smsg((char_u *)_("Wrong COMPOUNDSYLMAX value in %s line %d: %s"),
5595 fname, lnum, items[1]);
5597 else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDDUP", 1))
5599 compoptions |= COMP_CHECKDUP;
5601 else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDREP", 1))
5603 compoptions |= COMP_CHECKREP;
5605 else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDCASE", 1))
5607 compoptions |= COMP_CHECKCASE;
5609 else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDTRIPLE", 1))
5611 compoptions |= COMP_CHECKTRIPLE;
5613 else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 2))
5615 if (atoi((char *)items[1]) == 0)
5616 smsg((char_u *)_("Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s"),
5617 fname, lnum, items[1]);
5619 else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 3))
5621 garray_T *gap = &spin->si_comppat;
5622 int i;
5624 /* Only add the couple if it isn't already there. */
5625 for (i = 0; i < gap->ga_len - 1; i += 2)
5626 if (STRCMP(((char_u **)(gap->ga_data))[i], items[1]) == 0
5627 && STRCMP(((char_u **)(gap->ga_data))[i + 1],
5628 items[2]) == 0)
5629 break;
5630 if (i >= gap->ga_len && ga_grow(gap, 2) == OK)
5632 ((char_u **)(gap->ga_data))[gap->ga_len++]
5633 = getroom_save(spin, items[1]);
5634 ((char_u **)(gap->ga_data))[gap->ga_len++]
5635 = getroom_save(spin, items[2]);
5638 else if (is_aff_rule(items, itemcnt, "SYLLABLE", 2)
5639 && syllable == NULL)
5641 syllable = getroom_save(spin, items[1]);
5643 else if (is_aff_rule(items, itemcnt, "NOBREAK", 1))
5645 spin->si_nobreak = TRUE;
5647 else if (is_aff_rule(items, itemcnt, "NOSPLITSUGS", 1))
5649 spin->si_nosplitsugs = TRUE;
5651 else if (is_aff_rule(items, itemcnt, "NOSUGFILE", 1))
5653 spin->si_nosugfile = TRUE;
5655 else if (is_aff_rule(items, itemcnt, "PFXPOSTPONE", 1))
5657 aff->af_pfxpostpone = TRUE;
5659 else if ((STRCMP(items[0], "PFX") == 0
5660 || STRCMP(items[0], "SFX") == 0)
5661 && aff_todo == 0
5662 && itemcnt >= 4)
5664 int lasti = 4;
5665 char_u key[AH_KEY_LEN];
5667 if (*items[0] == 'P')
5668 tp = &aff->af_pref;
5669 else
5670 tp = &aff->af_suff;
5672 /* Myspell allows the same affix name to be used multiple
5673 * times. The affix files that do this have an undocumented
5674 * "S" flag on all but the last block, thus we check for that
5675 * and store it in ah_follows. */
5676 vim_strncpy(key, items[1], AH_KEY_LEN - 1);
5677 hi = hash_find(tp, key);
5678 if (!HASHITEM_EMPTY(hi))
5680 cur_aff = HI2AH(hi);
5681 if (cur_aff->ah_combine != (*items[2] == 'Y'))
5682 smsg((char_u *)_("Different combining flag in continued affix block in %s line %d: %s"),
5683 fname, lnum, items[1]);
5684 if (!cur_aff->ah_follows)
5685 smsg((char_u *)_("Duplicate affix in %s line %d: %s"),
5686 fname, lnum, items[1]);
5688 else
5690 /* New affix letter. */
5691 cur_aff = (affheader_T *)getroom(spin,
5692 sizeof(affheader_T), TRUE);
5693 if (cur_aff == NULL)
5694 break;
5695 cur_aff->ah_flag = affitem2flag(aff->af_flagtype, items[1],
5696 fname, lnum);
5697 if (cur_aff->ah_flag == 0 || STRLEN(items[1]) >= AH_KEY_LEN)
5698 break;
5699 if (cur_aff->ah_flag == aff->af_bad
5700 || cur_aff->ah_flag == aff->af_rare
5701 || cur_aff->ah_flag == aff->af_keepcase
5702 || cur_aff->ah_flag == aff->af_needaffix
5703 || cur_aff->ah_flag == aff->af_circumfix
5704 || cur_aff->ah_flag == aff->af_nosuggest
5705 || cur_aff->ah_flag == aff->af_needcomp
5706 || cur_aff->ah_flag == aff->af_comproot)
5707 smsg((char_u *)_("Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in %s line %d: %s"),
5708 fname, lnum, items[1]);
5709 STRCPY(cur_aff->ah_key, items[1]);
5710 hash_add(tp, cur_aff->ah_key);
5712 cur_aff->ah_combine = (*items[2] == 'Y');
5715 /* Check for the "S" flag, which apparently means that another
5716 * block with the same affix name is following. */
5717 if (itemcnt > lasti && STRCMP(items[lasti], "S") == 0)
5719 ++lasti;
5720 cur_aff->ah_follows = TRUE;
5722 else
5723 cur_aff->ah_follows = FALSE;
5725 /* Myspell allows extra text after the item, but that might
5726 * mean mistakes go unnoticed. Require a comment-starter. */
5727 if (itemcnt > lasti && *items[lasti] != '#')
5728 smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]);
5730 if (STRCMP(items[2], "Y") != 0 && STRCMP(items[2], "N") != 0)
5731 smsg((char_u *)_("Expected Y or N in %s line %d: %s"),
5732 fname, lnum, items[2]);
5734 if (*items[0] == 'P' && aff->af_pfxpostpone)
5736 if (cur_aff->ah_newID == 0)
5738 /* Use a new number in the .spl file later, to be able
5739 * to handle multiple .aff files. */
5740 check_renumber(spin);
5741 cur_aff->ah_newID = ++spin->si_newprefID;
5743 /* We only really use ah_newID if the prefix is
5744 * postponed. We know that only after handling all
5745 * the items. */
5746 did_postpone_prefix = FALSE;
5748 else
5749 /* Did use the ID in a previous block. */
5750 did_postpone_prefix = TRUE;
5753 aff_todo = atoi((char *)items[3]);
5755 else if ((STRCMP(items[0], "PFX") == 0
5756 || STRCMP(items[0], "SFX") == 0)
5757 && aff_todo > 0
5758 && STRCMP(cur_aff->ah_key, items[1]) == 0
5759 && itemcnt >= 5)
5761 affentry_T *aff_entry;
5762 int upper = FALSE;
5763 int lasti = 5;
5765 /* Myspell allows extra text after the item, but that might
5766 * mean mistakes go unnoticed. Require a comment-starter.
5767 * Hunspell uses a "-" item. */
5768 if (itemcnt > lasti && *items[lasti] != '#'
5769 && (STRCMP(items[lasti], "-") != 0
5770 || itemcnt != lasti + 1))
5771 smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]);
5773 /* New item for an affix letter. */
5774 --aff_todo;
5775 aff_entry = (affentry_T *)getroom(spin,
5776 sizeof(affentry_T), TRUE);
5777 if (aff_entry == NULL)
5778 break;
5780 if (STRCMP(items[2], "0") != 0)
5781 aff_entry->ae_chop = getroom_save(spin, items[2]);
5782 if (STRCMP(items[3], "0") != 0)
5784 aff_entry->ae_add = getroom_save(spin, items[3]);
5786 /* Recognize flags on the affix: abcd/XYZ */
5787 aff_entry->ae_flags = vim_strchr(aff_entry->ae_add, '/');
5788 if (aff_entry->ae_flags != NULL)
5790 *aff_entry->ae_flags++ = NUL;
5791 aff_process_flags(aff, aff_entry);
5795 /* Don't use an affix entry with non-ASCII characters when
5796 * "spin->si_ascii" is TRUE. */
5797 if (!spin->si_ascii || !(has_non_ascii(aff_entry->ae_chop)
5798 || has_non_ascii(aff_entry->ae_add)))
5800 aff_entry->ae_next = cur_aff->ah_first;
5801 cur_aff->ah_first = aff_entry;
5803 if (STRCMP(items[4], ".") != 0)
5805 char_u buf[MAXLINELEN];
5807 aff_entry->ae_cond = getroom_save(spin, items[4]);
5808 if (*items[0] == 'P')
5809 sprintf((char *)buf, "^%s", items[4]);
5810 else
5811 sprintf((char *)buf, "%s$", items[4]);
5812 aff_entry->ae_prog = vim_regcomp(buf,
5813 RE_MAGIC + RE_STRING + RE_STRICT);
5814 if (aff_entry->ae_prog == NULL)
5815 smsg((char_u *)_("Broken condition in %s line %d: %s"),
5816 fname, lnum, items[4]);
5819 /* For postponed prefixes we need an entry in si_prefcond
5820 * for the condition. Use an existing one if possible.
5821 * Can't be done for an affix with flags, ignoring
5822 * COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG. */
5823 if (*items[0] == 'P' && aff->af_pfxpostpone
5824 && aff_entry->ae_flags == NULL)
5826 /* When the chop string is one lower-case letter and
5827 * the add string ends in the upper-case letter we set
5828 * the "upper" flag, clear "ae_chop" and remove the
5829 * letters from "ae_add". The condition must either
5830 * be empty or start with the same letter. */
5831 if (aff_entry->ae_chop != NULL
5832 && aff_entry->ae_add != NULL
5833 #ifdef FEAT_MBYTE
5834 && aff_entry->ae_chop[(*mb_ptr2len)(
5835 aff_entry->ae_chop)] == NUL
5836 #else
5837 && aff_entry->ae_chop[1] == NUL
5838 #endif
5841 int c, c_up;
5843 c = PTR2CHAR(aff_entry->ae_chop);
5844 c_up = SPELL_TOUPPER(c);
5845 if (c_up != c
5846 && (aff_entry->ae_cond == NULL
5847 || PTR2CHAR(aff_entry->ae_cond) == c))
5849 p = aff_entry->ae_add
5850 + STRLEN(aff_entry->ae_add);
5851 mb_ptr_back(aff_entry->ae_add, p);
5852 if (PTR2CHAR(p) == c_up)
5854 upper = TRUE;
5855 aff_entry->ae_chop = NULL;
5856 *p = NUL;
5858 /* The condition is matched with the
5859 * actual word, thus must check for the
5860 * upper-case letter. */
5861 if (aff_entry->ae_cond != NULL)
5863 char_u buf[MAXLINELEN];
5864 #ifdef FEAT_MBYTE
5865 if (has_mbyte)
5867 onecap_copy(items[4], buf, TRUE);
5868 aff_entry->ae_cond = getroom_save(
5869 spin, buf);
5871 else
5872 #endif
5873 *aff_entry->ae_cond = c_up;
5874 if (aff_entry->ae_cond != NULL)
5876 sprintf((char *)buf, "^%s",
5877 aff_entry->ae_cond);
5878 vim_free(aff_entry->ae_prog);
5879 aff_entry->ae_prog = vim_regcomp(
5880 buf, RE_MAGIC + RE_STRING);
5887 if (aff_entry->ae_chop == NULL
5888 && aff_entry->ae_flags == NULL)
5890 int idx;
5891 char_u **pp;
5892 int n;
5894 /* Find a previously used condition. */
5895 for (idx = spin->si_prefcond.ga_len - 1; idx >= 0;
5896 --idx)
5898 p = ((char_u **)spin->si_prefcond.ga_data)[idx];
5899 if (str_equal(p, aff_entry->ae_cond))
5900 break;
5902 if (idx < 0 && ga_grow(&spin->si_prefcond, 1) == OK)
5904 /* Not found, add a new condition. */
5905 idx = spin->si_prefcond.ga_len++;
5906 pp = ((char_u **)spin->si_prefcond.ga_data)
5907 + idx;
5908 if (aff_entry->ae_cond == NULL)
5909 *pp = NULL;
5910 else
5911 *pp = getroom_save(spin,
5912 aff_entry->ae_cond);
5915 /* Add the prefix to the prefix tree. */
5916 if (aff_entry->ae_add == NULL)
5917 p = (char_u *)"";
5918 else
5919 p = aff_entry->ae_add;
5921 /* PFX_FLAGS is a negative number, so that
5922 * tree_add_word() knows this is the prefix tree. */
5923 n = PFX_FLAGS;
5924 if (!cur_aff->ah_combine)
5925 n |= WFP_NC;
5926 if (upper)
5927 n |= WFP_UP;
5928 if (aff_entry->ae_comppermit)
5929 n |= WFP_COMPPERMIT;
5930 if (aff_entry->ae_compforbid)
5931 n |= WFP_COMPFORBID;
5932 tree_add_word(spin, p, spin->si_prefroot, n,
5933 idx, cur_aff->ah_newID);
5934 did_postpone_prefix = TRUE;
5937 /* Didn't actually use ah_newID, backup si_newprefID. */
5938 if (aff_todo == 0 && !did_postpone_prefix)
5940 --spin->si_newprefID;
5941 cur_aff->ah_newID = 0;
5946 else if (is_aff_rule(items, itemcnt, "FOL", 2) && fol == NULL)
5948 fol = vim_strsave(items[1]);
5950 else if (is_aff_rule(items, itemcnt, "LOW", 2) && low == NULL)
5952 low = vim_strsave(items[1]);
5954 else if (is_aff_rule(items, itemcnt, "UPP", 2) && upp == NULL)
5956 upp = vim_strsave(items[1]);
5958 else if (is_aff_rule(items, itemcnt, "REP", 2)
5959 || is_aff_rule(items, itemcnt, "REPSAL", 2))
5961 /* Ignore REP/REPSAL count */;
5962 if (!isdigit(*items[1]))
5963 smsg((char_u *)_("Expected REP(SAL) count in %s line %d"),
5964 fname, lnum);
5966 else if ((STRCMP(items[0], "REP") == 0
5967 || STRCMP(items[0], "REPSAL") == 0)
5968 && itemcnt >= 3)
5970 /* REP/REPSAL item */
5971 /* Myspell ignores extra arguments, we require it starts with
5972 * # to detect mistakes. */
5973 if (itemcnt > 3 && items[3][0] != '#')
5974 smsg((char_u *)_(e_afftrailing), fname, lnum, items[3]);
5975 if (items[0][3] == 'S' ? do_repsal : do_rep)
5977 /* Replace underscore with space (can't include a space
5978 * directly). */
5979 for (p = items[1]; *p != NUL; mb_ptr_adv(p))
5980 if (*p == '_')
5981 *p = ' ';
5982 for (p = items[2]; *p != NUL; mb_ptr_adv(p))
5983 if (*p == '_')
5984 *p = ' ';
5985 add_fromto(spin, items[0][3] == 'S'
5986 ? &spin->si_repsal
5987 : &spin->si_rep, items[1], items[2]);
5990 else if (is_aff_rule(items, itemcnt, "MAP", 2))
5992 /* MAP item or count */
5993 if (!found_map)
5995 /* First line contains the count. */
5996 found_map = TRUE;
5997 if (!isdigit(*items[1]))
5998 smsg((char_u *)_("Expected MAP count in %s line %d"),
5999 fname, lnum);
6001 else if (do_mapline)
6003 int c;
6005 /* Check that every character appears only once. */
6006 for (p = items[1]; *p != NUL; )
6008 #ifdef FEAT_MBYTE
6009 c = mb_ptr2char_adv(&p);
6010 #else
6011 c = *p++;
6012 #endif
6013 if ((spin->si_map.ga_len > 0
6014 && vim_strchr(spin->si_map.ga_data, c)
6015 != NULL)
6016 || vim_strchr(p, c) != NULL)
6017 smsg((char_u *)_("Duplicate character in MAP in %s line %d"),
6018 fname, lnum);
6021 /* We simply concatenate all the MAP strings, separated by
6022 * slashes. */
6023 ga_concat(&spin->si_map, items[1]);
6024 ga_append(&spin->si_map, '/');
6027 /* Accept "SAL from to" and "SAL from to #comment". */
6028 else if (is_aff_rule(items, itemcnt, "SAL", 3))
6030 if (do_sal)
6032 /* SAL item (sounds-a-like)
6033 * Either one of the known keys or a from-to pair. */
6034 if (STRCMP(items[1], "followup") == 0)
6035 spin->si_followup = sal_to_bool(items[2]);
6036 else if (STRCMP(items[1], "collapse_result") == 0)
6037 spin->si_collapse = sal_to_bool(items[2]);
6038 else if (STRCMP(items[1], "remove_accents") == 0)
6039 spin->si_rem_accents = sal_to_bool(items[2]);
6040 else
6041 /* when "to" is "_" it means empty */
6042 add_fromto(spin, &spin->si_sal, items[1],
6043 STRCMP(items[2], "_") == 0 ? (char_u *)""
6044 : items[2]);
6047 else if (is_aff_rule(items, itemcnt, "SOFOFROM", 2)
6048 && sofofrom == NULL)
6050 sofofrom = getroom_save(spin, items[1]);
6052 else if (is_aff_rule(items, itemcnt, "SOFOTO", 2)
6053 && sofoto == NULL)
6055 sofoto = getroom_save(spin, items[1]);
6057 else if (STRCMP(items[0], "COMMON") == 0)
6059 int i;
6061 for (i = 1; i < itemcnt; ++i)
6063 if (HASHITEM_EMPTY(hash_find(&spin->si_commonwords,
6064 items[i])))
6066 p = vim_strsave(items[i]);
6067 if (p == NULL)
6068 break;
6069 hash_add(&spin->si_commonwords, p);
6073 else
6074 smsg((char_u *)_("Unrecognized or duplicate item in %s line %d: %s"),
6075 fname, lnum, items[0]);
6079 if (fol != NULL || low != NULL || upp != NULL)
6081 if (spin->si_clear_chartab)
6083 /* Clear the char type tables, don't want to use any of the
6084 * currently used spell properties. */
6085 init_spell_chartab();
6086 spin->si_clear_chartab = FALSE;
6090 * Don't write a word table for an ASCII file, so that we don't check
6091 * for conflicts with a word table that matches 'encoding'.
6092 * Don't write one for utf-8 either, we use utf_*() and
6093 * mb_get_class(), the list of chars in the file will be incomplete.
6095 if (!spin->si_ascii
6096 #ifdef FEAT_MBYTE
6097 && !enc_utf8
6098 #endif
6101 if (fol == NULL || low == NULL || upp == NULL)
6102 smsg((char_u *)_("Missing FOL/LOW/UPP line in %s"), fname);
6103 else
6104 (void)set_spell_chartab(fol, low, upp);
6107 vim_free(fol);
6108 vim_free(low);
6109 vim_free(upp);
6112 /* Use compound specifications of the .aff file for the spell info. */
6113 if (compmax != 0)
6115 aff_check_number(spin->si_compmax, compmax, "COMPOUNDWORDMAX");
6116 spin->si_compmax = compmax;
6119 if (compminlen != 0)
6121 aff_check_number(spin->si_compminlen, compminlen, "COMPOUNDMIN");
6122 spin->si_compminlen = compminlen;
6125 if (compsylmax != 0)
6127 if (syllable == NULL)
6128 smsg((char_u *)_("COMPOUNDSYLMAX used without SYLLABLE"));
6129 aff_check_number(spin->si_compsylmax, compsylmax, "COMPOUNDSYLMAX");
6130 spin->si_compsylmax = compsylmax;
6133 if (compoptions != 0)
6135 aff_check_number(spin->si_compoptions, compoptions, "COMPOUND options");
6136 spin->si_compoptions |= compoptions;
6139 if (compflags != NULL)
6140 process_compflags(spin, aff, compflags);
6142 /* Check that we didn't use too many renumbered flags. */
6143 if (spin->si_newcompID < spin->si_newprefID)
6145 if (spin->si_newcompID == 127 || spin->si_newcompID == 255)
6146 MSG(_("Too many postponed prefixes"));
6147 else if (spin->si_newprefID == 0 || spin->si_newprefID == 127)
6148 MSG(_("Too many compound flags"));
6149 else
6150 MSG(_("Too many postponed prefixes and/or compound flags"));
6153 if (syllable != NULL)
6155 aff_check_string(spin->si_syllable, syllable, "SYLLABLE");
6156 spin->si_syllable = syllable;
6159 if (sofofrom != NULL || sofoto != NULL)
6161 if (sofofrom == NULL || sofoto == NULL)
6162 smsg((char_u *)_("Missing SOFO%s line in %s"),
6163 sofofrom == NULL ? "FROM" : "TO", fname);
6164 else if (spin->si_sal.ga_len > 0)
6165 smsg((char_u *)_("Both SAL and SOFO lines in %s"), fname);
6166 else
6168 aff_check_string(spin->si_sofofr, sofofrom, "SOFOFROM");
6169 aff_check_string(spin->si_sofoto, sofoto, "SOFOTO");
6170 spin->si_sofofr = sofofrom;
6171 spin->si_sofoto = sofoto;
6175 if (midword != NULL)
6177 aff_check_string(spin->si_midword, midword, "MIDWORD");
6178 spin->si_midword = midword;
6181 vim_free(pc);
6182 fclose(fd);
6183 return aff;
6187 * Return TRUE when items[0] equals "rulename", there are "mincount" items or
6188 * a comment is following after item "mincount".
6190 static int
6191 is_aff_rule(items, itemcnt, rulename, mincount)
6192 char_u **items;
6193 int itemcnt;
6194 char *rulename;
6195 int mincount;
6197 return (STRCMP(items[0], rulename) == 0
6198 && (itemcnt == mincount
6199 || (itemcnt > mincount && items[mincount][0] == '#')));
6203 * For affix "entry" move COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG from
6204 * ae_flags to ae_comppermit and ae_compforbid.
6206 static void
6207 aff_process_flags(affile, entry)
6208 afffile_T *affile;
6209 affentry_T *entry;
6211 char_u *p;
6212 char_u *prevp;
6213 unsigned flag;
6215 if (entry->ae_flags != NULL
6216 && (affile->af_compforbid != 0 || affile->af_comppermit != 0))
6218 for (p = entry->ae_flags; *p != NUL; )
6220 prevp = p;
6221 flag = get_affitem(affile->af_flagtype, &p);
6222 if (flag == affile->af_comppermit || flag == affile->af_compforbid)
6224 STRMOVE(prevp, p);
6225 p = prevp;
6226 if (flag == affile->af_comppermit)
6227 entry->ae_comppermit = TRUE;
6228 else
6229 entry->ae_compforbid = TRUE;
6231 if (affile->af_flagtype == AFT_NUM && *p == ',')
6232 ++p;
6234 if (*entry->ae_flags == NUL)
6235 entry->ae_flags = NULL; /* nothing left */
6240 * Return TRUE if "s" is the name of an info item in the affix file.
6242 static int
6243 spell_info_item(s)
6244 char_u *s;
6246 return STRCMP(s, "NAME") == 0
6247 || STRCMP(s, "HOME") == 0
6248 || STRCMP(s, "VERSION") == 0
6249 || STRCMP(s, "AUTHOR") == 0
6250 || STRCMP(s, "EMAIL") == 0
6251 || STRCMP(s, "COPYRIGHT") == 0;
6255 * Turn an affix flag name into a number, according to the FLAG type.
6256 * returns zero for failure.
6258 static unsigned
6259 affitem2flag(flagtype, item, fname, lnum)
6260 int flagtype;
6261 char_u *item;
6262 char_u *fname;
6263 int lnum;
6265 unsigned res;
6266 char_u *p = item;
6268 res = get_affitem(flagtype, &p);
6269 if (res == 0)
6271 if (flagtype == AFT_NUM)
6272 smsg((char_u *)_("Flag is not a number in %s line %d: %s"),
6273 fname, lnum, item);
6274 else
6275 smsg((char_u *)_("Illegal flag in %s line %d: %s"),
6276 fname, lnum, item);
6278 if (*p != NUL)
6280 smsg((char_u *)_(e_affname), fname, lnum, item);
6281 return 0;
6284 return res;
6288 * Get one affix name from "*pp" and advance the pointer.
6289 * Returns zero for an error, still advances the pointer then.
6291 static unsigned
6292 get_affitem(flagtype, pp)
6293 int flagtype;
6294 char_u **pp;
6296 int res;
6298 if (flagtype == AFT_NUM)
6300 if (!VIM_ISDIGIT(**pp))
6302 ++*pp; /* always advance, avoid getting stuck */
6303 return 0;
6305 res = getdigits(pp);
6307 else
6309 #ifdef FEAT_MBYTE
6310 res = mb_ptr2char_adv(pp);
6311 #else
6312 res = *(*pp)++;
6313 #endif
6314 if (flagtype == AFT_LONG || (flagtype == AFT_CAPLONG
6315 && res >= 'A' && res <= 'Z'))
6317 if (**pp == NUL)
6318 return 0;
6319 #ifdef FEAT_MBYTE
6320 res = mb_ptr2char_adv(pp) + (res << 16);
6321 #else
6322 res = *(*pp)++ + (res << 16);
6323 #endif
6326 return res;
6330 * Process the "compflags" string used in an affix file and append it to
6331 * spin->si_compflags.
6332 * The processing involves changing the affix names to ID numbers, so that
6333 * they fit in one byte.
6335 static void
6336 process_compflags(spin, aff, compflags)
6337 spellinfo_T *spin;
6338 afffile_T *aff;
6339 char_u *compflags;
6341 char_u *p;
6342 char_u *prevp;
6343 unsigned flag;
6344 compitem_T *ci;
6345 int id;
6346 int len;
6347 char_u *tp;
6348 char_u key[AH_KEY_LEN];
6349 hashitem_T *hi;
6351 /* Make room for the old and the new compflags, concatenated with a / in
6352 * between. Processing it makes it shorter, but we don't know by how
6353 * much, thus allocate the maximum. */
6354 len = (int)STRLEN(compflags) + 1;
6355 if (spin->si_compflags != NULL)
6356 len += (int)STRLEN(spin->si_compflags) + 1;
6357 p = getroom(spin, len, FALSE);
6358 if (p == NULL)
6359 return;
6360 if (spin->si_compflags != NULL)
6362 STRCPY(p, spin->si_compflags);
6363 STRCAT(p, "/");
6365 spin->si_compflags = p;
6366 tp = p + STRLEN(p);
6368 for (p = compflags; *p != NUL; )
6370 if (vim_strchr((char_u *)"/*+[]", *p) != NULL)
6371 /* Copy non-flag characters directly. */
6372 *tp++ = *p++;
6373 else
6375 /* First get the flag number, also checks validity. */
6376 prevp = p;
6377 flag = get_affitem(aff->af_flagtype, &p);
6378 if (flag != 0)
6380 /* Find the flag in the hashtable. If it was used before, use
6381 * the existing ID. Otherwise add a new entry. */
6382 vim_strncpy(key, prevp, p - prevp);
6383 hi = hash_find(&aff->af_comp, key);
6384 if (!HASHITEM_EMPTY(hi))
6385 id = HI2CI(hi)->ci_newID;
6386 else
6388 ci = (compitem_T *)getroom(spin, sizeof(compitem_T), TRUE);
6389 if (ci == NULL)
6390 break;
6391 STRCPY(ci->ci_key, key);
6392 ci->ci_flag = flag;
6393 /* Avoid using a flag ID that has a special meaning in a
6394 * regexp (also inside []). */
6397 check_renumber(spin);
6398 id = spin->si_newcompID--;
6399 } while (vim_strchr((char_u *)"/+*[]\\-^", id) != NULL);
6400 ci->ci_newID = id;
6401 hash_add(&aff->af_comp, ci->ci_key);
6403 *tp++ = id;
6405 if (aff->af_flagtype == AFT_NUM && *p == ',')
6406 ++p;
6410 *tp = NUL;
6414 * Check that the new IDs for postponed affixes and compounding don't overrun
6415 * each other. We have almost 255 available, but start at 0-127 to avoid
6416 * using two bytes for utf-8. When the 0-127 range is used up go to 128-255.
6417 * When that is used up an error message is given.
6419 static void
6420 check_renumber(spin)
6421 spellinfo_T *spin;
6423 if (spin->si_newprefID == spin->si_newcompID && spin->si_newcompID < 128)
6425 spin->si_newprefID = 127;
6426 spin->si_newcompID = 255;
6431 * Return TRUE if flag "flag" appears in affix list "afflist".
6433 static int
6434 flag_in_afflist(flagtype, afflist, flag)
6435 int flagtype;
6436 char_u *afflist;
6437 unsigned flag;
6439 char_u *p;
6440 unsigned n;
6442 switch (flagtype)
6444 case AFT_CHAR:
6445 return vim_strchr(afflist, flag) != NULL;
6447 case AFT_CAPLONG:
6448 case AFT_LONG:
6449 for (p = afflist; *p != NUL; )
6451 #ifdef FEAT_MBYTE
6452 n = mb_ptr2char_adv(&p);
6453 #else
6454 n = *p++;
6455 #endif
6456 if ((flagtype == AFT_LONG || (n >= 'A' && n <= 'Z'))
6457 && *p != NUL)
6458 #ifdef FEAT_MBYTE
6459 n = mb_ptr2char_adv(&p) + (n << 16);
6460 #else
6461 n = *p++ + (n << 16);
6462 #endif
6463 if (n == flag)
6464 return TRUE;
6466 break;
6468 case AFT_NUM:
6469 for (p = afflist; *p != NUL; )
6471 n = getdigits(&p);
6472 if (n == flag)
6473 return TRUE;
6474 if (*p != NUL) /* skip over comma */
6475 ++p;
6477 break;
6479 return FALSE;
6483 * Give a warning when "spinval" and "affval" numbers are set and not the same.
6485 static void
6486 aff_check_number(spinval, affval, name)
6487 int spinval;
6488 int affval;
6489 char *name;
6491 if (spinval != 0 && spinval != affval)
6492 smsg((char_u *)_("%s value differs from what is used in another .aff file"), name);
6496 * Give a warning when "spinval" and "affval" strings are set and not the same.
6498 static void
6499 aff_check_string(spinval, affval, name)
6500 char_u *spinval;
6501 char_u *affval;
6502 char *name;
6504 if (spinval != NULL && STRCMP(spinval, affval) != 0)
6505 smsg((char_u *)_("%s value differs from what is used in another .aff file"), name);
6509 * Return TRUE if strings "s1" and "s2" are equal. Also consider both being
6510 * NULL as equal.
6512 static int
6513 str_equal(s1, s2)
6514 char_u *s1;
6515 char_u *s2;
6517 if (s1 == NULL || s2 == NULL)
6518 return s1 == s2;
6519 return STRCMP(s1, s2) == 0;
6523 * Add a from-to item to "gap". Used for REP and SAL items.
6524 * They are stored case-folded.
6526 static void
6527 add_fromto(spin, gap, from, to)
6528 spellinfo_T *spin;
6529 garray_T *gap;
6530 char_u *from;
6531 char_u *to;
6533 fromto_T *ftp;
6534 char_u word[MAXWLEN];
6536 if (ga_grow(gap, 1) == OK)
6538 ftp = ((fromto_T *)gap->ga_data) + gap->ga_len;
6539 (void)spell_casefold(from, (int)STRLEN(from), word, MAXWLEN);
6540 ftp->ft_from = getroom_save(spin, word);
6541 (void)spell_casefold(to, (int)STRLEN(to), word, MAXWLEN);
6542 ftp->ft_to = getroom_save(spin, word);
6543 ++gap->ga_len;
6548 * Convert a boolean argument in a SAL line to TRUE or FALSE;
6550 static int
6551 sal_to_bool(s)
6552 char_u *s;
6554 return STRCMP(s, "1") == 0 || STRCMP(s, "true") == 0;
6558 * Return TRUE if string "s" contains a non-ASCII character (128 or higher).
6559 * When "s" is NULL FALSE is returned.
6561 static int
6562 has_non_ascii(s)
6563 char_u *s;
6565 char_u *p;
6567 if (s != NULL)
6568 for (p = s; *p != NUL; ++p)
6569 if (*p >= 128)
6570 return TRUE;
6571 return FALSE;
6575 * Free the structure filled by spell_read_aff().
6577 static void
6578 spell_free_aff(aff)
6579 afffile_T *aff;
6581 hashtab_T *ht;
6582 hashitem_T *hi;
6583 int todo;
6584 affheader_T *ah;
6585 affentry_T *ae;
6587 vim_free(aff->af_enc);
6589 /* All this trouble to free the "ae_prog" items... */
6590 for (ht = &aff->af_pref; ; ht = &aff->af_suff)
6592 todo = (int)ht->ht_used;
6593 for (hi = ht->ht_array; todo > 0; ++hi)
6595 if (!HASHITEM_EMPTY(hi))
6597 --todo;
6598 ah = HI2AH(hi);
6599 for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
6600 vim_free(ae->ae_prog);
6603 if (ht == &aff->af_suff)
6604 break;
6607 hash_clear(&aff->af_pref);
6608 hash_clear(&aff->af_suff);
6609 hash_clear(&aff->af_comp);
6613 * Read dictionary file "fname".
6614 * Returns OK or FAIL;
6616 static int
6617 spell_read_dic(spin, fname, affile)
6618 spellinfo_T *spin;
6619 char_u *fname;
6620 afffile_T *affile;
6622 hashtab_T ht;
6623 char_u line[MAXLINELEN];
6624 char_u *p;
6625 char_u *afflist;
6626 char_u store_afflist[MAXWLEN];
6627 int pfxlen;
6628 int need_affix;
6629 char_u *dw;
6630 char_u *pc;
6631 char_u *w;
6632 int l;
6633 hash_T hash;
6634 hashitem_T *hi;
6635 FILE *fd;
6636 int lnum = 1;
6637 int non_ascii = 0;
6638 int retval = OK;
6639 char_u message[MAXLINELEN + MAXWLEN];
6640 int flags;
6641 int duplicate = 0;
6644 * Open the file.
6646 fd = mch_fopen((char *)fname, "r");
6647 if (fd == NULL)
6649 EMSG2(_(e_notopen), fname);
6650 return FAIL;
6653 /* The hashtable is only used to detect duplicated words. */
6654 hash_init(&ht);
6656 vim_snprintf((char *)IObuff, IOSIZE,
6657 _("Reading dictionary file %s ..."), fname);
6658 spell_message(spin, IObuff);
6660 /* start with a message for the first line */
6661 spin->si_msg_count = 999999;
6663 /* Read and ignore the first line: word count. */
6664 (void)vim_fgets(line, MAXLINELEN, fd);
6665 if (!vim_isdigit(*skipwhite(line)))
6666 EMSG2(_("E760: No word count in %s"), fname);
6669 * Read all the lines in the file one by one.
6670 * The words are converted to 'encoding' here, before being added to
6671 * the hashtable.
6673 while (!vim_fgets(line, MAXLINELEN, fd) && !got_int)
6675 line_breakcheck();
6676 ++lnum;
6677 if (line[0] == '#' || line[0] == '/')
6678 continue; /* comment line */
6680 /* Remove CR, LF and white space from the end. White space halfway
6681 * the word is kept to allow e.g., "et al.". */
6682 l = (int)STRLEN(line);
6683 while (l > 0 && line[l - 1] <= ' ')
6684 --l;
6685 if (l == 0)
6686 continue; /* empty line */
6687 line[l] = NUL;
6689 #ifdef FEAT_MBYTE
6690 /* Convert from "SET" to 'encoding' when needed. */
6691 if (spin->si_conv.vc_type != CONV_NONE)
6693 pc = string_convert(&spin->si_conv, line, NULL);
6694 if (pc == NULL)
6696 smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
6697 fname, lnum, line);
6698 continue;
6700 w = pc;
6702 else
6703 #endif
6705 pc = NULL;
6706 w = line;
6709 /* Truncate the word at the "/", set "afflist" to what follows.
6710 * Replace "\/" by "/" and "\\" by "\". */
6711 afflist = NULL;
6712 for (p = w; *p != NUL; mb_ptr_adv(p))
6714 if (*p == '\\' && (p[1] == '\\' || p[1] == '/'))
6715 STRMOVE(p, p + 1);
6716 else if (*p == '/')
6718 *p = NUL;
6719 afflist = p + 1;
6720 break;
6724 /* Skip non-ASCII words when "spin->si_ascii" is TRUE. */
6725 if (spin->si_ascii && has_non_ascii(w))
6727 ++non_ascii;
6728 vim_free(pc);
6729 continue;
6732 /* This takes time, print a message every 10000 words. */
6733 if (spin->si_verbose && spin->si_msg_count > 10000)
6735 spin->si_msg_count = 0;
6736 vim_snprintf((char *)message, sizeof(message),
6737 _("line %6d, word %6d - %s"),
6738 lnum, spin->si_foldwcount + spin->si_keepwcount, w);
6739 msg_start();
6740 msg_puts_long_attr(message, 0);
6741 msg_clr_eos();
6742 msg_didout = FALSE;
6743 msg_col = 0;
6744 out_flush();
6747 /* Store the word in the hashtable to be able to find duplicates. */
6748 dw = (char_u *)getroom_save(spin, w);
6749 if (dw == NULL)
6751 retval = FAIL;
6752 vim_free(pc);
6753 break;
6756 hash = hash_hash(dw);
6757 hi = hash_lookup(&ht, dw, hash);
6758 if (!HASHITEM_EMPTY(hi))
6760 if (p_verbose > 0)
6761 smsg((char_u *)_("Duplicate word in %s line %d: %s"),
6762 fname, lnum, dw);
6763 else if (duplicate == 0)
6764 smsg((char_u *)_("First duplicate word in %s line %d: %s"),
6765 fname, lnum, dw);
6766 ++duplicate;
6768 else
6769 hash_add_item(&ht, hi, dw, hash);
6771 flags = 0;
6772 store_afflist[0] = NUL;
6773 pfxlen = 0;
6774 need_affix = FALSE;
6775 if (afflist != NULL)
6777 /* Extract flags from the affix list. */
6778 flags |= get_affix_flags(affile, afflist);
6780 if (affile->af_needaffix != 0 && flag_in_afflist(
6781 affile->af_flagtype, afflist, affile->af_needaffix))
6782 need_affix = TRUE;
6784 if (affile->af_pfxpostpone)
6785 /* Need to store the list of prefix IDs with the word. */
6786 pfxlen = get_pfxlist(affile, afflist, store_afflist);
6788 if (spin->si_compflags != NULL)
6789 /* Need to store the list of compound flags with the word.
6790 * Concatenate them to the list of prefix IDs. */
6791 get_compflags(affile, afflist, store_afflist + pfxlen);
6794 /* Add the word to the word tree(s). */
6795 if (store_word(spin, dw, flags, spin->si_region,
6796 store_afflist, need_affix) == FAIL)
6797 retval = FAIL;
6799 if (afflist != NULL)
6801 /* Find all matching suffixes and add the resulting words.
6802 * Additionally do matching prefixes that combine. */
6803 if (store_aff_word(spin, dw, afflist, affile,
6804 &affile->af_suff, &affile->af_pref,
6805 CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
6806 retval = FAIL;
6808 /* Find all matching prefixes and add the resulting words. */
6809 if (store_aff_word(spin, dw, afflist, affile,
6810 &affile->af_pref, NULL,
6811 CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
6812 retval = FAIL;
6815 vim_free(pc);
6818 if (duplicate > 0)
6819 smsg((char_u *)_("%d duplicate word(s) in %s"), duplicate, fname);
6820 if (spin->si_ascii && non_ascii > 0)
6821 smsg((char_u *)_("Ignored %d word(s) with non-ASCII characters in %s"),
6822 non_ascii, fname);
6823 hash_clear(&ht);
6825 fclose(fd);
6826 return retval;
6830 * Check for affix flags in "afflist" that are turned into word flags.
6831 * Return WF_ flags.
6833 static int
6834 get_affix_flags(affile, afflist)
6835 afffile_T *affile;
6836 char_u *afflist;
6838 int flags = 0;
6840 if (affile->af_keepcase != 0 && flag_in_afflist(
6841 affile->af_flagtype, afflist, affile->af_keepcase))
6842 flags |= WF_KEEPCAP | WF_FIXCAP;
6843 if (affile->af_rare != 0 && flag_in_afflist(
6844 affile->af_flagtype, afflist, affile->af_rare))
6845 flags |= WF_RARE;
6846 if (affile->af_bad != 0 && flag_in_afflist(
6847 affile->af_flagtype, afflist, affile->af_bad))
6848 flags |= WF_BANNED;
6849 if (affile->af_needcomp != 0 && flag_in_afflist(
6850 affile->af_flagtype, afflist, affile->af_needcomp))
6851 flags |= WF_NEEDCOMP;
6852 if (affile->af_comproot != 0 && flag_in_afflist(
6853 affile->af_flagtype, afflist, affile->af_comproot))
6854 flags |= WF_COMPROOT;
6855 if (affile->af_nosuggest != 0 && flag_in_afflist(
6856 affile->af_flagtype, afflist, affile->af_nosuggest))
6857 flags |= WF_NOSUGGEST;
6858 return flags;
6862 * Get the list of prefix IDs from the affix list "afflist".
6863 * Used for PFXPOSTPONE.
6864 * Put the resulting flags in "store_afflist[MAXWLEN]" with a terminating NUL
6865 * and return the number of affixes.
6867 static int
6868 get_pfxlist(affile, afflist, store_afflist)
6869 afffile_T *affile;
6870 char_u *afflist;
6871 char_u *store_afflist;
6873 char_u *p;
6874 char_u *prevp;
6875 int cnt = 0;
6876 int id;
6877 char_u key[AH_KEY_LEN];
6878 hashitem_T *hi;
6880 for (p = afflist; *p != NUL; )
6882 prevp = p;
6883 if (get_affitem(affile->af_flagtype, &p) != 0)
6885 /* A flag is a postponed prefix flag if it appears in "af_pref"
6886 * and it's ID is not zero. */
6887 vim_strncpy(key, prevp, p - prevp);
6888 hi = hash_find(&affile->af_pref, key);
6889 if (!HASHITEM_EMPTY(hi))
6891 id = HI2AH(hi)->ah_newID;
6892 if (id != 0)
6893 store_afflist[cnt++] = id;
6896 if (affile->af_flagtype == AFT_NUM && *p == ',')
6897 ++p;
6900 store_afflist[cnt] = NUL;
6901 return cnt;
6905 * Get the list of compound IDs from the affix list "afflist" that are used
6906 * for compound words.
6907 * Puts the flags in "store_afflist[]".
6909 static void
6910 get_compflags(affile, afflist, store_afflist)
6911 afffile_T *affile;
6912 char_u *afflist;
6913 char_u *store_afflist;
6915 char_u *p;
6916 char_u *prevp;
6917 int cnt = 0;
6918 char_u key[AH_KEY_LEN];
6919 hashitem_T *hi;
6921 for (p = afflist; *p != NUL; )
6923 prevp = p;
6924 if (get_affitem(affile->af_flagtype, &p) != 0)
6926 /* A flag is a compound flag if it appears in "af_comp". */
6927 vim_strncpy(key, prevp, p - prevp);
6928 hi = hash_find(&affile->af_comp, key);
6929 if (!HASHITEM_EMPTY(hi))
6930 store_afflist[cnt++] = HI2CI(hi)->ci_newID;
6932 if (affile->af_flagtype == AFT_NUM && *p == ',')
6933 ++p;
6936 store_afflist[cnt] = NUL;
6940 * Apply affixes to a word and store the resulting words.
6941 * "ht" is the hashtable with affentry_T that need to be applied, either
6942 * prefixes or suffixes.
6943 * "xht", when not NULL, is the prefix hashtable, to be used additionally on
6944 * the resulting words for combining affixes.
6946 * Returns FAIL when out of memory.
6948 static int
6949 store_aff_word(spin, word, afflist, affile, ht, xht, condit, flags,
6950 pfxlist, pfxlen)
6951 spellinfo_T *spin; /* spell info */
6952 char_u *word; /* basic word start */
6953 char_u *afflist; /* list of names of supported affixes */
6954 afffile_T *affile;
6955 hashtab_T *ht;
6956 hashtab_T *xht;
6957 int condit; /* CONDIT_SUF et al. */
6958 int flags; /* flags for the word */
6959 char_u *pfxlist; /* list of prefix IDs */
6960 int pfxlen; /* nr of flags in "pfxlist" for prefixes, rest
6961 * is compound flags */
6963 int todo;
6964 hashitem_T *hi;
6965 affheader_T *ah;
6966 affentry_T *ae;
6967 regmatch_T regmatch;
6968 char_u newword[MAXWLEN];
6969 int retval = OK;
6970 int i, j;
6971 char_u *p;
6972 int use_flags;
6973 char_u *use_pfxlist;
6974 int use_pfxlen;
6975 int need_affix;
6976 char_u store_afflist[MAXWLEN];
6977 char_u pfx_pfxlist[MAXWLEN];
6978 size_t wordlen = STRLEN(word);
6979 int use_condit;
6981 todo = (int)ht->ht_used;
6982 for (hi = ht->ht_array; todo > 0 && retval == OK; ++hi)
6984 if (!HASHITEM_EMPTY(hi))
6986 --todo;
6987 ah = HI2AH(hi);
6989 /* Check that the affix combines, if required, and that the word
6990 * supports this affix. */
6991 if (((condit & CONDIT_COMB) == 0 || ah->ah_combine)
6992 && flag_in_afflist(affile->af_flagtype, afflist,
6993 ah->ah_flag))
6995 /* Loop over all affix entries with this name. */
6996 for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
6998 /* Check the condition. It's not logical to match case
6999 * here, but it is required for compatibility with
7000 * Myspell.
7001 * Another requirement from Myspell is that the chop
7002 * string is shorter than the word itself.
7003 * For prefixes, when "PFXPOSTPONE" was used, only do
7004 * prefixes with a chop string and/or flags.
7005 * When a previously added affix had CIRCUMFIX this one
7006 * must have it too, if it had not then this one must not
7007 * have one either. */
7008 regmatch.regprog = ae->ae_prog;
7009 regmatch.rm_ic = FALSE;
7010 if ((xht != NULL || !affile->af_pfxpostpone
7011 || ae->ae_chop != NULL
7012 || ae->ae_flags != NULL)
7013 && (ae->ae_chop == NULL
7014 || STRLEN(ae->ae_chop) < wordlen)
7015 && (ae->ae_prog == NULL
7016 || vim_regexec(&regmatch, word, (colnr_T)0))
7017 && (((condit & CONDIT_CFIX) == 0)
7018 == ((condit & CONDIT_AFF) == 0
7019 || ae->ae_flags == NULL
7020 || !flag_in_afflist(affile->af_flagtype,
7021 ae->ae_flags, affile->af_circumfix))))
7023 /* Match. Remove the chop and add the affix. */
7024 if (xht == NULL)
7026 /* prefix: chop/add at the start of the word */
7027 if (ae->ae_add == NULL)
7028 *newword = NUL;
7029 else
7030 STRCPY(newword, ae->ae_add);
7031 p = word;
7032 if (ae->ae_chop != NULL)
7034 /* Skip chop string. */
7035 #ifdef FEAT_MBYTE
7036 if (has_mbyte)
7038 i = mb_charlen(ae->ae_chop);
7039 for ( ; i > 0; --i)
7040 mb_ptr_adv(p);
7042 else
7043 #endif
7044 p += STRLEN(ae->ae_chop);
7046 STRCAT(newword, p);
7048 else
7050 /* suffix: chop/add at the end of the word */
7051 STRCPY(newword, word);
7052 if (ae->ae_chop != NULL)
7054 /* Remove chop string. */
7055 p = newword + STRLEN(newword);
7056 i = (int)MB_CHARLEN(ae->ae_chop);
7057 for ( ; i > 0; --i)
7058 mb_ptr_back(newword, p);
7059 *p = NUL;
7061 if (ae->ae_add != NULL)
7062 STRCAT(newword, ae->ae_add);
7065 use_flags = flags;
7066 use_pfxlist = pfxlist;
7067 use_pfxlen = pfxlen;
7068 need_affix = FALSE;
7069 use_condit = condit | CONDIT_COMB | CONDIT_AFF;
7070 if (ae->ae_flags != NULL)
7072 /* Extract flags from the affix list. */
7073 use_flags |= get_affix_flags(affile, ae->ae_flags);
7075 if (affile->af_needaffix != 0 && flag_in_afflist(
7076 affile->af_flagtype, ae->ae_flags,
7077 affile->af_needaffix))
7078 need_affix = TRUE;
7080 /* When there is a CIRCUMFIX flag the other affix
7081 * must also have it and we don't add the word
7082 * with one affix. */
7083 if (affile->af_circumfix != 0 && flag_in_afflist(
7084 affile->af_flagtype, ae->ae_flags,
7085 affile->af_circumfix))
7087 use_condit |= CONDIT_CFIX;
7088 if ((condit & CONDIT_CFIX) == 0)
7089 need_affix = TRUE;
7092 if (affile->af_pfxpostpone
7093 || spin->si_compflags != NULL)
7095 if (affile->af_pfxpostpone)
7096 /* Get prefix IDS from the affix list. */
7097 use_pfxlen = get_pfxlist(affile,
7098 ae->ae_flags, store_afflist);
7099 else
7100 use_pfxlen = 0;
7101 use_pfxlist = store_afflist;
7103 /* Combine the prefix IDs. Avoid adding the
7104 * same ID twice. */
7105 for (i = 0; i < pfxlen; ++i)
7107 for (j = 0; j < use_pfxlen; ++j)
7108 if (pfxlist[i] == use_pfxlist[j])
7109 break;
7110 if (j == use_pfxlen)
7111 use_pfxlist[use_pfxlen++] = pfxlist[i];
7114 if (spin->si_compflags != NULL)
7115 /* Get compound IDS from the affix list. */
7116 get_compflags(affile, ae->ae_flags,
7117 use_pfxlist + use_pfxlen);
7119 /* Combine the list of compound flags.
7120 * Concatenate them to the prefix IDs list.
7121 * Avoid adding the same ID twice. */
7122 for (i = pfxlen; pfxlist[i] != NUL; ++i)
7124 for (j = use_pfxlen;
7125 use_pfxlist[j] != NUL; ++j)
7126 if (pfxlist[i] == use_pfxlist[j])
7127 break;
7128 if (use_pfxlist[j] == NUL)
7130 use_pfxlist[j++] = pfxlist[i];
7131 use_pfxlist[j] = NUL;
7137 /* Obey a "COMPOUNDFORBIDFLAG" of the affix: don't
7138 * use the compound flags. */
7139 if (use_pfxlist != NULL && ae->ae_compforbid)
7141 vim_strncpy(pfx_pfxlist, use_pfxlist, use_pfxlen);
7142 use_pfxlist = pfx_pfxlist;
7145 /* When there are postponed prefixes... */
7146 if (spin->si_prefroot != NULL
7147 && spin->si_prefroot->wn_sibling != NULL)
7149 /* ... add a flag to indicate an affix was used. */
7150 use_flags |= WF_HAS_AFF;
7152 /* ... don't use a prefix list if combining
7153 * affixes is not allowed. But do use the
7154 * compound flags after them. */
7155 if (!ah->ah_combine && use_pfxlist != NULL)
7156 use_pfxlist += use_pfxlen;
7159 /* When compounding is supported and there is no
7160 * "COMPOUNDPERMITFLAG" then forbid compounding on the
7161 * side where the affix is applied. */
7162 if (spin->si_compflags != NULL && !ae->ae_comppermit)
7164 if (xht != NULL)
7165 use_flags |= WF_NOCOMPAFT;
7166 else
7167 use_flags |= WF_NOCOMPBEF;
7170 /* Store the modified word. */
7171 if (store_word(spin, newword, use_flags,
7172 spin->si_region, use_pfxlist,
7173 need_affix) == FAIL)
7174 retval = FAIL;
7176 /* When added a prefix or a first suffix and the affix
7177 * has flags may add a(nother) suffix. RECURSIVE! */
7178 if ((condit & CONDIT_SUF) && ae->ae_flags != NULL)
7179 if (store_aff_word(spin, newword, ae->ae_flags,
7180 affile, &affile->af_suff, xht,
7181 use_condit & (xht == NULL
7182 ? ~0 : ~CONDIT_SUF),
7183 use_flags, use_pfxlist, pfxlen) == FAIL)
7184 retval = FAIL;
7186 /* When added a suffix and combining is allowed also
7187 * try adding a prefix additionally. Both for the
7188 * word flags and for the affix flags. RECURSIVE! */
7189 if (xht != NULL && ah->ah_combine)
7191 if (store_aff_word(spin, newword,
7192 afflist, affile,
7193 xht, NULL, use_condit,
7194 use_flags, use_pfxlist,
7195 pfxlen) == FAIL
7196 || (ae->ae_flags != NULL
7197 && store_aff_word(spin, newword,
7198 ae->ae_flags, affile,
7199 xht, NULL, use_condit,
7200 use_flags, use_pfxlist,
7201 pfxlen) == FAIL))
7202 retval = FAIL;
7210 return retval;
7214 * Read a file with a list of words.
7216 static int
7217 spell_read_wordfile(spin, fname)
7218 spellinfo_T *spin;
7219 char_u *fname;
7221 FILE *fd;
7222 long lnum = 0;
7223 char_u rline[MAXLINELEN];
7224 char_u *line;
7225 char_u *pc = NULL;
7226 char_u *p;
7227 int l;
7228 int retval = OK;
7229 int did_word = FALSE;
7230 int non_ascii = 0;
7231 int flags;
7232 int regionmask;
7235 * Open the file.
7237 fd = mch_fopen((char *)fname, "r");
7238 if (fd == NULL)
7240 EMSG2(_(e_notopen), fname);
7241 return FAIL;
7244 vim_snprintf((char *)IObuff, IOSIZE, _("Reading word file %s ..."), fname);
7245 spell_message(spin, IObuff);
7248 * Read all the lines in the file one by one.
7250 while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
7252 line_breakcheck();
7253 ++lnum;
7255 /* Skip comment lines. */
7256 if (*rline == '#')
7257 continue;
7259 /* Remove CR, LF and white space from the end. */
7260 l = (int)STRLEN(rline);
7261 while (l > 0 && rline[l - 1] <= ' ')
7262 --l;
7263 if (l == 0)
7264 continue; /* empty or blank line */
7265 rline[l] = NUL;
7267 /* Convert from "/encoding={encoding}" to 'encoding' when needed. */
7268 vim_free(pc);
7269 #ifdef FEAT_MBYTE
7270 if (spin->si_conv.vc_type != CONV_NONE)
7272 pc = string_convert(&spin->si_conv, rline, NULL);
7273 if (pc == NULL)
7275 smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
7276 fname, lnum, rline);
7277 continue;
7279 line = pc;
7281 else
7282 #endif
7284 pc = NULL;
7285 line = rline;
7288 if (*line == '/')
7290 ++line;
7291 if (STRNCMP(line, "encoding=", 9) == 0)
7293 if (spin->si_conv.vc_type != CONV_NONE)
7294 smsg((char_u *)_("Duplicate /encoding= line ignored in %s line %d: %s"),
7295 fname, lnum, line - 1);
7296 else if (did_word)
7297 smsg((char_u *)_("/encoding= line after word ignored in %s line %d: %s"),
7298 fname, lnum, line - 1);
7299 else
7301 #ifdef FEAT_MBYTE
7302 char_u *enc;
7304 /* Setup for conversion to 'encoding'. */
7305 line += 9;
7306 enc = enc_canonize(line);
7307 if (enc != NULL && !spin->si_ascii
7308 && convert_setup(&spin->si_conv, enc,
7309 p_enc) == FAIL)
7310 smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
7311 fname, line, p_enc);
7312 vim_free(enc);
7313 spin->si_conv.vc_fail = TRUE;
7314 #else
7315 smsg((char_u *)_("Conversion in %s not supported"), fname);
7316 #endif
7318 continue;
7321 if (STRNCMP(line, "regions=", 8) == 0)
7323 if (spin->si_region_count > 1)
7324 smsg((char_u *)_("Duplicate /regions= line ignored in %s line %d: %s"),
7325 fname, lnum, line);
7326 else
7328 line += 8;
7329 if (STRLEN(line) > 16)
7330 smsg((char_u *)_("Too many regions in %s line %d: %s"),
7331 fname, lnum, line);
7332 else
7334 spin->si_region_count = (int)STRLEN(line) / 2;
7335 STRCPY(spin->si_region_name, line);
7337 /* Adjust the mask for a word valid in all regions. */
7338 spin->si_region = (1 << spin->si_region_count) - 1;
7341 continue;
7344 smsg((char_u *)_("/ line ignored in %s line %d: %s"),
7345 fname, lnum, line - 1);
7346 continue;
7349 flags = 0;
7350 regionmask = spin->si_region;
7352 /* Check for flags and region after a slash. */
7353 p = vim_strchr(line, '/');
7354 if (p != NULL)
7356 *p++ = NUL;
7357 while (*p != NUL)
7359 if (*p == '=') /* keep-case word */
7360 flags |= WF_KEEPCAP | WF_FIXCAP;
7361 else if (*p == '!') /* Bad, bad, wicked word. */
7362 flags |= WF_BANNED;
7363 else if (*p == '?') /* Rare word. */
7364 flags |= WF_RARE;
7365 else if (VIM_ISDIGIT(*p)) /* region number(s) */
7367 if ((flags & WF_REGION) == 0) /* first one */
7368 regionmask = 0;
7369 flags |= WF_REGION;
7371 l = *p - '0';
7372 if (l > spin->si_region_count)
7374 smsg((char_u *)_("Invalid region nr in %s line %d: %s"),
7375 fname, lnum, p);
7376 break;
7378 regionmask |= 1 << (l - 1);
7380 else
7382 smsg((char_u *)_("Unrecognized flags in %s line %d: %s"),
7383 fname, lnum, p);
7384 break;
7386 ++p;
7390 /* Skip non-ASCII words when "spin->si_ascii" is TRUE. */
7391 if (spin->si_ascii && has_non_ascii(line))
7393 ++non_ascii;
7394 continue;
7397 /* Normal word: store it. */
7398 if (store_word(spin, line, flags, regionmask, NULL, FALSE) == FAIL)
7400 retval = FAIL;
7401 break;
7403 did_word = TRUE;
7406 vim_free(pc);
7407 fclose(fd);
7409 if (spin->si_ascii && non_ascii > 0)
7411 vim_snprintf((char *)IObuff, IOSIZE,
7412 _("Ignored %d words with non-ASCII characters"), non_ascii);
7413 spell_message(spin, IObuff);
7416 return retval;
7420 * Get part of an sblock_T, "len" bytes long.
7421 * This avoids calling free() for every little struct we use (and keeping
7422 * track of them).
7423 * The memory is cleared to all zeros.
7424 * Returns NULL when out of memory.
7426 static void *
7427 getroom(spin, len, align)
7428 spellinfo_T *spin;
7429 size_t len; /* length needed */
7430 int align; /* align for pointer */
7432 char_u *p;
7433 sblock_T *bl = spin->si_blocks;
7435 if (align && bl != NULL)
7436 /* Round size up for alignment. On some systems structures need to be
7437 * aligned to the size of a pointer (e.g., SPARC). */
7438 bl->sb_used = (bl->sb_used + sizeof(char *) - 1)
7439 & ~(sizeof(char *) - 1);
7441 if (bl == NULL || bl->sb_used + len > SBLOCKSIZE)
7443 /* Allocate a block of memory. This is not freed until much later. */
7444 bl = (sblock_T *)alloc_clear((unsigned)(sizeof(sblock_T) + SBLOCKSIZE));
7445 if (bl == NULL)
7446 return NULL;
7447 bl->sb_next = spin->si_blocks;
7448 spin->si_blocks = bl;
7449 bl->sb_used = 0;
7450 ++spin->si_blocks_cnt;
7453 p = bl->sb_data + bl->sb_used;
7454 bl->sb_used += (int)len;
7456 return p;
7460 * Make a copy of a string into memory allocated with getroom().
7462 static char_u *
7463 getroom_save(spin, s)
7464 spellinfo_T *spin;
7465 char_u *s;
7467 char_u *sc;
7469 sc = (char_u *)getroom(spin, STRLEN(s) + 1, FALSE);
7470 if (sc != NULL)
7471 STRCPY(sc, s);
7472 return sc;
7477 * Free the list of allocated sblock_T.
7479 static void
7480 free_blocks(bl)
7481 sblock_T *bl;
7483 sblock_T *next;
7485 while (bl != NULL)
7487 next = bl->sb_next;
7488 vim_free(bl);
7489 bl = next;
7494 * Allocate the root of a word tree.
7496 static wordnode_T *
7497 wordtree_alloc(spin)
7498 spellinfo_T *spin;
7500 return (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
7504 * Store a word in the tree(s).
7505 * Always store it in the case-folded tree. For a keep-case word this is
7506 * useful when the word can also be used with all caps (no WF_FIXCAP flag) and
7507 * used to find suggestions.
7508 * For a keep-case word also store it in the keep-case tree.
7509 * When "pfxlist" is not NULL store the word for each postponed prefix ID and
7510 * compound flag.
7512 static int
7513 store_word(spin, word, flags, region, pfxlist, need_affix)
7514 spellinfo_T *spin;
7515 char_u *word;
7516 int flags; /* extra flags, WF_BANNED */
7517 int region; /* supported region(s) */
7518 char_u *pfxlist; /* list of prefix IDs or NULL */
7519 int need_affix; /* only store word with affix ID */
7521 int len = (int)STRLEN(word);
7522 int ct = captype(word, word + len);
7523 char_u foldword[MAXWLEN];
7524 int res = OK;
7525 char_u *p;
7527 (void)spell_casefold(word, len, foldword, MAXWLEN);
7528 for (p = pfxlist; res == OK; ++p)
7530 if (!need_affix || (p != NULL && *p != NUL))
7531 res = tree_add_word(spin, foldword, spin->si_foldroot, ct | flags,
7532 region, p == NULL ? 0 : *p);
7533 if (p == NULL || *p == NUL)
7534 break;
7536 ++spin->si_foldwcount;
7538 if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP)))
7540 for (p = pfxlist; res == OK; ++p)
7542 if (!need_affix || (p != NULL && *p != NUL))
7543 res = tree_add_word(spin, word, spin->si_keeproot, flags,
7544 region, p == NULL ? 0 : *p);
7545 if (p == NULL || *p == NUL)
7546 break;
7548 ++spin->si_keepwcount;
7550 return res;
7554 * Add word "word" to a word tree at "root".
7555 * When "flags" < 0 we are adding to the prefix tree where "flags" is used for
7556 * "rare" and "region" is the condition nr.
7557 * Returns FAIL when out of memory.
7559 static int
7560 tree_add_word(spin, word, root, flags, region, affixID)
7561 spellinfo_T *spin;
7562 char_u *word;
7563 wordnode_T *root;
7564 int flags;
7565 int region;
7566 int affixID;
7568 wordnode_T *node = root;
7569 wordnode_T *np;
7570 wordnode_T *copyp, **copyprev;
7571 wordnode_T **prev = NULL;
7572 int i;
7574 /* Add each byte of the word to the tree, including the NUL at the end. */
7575 for (i = 0; ; ++i)
7577 /* When there is more than one reference to this node we need to make
7578 * a copy, so that we can modify it. Copy the whole list of siblings
7579 * (we don't optimize for a partly shared list of siblings). */
7580 if (node != NULL && node->wn_refs > 1)
7582 --node->wn_refs;
7583 copyprev = prev;
7584 for (copyp = node; copyp != NULL; copyp = copyp->wn_sibling)
7586 /* Allocate a new node and copy the info. */
7587 np = get_wordnode(spin);
7588 if (np == NULL)
7589 return FAIL;
7590 np->wn_child = copyp->wn_child;
7591 if (np->wn_child != NULL)
7592 ++np->wn_child->wn_refs; /* child gets extra ref */
7593 np->wn_byte = copyp->wn_byte;
7594 if (np->wn_byte == NUL)
7596 np->wn_flags = copyp->wn_flags;
7597 np->wn_region = copyp->wn_region;
7598 np->wn_affixID = copyp->wn_affixID;
7601 /* Link the new node in the list, there will be one ref. */
7602 np->wn_refs = 1;
7603 if (copyprev != NULL)
7604 *copyprev = np;
7605 copyprev = &np->wn_sibling;
7607 /* Let "node" point to the head of the copied list. */
7608 if (copyp == node)
7609 node = np;
7613 /* Look for the sibling that has the same character. They are sorted
7614 * on byte value, thus stop searching when a sibling is found with a
7615 * higher byte value. For zero bytes (end of word) the sorting is
7616 * done on flags and then on affixID. */
7617 while (node != NULL
7618 && (node->wn_byte < word[i]
7619 || (node->wn_byte == NUL
7620 && (flags < 0
7621 ? node->wn_affixID < (unsigned)affixID
7622 : (node->wn_flags < (unsigned)(flags & WN_MASK)
7623 || (node->wn_flags == (flags & WN_MASK)
7624 && (spin->si_sugtree
7625 ? (node->wn_region & 0xffff) < region
7626 : node->wn_affixID
7627 < (unsigned)affixID)))))))
7629 prev = &node->wn_sibling;
7630 node = *prev;
7632 if (node == NULL
7633 || node->wn_byte != word[i]
7634 || (word[i] == NUL
7635 && (flags < 0
7636 || spin->si_sugtree
7637 || node->wn_flags != (flags & WN_MASK)
7638 || node->wn_affixID != affixID)))
7640 /* Allocate a new node. */
7641 np = get_wordnode(spin);
7642 if (np == NULL)
7643 return FAIL;
7644 np->wn_byte = word[i];
7646 /* If "node" is NULL this is a new child or the end of the sibling
7647 * list: ref count is one. Otherwise use ref count of sibling and
7648 * make ref count of sibling one (matters when inserting in front
7649 * of the list of siblings). */
7650 if (node == NULL)
7651 np->wn_refs = 1;
7652 else
7654 np->wn_refs = node->wn_refs;
7655 node->wn_refs = 1;
7657 *prev = np;
7658 np->wn_sibling = node;
7659 node = np;
7662 if (word[i] == NUL)
7664 node->wn_flags = flags;
7665 node->wn_region |= region;
7666 node->wn_affixID = affixID;
7667 break;
7669 prev = &node->wn_child;
7670 node = *prev;
7672 #ifdef SPELL_PRINTTREE
7673 smsg("Added \"%s\"", word);
7674 spell_print_tree(root->wn_sibling);
7675 #endif
7677 /* count nr of words added since last message */
7678 ++spin->si_msg_count;
7680 if (spin->si_compress_cnt > 1)
7682 if (--spin->si_compress_cnt == 1)
7683 /* Did enough words to lower the block count limit. */
7684 spin->si_blocks_cnt += compress_inc;
7688 * When we have allocated lots of memory we need to compress the word tree
7689 * to free up some room. But compression is slow, and we might actually
7690 * need that room, thus only compress in the following situations:
7691 * 1. When not compressed before (si_compress_cnt == 0): when using
7692 * "compress_start" blocks.
7693 * 2. When compressed before and used "compress_inc" blocks before
7694 * adding "compress_added" words (si_compress_cnt > 1).
7695 * 3. When compressed before, added "compress_added" words
7696 * (si_compress_cnt == 1) and the number of free nodes drops below the
7697 * maximum word length.
7699 #ifndef SPELL_PRINTTREE
7700 if (spin->si_compress_cnt == 1
7701 ? spin->si_free_count < MAXWLEN
7702 : spin->si_blocks_cnt >= compress_start)
7703 #endif
7705 /* Decrement the block counter. The effect is that we compress again
7706 * when the freed up room has been used and another "compress_inc"
7707 * blocks have been allocated. Unless "compress_added" words have
7708 * been added, then the limit is put back again. */
7709 spin->si_blocks_cnt -= compress_inc;
7710 spin->si_compress_cnt = compress_added;
7712 if (spin->si_verbose)
7714 msg_start();
7715 msg_puts((char_u *)_(msg_compressing));
7716 msg_clr_eos();
7717 msg_didout = FALSE;
7718 msg_col = 0;
7719 out_flush();
7722 /* Compress both trees. Either they both have many nodes, which makes
7723 * compression useful, or one of them is small, which means
7724 * compression goes fast. But when filling the souldfold word tree
7725 * there is no keep-case tree. */
7726 wordtree_compress(spin, spin->si_foldroot);
7727 if (affixID >= 0)
7728 wordtree_compress(spin, spin->si_keeproot);
7731 return OK;
7735 * Check the 'mkspellmem' option. Return FAIL if it's wrong.
7736 * Sets "sps_flags".
7739 spell_check_msm()
7741 char_u *p = p_msm;
7742 long start = 0;
7743 long incr = 0;
7744 long added = 0;
7746 if (!VIM_ISDIGIT(*p))
7747 return FAIL;
7748 /* block count = (value * 1024) / SBLOCKSIZE (but avoid overflow)*/
7749 start = (getdigits(&p) * 10) / (SBLOCKSIZE / 102);
7750 if (*p != ',')
7751 return FAIL;
7752 ++p;
7753 if (!VIM_ISDIGIT(*p))
7754 return FAIL;
7755 incr = (getdigits(&p) * 102) / (SBLOCKSIZE / 10);
7756 if (*p != ',')
7757 return FAIL;
7758 ++p;
7759 if (!VIM_ISDIGIT(*p))
7760 return FAIL;
7761 added = getdigits(&p) * 1024;
7762 if (*p != NUL)
7763 return FAIL;
7765 if (start == 0 || incr == 0 || added == 0 || incr > start)
7766 return FAIL;
7768 compress_start = start;
7769 compress_inc = incr;
7770 compress_added = added;
7771 return OK;
7776 * Get a wordnode_T, either from the list of previously freed nodes or
7777 * allocate a new one.
7779 static wordnode_T *
7780 get_wordnode(spin)
7781 spellinfo_T *spin;
7783 wordnode_T *n;
7785 if (spin->si_first_free == NULL)
7786 n = (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
7787 else
7789 n = spin->si_first_free;
7790 spin->si_first_free = n->wn_child;
7791 vim_memset(n, 0, sizeof(wordnode_T));
7792 --spin->si_free_count;
7794 #ifdef SPELL_PRINTTREE
7795 n->wn_nr = ++spin->si_wordnode_nr;
7796 #endif
7797 return n;
7801 * Decrement the reference count on a node (which is the head of a list of
7802 * siblings). If the reference count becomes zero free the node and its
7803 * siblings.
7804 * Returns the number of nodes actually freed.
7806 static int
7807 deref_wordnode(spin, node)
7808 spellinfo_T *spin;
7809 wordnode_T *node;
7811 wordnode_T *np;
7812 int cnt = 0;
7814 if (--node->wn_refs == 0)
7816 for (np = node; np != NULL; np = np->wn_sibling)
7818 if (np->wn_child != NULL)
7819 cnt += deref_wordnode(spin, np->wn_child);
7820 free_wordnode(spin, np);
7821 ++cnt;
7823 ++cnt; /* length field */
7825 return cnt;
7829 * Free a wordnode_T for re-use later.
7830 * Only the "wn_child" field becomes invalid.
7832 static void
7833 free_wordnode(spin, n)
7834 spellinfo_T *spin;
7835 wordnode_T *n;
7837 n->wn_child = spin->si_first_free;
7838 spin->si_first_free = n;
7839 ++spin->si_free_count;
7843 * Compress a tree: find tails that are identical and can be shared.
7845 static void
7846 wordtree_compress(spin, root)
7847 spellinfo_T *spin;
7848 wordnode_T *root;
7850 hashtab_T ht;
7851 int n;
7852 int tot = 0;
7853 int perc;
7855 /* Skip the root itself, it's not actually used. The first sibling is the
7856 * start of the tree. */
7857 if (root->wn_sibling != NULL)
7859 hash_init(&ht);
7860 n = node_compress(spin, root->wn_sibling, &ht, &tot);
7862 #ifndef SPELL_PRINTTREE
7863 if (spin->si_verbose || p_verbose > 2)
7864 #endif
7866 if (tot > 1000000)
7867 perc = (tot - n) / (tot / 100);
7868 else if (tot == 0)
7869 perc = 0;
7870 else
7871 perc = (tot - n) * 100 / tot;
7872 vim_snprintf((char *)IObuff, IOSIZE,
7873 _("Compressed %d of %d nodes; %d (%d%%) remaining"),
7874 n, tot, tot - n, perc);
7875 spell_message(spin, IObuff);
7877 #ifdef SPELL_PRINTTREE
7878 spell_print_tree(root->wn_sibling);
7879 #endif
7880 hash_clear(&ht);
7885 * Compress a node, its siblings and its children, depth first.
7886 * Returns the number of compressed nodes.
7888 static int
7889 node_compress(spin, node, ht, tot)
7890 spellinfo_T *spin;
7891 wordnode_T *node;
7892 hashtab_T *ht;
7893 int *tot; /* total count of nodes before compressing,
7894 incremented while going through the tree */
7896 wordnode_T *np;
7897 wordnode_T *tp;
7898 wordnode_T *child;
7899 hash_T hash;
7900 hashitem_T *hi;
7901 int len = 0;
7902 unsigned nr, n;
7903 int compressed = 0;
7906 * Go through the list of siblings. Compress each child and then try
7907 * finding an identical child to replace it.
7908 * Note that with "child" we mean not just the node that is pointed to,
7909 * but the whole list of siblings of which the child node is the first.
7911 for (np = node; np != NULL && !got_int; np = np->wn_sibling)
7913 ++len;
7914 if ((child = np->wn_child) != NULL)
7916 /* Compress the child first. This fills hashkey. */
7917 compressed += node_compress(spin, child, ht, tot);
7919 /* Try to find an identical child. */
7920 hash = hash_hash(child->wn_u1.hashkey);
7921 hi = hash_lookup(ht, child->wn_u1.hashkey, hash);
7922 if (!HASHITEM_EMPTY(hi))
7924 /* There are children we encountered before with a hash value
7925 * identical to the current child. Now check if there is one
7926 * that is really identical. */
7927 for (tp = HI2WN(hi); tp != NULL; tp = tp->wn_u2.next)
7928 if (node_equal(child, tp))
7930 /* Found one! Now use that child in place of the
7931 * current one. This means the current child and all
7932 * its siblings is unlinked from the tree. */
7933 ++tp->wn_refs;
7934 compressed += deref_wordnode(spin, child);
7935 np->wn_child = tp;
7936 break;
7938 if (tp == NULL)
7940 /* No other child with this hash value equals the child of
7941 * the node, add it to the linked list after the first
7942 * item. */
7943 tp = HI2WN(hi);
7944 child->wn_u2.next = tp->wn_u2.next;
7945 tp->wn_u2.next = child;
7948 else
7949 /* No other child has this hash value, add it to the
7950 * hashtable. */
7951 hash_add_item(ht, hi, child->wn_u1.hashkey, hash);
7954 *tot += len + 1; /* add one for the node that stores the length */
7957 * Make a hash key for the node and its siblings, so that we can quickly
7958 * find a lookalike node. This must be done after compressing the sibling
7959 * list, otherwise the hash key would become invalid by the compression.
7961 node->wn_u1.hashkey[0] = len;
7962 nr = 0;
7963 for (np = node; np != NULL; np = np->wn_sibling)
7965 if (np->wn_byte == NUL)
7966 /* end node: use wn_flags, wn_region and wn_affixID */
7967 n = np->wn_flags + (np->wn_region << 8) + (np->wn_affixID << 16);
7968 else
7969 /* byte node: use the byte value and the child pointer */
7970 n = (unsigned)(np->wn_byte + ((long_u)np->wn_child << 8));
7971 nr = nr * 101 + n;
7974 /* Avoid NUL bytes, it terminates the hash key. */
7975 n = nr & 0xff;
7976 node->wn_u1.hashkey[1] = n == 0 ? 1 : n;
7977 n = (nr >> 8) & 0xff;
7978 node->wn_u1.hashkey[2] = n == 0 ? 1 : n;
7979 n = (nr >> 16) & 0xff;
7980 node->wn_u1.hashkey[3] = n == 0 ? 1 : n;
7981 n = (nr >> 24) & 0xff;
7982 node->wn_u1.hashkey[4] = n == 0 ? 1 : n;
7983 node->wn_u1.hashkey[5] = NUL;
7985 /* Check for CTRL-C pressed now and then. */
7986 fast_breakcheck();
7988 return compressed;
7992 * Return TRUE when two nodes have identical siblings and children.
7994 static int
7995 node_equal(n1, n2)
7996 wordnode_T *n1;
7997 wordnode_T *n2;
7999 wordnode_T *p1;
8000 wordnode_T *p2;
8002 for (p1 = n1, p2 = n2; p1 != NULL && p2 != NULL;
8003 p1 = p1->wn_sibling, p2 = p2->wn_sibling)
8004 if (p1->wn_byte != p2->wn_byte
8005 || (p1->wn_byte == NUL
8006 ? (p1->wn_flags != p2->wn_flags
8007 || p1->wn_region != p2->wn_region
8008 || p1->wn_affixID != p2->wn_affixID)
8009 : (p1->wn_child != p2->wn_child)))
8010 break;
8012 return p1 == NULL && p2 == NULL;
8016 * Write a number to file "fd", MSB first, in "len" bytes.
8018 void
8019 put_bytes(fd, nr, len)
8020 FILE *fd;
8021 long_u nr;
8022 int len;
8024 int i;
8026 for (i = len - 1; i >= 0; --i)
8027 putc((int)(nr >> (i * 8)), fd);
8030 #ifdef _MSC_VER
8031 # if (_MSC_VER <= 1200)
8032 /* This line is required for VC6 without the service pack. Also see the
8033 * matching #pragma below. */
8034 # pragma optimize("", off)
8035 # endif
8036 #endif
8039 * Write spin->si_sugtime to file "fd".
8041 static void
8042 put_sugtime(spin, fd)
8043 spellinfo_T *spin;
8044 FILE *fd;
8046 int c;
8047 int i;
8049 /* time_t can be up to 8 bytes in size, more than long_u, thus we
8050 * can't use put_bytes() here. */
8051 for (i = 7; i >= 0; --i)
8052 if (i + 1 > (int)sizeof(time_t))
8053 /* ">>" doesn't work well when shifting more bits than avail */
8054 putc(0, fd);
8055 else
8057 c = (unsigned)spin->si_sugtime >> (i * 8);
8058 putc(c, fd);
8062 #ifdef _MSC_VER
8063 # if (_MSC_VER <= 1200)
8064 # pragma optimize("", on)
8065 # endif
8066 #endif
8068 static int
8069 #ifdef __BORLANDC__
8070 _RTLENTRYF
8071 #endif
8072 rep_compare __ARGS((const void *s1, const void *s2));
8075 * Function given to qsort() to sort the REP items on "from" string.
8077 static int
8078 #ifdef __BORLANDC__
8079 _RTLENTRYF
8080 #endif
8081 rep_compare(s1, s2)
8082 const void *s1;
8083 const void *s2;
8085 fromto_T *p1 = (fromto_T *)s1;
8086 fromto_T *p2 = (fromto_T *)s2;
8088 return STRCMP(p1->ft_from, p2->ft_from);
8092 * Write the Vim .spl file "fname".
8093 * Return FAIL or OK;
8095 static int
8096 write_vim_spell(spin, fname)
8097 spellinfo_T *spin;
8098 char_u *fname;
8100 FILE *fd;
8101 int regionmask;
8102 int round;
8103 wordnode_T *tree;
8104 int nodecount;
8105 int i;
8106 int l;
8107 garray_T *gap;
8108 fromto_T *ftp;
8109 char_u *p;
8110 int rr;
8111 int retval = OK;
8112 size_t fwv = 1; /* collect return value of fwrite() to avoid
8113 warnings from picky compiler */
8115 fd = mch_fopen((char *)fname, "w");
8116 if (fd == NULL)
8118 EMSG2(_(e_notopen), fname);
8119 return FAIL;
8122 /* <HEADER>: <fileID> <versionnr> */
8123 /* <fileID> */
8124 fwv &= fwrite(VIMSPELLMAGIC, VIMSPELLMAGICL, (size_t)1, fd);
8125 if (fwv != (size_t)1)
8126 /* Catch first write error, don't try writing more. */
8127 goto theend;
8129 putc(VIMSPELLVERSION, fd); /* <versionnr> */
8132 * <SECTIONS>: <section> ... <sectionend>
8135 /* SN_INFO: <infotext> */
8136 if (spin->si_info != NULL)
8138 putc(SN_INFO, fd); /* <sectionID> */
8139 putc(0, fd); /* <sectionflags> */
8141 i = (int)STRLEN(spin->si_info);
8142 put_bytes(fd, (long_u)i, 4); /* <sectionlen> */
8143 fwv &= fwrite(spin->si_info, (size_t)i, (size_t)1, fd); /* <infotext> */
8146 /* SN_REGION: <regionname> ...
8147 * Write the region names only if there is more than one. */
8148 if (spin->si_region_count > 1)
8150 putc(SN_REGION, fd); /* <sectionID> */
8151 putc(SNF_REQUIRED, fd); /* <sectionflags> */
8152 l = spin->si_region_count * 2;
8153 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8154 fwv &= fwrite(spin->si_region_name, (size_t)l, (size_t)1, fd);
8155 /* <regionname> ... */
8156 regionmask = (1 << spin->si_region_count) - 1;
8158 else
8159 regionmask = 0;
8161 /* SN_CHARFLAGS: <charflagslen> <charflags> <folcharslen> <folchars>
8163 * The table with character flags and the table for case folding.
8164 * This makes sure the same characters are recognized as word characters
8165 * when generating an when using a spell file.
8166 * Skip this for ASCII, the table may conflict with the one used for
8167 * 'encoding'.
8168 * Also skip this for an .add.spl file, the main spell file must contain
8169 * the table (avoids that it conflicts). File is shorter too.
8171 if (!spin->si_ascii && !spin->si_add)
8173 char_u folchars[128 * 8];
8174 int flags;
8176 putc(SN_CHARFLAGS, fd); /* <sectionID> */
8177 putc(SNF_REQUIRED, fd); /* <sectionflags> */
8179 /* Form the <folchars> string first, we need to know its length. */
8180 l = 0;
8181 for (i = 128; i < 256; ++i)
8183 #ifdef FEAT_MBYTE
8184 if (has_mbyte)
8185 l += mb_char2bytes(spelltab.st_fold[i], folchars + l);
8186 else
8187 #endif
8188 folchars[l++] = spelltab.st_fold[i];
8190 put_bytes(fd, (long_u)(1 + 128 + 2 + l), 4); /* <sectionlen> */
8192 fputc(128, fd); /* <charflagslen> */
8193 for (i = 128; i < 256; ++i)
8195 flags = 0;
8196 if (spelltab.st_isw[i])
8197 flags |= CF_WORD;
8198 if (spelltab.st_isu[i])
8199 flags |= CF_UPPER;
8200 fputc(flags, fd); /* <charflags> */
8203 put_bytes(fd, (long_u)l, 2); /* <folcharslen> */
8204 fwv &= fwrite(folchars, (size_t)l, (size_t)1, fd); /* <folchars> */
8207 /* SN_MIDWORD: <midword> */
8208 if (spin->si_midword != NULL)
8210 putc(SN_MIDWORD, fd); /* <sectionID> */
8211 putc(SNF_REQUIRED, fd); /* <sectionflags> */
8213 i = (int)STRLEN(spin->si_midword);
8214 put_bytes(fd, (long_u)i, 4); /* <sectionlen> */
8215 fwv &= fwrite(spin->si_midword, (size_t)i, (size_t)1, fd);
8216 /* <midword> */
8219 /* SN_PREFCOND: <prefcondcnt> <prefcond> ... */
8220 if (spin->si_prefcond.ga_len > 0)
8222 putc(SN_PREFCOND, fd); /* <sectionID> */
8223 putc(SNF_REQUIRED, fd); /* <sectionflags> */
8225 l = write_spell_prefcond(NULL, &spin->si_prefcond);
8226 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8228 write_spell_prefcond(fd, &spin->si_prefcond);
8231 /* SN_REP: <repcount> <rep> ...
8232 * SN_SAL: <salflags> <salcount> <sal> ...
8233 * SN_REPSAL: <repcount> <rep> ... */
8235 /* round 1: SN_REP section
8236 * round 2: SN_SAL section (unless SN_SOFO is used)
8237 * round 3: SN_REPSAL section */
8238 for (round = 1; round <= 3; ++round)
8240 if (round == 1)
8241 gap = &spin->si_rep;
8242 else if (round == 2)
8244 /* Don't write SN_SAL when using a SN_SOFO section */
8245 if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
8246 continue;
8247 gap = &spin->si_sal;
8249 else
8250 gap = &spin->si_repsal;
8252 /* Don't write the section if there are no items. */
8253 if (gap->ga_len == 0)
8254 continue;
8256 /* Sort the REP/REPSAL items. */
8257 if (round != 2)
8258 qsort(gap->ga_data, (size_t)gap->ga_len,
8259 sizeof(fromto_T), rep_compare);
8261 i = round == 1 ? SN_REP : (round == 2 ? SN_SAL : SN_REPSAL);
8262 putc(i, fd); /* <sectionID> */
8264 /* This is for making suggestions, section is not required. */
8265 putc(0, fd); /* <sectionflags> */
8267 /* Compute the length of what follows. */
8268 l = 2; /* count <repcount> or <salcount> */
8269 for (i = 0; i < gap->ga_len; ++i)
8271 ftp = &((fromto_T *)gap->ga_data)[i];
8272 l += 1 + (int)STRLEN(ftp->ft_from); /* count <*fromlen> and <*from> */
8273 l += 1 + (int)STRLEN(ftp->ft_to); /* count <*tolen> and <*to> */
8275 if (round == 2)
8276 ++l; /* count <salflags> */
8277 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8279 if (round == 2)
8281 i = 0;
8282 if (spin->si_followup)
8283 i |= SAL_F0LLOWUP;
8284 if (spin->si_collapse)
8285 i |= SAL_COLLAPSE;
8286 if (spin->si_rem_accents)
8287 i |= SAL_REM_ACCENTS;
8288 putc(i, fd); /* <salflags> */
8291 put_bytes(fd, (long_u)gap->ga_len, 2); /* <repcount> or <salcount> */
8292 for (i = 0; i < gap->ga_len; ++i)
8294 /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */
8295 /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */
8296 ftp = &((fromto_T *)gap->ga_data)[i];
8297 for (rr = 1; rr <= 2; ++rr)
8299 p = rr == 1 ? ftp->ft_from : ftp->ft_to;
8300 l = (int)STRLEN(p);
8301 putc(l, fd);
8302 if (l > 0)
8303 fwv &= fwrite(p, l, (size_t)1, fd);
8309 /* SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
8310 * This is for making suggestions, section is not required. */
8311 if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
8313 putc(SN_SOFO, fd); /* <sectionID> */
8314 putc(0, fd); /* <sectionflags> */
8316 l = (int)STRLEN(spin->si_sofofr);
8317 put_bytes(fd, (long_u)(l + STRLEN(spin->si_sofoto) + 4), 4);
8318 /* <sectionlen> */
8320 put_bytes(fd, (long_u)l, 2); /* <sofofromlen> */
8321 fwv &= fwrite(spin->si_sofofr, l, (size_t)1, fd); /* <sofofrom> */
8323 l = (int)STRLEN(spin->si_sofoto);
8324 put_bytes(fd, (long_u)l, 2); /* <sofotolen> */
8325 fwv &= fwrite(spin->si_sofoto, l, (size_t)1, fd); /* <sofoto> */
8328 /* SN_WORDS: <word> ...
8329 * This is for making suggestions, section is not required. */
8330 if (spin->si_commonwords.ht_used > 0)
8332 putc(SN_WORDS, fd); /* <sectionID> */
8333 putc(0, fd); /* <sectionflags> */
8335 /* round 1: count the bytes
8336 * round 2: write the bytes */
8337 for (round = 1; round <= 2; ++round)
8339 int todo;
8340 int len = 0;
8341 hashitem_T *hi;
8343 todo = (int)spin->si_commonwords.ht_used;
8344 for (hi = spin->si_commonwords.ht_array; todo > 0; ++hi)
8345 if (!HASHITEM_EMPTY(hi))
8347 l = (int)STRLEN(hi->hi_key) + 1;
8348 len += l;
8349 if (round == 2) /* <word> */
8350 fwv &= fwrite(hi->hi_key, (size_t)l, (size_t)1, fd);
8351 --todo;
8353 if (round == 1)
8354 put_bytes(fd, (long_u)len, 4); /* <sectionlen> */
8358 /* SN_MAP: <mapstr>
8359 * This is for making suggestions, section is not required. */
8360 if (spin->si_map.ga_len > 0)
8362 putc(SN_MAP, fd); /* <sectionID> */
8363 putc(0, fd); /* <sectionflags> */
8364 l = spin->si_map.ga_len;
8365 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8366 fwv &= fwrite(spin->si_map.ga_data, (size_t)l, (size_t)1, fd);
8367 /* <mapstr> */
8370 /* SN_SUGFILE: <timestamp>
8371 * This is used to notify that a .sug file may be available and at the
8372 * same time allows for checking that a .sug file that is found matches
8373 * with this .spl file. That's because the word numbers must be exactly
8374 * right. */
8375 if (!spin->si_nosugfile
8376 && (spin->si_sal.ga_len > 0
8377 || (spin->si_sofofr != NULL && spin->si_sofoto != NULL)))
8379 putc(SN_SUGFILE, fd); /* <sectionID> */
8380 putc(0, fd); /* <sectionflags> */
8381 put_bytes(fd, (long_u)8, 4); /* <sectionlen> */
8383 /* Set si_sugtime and write it to the file. */
8384 spin->si_sugtime = time(NULL);
8385 put_sugtime(spin, fd); /* <timestamp> */
8388 /* SN_NOSPLITSUGS: nothing
8389 * This is used to notify that no suggestions with word splits are to be
8390 * made. */
8391 if (spin->si_nosplitsugs)
8393 putc(SN_NOSPLITSUGS, fd); /* <sectionID> */
8394 putc(0, fd); /* <sectionflags> */
8395 put_bytes(fd, (long_u)0, 4); /* <sectionlen> */
8398 /* SN_COMPOUND: compound info.
8399 * We don't mark it required, when not supported all compound words will
8400 * be bad words. */
8401 if (spin->si_compflags != NULL)
8403 putc(SN_COMPOUND, fd); /* <sectionID> */
8404 putc(0, fd); /* <sectionflags> */
8406 l = (int)STRLEN(spin->si_compflags);
8407 for (i = 0; i < spin->si_comppat.ga_len; ++i)
8408 l += (int)STRLEN(((char_u **)(spin->si_comppat.ga_data))[i]) + 1;
8409 put_bytes(fd, (long_u)(l + 7), 4); /* <sectionlen> */
8411 putc(spin->si_compmax, fd); /* <compmax> */
8412 putc(spin->si_compminlen, fd); /* <compminlen> */
8413 putc(spin->si_compsylmax, fd); /* <compsylmax> */
8414 putc(0, fd); /* for Vim 7.0b compatibility */
8415 putc(spin->si_compoptions, fd); /* <compoptions> */
8416 put_bytes(fd, (long_u)spin->si_comppat.ga_len, 2);
8417 /* <comppatcount> */
8418 for (i = 0; i < spin->si_comppat.ga_len; ++i)
8420 p = ((char_u **)(spin->si_comppat.ga_data))[i];
8421 putc((int)STRLEN(p), fd); /* <comppatlen> */
8422 fwv &= fwrite(p, (size_t)STRLEN(p), (size_t)1, fd);
8423 /* <comppattext> */
8425 /* <compflags> */
8426 fwv &= fwrite(spin->si_compflags, (size_t)STRLEN(spin->si_compflags),
8427 (size_t)1, fd);
8430 /* SN_NOBREAK: NOBREAK flag */
8431 if (spin->si_nobreak)
8433 putc(SN_NOBREAK, fd); /* <sectionID> */
8434 putc(0, fd); /* <sectionflags> */
8436 /* It's empty, the presence of the section flags the feature. */
8437 put_bytes(fd, (long_u)0, 4); /* <sectionlen> */
8440 /* SN_SYLLABLE: syllable info.
8441 * We don't mark it required, when not supported syllables will not be
8442 * counted. */
8443 if (spin->si_syllable != NULL)
8445 putc(SN_SYLLABLE, fd); /* <sectionID> */
8446 putc(0, fd); /* <sectionflags> */
8448 l = (int)STRLEN(spin->si_syllable);
8449 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8450 fwv &= fwrite(spin->si_syllable, (size_t)l, (size_t)1, fd);
8451 /* <syllable> */
8454 /* end of <SECTIONS> */
8455 putc(SN_END, fd); /* <sectionend> */
8459 * <LWORDTREE> <KWORDTREE> <PREFIXTREE>
8461 spin->si_memtot = 0;
8462 for (round = 1; round <= 3; ++round)
8464 if (round == 1)
8465 tree = spin->si_foldroot->wn_sibling;
8466 else if (round == 2)
8467 tree = spin->si_keeproot->wn_sibling;
8468 else
8469 tree = spin->si_prefroot->wn_sibling;
8471 /* Clear the index and wnode fields in the tree. */
8472 clear_node(tree);
8474 /* Count the number of nodes. Needed to be able to allocate the
8475 * memory when reading the nodes. Also fills in index for shared
8476 * nodes. */
8477 nodecount = put_node(NULL, tree, 0, regionmask, round == 3);
8479 /* number of nodes in 4 bytes */
8480 put_bytes(fd, (long_u)nodecount, 4); /* <nodecount> */
8481 spin->si_memtot += nodecount + nodecount * sizeof(int);
8483 /* Write the nodes. */
8484 (void)put_node(fd, tree, 0, regionmask, round == 3);
8487 /* Write another byte to check for errors (file system full). */
8488 if (putc(0, fd) == EOF)
8489 retval = FAIL;
8490 theend:
8491 if (fclose(fd) == EOF)
8492 retval = FAIL;
8494 if (fwv != (size_t)1)
8495 retval = FAIL;
8496 if (retval == FAIL)
8497 EMSG(_(e_write));
8499 return retval;
8503 * Clear the index and wnode fields of "node", it siblings and its
8504 * children. This is needed because they are a union with other items to save
8505 * space.
8507 static void
8508 clear_node(node)
8509 wordnode_T *node;
8511 wordnode_T *np;
8513 if (node != NULL)
8514 for (np = node; np != NULL; np = np->wn_sibling)
8516 np->wn_u1.index = 0;
8517 np->wn_u2.wnode = NULL;
8519 if (np->wn_byte != NUL)
8520 clear_node(np->wn_child);
8526 * Dump a word tree at node "node".
8528 * This first writes the list of possible bytes (siblings). Then for each
8529 * byte recursively write the children.
8531 * NOTE: The code here must match the code in read_tree_node(), since
8532 * assumptions are made about the indexes (so that we don't have to write them
8533 * in the file).
8535 * Returns the number of nodes used.
8537 static int
8538 put_node(fd, node, idx, regionmask, prefixtree)
8539 FILE *fd; /* NULL when only counting */
8540 wordnode_T *node;
8541 int idx;
8542 int regionmask;
8543 int prefixtree; /* TRUE for PREFIXTREE */
8545 int newindex = idx;
8546 int siblingcount = 0;
8547 wordnode_T *np;
8548 int flags;
8550 /* If "node" is zero the tree is empty. */
8551 if (node == NULL)
8552 return 0;
8554 /* Store the index where this node is written. */
8555 node->wn_u1.index = idx;
8557 /* Count the number of siblings. */
8558 for (np = node; np != NULL; np = np->wn_sibling)
8559 ++siblingcount;
8561 /* Write the sibling count. */
8562 if (fd != NULL)
8563 putc(siblingcount, fd); /* <siblingcount> */
8565 /* Write each sibling byte and optionally extra info. */
8566 for (np = node; np != NULL; np = np->wn_sibling)
8568 if (np->wn_byte == 0)
8570 if (fd != NULL)
8572 /* For a NUL byte (end of word) write the flags etc. */
8573 if (prefixtree)
8575 /* In PREFIXTREE write the required affixID and the
8576 * associated condition nr (stored in wn_region). The
8577 * byte value is misused to store the "rare" and "not
8578 * combining" flags */
8579 if (np->wn_flags == (short_u)PFX_FLAGS)
8580 putc(BY_NOFLAGS, fd); /* <byte> */
8581 else
8583 putc(BY_FLAGS, fd); /* <byte> */
8584 putc(np->wn_flags, fd); /* <pflags> */
8586 putc(np->wn_affixID, fd); /* <affixID> */
8587 put_bytes(fd, (long_u)np->wn_region, 2); /* <prefcondnr> */
8589 else
8591 /* For word trees we write the flag/region items. */
8592 flags = np->wn_flags;
8593 if (regionmask != 0 && np->wn_region != regionmask)
8594 flags |= WF_REGION;
8595 if (np->wn_affixID != 0)
8596 flags |= WF_AFX;
8597 if (flags == 0)
8599 /* word without flags or region */
8600 putc(BY_NOFLAGS, fd); /* <byte> */
8602 else
8604 if (np->wn_flags >= 0x100)
8606 putc(BY_FLAGS2, fd); /* <byte> */
8607 putc(flags, fd); /* <flags> */
8608 putc((unsigned)flags >> 8, fd); /* <flags2> */
8610 else
8612 putc(BY_FLAGS, fd); /* <byte> */
8613 putc(flags, fd); /* <flags> */
8615 if (flags & WF_REGION)
8616 putc(np->wn_region, fd); /* <region> */
8617 if (flags & WF_AFX)
8618 putc(np->wn_affixID, fd); /* <affixID> */
8623 else
8625 if (np->wn_child->wn_u1.index != 0
8626 && np->wn_child->wn_u2.wnode != node)
8628 /* The child is written elsewhere, write the reference. */
8629 if (fd != NULL)
8631 putc(BY_INDEX, fd); /* <byte> */
8632 /* <nodeidx> */
8633 put_bytes(fd, (long_u)np->wn_child->wn_u1.index, 3);
8636 else if (np->wn_child->wn_u2.wnode == NULL)
8637 /* We will write the child below and give it an index. */
8638 np->wn_child->wn_u2.wnode = node;
8640 if (fd != NULL)
8641 if (putc(np->wn_byte, fd) == EOF) /* <byte> or <xbyte> */
8643 EMSG(_(e_write));
8644 return 0;
8649 /* Space used in the array when reading: one for each sibling and one for
8650 * the count. */
8651 newindex += siblingcount + 1;
8653 /* Recursively dump the children of each sibling. */
8654 for (np = node; np != NULL; np = np->wn_sibling)
8655 if (np->wn_byte != 0 && np->wn_child->wn_u2.wnode == node)
8656 newindex = put_node(fd, np->wn_child, newindex, regionmask,
8657 prefixtree);
8659 return newindex;
8664 * ":mkspell [-ascii] outfile infile ..."
8665 * ":mkspell [-ascii] addfile"
8667 void
8668 ex_mkspell(eap)
8669 exarg_T *eap;
8671 int fcount;
8672 char_u **fnames;
8673 char_u *arg = eap->arg;
8674 int ascii = FALSE;
8676 if (STRNCMP(arg, "-ascii", 6) == 0)
8678 ascii = TRUE;
8679 arg = skipwhite(arg + 6);
8682 /* Expand all the remaining arguments (e.g., $VIMRUNTIME). */
8683 if (get_arglist_exp(arg, &fcount, &fnames) == OK)
8685 mkspell(fcount, fnames, ascii, eap->forceit, FALSE);
8686 FreeWild(fcount, fnames);
8691 * Create the .sug file.
8692 * Uses the soundfold info in "spin".
8693 * Writes the file with the name "wfname", with ".spl" changed to ".sug".
8695 static void
8696 spell_make_sugfile(spin, wfname)
8697 spellinfo_T *spin;
8698 char_u *wfname;
8700 char_u fname[MAXPATHL];
8701 int len;
8702 slang_T *slang;
8703 int free_slang = FALSE;
8706 * Read back the .spl file that was written. This fills the required
8707 * info for soundfolding. This also uses less memory than the
8708 * pointer-linked version of the trie. And it avoids having two versions
8709 * of the code for the soundfolding stuff.
8710 * It might have been done already by spell_reload_one().
8712 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
8713 if (fullpathcmp(wfname, slang->sl_fname, FALSE) == FPC_SAME)
8714 break;
8715 if (slang == NULL)
8717 spell_message(spin, (char_u *)_("Reading back spell file..."));
8718 slang = spell_load_file(wfname, NULL, NULL, FALSE);
8719 if (slang == NULL)
8720 return;
8721 free_slang = TRUE;
8725 * Clear the info in "spin" that is used.
8727 spin->si_blocks = NULL;
8728 spin->si_blocks_cnt = 0;
8729 spin->si_compress_cnt = 0; /* will stay at 0 all the time*/
8730 spin->si_free_count = 0;
8731 spin->si_first_free = NULL;
8732 spin->si_foldwcount = 0;
8735 * Go through the trie of good words, soundfold each word and add it to
8736 * the soundfold trie.
8738 spell_message(spin, (char_u *)_("Performing soundfolding..."));
8739 if (sug_filltree(spin, slang) == FAIL)
8740 goto theend;
8743 * Create the table which links each soundfold word with a list of the
8744 * good words it may come from. Creates buffer "spin->si_spellbuf".
8745 * This also removes the wordnr from the NUL byte entries to make
8746 * compression possible.
8748 if (sug_maketable(spin) == FAIL)
8749 goto theend;
8751 smsg((char_u *)_("Number of words after soundfolding: %ld"),
8752 (long)spin->si_spellbuf->b_ml.ml_line_count);
8755 * Compress the soundfold trie.
8757 spell_message(spin, (char_u *)_(msg_compressing));
8758 wordtree_compress(spin, spin->si_foldroot);
8761 * Write the .sug file.
8762 * Make the file name by changing ".spl" to ".sug".
8764 STRCPY(fname, wfname);
8765 len = (int)STRLEN(fname);
8766 fname[len - 2] = 'u';
8767 fname[len - 1] = 'g';
8768 sug_write(spin, fname);
8770 theend:
8771 if (free_slang)
8772 slang_free(slang);
8773 free_blocks(spin->si_blocks);
8774 close_spellbuf(spin->si_spellbuf);
8778 * Build the soundfold trie for language "slang".
8780 static int
8781 sug_filltree(spin, slang)
8782 spellinfo_T *spin;
8783 slang_T *slang;
8785 char_u *byts;
8786 idx_T *idxs;
8787 int depth;
8788 idx_T arridx[MAXWLEN];
8789 int curi[MAXWLEN];
8790 char_u tword[MAXWLEN];
8791 char_u tsalword[MAXWLEN];
8792 int c;
8793 idx_T n;
8794 unsigned words_done = 0;
8795 int wordcount[MAXWLEN];
8797 /* We use si_foldroot for the souldfolded trie. */
8798 spin->si_foldroot = wordtree_alloc(spin);
8799 if (spin->si_foldroot == NULL)
8800 return FAIL;
8802 /* let tree_add_word() know we're adding to the soundfolded tree */
8803 spin->si_sugtree = TRUE;
8806 * Go through the whole case-folded tree, soundfold each word and put it
8807 * in the trie.
8809 byts = slang->sl_fbyts;
8810 idxs = slang->sl_fidxs;
8812 arridx[0] = 0;
8813 curi[0] = 1;
8814 wordcount[0] = 0;
8816 depth = 0;
8817 while (depth >= 0 && !got_int)
8819 if (curi[depth] > byts[arridx[depth]])
8821 /* Done all bytes at this node, go up one level. */
8822 idxs[arridx[depth]] = wordcount[depth];
8823 if (depth > 0)
8824 wordcount[depth - 1] += wordcount[depth];
8826 --depth;
8827 line_breakcheck();
8829 else
8832 /* Do one more byte at this node. */
8833 n = arridx[depth] + curi[depth];
8834 ++curi[depth];
8836 c = byts[n];
8837 if (c == 0)
8839 /* Sound-fold the word. */
8840 tword[depth] = NUL;
8841 spell_soundfold(slang, tword, TRUE, tsalword);
8843 /* We use the "flags" field for the MSB of the wordnr,
8844 * "region" for the LSB of the wordnr. */
8845 if (tree_add_word(spin, tsalword, spin->si_foldroot,
8846 words_done >> 16, words_done & 0xffff,
8847 0) == FAIL)
8848 return FAIL;
8850 ++words_done;
8851 ++wordcount[depth];
8853 /* Reset the block count each time to avoid compression
8854 * kicking in. */
8855 spin->si_blocks_cnt = 0;
8857 /* Skip over any other NUL bytes (same word with different
8858 * flags). */
8859 while (byts[n + 1] == 0)
8861 ++n;
8862 ++curi[depth];
8865 else
8867 /* Normal char, go one level deeper. */
8868 tword[depth++] = c;
8869 arridx[depth] = idxs[n];
8870 curi[depth] = 1;
8871 wordcount[depth] = 0;
8876 smsg((char_u *)_("Total number of words: %d"), words_done);
8878 return OK;
8882 * Make the table that links each word in the soundfold trie to the words it
8883 * can be produced from.
8884 * This is not unlike lines in a file, thus use a memfile to be able to access
8885 * the table efficiently.
8886 * Returns FAIL when out of memory.
8888 static int
8889 sug_maketable(spin)
8890 spellinfo_T *spin;
8892 garray_T ga;
8893 int res = OK;
8895 /* Allocate a buffer, open a memline for it and create the swap file
8896 * (uses a temp file, not a .swp file). */
8897 spin->si_spellbuf = open_spellbuf();
8898 if (spin->si_spellbuf == NULL)
8899 return FAIL;
8901 /* Use a buffer to store the line info, avoids allocating many small
8902 * pieces of memory. */
8903 ga_init2(&ga, 1, 100);
8905 /* recursively go through the tree */
8906 if (sug_filltable(spin, spin->si_foldroot->wn_sibling, 0, &ga) == -1)
8907 res = FAIL;
8909 ga_clear(&ga);
8910 return res;
8914 * Fill the table for one node and its children.
8915 * Returns the wordnr at the start of the node.
8916 * Returns -1 when out of memory.
8918 static int
8919 sug_filltable(spin, node, startwordnr, gap)
8920 spellinfo_T *spin;
8921 wordnode_T *node;
8922 int startwordnr;
8923 garray_T *gap; /* place to store line of numbers */
8925 wordnode_T *p, *np;
8926 int wordnr = startwordnr;
8927 int nr;
8928 int prev_nr;
8930 for (p = node; p != NULL; p = p->wn_sibling)
8932 if (p->wn_byte == NUL)
8934 gap->ga_len = 0;
8935 prev_nr = 0;
8936 for (np = p; np != NULL && np->wn_byte == NUL; np = np->wn_sibling)
8938 if (ga_grow(gap, 10) == FAIL)
8939 return -1;
8941 nr = (np->wn_flags << 16) + (np->wn_region & 0xffff);
8942 /* Compute the offset from the previous nr and store the
8943 * offset in a way that it takes a minimum number of bytes.
8944 * It's a bit like utf-8, but without the need to mark
8945 * following bytes. */
8946 nr -= prev_nr;
8947 prev_nr += nr;
8948 gap->ga_len += offset2bytes(nr,
8949 (char_u *)gap->ga_data + gap->ga_len);
8952 /* add the NUL byte */
8953 ((char_u *)gap->ga_data)[gap->ga_len++] = NUL;
8955 if (ml_append_buf(spin->si_spellbuf, (linenr_T)wordnr,
8956 gap->ga_data, gap->ga_len, TRUE) == FAIL)
8957 return -1;
8958 ++wordnr;
8960 /* Remove extra NUL entries, we no longer need them. We don't
8961 * bother freeing the nodes, the won't be reused anyway. */
8962 while (p->wn_sibling != NULL && p->wn_sibling->wn_byte == NUL)
8963 p->wn_sibling = p->wn_sibling->wn_sibling;
8965 /* Clear the flags on the remaining NUL node, so that compression
8966 * works a lot better. */
8967 p->wn_flags = 0;
8968 p->wn_region = 0;
8970 else
8972 wordnr = sug_filltable(spin, p->wn_child, wordnr, gap);
8973 if (wordnr == -1)
8974 return -1;
8977 return wordnr;
8981 * Convert an offset into a minimal number of bytes.
8982 * Similar to utf_char2byters, but use 8 bits in followup bytes and avoid NUL
8983 * bytes.
8985 static int
8986 offset2bytes(nr, buf)
8987 int nr;
8988 char_u *buf;
8990 int rem;
8991 int b1, b2, b3, b4;
8993 /* Split the number in parts of base 255. We need to avoid NUL bytes. */
8994 b1 = nr % 255 + 1;
8995 rem = nr / 255;
8996 b2 = rem % 255 + 1;
8997 rem = rem / 255;
8998 b3 = rem % 255 + 1;
8999 b4 = rem / 255 + 1;
9001 if (b4 > 1 || b3 > 0x1f) /* 4 bytes */
9003 buf[0] = 0xe0 + b4;
9004 buf[1] = b3;
9005 buf[2] = b2;
9006 buf[3] = b1;
9007 return 4;
9009 if (b3 > 1 || b2 > 0x3f ) /* 3 bytes */
9011 buf[0] = 0xc0 + b3;
9012 buf[1] = b2;
9013 buf[2] = b1;
9014 return 3;
9016 if (b2 > 1 || b1 > 0x7f ) /* 2 bytes */
9018 buf[0] = 0x80 + b2;
9019 buf[1] = b1;
9020 return 2;
9022 /* 1 byte */
9023 buf[0] = b1;
9024 return 1;
9028 * Opposite of offset2bytes().
9029 * "pp" points to the bytes and is advanced over it.
9030 * Returns the offset.
9032 static int
9033 bytes2offset(pp)
9034 char_u **pp;
9036 char_u *p = *pp;
9037 int nr;
9038 int c;
9040 c = *p++;
9041 if ((c & 0x80) == 0x00) /* 1 byte */
9043 nr = c - 1;
9045 else if ((c & 0xc0) == 0x80) /* 2 bytes */
9047 nr = (c & 0x3f) - 1;
9048 nr = nr * 255 + (*p++ - 1);
9050 else if ((c & 0xe0) == 0xc0) /* 3 bytes */
9052 nr = (c & 0x1f) - 1;
9053 nr = nr * 255 + (*p++ - 1);
9054 nr = nr * 255 + (*p++ - 1);
9056 else /* 4 bytes */
9058 nr = (c & 0x0f) - 1;
9059 nr = nr * 255 + (*p++ - 1);
9060 nr = nr * 255 + (*p++ - 1);
9061 nr = nr * 255 + (*p++ - 1);
9064 *pp = p;
9065 return nr;
9069 * Write the .sug file in "fname".
9071 static void
9072 sug_write(spin, fname)
9073 spellinfo_T *spin;
9074 char_u *fname;
9076 FILE *fd;
9077 wordnode_T *tree;
9078 int nodecount;
9079 int wcount;
9080 char_u *line;
9081 linenr_T lnum;
9082 int len;
9084 /* Create the file. Note that an existing file is silently overwritten! */
9085 fd = mch_fopen((char *)fname, "w");
9086 if (fd == NULL)
9088 EMSG2(_(e_notopen), fname);
9089 return;
9092 vim_snprintf((char *)IObuff, IOSIZE,
9093 _("Writing suggestion file %s ..."), fname);
9094 spell_message(spin, IObuff);
9097 * <SUGHEADER>: <fileID> <versionnr> <timestamp>
9099 if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) /* <fileID> */
9101 EMSG(_(e_write));
9102 goto theend;
9104 putc(VIMSUGVERSION, fd); /* <versionnr> */
9106 /* Write si_sugtime to the file. */
9107 put_sugtime(spin, fd); /* <timestamp> */
9110 * <SUGWORDTREE>
9112 spin->si_memtot = 0;
9113 tree = spin->si_foldroot->wn_sibling;
9115 /* Clear the index and wnode fields in the tree. */
9116 clear_node(tree);
9118 /* Count the number of nodes. Needed to be able to allocate the
9119 * memory when reading the nodes. Also fills in index for shared
9120 * nodes. */
9121 nodecount = put_node(NULL, tree, 0, 0, FALSE);
9123 /* number of nodes in 4 bytes */
9124 put_bytes(fd, (long_u)nodecount, 4); /* <nodecount> */
9125 spin->si_memtot += nodecount + nodecount * sizeof(int);
9127 /* Write the nodes. */
9128 (void)put_node(fd, tree, 0, 0, FALSE);
9131 * <SUGTABLE>: <sugwcount> <sugline> ...
9133 wcount = spin->si_spellbuf->b_ml.ml_line_count;
9134 put_bytes(fd, (long_u)wcount, 4); /* <sugwcount> */
9136 for (lnum = 1; lnum <= (linenr_T)wcount; ++lnum)
9138 /* <sugline>: <sugnr> ... NUL */
9139 line = ml_get_buf(spin->si_spellbuf, lnum, FALSE);
9140 len = (int)STRLEN(line) + 1;
9141 if (fwrite(line, (size_t)len, (size_t)1, fd) == 0)
9143 EMSG(_(e_write));
9144 goto theend;
9146 spin->si_memtot += len;
9149 /* Write another byte to check for errors. */
9150 if (putc(0, fd) == EOF)
9151 EMSG(_(e_write));
9153 vim_snprintf((char *)IObuff, IOSIZE,
9154 _("Estimated runtime memory use: %d bytes"), spin->si_memtot);
9155 spell_message(spin, IObuff);
9157 theend:
9158 /* close the file */
9159 fclose(fd);
9163 * Open a spell buffer. This is a nameless buffer that is not in the buffer
9164 * list and only contains text lines. Can use a swapfile to reduce memory
9165 * use.
9166 * Most other fields are invalid! Esp. watch out for string options being
9167 * NULL and there is no undo info.
9168 * Returns NULL when out of memory.
9170 static buf_T *
9171 open_spellbuf()
9173 buf_T *buf;
9175 buf = (buf_T *)alloc_clear(sizeof(buf_T));
9176 if (buf != NULL)
9178 buf->b_spell = TRUE;
9179 buf->b_p_swf = TRUE; /* may create a swap file */
9180 ml_open(buf);
9181 ml_open_file(buf); /* create swap file now */
9183 return buf;
9187 * Close the buffer used for spell info.
9189 static void
9190 close_spellbuf(buf)
9191 buf_T *buf;
9193 if (buf != NULL)
9195 ml_close(buf, TRUE);
9196 vim_free(buf);
9202 * Create a Vim spell file from one or more word lists.
9203 * "fnames[0]" is the output file name.
9204 * "fnames[fcount - 1]" is the last input file name.
9205 * Exception: when "fnames[0]" ends in ".add" it's used as the input file name
9206 * and ".spl" is appended to make the output file name.
9208 static void
9209 mkspell(fcount, fnames, ascii, overwrite, added_word)
9210 int fcount;
9211 char_u **fnames;
9212 int ascii; /* -ascii argument given */
9213 int overwrite; /* overwrite existing output file */
9214 int added_word; /* invoked through "zg" */
9216 char_u fname[MAXPATHL];
9217 char_u wfname[MAXPATHL];
9218 char_u **innames;
9219 int incount;
9220 afffile_T *(afile[8]);
9221 int i;
9222 int len;
9223 struct stat st;
9224 int error = FALSE;
9225 spellinfo_T spin;
9227 vim_memset(&spin, 0, sizeof(spin));
9228 spin.si_verbose = !added_word;
9229 spin.si_ascii = ascii;
9230 spin.si_followup = TRUE;
9231 spin.si_rem_accents = TRUE;
9232 ga_init2(&spin.si_rep, (int)sizeof(fromto_T), 20);
9233 ga_init2(&spin.si_repsal, (int)sizeof(fromto_T), 20);
9234 ga_init2(&spin.si_sal, (int)sizeof(fromto_T), 20);
9235 ga_init2(&spin.si_map, (int)sizeof(char_u), 100);
9236 ga_init2(&spin.si_comppat, (int)sizeof(char_u *), 20);
9237 ga_init2(&spin.si_prefcond, (int)sizeof(char_u *), 50);
9238 hash_init(&spin.si_commonwords);
9239 spin.si_newcompID = 127; /* start compound ID at first maximum */
9241 /* default: fnames[0] is output file, following are input files */
9242 innames = &fnames[1];
9243 incount = fcount - 1;
9245 if (fcount >= 1)
9247 len = (int)STRLEN(fnames[0]);
9248 if (fcount == 1 && len > 4 && STRCMP(fnames[0] + len - 4, ".add") == 0)
9250 /* For ":mkspell path/en.latin1.add" output file is
9251 * "path/en.latin1.add.spl". */
9252 innames = &fnames[0];
9253 incount = 1;
9254 vim_snprintf((char *)wfname, sizeof(wfname), "%s.spl", fnames[0]);
9256 else if (fcount == 1)
9258 /* For ":mkspell path/vim" output file is "path/vim.latin1.spl". */
9259 innames = &fnames[0];
9260 incount = 1;
9261 vim_snprintf((char *)wfname, sizeof(wfname), "%s.%s.spl", fnames[0],
9262 spin.si_ascii ? (char_u *)"ascii" : spell_enc());
9264 else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0)
9266 /* Name ends in ".spl", use as the file name. */
9267 vim_strncpy(wfname, fnames[0], sizeof(wfname) - 1);
9269 else
9270 /* Name should be language, make the file name from it. */
9271 vim_snprintf((char *)wfname, sizeof(wfname), "%s.%s.spl", fnames[0],
9272 spin.si_ascii ? (char_u *)"ascii" : spell_enc());
9274 /* Check for .ascii.spl. */
9275 if (strstr((char *)gettail(wfname), ".ascii.") != NULL)
9276 spin.si_ascii = TRUE;
9278 /* Check for .add.spl. */
9279 if (strstr((char *)gettail(wfname), ".add.") != NULL)
9280 spin.si_add = TRUE;
9283 if (incount <= 0)
9284 EMSG(_(e_invarg)); /* need at least output and input names */
9285 else if (vim_strchr(gettail(wfname), '_') != NULL)
9286 EMSG(_("E751: Output file name must not have region name"));
9287 else if (incount > 8)
9288 EMSG(_("E754: Only up to 8 regions supported"));
9289 else
9291 /* Check for overwriting before doing things that may take a lot of
9292 * time. */
9293 if (!overwrite && mch_stat((char *)wfname, &st) >= 0)
9295 EMSG(_(e_exists));
9296 return;
9298 if (mch_isdir(wfname))
9300 EMSG2(_(e_isadir2), wfname);
9301 return;
9305 * Init the aff and dic pointers.
9306 * Get the region names if there are more than 2 arguments.
9308 for (i = 0; i < incount; ++i)
9310 afile[i] = NULL;
9312 if (incount > 1)
9314 len = (int)STRLEN(innames[i]);
9315 if (STRLEN(gettail(innames[i])) < 5
9316 || innames[i][len - 3] != '_')
9318 EMSG2(_("E755: Invalid region in %s"), innames[i]);
9319 return;
9321 spin.si_region_name[i * 2] = TOLOWER_ASC(innames[i][len - 2]);
9322 spin.si_region_name[i * 2 + 1] =
9323 TOLOWER_ASC(innames[i][len - 1]);
9326 spin.si_region_count = incount;
9328 spin.si_foldroot = wordtree_alloc(&spin);
9329 spin.si_keeproot = wordtree_alloc(&spin);
9330 spin.si_prefroot = wordtree_alloc(&spin);
9331 if (spin.si_foldroot == NULL
9332 || spin.si_keeproot == NULL
9333 || spin.si_prefroot == NULL)
9335 free_blocks(spin.si_blocks);
9336 return;
9339 /* When not producing a .add.spl file clear the character table when
9340 * we encounter one in the .aff file. This means we dump the current
9341 * one in the .spl file if the .aff file doesn't define one. That's
9342 * better than guessing the contents, the table will match a
9343 * previously loaded spell file. */
9344 if (!spin.si_add)
9345 spin.si_clear_chartab = TRUE;
9348 * Read all the .aff and .dic files.
9349 * Text is converted to 'encoding'.
9350 * Words are stored in the case-folded and keep-case trees.
9352 for (i = 0; i < incount && !error; ++i)
9354 spin.si_conv.vc_type = CONV_NONE;
9355 spin.si_region = 1 << i;
9357 vim_snprintf((char *)fname, sizeof(fname), "%s.aff", innames[i]);
9358 if (mch_stat((char *)fname, &st) >= 0)
9360 /* Read the .aff file. Will init "spin->si_conv" based on the
9361 * "SET" line. */
9362 afile[i] = spell_read_aff(&spin, fname);
9363 if (afile[i] == NULL)
9364 error = TRUE;
9365 else
9367 /* Read the .dic file and store the words in the trees. */
9368 vim_snprintf((char *)fname, sizeof(fname), "%s.dic",
9369 innames[i]);
9370 if (spell_read_dic(&spin, fname, afile[i]) == FAIL)
9371 error = TRUE;
9374 else
9376 /* No .aff file, try reading the file as a word list. Store
9377 * the words in the trees. */
9378 if (spell_read_wordfile(&spin, innames[i]) == FAIL)
9379 error = TRUE;
9382 #ifdef FEAT_MBYTE
9383 /* Free any conversion stuff. */
9384 convert_setup(&spin.si_conv, NULL, NULL);
9385 #endif
9388 if (spin.si_compflags != NULL && spin.si_nobreak)
9389 MSG(_("Warning: both compounding and NOBREAK specified"));
9391 if (!error && !got_int)
9394 * Combine tails in the tree.
9396 spell_message(&spin, (char_u *)_(msg_compressing));
9397 wordtree_compress(&spin, spin.si_foldroot);
9398 wordtree_compress(&spin, spin.si_keeproot);
9399 wordtree_compress(&spin, spin.si_prefroot);
9402 if (!error && !got_int)
9405 * Write the info in the spell file.
9407 vim_snprintf((char *)IObuff, IOSIZE,
9408 _("Writing spell file %s ..."), wfname);
9409 spell_message(&spin, IObuff);
9411 error = write_vim_spell(&spin, wfname) == FAIL;
9413 spell_message(&spin, (char_u *)_("Done!"));
9414 vim_snprintf((char *)IObuff, IOSIZE,
9415 _("Estimated runtime memory use: %d bytes"), spin.si_memtot);
9416 spell_message(&spin, IObuff);
9419 * If the file is loaded need to reload it.
9421 if (!error)
9422 spell_reload_one(wfname, added_word);
9425 /* Free the allocated memory. */
9426 ga_clear(&spin.si_rep);
9427 ga_clear(&spin.si_repsal);
9428 ga_clear(&spin.si_sal);
9429 ga_clear(&spin.si_map);
9430 ga_clear(&spin.si_comppat);
9431 ga_clear(&spin.si_prefcond);
9432 hash_clear_all(&spin.si_commonwords, 0);
9434 /* Free the .aff file structures. */
9435 for (i = 0; i < incount; ++i)
9436 if (afile[i] != NULL)
9437 spell_free_aff(afile[i]);
9439 /* Free all the bits and pieces at once. */
9440 free_blocks(spin.si_blocks);
9443 * If there is soundfolding info and no NOSUGFILE item create the
9444 * .sug file with the soundfolded word trie.
9446 if (spin.si_sugtime != 0 && !error && !got_int)
9447 spell_make_sugfile(&spin, wfname);
9453 * Display a message for spell file processing when 'verbose' is set or using
9454 * ":mkspell". "str" can be IObuff.
9456 static void
9457 spell_message(spin, str)
9458 spellinfo_T *spin;
9459 char_u *str;
9461 if (spin->si_verbose || p_verbose > 2)
9463 if (!spin->si_verbose)
9464 verbose_enter();
9465 MSG(str);
9466 out_flush();
9467 if (!spin->si_verbose)
9468 verbose_leave();
9473 * ":[count]spellgood {word}"
9474 * ":[count]spellwrong {word}"
9475 * ":[count]spellundo {word}"
9477 void
9478 ex_spell(eap)
9479 exarg_T *eap;
9481 spell_add_word(eap->arg, (int)STRLEN(eap->arg), eap->cmdidx == CMD_spellwrong,
9482 eap->forceit ? 0 : (int)eap->line2,
9483 eap->cmdidx == CMD_spellundo);
9487 * Add "word[len]" to 'spellfile' as a good or bad word.
9489 void
9490 spell_add_word(word, len, bad, idx, undo)
9491 char_u *word;
9492 int len;
9493 int bad;
9494 int idx; /* "zG" and "zW": zero, otherwise index in
9495 'spellfile' */
9496 int undo; /* TRUE for "zug", "zuG", "zuw" and "zuW" */
9498 FILE *fd = NULL;
9499 buf_T *buf = NULL;
9500 int new_spf = FALSE;
9501 char_u *fname;
9502 char_u fnamebuf[MAXPATHL];
9503 char_u line[MAXWLEN * 2];
9504 long fpos, fpos_next = 0;
9505 int i;
9506 char_u *spf;
9508 if (idx == 0) /* use internal wordlist */
9510 if (int_wordlist == NULL)
9512 int_wordlist = vim_tempname('s');
9513 if (int_wordlist == NULL)
9514 return;
9516 fname = int_wordlist;
9518 else
9520 /* If 'spellfile' isn't set figure out a good default value. */
9521 if (*curbuf->b_p_spf == NUL)
9523 init_spellfile();
9524 new_spf = TRUE;
9527 if (*curbuf->b_p_spf == NUL)
9529 EMSG2(_(e_notset), "spellfile");
9530 return;
9533 for (spf = curbuf->b_p_spf, i = 1; *spf != NUL; ++i)
9535 copy_option_part(&spf, fnamebuf, MAXPATHL, ",");
9536 if (i == idx)
9537 break;
9538 if (*spf == NUL)
9540 EMSGN(_("E765: 'spellfile' does not have %ld entries"), idx);
9541 return;
9545 /* Check that the user isn't editing the .add file somewhere. */
9546 buf = buflist_findname_exp(fnamebuf);
9547 if (buf != NULL && buf->b_ml.ml_mfp == NULL)
9548 buf = NULL;
9549 if (buf != NULL && bufIsChanged(buf))
9551 EMSG(_(e_bufloaded));
9552 return;
9555 fname = fnamebuf;
9558 if (bad || undo)
9560 /* When the word appears as good word we need to remove that one,
9561 * since its flags sort before the one with WF_BANNED. */
9562 fd = mch_fopen((char *)fname, "r");
9563 if (fd != NULL)
9565 while (!vim_fgets(line, MAXWLEN * 2, fd))
9567 fpos = fpos_next;
9568 fpos_next = ftell(fd);
9569 if (STRNCMP(word, line, len) == 0
9570 && (line[len] == '/' || line[len] < ' '))
9572 /* Found duplicate word. Remove it by writing a '#' at
9573 * the start of the line. Mixing reading and writing
9574 * doesn't work for all systems, close the file first. */
9575 fclose(fd);
9576 fd = mch_fopen((char *)fname, "r+");
9577 if (fd == NULL)
9578 break;
9579 if (fseek(fd, fpos, SEEK_SET) == 0)
9581 fputc('#', fd);
9582 if (undo)
9584 home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
9585 smsg((char_u *)_("Word removed from %s"), NameBuff);
9588 fseek(fd, fpos_next, SEEK_SET);
9591 fclose(fd);
9595 if (!undo)
9597 fd = mch_fopen((char *)fname, "a");
9598 if (fd == NULL && new_spf)
9600 char_u *p;
9602 /* We just initialized the 'spellfile' option and can't open the
9603 * file. We may need to create the "spell" directory first. We
9604 * already checked the runtime directory is writable in
9605 * init_spellfile(). */
9606 if (!dir_of_file_exists(fname) && (p = gettail_sep(fname)) != fname)
9608 int c = *p;
9610 /* The directory doesn't exist. Try creating it and opening
9611 * the file again. */
9612 *p = NUL;
9613 vim_mkdir(fname, 0755);
9614 *p = c;
9615 fd = mch_fopen((char *)fname, "a");
9619 if (fd == NULL)
9620 EMSG2(_(e_notopen), fname);
9621 else
9623 if (bad)
9624 fprintf(fd, "%.*s/!\n", len, word);
9625 else
9626 fprintf(fd, "%.*s\n", len, word);
9627 fclose(fd);
9629 home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
9630 smsg((char_u *)_("Word added to %s"), NameBuff);
9634 if (fd != NULL)
9636 /* Update the .add.spl file. */
9637 mkspell(1, &fname, FALSE, TRUE, TRUE);
9639 /* If the .add file is edited somewhere, reload it. */
9640 if (buf != NULL)
9641 buf_reload(buf, buf->b_orig_mode);
9643 redraw_all_later(SOME_VALID);
9648 * Initialize 'spellfile' for the current buffer.
9650 static void
9651 init_spellfile()
9653 char_u buf[MAXPATHL];
9654 int l;
9655 char_u *fname;
9656 char_u *rtp;
9657 char_u *lend;
9658 int aspath = FALSE;
9659 char_u *lstart = curbuf->b_p_spl;
9661 if (*curbuf->b_p_spl != NUL && curbuf->b_langp.ga_len > 0)
9663 /* Find the end of the language name. Exclude the region. If there
9664 * is a path separator remember the start of the tail. */
9665 for (lend = curbuf->b_p_spl; *lend != NUL
9666 && vim_strchr((char_u *)",._", *lend) == NULL; ++lend)
9667 if (vim_ispathsep(*lend))
9669 aspath = TRUE;
9670 lstart = lend + 1;
9673 /* Loop over all entries in 'runtimepath'. Use the first one where we
9674 * are allowed to write. */
9675 rtp = p_rtp;
9676 while (*rtp != NUL)
9678 if (aspath)
9679 /* Use directory of an entry with path, e.g., for
9680 * "/dir/lg.utf-8.spl" use "/dir". */
9681 vim_strncpy(buf, curbuf->b_p_spl, lstart - curbuf->b_p_spl - 1);
9682 else
9683 /* Copy the path from 'runtimepath' to buf[]. */
9684 copy_option_part(&rtp, buf, MAXPATHL, ",");
9685 if (filewritable(buf) == 2)
9687 /* Use the first language name from 'spelllang' and the
9688 * encoding used in the first loaded .spl file. */
9689 if (aspath)
9690 vim_strncpy(buf, curbuf->b_p_spl, lend - curbuf->b_p_spl);
9691 else
9693 /* Create the "spell" directory if it doesn't exist yet. */
9694 l = (int)STRLEN(buf);
9695 vim_snprintf((char *)buf + l, MAXPATHL - l, "/spell");
9696 if (!filewritable(buf) != 2)
9697 vim_mkdir(buf, 0755);
9699 l = (int)STRLEN(buf);
9700 vim_snprintf((char *)buf + l, MAXPATHL - l,
9701 "/%.*s", (int)(lend - lstart), lstart);
9703 l = (int)STRLEN(buf);
9704 fname = LANGP_ENTRY(curbuf->b_langp, 0)->lp_slang->sl_fname;
9705 vim_snprintf((char *)buf + l, MAXPATHL - l, ".%s.add",
9706 fname != NULL
9707 && strstr((char *)gettail(fname), ".ascii.") != NULL
9708 ? (char_u *)"ascii" : spell_enc());
9709 set_option_value((char_u *)"spellfile", 0L, buf, OPT_LOCAL);
9710 break;
9712 aspath = FALSE;
9719 * Init the chartab used for spelling for ASCII.
9720 * EBCDIC is not supported!
9722 static void
9723 clear_spell_chartab(sp)
9724 spelltab_T *sp;
9726 int i;
9728 /* Init everything to FALSE. */
9729 vim_memset(sp->st_isw, FALSE, sizeof(sp->st_isw));
9730 vim_memset(sp->st_isu, FALSE, sizeof(sp->st_isu));
9731 for (i = 0; i < 256; ++i)
9733 sp->st_fold[i] = i;
9734 sp->st_upper[i] = i;
9737 /* We include digits. A word shouldn't start with a digit, but handling
9738 * that is done separately. */
9739 for (i = '0'; i <= '9'; ++i)
9740 sp->st_isw[i] = TRUE;
9741 for (i = 'A'; i <= 'Z'; ++i)
9743 sp->st_isw[i] = TRUE;
9744 sp->st_isu[i] = TRUE;
9745 sp->st_fold[i] = i + 0x20;
9747 for (i = 'a'; i <= 'z'; ++i)
9749 sp->st_isw[i] = TRUE;
9750 sp->st_upper[i] = i - 0x20;
9755 * Init the chartab used for spelling. Only depends on 'encoding'.
9756 * Called once while starting up and when 'encoding' changes.
9757 * The default is to use isalpha(), but the spell file should define the word
9758 * characters to make it possible that 'encoding' differs from the current
9759 * locale. For utf-8 we don't use isalpha() but our own functions.
9761 void
9762 init_spell_chartab()
9764 int i;
9766 did_set_spelltab = FALSE;
9767 clear_spell_chartab(&spelltab);
9768 #ifdef FEAT_MBYTE
9769 if (enc_dbcs)
9771 /* DBCS: assume double-wide characters are word characters. */
9772 for (i = 128; i <= 255; ++i)
9773 if (MB_BYTE2LEN(i) == 2)
9774 spelltab.st_isw[i] = TRUE;
9776 else if (enc_utf8)
9778 for (i = 128; i < 256; ++i)
9780 int f = utf_fold(i);
9781 int u = utf_toupper(i);
9783 spelltab.st_isu[i] = utf_isupper(i);
9784 spelltab.st_isw[i] = spelltab.st_isu[i] || utf_islower(i);
9785 /* The folded/upper-cased value is different between latin1 and
9786 * utf8 for 0xb5, causing E763 for no good reason. Use the latin1
9787 * value for utf-8 to avoid this. */
9788 spelltab.st_fold[i] = (f < 256) ? f : i;
9789 spelltab.st_upper[i] = (u < 256) ? u : i;
9792 else
9793 #endif
9795 /* Rough guess: use locale-dependent library functions. */
9796 for (i = 128; i < 256; ++i)
9798 if (MB_ISUPPER(i))
9800 spelltab.st_isw[i] = TRUE;
9801 spelltab.st_isu[i] = TRUE;
9802 spelltab.st_fold[i] = MB_TOLOWER(i);
9804 else if (MB_ISLOWER(i))
9806 spelltab.st_isw[i] = TRUE;
9807 spelltab.st_upper[i] = MB_TOUPPER(i);
9814 * Set the spell character tables from strings in the affix file.
9816 static int
9817 set_spell_chartab(fol, low, upp)
9818 char_u *fol;
9819 char_u *low;
9820 char_u *upp;
9822 /* We build the new tables here first, so that we can compare with the
9823 * previous one. */
9824 spelltab_T new_st;
9825 char_u *pf = fol, *pl = low, *pu = upp;
9826 int f, l, u;
9828 clear_spell_chartab(&new_st);
9830 while (*pf != NUL)
9832 if (*pl == NUL || *pu == NUL)
9834 EMSG(_(e_affform));
9835 return FAIL;
9837 #ifdef FEAT_MBYTE
9838 f = mb_ptr2char_adv(&pf);
9839 l = mb_ptr2char_adv(&pl);
9840 u = mb_ptr2char_adv(&pu);
9841 #else
9842 f = *pf++;
9843 l = *pl++;
9844 u = *pu++;
9845 #endif
9846 /* Every character that appears is a word character. */
9847 if (f < 256)
9848 new_st.st_isw[f] = TRUE;
9849 if (l < 256)
9850 new_st.st_isw[l] = TRUE;
9851 if (u < 256)
9852 new_st.st_isw[u] = TRUE;
9854 /* if "LOW" and "FOL" are not the same the "LOW" char needs
9855 * case-folding */
9856 if (l < 256 && l != f)
9858 if (f >= 256)
9860 EMSG(_(e_affrange));
9861 return FAIL;
9863 new_st.st_fold[l] = f;
9866 /* if "UPP" and "FOL" are not the same the "UPP" char needs
9867 * case-folding, it's upper case and the "UPP" is the upper case of
9868 * "FOL" . */
9869 if (u < 256 && u != f)
9871 if (f >= 256)
9873 EMSG(_(e_affrange));
9874 return FAIL;
9876 new_st.st_fold[u] = f;
9877 new_st.st_isu[u] = TRUE;
9878 new_st.st_upper[f] = u;
9882 if (*pl != NUL || *pu != NUL)
9884 EMSG(_(e_affform));
9885 return FAIL;
9888 return set_spell_finish(&new_st);
9892 * Set the spell character tables from strings in the .spl file.
9894 static void
9895 set_spell_charflags(flags, cnt, fol)
9896 char_u *flags;
9897 int cnt; /* length of "flags" */
9898 char_u *fol;
9900 /* We build the new tables here first, so that we can compare with the
9901 * previous one. */
9902 spelltab_T new_st;
9903 int i;
9904 char_u *p = fol;
9905 int c;
9907 clear_spell_chartab(&new_st);
9909 for (i = 0; i < 128; ++i)
9911 if (i < cnt)
9913 new_st.st_isw[i + 128] = (flags[i] & CF_WORD) != 0;
9914 new_st.st_isu[i + 128] = (flags[i] & CF_UPPER) != 0;
9917 if (*p != NUL)
9919 #ifdef FEAT_MBYTE
9920 c = mb_ptr2char_adv(&p);
9921 #else
9922 c = *p++;
9923 #endif
9924 new_st.st_fold[i + 128] = c;
9925 if (i + 128 != c && new_st.st_isu[i + 128] && c < 256)
9926 new_st.st_upper[c] = i + 128;
9930 (void)set_spell_finish(&new_st);
9933 static int
9934 set_spell_finish(new_st)
9935 spelltab_T *new_st;
9937 int i;
9939 if (did_set_spelltab)
9941 /* check that it's the same table */
9942 for (i = 0; i < 256; ++i)
9944 if (spelltab.st_isw[i] != new_st->st_isw[i]
9945 || spelltab.st_isu[i] != new_st->st_isu[i]
9946 || spelltab.st_fold[i] != new_st->st_fold[i]
9947 || spelltab.st_upper[i] != new_st->st_upper[i])
9949 EMSG(_("E763: Word characters differ between spell files"));
9950 return FAIL;
9954 else
9956 /* copy the new spelltab into the one being used */
9957 spelltab = *new_st;
9958 did_set_spelltab = TRUE;
9961 return OK;
9965 * Return TRUE if "p" points to a word character.
9966 * As a special case we see "midword" characters as word character when it is
9967 * followed by a word character. This finds they'there but not 'they there'.
9968 * Thus this only works properly when past the first character of the word.
9970 static int
9971 spell_iswordp(p, buf)
9972 char_u *p;
9973 buf_T *buf; /* buffer used */
9975 #ifdef FEAT_MBYTE
9976 char_u *s;
9977 int l;
9978 int c;
9980 if (has_mbyte)
9982 l = MB_BYTE2LEN(*p);
9983 s = p;
9984 if (l == 1)
9986 /* be quick for ASCII */
9987 if (buf->b_spell_ismw[*p])
9989 s = p + 1; /* skip a mid-word character */
9990 l = MB_BYTE2LEN(*s);
9993 else
9995 c = mb_ptr2char(p);
9996 if (c < 256 ? buf->b_spell_ismw[c]
9997 : (buf->b_spell_ismw_mb != NULL
9998 && vim_strchr(buf->b_spell_ismw_mb, c) != NULL))
10000 s = p + l;
10001 l = MB_BYTE2LEN(*s);
10005 c = mb_ptr2char(s);
10006 if (c > 255)
10007 return spell_mb_isword_class(mb_get_class(s));
10008 return spelltab.st_isw[c];
10010 #endif
10012 return spelltab.st_isw[buf->b_spell_ismw[*p] ? p[1] : p[0]];
10016 * Return TRUE if "p" points to a word character.
10017 * Unlike spell_iswordp() this doesn't check for "midword" characters.
10019 static int
10020 spell_iswordp_nmw(p)
10021 char_u *p;
10023 #ifdef FEAT_MBYTE
10024 int c;
10026 if (has_mbyte)
10028 c = mb_ptr2char(p);
10029 if (c > 255)
10030 return spell_mb_isword_class(mb_get_class(p));
10031 return spelltab.st_isw[c];
10033 #endif
10034 return spelltab.st_isw[*p];
10037 #ifdef FEAT_MBYTE
10039 * Return TRUE if word class indicates a word character.
10040 * Only for characters above 255.
10041 * Unicode subscript and superscript are not considered word characters.
10043 static int
10044 spell_mb_isword_class(cl)
10045 int cl;
10047 return cl >= 2 && cl != 0x2070 && cl != 0x2080;
10051 * Return TRUE if "p" points to a word character.
10052 * Wide version of spell_iswordp().
10054 static int
10055 spell_iswordp_w(p, buf)
10056 int *p;
10057 buf_T *buf;
10059 int *s;
10061 if (*p < 256 ? buf->b_spell_ismw[*p]
10062 : (buf->b_spell_ismw_mb != NULL
10063 && vim_strchr(buf->b_spell_ismw_mb, *p) != NULL))
10064 s = p + 1;
10065 else
10066 s = p;
10068 if (*s > 255)
10070 if (enc_utf8)
10071 return spell_mb_isword_class(utf_class(*s));
10072 if (enc_dbcs)
10073 return dbcs_class((unsigned)*s >> 8, *s & 0xff) >= 2;
10074 return 0;
10076 return spelltab.st_isw[*s];
10078 #endif
10081 * Write the table with prefix conditions to the .spl file.
10082 * When "fd" is NULL only count the length of what is written.
10084 static int
10085 write_spell_prefcond(fd, gap)
10086 FILE *fd;
10087 garray_T *gap;
10089 int i;
10090 char_u *p;
10091 int len;
10092 int totlen;
10093 size_t x = 1; /* collect return value of fwrite() */
10095 if (fd != NULL)
10096 put_bytes(fd, (long_u)gap->ga_len, 2); /* <prefcondcnt> */
10098 totlen = 2 + gap->ga_len; /* length of <prefcondcnt> and <condlen> bytes */
10100 for (i = 0; i < gap->ga_len; ++i)
10102 /* <prefcond> : <condlen> <condstr> */
10103 p = ((char_u **)gap->ga_data)[i];
10104 if (p != NULL)
10106 len = (int)STRLEN(p);
10107 if (fd != NULL)
10109 fputc(len, fd);
10110 x &= fwrite(p, (size_t)len, (size_t)1, fd);
10112 totlen += len;
10114 else if (fd != NULL)
10115 fputc(0, fd);
10118 return totlen;
10122 * Case-fold "str[len]" into "buf[buflen]". The result is NUL terminated.
10123 * Uses the character definitions from the .spl file.
10124 * When using a multi-byte 'encoding' the length may change!
10125 * Returns FAIL when something wrong.
10127 static int
10128 spell_casefold(str, len, buf, buflen)
10129 char_u *str;
10130 int len;
10131 char_u *buf;
10132 int buflen;
10134 int i;
10136 if (len >= buflen)
10138 buf[0] = NUL;
10139 return FAIL; /* result will not fit */
10142 #ifdef FEAT_MBYTE
10143 if (has_mbyte)
10145 int outi = 0;
10146 char_u *p;
10147 int c;
10149 /* Fold one character at a time. */
10150 for (p = str; p < str + len; )
10152 if (outi + MB_MAXBYTES > buflen)
10154 buf[outi] = NUL;
10155 return FAIL;
10157 c = mb_cptr2char_adv(&p);
10158 outi += mb_char2bytes(SPELL_TOFOLD(c), buf + outi);
10160 buf[outi] = NUL;
10162 else
10163 #endif
10165 /* Be quick for non-multibyte encodings. */
10166 for (i = 0; i < len; ++i)
10167 buf[i] = spelltab.st_fold[str[i]];
10168 buf[i] = NUL;
10171 return OK;
10174 /* values for sps_flags */
10175 #define SPS_BEST 1
10176 #define SPS_FAST 2
10177 #define SPS_DOUBLE 4
10179 static int sps_flags = SPS_BEST; /* flags from 'spellsuggest' */
10180 static int sps_limit = 9999; /* max nr of suggestions given */
10183 * Check the 'spellsuggest' option. Return FAIL if it's wrong.
10184 * Sets "sps_flags" and "sps_limit".
10187 spell_check_sps()
10189 char_u *p;
10190 char_u *s;
10191 char_u buf[MAXPATHL];
10192 int f;
10194 sps_flags = 0;
10195 sps_limit = 9999;
10197 for (p = p_sps; *p != NUL; )
10199 copy_option_part(&p, buf, MAXPATHL, ",");
10201 f = 0;
10202 if (VIM_ISDIGIT(*buf))
10204 s = buf;
10205 sps_limit = getdigits(&s);
10206 if (*s != NUL && !VIM_ISDIGIT(*s))
10207 f = -1;
10209 else if (STRCMP(buf, "best") == 0)
10210 f = SPS_BEST;
10211 else if (STRCMP(buf, "fast") == 0)
10212 f = SPS_FAST;
10213 else if (STRCMP(buf, "double") == 0)
10214 f = SPS_DOUBLE;
10215 else if (STRNCMP(buf, "expr:", 5) != 0
10216 && STRNCMP(buf, "file:", 5) != 0)
10217 f = -1;
10219 if (f == -1 || (sps_flags != 0 && f != 0))
10221 sps_flags = SPS_BEST;
10222 sps_limit = 9999;
10223 return FAIL;
10225 if (f != 0)
10226 sps_flags = f;
10229 if (sps_flags == 0)
10230 sps_flags = SPS_BEST;
10232 return OK;
10236 * "z?": Find badly spelled word under or after the cursor.
10237 * Give suggestions for the properly spelled word.
10238 * In Visual mode use the highlighted word as the bad word.
10239 * When "count" is non-zero use that suggestion.
10241 void
10242 spell_suggest(count)
10243 int count;
10245 char_u *line;
10246 pos_T prev_cursor = curwin->w_cursor;
10247 char_u wcopy[MAXWLEN + 2];
10248 char_u *p;
10249 int i;
10250 int c;
10251 suginfo_T sug;
10252 suggest_T *stp;
10253 int mouse_used;
10254 int need_cap;
10255 int limit;
10256 int selected = count;
10257 int badlen = 0;
10258 int msg_scroll_save = msg_scroll;
10260 if (no_spell_checking(curwin))
10261 return;
10263 #ifdef FEAT_VISUAL
10264 if (VIsual_active)
10266 /* Use the Visually selected text as the bad word. But reject
10267 * a multi-line selection. */
10268 if (curwin->w_cursor.lnum != VIsual.lnum)
10270 vim_beep();
10271 return;
10273 badlen = (int)curwin->w_cursor.col - (int)VIsual.col;
10274 if (badlen < 0)
10275 badlen = -badlen;
10276 else
10277 curwin->w_cursor.col = VIsual.col;
10278 ++badlen;
10279 end_visual_mode();
10281 else
10282 #endif
10283 /* Find the start of the badly spelled word. */
10284 if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0
10285 || curwin->w_cursor.col > prev_cursor.col)
10287 /* No bad word or it starts after the cursor: use the word under the
10288 * cursor. */
10289 curwin->w_cursor = prev_cursor;
10290 line = ml_get_curline();
10291 p = line + curwin->w_cursor.col;
10292 /* Backup to before start of word. */
10293 while (p > line && spell_iswordp_nmw(p))
10294 mb_ptr_back(line, p);
10295 /* Forward to start of word. */
10296 while (*p != NUL && !spell_iswordp_nmw(p))
10297 mb_ptr_adv(p);
10299 if (!spell_iswordp_nmw(p)) /* No word found. */
10301 beep_flush();
10302 return;
10304 curwin->w_cursor.col = (colnr_T)(p - line);
10307 /* Get the word and its length. */
10309 /* Figure out if the word should be capitalised. */
10310 need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);
10312 /* Make a copy of current line since autocommands may free the line. */
10313 line = vim_strsave(ml_get_curline());
10314 if (line == NULL)
10315 goto skip;
10317 /* Get the list of suggestions. Limit to 'lines' - 2 or the number in
10318 * 'spellsuggest', whatever is smaller. */
10319 if (sps_limit > (int)Rows - 2)
10320 limit = (int)Rows - 2;
10321 else
10322 limit = sps_limit;
10323 spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
10324 TRUE, need_cap, TRUE);
10326 if (sug.su_ga.ga_len == 0)
10327 MSG(_("Sorry, no suggestions"));
10328 else if (count > 0)
10330 if (count > sug.su_ga.ga_len)
10331 smsg((char_u *)_("Sorry, only %ld suggestions"),
10332 (long)sug.su_ga.ga_len);
10334 else
10336 vim_free(repl_from);
10337 repl_from = NULL;
10338 vim_free(repl_to);
10339 repl_to = NULL;
10341 #ifdef FEAT_RIGHTLEFT
10342 /* When 'rightleft' is set the list is drawn right-left. */
10343 cmdmsg_rl = curwin->w_p_rl;
10344 if (cmdmsg_rl)
10345 msg_col = Columns - 1;
10346 #endif
10348 /* List the suggestions. */
10349 msg_start();
10350 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
10351 lines_left = Rows; /* avoid more prompt */
10352 vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"),
10353 sug.su_badlen, sug.su_badptr);
10354 #ifdef FEAT_RIGHTLEFT
10355 if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0)
10357 /* And now the rabbit from the high hat: Avoid showing the
10358 * untranslated message rightleft. */
10359 vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC",
10360 sug.su_badlen, sug.su_badptr);
10362 #endif
10363 msg_puts(IObuff);
10364 msg_clr_eos();
10365 msg_putchar('\n');
10367 msg_scroll = TRUE;
10368 for (i = 0; i < sug.su_ga.ga_len; ++i)
10370 stp = &SUG(sug.su_ga, i);
10372 /* The suggested word may replace only part of the bad word, add
10373 * the not replaced part. */
10374 STRCPY(wcopy, stp->st_word);
10375 if (sug.su_badlen > stp->st_orglen)
10376 vim_strncpy(wcopy + stp->st_wordlen,
10377 sug.su_badptr + stp->st_orglen,
10378 sug.su_badlen - stp->st_orglen);
10379 vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1);
10380 #ifdef FEAT_RIGHTLEFT
10381 if (cmdmsg_rl)
10382 rl_mirror(IObuff);
10383 #endif
10384 msg_puts(IObuff);
10386 vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy);
10387 msg_puts(IObuff);
10389 /* The word may replace more than "su_badlen". */
10390 if (sug.su_badlen < stp->st_orglen)
10392 vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""),
10393 stp->st_orglen, sug.su_badptr);
10394 msg_puts(IObuff);
10397 if (p_verbose > 0)
10399 /* Add the score. */
10400 if (sps_flags & (SPS_DOUBLE | SPS_BEST))
10401 vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)",
10402 stp->st_salscore ? "s " : "",
10403 stp->st_score, stp->st_altscore);
10404 else
10405 vim_snprintf((char *)IObuff, IOSIZE, " (%d)",
10406 stp->st_score);
10407 #ifdef FEAT_RIGHTLEFT
10408 if (cmdmsg_rl)
10409 /* Mirror the numbers, but keep the leading space. */
10410 rl_mirror(IObuff + 1);
10411 #endif
10412 msg_advance(30);
10413 msg_puts(IObuff);
10415 msg_putchar('\n');
10418 #ifdef FEAT_RIGHTLEFT
10419 cmdmsg_rl = FALSE;
10420 msg_col = 0;
10421 #endif
10422 /* Ask for choice. */
10423 selected = prompt_for_number(&mouse_used);
10424 if (mouse_used)
10425 selected -= lines_left;
10426 lines_left = Rows; /* avoid more prompt */
10427 /* don't delay for 'smd' in normal_cmd() */
10428 msg_scroll = msg_scroll_save;
10431 if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)
10433 /* Save the from and to text for :spellrepall. */
10434 stp = &SUG(sug.su_ga, selected - 1);
10435 if (sug.su_badlen > stp->st_orglen)
10437 /* Replacing less than "su_badlen", append the remainder to
10438 * repl_to. */
10439 repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);
10440 vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word,
10441 sug.su_badlen - stp->st_orglen,
10442 sug.su_badptr + stp->st_orglen);
10443 repl_to = vim_strsave(IObuff);
10445 else
10447 /* Replacing su_badlen or more, use the whole word. */
10448 repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);
10449 repl_to = vim_strsave(stp->st_word);
10452 /* Replace the word. */
10453 p = alloc((unsigned)STRLEN(line) - stp->st_orglen
10454 + stp->st_wordlen + 1);
10455 if (p != NULL)
10457 c = (int)(sug.su_badptr - line);
10458 mch_memmove(p, line, c);
10459 STRCPY(p + c, stp->st_word);
10460 STRCAT(p, sug.su_badptr + stp->st_orglen);
10461 ml_replace(curwin->w_cursor.lnum, p, FALSE);
10462 curwin->w_cursor.col = c;
10464 /* For redo we use a change-word command. */
10465 ResetRedobuff();
10466 AppendToRedobuff((char_u *)"ciw");
10467 AppendToRedobuffLit(p + c,
10468 stp->st_wordlen + sug.su_badlen - stp->st_orglen);
10469 AppendCharToRedobuff(ESC);
10471 /* After this "p" may be invalid. */
10472 changed_bytes(curwin->w_cursor.lnum, c);
10475 else
10476 curwin->w_cursor = prev_cursor;
10478 spell_find_cleanup(&sug);
10479 skip:
10480 vim_free(line);
10484 * Check if the word at line "lnum" column "col" is required to start with a
10485 * capital. This uses 'spellcapcheck' of the current buffer.
10487 static int
10488 check_need_cap(lnum, col)
10489 linenr_T lnum;
10490 colnr_T col;
10492 int need_cap = FALSE;
10493 char_u *line;
10494 char_u *line_copy = NULL;
10495 char_u *p;
10496 colnr_T endcol;
10497 regmatch_T regmatch;
10499 if (curbuf->b_cap_prog == NULL)
10500 return FALSE;
10502 line = ml_get_curline();
10503 endcol = 0;
10504 if ((int)(skipwhite(line) - line) >= (int)col)
10506 /* At start of line, check if previous line is empty or sentence
10507 * ends there. */
10508 if (lnum == 1)
10509 need_cap = TRUE;
10510 else
10512 line = ml_get(lnum - 1);
10513 if (*skipwhite(line) == NUL)
10514 need_cap = TRUE;
10515 else
10517 /* Append a space in place of the line break. */
10518 line_copy = concat_str(line, (char_u *)" ");
10519 line = line_copy;
10520 endcol = (colnr_T)STRLEN(line);
10524 else
10525 endcol = col;
10527 if (endcol > 0)
10529 /* Check if sentence ends before the bad word. */
10530 regmatch.regprog = curbuf->b_cap_prog;
10531 regmatch.rm_ic = FALSE;
10532 p = line + endcol;
10533 for (;;)
10535 mb_ptr_back(line, p);
10536 if (p == line || spell_iswordp_nmw(p))
10537 break;
10538 if (vim_regexec(&regmatch, p, 0)
10539 && regmatch.endp[0] == line + endcol)
10541 need_cap = TRUE;
10542 break;
10547 vim_free(line_copy);
10549 return need_cap;
10554 * ":spellrepall"
10556 void
10557 ex_spellrepall(eap)
10558 exarg_T *eap UNUSED;
10560 pos_T pos = curwin->w_cursor;
10561 char_u *frompat;
10562 int addlen;
10563 char_u *line;
10564 char_u *p;
10565 int save_ws = p_ws;
10566 linenr_T prev_lnum = 0;
10568 if (repl_from == NULL || repl_to == NULL)
10570 EMSG(_("E752: No previous spell replacement"));
10571 return;
10573 addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from));
10575 frompat = alloc((unsigned)STRLEN(repl_from) + 7);
10576 if (frompat == NULL)
10577 return;
10578 sprintf((char *)frompat, "\\V\\<%s\\>", repl_from);
10579 p_ws = FALSE;
10581 sub_nsubs = 0;
10582 sub_nlines = 0;
10583 curwin->w_cursor.lnum = 0;
10584 while (!got_int)
10586 if (do_search(NULL, '/', frompat, 1L, SEARCH_KEEP, NULL) == 0
10587 || u_save_cursor() == FAIL)
10588 break;
10590 /* Only replace when the right word isn't there yet. This happens
10591 * when changing "etc" to "etc.". */
10592 line = ml_get_curline();
10593 if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col,
10594 repl_to, STRLEN(repl_to)) != 0)
10596 p = alloc((unsigned)STRLEN(line) + addlen + 1);
10597 if (p == NULL)
10598 break;
10599 mch_memmove(p, line, curwin->w_cursor.col);
10600 STRCPY(p + curwin->w_cursor.col, repl_to);
10601 STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from));
10602 ml_replace(curwin->w_cursor.lnum, p, FALSE);
10603 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
10605 if (curwin->w_cursor.lnum != prev_lnum)
10607 ++sub_nlines;
10608 prev_lnum = curwin->w_cursor.lnum;
10610 ++sub_nsubs;
10612 curwin->w_cursor.col += (colnr_T)STRLEN(repl_to);
10615 p_ws = save_ws;
10616 curwin->w_cursor = pos;
10617 vim_free(frompat);
10619 if (sub_nsubs == 0)
10620 EMSG2(_("E753: Not found: %s"), repl_from);
10621 else
10622 do_sub_msg(FALSE);
10626 * Find spell suggestions for "word". Return them in the growarray "*gap" as
10627 * a list of allocated strings.
10629 void
10630 spell_suggest_list(gap, word, maxcount, need_cap, interactive)
10631 garray_T *gap;
10632 char_u *word;
10633 int maxcount; /* maximum nr of suggestions */
10634 int need_cap; /* 'spellcapcheck' matched */
10635 int interactive;
10637 suginfo_T sug;
10638 int i;
10639 suggest_T *stp;
10640 char_u *wcopy;
10642 spell_find_suggest(word, 0, &sug, maxcount, FALSE, need_cap, interactive);
10644 /* Make room in "gap". */
10645 ga_init2(gap, sizeof(char_u *), sug.su_ga.ga_len + 1);
10646 if (ga_grow(gap, sug.su_ga.ga_len) == OK)
10648 for (i = 0; i < sug.su_ga.ga_len; ++i)
10650 stp = &SUG(sug.su_ga, i);
10652 /* The suggested word may replace only part of "word", add the not
10653 * replaced part. */
10654 wcopy = alloc(stp->st_wordlen
10655 + (unsigned)STRLEN(sug.su_badptr + stp->st_orglen) + 1);
10656 if (wcopy == NULL)
10657 break;
10658 STRCPY(wcopy, stp->st_word);
10659 STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen);
10660 ((char_u **)gap->ga_data)[gap->ga_len++] = wcopy;
10664 spell_find_cleanup(&sug);
10668 * Find spell suggestions for the word at the start of "badptr".
10669 * Return the suggestions in "su->su_ga".
10670 * The maximum number of suggestions is "maxcount".
10671 * Note: does use info for the current window.
10672 * This is based on the mechanisms of Aspell, but completely reimplemented.
10674 static void
10675 spell_find_suggest(badptr, badlen, su, maxcount, banbadword, need_cap, interactive)
10676 char_u *badptr;
10677 int badlen; /* length of bad word or 0 if unknown */
10678 suginfo_T *su;
10679 int maxcount;
10680 int banbadword; /* don't include badword in suggestions */
10681 int need_cap; /* word should start with capital */
10682 int interactive;
10684 hlf_T attr = HLF_COUNT;
10685 char_u buf[MAXPATHL];
10686 char_u *p;
10687 int do_combine = FALSE;
10688 char_u *sps_copy;
10689 #ifdef FEAT_EVAL
10690 static int expr_busy = FALSE;
10691 #endif
10692 int c;
10693 int i;
10694 langp_T *lp;
10697 * Set the info in "*su".
10699 vim_memset(su, 0, sizeof(suginfo_T));
10700 ga_init2(&su->su_ga, (int)sizeof(suggest_T), 10);
10701 ga_init2(&su->su_sga, (int)sizeof(suggest_T), 10);
10702 if (*badptr == NUL)
10703 return;
10704 hash_init(&su->su_banned);
10706 su->su_badptr = badptr;
10707 if (badlen != 0)
10708 su->su_badlen = badlen;
10709 else
10710 su->su_badlen = spell_check(curwin, su->su_badptr, &attr, NULL, FALSE);
10711 su->su_maxcount = maxcount;
10712 su->su_maxscore = SCORE_MAXINIT;
10714 if (su->su_badlen >= MAXWLEN)
10715 su->su_badlen = MAXWLEN - 1; /* just in case */
10716 vim_strncpy(su->su_badword, su->su_badptr, su->su_badlen);
10717 (void)spell_casefold(su->su_badptr, su->su_badlen,
10718 su->su_fbadword, MAXWLEN);
10719 /* get caps flags for bad word */
10720 su->su_badflags = badword_captype(su->su_badptr,
10721 su->su_badptr + su->su_badlen);
10722 if (need_cap)
10723 su->su_badflags |= WF_ONECAP;
10725 /* Find the default language for sound folding. We simply use the first
10726 * one in 'spelllang' that supports sound folding. That's good for when
10727 * using multiple files for one language, it's not that bad when mixing
10728 * languages (e.g., "pl,en"). */
10729 for (i = 0; i < curbuf->b_langp.ga_len; ++i)
10731 lp = LANGP_ENTRY(curbuf->b_langp, i);
10732 if (lp->lp_sallang != NULL)
10734 su->su_sallang = lp->lp_sallang;
10735 break;
10739 /* Soundfold the bad word with the default sound folding, so that we don't
10740 * have to do this many times. */
10741 if (su->su_sallang != NULL)
10742 spell_soundfold(su->su_sallang, su->su_fbadword, TRUE,
10743 su->su_sal_badword);
10745 /* If the word is not capitalised and spell_check() doesn't consider the
10746 * word to be bad then it might need to be capitalised. Add a suggestion
10747 * for that. */
10748 c = PTR2CHAR(su->su_badptr);
10749 if (!SPELL_ISUPPER(c) && attr == HLF_COUNT)
10751 make_case_word(su->su_badword, buf, WF_ONECAP);
10752 add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE,
10753 0, TRUE, su->su_sallang, FALSE);
10756 /* Ban the bad word itself. It may appear in another region. */
10757 if (banbadword)
10758 add_banned(su, su->su_badword);
10760 /* Make a copy of 'spellsuggest', because the expression may change it. */
10761 sps_copy = vim_strsave(p_sps);
10762 if (sps_copy == NULL)
10763 return;
10765 /* Loop over the items in 'spellsuggest'. */
10766 for (p = sps_copy; *p != NUL; )
10768 copy_option_part(&p, buf, MAXPATHL, ",");
10770 if (STRNCMP(buf, "expr:", 5) == 0)
10772 #ifdef FEAT_EVAL
10773 /* Evaluate an expression. Skip this when called recursively,
10774 * when using spellsuggest() in the expression. */
10775 if (!expr_busy)
10777 expr_busy = TRUE;
10778 spell_suggest_expr(su, buf + 5);
10779 expr_busy = FALSE;
10781 #endif
10783 else if (STRNCMP(buf, "file:", 5) == 0)
10784 /* Use list of suggestions in a file. */
10785 spell_suggest_file(su, buf + 5);
10786 else
10788 /* Use internal method. */
10789 spell_suggest_intern(su, interactive);
10790 if (sps_flags & SPS_DOUBLE)
10791 do_combine = TRUE;
10795 vim_free(sps_copy);
10797 if (do_combine)
10798 /* Combine the two list of suggestions. This must be done last,
10799 * because sorting changes the order again. */
10800 score_combine(su);
10803 #ifdef FEAT_EVAL
10805 * Find suggestions by evaluating expression "expr".
10807 static void
10808 spell_suggest_expr(su, expr)
10809 suginfo_T *su;
10810 char_u *expr;
10812 list_T *list;
10813 listitem_T *li;
10814 int score;
10815 char_u *p;
10817 /* The work is split up in a few parts to avoid having to export
10818 * suginfo_T.
10819 * First evaluate the expression and get the resulting list. */
10820 list = eval_spell_expr(su->su_badword, expr);
10821 if (list != NULL)
10823 /* Loop over the items in the list. */
10824 for (li = list->lv_first; li != NULL; li = li->li_next)
10825 if (li->li_tv.v_type == VAR_LIST)
10827 /* Get the word and the score from the items. */
10828 score = get_spellword(li->li_tv.vval.v_list, &p);
10829 if (score >= 0 && score <= su->su_maxscore)
10830 add_suggestion(su, &su->su_ga, p, su->su_badlen,
10831 score, 0, TRUE, su->su_sallang, FALSE);
10833 list_unref(list);
10836 /* Remove bogus suggestions, sort and truncate at "maxcount". */
10837 check_suggestions(su, &su->su_ga);
10838 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10840 #endif
10843 * Find suggestions in file "fname". Used for "file:" in 'spellsuggest'.
10845 static void
10846 spell_suggest_file(su, fname)
10847 suginfo_T *su;
10848 char_u *fname;
10850 FILE *fd;
10851 char_u line[MAXWLEN * 2];
10852 char_u *p;
10853 int len;
10854 char_u cword[MAXWLEN];
10856 /* Open the file. */
10857 fd = mch_fopen((char *)fname, "r");
10858 if (fd == NULL)
10860 EMSG2(_(e_notopen), fname);
10861 return;
10864 /* Read it line by line. */
10865 while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int)
10867 line_breakcheck();
10869 p = vim_strchr(line, '/');
10870 if (p == NULL)
10871 continue; /* No Tab found, just skip the line. */
10872 *p++ = NUL;
10873 if (STRICMP(su->su_badword, line) == 0)
10875 /* Match! Isolate the good word, until CR or NL. */
10876 for (len = 0; p[len] >= ' '; ++len)
10878 p[len] = NUL;
10880 /* If the suggestion doesn't have specific case duplicate the case
10881 * of the bad word. */
10882 if (captype(p, NULL) == 0)
10884 make_case_word(p, cword, su->su_badflags);
10885 p = cword;
10888 add_suggestion(su, &su->su_ga, p, su->su_badlen,
10889 SCORE_FILE, 0, TRUE, su->su_sallang, FALSE);
10893 fclose(fd);
10895 /* Remove bogus suggestions, sort and truncate at "maxcount". */
10896 check_suggestions(su, &su->su_ga);
10897 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10901 * Find suggestions for the internal method indicated by "sps_flags".
10903 static void
10904 spell_suggest_intern(su, interactive)
10905 suginfo_T *su;
10906 int interactive;
10909 * Load the .sug file(s) that are available and not done yet.
10911 suggest_load_files();
10914 * 1. Try special cases, such as repeating a word: "the the" -> "the".
10916 * Set a maximum score to limit the combination of operations that is
10917 * tried.
10919 suggest_try_special(su);
10922 * 2. Try inserting/deleting/swapping/changing a letter, use REP entries
10923 * from the .aff file and inserting a space (split the word).
10925 suggest_try_change(su);
10927 /* For the resulting top-scorers compute the sound-a-like score. */
10928 if (sps_flags & SPS_DOUBLE)
10929 score_comp_sal(su);
10932 * 3. Try finding sound-a-like words.
10934 if ((sps_flags & SPS_FAST) == 0)
10936 if (sps_flags & SPS_BEST)
10937 /* Adjust the word score for the suggestions found so far for how
10938 * they sounds like. */
10939 rescore_suggestions(su);
10942 * While going through the soundfold tree "su_maxscore" is the score
10943 * for the soundfold word, limits the changes that are being tried,
10944 * and "su_sfmaxscore" the rescored score, which is set by
10945 * cleanup_suggestions().
10946 * First find words with a small edit distance, because this is much
10947 * faster and often already finds the top-N suggestions. If we didn't
10948 * find many suggestions try again with a higher edit distance.
10949 * "sl_sounddone" is used to avoid doing the same word twice.
10951 suggest_try_soundalike_prep();
10952 su->su_maxscore = SCORE_SFMAX1;
10953 su->su_sfmaxscore = SCORE_MAXINIT * 3;
10954 suggest_try_soundalike(su);
10955 if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
10957 /* We didn't find enough matches, try again, allowing more
10958 * changes to the soundfold word. */
10959 su->su_maxscore = SCORE_SFMAX2;
10960 suggest_try_soundalike(su);
10961 if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
10963 /* Still didn't find enough matches, try again, allowing even
10964 * more changes to the soundfold word. */
10965 su->su_maxscore = SCORE_SFMAX3;
10966 suggest_try_soundalike(su);
10969 su->su_maxscore = su->su_sfmaxscore;
10970 suggest_try_soundalike_finish();
10973 /* When CTRL-C was hit while searching do show the results. Only clear
10974 * got_int when using a command, not for spellsuggest(). */
10975 ui_breakcheck();
10976 if (interactive && got_int)
10978 (void)vgetc();
10979 got_int = FALSE;
10982 if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0)
10984 if (sps_flags & SPS_BEST)
10985 /* Adjust the word score for how it sounds like. */
10986 rescore_suggestions(su);
10988 /* Remove bogus suggestions, sort and truncate at "maxcount". */
10989 check_suggestions(su, &su->su_ga);
10990 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10995 * Load the .sug files for languages that have one and weren't loaded yet.
10997 static void
10998 suggest_load_files()
11000 langp_T *lp;
11001 int lpi;
11002 slang_T *slang;
11003 char_u *dotp;
11004 FILE *fd;
11005 char_u buf[MAXWLEN];
11006 int i;
11007 time_t timestamp;
11008 int wcount;
11009 int wordnr;
11010 garray_T ga;
11011 int c;
11013 /* Do this for all languages that support sound folding. */
11014 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
11016 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
11017 slang = lp->lp_slang;
11018 if (slang->sl_sugtime != 0 && !slang->sl_sugloaded)
11020 /* Change ".spl" to ".sug" and open the file. When the file isn't
11021 * found silently skip it. Do set "sl_sugloaded" so that we
11022 * don't try again and again. */
11023 slang->sl_sugloaded = TRUE;
11025 dotp = vim_strrchr(slang->sl_fname, '.');
11026 if (dotp == NULL || fnamecmp(dotp, ".spl") != 0)
11027 continue;
11028 STRCPY(dotp, ".sug");
11029 fd = mch_fopen((char *)slang->sl_fname, "r");
11030 if (fd == NULL)
11031 goto nextone;
11034 * <SUGHEADER>: <fileID> <versionnr> <timestamp>
11036 for (i = 0; i < VIMSUGMAGICL; ++i)
11037 buf[i] = getc(fd); /* <fileID> */
11038 if (STRNCMP(buf, VIMSUGMAGIC, VIMSUGMAGICL) != 0)
11040 EMSG2(_("E778: This does not look like a .sug file: %s"),
11041 slang->sl_fname);
11042 goto nextone;
11044 c = getc(fd); /* <versionnr> */
11045 if (c < VIMSUGVERSION)
11047 EMSG2(_("E779: Old .sug file, needs to be updated: %s"),
11048 slang->sl_fname);
11049 goto nextone;
11051 else if (c > VIMSUGVERSION)
11053 EMSG2(_("E780: .sug file is for newer version of Vim: %s"),
11054 slang->sl_fname);
11055 goto nextone;
11058 /* Check the timestamp, it must be exactly the same as the one in
11059 * the .spl file. Otherwise the word numbers won't match. */
11060 timestamp = get8c(fd); /* <timestamp> */
11061 if (timestamp != slang->sl_sugtime)
11063 EMSG2(_("E781: .sug file doesn't match .spl file: %s"),
11064 slang->sl_fname);
11065 goto nextone;
11069 * <SUGWORDTREE>: <wordtree>
11070 * Read the trie with the soundfolded words.
11072 if (spell_read_tree(fd, &slang->sl_sbyts, &slang->sl_sidxs,
11073 FALSE, 0) != 0)
11075 someerror:
11076 EMSG2(_("E782: error while reading .sug file: %s"),
11077 slang->sl_fname);
11078 slang_clear_sug(slang);
11079 goto nextone;
11083 * <SUGTABLE>: <sugwcount> <sugline> ...
11085 * Read the table with word numbers. We use a file buffer for
11086 * this, because it's so much like a file with lines. Makes it
11087 * possible to swap the info and save on memory use.
11089 slang->sl_sugbuf = open_spellbuf();
11090 if (slang->sl_sugbuf == NULL)
11091 goto someerror;
11092 /* <sugwcount> */
11093 wcount = get4c(fd);
11094 if (wcount < 0)
11095 goto someerror;
11097 /* Read all the wordnr lists into the buffer, one NUL terminated
11098 * list per line. */
11099 ga_init2(&ga, 1, 100);
11100 for (wordnr = 0; wordnr < wcount; ++wordnr)
11102 ga.ga_len = 0;
11103 for (;;)
11105 c = getc(fd); /* <sugline> */
11106 if (c < 0 || ga_grow(&ga, 1) == FAIL)
11107 goto someerror;
11108 ((char_u *)ga.ga_data)[ga.ga_len++] = c;
11109 if (c == NUL)
11110 break;
11112 if (ml_append_buf(slang->sl_sugbuf, (linenr_T)wordnr,
11113 ga.ga_data, ga.ga_len, TRUE) == FAIL)
11114 goto someerror;
11116 ga_clear(&ga);
11119 * Need to put word counts in the word tries, so that we can find
11120 * a word by its number.
11122 tree_count_words(slang->sl_fbyts, slang->sl_fidxs);
11123 tree_count_words(slang->sl_sbyts, slang->sl_sidxs);
11125 nextone:
11126 if (fd != NULL)
11127 fclose(fd);
11128 STRCPY(dotp, ".spl");
11135 * Fill in the wordcount fields for a trie.
11136 * Returns the total number of words.
11138 static void
11139 tree_count_words(byts, idxs)
11140 char_u *byts;
11141 idx_T *idxs;
11143 int depth;
11144 idx_T arridx[MAXWLEN];
11145 int curi[MAXWLEN];
11146 int c;
11147 idx_T n;
11148 int wordcount[MAXWLEN];
11150 arridx[0] = 0;
11151 curi[0] = 1;
11152 wordcount[0] = 0;
11153 depth = 0;
11154 while (depth >= 0 && !got_int)
11156 if (curi[depth] > byts[arridx[depth]])
11158 /* Done all bytes at this node, go up one level. */
11159 idxs[arridx[depth]] = wordcount[depth];
11160 if (depth > 0)
11161 wordcount[depth - 1] += wordcount[depth];
11163 --depth;
11164 fast_breakcheck();
11166 else
11168 /* Do one more byte at this node. */
11169 n = arridx[depth] + curi[depth];
11170 ++curi[depth];
11172 c = byts[n];
11173 if (c == 0)
11175 /* End of word, count it. */
11176 ++wordcount[depth];
11178 /* Skip over any other NUL bytes (same word with different
11179 * flags). */
11180 while (byts[n + 1] == 0)
11182 ++n;
11183 ++curi[depth];
11186 else
11188 /* Normal char, go one level deeper to count the words. */
11189 ++depth;
11190 arridx[depth] = idxs[n];
11191 curi[depth] = 1;
11192 wordcount[depth] = 0;
11199 * Free the info put in "*su" by spell_find_suggest().
11201 static void
11202 spell_find_cleanup(su)
11203 suginfo_T *su;
11205 int i;
11207 /* Free the suggestions. */
11208 for (i = 0; i < su->su_ga.ga_len; ++i)
11209 vim_free(SUG(su->su_ga, i).st_word);
11210 ga_clear(&su->su_ga);
11211 for (i = 0; i < su->su_sga.ga_len; ++i)
11212 vim_free(SUG(su->su_sga, i).st_word);
11213 ga_clear(&su->su_sga);
11215 /* Free the banned words. */
11216 hash_clear_all(&su->su_banned, 0);
11220 * Make a copy of "word", with the first letter upper or lower cased, to
11221 * "wcopy[MAXWLEN]". "word" must not be empty.
11222 * The result is NUL terminated.
11224 static void
11225 onecap_copy(word, wcopy, upper)
11226 char_u *word;
11227 char_u *wcopy;
11228 int upper; /* TRUE: first letter made upper case */
11230 char_u *p;
11231 int c;
11232 int l;
11234 p = word;
11235 #ifdef FEAT_MBYTE
11236 if (has_mbyte)
11237 c = mb_cptr2char_adv(&p);
11238 else
11239 #endif
11240 c = *p++;
11241 if (upper)
11242 c = SPELL_TOUPPER(c);
11243 else
11244 c = SPELL_TOFOLD(c);
11245 #ifdef FEAT_MBYTE
11246 if (has_mbyte)
11247 l = mb_char2bytes(c, wcopy);
11248 else
11249 #endif
11251 l = 1;
11252 wcopy[0] = c;
11254 vim_strncpy(wcopy + l, p, MAXWLEN - l - 1);
11258 * Make a copy of "word" with all the letters upper cased into
11259 * "wcopy[MAXWLEN]". The result is NUL terminated.
11261 static void
11262 allcap_copy(word, wcopy)
11263 char_u *word;
11264 char_u *wcopy;
11266 char_u *s;
11267 char_u *d;
11268 int c;
11270 d = wcopy;
11271 for (s = word; *s != NUL; )
11273 #ifdef FEAT_MBYTE
11274 if (has_mbyte)
11275 c = mb_cptr2char_adv(&s);
11276 else
11277 #endif
11278 c = *s++;
11280 #ifdef FEAT_MBYTE
11281 /* We only change ß to SS when we are certain latin1 is used. It
11282 * would cause weird errors in other 8-bit encodings. */
11283 if (enc_latin1like && c == 0xdf)
11285 c = 'S';
11286 if (d - wcopy >= MAXWLEN - 1)
11287 break;
11288 *d++ = c;
11290 else
11291 #endif
11292 c = SPELL_TOUPPER(c);
11294 #ifdef FEAT_MBYTE
11295 if (has_mbyte)
11297 if (d - wcopy >= MAXWLEN - MB_MAXBYTES)
11298 break;
11299 d += mb_char2bytes(c, d);
11301 else
11302 #endif
11304 if (d - wcopy >= MAXWLEN - 1)
11305 break;
11306 *d++ = c;
11309 *d = NUL;
11313 * Try finding suggestions by recognizing specific situations.
11315 static void
11316 suggest_try_special(su)
11317 suginfo_T *su;
11319 char_u *p;
11320 size_t len;
11321 int c;
11322 char_u word[MAXWLEN];
11325 * Recognize a word that is repeated: "the the".
11327 p = skiptowhite(su->su_fbadword);
11328 len = p - su->su_fbadword;
11329 p = skipwhite(p);
11330 if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0)
11332 /* Include badflags: if the badword is onecap or allcap
11333 * use that for the goodword too: "The the" -> "The". */
11334 c = su->su_fbadword[len];
11335 su->su_fbadword[len] = NUL;
11336 make_case_word(su->su_fbadword, word, su->su_badflags);
11337 su->su_fbadword[len] = c;
11339 /* Give a soundalike score of 0, compute the score as if deleting one
11340 * character. */
11341 add_suggestion(su, &su->su_ga, word, su->su_badlen,
11342 RESCORE(SCORE_REP, 0), 0, TRUE, su->su_sallang, FALSE);
11347 * Try finding suggestions by adding/removing/swapping letters.
11349 static void
11350 suggest_try_change(su)
11351 suginfo_T *su;
11353 char_u fword[MAXWLEN]; /* copy of the bad word, case-folded */
11354 int n;
11355 char_u *p;
11356 int lpi;
11357 langp_T *lp;
11359 /* We make a copy of the case-folded bad word, so that we can modify it
11360 * to find matches (esp. REP items). Append some more text, changing
11361 * chars after the bad word may help. */
11362 STRCPY(fword, su->su_fbadword);
11363 n = (int)STRLEN(fword);
11364 p = su->su_badptr + su->su_badlen;
11365 (void)spell_casefold(p, (int)STRLEN(p), fword + n, MAXWLEN - n);
11367 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
11369 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
11371 /* If reloading a spell file fails it's still in the list but
11372 * everything has been cleared. */
11373 if (lp->lp_slang->sl_fbyts == NULL)
11374 continue;
11376 /* Try it for this language. Will add possible suggestions. */
11377 suggest_trie_walk(su, lp, fword, FALSE);
11381 /* Check the maximum score, if we go over it we won't try this change. */
11382 #define TRY_DEEPER(su, stack, depth, add) \
11383 (stack[depth].ts_score + (add) < su->su_maxscore)
11386 * Try finding suggestions by adding/removing/swapping letters.
11388 * This uses a state machine. At each node in the tree we try various
11389 * operations. When trying if an operation works "depth" is increased and the
11390 * stack[] is used to store info. This allows combinations, thus insert one
11391 * character, replace one and delete another. The number of changes is
11392 * limited by su->su_maxscore.
11394 * After implementing this I noticed an article by Kemal Oflazer that
11395 * describes something similar: "Error-tolerant Finite State Recognition with
11396 * Applications to Morphological Analysis and Spelling Correction" (1996).
11397 * The implementation in the article is simplified and requires a stack of
11398 * unknown depth. The implementation here only needs a stack depth equal to
11399 * the length of the word.
11401 * This is also used for the sound-folded word, "soundfold" is TRUE then.
11402 * The mechanism is the same, but we find a match with a sound-folded word
11403 * that comes from one or more original words. Each of these words may be
11404 * added, this is done by add_sound_suggest().
11405 * Don't use:
11406 * the prefix tree or the keep-case tree
11407 * "su->su_badlen"
11408 * anything to do with upper and lower case
11409 * anything to do with word or non-word characters ("spell_iswordp()")
11410 * banned words
11411 * word flags (rare, region, compounding)
11412 * word splitting for now
11413 * "similar_chars()"
11414 * use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep"
11416 static void
11417 suggest_trie_walk(su, lp, fword, soundfold)
11418 suginfo_T *su;
11419 langp_T *lp;
11420 char_u *fword;
11421 int soundfold;
11423 char_u tword[MAXWLEN]; /* good word collected so far */
11424 trystate_T stack[MAXWLEN];
11425 char_u preword[MAXWLEN * 3]; /* word found with proper case;
11426 * concatenation of prefix compound
11427 * words and split word. NUL terminated
11428 * when going deeper but not when coming
11429 * back. */
11430 char_u compflags[MAXWLEN]; /* compound flags, one for each word */
11431 trystate_T *sp;
11432 int newscore;
11433 int score;
11434 char_u *byts, *fbyts, *pbyts;
11435 idx_T *idxs, *fidxs, *pidxs;
11436 int depth;
11437 int c, c2, c3;
11438 int n = 0;
11439 int flags;
11440 garray_T *gap;
11441 idx_T arridx;
11442 int len;
11443 char_u *p;
11444 fromto_T *ftp;
11445 int fl = 0, tl;
11446 int repextra = 0; /* extra bytes in fword[] from REP item */
11447 slang_T *slang = lp->lp_slang;
11448 int fword_ends;
11449 int goodword_ends;
11450 #ifdef DEBUG_TRIEWALK
11451 /* Stores the name of the change made at each level. */
11452 char_u changename[MAXWLEN][80];
11453 #endif
11454 int breakcheckcount = 1000;
11455 int compound_ok;
11458 * Go through the whole case-fold tree, try changes at each node.
11459 * "tword[]" contains the word collected from nodes in the tree.
11460 * "fword[]" the word we are trying to match with (initially the bad
11461 * word).
11463 depth = 0;
11464 sp = &stack[0];
11465 vim_memset(sp, 0, sizeof(trystate_T));
11466 sp->ts_curi = 1;
11468 if (soundfold)
11470 /* Going through the soundfold tree. */
11471 byts = fbyts = slang->sl_sbyts;
11472 idxs = fidxs = slang->sl_sidxs;
11473 pbyts = NULL;
11474 pidxs = NULL;
11475 sp->ts_prefixdepth = PFD_NOPREFIX;
11476 sp->ts_state = STATE_START;
11478 else
11481 * When there are postponed prefixes we need to use these first. At
11482 * the end of the prefix we continue in the case-fold tree.
11484 fbyts = slang->sl_fbyts;
11485 fidxs = slang->sl_fidxs;
11486 pbyts = slang->sl_pbyts;
11487 pidxs = slang->sl_pidxs;
11488 if (pbyts != NULL)
11490 byts = pbyts;
11491 idxs = pidxs;
11492 sp->ts_prefixdepth = PFD_PREFIXTREE;
11493 sp->ts_state = STATE_NOPREFIX; /* try without prefix first */
11495 else
11497 byts = fbyts;
11498 idxs = fidxs;
11499 sp->ts_prefixdepth = PFD_NOPREFIX;
11500 sp->ts_state = STATE_START;
11505 * Loop to find all suggestions. At each round we either:
11506 * - For the current state try one operation, advance "ts_curi",
11507 * increase "depth".
11508 * - When a state is done go to the next, set "ts_state".
11509 * - When all states are tried decrease "depth".
11511 while (depth >= 0 && !got_int)
11513 sp = &stack[depth];
11514 switch (sp->ts_state)
11516 case STATE_START:
11517 case STATE_NOPREFIX:
11519 * Start of node: Deal with NUL bytes, which means
11520 * tword[] may end here.
11522 arridx = sp->ts_arridx; /* current node in the tree */
11523 len = byts[arridx]; /* bytes in this node */
11524 arridx += sp->ts_curi; /* index of current byte */
11526 if (sp->ts_prefixdepth == PFD_PREFIXTREE)
11528 /* Skip over the NUL bytes, we use them later. */
11529 for (n = 0; n < len && byts[arridx + n] == 0; ++n)
11531 sp->ts_curi += n;
11533 /* Always past NUL bytes now. */
11534 n = (int)sp->ts_state;
11535 sp->ts_state = STATE_ENDNUL;
11536 sp->ts_save_badflags = su->su_badflags;
11538 /* At end of a prefix or at start of prefixtree: check for
11539 * following word. */
11540 if (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)
11542 /* Set su->su_badflags to the caps type at this position.
11543 * Use the caps type until here for the prefix itself. */
11544 #ifdef FEAT_MBYTE
11545 if (has_mbyte)
11546 n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
11547 else
11548 #endif
11549 n = sp->ts_fidx;
11550 flags = badword_captype(su->su_badptr, su->su_badptr + n);
11551 su->su_badflags = badword_captype(su->su_badptr + n,
11552 su->su_badptr + su->su_badlen);
11553 #ifdef DEBUG_TRIEWALK
11554 sprintf(changename[depth], "prefix");
11555 #endif
11556 go_deeper(stack, depth, 0);
11557 ++depth;
11558 sp = &stack[depth];
11559 sp->ts_prefixdepth = depth - 1;
11560 byts = fbyts;
11561 idxs = fidxs;
11562 sp->ts_arridx = 0;
11564 /* Move the prefix to preword[] with the right case
11565 * and make find_keepcap_word() works. */
11566 tword[sp->ts_twordlen] = NUL;
11567 make_case_word(tword + sp->ts_splitoff,
11568 preword + sp->ts_prewordlen, flags);
11569 sp->ts_prewordlen = (char_u)STRLEN(preword);
11570 sp->ts_splitoff = sp->ts_twordlen;
11572 break;
11575 if (sp->ts_curi > len || byts[arridx] != 0)
11577 /* Past bytes in node and/or past NUL bytes. */
11578 sp->ts_state = STATE_ENDNUL;
11579 sp->ts_save_badflags = su->su_badflags;
11580 break;
11584 * End of word in tree.
11586 ++sp->ts_curi; /* eat one NUL byte */
11588 flags = (int)idxs[arridx];
11590 /* Skip words with the NOSUGGEST flag. */
11591 if (flags & WF_NOSUGGEST)
11592 break;
11594 fword_ends = (fword[sp->ts_fidx] == NUL
11595 || (soundfold
11596 ? vim_iswhite(fword[sp->ts_fidx])
11597 : !spell_iswordp(fword + sp->ts_fidx, curbuf)));
11598 tword[sp->ts_twordlen] = NUL;
11600 if (sp->ts_prefixdepth <= PFD_NOTSPECIAL
11601 && (sp->ts_flags & TSF_PREFIXOK) == 0)
11603 /* There was a prefix before the word. Check that the prefix
11604 * can be used with this word. */
11605 /* Count the length of the NULs in the prefix. If there are
11606 * none this must be the first try without a prefix. */
11607 n = stack[sp->ts_prefixdepth].ts_arridx;
11608 len = pbyts[n++];
11609 for (c = 0; c < len && pbyts[n + c] == 0; ++c)
11611 if (c > 0)
11613 c = valid_word_prefix(c, n, flags,
11614 tword + sp->ts_splitoff, slang, FALSE);
11615 if (c == 0)
11616 break;
11618 /* Use the WF_RARE flag for a rare prefix. */
11619 if (c & WF_RAREPFX)
11620 flags |= WF_RARE;
11622 /* Tricky: when checking for both prefix and compounding
11623 * we run into the prefix flag first.
11624 * Remember that it's OK, so that we accept the prefix
11625 * when arriving at a compound flag. */
11626 sp->ts_flags |= TSF_PREFIXOK;
11630 /* Check NEEDCOMPOUND: can't use word without compounding. Do try
11631 * appending another compound word below. */
11632 if (sp->ts_complen == sp->ts_compsplit && fword_ends
11633 && (flags & WF_NEEDCOMP))
11634 goodword_ends = FALSE;
11635 else
11636 goodword_ends = TRUE;
11638 p = NULL;
11639 compound_ok = TRUE;
11640 if (sp->ts_complen > sp->ts_compsplit)
11642 if (slang->sl_nobreak)
11644 /* There was a word before this word. When there was no
11645 * change in this word (it was correct) add the first word
11646 * as a suggestion. If this word was corrected too, we
11647 * need to check if a correct word follows. */
11648 if (sp->ts_fidx - sp->ts_splitfidx
11649 == sp->ts_twordlen - sp->ts_splitoff
11650 && STRNCMP(fword + sp->ts_splitfidx,
11651 tword + sp->ts_splitoff,
11652 sp->ts_fidx - sp->ts_splitfidx) == 0)
11654 preword[sp->ts_prewordlen] = NUL;
11655 newscore = score_wordcount_adj(slang, sp->ts_score,
11656 preword + sp->ts_prewordlen,
11657 sp->ts_prewordlen > 0);
11658 /* Add the suggestion if the score isn't too bad. */
11659 if (newscore <= su->su_maxscore)
11660 add_suggestion(su, &su->su_ga, preword,
11661 sp->ts_splitfidx - repextra,
11662 newscore, 0, FALSE,
11663 lp->lp_sallang, FALSE);
11664 break;
11667 else
11669 /* There was a compound word before this word. If this
11670 * word does not support compounding then give up
11671 * (splitting is tried for the word without compound
11672 * flag). */
11673 if (((unsigned)flags >> 24) == 0
11674 || sp->ts_twordlen - sp->ts_splitoff
11675 < slang->sl_compminlen)
11676 break;
11677 #ifdef FEAT_MBYTE
11678 /* For multi-byte chars check character length against
11679 * COMPOUNDMIN. */
11680 if (has_mbyte
11681 && slang->sl_compminlen > 0
11682 && mb_charlen(tword + sp->ts_splitoff)
11683 < slang->sl_compminlen)
11684 break;
11685 #endif
11687 compflags[sp->ts_complen] = ((unsigned)flags >> 24);
11688 compflags[sp->ts_complen + 1] = NUL;
11689 vim_strncpy(preword + sp->ts_prewordlen,
11690 tword + sp->ts_splitoff,
11691 sp->ts_twordlen - sp->ts_splitoff);
11693 /* Verify CHECKCOMPOUNDPATTERN rules. */
11694 if (match_checkcompoundpattern(preword, sp->ts_prewordlen,
11695 &slang->sl_comppat))
11696 compound_ok = FALSE;
11698 if (compound_ok)
11700 p = preword;
11701 while (*skiptowhite(p) != NUL)
11702 p = skipwhite(skiptowhite(p));
11703 if (fword_ends && !can_compound(slang, p,
11704 compflags + sp->ts_compsplit))
11705 /* Compound is not allowed. But it may still be
11706 * possible if we add another (short) word. */
11707 compound_ok = FALSE;
11710 /* Get pointer to last char of previous word. */
11711 p = preword + sp->ts_prewordlen;
11712 mb_ptr_back(preword, p);
11717 * Form the word with proper case in preword.
11718 * If there is a word from a previous split, append.
11719 * For the soundfold tree don't change the case, simply append.
11721 if (soundfold)
11722 STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
11723 else if (flags & WF_KEEPCAP)
11724 /* Must find the word in the keep-case tree. */
11725 find_keepcap_word(slang, tword + sp->ts_splitoff,
11726 preword + sp->ts_prewordlen);
11727 else
11729 /* Include badflags: If the badword is onecap or allcap
11730 * use that for the goodword too. But if the badword is
11731 * allcap and it's only one char long use onecap. */
11732 c = su->su_badflags;
11733 if ((c & WF_ALLCAP)
11734 #ifdef FEAT_MBYTE
11735 && su->su_badlen == (*mb_ptr2len)(su->su_badptr)
11736 #else
11737 && su->su_badlen == 1
11738 #endif
11740 c = WF_ONECAP;
11741 c |= flags;
11743 /* When appending a compound word after a word character don't
11744 * use Onecap. */
11745 if (p != NULL && spell_iswordp_nmw(p))
11746 c &= ~WF_ONECAP;
11747 make_case_word(tword + sp->ts_splitoff,
11748 preword + sp->ts_prewordlen, c);
11751 if (!soundfold)
11753 /* Don't use a banned word. It may appear again as a good
11754 * word, thus remember it. */
11755 if (flags & WF_BANNED)
11757 add_banned(su, preword + sp->ts_prewordlen);
11758 break;
11760 if ((sp->ts_complen == sp->ts_compsplit
11761 && WAS_BANNED(su, preword + sp->ts_prewordlen))
11762 || WAS_BANNED(su, preword))
11764 if (slang->sl_compprog == NULL)
11765 break;
11766 /* the word so far was banned but we may try compounding */
11767 goodword_ends = FALSE;
11771 newscore = 0;
11772 if (!soundfold) /* soundfold words don't have flags */
11774 if ((flags & WF_REGION)
11775 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
11776 newscore += SCORE_REGION;
11777 if (flags & WF_RARE)
11778 newscore += SCORE_RARE;
11780 if (!spell_valid_case(su->su_badflags,
11781 captype(preword + sp->ts_prewordlen, NULL)))
11782 newscore += SCORE_ICASE;
11785 /* TODO: how about splitting in the soundfold tree? */
11786 if (fword_ends
11787 && goodword_ends
11788 && sp->ts_fidx >= sp->ts_fidxtry
11789 && compound_ok)
11791 /* The badword also ends: add suggestions. */
11792 #ifdef DEBUG_TRIEWALK
11793 if (soundfold && STRCMP(preword, "smwrd") == 0)
11795 int j;
11797 /* print the stack of changes that brought us here */
11798 smsg("------ %s -------", fword);
11799 for (j = 0; j < depth; ++j)
11800 smsg("%s", changename[j]);
11802 #endif
11803 if (soundfold)
11805 /* For soundfolded words we need to find the original
11806 * words, the edit distance and then add them. */
11807 add_sound_suggest(su, preword, sp->ts_score, lp);
11809 else
11811 /* Give a penalty when changing non-word char to word
11812 * char, e.g., "thes," -> "these". */
11813 p = fword + sp->ts_fidx;
11814 mb_ptr_back(fword, p);
11815 if (!spell_iswordp(p, curbuf))
11817 p = preword + STRLEN(preword);
11818 mb_ptr_back(preword, p);
11819 if (spell_iswordp(p, curbuf))
11820 newscore += SCORE_NONWORD;
11823 /* Give a bonus to words seen before. */
11824 score = score_wordcount_adj(slang,
11825 sp->ts_score + newscore,
11826 preword + sp->ts_prewordlen,
11827 sp->ts_prewordlen > 0);
11829 /* Add the suggestion if the score isn't too bad. */
11830 if (score <= su->su_maxscore)
11832 add_suggestion(su, &su->su_ga, preword,
11833 sp->ts_fidx - repextra,
11834 score, 0, FALSE, lp->lp_sallang, FALSE);
11836 if (su->su_badflags & WF_MIXCAP)
11838 /* We really don't know if the word should be
11839 * upper or lower case, add both. */
11840 c = captype(preword, NULL);
11841 if (c == 0 || c == WF_ALLCAP)
11843 make_case_word(tword + sp->ts_splitoff,
11844 preword + sp->ts_prewordlen,
11845 c == 0 ? WF_ALLCAP : 0);
11847 add_suggestion(su, &su->su_ga, preword,
11848 sp->ts_fidx - repextra,
11849 score + SCORE_ICASE, 0, FALSE,
11850 lp->lp_sallang, FALSE);
11858 * Try word split and/or compounding.
11860 if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
11861 #ifdef FEAT_MBYTE
11862 /* Don't split halfway a character. */
11863 && (!has_mbyte || sp->ts_tcharlen == 0)
11864 #endif
11867 int try_compound;
11868 int try_split;
11870 /* If past the end of the bad word don't try a split.
11871 * Otherwise try changing the next word. E.g., find
11872 * suggestions for "the the" where the second "the" is
11873 * different. It's done like a split.
11874 * TODO: word split for soundfold words */
11875 try_split = (sp->ts_fidx - repextra < su->su_badlen)
11876 && !soundfold;
11878 /* Get here in several situations:
11879 * 1. The word in the tree ends:
11880 * If the word allows compounding try that. Otherwise try
11881 * a split by inserting a space. For both check that a
11882 * valid words starts at fword[sp->ts_fidx].
11883 * For NOBREAK do like compounding to be able to check if
11884 * the next word is valid.
11885 * 2. The badword does end, but it was due to a change (e.g.,
11886 * a swap). No need to split, but do check that the
11887 * following word is valid.
11888 * 3. The badword and the word in the tree end. It may still
11889 * be possible to compound another (short) word.
11891 try_compound = FALSE;
11892 if (!soundfold
11893 && slang->sl_compprog != NULL
11894 && ((unsigned)flags >> 24) != 0
11895 && sp->ts_twordlen - sp->ts_splitoff
11896 >= slang->sl_compminlen
11897 #ifdef FEAT_MBYTE
11898 && (!has_mbyte
11899 || slang->sl_compminlen == 0
11900 || mb_charlen(tword + sp->ts_splitoff)
11901 >= slang->sl_compminlen)
11902 #endif
11903 && (slang->sl_compsylmax < MAXWLEN
11904 || sp->ts_complen + 1 - sp->ts_compsplit
11905 < slang->sl_compmax)
11906 && (can_be_compound(sp, slang,
11907 compflags, ((unsigned)flags >> 24))))
11910 try_compound = TRUE;
11911 compflags[sp->ts_complen] = ((unsigned)flags >> 24);
11912 compflags[sp->ts_complen + 1] = NUL;
11915 /* For NOBREAK we never try splitting, it won't make any word
11916 * valid. */
11917 if (slang->sl_nobreak)
11918 try_compound = TRUE;
11920 /* If we could add a compound word, and it's also possible to
11921 * split at this point, do the split first and set
11922 * TSF_DIDSPLIT to avoid doing it again. */
11923 else if (!fword_ends
11924 && try_compound
11925 && (sp->ts_flags & TSF_DIDSPLIT) == 0)
11927 try_compound = FALSE;
11928 sp->ts_flags |= TSF_DIDSPLIT;
11929 --sp->ts_curi; /* do the same NUL again */
11930 compflags[sp->ts_complen] = NUL;
11932 else
11933 sp->ts_flags &= ~TSF_DIDSPLIT;
11935 if (try_split || try_compound)
11937 if (!try_compound && (!fword_ends || !goodword_ends))
11939 /* If we're going to split need to check that the
11940 * words so far are valid for compounding. If there
11941 * is only one word it must not have the NEEDCOMPOUND
11942 * flag. */
11943 if (sp->ts_complen == sp->ts_compsplit
11944 && (flags & WF_NEEDCOMP))
11945 break;
11946 p = preword;
11947 while (*skiptowhite(p) != NUL)
11948 p = skipwhite(skiptowhite(p));
11949 if (sp->ts_complen > sp->ts_compsplit
11950 && !can_compound(slang, p,
11951 compflags + sp->ts_compsplit))
11952 break;
11954 if (slang->sl_nosplitsugs)
11955 newscore += SCORE_SPLIT_NO;
11956 else
11957 newscore += SCORE_SPLIT;
11959 /* Give a bonus to words seen before. */
11960 newscore = score_wordcount_adj(slang, newscore,
11961 preword + sp->ts_prewordlen, TRUE);
11964 if (TRY_DEEPER(su, stack, depth, newscore))
11966 go_deeper(stack, depth, newscore);
11967 #ifdef DEBUG_TRIEWALK
11968 if (!try_compound && !fword_ends)
11969 sprintf(changename[depth], "%.*s-%s: split",
11970 sp->ts_twordlen, tword, fword + sp->ts_fidx);
11971 else
11972 sprintf(changename[depth], "%.*s-%s: compound",
11973 sp->ts_twordlen, tword, fword + sp->ts_fidx);
11974 #endif
11975 /* Save things to be restored at STATE_SPLITUNDO. */
11976 sp->ts_save_badflags = su->su_badflags;
11977 sp->ts_state = STATE_SPLITUNDO;
11979 ++depth;
11980 sp = &stack[depth];
11982 /* Append a space to preword when splitting. */
11983 if (!try_compound && !fword_ends)
11984 STRCAT(preword, " ");
11985 sp->ts_prewordlen = (char_u)STRLEN(preword);
11986 sp->ts_splitoff = sp->ts_twordlen;
11987 sp->ts_splitfidx = sp->ts_fidx;
11989 /* If the badword has a non-word character at this
11990 * position skip it. That means replacing the
11991 * non-word character with a space. Always skip a
11992 * character when the word ends. But only when the
11993 * good word can end. */
11994 if (((!try_compound && !spell_iswordp_nmw(fword
11995 + sp->ts_fidx))
11996 || fword_ends)
11997 && fword[sp->ts_fidx] != NUL
11998 && goodword_ends)
12000 int l;
12002 #ifdef FEAT_MBYTE
12003 if (has_mbyte)
12004 l = MB_BYTE2LEN(fword[sp->ts_fidx]);
12005 else
12006 #endif
12007 l = 1;
12008 if (fword_ends)
12010 /* Copy the skipped character to preword. */
12011 mch_memmove(preword + sp->ts_prewordlen,
12012 fword + sp->ts_fidx, l);
12013 sp->ts_prewordlen += l;
12014 preword[sp->ts_prewordlen] = NUL;
12016 else
12017 sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
12018 sp->ts_fidx += l;
12021 /* When compounding include compound flag in
12022 * compflags[] (already set above). When splitting we
12023 * may start compounding over again. */
12024 if (try_compound)
12025 ++sp->ts_complen;
12026 else
12027 sp->ts_compsplit = sp->ts_complen;
12028 sp->ts_prefixdepth = PFD_NOPREFIX;
12030 /* set su->su_badflags to the caps type at this
12031 * position */
12032 #ifdef FEAT_MBYTE
12033 if (has_mbyte)
12034 n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
12035 else
12036 #endif
12037 n = sp->ts_fidx;
12038 su->su_badflags = badword_captype(su->su_badptr + n,
12039 su->su_badptr + su->su_badlen);
12041 /* Restart at top of the tree. */
12042 sp->ts_arridx = 0;
12044 /* If there are postponed prefixes, try these too. */
12045 if (pbyts != NULL)
12047 byts = pbyts;
12048 idxs = pidxs;
12049 sp->ts_prefixdepth = PFD_PREFIXTREE;
12050 sp->ts_state = STATE_NOPREFIX;
12055 break;
12057 case STATE_SPLITUNDO:
12058 /* Undo the changes done for word split or compound word. */
12059 su->su_badflags = sp->ts_save_badflags;
12061 /* Continue looking for NUL bytes. */
12062 sp->ts_state = STATE_START;
12064 /* In case we went into the prefix tree. */
12065 byts = fbyts;
12066 idxs = fidxs;
12067 break;
12069 case STATE_ENDNUL:
12070 /* Past the NUL bytes in the node. */
12071 su->su_badflags = sp->ts_save_badflags;
12072 if (fword[sp->ts_fidx] == NUL
12073 #ifdef FEAT_MBYTE
12074 && sp->ts_tcharlen == 0
12075 #endif
12078 /* The badword ends, can't use STATE_PLAIN. */
12079 sp->ts_state = STATE_DEL;
12080 break;
12082 sp->ts_state = STATE_PLAIN;
12083 /*FALLTHROUGH*/
12085 case STATE_PLAIN:
12087 * Go over all possible bytes at this node, add each to tword[]
12088 * and use child node. "ts_curi" is the index.
12090 arridx = sp->ts_arridx;
12091 if (sp->ts_curi > byts[arridx])
12093 /* Done all bytes at this node, do next state. When still at
12094 * already changed bytes skip the other tricks. */
12095 if (sp->ts_fidx >= sp->ts_fidxtry)
12096 sp->ts_state = STATE_DEL;
12097 else
12098 sp->ts_state = STATE_FINAL;
12100 else
12102 arridx += sp->ts_curi++;
12103 c = byts[arridx];
12105 /* Normal byte, go one level deeper. If it's not equal to the
12106 * byte in the bad word adjust the score. But don't even try
12107 * when the byte was already changed. And don't try when we
12108 * just deleted this byte, accepting it is always cheaper then
12109 * delete + substitute. */
12110 if (c == fword[sp->ts_fidx]
12111 #ifdef FEAT_MBYTE
12112 || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE)
12113 #endif
12115 newscore = 0;
12116 else
12117 newscore = SCORE_SUBST;
12118 if ((newscore == 0
12119 || (sp->ts_fidx >= sp->ts_fidxtry
12120 && ((sp->ts_flags & TSF_DIDDEL) == 0
12121 || c != fword[sp->ts_delidx])))
12122 && TRY_DEEPER(su, stack, depth, newscore))
12124 go_deeper(stack, depth, newscore);
12125 #ifdef DEBUG_TRIEWALK
12126 if (newscore > 0)
12127 sprintf(changename[depth], "%.*s-%s: subst %c to %c",
12128 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12129 fword[sp->ts_fidx], c);
12130 else
12131 sprintf(changename[depth], "%.*s-%s: accept %c",
12132 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12133 fword[sp->ts_fidx]);
12134 #endif
12135 ++depth;
12136 sp = &stack[depth];
12137 ++sp->ts_fidx;
12138 tword[sp->ts_twordlen++] = c;
12139 sp->ts_arridx = idxs[arridx];
12140 #ifdef FEAT_MBYTE
12141 if (newscore == SCORE_SUBST)
12142 sp->ts_isdiff = DIFF_YES;
12143 if (has_mbyte)
12145 /* Multi-byte characters are a bit complicated to
12146 * handle: They differ when any of the bytes differ
12147 * and then their length may also differ. */
12148 if (sp->ts_tcharlen == 0)
12150 /* First byte. */
12151 sp->ts_tcharidx = 0;
12152 sp->ts_tcharlen = MB_BYTE2LEN(c);
12153 sp->ts_fcharstart = sp->ts_fidx - 1;
12154 sp->ts_isdiff = (newscore != 0)
12155 ? DIFF_YES : DIFF_NONE;
12157 else if (sp->ts_isdiff == DIFF_INSERT)
12158 /* When inserting trail bytes don't advance in the
12159 * bad word. */
12160 --sp->ts_fidx;
12161 if (++sp->ts_tcharidx == sp->ts_tcharlen)
12163 /* Last byte of character. */
12164 if (sp->ts_isdiff == DIFF_YES)
12166 /* Correct ts_fidx for the byte length of the
12167 * character (we didn't check that before). */
12168 sp->ts_fidx = sp->ts_fcharstart
12169 + MB_BYTE2LEN(
12170 fword[sp->ts_fcharstart]);
12172 /* For changing a composing character adjust
12173 * the score from SCORE_SUBST to
12174 * SCORE_SUBCOMP. */
12175 if (enc_utf8
12176 && utf_iscomposing(
12177 mb_ptr2char(tword
12178 + sp->ts_twordlen
12179 - sp->ts_tcharlen))
12180 && utf_iscomposing(
12181 mb_ptr2char(fword
12182 + sp->ts_fcharstart)))
12183 sp->ts_score -=
12184 SCORE_SUBST - SCORE_SUBCOMP;
12186 /* For a similar character adjust score from
12187 * SCORE_SUBST to SCORE_SIMILAR. */
12188 else if (!soundfold
12189 && slang->sl_has_map
12190 && similar_chars(slang,
12191 mb_ptr2char(tword
12192 + sp->ts_twordlen
12193 - sp->ts_tcharlen),
12194 mb_ptr2char(fword
12195 + sp->ts_fcharstart)))
12196 sp->ts_score -=
12197 SCORE_SUBST - SCORE_SIMILAR;
12199 else if (sp->ts_isdiff == DIFF_INSERT
12200 && sp->ts_twordlen > sp->ts_tcharlen)
12202 p = tword + sp->ts_twordlen - sp->ts_tcharlen;
12203 c = mb_ptr2char(p);
12204 if (enc_utf8 && utf_iscomposing(c))
12206 /* Inserting a composing char doesn't
12207 * count that much. */
12208 sp->ts_score -= SCORE_INS - SCORE_INSCOMP;
12210 else
12212 /* If the previous character was the same,
12213 * thus doubling a character, give a bonus
12214 * to the score. Also for the soundfold
12215 * tree (might seem illogical but does
12216 * give better scores). */
12217 mb_ptr_back(tword, p);
12218 if (c == mb_ptr2char(p))
12219 sp->ts_score -= SCORE_INS
12220 - SCORE_INSDUP;
12224 /* Starting a new char, reset the length. */
12225 sp->ts_tcharlen = 0;
12228 else
12229 #endif
12231 /* If we found a similar char adjust the score.
12232 * We do this after calling go_deeper() because
12233 * it's slow. */
12234 if (newscore != 0
12235 && !soundfold
12236 && slang->sl_has_map
12237 && similar_chars(slang,
12238 c, fword[sp->ts_fidx - 1]))
12239 sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
12243 break;
12245 case STATE_DEL:
12246 #ifdef FEAT_MBYTE
12247 /* When past the first byte of a multi-byte char don't try
12248 * delete/insert/swap a character. */
12249 if (has_mbyte && sp->ts_tcharlen > 0)
12251 sp->ts_state = STATE_FINAL;
12252 break;
12254 #endif
12256 * Try skipping one character in the bad word (delete it).
12258 sp->ts_state = STATE_INS_PREP;
12259 sp->ts_curi = 1;
12260 if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')
12261 /* Deleting a vowel at the start of a word counts less, see
12262 * soundalike_score(). */
12263 newscore = 2 * SCORE_DEL / 3;
12264 else
12265 newscore = SCORE_DEL;
12266 if (fword[sp->ts_fidx] != NUL
12267 && TRY_DEEPER(su, stack, depth, newscore))
12269 go_deeper(stack, depth, newscore);
12270 #ifdef DEBUG_TRIEWALK
12271 sprintf(changename[depth], "%.*s-%s: delete %c",
12272 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12273 fword[sp->ts_fidx]);
12274 #endif
12275 ++depth;
12277 /* Remember what character we deleted, so that we can avoid
12278 * inserting it again. */
12279 stack[depth].ts_flags |= TSF_DIDDEL;
12280 stack[depth].ts_delidx = sp->ts_fidx;
12282 /* Advance over the character in fword[]. Give a bonus to the
12283 * score if the same character is following "nn" -> "n". It's
12284 * a bit illogical for soundfold tree but it does give better
12285 * results. */
12286 #ifdef FEAT_MBYTE
12287 if (has_mbyte)
12289 c = mb_ptr2char(fword + sp->ts_fidx);
12290 stack[depth].ts_fidx += MB_BYTE2LEN(fword[sp->ts_fidx]);
12291 if (enc_utf8 && utf_iscomposing(c))
12292 stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
12293 else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))
12294 stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
12296 else
12297 #endif
12299 ++stack[depth].ts_fidx;
12300 if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])
12301 stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
12303 break;
12305 /*FALLTHROUGH*/
12307 case STATE_INS_PREP:
12308 if (sp->ts_flags & TSF_DIDDEL)
12310 /* If we just deleted a byte then inserting won't make sense,
12311 * a substitute is always cheaper. */
12312 sp->ts_state = STATE_SWAP;
12313 break;
12316 /* skip over NUL bytes */
12317 n = sp->ts_arridx;
12318 for (;;)
12320 if (sp->ts_curi > byts[n])
12322 /* Only NUL bytes at this node, go to next state. */
12323 sp->ts_state = STATE_SWAP;
12324 break;
12326 if (byts[n + sp->ts_curi] != NUL)
12328 /* Found a byte to insert. */
12329 sp->ts_state = STATE_INS;
12330 break;
12332 ++sp->ts_curi;
12334 break;
12336 /*FALLTHROUGH*/
12338 case STATE_INS:
12339 /* Insert one byte. Repeat this for each possible byte at this
12340 * node. */
12341 n = sp->ts_arridx;
12342 if (sp->ts_curi > byts[n])
12344 /* Done all bytes at this node, go to next state. */
12345 sp->ts_state = STATE_SWAP;
12346 break;
12349 /* Do one more byte at this node, but:
12350 * - Skip NUL bytes.
12351 * - Skip the byte if it's equal to the byte in the word,
12352 * accepting that byte is always better.
12354 n += sp->ts_curi++;
12355 c = byts[n];
12356 if (soundfold && sp->ts_twordlen == 0 && c == '*')
12357 /* Inserting a vowel at the start of a word counts less,
12358 * see soundalike_score(). */
12359 newscore = 2 * SCORE_INS / 3;
12360 else
12361 newscore = SCORE_INS;
12362 if (c != fword[sp->ts_fidx]
12363 && TRY_DEEPER(su, stack, depth, newscore))
12365 go_deeper(stack, depth, newscore);
12366 #ifdef DEBUG_TRIEWALK
12367 sprintf(changename[depth], "%.*s-%s: insert %c",
12368 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12370 #endif
12371 ++depth;
12372 sp = &stack[depth];
12373 tword[sp->ts_twordlen++] = c;
12374 sp->ts_arridx = idxs[n];
12375 #ifdef FEAT_MBYTE
12376 if (has_mbyte)
12378 fl = MB_BYTE2LEN(c);
12379 if (fl > 1)
12381 /* There are following bytes for the same character.
12382 * We must find all bytes before trying
12383 * delete/insert/swap/etc. */
12384 sp->ts_tcharlen = fl;
12385 sp->ts_tcharidx = 1;
12386 sp->ts_isdiff = DIFF_INSERT;
12389 else
12390 fl = 1;
12391 if (fl == 1)
12392 #endif
12394 /* If the previous character was the same, thus doubling a
12395 * character, give a bonus to the score. Also for
12396 * soundfold words (illogical but does give a better
12397 * score). */
12398 if (sp->ts_twordlen >= 2
12399 && tword[sp->ts_twordlen - 2] == c)
12400 sp->ts_score -= SCORE_INS - SCORE_INSDUP;
12403 break;
12405 case STATE_SWAP:
12407 * Swap two bytes in the bad word: "12" -> "21".
12408 * We change "fword" here, it's changed back afterwards at
12409 * STATE_UNSWAP.
12411 p = fword + sp->ts_fidx;
12412 c = *p;
12413 if (c == NUL)
12415 /* End of word, can't swap or replace. */
12416 sp->ts_state = STATE_FINAL;
12417 break;
12420 /* Don't swap if the first character is not a word character.
12421 * SWAP3 etc. also don't make sense then. */
12422 if (!soundfold && !spell_iswordp(p, curbuf))
12424 sp->ts_state = STATE_REP_INI;
12425 break;
12428 #ifdef FEAT_MBYTE
12429 if (has_mbyte)
12431 n = mb_cptr2len(p);
12432 c = mb_ptr2char(p);
12433 if (p[n] == NUL)
12434 c2 = NUL;
12435 else if (!soundfold && !spell_iswordp(p + n, curbuf))
12436 c2 = c; /* don't swap non-word char */
12437 else
12438 c2 = mb_ptr2char(p + n);
12440 else
12441 #endif
12443 if (p[1] == NUL)
12444 c2 = NUL;
12445 else if (!soundfold && !spell_iswordp(p + 1, curbuf))
12446 c2 = c; /* don't swap non-word char */
12447 else
12448 c2 = p[1];
12451 /* When the second character is NUL we can't swap. */
12452 if (c2 == NUL)
12454 sp->ts_state = STATE_REP_INI;
12455 break;
12458 /* When characters are identical, swap won't do anything.
12459 * Also get here if the second char is not a word character. */
12460 if (c == c2)
12462 sp->ts_state = STATE_SWAP3;
12463 break;
12465 if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
12467 go_deeper(stack, depth, SCORE_SWAP);
12468 #ifdef DEBUG_TRIEWALK
12469 sprintf(changename[depth], "%.*s-%s: swap %c and %c",
12470 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12471 c, c2);
12472 #endif
12473 sp->ts_state = STATE_UNSWAP;
12474 ++depth;
12475 #ifdef FEAT_MBYTE
12476 if (has_mbyte)
12478 fl = mb_char2len(c2);
12479 mch_memmove(p, p + n, fl);
12480 mb_char2bytes(c, p + fl);
12481 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
12483 else
12484 #endif
12486 p[0] = c2;
12487 p[1] = c;
12488 stack[depth].ts_fidxtry = sp->ts_fidx + 2;
12491 else
12492 /* If this swap doesn't work then SWAP3 won't either. */
12493 sp->ts_state = STATE_REP_INI;
12494 break;
12496 case STATE_UNSWAP:
12497 /* Undo the STATE_SWAP swap: "21" -> "12". */
12498 p = fword + sp->ts_fidx;
12499 #ifdef FEAT_MBYTE
12500 if (has_mbyte)
12502 n = MB_BYTE2LEN(*p);
12503 c = mb_ptr2char(p + n);
12504 mch_memmove(p + MB_BYTE2LEN(p[n]), p, n);
12505 mb_char2bytes(c, p);
12507 else
12508 #endif
12510 c = *p;
12511 *p = p[1];
12512 p[1] = c;
12514 /*FALLTHROUGH*/
12516 case STATE_SWAP3:
12517 /* Swap two bytes, skipping one: "123" -> "321". We change
12518 * "fword" here, it's changed back afterwards at STATE_UNSWAP3. */
12519 p = fword + sp->ts_fidx;
12520 #ifdef FEAT_MBYTE
12521 if (has_mbyte)
12523 n = mb_cptr2len(p);
12524 c = mb_ptr2char(p);
12525 fl = mb_cptr2len(p + n);
12526 c2 = mb_ptr2char(p + n);
12527 if (!soundfold && !spell_iswordp(p + n + fl, curbuf))
12528 c3 = c; /* don't swap non-word char */
12529 else
12530 c3 = mb_ptr2char(p + n + fl);
12532 else
12533 #endif
12535 c = *p;
12536 c2 = p[1];
12537 if (!soundfold && !spell_iswordp(p + 2, curbuf))
12538 c3 = c; /* don't swap non-word char */
12539 else
12540 c3 = p[2];
12543 /* When characters are identical: "121" then SWAP3 result is
12544 * identical, ROT3L result is same as SWAP: "211", ROT3L result is
12545 * same as SWAP on next char: "112". Thus skip all swapping.
12546 * Also skip when c3 is NUL.
12547 * Also get here when the third character is not a word character.
12548 * Second character may any char: "a.b" -> "b.a" */
12549 if (c == c3 || c3 == NUL)
12551 sp->ts_state = STATE_REP_INI;
12552 break;
12554 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12556 go_deeper(stack, depth, SCORE_SWAP3);
12557 #ifdef DEBUG_TRIEWALK
12558 sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",
12559 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12560 c, c3);
12561 #endif
12562 sp->ts_state = STATE_UNSWAP3;
12563 ++depth;
12564 #ifdef FEAT_MBYTE
12565 if (has_mbyte)
12567 tl = mb_char2len(c3);
12568 mch_memmove(p, p + n + fl, tl);
12569 mb_char2bytes(c2, p + tl);
12570 mb_char2bytes(c, p + fl + tl);
12571 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
12573 else
12574 #endif
12576 p[0] = p[2];
12577 p[2] = c;
12578 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12581 else
12582 sp->ts_state = STATE_REP_INI;
12583 break;
12585 case STATE_UNSWAP3:
12586 /* Undo STATE_SWAP3: "321" -> "123" */
12587 p = fword + sp->ts_fidx;
12588 #ifdef FEAT_MBYTE
12589 if (has_mbyte)
12591 n = MB_BYTE2LEN(*p);
12592 c2 = mb_ptr2char(p + n);
12593 fl = MB_BYTE2LEN(p[n]);
12594 c = mb_ptr2char(p + n + fl);
12595 tl = MB_BYTE2LEN(p[n + fl]);
12596 mch_memmove(p + fl + tl, p, n);
12597 mb_char2bytes(c, p);
12598 mb_char2bytes(c2, p + tl);
12599 p = p + tl;
12601 else
12602 #endif
12604 c = *p;
12605 *p = p[2];
12606 p[2] = c;
12607 ++p;
12610 if (!soundfold && !spell_iswordp(p, curbuf))
12612 /* Middle char is not a word char, skip the rotate. First and
12613 * third char were already checked at swap and swap3. */
12614 sp->ts_state = STATE_REP_INI;
12615 break;
12618 /* Rotate three characters left: "123" -> "231". We change
12619 * "fword" here, it's changed back afterwards at STATE_UNROT3L. */
12620 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12622 go_deeper(stack, depth, SCORE_SWAP3);
12623 #ifdef DEBUG_TRIEWALK
12624 p = fword + sp->ts_fidx;
12625 sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",
12626 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12627 p[0], p[1], p[2]);
12628 #endif
12629 sp->ts_state = STATE_UNROT3L;
12630 ++depth;
12631 p = fword + sp->ts_fidx;
12632 #ifdef FEAT_MBYTE
12633 if (has_mbyte)
12635 n = mb_cptr2len(p);
12636 c = mb_ptr2char(p);
12637 fl = mb_cptr2len(p + n);
12638 fl += mb_cptr2len(p + n + fl);
12639 mch_memmove(p, p + n, fl);
12640 mb_char2bytes(c, p + fl);
12641 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
12643 else
12644 #endif
12646 c = *p;
12647 *p = p[1];
12648 p[1] = p[2];
12649 p[2] = c;
12650 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12653 else
12654 sp->ts_state = STATE_REP_INI;
12655 break;
12657 case STATE_UNROT3L:
12658 /* Undo ROT3L: "231" -> "123" */
12659 p = fword + sp->ts_fidx;
12660 #ifdef FEAT_MBYTE
12661 if (has_mbyte)
12663 n = MB_BYTE2LEN(*p);
12664 n += MB_BYTE2LEN(p[n]);
12665 c = mb_ptr2char(p + n);
12666 tl = MB_BYTE2LEN(p[n]);
12667 mch_memmove(p + tl, p, n);
12668 mb_char2bytes(c, p);
12670 else
12671 #endif
12673 c = p[2];
12674 p[2] = p[1];
12675 p[1] = *p;
12676 *p = c;
12679 /* Rotate three bytes right: "123" -> "312". We change "fword"
12680 * here, it's changed back afterwards at STATE_UNROT3R. */
12681 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12683 go_deeper(stack, depth, SCORE_SWAP3);
12684 #ifdef DEBUG_TRIEWALK
12685 p = fword + sp->ts_fidx;
12686 sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",
12687 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12688 p[0], p[1], p[2]);
12689 #endif
12690 sp->ts_state = STATE_UNROT3R;
12691 ++depth;
12692 p = fword + sp->ts_fidx;
12693 #ifdef FEAT_MBYTE
12694 if (has_mbyte)
12696 n = mb_cptr2len(p);
12697 n += mb_cptr2len(p + n);
12698 c = mb_ptr2char(p + n);
12699 tl = mb_cptr2len(p + n);
12700 mch_memmove(p + tl, p, n);
12701 mb_char2bytes(c, p);
12702 stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
12704 else
12705 #endif
12707 c = p[2];
12708 p[2] = p[1];
12709 p[1] = *p;
12710 *p = c;
12711 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12714 else
12715 sp->ts_state = STATE_REP_INI;
12716 break;
12718 case STATE_UNROT3R:
12719 /* Undo ROT3R: "312" -> "123" */
12720 p = fword + sp->ts_fidx;
12721 #ifdef FEAT_MBYTE
12722 if (has_mbyte)
12724 c = mb_ptr2char(p);
12725 tl = MB_BYTE2LEN(*p);
12726 n = MB_BYTE2LEN(p[tl]);
12727 n += MB_BYTE2LEN(p[tl + n]);
12728 mch_memmove(p, p + tl, n);
12729 mb_char2bytes(c, p + n);
12731 else
12732 #endif
12734 c = *p;
12735 *p = p[1];
12736 p[1] = p[2];
12737 p[2] = c;
12739 /*FALLTHROUGH*/
12741 case STATE_REP_INI:
12742 /* Check if matching with REP items from the .aff file would work.
12743 * Quickly skip if:
12744 * - there are no REP items and we are not in the soundfold trie
12745 * - the score is going to be too high anyway
12746 * - already applied a REP item or swapped here */
12747 if ((lp->lp_replang == NULL && !soundfold)
12748 || sp->ts_score + SCORE_REP >= su->su_maxscore
12749 || sp->ts_fidx < sp->ts_fidxtry)
12751 sp->ts_state = STATE_FINAL;
12752 break;
12755 /* Use the first byte to quickly find the first entry that may
12756 * match. If the index is -1 there is none. */
12757 if (soundfold)
12758 sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
12759 else
12760 sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];
12762 if (sp->ts_curi < 0)
12764 sp->ts_state = STATE_FINAL;
12765 break;
12768 sp->ts_state = STATE_REP;
12769 /*FALLTHROUGH*/
12771 case STATE_REP:
12772 /* Try matching with REP items from the .aff file. For each match
12773 * replace the characters and check if the resulting word is
12774 * valid. */
12775 p = fword + sp->ts_fidx;
12777 if (soundfold)
12778 gap = &slang->sl_repsal;
12779 else
12780 gap = &lp->lp_replang->sl_rep;
12781 while (sp->ts_curi < gap->ga_len)
12783 ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
12784 if (*ftp->ft_from != *p)
12786 /* past possible matching entries */
12787 sp->ts_curi = gap->ga_len;
12788 break;
12790 if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
12791 && TRY_DEEPER(su, stack, depth, SCORE_REP))
12793 go_deeper(stack, depth, SCORE_REP);
12794 #ifdef DEBUG_TRIEWALK
12795 sprintf(changename[depth], "%.*s-%s: replace %s with %s",
12796 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12797 ftp->ft_from, ftp->ft_to);
12798 #endif
12799 /* Need to undo this afterwards. */
12800 sp->ts_state = STATE_REP_UNDO;
12802 /* Change the "from" to the "to" string. */
12803 ++depth;
12804 fl = (int)STRLEN(ftp->ft_from);
12805 tl = (int)STRLEN(ftp->ft_to);
12806 if (fl != tl)
12808 STRMOVE(p + tl, p + fl);
12809 repextra += tl - fl;
12811 mch_memmove(p, ftp->ft_to, tl);
12812 stack[depth].ts_fidxtry = sp->ts_fidx + tl;
12813 #ifdef FEAT_MBYTE
12814 stack[depth].ts_tcharlen = 0;
12815 #endif
12816 break;
12820 if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
12821 /* No (more) matches. */
12822 sp->ts_state = STATE_FINAL;
12824 break;
12826 case STATE_REP_UNDO:
12827 /* Undo a REP replacement and continue with the next one. */
12828 if (soundfold)
12829 gap = &slang->sl_repsal;
12830 else
12831 gap = &lp->lp_replang->sl_rep;
12832 ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
12833 fl = (int)STRLEN(ftp->ft_from);
12834 tl = (int)STRLEN(ftp->ft_to);
12835 p = fword + sp->ts_fidx;
12836 if (fl != tl)
12838 STRMOVE(p + fl, p + tl);
12839 repextra -= tl - fl;
12841 mch_memmove(p, ftp->ft_from, fl);
12842 sp->ts_state = STATE_REP;
12843 break;
12845 default:
12846 /* Did all possible states at this level, go up one level. */
12847 --depth;
12849 if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
12851 /* Continue in or go back to the prefix tree. */
12852 byts = pbyts;
12853 idxs = pidxs;
12856 /* Don't check for CTRL-C too often, it takes time. */
12857 if (--breakcheckcount == 0)
12859 ui_breakcheck();
12860 breakcheckcount = 1000;
12868 * Go one level deeper in the tree.
12870 static void
12871 go_deeper(stack, depth, score_add)
12872 trystate_T *stack;
12873 int depth;
12874 int score_add;
12876 stack[depth + 1] = stack[depth];
12877 stack[depth + 1].ts_state = STATE_START;
12878 stack[depth + 1].ts_score = stack[depth].ts_score + score_add;
12879 stack[depth + 1].ts_curi = 1; /* start just after length byte */
12880 stack[depth + 1].ts_flags = 0;
12883 #ifdef FEAT_MBYTE
12885 * Case-folding may change the number of bytes: Count nr of chars in
12886 * fword[flen] and return the byte length of that many chars in "word".
12888 static int
12889 nofold_len(fword, flen, word)
12890 char_u *fword;
12891 int flen;
12892 char_u *word;
12894 char_u *p;
12895 int i = 0;
12897 for (p = fword; p < fword + flen; mb_ptr_adv(p))
12898 ++i;
12899 for (p = word; i > 0; mb_ptr_adv(p))
12900 --i;
12901 return (int)(p - word);
12903 #endif
12906 * "fword" is a good word with case folded. Find the matching keep-case
12907 * words and put it in "kword".
12908 * Theoretically there could be several keep-case words that result in the
12909 * same case-folded word, but we only find one...
12911 static void
12912 find_keepcap_word(slang, fword, kword)
12913 slang_T *slang;
12914 char_u *fword;
12915 char_u *kword;
12917 char_u uword[MAXWLEN]; /* "fword" in upper-case */
12918 int depth;
12919 idx_T tryidx;
12921 /* The following arrays are used at each depth in the tree. */
12922 idx_T arridx[MAXWLEN];
12923 int round[MAXWLEN];
12924 int fwordidx[MAXWLEN];
12925 int uwordidx[MAXWLEN];
12926 int kwordlen[MAXWLEN];
12928 int flen, ulen;
12929 int l;
12930 int len;
12931 int c;
12932 idx_T lo, hi, m;
12933 char_u *p;
12934 char_u *byts = slang->sl_kbyts; /* array with bytes of the words */
12935 idx_T *idxs = slang->sl_kidxs; /* array with indexes */
12937 if (byts == NULL)
12939 /* array is empty: "cannot happen" */
12940 *kword = NUL;
12941 return;
12944 /* Make an all-cap version of "fword". */
12945 allcap_copy(fword, uword);
12948 * Each character needs to be tried both case-folded and upper-case.
12949 * All this gets very complicated if we keep in mind that changing case
12950 * may change the byte length of a multi-byte character...
12952 depth = 0;
12953 arridx[0] = 0;
12954 round[0] = 0;
12955 fwordidx[0] = 0;
12956 uwordidx[0] = 0;
12957 kwordlen[0] = 0;
12958 while (depth >= 0)
12960 if (fword[fwordidx[depth]] == NUL)
12962 /* We are at the end of "fword". If the tree allows a word to end
12963 * here we have found a match. */
12964 if (byts[arridx[depth] + 1] == 0)
12966 kword[kwordlen[depth]] = NUL;
12967 return;
12970 /* kword is getting too long, continue one level up */
12971 --depth;
12973 else if (++round[depth] > 2)
12975 /* tried both fold-case and upper-case character, continue one
12976 * level up */
12977 --depth;
12979 else
12982 * round[depth] == 1: Try using the folded-case character.
12983 * round[depth] == 2: Try using the upper-case character.
12985 #ifdef FEAT_MBYTE
12986 if (has_mbyte)
12988 flen = mb_cptr2len(fword + fwordidx[depth]);
12989 ulen = mb_cptr2len(uword + uwordidx[depth]);
12991 else
12992 #endif
12993 ulen = flen = 1;
12994 if (round[depth] == 1)
12996 p = fword + fwordidx[depth];
12997 l = flen;
12999 else
13001 p = uword + uwordidx[depth];
13002 l = ulen;
13005 for (tryidx = arridx[depth]; l > 0; --l)
13007 /* Perform a binary search in the list of accepted bytes. */
13008 len = byts[tryidx++];
13009 c = *p++;
13010 lo = tryidx;
13011 hi = tryidx + len - 1;
13012 while (lo < hi)
13014 m = (lo + hi) / 2;
13015 if (byts[m] > c)
13016 hi = m - 1;
13017 else if (byts[m] < c)
13018 lo = m + 1;
13019 else
13021 lo = hi = m;
13022 break;
13026 /* Stop if there is no matching byte. */
13027 if (hi < lo || byts[lo] != c)
13028 break;
13030 /* Continue at the child (if there is one). */
13031 tryidx = idxs[lo];
13034 if (l == 0)
13037 * Found the matching char. Copy it to "kword" and go a
13038 * level deeper.
13040 if (round[depth] == 1)
13042 STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth],
13043 flen);
13044 kwordlen[depth + 1] = kwordlen[depth] + flen;
13046 else
13048 STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth],
13049 ulen);
13050 kwordlen[depth + 1] = kwordlen[depth] + ulen;
13052 fwordidx[depth + 1] = fwordidx[depth] + flen;
13053 uwordidx[depth + 1] = uwordidx[depth] + ulen;
13055 ++depth;
13056 arridx[depth] = tryidx;
13057 round[depth] = 0;
13062 /* Didn't find it: "cannot happen". */
13063 *kword = NUL;
13067 * Compute the sound-a-like score for suggestions in su->su_ga and add them to
13068 * su->su_sga.
13070 static void
13071 score_comp_sal(su)
13072 suginfo_T *su;
13074 langp_T *lp;
13075 char_u badsound[MAXWLEN];
13076 int i;
13077 suggest_T *stp;
13078 suggest_T *sstp;
13079 int score;
13080 int lpi;
13082 if (ga_grow(&su->su_sga, su->su_ga.ga_len) == FAIL)
13083 return;
13085 /* Use the sound-folding of the first language that supports it. */
13086 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13088 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13089 if (lp->lp_slang->sl_sal.ga_len > 0)
13091 /* soundfold the bad word */
13092 spell_soundfold(lp->lp_slang, su->su_fbadword, TRUE, badsound);
13094 for (i = 0; i < su->su_ga.ga_len; ++i)
13096 stp = &SUG(su->su_ga, i);
13098 /* Case-fold the suggested word, sound-fold it and compute the
13099 * sound-a-like score. */
13100 score = stp_sal_score(stp, su, lp->lp_slang, badsound);
13101 if (score < SCORE_MAXMAX)
13103 /* Add the suggestion. */
13104 sstp = &SUG(su->su_sga, su->su_sga.ga_len);
13105 sstp->st_word = vim_strsave(stp->st_word);
13106 if (sstp->st_word != NULL)
13108 sstp->st_wordlen = stp->st_wordlen;
13109 sstp->st_score = score;
13110 sstp->st_altscore = 0;
13111 sstp->st_orglen = stp->st_orglen;
13112 ++su->su_sga.ga_len;
13116 break;
13122 * Combine the list of suggestions in su->su_ga and su->su_sga.
13123 * They are intwined.
13125 static void
13126 score_combine(su)
13127 suginfo_T *su;
13129 int i;
13130 int j;
13131 garray_T ga;
13132 garray_T *gap;
13133 langp_T *lp;
13134 suggest_T *stp;
13135 char_u *p;
13136 char_u badsound[MAXWLEN];
13137 int round;
13138 int lpi;
13139 slang_T *slang = NULL;
13141 /* Add the alternate score to su_ga. */
13142 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13144 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13145 if (lp->lp_slang->sl_sal.ga_len > 0)
13147 /* soundfold the bad word */
13148 slang = lp->lp_slang;
13149 spell_soundfold(slang, su->su_fbadword, TRUE, badsound);
13151 for (i = 0; i < su->su_ga.ga_len; ++i)
13153 stp = &SUG(su->su_ga, i);
13154 stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
13155 if (stp->st_altscore == SCORE_MAXMAX)
13156 stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
13157 else
13158 stp->st_score = (stp->st_score * 3
13159 + stp->st_altscore) / 4;
13160 stp->st_salscore = FALSE;
13162 break;
13166 if (slang == NULL) /* Using "double" without sound folding. */
13168 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore,
13169 su->su_maxcount);
13170 return;
13173 /* Add the alternate score to su_sga. */
13174 for (i = 0; i < su->su_sga.ga_len; ++i)
13176 stp = &SUG(su->su_sga, i);
13177 stp->st_altscore = spell_edit_score(slang,
13178 su->su_badword, stp->st_word);
13179 if (stp->st_score == SCORE_MAXMAX)
13180 stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
13181 else
13182 stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8;
13183 stp->st_salscore = TRUE;
13186 /* Remove bad suggestions, sort the suggestions and truncate at "maxcount"
13187 * for both lists. */
13188 check_suggestions(su, &su->su_ga);
13189 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
13190 check_suggestions(su, &su->su_sga);
13191 (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount);
13193 ga_init2(&ga, (int)sizeof(suginfo_T), 1);
13194 if (ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len) == FAIL)
13195 return;
13197 stp = &SUG(ga, 0);
13198 for (i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i)
13200 /* round 1: get a suggestion from su_ga
13201 * round 2: get a suggestion from su_sga */
13202 for (round = 1; round <= 2; ++round)
13204 gap = round == 1 ? &su->su_ga : &su->su_sga;
13205 if (i < gap->ga_len)
13207 /* Don't add a word if it's already there. */
13208 p = SUG(*gap, i).st_word;
13209 for (j = 0; j < ga.ga_len; ++j)
13210 if (STRCMP(stp[j].st_word, p) == 0)
13211 break;
13212 if (j == ga.ga_len)
13213 stp[ga.ga_len++] = SUG(*gap, i);
13214 else
13215 vim_free(p);
13220 ga_clear(&su->su_ga);
13221 ga_clear(&su->su_sga);
13223 /* Truncate the list to the number of suggestions that will be displayed. */
13224 if (ga.ga_len > su->su_maxcount)
13226 for (i = su->su_maxcount; i < ga.ga_len; ++i)
13227 vim_free(stp[i].st_word);
13228 ga.ga_len = su->su_maxcount;
13231 su->su_ga = ga;
13235 * For the goodword in "stp" compute the soundalike score compared to the
13236 * badword.
13238 static int
13239 stp_sal_score(stp, su, slang, badsound)
13240 suggest_T *stp;
13241 suginfo_T *su;
13242 slang_T *slang;
13243 char_u *badsound; /* sound-folded badword */
13245 char_u *p;
13246 char_u *pbad;
13247 char_u *pgood;
13248 char_u badsound2[MAXWLEN];
13249 char_u fword[MAXWLEN];
13250 char_u goodsound[MAXWLEN];
13251 char_u goodword[MAXWLEN];
13252 int lendiff;
13254 lendiff = (int)(su->su_badlen - stp->st_orglen);
13255 if (lendiff >= 0)
13256 pbad = badsound;
13257 else
13259 /* soundfold the bad word with more characters following */
13260 (void)spell_casefold(su->su_badptr, stp->st_orglen, fword, MAXWLEN);
13262 /* When joining two words the sound often changes a lot. E.g., "t he"
13263 * sounds like "t h" while "the" sounds like "@". Avoid that by
13264 * removing the space. Don't do it when the good word also contains a
13265 * space. */
13266 if (vim_iswhite(su->su_badptr[su->su_badlen])
13267 && *skiptowhite(stp->st_word) == NUL)
13268 for (p = fword; *(p = skiptowhite(p)) != NUL; )
13269 STRMOVE(p, p + 1);
13271 spell_soundfold(slang, fword, TRUE, badsound2);
13272 pbad = badsound2;
13275 if (lendiff > 0)
13277 /* Add part of the bad word to the good word, so that we soundfold
13278 * what replaces the bad word. */
13279 STRCPY(goodword, stp->st_word);
13280 vim_strncpy(goodword + stp->st_wordlen,
13281 su->su_badptr + su->su_badlen - lendiff, lendiff);
13282 pgood = goodword;
13284 else
13285 pgood = stp->st_word;
13287 /* Sound-fold the word and compute the score for the difference. */
13288 spell_soundfold(slang, pgood, FALSE, goodsound);
13290 return soundalike_score(goodsound, pbad);
13293 /* structure used to store soundfolded words that add_sound_suggest() has
13294 * handled already. */
13295 typedef struct
13297 short sft_score; /* lowest score used */
13298 char_u sft_word[1]; /* soundfolded word, actually longer */
13299 } sftword_T;
13301 static sftword_T dumsft;
13302 #define HIKEY2SFT(p) ((sftword_T *)(p - (dumsft.sft_word - (char_u *)&dumsft)))
13303 #define HI2SFT(hi) HIKEY2SFT((hi)->hi_key)
13306 * Prepare for calling suggest_try_soundalike().
13308 static void
13309 suggest_try_soundalike_prep()
13311 langp_T *lp;
13312 int lpi;
13313 slang_T *slang;
13315 /* Do this for all languages that support sound folding and for which a
13316 * .sug file has been loaded. */
13317 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13319 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13320 slang = lp->lp_slang;
13321 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13322 /* prepare the hashtable used by add_sound_suggest() */
13323 hash_init(&slang->sl_sounddone);
13328 * Find suggestions by comparing the word in a sound-a-like form.
13329 * Note: This doesn't support postponed prefixes.
13331 static void
13332 suggest_try_soundalike(su)
13333 suginfo_T *su;
13335 char_u salword[MAXWLEN];
13336 langp_T *lp;
13337 int lpi;
13338 slang_T *slang;
13340 /* Do this for all languages that support sound folding and for which a
13341 * .sug file has been loaded. */
13342 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13344 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13345 slang = lp->lp_slang;
13346 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13348 /* soundfold the bad word */
13349 spell_soundfold(slang, su->su_fbadword, TRUE, salword);
13351 /* try all kinds of inserts/deletes/swaps/etc. */
13352 /* TODO: also soundfold the next words, so that we can try joining
13353 * and splitting */
13354 suggest_trie_walk(su, lp, salword, TRUE);
13360 * Finish up after calling suggest_try_soundalike().
13362 static void
13363 suggest_try_soundalike_finish()
13365 langp_T *lp;
13366 int lpi;
13367 slang_T *slang;
13368 int todo;
13369 hashitem_T *hi;
13371 /* Do this for all languages that support sound folding and for which a
13372 * .sug file has been loaded. */
13373 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13375 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13376 slang = lp->lp_slang;
13377 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13379 /* Free the info about handled words. */
13380 todo = (int)slang->sl_sounddone.ht_used;
13381 for (hi = slang->sl_sounddone.ht_array; todo > 0; ++hi)
13382 if (!HASHITEM_EMPTY(hi))
13384 vim_free(HI2SFT(hi));
13385 --todo;
13388 /* Clear the hashtable, it may also be used by another region. */
13389 hash_clear(&slang->sl_sounddone);
13390 hash_init(&slang->sl_sounddone);
13396 * A match with a soundfolded word is found. Add the good word(s) that
13397 * produce this soundfolded word.
13399 static void
13400 add_sound_suggest(su, goodword, score, lp)
13401 suginfo_T *su;
13402 char_u *goodword;
13403 int score; /* soundfold score */
13404 langp_T *lp;
13406 slang_T *slang = lp->lp_slang; /* language for sound folding */
13407 int sfwordnr;
13408 char_u *nrline;
13409 int orgnr;
13410 char_u theword[MAXWLEN];
13411 int i;
13412 int wlen;
13413 char_u *byts;
13414 idx_T *idxs;
13415 int n;
13416 int wordcount;
13417 int wc;
13418 int goodscore;
13419 hash_T hash;
13420 hashitem_T *hi;
13421 sftword_T *sft;
13422 int bc, gc;
13423 int limit;
13426 * It's very well possible that the same soundfold word is found several
13427 * times with different scores. Since the following is quite slow only do
13428 * the words that have a better score than before. Use a hashtable to
13429 * remember the words that have been done.
13431 hash = hash_hash(goodword);
13432 hi = hash_lookup(&slang->sl_sounddone, goodword, hash);
13433 if (HASHITEM_EMPTY(hi))
13435 sft = (sftword_T *)alloc((unsigned)(sizeof(sftword_T)
13436 + STRLEN(goodword)));
13437 if (sft != NULL)
13439 sft->sft_score = score;
13440 STRCPY(sft->sft_word, goodword);
13441 hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash);
13444 else
13446 sft = HI2SFT(hi);
13447 if (score >= sft->sft_score)
13448 return;
13449 sft->sft_score = score;
13453 * Find the word nr in the soundfold tree.
13455 sfwordnr = soundfold_find(slang, goodword);
13456 if (sfwordnr < 0)
13458 EMSG2(_(e_intern2), "add_sound_suggest()");
13459 return;
13463 * go over the list of good words that produce this soundfold word
13465 nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)(sfwordnr + 1), FALSE);
13466 orgnr = 0;
13467 while (*nrline != NUL)
13469 /* The wordnr was stored in a minimal nr of bytes as an offset to the
13470 * previous wordnr. */
13471 orgnr += bytes2offset(&nrline);
13473 byts = slang->sl_fbyts;
13474 idxs = slang->sl_fidxs;
13476 /* Lookup the word "orgnr" one of the two tries. */
13477 n = 0;
13478 wlen = 0;
13479 wordcount = 0;
13480 for (;;)
13482 i = 1;
13483 if (wordcount == orgnr && byts[n + 1] == NUL)
13484 break; /* found end of word */
13486 if (byts[n + 1] == NUL)
13487 ++wordcount;
13489 /* skip over the NUL bytes */
13490 for ( ; byts[n + i] == NUL; ++i)
13491 if (i > byts[n]) /* safety check */
13493 STRCPY(theword + wlen, "BAD");
13494 goto badword;
13497 /* One of the siblings must have the word. */
13498 for ( ; i < byts[n]; ++i)
13500 wc = idxs[idxs[n + i]]; /* nr of words under this byte */
13501 if (wordcount + wc > orgnr)
13502 break;
13503 wordcount += wc;
13506 theword[wlen++] = byts[n + i];
13507 n = idxs[n + i];
13509 badword:
13510 theword[wlen] = NUL;
13512 /* Go over the possible flags and regions. */
13513 for (; i <= byts[n] && byts[n + i] == NUL; ++i)
13515 char_u cword[MAXWLEN];
13516 char_u *p;
13517 int flags = (int)idxs[n + i];
13519 /* Skip words with the NOSUGGEST flag */
13520 if (flags & WF_NOSUGGEST)
13521 continue;
13523 if (flags & WF_KEEPCAP)
13525 /* Must find the word in the keep-case tree. */
13526 find_keepcap_word(slang, theword, cword);
13527 p = cword;
13529 else
13531 flags |= su->su_badflags;
13532 if ((flags & WF_CAPMASK) != 0)
13534 /* Need to fix case according to "flags". */
13535 make_case_word(theword, cword, flags);
13536 p = cword;
13538 else
13539 p = theword;
13542 /* Add the suggestion. */
13543 if (sps_flags & SPS_DOUBLE)
13545 /* Add the suggestion if the score isn't too bad. */
13546 if (score <= su->su_maxscore)
13547 add_suggestion(su, &su->su_sga, p, su->su_badlen,
13548 score, 0, FALSE, slang, FALSE);
13550 else
13552 /* Add a penalty for words in another region. */
13553 if ((flags & WF_REGION)
13554 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
13555 goodscore = SCORE_REGION;
13556 else
13557 goodscore = 0;
13559 /* Add a small penalty for changing the first letter from
13560 * lower to upper case. Helps for "tath" -> "Kath", which is
13561 * less common thatn "tath" -> "path". Don't do it when the
13562 * letter is the same, that has already been counted. */
13563 gc = PTR2CHAR(p);
13564 if (SPELL_ISUPPER(gc))
13566 bc = PTR2CHAR(su->su_badword);
13567 if (!SPELL_ISUPPER(bc)
13568 && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc))
13569 goodscore += SCORE_ICASE / 2;
13572 /* Compute the score for the good word. This only does letter
13573 * insert/delete/swap/replace. REP items are not considered,
13574 * which may make the score a bit higher.
13575 * Use a limit for the score to make it work faster. Use
13576 * MAXSCORE(), because RESCORE() will change the score.
13577 * If the limit is very high then the iterative method is
13578 * inefficient, using an array is quicker. */
13579 limit = MAXSCORE(su->su_sfmaxscore - goodscore, score);
13580 if (limit > SCORE_LIMITMAX)
13581 goodscore += spell_edit_score(slang, su->su_badword, p);
13582 else
13583 goodscore += spell_edit_score_limit(slang, su->su_badword,
13584 p, limit);
13586 /* When going over the limit don't bother to do the rest. */
13587 if (goodscore < SCORE_MAXMAX)
13589 /* Give a bonus to words seen before. */
13590 goodscore = score_wordcount_adj(slang, goodscore, p, FALSE);
13592 /* Add the suggestion if the score isn't too bad. */
13593 goodscore = RESCORE(goodscore, score);
13594 if (goodscore <= su->su_sfmaxscore)
13595 add_suggestion(su, &su->su_ga, p, su->su_badlen,
13596 goodscore, score, TRUE, slang, TRUE);
13600 /* smsg("word %s (%d): %s (%d)", sftword, sftnr, theword, orgnr); */
13605 * Find word "word" in fold-case tree for "slang" and return the word number.
13607 static int
13608 soundfold_find(slang, word)
13609 slang_T *slang;
13610 char_u *word;
13612 idx_T arridx = 0;
13613 int len;
13614 int wlen = 0;
13615 int c;
13616 char_u *ptr = word;
13617 char_u *byts;
13618 idx_T *idxs;
13619 int wordnr = 0;
13621 byts = slang->sl_sbyts;
13622 idxs = slang->sl_sidxs;
13624 for (;;)
13626 /* First byte is the number of possible bytes. */
13627 len = byts[arridx++];
13629 /* If the first possible byte is a zero the word could end here.
13630 * If the word ends we found the word. If not skip the NUL bytes. */
13631 c = ptr[wlen];
13632 if (byts[arridx] == NUL)
13634 if (c == NUL)
13635 break;
13637 /* Skip over the zeros, there can be several. */
13638 while (len > 0 && byts[arridx] == NUL)
13640 ++arridx;
13641 --len;
13643 if (len == 0)
13644 return -1; /* no children, word should have ended here */
13645 ++wordnr;
13648 /* If the word ends we didn't find it. */
13649 if (c == NUL)
13650 return -1;
13652 /* Perform a binary search in the list of accepted bytes. */
13653 if (c == TAB) /* <Tab> is handled like <Space> */
13654 c = ' ';
13655 while (byts[arridx] < c)
13657 /* The word count is in the first idxs[] entry of the child. */
13658 wordnr += idxs[idxs[arridx]];
13659 ++arridx;
13660 if (--len == 0) /* end of the bytes, didn't find it */
13661 return -1;
13663 if (byts[arridx] != c) /* didn't find the byte */
13664 return -1;
13666 /* Continue at the child (if there is one). */
13667 arridx = idxs[arridx];
13668 ++wlen;
13670 /* One space in the good word may stand for several spaces in the
13671 * checked word. */
13672 if (c == ' ')
13673 while (ptr[wlen] == ' ' || ptr[wlen] == TAB)
13674 ++wlen;
13677 return wordnr;
13681 * Copy "fword" to "cword", fixing case according to "flags".
13683 static void
13684 make_case_word(fword, cword, flags)
13685 char_u *fword;
13686 char_u *cword;
13687 int flags;
13689 if (flags & WF_ALLCAP)
13690 /* Make it all upper-case */
13691 allcap_copy(fword, cword);
13692 else if (flags & WF_ONECAP)
13693 /* Make the first letter upper-case */
13694 onecap_copy(fword, cword, TRUE);
13695 else
13696 /* Use goodword as-is. */
13697 STRCPY(cword, fword);
13701 * Use map string "map" for languages "lp".
13703 static void
13704 set_map_str(lp, map)
13705 slang_T *lp;
13706 char_u *map;
13708 char_u *p;
13709 int headc = 0;
13710 int c;
13711 int i;
13713 if (*map == NUL)
13715 lp->sl_has_map = FALSE;
13716 return;
13718 lp->sl_has_map = TRUE;
13720 /* Init the array and hash tables empty. */
13721 for (i = 0; i < 256; ++i)
13722 lp->sl_map_array[i] = 0;
13723 #ifdef FEAT_MBYTE
13724 hash_init(&lp->sl_map_hash);
13725 #endif
13728 * The similar characters are stored separated with slashes:
13729 * "aaa/bbb/ccc/". Fill sl_map_array[c] with the character before c and
13730 * before the same slash. For characters above 255 sl_map_hash is used.
13732 for (p = map; *p != NUL; )
13734 #ifdef FEAT_MBYTE
13735 c = mb_cptr2char_adv(&p);
13736 #else
13737 c = *p++;
13738 #endif
13739 if (c == '/')
13740 headc = 0;
13741 else
13743 if (headc == 0)
13744 headc = c;
13746 #ifdef FEAT_MBYTE
13747 /* Characters above 255 don't fit in sl_map_array[], put them in
13748 * the hash table. Each entry is the char, a NUL the headchar and
13749 * a NUL. */
13750 if (c >= 256)
13752 int cl = mb_char2len(c);
13753 int headcl = mb_char2len(headc);
13754 char_u *b;
13755 hash_T hash;
13756 hashitem_T *hi;
13758 b = alloc((unsigned)(cl + headcl + 2));
13759 if (b == NULL)
13760 return;
13761 mb_char2bytes(c, b);
13762 b[cl] = NUL;
13763 mb_char2bytes(headc, b + cl + 1);
13764 b[cl + 1 + headcl] = NUL;
13765 hash = hash_hash(b);
13766 hi = hash_lookup(&lp->sl_map_hash, b, hash);
13767 if (HASHITEM_EMPTY(hi))
13768 hash_add_item(&lp->sl_map_hash, hi, b, hash);
13769 else
13771 /* This should have been checked when generating the .spl
13772 * file. */
13773 EMSG(_("E783: duplicate char in MAP entry"));
13774 vim_free(b);
13777 else
13778 #endif
13779 lp->sl_map_array[c] = headc;
13785 * Return TRUE if "c1" and "c2" are similar characters according to the MAP
13786 * lines in the .aff file.
13788 static int
13789 similar_chars(slang, c1, c2)
13790 slang_T *slang;
13791 int c1;
13792 int c2;
13794 int m1, m2;
13795 #ifdef FEAT_MBYTE
13796 char_u buf[MB_MAXBYTES];
13797 hashitem_T *hi;
13799 if (c1 >= 256)
13801 buf[mb_char2bytes(c1, buf)] = 0;
13802 hi = hash_find(&slang->sl_map_hash, buf);
13803 if (HASHITEM_EMPTY(hi))
13804 m1 = 0;
13805 else
13806 m1 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
13808 else
13809 #endif
13810 m1 = slang->sl_map_array[c1];
13811 if (m1 == 0)
13812 return FALSE;
13815 #ifdef FEAT_MBYTE
13816 if (c2 >= 256)
13818 buf[mb_char2bytes(c2, buf)] = 0;
13819 hi = hash_find(&slang->sl_map_hash, buf);
13820 if (HASHITEM_EMPTY(hi))
13821 m2 = 0;
13822 else
13823 m2 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
13825 else
13826 #endif
13827 m2 = slang->sl_map_array[c2];
13829 return m1 == m2;
13833 * Add a suggestion to the list of suggestions.
13834 * For a suggestion that is already in the list the lowest score is remembered.
13836 static void
13837 add_suggestion(su, gap, goodword, badlenarg, score, altscore, had_bonus,
13838 slang, maxsf)
13839 suginfo_T *su;
13840 garray_T *gap; /* either su_ga or su_sga */
13841 char_u *goodword;
13842 int badlenarg; /* len of bad word replaced with "goodword" */
13843 int score;
13844 int altscore;
13845 int had_bonus; /* value for st_had_bonus */
13846 slang_T *slang; /* language for sound folding */
13847 int maxsf; /* su_maxscore applies to soundfold score,
13848 su_sfmaxscore to the total score. */
13850 int goodlen; /* len of goodword changed */
13851 int badlen; /* len of bad word changed */
13852 suggest_T *stp;
13853 suggest_T new_sug;
13854 int i;
13855 char_u *pgood, *pbad;
13857 /* Minimize "badlen" for consistency. Avoids that changing "the the" to
13858 * "thee the" is added next to changing the first "the" the "thee". */
13859 pgood = goodword + STRLEN(goodword);
13860 pbad = su->su_badptr + badlenarg;
13861 for (;;)
13863 goodlen = (int)(pgood - goodword);
13864 badlen = (int)(pbad - su->su_badptr);
13865 if (goodlen <= 0 || badlen <= 0)
13866 break;
13867 mb_ptr_back(goodword, pgood);
13868 mb_ptr_back(su->su_badptr, pbad);
13869 #ifdef FEAT_MBYTE
13870 if (has_mbyte)
13872 if (mb_ptr2char(pgood) != mb_ptr2char(pbad))
13873 break;
13875 else
13876 #endif
13877 if (*pgood != *pbad)
13878 break;
13881 if (badlen == 0 && goodlen == 0)
13882 /* goodword doesn't change anything; may happen for "the the" changing
13883 * the first "the" to itself. */
13884 return;
13886 if (gap->ga_len == 0)
13887 i = -1;
13888 else
13890 /* Check if the word is already there. Also check the length that is
13891 * being replaced "thes," -> "these" is a different suggestion from
13892 * "thes" -> "these". */
13893 stp = &SUG(*gap, 0);
13894 for (i = gap->ga_len; --i >= 0; ++stp)
13895 if (stp->st_wordlen == goodlen
13896 && stp->st_orglen == badlen
13897 && STRNCMP(stp->st_word, goodword, goodlen) == 0)
13900 * Found it. Remember the word with the lowest score.
13902 if (stp->st_slang == NULL)
13903 stp->st_slang = slang;
13905 new_sug.st_score = score;
13906 new_sug.st_altscore = altscore;
13907 new_sug.st_had_bonus = had_bonus;
13909 if (stp->st_had_bonus != had_bonus)
13911 /* Only one of the two had the soundalike score computed.
13912 * Need to do that for the other one now, otherwise the
13913 * scores can't be compared. This happens because
13914 * suggest_try_change() doesn't compute the soundalike
13915 * word to keep it fast, while some special methods set
13916 * the soundalike score to zero. */
13917 if (had_bonus)
13918 rescore_one(su, stp);
13919 else
13921 new_sug.st_word = stp->st_word;
13922 new_sug.st_wordlen = stp->st_wordlen;
13923 new_sug.st_slang = stp->st_slang;
13924 new_sug.st_orglen = badlen;
13925 rescore_one(su, &new_sug);
13929 if (stp->st_score > new_sug.st_score)
13931 stp->st_score = new_sug.st_score;
13932 stp->st_altscore = new_sug.st_altscore;
13933 stp->st_had_bonus = new_sug.st_had_bonus;
13935 break;
13939 if (i < 0 && ga_grow(gap, 1) == OK)
13941 /* Add a suggestion. */
13942 stp = &SUG(*gap, gap->ga_len);
13943 stp->st_word = vim_strnsave(goodword, goodlen);
13944 if (stp->st_word != NULL)
13946 stp->st_wordlen = goodlen;
13947 stp->st_score = score;
13948 stp->st_altscore = altscore;
13949 stp->st_had_bonus = had_bonus;
13950 stp->st_orglen = badlen;
13951 stp->st_slang = slang;
13952 ++gap->ga_len;
13954 /* If we have too many suggestions now, sort the list and keep
13955 * the best suggestions. */
13956 if (gap->ga_len > SUG_MAX_COUNT(su))
13958 if (maxsf)
13959 su->su_sfmaxscore = cleanup_suggestions(gap,
13960 su->su_sfmaxscore, SUG_CLEAN_COUNT(su));
13961 else
13963 i = su->su_maxscore;
13964 su->su_maxscore = cleanup_suggestions(gap,
13965 su->su_maxscore, SUG_CLEAN_COUNT(su));
13973 * Suggestions may in fact be flagged as errors. Esp. for banned words and
13974 * for split words, such as "the the". Remove these from the list here.
13976 static void
13977 check_suggestions(su, gap)
13978 suginfo_T *su;
13979 garray_T *gap; /* either su_ga or su_sga */
13981 suggest_T *stp;
13982 int i;
13983 char_u longword[MAXWLEN + 1];
13984 int len;
13985 hlf_T attr;
13987 stp = &SUG(*gap, 0);
13988 for (i = gap->ga_len - 1; i >= 0; --i)
13990 /* Need to append what follows to check for "the the". */
13991 STRCPY(longword, stp[i].st_word);
13992 len = stp[i].st_wordlen;
13993 vim_strncpy(longword + len, su->su_badptr + stp[i].st_orglen,
13994 MAXWLEN - len);
13995 attr = HLF_COUNT;
13996 (void)spell_check(curwin, longword, &attr, NULL, FALSE);
13997 if (attr != HLF_COUNT)
13999 /* Remove this entry. */
14000 vim_free(stp[i].st_word);
14001 --gap->ga_len;
14002 if (i < gap->ga_len)
14003 mch_memmove(stp + i, stp + i + 1,
14004 sizeof(suggest_T) * (gap->ga_len - i));
14011 * Add a word to be banned.
14013 static void
14014 add_banned(su, word)
14015 suginfo_T *su;
14016 char_u *word;
14018 char_u *s;
14019 hash_T hash;
14020 hashitem_T *hi;
14022 hash = hash_hash(word);
14023 hi = hash_lookup(&su->su_banned, word, hash);
14024 if (HASHITEM_EMPTY(hi))
14026 s = vim_strsave(word);
14027 if (s != NULL)
14028 hash_add_item(&su->su_banned, hi, s, hash);
14033 * Recompute the score for all suggestions if sound-folding is possible. This
14034 * is slow, thus only done for the final results.
14036 static void
14037 rescore_suggestions(su)
14038 suginfo_T *su;
14040 int i;
14042 if (su->su_sallang != NULL)
14043 for (i = 0; i < su->su_ga.ga_len; ++i)
14044 rescore_one(su, &SUG(su->su_ga, i));
14048 * Recompute the score for one suggestion if sound-folding is possible.
14050 static void
14051 rescore_one(su, stp)
14052 suginfo_T *su;
14053 suggest_T *stp;
14055 slang_T *slang = stp->st_slang;
14056 char_u sal_badword[MAXWLEN];
14057 char_u *p;
14059 /* Only rescore suggestions that have no sal score yet and do have a
14060 * language. */
14061 if (slang != NULL && slang->sl_sal.ga_len > 0 && !stp->st_had_bonus)
14063 if (slang == su->su_sallang)
14064 p = su->su_sal_badword;
14065 else
14067 spell_soundfold(slang, su->su_fbadword, TRUE, sal_badword);
14068 p = sal_badword;
14071 stp->st_altscore = stp_sal_score(stp, su, slang, p);
14072 if (stp->st_altscore == SCORE_MAXMAX)
14073 stp->st_altscore = SCORE_BIG;
14074 stp->st_score = RESCORE(stp->st_score, stp->st_altscore);
14075 stp->st_had_bonus = TRUE;
14079 static int
14080 #ifdef __BORLANDC__
14081 _RTLENTRYF
14082 #endif
14083 sug_compare __ARGS((const void *s1, const void *s2));
14086 * Function given to qsort() to sort the suggestions on st_score.
14087 * First on "st_score", then "st_altscore" then alphabetically.
14089 static int
14090 #ifdef __BORLANDC__
14091 _RTLENTRYF
14092 #endif
14093 sug_compare(s1, s2)
14094 const void *s1;
14095 const void *s2;
14097 suggest_T *p1 = (suggest_T *)s1;
14098 suggest_T *p2 = (suggest_T *)s2;
14099 int n = p1->st_score - p2->st_score;
14101 if (n == 0)
14103 n = p1->st_altscore - p2->st_altscore;
14104 if (n == 0)
14105 n = STRICMP(p1->st_word, p2->st_word);
14107 return n;
14111 * Cleanup the suggestions:
14112 * - Sort on score.
14113 * - Remove words that won't be displayed.
14114 * Returns the maximum score in the list or "maxscore" unmodified.
14116 static int
14117 cleanup_suggestions(gap, maxscore, keep)
14118 garray_T *gap;
14119 int maxscore;
14120 int keep; /* nr of suggestions to keep */
14122 suggest_T *stp = &SUG(*gap, 0);
14123 int i;
14125 /* Sort the list. */
14126 qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T), sug_compare);
14128 /* Truncate the list to the number of suggestions that will be displayed. */
14129 if (gap->ga_len > keep)
14131 for (i = keep; i < gap->ga_len; ++i)
14132 vim_free(stp[i].st_word);
14133 gap->ga_len = keep;
14134 return stp[keep - 1].st_score;
14136 return maxscore;
14139 #if defined(FEAT_EVAL) || defined(PROTO)
14141 * Soundfold a string, for soundfold().
14142 * Result is in allocated memory, NULL for an error.
14144 char_u *
14145 eval_soundfold(word)
14146 char_u *word;
14148 langp_T *lp;
14149 char_u sound[MAXWLEN];
14150 int lpi;
14152 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
14153 /* Use the sound-folding of the first language that supports it. */
14154 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
14156 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
14157 if (lp->lp_slang->sl_sal.ga_len > 0)
14159 /* soundfold the word */
14160 spell_soundfold(lp->lp_slang, word, FALSE, sound);
14161 return vim_strsave(sound);
14165 /* No language with sound folding, return word as-is. */
14166 return vim_strsave(word);
14168 #endif
14171 * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]".
14173 * There are many ways to turn a word into a sound-a-like representation. The
14174 * oldest is Soundex (1918!). A nice overview can be found in "Approximate
14175 * swedish name matching - survey and test of different algorithms" by Klas
14176 * Erikson.
14178 * We support two methods:
14179 * 1. SOFOFROM/SOFOTO do a simple character mapping.
14180 * 2. SAL items define a more advanced sound-folding (and much slower).
14182 static void
14183 spell_soundfold(slang, inword, folded, res)
14184 slang_T *slang;
14185 char_u *inword;
14186 int folded; /* "inword" is already case-folded */
14187 char_u *res;
14189 char_u fword[MAXWLEN];
14190 char_u *word;
14192 if (slang->sl_sofo)
14193 /* SOFOFROM and SOFOTO used */
14194 spell_soundfold_sofo(slang, inword, res);
14195 else
14197 /* SAL items used. Requires the word to be case-folded. */
14198 if (folded)
14199 word = inword;
14200 else
14202 (void)spell_casefold(inword, (int)STRLEN(inword), fword, MAXWLEN);
14203 word = fword;
14206 #ifdef FEAT_MBYTE
14207 if (has_mbyte)
14208 spell_soundfold_wsal(slang, word, res);
14209 else
14210 #endif
14211 spell_soundfold_sal(slang, word, res);
14216 * Perform sound folding of "inword" into "res" according to SOFOFROM and
14217 * SOFOTO lines.
14219 static void
14220 spell_soundfold_sofo(slang, inword, res)
14221 slang_T *slang;
14222 char_u *inword;
14223 char_u *res;
14225 char_u *s;
14226 int ri = 0;
14227 int c;
14229 #ifdef FEAT_MBYTE
14230 if (has_mbyte)
14232 int prevc = 0;
14233 int *ip;
14235 /* The sl_sal_first[] table contains the translation for chars up to
14236 * 255, sl_sal the rest. */
14237 for (s = inword; *s != NUL; )
14239 c = mb_cptr2char_adv(&s);
14240 if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c))
14241 c = ' ';
14242 else if (c < 256)
14243 c = slang->sl_sal_first[c];
14244 else
14246 ip = ((int **)slang->sl_sal.ga_data)[c & 0xff];
14247 if (ip == NULL) /* empty list, can't match */
14248 c = NUL;
14249 else
14250 for (;;) /* find "c" in the list */
14252 if (*ip == 0) /* not found */
14254 c = NUL;
14255 break;
14257 if (*ip == c) /* match! */
14259 c = ip[1];
14260 break;
14262 ip += 2;
14266 if (c != NUL && c != prevc)
14268 ri += mb_char2bytes(c, res + ri);
14269 if (ri + MB_MAXBYTES > MAXWLEN)
14270 break;
14271 prevc = c;
14275 else
14276 #endif
14278 /* The sl_sal_first[] table contains the translation. */
14279 for (s = inword; (c = *s) != NUL; ++s)
14281 if (vim_iswhite(c))
14282 c = ' ';
14283 else
14284 c = slang->sl_sal_first[c];
14285 if (c != NUL && (ri == 0 || res[ri - 1] != c))
14286 res[ri++] = c;
14290 res[ri] = NUL;
14293 static void
14294 spell_soundfold_sal(slang, inword, res)
14295 slang_T *slang;
14296 char_u *inword;
14297 char_u *res;
14299 salitem_T *smp;
14300 char_u word[MAXWLEN];
14301 char_u *s = inword;
14302 char_u *t;
14303 char_u *pf;
14304 int i, j, z;
14305 int reslen;
14306 int n, k = 0;
14307 int z0;
14308 int k0;
14309 int n0;
14310 int c;
14311 int pri;
14312 int p0 = -333;
14313 int c0;
14315 /* Remove accents, if wanted. We actually remove all non-word characters.
14316 * But keep white space. We need a copy, the word may be changed here. */
14317 if (slang->sl_rem_accents)
14319 t = word;
14320 while (*s != NUL)
14322 if (vim_iswhite(*s))
14324 *t++ = ' ';
14325 s = skipwhite(s);
14327 else
14329 if (spell_iswordp_nmw(s))
14330 *t++ = *s;
14331 ++s;
14334 *t = NUL;
14336 else
14337 STRCPY(word, s);
14339 smp = (salitem_T *)slang->sl_sal.ga_data;
14342 * This comes from Aspell phonet.cpp. Converted from C++ to C.
14343 * Changed to keep spaces.
14345 i = reslen = z = 0;
14346 while ((c = word[i]) != NUL)
14348 /* Start with the first rule that has the character in the word. */
14349 n = slang->sl_sal_first[c];
14350 z0 = 0;
14352 if (n >= 0)
14354 /* check all rules for the same letter */
14355 for (; (s = smp[n].sm_lead)[0] == c; ++n)
14357 /* Quickly skip entries that don't match the word. Most
14358 * entries are less then three chars, optimize for that. */
14359 k = smp[n].sm_leadlen;
14360 if (k > 1)
14362 if (word[i + 1] != s[1])
14363 continue;
14364 if (k > 2)
14366 for (j = 2; j < k; ++j)
14367 if (word[i + j] != s[j])
14368 break;
14369 if (j < k)
14370 continue;
14374 if ((pf = smp[n].sm_oneof) != NULL)
14376 /* Check for match with one of the chars in "sm_oneof". */
14377 while (*pf != NUL && *pf != word[i + k])
14378 ++pf;
14379 if (*pf == NUL)
14380 continue;
14381 ++k;
14383 s = smp[n].sm_rules;
14384 pri = 5; /* default priority */
14386 p0 = *s;
14387 k0 = k;
14388 while (*s == '-' && k > 1)
14390 k--;
14391 s++;
14393 if (*s == '<')
14394 s++;
14395 if (VIM_ISDIGIT(*s))
14397 /* determine priority */
14398 pri = *s - '0';
14399 s++;
14401 if (*s == '^' && *(s + 1) == '^')
14402 s++;
14404 if (*s == NUL
14405 || (*s == '^'
14406 && (i == 0 || !(word[i - 1] == ' '
14407 || spell_iswordp(word + i - 1, curbuf)))
14408 && (*(s + 1) != '$'
14409 || (!spell_iswordp(word + i + k0, curbuf))))
14410 || (*s == '$' && i > 0
14411 && spell_iswordp(word + i - 1, curbuf)
14412 && (!spell_iswordp(word + i + k0, curbuf))))
14414 /* search for followup rules, if: */
14415 /* followup and k > 1 and NO '-' in searchstring */
14416 c0 = word[i + k - 1];
14417 n0 = slang->sl_sal_first[c0];
14419 if (slang->sl_followup && k > 1 && n0 >= 0
14420 && p0 != '-' && word[i + k] != NUL)
14422 /* test follow-up rule for "word[i + k]" */
14423 for ( ; (s = smp[n0].sm_lead)[0] == c0; ++n0)
14425 /* Quickly skip entries that don't match the word.
14426 * */
14427 k0 = smp[n0].sm_leadlen;
14428 if (k0 > 1)
14430 if (word[i + k] != s[1])
14431 continue;
14432 if (k0 > 2)
14434 pf = word + i + k + 1;
14435 for (j = 2; j < k0; ++j)
14436 if (*pf++ != s[j])
14437 break;
14438 if (j < k0)
14439 continue;
14442 k0 += k - 1;
14444 if ((pf = smp[n0].sm_oneof) != NULL)
14446 /* Check for match with one of the chars in
14447 * "sm_oneof". */
14448 while (*pf != NUL && *pf != word[i + k0])
14449 ++pf;
14450 if (*pf == NUL)
14451 continue;
14452 ++k0;
14455 p0 = 5;
14456 s = smp[n0].sm_rules;
14457 while (*s == '-')
14459 /* "k0" gets NOT reduced because
14460 * "if (k0 == k)" */
14461 s++;
14463 if (*s == '<')
14464 s++;
14465 if (VIM_ISDIGIT(*s))
14467 p0 = *s - '0';
14468 s++;
14471 if (*s == NUL
14472 /* *s == '^' cuts */
14473 || (*s == '$'
14474 && !spell_iswordp(word + i + k0,
14475 curbuf)))
14477 if (k0 == k)
14478 /* this is just a piece of the string */
14479 continue;
14481 if (p0 < pri)
14482 /* priority too low */
14483 continue;
14484 /* rule fits; stop search */
14485 break;
14489 if (p0 >= pri && smp[n0].sm_lead[0] == c0)
14490 continue;
14493 /* replace string */
14494 s = smp[n].sm_to;
14495 if (s == NULL)
14496 s = (char_u *)"";
14497 pf = smp[n].sm_rules;
14498 p0 = (vim_strchr(pf, '<') != NULL) ? 1 : 0;
14499 if (p0 == 1 && z == 0)
14501 /* rule with '<' is used */
14502 if (reslen > 0 && *s != NUL && (res[reslen - 1] == c
14503 || res[reslen - 1] == *s))
14504 reslen--;
14505 z0 = 1;
14506 z = 1;
14507 k0 = 0;
14508 while (*s != NUL && word[i + k0] != NUL)
14510 word[i + k0] = *s;
14511 k0++;
14512 s++;
14514 if (k > k0)
14515 STRMOVE(word + i + k0, word + i + k);
14517 /* new "actual letter" */
14518 c = word[i];
14520 else
14522 /* no '<' rule used */
14523 i += k - 1;
14524 z = 0;
14525 while (*s != NUL && s[1] != NUL && reslen < MAXWLEN)
14527 if (reslen == 0 || res[reslen - 1] != *s)
14528 res[reslen++] = *s;
14529 s++;
14531 /* new "actual letter" */
14532 c = *s;
14533 if (strstr((char *)pf, "^^") != NULL)
14535 if (c != NUL)
14536 res[reslen++] = c;
14537 STRMOVE(word, word + i + 1);
14538 i = 0;
14539 z0 = 1;
14542 break;
14546 else if (vim_iswhite(c))
14548 c = ' ';
14549 k = 1;
14552 if (z0 == 0)
14554 if (k && !p0 && reslen < MAXWLEN && c != NUL
14555 && (!slang->sl_collapse || reslen == 0
14556 || res[reslen - 1] != c))
14557 /* condense only double letters */
14558 res[reslen++] = c;
14560 i++;
14561 z = 0;
14562 k = 0;
14566 res[reslen] = NUL;
14569 #ifdef FEAT_MBYTE
14571 * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]".
14572 * Multi-byte version of spell_soundfold().
14574 static void
14575 spell_soundfold_wsal(slang, inword, res)
14576 slang_T *slang;
14577 char_u *inword;
14578 char_u *res;
14580 salitem_T *smp = (salitem_T *)slang->sl_sal.ga_data;
14581 int word[MAXWLEN];
14582 int wres[MAXWLEN];
14583 int l;
14584 char_u *s;
14585 int *ws;
14586 char_u *t;
14587 int *pf;
14588 int i, j, z;
14589 int reslen;
14590 int n, k = 0;
14591 int z0;
14592 int k0;
14593 int n0;
14594 int c;
14595 int pri;
14596 int p0 = -333;
14597 int c0;
14598 int did_white = FALSE;
14601 * Convert the multi-byte string to a wide-character string.
14602 * Remove accents, if wanted. We actually remove all non-word characters.
14603 * But keep white space.
14605 n = 0;
14606 for (s = inword; *s != NUL; )
14608 t = s;
14609 c = mb_cptr2char_adv(&s);
14610 if (slang->sl_rem_accents)
14612 if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c))
14614 if (did_white)
14615 continue;
14616 c = ' ';
14617 did_white = TRUE;
14619 else
14621 did_white = FALSE;
14622 if (!spell_iswordp_nmw(t))
14623 continue;
14626 word[n++] = c;
14628 word[n] = NUL;
14631 * This comes from Aspell phonet.cpp.
14632 * Converted from C++ to C. Added support for multi-byte chars.
14633 * Changed to keep spaces.
14635 i = reslen = z = 0;
14636 while ((c = word[i]) != NUL)
14638 /* Start with the first rule that has the character in the word. */
14639 n = slang->sl_sal_first[c & 0xff];
14640 z0 = 0;
14642 if (n >= 0)
14644 /* check all rules for the same index byte */
14645 for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff); ++n)
14647 /* Quickly skip entries that don't match the word. Most
14648 * entries are less then three chars, optimize for that. */
14649 if (c != ws[0])
14650 continue;
14651 k = smp[n].sm_leadlen;
14652 if (k > 1)
14654 if (word[i + 1] != ws[1])
14655 continue;
14656 if (k > 2)
14658 for (j = 2; j < k; ++j)
14659 if (word[i + j] != ws[j])
14660 break;
14661 if (j < k)
14662 continue;
14666 if ((pf = smp[n].sm_oneof_w) != NULL)
14668 /* Check for match with one of the chars in "sm_oneof". */
14669 while (*pf != NUL && *pf != word[i + k])
14670 ++pf;
14671 if (*pf == NUL)
14672 continue;
14673 ++k;
14675 s = smp[n].sm_rules;
14676 pri = 5; /* default priority */
14678 p0 = *s;
14679 k0 = k;
14680 while (*s == '-' && k > 1)
14682 k--;
14683 s++;
14685 if (*s == '<')
14686 s++;
14687 if (VIM_ISDIGIT(*s))
14689 /* determine priority */
14690 pri = *s - '0';
14691 s++;
14693 if (*s == '^' && *(s + 1) == '^')
14694 s++;
14696 if (*s == NUL
14697 || (*s == '^'
14698 && (i == 0 || !(word[i - 1] == ' '
14699 || spell_iswordp_w(word + i - 1, curbuf)))
14700 && (*(s + 1) != '$'
14701 || (!spell_iswordp_w(word + i + k0, curbuf))))
14702 || (*s == '$' && i > 0
14703 && spell_iswordp_w(word + i - 1, curbuf)
14704 && (!spell_iswordp_w(word + i + k0, curbuf))))
14706 /* search for followup rules, if: */
14707 /* followup and k > 1 and NO '-' in searchstring */
14708 c0 = word[i + k - 1];
14709 n0 = slang->sl_sal_first[c0 & 0xff];
14711 if (slang->sl_followup && k > 1 && n0 >= 0
14712 && p0 != '-' && word[i + k] != NUL)
14714 /* Test follow-up rule for "word[i + k]"; loop over
14715 * all entries with the same index byte. */
14716 for ( ; ((ws = smp[n0].sm_lead_w)[0] & 0xff)
14717 == (c0 & 0xff); ++n0)
14719 /* Quickly skip entries that don't match the word.
14721 if (c0 != ws[0])
14722 continue;
14723 k0 = smp[n0].sm_leadlen;
14724 if (k0 > 1)
14726 if (word[i + k] != ws[1])
14727 continue;
14728 if (k0 > 2)
14730 pf = word + i + k + 1;
14731 for (j = 2; j < k0; ++j)
14732 if (*pf++ != ws[j])
14733 break;
14734 if (j < k0)
14735 continue;
14738 k0 += k - 1;
14740 if ((pf = smp[n0].sm_oneof_w) != NULL)
14742 /* Check for match with one of the chars in
14743 * "sm_oneof". */
14744 while (*pf != NUL && *pf != word[i + k0])
14745 ++pf;
14746 if (*pf == NUL)
14747 continue;
14748 ++k0;
14751 p0 = 5;
14752 s = smp[n0].sm_rules;
14753 while (*s == '-')
14755 /* "k0" gets NOT reduced because
14756 * "if (k0 == k)" */
14757 s++;
14759 if (*s == '<')
14760 s++;
14761 if (VIM_ISDIGIT(*s))
14763 p0 = *s - '0';
14764 s++;
14767 if (*s == NUL
14768 /* *s == '^' cuts */
14769 || (*s == '$'
14770 && !spell_iswordp_w(word + i + k0,
14771 curbuf)))
14773 if (k0 == k)
14774 /* this is just a piece of the string */
14775 continue;
14777 if (p0 < pri)
14778 /* priority too low */
14779 continue;
14780 /* rule fits; stop search */
14781 break;
14785 if (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff)
14786 == (c0 & 0xff))
14787 continue;
14790 /* replace string */
14791 ws = smp[n].sm_to_w;
14792 s = smp[n].sm_rules;
14793 p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0;
14794 if (p0 == 1 && z == 0)
14796 /* rule with '<' is used */
14797 if (reslen > 0 && ws != NULL && *ws != NUL
14798 && (wres[reslen - 1] == c
14799 || wres[reslen - 1] == *ws))
14800 reslen--;
14801 z0 = 1;
14802 z = 1;
14803 k0 = 0;
14804 if (ws != NULL)
14805 while (*ws != NUL && word[i + k0] != NUL)
14807 word[i + k0] = *ws;
14808 k0++;
14809 ws++;
14811 if (k > k0)
14812 mch_memmove(word + i + k0, word + i + k,
14813 sizeof(int) * (STRLEN(word + i + k) + 1));
14815 /* new "actual letter" */
14816 c = word[i];
14818 else
14820 /* no '<' rule used */
14821 i += k - 1;
14822 z = 0;
14823 if (ws != NULL)
14824 while (*ws != NUL && ws[1] != NUL
14825 && reslen < MAXWLEN)
14827 if (reslen == 0 || wres[reslen - 1] != *ws)
14828 wres[reslen++] = *ws;
14829 ws++;
14831 /* new "actual letter" */
14832 if (ws == NULL)
14833 c = NUL;
14834 else
14835 c = *ws;
14836 if (strstr((char *)s, "^^") != NULL)
14838 if (c != NUL)
14839 wres[reslen++] = c;
14840 mch_memmove(word, word + i + 1,
14841 sizeof(int) * (STRLEN(word + i + 1) + 1));
14842 i = 0;
14843 z0 = 1;
14846 break;
14850 else if (vim_iswhite(c))
14852 c = ' ';
14853 k = 1;
14856 if (z0 == 0)
14858 if (k && !p0 && reslen < MAXWLEN && c != NUL
14859 && (!slang->sl_collapse || reslen == 0
14860 || wres[reslen - 1] != c))
14861 /* condense only double letters */
14862 wres[reslen++] = c;
14864 i++;
14865 z = 0;
14866 k = 0;
14870 /* Convert wide characters in "wres" to a multi-byte string in "res". */
14871 l = 0;
14872 for (n = 0; n < reslen; ++n)
14874 l += mb_char2bytes(wres[n], res + l);
14875 if (l + MB_MAXBYTES > MAXWLEN)
14876 break;
14878 res[l] = NUL;
14880 #endif
14883 * Compute a score for two sound-a-like words.
14884 * This permits up to two inserts/deletes/swaps/etc. to keep things fast.
14885 * Instead of a generic loop we write out the code. That keeps it fast by
14886 * avoiding checks that will not be possible.
14888 static int
14889 soundalike_score(goodstart, badstart)
14890 char_u *goodstart; /* sound-folded good word */
14891 char_u *badstart; /* sound-folded bad word */
14893 char_u *goodsound = goodstart;
14894 char_u *badsound = badstart;
14895 int goodlen;
14896 int badlen;
14897 int n;
14898 char_u *pl, *ps;
14899 char_u *pl2, *ps2;
14900 int score = 0;
14902 /* adding/inserting "*" at the start (word starts with vowel) shouldn't be
14903 * counted so much, vowels halfway the word aren't counted at all. */
14904 if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound)
14906 if (badsound[1] == goodsound[1]
14907 || (badsound[1] != NUL
14908 && goodsound[1] != NUL
14909 && badsound[2] == goodsound[2]))
14911 /* handle like a substitute */
14913 else
14915 score = 2 * SCORE_DEL / 3;
14916 if (*badsound == '*')
14917 ++badsound;
14918 else
14919 ++goodsound;
14923 goodlen = (int)STRLEN(goodsound);
14924 badlen = (int)STRLEN(badsound);
14926 /* Return quickly if the lengths are too different to be fixed by two
14927 * changes. */
14928 n = goodlen - badlen;
14929 if (n < -2 || n > 2)
14930 return SCORE_MAXMAX;
14932 if (n > 0)
14934 pl = goodsound; /* goodsound is longest */
14935 ps = badsound;
14937 else
14939 pl = badsound; /* badsound is longest */
14940 ps = goodsound;
14943 /* Skip over the identical part. */
14944 while (*pl == *ps && *pl != NUL)
14946 ++pl;
14947 ++ps;
14950 switch (n)
14952 case -2:
14953 case 2:
14955 * Must delete two characters from "pl".
14957 ++pl; /* first delete */
14958 while (*pl == *ps)
14960 ++pl;
14961 ++ps;
14963 /* strings must be equal after second delete */
14964 if (STRCMP(pl + 1, ps) == 0)
14965 return score + SCORE_DEL * 2;
14967 /* Failed to compare. */
14968 break;
14970 case -1:
14971 case 1:
14973 * Minimal one delete from "pl" required.
14976 /* 1: delete */
14977 pl2 = pl + 1;
14978 ps2 = ps;
14979 while (*pl2 == *ps2)
14981 if (*pl2 == NUL) /* reached the end */
14982 return score + SCORE_DEL;
14983 ++pl2;
14984 ++ps2;
14987 /* 2: delete then swap, then rest must be equal */
14988 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
14989 && STRCMP(pl2 + 2, ps2 + 2) == 0)
14990 return score + SCORE_DEL + SCORE_SWAP;
14992 /* 3: delete then substitute, then the rest must be equal */
14993 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
14994 return score + SCORE_DEL + SCORE_SUBST;
14996 /* 4: first swap then delete */
14997 if (pl[0] == ps[1] && pl[1] == ps[0])
14999 pl2 = pl + 2; /* swap, skip two chars */
15000 ps2 = ps + 2;
15001 while (*pl2 == *ps2)
15003 ++pl2;
15004 ++ps2;
15006 /* delete a char and then strings must be equal */
15007 if (STRCMP(pl2 + 1, ps2) == 0)
15008 return score + SCORE_SWAP + SCORE_DEL;
15011 /* 5: first substitute then delete */
15012 pl2 = pl + 1; /* substitute, skip one char */
15013 ps2 = ps + 1;
15014 while (*pl2 == *ps2)
15016 ++pl2;
15017 ++ps2;
15019 /* delete a char and then strings must be equal */
15020 if (STRCMP(pl2 + 1, ps2) == 0)
15021 return score + SCORE_SUBST + SCORE_DEL;
15023 /* Failed to compare. */
15024 break;
15026 case 0:
15028 * Lengths are equal, thus changes must result in same length: An
15029 * insert is only possible in combination with a delete.
15030 * 1: check if for identical strings
15032 if (*pl == NUL)
15033 return score;
15035 /* 2: swap */
15036 if (pl[0] == ps[1] && pl[1] == ps[0])
15038 pl2 = pl + 2; /* swap, skip two chars */
15039 ps2 = ps + 2;
15040 while (*pl2 == *ps2)
15042 if (*pl2 == NUL) /* reached the end */
15043 return score + SCORE_SWAP;
15044 ++pl2;
15045 ++ps2;
15047 /* 3: swap and swap again */
15048 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
15049 && STRCMP(pl2 + 2, ps2 + 2) == 0)
15050 return score + SCORE_SWAP + SCORE_SWAP;
15052 /* 4: swap and substitute */
15053 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
15054 return score + SCORE_SWAP + SCORE_SUBST;
15057 /* 5: substitute */
15058 pl2 = pl + 1;
15059 ps2 = ps + 1;
15060 while (*pl2 == *ps2)
15062 if (*pl2 == NUL) /* reached the end */
15063 return score + SCORE_SUBST;
15064 ++pl2;
15065 ++ps2;
15068 /* 6: substitute and swap */
15069 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
15070 && STRCMP(pl2 + 2, ps2 + 2) == 0)
15071 return score + SCORE_SUBST + SCORE_SWAP;
15073 /* 7: substitute and substitute */
15074 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
15075 return score + SCORE_SUBST + SCORE_SUBST;
15077 /* 8: insert then delete */
15078 pl2 = pl;
15079 ps2 = ps + 1;
15080 while (*pl2 == *ps2)
15082 ++pl2;
15083 ++ps2;
15085 if (STRCMP(pl2 + 1, ps2) == 0)
15086 return score + SCORE_INS + SCORE_DEL;
15088 /* 9: delete then insert */
15089 pl2 = pl + 1;
15090 ps2 = ps;
15091 while (*pl2 == *ps2)
15093 ++pl2;
15094 ++ps2;
15096 if (STRCMP(pl2, ps2 + 1) == 0)
15097 return score + SCORE_INS + SCORE_DEL;
15099 /* Failed to compare. */
15100 break;
15103 return SCORE_MAXMAX;
15107 * Compute the "edit distance" to turn "badword" into "goodword". The less
15108 * deletes/inserts/substitutes/swaps are required the lower the score.
15110 * The algorithm is described by Du and Chang, 1992.
15111 * The implementation of the algorithm comes from Aspell editdist.cpp,
15112 * edit_distance(). It has been converted from C++ to C and modified to
15113 * support multi-byte characters.
15115 static int
15116 spell_edit_score(slang, badword, goodword)
15117 slang_T *slang;
15118 char_u *badword;
15119 char_u *goodword;
15121 int *cnt;
15122 int badlen, goodlen; /* lengths including NUL */
15123 int j, i;
15124 int t;
15125 int bc, gc;
15126 int pbc, pgc;
15127 #ifdef FEAT_MBYTE
15128 char_u *p;
15129 int wbadword[MAXWLEN];
15130 int wgoodword[MAXWLEN];
15132 if (has_mbyte)
15134 /* Get the characters from the multi-byte strings and put them in an
15135 * int array for easy access. */
15136 for (p = badword, badlen = 0; *p != NUL; )
15137 wbadword[badlen++] = mb_cptr2char_adv(&p);
15138 wbadword[badlen++] = 0;
15139 for (p = goodword, goodlen = 0; *p != NUL; )
15140 wgoodword[goodlen++] = mb_cptr2char_adv(&p);
15141 wgoodword[goodlen++] = 0;
15143 else
15144 #endif
15146 badlen = (int)STRLEN(badword) + 1;
15147 goodlen = (int)STRLEN(goodword) + 1;
15150 /* We use "cnt" as an array: CNT(badword_idx, goodword_idx). */
15151 #define CNT(a, b) cnt[(a) + (b) * (badlen + 1)]
15152 cnt = (int *)lalloc((long_u)(sizeof(int) * (badlen + 1) * (goodlen + 1)),
15153 TRUE);
15154 if (cnt == NULL)
15155 return 0; /* out of memory */
15157 CNT(0, 0) = 0;
15158 for (j = 1; j <= goodlen; ++j)
15159 CNT(0, j) = CNT(0, j - 1) + SCORE_INS;
15161 for (i = 1; i <= badlen; ++i)
15163 CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL;
15164 for (j = 1; j <= goodlen; ++j)
15166 #ifdef FEAT_MBYTE
15167 if (has_mbyte)
15169 bc = wbadword[i - 1];
15170 gc = wgoodword[j - 1];
15172 else
15173 #endif
15175 bc = badword[i - 1];
15176 gc = goodword[j - 1];
15178 if (bc == gc)
15179 CNT(i, j) = CNT(i - 1, j - 1);
15180 else
15182 /* Use a better score when there is only a case difference. */
15183 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15184 CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1);
15185 else
15187 /* For a similar character use SCORE_SIMILAR. */
15188 if (slang != NULL
15189 && slang->sl_has_map
15190 && similar_chars(slang, gc, bc))
15191 CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1);
15192 else
15193 CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1);
15196 if (i > 1 && j > 1)
15198 #ifdef FEAT_MBYTE
15199 if (has_mbyte)
15201 pbc = wbadword[i - 2];
15202 pgc = wgoodword[j - 2];
15204 else
15205 #endif
15207 pbc = badword[i - 2];
15208 pgc = goodword[j - 2];
15210 if (bc == pgc && pbc == gc)
15212 t = SCORE_SWAP + CNT(i - 2, j - 2);
15213 if (t < CNT(i, j))
15214 CNT(i, j) = t;
15217 t = SCORE_DEL + CNT(i - 1, j);
15218 if (t < CNT(i, j))
15219 CNT(i, j) = t;
15220 t = SCORE_INS + CNT(i, j - 1);
15221 if (t < CNT(i, j))
15222 CNT(i, j) = t;
15227 i = CNT(badlen - 1, goodlen - 1);
15228 vim_free(cnt);
15229 return i;
15232 typedef struct
15234 int badi;
15235 int goodi;
15236 int score;
15237 } limitscore_T;
15240 * Like spell_edit_score(), but with a limit on the score to make it faster.
15241 * May return SCORE_MAXMAX when the score is higher than "limit".
15243 * This uses a stack for the edits still to be tried.
15244 * The idea comes from Aspell leditdist.cpp. Rewritten in C and added support
15245 * for multi-byte characters.
15247 static int
15248 spell_edit_score_limit(slang, badword, goodword, limit)
15249 slang_T *slang;
15250 char_u *badword;
15251 char_u *goodword;
15252 int limit;
15254 limitscore_T stack[10]; /* allow for over 3 * 2 edits */
15255 int stackidx;
15256 int bi, gi;
15257 int bi2, gi2;
15258 int bc, gc;
15259 int score;
15260 int score_off;
15261 int minscore;
15262 int round;
15264 #ifdef FEAT_MBYTE
15265 /* Multi-byte characters require a bit more work, use a different function
15266 * to avoid testing "has_mbyte" quite often. */
15267 if (has_mbyte)
15268 return spell_edit_score_limit_w(slang, badword, goodword, limit);
15269 #endif
15272 * The idea is to go from start to end over the words. So long as
15273 * characters are equal just continue, this always gives the lowest score.
15274 * When there is a difference try several alternatives. Each alternative
15275 * increases "score" for the edit distance. Some of the alternatives are
15276 * pushed unto a stack and tried later, some are tried right away. At the
15277 * end of the word the score for one alternative is known. The lowest
15278 * possible score is stored in "minscore".
15280 stackidx = 0;
15281 bi = 0;
15282 gi = 0;
15283 score = 0;
15284 minscore = limit + 1;
15286 for (;;)
15288 /* Skip over an equal part, score remains the same. */
15289 for (;;)
15291 bc = badword[bi];
15292 gc = goodword[gi];
15293 if (bc != gc) /* stop at a char that's different */
15294 break;
15295 if (bc == NUL) /* both words end */
15297 if (score < minscore)
15298 minscore = score;
15299 goto pop; /* do next alternative */
15301 ++bi;
15302 ++gi;
15305 if (gc == NUL) /* goodword ends, delete badword chars */
15309 if ((score += SCORE_DEL) >= minscore)
15310 goto pop; /* do next alternative */
15311 } while (badword[++bi] != NUL);
15312 minscore = score;
15314 else if (bc == NUL) /* badword ends, insert badword chars */
15318 if ((score += SCORE_INS) >= minscore)
15319 goto pop; /* do next alternative */
15320 } while (goodword[++gi] != NUL);
15321 minscore = score;
15323 else /* both words continue */
15325 /* If not close to the limit, perform a change. Only try changes
15326 * that may lead to a lower score than "minscore".
15327 * round 0: try deleting a char from badword
15328 * round 1: try inserting a char in badword */
15329 for (round = 0; round <= 1; ++round)
15331 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
15332 if (score_off < minscore)
15334 if (score_off + SCORE_EDIT_MIN >= minscore)
15336 /* Near the limit, rest of the words must match. We
15337 * can check that right now, no need to push an item
15338 * onto the stack. */
15339 bi2 = bi + 1 - round;
15340 gi2 = gi + round;
15341 while (goodword[gi2] == badword[bi2])
15343 if (goodword[gi2] == NUL)
15345 minscore = score_off;
15346 break;
15348 ++bi2;
15349 ++gi2;
15352 else
15354 /* try deleting/inserting a character later */
15355 stack[stackidx].badi = bi + 1 - round;
15356 stack[stackidx].goodi = gi + round;
15357 stack[stackidx].score = score_off;
15358 ++stackidx;
15363 if (score + SCORE_SWAP < minscore)
15365 /* If swapping two characters makes a match then the
15366 * substitution is more expensive, thus there is no need to
15367 * try both. */
15368 if (gc == badword[bi + 1] && bc == goodword[gi + 1])
15370 /* Swap two characters, that is: skip them. */
15371 gi += 2;
15372 bi += 2;
15373 score += SCORE_SWAP;
15374 continue;
15378 /* Substitute one character for another which is the same
15379 * thing as deleting a character from both goodword and badword.
15380 * Use a better score when there is only a case difference. */
15381 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15382 score += SCORE_ICASE;
15383 else
15385 /* For a similar character use SCORE_SIMILAR. */
15386 if (slang != NULL
15387 && slang->sl_has_map
15388 && similar_chars(slang, gc, bc))
15389 score += SCORE_SIMILAR;
15390 else
15391 score += SCORE_SUBST;
15394 if (score < minscore)
15396 /* Do the substitution. */
15397 ++gi;
15398 ++bi;
15399 continue;
15402 pop:
15404 * Get here to try the next alternative, pop it from the stack.
15406 if (stackidx == 0) /* stack is empty, finished */
15407 break;
15409 /* pop an item from the stack */
15410 --stackidx;
15411 gi = stack[stackidx].goodi;
15412 bi = stack[stackidx].badi;
15413 score = stack[stackidx].score;
15416 /* When the score goes over "limit" it may actually be much higher.
15417 * Return a very large number to avoid going below the limit when giving a
15418 * bonus. */
15419 if (minscore > limit)
15420 return SCORE_MAXMAX;
15421 return minscore;
15424 #ifdef FEAT_MBYTE
15426 * Multi-byte version of spell_edit_score_limit().
15427 * Keep it in sync with the above!
15429 static int
15430 spell_edit_score_limit_w(slang, badword, goodword, limit)
15431 slang_T *slang;
15432 char_u *badword;
15433 char_u *goodword;
15434 int limit;
15436 limitscore_T stack[10]; /* allow for over 3 * 2 edits */
15437 int stackidx;
15438 int bi, gi;
15439 int bi2, gi2;
15440 int bc, gc;
15441 int score;
15442 int score_off;
15443 int minscore;
15444 int round;
15445 char_u *p;
15446 int wbadword[MAXWLEN];
15447 int wgoodword[MAXWLEN];
15449 /* Get the characters from the multi-byte strings and put them in an
15450 * int array for easy access. */
15451 bi = 0;
15452 for (p = badword; *p != NUL; )
15453 wbadword[bi++] = mb_cptr2char_adv(&p);
15454 wbadword[bi++] = 0;
15455 gi = 0;
15456 for (p = goodword; *p != NUL; )
15457 wgoodword[gi++] = mb_cptr2char_adv(&p);
15458 wgoodword[gi++] = 0;
15461 * The idea is to go from start to end over the words. So long as
15462 * characters are equal just continue, this always gives the lowest score.
15463 * When there is a difference try several alternatives. Each alternative
15464 * increases "score" for the edit distance. Some of the alternatives are
15465 * pushed unto a stack and tried later, some are tried right away. At the
15466 * end of the word the score for one alternative is known. The lowest
15467 * possible score is stored in "minscore".
15469 stackidx = 0;
15470 bi = 0;
15471 gi = 0;
15472 score = 0;
15473 minscore = limit + 1;
15475 for (;;)
15477 /* Skip over an equal part, score remains the same. */
15478 for (;;)
15480 bc = wbadword[bi];
15481 gc = wgoodword[gi];
15483 if (bc != gc) /* stop at a char that's different */
15484 break;
15485 if (bc == NUL) /* both words end */
15487 if (score < minscore)
15488 minscore = score;
15489 goto pop; /* do next alternative */
15491 ++bi;
15492 ++gi;
15495 if (gc == NUL) /* goodword ends, delete badword chars */
15499 if ((score += SCORE_DEL) >= minscore)
15500 goto pop; /* do next alternative */
15501 } while (wbadword[++bi] != NUL);
15502 minscore = score;
15504 else if (bc == NUL) /* badword ends, insert badword chars */
15508 if ((score += SCORE_INS) >= minscore)
15509 goto pop; /* do next alternative */
15510 } while (wgoodword[++gi] != NUL);
15511 minscore = score;
15513 else /* both words continue */
15515 /* If not close to the limit, perform a change. Only try changes
15516 * that may lead to a lower score than "minscore".
15517 * round 0: try deleting a char from badword
15518 * round 1: try inserting a char in badword */
15519 for (round = 0; round <= 1; ++round)
15521 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
15522 if (score_off < minscore)
15524 if (score_off + SCORE_EDIT_MIN >= minscore)
15526 /* Near the limit, rest of the words must match. We
15527 * can check that right now, no need to push an item
15528 * onto the stack. */
15529 bi2 = bi + 1 - round;
15530 gi2 = gi + round;
15531 while (wgoodword[gi2] == wbadword[bi2])
15533 if (wgoodword[gi2] == NUL)
15535 minscore = score_off;
15536 break;
15538 ++bi2;
15539 ++gi2;
15542 else
15544 /* try deleting a character from badword later */
15545 stack[stackidx].badi = bi + 1 - round;
15546 stack[stackidx].goodi = gi + round;
15547 stack[stackidx].score = score_off;
15548 ++stackidx;
15553 if (score + SCORE_SWAP < minscore)
15555 /* If swapping two characters makes a match then the
15556 * substitution is more expensive, thus there is no need to
15557 * try both. */
15558 if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1])
15560 /* Swap two characters, that is: skip them. */
15561 gi += 2;
15562 bi += 2;
15563 score += SCORE_SWAP;
15564 continue;
15568 /* Substitute one character for another which is the same
15569 * thing as deleting a character from both goodword and badword.
15570 * Use a better score when there is only a case difference. */
15571 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15572 score += SCORE_ICASE;
15573 else
15575 /* For a similar character use SCORE_SIMILAR. */
15576 if (slang != NULL
15577 && slang->sl_has_map
15578 && similar_chars(slang, gc, bc))
15579 score += SCORE_SIMILAR;
15580 else
15581 score += SCORE_SUBST;
15584 if (score < minscore)
15586 /* Do the substitution. */
15587 ++gi;
15588 ++bi;
15589 continue;
15592 pop:
15594 * Get here to try the next alternative, pop it from the stack.
15596 if (stackidx == 0) /* stack is empty, finished */
15597 break;
15599 /* pop an item from the stack */
15600 --stackidx;
15601 gi = stack[stackidx].goodi;
15602 bi = stack[stackidx].badi;
15603 score = stack[stackidx].score;
15606 /* When the score goes over "limit" it may actually be much higher.
15607 * Return a very large number to avoid going below the limit when giving a
15608 * bonus. */
15609 if (minscore > limit)
15610 return SCORE_MAXMAX;
15611 return minscore;
15613 #endif
15616 * ":spellinfo"
15618 void
15619 ex_spellinfo(eap)
15620 exarg_T *eap UNUSED;
15622 int lpi;
15623 langp_T *lp;
15624 char_u *p;
15626 if (no_spell_checking(curwin))
15627 return;
15629 msg_start();
15630 for (lpi = 0; lpi < curbuf->b_langp.ga_len && !got_int; ++lpi)
15632 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
15633 msg_puts((char_u *)"file: ");
15634 msg_puts(lp->lp_slang->sl_fname);
15635 msg_putchar('\n');
15636 p = lp->lp_slang->sl_info;
15637 if (p != NULL)
15639 msg_puts(p);
15640 msg_putchar('\n');
15643 msg_end();
15646 #define DUMPFLAG_KEEPCASE 1 /* round 2: keep-case tree */
15647 #define DUMPFLAG_COUNT 2 /* include word count */
15648 #define DUMPFLAG_ICASE 4 /* ignore case when finding matches */
15649 #define DUMPFLAG_ONECAP 8 /* pattern starts with capital */
15650 #define DUMPFLAG_ALLCAP 16 /* pattern is all capitals */
15653 * ":spelldump"
15655 void
15656 ex_spelldump(eap)
15657 exarg_T *eap;
15659 buf_T *buf = curbuf;
15661 if (no_spell_checking(curwin))
15662 return;
15664 /* Create a new empty buffer by splitting the window. */
15665 do_cmdline_cmd((char_u *)"new");
15666 if (!bufempty() || !buf_valid(buf))
15667 return;
15669 spell_dump_compl(buf, NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0);
15671 /* Delete the empty line that we started with. */
15672 if (curbuf->b_ml.ml_line_count > 1)
15673 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
15675 redraw_later(NOT_VALID);
15679 * Go through all possible words and:
15680 * 1. When "pat" is NULL: dump a list of all words in the current buffer.
15681 * "ic" and "dir" are not used.
15682 * 2. When "pat" is not NULL: add matching words to insert mode completion.
15684 void
15685 spell_dump_compl(buf, pat, ic, dir, dumpflags_arg)
15686 buf_T *buf; /* buffer with spell checking */
15687 char_u *pat; /* leading part of the word */
15688 int ic; /* ignore case */
15689 int *dir; /* direction for adding matches */
15690 int dumpflags_arg; /* DUMPFLAG_* */
15692 langp_T *lp;
15693 slang_T *slang;
15694 idx_T arridx[MAXWLEN];
15695 int curi[MAXWLEN];
15696 char_u word[MAXWLEN];
15697 int c;
15698 char_u *byts;
15699 idx_T *idxs;
15700 linenr_T lnum = 0;
15701 int round;
15702 int depth;
15703 int n;
15704 int flags;
15705 char_u *region_names = NULL; /* region names being used */
15706 int do_region = TRUE; /* dump region names and numbers */
15707 char_u *p;
15708 int lpi;
15709 int dumpflags = dumpflags_arg;
15710 int patlen;
15712 /* When ignoring case or when the pattern starts with capital pass this on
15713 * to dump_word(). */
15714 if (pat != NULL)
15716 if (ic)
15717 dumpflags |= DUMPFLAG_ICASE;
15718 else
15720 n = captype(pat, NULL);
15721 if (n == WF_ONECAP)
15722 dumpflags |= DUMPFLAG_ONECAP;
15723 else if (n == WF_ALLCAP
15724 #ifdef FEAT_MBYTE
15725 && (int)STRLEN(pat) > mb_ptr2len(pat)
15726 #else
15727 && (int)STRLEN(pat) > 1
15728 #endif
15730 dumpflags |= DUMPFLAG_ALLCAP;
15734 /* Find out if we can support regions: All languages must support the same
15735 * regions or none at all. */
15736 for (lpi = 0; lpi < buf->b_langp.ga_len; ++lpi)
15738 lp = LANGP_ENTRY(buf->b_langp, lpi);
15739 p = lp->lp_slang->sl_regions;
15740 if (p[0] != 0)
15742 if (region_names == NULL) /* first language with regions */
15743 region_names = p;
15744 else if (STRCMP(region_names, p) != 0)
15746 do_region = FALSE; /* region names are different */
15747 break;
15752 if (do_region && region_names != NULL)
15754 if (pat == NULL)
15756 vim_snprintf((char *)IObuff, IOSIZE, "/regions=%s", region_names);
15757 ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
15760 else
15761 do_region = FALSE;
15764 * Loop over all files loaded for the entries in 'spelllang'.
15766 for (lpi = 0; lpi < buf->b_langp.ga_len; ++lpi)
15768 lp = LANGP_ENTRY(buf->b_langp, lpi);
15769 slang = lp->lp_slang;
15770 if (slang->sl_fbyts == NULL) /* reloading failed */
15771 continue;
15773 if (pat == NULL)
15775 vim_snprintf((char *)IObuff, IOSIZE, "# file: %s", slang->sl_fname);
15776 ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
15779 /* When matching with a pattern and there are no prefixes only use
15780 * parts of the tree that match "pat". */
15781 if (pat != NULL && slang->sl_pbyts == NULL)
15782 patlen = (int)STRLEN(pat);
15783 else
15784 patlen = -1;
15786 /* round 1: case-folded tree
15787 * round 2: keep-case tree */
15788 for (round = 1; round <= 2; ++round)
15790 if (round == 1)
15792 dumpflags &= ~DUMPFLAG_KEEPCASE;
15793 byts = slang->sl_fbyts;
15794 idxs = slang->sl_fidxs;
15796 else
15798 dumpflags |= DUMPFLAG_KEEPCASE;
15799 byts = slang->sl_kbyts;
15800 idxs = slang->sl_kidxs;
15802 if (byts == NULL)
15803 continue; /* array is empty */
15805 depth = 0;
15806 arridx[0] = 0;
15807 curi[0] = 1;
15808 while (depth >= 0 && !got_int
15809 && (pat == NULL || !compl_interrupted))
15811 if (curi[depth] > byts[arridx[depth]])
15813 /* Done all bytes at this node, go up one level. */
15814 --depth;
15815 line_breakcheck();
15816 ins_compl_check_keys(50);
15818 else
15820 /* Do one more byte at this node. */
15821 n = arridx[depth] + curi[depth];
15822 ++curi[depth];
15823 c = byts[n];
15824 if (c == 0)
15826 /* End of word, deal with the word.
15827 * Don't use keep-case words in the fold-case tree,
15828 * they will appear in the keep-case tree.
15829 * Only use the word when the region matches. */
15830 flags = (int)idxs[n];
15831 if ((round == 2 || (flags & WF_KEEPCAP) == 0)
15832 && (flags & WF_NEEDCOMP) == 0
15833 && (do_region
15834 || (flags & WF_REGION) == 0
15835 || (((unsigned)flags >> 16)
15836 & lp->lp_region) != 0))
15838 word[depth] = NUL;
15839 if (!do_region)
15840 flags &= ~WF_REGION;
15842 /* Dump the basic word if there is no prefix or
15843 * when it's the first one. */
15844 c = (unsigned)flags >> 24;
15845 if (c == 0 || curi[depth] == 2)
15847 dump_word(slang, word, pat, dir,
15848 dumpflags, flags, lnum);
15849 if (pat == NULL)
15850 ++lnum;
15853 /* Apply the prefix, if there is one. */
15854 if (c != 0)
15855 lnum = dump_prefixes(slang, word, pat, dir,
15856 dumpflags, flags, lnum);
15859 else
15861 /* Normal char, go one level deeper. */
15862 word[depth++] = c;
15863 arridx[depth] = idxs[n];
15864 curi[depth] = 1;
15866 /* Check if this characters matches with the pattern.
15867 * If not skip the whole tree below it.
15868 * Always ignore case here, dump_word() will check
15869 * proper case later. This isn't exactly right when
15870 * length changes for multi-byte characters with
15871 * ignore case... */
15872 if (depth <= patlen
15873 && MB_STRNICMP(word, pat, depth) != 0)
15874 --depth;
15883 * Dump one word: apply case modifications and append a line to the buffer.
15884 * When "lnum" is zero add insert mode completion.
15886 static void
15887 dump_word(slang, word, pat, dir, dumpflags, wordflags, lnum)
15888 slang_T *slang;
15889 char_u *word;
15890 char_u *pat;
15891 int *dir;
15892 int dumpflags;
15893 int wordflags;
15894 linenr_T lnum;
15896 int keepcap = FALSE;
15897 char_u *p;
15898 char_u *tw;
15899 char_u cword[MAXWLEN];
15900 char_u badword[MAXWLEN + 10];
15901 int i;
15902 int flags = wordflags;
15904 if (dumpflags & DUMPFLAG_ONECAP)
15905 flags |= WF_ONECAP;
15906 if (dumpflags & DUMPFLAG_ALLCAP)
15907 flags |= WF_ALLCAP;
15909 if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0)
15911 /* Need to fix case according to "flags". */
15912 make_case_word(word, cword, flags);
15913 p = cword;
15915 else
15917 p = word;
15918 if ((dumpflags & DUMPFLAG_KEEPCASE)
15919 && ((captype(word, NULL) & WF_KEEPCAP) == 0
15920 || (flags & WF_FIXCAP) != 0))
15921 keepcap = TRUE;
15923 tw = p;
15925 if (pat == NULL)
15927 /* Add flags and regions after a slash. */
15928 if ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap)
15930 STRCPY(badword, p);
15931 STRCAT(badword, "/");
15932 if (keepcap)
15933 STRCAT(badword, "=");
15934 if (flags & WF_BANNED)
15935 STRCAT(badword, "!");
15936 else if (flags & WF_RARE)
15937 STRCAT(badword, "?");
15938 if (flags & WF_REGION)
15939 for (i = 0; i < 7; ++i)
15940 if (flags & (0x10000 << i))
15941 sprintf((char *)badword + STRLEN(badword), "%d", i + 1);
15942 p = badword;
15945 if (dumpflags & DUMPFLAG_COUNT)
15947 hashitem_T *hi;
15949 /* Include the word count for ":spelldump!". */
15950 hi = hash_find(&slang->sl_wordcount, tw);
15951 if (!HASHITEM_EMPTY(hi))
15953 vim_snprintf((char *)IObuff, IOSIZE, "%s\t%d",
15954 tw, HI2WC(hi)->wc_count);
15955 p = IObuff;
15959 ml_append(lnum, p, (colnr_T)0, FALSE);
15961 else if (((dumpflags & DUMPFLAG_ICASE)
15962 ? MB_STRNICMP(p, pat, STRLEN(pat)) == 0
15963 : STRNCMP(p, pat, STRLEN(pat)) == 0)
15964 && ins_compl_add_infercase(p, (int)STRLEN(p),
15965 p_ic, NULL, *dir, 0) == OK)
15966 /* if dir was BACKWARD then honor it just once */
15967 *dir = FORWARD;
15971 * For ":spelldump": Find matching prefixes for "word". Prepend each to
15972 * "word" and append a line to the buffer.
15973 * When "lnum" is zero add insert mode completion.
15974 * Return the updated line number.
15976 static linenr_T
15977 dump_prefixes(slang, word, pat, dir, dumpflags, flags, startlnum)
15978 slang_T *slang;
15979 char_u *word; /* case-folded word */
15980 char_u *pat;
15981 int *dir;
15982 int dumpflags;
15983 int flags; /* flags with prefix ID */
15984 linenr_T startlnum;
15986 idx_T arridx[MAXWLEN];
15987 int curi[MAXWLEN];
15988 char_u prefix[MAXWLEN];
15989 char_u word_up[MAXWLEN];
15990 int has_word_up = FALSE;
15991 int c;
15992 char_u *byts;
15993 idx_T *idxs;
15994 linenr_T lnum = startlnum;
15995 int depth;
15996 int n;
15997 int len;
15998 int i;
16000 /* If the word starts with a lower-case letter make the word with an
16001 * upper-case letter in word_up[]. */
16002 c = PTR2CHAR(word);
16003 if (SPELL_TOUPPER(c) != c)
16005 onecap_copy(word, word_up, TRUE);
16006 has_word_up = TRUE;
16009 byts = slang->sl_pbyts;
16010 idxs = slang->sl_pidxs;
16011 if (byts != NULL) /* array not is empty */
16014 * Loop over all prefixes, building them byte-by-byte in prefix[].
16015 * When at the end of a prefix check that it supports "flags".
16017 depth = 0;
16018 arridx[0] = 0;
16019 curi[0] = 1;
16020 while (depth >= 0 && !got_int)
16022 n = arridx[depth];
16023 len = byts[n];
16024 if (curi[depth] > len)
16026 /* Done all bytes at this node, go up one level. */
16027 --depth;
16028 line_breakcheck();
16030 else
16032 /* Do one more byte at this node. */
16033 n += curi[depth];
16034 ++curi[depth];
16035 c = byts[n];
16036 if (c == 0)
16038 /* End of prefix, find out how many IDs there are. */
16039 for (i = 1; i < len; ++i)
16040 if (byts[n + i] != 0)
16041 break;
16042 curi[depth] += i - 1;
16044 c = valid_word_prefix(i, n, flags, word, slang, FALSE);
16045 if (c != 0)
16047 vim_strncpy(prefix + depth, word, MAXWLEN - depth - 1);
16048 dump_word(slang, prefix, pat, dir, dumpflags,
16049 (c & WF_RAREPFX) ? (flags | WF_RARE)
16050 : flags, lnum);
16051 if (lnum != 0)
16052 ++lnum;
16055 /* Check for prefix that matches the word when the
16056 * first letter is upper-case, but only if the prefix has
16057 * a condition. */
16058 if (has_word_up)
16060 c = valid_word_prefix(i, n, flags, word_up, slang,
16061 TRUE);
16062 if (c != 0)
16064 vim_strncpy(prefix + depth, word_up,
16065 MAXWLEN - depth - 1);
16066 dump_word(slang, prefix, pat, dir, dumpflags,
16067 (c & WF_RAREPFX) ? (flags | WF_RARE)
16068 : flags, lnum);
16069 if (lnum != 0)
16070 ++lnum;
16074 else
16076 /* Normal char, go one level deeper. */
16077 prefix[depth++] = c;
16078 arridx[depth] = idxs[n];
16079 curi[depth] = 1;
16085 return lnum;
16089 * Move "p" to the end of word "start".
16090 * Uses the spell-checking word characters.
16092 char_u *
16093 spell_to_word_end(start, buf)
16094 char_u *start;
16095 buf_T *buf;
16097 char_u *p = start;
16099 while (*p != NUL && spell_iswordp(p, buf))
16100 mb_ptr_adv(p);
16101 return p;
16104 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
16106 * For Insert mode completion CTRL-X s:
16107 * Find start of the word in front of column "startcol".
16108 * We don't check if it is badly spelled, with completion we can only change
16109 * the word in front of the cursor.
16110 * Returns the column number of the word.
16113 spell_word_start(startcol)
16114 int startcol;
16116 char_u *line;
16117 char_u *p;
16118 int col = 0;
16120 if (no_spell_checking(curwin))
16121 return startcol;
16123 /* Find a word character before "startcol". */
16124 line = ml_get_curline();
16125 for (p = line + startcol; p > line; )
16127 mb_ptr_back(line, p);
16128 if (spell_iswordp_nmw(p))
16129 break;
16132 /* Go back to start of the word. */
16133 while (p > line)
16135 col = (int)(p - line);
16136 mb_ptr_back(line, p);
16137 if (!spell_iswordp(p, curbuf))
16138 break;
16139 col = 0;
16142 return col;
16146 * Need to check for 'spellcapcheck' now, the word is removed before
16147 * expand_spelling() is called. Therefore the ugly global variable.
16149 static int spell_expand_need_cap;
16151 void
16152 spell_expand_check_cap(col)
16153 colnr_T col;
16155 spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col);
16159 * Get list of spelling suggestions.
16160 * Used for Insert mode completion CTRL-X ?.
16161 * Returns the number of matches. The matches are in "matchp[]", array of
16162 * allocated strings.
16165 expand_spelling(lnum, pat, matchp)
16166 linenr_T lnum UNUSED;
16167 char_u *pat;
16168 char_u ***matchp;
16170 garray_T ga;
16172 spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, TRUE);
16173 *matchp = ga.ga_data;
16174 return ga.ga_len;
16176 #endif
16178 #endif /* FEAT_SPELL */