Merged from the latest developing branch.
[MacVim.git] / src / spell.c
blob22630b5497a3bd748762417246265d4ee7146b9c
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 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 #ifdef HAVE_FCNTL_H
315 # include <fcntl.h>
316 #endif
318 #ifndef UNIX /* it's in os_unix.h for Unix */
319 # include <time.h> /* for time_t */
320 #endif
322 #define MAXWLEN 250 /* Assume max. word len is this many bytes.
323 Some places assume a word length fits in a
324 byte, thus it can't be above 255. */
326 /* Type used for indexes in the word tree need to be at least 4 bytes. If int
327 * is 8 bytes we could use something smaller, but what? */
328 #if SIZEOF_INT > 3
329 typedef int idx_T;
330 #else
331 typedef long idx_T;
332 #endif
334 /* Flags used for a word. Only the lowest byte can be used, the region byte
335 * comes above it. */
336 #define WF_REGION 0x01 /* region byte follows */
337 #define WF_ONECAP 0x02 /* word with one capital (or all capitals) */
338 #define WF_ALLCAP 0x04 /* word must be all capitals */
339 #define WF_RARE 0x08 /* rare word */
340 #define WF_BANNED 0x10 /* bad word */
341 #define WF_AFX 0x20 /* affix ID follows */
342 #define WF_FIXCAP 0x40 /* keep-case word, allcap not allowed */
343 #define WF_KEEPCAP 0x80 /* keep-case word */
345 /* for <flags2>, shifted up one byte to be used in wn_flags */
346 #define WF_HAS_AFF 0x0100 /* word includes affix */
347 #define WF_NEEDCOMP 0x0200 /* word only valid in compound */
348 #define WF_NOSUGGEST 0x0400 /* word not to be suggested */
349 #define WF_COMPROOT 0x0800 /* already compounded word, COMPOUNDROOT */
350 #define WF_NOCOMPBEF 0x1000 /* no compounding before this word */
351 #define WF_NOCOMPAFT 0x2000 /* no compounding after this word */
353 /* only used for su_badflags */
354 #define WF_MIXCAP 0x20 /* mix of upper and lower case: macaRONI */
356 #define WF_CAPMASK (WF_ONECAP | WF_ALLCAP | WF_KEEPCAP | WF_FIXCAP)
358 /* flags for <pflags> */
359 #define WFP_RARE 0x01 /* rare prefix */
360 #define WFP_NC 0x02 /* prefix is not combining */
361 #define WFP_UP 0x04 /* to-upper prefix */
362 #define WFP_COMPPERMIT 0x08 /* prefix with COMPOUNDPERMITFLAG */
363 #define WFP_COMPFORBID 0x10 /* prefix with COMPOUNDFORBIDFLAG */
365 /* Flags for postponed prefixes in "sl_pidxs". Must be above affixID (one
366 * byte) and prefcondnr (two bytes). */
367 #define WF_RAREPFX (WFP_RARE << 24) /* rare postponed prefix */
368 #define WF_PFX_NC (WFP_NC << 24) /* non-combining postponed prefix */
369 #define WF_PFX_UP (WFP_UP << 24) /* to-upper postponed prefix */
370 #define WF_PFX_COMPPERMIT (WFP_COMPPERMIT << 24) /* postponed prefix with
371 * COMPOUNDPERMITFLAG */
372 #define WF_PFX_COMPFORBID (WFP_COMPFORBID << 24) /* postponed prefix with
373 * COMPOUNDFORBIDFLAG */
376 /* flags for <compoptions> */
377 #define COMP_CHECKDUP 1 /* CHECKCOMPOUNDDUP */
378 #define COMP_CHECKREP 2 /* CHECKCOMPOUNDREP */
379 #define COMP_CHECKCASE 4 /* CHECKCOMPOUNDCASE */
380 #define COMP_CHECKTRIPLE 8 /* CHECKCOMPOUNDTRIPLE */
382 /* Special byte values for <byte>. Some are only used in the tree for
383 * postponed prefixes, some only in the other trees. This is a bit messy... */
384 #define BY_NOFLAGS 0 /* end of word without flags or region; for
385 * postponed prefix: no <pflags> */
386 #define BY_INDEX 1 /* child is shared, index follows */
387 #define BY_FLAGS 2 /* end of word, <flags> byte follows; for
388 * postponed prefix: <pflags> follows */
389 #define BY_FLAGS2 3 /* end of word, <flags> and <flags2> bytes
390 * follow; never used in prefix tree */
391 #define BY_SPECIAL BY_FLAGS2 /* highest special byte value */
393 /* Info from "REP", "REPSAL" and "SAL" entries in ".aff" file used in si_rep,
394 * si_repsal, sl_rep, and si_sal. Not for sl_sal!
395 * One replacement: from "ft_from" to "ft_to". */
396 typedef struct fromto_S
398 char_u *ft_from;
399 char_u *ft_to;
400 } fromto_T;
402 /* Info from "SAL" entries in ".aff" file used in sl_sal.
403 * The info is split for quick processing by spell_soundfold().
404 * Note that "sm_oneof" and "sm_rules" point into sm_lead. */
405 typedef struct salitem_S
407 char_u *sm_lead; /* leading letters */
408 int sm_leadlen; /* length of "sm_lead" */
409 char_u *sm_oneof; /* letters from () or NULL */
410 char_u *sm_rules; /* rules like ^, $, priority */
411 char_u *sm_to; /* replacement. */
412 #ifdef FEAT_MBYTE
413 int *sm_lead_w; /* wide character copy of "sm_lead" */
414 int *sm_oneof_w; /* wide character copy of "sm_oneof" */
415 int *sm_to_w; /* wide character copy of "sm_to" */
416 #endif
417 } salitem_T;
419 #ifdef FEAT_MBYTE
420 typedef int salfirst_T;
421 #else
422 typedef short salfirst_T;
423 #endif
425 /* Values for SP_*ERROR are negative, positive values are used by
426 * read_cnt_string(). */
427 #define SP_TRUNCERROR -1 /* spell file truncated error */
428 #define SP_FORMERROR -2 /* format error in spell file */
429 #define SP_OTHERERROR -3 /* other error while reading spell file */
432 * Structure used to store words and other info for one language, loaded from
433 * a .spl file.
434 * The main access is through the tree in "sl_fbyts/sl_fidxs", storing the
435 * case-folded words. "sl_kbyts/sl_kidxs" is for keep-case words.
437 * The "byts" array stores the possible bytes in each tree node, preceded by
438 * the number of possible bytes, sorted on byte value:
439 * <len> <byte1> <byte2> ...
440 * The "idxs" array stores the index of the child node corresponding to the
441 * byte in "byts".
442 * Exception: when the byte is zero, the word may end here and "idxs" holds
443 * the flags, region mask and affixID for the word. There may be several
444 * zeros in sequence for alternative flag/region/affixID combinations.
446 typedef struct slang_S slang_T;
447 struct slang_S
449 slang_T *sl_next; /* next language */
450 char_u *sl_name; /* language name "en", "en.rare", "nl", etc. */
451 char_u *sl_fname; /* name of .spl file */
452 int sl_add; /* TRUE if it's a .add file. */
454 char_u *sl_fbyts; /* case-folded word bytes */
455 idx_T *sl_fidxs; /* case-folded word indexes */
456 char_u *sl_kbyts; /* keep-case word bytes */
457 idx_T *sl_kidxs; /* keep-case word indexes */
458 char_u *sl_pbyts; /* prefix tree word bytes */
459 idx_T *sl_pidxs; /* prefix tree word indexes */
461 char_u *sl_info; /* infotext string or NULL */
463 char_u sl_regions[17]; /* table with up to 8 region names plus NUL */
465 char_u *sl_midword; /* MIDWORD string or NULL */
467 hashtab_T sl_wordcount; /* hashtable with word count, wordcount_T */
469 int sl_compmax; /* COMPOUNDWORDMAX (default: MAXWLEN) */
470 int sl_compminlen; /* COMPOUNDMIN (default: 0) */
471 int sl_compsylmax; /* COMPOUNDSYLMAX (default: MAXWLEN) */
472 int sl_compoptions; /* COMP_* flags */
473 garray_T sl_comppat; /* CHECKCOMPOUNDPATTERN items */
474 regprog_T *sl_compprog; /* COMPOUNDRULE turned into a regexp progrm
475 * (NULL when no compounding) */
476 char_u *sl_compstartflags; /* flags for first compound word */
477 char_u *sl_compallflags; /* all flags for compound words */
478 char_u sl_nobreak; /* When TRUE: no spaces between words */
479 char_u *sl_syllable; /* SYLLABLE repeatable chars or NULL */
480 garray_T sl_syl_items; /* syllable items */
482 int sl_prefixcnt; /* number of items in "sl_prefprog" */
483 regprog_T **sl_prefprog; /* table with regprogs for prefixes */
485 garray_T sl_rep; /* list of fromto_T entries from REP lines */
486 short sl_rep_first[256]; /* indexes where byte first appears, -1 if
487 there is none */
488 garray_T sl_sal; /* list of salitem_T entries from SAL lines */
489 salfirst_T sl_sal_first[256]; /* indexes where byte first appears, -1 if
490 there is none */
491 int sl_followup; /* SAL followup */
492 int sl_collapse; /* SAL collapse_result */
493 int sl_rem_accents; /* SAL remove_accents */
494 int sl_sofo; /* SOFOFROM and SOFOTO instead of SAL items:
495 * "sl_sal_first" maps chars, when has_mbyte
496 * "sl_sal" is a list of wide char lists. */
497 garray_T sl_repsal; /* list of fromto_T entries from REPSAL lines */
498 short sl_repsal_first[256]; /* sl_rep_first for REPSAL lines */
499 int sl_nosplitsugs; /* don't suggest splitting a word */
501 /* Info from the .sug file. Loaded on demand. */
502 time_t sl_sugtime; /* timestamp for .sug file */
503 char_u *sl_sbyts; /* soundfolded word bytes */
504 idx_T *sl_sidxs; /* soundfolded word indexes */
505 buf_T *sl_sugbuf; /* buffer with word number table */
506 int sl_sugloaded; /* TRUE when .sug file was loaded or failed to
507 load */
509 int sl_has_map; /* TRUE if there is a MAP line */
510 #ifdef FEAT_MBYTE
511 hashtab_T sl_map_hash; /* MAP for multi-byte chars */
512 int sl_map_array[256]; /* MAP for first 256 chars */
513 #else
514 char_u sl_map_array[256]; /* MAP for first 256 chars */
515 #endif
516 hashtab_T sl_sounddone; /* table with soundfolded words that have
517 handled, see add_sound_suggest() */
520 /* First language that is loaded, start of the linked list of loaded
521 * languages. */
522 static slang_T *first_lang = NULL;
524 /* Flags used in .spl file for soundsalike flags. */
525 #define SAL_F0LLOWUP 1
526 #define SAL_COLLAPSE 2
527 #define SAL_REM_ACCENTS 4
530 * Structure used in "b_langp", filled from 'spelllang'.
532 typedef struct langp_S
534 slang_T *lp_slang; /* info for this language */
535 slang_T *lp_sallang; /* language used for sound folding or NULL */
536 slang_T *lp_replang; /* language used for REP items or NULL */
537 int lp_region; /* bitmask for region or REGION_ALL */
538 } langp_T;
540 #define LANGP_ENTRY(ga, i) (((langp_T *)(ga).ga_data) + (i))
542 #define REGION_ALL 0xff /* word valid in all regions */
544 #define VIMSPELLMAGIC "VIMspell" /* string at start of Vim spell file */
545 #define VIMSPELLMAGICL 8
546 #define VIMSPELLVERSION 50
548 #define VIMSUGMAGIC "VIMsug" /* string at start of Vim .sug file */
549 #define VIMSUGMAGICL 6
550 #define VIMSUGVERSION 1
552 /* Section IDs. Only renumber them when VIMSPELLVERSION changes! */
553 #define SN_REGION 0 /* <regionname> section */
554 #define SN_CHARFLAGS 1 /* charflags section */
555 #define SN_MIDWORD 2 /* <midword> section */
556 #define SN_PREFCOND 3 /* <prefcond> section */
557 #define SN_REP 4 /* REP items section */
558 #define SN_SAL 5 /* SAL items section */
559 #define SN_SOFO 6 /* soundfolding section */
560 #define SN_MAP 7 /* MAP items section */
561 #define SN_COMPOUND 8 /* compound words section */
562 #define SN_SYLLABLE 9 /* syllable section */
563 #define SN_NOBREAK 10 /* NOBREAK section */
564 #define SN_SUGFILE 11 /* timestamp for .sug file */
565 #define SN_REPSAL 12 /* REPSAL items section */
566 #define SN_WORDS 13 /* common words */
567 #define SN_NOSPLITSUGS 14 /* don't split word for suggestions */
568 #define SN_INFO 15 /* info section */
569 #define SN_END 255 /* end of sections */
571 #define SNF_REQUIRED 1 /* <sectionflags>: required section */
573 /* Result values. Lower number is accepted over higher one. */
574 #define SP_BANNED -1
575 #define SP_OK 0
576 #define SP_RARE 1
577 #define SP_LOCAL 2
578 #define SP_BAD 3
580 /* file used for "zG" and "zW" */
581 static char_u *int_wordlist = NULL;
583 typedef struct wordcount_S
585 short_u wc_count; /* nr of times word was seen */
586 char_u wc_word[1]; /* word, actually longer */
587 } wordcount_T;
589 static wordcount_T dumwc;
590 #define WC_KEY_OFF (unsigned)(dumwc.wc_word - (char_u *)&dumwc)
591 #define HI2WC(hi) ((wordcount_T *)((hi)->hi_key - WC_KEY_OFF))
592 #define MAXWORDCOUNT 0xffff
595 * Information used when looking for suggestions.
597 typedef struct suginfo_S
599 garray_T su_ga; /* suggestions, contains "suggest_T" */
600 int su_maxcount; /* max. number of suggestions displayed */
601 int su_maxscore; /* maximum score for adding to su_ga */
602 int su_sfmaxscore; /* idem, for when doing soundfold words */
603 garray_T su_sga; /* like su_ga, sound-folded scoring */
604 char_u *su_badptr; /* start of bad word in line */
605 int su_badlen; /* length of detected bad word in line */
606 int su_badflags; /* caps flags for bad word */
607 char_u su_badword[MAXWLEN]; /* bad word truncated at su_badlen */
608 char_u su_fbadword[MAXWLEN]; /* su_badword case-folded */
609 char_u su_sal_badword[MAXWLEN]; /* su_badword soundfolded */
610 hashtab_T su_banned; /* table with banned words */
611 slang_T *su_sallang; /* default language for sound folding */
612 } suginfo_T;
614 /* One word suggestion. Used in "si_ga". */
615 typedef struct suggest_S
617 char_u *st_word; /* suggested word, allocated string */
618 int st_wordlen; /* STRLEN(st_word) */
619 int st_orglen; /* length of replaced text */
620 int st_score; /* lower is better */
621 int st_altscore; /* used when st_score compares equal */
622 int st_salscore; /* st_score is for soundalike */
623 int st_had_bonus; /* bonus already included in score */
624 slang_T *st_slang; /* language used for sound folding */
625 } suggest_T;
627 #define SUG(ga, i) (((suggest_T *)(ga).ga_data)[i])
629 /* TRUE if a word appears in the list of banned words. */
630 #define WAS_BANNED(su, word) (!HASHITEM_EMPTY(hash_find(&su->su_banned, word)))
632 /* Number of suggestions kept when cleaning up. we need to keep more than
633 * what is displayed, because when rescore_suggestions() is called the score
634 * may change and wrong suggestions may be removed later. */
635 #define SUG_CLEAN_COUNT(su) ((su)->su_maxcount < 130 ? 150 : (su)->su_maxcount + 20)
637 /* Threshold for sorting and cleaning up suggestions. Don't want to keep lots
638 * of suggestions that are not going to be displayed. */
639 #define SUG_MAX_COUNT(su) (SUG_CLEAN_COUNT(su) + 50)
641 /* score for various changes */
642 #define SCORE_SPLIT 149 /* split bad word */
643 #define SCORE_SPLIT_NO 249 /* split bad word with NOSPLITSUGS */
644 #define SCORE_ICASE 52 /* slightly different case */
645 #define SCORE_REGION 200 /* word is for different region */
646 #define SCORE_RARE 180 /* rare word */
647 #define SCORE_SWAP 75 /* swap two characters */
648 #define SCORE_SWAP3 110 /* swap two characters in three */
649 #define SCORE_REP 65 /* REP replacement */
650 #define SCORE_SUBST 93 /* substitute a character */
651 #define SCORE_SIMILAR 33 /* substitute a similar character */
652 #define SCORE_SUBCOMP 33 /* substitute a composing character */
653 #define SCORE_DEL 94 /* delete a character */
654 #define SCORE_DELDUP 66 /* delete a duplicated character */
655 #define SCORE_DELCOMP 28 /* delete a composing character */
656 #define SCORE_INS 96 /* insert a character */
657 #define SCORE_INSDUP 67 /* insert a duplicate character */
658 #define SCORE_INSCOMP 30 /* insert a composing character */
659 #define SCORE_NONWORD 103 /* change non-word to word char */
661 #define SCORE_FILE 30 /* suggestion from a file */
662 #define SCORE_MAXINIT 350 /* Initial maximum score: higher == slower.
663 * 350 allows for about three changes. */
665 #define SCORE_COMMON1 30 /* subtracted for words seen before */
666 #define SCORE_COMMON2 40 /* subtracted for words often seen */
667 #define SCORE_COMMON3 50 /* subtracted for words very often seen */
668 #define SCORE_THRES2 10 /* word count threshold for COMMON2 */
669 #define SCORE_THRES3 100 /* word count threshold for COMMON3 */
671 /* When trying changed soundfold words it becomes slow when trying more than
672 * two changes. With less then two changes it's slightly faster but we miss a
673 * few good suggestions. In rare cases we need to try three of four changes.
675 #define SCORE_SFMAX1 200 /* maximum score for first try */
676 #define SCORE_SFMAX2 300 /* maximum score for second try */
677 #define SCORE_SFMAX3 400 /* maximum score for third try */
679 #define SCORE_BIG SCORE_INS * 3 /* big difference */
680 #define SCORE_MAXMAX 999999 /* accept any score */
681 #define SCORE_LIMITMAX 350 /* for spell_edit_score_limit() */
683 /* for spell_edit_score_limit() we need to know the minimum value of
684 * SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS */
685 #define SCORE_EDIT_MIN SCORE_SIMILAR
688 * Structure to store info for word matching.
690 typedef struct matchinf_S
692 langp_T *mi_lp; /* info for language and region */
694 /* pointers to original text to be checked */
695 char_u *mi_word; /* start of word being checked */
696 char_u *mi_end; /* end of matching word so far */
697 char_u *mi_fend; /* next char to be added to mi_fword */
698 char_u *mi_cend; /* char after what was used for
699 mi_capflags */
701 /* case-folded text */
702 char_u mi_fword[MAXWLEN + 1]; /* mi_word case-folded */
703 int mi_fwordlen; /* nr of valid bytes in mi_fword */
705 /* for when checking word after a prefix */
706 int mi_prefarridx; /* index in sl_pidxs with list of
707 affixID/condition */
708 int mi_prefcnt; /* number of entries at mi_prefarridx */
709 int mi_prefixlen; /* byte length of prefix */
710 #ifdef FEAT_MBYTE
711 int mi_cprefixlen; /* byte length of prefix in original
712 case */
713 #else
714 # define mi_cprefixlen mi_prefixlen /* it's the same value */
715 #endif
717 /* for when checking a compound word */
718 int mi_compoff; /* start of following word offset */
719 char_u mi_compflags[MAXWLEN]; /* flags for compound words used */
720 int mi_complen; /* nr of compound words used */
721 int mi_compextra; /* nr of COMPOUNDROOT words */
723 /* others */
724 int mi_result; /* result so far: SP_BAD, SP_OK, etc. */
725 int mi_capflags; /* WF_ONECAP WF_ALLCAP WF_KEEPCAP */
726 buf_T *mi_buf; /* buffer being checked */
728 /* for NOBREAK */
729 int mi_result2; /* "mi_resul" without following word */
730 char_u *mi_end2; /* "mi_end" without following word */
731 } matchinf_T;
734 * The tables used for recognizing word characters according to spelling.
735 * These are only used for the first 256 characters of 'encoding'.
737 typedef struct spelltab_S
739 char_u st_isw[256]; /* flags: is word char */
740 char_u st_isu[256]; /* flags: is uppercase char */
741 char_u st_fold[256]; /* chars: folded case */
742 char_u st_upper[256]; /* chars: upper case */
743 } spelltab_T;
745 static spelltab_T spelltab;
746 static int did_set_spelltab;
748 #define CF_WORD 0x01
749 #define CF_UPPER 0x02
751 static void clear_spell_chartab __ARGS((spelltab_T *sp));
752 static int set_spell_finish __ARGS((spelltab_T *new_st));
753 static int spell_iswordp __ARGS((char_u *p, buf_T *buf));
754 static int spell_iswordp_nmw __ARGS((char_u *p));
755 #ifdef FEAT_MBYTE
756 static int spell_mb_isword_class __ARGS((int cl));
757 static int spell_iswordp_w __ARGS((int *p, buf_T *buf));
758 #endif
759 static int write_spell_prefcond __ARGS((FILE *fd, garray_T *gap));
762 * For finding suggestions: At each node in the tree these states are tried:
764 typedef enum
766 STATE_START = 0, /* At start of node check for NUL bytes (goodword
767 * ends); if badword ends there is a match, otherwise
768 * try splitting word. */
769 STATE_NOPREFIX, /* try without prefix */
770 STATE_SPLITUNDO, /* Undo splitting. */
771 STATE_ENDNUL, /* Past NUL bytes at start of the node. */
772 STATE_PLAIN, /* Use each byte of the node. */
773 STATE_DEL, /* Delete a byte from the bad word. */
774 STATE_INS_PREP, /* Prepare for inserting bytes. */
775 STATE_INS, /* Insert a byte in the bad word. */
776 STATE_SWAP, /* Swap two bytes. */
777 STATE_UNSWAP, /* Undo swap two characters. */
778 STATE_SWAP3, /* Swap two characters over three. */
779 STATE_UNSWAP3, /* Undo Swap two characters over three. */
780 STATE_UNROT3L, /* Undo rotate three characters left */
781 STATE_UNROT3R, /* Undo rotate three characters right */
782 STATE_REP_INI, /* Prepare for using REP items. */
783 STATE_REP, /* Use matching REP items from the .aff file. */
784 STATE_REP_UNDO, /* Undo a REP item replacement. */
785 STATE_FINAL /* End of this node. */
786 } state_T;
789 * Struct to keep the state at each level in suggest_try_change().
791 typedef struct trystate_S
793 state_T ts_state; /* state at this level, STATE_ */
794 int ts_score; /* score */
795 idx_T ts_arridx; /* index in tree array, start of node */
796 short ts_curi; /* index in list of child nodes */
797 char_u ts_fidx; /* index in fword[], case-folded bad word */
798 char_u ts_fidxtry; /* ts_fidx at which bytes may be changed */
799 char_u ts_twordlen; /* valid length of tword[] */
800 char_u ts_prefixdepth; /* stack depth for end of prefix or
801 * PFD_PREFIXTREE or PFD_NOPREFIX */
802 char_u ts_flags; /* TSF_ flags */
803 #ifdef FEAT_MBYTE
804 char_u ts_tcharlen; /* number of bytes in tword character */
805 char_u ts_tcharidx; /* current byte index in tword character */
806 char_u ts_isdiff; /* DIFF_ values */
807 char_u ts_fcharstart; /* index in fword where badword char started */
808 #endif
809 char_u ts_prewordlen; /* length of word in "preword[]" */
810 char_u ts_splitoff; /* index in "tword" after last split */
811 char_u ts_splitfidx; /* "ts_fidx" at word split */
812 char_u ts_complen; /* nr of compound words used */
813 char_u ts_compsplit; /* index for "compflags" where word was spit */
814 char_u ts_save_badflags; /* su_badflags saved here */
815 char_u ts_delidx; /* index in fword for char that was deleted,
816 valid when "ts_flags" has TSF_DIDDEL */
817 } trystate_T;
819 /* values for ts_isdiff */
820 #define DIFF_NONE 0 /* no different byte (yet) */
821 #define DIFF_YES 1 /* different byte found */
822 #define DIFF_INSERT 2 /* inserting character */
824 /* values for ts_flags */
825 #define TSF_PREFIXOK 1 /* already checked that prefix is OK */
826 #define TSF_DIDSPLIT 2 /* tried split at this point */
827 #define TSF_DIDDEL 4 /* did a delete, "ts_delidx" has index */
829 /* special values ts_prefixdepth */
830 #define PFD_NOPREFIX 0xff /* not using prefixes */
831 #define PFD_PREFIXTREE 0xfe /* walking through the prefix tree */
832 #define PFD_NOTSPECIAL 0xfd /* highest value that's not special */
834 /* mode values for find_word */
835 #define FIND_FOLDWORD 0 /* find word case-folded */
836 #define FIND_KEEPWORD 1 /* find keep-case word */
837 #define FIND_PREFIX 2 /* find word after prefix */
838 #define FIND_COMPOUND 3 /* find case-folded compound word */
839 #define FIND_KEEPCOMPOUND 4 /* find keep-case compound word */
841 static slang_T *slang_alloc __ARGS((char_u *lang));
842 static void slang_free __ARGS((slang_T *lp));
843 static void slang_clear __ARGS((slang_T *lp));
844 static void slang_clear_sug __ARGS((slang_T *lp));
845 static void find_word __ARGS((matchinf_T *mip, int mode));
846 static int can_compound __ARGS((slang_T *slang, char_u *word, char_u *flags));
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 int get2c __ARGS((FILE *fd));
858 static int get3c __ARGS((FILE *fd));
859 static int get4c __ARGS((FILE *fd));
860 static time_t get8c __ARGS((FILE *fd));
861 static char_u *read_cnt_string __ARGS((FILE *fd, int cnt_bytes, int *lenp));
862 static char_u *read_string __ARGS((FILE *fd, int cnt));
863 static int read_region_section __ARGS((FILE *fd, slang_T *slang, int len));
864 static int read_charflags_section __ARGS((FILE *fd));
865 static int read_prefcond_section __ARGS((FILE *fd, slang_T *lp));
866 static int read_rep_section __ARGS((FILE *fd, garray_T *gap, short *first));
867 static int read_sal_section __ARGS((FILE *fd, slang_T *slang));
868 static int read_words_section __ARGS((FILE *fd, slang_T *lp, int len));
869 static void count_common_word __ARGS((slang_T *lp, char_u *word, int len, int count));
870 static int score_wordcount_adj __ARGS((slang_T *slang, int score, char_u *word, int split));
871 static int read_sofo_section __ARGS((FILE *fd, slang_T *slang));
872 static int read_compound __ARGS((FILE *fd, slang_T *slang, int len));
873 static int byte_in_str __ARGS((char_u *str, int byte));
874 static int init_syl_tab __ARGS((slang_T *slang));
875 static int count_syllables __ARGS((slang_T *slang, char_u *word));
876 static int set_sofo __ARGS((slang_T *lp, char_u *from, char_u *to));
877 static void set_sal_first __ARGS((slang_T *lp));
878 #ifdef FEAT_MBYTE
879 static int *mb_str2wide __ARGS((char_u *s));
880 #endif
881 static int spell_read_tree __ARGS((FILE *fd, char_u **bytsp, idx_T **idxsp, int prefixtree, int prefixcnt));
882 static idx_T read_tree_node __ARGS((FILE *fd, char_u *byts, idx_T *idxs, int maxidx, int startidx, int prefixtree, int maxprefcondnr));
883 static void clear_midword __ARGS((buf_T *buf));
884 static void use_midword __ARGS((slang_T *lp, buf_T *buf));
885 static int find_region __ARGS((char_u *rp, char_u *region));
886 static int captype __ARGS((char_u *word, char_u *end));
887 static int badword_captype __ARGS((char_u *word, char_u *end));
888 static void spell_reload_one __ARGS((char_u *fname, int added_word));
889 static void set_spell_charflags __ARGS((char_u *flags, int cnt, char_u *upp));
890 static int set_spell_chartab __ARGS((char_u *fol, char_u *low, char_u *upp));
891 static int spell_casefold __ARGS((char_u *p, int len, char_u *buf, int buflen));
892 static int check_need_cap __ARGS((linenr_T lnum, colnr_T col));
893 static void spell_find_suggest __ARGS((char_u *badptr, int badlen, suginfo_T *su, int maxcount, int banbadword, int need_cap, int interactive));
894 #ifdef FEAT_EVAL
895 static void spell_suggest_expr __ARGS((suginfo_T *su, char_u *expr));
896 #endif
897 static void spell_suggest_file __ARGS((suginfo_T *su, char_u *fname));
898 static void spell_suggest_intern __ARGS((suginfo_T *su, int interactive));
899 static void suggest_load_files __ARGS((void));
900 static void tree_count_words __ARGS((char_u *byts, idx_T *idxs));
901 static void spell_find_cleanup __ARGS((suginfo_T *su));
902 static void onecap_copy __ARGS((char_u *word, char_u *wcopy, int upper));
903 static void allcap_copy __ARGS((char_u *word, char_u *wcopy));
904 static void suggest_try_special __ARGS((suginfo_T *su));
905 static void suggest_try_change __ARGS((suginfo_T *su));
906 static void suggest_trie_walk __ARGS((suginfo_T *su, langp_T *lp, char_u *fword, int soundfold));
907 static void go_deeper __ARGS((trystate_T *stack, int depth, int score_add));
908 #ifdef FEAT_MBYTE
909 static int nofold_len __ARGS((char_u *fword, int flen, char_u *word));
910 #endif
911 static void find_keepcap_word __ARGS((slang_T *slang, char_u *fword, char_u *kword));
912 static void score_comp_sal __ARGS((suginfo_T *su));
913 static void score_combine __ARGS((suginfo_T *su));
914 static int stp_sal_score __ARGS((suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *badsound));
915 static void suggest_try_soundalike_prep __ARGS((void));
916 static void suggest_try_soundalike __ARGS((suginfo_T *su));
917 static void suggest_try_soundalike_finish __ARGS((void));
918 static void add_sound_suggest __ARGS((suginfo_T *su, char_u *goodword, int score, langp_T *lp));
919 static int soundfold_find __ARGS((slang_T *slang, char_u *word));
920 static void make_case_word __ARGS((char_u *fword, char_u *cword, int flags));
921 static void set_map_str __ARGS((slang_T *lp, char_u *map));
922 static int similar_chars __ARGS((slang_T *slang, int c1, int c2));
923 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));
924 static void check_suggestions __ARGS((suginfo_T *su, garray_T *gap));
925 static void add_banned __ARGS((suginfo_T *su, char_u *word));
926 static void rescore_suggestions __ARGS((suginfo_T *su));
927 static void rescore_one __ARGS((suginfo_T *su, suggest_T *stp));
928 static int cleanup_suggestions __ARGS((garray_T *gap, int maxscore, int keep));
929 static void spell_soundfold __ARGS((slang_T *slang, char_u *inword, int folded, char_u *res));
930 static void spell_soundfold_sofo __ARGS((slang_T *slang, char_u *inword, char_u *res));
931 static void spell_soundfold_sal __ARGS((slang_T *slang, char_u *inword, char_u *res));
932 #ifdef FEAT_MBYTE
933 static void spell_soundfold_wsal __ARGS((slang_T *slang, char_u *inword, char_u *res));
934 #endif
935 static int soundalike_score __ARGS((char_u *goodsound, char_u *badsound));
936 static int spell_edit_score __ARGS((slang_T *slang, char_u *badword, char_u *goodword));
937 static int spell_edit_score_limit __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit));
938 #ifdef FEAT_MBYTE
939 static int spell_edit_score_limit_w __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit));
940 #endif
941 static void dump_word __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T lnum));
942 static linenr_T dump_prefixes __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T startlnum));
943 static buf_T *open_spellbuf __ARGS((void));
944 static void close_spellbuf __ARGS((buf_T *buf));
947 * Use our own character-case definitions, because the current locale may
948 * differ from what the .spl file uses.
949 * These must not be called with negative number!
951 #ifndef FEAT_MBYTE
952 /* Non-multi-byte implementation. */
953 # define SPELL_TOFOLD(c) ((c) < 256 ? spelltab.st_fold[c] : (c))
954 # define SPELL_TOUPPER(c) ((c) < 256 ? spelltab.st_upper[c] : (c))
955 # define SPELL_ISUPPER(c) ((c) < 256 ? spelltab.st_isu[c] : FALSE)
956 #else
957 # if defined(HAVE_WCHAR_H)
958 # include <wchar.h> /* for towupper() and towlower() */
959 # endif
960 /* Multi-byte implementation. For Unicode we can call utf_*(), but don't do
961 * that for ASCII, because we don't want to use 'casemap' here. Otherwise use
962 * the "w" library function for characters above 255 if available. */
963 # ifdef HAVE_TOWLOWER
964 # define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \
965 : (c) < 256 ? spelltab.st_fold[c] : towlower(c))
966 # else
967 # define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \
968 : (c) < 256 ? spelltab.st_fold[c] : (c))
969 # endif
971 # ifdef HAVE_TOWUPPER
972 # define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \
973 : (c) < 256 ? spelltab.st_upper[c] : towupper(c))
974 # else
975 # define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \
976 : (c) < 256 ? spelltab.st_upper[c] : (c))
977 # endif
979 # ifdef HAVE_ISWUPPER
980 # define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \
981 : (c) < 256 ? spelltab.st_isu[c] : iswupper(c))
982 # else
983 # define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \
984 : (c) < 256 ? spelltab.st_isu[c] : (FALSE))
985 # endif
986 #endif
989 static char *e_format = N_("E759: Format error in spell file");
990 static char *e_spell_trunc = N_("E758: Truncated spell file");
991 static char *e_afftrailing = N_("Trailing text in %s line %d: %s");
992 static char *e_affname = N_("Affix name too long in %s line %d: %s");
993 static char *e_affform = N_("E761: Format error in affix file FOL, LOW or UPP");
994 static char *e_affrange = N_("E762: Character in FOL, LOW or UPP is out of range");
995 static char *msg_compressing = N_("Compressing word tree...");
997 /* Remember what "z?" replaced. */
998 static char_u *repl_from = NULL;
999 static char_u *repl_to = NULL;
1002 * Main spell-checking function.
1003 * "ptr" points to a character that could be the start of a word.
1004 * "*attrp" is set to the highlight index for a badly spelled word. For a
1005 * non-word or when it's OK it remains unchanged.
1006 * This must only be called when 'spelllang' is not empty.
1008 * "capcol" is used to check for a Capitalised word after the end of a
1009 * sentence. If it's zero then perform the check. Return the column where to
1010 * check next, or -1 when no sentence end was found. If it's NULL then don't
1011 * worry.
1013 * Returns the length of the word in bytes, also when it's OK, so that the
1014 * caller can skip over the word.
1017 spell_check(wp, ptr, attrp, capcol, docount)
1018 win_T *wp; /* current window */
1019 char_u *ptr;
1020 hlf_T *attrp;
1021 int *capcol; /* column to check for Capital */
1022 int docount; /* count good words */
1024 matchinf_T mi; /* Most things are put in "mi" so that it can
1025 be passed to functions quickly. */
1026 int nrlen = 0; /* found a number first */
1027 int c;
1028 int wrongcaplen = 0;
1029 int lpi;
1030 int count_word = docount;
1032 /* A word never starts at a space or a control character. Return quickly
1033 * then, skipping over the character. */
1034 if (*ptr <= ' ')
1035 return 1;
1037 /* Return here when loading language files failed. */
1038 if (wp->w_buffer->b_langp.ga_len == 0)
1039 return 1;
1041 vim_memset(&mi, 0, sizeof(matchinf_T));
1043 /* A number is always OK. Also skip hexadecimal numbers 0xFF99 and
1044 * 0X99FF. But always do check spelling to find "3GPP" and "11
1045 * julifeest". */
1046 if (*ptr >= '0' && *ptr <= '9')
1048 if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X'))
1049 mi.mi_end = skiphex(ptr + 2);
1050 else
1051 mi.mi_end = skipdigits(ptr);
1052 nrlen = (int)(mi.mi_end - ptr);
1055 /* Find the normal end of the word (until the next non-word character). */
1056 mi.mi_word = ptr;
1057 mi.mi_fend = ptr;
1058 if (spell_iswordp(mi.mi_fend, wp->w_buffer))
1062 mb_ptr_adv(mi.mi_fend);
1063 } while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp->w_buffer));
1065 if (capcol != NULL && *capcol == 0 && wp->w_buffer->b_cap_prog != NULL)
1067 /* Check word starting with capital letter. */
1068 c = PTR2CHAR(ptr);
1069 if (!SPELL_ISUPPER(c))
1070 wrongcaplen = (int)(mi.mi_fend - ptr);
1073 if (capcol != NULL)
1074 *capcol = -1;
1076 /* We always use the characters up to the next non-word character,
1077 * also for bad words. */
1078 mi.mi_end = mi.mi_fend;
1080 /* Check caps type later. */
1081 mi.mi_buf = wp->w_buffer;
1083 /* case-fold the word with one non-word character, so that we can check
1084 * for the word end. */
1085 if (*mi.mi_fend != NUL)
1086 mb_ptr_adv(mi.mi_fend);
1088 (void)spell_casefold(ptr, (int)(mi.mi_fend - ptr), mi.mi_fword,
1089 MAXWLEN + 1);
1090 mi.mi_fwordlen = (int)STRLEN(mi.mi_fword);
1092 /* The word is bad unless we recognize it. */
1093 mi.mi_result = SP_BAD;
1094 mi.mi_result2 = SP_BAD;
1097 * Loop over the languages specified in 'spelllang'.
1098 * We check them all, because a word may be matched longer in another
1099 * language.
1101 for (lpi = 0; lpi < wp->w_buffer->b_langp.ga_len; ++lpi)
1103 mi.mi_lp = LANGP_ENTRY(wp->w_buffer->b_langp, lpi);
1105 /* If reloading fails the language is still in the list but everything
1106 * has been cleared. */
1107 if (mi.mi_lp->lp_slang->sl_fidxs == NULL)
1108 continue;
1110 /* Check for a matching word in case-folded words. */
1111 find_word(&mi, FIND_FOLDWORD);
1113 /* Check for a matching word in keep-case words. */
1114 find_word(&mi, FIND_KEEPWORD);
1116 /* Check for matching prefixes. */
1117 find_prefix(&mi, FIND_FOLDWORD);
1119 /* For a NOBREAK language, may want to use a word without a following
1120 * word as a backup. */
1121 if (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD
1122 && mi.mi_result2 != SP_BAD)
1124 mi.mi_result = mi.mi_result2;
1125 mi.mi_end = mi.mi_end2;
1128 /* Count the word in the first language where it's found to be OK. */
1129 if (count_word && mi.mi_result == SP_OK)
1131 count_common_word(mi.mi_lp->lp_slang, ptr,
1132 (int)(mi.mi_end - ptr), 1);
1133 count_word = FALSE;
1137 if (mi.mi_result != SP_OK)
1139 /* If we found a number skip over it. Allows for "42nd". Do flag
1140 * rare and local words, e.g., "3GPP". */
1141 if (nrlen > 0)
1143 if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)
1144 return nrlen;
1147 /* When we are at a non-word character there is no error, just
1148 * skip over the character (try looking for a word after it). */
1149 else if (!spell_iswordp_nmw(ptr))
1151 if (capcol != NULL && wp->w_buffer->b_cap_prog != NULL)
1153 regmatch_T regmatch;
1155 /* Check for end of sentence. */
1156 regmatch.regprog = wp->w_buffer->b_cap_prog;
1157 regmatch.rm_ic = FALSE;
1158 if (vim_regexec(&regmatch, ptr, 0))
1159 *capcol = (int)(regmatch.endp[0] - ptr);
1162 #ifdef FEAT_MBYTE
1163 if (has_mbyte)
1164 return (*mb_ptr2len)(ptr);
1165 #endif
1166 return 1;
1168 else if (mi.mi_end == ptr)
1169 /* Always include at least one character. Required for when there
1170 * is a mixup in "midword". */
1171 mb_ptr_adv(mi.mi_end);
1172 else if (mi.mi_result == SP_BAD
1173 && LANGP_ENTRY(wp->w_buffer->b_langp, 0)->lp_slang->sl_nobreak)
1175 char_u *p, *fp;
1176 int save_result = mi.mi_result;
1178 /* First language in 'spelllang' is NOBREAK. Find first position
1179 * at which any word would be valid. */
1180 mi.mi_lp = LANGP_ENTRY(wp->w_buffer->b_langp, 0);
1181 if (mi.mi_lp->lp_slang->sl_fidxs != NULL)
1183 p = mi.mi_word;
1184 fp = mi.mi_fword;
1185 for (;;)
1187 mb_ptr_adv(p);
1188 mb_ptr_adv(fp);
1189 if (p >= mi.mi_end)
1190 break;
1191 mi.mi_compoff = (int)(fp - mi.mi_fword);
1192 find_word(&mi, FIND_COMPOUND);
1193 if (mi.mi_result != SP_BAD)
1195 mi.mi_end = p;
1196 break;
1199 mi.mi_result = save_result;
1203 if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)
1204 *attrp = HLF_SPB;
1205 else if (mi.mi_result == SP_RARE)
1206 *attrp = HLF_SPR;
1207 else
1208 *attrp = HLF_SPL;
1211 if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE))
1213 /* Report SpellCap only when the word isn't badly spelled. */
1214 *attrp = HLF_SPC;
1215 return wrongcaplen;
1218 return (int)(mi.mi_end - ptr);
1222 * Check if the word at "mip->mi_word" is in the tree.
1223 * When "mode" is FIND_FOLDWORD check in fold-case word tree.
1224 * When "mode" is FIND_KEEPWORD check in keep-case word tree.
1225 * When "mode" is FIND_PREFIX check for word after prefix in fold-case word
1226 * tree.
1228 * For a match mip->mi_result is updated.
1230 static void
1231 find_word(mip, mode)
1232 matchinf_T *mip;
1233 int mode;
1235 idx_T arridx = 0;
1236 int endlen[MAXWLEN]; /* length at possible word endings */
1237 idx_T endidx[MAXWLEN]; /* possible word endings */
1238 int endidxcnt = 0;
1239 int len;
1240 int wlen = 0;
1241 int flen;
1242 int c;
1243 char_u *ptr;
1244 idx_T lo, hi, m;
1245 #ifdef FEAT_MBYTE
1246 char_u *s;
1247 #endif
1248 char_u *p;
1249 int res = SP_BAD;
1250 slang_T *slang = mip->mi_lp->lp_slang;
1251 unsigned flags;
1252 char_u *byts;
1253 idx_T *idxs;
1254 int word_ends;
1255 int prefix_found;
1256 int nobreak_result;
1258 if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND)
1260 /* Check for word with matching case in keep-case tree. */
1261 ptr = mip->mi_word;
1262 flen = 9999; /* no case folding, always enough bytes */
1263 byts = slang->sl_kbyts;
1264 idxs = slang->sl_kidxs;
1266 if (mode == FIND_KEEPCOMPOUND)
1267 /* Skip over the previously found word(s). */
1268 wlen += mip->mi_compoff;
1270 else
1272 /* Check for case-folded in case-folded tree. */
1273 ptr = mip->mi_fword;
1274 flen = mip->mi_fwordlen; /* available case-folded bytes */
1275 byts = slang->sl_fbyts;
1276 idxs = slang->sl_fidxs;
1278 if (mode == FIND_PREFIX)
1280 /* Skip over the prefix. */
1281 wlen = mip->mi_prefixlen;
1282 flen -= mip->mi_prefixlen;
1284 else if (mode == FIND_COMPOUND)
1286 /* Skip over the previously found word(s). */
1287 wlen = mip->mi_compoff;
1288 flen -= mip->mi_compoff;
1293 if (byts == NULL)
1294 return; /* array is empty */
1297 * Repeat advancing in the tree until:
1298 * - there is a byte that doesn't match,
1299 * - we reach the end of the tree,
1300 * - or we reach the end of the line.
1302 for (;;)
1304 if (flen <= 0 && *mip->mi_fend != NUL)
1305 flen = fold_more(mip);
1307 len = byts[arridx++];
1309 /* If the first possible byte is a zero the word could end here.
1310 * Remember this index, we first check for the longest word. */
1311 if (byts[arridx] == 0)
1313 if (endidxcnt == MAXWLEN)
1315 /* Must be a corrupted spell file. */
1316 EMSG(_(e_format));
1317 return;
1319 endlen[endidxcnt] = wlen;
1320 endidx[endidxcnt++] = arridx++;
1321 --len;
1323 /* Skip over the zeros, there can be several flag/region
1324 * combinations. */
1325 while (len > 0 && byts[arridx] == 0)
1327 ++arridx;
1328 --len;
1330 if (len == 0)
1331 break; /* no children, word must end here */
1334 /* Stop looking at end of the line. */
1335 if (ptr[wlen] == NUL)
1336 break;
1338 /* Perform a binary search in the list of accepted bytes. */
1339 c = ptr[wlen];
1340 if (c == TAB) /* <Tab> is handled like <Space> */
1341 c = ' ';
1342 lo = arridx;
1343 hi = arridx + len - 1;
1344 while (lo < hi)
1346 m = (lo + hi) / 2;
1347 if (byts[m] > c)
1348 hi = m - 1;
1349 else if (byts[m] < c)
1350 lo = m + 1;
1351 else
1353 lo = hi = m;
1354 break;
1358 /* Stop if there is no matching byte. */
1359 if (hi < lo || byts[lo] != c)
1360 break;
1362 /* Continue at the child (if there is one). */
1363 arridx = idxs[lo];
1364 ++wlen;
1365 --flen;
1367 /* One space in the good word may stand for several spaces in the
1368 * checked word. */
1369 if (c == ' ')
1371 for (;;)
1373 if (flen <= 0 && *mip->mi_fend != NUL)
1374 flen = fold_more(mip);
1375 if (ptr[wlen] != ' ' && ptr[wlen] != TAB)
1376 break;
1377 ++wlen;
1378 --flen;
1384 * Verify that one of the possible endings is valid. Try the longest
1385 * first.
1387 while (endidxcnt > 0)
1389 --endidxcnt;
1390 arridx = endidx[endidxcnt];
1391 wlen = endlen[endidxcnt];
1393 #ifdef FEAT_MBYTE
1394 if ((*mb_head_off)(ptr, ptr + wlen) > 0)
1395 continue; /* not at first byte of character */
1396 #endif
1397 if (spell_iswordp(ptr + wlen, mip->mi_buf))
1399 if (slang->sl_compprog == NULL && !slang->sl_nobreak)
1400 continue; /* next char is a word character */
1401 word_ends = FALSE;
1403 else
1404 word_ends = TRUE;
1405 /* The prefix flag is before compound flags. Once a valid prefix flag
1406 * has been found we try compound flags. */
1407 prefix_found = FALSE;
1409 #ifdef FEAT_MBYTE
1410 if (mode != FIND_KEEPWORD && has_mbyte)
1412 /* Compute byte length in original word, length may change
1413 * when folding case. This can be slow, take a shortcut when the
1414 * case-folded word is equal to the keep-case word. */
1415 p = mip->mi_word;
1416 if (STRNCMP(ptr, p, wlen) != 0)
1418 for (s = ptr; s < ptr + wlen; mb_ptr_adv(s))
1419 mb_ptr_adv(p);
1420 wlen = (int)(p - mip->mi_word);
1423 #endif
1425 /* Check flags and region. For FIND_PREFIX check the condition and
1426 * prefix ID.
1427 * Repeat this if there are more flags/region alternatives until there
1428 * is a match. */
1429 res = SP_BAD;
1430 for (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0;
1431 --len, ++arridx)
1433 flags = idxs[arridx];
1435 /* For the fold-case tree check that the case of the checked word
1436 * matches with what the word in the tree requires.
1437 * For keep-case tree the case is always right. For prefixes we
1438 * don't bother to check. */
1439 if (mode == FIND_FOLDWORD)
1441 if (mip->mi_cend != mip->mi_word + wlen)
1443 /* mi_capflags was set for a different word length, need
1444 * to do it again. */
1445 mip->mi_cend = mip->mi_word + wlen;
1446 mip->mi_capflags = captype(mip->mi_word, mip->mi_cend);
1449 if (mip->mi_capflags == WF_KEEPCAP
1450 || !spell_valid_case(mip->mi_capflags, flags))
1451 continue;
1454 /* When mode is FIND_PREFIX the word must support the prefix:
1455 * check the prefix ID and the condition. Do that for the list at
1456 * mip->mi_prefarridx that find_prefix() filled. */
1457 else if (mode == FIND_PREFIX && !prefix_found)
1459 c = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx,
1460 flags,
1461 mip->mi_word + mip->mi_cprefixlen, slang,
1462 FALSE);
1463 if (c == 0)
1464 continue;
1466 /* Use the WF_RARE flag for a rare prefix. */
1467 if (c & WF_RAREPFX)
1468 flags |= WF_RARE;
1469 prefix_found = TRUE;
1472 if (slang->sl_nobreak)
1474 if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND)
1475 && (flags & WF_BANNED) == 0)
1477 /* NOBREAK: found a valid following word. That's all we
1478 * need to know, so return. */
1479 mip->mi_result = SP_OK;
1480 break;
1484 else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND
1485 || !word_ends))
1487 /* If there is no compound flag or the word is shorter than
1488 * COMPOUNDMIN reject it quickly.
1489 * Makes you wonder why someone puts a compound flag on a word
1490 * that's too short... Myspell compatibility requires this
1491 * anyway. */
1492 if (((unsigned)flags >> 24) == 0
1493 || wlen - mip->mi_compoff < slang->sl_compminlen)
1494 continue;
1495 #ifdef FEAT_MBYTE
1496 /* For multi-byte chars check character length against
1497 * COMPOUNDMIN. */
1498 if (has_mbyte
1499 && slang->sl_compminlen > 0
1500 && mb_charlen_len(mip->mi_word + mip->mi_compoff,
1501 wlen - mip->mi_compoff) < slang->sl_compminlen)
1502 continue;
1503 #endif
1505 /* Limit the number of compound words to COMPOUNDWORDMAX if no
1506 * maximum for syllables is specified. */
1507 if (!word_ends && mip->mi_complen + mip->mi_compextra + 2
1508 > slang->sl_compmax
1509 && slang->sl_compsylmax == MAXWLEN)
1510 continue;
1512 /* Don't allow compounding on a side where an affix was added,
1513 * unless COMPOUNDPERMITFLAG was used. */
1514 if (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF))
1515 continue;
1516 if (!word_ends && (flags & WF_NOCOMPAFT))
1517 continue;
1519 /* Quickly check if compounding is possible with this flag. */
1520 if (!byte_in_str(mip->mi_complen == 0
1521 ? slang->sl_compstartflags
1522 : slang->sl_compallflags,
1523 ((unsigned)flags >> 24)))
1524 continue;
1526 if (mode == FIND_COMPOUND)
1528 int capflags;
1530 /* Need to check the caps type of the appended compound
1531 * word. */
1532 #ifdef FEAT_MBYTE
1533 if (has_mbyte && STRNCMP(ptr, mip->mi_word,
1534 mip->mi_compoff) != 0)
1536 /* case folding may have changed the length */
1537 p = mip->mi_word;
1538 for (s = ptr; s < ptr + mip->mi_compoff; mb_ptr_adv(s))
1539 mb_ptr_adv(p);
1541 else
1542 #endif
1543 p = mip->mi_word + mip->mi_compoff;
1544 capflags = captype(p, mip->mi_word + wlen);
1545 if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP
1546 && (flags & WF_FIXCAP) != 0))
1547 continue;
1549 if (capflags != WF_ALLCAP)
1551 /* When the character before the word is a word
1552 * character we do not accept a Onecap word. We do
1553 * accept a no-caps word, even when the dictionary
1554 * word specifies ONECAP. */
1555 mb_ptr_back(mip->mi_word, p);
1556 if (spell_iswordp_nmw(p)
1557 ? capflags == WF_ONECAP
1558 : (flags & WF_ONECAP) != 0
1559 && capflags != WF_ONECAP)
1560 continue;
1564 /* If the word ends the sequence of compound flags of the
1565 * words must match with one of the COMPOUNDRULE items and
1566 * the number of syllables must not be too large. */
1567 mip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24);
1568 mip->mi_compflags[mip->mi_complen + 1] = NUL;
1569 if (word_ends)
1571 char_u fword[MAXWLEN];
1573 if (slang->sl_compsylmax < MAXWLEN)
1575 /* "fword" is only needed for checking syllables. */
1576 if (ptr == mip->mi_word)
1577 (void)spell_casefold(ptr, wlen, fword, MAXWLEN);
1578 else
1579 vim_strncpy(fword, ptr, endlen[endidxcnt]);
1581 if (!can_compound(slang, fword, mip->mi_compflags))
1582 continue;
1586 /* Check NEEDCOMPOUND: can't use word without compounding. */
1587 else if (flags & WF_NEEDCOMP)
1588 continue;
1590 nobreak_result = SP_OK;
1592 if (!word_ends)
1594 int save_result = mip->mi_result;
1595 char_u *save_end = mip->mi_end;
1596 langp_T *save_lp = mip->mi_lp;
1597 int lpi;
1599 /* Check that a valid word follows. If there is one and we
1600 * are compounding, it will set "mi_result", thus we are
1601 * always finished here. For NOBREAK we only check that a
1602 * valid word follows.
1603 * Recursive! */
1604 if (slang->sl_nobreak)
1605 mip->mi_result = SP_BAD;
1607 /* Find following word in case-folded tree. */
1608 mip->mi_compoff = endlen[endidxcnt];
1609 #ifdef FEAT_MBYTE
1610 if (has_mbyte && mode == FIND_KEEPWORD)
1612 /* Compute byte length in case-folded word from "wlen":
1613 * byte length in keep-case word. Length may change when
1614 * folding case. This can be slow, take a shortcut when
1615 * the case-folded word is equal to the keep-case word. */
1616 p = mip->mi_fword;
1617 if (STRNCMP(ptr, p, wlen) != 0)
1619 for (s = ptr; s < ptr + wlen; mb_ptr_adv(s))
1620 mb_ptr_adv(p);
1621 mip->mi_compoff = (int)(p - mip->mi_fword);
1624 #endif
1625 c = mip->mi_compoff;
1626 ++mip->mi_complen;
1627 if (flags & WF_COMPROOT)
1628 ++mip->mi_compextra;
1630 /* For NOBREAK we need to try all NOBREAK languages, at least
1631 * to find the ".add" file(s). */
1632 for (lpi = 0; lpi < mip->mi_buf->b_langp.ga_len; ++lpi)
1634 if (slang->sl_nobreak)
1636 mip->mi_lp = LANGP_ENTRY(mip->mi_buf->b_langp, lpi);
1637 if (mip->mi_lp->lp_slang->sl_fidxs == NULL
1638 || !mip->mi_lp->lp_slang->sl_nobreak)
1639 continue;
1642 find_word(mip, FIND_COMPOUND);
1644 /* When NOBREAK any word that matches is OK. Otherwise we
1645 * need to find the longest match, thus try with keep-case
1646 * and prefix too. */
1647 if (!slang->sl_nobreak || mip->mi_result == SP_BAD)
1649 /* Find following word in keep-case tree. */
1650 mip->mi_compoff = wlen;
1651 find_word(mip, FIND_KEEPCOMPOUND);
1653 #if 0 /* Disabled, a prefix must not appear halfway a compound word,
1654 unless the COMPOUNDPERMITFLAG is used and then it can't be a
1655 postponed prefix. */
1656 if (!slang->sl_nobreak || mip->mi_result == SP_BAD)
1658 /* Check for following word with prefix. */
1659 mip->mi_compoff = c;
1660 find_prefix(mip, FIND_COMPOUND);
1662 #endif
1665 if (!slang->sl_nobreak)
1666 break;
1668 --mip->mi_complen;
1669 if (flags & WF_COMPROOT)
1670 --mip->mi_compextra;
1671 mip->mi_lp = save_lp;
1673 if (slang->sl_nobreak)
1675 nobreak_result = mip->mi_result;
1676 mip->mi_result = save_result;
1677 mip->mi_end = save_end;
1679 else
1681 if (mip->mi_result == SP_OK)
1682 break;
1683 continue;
1687 if (flags & WF_BANNED)
1688 res = SP_BANNED;
1689 else if (flags & WF_REGION)
1691 /* Check region. */
1692 if ((mip->mi_lp->lp_region & (flags >> 16)) != 0)
1693 res = SP_OK;
1694 else
1695 res = SP_LOCAL;
1697 else if (flags & WF_RARE)
1698 res = SP_RARE;
1699 else
1700 res = SP_OK;
1702 /* Always use the longest match and the best result. For NOBREAK
1703 * we separately keep the longest match without a following good
1704 * word as a fall-back. */
1705 if (nobreak_result == SP_BAD)
1707 if (mip->mi_result2 > res)
1709 mip->mi_result2 = res;
1710 mip->mi_end2 = mip->mi_word + wlen;
1712 else if (mip->mi_result2 == res
1713 && mip->mi_end2 < mip->mi_word + wlen)
1714 mip->mi_end2 = mip->mi_word + wlen;
1716 else if (mip->mi_result > res)
1718 mip->mi_result = res;
1719 mip->mi_end = mip->mi_word + wlen;
1721 else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen)
1722 mip->mi_end = mip->mi_word + wlen;
1724 if (mip->mi_result == SP_OK)
1725 break;
1728 if (mip->mi_result == SP_OK)
1729 break;
1734 * Return TRUE if "flags" is a valid sequence of compound flags and "word"
1735 * does not have too many syllables.
1737 static int
1738 can_compound(slang, word, flags)
1739 slang_T *slang;
1740 char_u *word;
1741 char_u *flags;
1743 regmatch_T regmatch;
1744 #ifdef FEAT_MBYTE
1745 char_u uflags[MAXWLEN * 2];
1746 int i;
1747 #endif
1748 char_u *p;
1750 if (slang->sl_compprog == NULL)
1751 return FALSE;
1752 #ifdef FEAT_MBYTE
1753 if (enc_utf8)
1755 /* Need to convert the single byte flags to utf8 characters. */
1756 p = uflags;
1757 for (i = 0; flags[i] != NUL; ++i)
1758 p += mb_char2bytes(flags[i], p);
1759 *p = NUL;
1760 p = uflags;
1762 else
1763 #endif
1764 p = flags;
1765 regmatch.regprog = slang->sl_compprog;
1766 regmatch.rm_ic = FALSE;
1767 if (!vim_regexec(&regmatch, p, 0))
1768 return FALSE;
1770 /* Count the number of syllables. This may be slow, do it last. If there
1771 * are too many syllables AND the number of compound words is above
1772 * COMPOUNDWORDMAX then compounding is not allowed. */
1773 if (slang->sl_compsylmax < MAXWLEN
1774 && count_syllables(slang, word) > slang->sl_compsylmax)
1775 return (int)STRLEN(flags) < slang->sl_compmax;
1776 return TRUE;
1780 * Return non-zero if the prefix indicated by "arridx" matches with the prefix
1781 * ID in "flags" for the word "word".
1782 * The WF_RAREPFX flag is included in the return value for a rare prefix.
1784 static int
1785 valid_word_prefix(totprefcnt, arridx, flags, word, slang, cond_req)
1786 int totprefcnt; /* nr of prefix IDs */
1787 int arridx; /* idx in sl_pidxs[] */
1788 int flags;
1789 char_u *word;
1790 slang_T *slang;
1791 int cond_req; /* only use prefixes with a condition */
1793 int prefcnt;
1794 int pidx;
1795 regprog_T *rp;
1796 regmatch_T regmatch;
1797 int prefid;
1799 prefid = (unsigned)flags >> 24;
1800 for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt)
1802 pidx = slang->sl_pidxs[arridx + prefcnt];
1804 /* Check the prefix ID. */
1805 if (prefid != (pidx & 0xff))
1806 continue;
1808 /* Check if the prefix doesn't combine and the word already has a
1809 * suffix. */
1810 if ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC))
1811 continue;
1813 /* Check the condition, if there is one. The condition index is
1814 * stored in the two bytes above the prefix ID byte. */
1815 rp = slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff];
1816 if (rp != NULL)
1818 regmatch.regprog = rp;
1819 regmatch.rm_ic = FALSE;
1820 if (!vim_regexec(&regmatch, word, 0))
1821 continue;
1823 else if (cond_req)
1824 continue;
1826 /* It's a match! Return the WF_ flags. */
1827 return pidx;
1829 return 0;
1833 * Check if the word at "mip->mi_word" has a matching prefix.
1834 * If it does, then check the following word.
1836 * If "mode" is "FIND_COMPOUND" then do the same after another word, find a
1837 * prefix in a compound word.
1839 * For a match mip->mi_result is updated.
1841 static void
1842 find_prefix(mip, mode)
1843 matchinf_T *mip;
1844 int mode;
1846 idx_T arridx = 0;
1847 int len;
1848 int wlen = 0;
1849 int flen;
1850 int c;
1851 char_u *ptr;
1852 idx_T lo, hi, m;
1853 slang_T *slang = mip->mi_lp->lp_slang;
1854 char_u *byts;
1855 idx_T *idxs;
1857 byts = slang->sl_pbyts;
1858 if (byts == NULL)
1859 return; /* array is empty */
1861 /* We use the case-folded word here, since prefixes are always
1862 * case-folded. */
1863 ptr = mip->mi_fword;
1864 flen = mip->mi_fwordlen; /* available case-folded bytes */
1865 if (mode == FIND_COMPOUND)
1867 /* Skip over the previously found word(s). */
1868 ptr += mip->mi_compoff;
1869 flen -= mip->mi_compoff;
1871 idxs = slang->sl_pidxs;
1874 * Repeat advancing in the tree until:
1875 * - there is a byte that doesn't match,
1876 * - we reach the end of the tree,
1877 * - or we reach the end of the line.
1879 for (;;)
1881 if (flen == 0 && *mip->mi_fend != NUL)
1882 flen = fold_more(mip);
1884 len = byts[arridx++];
1886 /* If the first possible byte is a zero the prefix could end here.
1887 * Check if the following word matches and supports the prefix. */
1888 if (byts[arridx] == 0)
1890 /* There can be several prefixes with different conditions. We
1891 * try them all, since we don't know which one will give the
1892 * longest match. The word is the same each time, pass the list
1893 * of possible prefixes to find_word(). */
1894 mip->mi_prefarridx = arridx;
1895 mip->mi_prefcnt = len;
1896 while (len > 0 && byts[arridx] == 0)
1898 ++arridx;
1899 --len;
1901 mip->mi_prefcnt -= len;
1903 /* Find the word that comes after the prefix. */
1904 mip->mi_prefixlen = wlen;
1905 if (mode == FIND_COMPOUND)
1906 /* Skip over the previously found word(s). */
1907 mip->mi_prefixlen += mip->mi_compoff;
1909 #ifdef FEAT_MBYTE
1910 if (has_mbyte)
1912 /* Case-folded length may differ from original length. */
1913 mip->mi_cprefixlen = nofold_len(mip->mi_fword,
1914 mip->mi_prefixlen, mip->mi_word);
1916 else
1917 mip->mi_cprefixlen = mip->mi_prefixlen;
1918 #endif
1919 find_word(mip, FIND_PREFIX);
1922 if (len == 0)
1923 break; /* no children, word must end here */
1926 /* Stop looking at end of the line. */
1927 if (ptr[wlen] == NUL)
1928 break;
1930 /* Perform a binary search in the list of accepted bytes. */
1931 c = ptr[wlen];
1932 lo = arridx;
1933 hi = arridx + len - 1;
1934 while (lo < hi)
1936 m = (lo + hi) / 2;
1937 if (byts[m] > c)
1938 hi = m - 1;
1939 else if (byts[m] < c)
1940 lo = m + 1;
1941 else
1943 lo = hi = m;
1944 break;
1948 /* Stop if there is no matching byte. */
1949 if (hi < lo || byts[lo] != c)
1950 break;
1952 /* Continue at the child (if there is one). */
1953 arridx = idxs[lo];
1954 ++wlen;
1955 --flen;
1960 * Need to fold at least one more character. Do until next non-word character
1961 * for efficiency. Include the non-word character too.
1962 * Return the length of the folded chars in bytes.
1964 static int
1965 fold_more(mip)
1966 matchinf_T *mip;
1968 int flen;
1969 char_u *p;
1971 p = mip->mi_fend;
1974 mb_ptr_adv(mip->mi_fend);
1975 } while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_buf));
1977 /* Include the non-word character so that we can check for the word end. */
1978 if (*mip->mi_fend != NUL)
1979 mb_ptr_adv(mip->mi_fend);
1981 (void)spell_casefold(p, (int)(mip->mi_fend - p),
1982 mip->mi_fword + mip->mi_fwordlen,
1983 MAXWLEN - mip->mi_fwordlen);
1984 flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen);
1985 mip->mi_fwordlen += flen;
1986 return flen;
1990 * Check case flags for a word. Return TRUE if the word has the requested
1991 * case.
1993 static int
1994 spell_valid_case(wordflags, treeflags)
1995 int wordflags; /* flags for the checked word. */
1996 int treeflags; /* flags for the word in the spell tree */
1998 return ((wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0)
1999 || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0
2000 && ((treeflags & WF_ONECAP) == 0
2001 || (wordflags & WF_ONECAP) != 0)));
2005 * Return TRUE if spell checking is not enabled.
2007 static int
2008 no_spell_checking(wp)
2009 win_T *wp;
2011 if (!wp->w_p_spell || *wp->w_buffer->b_p_spl == NUL
2012 || wp->w_buffer->b_langp.ga_len == 0)
2014 EMSG(_("E756: Spell checking is not enabled"));
2015 return TRUE;
2017 return FALSE;
2021 * Move to next spell error.
2022 * "curline" is FALSE for "[s", "]s", "[S" and "]S".
2023 * "curline" is TRUE to find word under/after cursor in the same line.
2024 * For Insert mode completion "dir" is BACKWARD and "curline" is TRUE: move
2025 * to after badly spelled word before the cursor.
2026 * Return 0 if not found, length of the badly spelled word otherwise.
2029 spell_move_to(wp, dir, allwords, curline, attrp)
2030 win_T *wp;
2031 int dir; /* FORWARD or BACKWARD */
2032 int allwords; /* TRUE for "[s"/"]s", FALSE for "[S"/"]S" */
2033 int curline;
2034 hlf_T *attrp; /* return: attributes of bad word or NULL
2035 (only when "dir" is FORWARD) */
2037 linenr_T lnum;
2038 pos_T found_pos;
2039 int found_len = 0;
2040 char_u *line;
2041 char_u *p;
2042 char_u *endp;
2043 hlf_T attr;
2044 int len;
2045 # ifdef FEAT_SYN_HL
2046 int has_syntax = syntax_present(wp->w_buffer);
2047 # endif
2048 int col;
2049 int can_spell;
2050 char_u *buf = NULL;
2051 int buflen = 0;
2052 int skip = 0;
2053 int capcol = -1;
2054 int found_one = FALSE;
2055 int wrapped = FALSE;
2057 if (no_spell_checking(wp))
2058 return 0;
2061 * Start looking for bad word at the start of the line, because we can't
2062 * start halfway a word, we don't know where it starts or ends.
2064 * When searching backwards, we continue in the line to find the last
2065 * bad word (in the cursor line: before the cursor).
2067 * We concatenate the start of the next line, so that wrapped words work
2068 * (e.g. "et<line-break>cetera"). Doesn't work when searching backwards
2069 * though...
2071 lnum = wp->w_cursor.lnum;
2072 clearpos(&found_pos);
2074 while (!got_int)
2076 line = ml_get_buf(wp->w_buffer, lnum, FALSE);
2078 len = (int)STRLEN(line);
2079 if (buflen < len + MAXWLEN + 2)
2081 vim_free(buf);
2082 buflen = len + MAXWLEN + 2;
2083 buf = alloc(buflen);
2084 if (buf == NULL)
2085 break;
2088 /* In first line check first word for Capital. */
2089 if (lnum == 1)
2090 capcol = 0;
2092 /* For checking first word with a capital skip white space. */
2093 if (capcol == 0)
2094 capcol = (int)(skipwhite(line) - line);
2095 else if (curline && wp == curwin)
2097 /* For spellbadword(): check if first word needs a capital. */
2098 col = (int)(skipwhite(line) - line);
2099 if (check_need_cap(lnum, col))
2100 capcol = col;
2102 /* Need to get the line again, may have looked at the previous
2103 * one. */
2104 line = ml_get_buf(wp->w_buffer, lnum, FALSE);
2107 /* Copy the line into "buf" and append the start of the next line if
2108 * possible. */
2109 STRCPY(buf, line);
2110 if (lnum < wp->w_buffer->b_ml.ml_line_count)
2111 spell_cat_line(buf + STRLEN(buf),
2112 ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN);
2114 p = buf + skip;
2115 endp = buf + len;
2116 while (p < endp)
2118 /* When searching backward don't search after the cursor. Unless
2119 * we wrapped around the end of the buffer. */
2120 if (dir == BACKWARD
2121 && lnum == wp->w_cursor.lnum
2122 && !wrapped
2123 && (colnr_T)(p - buf) >= wp->w_cursor.col)
2124 break;
2126 /* start of word */
2127 attr = HLF_COUNT;
2128 len = spell_check(wp, p, &attr, &capcol, FALSE);
2130 if (attr != HLF_COUNT)
2132 /* We found a bad word. Check the attribute. */
2133 if (allwords || attr == HLF_SPB)
2135 /* When searching forward only accept a bad word after
2136 * the cursor. */
2137 if (dir == BACKWARD
2138 || lnum != wp->w_cursor.lnum
2139 || (lnum == wp->w_cursor.lnum
2140 && (wrapped
2141 || (colnr_T)(curline ? p - buf + len
2142 : p - buf)
2143 > wp->w_cursor.col)))
2145 # ifdef FEAT_SYN_HL
2146 if (has_syntax)
2148 col = (int)(p - buf);
2149 (void)syn_get_id(wp, lnum, (colnr_T)col,
2150 FALSE, &can_spell, FALSE);
2151 if (!can_spell)
2152 attr = HLF_COUNT;
2154 else
2155 #endif
2156 can_spell = TRUE;
2158 if (can_spell)
2160 found_one = TRUE;
2161 found_pos.lnum = lnum;
2162 found_pos.col = (int)(p - buf);
2163 #ifdef FEAT_VIRTUALEDIT
2164 found_pos.coladd = 0;
2165 #endif
2166 if (dir == FORWARD)
2168 /* No need to search further. */
2169 wp->w_cursor = found_pos;
2170 vim_free(buf);
2171 if (attrp != NULL)
2172 *attrp = attr;
2173 return len;
2175 else if (curline)
2176 /* Insert mode completion: put cursor after
2177 * the bad word. */
2178 found_pos.col += len;
2179 found_len = len;
2182 else
2183 found_one = TRUE;
2187 /* advance to character after the word */
2188 p += len;
2189 capcol -= len;
2192 if (dir == BACKWARD && found_pos.lnum != 0)
2194 /* Use the last match in the line (before the cursor). */
2195 wp->w_cursor = found_pos;
2196 vim_free(buf);
2197 return found_len;
2200 if (curline)
2201 break; /* only check cursor line */
2203 /* Advance to next line. */
2204 if (dir == BACKWARD)
2206 /* If we are back at the starting line and searched it again there
2207 * is no match, give up. */
2208 if (lnum == wp->w_cursor.lnum && wrapped)
2209 break;
2211 if (lnum > 1)
2212 --lnum;
2213 else if (!p_ws)
2214 break; /* at first line and 'nowrapscan' */
2215 else
2217 /* Wrap around to the end of the buffer. May search the
2218 * starting line again and accept the last match. */
2219 lnum = wp->w_buffer->b_ml.ml_line_count;
2220 wrapped = TRUE;
2221 if (!shortmess(SHM_SEARCH))
2222 give_warning((char_u *)_(top_bot_msg), TRUE);
2224 capcol = -1;
2226 else
2228 if (lnum < wp->w_buffer->b_ml.ml_line_count)
2229 ++lnum;
2230 else if (!p_ws)
2231 break; /* at first line and 'nowrapscan' */
2232 else
2234 /* Wrap around to the start of the buffer. May search the
2235 * starting line again and accept the first match. */
2236 lnum = 1;
2237 wrapped = TRUE;
2238 if (!shortmess(SHM_SEARCH))
2239 give_warning((char_u *)_(bot_top_msg), TRUE);
2242 /* If we are back at the starting line and there is no match then
2243 * give up. */
2244 if (lnum == wp->w_cursor.lnum && !found_one)
2245 break;
2247 /* Skip the characters at the start of the next line that were
2248 * included in a match crossing line boundaries. */
2249 if (attr == HLF_COUNT)
2250 skip = (int)(p - endp);
2251 else
2252 skip = 0;
2254 /* Capcol skips over the inserted space. */
2255 --capcol;
2257 /* But after empty line check first word in next line */
2258 if (*skipwhite(line) == NUL)
2259 capcol = 0;
2262 line_breakcheck();
2265 vim_free(buf);
2266 return 0;
2270 * For spell checking: concatenate the start of the following line "line" into
2271 * "buf", blanking-out special characters. Copy less then "maxlen" bytes.
2272 * Keep the blanks at the start of the next line, this is used in win_line()
2273 * to skip those bytes if the word was OK.
2275 void
2276 spell_cat_line(buf, line, maxlen)
2277 char_u *buf;
2278 char_u *line;
2279 int maxlen;
2281 char_u *p;
2282 int n;
2284 p = skipwhite(line);
2285 while (vim_strchr((char_u *)"*#/\"\t", *p) != NULL)
2286 p = skipwhite(p + 1);
2288 if (*p != NUL)
2290 /* Only worth concatenating if there is something else than spaces to
2291 * concatenate. */
2292 n = (int)(p - line) + 1;
2293 if (n < maxlen - 1)
2295 vim_memset(buf, ' ', n);
2296 vim_strncpy(buf + n, p, maxlen - 1 - n);
2302 * Structure used for the cookie argument of do_in_runtimepath().
2304 typedef struct spelload_S
2306 char_u sl_lang[MAXWLEN + 1]; /* language name */
2307 slang_T *sl_slang; /* resulting slang_T struct */
2308 int sl_nobreak; /* NOBREAK language found */
2309 } spelload_T;
2312 * Load word list(s) for "lang" from Vim spell file(s).
2313 * "lang" must be the language without the region: e.g., "en".
2315 static void
2316 spell_load_lang(lang)
2317 char_u *lang;
2319 char_u fname_enc[85];
2320 int r;
2321 spelload_T sl;
2322 #ifdef FEAT_AUTOCMD
2323 int round;
2324 #endif
2326 /* Copy the language name to pass it to spell_load_cb() as a cookie.
2327 * It's truncated when an error is detected. */
2328 STRCPY(sl.sl_lang, lang);
2329 sl.sl_slang = NULL;
2330 sl.sl_nobreak = FALSE;
2332 #ifdef FEAT_AUTOCMD
2333 /* We may retry when no spell file is found for the language, an
2334 * autocommand may load it then. */
2335 for (round = 1; round <= 2; ++round)
2336 #endif
2339 * Find the first spell file for "lang" in 'runtimepath' and load it.
2341 vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,
2342 "spell/%s.%s.spl", lang, spell_enc());
2343 r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl);
2345 if (r == FAIL && *sl.sl_lang != NUL)
2347 /* Try loading the ASCII version. */
2348 vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,
2349 "spell/%s.ascii.spl", lang);
2350 r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl);
2352 #ifdef FEAT_AUTOCMD
2353 if (r == FAIL && *sl.sl_lang != NUL && round == 1
2354 && apply_autocmds(EVENT_SPELLFILEMISSING, lang,
2355 curbuf->b_fname, FALSE, curbuf))
2356 continue;
2357 break;
2358 #endif
2360 #ifdef FEAT_AUTOCMD
2361 break;
2362 #endif
2365 if (r == FAIL)
2367 smsg((char_u *)_("Warning: Cannot find word list \"%s.%s.spl\" or \"%s.ascii.spl\""),
2368 lang, spell_enc(), lang);
2370 else if (sl.sl_slang != NULL)
2372 /* At least one file was loaded, now load ALL the additions. */
2373 STRCPY(fname_enc + STRLEN(fname_enc) - 3, "add.spl");
2374 do_in_runtimepath(fname_enc, TRUE, spell_load_cb, &sl);
2379 * Return the encoding used for spell checking: Use 'encoding', except that we
2380 * use "latin1" for "latin9". And limit to 60 characters (just in case).
2382 static char_u *
2383 spell_enc()
2386 #ifdef FEAT_MBYTE
2387 if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0)
2388 return p_enc;
2389 #endif
2390 return (char_u *)"latin1";
2394 * Get the name of the .spl file for the internal wordlist into
2395 * "fname[MAXPATHL]".
2397 static void
2398 int_wordlist_spl(fname)
2399 char_u *fname;
2401 vim_snprintf((char *)fname, MAXPATHL, "%s.%s.spl",
2402 int_wordlist, spell_enc());
2406 * Allocate a new slang_T for language "lang". "lang" can be NULL.
2407 * Caller must fill "sl_next".
2409 static slang_T *
2410 slang_alloc(lang)
2411 char_u *lang;
2413 slang_T *lp;
2415 lp = (slang_T *)alloc_clear(sizeof(slang_T));
2416 if (lp != NULL)
2418 if (lang != NULL)
2419 lp->sl_name = vim_strsave(lang);
2420 ga_init2(&lp->sl_rep, sizeof(fromto_T), 10);
2421 ga_init2(&lp->sl_repsal, sizeof(fromto_T), 10);
2422 lp->sl_compmax = MAXWLEN;
2423 lp->sl_compsylmax = MAXWLEN;
2424 hash_init(&lp->sl_wordcount);
2427 return lp;
2431 * Free the contents of an slang_T and the structure itself.
2433 static void
2434 slang_free(lp)
2435 slang_T *lp;
2437 vim_free(lp->sl_name);
2438 vim_free(lp->sl_fname);
2439 slang_clear(lp);
2440 vim_free(lp);
2444 * Clear an slang_T so that the file can be reloaded.
2446 static void
2447 slang_clear(lp)
2448 slang_T *lp;
2450 garray_T *gap;
2451 fromto_T *ftp;
2452 salitem_T *smp;
2453 int i;
2454 int round;
2456 vim_free(lp->sl_fbyts);
2457 lp->sl_fbyts = NULL;
2458 vim_free(lp->sl_kbyts);
2459 lp->sl_kbyts = NULL;
2460 vim_free(lp->sl_pbyts);
2461 lp->sl_pbyts = NULL;
2463 vim_free(lp->sl_fidxs);
2464 lp->sl_fidxs = NULL;
2465 vim_free(lp->sl_kidxs);
2466 lp->sl_kidxs = NULL;
2467 vim_free(lp->sl_pidxs);
2468 lp->sl_pidxs = NULL;
2470 for (round = 1; round <= 2; ++round)
2472 gap = round == 1 ? &lp->sl_rep : &lp->sl_repsal;
2473 while (gap->ga_len > 0)
2475 ftp = &((fromto_T *)gap->ga_data)[--gap->ga_len];
2476 vim_free(ftp->ft_from);
2477 vim_free(ftp->ft_to);
2479 ga_clear(gap);
2482 gap = &lp->sl_sal;
2483 if (lp->sl_sofo)
2485 /* "ga_len" is set to 1 without adding an item for latin1 */
2486 if (gap->ga_data != NULL)
2487 /* SOFOFROM and SOFOTO items: free lists of wide characters. */
2488 for (i = 0; i < gap->ga_len; ++i)
2489 vim_free(((int **)gap->ga_data)[i]);
2491 else
2492 /* SAL items: free salitem_T items */
2493 while (gap->ga_len > 0)
2495 smp = &((salitem_T *)gap->ga_data)[--gap->ga_len];
2496 vim_free(smp->sm_lead);
2497 /* Don't free sm_oneof and sm_rules, they point into sm_lead. */
2498 vim_free(smp->sm_to);
2499 #ifdef FEAT_MBYTE
2500 vim_free(smp->sm_lead_w);
2501 vim_free(smp->sm_oneof_w);
2502 vim_free(smp->sm_to_w);
2503 #endif
2505 ga_clear(gap);
2507 for (i = 0; i < lp->sl_prefixcnt; ++i)
2508 vim_free(lp->sl_prefprog[i]);
2509 lp->sl_prefixcnt = 0;
2510 vim_free(lp->sl_prefprog);
2511 lp->sl_prefprog = NULL;
2513 vim_free(lp->sl_info);
2514 lp->sl_info = NULL;
2516 vim_free(lp->sl_midword);
2517 lp->sl_midword = NULL;
2519 vim_free(lp->sl_compprog);
2520 vim_free(lp->sl_compstartflags);
2521 vim_free(lp->sl_compallflags);
2522 lp->sl_compprog = NULL;
2523 lp->sl_compstartflags = NULL;
2524 lp->sl_compallflags = NULL;
2526 vim_free(lp->sl_syllable);
2527 lp->sl_syllable = NULL;
2528 ga_clear(&lp->sl_syl_items);
2530 ga_clear_strings(&lp->sl_comppat);
2532 hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF);
2533 hash_init(&lp->sl_wordcount);
2535 #ifdef FEAT_MBYTE
2536 hash_clear_all(&lp->sl_map_hash, 0);
2537 #endif
2539 /* Clear info from .sug file. */
2540 slang_clear_sug(lp);
2542 lp->sl_compmax = MAXWLEN;
2543 lp->sl_compminlen = 0;
2544 lp->sl_compsylmax = MAXWLEN;
2545 lp->sl_regions[0] = NUL;
2549 * Clear the info from the .sug file in "lp".
2551 static void
2552 slang_clear_sug(lp)
2553 slang_T *lp;
2555 vim_free(lp->sl_sbyts);
2556 lp->sl_sbyts = NULL;
2557 vim_free(lp->sl_sidxs);
2558 lp->sl_sidxs = NULL;
2559 close_spellbuf(lp->sl_sugbuf);
2560 lp->sl_sugbuf = NULL;
2561 lp->sl_sugloaded = FALSE;
2562 lp->sl_sugtime = 0;
2566 * Load one spell file and store the info into a slang_T.
2567 * Invoked through do_in_runtimepath().
2569 static void
2570 spell_load_cb(fname, cookie)
2571 char_u *fname;
2572 void *cookie;
2574 spelload_T *slp = (spelload_T *)cookie;
2575 slang_T *slang;
2577 slang = spell_load_file(fname, slp->sl_lang, NULL, FALSE);
2578 if (slang != NULL)
2580 /* When a previously loaded file has NOBREAK also use it for the
2581 * ".add" files. */
2582 if (slp->sl_nobreak && slang->sl_add)
2583 slang->sl_nobreak = TRUE;
2584 else if (slang->sl_nobreak)
2585 slp->sl_nobreak = TRUE;
2587 slp->sl_slang = slang;
2592 * Load one spell file and store the info into a slang_T.
2594 * This is invoked in three ways:
2595 * - From spell_load_cb() to load a spell file for the first time. "lang" is
2596 * the language name, "old_lp" is NULL. Will allocate an slang_T.
2597 * - To reload a spell file that was changed. "lang" is NULL and "old_lp"
2598 * points to the existing slang_T.
2599 * - Just after writing a .spl file; it's read back to produce the .sug file.
2600 * "old_lp" is NULL and "lang" is NULL. Will allocate an slang_T.
2602 * Returns the slang_T the spell file was loaded into. NULL for error.
2604 static slang_T *
2605 spell_load_file(fname, lang, old_lp, silent)
2606 char_u *fname;
2607 char_u *lang;
2608 slang_T *old_lp;
2609 int silent; /* no error if file doesn't exist */
2611 FILE *fd;
2612 char_u buf[VIMSPELLMAGICL];
2613 char_u *p;
2614 int i;
2615 int n;
2616 int len;
2617 char_u *save_sourcing_name = sourcing_name;
2618 linenr_T save_sourcing_lnum = sourcing_lnum;
2619 slang_T *lp = NULL;
2620 int c = 0;
2621 int res;
2623 fd = mch_fopen((char *)fname, "r");
2624 if (fd == NULL)
2626 if (!silent)
2627 EMSG2(_(e_notopen), fname);
2628 else if (p_verbose > 2)
2630 verbose_enter();
2631 smsg((char_u *)e_notopen, fname);
2632 verbose_leave();
2634 goto endFAIL;
2636 if (p_verbose > 2)
2638 verbose_enter();
2639 smsg((char_u *)_("Reading spell file \"%s\""), fname);
2640 verbose_leave();
2643 if (old_lp == NULL)
2645 lp = slang_alloc(lang);
2646 if (lp == NULL)
2647 goto endFAIL;
2649 /* Remember the file name, used to reload the file when it's updated. */
2650 lp->sl_fname = vim_strsave(fname);
2651 if (lp->sl_fname == NULL)
2652 goto endFAIL;
2654 /* Check for .add.spl. */
2655 lp->sl_add = strstr((char *)gettail(fname), ".add.") != NULL;
2657 else
2658 lp = old_lp;
2660 /* Set sourcing_name, so that error messages mention the file name. */
2661 sourcing_name = fname;
2662 sourcing_lnum = 0;
2665 * <HEADER>: <fileID>
2667 for (i = 0; i < VIMSPELLMAGICL; ++i)
2668 buf[i] = getc(fd); /* <fileID> */
2669 if (STRNCMP(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0)
2671 EMSG(_("E757: This does not look like a spell file"));
2672 goto endFAIL;
2674 c = getc(fd); /* <versionnr> */
2675 if (c < VIMSPELLVERSION)
2677 EMSG(_("E771: Old spell file, needs to be updated"));
2678 goto endFAIL;
2680 else if (c > VIMSPELLVERSION)
2682 EMSG(_("E772: Spell file is for newer version of Vim"));
2683 goto endFAIL;
2688 * <SECTIONS>: <section> ... <sectionend>
2689 * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
2691 for (;;)
2693 n = getc(fd); /* <sectionID> or <sectionend> */
2694 if (n == SN_END)
2695 break;
2696 c = getc(fd); /* <sectionflags> */
2697 len = get4c(fd); /* <sectionlen> */
2698 if (len < 0)
2699 goto truncerr;
2701 res = 0;
2702 switch (n)
2704 case SN_INFO:
2705 lp->sl_info = read_string(fd, len); /* <infotext> */
2706 if (lp->sl_info == NULL)
2707 goto endFAIL;
2708 break;
2710 case SN_REGION:
2711 res = read_region_section(fd, lp, len);
2712 break;
2714 case SN_CHARFLAGS:
2715 res = read_charflags_section(fd);
2716 break;
2718 case SN_MIDWORD:
2719 lp->sl_midword = read_string(fd, len); /* <midword> */
2720 if (lp->sl_midword == NULL)
2721 goto endFAIL;
2722 break;
2724 case SN_PREFCOND:
2725 res = read_prefcond_section(fd, lp);
2726 break;
2728 case SN_REP:
2729 res = read_rep_section(fd, &lp->sl_rep, lp->sl_rep_first);
2730 break;
2732 case SN_REPSAL:
2733 res = read_rep_section(fd, &lp->sl_repsal, lp->sl_repsal_first);
2734 break;
2736 case SN_SAL:
2737 res = read_sal_section(fd, lp);
2738 break;
2740 case SN_SOFO:
2741 res = read_sofo_section(fd, lp);
2742 break;
2744 case SN_MAP:
2745 p = read_string(fd, len); /* <mapstr> */
2746 if (p == NULL)
2747 goto endFAIL;
2748 set_map_str(lp, p);
2749 vim_free(p);
2750 break;
2752 case SN_WORDS:
2753 res = read_words_section(fd, lp, len);
2754 break;
2756 case SN_SUGFILE:
2757 lp->sl_sugtime = get8c(fd); /* <timestamp> */
2758 break;
2760 case SN_NOSPLITSUGS:
2761 lp->sl_nosplitsugs = TRUE; /* <timestamp> */
2762 break;
2764 case SN_COMPOUND:
2765 res = read_compound(fd, lp, len);
2766 break;
2768 case SN_NOBREAK:
2769 lp->sl_nobreak = TRUE;
2770 break;
2772 case SN_SYLLABLE:
2773 lp->sl_syllable = read_string(fd, len); /* <syllable> */
2774 if (lp->sl_syllable == NULL)
2775 goto endFAIL;
2776 if (init_syl_tab(lp) == FAIL)
2777 goto endFAIL;
2778 break;
2780 default:
2781 /* Unsupported section. When it's required give an error
2782 * message. When it's not required skip the contents. */
2783 if (c & SNF_REQUIRED)
2785 EMSG(_("E770: Unsupported section in spell file"));
2786 goto endFAIL;
2788 while (--len >= 0)
2789 if (getc(fd) < 0)
2790 goto truncerr;
2791 break;
2793 someerror:
2794 if (res == SP_FORMERROR)
2796 EMSG(_(e_format));
2797 goto endFAIL;
2799 if (res == SP_TRUNCERROR)
2801 truncerr:
2802 EMSG(_(e_spell_trunc));
2803 goto endFAIL;
2805 if (res == SP_OTHERERROR)
2806 goto endFAIL;
2809 /* <LWORDTREE> */
2810 res = spell_read_tree(fd, &lp->sl_fbyts, &lp->sl_fidxs, FALSE, 0);
2811 if (res != 0)
2812 goto someerror;
2814 /* <KWORDTREE> */
2815 res = spell_read_tree(fd, &lp->sl_kbyts, &lp->sl_kidxs, FALSE, 0);
2816 if (res != 0)
2817 goto someerror;
2819 /* <PREFIXTREE> */
2820 res = spell_read_tree(fd, &lp->sl_pbyts, &lp->sl_pidxs, TRUE,
2821 lp->sl_prefixcnt);
2822 if (res != 0)
2823 goto someerror;
2825 /* For a new file link it in the list of spell files. */
2826 if (old_lp == NULL && lang != NULL)
2828 lp->sl_next = first_lang;
2829 first_lang = lp;
2832 goto endOK;
2834 endFAIL:
2835 if (lang != NULL)
2836 /* truncating the name signals the error to spell_load_lang() */
2837 *lang = NUL;
2838 if (lp != NULL && old_lp == NULL)
2839 slang_free(lp);
2840 lp = NULL;
2842 endOK:
2843 if (fd != NULL)
2844 fclose(fd);
2845 sourcing_name = save_sourcing_name;
2846 sourcing_lnum = save_sourcing_lnum;
2848 return lp;
2852 * Read 2 bytes from "fd" and turn them into an int, MSB first.
2854 static int
2855 get2c(fd)
2856 FILE *fd;
2858 long n;
2860 n = getc(fd);
2861 n = (n << 8) + getc(fd);
2862 return n;
2866 * Read 3 bytes from "fd" and turn them into an int, MSB first.
2868 static int
2869 get3c(fd)
2870 FILE *fd;
2872 long n;
2874 n = getc(fd);
2875 n = (n << 8) + getc(fd);
2876 n = (n << 8) + getc(fd);
2877 return n;
2881 * Read 4 bytes from "fd" and turn them into an int, MSB first.
2883 static int
2884 get4c(fd)
2885 FILE *fd;
2887 long n;
2889 n = getc(fd);
2890 n = (n << 8) + getc(fd);
2891 n = (n << 8) + getc(fd);
2892 n = (n << 8) + getc(fd);
2893 return n;
2897 * Read 8 bytes from "fd" and turn them into a time_t, MSB first.
2899 static time_t
2900 get8c(fd)
2901 FILE *fd;
2903 time_t n = 0;
2904 int i;
2906 for (i = 0; i < 8; ++i)
2907 n = (n << 8) + getc(fd);
2908 return n;
2912 * Read a length field from "fd" in "cnt_bytes" bytes.
2913 * Allocate memory, read the string into it and add a NUL at the end.
2914 * Returns NULL when the count is zero.
2915 * Sets "*cntp" to SP_*ERROR when there is an error, length of the result
2916 * otherwise.
2918 static char_u *
2919 read_cnt_string(fd, cnt_bytes, cntp)
2920 FILE *fd;
2921 int cnt_bytes;
2922 int *cntp;
2924 int cnt = 0;
2925 int i;
2926 char_u *str;
2928 /* read the length bytes, MSB first */
2929 for (i = 0; i < cnt_bytes; ++i)
2930 cnt = (cnt << 8) + getc(fd);
2931 if (cnt < 0)
2933 *cntp = SP_TRUNCERROR;
2934 return NULL;
2936 *cntp = cnt;
2937 if (cnt == 0)
2938 return NULL; /* nothing to read, return NULL */
2940 str = read_string(fd, cnt);
2941 if (str == NULL)
2942 *cntp = SP_OTHERERROR;
2943 return str;
2947 * Read a string of length "cnt" from "fd" into allocated memory.
2948 * Returns NULL when out of memory.
2950 static char_u *
2951 read_string(fd, cnt)
2952 FILE *fd;
2953 int cnt;
2955 char_u *str;
2956 int i;
2958 /* allocate memory */
2959 str = alloc((unsigned)cnt + 1);
2960 if (str != NULL)
2962 /* Read the string. Doesn't check for truncated file. */
2963 for (i = 0; i < cnt; ++i)
2964 str[i] = getc(fd);
2965 str[i] = NUL;
2967 return str;
2971 * Read SN_REGION: <regionname> ...
2972 * Return SP_*ERROR flags.
2974 static int
2975 read_region_section(fd, lp, len)
2976 FILE *fd;
2977 slang_T *lp;
2978 int len;
2980 int i;
2982 if (len > 16)
2983 return SP_FORMERROR;
2984 for (i = 0; i < len; ++i)
2985 lp->sl_regions[i] = getc(fd); /* <regionname> */
2986 lp->sl_regions[len] = NUL;
2987 return 0;
2991 * Read SN_CHARFLAGS section: <charflagslen> <charflags>
2992 * <folcharslen> <folchars>
2993 * Return SP_*ERROR flags.
2995 static int
2996 read_charflags_section(fd)
2997 FILE *fd;
2999 char_u *flags;
3000 char_u *fol;
3001 int flagslen, follen;
3003 /* <charflagslen> <charflags> */
3004 flags = read_cnt_string(fd, 1, &flagslen);
3005 if (flagslen < 0)
3006 return flagslen;
3008 /* <folcharslen> <folchars> */
3009 fol = read_cnt_string(fd, 2, &follen);
3010 if (follen < 0)
3012 vim_free(flags);
3013 return follen;
3016 /* Set the word-char flags and fill SPELL_ISUPPER() table. */
3017 if (flags != NULL && fol != NULL)
3018 set_spell_charflags(flags, flagslen, fol);
3020 vim_free(flags);
3021 vim_free(fol);
3023 /* When <charflagslen> is zero then <fcharlen> must also be zero. */
3024 if ((flags == NULL) != (fol == NULL))
3025 return SP_FORMERROR;
3026 return 0;
3030 * Read SN_PREFCOND section.
3031 * Return SP_*ERROR flags.
3033 static int
3034 read_prefcond_section(fd, lp)
3035 FILE *fd;
3036 slang_T *lp;
3038 int cnt;
3039 int i;
3040 int n;
3041 char_u *p;
3042 char_u buf[MAXWLEN + 1];
3044 /* <prefcondcnt> <prefcond> ... */
3045 cnt = get2c(fd); /* <prefcondcnt> */
3046 if (cnt <= 0)
3047 return SP_FORMERROR;
3049 lp->sl_prefprog = (regprog_T **)alloc_clear(
3050 (unsigned)sizeof(regprog_T *) * cnt);
3051 if (lp->sl_prefprog == NULL)
3052 return SP_OTHERERROR;
3053 lp->sl_prefixcnt = cnt;
3055 for (i = 0; i < cnt; ++i)
3057 /* <prefcond> : <condlen> <condstr> */
3058 n = getc(fd); /* <condlen> */
3059 if (n < 0 || n >= MAXWLEN)
3060 return SP_FORMERROR;
3062 /* When <condlen> is zero we have an empty condition. Otherwise
3063 * compile the regexp program used to check for the condition. */
3064 if (n > 0)
3066 buf[0] = '^'; /* always match at one position only */
3067 p = buf + 1;
3068 while (n-- > 0)
3069 *p++ = getc(fd); /* <condstr> */
3070 *p = NUL;
3071 lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC + RE_STRING);
3074 return 0;
3078 * Read REP or REPSAL items section from "fd": <repcount> <rep> ...
3079 * Return SP_*ERROR flags.
3081 static int
3082 read_rep_section(fd, gap, first)
3083 FILE *fd;
3084 garray_T *gap;
3085 short *first;
3087 int cnt;
3088 fromto_T *ftp;
3089 int i;
3091 cnt = get2c(fd); /* <repcount> */
3092 if (cnt < 0)
3093 return SP_TRUNCERROR;
3095 if (ga_grow(gap, cnt) == FAIL)
3096 return SP_OTHERERROR;
3098 /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */
3099 for (; gap->ga_len < cnt; ++gap->ga_len)
3101 ftp = &((fromto_T *)gap->ga_data)[gap->ga_len];
3102 ftp->ft_from = read_cnt_string(fd, 1, &i);
3103 if (i < 0)
3104 return i;
3105 if (i == 0)
3106 return SP_FORMERROR;
3107 ftp->ft_to = read_cnt_string(fd, 1, &i);
3108 if (i <= 0)
3110 vim_free(ftp->ft_from);
3111 if (i < 0)
3112 return i;
3113 return SP_FORMERROR;
3117 /* Fill the first-index table. */
3118 for (i = 0; i < 256; ++i)
3119 first[i] = -1;
3120 for (i = 0; i < gap->ga_len; ++i)
3122 ftp = &((fromto_T *)gap->ga_data)[i];
3123 if (first[*ftp->ft_from] == -1)
3124 first[*ftp->ft_from] = i;
3126 return 0;
3130 * Read SN_SAL section: <salflags> <salcount> <sal> ...
3131 * Return SP_*ERROR flags.
3133 static int
3134 read_sal_section(fd, slang)
3135 FILE *fd;
3136 slang_T *slang;
3138 int i;
3139 int cnt;
3140 garray_T *gap;
3141 salitem_T *smp;
3142 int ccnt;
3143 char_u *p;
3144 int c = NUL;
3146 slang->sl_sofo = FALSE;
3148 i = getc(fd); /* <salflags> */
3149 if (i & SAL_F0LLOWUP)
3150 slang->sl_followup = TRUE;
3151 if (i & SAL_COLLAPSE)
3152 slang->sl_collapse = TRUE;
3153 if (i & SAL_REM_ACCENTS)
3154 slang->sl_rem_accents = TRUE;
3156 cnt = get2c(fd); /* <salcount> */
3157 if (cnt < 0)
3158 return SP_TRUNCERROR;
3160 gap = &slang->sl_sal;
3161 ga_init2(gap, sizeof(salitem_T), 10);
3162 if (ga_grow(gap, cnt + 1) == FAIL)
3163 return SP_OTHERERROR;
3165 /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */
3166 for (; gap->ga_len < cnt; ++gap->ga_len)
3168 smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
3169 ccnt = getc(fd); /* <salfromlen> */
3170 if (ccnt < 0)
3171 return SP_TRUNCERROR;
3172 if ((p = alloc(ccnt + 2)) == NULL)
3173 return SP_OTHERERROR;
3174 smp->sm_lead = p;
3176 /* Read up to the first special char into sm_lead. */
3177 for (i = 0; i < ccnt; ++i)
3179 c = getc(fd); /* <salfrom> */
3180 if (vim_strchr((char_u *)"0123456789(-<^$", c) != NULL)
3181 break;
3182 *p++ = c;
3184 smp->sm_leadlen = (int)(p - smp->sm_lead);
3185 *p++ = NUL;
3187 /* Put (abc) chars in sm_oneof, if any. */
3188 if (c == '(')
3190 smp->sm_oneof = p;
3191 for (++i; i < ccnt; ++i)
3193 c = getc(fd); /* <salfrom> */
3194 if (c == ')')
3195 break;
3196 *p++ = c;
3198 *p++ = NUL;
3199 if (++i < ccnt)
3200 c = getc(fd);
3202 else
3203 smp->sm_oneof = NULL;
3205 /* Any following chars go in sm_rules. */
3206 smp->sm_rules = p;
3207 if (i < ccnt)
3208 /* store the char we got while checking for end of sm_lead */
3209 *p++ = c;
3210 for (++i; i < ccnt; ++i)
3211 *p++ = getc(fd); /* <salfrom> */
3212 *p++ = NUL;
3214 /* <saltolen> <salto> */
3215 smp->sm_to = read_cnt_string(fd, 1, &ccnt);
3216 if (ccnt < 0)
3218 vim_free(smp->sm_lead);
3219 return ccnt;
3222 #ifdef FEAT_MBYTE
3223 if (has_mbyte)
3225 /* convert the multi-byte strings to wide char strings */
3226 smp->sm_lead_w = mb_str2wide(smp->sm_lead);
3227 smp->sm_leadlen = mb_charlen(smp->sm_lead);
3228 if (smp->sm_oneof == NULL)
3229 smp->sm_oneof_w = NULL;
3230 else
3231 smp->sm_oneof_w = mb_str2wide(smp->sm_oneof);
3232 if (smp->sm_to == NULL)
3233 smp->sm_to_w = NULL;
3234 else
3235 smp->sm_to_w = mb_str2wide(smp->sm_to);
3236 if (smp->sm_lead_w == NULL
3237 || (smp->sm_oneof_w == NULL && smp->sm_oneof != NULL)
3238 || (smp->sm_to_w == NULL && smp->sm_to != NULL))
3240 vim_free(smp->sm_lead);
3241 vim_free(smp->sm_to);
3242 vim_free(smp->sm_lead_w);
3243 vim_free(smp->sm_oneof_w);
3244 vim_free(smp->sm_to_w);
3245 return SP_OTHERERROR;
3248 #endif
3251 if (gap->ga_len > 0)
3253 /* Add one extra entry to mark the end with an empty sm_lead. Avoids
3254 * that we need to check the index every time. */
3255 smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
3256 if ((p = alloc(1)) == NULL)
3257 return SP_OTHERERROR;
3258 p[0] = NUL;
3259 smp->sm_lead = p;
3260 smp->sm_leadlen = 0;
3261 smp->sm_oneof = NULL;
3262 smp->sm_rules = p;
3263 smp->sm_to = NULL;
3264 #ifdef FEAT_MBYTE
3265 if (has_mbyte)
3267 smp->sm_lead_w = mb_str2wide(smp->sm_lead);
3268 smp->sm_leadlen = 0;
3269 smp->sm_oneof_w = NULL;
3270 smp->sm_to_w = NULL;
3272 #endif
3273 ++gap->ga_len;
3276 /* Fill the first-index table. */
3277 set_sal_first(slang);
3279 return 0;
3283 * Read SN_WORDS: <word> ...
3284 * Return SP_*ERROR flags.
3286 static int
3287 read_words_section(fd, lp, len)
3288 FILE *fd;
3289 slang_T *lp;
3290 int len;
3292 int done = 0;
3293 int i;
3294 char_u word[MAXWLEN];
3296 while (done < len)
3298 /* Read one word at a time. */
3299 for (i = 0; ; ++i)
3301 word[i] = getc(fd);
3302 if (word[i] == NUL)
3303 break;
3304 if (i == MAXWLEN - 1)
3305 return SP_FORMERROR;
3308 /* Init the count to 10. */
3309 count_common_word(lp, word, -1, 10);
3310 done += i + 1;
3312 return 0;
3316 * Add a word to the hashtable of common words.
3317 * If it's already there then the counter is increased.
3319 static void
3320 count_common_word(lp, word, len, count)
3321 slang_T *lp;
3322 char_u *word;
3323 int len; /* word length, -1 for upto NUL */
3324 int count; /* 1 to count once, 10 to init */
3326 hash_T hash;
3327 hashitem_T *hi;
3328 wordcount_T *wc;
3329 char_u buf[MAXWLEN];
3330 char_u *p;
3332 if (len == -1)
3333 p = word;
3334 else
3336 vim_strncpy(buf, word, len);
3337 p = buf;
3340 hash = hash_hash(p);
3341 hi = hash_lookup(&lp->sl_wordcount, p, hash);
3342 if (HASHITEM_EMPTY(hi))
3344 wc = (wordcount_T *)alloc((unsigned)(sizeof(wordcount_T) + STRLEN(p)));
3345 if (wc == NULL)
3346 return;
3347 STRCPY(wc->wc_word, p);
3348 wc->wc_count = count;
3349 hash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash);
3351 else
3353 wc = HI2WC(hi);
3354 if ((wc->wc_count += count) < (unsigned)count) /* check for overflow */
3355 wc->wc_count = MAXWORDCOUNT;
3360 * Adjust the score of common words.
3362 static int
3363 score_wordcount_adj(slang, score, word, split)
3364 slang_T *slang;
3365 int score;
3366 char_u *word;
3367 int split; /* word was split, less bonus */
3369 hashitem_T *hi;
3370 wordcount_T *wc;
3371 int bonus;
3372 int newscore;
3374 hi = hash_find(&slang->sl_wordcount, word);
3375 if (!HASHITEM_EMPTY(hi))
3377 wc = HI2WC(hi);
3378 if (wc->wc_count < SCORE_THRES2)
3379 bonus = SCORE_COMMON1;
3380 else if (wc->wc_count < SCORE_THRES3)
3381 bonus = SCORE_COMMON2;
3382 else
3383 bonus = SCORE_COMMON3;
3384 if (split)
3385 newscore = score - bonus / 2;
3386 else
3387 newscore = score - bonus;
3388 if (newscore < 0)
3389 return 0;
3390 return newscore;
3392 return score;
3396 * SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
3397 * Return SP_*ERROR flags.
3399 static int
3400 read_sofo_section(fd, slang)
3401 FILE *fd;
3402 slang_T *slang;
3404 int cnt;
3405 char_u *from, *to;
3406 int res;
3408 slang->sl_sofo = TRUE;
3410 /* <sofofromlen> <sofofrom> */
3411 from = read_cnt_string(fd, 2, &cnt);
3412 if (cnt < 0)
3413 return cnt;
3415 /* <sofotolen> <sofoto> */
3416 to = read_cnt_string(fd, 2, &cnt);
3417 if (cnt < 0)
3419 vim_free(from);
3420 return cnt;
3423 /* Store the info in slang->sl_sal and/or slang->sl_sal_first. */
3424 if (from != NULL && to != NULL)
3425 res = set_sofo(slang, from, to);
3426 else if (from != NULL || to != NULL)
3427 res = SP_FORMERROR; /* only one of two strings is an error */
3428 else
3429 res = 0;
3431 vim_free(from);
3432 vim_free(to);
3433 return res;
3437 * Read the compound section from the .spl file:
3438 * <compmax> <compminlen> <compsylmax> <compoptions> <compflags>
3439 * Returns SP_*ERROR flags.
3441 static int
3442 read_compound(fd, slang, len)
3443 FILE *fd;
3444 slang_T *slang;
3445 int len;
3447 int todo = len;
3448 int c;
3449 int atstart;
3450 char_u *pat;
3451 char_u *pp;
3452 char_u *cp;
3453 char_u *ap;
3454 int cnt;
3455 garray_T *gap;
3457 if (todo < 2)
3458 return SP_FORMERROR; /* need at least two bytes */
3460 --todo;
3461 c = getc(fd); /* <compmax> */
3462 if (c < 2)
3463 c = MAXWLEN;
3464 slang->sl_compmax = c;
3466 --todo;
3467 c = getc(fd); /* <compminlen> */
3468 if (c < 1)
3469 c = 0;
3470 slang->sl_compminlen = c;
3472 --todo;
3473 c = getc(fd); /* <compsylmax> */
3474 if (c < 1)
3475 c = MAXWLEN;
3476 slang->sl_compsylmax = c;
3478 c = getc(fd); /* <compoptions> */
3479 if (c != 0)
3480 ungetc(c, fd); /* be backwards compatible with Vim 7.0b */
3481 else
3483 --todo;
3484 c = getc(fd); /* only use the lower byte for now */
3485 --todo;
3486 slang->sl_compoptions = c;
3488 gap = &slang->sl_comppat;
3489 c = get2c(fd); /* <comppatcount> */
3490 todo -= 2;
3491 ga_init2(gap, sizeof(char_u *), c);
3492 if (ga_grow(gap, c) == OK)
3493 while (--c >= 0)
3495 ((char_u **)(gap->ga_data))[gap->ga_len++] =
3496 read_cnt_string(fd, 1, &cnt);
3497 /* <comppatlen> <comppattext> */
3498 if (cnt < 0)
3499 return cnt;
3500 todo -= cnt + 1;
3503 if (todo < 0)
3504 return SP_FORMERROR;
3506 /* Turn the COMPOUNDRULE items into a regexp pattern:
3507 * "a[bc]/a*b+" -> "^\(a[bc]\|a*b\+\)$".
3508 * Inserting backslashes may double the length, "^\(\)$<Nul>" is 7 bytes.
3509 * Conversion to utf-8 may double the size. */
3510 c = todo * 2 + 7;
3511 #ifdef FEAT_MBYTE
3512 if (enc_utf8)
3513 c += todo * 2;
3514 #endif
3515 pat = alloc((unsigned)c);
3516 if (pat == NULL)
3517 return SP_OTHERERROR;
3519 /* We also need a list of all flags that can appear at the start and one
3520 * for all flags. */
3521 cp = alloc(todo + 1);
3522 if (cp == NULL)
3524 vim_free(pat);
3525 return SP_OTHERERROR;
3527 slang->sl_compstartflags = cp;
3528 *cp = NUL;
3530 ap = alloc(todo + 1);
3531 if (ap == NULL)
3533 vim_free(pat);
3534 return SP_OTHERERROR;
3536 slang->sl_compallflags = ap;
3537 *ap = NUL;
3539 pp = pat;
3540 *pp++ = '^';
3541 *pp++ = '\\';
3542 *pp++ = '(';
3544 atstart = 1;
3545 while (todo-- > 0)
3547 c = getc(fd); /* <compflags> */
3549 /* Add all flags to "sl_compallflags". */
3550 if (vim_strchr((char_u *)"+*[]/", c) == NULL
3551 && !byte_in_str(slang->sl_compallflags, c))
3553 *ap++ = c;
3554 *ap = NUL;
3557 if (atstart != 0)
3559 /* At start of item: copy flags to "sl_compstartflags". For a
3560 * [abc] item set "atstart" to 2 and copy up to the ']'. */
3561 if (c == '[')
3562 atstart = 2;
3563 else if (c == ']')
3564 atstart = 0;
3565 else
3567 if (!byte_in_str(slang->sl_compstartflags, c))
3569 *cp++ = c;
3570 *cp = NUL;
3572 if (atstart == 1)
3573 atstart = 0;
3576 if (c == '/') /* slash separates two items */
3578 *pp++ = '\\';
3579 *pp++ = '|';
3580 atstart = 1;
3582 else /* normal char, "[abc]" and '*' are copied as-is */
3584 if (c == '+' || c == '~')
3585 *pp++ = '\\'; /* "a+" becomes "a\+" */
3586 #ifdef FEAT_MBYTE
3587 if (enc_utf8)
3588 pp += mb_char2bytes(c, pp);
3589 else
3590 #endif
3591 *pp++ = c;
3595 *pp++ = '\\';
3596 *pp++ = ')';
3597 *pp++ = '$';
3598 *pp = NUL;
3600 slang->sl_compprog = vim_regcomp(pat, RE_MAGIC + RE_STRING + RE_STRICT);
3601 vim_free(pat);
3602 if (slang->sl_compprog == NULL)
3603 return SP_FORMERROR;
3605 return 0;
3609 * Return TRUE if byte "n" appears in "str".
3610 * Like strchr() but independent of locale.
3612 static int
3613 byte_in_str(str, n)
3614 char_u *str;
3615 int n;
3617 char_u *p;
3619 for (p = str; *p != NUL; ++p)
3620 if (*p == n)
3621 return TRUE;
3622 return FALSE;
3625 #define SY_MAXLEN 30
3626 typedef struct syl_item_S
3628 char_u sy_chars[SY_MAXLEN]; /* the sequence of chars */
3629 int sy_len;
3630 } syl_item_T;
3633 * Truncate "slang->sl_syllable" at the first slash and put the following items
3634 * in "slang->sl_syl_items".
3636 static int
3637 init_syl_tab(slang)
3638 slang_T *slang;
3640 char_u *p;
3641 char_u *s;
3642 int l;
3643 syl_item_T *syl;
3645 ga_init2(&slang->sl_syl_items, sizeof(syl_item_T), 4);
3646 p = vim_strchr(slang->sl_syllable, '/');
3647 while (p != NULL)
3649 *p++ = NUL;
3650 if (*p == NUL) /* trailing slash */
3651 break;
3652 s = p;
3653 p = vim_strchr(p, '/');
3654 if (p == NULL)
3655 l = (int)STRLEN(s);
3656 else
3657 l = (int)(p - s);
3658 if (l >= SY_MAXLEN)
3659 return SP_FORMERROR;
3660 if (ga_grow(&slang->sl_syl_items, 1) == FAIL)
3661 return SP_OTHERERROR;
3662 syl = ((syl_item_T *)slang->sl_syl_items.ga_data)
3663 + slang->sl_syl_items.ga_len++;
3664 vim_strncpy(syl->sy_chars, s, l);
3665 syl->sy_len = l;
3667 return OK;
3671 * Count the number of syllables in "word".
3672 * When "word" contains spaces the syllables after the last space are counted.
3673 * Returns zero if syllables are not defines.
3675 static int
3676 count_syllables(slang, word)
3677 slang_T *slang;
3678 char_u *word;
3680 int cnt = 0;
3681 int skip = FALSE;
3682 char_u *p;
3683 int len;
3684 int i;
3685 syl_item_T *syl;
3686 int c;
3688 if (slang->sl_syllable == NULL)
3689 return 0;
3691 for (p = word; *p != NUL; p += len)
3693 /* When running into a space reset counter. */
3694 if (*p == ' ')
3696 len = 1;
3697 cnt = 0;
3698 continue;
3701 /* Find longest match of syllable items. */
3702 len = 0;
3703 for (i = 0; i < slang->sl_syl_items.ga_len; ++i)
3705 syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i;
3706 if (syl->sy_len > len
3707 && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0)
3708 len = syl->sy_len;
3710 if (len != 0) /* found a match, count syllable */
3712 ++cnt;
3713 skip = FALSE;
3715 else
3717 /* No recognized syllable item, at least a syllable char then? */
3718 #ifdef FEAT_MBYTE
3719 c = mb_ptr2char(p);
3720 len = (*mb_ptr2len)(p);
3721 #else
3722 c = *p;
3723 len = 1;
3724 #endif
3725 if (vim_strchr(slang->sl_syllable, c) == NULL)
3726 skip = FALSE; /* No, search for next syllable */
3727 else if (!skip)
3729 ++cnt; /* Yes, count it */
3730 skip = TRUE; /* don't count following syllable chars */
3734 return cnt;
3738 * Set the SOFOFROM and SOFOTO items in language "lp".
3739 * Returns SP_*ERROR flags when there is something wrong.
3741 static int
3742 set_sofo(lp, from, to)
3743 slang_T *lp;
3744 char_u *from;
3745 char_u *to;
3747 int i;
3749 #ifdef FEAT_MBYTE
3750 garray_T *gap;
3751 char_u *s;
3752 char_u *p;
3753 int c;
3754 int *inp;
3756 if (has_mbyte)
3758 /* Use "sl_sal" as an array with 256 pointers to a list of wide
3759 * characters. The index is the low byte of the character.
3760 * The list contains from-to pairs with a terminating NUL.
3761 * sl_sal_first[] is used for latin1 "from" characters. */
3762 gap = &lp->sl_sal;
3763 ga_init2(gap, sizeof(int *), 1);
3764 if (ga_grow(gap, 256) == FAIL)
3765 return SP_OTHERERROR;
3766 vim_memset(gap->ga_data, 0, sizeof(int *) * 256);
3767 gap->ga_len = 256;
3769 /* First count the number of items for each list. Temporarily use
3770 * sl_sal_first[] for this. */
3771 for (p = from, s = to; *p != NUL && *s != NUL; )
3773 c = mb_cptr2char_adv(&p);
3774 mb_cptr_adv(s);
3775 if (c >= 256)
3776 ++lp->sl_sal_first[c & 0xff];
3778 if (*p != NUL || *s != NUL) /* lengths differ */
3779 return SP_FORMERROR;
3781 /* Allocate the lists. */
3782 for (i = 0; i < 256; ++i)
3783 if (lp->sl_sal_first[i] > 0)
3785 p = alloc(sizeof(int) * (lp->sl_sal_first[i] * 2 + 1));
3786 if (p == NULL)
3787 return SP_OTHERERROR;
3788 ((int **)gap->ga_data)[i] = (int *)p;
3789 *(int *)p = 0;
3792 /* Put the characters up to 255 in sl_sal_first[] the rest in a sl_sal
3793 * list. */
3794 vim_memset(lp->sl_sal_first, 0, sizeof(salfirst_T) * 256);
3795 for (p = from, s = to; *p != NUL && *s != NUL; )
3797 c = mb_cptr2char_adv(&p);
3798 i = mb_cptr2char_adv(&s);
3799 if (c >= 256)
3801 /* Append the from-to chars at the end of the list with
3802 * the low byte. */
3803 inp = ((int **)gap->ga_data)[c & 0xff];
3804 while (*inp != 0)
3805 ++inp;
3806 *inp++ = c; /* from char */
3807 *inp++ = i; /* to char */
3808 *inp++ = NUL; /* NUL at the end */
3810 else
3811 /* mapping byte to char is done in sl_sal_first[] */
3812 lp->sl_sal_first[c] = i;
3815 else
3816 #endif
3818 /* mapping bytes to bytes is done in sl_sal_first[] */
3819 if (STRLEN(from) != STRLEN(to))
3820 return SP_FORMERROR;
3822 for (i = 0; to[i] != NUL; ++i)
3823 lp->sl_sal_first[from[i]] = to[i];
3824 lp->sl_sal.ga_len = 1; /* indicates we have soundfolding */
3827 return 0;
3831 * Fill the first-index table for "lp".
3833 static void
3834 set_sal_first(lp)
3835 slang_T *lp;
3837 salfirst_T *sfirst;
3838 int i;
3839 salitem_T *smp;
3840 int c;
3841 garray_T *gap = &lp->sl_sal;
3843 sfirst = lp->sl_sal_first;
3844 for (i = 0; i < 256; ++i)
3845 sfirst[i] = -1;
3846 smp = (salitem_T *)gap->ga_data;
3847 for (i = 0; i < gap->ga_len; ++i)
3849 #ifdef FEAT_MBYTE
3850 if (has_mbyte)
3851 /* Use the lowest byte of the first character. For latin1 it's
3852 * the character, for other encodings it should differ for most
3853 * characters. */
3854 c = *smp[i].sm_lead_w & 0xff;
3855 else
3856 #endif
3857 c = *smp[i].sm_lead;
3858 if (sfirst[c] == -1)
3860 sfirst[c] = i;
3861 #ifdef FEAT_MBYTE
3862 if (has_mbyte)
3864 int n;
3866 /* Make sure all entries with this byte are following each
3867 * other. Move the ones that are in the wrong position. Do
3868 * keep the same ordering! */
3869 while (i + 1 < gap->ga_len
3870 && (*smp[i + 1].sm_lead_w & 0xff) == c)
3871 /* Skip over entry with same index byte. */
3872 ++i;
3874 for (n = 1; i + n < gap->ga_len; ++n)
3875 if ((*smp[i + n].sm_lead_w & 0xff) == c)
3877 salitem_T tsal;
3879 /* Move entry with same index byte after the entries
3880 * we already found. */
3881 ++i;
3882 --n;
3883 tsal = smp[i + n];
3884 mch_memmove(smp + i + 1, smp + i,
3885 sizeof(salitem_T) * n);
3886 smp[i] = tsal;
3889 #endif
3894 #ifdef FEAT_MBYTE
3896 * Turn a multi-byte string into a wide character string.
3897 * Return it in allocated memory (NULL for out-of-memory)
3899 static int *
3900 mb_str2wide(s)
3901 char_u *s;
3903 int *res;
3904 char_u *p;
3905 int i = 0;
3907 res = (int *)alloc(sizeof(int) * (mb_charlen(s) + 1));
3908 if (res != NULL)
3910 for (p = s; *p != NUL; )
3911 res[i++] = mb_ptr2char_adv(&p);
3912 res[i] = NUL;
3914 return res;
3916 #endif
3919 * Read a tree from the .spl or .sug file.
3920 * Allocates the memory and stores pointers in "bytsp" and "idxsp".
3921 * This is skipped when the tree has zero length.
3922 * Returns zero when OK, SP_ value for an error.
3924 static int
3925 spell_read_tree(fd, bytsp, idxsp, prefixtree, prefixcnt)
3926 FILE *fd;
3927 char_u **bytsp;
3928 idx_T **idxsp;
3929 int prefixtree; /* TRUE for the prefix tree */
3930 int prefixcnt; /* when "prefixtree" is TRUE: prefix count */
3932 int len;
3933 int idx;
3934 char_u *bp;
3935 idx_T *ip;
3937 /* The tree size was computed when writing the file, so that we can
3938 * allocate it as one long block. <nodecount> */
3939 len = get4c(fd);
3940 if (len < 0)
3941 return SP_TRUNCERROR;
3942 if (len > 0)
3944 /* Allocate the byte array. */
3945 bp = lalloc((long_u)len, TRUE);
3946 if (bp == NULL)
3947 return SP_OTHERERROR;
3948 *bytsp = bp;
3950 /* Allocate the index array. */
3951 ip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE);
3952 if (ip == NULL)
3953 return SP_OTHERERROR;
3954 *idxsp = ip;
3956 /* Recursively read the tree and store it in the array. */
3957 idx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt);
3958 if (idx < 0)
3959 return idx;
3961 return 0;
3965 * Read one row of siblings from the spell file and store it in the byte array
3966 * "byts" and index array "idxs". Recursively read the children.
3968 * NOTE: The code here must match put_node()!
3970 * Returns the index (>= 0) following the siblings.
3971 * Returns SP_TRUNCERROR if the file is shorter than expected.
3972 * Returns SP_FORMERROR if there is a format error.
3974 static idx_T
3975 read_tree_node(fd, byts, idxs, maxidx, startidx, prefixtree, maxprefcondnr)
3976 FILE *fd;
3977 char_u *byts;
3978 idx_T *idxs;
3979 int maxidx; /* size of arrays */
3980 idx_T startidx; /* current index in "byts" and "idxs" */
3981 int prefixtree; /* TRUE for reading PREFIXTREE */
3982 int maxprefcondnr; /* maximum for <prefcondnr> */
3984 int len;
3985 int i;
3986 int n;
3987 idx_T idx = startidx;
3988 int c;
3989 int c2;
3990 #define SHARED_MASK 0x8000000
3992 len = getc(fd); /* <siblingcount> */
3993 if (len <= 0)
3994 return SP_TRUNCERROR;
3996 if (startidx + len >= maxidx)
3997 return SP_FORMERROR;
3998 byts[idx++] = len;
4000 /* Read the byte values, flag/region bytes and shared indexes. */
4001 for (i = 1; i <= len; ++i)
4003 c = getc(fd); /* <byte> */
4004 if (c < 0)
4005 return SP_TRUNCERROR;
4006 if (c <= BY_SPECIAL)
4008 if (c == BY_NOFLAGS && !prefixtree)
4010 /* No flags, all regions. */
4011 idxs[idx] = 0;
4012 c = 0;
4014 else if (c != BY_INDEX)
4016 if (prefixtree)
4018 /* Read the optional pflags byte, the prefix ID and the
4019 * condition nr. In idxs[] store the prefix ID in the low
4020 * byte, the condition index shifted up 8 bits, the flags
4021 * shifted up 24 bits. */
4022 if (c == BY_FLAGS)
4023 c = getc(fd) << 24; /* <pflags> */
4024 else
4025 c = 0;
4027 c |= getc(fd); /* <affixID> */
4029 n = get2c(fd); /* <prefcondnr> */
4030 if (n >= maxprefcondnr)
4031 return SP_FORMERROR;
4032 c |= (n << 8);
4034 else /* c must be BY_FLAGS or BY_FLAGS2 */
4036 /* Read flags and optional region and prefix ID. In
4037 * idxs[] the flags go in the low two bytes, region above
4038 * that and prefix ID above the region. */
4039 c2 = c;
4040 c = getc(fd); /* <flags> */
4041 if (c2 == BY_FLAGS2)
4042 c = (getc(fd) << 8) + c; /* <flags2> */
4043 if (c & WF_REGION)
4044 c = (getc(fd) << 16) + c; /* <region> */
4045 if (c & WF_AFX)
4046 c = (getc(fd) << 24) + c; /* <affixID> */
4049 idxs[idx] = c;
4050 c = 0;
4052 else /* c == BY_INDEX */
4054 /* <nodeidx> */
4055 n = get3c(fd);
4056 if (n < 0 || n >= maxidx)
4057 return SP_FORMERROR;
4058 idxs[idx] = n + SHARED_MASK;
4059 c = getc(fd); /* <xbyte> */
4062 byts[idx++] = c;
4065 /* Recursively read the children for non-shared siblings.
4066 * Skip the end-of-word ones (zero byte value) and the shared ones (and
4067 * remove SHARED_MASK) */
4068 for (i = 1; i <= len; ++i)
4069 if (byts[startidx + i] != 0)
4071 if (idxs[startidx + i] & SHARED_MASK)
4072 idxs[startidx + i] &= ~SHARED_MASK;
4073 else
4075 idxs[startidx + i] = idx;
4076 idx = read_tree_node(fd, byts, idxs, maxidx, idx,
4077 prefixtree, maxprefcondnr);
4078 if (idx < 0)
4079 break;
4083 return idx;
4087 * Parse 'spelllang' and set buf->b_langp accordingly.
4088 * Returns NULL if it's OK, an error message otherwise.
4090 char_u *
4091 did_set_spelllang(buf)
4092 buf_T *buf;
4094 garray_T ga;
4095 char_u *splp;
4096 char_u *region;
4097 char_u region_cp[3];
4098 int filename;
4099 int region_mask;
4100 slang_T *slang;
4101 int c;
4102 char_u lang[MAXWLEN + 1];
4103 char_u spf_name[MAXPATHL];
4104 int len;
4105 char_u *p;
4106 int round;
4107 char_u *spf;
4108 char_u *use_region = NULL;
4109 int dont_use_region = FALSE;
4110 int nobreak = FALSE;
4111 int i, j;
4112 langp_T *lp, *lp2;
4113 static int recursive = FALSE;
4114 char_u *ret_msg = NULL;
4115 char_u *spl_copy;
4117 /* We don't want to do this recursively. May happen when a language is
4118 * not available and the SpellFileMissing autocommand opens a new buffer
4119 * in which 'spell' is set. */
4120 if (recursive)
4121 return NULL;
4122 recursive = TRUE;
4124 ga_init2(&ga, sizeof(langp_T), 2);
4125 clear_midword(buf);
4127 /* Make a copy of 'spellang', the SpellFileMissing autocommands may change
4128 * it under our fingers. */
4129 spl_copy = vim_strsave(buf->b_p_spl);
4130 if (spl_copy == NULL)
4131 goto theend;
4133 /* loop over comma separated language names. */
4134 for (splp = spl_copy; *splp != NUL; )
4136 /* Get one language name. */
4137 copy_option_part(&splp, lang, MAXWLEN, ",");
4139 region = NULL;
4140 len = (int)STRLEN(lang);
4142 /* If the name ends in ".spl" use it as the name of the spell file.
4143 * If there is a region name let "region" point to it and remove it
4144 * from the name. */
4145 if (len > 4 && fnamecmp(lang + len - 4, ".spl") == 0)
4147 filename = TRUE;
4149 /* Locate a region and remove it from the file name. */
4150 p = vim_strchr(gettail(lang), '_');
4151 if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2])
4152 && !ASCII_ISALPHA(p[3]))
4154 vim_strncpy(region_cp, p + 1, 2);
4155 mch_memmove(p, p + 3, len - (p - lang) - 2);
4156 len -= 3;
4157 region = region_cp;
4159 else
4160 dont_use_region = TRUE;
4162 /* Check if we loaded this language before. */
4163 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4164 if (fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME)
4165 break;
4167 else
4169 filename = FALSE;
4170 if (len > 3 && lang[len - 3] == '_')
4172 region = lang + len - 2;
4173 len -= 3;
4174 lang[len] = NUL;
4176 else
4177 dont_use_region = TRUE;
4179 /* Check if we loaded this language before. */
4180 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4181 if (STRICMP(lang, slang->sl_name) == 0)
4182 break;
4185 if (region != NULL)
4187 /* If the region differs from what was used before then don't
4188 * use it for 'spellfile'. */
4189 if (use_region != NULL && STRCMP(region, use_region) != 0)
4190 dont_use_region = TRUE;
4191 use_region = region;
4194 /* If not found try loading the language now. */
4195 if (slang == NULL)
4197 if (filename)
4198 (void)spell_load_file(lang, lang, NULL, FALSE);
4199 else
4201 spell_load_lang(lang);
4202 #ifdef FEAT_AUTOCMD
4203 /* SpellFileMissing autocommands may do anything, including
4204 * destroying the buffer we are using... */
4205 if (!buf_valid(buf))
4207 ret_msg = (char_u *)"E797: SpellFileMissing autocommand deleted buffer";
4208 goto theend;
4210 #endif
4215 * Loop over the languages, there can be several files for "lang".
4217 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4218 if (filename ? fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME
4219 : STRICMP(lang, slang->sl_name) == 0)
4221 region_mask = REGION_ALL;
4222 if (!filename && region != NULL)
4224 /* find region in sl_regions */
4225 c = find_region(slang->sl_regions, region);
4226 if (c == REGION_ALL)
4228 if (slang->sl_add)
4230 if (*slang->sl_regions != NUL)
4231 /* This addition file is for other regions. */
4232 region_mask = 0;
4234 else
4235 /* This is probably an error. Give a warning and
4236 * accept the words anyway. */
4237 smsg((char_u *)
4238 _("Warning: region %s not supported"),
4239 region);
4241 else
4242 region_mask = 1 << c;
4245 if (region_mask != 0)
4247 if (ga_grow(&ga, 1) == FAIL)
4249 ga_clear(&ga);
4250 ret_msg = e_outofmem;
4251 goto theend;
4253 LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;
4254 LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
4255 ++ga.ga_len;
4256 use_midword(slang, buf);
4257 if (slang->sl_nobreak)
4258 nobreak = TRUE;
4263 /* round 0: load int_wordlist, if possible.
4264 * round 1: load first name in 'spellfile'.
4265 * round 2: load second name in 'spellfile.
4266 * etc. */
4267 spf = buf->b_p_spf;
4268 for (round = 0; round == 0 || *spf != NUL; ++round)
4270 if (round == 0)
4272 /* Internal wordlist, if there is one. */
4273 if (int_wordlist == NULL)
4274 continue;
4275 int_wordlist_spl(spf_name);
4277 else
4279 /* One entry in 'spellfile'. */
4280 copy_option_part(&spf, spf_name, MAXPATHL - 5, ",");
4281 STRCAT(spf_name, ".spl");
4283 /* If it was already found above then skip it. */
4284 for (c = 0; c < ga.ga_len; ++c)
4286 p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname;
4287 if (p != NULL && fullpathcmp(spf_name, p, FALSE) == FPC_SAME)
4288 break;
4290 if (c < ga.ga_len)
4291 continue;
4294 /* Check if it was loaded already. */
4295 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4296 if (fullpathcmp(spf_name, slang->sl_fname, FALSE) == FPC_SAME)
4297 break;
4298 if (slang == NULL)
4300 /* Not loaded, try loading it now. The language name includes the
4301 * region name, the region is ignored otherwise. for int_wordlist
4302 * use an arbitrary name. */
4303 if (round == 0)
4304 STRCPY(lang, "internal wordlist");
4305 else
4307 vim_strncpy(lang, gettail(spf_name), MAXWLEN);
4308 p = vim_strchr(lang, '.');
4309 if (p != NULL)
4310 *p = NUL; /* truncate at ".encoding.add" */
4312 slang = spell_load_file(spf_name, lang, NULL, TRUE);
4314 /* If one of the languages has NOBREAK we assume the addition
4315 * files also have this. */
4316 if (slang != NULL && nobreak)
4317 slang->sl_nobreak = TRUE;
4319 if (slang != NULL && ga_grow(&ga, 1) == OK)
4321 region_mask = REGION_ALL;
4322 if (use_region != NULL && !dont_use_region)
4324 /* find region in sl_regions */
4325 c = find_region(slang->sl_regions, use_region);
4326 if (c != REGION_ALL)
4327 region_mask = 1 << c;
4328 else if (*slang->sl_regions != NUL)
4329 /* This spell file is for other regions. */
4330 region_mask = 0;
4333 if (region_mask != 0)
4335 LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;
4336 LANGP_ENTRY(ga, ga.ga_len)->lp_sallang = NULL;
4337 LANGP_ENTRY(ga, ga.ga_len)->lp_replang = NULL;
4338 LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
4339 ++ga.ga_len;
4340 use_midword(slang, buf);
4345 /* Everything is fine, store the new b_langp value. */
4346 ga_clear(&buf->b_langp);
4347 buf->b_langp = ga;
4349 /* For each language figure out what language to use for sound folding and
4350 * REP items. If the language doesn't support it itself use another one
4351 * with the same name. E.g. for "en-math" use "en". */
4352 for (i = 0; i < ga.ga_len; ++i)
4354 lp = LANGP_ENTRY(ga, i);
4356 /* sound folding */
4357 if (lp->lp_slang->sl_sal.ga_len > 0)
4358 /* language does sound folding itself */
4359 lp->lp_sallang = lp->lp_slang;
4360 else
4361 /* find first similar language that does sound folding */
4362 for (j = 0; j < ga.ga_len; ++j)
4364 lp2 = LANGP_ENTRY(ga, j);
4365 if (lp2->lp_slang->sl_sal.ga_len > 0
4366 && STRNCMP(lp->lp_slang->sl_name,
4367 lp2->lp_slang->sl_name, 2) == 0)
4369 lp->lp_sallang = lp2->lp_slang;
4370 break;
4374 /* REP items */
4375 if (lp->lp_slang->sl_rep.ga_len > 0)
4376 /* language has REP items itself */
4377 lp->lp_replang = lp->lp_slang;
4378 else
4379 /* find first similar language that has REP items */
4380 for (j = 0; j < ga.ga_len; ++j)
4382 lp2 = LANGP_ENTRY(ga, j);
4383 if (lp2->lp_slang->sl_rep.ga_len > 0
4384 && STRNCMP(lp->lp_slang->sl_name,
4385 lp2->lp_slang->sl_name, 2) == 0)
4387 lp->lp_replang = lp2->lp_slang;
4388 break;
4393 theend:
4394 vim_free(spl_copy);
4395 recursive = FALSE;
4396 return ret_msg;
4400 * Clear the midword characters for buffer "buf".
4402 static void
4403 clear_midword(buf)
4404 buf_T *buf;
4406 vim_memset(buf->b_spell_ismw, 0, 256);
4407 #ifdef FEAT_MBYTE
4408 vim_free(buf->b_spell_ismw_mb);
4409 buf->b_spell_ismw_mb = NULL;
4410 #endif
4414 * Use the "sl_midword" field of language "lp" for buffer "buf".
4415 * They add up to any currently used midword characters.
4417 static void
4418 use_midword(lp, buf)
4419 slang_T *lp;
4420 buf_T *buf;
4422 char_u *p;
4424 if (lp->sl_midword == NULL) /* there aren't any */
4425 return;
4427 for (p = lp->sl_midword; *p != NUL; )
4428 #ifdef FEAT_MBYTE
4429 if (has_mbyte)
4431 int c, l, n;
4432 char_u *bp;
4434 c = mb_ptr2char(p);
4435 l = (*mb_ptr2len)(p);
4436 if (c < 256 && l <= 2)
4437 buf->b_spell_ismw[c] = TRUE;
4438 else if (buf->b_spell_ismw_mb == NULL)
4439 /* First multi-byte char in "b_spell_ismw_mb". */
4440 buf->b_spell_ismw_mb = vim_strnsave(p, l);
4441 else
4443 /* Append multi-byte chars to "b_spell_ismw_mb". */
4444 n = (int)STRLEN(buf->b_spell_ismw_mb);
4445 bp = vim_strnsave(buf->b_spell_ismw_mb, n + l);
4446 if (bp != NULL)
4448 vim_free(buf->b_spell_ismw_mb);
4449 buf->b_spell_ismw_mb = bp;
4450 vim_strncpy(bp + n, p, l);
4453 p += l;
4455 else
4456 #endif
4457 buf->b_spell_ismw[*p++] = TRUE;
4461 * Find the region "region[2]" in "rp" (points to "sl_regions").
4462 * Each region is simply stored as the two characters of it's name.
4463 * Returns the index if found (first is 0), REGION_ALL if not found.
4465 static int
4466 find_region(rp, region)
4467 char_u *rp;
4468 char_u *region;
4470 int i;
4472 for (i = 0; ; i += 2)
4474 if (rp[i] == NUL)
4475 return REGION_ALL;
4476 if (rp[i] == region[0] && rp[i + 1] == region[1])
4477 break;
4479 return i / 2;
4483 * Return case type of word:
4484 * w word 0
4485 * Word WF_ONECAP
4486 * W WORD WF_ALLCAP
4487 * WoRd wOrd WF_KEEPCAP
4489 static int
4490 captype(word, end)
4491 char_u *word;
4492 char_u *end; /* When NULL use up to NUL byte. */
4494 char_u *p;
4495 int c;
4496 int firstcap;
4497 int allcap;
4498 int past_second = FALSE; /* past second word char */
4500 /* find first letter */
4501 for (p = word; !spell_iswordp_nmw(p); mb_ptr_adv(p))
4502 if (end == NULL ? *p == NUL : p >= end)
4503 return 0; /* only non-word characters, illegal word */
4504 #ifdef FEAT_MBYTE
4505 if (has_mbyte)
4506 c = mb_ptr2char_adv(&p);
4507 else
4508 #endif
4509 c = *p++;
4510 firstcap = allcap = SPELL_ISUPPER(c);
4513 * Need to check all letters to find a word with mixed upper/lower.
4514 * But a word with an upper char only at start is a ONECAP.
4516 for ( ; end == NULL ? *p != NUL : p < end; mb_ptr_adv(p))
4517 if (spell_iswordp_nmw(p))
4519 c = PTR2CHAR(p);
4520 if (!SPELL_ISUPPER(c))
4522 /* UUl -> KEEPCAP */
4523 if (past_second && allcap)
4524 return WF_KEEPCAP;
4525 allcap = FALSE;
4527 else if (!allcap)
4528 /* UlU -> KEEPCAP */
4529 return WF_KEEPCAP;
4530 past_second = TRUE;
4533 if (allcap)
4534 return WF_ALLCAP;
4535 if (firstcap)
4536 return WF_ONECAP;
4537 return 0;
4541 * Like captype() but for a KEEPCAP word add ONECAP if the word starts with a
4542 * capital. So that make_case_word() can turn WOrd into Word.
4543 * Add ALLCAP for "WOrD".
4545 static int
4546 badword_captype(word, end)
4547 char_u *word;
4548 char_u *end;
4550 int flags = captype(word, end);
4551 int c;
4552 int l, u;
4553 int first;
4554 char_u *p;
4556 if (flags & WF_KEEPCAP)
4558 /* Count the number of UPPER and lower case letters. */
4559 l = u = 0;
4560 first = FALSE;
4561 for (p = word; p < end; mb_ptr_adv(p))
4563 c = PTR2CHAR(p);
4564 if (SPELL_ISUPPER(c))
4566 ++u;
4567 if (p == word)
4568 first = TRUE;
4570 else
4571 ++l;
4574 /* If there are more UPPER than lower case letters suggest an
4575 * ALLCAP word. Otherwise, if the first letter is UPPER then
4576 * suggest ONECAP. Exception: "ALl" most likely should be "All",
4577 * require three upper case letters. */
4578 if (u > l && u > 2)
4579 flags |= WF_ALLCAP;
4580 else if (first)
4581 flags |= WF_ONECAP;
4583 if (u >= 2 && l >= 2) /* maCARONI maCAroni */
4584 flags |= WF_MIXCAP;
4586 return flags;
4589 # if defined(FEAT_MBYTE) || defined(EXITFREE) || defined(PROTO)
4591 * Free all languages.
4593 void
4594 spell_free_all()
4596 slang_T *slang;
4597 buf_T *buf;
4598 char_u fname[MAXPATHL];
4600 /* Go through all buffers and handle 'spelllang'. */
4601 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
4602 ga_clear(&buf->b_langp);
4604 while (first_lang != NULL)
4606 slang = first_lang;
4607 first_lang = slang->sl_next;
4608 slang_free(slang);
4611 if (int_wordlist != NULL)
4613 /* Delete the internal wordlist and its .spl file */
4614 mch_remove(int_wordlist);
4615 int_wordlist_spl(fname);
4616 mch_remove(fname);
4617 vim_free(int_wordlist);
4618 int_wordlist = NULL;
4621 init_spell_chartab();
4623 vim_free(repl_to);
4624 repl_to = NULL;
4625 vim_free(repl_from);
4626 repl_from = NULL;
4628 # endif
4630 # if defined(FEAT_MBYTE) || defined(PROTO)
4632 * Clear all spelling tables and reload them.
4633 * Used after 'encoding' is set and when ":mkspell" was used.
4635 void
4636 spell_reload()
4638 buf_T *buf;
4639 win_T *wp;
4641 /* Initialize the table for spell_iswordp(). */
4642 init_spell_chartab();
4644 /* Unload all allocated memory. */
4645 spell_free_all();
4647 /* Go through all buffers and handle 'spelllang'. */
4648 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
4650 /* Only load the wordlists when 'spelllang' is set and there is a
4651 * window for this buffer in which 'spell' is set. */
4652 if (*buf->b_p_spl != NUL)
4654 FOR_ALL_WINDOWS(wp)
4655 if (wp->w_buffer == buf && wp->w_p_spell)
4657 (void)did_set_spelllang(buf);
4658 # ifdef FEAT_WINDOWS
4659 break;
4660 # endif
4665 # endif
4668 * Reload the spell file "fname" if it's loaded.
4670 static void
4671 spell_reload_one(fname, added_word)
4672 char_u *fname;
4673 int added_word; /* invoked through "zg" */
4675 slang_T *slang;
4676 int didit = FALSE;
4678 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4680 if (fullpathcmp(fname, slang->sl_fname, FALSE) == FPC_SAME)
4682 slang_clear(slang);
4683 if (spell_load_file(fname, NULL, slang, FALSE) == NULL)
4684 /* reloading failed, clear the language */
4685 slang_clear(slang);
4686 redraw_all_later(SOME_VALID);
4687 didit = TRUE;
4691 /* When "zg" was used and the file wasn't loaded yet, should redo
4692 * 'spelllang' to load it now. */
4693 if (added_word && !didit)
4694 did_set_spelllang(curbuf);
4699 * Functions for ":mkspell".
4702 #define MAXLINELEN 500 /* Maximum length in bytes of a line in a .aff
4703 and .dic file. */
4705 * Main structure to store the contents of a ".aff" file.
4707 typedef struct afffile_S
4709 char_u *af_enc; /* "SET", normalized, alloc'ed string or NULL */
4710 int af_flagtype; /* AFT_CHAR, AFT_LONG, AFT_NUM or AFT_CAPLONG */
4711 unsigned af_rare; /* RARE ID for rare word */
4712 unsigned af_keepcase; /* KEEPCASE ID for keep-case word */
4713 unsigned af_bad; /* BAD ID for banned word */
4714 unsigned af_needaffix; /* NEEDAFFIX ID */
4715 unsigned af_circumfix; /* CIRCUMFIX ID */
4716 unsigned af_needcomp; /* NEEDCOMPOUND ID */
4717 unsigned af_comproot; /* COMPOUNDROOT ID */
4718 unsigned af_compforbid; /* COMPOUNDFORBIDFLAG ID */
4719 unsigned af_comppermit; /* COMPOUNDPERMITFLAG ID */
4720 unsigned af_nosuggest; /* NOSUGGEST ID */
4721 int af_pfxpostpone; /* postpone prefixes without chop string and
4722 without flags */
4723 hashtab_T af_pref; /* hashtable for prefixes, affheader_T */
4724 hashtab_T af_suff; /* hashtable for suffixes, affheader_T */
4725 hashtab_T af_comp; /* hashtable for compound flags, compitem_T */
4726 } afffile_T;
4728 #define AFT_CHAR 0 /* flags are one character */
4729 #define AFT_LONG 1 /* flags are two characters */
4730 #define AFT_CAPLONG 2 /* flags are one or two characters */
4731 #define AFT_NUM 3 /* flags are numbers, comma separated */
4733 typedef struct affentry_S affentry_T;
4734 /* Affix entry from ".aff" file. Used for prefixes and suffixes. */
4735 struct affentry_S
4737 affentry_T *ae_next; /* next affix with same name/number */
4738 char_u *ae_chop; /* text to chop off basic word (can be NULL) */
4739 char_u *ae_add; /* text to add to basic word (can be NULL) */
4740 char_u *ae_flags; /* flags on the affix (can be NULL) */
4741 char_u *ae_cond; /* condition (NULL for ".") */
4742 regprog_T *ae_prog; /* regexp program for ae_cond or NULL */
4743 char ae_compforbid; /* COMPOUNDFORBIDFLAG found */
4744 char ae_comppermit; /* COMPOUNDPERMITFLAG found */
4747 #ifdef FEAT_MBYTE
4748 # define AH_KEY_LEN 17 /* 2 x 8 bytes + NUL */
4749 #else
4750 # define AH_KEY_LEN 7 /* 6 digits + NUL */
4751 #endif
4753 /* Affix header from ".aff" file. Used for af_pref and af_suff. */
4754 typedef struct affheader_S
4756 char_u ah_key[AH_KEY_LEN]; /* key for hashtab == name of affix */
4757 unsigned ah_flag; /* affix name as number, uses "af_flagtype" */
4758 int ah_newID; /* prefix ID after renumbering; 0 if not used */
4759 int ah_combine; /* suffix may combine with prefix */
4760 int ah_follows; /* another affix block should be following */
4761 affentry_T *ah_first; /* first affix entry */
4762 } affheader_T;
4764 #define HI2AH(hi) ((affheader_T *)(hi)->hi_key)
4766 /* Flag used in compound items. */
4767 typedef struct compitem_S
4769 char_u ci_key[AH_KEY_LEN]; /* key for hashtab == name of compound */
4770 unsigned ci_flag; /* affix name as number, uses "af_flagtype" */
4771 int ci_newID; /* affix ID after renumbering. */
4772 } compitem_T;
4774 #define HI2CI(hi) ((compitem_T *)(hi)->hi_key)
4777 * Structure that is used to store the items in the word tree. This avoids
4778 * the need to keep track of each allocated thing, everything is freed all at
4779 * once after ":mkspell" is done.
4781 #define SBLOCKSIZE 16000 /* size of sb_data */
4782 typedef struct sblock_S sblock_T;
4783 struct sblock_S
4785 sblock_T *sb_next; /* next block in list */
4786 int sb_used; /* nr of bytes already in use */
4787 char_u sb_data[1]; /* data, actually longer */
4791 * A node in the tree.
4793 typedef struct wordnode_S wordnode_T;
4794 struct wordnode_S
4796 union /* shared to save space */
4798 char_u hashkey[6]; /* the hash key, only used while compressing */
4799 int index; /* index in written nodes (valid after first
4800 round) */
4801 } wn_u1;
4802 union /* shared to save space */
4804 wordnode_T *next; /* next node with same hash key */
4805 wordnode_T *wnode; /* parent node that will write this node */
4806 } wn_u2;
4807 wordnode_T *wn_child; /* child (next byte in word) */
4808 wordnode_T *wn_sibling; /* next sibling (alternate byte in word,
4809 always sorted) */
4810 int wn_refs; /* Nr. of references to this node. Only
4811 relevant for first node in a list of
4812 siblings, in following siblings it is
4813 always one. */
4814 char_u wn_byte; /* Byte for this node. NUL for word end */
4816 /* Info for when "wn_byte" is NUL.
4817 * In PREFIXTREE "wn_region" is used for the prefcondnr.
4818 * In the soundfolded word tree "wn_flags" has the MSW of the wordnr and
4819 * "wn_region" the LSW of the wordnr. */
4820 char_u wn_affixID; /* supported/required prefix ID or 0 */
4821 short_u wn_flags; /* WF_ flags */
4822 short wn_region; /* region mask */
4824 #ifdef SPELL_PRINTTREE
4825 int wn_nr; /* sequence nr for printing */
4826 #endif
4829 #define WN_MASK 0xffff /* mask relevant bits of "wn_flags" */
4831 #define HI2WN(hi) (wordnode_T *)((hi)->hi_key)
4834 * Info used while reading the spell files.
4836 typedef struct spellinfo_S
4838 wordnode_T *si_foldroot; /* tree with case-folded words */
4839 long si_foldwcount; /* nr of words in si_foldroot */
4841 wordnode_T *si_keeproot; /* tree with keep-case words */
4842 long si_keepwcount; /* nr of words in si_keeproot */
4844 wordnode_T *si_prefroot; /* tree with postponed prefixes */
4846 long si_sugtree; /* creating the soundfolding trie */
4848 sblock_T *si_blocks; /* memory blocks used */
4849 long si_blocks_cnt; /* memory blocks allocated */
4850 long si_compress_cnt; /* words to add before lowering
4851 compression limit */
4852 wordnode_T *si_first_free; /* List of nodes that have been freed during
4853 compression, linked by "wn_child" field. */
4854 long si_free_count; /* number of nodes in si_first_free */
4855 #ifdef SPELL_PRINTTREE
4856 int si_wordnode_nr; /* sequence nr for nodes */
4857 #endif
4858 buf_T *si_spellbuf; /* buffer used to store soundfold word table */
4860 int si_ascii; /* handling only ASCII words */
4861 int si_add; /* addition file */
4862 int si_clear_chartab; /* when TRUE clear char tables */
4863 int si_region; /* region mask */
4864 vimconv_T si_conv; /* for conversion to 'encoding' */
4865 int si_memtot; /* runtime memory used */
4866 int si_verbose; /* verbose messages */
4867 int si_msg_count; /* number of words added since last message */
4868 char_u *si_info; /* info text chars or NULL */
4869 int si_region_count; /* number of regions supported (1 when there
4870 are no regions) */
4871 char_u si_region_name[16]; /* region names; used only if
4872 * si_region_count > 1) */
4874 garray_T si_rep; /* list of fromto_T entries from REP lines */
4875 garray_T si_repsal; /* list of fromto_T entries from REPSAL lines */
4876 garray_T si_sal; /* list of fromto_T entries from SAL lines */
4877 char_u *si_sofofr; /* SOFOFROM text */
4878 char_u *si_sofoto; /* SOFOTO text */
4879 int si_nosugfile; /* NOSUGFILE item found */
4880 int si_nosplitsugs; /* NOSPLITSUGS item found */
4881 int si_followup; /* soundsalike: ? */
4882 int si_collapse; /* soundsalike: ? */
4883 hashtab_T si_commonwords; /* hashtable for common words */
4884 time_t si_sugtime; /* timestamp for .sug file */
4885 int si_rem_accents; /* soundsalike: remove accents */
4886 garray_T si_map; /* MAP info concatenated */
4887 char_u *si_midword; /* MIDWORD chars or NULL */
4888 int si_compmax; /* max nr of words for compounding */
4889 int si_compminlen; /* minimal length for compounding */
4890 int si_compsylmax; /* max nr of syllables for compounding */
4891 int si_compoptions; /* COMP_ flags */
4892 garray_T si_comppat; /* CHECKCOMPOUNDPATTERN items, each stored as
4893 a string */
4894 char_u *si_compflags; /* flags used for compounding */
4895 char_u si_nobreak; /* NOBREAK */
4896 char_u *si_syllable; /* syllable string */
4897 garray_T si_prefcond; /* table with conditions for postponed
4898 * prefixes, each stored as a string */
4899 int si_newprefID; /* current value for ah_newID */
4900 int si_newcompID; /* current value for compound ID */
4901 } spellinfo_T;
4903 static afffile_T *spell_read_aff __ARGS((spellinfo_T *spin, char_u *fname));
4904 static void aff_process_flags __ARGS((afffile_T *affile, affentry_T *entry));
4905 static int spell_info_item __ARGS((char_u *s));
4906 static unsigned affitem2flag __ARGS((int flagtype, char_u *item, char_u *fname, int lnum));
4907 static unsigned get_affitem __ARGS((int flagtype, char_u **pp));
4908 static void process_compflags __ARGS((spellinfo_T *spin, afffile_T *aff, char_u *compflags));
4909 static void check_renumber __ARGS((spellinfo_T *spin));
4910 static int flag_in_afflist __ARGS((int flagtype, char_u *afflist, unsigned flag));
4911 static void aff_check_number __ARGS((int spinval, int affval, char *name));
4912 static void aff_check_string __ARGS((char_u *spinval, char_u *affval, char *name));
4913 static int str_equal __ARGS((char_u *s1, char_u *s2));
4914 static void add_fromto __ARGS((spellinfo_T *spin, garray_T *gap, char_u *from, char_u *to));
4915 static int sal_to_bool __ARGS((char_u *s));
4916 static int has_non_ascii __ARGS((char_u *s));
4917 static void spell_free_aff __ARGS((afffile_T *aff));
4918 static int spell_read_dic __ARGS((spellinfo_T *spin, char_u *fname, afffile_T *affile));
4919 static int get_affix_flags __ARGS((afffile_T *affile, char_u *afflist));
4920 static int get_pfxlist __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist));
4921 static void get_compflags __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist));
4922 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));
4923 static int spell_read_wordfile __ARGS((spellinfo_T *spin, char_u *fname));
4924 static void *getroom __ARGS((spellinfo_T *spin, size_t len, int align));
4925 static char_u *getroom_save __ARGS((spellinfo_T *spin, char_u *s));
4926 static void free_blocks __ARGS((sblock_T *bl));
4927 static wordnode_T *wordtree_alloc __ARGS((spellinfo_T *spin));
4928 static int store_word __ARGS((spellinfo_T *spin, char_u *word, int flags, int region, char_u *pfxlist, int need_affix));
4929 static int tree_add_word __ARGS((spellinfo_T *spin, char_u *word, wordnode_T *tree, int flags, int region, int affixID));
4930 static wordnode_T *get_wordnode __ARGS((spellinfo_T *spin));
4931 static int deref_wordnode __ARGS((spellinfo_T *spin, wordnode_T *node));
4932 static void free_wordnode __ARGS((spellinfo_T *spin, wordnode_T *n));
4933 static void wordtree_compress __ARGS((spellinfo_T *spin, wordnode_T *root));
4934 static int node_compress __ARGS((spellinfo_T *spin, wordnode_T *node, hashtab_T *ht, int *tot));
4935 static int node_equal __ARGS((wordnode_T *n1, wordnode_T *n2));
4936 static void put_sugtime __ARGS((spellinfo_T *spin, FILE *fd));
4937 static int write_vim_spell __ARGS((spellinfo_T *spin, char_u *fname));
4938 static void clear_node __ARGS((wordnode_T *node));
4939 static int put_node __ARGS((FILE *fd, wordnode_T *node, int index, int regionmask, int prefixtree));
4940 static void spell_make_sugfile __ARGS((spellinfo_T *spin, char_u *wfname));
4941 static int sug_filltree __ARGS((spellinfo_T *spin, slang_T *slang));
4942 static int sug_maketable __ARGS((spellinfo_T *spin));
4943 static int sug_filltable __ARGS((spellinfo_T *spin, wordnode_T *node, int startwordnr, garray_T *gap));
4944 static int offset2bytes __ARGS((int nr, char_u *buf));
4945 static int bytes2offset __ARGS((char_u **pp));
4946 static void sug_write __ARGS((spellinfo_T *spin, char_u *fname));
4947 static void mkspell __ARGS((int fcount, char_u **fnames, int ascii, int overwrite, int added_word));
4948 static void spell_message __ARGS((spellinfo_T *spin, char_u *str));
4949 static void init_spellfile __ARGS((void));
4951 /* In the postponed prefixes tree wn_flags is used to store the WFP_ flags,
4952 * but it must be negative to indicate the prefix tree to tree_add_word().
4953 * Use a negative number with the lower 8 bits zero. */
4954 #define PFX_FLAGS -256
4956 /* flags for "condit" argument of store_aff_word() */
4957 #define CONDIT_COMB 1 /* affix must combine */
4958 #define CONDIT_CFIX 2 /* affix must have CIRCUMFIX flag */
4959 #define CONDIT_SUF 4 /* add a suffix for matching flags */
4960 #define CONDIT_AFF 8 /* word already has an affix */
4963 * Tunable parameters for when the tree is compressed. See 'mkspellmem'.
4965 static long compress_start = 30000; /* memory / SBLOCKSIZE */
4966 static long compress_inc = 100; /* memory / SBLOCKSIZE */
4967 static long compress_added = 500000; /* word count */
4969 #ifdef SPELL_PRINTTREE
4971 * For debugging the tree code: print the current tree in a (more or less)
4972 * readable format, so that we can see what happens when adding a word and/or
4973 * compressing the tree.
4974 * Based on code from Olaf Seibert.
4976 #define PRINTLINESIZE 1000
4977 #define PRINTWIDTH 6
4979 #define PRINTSOME(l, depth, fmt, a1, a2) vim_snprintf(l + depth * PRINTWIDTH, \
4980 PRINTLINESIZE - PRINTWIDTH * depth, fmt, a1, a2)
4982 static char line1[PRINTLINESIZE];
4983 static char line2[PRINTLINESIZE];
4984 static char line3[PRINTLINESIZE];
4986 static void
4987 spell_clear_flags(wordnode_T *node)
4989 wordnode_T *np;
4991 for (np = node; np != NULL; np = np->wn_sibling)
4993 np->wn_u1.index = FALSE;
4994 spell_clear_flags(np->wn_child);
4998 static void
4999 spell_print_node(wordnode_T *node, int depth)
5001 if (node->wn_u1.index)
5003 /* Done this node before, print the reference. */
5004 PRINTSOME(line1, depth, "(%d)", node->wn_nr, 0);
5005 PRINTSOME(line2, depth, " ", 0, 0);
5006 PRINTSOME(line3, depth, " ", 0, 0);
5007 msg(line1);
5008 msg(line2);
5009 msg(line3);
5011 else
5013 node->wn_u1.index = TRUE;
5015 if (node->wn_byte != NUL)
5017 if (node->wn_child != NULL)
5018 PRINTSOME(line1, depth, " %c -> ", node->wn_byte, 0);
5019 else
5020 /* Cannot happen? */
5021 PRINTSOME(line1, depth, " %c ???", node->wn_byte, 0);
5023 else
5024 PRINTSOME(line1, depth, " $ ", 0, 0);
5026 PRINTSOME(line2, depth, "%d/%d ", node->wn_nr, node->wn_refs);
5028 if (node->wn_sibling != NULL)
5029 PRINTSOME(line3, depth, " | ", 0, 0);
5030 else
5031 PRINTSOME(line3, depth, " ", 0, 0);
5033 if (node->wn_byte == NUL)
5035 msg(line1);
5036 msg(line2);
5037 msg(line3);
5040 /* do the children */
5041 if (node->wn_byte != NUL && node->wn_child != NULL)
5042 spell_print_node(node->wn_child, depth + 1);
5044 /* do the siblings */
5045 if (node->wn_sibling != NULL)
5047 /* get rid of all parent details except | */
5048 STRCPY(line1, line3);
5049 STRCPY(line2, line3);
5050 spell_print_node(node->wn_sibling, depth);
5055 static void
5056 spell_print_tree(wordnode_T *root)
5058 if (root != NULL)
5060 /* Clear the "wn_u1.index" fields, used to remember what has been
5061 * done. */
5062 spell_clear_flags(root);
5064 /* Recursively print the tree. */
5065 spell_print_node(root, 0);
5068 #endif /* SPELL_PRINTTREE */
5071 * Read the affix file "fname".
5072 * Returns an afffile_T, NULL for complete failure.
5074 static afffile_T *
5075 spell_read_aff(spin, fname)
5076 spellinfo_T *spin;
5077 char_u *fname;
5079 FILE *fd;
5080 afffile_T *aff;
5081 char_u rline[MAXLINELEN];
5082 char_u *line;
5083 char_u *pc = NULL;
5084 #define MAXITEMCNT 30
5085 char_u *(items[MAXITEMCNT]);
5086 int itemcnt;
5087 char_u *p;
5088 int lnum = 0;
5089 affheader_T *cur_aff = NULL;
5090 int did_postpone_prefix = FALSE;
5091 int aff_todo = 0;
5092 hashtab_T *tp;
5093 char_u *low = NULL;
5094 char_u *fol = NULL;
5095 char_u *upp = NULL;
5096 int do_rep;
5097 int do_repsal;
5098 int do_sal;
5099 int do_mapline;
5100 int found_map = FALSE;
5101 hashitem_T *hi;
5102 int l;
5103 int compminlen = 0; /* COMPOUNDMIN value */
5104 int compsylmax = 0; /* COMPOUNDSYLMAX value */
5105 int compoptions = 0; /* COMP_ flags */
5106 int compmax = 0; /* COMPOUNDWORDMAX value */
5107 char_u *compflags = NULL; /* COMPOUNDFLAG and COMPOUNDRULE
5108 concatenated */
5109 char_u *midword = NULL; /* MIDWORD value */
5110 char_u *syllable = NULL; /* SYLLABLE value */
5111 char_u *sofofrom = NULL; /* SOFOFROM value */
5112 char_u *sofoto = NULL; /* SOFOTO value */
5115 * Open the file.
5117 fd = mch_fopen((char *)fname, "r");
5118 if (fd == NULL)
5120 EMSG2(_(e_notopen), fname);
5121 return NULL;
5124 vim_snprintf((char *)IObuff, IOSIZE, _("Reading affix file %s ..."), fname);
5125 spell_message(spin, IObuff);
5127 /* Only do REP lines when not done in another .aff file already. */
5128 do_rep = spin->si_rep.ga_len == 0;
5130 /* Only do REPSAL lines when not done in another .aff file already. */
5131 do_repsal = spin->si_repsal.ga_len == 0;
5133 /* Only do SAL lines when not done in another .aff file already. */
5134 do_sal = spin->si_sal.ga_len == 0;
5136 /* Only do MAP lines when not done in another .aff file already. */
5137 do_mapline = spin->si_map.ga_len == 0;
5140 * Allocate and init the afffile_T structure.
5142 aff = (afffile_T *)getroom(spin, sizeof(afffile_T), TRUE);
5143 if (aff == NULL)
5145 fclose(fd);
5146 return NULL;
5148 hash_init(&aff->af_pref);
5149 hash_init(&aff->af_suff);
5150 hash_init(&aff->af_comp);
5153 * Read all the lines in the file one by one.
5155 while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
5157 line_breakcheck();
5158 ++lnum;
5160 /* Skip comment lines. */
5161 if (*rline == '#')
5162 continue;
5164 /* Convert from "SET" to 'encoding' when needed. */
5165 vim_free(pc);
5166 #ifdef FEAT_MBYTE
5167 if (spin->si_conv.vc_type != CONV_NONE)
5169 pc = string_convert(&spin->si_conv, rline, NULL);
5170 if (pc == NULL)
5172 smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
5173 fname, lnum, rline);
5174 continue;
5176 line = pc;
5178 else
5179 #endif
5181 pc = NULL;
5182 line = rline;
5185 /* Split the line up in white separated items. Put a NUL after each
5186 * item. */
5187 itemcnt = 0;
5188 for (p = line; ; )
5190 while (*p != NUL && *p <= ' ') /* skip white space and CR/NL */
5191 ++p;
5192 if (*p == NUL)
5193 break;
5194 if (itemcnt == MAXITEMCNT) /* too many items */
5195 break;
5196 items[itemcnt++] = p;
5197 /* A few items have arbitrary text argument, don't split them. */
5198 if (itemcnt == 2 && spell_info_item(items[0]))
5199 while (*p >= ' ' || *p == TAB) /* skip until CR/NL */
5200 ++p;
5201 else
5202 while (*p > ' ') /* skip until white space or CR/NL */
5203 ++p;
5204 if (*p == NUL)
5205 break;
5206 *p++ = NUL;
5209 /* Handle non-empty lines. */
5210 if (itemcnt > 0)
5212 if (STRCMP(items[0], "SET") == 0 && itemcnt == 2
5213 && aff->af_enc == NULL)
5215 #ifdef FEAT_MBYTE
5216 /* Setup for conversion from "ENC" to 'encoding'. */
5217 aff->af_enc = enc_canonize(items[1]);
5218 if (aff->af_enc != NULL && !spin->si_ascii
5219 && convert_setup(&spin->si_conv, aff->af_enc,
5220 p_enc) == FAIL)
5221 smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
5222 fname, aff->af_enc, p_enc);
5223 spin->si_conv.vc_fail = TRUE;
5224 #else
5225 smsg((char_u *)_("Conversion in %s not supported"), fname);
5226 #endif
5228 else if (STRCMP(items[0], "FLAG") == 0 && itemcnt == 2
5229 && aff->af_flagtype == AFT_CHAR)
5231 if (STRCMP(items[1], "long") == 0)
5232 aff->af_flagtype = AFT_LONG;
5233 else if (STRCMP(items[1], "num") == 0)
5234 aff->af_flagtype = AFT_NUM;
5235 else if (STRCMP(items[1], "caplong") == 0)
5236 aff->af_flagtype = AFT_CAPLONG;
5237 else
5238 smsg((char_u *)_("Invalid value for FLAG in %s line %d: %s"),
5239 fname, lnum, items[1]);
5240 if (aff->af_rare != 0
5241 || aff->af_keepcase != 0
5242 || aff->af_bad != 0
5243 || aff->af_needaffix != 0
5244 || aff->af_circumfix != 0
5245 || aff->af_needcomp != 0
5246 || aff->af_comproot != 0
5247 || aff->af_nosuggest != 0
5248 || compflags != NULL
5249 || aff->af_suff.ht_used > 0
5250 || aff->af_pref.ht_used > 0)
5251 smsg((char_u *)_("FLAG after using flags in %s line %d: %s"),
5252 fname, lnum, items[1]);
5254 else if (spell_info_item(items[0]))
5256 p = (char_u *)getroom(spin,
5257 (spin->si_info == NULL ? 0 : STRLEN(spin->si_info))
5258 + STRLEN(items[0])
5259 + STRLEN(items[1]) + 3, FALSE);
5260 if (p != NULL)
5262 if (spin->si_info != NULL)
5264 STRCPY(p, spin->si_info);
5265 STRCAT(p, "\n");
5267 STRCAT(p, items[0]);
5268 STRCAT(p, " ");
5269 STRCAT(p, items[1]);
5270 spin->si_info = p;
5273 else if (STRCMP(items[0], "MIDWORD") == 0 && itemcnt == 2
5274 && midword == NULL)
5276 midword = getroom_save(spin, items[1]);
5278 else if (STRCMP(items[0], "TRY") == 0 && itemcnt == 2)
5280 /* ignored, we look in the tree for what chars may appear */
5282 /* TODO: remove "RAR" later */
5283 else if ((STRCMP(items[0], "RAR") == 0
5284 || STRCMP(items[0], "RARE") == 0) && itemcnt == 2
5285 && aff->af_rare == 0)
5287 aff->af_rare = affitem2flag(aff->af_flagtype, items[1],
5288 fname, lnum);
5290 /* TODO: remove "KEP" later */
5291 else if ((STRCMP(items[0], "KEP") == 0
5292 || STRCMP(items[0], "KEEPCASE") == 0) && itemcnt == 2
5293 && aff->af_keepcase == 0)
5295 aff->af_keepcase = affitem2flag(aff->af_flagtype, items[1],
5296 fname, lnum);
5298 else if (STRCMP(items[0], "BAD") == 0 && itemcnt == 2
5299 && aff->af_bad == 0)
5301 aff->af_bad = affitem2flag(aff->af_flagtype, items[1],
5302 fname, lnum);
5304 else if (STRCMP(items[0], "NEEDAFFIX") == 0 && itemcnt == 2
5305 && aff->af_needaffix == 0)
5307 aff->af_needaffix = affitem2flag(aff->af_flagtype, items[1],
5308 fname, lnum);
5310 else if (STRCMP(items[0], "CIRCUMFIX") == 0 && itemcnt == 2
5311 && aff->af_circumfix == 0)
5313 aff->af_circumfix = affitem2flag(aff->af_flagtype, items[1],
5314 fname, lnum);
5316 else if (STRCMP(items[0], "NOSUGGEST") == 0 && itemcnt == 2
5317 && aff->af_nosuggest == 0)
5319 aff->af_nosuggest = affitem2flag(aff->af_flagtype, items[1],
5320 fname, lnum);
5322 else if (STRCMP(items[0], "NEEDCOMPOUND") == 0 && itemcnt == 2
5323 && aff->af_needcomp == 0)
5325 aff->af_needcomp = affitem2flag(aff->af_flagtype, items[1],
5326 fname, lnum);
5328 else if (STRCMP(items[0], "COMPOUNDROOT") == 0 && itemcnt == 2
5329 && aff->af_comproot == 0)
5331 aff->af_comproot = affitem2flag(aff->af_flagtype, items[1],
5332 fname, lnum);
5334 else if (STRCMP(items[0], "COMPOUNDFORBIDFLAG") == 0
5335 && itemcnt == 2 && aff->af_compforbid == 0)
5337 aff->af_compforbid = affitem2flag(aff->af_flagtype, items[1],
5338 fname, lnum);
5339 if (aff->af_pref.ht_used > 0)
5340 smsg((char_u *)_("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d"),
5341 fname, lnum);
5343 else if (STRCMP(items[0], "COMPOUNDPERMITFLAG") == 0
5344 && itemcnt == 2 && aff->af_comppermit == 0)
5346 aff->af_comppermit = affitem2flag(aff->af_flagtype, items[1],
5347 fname, lnum);
5348 if (aff->af_pref.ht_used > 0)
5349 smsg((char_u *)_("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d"),
5350 fname, lnum);
5352 else if (STRCMP(items[0], "COMPOUNDFLAG") == 0 && itemcnt == 2
5353 && compflags == NULL)
5355 /* Turn flag "c" into COMPOUNDRULE compatible string "c+",
5356 * "Na" into "Na+", "1234" into "1234+". */
5357 p = getroom(spin, STRLEN(items[1]) + 2, FALSE);
5358 if (p != NULL)
5360 STRCPY(p, items[1]);
5361 STRCAT(p, "+");
5362 compflags = p;
5365 else if (STRCMP(items[0], "COMPOUNDRULE") == 0 && itemcnt == 2)
5367 /* Concatenate this string to previously defined ones, using a
5368 * slash to separate them. */
5369 l = (int)STRLEN(items[1]) + 1;
5370 if (compflags != NULL)
5371 l += (int)STRLEN(compflags) + 1;
5372 p = getroom(spin, l, FALSE);
5373 if (p != NULL)
5375 if (compflags != NULL)
5377 STRCPY(p, compflags);
5378 STRCAT(p, "/");
5380 STRCAT(p, items[1]);
5381 compflags = p;
5384 else if (STRCMP(items[0], "COMPOUNDWORDMAX") == 0 && itemcnt == 2
5385 && compmax == 0)
5387 compmax = atoi((char *)items[1]);
5388 if (compmax == 0)
5389 smsg((char_u *)_("Wrong COMPOUNDWORDMAX value in %s line %d: %s"),
5390 fname, lnum, items[1]);
5392 else if (STRCMP(items[0], "COMPOUNDMIN") == 0 && itemcnt == 2
5393 && compminlen == 0)
5395 compminlen = atoi((char *)items[1]);
5396 if (compminlen == 0)
5397 smsg((char_u *)_("Wrong COMPOUNDMIN value in %s line %d: %s"),
5398 fname, lnum, items[1]);
5400 else if (STRCMP(items[0], "COMPOUNDSYLMAX") == 0 && itemcnt == 2
5401 && compsylmax == 0)
5403 compsylmax = atoi((char *)items[1]);
5404 if (compsylmax == 0)
5405 smsg((char_u *)_("Wrong COMPOUNDSYLMAX value in %s line %d: %s"),
5406 fname, lnum, items[1]);
5408 else if (STRCMP(items[0], "CHECKCOMPOUNDDUP") == 0 && itemcnt == 1)
5410 compoptions |= COMP_CHECKDUP;
5412 else if (STRCMP(items[0], "CHECKCOMPOUNDREP") == 0 && itemcnt == 1)
5414 compoptions |= COMP_CHECKREP;
5416 else if (STRCMP(items[0], "CHECKCOMPOUNDCASE") == 0 && itemcnt == 1)
5418 compoptions |= COMP_CHECKCASE;
5420 else if (STRCMP(items[0], "CHECKCOMPOUNDTRIPLE") == 0
5421 && itemcnt == 1)
5423 compoptions |= COMP_CHECKTRIPLE;
5425 else if (STRCMP(items[0], "CHECKCOMPOUNDPATTERN") == 0
5426 && itemcnt == 2)
5428 if (atoi((char *)items[1]) == 0)
5429 smsg((char_u *)_("Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s"),
5430 fname, lnum, items[1]);
5432 else if (STRCMP(items[0], "CHECKCOMPOUNDPATTERN") == 0
5433 && itemcnt == 3)
5435 garray_T *gap = &spin->si_comppat;
5436 int i;
5438 /* Only add the couple if it isn't already there. */
5439 for (i = 0; i < gap->ga_len - 1; i += 2)
5440 if (STRCMP(((char_u **)(gap->ga_data))[i], items[1]) == 0
5441 && STRCMP(((char_u **)(gap->ga_data))[i + 1],
5442 items[2]) == 0)
5443 break;
5444 if (i >= gap->ga_len && ga_grow(gap, 2) == OK)
5446 ((char_u **)(gap->ga_data))[gap->ga_len++]
5447 = getroom_save(spin, items[1]);
5448 ((char_u **)(gap->ga_data))[gap->ga_len++]
5449 = getroom_save(spin, items[2]);
5452 else if (STRCMP(items[0], "SYLLABLE") == 0 && itemcnt == 2
5453 && syllable == NULL)
5455 syllable = getroom_save(spin, items[1]);
5457 else if (STRCMP(items[0], "NOBREAK") == 0 && itemcnt == 1)
5459 spin->si_nobreak = TRUE;
5461 else if (STRCMP(items[0], "NOSPLITSUGS") == 0 && itemcnt == 1)
5463 spin->si_nosplitsugs = TRUE;
5465 else if (STRCMP(items[0], "NOSUGFILE") == 0 && itemcnt == 1)
5467 spin->si_nosugfile = TRUE;
5469 else if (STRCMP(items[0], "PFXPOSTPONE") == 0 && itemcnt == 1)
5471 aff->af_pfxpostpone = TRUE;
5473 else if ((STRCMP(items[0], "PFX") == 0
5474 || STRCMP(items[0], "SFX") == 0)
5475 && aff_todo == 0
5476 && itemcnt >= 4)
5478 int lasti = 4;
5479 char_u key[AH_KEY_LEN];
5481 if (*items[0] == 'P')
5482 tp = &aff->af_pref;
5483 else
5484 tp = &aff->af_suff;
5486 /* Myspell allows the same affix name to be used multiple
5487 * times. The affix files that do this have an undocumented
5488 * "S" flag on all but the last block, thus we check for that
5489 * and store it in ah_follows. */
5490 vim_strncpy(key, items[1], AH_KEY_LEN - 1);
5491 hi = hash_find(tp, key);
5492 if (!HASHITEM_EMPTY(hi))
5494 cur_aff = HI2AH(hi);
5495 if (cur_aff->ah_combine != (*items[2] == 'Y'))
5496 smsg((char_u *)_("Different combining flag in continued affix block in %s line %d: %s"),
5497 fname, lnum, items[1]);
5498 if (!cur_aff->ah_follows)
5499 smsg((char_u *)_("Duplicate affix in %s line %d: %s"),
5500 fname, lnum, items[1]);
5502 else
5504 /* New affix letter. */
5505 cur_aff = (affheader_T *)getroom(spin,
5506 sizeof(affheader_T), TRUE);
5507 if (cur_aff == NULL)
5508 break;
5509 cur_aff->ah_flag = affitem2flag(aff->af_flagtype, items[1],
5510 fname, lnum);
5511 if (cur_aff->ah_flag == 0 || STRLEN(items[1]) >= AH_KEY_LEN)
5512 break;
5513 if (cur_aff->ah_flag == aff->af_bad
5514 || cur_aff->ah_flag == aff->af_rare
5515 || cur_aff->ah_flag == aff->af_keepcase
5516 || cur_aff->ah_flag == aff->af_needaffix
5517 || cur_aff->ah_flag == aff->af_circumfix
5518 || cur_aff->ah_flag == aff->af_nosuggest
5519 || cur_aff->ah_flag == aff->af_needcomp
5520 || cur_aff->ah_flag == aff->af_comproot)
5521 smsg((char_u *)_("Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in %s line %d: %s"),
5522 fname, lnum, items[1]);
5523 STRCPY(cur_aff->ah_key, items[1]);
5524 hash_add(tp, cur_aff->ah_key);
5526 cur_aff->ah_combine = (*items[2] == 'Y');
5529 /* Check for the "S" flag, which apparently means that another
5530 * block with the same affix name is following. */
5531 if (itemcnt > lasti && STRCMP(items[lasti], "S") == 0)
5533 ++lasti;
5534 cur_aff->ah_follows = TRUE;
5536 else
5537 cur_aff->ah_follows = FALSE;
5539 /* Myspell allows extra text after the item, but that might
5540 * mean mistakes go unnoticed. Require a comment-starter. */
5541 if (itemcnt > lasti && *items[lasti] != '#')
5542 smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]);
5544 if (STRCMP(items[2], "Y") != 0 && STRCMP(items[2], "N") != 0)
5545 smsg((char_u *)_("Expected Y or N in %s line %d: %s"),
5546 fname, lnum, items[2]);
5548 if (*items[0] == 'P' && aff->af_pfxpostpone)
5550 if (cur_aff->ah_newID == 0)
5552 /* Use a new number in the .spl file later, to be able
5553 * to handle multiple .aff files. */
5554 check_renumber(spin);
5555 cur_aff->ah_newID = ++spin->si_newprefID;
5557 /* We only really use ah_newID if the prefix is
5558 * postponed. We know that only after handling all
5559 * the items. */
5560 did_postpone_prefix = FALSE;
5562 else
5563 /* Did use the ID in a previous block. */
5564 did_postpone_prefix = TRUE;
5567 aff_todo = atoi((char *)items[3]);
5569 else if ((STRCMP(items[0], "PFX") == 0
5570 || STRCMP(items[0], "SFX") == 0)
5571 && aff_todo > 0
5572 && STRCMP(cur_aff->ah_key, items[1]) == 0
5573 && itemcnt >= 5)
5575 affentry_T *aff_entry;
5576 int upper = FALSE;
5577 int lasti = 5;
5579 /* Myspell allows extra text after the item, but that might
5580 * mean mistakes go unnoticed. Require a comment-starter.
5581 * Hunspell uses a "-" item. */
5582 if (itemcnt > lasti && *items[lasti] != '#'
5583 && (STRCMP(items[lasti], "-") != 0
5584 || itemcnt != lasti + 1))
5585 smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]);
5587 /* New item for an affix letter. */
5588 --aff_todo;
5589 aff_entry = (affentry_T *)getroom(spin,
5590 sizeof(affentry_T), TRUE);
5591 if (aff_entry == NULL)
5592 break;
5594 if (STRCMP(items[2], "0") != 0)
5595 aff_entry->ae_chop = getroom_save(spin, items[2]);
5596 if (STRCMP(items[3], "0") != 0)
5598 aff_entry->ae_add = getroom_save(spin, items[3]);
5600 /* Recognize flags on the affix: abcd/XYZ */
5601 aff_entry->ae_flags = vim_strchr(aff_entry->ae_add, '/');
5602 if (aff_entry->ae_flags != NULL)
5604 *aff_entry->ae_flags++ = NUL;
5605 aff_process_flags(aff, aff_entry);
5609 /* Don't use an affix entry with non-ASCII characters when
5610 * "spin->si_ascii" is TRUE. */
5611 if (!spin->si_ascii || !(has_non_ascii(aff_entry->ae_chop)
5612 || has_non_ascii(aff_entry->ae_add)))
5614 aff_entry->ae_next = cur_aff->ah_first;
5615 cur_aff->ah_first = aff_entry;
5617 if (STRCMP(items[4], ".") != 0)
5619 char_u buf[MAXLINELEN];
5621 aff_entry->ae_cond = getroom_save(spin, items[4]);
5622 if (*items[0] == 'P')
5623 sprintf((char *)buf, "^%s", items[4]);
5624 else
5625 sprintf((char *)buf, "%s$", items[4]);
5626 aff_entry->ae_prog = vim_regcomp(buf,
5627 RE_MAGIC + RE_STRING + RE_STRICT);
5628 if (aff_entry->ae_prog == NULL)
5629 smsg((char_u *)_("Broken condition in %s line %d: %s"),
5630 fname, lnum, items[4]);
5633 /* For postponed prefixes we need an entry in si_prefcond
5634 * for the condition. Use an existing one if possible.
5635 * Can't be done for an affix with flags, ignoring
5636 * COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG. */
5637 if (*items[0] == 'P' && aff->af_pfxpostpone
5638 && aff_entry->ae_flags == NULL)
5640 /* When the chop string is one lower-case letter and
5641 * the add string ends in the upper-case letter we set
5642 * the "upper" flag, clear "ae_chop" and remove the
5643 * letters from "ae_add". The condition must either
5644 * be empty or start with the same letter. */
5645 if (aff_entry->ae_chop != NULL
5646 && aff_entry->ae_add != NULL
5647 #ifdef FEAT_MBYTE
5648 && aff_entry->ae_chop[(*mb_ptr2len)(
5649 aff_entry->ae_chop)] == NUL
5650 #else
5651 && aff_entry->ae_chop[1] == NUL
5652 #endif
5655 int c, c_up;
5657 c = PTR2CHAR(aff_entry->ae_chop);
5658 c_up = SPELL_TOUPPER(c);
5659 if (c_up != c
5660 && (aff_entry->ae_cond == NULL
5661 || PTR2CHAR(aff_entry->ae_cond) == c))
5663 p = aff_entry->ae_add
5664 + STRLEN(aff_entry->ae_add);
5665 mb_ptr_back(aff_entry->ae_add, p);
5666 if (PTR2CHAR(p) == c_up)
5668 upper = TRUE;
5669 aff_entry->ae_chop = NULL;
5670 *p = NUL;
5672 /* The condition is matched with the
5673 * actual word, thus must check for the
5674 * upper-case letter. */
5675 if (aff_entry->ae_cond != NULL)
5677 char_u buf[MAXLINELEN];
5678 #ifdef FEAT_MBYTE
5679 if (has_mbyte)
5681 onecap_copy(items[4], buf, TRUE);
5682 aff_entry->ae_cond = getroom_save(
5683 spin, buf);
5685 else
5686 #endif
5687 *aff_entry->ae_cond = c_up;
5688 if (aff_entry->ae_cond != NULL)
5690 sprintf((char *)buf, "^%s",
5691 aff_entry->ae_cond);
5692 vim_free(aff_entry->ae_prog);
5693 aff_entry->ae_prog = vim_regcomp(
5694 buf, RE_MAGIC + RE_STRING);
5701 if (aff_entry->ae_chop == NULL
5702 && aff_entry->ae_flags == NULL)
5704 int idx;
5705 char_u **pp;
5706 int n;
5708 /* Find a previously used condition. */
5709 for (idx = spin->si_prefcond.ga_len - 1; idx >= 0;
5710 --idx)
5712 p = ((char_u **)spin->si_prefcond.ga_data)[idx];
5713 if (str_equal(p, aff_entry->ae_cond))
5714 break;
5716 if (idx < 0 && ga_grow(&spin->si_prefcond, 1) == OK)
5718 /* Not found, add a new condition. */
5719 idx = spin->si_prefcond.ga_len++;
5720 pp = ((char_u **)spin->si_prefcond.ga_data)
5721 + idx;
5722 if (aff_entry->ae_cond == NULL)
5723 *pp = NULL;
5724 else
5725 *pp = getroom_save(spin,
5726 aff_entry->ae_cond);
5729 /* Add the prefix to the prefix tree. */
5730 if (aff_entry->ae_add == NULL)
5731 p = (char_u *)"";
5732 else
5733 p = aff_entry->ae_add;
5735 /* PFX_FLAGS is a negative number, so that
5736 * tree_add_word() knows this is the prefix tree. */
5737 n = PFX_FLAGS;
5738 if (!cur_aff->ah_combine)
5739 n |= WFP_NC;
5740 if (upper)
5741 n |= WFP_UP;
5742 if (aff_entry->ae_comppermit)
5743 n |= WFP_COMPPERMIT;
5744 if (aff_entry->ae_compforbid)
5745 n |= WFP_COMPFORBID;
5746 tree_add_word(spin, p, spin->si_prefroot, n,
5747 idx, cur_aff->ah_newID);
5748 did_postpone_prefix = TRUE;
5751 /* Didn't actually use ah_newID, backup si_newprefID. */
5752 if (aff_todo == 0 && !did_postpone_prefix)
5754 --spin->si_newprefID;
5755 cur_aff->ah_newID = 0;
5760 else if (STRCMP(items[0], "FOL") == 0 && itemcnt == 2
5761 && fol == NULL)
5763 fol = vim_strsave(items[1]);
5765 else if (STRCMP(items[0], "LOW") == 0 && itemcnt == 2
5766 && low == NULL)
5768 low = vim_strsave(items[1]);
5770 else if (STRCMP(items[0], "UPP") == 0 && itemcnt == 2
5771 && upp == NULL)
5773 upp = vim_strsave(items[1]);
5775 else if ((STRCMP(items[0], "REP") == 0
5776 || STRCMP(items[0], "REPSAL") == 0)
5777 && itemcnt == 2)
5779 /* Ignore REP/REPSAL count */;
5780 if (!isdigit(*items[1]))
5781 smsg((char_u *)_("Expected REP(SAL) count in %s line %d"),
5782 fname, lnum);
5784 else if ((STRCMP(items[0], "REP") == 0
5785 || STRCMP(items[0], "REPSAL") == 0)
5786 && itemcnt >= 3)
5788 /* REP/REPSAL item */
5789 /* Myspell ignores extra arguments, we require it starts with
5790 * # to detect mistakes. */
5791 if (itemcnt > 3 && items[3][0] != '#')
5792 smsg((char_u *)_(e_afftrailing), fname, lnum, items[3]);
5793 if (items[0][3] == 'S' ? do_repsal : do_rep)
5795 /* Replace underscore with space (can't include a space
5796 * directly). */
5797 for (p = items[1]; *p != NUL; mb_ptr_adv(p))
5798 if (*p == '_')
5799 *p = ' ';
5800 for (p = items[2]; *p != NUL; mb_ptr_adv(p))
5801 if (*p == '_')
5802 *p = ' ';
5803 add_fromto(spin, items[0][3] == 'S'
5804 ? &spin->si_repsal
5805 : &spin->si_rep, items[1], items[2]);
5808 else if (STRCMP(items[0], "MAP") == 0 && itemcnt == 2)
5810 /* MAP item or count */
5811 if (!found_map)
5813 /* First line contains the count. */
5814 found_map = TRUE;
5815 if (!isdigit(*items[1]))
5816 smsg((char_u *)_("Expected MAP count in %s line %d"),
5817 fname, lnum);
5819 else if (do_mapline)
5821 int c;
5823 /* Check that every character appears only once. */
5824 for (p = items[1]; *p != NUL; )
5826 #ifdef FEAT_MBYTE
5827 c = mb_ptr2char_adv(&p);
5828 #else
5829 c = *p++;
5830 #endif
5831 if ((spin->si_map.ga_len > 0
5832 && vim_strchr(spin->si_map.ga_data, c)
5833 != NULL)
5834 || vim_strchr(p, c) != NULL)
5835 smsg((char_u *)_("Duplicate character in MAP in %s line %d"),
5836 fname, lnum);
5839 /* We simply concatenate all the MAP strings, separated by
5840 * slashes. */
5841 ga_concat(&spin->si_map, items[1]);
5842 ga_append(&spin->si_map, '/');
5845 /* Accept "SAL from to" and "SAL from to # comment". */
5846 else if (STRCMP(items[0], "SAL") == 0
5847 && (itemcnt == 3 || (itemcnt > 3 && items[3][0] == '#')))
5849 if (do_sal)
5851 /* SAL item (sounds-a-like)
5852 * Either one of the known keys or a from-to pair. */
5853 if (STRCMP(items[1], "followup") == 0)
5854 spin->si_followup = sal_to_bool(items[2]);
5855 else if (STRCMP(items[1], "collapse_result") == 0)
5856 spin->si_collapse = sal_to_bool(items[2]);
5857 else if (STRCMP(items[1], "remove_accents") == 0)
5858 spin->si_rem_accents = sal_to_bool(items[2]);
5859 else
5860 /* when "to" is "_" it means empty */
5861 add_fromto(spin, &spin->si_sal, items[1],
5862 STRCMP(items[2], "_") == 0 ? (char_u *)""
5863 : items[2]);
5866 else if (STRCMP(items[0], "SOFOFROM") == 0 && itemcnt == 2
5867 && sofofrom == NULL)
5869 sofofrom = getroom_save(spin, items[1]);
5871 else if (STRCMP(items[0], "SOFOTO") == 0 && itemcnt == 2
5872 && sofoto == NULL)
5874 sofoto = getroom_save(spin, items[1]);
5876 else if (STRCMP(items[0], "COMMON") == 0)
5878 int i;
5880 for (i = 1; i < itemcnt; ++i)
5882 if (HASHITEM_EMPTY(hash_find(&spin->si_commonwords,
5883 items[i])))
5885 p = vim_strsave(items[i]);
5886 if (p == NULL)
5887 break;
5888 hash_add(&spin->si_commonwords, p);
5892 else
5893 smsg((char_u *)_("Unrecognized or duplicate item in %s line %d: %s"),
5894 fname, lnum, items[0]);
5898 if (fol != NULL || low != NULL || upp != NULL)
5900 if (spin->si_clear_chartab)
5902 /* Clear the char type tables, don't want to use any of the
5903 * currently used spell properties. */
5904 init_spell_chartab();
5905 spin->si_clear_chartab = FALSE;
5909 * Don't write a word table for an ASCII file, so that we don't check
5910 * for conflicts with a word table that matches 'encoding'.
5911 * Don't write one for utf-8 either, we use utf_*() and
5912 * mb_get_class(), the list of chars in the file will be incomplete.
5914 if (!spin->si_ascii
5915 #ifdef FEAT_MBYTE
5916 && !enc_utf8
5917 #endif
5920 if (fol == NULL || low == NULL || upp == NULL)
5921 smsg((char_u *)_("Missing FOL/LOW/UPP line in %s"), fname);
5922 else
5923 (void)set_spell_chartab(fol, low, upp);
5926 vim_free(fol);
5927 vim_free(low);
5928 vim_free(upp);
5931 /* Use compound specifications of the .aff file for the spell info. */
5932 if (compmax != 0)
5934 aff_check_number(spin->si_compmax, compmax, "COMPOUNDWORDMAX");
5935 spin->si_compmax = compmax;
5938 if (compminlen != 0)
5940 aff_check_number(spin->si_compminlen, compminlen, "COMPOUNDMIN");
5941 spin->si_compminlen = compminlen;
5944 if (compsylmax != 0)
5946 if (syllable == NULL)
5947 smsg((char_u *)_("COMPOUNDSYLMAX used without SYLLABLE"));
5948 aff_check_number(spin->si_compsylmax, compsylmax, "COMPOUNDSYLMAX");
5949 spin->si_compsylmax = compsylmax;
5952 if (compoptions != 0)
5954 aff_check_number(spin->si_compoptions, compoptions, "COMPOUND options");
5955 spin->si_compoptions |= compoptions;
5958 if (compflags != NULL)
5959 process_compflags(spin, aff, compflags);
5961 /* Check that we didn't use too many renumbered flags. */
5962 if (spin->si_newcompID < spin->si_newprefID)
5964 if (spin->si_newcompID == 127 || spin->si_newcompID == 255)
5965 MSG(_("Too many postponed prefixes"));
5966 else if (spin->si_newprefID == 0 || spin->si_newprefID == 127)
5967 MSG(_("Too many compound flags"));
5968 else
5969 MSG(_("Too many posponed prefixes and/or compound flags"));
5972 if (syllable != NULL)
5974 aff_check_string(spin->si_syllable, syllable, "SYLLABLE");
5975 spin->si_syllable = syllable;
5978 if (sofofrom != NULL || sofoto != NULL)
5980 if (sofofrom == NULL || sofoto == NULL)
5981 smsg((char_u *)_("Missing SOFO%s line in %s"),
5982 sofofrom == NULL ? "FROM" : "TO", fname);
5983 else if (spin->si_sal.ga_len > 0)
5984 smsg((char_u *)_("Both SAL and SOFO lines in %s"), fname);
5985 else
5987 aff_check_string(spin->si_sofofr, sofofrom, "SOFOFROM");
5988 aff_check_string(spin->si_sofoto, sofoto, "SOFOTO");
5989 spin->si_sofofr = sofofrom;
5990 spin->si_sofoto = sofoto;
5994 if (midword != NULL)
5996 aff_check_string(spin->si_midword, midword, "MIDWORD");
5997 spin->si_midword = midword;
6000 vim_free(pc);
6001 fclose(fd);
6002 return aff;
6006 * For affix "entry" move COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG from
6007 * ae_flags to ae_comppermit and ae_compforbid.
6009 static void
6010 aff_process_flags(affile, entry)
6011 afffile_T *affile;
6012 affentry_T *entry;
6014 char_u *p;
6015 char_u *prevp;
6016 unsigned flag;
6018 if (entry->ae_flags != NULL
6019 && (affile->af_compforbid != 0 || affile->af_comppermit != 0))
6021 for (p = entry->ae_flags; *p != NUL; )
6023 prevp = p;
6024 flag = get_affitem(affile->af_flagtype, &p);
6025 if (flag == affile->af_comppermit || flag == affile->af_compforbid)
6027 mch_memmove(prevp, p, STRLEN(p) + 1);
6028 p = prevp;
6029 if (flag == affile->af_comppermit)
6030 entry->ae_comppermit = TRUE;
6031 else
6032 entry->ae_compforbid = TRUE;
6034 if (affile->af_flagtype == AFT_NUM && *p == ',')
6035 ++p;
6037 if (*entry->ae_flags == NUL)
6038 entry->ae_flags = NULL; /* nothing left */
6043 * Return TRUE if "s" is the name of an info item in the affix file.
6045 static int
6046 spell_info_item(s)
6047 char_u *s;
6049 return STRCMP(s, "NAME") == 0
6050 || STRCMP(s, "HOME") == 0
6051 || STRCMP(s, "VERSION") == 0
6052 || STRCMP(s, "AUTHOR") == 0
6053 || STRCMP(s, "EMAIL") == 0
6054 || STRCMP(s, "COPYRIGHT") == 0;
6058 * Turn an affix flag name into a number, according to the FLAG type.
6059 * returns zero for failure.
6061 static unsigned
6062 affitem2flag(flagtype, item, fname, lnum)
6063 int flagtype;
6064 char_u *item;
6065 char_u *fname;
6066 int lnum;
6068 unsigned res;
6069 char_u *p = item;
6071 res = get_affitem(flagtype, &p);
6072 if (res == 0)
6074 if (flagtype == AFT_NUM)
6075 smsg((char_u *)_("Flag is not a number in %s line %d: %s"),
6076 fname, lnum, item);
6077 else
6078 smsg((char_u *)_("Illegal flag in %s line %d: %s"),
6079 fname, lnum, item);
6081 if (*p != NUL)
6083 smsg((char_u *)_(e_affname), fname, lnum, item);
6084 return 0;
6087 return res;
6091 * Get one affix name from "*pp" and advance the pointer.
6092 * Returns zero for an error, still advances the pointer then.
6094 static unsigned
6095 get_affitem(flagtype, pp)
6096 int flagtype;
6097 char_u **pp;
6099 int res;
6101 if (flagtype == AFT_NUM)
6103 if (!VIM_ISDIGIT(**pp))
6105 ++*pp; /* always advance, avoid getting stuck */
6106 return 0;
6108 res = getdigits(pp);
6110 else
6112 #ifdef FEAT_MBYTE
6113 res = mb_ptr2char_adv(pp);
6114 #else
6115 res = *(*pp)++;
6116 #endif
6117 if (flagtype == AFT_LONG || (flagtype == AFT_CAPLONG
6118 && res >= 'A' && res <= 'Z'))
6120 if (**pp == NUL)
6121 return 0;
6122 #ifdef FEAT_MBYTE
6123 res = mb_ptr2char_adv(pp) + (res << 16);
6124 #else
6125 res = *(*pp)++ + (res << 16);
6126 #endif
6129 return res;
6133 * Process the "compflags" string used in an affix file and append it to
6134 * spin->si_compflags.
6135 * The processing involves changing the affix names to ID numbers, so that
6136 * they fit in one byte.
6138 static void
6139 process_compflags(spin, aff, compflags)
6140 spellinfo_T *spin;
6141 afffile_T *aff;
6142 char_u *compflags;
6144 char_u *p;
6145 char_u *prevp;
6146 unsigned flag;
6147 compitem_T *ci;
6148 int id;
6149 int len;
6150 char_u *tp;
6151 char_u key[AH_KEY_LEN];
6152 hashitem_T *hi;
6154 /* Make room for the old and the new compflags, concatenated with a / in
6155 * between. Processing it makes it shorter, but we don't know by how
6156 * much, thus allocate the maximum. */
6157 len = (int)STRLEN(compflags) + 1;
6158 if (spin->si_compflags != NULL)
6159 len += (int)STRLEN(spin->si_compflags) + 1;
6160 p = getroom(spin, len, FALSE);
6161 if (p == NULL)
6162 return;
6163 if (spin->si_compflags != NULL)
6165 STRCPY(p, spin->si_compflags);
6166 STRCAT(p, "/");
6168 spin->si_compflags = p;
6169 tp = p + STRLEN(p);
6171 for (p = compflags; *p != NUL; )
6173 if (vim_strchr((char_u *)"/*+[]", *p) != NULL)
6174 /* Copy non-flag characters directly. */
6175 *tp++ = *p++;
6176 else
6178 /* First get the flag number, also checks validity. */
6179 prevp = p;
6180 flag = get_affitem(aff->af_flagtype, &p);
6181 if (flag != 0)
6183 /* Find the flag in the hashtable. If it was used before, use
6184 * the existing ID. Otherwise add a new entry. */
6185 vim_strncpy(key, prevp, p - prevp);
6186 hi = hash_find(&aff->af_comp, key);
6187 if (!HASHITEM_EMPTY(hi))
6188 id = HI2CI(hi)->ci_newID;
6189 else
6191 ci = (compitem_T *)getroom(spin, sizeof(compitem_T), TRUE);
6192 if (ci == NULL)
6193 break;
6194 STRCPY(ci->ci_key, key);
6195 ci->ci_flag = flag;
6196 /* Avoid using a flag ID that has a special meaning in a
6197 * regexp (also inside []). */
6200 check_renumber(spin);
6201 id = spin->si_newcompID--;
6202 } while (vim_strchr((char_u *)"/+*[]\\-^", id) != NULL);
6203 ci->ci_newID = id;
6204 hash_add(&aff->af_comp, ci->ci_key);
6206 *tp++ = id;
6208 if (aff->af_flagtype == AFT_NUM && *p == ',')
6209 ++p;
6213 *tp = NUL;
6217 * Check that the new IDs for postponed affixes and compounding don't overrun
6218 * each other. We have almost 255 available, but start at 0-127 to avoid
6219 * using two bytes for utf-8. When the 0-127 range is used up go to 128-255.
6220 * When that is used up an error message is given.
6222 static void
6223 check_renumber(spin)
6224 spellinfo_T *spin;
6226 if (spin->si_newprefID == spin->si_newcompID && spin->si_newcompID < 128)
6228 spin->si_newprefID = 127;
6229 spin->si_newcompID = 255;
6234 * Return TRUE if flag "flag" appears in affix list "afflist".
6236 static int
6237 flag_in_afflist(flagtype, afflist, flag)
6238 int flagtype;
6239 char_u *afflist;
6240 unsigned flag;
6242 char_u *p;
6243 unsigned n;
6245 switch (flagtype)
6247 case AFT_CHAR:
6248 return vim_strchr(afflist, flag) != NULL;
6250 case AFT_CAPLONG:
6251 case AFT_LONG:
6252 for (p = afflist; *p != NUL; )
6254 #ifdef FEAT_MBYTE
6255 n = mb_ptr2char_adv(&p);
6256 #else
6257 n = *p++;
6258 #endif
6259 if ((flagtype == AFT_LONG || (n >= 'A' && n <= 'Z'))
6260 && *p != NUL)
6261 #ifdef FEAT_MBYTE
6262 n = mb_ptr2char_adv(&p) + (n << 16);
6263 #else
6264 n = *p++ + (n << 16);
6265 #endif
6266 if (n == flag)
6267 return TRUE;
6269 break;
6271 case AFT_NUM:
6272 for (p = afflist; *p != NUL; )
6274 n = getdigits(&p);
6275 if (n == flag)
6276 return TRUE;
6277 if (*p != NUL) /* skip over comma */
6278 ++p;
6280 break;
6282 return FALSE;
6286 * Give a warning when "spinval" and "affval" numbers are set and not the same.
6288 static void
6289 aff_check_number(spinval, affval, name)
6290 int spinval;
6291 int affval;
6292 char *name;
6294 if (spinval != 0 && spinval != affval)
6295 smsg((char_u *)_("%s value differs from what is used in another .aff file"), name);
6299 * Give a warning when "spinval" and "affval" strings are set and not the same.
6301 static void
6302 aff_check_string(spinval, affval, name)
6303 char_u *spinval;
6304 char_u *affval;
6305 char *name;
6307 if (spinval != NULL && STRCMP(spinval, affval) != 0)
6308 smsg((char_u *)_("%s value differs from what is used in another .aff file"), name);
6312 * Return TRUE if strings "s1" and "s2" are equal. Also consider both being
6313 * NULL as equal.
6315 static int
6316 str_equal(s1, s2)
6317 char_u *s1;
6318 char_u *s2;
6320 if (s1 == NULL || s2 == NULL)
6321 return s1 == s2;
6322 return STRCMP(s1, s2) == 0;
6326 * Add a from-to item to "gap". Used for REP and SAL items.
6327 * They are stored case-folded.
6329 static void
6330 add_fromto(spin, gap, from, to)
6331 spellinfo_T *spin;
6332 garray_T *gap;
6333 char_u *from;
6334 char_u *to;
6336 fromto_T *ftp;
6337 char_u word[MAXWLEN];
6339 if (ga_grow(gap, 1) == OK)
6341 ftp = ((fromto_T *)gap->ga_data) + gap->ga_len;
6342 (void)spell_casefold(from, (int)STRLEN(from), word, MAXWLEN);
6343 ftp->ft_from = getroom_save(spin, word);
6344 (void)spell_casefold(to, (int)STRLEN(to), word, MAXWLEN);
6345 ftp->ft_to = getroom_save(spin, word);
6346 ++gap->ga_len;
6351 * Convert a boolean argument in a SAL line to TRUE or FALSE;
6353 static int
6354 sal_to_bool(s)
6355 char_u *s;
6357 return STRCMP(s, "1") == 0 || STRCMP(s, "true") == 0;
6361 * Return TRUE if string "s" contains a non-ASCII character (128 or higher).
6362 * When "s" is NULL FALSE is returned.
6364 static int
6365 has_non_ascii(s)
6366 char_u *s;
6368 char_u *p;
6370 if (s != NULL)
6371 for (p = s; *p != NUL; ++p)
6372 if (*p >= 128)
6373 return TRUE;
6374 return FALSE;
6378 * Free the structure filled by spell_read_aff().
6380 static void
6381 spell_free_aff(aff)
6382 afffile_T *aff;
6384 hashtab_T *ht;
6385 hashitem_T *hi;
6386 int todo;
6387 affheader_T *ah;
6388 affentry_T *ae;
6390 vim_free(aff->af_enc);
6392 /* All this trouble to free the "ae_prog" items... */
6393 for (ht = &aff->af_pref; ; ht = &aff->af_suff)
6395 todo = (int)ht->ht_used;
6396 for (hi = ht->ht_array; todo > 0; ++hi)
6398 if (!HASHITEM_EMPTY(hi))
6400 --todo;
6401 ah = HI2AH(hi);
6402 for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
6403 vim_free(ae->ae_prog);
6406 if (ht == &aff->af_suff)
6407 break;
6410 hash_clear(&aff->af_pref);
6411 hash_clear(&aff->af_suff);
6412 hash_clear(&aff->af_comp);
6416 * Read dictionary file "fname".
6417 * Returns OK or FAIL;
6419 static int
6420 spell_read_dic(spin, fname, affile)
6421 spellinfo_T *spin;
6422 char_u *fname;
6423 afffile_T *affile;
6425 hashtab_T ht;
6426 char_u line[MAXLINELEN];
6427 char_u *p;
6428 char_u *afflist;
6429 char_u store_afflist[MAXWLEN];
6430 int pfxlen;
6431 int need_affix;
6432 char_u *dw;
6433 char_u *pc;
6434 char_u *w;
6435 int l;
6436 hash_T hash;
6437 hashitem_T *hi;
6438 FILE *fd;
6439 int lnum = 1;
6440 int non_ascii = 0;
6441 int retval = OK;
6442 char_u message[MAXLINELEN + MAXWLEN];
6443 int flags;
6444 int duplicate = 0;
6447 * Open the file.
6449 fd = mch_fopen((char *)fname, "r");
6450 if (fd == NULL)
6452 EMSG2(_(e_notopen), fname);
6453 return FAIL;
6456 /* The hashtable is only used to detect duplicated words. */
6457 hash_init(&ht);
6459 vim_snprintf((char *)IObuff, IOSIZE,
6460 _("Reading dictionary file %s ..."), fname);
6461 spell_message(spin, IObuff);
6463 /* start with a message for the first line */
6464 spin->si_msg_count = 999999;
6466 /* Read and ignore the first line: word count. */
6467 (void)vim_fgets(line, MAXLINELEN, fd);
6468 if (!vim_isdigit(*skipwhite(line)))
6469 EMSG2(_("E760: No word count in %s"), fname);
6472 * Read all the lines in the file one by one.
6473 * The words are converted to 'encoding' here, before being added to
6474 * the hashtable.
6476 while (!vim_fgets(line, MAXLINELEN, fd) && !got_int)
6478 line_breakcheck();
6479 ++lnum;
6480 if (line[0] == '#' || line[0] == '/')
6481 continue; /* comment line */
6483 /* Remove CR, LF and white space from the end. White space halfway
6484 * the word is kept to allow e.g., "et al.". */
6485 l = (int)STRLEN(line);
6486 while (l > 0 && line[l - 1] <= ' ')
6487 --l;
6488 if (l == 0)
6489 continue; /* empty line */
6490 line[l] = NUL;
6492 #ifdef FEAT_MBYTE
6493 /* Convert from "SET" to 'encoding' when needed. */
6494 if (spin->si_conv.vc_type != CONV_NONE)
6496 pc = string_convert(&spin->si_conv, line, NULL);
6497 if (pc == NULL)
6499 smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
6500 fname, lnum, line);
6501 continue;
6503 w = pc;
6505 else
6506 #endif
6508 pc = NULL;
6509 w = line;
6512 /* Truncate the word at the "/", set "afflist" to what follows.
6513 * Replace "\/" by "/" and "\\" by "\". */
6514 afflist = NULL;
6515 for (p = w; *p != NUL; mb_ptr_adv(p))
6517 if (*p == '\\' && (p[1] == '\\' || p[1] == '/'))
6518 mch_memmove(p, p + 1, STRLEN(p));
6519 else if (*p == '/')
6521 *p = NUL;
6522 afflist = p + 1;
6523 break;
6527 /* Skip non-ASCII words when "spin->si_ascii" is TRUE. */
6528 if (spin->si_ascii && has_non_ascii(w))
6530 ++non_ascii;
6531 vim_free(pc);
6532 continue;
6535 /* This takes time, print a message every 10000 words. */
6536 if (spin->si_verbose && spin->si_msg_count > 10000)
6538 spin->si_msg_count = 0;
6539 vim_snprintf((char *)message, sizeof(message),
6540 _("line %6d, word %6d - %s"),
6541 lnum, spin->si_foldwcount + spin->si_keepwcount, w);
6542 msg_start();
6543 msg_puts_long_attr(message, 0);
6544 msg_clr_eos();
6545 msg_didout = FALSE;
6546 msg_col = 0;
6547 out_flush();
6550 /* Store the word in the hashtable to be able to find duplicates. */
6551 dw = (char_u *)getroom_save(spin, w);
6552 if (dw == NULL)
6554 retval = FAIL;
6555 vim_free(pc);
6556 break;
6559 hash = hash_hash(dw);
6560 hi = hash_lookup(&ht, dw, hash);
6561 if (!HASHITEM_EMPTY(hi))
6563 if (p_verbose > 0)
6564 smsg((char_u *)_("Duplicate word in %s line %d: %s"),
6565 fname, lnum, dw);
6566 else if (duplicate == 0)
6567 smsg((char_u *)_("First duplicate word in %s line %d: %s"),
6568 fname, lnum, dw);
6569 ++duplicate;
6571 else
6572 hash_add_item(&ht, hi, dw, hash);
6574 flags = 0;
6575 store_afflist[0] = NUL;
6576 pfxlen = 0;
6577 need_affix = FALSE;
6578 if (afflist != NULL)
6580 /* Extract flags from the affix list. */
6581 flags |= get_affix_flags(affile, afflist);
6583 if (affile->af_needaffix != 0 && flag_in_afflist(
6584 affile->af_flagtype, afflist, affile->af_needaffix))
6585 need_affix = TRUE;
6587 if (affile->af_pfxpostpone)
6588 /* Need to store the list of prefix IDs with the word. */
6589 pfxlen = get_pfxlist(affile, afflist, store_afflist);
6591 if (spin->si_compflags != NULL)
6592 /* Need to store the list of compound flags with the word.
6593 * Concatenate them to the list of prefix IDs. */
6594 get_compflags(affile, afflist, store_afflist + pfxlen);
6597 /* Add the word to the word tree(s). */
6598 if (store_word(spin, dw, flags, spin->si_region,
6599 store_afflist, need_affix) == FAIL)
6600 retval = FAIL;
6602 if (afflist != NULL)
6604 /* Find all matching suffixes and add the resulting words.
6605 * Additionally do matching prefixes that combine. */
6606 if (store_aff_word(spin, dw, afflist, affile,
6607 &affile->af_suff, &affile->af_pref,
6608 CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
6609 retval = FAIL;
6611 /* Find all matching prefixes and add the resulting words. */
6612 if (store_aff_word(spin, dw, afflist, affile,
6613 &affile->af_pref, NULL,
6614 CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
6615 retval = FAIL;
6618 vim_free(pc);
6621 if (duplicate > 0)
6622 smsg((char_u *)_("%d duplicate word(s) in %s"), duplicate, fname);
6623 if (spin->si_ascii && non_ascii > 0)
6624 smsg((char_u *)_("Ignored %d word(s) with non-ASCII characters in %s"),
6625 non_ascii, fname);
6626 hash_clear(&ht);
6628 fclose(fd);
6629 return retval;
6633 * Check for affix flags in "afflist" that are turned into word flags.
6634 * Return WF_ flags.
6636 static int
6637 get_affix_flags(affile, afflist)
6638 afffile_T *affile;
6639 char_u *afflist;
6641 int flags = 0;
6643 if (affile->af_keepcase != 0 && flag_in_afflist(
6644 affile->af_flagtype, afflist, affile->af_keepcase))
6645 flags |= WF_KEEPCAP | WF_FIXCAP;
6646 if (affile->af_rare != 0 && flag_in_afflist(
6647 affile->af_flagtype, afflist, affile->af_rare))
6648 flags |= WF_RARE;
6649 if (affile->af_bad != 0 && flag_in_afflist(
6650 affile->af_flagtype, afflist, affile->af_bad))
6651 flags |= WF_BANNED;
6652 if (affile->af_needcomp != 0 && flag_in_afflist(
6653 affile->af_flagtype, afflist, affile->af_needcomp))
6654 flags |= WF_NEEDCOMP;
6655 if (affile->af_comproot != 0 && flag_in_afflist(
6656 affile->af_flagtype, afflist, affile->af_comproot))
6657 flags |= WF_COMPROOT;
6658 if (affile->af_nosuggest != 0 && flag_in_afflist(
6659 affile->af_flagtype, afflist, affile->af_nosuggest))
6660 flags |= WF_NOSUGGEST;
6661 return flags;
6665 * Get the list of prefix IDs from the affix list "afflist".
6666 * Used for PFXPOSTPONE.
6667 * Put the resulting flags in "store_afflist[MAXWLEN]" with a terminating NUL
6668 * and return the number of affixes.
6670 static int
6671 get_pfxlist(affile, afflist, store_afflist)
6672 afffile_T *affile;
6673 char_u *afflist;
6674 char_u *store_afflist;
6676 char_u *p;
6677 char_u *prevp;
6678 int cnt = 0;
6679 int id;
6680 char_u key[AH_KEY_LEN];
6681 hashitem_T *hi;
6683 for (p = afflist; *p != NUL; )
6685 prevp = p;
6686 if (get_affitem(affile->af_flagtype, &p) != 0)
6688 /* A flag is a postponed prefix flag if it appears in "af_pref"
6689 * and it's ID is not zero. */
6690 vim_strncpy(key, prevp, p - prevp);
6691 hi = hash_find(&affile->af_pref, key);
6692 if (!HASHITEM_EMPTY(hi))
6694 id = HI2AH(hi)->ah_newID;
6695 if (id != 0)
6696 store_afflist[cnt++] = id;
6699 if (affile->af_flagtype == AFT_NUM && *p == ',')
6700 ++p;
6703 store_afflist[cnt] = NUL;
6704 return cnt;
6708 * Get the list of compound IDs from the affix list "afflist" that are used
6709 * for compound words.
6710 * Puts the flags in "store_afflist[]".
6712 static void
6713 get_compflags(affile, afflist, store_afflist)
6714 afffile_T *affile;
6715 char_u *afflist;
6716 char_u *store_afflist;
6718 char_u *p;
6719 char_u *prevp;
6720 int cnt = 0;
6721 char_u key[AH_KEY_LEN];
6722 hashitem_T *hi;
6724 for (p = afflist; *p != NUL; )
6726 prevp = p;
6727 if (get_affitem(affile->af_flagtype, &p) != 0)
6729 /* A flag is a compound flag if it appears in "af_comp". */
6730 vim_strncpy(key, prevp, p - prevp);
6731 hi = hash_find(&affile->af_comp, key);
6732 if (!HASHITEM_EMPTY(hi))
6733 store_afflist[cnt++] = HI2CI(hi)->ci_newID;
6735 if (affile->af_flagtype == AFT_NUM && *p == ',')
6736 ++p;
6739 store_afflist[cnt] = NUL;
6743 * Apply affixes to a word and store the resulting words.
6744 * "ht" is the hashtable with affentry_T that need to be applied, either
6745 * prefixes or suffixes.
6746 * "xht", when not NULL, is the prefix hashtable, to be used additionally on
6747 * the resulting words for combining affixes.
6749 * Returns FAIL when out of memory.
6751 static int
6752 store_aff_word(spin, word, afflist, affile, ht, xht, condit, flags,
6753 pfxlist, pfxlen)
6754 spellinfo_T *spin; /* spell info */
6755 char_u *word; /* basic word start */
6756 char_u *afflist; /* list of names of supported affixes */
6757 afffile_T *affile;
6758 hashtab_T *ht;
6759 hashtab_T *xht;
6760 int condit; /* CONDIT_SUF et al. */
6761 int flags; /* flags for the word */
6762 char_u *pfxlist; /* list of prefix IDs */
6763 int pfxlen; /* nr of flags in "pfxlist" for prefixes, rest
6764 * is compound flags */
6766 int todo;
6767 hashitem_T *hi;
6768 affheader_T *ah;
6769 affentry_T *ae;
6770 regmatch_T regmatch;
6771 char_u newword[MAXWLEN];
6772 int retval = OK;
6773 int i, j;
6774 char_u *p;
6775 int use_flags;
6776 char_u *use_pfxlist;
6777 int use_pfxlen;
6778 int need_affix;
6779 char_u store_afflist[MAXWLEN];
6780 char_u pfx_pfxlist[MAXWLEN];
6781 size_t wordlen = STRLEN(word);
6782 int use_condit;
6784 todo = (int)ht->ht_used;
6785 for (hi = ht->ht_array; todo > 0 && retval == OK; ++hi)
6787 if (!HASHITEM_EMPTY(hi))
6789 --todo;
6790 ah = HI2AH(hi);
6792 /* Check that the affix combines, if required, and that the word
6793 * supports this affix. */
6794 if (((condit & CONDIT_COMB) == 0 || ah->ah_combine)
6795 && flag_in_afflist(affile->af_flagtype, afflist,
6796 ah->ah_flag))
6798 /* Loop over all affix entries with this name. */
6799 for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
6801 /* Check the condition. It's not logical to match case
6802 * here, but it is required for compatibility with
6803 * Myspell.
6804 * Another requirement from Myspell is that the chop
6805 * string is shorter than the word itself.
6806 * For prefixes, when "PFXPOSTPONE" was used, only do
6807 * prefixes with a chop string and/or flags.
6808 * When a previously added affix had CIRCUMFIX this one
6809 * must have it too, if it had not then this one must not
6810 * have one either. */
6811 regmatch.regprog = ae->ae_prog;
6812 regmatch.rm_ic = FALSE;
6813 if ((xht != NULL || !affile->af_pfxpostpone
6814 || ae->ae_chop != NULL
6815 || ae->ae_flags != NULL)
6816 && (ae->ae_chop == NULL
6817 || STRLEN(ae->ae_chop) < wordlen)
6818 && (ae->ae_prog == NULL
6819 || vim_regexec(&regmatch, word, (colnr_T)0))
6820 && (((condit & CONDIT_CFIX) == 0)
6821 == ((condit & CONDIT_AFF) == 0
6822 || ae->ae_flags == NULL
6823 || !flag_in_afflist(affile->af_flagtype,
6824 ae->ae_flags, affile->af_circumfix))))
6826 /* Match. Remove the chop and add the affix. */
6827 if (xht == NULL)
6829 /* prefix: chop/add at the start of the word */
6830 if (ae->ae_add == NULL)
6831 *newword = NUL;
6832 else
6833 STRCPY(newword, ae->ae_add);
6834 p = word;
6835 if (ae->ae_chop != NULL)
6837 /* Skip chop string. */
6838 #ifdef FEAT_MBYTE
6839 if (has_mbyte)
6841 i = mb_charlen(ae->ae_chop);
6842 for ( ; i > 0; --i)
6843 mb_ptr_adv(p);
6845 else
6846 #endif
6847 p += STRLEN(ae->ae_chop);
6849 STRCAT(newword, p);
6851 else
6853 /* suffix: chop/add at the end of the word */
6854 STRCPY(newword, word);
6855 if (ae->ae_chop != NULL)
6857 /* Remove chop string. */
6858 p = newword + STRLEN(newword);
6859 i = (int)MB_CHARLEN(ae->ae_chop);
6860 for ( ; i > 0; --i)
6861 mb_ptr_back(newword, p);
6862 *p = NUL;
6864 if (ae->ae_add != NULL)
6865 STRCAT(newword, ae->ae_add);
6868 use_flags = flags;
6869 use_pfxlist = pfxlist;
6870 use_pfxlen = pfxlen;
6871 need_affix = FALSE;
6872 use_condit = condit | CONDIT_COMB | CONDIT_AFF;
6873 if (ae->ae_flags != NULL)
6875 /* Extract flags from the affix list. */
6876 use_flags |= get_affix_flags(affile, ae->ae_flags);
6878 if (affile->af_needaffix != 0 && flag_in_afflist(
6879 affile->af_flagtype, ae->ae_flags,
6880 affile->af_needaffix))
6881 need_affix = TRUE;
6883 /* When there is a CIRCUMFIX flag the other affix
6884 * must also have it and we don't add the word
6885 * with one affix. */
6886 if (affile->af_circumfix != 0 && flag_in_afflist(
6887 affile->af_flagtype, ae->ae_flags,
6888 affile->af_circumfix))
6890 use_condit |= CONDIT_CFIX;
6891 if ((condit & CONDIT_CFIX) == 0)
6892 need_affix = TRUE;
6895 if (affile->af_pfxpostpone
6896 || spin->si_compflags != NULL)
6898 if (affile->af_pfxpostpone)
6899 /* Get prefix IDS from the affix list. */
6900 use_pfxlen = get_pfxlist(affile,
6901 ae->ae_flags, store_afflist);
6902 else
6903 use_pfxlen = 0;
6904 use_pfxlist = store_afflist;
6906 /* Combine the prefix IDs. Avoid adding the
6907 * same ID twice. */
6908 for (i = 0; i < pfxlen; ++i)
6910 for (j = 0; j < use_pfxlen; ++j)
6911 if (pfxlist[i] == use_pfxlist[j])
6912 break;
6913 if (j == use_pfxlen)
6914 use_pfxlist[use_pfxlen++] = pfxlist[i];
6917 if (spin->si_compflags != NULL)
6918 /* Get compound IDS from the affix list. */
6919 get_compflags(affile, ae->ae_flags,
6920 use_pfxlist + use_pfxlen);
6922 /* Combine the list of compound flags.
6923 * Concatenate them to the prefix IDs list.
6924 * Avoid adding the same ID twice. */
6925 for (i = pfxlen; pfxlist[i] != NUL; ++i)
6927 for (j = use_pfxlen;
6928 use_pfxlist[j] != NUL; ++j)
6929 if (pfxlist[i] == use_pfxlist[j])
6930 break;
6931 if (use_pfxlist[j] == NUL)
6933 use_pfxlist[j++] = pfxlist[i];
6934 use_pfxlist[j] = NUL;
6940 /* Obey a "COMPOUNDFORBIDFLAG" of the affix: don't
6941 * use the compound flags. */
6942 if (use_pfxlist != NULL && ae->ae_compforbid)
6944 vim_strncpy(pfx_pfxlist, use_pfxlist, use_pfxlen);
6945 use_pfxlist = pfx_pfxlist;
6948 /* When there are postponed prefixes... */
6949 if (spin->si_prefroot != NULL
6950 && spin->si_prefroot->wn_sibling != NULL)
6952 /* ... add a flag to indicate an affix was used. */
6953 use_flags |= WF_HAS_AFF;
6955 /* ... don't use a prefix list if combining
6956 * affixes is not allowed. But do use the
6957 * compound flags after them. */
6958 if (!ah->ah_combine && use_pfxlist != NULL)
6959 use_pfxlist += use_pfxlen;
6962 /* When compounding is supported and there is no
6963 * "COMPOUNDPERMITFLAG" then forbid compounding on the
6964 * side where the affix is applied. */
6965 if (spin->si_compflags != NULL && !ae->ae_comppermit)
6967 if (xht != NULL)
6968 use_flags |= WF_NOCOMPAFT;
6969 else
6970 use_flags |= WF_NOCOMPBEF;
6973 /* Store the modified word. */
6974 if (store_word(spin, newword, use_flags,
6975 spin->si_region, use_pfxlist,
6976 need_affix) == FAIL)
6977 retval = FAIL;
6979 /* When added a prefix or a first suffix and the affix
6980 * has flags may add a(nother) suffix. RECURSIVE! */
6981 if ((condit & CONDIT_SUF) && ae->ae_flags != NULL)
6982 if (store_aff_word(spin, newword, ae->ae_flags,
6983 affile, &affile->af_suff, xht,
6984 use_condit & (xht == NULL
6985 ? ~0 : ~CONDIT_SUF),
6986 use_flags, use_pfxlist, pfxlen) == FAIL)
6987 retval = FAIL;
6989 /* When added a suffix and combining is allowed also
6990 * try adding a prefix additionally. Both for the
6991 * word flags and for the affix flags. RECURSIVE! */
6992 if (xht != NULL && ah->ah_combine)
6994 if (store_aff_word(spin, newword,
6995 afflist, affile,
6996 xht, NULL, use_condit,
6997 use_flags, use_pfxlist,
6998 pfxlen) == FAIL
6999 || (ae->ae_flags != NULL
7000 && store_aff_word(spin, newword,
7001 ae->ae_flags, affile,
7002 xht, NULL, use_condit,
7003 use_flags, use_pfxlist,
7004 pfxlen) == FAIL))
7005 retval = FAIL;
7013 return retval;
7017 * Read a file with a list of words.
7019 static int
7020 spell_read_wordfile(spin, fname)
7021 spellinfo_T *spin;
7022 char_u *fname;
7024 FILE *fd;
7025 long lnum = 0;
7026 char_u rline[MAXLINELEN];
7027 char_u *line;
7028 char_u *pc = NULL;
7029 char_u *p;
7030 int l;
7031 int retval = OK;
7032 int did_word = FALSE;
7033 int non_ascii = 0;
7034 int flags;
7035 int regionmask;
7038 * Open the file.
7040 fd = mch_fopen((char *)fname, "r");
7041 if (fd == NULL)
7043 EMSG2(_(e_notopen), fname);
7044 return FAIL;
7047 vim_snprintf((char *)IObuff, IOSIZE, _("Reading word file %s ..."), fname);
7048 spell_message(spin, IObuff);
7051 * Read all the lines in the file one by one.
7053 while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
7055 line_breakcheck();
7056 ++lnum;
7058 /* Skip comment lines. */
7059 if (*rline == '#')
7060 continue;
7062 /* Remove CR, LF and white space from the end. */
7063 l = (int)STRLEN(rline);
7064 while (l > 0 && rline[l - 1] <= ' ')
7065 --l;
7066 if (l == 0)
7067 continue; /* empty or blank line */
7068 rline[l] = NUL;
7070 /* Convert from "/encoding={encoding}" to 'encoding' when needed. */
7071 vim_free(pc);
7072 #ifdef FEAT_MBYTE
7073 if (spin->si_conv.vc_type != CONV_NONE)
7075 pc = string_convert(&spin->si_conv, rline, NULL);
7076 if (pc == NULL)
7078 smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
7079 fname, lnum, rline);
7080 continue;
7082 line = pc;
7084 else
7085 #endif
7087 pc = NULL;
7088 line = rline;
7091 if (*line == '/')
7093 ++line;
7094 if (STRNCMP(line, "encoding=", 9) == 0)
7096 if (spin->si_conv.vc_type != CONV_NONE)
7097 smsg((char_u *)_("Duplicate /encoding= line ignored in %s line %d: %s"),
7098 fname, lnum, line - 1);
7099 else if (did_word)
7100 smsg((char_u *)_("/encoding= line after word ignored in %s line %d: %s"),
7101 fname, lnum, line - 1);
7102 else
7104 #ifdef FEAT_MBYTE
7105 char_u *enc;
7107 /* Setup for conversion to 'encoding'. */
7108 line += 9;
7109 enc = enc_canonize(line);
7110 if (enc != NULL && !spin->si_ascii
7111 && convert_setup(&spin->si_conv, enc,
7112 p_enc) == FAIL)
7113 smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
7114 fname, line, p_enc);
7115 vim_free(enc);
7116 spin->si_conv.vc_fail = TRUE;
7117 #else
7118 smsg((char_u *)_("Conversion in %s not supported"), fname);
7119 #endif
7121 continue;
7124 if (STRNCMP(line, "regions=", 8) == 0)
7126 if (spin->si_region_count > 1)
7127 smsg((char_u *)_("Duplicate /regions= line ignored in %s line %d: %s"),
7128 fname, lnum, line);
7129 else
7131 line += 8;
7132 if (STRLEN(line) > 16)
7133 smsg((char_u *)_("Too many regions in %s line %d: %s"),
7134 fname, lnum, line);
7135 else
7137 spin->si_region_count = (int)STRLEN(line) / 2;
7138 STRCPY(spin->si_region_name, line);
7140 /* Adjust the mask for a word valid in all regions. */
7141 spin->si_region = (1 << spin->si_region_count) - 1;
7144 continue;
7147 smsg((char_u *)_("/ line ignored in %s line %d: %s"),
7148 fname, lnum, line - 1);
7149 continue;
7152 flags = 0;
7153 regionmask = spin->si_region;
7155 /* Check for flags and region after a slash. */
7156 p = vim_strchr(line, '/');
7157 if (p != NULL)
7159 *p++ = NUL;
7160 while (*p != NUL)
7162 if (*p == '=') /* keep-case word */
7163 flags |= WF_KEEPCAP | WF_FIXCAP;
7164 else if (*p == '!') /* Bad, bad, wicked word. */
7165 flags |= WF_BANNED;
7166 else if (*p == '?') /* Rare word. */
7167 flags |= WF_RARE;
7168 else if (VIM_ISDIGIT(*p)) /* region number(s) */
7170 if ((flags & WF_REGION) == 0) /* first one */
7171 regionmask = 0;
7172 flags |= WF_REGION;
7174 l = *p - '0';
7175 if (l > spin->si_region_count)
7177 smsg((char_u *)_("Invalid region nr in %s line %d: %s"),
7178 fname, lnum, p);
7179 break;
7181 regionmask |= 1 << (l - 1);
7183 else
7185 smsg((char_u *)_("Unrecognized flags in %s line %d: %s"),
7186 fname, lnum, p);
7187 break;
7189 ++p;
7193 /* Skip non-ASCII words when "spin->si_ascii" is TRUE. */
7194 if (spin->si_ascii && has_non_ascii(line))
7196 ++non_ascii;
7197 continue;
7200 /* Normal word: store it. */
7201 if (store_word(spin, line, flags, regionmask, NULL, FALSE) == FAIL)
7203 retval = FAIL;
7204 break;
7206 did_word = TRUE;
7209 vim_free(pc);
7210 fclose(fd);
7212 if (spin->si_ascii && non_ascii > 0)
7214 vim_snprintf((char *)IObuff, IOSIZE,
7215 _("Ignored %d words with non-ASCII characters"), non_ascii);
7216 spell_message(spin, IObuff);
7219 return retval;
7223 * Get part of an sblock_T, "len" bytes long.
7224 * This avoids calling free() for every little struct we use (and keeping
7225 * track of them).
7226 * The memory is cleared to all zeros.
7227 * Returns NULL when out of memory.
7229 static void *
7230 getroom(spin, len, align)
7231 spellinfo_T *spin;
7232 size_t len; /* length needed */
7233 int align; /* align for pointer */
7235 char_u *p;
7236 sblock_T *bl = spin->si_blocks;
7238 if (align && bl != NULL)
7239 /* Round size up for alignment. On some systems structures need to be
7240 * aligned to the size of a pointer (e.g., SPARC). */
7241 bl->sb_used = (bl->sb_used + sizeof(char *) - 1)
7242 & ~(sizeof(char *) - 1);
7244 if (bl == NULL || bl->sb_used + len > SBLOCKSIZE)
7246 /* Allocate a block of memory. This is not freed until much later. */
7247 bl = (sblock_T *)alloc_clear((unsigned)(sizeof(sblock_T) + SBLOCKSIZE));
7248 if (bl == NULL)
7249 return NULL;
7250 bl->sb_next = spin->si_blocks;
7251 spin->si_blocks = bl;
7252 bl->sb_used = 0;
7253 ++spin->si_blocks_cnt;
7256 p = bl->sb_data + bl->sb_used;
7257 bl->sb_used += (int)len;
7259 return p;
7263 * Make a copy of a string into memory allocated with getroom().
7265 static char_u *
7266 getroom_save(spin, s)
7267 spellinfo_T *spin;
7268 char_u *s;
7270 char_u *sc;
7272 sc = (char_u *)getroom(spin, STRLEN(s) + 1, FALSE);
7273 if (sc != NULL)
7274 STRCPY(sc, s);
7275 return sc;
7280 * Free the list of allocated sblock_T.
7282 static void
7283 free_blocks(bl)
7284 sblock_T *bl;
7286 sblock_T *next;
7288 while (bl != NULL)
7290 next = bl->sb_next;
7291 vim_free(bl);
7292 bl = next;
7297 * Allocate the root of a word tree.
7299 static wordnode_T *
7300 wordtree_alloc(spin)
7301 spellinfo_T *spin;
7303 return (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
7307 * Store a word in the tree(s).
7308 * Always store it in the case-folded tree. For a keep-case word this is
7309 * useful when the word can also be used with all caps (no WF_FIXCAP flag) and
7310 * used to find suggestions.
7311 * For a keep-case word also store it in the keep-case tree.
7312 * When "pfxlist" is not NULL store the word for each postponed prefix ID and
7313 * compound flag.
7315 static int
7316 store_word(spin, word, flags, region, pfxlist, need_affix)
7317 spellinfo_T *spin;
7318 char_u *word;
7319 int flags; /* extra flags, WF_BANNED */
7320 int region; /* supported region(s) */
7321 char_u *pfxlist; /* list of prefix IDs or NULL */
7322 int need_affix; /* only store word with affix ID */
7324 int len = (int)STRLEN(word);
7325 int ct = captype(word, word + len);
7326 char_u foldword[MAXWLEN];
7327 int res = OK;
7328 char_u *p;
7330 (void)spell_casefold(word, len, foldword, MAXWLEN);
7331 for (p = pfxlist; res == OK; ++p)
7333 if (!need_affix || (p != NULL && *p != NUL))
7334 res = tree_add_word(spin, foldword, spin->si_foldroot, ct | flags,
7335 region, p == NULL ? 0 : *p);
7336 if (p == NULL || *p == NUL)
7337 break;
7339 ++spin->si_foldwcount;
7341 if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP)))
7343 for (p = pfxlist; res == OK; ++p)
7345 if (!need_affix || (p != NULL && *p != NUL))
7346 res = tree_add_word(spin, word, spin->si_keeproot, flags,
7347 region, p == NULL ? 0 : *p);
7348 if (p == NULL || *p == NUL)
7349 break;
7351 ++spin->si_keepwcount;
7353 return res;
7357 * Add word "word" to a word tree at "root".
7358 * When "flags" < 0 we are adding to the prefix tree where "flags" is used for
7359 * "rare" and "region" is the condition nr.
7360 * Returns FAIL when out of memory.
7362 static int
7363 tree_add_word(spin, word, root, flags, region, affixID)
7364 spellinfo_T *spin;
7365 char_u *word;
7366 wordnode_T *root;
7367 int flags;
7368 int region;
7369 int affixID;
7371 wordnode_T *node = root;
7372 wordnode_T *np;
7373 wordnode_T *copyp, **copyprev;
7374 wordnode_T **prev = NULL;
7375 int i;
7377 /* Add each byte of the word to the tree, including the NUL at the end. */
7378 for (i = 0; ; ++i)
7380 /* When there is more than one reference to this node we need to make
7381 * a copy, so that we can modify it. Copy the whole list of siblings
7382 * (we don't optimize for a partly shared list of siblings). */
7383 if (node != NULL && node->wn_refs > 1)
7385 --node->wn_refs;
7386 copyprev = prev;
7387 for (copyp = node; copyp != NULL; copyp = copyp->wn_sibling)
7389 /* Allocate a new node and copy the info. */
7390 np = get_wordnode(spin);
7391 if (np == NULL)
7392 return FAIL;
7393 np->wn_child = copyp->wn_child;
7394 if (np->wn_child != NULL)
7395 ++np->wn_child->wn_refs; /* child gets extra ref */
7396 np->wn_byte = copyp->wn_byte;
7397 if (np->wn_byte == NUL)
7399 np->wn_flags = copyp->wn_flags;
7400 np->wn_region = copyp->wn_region;
7401 np->wn_affixID = copyp->wn_affixID;
7404 /* Link the new node in the list, there will be one ref. */
7405 np->wn_refs = 1;
7406 if (copyprev != NULL)
7407 *copyprev = np;
7408 copyprev = &np->wn_sibling;
7410 /* Let "node" point to the head of the copied list. */
7411 if (copyp == node)
7412 node = np;
7416 /* Look for the sibling that has the same character. They are sorted
7417 * on byte value, thus stop searching when a sibling is found with a
7418 * higher byte value. For zero bytes (end of word) the sorting is
7419 * done on flags and then on affixID. */
7420 while (node != NULL
7421 && (node->wn_byte < word[i]
7422 || (node->wn_byte == NUL
7423 && (flags < 0
7424 ? node->wn_affixID < (unsigned)affixID
7425 : (node->wn_flags < (unsigned)(flags & WN_MASK)
7426 || (node->wn_flags == (flags & WN_MASK)
7427 && (spin->si_sugtree
7428 ? (node->wn_region & 0xffff) < region
7429 : node->wn_affixID
7430 < (unsigned)affixID)))))))
7432 prev = &node->wn_sibling;
7433 node = *prev;
7435 if (node == NULL
7436 || node->wn_byte != word[i]
7437 || (word[i] == NUL
7438 && (flags < 0
7439 || spin->si_sugtree
7440 || node->wn_flags != (flags & WN_MASK)
7441 || node->wn_affixID != affixID)))
7443 /* Allocate a new node. */
7444 np = get_wordnode(spin);
7445 if (np == NULL)
7446 return FAIL;
7447 np->wn_byte = word[i];
7449 /* If "node" is NULL this is a new child or the end of the sibling
7450 * list: ref count is one. Otherwise use ref count of sibling and
7451 * make ref count of sibling one (matters when inserting in front
7452 * of the list of siblings). */
7453 if (node == NULL)
7454 np->wn_refs = 1;
7455 else
7457 np->wn_refs = node->wn_refs;
7458 node->wn_refs = 1;
7460 *prev = np;
7461 np->wn_sibling = node;
7462 node = np;
7465 if (word[i] == NUL)
7467 node->wn_flags = flags;
7468 node->wn_region |= region;
7469 node->wn_affixID = affixID;
7470 break;
7472 prev = &node->wn_child;
7473 node = *prev;
7475 #ifdef SPELL_PRINTTREE
7476 smsg("Added \"%s\"", word);
7477 spell_print_tree(root->wn_sibling);
7478 #endif
7480 /* count nr of words added since last message */
7481 ++spin->si_msg_count;
7483 if (spin->si_compress_cnt > 1)
7485 if (--spin->si_compress_cnt == 1)
7486 /* Did enough words to lower the block count limit. */
7487 spin->si_blocks_cnt += compress_inc;
7491 * When we have allocated lots of memory we need to compress the word tree
7492 * to free up some room. But compression is slow, and we might actually
7493 * need that room, thus only compress in the following situations:
7494 * 1. When not compressed before (si_compress_cnt == 0): when using
7495 * "compress_start" blocks.
7496 * 2. When compressed before and used "compress_inc" blocks before
7497 * adding "compress_added" words (si_compress_cnt > 1).
7498 * 3. When compressed before, added "compress_added" words
7499 * (si_compress_cnt == 1) and the number of free nodes drops below the
7500 * maximum word length.
7502 #ifndef SPELL_PRINTTREE
7503 if (spin->si_compress_cnt == 1
7504 ? spin->si_free_count < MAXWLEN
7505 : spin->si_blocks_cnt >= compress_start)
7506 #endif
7508 /* Decrement the block counter. The effect is that we compress again
7509 * when the freed up room has been used and another "compress_inc"
7510 * blocks have been allocated. Unless "compress_added" words have
7511 * been added, then the limit is put back again. */
7512 spin->si_blocks_cnt -= compress_inc;
7513 spin->si_compress_cnt = compress_added;
7515 if (spin->si_verbose)
7517 msg_start();
7518 msg_puts((char_u *)_(msg_compressing));
7519 msg_clr_eos();
7520 msg_didout = FALSE;
7521 msg_col = 0;
7522 out_flush();
7525 /* Compress both trees. Either they both have many nodes, which makes
7526 * compression useful, or one of them is small, which means
7527 * compression goes fast. But when filling the souldfold word tree
7528 * there is no keep-case tree. */
7529 wordtree_compress(spin, spin->si_foldroot);
7530 if (affixID >= 0)
7531 wordtree_compress(spin, spin->si_keeproot);
7534 return OK;
7538 * Check the 'mkspellmem' option. Return FAIL if it's wrong.
7539 * Sets "sps_flags".
7542 spell_check_msm()
7544 char_u *p = p_msm;
7545 long start = 0;
7546 long incr = 0;
7547 long added = 0;
7549 if (!VIM_ISDIGIT(*p))
7550 return FAIL;
7551 /* block count = (value * 1024) / SBLOCKSIZE (but avoid overflow)*/
7552 start = (getdigits(&p) * 10) / (SBLOCKSIZE / 102);
7553 if (*p != ',')
7554 return FAIL;
7555 ++p;
7556 if (!VIM_ISDIGIT(*p))
7557 return FAIL;
7558 incr = (getdigits(&p) * 102) / (SBLOCKSIZE / 10);
7559 if (*p != ',')
7560 return FAIL;
7561 ++p;
7562 if (!VIM_ISDIGIT(*p))
7563 return FAIL;
7564 added = getdigits(&p) * 1024;
7565 if (*p != NUL)
7566 return FAIL;
7568 if (start == 0 || incr == 0 || added == 0 || incr > start)
7569 return FAIL;
7571 compress_start = start;
7572 compress_inc = incr;
7573 compress_added = added;
7574 return OK;
7579 * Get a wordnode_T, either from the list of previously freed nodes or
7580 * allocate a new one.
7582 static wordnode_T *
7583 get_wordnode(spin)
7584 spellinfo_T *spin;
7586 wordnode_T *n;
7588 if (spin->si_first_free == NULL)
7589 n = (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
7590 else
7592 n = spin->si_first_free;
7593 spin->si_first_free = n->wn_child;
7594 vim_memset(n, 0, sizeof(wordnode_T));
7595 --spin->si_free_count;
7597 #ifdef SPELL_PRINTTREE
7598 n->wn_nr = ++spin->si_wordnode_nr;
7599 #endif
7600 return n;
7604 * Decrement the reference count on a node (which is the head of a list of
7605 * siblings). If the reference count becomes zero free the node and its
7606 * siblings.
7607 * Returns the number of nodes actually freed.
7609 static int
7610 deref_wordnode(spin, node)
7611 spellinfo_T *spin;
7612 wordnode_T *node;
7614 wordnode_T *np;
7615 int cnt = 0;
7617 if (--node->wn_refs == 0)
7619 for (np = node; np != NULL; np = np->wn_sibling)
7621 if (np->wn_child != NULL)
7622 cnt += deref_wordnode(spin, np->wn_child);
7623 free_wordnode(spin, np);
7624 ++cnt;
7626 ++cnt; /* length field */
7628 return cnt;
7632 * Free a wordnode_T for re-use later.
7633 * Only the "wn_child" field becomes invalid.
7635 static void
7636 free_wordnode(spin, n)
7637 spellinfo_T *spin;
7638 wordnode_T *n;
7640 n->wn_child = spin->si_first_free;
7641 spin->si_first_free = n;
7642 ++spin->si_free_count;
7646 * Compress a tree: find tails that are identical and can be shared.
7648 static void
7649 wordtree_compress(spin, root)
7650 spellinfo_T *spin;
7651 wordnode_T *root;
7653 hashtab_T ht;
7654 int n;
7655 int tot = 0;
7656 int perc;
7658 /* Skip the root itself, it's not actually used. The first sibling is the
7659 * start of the tree. */
7660 if (root->wn_sibling != NULL)
7662 hash_init(&ht);
7663 n = node_compress(spin, root->wn_sibling, &ht, &tot);
7665 #ifndef SPELL_PRINTTREE
7666 if (spin->si_verbose || p_verbose > 2)
7667 #endif
7669 if (tot > 1000000)
7670 perc = (tot - n) / (tot / 100);
7671 else if (tot == 0)
7672 perc = 0;
7673 else
7674 perc = (tot - n) * 100 / tot;
7675 vim_snprintf((char *)IObuff, IOSIZE,
7676 _("Compressed %d of %d nodes; %d (%d%%) remaining"),
7677 n, tot, tot - n, perc);
7678 spell_message(spin, IObuff);
7680 #ifdef SPELL_PRINTTREE
7681 spell_print_tree(root->wn_sibling);
7682 #endif
7683 hash_clear(&ht);
7688 * Compress a node, its siblings and its children, depth first.
7689 * Returns the number of compressed nodes.
7691 static int
7692 node_compress(spin, node, ht, tot)
7693 spellinfo_T *spin;
7694 wordnode_T *node;
7695 hashtab_T *ht;
7696 int *tot; /* total count of nodes before compressing,
7697 incremented while going through the tree */
7699 wordnode_T *np;
7700 wordnode_T *tp;
7701 wordnode_T *child;
7702 hash_T hash;
7703 hashitem_T *hi;
7704 int len = 0;
7705 unsigned nr, n;
7706 int compressed = 0;
7709 * Go through the list of siblings. Compress each child and then try
7710 * finding an identical child to replace it.
7711 * Note that with "child" we mean not just the node that is pointed to,
7712 * but the whole list of siblings of which the child node is the first.
7714 for (np = node; np != NULL && !got_int; np = np->wn_sibling)
7716 ++len;
7717 if ((child = np->wn_child) != NULL)
7719 /* Compress the child first. This fills hashkey. */
7720 compressed += node_compress(spin, child, ht, tot);
7722 /* Try to find an identical child. */
7723 hash = hash_hash(child->wn_u1.hashkey);
7724 hi = hash_lookup(ht, child->wn_u1.hashkey, hash);
7725 if (!HASHITEM_EMPTY(hi))
7727 /* There are children we encountered before with a hash value
7728 * identical to the current child. Now check if there is one
7729 * that is really identical. */
7730 for (tp = HI2WN(hi); tp != NULL; tp = tp->wn_u2.next)
7731 if (node_equal(child, tp))
7733 /* Found one! Now use that child in place of the
7734 * current one. This means the current child and all
7735 * its siblings is unlinked from the tree. */
7736 ++tp->wn_refs;
7737 compressed += deref_wordnode(spin, child);
7738 np->wn_child = tp;
7739 break;
7741 if (tp == NULL)
7743 /* No other child with this hash value equals the child of
7744 * the node, add it to the linked list after the first
7745 * item. */
7746 tp = HI2WN(hi);
7747 child->wn_u2.next = tp->wn_u2.next;
7748 tp->wn_u2.next = child;
7751 else
7752 /* No other child has this hash value, add it to the
7753 * hashtable. */
7754 hash_add_item(ht, hi, child->wn_u1.hashkey, hash);
7757 *tot += len + 1; /* add one for the node that stores the length */
7760 * Make a hash key for the node and its siblings, so that we can quickly
7761 * find a lookalike node. This must be done after compressing the sibling
7762 * list, otherwise the hash key would become invalid by the compression.
7764 node->wn_u1.hashkey[0] = len;
7765 nr = 0;
7766 for (np = node; np != NULL; np = np->wn_sibling)
7768 if (np->wn_byte == NUL)
7769 /* end node: use wn_flags, wn_region and wn_affixID */
7770 n = np->wn_flags + (np->wn_region << 8) + (np->wn_affixID << 16);
7771 else
7772 /* byte node: use the byte value and the child pointer */
7773 n = (unsigned)(np->wn_byte + ((long_u)np->wn_child << 8));
7774 nr = nr * 101 + n;
7777 /* Avoid NUL bytes, it terminates the hash key. */
7778 n = nr & 0xff;
7779 node->wn_u1.hashkey[1] = n == 0 ? 1 : n;
7780 n = (nr >> 8) & 0xff;
7781 node->wn_u1.hashkey[2] = n == 0 ? 1 : n;
7782 n = (nr >> 16) & 0xff;
7783 node->wn_u1.hashkey[3] = n == 0 ? 1 : n;
7784 n = (nr >> 24) & 0xff;
7785 node->wn_u1.hashkey[4] = n == 0 ? 1 : n;
7786 node->wn_u1.hashkey[5] = NUL;
7788 /* Check for CTRL-C pressed now and then. */
7789 fast_breakcheck();
7791 return compressed;
7795 * Return TRUE when two nodes have identical siblings and children.
7797 static int
7798 node_equal(n1, n2)
7799 wordnode_T *n1;
7800 wordnode_T *n2;
7802 wordnode_T *p1;
7803 wordnode_T *p2;
7805 for (p1 = n1, p2 = n2; p1 != NULL && p2 != NULL;
7806 p1 = p1->wn_sibling, p2 = p2->wn_sibling)
7807 if (p1->wn_byte != p2->wn_byte
7808 || (p1->wn_byte == NUL
7809 ? (p1->wn_flags != p2->wn_flags
7810 || p1->wn_region != p2->wn_region
7811 || p1->wn_affixID != p2->wn_affixID)
7812 : (p1->wn_child != p2->wn_child)))
7813 break;
7815 return p1 == NULL && p2 == NULL;
7819 * Write a number to file "fd", MSB first, in "len" bytes.
7821 void
7822 put_bytes(fd, nr, len)
7823 FILE *fd;
7824 long_u nr;
7825 int len;
7827 int i;
7829 for (i = len - 1; i >= 0; --i)
7830 putc((int)(nr >> (i * 8)), fd);
7833 #ifdef _MSC_VER
7834 # if (_MSC_VER <= 1200)
7835 /* This line is required for VC6 without the service pack. Also see the
7836 * matching #pragma below. */
7837 # pragma optimize("", off)
7838 # endif
7839 #endif
7842 * Write spin->si_sugtime to file "fd".
7844 static void
7845 put_sugtime(spin, fd)
7846 spellinfo_T *spin;
7847 FILE *fd;
7849 int c;
7850 int i;
7852 /* time_t can be up to 8 bytes in size, more than long_u, thus we
7853 * can't use put_bytes() here. */
7854 for (i = 7; i >= 0; --i)
7855 if (i + 1 > sizeof(time_t))
7856 /* ">>" doesn't work well when shifting more bits than avail */
7857 putc(0, fd);
7858 else
7860 c = (unsigned)spin->si_sugtime >> (i * 8);
7861 putc(c, fd);
7865 #ifdef _MSC_VER
7866 # if (_MSC_VER <= 1200)
7867 # pragma optimize("", on)
7868 # endif
7869 #endif
7871 static int
7872 #ifdef __BORLANDC__
7873 _RTLENTRYF
7874 #endif
7875 rep_compare __ARGS((const void *s1, const void *s2));
7878 * Function given to qsort() to sort the REP items on "from" string.
7880 static int
7881 #ifdef __BORLANDC__
7882 _RTLENTRYF
7883 #endif
7884 rep_compare(s1, s2)
7885 const void *s1;
7886 const void *s2;
7888 fromto_T *p1 = (fromto_T *)s1;
7889 fromto_T *p2 = (fromto_T *)s2;
7891 return STRCMP(p1->ft_from, p2->ft_from);
7895 * Write the Vim .spl file "fname".
7896 * Return FAIL or OK;
7898 static int
7899 write_vim_spell(spin, fname)
7900 spellinfo_T *spin;
7901 char_u *fname;
7903 FILE *fd;
7904 int regionmask;
7905 int round;
7906 wordnode_T *tree;
7907 int nodecount;
7908 int i;
7909 int l;
7910 garray_T *gap;
7911 fromto_T *ftp;
7912 char_u *p;
7913 int rr;
7914 int retval = OK;
7916 fd = mch_fopen((char *)fname, "w");
7917 if (fd == NULL)
7919 EMSG2(_(e_notopen), fname);
7920 return FAIL;
7923 /* <HEADER>: <fileID> <versionnr> */
7924 /* <fileID> */
7925 if (fwrite(VIMSPELLMAGIC, VIMSPELLMAGICL, (size_t)1, fd) != 1)
7927 EMSG(_(e_write));
7928 retval = FAIL;
7930 putc(VIMSPELLVERSION, fd); /* <versionnr> */
7933 * <SECTIONS>: <section> ... <sectionend>
7936 /* SN_INFO: <infotext> */
7937 if (spin->si_info != NULL)
7939 putc(SN_INFO, fd); /* <sectionID> */
7940 putc(0, fd); /* <sectionflags> */
7942 i = (int)STRLEN(spin->si_info);
7943 put_bytes(fd, (long_u)i, 4); /* <sectionlen> */
7944 fwrite(spin->si_info, (size_t)i, (size_t)1, fd); /* <infotext> */
7947 /* SN_REGION: <regionname> ...
7948 * Write the region names only if there is more than one. */
7949 if (spin->si_region_count > 1)
7951 putc(SN_REGION, fd); /* <sectionID> */
7952 putc(SNF_REQUIRED, fd); /* <sectionflags> */
7953 l = spin->si_region_count * 2;
7954 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
7955 fwrite(spin->si_region_name, (size_t)l, (size_t)1, fd);
7956 /* <regionname> ... */
7957 regionmask = (1 << spin->si_region_count) - 1;
7959 else
7960 regionmask = 0;
7962 /* SN_CHARFLAGS: <charflagslen> <charflags> <folcharslen> <folchars>
7964 * The table with character flags and the table for case folding.
7965 * This makes sure the same characters are recognized as word characters
7966 * when generating an when using a spell file.
7967 * Skip this for ASCII, the table may conflict with the one used for
7968 * 'encoding'.
7969 * Also skip this for an .add.spl file, the main spell file must contain
7970 * the table (avoids that it conflicts). File is shorter too.
7972 if (!spin->si_ascii && !spin->si_add)
7974 char_u folchars[128 * 8];
7975 int flags;
7977 putc(SN_CHARFLAGS, fd); /* <sectionID> */
7978 putc(SNF_REQUIRED, fd); /* <sectionflags> */
7980 /* Form the <folchars> string first, we need to know its length. */
7981 l = 0;
7982 for (i = 128; i < 256; ++i)
7984 #ifdef FEAT_MBYTE
7985 if (has_mbyte)
7986 l += mb_char2bytes(spelltab.st_fold[i], folchars + l);
7987 else
7988 #endif
7989 folchars[l++] = spelltab.st_fold[i];
7991 put_bytes(fd, (long_u)(1 + 128 + 2 + l), 4); /* <sectionlen> */
7993 fputc(128, fd); /* <charflagslen> */
7994 for (i = 128; i < 256; ++i)
7996 flags = 0;
7997 if (spelltab.st_isw[i])
7998 flags |= CF_WORD;
7999 if (spelltab.st_isu[i])
8000 flags |= CF_UPPER;
8001 fputc(flags, fd); /* <charflags> */
8004 put_bytes(fd, (long_u)l, 2); /* <folcharslen> */
8005 fwrite(folchars, (size_t)l, (size_t)1, fd); /* <folchars> */
8008 /* SN_MIDWORD: <midword> */
8009 if (spin->si_midword != NULL)
8011 putc(SN_MIDWORD, fd); /* <sectionID> */
8012 putc(SNF_REQUIRED, fd); /* <sectionflags> */
8014 i = (int)STRLEN(spin->si_midword);
8015 put_bytes(fd, (long_u)i, 4); /* <sectionlen> */
8016 fwrite(spin->si_midword, (size_t)i, (size_t)1, fd); /* <midword> */
8019 /* SN_PREFCOND: <prefcondcnt> <prefcond> ... */
8020 if (spin->si_prefcond.ga_len > 0)
8022 putc(SN_PREFCOND, fd); /* <sectionID> */
8023 putc(SNF_REQUIRED, fd); /* <sectionflags> */
8025 l = write_spell_prefcond(NULL, &spin->si_prefcond);
8026 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8028 write_spell_prefcond(fd, &spin->si_prefcond);
8031 /* SN_REP: <repcount> <rep> ...
8032 * SN_SAL: <salflags> <salcount> <sal> ...
8033 * SN_REPSAL: <repcount> <rep> ... */
8035 /* round 1: SN_REP section
8036 * round 2: SN_SAL section (unless SN_SOFO is used)
8037 * round 3: SN_REPSAL section */
8038 for (round = 1; round <= 3; ++round)
8040 if (round == 1)
8041 gap = &spin->si_rep;
8042 else if (round == 2)
8044 /* Don't write SN_SAL when using a SN_SOFO section */
8045 if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
8046 continue;
8047 gap = &spin->si_sal;
8049 else
8050 gap = &spin->si_repsal;
8052 /* Don't write the section if there are no items. */
8053 if (gap->ga_len == 0)
8054 continue;
8056 /* Sort the REP/REPSAL items. */
8057 if (round != 2)
8058 qsort(gap->ga_data, (size_t)gap->ga_len,
8059 sizeof(fromto_T), rep_compare);
8061 i = round == 1 ? SN_REP : (round == 2 ? SN_SAL : SN_REPSAL);
8062 putc(i, fd); /* <sectionID> */
8064 /* This is for making suggestions, section is not required. */
8065 putc(0, fd); /* <sectionflags> */
8067 /* Compute the length of what follows. */
8068 l = 2; /* count <repcount> or <salcount> */
8069 for (i = 0; i < gap->ga_len; ++i)
8071 ftp = &((fromto_T *)gap->ga_data)[i];
8072 l += 1 + (int)STRLEN(ftp->ft_from); /* count <*fromlen> and <*from> */
8073 l += 1 + (int)STRLEN(ftp->ft_to); /* count <*tolen> and <*to> */
8075 if (round == 2)
8076 ++l; /* count <salflags> */
8077 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8079 if (round == 2)
8081 i = 0;
8082 if (spin->si_followup)
8083 i |= SAL_F0LLOWUP;
8084 if (spin->si_collapse)
8085 i |= SAL_COLLAPSE;
8086 if (spin->si_rem_accents)
8087 i |= SAL_REM_ACCENTS;
8088 putc(i, fd); /* <salflags> */
8091 put_bytes(fd, (long_u)gap->ga_len, 2); /* <repcount> or <salcount> */
8092 for (i = 0; i < gap->ga_len; ++i)
8094 /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */
8095 /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */
8096 ftp = &((fromto_T *)gap->ga_data)[i];
8097 for (rr = 1; rr <= 2; ++rr)
8099 p = rr == 1 ? ftp->ft_from : ftp->ft_to;
8100 l = (int)STRLEN(p);
8101 putc(l, fd);
8102 fwrite(p, l, (size_t)1, fd);
8108 /* SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
8109 * This is for making suggestions, section is not required. */
8110 if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
8112 putc(SN_SOFO, fd); /* <sectionID> */
8113 putc(0, fd); /* <sectionflags> */
8115 l = (int)STRLEN(spin->si_sofofr);
8116 put_bytes(fd, (long_u)(l + STRLEN(spin->si_sofoto) + 4), 4);
8117 /* <sectionlen> */
8119 put_bytes(fd, (long_u)l, 2); /* <sofofromlen> */
8120 fwrite(spin->si_sofofr, l, (size_t)1, fd); /* <sofofrom> */
8122 l = (int)STRLEN(spin->si_sofoto);
8123 put_bytes(fd, (long_u)l, 2); /* <sofotolen> */
8124 fwrite(spin->si_sofoto, l, (size_t)1, fd); /* <sofoto> */
8127 /* SN_WORDS: <word> ...
8128 * This is for making suggestions, section is not required. */
8129 if (spin->si_commonwords.ht_used > 0)
8131 putc(SN_WORDS, fd); /* <sectionID> */
8132 putc(0, fd); /* <sectionflags> */
8134 /* round 1: count the bytes
8135 * round 2: write the bytes */
8136 for (round = 1; round <= 2; ++round)
8138 int todo;
8139 int len = 0;
8140 hashitem_T *hi;
8142 todo = (int)spin->si_commonwords.ht_used;
8143 for (hi = spin->si_commonwords.ht_array; todo > 0; ++hi)
8144 if (!HASHITEM_EMPTY(hi))
8146 l = (int)STRLEN(hi->hi_key) + 1;
8147 len += l;
8148 if (round == 2) /* <word> */
8149 fwrite(hi->hi_key, (size_t)l, (size_t)1, fd);
8150 --todo;
8152 if (round == 1)
8153 put_bytes(fd, (long_u)len, 4); /* <sectionlen> */
8157 /* SN_MAP: <mapstr>
8158 * This is for making suggestions, section is not required. */
8159 if (spin->si_map.ga_len > 0)
8161 putc(SN_MAP, fd); /* <sectionID> */
8162 putc(0, fd); /* <sectionflags> */
8163 l = spin->si_map.ga_len;
8164 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8165 fwrite(spin->si_map.ga_data, (size_t)l, (size_t)1, fd);
8166 /* <mapstr> */
8169 /* SN_SUGFILE: <timestamp>
8170 * This is used to notify that a .sug file may be available and at the
8171 * same time allows for checking that a .sug file that is found matches
8172 * with this .spl file. That's because the word numbers must be exactly
8173 * right. */
8174 if (!spin->si_nosugfile
8175 && (spin->si_sal.ga_len > 0
8176 || (spin->si_sofofr != NULL && spin->si_sofoto != NULL)))
8178 putc(SN_SUGFILE, fd); /* <sectionID> */
8179 putc(0, fd); /* <sectionflags> */
8180 put_bytes(fd, (long_u)8, 4); /* <sectionlen> */
8182 /* Set si_sugtime and write it to the file. */
8183 spin->si_sugtime = time(NULL);
8184 put_sugtime(spin, fd); /* <timestamp> */
8187 /* SN_NOSPLITSUGS: nothing
8188 * This is used to notify that no suggestions with word splits are to be
8189 * made. */
8190 if (spin->si_nosplitsugs)
8192 putc(SN_NOSPLITSUGS, fd); /* <sectionID> */
8193 putc(0, fd); /* <sectionflags> */
8194 put_bytes(fd, (long_u)0, 4); /* <sectionlen> */
8197 /* SN_COMPOUND: compound info.
8198 * We don't mark it required, when not supported all compound words will
8199 * be bad words. */
8200 if (spin->si_compflags != NULL)
8202 putc(SN_COMPOUND, fd); /* <sectionID> */
8203 putc(0, fd); /* <sectionflags> */
8205 l = (int)STRLEN(spin->si_compflags);
8206 for (i = 0; i < spin->si_comppat.ga_len; ++i)
8207 l += (int)STRLEN(((char_u **)(spin->si_comppat.ga_data))[i]) + 1;
8208 put_bytes(fd, (long_u)(l + 7), 4); /* <sectionlen> */
8210 putc(spin->si_compmax, fd); /* <compmax> */
8211 putc(spin->si_compminlen, fd); /* <compminlen> */
8212 putc(spin->si_compsylmax, fd); /* <compsylmax> */
8213 putc(0, fd); /* for Vim 7.0b compatibility */
8214 putc(spin->si_compoptions, fd); /* <compoptions> */
8215 put_bytes(fd, (long_u)spin->si_comppat.ga_len, 2);
8216 /* <comppatcount> */
8217 for (i = 0; i < spin->si_comppat.ga_len; ++i)
8219 p = ((char_u **)(spin->si_comppat.ga_data))[i];
8220 putc((int)STRLEN(p), fd); /* <comppatlen> */
8221 fwrite(p, (size_t)STRLEN(p), (size_t)1, fd);/* <comppattext> */
8223 /* <compflags> */
8224 fwrite(spin->si_compflags, (size_t)STRLEN(spin->si_compflags),
8225 (size_t)1, fd);
8228 /* SN_NOBREAK: NOBREAK flag */
8229 if (spin->si_nobreak)
8231 putc(SN_NOBREAK, fd); /* <sectionID> */
8232 putc(0, fd); /* <sectionflags> */
8234 /* It's empty, the presence of the section flags the feature. */
8235 put_bytes(fd, (long_u)0, 4); /* <sectionlen> */
8238 /* SN_SYLLABLE: syllable info.
8239 * We don't mark it required, when not supported syllables will not be
8240 * counted. */
8241 if (spin->si_syllable != NULL)
8243 putc(SN_SYLLABLE, fd); /* <sectionID> */
8244 putc(0, fd); /* <sectionflags> */
8246 l = (int)STRLEN(spin->si_syllable);
8247 put_bytes(fd, (long_u)l, 4); /* <sectionlen> */
8248 fwrite(spin->si_syllable, (size_t)l, (size_t)1, fd); /* <syllable> */
8251 /* end of <SECTIONS> */
8252 putc(SN_END, fd); /* <sectionend> */
8256 * <LWORDTREE> <KWORDTREE> <PREFIXTREE>
8258 spin->si_memtot = 0;
8259 for (round = 1; round <= 3; ++round)
8261 if (round == 1)
8262 tree = spin->si_foldroot->wn_sibling;
8263 else if (round == 2)
8264 tree = spin->si_keeproot->wn_sibling;
8265 else
8266 tree = spin->si_prefroot->wn_sibling;
8268 /* Clear the index and wnode fields in the tree. */
8269 clear_node(tree);
8271 /* Count the number of nodes. Needed to be able to allocate the
8272 * memory when reading the nodes. Also fills in index for shared
8273 * nodes. */
8274 nodecount = put_node(NULL, tree, 0, regionmask, round == 3);
8276 /* number of nodes in 4 bytes */
8277 put_bytes(fd, (long_u)nodecount, 4); /* <nodecount> */
8278 spin->si_memtot += nodecount + nodecount * sizeof(int);
8280 /* Write the nodes. */
8281 (void)put_node(fd, tree, 0, regionmask, round == 3);
8284 /* Write another byte to check for errors. */
8285 if (putc(0, fd) == EOF)
8286 retval = FAIL;
8288 if (fclose(fd) == EOF)
8289 retval = FAIL;
8291 return retval;
8295 * Clear the index and wnode fields of "node", it siblings and its
8296 * children. This is needed because they are a union with other items to save
8297 * space.
8299 static void
8300 clear_node(node)
8301 wordnode_T *node;
8303 wordnode_T *np;
8305 if (node != NULL)
8306 for (np = node; np != NULL; np = np->wn_sibling)
8308 np->wn_u1.index = 0;
8309 np->wn_u2.wnode = NULL;
8311 if (np->wn_byte != NUL)
8312 clear_node(np->wn_child);
8318 * Dump a word tree at node "node".
8320 * This first writes the list of possible bytes (siblings). Then for each
8321 * byte recursively write the children.
8323 * NOTE: The code here must match the code in read_tree_node(), since
8324 * assumptions are made about the indexes (so that we don't have to write them
8325 * in the file).
8327 * Returns the number of nodes used.
8329 static int
8330 put_node(fd, node, idx, regionmask, prefixtree)
8331 FILE *fd; /* NULL when only counting */
8332 wordnode_T *node;
8333 int idx;
8334 int regionmask;
8335 int prefixtree; /* TRUE for PREFIXTREE */
8337 int newindex = idx;
8338 int siblingcount = 0;
8339 wordnode_T *np;
8340 int flags;
8342 /* If "node" is zero the tree is empty. */
8343 if (node == NULL)
8344 return 0;
8346 /* Store the index where this node is written. */
8347 node->wn_u1.index = idx;
8349 /* Count the number of siblings. */
8350 for (np = node; np != NULL; np = np->wn_sibling)
8351 ++siblingcount;
8353 /* Write the sibling count. */
8354 if (fd != NULL)
8355 putc(siblingcount, fd); /* <siblingcount> */
8357 /* Write each sibling byte and optionally extra info. */
8358 for (np = node; np != NULL; np = np->wn_sibling)
8360 if (np->wn_byte == 0)
8362 if (fd != NULL)
8364 /* For a NUL byte (end of word) write the flags etc. */
8365 if (prefixtree)
8367 /* In PREFIXTREE write the required affixID and the
8368 * associated condition nr (stored in wn_region). The
8369 * byte value is misused to store the "rare" and "not
8370 * combining" flags */
8371 if (np->wn_flags == (short_u)PFX_FLAGS)
8372 putc(BY_NOFLAGS, fd); /* <byte> */
8373 else
8375 putc(BY_FLAGS, fd); /* <byte> */
8376 putc(np->wn_flags, fd); /* <pflags> */
8378 putc(np->wn_affixID, fd); /* <affixID> */
8379 put_bytes(fd, (long_u)np->wn_region, 2); /* <prefcondnr> */
8381 else
8383 /* For word trees we write the flag/region items. */
8384 flags = np->wn_flags;
8385 if (regionmask != 0 && np->wn_region != regionmask)
8386 flags |= WF_REGION;
8387 if (np->wn_affixID != 0)
8388 flags |= WF_AFX;
8389 if (flags == 0)
8391 /* word without flags or region */
8392 putc(BY_NOFLAGS, fd); /* <byte> */
8394 else
8396 if (np->wn_flags >= 0x100)
8398 putc(BY_FLAGS2, fd); /* <byte> */
8399 putc(flags, fd); /* <flags> */
8400 putc((unsigned)flags >> 8, fd); /* <flags2> */
8402 else
8404 putc(BY_FLAGS, fd); /* <byte> */
8405 putc(flags, fd); /* <flags> */
8407 if (flags & WF_REGION)
8408 putc(np->wn_region, fd); /* <region> */
8409 if (flags & WF_AFX)
8410 putc(np->wn_affixID, fd); /* <affixID> */
8415 else
8417 if (np->wn_child->wn_u1.index != 0
8418 && np->wn_child->wn_u2.wnode != node)
8420 /* The child is written elsewhere, write the reference. */
8421 if (fd != NULL)
8423 putc(BY_INDEX, fd); /* <byte> */
8424 /* <nodeidx> */
8425 put_bytes(fd, (long_u)np->wn_child->wn_u1.index, 3);
8428 else if (np->wn_child->wn_u2.wnode == NULL)
8429 /* We will write the child below and give it an index. */
8430 np->wn_child->wn_u2.wnode = node;
8432 if (fd != NULL)
8433 if (putc(np->wn_byte, fd) == EOF) /* <byte> or <xbyte> */
8435 EMSG(_(e_write));
8436 return 0;
8441 /* Space used in the array when reading: one for each sibling and one for
8442 * the count. */
8443 newindex += siblingcount + 1;
8445 /* Recursively dump the children of each sibling. */
8446 for (np = node; np != NULL; np = np->wn_sibling)
8447 if (np->wn_byte != 0 && np->wn_child->wn_u2.wnode == node)
8448 newindex = put_node(fd, np->wn_child, newindex, regionmask,
8449 prefixtree);
8451 return newindex;
8456 * ":mkspell [-ascii] outfile infile ..."
8457 * ":mkspell [-ascii] addfile"
8459 void
8460 ex_mkspell(eap)
8461 exarg_T *eap;
8463 int fcount;
8464 char_u **fnames;
8465 char_u *arg = eap->arg;
8466 int ascii = FALSE;
8468 if (STRNCMP(arg, "-ascii", 6) == 0)
8470 ascii = TRUE;
8471 arg = skipwhite(arg + 6);
8474 /* Expand all the remaining arguments (e.g., $VIMRUNTIME). */
8475 if (get_arglist_exp(arg, &fcount, &fnames) == OK)
8477 mkspell(fcount, fnames, ascii, eap->forceit, FALSE);
8478 FreeWild(fcount, fnames);
8483 * Create the .sug file.
8484 * Uses the soundfold info in "spin".
8485 * Writes the file with the name "wfname", with ".spl" changed to ".sug".
8487 static void
8488 spell_make_sugfile(spin, wfname)
8489 spellinfo_T *spin;
8490 char_u *wfname;
8492 char_u fname[MAXPATHL];
8493 int len;
8494 slang_T *slang;
8495 int free_slang = FALSE;
8498 * Read back the .spl file that was written. This fills the required
8499 * info for soundfolding. This also uses less memory than the
8500 * pointer-linked version of the trie. And it avoids having two versions
8501 * of the code for the soundfolding stuff.
8502 * It might have been done already by spell_reload_one().
8504 for (slang = first_lang; slang != NULL; slang = slang->sl_next)
8505 if (fullpathcmp(wfname, slang->sl_fname, FALSE) == FPC_SAME)
8506 break;
8507 if (slang == NULL)
8509 spell_message(spin, (char_u *)_("Reading back spell file..."));
8510 slang = spell_load_file(wfname, NULL, NULL, FALSE);
8511 if (slang == NULL)
8512 return;
8513 free_slang = TRUE;
8517 * Clear the info in "spin" that is used.
8519 spin->si_blocks = NULL;
8520 spin->si_blocks_cnt = 0;
8521 spin->si_compress_cnt = 0; /* will stay at 0 all the time*/
8522 spin->si_free_count = 0;
8523 spin->si_first_free = NULL;
8524 spin->si_foldwcount = 0;
8527 * Go through the trie of good words, soundfold each word and add it to
8528 * the soundfold trie.
8530 spell_message(spin, (char_u *)_("Performing soundfolding..."));
8531 if (sug_filltree(spin, slang) == FAIL)
8532 goto theend;
8535 * Create the table which links each soundfold word with a list of the
8536 * good words it may come from. Creates buffer "spin->si_spellbuf".
8537 * This also removes the wordnr from the NUL byte entries to make
8538 * compression possible.
8540 if (sug_maketable(spin) == FAIL)
8541 goto theend;
8543 smsg((char_u *)_("Number of words after soundfolding: %ld"),
8544 (long)spin->si_spellbuf->b_ml.ml_line_count);
8547 * Compress the soundfold trie.
8549 spell_message(spin, (char_u *)_(msg_compressing));
8550 wordtree_compress(spin, spin->si_foldroot);
8553 * Write the .sug file.
8554 * Make the file name by changing ".spl" to ".sug".
8556 STRCPY(fname, wfname);
8557 len = (int)STRLEN(fname);
8558 fname[len - 2] = 'u';
8559 fname[len - 1] = 'g';
8560 sug_write(spin, fname);
8562 theend:
8563 if (free_slang)
8564 slang_free(slang);
8565 free_blocks(spin->si_blocks);
8566 close_spellbuf(spin->si_spellbuf);
8570 * Build the soundfold trie for language "slang".
8572 static int
8573 sug_filltree(spin, slang)
8574 spellinfo_T *spin;
8575 slang_T *slang;
8577 char_u *byts;
8578 idx_T *idxs;
8579 int depth;
8580 idx_T arridx[MAXWLEN];
8581 int curi[MAXWLEN];
8582 char_u tword[MAXWLEN];
8583 char_u tsalword[MAXWLEN];
8584 int c;
8585 idx_T n;
8586 unsigned words_done = 0;
8587 int wordcount[MAXWLEN];
8589 /* We use si_foldroot for the souldfolded trie. */
8590 spin->si_foldroot = wordtree_alloc(spin);
8591 if (spin->si_foldroot == NULL)
8592 return FAIL;
8594 /* let tree_add_word() know we're adding to the soundfolded tree */
8595 spin->si_sugtree = TRUE;
8598 * Go through the whole case-folded tree, soundfold each word and put it
8599 * in the trie.
8601 byts = slang->sl_fbyts;
8602 idxs = slang->sl_fidxs;
8604 arridx[0] = 0;
8605 curi[0] = 1;
8606 wordcount[0] = 0;
8608 depth = 0;
8609 while (depth >= 0 && !got_int)
8611 if (curi[depth] > byts[arridx[depth]])
8613 /* Done all bytes at this node, go up one level. */
8614 idxs[arridx[depth]] = wordcount[depth];
8615 if (depth > 0)
8616 wordcount[depth - 1] += wordcount[depth];
8618 --depth;
8619 line_breakcheck();
8621 else
8624 /* Do one more byte at this node. */
8625 n = arridx[depth] + curi[depth];
8626 ++curi[depth];
8628 c = byts[n];
8629 if (c == 0)
8631 /* Sound-fold the word. */
8632 tword[depth] = NUL;
8633 spell_soundfold(slang, tword, TRUE, tsalword);
8635 /* We use the "flags" field for the MSB of the wordnr,
8636 * "region" for the LSB of the wordnr. */
8637 if (tree_add_word(spin, tsalword, spin->si_foldroot,
8638 words_done >> 16, words_done & 0xffff,
8639 0) == FAIL)
8640 return FAIL;
8642 ++words_done;
8643 ++wordcount[depth];
8645 /* Reset the block count each time to avoid compression
8646 * kicking in. */
8647 spin->si_blocks_cnt = 0;
8649 /* Skip over any other NUL bytes (same word with different
8650 * flags). */
8651 while (byts[n + 1] == 0)
8653 ++n;
8654 ++curi[depth];
8657 else
8659 /* Normal char, go one level deeper. */
8660 tword[depth++] = c;
8661 arridx[depth] = idxs[n];
8662 curi[depth] = 1;
8663 wordcount[depth] = 0;
8668 smsg((char_u *)_("Total number of words: %d"), words_done);
8670 return OK;
8674 * Make the table that links each word in the soundfold trie to the words it
8675 * can be produced from.
8676 * This is not unlike lines in a file, thus use a memfile to be able to access
8677 * the table efficiently.
8678 * Returns FAIL when out of memory.
8680 static int
8681 sug_maketable(spin)
8682 spellinfo_T *spin;
8684 garray_T ga;
8685 int res = OK;
8687 /* Allocate a buffer, open a memline for it and create the swap file
8688 * (uses a temp file, not a .swp file). */
8689 spin->si_spellbuf = open_spellbuf();
8690 if (spin->si_spellbuf == NULL)
8691 return FAIL;
8693 /* Use a buffer to store the line info, avoids allocating many small
8694 * pieces of memory. */
8695 ga_init2(&ga, 1, 100);
8697 /* recursively go through the tree */
8698 if (sug_filltable(spin, spin->si_foldroot->wn_sibling, 0, &ga) == -1)
8699 res = FAIL;
8701 ga_clear(&ga);
8702 return res;
8706 * Fill the table for one node and its children.
8707 * Returns the wordnr at the start of the node.
8708 * Returns -1 when out of memory.
8710 static int
8711 sug_filltable(spin, node, startwordnr, gap)
8712 spellinfo_T *spin;
8713 wordnode_T *node;
8714 int startwordnr;
8715 garray_T *gap; /* place to store line of numbers */
8717 wordnode_T *p, *np;
8718 int wordnr = startwordnr;
8719 int nr;
8720 int prev_nr;
8722 for (p = node; p != NULL; p = p->wn_sibling)
8724 if (p->wn_byte == NUL)
8726 gap->ga_len = 0;
8727 prev_nr = 0;
8728 for (np = p; np != NULL && np->wn_byte == NUL; np = np->wn_sibling)
8730 if (ga_grow(gap, 10) == FAIL)
8731 return -1;
8733 nr = (np->wn_flags << 16) + (np->wn_region & 0xffff);
8734 /* Compute the offset from the previous nr and store the
8735 * offset in a way that it takes a minimum number of bytes.
8736 * It's a bit like utf-8, but without the need to mark
8737 * following bytes. */
8738 nr -= prev_nr;
8739 prev_nr += nr;
8740 gap->ga_len += offset2bytes(nr,
8741 (char_u *)gap->ga_data + gap->ga_len);
8744 /* add the NUL byte */
8745 ((char_u *)gap->ga_data)[gap->ga_len++] = NUL;
8747 if (ml_append_buf(spin->si_spellbuf, (linenr_T)wordnr,
8748 gap->ga_data, gap->ga_len, TRUE) == FAIL)
8749 return -1;
8750 ++wordnr;
8752 /* Remove extra NUL entries, we no longer need them. We don't
8753 * bother freeing the nodes, the won't be reused anyway. */
8754 while (p->wn_sibling != NULL && p->wn_sibling->wn_byte == NUL)
8755 p->wn_sibling = p->wn_sibling->wn_sibling;
8757 /* Clear the flags on the remaining NUL node, so that compression
8758 * works a lot better. */
8759 p->wn_flags = 0;
8760 p->wn_region = 0;
8762 else
8764 wordnr = sug_filltable(spin, p->wn_child, wordnr, gap);
8765 if (wordnr == -1)
8766 return -1;
8769 return wordnr;
8773 * Convert an offset into a minimal number of bytes.
8774 * Similar to utf_char2byters, but use 8 bits in followup bytes and avoid NUL
8775 * bytes.
8777 static int
8778 offset2bytes(nr, buf)
8779 int nr;
8780 char_u *buf;
8782 int rem;
8783 int b1, b2, b3, b4;
8785 /* Split the number in parts of base 255. We need to avoid NUL bytes. */
8786 b1 = nr % 255 + 1;
8787 rem = nr / 255;
8788 b2 = rem % 255 + 1;
8789 rem = rem / 255;
8790 b3 = rem % 255 + 1;
8791 b4 = rem / 255 + 1;
8793 if (b4 > 1 || b3 > 0x1f) /* 4 bytes */
8795 buf[0] = 0xe0 + b4;
8796 buf[1] = b3;
8797 buf[2] = b2;
8798 buf[3] = b1;
8799 return 4;
8801 if (b3 > 1 || b2 > 0x3f ) /* 3 bytes */
8803 buf[0] = 0xc0 + b3;
8804 buf[1] = b2;
8805 buf[2] = b1;
8806 return 3;
8808 if (b2 > 1 || b1 > 0x7f ) /* 2 bytes */
8810 buf[0] = 0x80 + b2;
8811 buf[1] = b1;
8812 return 2;
8814 /* 1 byte */
8815 buf[0] = b1;
8816 return 1;
8820 * Opposite of offset2bytes().
8821 * "pp" points to the bytes and is advanced over it.
8822 * Returns the offset.
8824 static int
8825 bytes2offset(pp)
8826 char_u **pp;
8828 char_u *p = *pp;
8829 int nr;
8830 int c;
8832 c = *p++;
8833 if ((c & 0x80) == 0x00) /* 1 byte */
8835 nr = c - 1;
8837 else if ((c & 0xc0) == 0x80) /* 2 bytes */
8839 nr = (c & 0x3f) - 1;
8840 nr = nr * 255 + (*p++ - 1);
8842 else if ((c & 0xe0) == 0xc0) /* 3 bytes */
8844 nr = (c & 0x1f) - 1;
8845 nr = nr * 255 + (*p++ - 1);
8846 nr = nr * 255 + (*p++ - 1);
8848 else /* 4 bytes */
8850 nr = (c & 0x0f) - 1;
8851 nr = nr * 255 + (*p++ - 1);
8852 nr = nr * 255 + (*p++ - 1);
8853 nr = nr * 255 + (*p++ - 1);
8856 *pp = p;
8857 return nr;
8861 * Write the .sug file in "fname".
8863 static void
8864 sug_write(spin, fname)
8865 spellinfo_T *spin;
8866 char_u *fname;
8868 FILE *fd;
8869 wordnode_T *tree;
8870 int nodecount;
8871 int wcount;
8872 char_u *line;
8873 linenr_T lnum;
8874 int len;
8876 /* Create the file. Note that an existing file is silently overwritten! */
8877 fd = mch_fopen((char *)fname, "w");
8878 if (fd == NULL)
8880 EMSG2(_(e_notopen), fname);
8881 return;
8884 vim_snprintf((char *)IObuff, IOSIZE,
8885 _("Writing suggestion file %s ..."), fname);
8886 spell_message(spin, IObuff);
8889 * <SUGHEADER>: <fileID> <versionnr> <timestamp>
8891 if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) /* <fileID> */
8893 EMSG(_(e_write));
8894 goto theend;
8896 putc(VIMSUGVERSION, fd); /* <versionnr> */
8898 /* Write si_sugtime to the file. */
8899 put_sugtime(spin, fd); /* <timestamp> */
8902 * <SUGWORDTREE>
8904 spin->si_memtot = 0;
8905 tree = spin->si_foldroot->wn_sibling;
8907 /* Clear the index and wnode fields in the tree. */
8908 clear_node(tree);
8910 /* Count the number of nodes. Needed to be able to allocate the
8911 * memory when reading the nodes. Also fills in index for shared
8912 * nodes. */
8913 nodecount = put_node(NULL, tree, 0, 0, FALSE);
8915 /* number of nodes in 4 bytes */
8916 put_bytes(fd, (long_u)nodecount, 4); /* <nodecount> */
8917 spin->si_memtot += nodecount + nodecount * sizeof(int);
8919 /* Write the nodes. */
8920 (void)put_node(fd, tree, 0, 0, FALSE);
8923 * <SUGTABLE>: <sugwcount> <sugline> ...
8925 wcount = spin->si_spellbuf->b_ml.ml_line_count;
8926 put_bytes(fd, (long_u)wcount, 4); /* <sugwcount> */
8928 for (lnum = 1; lnum <= (linenr_T)wcount; ++lnum)
8930 /* <sugline>: <sugnr> ... NUL */
8931 line = ml_get_buf(spin->si_spellbuf, lnum, FALSE);
8932 len = (int)STRLEN(line) + 1;
8933 if (fwrite(line, (size_t)len, (size_t)1, fd) == 0)
8935 EMSG(_(e_write));
8936 goto theend;
8938 spin->si_memtot += len;
8941 /* Write another byte to check for errors. */
8942 if (putc(0, fd) == EOF)
8943 EMSG(_(e_write));
8945 vim_snprintf((char *)IObuff, IOSIZE,
8946 _("Estimated runtime memory use: %d bytes"), spin->si_memtot);
8947 spell_message(spin, IObuff);
8949 theend:
8950 /* close the file */
8951 fclose(fd);
8955 * Open a spell buffer. This is a nameless buffer that is not in the buffer
8956 * list and only contains text lines. Can use a swapfile to reduce memory
8957 * use.
8958 * Most other fields are invalid! Esp. watch out for string options being
8959 * NULL and there is no undo info.
8960 * Returns NULL when out of memory.
8962 static buf_T *
8963 open_spellbuf()
8965 buf_T *buf;
8967 buf = (buf_T *)alloc_clear(sizeof(buf_T));
8968 if (buf != NULL)
8970 buf->b_spell = TRUE;
8971 buf->b_p_swf = TRUE; /* may create a swap file */
8972 ml_open(buf);
8973 ml_open_file(buf); /* create swap file now */
8975 return buf;
8979 * Close the buffer used for spell info.
8981 static void
8982 close_spellbuf(buf)
8983 buf_T *buf;
8985 if (buf != NULL)
8987 ml_close(buf, TRUE);
8988 vim_free(buf);
8994 * Create a Vim spell file from one or more word lists.
8995 * "fnames[0]" is the output file name.
8996 * "fnames[fcount - 1]" is the last input file name.
8997 * Exception: when "fnames[0]" ends in ".add" it's used as the input file name
8998 * and ".spl" is appended to make the output file name.
9000 static void
9001 mkspell(fcount, fnames, ascii, overwrite, added_word)
9002 int fcount;
9003 char_u **fnames;
9004 int ascii; /* -ascii argument given */
9005 int overwrite; /* overwrite existing output file */
9006 int added_word; /* invoked through "zg" */
9008 char_u fname[MAXPATHL];
9009 char_u wfname[MAXPATHL];
9010 char_u **innames;
9011 int incount;
9012 afffile_T *(afile[8]);
9013 int i;
9014 int len;
9015 struct stat st;
9016 int error = FALSE;
9017 spellinfo_T spin;
9019 vim_memset(&spin, 0, sizeof(spin));
9020 spin.si_verbose = !added_word;
9021 spin.si_ascii = ascii;
9022 spin.si_followup = TRUE;
9023 spin.si_rem_accents = TRUE;
9024 ga_init2(&spin.si_rep, (int)sizeof(fromto_T), 20);
9025 ga_init2(&spin.si_repsal, (int)sizeof(fromto_T), 20);
9026 ga_init2(&spin.si_sal, (int)sizeof(fromto_T), 20);
9027 ga_init2(&spin.si_map, (int)sizeof(char_u), 100);
9028 ga_init2(&spin.si_comppat, (int)sizeof(char_u *), 20);
9029 ga_init2(&spin.si_prefcond, (int)sizeof(char_u *), 50);
9030 hash_init(&spin.si_commonwords);
9031 spin.si_newcompID = 127; /* start compound ID at first maximum */
9033 /* default: fnames[0] is output file, following are input files */
9034 innames = &fnames[1];
9035 incount = fcount - 1;
9037 if (fcount >= 1)
9039 len = (int)STRLEN(fnames[0]);
9040 if (fcount == 1 && len > 4 && STRCMP(fnames[0] + len - 4, ".add") == 0)
9042 /* For ":mkspell path/en.latin1.add" output file is
9043 * "path/en.latin1.add.spl". */
9044 innames = &fnames[0];
9045 incount = 1;
9046 vim_snprintf((char *)wfname, sizeof(wfname), "%s.spl", fnames[0]);
9048 else if (fcount == 1)
9050 /* For ":mkspell path/vim" output file is "path/vim.latin1.spl". */
9051 innames = &fnames[0];
9052 incount = 1;
9053 vim_snprintf((char *)wfname, sizeof(wfname), "%s.%s.spl", fnames[0],
9054 spin.si_ascii ? (char_u *)"ascii" : spell_enc());
9056 else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0)
9058 /* Name ends in ".spl", use as the file name. */
9059 vim_strncpy(wfname, fnames[0], sizeof(wfname) - 1);
9061 else
9062 /* Name should be language, make the file name from it. */
9063 vim_snprintf((char *)wfname, sizeof(wfname), "%s.%s.spl", fnames[0],
9064 spin.si_ascii ? (char_u *)"ascii" : spell_enc());
9066 /* Check for .ascii.spl. */
9067 if (strstr((char *)gettail(wfname), ".ascii.") != NULL)
9068 spin.si_ascii = TRUE;
9070 /* Check for .add.spl. */
9071 if (strstr((char *)gettail(wfname), ".add.") != NULL)
9072 spin.si_add = TRUE;
9075 if (incount <= 0)
9076 EMSG(_(e_invarg)); /* need at least output and input names */
9077 else if (vim_strchr(gettail(wfname), '_') != NULL)
9078 EMSG(_("E751: Output file name must not have region name"));
9079 else if (incount > 8)
9080 EMSG(_("E754: Only up to 8 regions supported"));
9081 else
9083 /* Check for overwriting before doing things that may take a lot of
9084 * time. */
9085 if (!overwrite && mch_stat((char *)wfname, &st) >= 0)
9087 EMSG(_(e_exists));
9088 return;
9090 if (mch_isdir(wfname))
9092 EMSG2(_(e_isadir2), wfname);
9093 return;
9097 * Init the aff and dic pointers.
9098 * Get the region names if there are more than 2 arguments.
9100 for (i = 0; i < incount; ++i)
9102 afile[i] = NULL;
9104 if (incount > 1)
9106 len = (int)STRLEN(innames[i]);
9107 if (STRLEN(gettail(innames[i])) < 5
9108 || innames[i][len - 3] != '_')
9110 EMSG2(_("E755: Invalid region in %s"), innames[i]);
9111 return;
9113 spin.si_region_name[i * 2] = TOLOWER_ASC(innames[i][len - 2]);
9114 spin.si_region_name[i * 2 + 1] =
9115 TOLOWER_ASC(innames[i][len - 1]);
9118 spin.si_region_count = incount;
9120 spin.si_foldroot = wordtree_alloc(&spin);
9121 spin.si_keeproot = wordtree_alloc(&spin);
9122 spin.si_prefroot = wordtree_alloc(&spin);
9123 if (spin.si_foldroot == NULL
9124 || spin.si_keeproot == NULL
9125 || spin.si_prefroot == NULL)
9127 free_blocks(spin.si_blocks);
9128 return;
9131 /* When not producing a .add.spl file clear the character table when
9132 * we encounter one in the .aff file. This means we dump the current
9133 * one in the .spl file if the .aff file doesn't define one. That's
9134 * better than guessing the contents, the table will match a
9135 * previously loaded spell file. */
9136 if (!spin.si_add)
9137 spin.si_clear_chartab = TRUE;
9140 * Read all the .aff and .dic files.
9141 * Text is converted to 'encoding'.
9142 * Words are stored in the case-folded and keep-case trees.
9144 for (i = 0; i < incount && !error; ++i)
9146 spin.si_conv.vc_type = CONV_NONE;
9147 spin.si_region = 1 << i;
9149 vim_snprintf((char *)fname, sizeof(fname), "%s.aff", innames[i]);
9150 if (mch_stat((char *)fname, &st) >= 0)
9152 /* Read the .aff file. Will init "spin->si_conv" based on the
9153 * "SET" line. */
9154 afile[i] = spell_read_aff(&spin, fname);
9155 if (afile[i] == NULL)
9156 error = TRUE;
9157 else
9159 /* Read the .dic file and store the words in the trees. */
9160 vim_snprintf((char *)fname, sizeof(fname), "%s.dic",
9161 innames[i]);
9162 if (spell_read_dic(&spin, fname, afile[i]) == FAIL)
9163 error = TRUE;
9166 else
9168 /* No .aff file, try reading the file as a word list. Store
9169 * the words in the trees. */
9170 if (spell_read_wordfile(&spin, innames[i]) == FAIL)
9171 error = TRUE;
9174 #ifdef FEAT_MBYTE
9175 /* Free any conversion stuff. */
9176 convert_setup(&spin.si_conv, NULL, NULL);
9177 #endif
9180 if (spin.si_compflags != NULL && spin.si_nobreak)
9181 MSG(_("Warning: both compounding and NOBREAK specified"));
9183 if (!error && !got_int)
9186 * Combine tails in the tree.
9188 spell_message(&spin, (char_u *)_(msg_compressing));
9189 wordtree_compress(&spin, spin.si_foldroot);
9190 wordtree_compress(&spin, spin.si_keeproot);
9191 wordtree_compress(&spin, spin.si_prefroot);
9194 if (!error && !got_int)
9197 * Write the info in the spell file.
9199 vim_snprintf((char *)IObuff, IOSIZE,
9200 _("Writing spell file %s ..."), wfname);
9201 spell_message(&spin, IObuff);
9203 error = write_vim_spell(&spin, wfname) == FAIL;
9205 spell_message(&spin, (char_u *)_("Done!"));
9206 vim_snprintf((char *)IObuff, IOSIZE,
9207 _("Estimated runtime memory use: %d bytes"), spin.si_memtot);
9208 spell_message(&spin, IObuff);
9211 * If the file is loaded need to reload it.
9213 if (!error)
9214 spell_reload_one(wfname, added_word);
9217 /* Free the allocated memory. */
9218 ga_clear(&spin.si_rep);
9219 ga_clear(&spin.si_repsal);
9220 ga_clear(&spin.si_sal);
9221 ga_clear(&spin.si_map);
9222 ga_clear(&spin.si_comppat);
9223 ga_clear(&spin.si_prefcond);
9224 hash_clear_all(&spin.si_commonwords, 0);
9226 /* Free the .aff file structures. */
9227 for (i = 0; i < incount; ++i)
9228 if (afile[i] != NULL)
9229 spell_free_aff(afile[i]);
9231 /* Free all the bits and pieces at once. */
9232 free_blocks(spin.si_blocks);
9235 * If there is soundfolding info and no NOSUGFILE item create the
9236 * .sug file with the soundfolded word trie.
9238 if (spin.si_sugtime != 0 && !error && !got_int)
9239 spell_make_sugfile(&spin, wfname);
9245 * Display a message for spell file processing when 'verbose' is set or using
9246 * ":mkspell". "str" can be IObuff.
9248 static void
9249 spell_message(spin, str)
9250 spellinfo_T *spin;
9251 char_u *str;
9253 if (spin->si_verbose || p_verbose > 2)
9255 if (!spin->si_verbose)
9256 verbose_enter();
9257 MSG(str);
9258 out_flush();
9259 if (!spin->si_verbose)
9260 verbose_leave();
9265 * ":[count]spellgood {word}"
9266 * ":[count]spellwrong {word}"
9267 * ":[count]spellundo {word}"
9269 void
9270 ex_spell(eap)
9271 exarg_T *eap;
9273 spell_add_word(eap->arg, (int)STRLEN(eap->arg), eap->cmdidx == CMD_spellwrong,
9274 eap->forceit ? 0 : (int)eap->line2,
9275 eap->cmdidx == CMD_spellundo);
9279 * Add "word[len]" to 'spellfile' as a good or bad word.
9281 void
9282 spell_add_word(word, len, bad, idx, undo)
9283 char_u *word;
9284 int len;
9285 int bad;
9286 int idx; /* "zG" and "zW": zero, otherwise index in
9287 'spellfile' */
9288 int undo; /* TRUE for "zug", "zuG", "zuw" and "zuW" */
9290 FILE *fd = NULL;
9291 buf_T *buf = NULL;
9292 int new_spf = FALSE;
9293 char_u *fname;
9294 char_u fnamebuf[MAXPATHL];
9295 char_u line[MAXWLEN * 2];
9296 long fpos, fpos_next = 0;
9297 int i;
9298 char_u *spf;
9300 if (idx == 0) /* use internal wordlist */
9302 if (int_wordlist == NULL)
9304 int_wordlist = vim_tempname('s');
9305 if (int_wordlist == NULL)
9306 return;
9308 fname = int_wordlist;
9310 else
9312 /* If 'spellfile' isn't set figure out a good default value. */
9313 if (*curbuf->b_p_spf == NUL)
9315 init_spellfile();
9316 new_spf = TRUE;
9319 if (*curbuf->b_p_spf == NUL)
9321 EMSG2(_(e_notset), "spellfile");
9322 return;
9325 for (spf = curbuf->b_p_spf, i = 1; *spf != NUL; ++i)
9327 copy_option_part(&spf, fnamebuf, MAXPATHL, ",");
9328 if (i == idx)
9329 break;
9330 if (*spf == NUL)
9332 EMSGN(_("E765: 'spellfile' does not have %ld entries"), idx);
9333 return;
9337 /* Check that the user isn't editing the .add file somewhere. */
9338 buf = buflist_findname_exp(fnamebuf);
9339 if (buf != NULL && buf->b_ml.ml_mfp == NULL)
9340 buf = NULL;
9341 if (buf != NULL && bufIsChanged(buf))
9343 EMSG(_(e_bufloaded));
9344 return;
9347 fname = fnamebuf;
9350 if (bad || undo)
9352 /* When the word appears as good word we need to remove that one,
9353 * since its flags sort before the one with WF_BANNED. */
9354 fd = mch_fopen((char *)fname, "r");
9355 if (fd != NULL)
9357 while (!vim_fgets(line, MAXWLEN * 2, fd))
9359 fpos = fpos_next;
9360 fpos_next = ftell(fd);
9361 if (STRNCMP(word, line, len) == 0
9362 && (line[len] == '/' || line[len] < ' '))
9364 /* Found duplicate word. Remove it by writing a '#' at
9365 * the start of the line. Mixing reading and writing
9366 * doesn't work for all systems, close the file first. */
9367 fclose(fd);
9368 fd = mch_fopen((char *)fname, "r+");
9369 if (fd == NULL)
9370 break;
9371 if (fseek(fd, fpos, SEEK_SET) == 0)
9373 fputc('#', fd);
9374 if (undo)
9376 home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
9377 smsg((char_u *)_("Word removed from %s"), NameBuff);
9380 fseek(fd, fpos_next, SEEK_SET);
9383 fclose(fd);
9387 if (!undo)
9389 fd = mch_fopen((char *)fname, "a");
9390 if (fd == NULL && new_spf)
9392 char_u *p;
9394 /* We just initialized the 'spellfile' option and can't open the
9395 * file. We may need to create the "spell" directory first. We
9396 * already checked the runtime directory is writable in
9397 * init_spellfile(). */
9398 if (!dir_of_file_exists(fname) && (p = gettail_sep(fname)) != fname)
9400 int c = *p;
9402 /* The directory doesn't exist. Try creating it and opening
9403 * the file again. */
9404 *p = NUL;
9405 vim_mkdir(fname, 0755);
9406 *p = c;
9407 fd = mch_fopen((char *)fname, "a");
9411 if (fd == NULL)
9412 EMSG2(_(e_notopen), fname);
9413 else
9415 if (bad)
9416 fprintf(fd, "%.*s/!\n", len, word);
9417 else
9418 fprintf(fd, "%.*s\n", len, word);
9419 fclose(fd);
9421 home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
9422 smsg((char_u *)_("Word added to %s"), NameBuff);
9426 if (fd != NULL)
9428 /* Update the .add.spl file. */
9429 mkspell(1, &fname, FALSE, TRUE, TRUE);
9431 /* If the .add file is edited somewhere, reload it. */
9432 if (buf != NULL)
9433 buf_reload(buf, buf->b_orig_mode);
9435 redraw_all_later(SOME_VALID);
9440 * Initialize 'spellfile' for the current buffer.
9442 static void
9443 init_spellfile()
9445 char_u buf[MAXPATHL];
9446 int l;
9447 char_u *fname;
9448 char_u *rtp;
9449 char_u *lend;
9450 int aspath = FALSE;
9451 char_u *lstart = curbuf->b_p_spl;
9453 if (*curbuf->b_p_spl != NUL && curbuf->b_langp.ga_len > 0)
9455 /* Find the end of the language name. Exclude the region. If there
9456 * is a path separator remember the start of the tail. */
9457 for (lend = curbuf->b_p_spl; *lend != NUL
9458 && vim_strchr((char_u *)",._", *lend) == NULL; ++lend)
9459 if (vim_ispathsep(*lend))
9461 aspath = TRUE;
9462 lstart = lend + 1;
9465 /* Loop over all entries in 'runtimepath'. Use the first one where we
9466 * are allowed to write. */
9467 rtp = p_rtp;
9468 while (*rtp != NUL)
9470 if (aspath)
9471 /* Use directory of an entry with path, e.g., for
9472 * "/dir/lg.utf-8.spl" use "/dir". */
9473 vim_strncpy(buf, curbuf->b_p_spl, lstart - curbuf->b_p_spl - 1);
9474 else
9475 /* Copy the path from 'runtimepath' to buf[]. */
9476 copy_option_part(&rtp, buf, MAXPATHL, ",");
9477 if (filewritable(buf) == 2)
9479 /* Use the first language name from 'spelllang' and the
9480 * encoding used in the first loaded .spl file. */
9481 if (aspath)
9482 vim_strncpy(buf, curbuf->b_p_spl, lend - curbuf->b_p_spl);
9483 else
9485 /* Create the "spell" directory if it doesn't exist yet. */
9486 l = (int)STRLEN(buf);
9487 vim_snprintf((char *)buf + l, MAXPATHL - l, "/spell");
9488 if (!filewritable(buf) != 2)
9489 vim_mkdir(buf, 0755);
9491 l = (int)STRLEN(buf);
9492 vim_snprintf((char *)buf + l, MAXPATHL - l,
9493 "/%.*s", (int)(lend - lstart), lstart);
9495 l = (int)STRLEN(buf);
9496 fname = LANGP_ENTRY(curbuf->b_langp, 0)->lp_slang->sl_fname;
9497 vim_snprintf((char *)buf + l, MAXPATHL - l, ".%s.add",
9498 fname != NULL
9499 && strstr((char *)gettail(fname), ".ascii.") != NULL
9500 ? (char_u *)"ascii" : spell_enc());
9501 set_option_value((char_u *)"spellfile", 0L, buf, OPT_LOCAL);
9502 break;
9504 aspath = FALSE;
9511 * Init the chartab used for spelling for ASCII.
9512 * EBCDIC is not supported!
9514 static void
9515 clear_spell_chartab(sp)
9516 spelltab_T *sp;
9518 int i;
9520 /* Init everything to FALSE. */
9521 vim_memset(sp->st_isw, FALSE, sizeof(sp->st_isw));
9522 vim_memset(sp->st_isu, FALSE, sizeof(sp->st_isu));
9523 for (i = 0; i < 256; ++i)
9525 sp->st_fold[i] = i;
9526 sp->st_upper[i] = i;
9529 /* We include digits. A word shouldn't start with a digit, but handling
9530 * that is done separately. */
9531 for (i = '0'; i <= '9'; ++i)
9532 sp->st_isw[i] = TRUE;
9533 for (i = 'A'; i <= 'Z'; ++i)
9535 sp->st_isw[i] = TRUE;
9536 sp->st_isu[i] = TRUE;
9537 sp->st_fold[i] = i + 0x20;
9539 for (i = 'a'; i <= 'z'; ++i)
9541 sp->st_isw[i] = TRUE;
9542 sp->st_upper[i] = i - 0x20;
9547 * Init the chartab used for spelling. Only depends on 'encoding'.
9548 * Called once while starting up and when 'encoding' changes.
9549 * The default is to use isalpha(), but the spell file should define the word
9550 * characters to make it possible that 'encoding' differs from the current
9551 * locale. For utf-8 we don't use isalpha() but our own functions.
9553 void
9554 init_spell_chartab()
9556 int i;
9558 did_set_spelltab = FALSE;
9559 clear_spell_chartab(&spelltab);
9560 #ifdef FEAT_MBYTE
9561 if (enc_dbcs)
9563 /* DBCS: assume double-wide characters are word characters. */
9564 for (i = 128; i <= 255; ++i)
9565 if (MB_BYTE2LEN(i) == 2)
9566 spelltab.st_isw[i] = TRUE;
9568 else if (enc_utf8)
9570 for (i = 128; i < 256; ++i)
9572 spelltab.st_isu[i] = utf_isupper(i);
9573 spelltab.st_isw[i] = spelltab.st_isu[i] || utf_islower(i);
9574 spelltab.st_fold[i] = utf_fold(i);
9575 spelltab.st_upper[i] = utf_toupper(i);
9578 else
9579 #endif
9581 /* Rough guess: use locale-dependent library functions. */
9582 for (i = 128; i < 256; ++i)
9584 if (MB_ISUPPER(i))
9586 spelltab.st_isw[i] = TRUE;
9587 spelltab.st_isu[i] = TRUE;
9588 spelltab.st_fold[i] = MB_TOLOWER(i);
9590 else if (MB_ISLOWER(i))
9592 spelltab.st_isw[i] = TRUE;
9593 spelltab.st_upper[i] = MB_TOUPPER(i);
9600 * Set the spell character tables from strings in the affix file.
9602 static int
9603 set_spell_chartab(fol, low, upp)
9604 char_u *fol;
9605 char_u *low;
9606 char_u *upp;
9608 /* We build the new tables here first, so that we can compare with the
9609 * previous one. */
9610 spelltab_T new_st;
9611 char_u *pf = fol, *pl = low, *pu = upp;
9612 int f, l, u;
9614 clear_spell_chartab(&new_st);
9616 while (*pf != NUL)
9618 if (*pl == NUL || *pu == NUL)
9620 EMSG(_(e_affform));
9621 return FAIL;
9623 #ifdef FEAT_MBYTE
9624 f = mb_ptr2char_adv(&pf);
9625 l = mb_ptr2char_adv(&pl);
9626 u = mb_ptr2char_adv(&pu);
9627 #else
9628 f = *pf++;
9629 l = *pl++;
9630 u = *pu++;
9631 #endif
9632 /* Every character that appears is a word character. */
9633 if (f < 256)
9634 new_st.st_isw[f] = TRUE;
9635 if (l < 256)
9636 new_st.st_isw[l] = TRUE;
9637 if (u < 256)
9638 new_st.st_isw[u] = TRUE;
9640 /* if "LOW" and "FOL" are not the same the "LOW" char needs
9641 * case-folding */
9642 if (l < 256 && l != f)
9644 if (f >= 256)
9646 EMSG(_(e_affrange));
9647 return FAIL;
9649 new_st.st_fold[l] = f;
9652 /* if "UPP" and "FOL" are not the same the "UPP" char needs
9653 * case-folding, it's upper case and the "UPP" is the upper case of
9654 * "FOL" . */
9655 if (u < 256 && u != f)
9657 if (f >= 256)
9659 EMSG(_(e_affrange));
9660 return FAIL;
9662 new_st.st_fold[u] = f;
9663 new_st.st_isu[u] = TRUE;
9664 new_st.st_upper[f] = u;
9668 if (*pl != NUL || *pu != NUL)
9670 EMSG(_(e_affform));
9671 return FAIL;
9674 return set_spell_finish(&new_st);
9678 * Set the spell character tables from strings in the .spl file.
9680 static void
9681 set_spell_charflags(flags, cnt, fol)
9682 char_u *flags;
9683 int cnt; /* length of "flags" */
9684 char_u *fol;
9686 /* We build the new tables here first, so that we can compare with the
9687 * previous one. */
9688 spelltab_T new_st;
9689 int i;
9690 char_u *p = fol;
9691 int c;
9693 clear_spell_chartab(&new_st);
9695 for (i = 0; i < 128; ++i)
9697 if (i < cnt)
9699 new_st.st_isw[i + 128] = (flags[i] & CF_WORD) != 0;
9700 new_st.st_isu[i + 128] = (flags[i] & CF_UPPER) != 0;
9703 if (*p != NUL)
9705 #ifdef FEAT_MBYTE
9706 c = mb_ptr2char_adv(&p);
9707 #else
9708 c = *p++;
9709 #endif
9710 new_st.st_fold[i + 128] = c;
9711 if (i + 128 != c && new_st.st_isu[i + 128] && c < 256)
9712 new_st.st_upper[c] = i + 128;
9716 (void)set_spell_finish(&new_st);
9719 static int
9720 set_spell_finish(new_st)
9721 spelltab_T *new_st;
9723 int i;
9725 if (did_set_spelltab)
9727 /* check that it's the same table */
9728 for (i = 0; i < 256; ++i)
9730 if (spelltab.st_isw[i] != new_st->st_isw[i]
9731 || spelltab.st_isu[i] != new_st->st_isu[i]
9732 || spelltab.st_fold[i] != new_st->st_fold[i]
9733 || spelltab.st_upper[i] != new_st->st_upper[i])
9735 EMSG(_("E763: Word characters differ between spell files"));
9736 return FAIL;
9740 else
9742 /* copy the new spelltab into the one being used */
9743 spelltab = *new_st;
9744 did_set_spelltab = TRUE;
9747 return OK;
9751 * Return TRUE if "p" points to a word character.
9752 * As a special case we see "midword" characters as word character when it is
9753 * followed by a word character. This finds they'there but not 'they there'.
9754 * Thus this only works properly when past the first character of the word.
9756 static int
9757 spell_iswordp(p, buf)
9758 char_u *p;
9759 buf_T *buf; /* buffer used */
9761 #ifdef FEAT_MBYTE
9762 char_u *s;
9763 int l;
9764 int c;
9766 if (has_mbyte)
9768 l = MB_BYTE2LEN(*p);
9769 s = p;
9770 if (l == 1)
9772 /* be quick for ASCII */
9773 if (buf->b_spell_ismw[*p])
9775 s = p + 1; /* skip a mid-word character */
9776 l = MB_BYTE2LEN(*s);
9779 else
9781 c = mb_ptr2char(p);
9782 if (c < 256 ? buf->b_spell_ismw[c]
9783 : (buf->b_spell_ismw_mb != NULL
9784 && vim_strchr(buf->b_spell_ismw_mb, c) != NULL))
9786 s = p + l;
9787 l = MB_BYTE2LEN(*s);
9791 c = mb_ptr2char(s);
9792 if (c > 255)
9793 return spell_mb_isword_class(mb_get_class(s));
9794 return spelltab.st_isw[c];
9796 #endif
9798 return spelltab.st_isw[buf->b_spell_ismw[*p] ? p[1] : p[0]];
9802 * Return TRUE if "p" points to a word character.
9803 * Unlike spell_iswordp() this doesn't check for "midword" characters.
9805 static int
9806 spell_iswordp_nmw(p)
9807 char_u *p;
9809 #ifdef FEAT_MBYTE
9810 int c;
9812 if (has_mbyte)
9814 c = mb_ptr2char(p);
9815 if (c > 255)
9816 return spell_mb_isword_class(mb_get_class(p));
9817 return spelltab.st_isw[c];
9819 #endif
9820 return spelltab.st_isw[*p];
9823 #ifdef FEAT_MBYTE
9825 * Return TRUE if word class indicates a word character.
9826 * Only for characters above 255.
9827 * Unicode subscript and superscript are not considered word characters.
9829 static int
9830 spell_mb_isword_class(cl)
9831 int cl;
9833 return cl >= 2 && cl != 0x2070 && cl != 0x2080;
9837 * Return TRUE if "p" points to a word character.
9838 * Wide version of spell_iswordp().
9840 static int
9841 spell_iswordp_w(p, buf)
9842 int *p;
9843 buf_T *buf;
9845 int *s;
9847 if (*p < 256 ? buf->b_spell_ismw[*p]
9848 : (buf->b_spell_ismw_mb != NULL
9849 && vim_strchr(buf->b_spell_ismw_mb, *p) != NULL))
9850 s = p + 1;
9851 else
9852 s = p;
9854 if (*s > 255)
9856 if (enc_utf8)
9857 return spell_mb_isword_class(utf_class(*s));
9858 if (enc_dbcs)
9859 return dbcs_class((unsigned)*s >> 8, *s & 0xff) >= 2;
9860 return 0;
9862 return spelltab.st_isw[*s];
9864 #endif
9867 * Write the table with prefix conditions to the .spl file.
9868 * When "fd" is NULL only count the length of what is written.
9870 static int
9871 write_spell_prefcond(fd, gap)
9872 FILE *fd;
9873 garray_T *gap;
9875 int i;
9876 char_u *p;
9877 int len;
9878 int totlen;
9880 if (fd != NULL)
9881 put_bytes(fd, (long_u)gap->ga_len, 2); /* <prefcondcnt> */
9883 totlen = 2 + gap->ga_len; /* length of <prefcondcnt> and <condlen> bytes */
9885 for (i = 0; i < gap->ga_len; ++i)
9887 /* <prefcond> : <condlen> <condstr> */
9888 p = ((char_u **)gap->ga_data)[i];
9889 if (p != NULL)
9891 len = (int)STRLEN(p);
9892 if (fd != NULL)
9894 fputc(len, fd);
9895 fwrite(p, (size_t)len, (size_t)1, fd);
9897 totlen += len;
9899 else if (fd != NULL)
9900 fputc(0, fd);
9903 return totlen;
9907 * Case-fold "str[len]" into "buf[buflen]". The result is NUL terminated.
9908 * Uses the character definitions from the .spl file.
9909 * When using a multi-byte 'encoding' the length may change!
9910 * Returns FAIL when something wrong.
9912 static int
9913 spell_casefold(str, len, buf, buflen)
9914 char_u *str;
9915 int len;
9916 char_u *buf;
9917 int buflen;
9919 int i;
9921 if (len >= buflen)
9923 buf[0] = NUL;
9924 return FAIL; /* result will not fit */
9927 #ifdef FEAT_MBYTE
9928 if (has_mbyte)
9930 int outi = 0;
9931 char_u *p;
9932 int c;
9934 /* Fold one character at a time. */
9935 for (p = str; p < str + len; )
9937 if (outi + MB_MAXBYTES > buflen)
9939 buf[outi] = NUL;
9940 return FAIL;
9942 c = mb_cptr2char_adv(&p);
9943 outi += mb_char2bytes(SPELL_TOFOLD(c), buf + outi);
9945 buf[outi] = NUL;
9947 else
9948 #endif
9950 /* Be quick for non-multibyte encodings. */
9951 for (i = 0; i < len; ++i)
9952 buf[i] = spelltab.st_fold[str[i]];
9953 buf[i] = NUL;
9956 return OK;
9959 /* values for sps_flags */
9960 #define SPS_BEST 1
9961 #define SPS_FAST 2
9962 #define SPS_DOUBLE 4
9964 static int sps_flags = SPS_BEST; /* flags from 'spellsuggest' */
9965 static int sps_limit = 9999; /* max nr of suggestions given */
9968 * Check the 'spellsuggest' option. Return FAIL if it's wrong.
9969 * Sets "sps_flags" and "sps_limit".
9972 spell_check_sps()
9974 char_u *p;
9975 char_u *s;
9976 char_u buf[MAXPATHL];
9977 int f;
9979 sps_flags = 0;
9980 sps_limit = 9999;
9982 for (p = p_sps; *p != NUL; )
9984 copy_option_part(&p, buf, MAXPATHL, ",");
9986 f = 0;
9987 if (VIM_ISDIGIT(*buf))
9989 s = buf;
9990 sps_limit = getdigits(&s);
9991 if (*s != NUL && !VIM_ISDIGIT(*s))
9992 f = -1;
9994 else if (STRCMP(buf, "best") == 0)
9995 f = SPS_BEST;
9996 else if (STRCMP(buf, "fast") == 0)
9997 f = SPS_FAST;
9998 else if (STRCMP(buf, "double") == 0)
9999 f = SPS_DOUBLE;
10000 else if (STRNCMP(buf, "expr:", 5) != 0
10001 && STRNCMP(buf, "file:", 5) != 0)
10002 f = -1;
10004 if (f == -1 || (sps_flags != 0 && f != 0))
10006 sps_flags = SPS_BEST;
10007 sps_limit = 9999;
10008 return FAIL;
10010 if (f != 0)
10011 sps_flags = f;
10014 if (sps_flags == 0)
10015 sps_flags = SPS_BEST;
10017 return OK;
10021 * "z?": Find badly spelled word under or after the cursor.
10022 * Give suggestions for the properly spelled word.
10023 * In Visual mode use the highlighted word as the bad word.
10024 * When "count" is non-zero use that suggestion.
10026 void
10027 spell_suggest(count)
10028 int count;
10030 char_u *line;
10031 pos_T prev_cursor = curwin->w_cursor;
10032 char_u wcopy[MAXWLEN + 2];
10033 char_u *p;
10034 int i;
10035 int c;
10036 suginfo_T sug;
10037 suggest_T *stp;
10038 int mouse_used;
10039 int need_cap;
10040 int limit;
10041 int selected = count;
10042 int badlen = 0;
10044 if (no_spell_checking(curwin))
10045 return;
10047 #ifdef FEAT_VISUAL
10048 if (VIsual_active)
10050 /* Use the Visually selected text as the bad word. But reject
10051 * a multi-line selection. */
10052 if (curwin->w_cursor.lnum != VIsual.lnum)
10054 vim_beep();
10055 return;
10057 badlen = (int)curwin->w_cursor.col - (int)VIsual.col;
10058 if (badlen < 0)
10059 badlen = -badlen;
10060 else
10061 curwin->w_cursor.col = VIsual.col;
10062 ++badlen;
10063 end_visual_mode();
10065 else
10066 #endif
10067 /* Find the start of the badly spelled word. */
10068 if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0
10069 || curwin->w_cursor.col > prev_cursor.col)
10071 /* No bad word or it starts after the cursor: use the word under the
10072 * cursor. */
10073 curwin->w_cursor = prev_cursor;
10074 line = ml_get_curline();
10075 p = line + curwin->w_cursor.col;
10076 /* Backup to before start of word. */
10077 while (p > line && spell_iswordp_nmw(p))
10078 mb_ptr_back(line, p);
10079 /* Forward to start of word. */
10080 while (*p != NUL && !spell_iswordp_nmw(p))
10081 mb_ptr_adv(p);
10083 if (!spell_iswordp_nmw(p)) /* No word found. */
10085 beep_flush();
10086 return;
10088 curwin->w_cursor.col = (colnr_T)(p - line);
10091 /* Get the word and its length. */
10093 /* Figure out if the word should be capitalised. */
10094 need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);
10096 line = ml_get_curline();
10098 /* Get the list of suggestions. Limit to 'lines' - 2 or the number in
10099 * 'spellsuggest', whatever is smaller. */
10100 if (sps_limit > (int)Rows - 2)
10101 limit = (int)Rows - 2;
10102 else
10103 limit = sps_limit;
10104 spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
10105 TRUE, need_cap, TRUE);
10107 if (sug.su_ga.ga_len == 0)
10108 MSG(_("Sorry, no suggestions"));
10109 else if (count > 0)
10111 if (count > sug.su_ga.ga_len)
10112 smsg((char_u *)_("Sorry, only %ld suggestions"),
10113 (long)sug.su_ga.ga_len);
10115 else
10117 vim_free(repl_from);
10118 repl_from = NULL;
10119 vim_free(repl_to);
10120 repl_to = NULL;
10122 #ifdef FEAT_RIGHTLEFT
10123 /* When 'rightleft' is set the list is drawn right-left. */
10124 cmdmsg_rl = curwin->w_p_rl;
10125 if (cmdmsg_rl)
10126 msg_col = Columns - 1;
10127 #endif
10129 /* List the suggestions. */
10130 msg_start();
10131 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
10132 lines_left = Rows; /* avoid more prompt */
10133 vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"),
10134 sug.su_badlen, sug.su_badptr);
10135 #ifdef FEAT_RIGHTLEFT
10136 if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0)
10138 /* And now the rabbit from the high hat: Avoid showing the
10139 * untranslated message rightleft. */
10140 vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC",
10141 sug.su_badlen, sug.su_badptr);
10143 #endif
10144 msg_puts(IObuff);
10145 msg_clr_eos();
10146 msg_putchar('\n');
10148 msg_scroll = TRUE;
10149 for (i = 0; i < sug.su_ga.ga_len; ++i)
10151 stp = &SUG(sug.su_ga, i);
10153 /* The suggested word may replace only part of the bad word, add
10154 * the not replaced part. */
10155 STRCPY(wcopy, stp->st_word);
10156 if (sug.su_badlen > stp->st_orglen)
10157 vim_strncpy(wcopy + stp->st_wordlen,
10158 sug.su_badptr + stp->st_orglen,
10159 sug.su_badlen - stp->st_orglen);
10160 vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1);
10161 #ifdef FEAT_RIGHTLEFT
10162 if (cmdmsg_rl)
10163 rl_mirror(IObuff);
10164 #endif
10165 msg_puts(IObuff);
10167 vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy);
10168 msg_puts(IObuff);
10170 /* The word may replace more than "su_badlen". */
10171 if (sug.su_badlen < stp->st_orglen)
10173 vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""),
10174 stp->st_orglen, sug.su_badptr);
10175 msg_puts(IObuff);
10178 if (p_verbose > 0)
10180 /* Add the score. */
10181 if (sps_flags & (SPS_DOUBLE | SPS_BEST))
10182 vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)",
10183 stp->st_salscore ? "s " : "",
10184 stp->st_score, stp->st_altscore);
10185 else
10186 vim_snprintf((char *)IObuff, IOSIZE, " (%d)",
10187 stp->st_score);
10188 #ifdef FEAT_RIGHTLEFT
10189 if (cmdmsg_rl)
10190 /* Mirror the numbers, but keep the leading space. */
10191 rl_mirror(IObuff + 1);
10192 #endif
10193 msg_advance(30);
10194 msg_puts(IObuff);
10196 msg_putchar('\n');
10199 #ifdef FEAT_RIGHTLEFT
10200 cmdmsg_rl = FALSE;
10201 msg_col = 0;
10202 #endif
10203 /* Ask for choice. */
10204 selected = prompt_for_number(&mouse_used);
10205 if (mouse_used)
10206 selected -= lines_left;
10207 lines_left = Rows; /* avoid more prompt */
10210 if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)
10212 /* Save the from and to text for :spellrepall. */
10213 stp = &SUG(sug.su_ga, selected - 1);
10214 if (sug.su_badlen > stp->st_orglen)
10216 /* Replacing less than "su_badlen", append the remainder to
10217 * repl_to. */
10218 repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);
10219 vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word,
10220 sug.su_badlen - stp->st_orglen,
10221 sug.su_badptr + stp->st_orglen);
10222 repl_to = vim_strsave(IObuff);
10224 else
10226 /* Replacing su_badlen or more, use the whole word. */
10227 repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);
10228 repl_to = vim_strsave(stp->st_word);
10231 /* Replace the word. */
10232 p = alloc((unsigned)STRLEN(line) - stp->st_orglen + stp->st_wordlen + 1);
10233 if (p != NULL)
10235 c = (int)(sug.su_badptr - line);
10236 mch_memmove(p, line, c);
10237 STRCPY(p + c, stp->st_word);
10238 STRCAT(p, sug.su_badptr + stp->st_orglen);
10239 ml_replace(curwin->w_cursor.lnum, p, FALSE);
10240 curwin->w_cursor.col = c;
10242 /* For redo we use a change-word command. */
10243 ResetRedobuff();
10244 AppendToRedobuff((char_u *)"ciw");
10245 AppendToRedobuffLit(p + c,
10246 stp->st_wordlen + sug.su_badlen - stp->st_orglen);
10247 AppendCharToRedobuff(ESC);
10249 /* After this "p" may be invalid. */
10250 changed_bytes(curwin->w_cursor.lnum, c);
10253 else
10254 curwin->w_cursor = prev_cursor;
10256 spell_find_cleanup(&sug);
10260 * Check if the word at line "lnum" column "col" is required to start with a
10261 * capital. This uses 'spellcapcheck' of the current buffer.
10263 static int
10264 check_need_cap(lnum, col)
10265 linenr_T lnum;
10266 colnr_T col;
10268 int need_cap = FALSE;
10269 char_u *line;
10270 char_u *line_copy = NULL;
10271 char_u *p;
10272 colnr_T endcol;
10273 regmatch_T regmatch;
10275 if (curbuf->b_cap_prog == NULL)
10276 return FALSE;
10278 line = ml_get_curline();
10279 endcol = 0;
10280 if ((int)(skipwhite(line) - line) >= (int)col)
10282 /* At start of line, check if previous line is empty or sentence
10283 * ends there. */
10284 if (lnum == 1)
10285 need_cap = TRUE;
10286 else
10288 line = ml_get(lnum - 1);
10289 if (*skipwhite(line) == NUL)
10290 need_cap = TRUE;
10291 else
10293 /* Append a space in place of the line break. */
10294 line_copy = concat_str(line, (char_u *)" ");
10295 line = line_copy;
10296 endcol = (colnr_T)STRLEN(line);
10300 else
10301 endcol = col;
10303 if (endcol > 0)
10305 /* Check if sentence ends before the bad word. */
10306 regmatch.regprog = curbuf->b_cap_prog;
10307 regmatch.rm_ic = FALSE;
10308 p = line + endcol;
10309 for (;;)
10311 mb_ptr_back(line, p);
10312 if (p == line || spell_iswordp_nmw(p))
10313 break;
10314 if (vim_regexec(&regmatch, p, 0)
10315 && regmatch.endp[0] == line + endcol)
10317 need_cap = TRUE;
10318 break;
10323 vim_free(line_copy);
10325 return need_cap;
10330 * ":spellrepall"
10332 /*ARGSUSED*/
10333 void
10334 ex_spellrepall(eap)
10335 exarg_T *eap;
10337 pos_T pos = curwin->w_cursor;
10338 char_u *frompat;
10339 int addlen;
10340 char_u *line;
10341 char_u *p;
10342 int save_ws = p_ws;
10343 linenr_T prev_lnum = 0;
10345 if (repl_from == NULL || repl_to == NULL)
10347 EMSG(_("E752: No previous spell replacement"));
10348 return;
10350 addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from));
10352 frompat = alloc((unsigned)STRLEN(repl_from) + 7);
10353 if (frompat == NULL)
10354 return;
10355 sprintf((char *)frompat, "\\V\\<%s\\>", repl_from);
10356 p_ws = FALSE;
10358 sub_nsubs = 0;
10359 sub_nlines = 0;
10360 curwin->w_cursor.lnum = 0;
10361 while (!got_int)
10363 if (do_search(NULL, '/', frompat, 1L, SEARCH_KEEP, NULL) == 0
10364 || u_save_cursor() == FAIL)
10365 break;
10367 /* Only replace when the right word isn't there yet. This happens
10368 * when changing "etc" to "etc.". */
10369 line = ml_get_curline();
10370 if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col,
10371 repl_to, STRLEN(repl_to)) != 0)
10373 p = alloc((unsigned)STRLEN(line) + addlen + 1);
10374 if (p == NULL)
10375 break;
10376 mch_memmove(p, line, curwin->w_cursor.col);
10377 STRCPY(p + curwin->w_cursor.col, repl_to);
10378 STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from));
10379 ml_replace(curwin->w_cursor.lnum, p, FALSE);
10380 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
10382 if (curwin->w_cursor.lnum != prev_lnum)
10384 ++sub_nlines;
10385 prev_lnum = curwin->w_cursor.lnum;
10387 ++sub_nsubs;
10389 curwin->w_cursor.col += (colnr_T)STRLEN(repl_to);
10392 p_ws = save_ws;
10393 curwin->w_cursor = pos;
10394 vim_free(frompat);
10396 if (sub_nsubs == 0)
10397 EMSG2(_("E753: Not found: %s"), repl_from);
10398 else
10399 do_sub_msg(FALSE);
10403 * Find spell suggestions for "word". Return them in the growarray "*gap" as
10404 * a list of allocated strings.
10406 void
10407 spell_suggest_list(gap, word, maxcount, need_cap, interactive)
10408 garray_T *gap;
10409 char_u *word;
10410 int maxcount; /* maximum nr of suggestions */
10411 int need_cap; /* 'spellcapcheck' matched */
10412 int interactive;
10414 suginfo_T sug;
10415 int i;
10416 suggest_T *stp;
10417 char_u *wcopy;
10419 spell_find_suggest(word, 0, &sug, maxcount, FALSE, need_cap, interactive);
10421 /* Make room in "gap". */
10422 ga_init2(gap, sizeof(char_u *), sug.su_ga.ga_len + 1);
10423 if (ga_grow(gap, sug.su_ga.ga_len) == OK)
10425 for (i = 0; i < sug.su_ga.ga_len; ++i)
10427 stp = &SUG(sug.su_ga, i);
10429 /* The suggested word may replace only part of "word", add the not
10430 * replaced part. */
10431 wcopy = alloc(stp->st_wordlen
10432 + (unsigned)STRLEN(sug.su_badptr + stp->st_orglen) + 1);
10433 if (wcopy == NULL)
10434 break;
10435 STRCPY(wcopy, stp->st_word);
10436 STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen);
10437 ((char_u **)gap->ga_data)[gap->ga_len++] = wcopy;
10441 spell_find_cleanup(&sug);
10445 * Find spell suggestions for the word at the start of "badptr".
10446 * Return the suggestions in "su->su_ga".
10447 * The maximum number of suggestions is "maxcount".
10448 * Note: does use info for the current window.
10449 * This is based on the mechanisms of Aspell, but completely reimplemented.
10451 static void
10452 spell_find_suggest(badptr, badlen, su, maxcount, banbadword, need_cap, interactive)
10453 char_u *badptr;
10454 int badlen; /* length of bad word or 0 if unknown */
10455 suginfo_T *su;
10456 int maxcount;
10457 int banbadword; /* don't include badword in suggestions */
10458 int need_cap; /* word should start with capital */
10459 int interactive;
10461 hlf_T attr = HLF_COUNT;
10462 char_u buf[MAXPATHL];
10463 char_u *p;
10464 int do_combine = FALSE;
10465 char_u *sps_copy;
10466 #ifdef FEAT_EVAL
10467 static int expr_busy = FALSE;
10468 #endif
10469 int c;
10470 int i;
10471 langp_T *lp;
10474 * Set the info in "*su".
10476 vim_memset(su, 0, sizeof(suginfo_T));
10477 ga_init2(&su->su_ga, (int)sizeof(suggest_T), 10);
10478 ga_init2(&su->su_sga, (int)sizeof(suggest_T), 10);
10479 if (*badptr == NUL)
10480 return;
10481 hash_init(&su->su_banned);
10483 su->su_badptr = badptr;
10484 if (badlen != 0)
10485 su->su_badlen = badlen;
10486 else
10487 su->su_badlen = spell_check(curwin, su->su_badptr, &attr, NULL, FALSE);
10488 su->su_maxcount = maxcount;
10489 su->su_maxscore = SCORE_MAXINIT;
10491 if (su->su_badlen >= MAXWLEN)
10492 su->su_badlen = MAXWLEN - 1; /* just in case */
10493 vim_strncpy(su->su_badword, su->su_badptr, su->su_badlen);
10494 (void)spell_casefold(su->su_badptr, su->su_badlen,
10495 su->su_fbadword, MAXWLEN);
10496 /* get caps flags for bad word */
10497 su->su_badflags = badword_captype(su->su_badptr,
10498 su->su_badptr + su->su_badlen);
10499 if (need_cap)
10500 su->su_badflags |= WF_ONECAP;
10502 /* Find the default language for sound folding. We simply use the first
10503 * one in 'spelllang' that supports sound folding. That's good for when
10504 * using multiple files for one language, it's not that bad when mixing
10505 * languages (e.g., "pl,en"). */
10506 for (i = 0; i < curbuf->b_langp.ga_len; ++i)
10508 lp = LANGP_ENTRY(curbuf->b_langp, i);
10509 if (lp->lp_sallang != NULL)
10511 su->su_sallang = lp->lp_sallang;
10512 break;
10516 /* Soundfold the bad word with the default sound folding, so that we don't
10517 * have to do this many times. */
10518 if (su->su_sallang != NULL)
10519 spell_soundfold(su->su_sallang, su->su_fbadword, TRUE,
10520 su->su_sal_badword);
10522 /* If the word is not capitalised and spell_check() doesn't consider the
10523 * word to be bad then it might need to be capitalised. Add a suggestion
10524 * for that. */
10525 c = PTR2CHAR(su->su_badptr);
10526 if (!SPELL_ISUPPER(c) && attr == HLF_COUNT)
10528 make_case_word(su->su_badword, buf, WF_ONECAP);
10529 add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE,
10530 0, TRUE, su->su_sallang, FALSE);
10533 /* Ban the bad word itself. It may appear in another region. */
10534 if (banbadword)
10535 add_banned(su, su->su_badword);
10537 /* Make a copy of 'spellsuggest', because the expression may change it. */
10538 sps_copy = vim_strsave(p_sps);
10539 if (sps_copy == NULL)
10540 return;
10542 /* Loop over the items in 'spellsuggest'. */
10543 for (p = sps_copy; *p != NUL; )
10545 copy_option_part(&p, buf, MAXPATHL, ",");
10547 if (STRNCMP(buf, "expr:", 5) == 0)
10549 #ifdef FEAT_EVAL
10550 /* Evaluate an expression. Skip this when called recursively,
10551 * when using spellsuggest() in the expression. */
10552 if (!expr_busy)
10554 expr_busy = TRUE;
10555 spell_suggest_expr(su, buf + 5);
10556 expr_busy = FALSE;
10558 #endif
10560 else if (STRNCMP(buf, "file:", 5) == 0)
10561 /* Use list of suggestions in a file. */
10562 spell_suggest_file(su, buf + 5);
10563 else
10565 /* Use internal method. */
10566 spell_suggest_intern(su, interactive);
10567 if (sps_flags & SPS_DOUBLE)
10568 do_combine = TRUE;
10572 vim_free(sps_copy);
10574 if (do_combine)
10575 /* Combine the two list of suggestions. This must be done last,
10576 * because sorting changes the order again. */
10577 score_combine(su);
10580 #ifdef FEAT_EVAL
10582 * Find suggestions by evaluating expression "expr".
10584 static void
10585 spell_suggest_expr(su, expr)
10586 suginfo_T *su;
10587 char_u *expr;
10589 list_T *list;
10590 listitem_T *li;
10591 int score;
10592 char_u *p;
10594 /* The work is split up in a few parts to avoid having to export
10595 * suginfo_T.
10596 * First evaluate the expression and get the resulting list. */
10597 list = eval_spell_expr(su->su_badword, expr);
10598 if (list != NULL)
10600 /* Loop over the items in the list. */
10601 for (li = list->lv_first; li != NULL; li = li->li_next)
10602 if (li->li_tv.v_type == VAR_LIST)
10604 /* Get the word and the score from the items. */
10605 score = get_spellword(li->li_tv.vval.v_list, &p);
10606 if (score >= 0 && score <= su->su_maxscore)
10607 add_suggestion(su, &su->su_ga, p, su->su_badlen,
10608 score, 0, TRUE, su->su_sallang, FALSE);
10610 list_unref(list);
10613 /* Remove bogus suggestions, sort and truncate at "maxcount". */
10614 check_suggestions(su, &su->su_ga);
10615 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10617 #endif
10620 * Find suggestions in file "fname". Used for "file:" in 'spellsuggest'.
10622 static void
10623 spell_suggest_file(su, fname)
10624 suginfo_T *su;
10625 char_u *fname;
10627 FILE *fd;
10628 char_u line[MAXWLEN * 2];
10629 char_u *p;
10630 int len;
10631 char_u cword[MAXWLEN];
10633 /* Open the file. */
10634 fd = mch_fopen((char *)fname, "r");
10635 if (fd == NULL)
10637 EMSG2(_(e_notopen), fname);
10638 return;
10641 /* Read it line by line. */
10642 while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int)
10644 line_breakcheck();
10646 p = vim_strchr(line, '/');
10647 if (p == NULL)
10648 continue; /* No Tab found, just skip the line. */
10649 *p++ = NUL;
10650 if (STRICMP(su->su_badword, line) == 0)
10652 /* Match! Isolate the good word, until CR or NL. */
10653 for (len = 0; p[len] >= ' '; ++len)
10655 p[len] = NUL;
10657 /* If the suggestion doesn't have specific case duplicate the case
10658 * of the bad word. */
10659 if (captype(p, NULL) == 0)
10661 make_case_word(p, cword, su->su_badflags);
10662 p = cword;
10665 add_suggestion(su, &su->su_ga, p, su->su_badlen,
10666 SCORE_FILE, 0, TRUE, su->su_sallang, FALSE);
10670 fclose(fd);
10672 /* Remove bogus suggestions, sort and truncate at "maxcount". */
10673 check_suggestions(su, &su->su_ga);
10674 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10678 * Find suggestions for the internal method indicated by "sps_flags".
10680 static void
10681 spell_suggest_intern(su, interactive)
10682 suginfo_T *su;
10683 int interactive;
10686 * Load the .sug file(s) that are available and not done yet.
10688 suggest_load_files();
10691 * 1. Try special cases, such as repeating a word: "the the" -> "the".
10693 * Set a maximum score to limit the combination of operations that is
10694 * tried.
10696 suggest_try_special(su);
10699 * 2. Try inserting/deleting/swapping/changing a letter, use REP entries
10700 * from the .aff file and inserting a space (split the word).
10702 suggest_try_change(su);
10704 /* For the resulting top-scorers compute the sound-a-like score. */
10705 if (sps_flags & SPS_DOUBLE)
10706 score_comp_sal(su);
10709 * 3. Try finding sound-a-like words.
10711 if ((sps_flags & SPS_FAST) == 0)
10713 if (sps_flags & SPS_BEST)
10714 /* Adjust the word score for the suggestions found so far for how
10715 * they sounds like. */
10716 rescore_suggestions(su);
10719 * While going throught the soundfold tree "su_maxscore" is the score
10720 * for the soundfold word, limits the changes that are being tried,
10721 * and "su_sfmaxscore" the rescored score, which is set by
10722 * cleanup_suggestions().
10723 * First find words with a small edit distance, because this is much
10724 * faster and often already finds the top-N suggestions. If we didn't
10725 * find many suggestions try again with a higher edit distance.
10726 * "sl_sounddone" is used to avoid doing the same word twice.
10728 suggest_try_soundalike_prep();
10729 su->su_maxscore = SCORE_SFMAX1;
10730 su->su_sfmaxscore = SCORE_MAXINIT * 3;
10731 suggest_try_soundalike(su);
10732 if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
10734 /* We didn't find enough matches, try again, allowing more
10735 * changes to the soundfold word. */
10736 su->su_maxscore = SCORE_SFMAX2;
10737 suggest_try_soundalike(su);
10738 if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
10740 /* Still didn't find enough matches, try again, allowing even
10741 * more changes to the soundfold word. */
10742 su->su_maxscore = SCORE_SFMAX3;
10743 suggest_try_soundalike(su);
10746 su->su_maxscore = su->su_sfmaxscore;
10747 suggest_try_soundalike_finish();
10750 /* When CTRL-C was hit while searching do show the results. Only clear
10751 * got_int when using a command, not for spellsuggest(). */
10752 ui_breakcheck();
10753 if (interactive && got_int)
10755 (void)vgetc();
10756 got_int = FALSE;
10759 if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0)
10761 if (sps_flags & SPS_BEST)
10762 /* Adjust the word score for how it sounds like. */
10763 rescore_suggestions(su);
10765 /* Remove bogus suggestions, sort and truncate at "maxcount". */
10766 check_suggestions(su, &su->su_ga);
10767 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10772 * Load the .sug files for languages that have one and weren't loaded yet.
10774 static void
10775 suggest_load_files()
10777 langp_T *lp;
10778 int lpi;
10779 slang_T *slang;
10780 char_u *dotp;
10781 FILE *fd;
10782 char_u buf[MAXWLEN];
10783 int i;
10784 time_t timestamp;
10785 int wcount;
10786 int wordnr;
10787 garray_T ga;
10788 int c;
10790 /* Do this for all languages that support sound folding. */
10791 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
10793 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
10794 slang = lp->lp_slang;
10795 if (slang->sl_sugtime != 0 && !slang->sl_sugloaded)
10797 /* Change ".spl" to ".sug" and open the file. When the file isn't
10798 * found silently skip it. Do set "sl_sugloaded" so that we
10799 * don't try again and again. */
10800 slang->sl_sugloaded = TRUE;
10802 dotp = vim_strrchr(slang->sl_fname, '.');
10803 if (dotp == NULL || fnamecmp(dotp, ".spl") != 0)
10804 continue;
10805 STRCPY(dotp, ".sug");
10806 fd = mch_fopen((char *)slang->sl_fname, "r");
10807 if (fd == NULL)
10808 goto nextone;
10811 * <SUGHEADER>: <fileID> <versionnr> <timestamp>
10813 for (i = 0; i < VIMSUGMAGICL; ++i)
10814 buf[i] = getc(fd); /* <fileID> */
10815 if (STRNCMP(buf, VIMSUGMAGIC, VIMSUGMAGICL) != 0)
10817 EMSG2(_("E778: This does not look like a .sug file: %s"),
10818 slang->sl_fname);
10819 goto nextone;
10821 c = getc(fd); /* <versionnr> */
10822 if (c < VIMSUGVERSION)
10824 EMSG2(_("E779: Old .sug file, needs to be updated: %s"),
10825 slang->sl_fname);
10826 goto nextone;
10828 else if (c > VIMSUGVERSION)
10830 EMSG2(_("E780: .sug file is for newer version of Vim: %s"),
10831 slang->sl_fname);
10832 goto nextone;
10835 /* Check the timestamp, it must be exactly the same as the one in
10836 * the .spl file. Otherwise the word numbers won't match. */
10837 timestamp = get8c(fd); /* <timestamp> */
10838 if (timestamp != slang->sl_sugtime)
10840 EMSG2(_("E781: .sug file doesn't match .spl file: %s"),
10841 slang->sl_fname);
10842 goto nextone;
10846 * <SUGWORDTREE>: <wordtree>
10847 * Read the trie with the soundfolded words.
10849 if (spell_read_tree(fd, &slang->sl_sbyts, &slang->sl_sidxs,
10850 FALSE, 0) != 0)
10852 someerror:
10853 EMSG2(_("E782: error while reading .sug file: %s"),
10854 slang->sl_fname);
10855 slang_clear_sug(slang);
10856 goto nextone;
10860 * <SUGTABLE>: <sugwcount> <sugline> ...
10862 * Read the table with word numbers. We use a file buffer for
10863 * this, because it's so much like a file with lines. Makes it
10864 * possible to swap the info and save on memory use.
10866 slang->sl_sugbuf = open_spellbuf();
10867 if (slang->sl_sugbuf == NULL)
10868 goto someerror;
10869 /* <sugwcount> */
10870 wcount = get4c(fd);
10871 if (wcount < 0)
10872 goto someerror;
10874 /* Read all the wordnr lists into the buffer, one NUL terminated
10875 * list per line. */
10876 ga_init2(&ga, 1, 100);
10877 for (wordnr = 0; wordnr < wcount; ++wordnr)
10879 ga.ga_len = 0;
10880 for (;;)
10882 c = getc(fd); /* <sugline> */
10883 if (c < 0 || ga_grow(&ga, 1) == FAIL)
10884 goto someerror;
10885 ((char_u *)ga.ga_data)[ga.ga_len++] = c;
10886 if (c == NUL)
10887 break;
10889 if (ml_append_buf(slang->sl_sugbuf, (linenr_T)wordnr,
10890 ga.ga_data, ga.ga_len, TRUE) == FAIL)
10891 goto someerror;
10893 ga_clear(&ga);
10896 * Need to put word counts in the word tries, so that we can find
10897 * a word by its number.
10899 tree_count_words(slang->sl_fbyts, slang->sl_fidxs);
10900 tree_count_words(slang->sl_sbyts, slang->sl_sidxs);
10902 nextone:
10903 if (fd != NULL)
10904 fclose(fd);
10905 STRCPY(dotp, ".spl");
10912 * Fill in the wordcount fields for a trie.
10913 * Returns the total number of words.
10915 static void
10916 tree_count_words(byts, idxs)
10917 char_u *byts;
10918 idx_T *idxs;
10920 int depth;
10921 idx_T arridx[MAXWLEN];
10922 int curi[MAXWLEN];
10923 int c;
10924 idx_T n;
10925 int wordcount[MAXWLEN];
10927 arridx[0] = 0;
10928 curi[0] = 1;
10929 wordcount[0] = 0;
10930 depth = 0;
10931 while (depth >= 0 && !got_int)
10933 if (curi[depth] > byts[arridx[depth]])
10935 /* Done all bytes at this node, go up one level. */
10936 idxs[arridx[depth]] = wordcount[depth];
10937 if (depth > 0)
10938 wordcount[depth - 1] += wordcount[depth];
10940 --depth;
10941 fast_breakcheck();
10943 else
10945 /* Do one more byte at this node. */
10946 n = arridx[depth] + curi[depth];
10947 ++curi[depth];
10949 c = byts[n];
10950 if (c == 0)
10952 /* End of word, count it. */
10953 ++wordcount[depth];
10955 /* Skip over any other NUL bytes (same word with different
10956 * flags). */
10957 while (byts[n + 1] == 0)
10959 ++n;
10960 ++curi[depth];
10963 else
10965 /* Normal char, go one level deeper to count the words. */
10966 ++depth;
10967 arridx[depth] = idxs[n];
10968 curi[depth] = 1;
10969 wordcount[depth] = 0;
10976 * Free the info put in "*su" by spell_find_suggest().
10978 static void
10979 spell_find_cleanup(su)
10980 suginfo_T *su;
10982 int i;
10984 /* Free the suggestions. */
10985 for (i = 0; i < su->su_ga.ga_len; ++i)
10986 vim_free(SUG(su->su_ga, i).st_word);
10987 ga_clear(&su->su_ga);
10988 for (i = 0; i < su->su_sga.ga_len; ++i)
10989 vim_free(SUG(su->su_sga, i).st_word);
10990 ga_clear(&su->su_sga);
10992 /* Free the banned words. */
10993 hash_clear_all(&su->su_banned, 0);
10997 * Make a copy of "word", with the first letter upper or lower cased, to
10998 * "wcopy[MAXWLEN]". "word" must not be empty.
10999 * The result is NUL terminated.
11001 static void
11002 onecap_copy(word, wcopy, upper)
11003 char_u *word;
11004 char_u *wcopy;
11005 int upper; /* TRUE: first letter made upper case */
11007 char_u *p;
11008 int c;
11009 int l;
11011 p = word;
11012 #ifdef FEAT_MBYTE
11013 if (has_mbyte)
11014 c = mb_cptr2char_adv(&p);
11015 else
11016 #endif
11017 c = *p++;
11018 if (upper)
11019 c = SPELL_TOUPPER(c);
11020 else
11021 c = SPELL_TOFOLD(c);
11022 #ifdef FEAT_MBYTE
11023 if (has_mbyte)
11024 l = mb_char2bytes(c, wcopy);
11025 else
11026 #endif
11028 l = 1;
11029 wcopy[0] = c;
11031 vim_strncpy(wcopy + l, p, MAXWLEN - l - 1);
11035 * Make a copy of "word" with all the letters upper cased into
11036 * "wcopy[MAXWLEN]". The result is NUL terminated.
11038 static void
11039 allcap_copy(word, wcopy)
11040 char_u *word;
11041 char_u *wcopy;
11043 char_u *s;
11044 char_u *d;
11045 int c;
11047 d = wcopy;
11048 for (s = word; *s != NUL; )
11050 #ifdef FEAT_MBYTE
11051 if (has_mbyte)
11052 c = mb_cptr2char_adv(&s);
11053 else
11054 #endif
11055 c = *s++;
11057 #ifdef FEAT_MBYTE
11058 /* We only change ß to SS when we are certain latin1 is used. It
11059 * would cause weird errors in other 8-bit encodings. */
11060 if (enc_latin1like && c == 0xdf)
11062 c = 'S';
11063 if (d - wcopy >= MAXWLEN - 1)
11064 break;
11065 *d++ = c;
11067 else
11068 #endif
11069 c = SPELL_TOUPPER(c);
11071 #ifdef FEAT_MBYTE
11072 if (has_mbyte)
11074 if (d - wcopy >= MAXWLEN - MB_MAXBYTES)
11075 break;
11076 d += mb_char2bytes(c, d);
11078 else
11079 #endif
11081 if (d - wcopy >= MAXWLEN - 1)
11082 break;
11083 *d++ = c;
11086 *d = NUL;
11090 * Try finding suggestions by recognizing specific situations.
11092 static void
11093 suggest_try_special(su)
11094 suginfo_T *su;
11096 char_u *p;
11097 size_t len;
11098 int c;
11099 char_u word[MAXWLEN];
11102 * Recognize a word that is repeated: "the the".
11104 p = skiptowhite(su->su_fbadword);
11105 len = p - su->su_fbadword;
11106 p = skipwhite(p);
11107 if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0)
11109 /* Include badflags: if the badword is onecap or allcap
11110 * use that for the goodword too: "The the" -> "The". */
11111 c = su->su_fbadword[len];
11112 su->su_fbadword[len] = NUL;
11113 make_case_word(su->su_fbadword, word, su->su_badflags);
11114 su->su_fbadword[len] = c;
11116 /* Give a soundalike score of 0, compute the score as if deleting one
11117 * character. */
11118 add_suggestion(su, &su->su_ga, word, su->su_badlen,
11119 RESCORE(SCORE_REP, 0), 0, TRUE, su->su_sallang, FALSE);
11124 * Try finding suggestions by adding/removing/swapping letters.
11126 static void
11127 suggest_try_change(su)
11128 suginfo_T *su;
11130 char_u fword[MAXWLEN]; /* copy of the bad word, case-folded */
11131 int n;
11132 char_u *p;
11133 int lpi;
11134 langp_T *lp;
11136 /* We make a copy of the case-folded bad word, so that we can modify it
11137 * to find matches (esp. REP items). Append some more text, changing
11138 * chars after the bad word may help. */
11139 STRCPY(fword, su->su_fbadword);
11140 n = (int)STRLEN(fword);
11141 p = su->su_badptr + su->su_badlen;
11142 (void)spell_casefold(p, (int)STRLEN(p), fword + n, MAXWLEN - n);
11144 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
11146 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
11148 /* If reloading a spell file fails it's still in the list but
11149 * everything has been cleared. */
11150 if (lp->lp_slang->sl_fbyts == NULL)
11151 continue;
11153 /* Try it for this language. Will add possible suggestions. */
11154 suggest_trie_walk(su, lp, fword, FALSE);
11158 /* Check the maximum score, if we go over it we won't try this change. */
11159 #define TRY_DEEPER(su, stack, depth, add) \
11160 (stack[depth].ts_score + (add) < su->su_maxscore)
11163 * Try finding suggestions by adding/removing/swapping letters.
11165 * This uses a state machine. At each node in the tree we try various
11166 * operations. When trying if an operation works "depth" is increased and the
11167 * stack[] is used to store info. This allows combinations, thus insert one
11168 * character, replace one and delete another. The number of changes is
11169 * limited by su->su_maxscore.
11171 * After implementing this I noticed an article by Kemal Oflazer that
11172 * describes something similar: "Error-tolerant Finite State Recognition with
11173 * Applications to Morphological Analysis and Spelling Correction" (1996).
11174 * The implementation in the article is simplified and requires a stack of
11175 * unknown depth. The implementation here only needs a stack depth equal to
11176 * the length of the word.
11178 * This is also used for the sound-folded word, "soundfold" is TRUE then.
11179 * The mechanism is the same, but we find a match with a sound-folded word
11180 * that comes from one or more original words. Each of these words may be
11181 * added, this is done by add_sound_suggest().
11182 * Don't use:
11183 * the prefix tree or the keep-case tree
11184 * "su->su_badlen"
11185 * anything to do with upper and lower case
11186 * anything to do with word or non-word characters ("spell_iswordp()")
11187 * banned words
11188 * word flags (rare, region, compounding)
11189 * word splitting for now
11190 * "similar_chars()"
11191 * use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep"
11193 static void
11194 suggest_trie_walk(su, lp, fword, soundfold)
11195 suginfo_T *su;
11196 langp_T *lp;
11197 char_u *fword;
11198 int soundfold;
11200 char_u tword[MAXWLEN]; /* good word collected so far */
11201 trystate_T stack[MAXWLEN];
11202 char_u preword[MAXWLEN * 3]; /* word found with proper case;
11203 * concatanation of prefix compound
11204 * words and split word. NUL terminated
11205 * when going deeper but not when coming
11206 * back. */
11207 char_u compflags[MAXWLEN]; /* compound flags, one for each word */
11208 trystate_T *sp;
11209 int newscore;
11210 int score;
11211 char_u *byts, *fbyts, *pbyts;
11212 idx_T *idxs, *fidxs, *pidxs;
11213 int depth;
11214 int c, c2, c3;
11215 int n = 0;
11216 int flags;
11217 garray_T *gap;
11218 idx_T arridx;
11219 int len;
11220 char_u *p;
11221 fromto_T *ftp;
11222 int fl = 0, tl;
11223 int repextra = 0; /* extra bytes in fword[] from REP item */
11224 slang_T *slang = lp->lp_slang;
11225 int fword_ends;
11226 int goodword_ends;
11227 #ifdef DEBUG_TRIEWALK
11228 /* Stores the name of the change made at each level. */
11229 char_u changename[MAXWLEN][80];
11230 #endif
11231 int breakcheckcount = 1000;
11232 int compound_ok;
11235 * Go through the whole case-fold tree, try changes at each node.
11236 * "tword[]" contains the word collected from nodes in the tree.
11237 * "fword[]" the word we are trying to match with (initially the bad
11238 * word).
11240 depth = 0;
11241 sp = &stack[0];
11242 vim_memset(sp, 0, sizeof(trystate_T));
11243 sp->ts_curi = 1;
11245 if (soundfold)
11247 /* Going through the soundfold tree. */
11248 byts = fbyts = slang->sl_sbyts;
11249 idxs = fidxs = slang->sl_sidxs;
11250 pbyts = NULL;
11251 pidxs = NULL;
11252 sp->ts_prefixdepth = PFD_NOPREFIX;
11253 sp->ts_state = STATE_START;
11255 else
11258 * When there are postponed prefixes we need to use these first. At
11259 * the end of the prefix we continue in the case-fold tree.
11261 fbyts = slang->sl_fbyts;
11262 fidxs = slang->sl_fidxs;
11263 pbyts = slang->sl_pbyts;
11264 pidxs = slang->sl_pidxs;
11265 if (pbyts != NULL)
11267 byts = pbyts;
11268 idxs = pidxs;
11269 sp->ts_prefixdepth = PFD_PREFIXTREE;
11270 sp->ts_state = STATE_NOPREFIX; /* try without prefix first */
11272 else
11274 byts = fbyts;
11275 idxs = fidxs;
11276 sp->ts_prefixdepth = PFD_NOPREFIX;
11277 sp->ts_state = STATE_START;
11282 * Loop to find all suggestions. At each round we either:
11283 * - For the current state try one operation, advance "ts_curi",
11284 * increase "depth".
11285 * - When a state is done go to the next, set "ts_state".
11286 * - When all states are tried decrease "depth".
11288 while (depth >= 0 && !got_int)
11290 sp = &stack[depth];
11291 switch (sp->ts_state)
11293 case STATE_START:
11294 case STATE_NOPREFIX:
11296 * Start of node: Deal with NUL bytes, which means
11297 * tword[] may end here.
11299 arridx = sp->ts_arridx; /* current node in the tree */
11300 len = byts[arridx]; /* bytes in this node */
11301 arridx += sp->ts_curi; /* index of current byte */
11303 if (sp->ts_prefixdepth == PFD_PREFIXTREE)
11305 /* Skip over the NUL bytes, we use them later. */
11306 for (n = 0; n < len && byts[arridx + n] == 0; ++n)
11308 sp->ts_curi += n;
11310 /* Always past NUL bytes now. */
11311 n = (int)sp->ts_state;
11312 sp->ts_state = STATE_ENDNUL;
11313 sp->ts_save_badflags = su->su_badflags;
11315 /* At end of a prefix or at start of prefixtree: check for
11316 * following word. */
11317 if (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)
11319 /* Set su->su_badflags to the caps type at this position.
11320 * Use the caps type until here for the prefix itself. */
11321 #ifdef FEAT_MBYTE
11322 if (has_mbyte)
11323 n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
11324 else
11325 #endif
11326 n = sp->ts_fidx;
11327 flags = badword_captype(su->su_badptr, su->su_badptr + n);
11328 su->su_badflags = badword_captype(su->su_badptr + n,
11329 su->su_badptr + su->su_badlen);
11330 #ifdef DEBUG_TRIEWALK
11331 sprintf(changename[depth], "prefix");
11332 #endif
11333 go_deeper(stack, depth, 0);
11334 ++depth;
11335 sp = &stack[depth];
11336 sp->ts_prefixdepth = depth - 1;
11337 byts = fbyts;
11338 idxs = fidxs;
11339 sp->ts_arridx = 0;
11341 /* Move the prefix to preword[] with the right case
11342 * and make find_keepcap_word() works. */
11343 tword[sp->ts_twordlen] = NUL;
11344 make_case_word(tword + sp->ts_splitoff,
11345 preword + sp->ts_prewordlen, flags);
11346 sp->ts_prewordlen = (char_u)STRLEN(preword);
11347 sp->ts_splitoff = sp->ts_twordlen;
11349 break;
11352 if (sp->ts_curi > len || byts[arridx] != 0)
11354 /* Past bytes in node and/or past NUL bytes. */
11355 sp->ts_state = STATE_ENDNUL;
11356 sp->ts_save_badflags = su->su_badflags;
11357 break;
11361 * End of word in tree.
11363 ++sp->ts_curi; /* eat one NUL byte */
11365 flags = (int)idxs[arridx];
11367 /* Skip words with the NOSUGGEST flag. */
11368 if (flags & WF_NOSUGGEST)
11369 break;
11371 fword_ends = (fword[sp->ts_fidx] == NUL
11372 || (soundfold
11373 ? vim_iswhite(fword[sp->ts_fidx])
11374 : !spell_iswordp(fword + sp->ts_fidx, curbuf)));
11375 tword[sp->ts_twordlen] = NUL;
11377 if (sp->ts_prefixdepth <= PFD_NOTSPECIAL
11378 && (sp->ts_flags & TSF_PREFIXOK) == 0)
11380 /* There was a prefix before the word. Check that the prefix
11381 * can be used with this word. */
11382 /* Count the length of the NULs in the prefix. If there are
11383 * none this must be the first try without a prefix. */
11384 n = stack[sp->ts_prefixdepth].ts_arridx;
11385 len = pbyts[n++];
11386 for (c = 0; c < len && pbyts[n + c] == 0; ++c)
11388 if (c > 0)
11390 c = valid_word_prefix(c, n, flags,
11391 tword + sp->ts_splitoff, slang, FALSE);
11392 if (c == 0)
11393 break;
11395 /* Use the WF_RARE flag for a rare prefix. */
11396 if (c & WF_RAREPFX)
11397 flags |= WF_RARE;
11399 /* Tricky: when checking for both prefix and compounding
11400 * we run into the prefix flag first.
11401 * Remember that it's OK, so that we accept the prefix
11402 * when arriving at a compound flag. */
11403 sp->ts_flags |= TSF_PREFIXOK;
11407 /* Check NEEDCOMPOUND: can't use word without compounding. Do try
11408 * appending another compound word below. */
11409 if (sp->ts_complen == sp->ts_compsplit && fword_ends
11410 && (flags & WF_NEEDCOMP))
11411 goodword_ends = FALSE;
11412 else
11413 goodword_ends = TRUE;
11415 p = NULL;
11416 compound_ok = TRUE;
11417 if (sp->ts_complen > sp->ts_compsplit)
11419 if (slang->sl_nobreak)
11421 /* There was a word before this word. When there was no
11422 * change in this word (it was correct) add the first word
11423 * as a suggestion. If this word was corrected too, we
11424 * need to check if a correct word follows. */
11425 if (sp->ts_fidx - sp->ts_splitfidx
11426 == sp->ts_twordlen - sp->ts_splitoff
11427 && STRNCMP(fword + sp->ts_splitfidx,
11428 tword + sp->ts_splitoff,
11429 sp->ts_fidx - sp->ts_splitfidx) == 0)
11431 preword[sp->ts_prewordlen] = NUL;
11432 newscore = score_wordcount_adj(slang, sp->ts_score,
11433 preword + sp->ts_prewordlen,
11434 sp->ts_prewordlen > 0);
11435 /* Add the suggestion if the score isn't too bad. */
11436 if (newscore <= su->su_maxscore)
11437 add_suggestion(su, &su->su_ga, preword,
11438 sp->ts_splitfidx - repextra,
11439 newscore, 0, FALSE,
11440 lp->lp_sallang, FALSE);
11441 break;
11444 else
11446 /* There was a compound word before this word. If this
11447 * word does not support compounding then give up
11448 * (splitting is tried for the word without compound
11449 * flag). */
11450 if (((unsigned)flags >> 24) == 0
11451 || sp->ts_twordlen - sp->ts_splitoff
11452 < slang->sl_compminlen)
11453 break;
11454 #ifdef FEAT_MBYTE
11455 /* For multi-byte chars check character length against
11456 * COMPOUNDMIN. */
11457 if (has_mbyte
11458 && slang->sl_compminlen > 0
11459 && mb_charlen(tword + sp->ts_splitoff)
11460 < slang->sl_compminlen)
11461 break;
11462 #endif
11464 compflags[sp->ts_complen] = ((unsigned)flags >> 24);
11465 compflags[sp->ts_complen + 1] = NUL;
11466 vim_strncpy(preword + sp->ts_prewordlen,
11467 tword + sp->ts_splitoff,
11468 sp->ts_twordlen - sp->ts_splitoff);
11469 p = preword;
11470 while (*skiptowhite(p) != NUL)
11471 p = skipwhite(skiptowhite(p));
11472 if (fword_ends && !can_compound(slang, p,
11473 compflags + sp->ts_compsplit))
11474 /* Compound is not allowed. But it may still be
11475 * possible if we add another (short) word. */
11476 compound_ok = FALSE;
11478 /* Get pointer to last char of previous word. */
11479 p = preword + sp->ts_prewordlen;
11480 mb_ptr_back(preword, p);
11485 * Form the word with proper case in preword.
11486 * If there is a word from a previous split, append.
11487 * For the soundfold tree don't change the case, simply append.
11489 if (soundfold)
11490 STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
11491 else if (flags & WF_KEEPCAP)
11492 /* Must find the word in the keep-case tree. */
11493 find_keepcap_word(slang, tword + sp->ts_splitoff,
11494 preword + sp->ts_prewordlen);
11495 else
11497 /* Include badflags: If the badword is onecap or allcap
11498 * use that for the goodword too. But if the badword is
11499 * allcap and it's only one char long use onecap. */
11500 c = su->su_badflags;
11501 if ((c & WF_ALLCAP)
11502 #ifdef FEAT_MBYTE
11503 && su->su_badlen == (*mb_ptr2len)(su->su_badptr)
11504 #else
11505 && su->su_badlen == 1
11506 #endif
11508 c = WF_ONECAP;
11509 c |= flags;
11511 /* When appending a compound word after a word character don't
11512 * use Onecap. */
11513 if (p != NULL && spell_iswordp_nmw(p))
11514 c &= ~WF_ONECAP;
11515 make_case_word(tword + sp->ts_splitoff,
11516 preword + sp->ts_prewordlen, c);
11519 if (!soundfold)
11521 /* Don't use a banned word. It may appear again as a good
11522 * word, thus remember it. */
11523 if (flags & WF_BANNED)
11525 add_banned(su, preword + sp->ts_prewordlen);
11526 break;
11528 if ((sp->ts_complen == sp->ts_compsplit
11529 && WAS_BANNED(su, preword + sp->ts_prewordlen))
11530 || WAS_BANNED(su, preword))
11532 if (slang->sl_compprog == NULL)
11533 break;
11534 /* the word so far was banned but we may try compounding */
11535 goodword_ends = FALSE;
11539 newscore = 0;
11540 if (!soundfold) /* soundfold words don't have flags */
11542 if ((flags & WF_REGION)
11543 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
11544 newscore += SCORE_REGION;
11545 if (flags & WF_RARE)
11546 newscore += SCORE_RARE;
11548 if (!spell_valid_case(su->su_badflags,
11549 captype(preword + sp->ts_prewordlen, NULL)))
11550 newscore += SCORE_ICASE;
11553 /* TODO: how about splitting in the soundfold tree? */
11554 if (fword_ends
11555 && goodword_ends
11556 && sp->ts_fidx >= sp->ts_fidxtry
11557 && compound_ok)
11559 /* The badword also ends: add suggestions. */
11560 #ifdef DEBUG_TRIEWALK
11561 if (soundfold && STRCMP(preword, "smwrd") == 0)
11563 int j;
11565 /* print the stack of changes that brought us here */
11566 smsg("------ %s -------", fword);
11567 for (j = 0; j < depth; ++j)
11568 smsg("%s", changename[j]);
11570 #endif
11571 if (soundfold)
11573 /* For soundfolded words we need to find the original
11574 * words, the edit distance and then add them. */
11575 add_sound_suggest(su, preword, sp->ts_score, lp);
11577 else
11579 /* Give a penalty when changing non-word char to word
11580 * char, e.g., "thes," -> "these". */
11581 p = fword + sp->ts_fidx;
11582 mb_ptr_back(fword, p);
11583 if (!spell_iswordp(p, curbuf))
11585 p = preword + STRLEN(preword);
11586 mb_ptr_back(preword, p);
11587 if (spell_iswordp(p, curbuf))
11588 newscore += SCORE_NONWORD;
11591 /* Give a bonus to words seen before. */
11592 score = score_wordcount_adj(slang,
11593 sp->ts_score + newscore,
11594 preword + sp->ts_prewordlen,
11595 sp->ts_prewordlen > 0);
11597 /* Add the suggestion if the score isn't too bad. */
11598 if (score <= su->su_maxscore)
11600 add_suggestion(su, &su->su_ga, preword,
11601 sp->ts_fidx - repextra,
11602 score, 0, FALSE, lp->lp_sallang, FALSE);
11604 if (su->su_badflags & WF_MIXCAP)
11606 /* We really don't know if the word should be
11607 * upper or lower case, add both. */
11608 c = captype(preword, NULL);
11609 if (c == 0 || c == WF_ALLCAP)
11611 make_case_word(tword + sp->ts_splitoff,
11612 preword + sp->ts_prewordlen,
11613 c == 0 ? WF_ALLCAP : 0);
11615 add_suggestion(su, &su->su_ga, preword,
11616 sp->ts_fidx - repextra,
11617 score + SCORE_ICASE, 0, FALSE,
11618 lp->lp_sallang, FALSE);
11626 * Try word split and/or compounding.
11628 if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
11629 #ifdef FEAT_MBYTE
11630 /* Don't split halfway a character. */
11631 && (!has_mbyte || sp->ts_tcharlen == 0)
11632 #endif
11635 int try_compound;
11636 int try_split;
11638 /* If past the end of the bad word don't try a split.
11639 * Otherwise try changing the next word. E.g., find
11640 * suggestions for "the the" where the second "the" is
11641 * different. It's done like a split.
11642 * TODO: word split for soundfold words */
11643 try_split = (sp->ts_fidx - repextra < su->su_badlen)
11644 && !soundfold;
11646 /* Get here in several situations:
11647 * 1. The word in the tree ends:
11648 * If the word allows compounding try that. Otherwise try
11649 * a split by inserting a space. For both check that a
11650 * valid words starts at fword[sp->ts_fidx].
11651 * For NOBREAK do like compounding to be able to check if
11652 * the next word is valid.
11653 * 2. The badword does end, but it was due to a change (e.g.,
11654 * a swap). No need to split, but do check that the
11655 * following word is valid.
11656 * 3. The badword and the word in the tree end. It may still
11657 * be possible to compound another (short) word.
11659 try_compound = FALSE;
11660 if (!soundfold
11661 && slang->sl_compprog != NULL
11662 && ((unsigned)flags >> 24) != 0
11663 && sp->ts_twordlen - sp->ts_splitoff
11664 >= slang->sl_compminlen
11665 #ifdef FEAT_MBYTE
11666 && (!has_mbyte
11667 || slang->sl_compminlen == 0
11668 || mb_charlen(tword + sp->ts_splitoff)
11669 >= slang->sl_compminlen)
11670 #endif
11671 && (slang->sl_compsylmax < MAXWLEN
11672 || sp->ts_complen + 1 - sp->ts_compsplit
11673 < slang->sl_compmax)
11674 && (byte_in_str(sp->ts_complen == sp->ts_compsplit
11675 ? slang->sl_compstartflags
11676 : slang->sl_compallflags,
11677 ((unsigned)flags >> 24))))
11679 try_compound = TRUE;
11680 compflags[sp->ts_complen] = ((unsigned)flags >> 24);
11681 compflags[sp->ts_complen + 1] = NUL;
11684 /* For NOBREAK we never try splitting, it won't make any word
11685 * valid. */
11686 if (slang->sl_nobreak)
11687 try_compound = TRUE;
11689 /* If we could add a compound word, and it's also possible to
11690 * split at this point, do the split first and set
11691 * TSF_DIDSPLIT to avoid doing it again. */
11692 else if (!fword_ends
11693 && try_compound
11694 && (sp->ts_flags & TSF_DIDSPLIT) == 0)
11696 try_compound = FALSE;
11697 sp->ts_flags |= TSF_DIDSPLIT;
11698 --sp->ts_curi; /* do the same NUL again */
11699 compflags[sp->ts_complen] = NUL;
11701 else
11702 sp->ts_flags &= ~TSF_DIDSPLIT;
11704 if (try_split || try_compound)
11706 if (!try_compound && (!fword_ends || !goodword_ends))
11708 /* If we're going to split need to check that the
11709 * words so far are valid for compounding. If there
11710 * is only one word it must not have the NEEDCOMPOUND
11711 * flag. */
11712 if (sp->ts_complen == sp->ts_compsplit
11713 && (flags & WF_NEEDCOMP))
11714 break;
11715 p = preword;
11716 while (*skiptowhite(p) != NUL)
11717 p = skipwhite(skiptowhite(p));
11718 if (sp->ts_complen > sp->ts_compsplit
11719 && !can_compound(slang, p,
11720 compflags + sp->ts_compsplit))
11721 break;
11723 if (slang->sl_nosplitsugs)
11724 newscore += SCORE_SPLIT_NO;
11725 else
11726 newscore += SCORE_SPLIT;
11728 /* Give a bonus to words seen before. */
11729 newscore = score_wordcount_adj(slang, newscore,
11730 preword + sp->ts_prewordlen, TRUE);
11733 if (TRY_DEEPER(su, stack, depth, newscore))
11735 go_deeper(stack, depth, newscore);
11736 #ifdef DEBUG_TRIEWALK
11737 if (!try_compound && !fword_ends)
11738 sprintf(changename[depth], "%.*s-%s: split",
11739 sp->ts_twordlen, tword, fword + sp->ts_fidx);
11740 else
11741 sprintf(changename[depth], "%.*s-%s: compound",
11742 sp->ts_twordlen, tword, fword + sp->ts_fidx);
11743 #endif
11744 /* Save things to be restored at STATE_SPLITUNDO. */
11745 sp->ts_save_badflags = su->su_badflags;
11746 sp->ts_state = STATE_SPLITUNDO;
11748 ++depth;
11749 sp = &stack[depth];
11751 /* Append a space to preword when splitting. */
11752 if (!try_compound && !fword_ends)
11753 STRCAT(preword, " ");
11754 sp->ts_prewordlen = (char_u)STRLEN(preword);
11755 sp->ts_splitoff = sp->ts_twordlen;
11756 sp->ts_splitfidx = sp->ts_fidx;
11758 /* If the badword has a non-word character at this
11759 * position skip it. That means replacing the
11760 * non-word character with a space. Always skip a
11761 * character when the word ends. But only when the
11762 * good word can end. */
11763 if (((!try_compound && !spell_iswordp_nmw(fword
11764 + sp->ts_fidx))
11765 || fword_ends)
11766 && fword[sp->ts_fidx] != NUL
11767 && goodword_ends)
11769 int l;
11771 #ifdef FEAT_MBYTE
11772 if (has_mbyte)
11773 l = MB_BYTE2LEN(fword[sp->ts_fidx]);
11774 else
11775 #endif
11776 l = 1;
11777 if (fword_ends)
11779 /* Copy the skipped character to preword. */
11780 mch_memmove(preword + sp->ts_prewordlen,
11781 fword + sp->ts_fidx, l);
11782 sp->ts_prewordlen += l;
11783 preword[sp->ts_prewordlen] = NUL;
11785 else
11786 sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
11787 sp->ts_fidx += l;
11790 /* When compounding include compound flag in
11791 * compflags[] (already set above). When splitting we
11792 * may start compounding over again. */
11793 if (try_compound)
11794 ++sp->ts_complen;
11795 else
11796 sp->ts_compsplit = sp->ts_complen;
11797 sp->ts_prefixdepth = PFD_NOPREFIX;
11799 /* set su->su_badflags to the caps type at this
11800 * position */
11801 #ifdef FEAT_MBYTE
11802 if (has_mbyte)
11803 n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
11804 else
11805 #endif
11806 n = sp->ts_fidx;
11807 su->su_badflags = badword_captype(su->su_badptr + n,
11808 su->su_badptr + su->su_badlen);
11810 /* Restart at top of the tree. */
11811 sp->ts_arridx = 0;
11813 /* If there are postponed prefixes, try these too. */
11814 if (pbyts != NULL)
11816 byts = pbyts;
11817 idxs = pidxs;
11818 sp->ts_prefixdepth = PFD_PREFIXTREE;
11819 sp->ts_state = STATE_NOPREFIX;
11824 break;
11826 case STATE_SPLITUNDO:
11827 /* Undo the changes done for word split or compound word. */
11828 su->su_badflags = sp->ts_save_badflags;
11830 /* Continue looking for NUL bytes. */
11831 sp->ts_state = STATE_START;
11833 /* In case we went into the prefix tree. */
11834 byts = fbyts;
11835 idxs = fidxs;
11836 break;
11838 case STATE_ENDNUL:
11839 /* Past the NUL bytes in the node. */
11840 su->su_badflags = sp->ts_save_badflags;
11841 if (fword[sp->ts_fidx] == NUL
11842 #ifdef FEAT_MBYTE
11843 && sp->ts_tcharlen == 0
11844 #endif
11847 /* The badword ends, can't use STATE_PLAIN. */
11848 sp->ts_state = STATE_DEL;
11849 break;
11851 sp->ts_state = STATE_PLAIN;
11852 /*FALLTHROUGH*/
11854 case STATE_PLAIN:
11856 * Go over all possible bytes at this node, add each to tword[]
11857 * and use child node. "ts_curi" is the index.
11859 arridx = sp->ts_arridx;
11860 if (sp->ts_curi > byts[arridx])
11862 /* Done all bytes at this node, do next state. When still at
11863 * already changed bytes skip the other tricks. */
11864 if (sp->ts_fidx >= sp->ts_fidxtry)
11865 sp->ts_state = STATE_DEL;
11866 else
11867 sp->ts_state = STATE_FINAL;
11869 else
11871 arridx += sp->ts_curi++;
11872 c = byts[arridx];
11874 /* Normal byte, go one level deeper. If it's not equal to the
11875 * byte in the bad word adjust the score. But don't even try
11876 * when the byte was already changed. And don't try when we
11877 * just deleted this byte, accepting it is always cheaper then
11878 * delete + substitute. */
11879 if (c == fword[sp->ts_fidx]
11880 #ifdef FEAT_MBYTE
11881 || (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE)
11882 #endif
11884 newscore = 0;
11885 else
11886 newscore = SCORE_SUBST;
11887 if ((newscore == 0
11888 || (sp->ts_fidx >= sp->ts_fidxtry
11889 && ((sp->ts_flags & TSF_DIDDEL) == 0
11890 || c != fword[sp->ts_delidx])))
11891 && TRY_DEEPER(su, stack, depth, newscore))
11893 go_deeper(stack, depth, newscore);
11894 #ifdef DEBUG_TRIEWALK
11895 if (newscore > 0)
11896 sprintf(changename[depth], "%.*s-%s: subst %c to %c",
11897 sp->ts_twordlen, tword, fword + sp->ts_fidx,
11898 fword[sp->ts_fidx], c);
11899 else
11900 sprintf(changename[depth], "%.*s-%s: accept %c",
11901 sp->ts_twordlen, tword, fword + sp->ts_fidx,
11902 fword[sp->ts_fidx]);
11903 #endif
11904 ++depth;
11905 sp = &stack[depth];
11906 ++sp->ts_fidx;
11907 tword[sp->ts_twordlen++] = c;
11908 sp->ts_arridx = idxs[arridx];
11909 #ifdef FEAT_MBYTE
11910 if (newscore == SCORE_SUBST)
11911 sp->ts_isdiff = DIFF_YES;
11912 if (has_mbyte)
11914 /* Multi-byte characters are a bit complicated to
11915 * handle: They differ when any of the bytes differ
11916 * and then their length may also differ. */
11917 if (sp->ts_tcharlen == 0)
11919 /* First byte. */
11920 sp->ts_tcharidx = 0;
11921 sp->ts_tcharlen = MB_BYTE2LEN(c);
11922 sp->ts_fcharstart = sp->ts_fidx - 1;
11923 sp->ts_isdiff = (newscore != 0)
11924 ? DIFF_YES : DIFF_NONE;
11926 else if (sp->ts_isdiff == DIFF_INSERT)
11927 /* When inserting trail bytes don't advance in the
11928 * bad word. */
11929 --sp->ts_fidx;
11930 if (++sp->ts_tcharidx == sp->ts_tcharlen)
11932 /* Last byte of character. */
11933 if (sp->ts_isdiff == DIFF_YES)
11935 /* Correct ts_fidx for the byte length of the
11936 * character (we didn't check that before). */
11937 sp->ts_fidx = sp->ts_fcharstart
11938 + MB_BYTE2LEN(
11939 fword[sp->ts_fcharstart]);
11941 /* For changing a composing character adjust
11942 * the score from SCORE_SUBST to
11943 * SCORE_SUBCOMP. */
11944 if (enc_utf8
11945 && utf_iscomposing(
11946 mb_ptr2char(tword
11947 + sp->ts_twordlen
11948 - sp->ts_tcharlen))
11949 && utf_iscomposing(
11950 mb_ptr2char(fword
11951 + sp->ts_fcharstart)))
11952 sp->ts_score -=
11953 SCORE_SUBST - SCORE_SUBCOMP;
11955 /* For a similar character adjust score from
11956 * SCORE_SUBST to SCORE_SIMILAR. */
11957 else if (!soundfold
11958 && slang->sl_has_map
11959 && similar_chars(slang,
11960 mb_ptr2char(tword
11961 + sp->ts_twordlen
11962 - sp->ts_tcharlen),
11963 mb_ptr2char(fword
11964 + sp->ts_fcharstart)))
11965 sp->ts_score -=
11966 SCORE_SUBST - SCORE_SIMILAR;
11968 else if (sp->ts_isdiff == DIFF_INSERT
11969 && sp->ts_twordlen > sp->ts_tcharlen)
11971 p = tword + sp->ts_twordlen - sp->ts_tcharlen;
11972 c = mb_ptr2char(p);
11973 if (enc_utf8 && utf_iscomposing(c))
11975 /* Inserting a composing char doesn't
11976 * count that much. */
11977 sp->ts_score -= SCORE_INS - SCORE_INSCOMP;
11979 else
11981 /* If the previous character was the same,
11982 * thus doubling a character, give a bonus
11983 * to the score. Also for the soundfold
11984 * tree (might seem illogical but does
11985 * give better scores). */
11986 mb_ptr_back(tword, p);
11987 if (c == mb_ptr2char(p))
11988 sp->ts_score -= SCORE_INS
11989 - SCORE_INSDUP;
11993 /* Starting a new char, reset the length. */
11994 sp->ts_tcharlen = 0;
11997 else
11998 #endif
12000 /* If we found a similar char adjust the score.
12001 * We do this after calling go_deeper() because
12002 * it's slow. */
12003 if (newscore != 0
12004 && !soundfold
12005 && slang->sl_has_map
12006 && similar_chars(slang,
12007 c, fword[sp->ts_fidx - 1]))
12008 sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
12012 break;
12014 case STATE_DEL:
12015 #ifdef FEAT_MBYTE
12016 /* When past the first byte of a multi-byte char don't try
12017 * delete/insert/swap a character. */
12018 if (has_mbyte && sp->ts_tcharlen > 0)
12020 sp->ts_state = STATE_FINAL;
12021 break;
12023 #endif
12025 * Try skipping one character in the bad word (delete it).
12027 sp->ts_state = STATE_INS_PREP;
12028 sp->ts_curi = 1;
12029 if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')
12030 /* Deleting a vowel at the start of a word counts less, see
12031 * soundalike_score(). */
12032 newscore = 2 * SCORE_DEL / 3;
12033 else
12034 newscore = SCORE_DEL;
12035 if (fword[sp->ts_fidx] != NUL
12036 && TRY_DEEPER(su, stack, depth, newscore))
12038 go_deeper(stack, depth, newscore);
12039 #ifdef DEBUG_TRIEWALK
12040 sprintf(changename[depth], "%.*s-%s: delete %c",
12041 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12042 fword[sp->ts_fidx]);
12043 #endif
12044 ++depth;
12046 /* Remember what character we deleted, so that we can avoid
12047 * inserting it again. */
12048 stack[depth].ts_flags |= TSF_DIDDEL;
12049 stack[depth].ts_delidx = sp->ts_fidx;
12051 /* Advance over the character in fword[]. Give a bonus to the
12052 * score if the same character is following "nn" -> "n". It's
12053 * a bit illogical for soundfold tree but it does give better
12054 * results. */
12055 #ifdef FEAT_MBYTE
12056 if (has_mbyte)
12058 c = mb_ptr2char(fword + sp->ts_fidx);
12059 stack[depth].ts_fidx += MB_BYTE2LEN(fword[sp->ts_fidx]);
12060 if (enc_utf8 && utf_iscomposing(c))
12061 stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
12062 else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))
12063 stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
12065 else
12066 #endif
12068 ++stack[depth].ts_fidx;
12069 if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])
12070 stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
12072 break;
12074 /*FALLTHROUGH*/
12076 case STATE_INS_PREP:
12077 if (sp->ts_flags & TSF_DIDDEL)
12079 /* If we just deleted a byte then inserting won't make sense,
12080 * a substitute is always cheaper. */
12081 sp->ts_state = STATE_SWAP;
12082 break;
12085 /* skip over NUL bytes */
12086 n = sp->ts_arridx;
12087 for (;;)
12089 if (sp->ts_curi > byts[n])
12091 /* Only NUL bytes at this node, go to next state. */
12092 sp->ts_state = STATE_SWAP;
12093 break;
12095 if (byts[n + sp->ts_curi] != NUL)
12097 /* Found a byte to insert. */
12098 sp->ts_state = STATE_INS;
12099 break;
12101 ++sp->ts_curi;
12103 break;
12105 /*FALLTHROUGH*/
12107 case STATE_INS:
12108 /* Insert one byte. Repeat this for each possible byte at this
12109 * node. */
12110 n = sp->ts_arridx;
12111 if (sp->ts_curi > byts[n])
12113 /* Done all bytes at this node, go to next state. */
12114 sp->ts_state = STATE_SWAP;
12115 break;
12118 /* Do one more byte at this node, but:
12119 * - Skip NUL bytes.
12120 * - Skip the byte if it's equal to the byte in the word,
12121 * accepting that byte is always better.
12123 n += sp->ts_curi++;
12124 c = byts[n];
12125 if (soundfold && sp->ts_twordlen == 0 && c == '*')
12126 /* Inserting a vowel at the start of a word counts less,
12127 * see soundalike_score(). */
12128 newscore = 2 * SCORE_INS / 3;
12129 else
12130 newscore = SCORE_INS;
12131 if (c != fword[sp->ts_fidx]
12132 && TRY_DEEPER(su, stack, depth, newscore))
12134 go_deeper(stack, depth, newscore);
12135 #ifdef DEBUG_TRIEWALK
12136 sprintf(changename[depth], "%.*s-%s: insert %c",
12137 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12139 #endif
12140 ++depth;
12141 sp = &stack[depth];
12142 tword[sp->ts_twordlen++] = c;
12143 sp->ts_arridx = idxs[n];
12144 #ifdef FEAT_MBYTE
12145 if (has_mbyte)
12147 fl = MB_BYTE2LEN(c);
12148 if (fl > 1)
12150 /* There are following bytes for the same character.
12151 * We must find all bytes before trying
12152 * delete/insert/swap/etc. */
12153 sp->ts_tcharlen = fl;
12154 sp->ts_tcharidx = 1;
12155 sp->ts_isdiff = DIFF_INSERT;
12158 else
12159 fl = 1;
12160 if (fl == 1)
12161 #endif
12163 /* If the previous character was the same, thus doubling a
12164 * character, give a bonus to the score. Also for
12165 * soundfold words (illogical but does give a better
12166 * score). */
12167 if (sp->ts_twordlen >= 2
12168 && tword[sp->ts_twordlen - 2] == c)
12169 sp->ts_score -= SCORE_INS - SCORE_INSDUP;
12172 break;
12174 case STATE_SWAP:
12176 * Swap two bytes in the bad word: "12" -> "21".
12177 * We change "fword" here, it's changed back afterwards at
12178 * STATE_UNSWAP.
12180 p = fword + sp->ts_fidx;
12181 c = *p;
12182 if (c == NUL)
12184 /* End of word, can't swap or replace. */
12185 sp->ts_state = STATE_FINAL;
12186 break;
12189 /* Don't swap if the first character is not a word character.
12190 * SWAP3 etc. also don't make sense then. */
12191 if (!soundfold && !spell_iswordp(p, curbuf))
12193 sp->ts_state = STATE_REP_INI;
12194 break;
12197 #ifdef FEAT_MBYTE
12198 if (has_mbyte)
12200 n = mb_cptr2len(p);
12201 c = mb_ptr2char(p);
12202 if (p[n] == NUL)
12203 c2 = NUL;
12204 else if (!soundfold && !spell_iswordp(p + n, curbuf))
12205 c2 = c; /* don't swap non-word char */
12206 else
12207 c2 = mb_ptr2char(p + n);
12209 else
12210 #endif
12212 if (p[1] == NUL)
12213 c2 = NUL;
12214 else if (!soundfold && !spell_iswordp(p + 1, curbuf))
12215 c2 = c; /* don't swap non-word char */
12216 else
12217 c2 = p[1];
12220 /* When the second character is NUL we can't swap. */
12221 if (c2 == NUL)
12223 sp->ts_state = STATE_REP_INI;
12224 break;
12227 /* When characters are identical, swap won't do anything.
12228 * Also get here if the second char is not a word character. */
12229 if (c == c2)
12231 sp->ts_state = STATE_SWAP3;
12232 break;
12234 if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
12236 go_deeper(stack, depth, SCORE_SWAP);
12237 #ifdef DEBUG_TRIEWALK
12238 sprintf(changename[depth], "%.*s-%s: swap %c and %c",
12239 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12240 c, c2);
12241 #endif
12242 sp->ts_state = STATE_UNSWAP;
12243 ++depth;
12244 #ifdef FEAT_MBYTE
12245 if (has_mbyte)
12247 fl = mb_char2len(c2);
12248 mch_memmove(p, p + n, fl);
12249 mb_char2bytes(c, p + fl);
12250 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
12252 else
12253 #endif
12255 p[0] = c2;
12256 p[1] = c;
12257 stack[depth].ts_fidxtry = sp->ts_fidx + 2;
12260 else
12261 /* If this swap doesn't work then SWAP3 won't either. */
12262 sp->ts_state = STATE_REP_INI;
12263 break;
12265 case STATE_UNSWAP:
12266 /* Undo the STATE_SWAP swap: "21" -> "12". */
12267 p = fword + sp->ts_fidx;
12268 #ifdef FEAT_MBYTE
12269 if (has_mbyte)
12271 n = MB_BYTE2LEN(*p);
12272 c = mb_ptr2char(p + n);
12273 mch_memmove(p + MB_BYTE2LEN(p[n]), p, n);
12274 mb_char2bytes(c, p);
12276 else
12277 #endif
12279 c = *p;
12280 *p = p[1];
12281 p[1] = c;
12283 /*FALLTHROUGH*/
12285 case STATE_SWAP3:
12286 /* Swap two bytes, skipping one: "123" -> "321". We change
12287 * "fword" here, it's changed back afterwards at STATE_UNSWAP3. */
12288 p = fword + sp->ts_fidx;
12289 #ifdef FEAT_MBYTE
12290 if (has_mbyte)
12292 n = mb_cptr2len(p);
12293 c = mb_ptr2char(p);
12294 fl = mb_cptr2len(p + n);
12295 c2 = mb_ptr2char(p + n);
12296 if (!soundfold && !spell_iswordp(p + n + fl, curbuf))
12297 c3 = c; /* don't swap non-word char */
12298 else
12299 c3 = mb_ptr2char(p + n + fl);
12301 else
12302 #endif
12304 c = *p;
12305 c2 = p[1];
12306 if (!soundfold && !spell_iswordp(p + 2, curbuf))
12307 c3 = c; /* don't swap non-word char */
12308 else
12309 c3 = p[2];
12312 /* When characters are identical: "121" then SWAP3 result is
12313 * identical, ROT3L result is same as SWAP: "211", ROT3L result is
12314 * same as SWAP on next char: "112". Thus skip all swapping.
12315 * Also skip when c3 is NUL.
12316 * Also get here when the third character is not a word character.
12317 * Second character may any char: "a.b" -> "b.a" */
12318 if (c == c3 || c3 == NUL)
12320 sp->ts_state = STATE_REP_INI;
12321 break;
12323 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12325 go_deeper(stack, depth, SCORE_SWAP3);
12326 #ifdef DEBUG_TRIEWALK
12327 sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",
12328 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12329 c, c3);
12330 #endif
12331 sp->ts_state = STATE_UNSWAP3;
12332 ++depth;
12333 #ifdef FEAT_MBYTE
12334 if (has_mbyte)
12336 tl = mb_char2len(c3);
12337 mch_memmove(p, p + n + fl, tl);
12338 mb_char2bytes(c2, p + tl);
12339 mb_char2bytes(c, p + fl + tl);
12340 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
12342 else
12343 #endif
12345 p[0] = p[2];
12346 p[2] = c;
12347 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12350 else
12351 sp->ts_state = STATE_REP_INI;
12352 break;
12354 case STATE_UNSWAP3:
12355 /* Undo STATE_SWAP3: "321" -> "123" */
12356 p = fword + sp->ts_fidx;
12357 #ifdef FEAT_MBYTE
12358 if (has_mbyte)
12360 n = MB_BYTE2LEN(*p);
12361 c2 = mb_ptr2char(p + n);
12362 fl = MB_BYTE2LEN(p[n]);
12363 c = mb_ptr2char(p + n + fl);
12364 tl = MB_BYTE2LEN(p[n + fl]);
12365 mch_memmove(p + fl + tl, p, n);
12366 mb_char2bytes(c, p);
12367 mb_char2bytes(c2, p + tl);
12368 p = p + tl;
12370 else
12371 #endif
12373 c = *p;
12374 *p = p[2];
12375 p[2] = c;
12376 ++p;
12379 if (!soundfold && !spell_iswordp(p, curbuf))
12381 /* Middle char is not a word char, skip the rotate. First and
12382 * third char were already checked at swap and swap3. */
12383 sp->ts_state = STATE_REP_INI;
12384 break;
12387 /* Rotate three characters left: "123" -> "231". We change
12388 * "fword" here, it's changed back afterwards at STATE_UNROT3L. */
12389 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12391 go_deeper(stack, depth, SCORE_SWAP3);
12392 #ifdef DEBUG_TRIEWALK
12393 p = fword + sp->ts_fidx;
12394 sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",
12395 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12396 p[0], p[1], p[2]);
12397 #endif
12398 sp->ts_state = STATE_UNROT3L;
12399 ++depth;
12400 p = fword + sp->ts_fidx;
12401 #ifdef FEAT_MBYTE
12402 if (has_mbyte)
12404 n = mb_cptr2len(p);
12405 c = mb_ptr2char(p);
12406 fl = mb_cptr2len(p + n);
12407 fl += mb_cptr2len(p + n + fl);
12408 mch_memmove(p, p + n, fl);
12409 mb_char2bytes(c, p + fl);
12410 stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
12412 else
12413 #endif
12415 c = *p;
12416 *p = p[1];
12417 p[1] = p[2];
12418 p[2] = c;
12419 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12422 else
12423 sp->ts_state = STATE_REP_INI;
12424 break;
12426 case STATE_UNROT3L:
12427 /* Undo ROT3L: "231" -> "123" */
12428 p = fword + sp->ts_fidx;
12429 #ifdef FEAT_MBYTE
12430 if (has_mbyte)
12432 n = MB_BYTE2LEN(*p);
12433 n += MB_BYTE2LEN(p[n]);
12434 c = mb_ptr2char(p + n);
12435 tl = MB_BYTE2LEN(p[n]);
12436 mch_memmove(p + tl, p, n);
12437 mb_char2bytes(c, p);
12439 else
12440 #endif
12442 c = p[2];
12443 p[2] = p[1];
12444 p[1] = *p;
12445 *p = c;
12448 /* Rotate three bytes right: "123" -> "312". We change "fword"
12449 * here, it's changed back afterwards at STATE_UNROT3R. */
12450 if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12452 go_deeper(stack, depth, SCORE_SWAP3);
12453 #ifdef DEBUG_TRIEWALK
12454 p = fword + sp->ts_fidx;
12455 sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",
12456 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12457 p[0], p[1], p[2]);
12458 #endif
12459 sp->ts_state = STATE_UNROT3R;
12460 ++depth;
12461 p = fword + sp->ts_fidx;
12462 #ifdef FEAT_MBYTE
12463 if (has_mbyte)
12465 n = mb_cptr2len(p);
12466 n += mb_cptr2len(p + n);
12467 c = mb_ptr2char(p + n);
12468 tl = mb_cptr2len(p + n);
12469 mch_memmove(p + tl, p, n);
12470 mb_char2bytes(c, p);
12471 stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
12473 else
12474 #endif
12476 c = p[2];
12477 p[2] = p[1];
12478 p[1] = *p;
12479 *p = c;
12480 stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12483 else
12484 sp->ts_state = STATE_REP_INI;
12485 break;
12487 case STATE_UNROT3R:
12488 /* Undo ROT3R: "312" -> "123" */
12489 p = fword + sp->ts_fidx;
12490 #ifdef FEAT_MBYTE
12491 if (has_mbyte)
12493 c = mb_ptr2char(p);
12494 tl = MB_BYTE2LEN(*p);
12495 n = MB_BYTE2LEN(p[tl]);
12496 n += MB_BYTE2LEN(p[tl + n]);
12497 mch_memmove(p, p + tl, n);
12498 mb_char2bytes(c, p + n);
12500 else
12501 #endif
12503 c = *p;
12504 *p = p[1];
12505 p[1] = p[2];
12506 p[2] = c;
12508 /*FALLTHROUGH*/
12510 case STATE_REP_INI:
12511 /* Check if matching with REP items from the .aff file would work.
12512 * Quickly skip if:
12513 * - there are no REP items and we are not in the soundfold trie
12514 * - the score is going to be too high anyway
12515 * - already applied a REP item or swapped here */
12516 if ((lp->lp_replang == NULL && !soundfold)
12517 || sp->ts_score + SCORE_REP >= su->su_maxscore
12518 || sp->ts_fidx < sp->ts_fidxtry)
12520 sp->ts_state = STATE_FINAL;
12521 break;
12524 /* Use the first byte to quickly find the first entry that may
12525 * match. If the index is -1 there is none. */
12526 if (soundfold)
12527 sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
12528 else
12529 sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];
12531 if (sp->ts_curi < 0)
12533 sp->ts_state = STATE_FINAL;
12534 break;
12537 sp->ts_state = STATE_REP;
12538 /*FALLTHROUGH*/
12540 case STATE_REP:
12541 /* Try matching with REP items from the .aff file. For each match
12542 * replace the characters and check if the resulting word is
12543 * valid. */
12544 p = fword + sp->ts_fidx;
12546 if (soundfold)
12547 gap = &slang->sl_repsal;
12548 else
12549 gap = &lp->lp_replang->sl_rep;
12550 while (sp->ts_curi < gap->ga_len)
12552 ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
12553 if (*ftp->ft_from != *p)
12555 /* past possible matching entries */
12556 sp->ts_curi = gap->ga_len;
12557 break;
12559 if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
12560 && TRY_DEEPER(su, stack, depth, SCORE_REP))
12562 go_deeper(stack, depth, SCORE_REP);
12563 #ifdef DEBUG_TRIEWALK
12564 sprintf(changename[depth], "%.*s-%s: replace %s with %s",
12565 sp->ts_twordlen, tword, fword + sp->ts_fidx,
12566 ftp->ft_from, ftp->ft_to);
12567 #endif
12568 /* Need to undo this afterwards. */
12569 sp->ts_state = STATE_REP_UNDO;
12571 /* Change the "from" to the "to" string. */
12572 ++depth;
12573 fl = (int)STRLEN(ftp->ft_from);
12574 tl = (int)STRLEN(ftp->ft_to);
12575 if (fl != tl)
12577 mch_memmove(p + tl, p + fl, STRLEN(p + fl) + 1);
12578 repextra += tl - fl;
12580 mch_memmove(p, ftp->ft_to, tl);
12581 stack[depth].ts_fidxtry = sp->ts_fidx + tl;
12582 #ifdef FEAT_MBYTE
12583 stack[depth].ts_tcharlen = 0;
12584 #endif
12585 break;
12589 if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
12590 /* No (more) matches. */
12591 sp->ts_state = STATE_FINAL;
12593 break;
12595 case STATE_REP_UNDO:
12596 /* Undo a REP replacement and continue with the next one. */
12597 if (soundfold)
12598 gap = &slang->sl_repsal;
12599 else
12600 gap = &lp->lp_replang->sl_rep;
12601 ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
12602 fl = (int)STRLEN(ftp->ft_from);
12603 tl = (int)STRLEN(ftp->ft_to);
12604 p = fword + sp->ts_fidx;
12605 if (fl != tl)
12607 mch_memmove(p + fl, p + tl, STRLEN(p + tl) + 1);
12608 repextra -= tl - fl;
12610 mch_memmove(p, ftp->ft_from, fl);
12611 sp->ts_state = STATE_REP;
12612 break;
12614 default:
12615 /* Did all possible states at this level, go up one level. */
12616 --depth;
12618 if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
12620 /* Continue in or go back to the prefix tree. */
12621 byts = pbyts;
12622 idxs = pidxs;
12625 /* Don't check for CTRL-C too often, it takes time. */
12626 if (--breakcheckcount == 0)
12628 ui_breakcheck();
12629 breakcheckcount = 1000;
12637 * Go one level deeper in the tree.
12639 static void
12640 go_deeper(stack, depth, score_add)
12641 trystate_T *stack;
12642 int depth;
12643 int score_add;
12645 stack[depth + 1] = stack[depth];
12646 stack[depth + 1].ts_state = STATE_START;
12647 stack[depth + 1].ts_score = stack[depth].ts_score + score_add;
12648 stack[depth + 1].ts_curi = 1; /* start just after length byte */
12649 stack[depth + 1].ts_flags = 0;
12652 #ifdef FEAT_MBYTE
12654 * Case-folding may change the number of bytes: Count nr of chars in
12655 * fword[flen] and return the byte length of that many chars in "word".
12657 static int
12658 nofold_len(fword, flen, word)
12659 char_u *fword;
12660 int flen;
12661 char_u *word;
12663 char_u *p;
12664 int i = 0;
12666 for (p = fword; p < fword + flen; mb_ptr_adv(p))
12667 ++i;
12668 for (p = word; i > 0; mb_ptr_adv(p))
12669 --i;
12670 return (int)(p - word);
12672 #endif
12675 * "fword" is a good word with case folded. Find the matching keep-case
12676 * words and put it in "kword".
12677 * Theoretically there could be several keep-case words that result in the
12678 * same case-folded word, but we only find one...
12680 static void
12681 find_keepcap_word(slang, fword, kword)
12682 slang_T *slang;
12683 char_u *fword;
12684 char_u *kword;
12686 char_u uword[MAXWLEN]; /* "fword" in upper-case */
12687 int depth;
12688 idx_T tryidx;
12690 /* The following arrays are used at each depth in the tree. */
12691 idx_T arridx[MAXWLEN];
12692 int round[MAXWLEN];
12693 int fwordidx[MAXWLEN];
12694 int uwordidx[MAXWLEN];
12695 int kwordlen[MAXWLEN];
12697 int flen, ulen;
12698 int l;
12699 int len;
12700 int c;
12701 idx_T lo, hi, m;
12702 char_u *p;
12703 char_u *byts = slang->sl_kbyts; /* array with bytes of the words */
12704 idx_T *idxs = slang->sl_kidxs; /* array with indexes */
12706 if (byts == NULL)
12708 /* array is empty: "cannot happen" */
12709 *kword = NUL;
12710 return;
12713 /* Make an all-cap version of "fword". */
12714 allcap_copy(fword, uword);
12717 * Each character needs to be tried both case-folded and upper-case.
12718 * All this gets very complicated if we keep in mind that changing case
12719 * may change the byte length of a multi-byte character...
12721 depth = 0;
12722 arridx[0] = 0;
12723 round[0] = 0;
12724 fwordidx[0] = 0;
12725 uwordidx[0] = 0;
12726 kwordlen[0] = 0;
12727 while (depth >= 0)
12729 if (fword[fwordidx[depth]] == NUL)
12731 /* We are at the end of "fword". If the tree allows a word to end
12732 * here we have found a match. */
12733 if (byts[arridx[depth] + 1] == 0)
12735 kword[kwordlen[depth]] = NUL;
12736 return;
12739 /* kword is getting too long, continue one level up */
12740 --depth;
12742 else if (++round[depth] > 2)
12744 /* tried both fold-case and upper-case character, continue one
12745 * level up */
12746 --depth;
12748 else
12751 * round[depth] == 1: Try using the folded-case character.
12752 * round[depth] == 2: Try using the upper-case character.
12754 #ifdef FEAT_MBYTE
12755 if (has_mbyte)
12757 flen = mb_cptr2len(fword + fwordidx[depth]);
12758 ulen = mb_cptr2len(uword + uwordidx[depth]);
12760 else
12761 #endif
12762 ulen = flen = 1;
12763 if (round[depth] == 1)
12765 p = fword + fwordidx[depth];
12766 l = flen;
12768 else
12770 p = uword + uwordidx[depth];
12771 l = ulen;
12774 for (tryidx = arridx[depth]; l > 0; --l)
12776 /* Perform a binary search in the list of accepted bytes. */
12777 len = byts[tryidx++];
12778 c = *p++;
12779 lo = tryidx;
12780 hi = tryidx + len - 1;
12781 while (lo < hi)
12783 m = (lo + hi) / 2;
12784 if (byts[m] > c)
12785 hi = m - 1;
12786 else if (byts[m] < c)
12787 lo = m + 1;
12788 else
12790 lo = hi = m;
12791 break;
12795 /* Stop if there is no matching byte. */
12796 if (hi < lo || byts[lo] != c)
12797 break;
12799 /* Continue at the child (if there is one). */
12800 tryidx = idxs[lo];
12803 if (l == 0)
12806 * Found the matching char. Copy it to "kword" and go a
12807 * level deeper.
12809 if (round[depth] == 1)
12811 STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth],
12812 flen);
12813 kwordlen[depth + 1] = kwordlen[depth] + flen;
12815 else
12817 STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth],
12818 ulen);
12819 kwordlen[depth + 1] = kwordlen[depth] + ulen;
12821 fwordidx[depth + 1] = fwordidx[depth] + flen;
12822 uwordidx[depth + 1] = uwordidx[depth] + ulen;
12824 ++depth;
12825 arridx[depth] = tryidx;
12826 round[depth] = 0;
12831 /* Didn't find it: "cannot happen". */
12832 *kword = NUL;
12836 * Compute the sound-a-like score for suggestions in su->su_ga and add them to
12837 * su->su_sga.
12839 static void
12840 score_comp_sal(su)
12841 suginfo_T *su;
12843 langp_T *lp;
12844 char_u badsound[MAXWLEN];
12845 int i;
12846 suggest_T *stp;
12847 suggest_T *sstp;
12848 int score;
12849 int lpi;
12851 if (ga_grow(&su->su_sga, su->su_ga.ga_len) == FAIL)
12852 return;
12854 /* Use the sound-folding of the first language that supports it. */
12855 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
12857 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
12858 if (lp->lp_slang->sl_sal.ga_len > 0)
12860 /* soundfold the bad word */
12861 spell_soundfold(lp->lp_slang, su->su_fbadword, TRUE, badsound);
12863 for (i = 0; i < su->su_ga.ga_len; ++i)
12865 stp = &SUG(su->su_ga, i);
12867 /* Case-fold the suggested word, sound-fold it and compute the
12868 * sound-a-like score. */
12869 score = stp_sal_score(stp, su, lp->lp_slang, badsound);
12870 if (score < SCORE_MAXMAX)
12872 /* Add the suggestion. */
12873 sstp = &SUG(su->su_sga, su->su_sga.ga_len);
12874 sstp->st_word = vim_strsave(stp->st_word);
12875 if (sstp->st_word != NULL)
12877 sstp->st_wordlen = stp->st_wordlen;
12878 sstp->st_score = score;
12879 sstp->st_altscore = 0;
12880 sstp->st_orglen = stp->st_orglen;
12881 ++su->su_sga.ga_len;
12885 break;
12891 * Combine the list of suggestions in su->su_ga and su->su_sga.
12892 * They are intwined.
12894 static void
12895 score_combine(su)
12896 suginfo_T *su;
12898 int i;
12899 int j;
12900 garray_T ga;
12901 garray_T *gap;
12902 langp_T *lp;
12903 suggest_T *stp;
12904 char_u *p;
12905 char_u badsound[MAXWLEN];
12906 int round;
12907 int lpi;
12908 slang_T *slang = NULL;
12910 /* Add the alternate score to su_ga. */
12911 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
12913 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
12914 if (lp->lp_slang->sl_sal.ga_len > 0)
12916 /* soundfold the bad word */
12917 slang = lp->lp_slang;
12918 spell_soundfold(slang, su->su_fbadword, TRUE, badsound);
12920 for (i = 0; i < su->su_ga.ga_len; ++i)
12922 stp = &SUG(su->su_ga, i);
12923 stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
12924 if (stp->st_altscore == SCORE_MAXMAX)
12925 stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
12926 else
12927 stp->st_score = (stp->st_score * 3
12928 + stp->st_altscore) / 4;
12929 stp->st_salscore = FALSE;
12931 break;
12935 if (slang == NULL) /* Using "double" without sound folding. */
12937 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore,
12938 su->su_maxcount);
12939 return;
12942 /* Add the alternate score to su_sga. */
12943 for (i = 0; i < su->su_sga.ga_len; ++i)
12945 stp = &SUG(su->su_sga, i);
12946 stp->st_altscore = spell_edit_score(slang,
12947 su->su_badword, stp->st_word);
12948 if (stp->st_score == SCORE_MAXMAX)
12949 stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
12950 else
12951 stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8;
12952 stp->st_salscore = TRUE;
12955 /* Remove bad suggestions, sort the suggestions and truncate at "maxcount"
12956 * for both lists. */
12957 check_suggestions(su, &su->su_ga);
12958 (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
12959 check_suggestions(su, &su->su_sga);
12960 (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount);
12962 ga_init2(&ga, (int)sizeof(suginfo_T), 1);
12963 if (ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len) == FAIL)
12964 return;
12966 stp = &SUG(ga, 0);
12967 for (i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i)
12969 /* round 1: get a suggestion from su_ga
12970 * round 2: get a suggestion from su_sga */
12971 for (round = 1; round <= 2; ++round)
12973 gap = round == 1 ? &su->su_ga : &su->su_sga;
12974 if (i < gap->ga_len)
12976 /* Don't add a word if it's already there. */
12977 p = SUG(*gap, i).st_word;
12978 for (j = 0; j < ga.ga_len; ++j)
12979 if (STRCMP(stp[j].st_word, p) == 0)
12980 break;
12981 if (j == ga.ga_len)
12982 stp[ga.ga_len++] = SUG(*gap, i);
12983 else
12984 vim_free(p);
12989 ga_clear(&su->su_ga);
12990 ga_clear(&su->su_sga);
12992 /* Truncate the list to the number of suggestions that will be displayed. */
12993 if (ga.ga_len > su->su_maxcount)
12995 for (i = su->su_maxcount; i < ga.ga_len; ++i)
12996 vim_free(stp[i].st_word);
12997 ga.ga_len = su->su_maxcount;
13000 su->su_ga = ga;
13004 * For the goodword in "stp" compute the soundalike score compared to the
13005 * badword.
13007 static int
13008 stp_sal_score(stp, su, slang, badsound)
13009 suggest_T *stp;
13010 suginfo_T *su;
13011 slang_T *slang;
13012 char_u *badsound; /* sound-folded badword */
13014 char_u *p;
13015 char_u *pbad;
13016 char_u *pgood;
13017 char_u badsound2[MAXWLEN];
13018 char_u fword[MAXWLEN];
13019 char_u goodsound[MAXWLEN];
13020 char_u goodword[MAXWLEN];
13021 int lendiff;
13023 lendiff = (int)(su->su_badlen - stp->st_orglen);
13024 if (lendiff >= 0)
13025 pbad = badsound;
13026 else
13028 /* soundfold the bad word with more characters following */
13029 (void)spell_casefold(su->su_badptr, stp->st_orglen, fword, MAXWLEN);
13031 /* When joining two words the sound often changes a lot. E.g., "t he"
13032 * sounds like "t h" while "the" sounds like "@". Avoid that by
13033 * removing the space. Don't do it when the good word also contains a
13034 * space. */
13035 if (vim_iswhite(su->su_badptr[su->su_badlen])
13036 && *skiptowhite(stp->st_word) == NUL)
13037 for (p = fword; *(p = skiptowhite(p)) != NUL; )
13038 mch_memmove(p, p + 1, STRLEN(p));
13040 spell_soundfold(slang, fword, TRUE, badsound2);
13041 pbad = badsound2;
13044 if (lendiff > 0)
13046 /* Add part of the bad word to the good word, so that we soundfold
13047 * what replaces the bad word. */
13048 STRCPY(goodword, stp->st_word);
13049 vim_strncpy(goodword + stp->st_wordlen,
13050 su->su_badptr + su->su_badlen - lendiff, lendiff);
13051 pgood = goodword;
13053 else
13054 pgood = stp->st_word;
13056 /* Sound-fold the word and compute the score for the difference. */
13057 spell_soundfold(slang, pgood, FALSE, goodsound);
13059 return soundalike_score(goodsound, pbad);
13062 /* structure used to store soundfolded words that add_sound_suggest() has
13063 * handled already. */
13064 typedef struct
13066 short sft_score; /* lowest score used */
13067 char_u sft_word[1]; /* soundfolded word, actually longer */
13068 } sftword_T;
13070 static sftword_T dumsft;
13071 #define HIKEY2SFT(p) ((sftword_T *)(p - (dumsft.sft_word - (char_u *)&dumsft)))
13072 #define HI2SFT(hi) HIKEY2SFT((hi)->hi_key)
13075 * Prepare for calling suggest_try_soundalike().
13077 static void
13078 suggest_try_soundalike_prep()
13080 langp_T *lp;
13081 int lpi;
13082 slang_T *slang;
13084 /* Do this for all languages that support sound folding and for which a
13085 * .sug file has been loaded. */
13086 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13088 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13089 slang = lp->lp_slang;
13090 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13091 /* prepare the hashtable used by add_sound_suggest() */
13092 hash_init(&slang->sl_sounddone);
13097 * Find suggestions by comparing the word in a sound-a-like form.
13098 * Note: This doesn't support postponed prefixes.
13100 static void
13101 suggest_try_soundalike(su)
13102 suginfo_T *su;
13104 char_u salword[MAXWLEN];
13105 langp_T *lp;
13106 int lpi;
13107 slang_T *slang;
13109 /* Do this for all languages that support sound folding and for which a
13110 * .sug file has been loaded. */
13111 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13113 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13114 slang = lp->lp_slang;
13115 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13117 /* soundfold the bad word */
13118 spell_soundfold(slang, su->su_fbadword, TRUE, salword);
13120 /* try all kinds of inserts/deletes/swaps/etc. */
13121 /* TODO: also soundfold the next words, so that we can try joining
13122 * and splitting */
13123 suggest_trie_walk(su, lp, salword, TRUE);
13129 * Finish up after calling suggest_try_soundalike().
13131 static void
13132 suggest_try_soundalike_finish()
13134 langp_T *lp;
13135 int lpi;
13136 slang_T *slang;
13137 int todo;
13138 hashitem_T *hi;
13140 /* Do this for all languages that support sound folding and for which a
13141 * .sug file has been loaded. */
13142 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13144 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13145 slang = lp->lp_slang;
13146 if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13148 /* Free the info about handled words. */
13149 todo = (int)slang->sl_sounddone.ht_used;
13150 for (hi = slang->sl_sounddone.ht_array; todo > 0; ++hi)
13151 if (!HASHITEM_EMPTY(hi))
13153 vim_free(HI2SFT(hi));
13154 --todo;
13157 /* Clear the hashtable, it may also be used by another region. */
13158 hash_clear(&slang->sl_sounddone);
13159 hash_init(&slang->sl_sounddone);
13165 * A match with a soundfolded word is found. Add the good word(s) that
13166 * produce this soundfolded word.
13168 static void
13169 add_sound_suggest(su, goodword, score, lp)
13170 suginfo_T *su;
13171 char_u *goodword;
13172 int score; /* soundfold score */
13173 langp_T *lp;
13175 slang_T *slang = lp->lp_slang; /* language for sound folding */
13176 int sfwordnr;
13177 char_u *nrline;
13178 int orgnr;
13179 char_u theword[MAXWLEN];
13180 int i;
13181 int wlen;
13182 char_u *byts;
13183 idx_T *idxs;
13184 int n;
13185 int wordcount;
13186 int wc;
13187 int goodscore;
13188 hash_T hash;
13189 hashitem_T *hi;
13190 sftword_T *sft;
13191 int bc, gc;
13192 int limit;
13195 * It's very well possible that the same soundfold word is found several
13196 * times with different scores. Since the following is quite slow only do
13197 * the words that have a better score than before. Use a hashtable to
13198 * remember the words that have been done.
13200 hash = hash_hash(goodword);
13201 hi = hash_lookup(&slang->sl_sounddone, goodword, hash);
13202 if (HASHITEM_EMPTY(hi))
13204 sft = (sftword_T *)alloc((unsigned)(sizeof(sftword_T)
13205 + STRLEN(goodword)));
13206 if (sft != NULL)
13208 sft->sft_score = score;
13209 STRCPY(sft->sft_word, goodword);
13210 hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash);
13213 else
13215 sft = HI2SFT(hi);
13216 if (score >= sft->sft_score)
13217 return;
13218 sft->sft_score = score;
13222 * Find the word nr in the soundfold tree.
13224 sfwordnr = soundfold_find(slang, goodword);
13225 if (sfwordnr < 0)
13227 EMSG2(_(e_intern2), "add_sound_suggest()");
13228 return;
13232 * go over the list of good words that produce this soundfold word
13234 nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)(sfwordnr + 1), FALSE);
13235 orgnr = 0;
13236 while (*nrline != NUL)
13238 /* The wordnr was stored in a minimal nr of bytes as an offset to the
13239 * previous wordnr. */
13240 orgnr += bytes2offset(&nrline);
13242 byts = slang->sl_fbyts;
13243 idxs = slang->sl_fidxs;
13245 /* Lookup the word "orgnr" one of the two tries. */
13246 n = 0;
13247 wlen = 0;
13248 wordcount = 0;
13249 for (;;)
13251 i = 1;
13252 if (wordcount == orgnr && byts[n + 1] == NUL)
13253 break; /* found end of word */
13255 if (byts[n + 1] == NUL)
13256 ++wordcount;
13258 /* skip over the NUL bytes */
13259 for ( ; byts[n + i] == NUL; ++i)
13260 if (i > byts[n]) /* safety check */
13262 STRCPY(theword + wlen, "BAD");
13263 goto badword;
13266 /* One of the siblings must have the word. */
13267 for ( ; i < byts[n]; ++i)
13269 wc = idxs[idxs[n + i]]; /* nr of words under this byte */
13270 if (wordcount + wc > orgnr)
13271 break;
13272 wordcount += wc;
13275 theword[wlen++] = byts[n + i];
13276 n = idxs[n + i];
13278 badword:
13279 theword[wlen] = NUL;
13281 /* Go over the possible flags and regions. */
13282 for (; i <= byts[n] && byts[n + i] == NUL; ++i)
13284 char_u cword[MAXWLEN];
13285 char_u *p;
13286 int flags = (int)idxs[n + i];
13288 /* Skip words with the NOSUGGEST flag */
13289 if (flags & WF_NOSUGGEST)
13290 continue;
13292 if (flags & WF_KEEPCAP)
13294 /* Must find the word in the keep-case tree. */
13295 find_keepcap_word(slang, theword, cword);
13296 p = cword;
13298 else
13300 flags |= su->su_badflags;
13301 if ((flags & WF_CAPMASK) != 0)
13303 /* Need to fix case according to "flags". */
13304 make_case_word(theword, cword, flags);
13305 p = cword;
13307 else
13308 p = theword;
13311 /* Add the suggestion. */
13312 if (sps_flags & SPS_DOUBLE)
13314 /* Add the suggestion if the score isn't too bad. */
13315 if (score <= su->su_maxscore)
13316 add_suggestion(su, &su->su_sga, p, su->su_badlen,
13317 score, 0, FALSE, slang, FALSE);
13319 else
13321 /* Add a penalty for words in another region. */
13322 if ((flags & WF_REGION)
13323 && (((unsigned)flags >> 16) & lp->lp_region) == 0)
13324 goodscore = SCORE_REGION;
13325 else
13326 goodscore = 0;
13328 /* Add a small penalty for changing the first letter from
13329 * lower to upper case. Helps for "tath" -> "Kath", which is
13330 * less common thatn "tath" -> "path". Don't do it when the
13331 * letter is the same, that has already been counted. */
13332 gc = PTR2CHAR(p);
13333 if (SPELL_ISUPPER(gc))
13335 bc = PTR2CHAR(su->su_badword);
13336 if (!SPELL_ISUPPER(bc)
13337 && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc))
13338 goodscore += SCORE_ICASE / 2;
13341 /* Compute the score for the good word. This only does letter
13342 * insert/delete/swap/replace. REP items are not considered,
13343 * which may make the score a bit higher.
13344 * Use a limit for the score to make it work faster. Use
13345 * MAXSCORE(), because RESCORE() will change the score.
13346 * If the limit is very high then the iterative method is
13347 * inefficient, using an array is quicker. */
13348 limit = MAXSCORE(su->su_sfmaxscore - goodscore, score);
13349 if (limit > SCORE_LIMITMAX)
13350 goodscore += spell_edit_score(slang, su->su_badword, p);
13351 else
13352 goodscore += spell_edit_score_limit(slang, su->su_badword,
13353 p, limit);
13355 /* When going over the limit don't bother to do the rest. */
13356 if (goodscore < SCORE_MAXMAX)
13358 /* Give a bonus to words seen before. */
13359 goodscore = score_wordcount_adj(slang, goodscore, p, FALSE);
13361 /* Add the suggestion if the score isn't too bad. */
13362 goodscore = RESCORE(goodscore, score);
13363 if (goodscore <= su->su_sfmaxscore)
13364 add_suggestion(su, &su->su_ga, p, su->su_badlen,
13365 goodscore, score, TRUE, slang, TRUE);
13369 /* smsg("word %s (%d): %s (%d)", sftword, sftnr, theword, orgnr); */
13374 * Find word "word" in fold-case tree for "slang" and return the word number.
13376 static int
13377 soundfold_find(slang, word)
13378 slang_T *slang;
13379 char_u *word;
13381 idx_T arridx = 0;
13382 int len;
13383 int wlen = 0;
13384 int c;
13385 char_u *ptr = word;
13386 char_u *byts;
13387 idx_T *idxs;
13388 int wordnr = 0;
13390 byts = slang->sl_sbyts;
13391 idxs = slang->sl_sidxs;
13393 for (;;)
13395 /* First byte is the number of possible bytes. */
13396 len = byts[arridx++];
13398 /* If the first possible byte is a zero the word could end here.
13399 * If the word ends we found the word. If not skip the NUL bytes. */
13400 c = ptr[wlen];
13401 if (byts[arridx] == NUL)
13403 if (c == NUL)
13404 break;
13406 /* Skip over the zeros, there can be several. */
13407 while (len > 0 && byts[arridx] == NUL)
13409 ++arridx;
13410 --len;
13412 if (len == 0)
13413 return -1; /* no children, word should have ended here */
13414 ++wordnr;
13417 /* If the word ends we didn't find it. */
13418 if (c == NUL)
13419 return -1;
13421 /* Perform a binary search in the list of accepted bytes. */
13422 if (c == TAB) /* <Tab> is handled like <Space> */
13423 c = ' ';
13424 while (byts[arridx] < c)
13426 /* The word count is in the first idxs[] entry of the child. */
13427 wordnr += idxs[idxs[arridx]];
13428 ++arridx;
13429 if (--len == 0) /* end of the bytes, didn't find it */
13430 return -1;
13432 if (byts[arridx] != c) /* didn't find the byte */
13433 return -1;
13435 /* Continue at the child (if there is one). */
13436 arridx = idxs[arridx];
13437 ++wlen;
13439 /* One space in the good word may stand for several spaces in the
13440 * checked word. */
13441 if (c == ' ')
13442 while (ptr[wlen] == ' ' || ptr[wlen] == TAB)
13443 ++wlen;
13446 return wordnr;
13450 * Copy "fword" to "cword", fixing case according to "flags".
13452 static void
13453 make_case_word(fword, cword, flags)
13454 char_u *fword;
13455 char_u *cword;
13456 int flags;
13458 if (flags & WF_ALLCAP)
13459 /* Make it all upper-case */
13460 allcap_copy(fword, cword);
13461 else if (flags & WF_ONECAP)
13462 /* Make the first letter upper-case */
13463 onecap_copy(fword, cword, TRUE);
13464 else
13465 /* Use goodword as-is. */
13466 STRCPY(cword, fword);
13470 * Use map string "map" for languages "lp".
13472 static void
13473 set_map_str(lp, map)
13474 slang_T *lp;
13475 char_u *map;
13477 char_u *p;
13478 int headc = 0;
13479 int c;
13480 int i;
13482 if (*map == NUL)
13484 lp->sl_has_map = FALSE;
13485 return;
13487 lp->sl_has_map = TRUE;
13489 /* Init the array and hash tables empty. */
13490 for (i = 0; i < 256; ++i)
13491 lp->sl_map_array[i] = 0;
13492 #ifdef FEAT_MBYTE
13493 hash_init(&lp->sl_map_hash);
13494 #endif
13497 * The similar characters are stored separated with slashes:
13498 * "aaa/bbb/ccc/". Fill sl_map_array[c] with the character before c and
13499 * before the same slash. For characters above 255 sl_map_hash is used.
13501 for (p = map; *p != NUL; )
13503 #ifdef FEAT_MBYTE
13504 c = mb_cptr2char_adv(&p);
13505 #else
13506 c = *p++;
13507 #endif
13508 if (c == '/')
13509 headc = 0;
13510 else
13512 if (headc == 0)
13513 headc = c;
13515 #ifdef FEAT_MBYTE
13516 /* Characters above 255 don't fit in sl_map_array[], put them in
13517 * the hash table. Each entry is the char, a NUL the headchar and
13518 * a NUL. */
13519 if (c >= 256)
13521 int cl = mb_char2len(c);
13522 int headcl = mb_char2len(headc);
13523 char_u *b;
13524 hash_T hash;
13525 hashitem_T *hi;
13527 b = alloc((unsigned)(cl + headcl + 2));
13528 if (b == NULL)
13529 return;
13530 mb_char2bytes(c, b);
13531 b[cl] = NUL;
13532 mb_char2bytes(headc, b + cl + 1);
13533 b[cl + 1 + headcl] = NUL;
13534 hash = hash_hash(b);
13535 hi = hash_lookup(&lp->sl_map_hash, b, hash);
13536 if (HASHITEM_EMPTY(hi))
13537 hash_add_item(&lp->sl_map_hash, hi, b, hash);
13538 else
13540 /* This should have been checked when generating the .spl
13541 * file. */
13542 EMSG(_("E783: duplicate char in MAP entry"));
13543 vim_free(b);
13546 else
13547 #endif
13548 lp->sl_map_array[c] = headc;
13554 * Return TRUE if "c1" and "c2" are similar characters according to the MAP
13555 * lines in the .aff file.
13557 static int
13558 similar_chars(slang, c1, c2)
13559 slang_T *slang;
13560 int c1;
13561 int c2;
13563 int m1, m2;
13564 #ifdef FEAT_MBYTE
13565 char_u buf[MB_MAXBYTES];
13566 hashitem_T *hi;
13568 if (c1 >= 256)
13570 buf[mb_char2bytes(c1, buf)] = 0;
13571 hi = hash_find(&slang->sl_map_hash, buf);
13572 if (HASHITEM_EMPTY(hi))
13573 m1 = 0;
13574 else
13575 m1 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
13577 else
13578 #endif
13579 m1 = slang->sl_map_array[c1];
13580 if (m1 == 0)
13581 return FALSE;
13584 #ifdef FEAT_MBYTE
13585 if (c2 >= 256)
13587 buf[mb_char2bytes(c2, buf)] = 0;
13588 hi = hash_find(&slang->sl_map_hash, buf);
13589 if (HASHITEM_EMPTY(hi))
13590 m2 = 0;
13591 else
13592 m2 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
13594 else
13595 #endif
13596 m2 = slang->sl_map_array[c2];
13598 return m1 == m2;
13602 * Add a suggestion to the list of suggestions.
13603 * For a suggestion that is already in the list the lowest score is remembered.
13605 static void
13606 add_suggestion(su, gap, goodword, badlenarg, score, altscore, had_bonus,
13607 slang, maxsf)
13608 suginfo_T *su;
13609 garray_T *gap; /* either su_ga or su_sga */
13610 char_u *goodword;
13611 int badlenarg; /* len of bad word replaced with "goodword" */
13612 int score;
13613 int altscore;
13614 int had_bonus; /* value for st_had_bonus */
13615 slang_T *slang; /* language for sound folding */
13616 int maxsf; /* su_maxscore applies to soundfold score,
13617 su_sfmaxscore to the total score. */
13619 int goodlen; /* len of goodword changed */
13620 int badlen; /* len of bad word changed */
13621 suggest_T *stp;
13622 suggest_T new_sug;
13623 int i;
13624 char_u *pgood, *pbad;
13626 /* Minimize "badlen" for consistency. Avoids that changing "the the" to
13627 * "thee the" is added next to changing the first "the" the "thee". */
13628 pgood = goodword + STRLEN(goodword);
13629 pbad = su->su_badptr + badlenarg;
13630 for (;;)
13632 goodlen = (int)(pgood - goodword);
13633 badlen = (int)(pbad - su->su_badptr);
13634 if (goodlen <= 0 || badlen <= 0)
13635 break;
13636 mb_ptr_back(goodword, pgood);
13637 mb_ptr_back(su->su_badptr, pbad);
13638 #ifdef FEAT_MBYTE
13639 if (has_mbyte)
13641 if (mb_ptr2char(pgood) != mb_ptr2char(pbad))
13642 break;
13644 else
13645 #endif
13646 if (*pgood != *pbad)
13647 break;
13650 if (badlen == 0 && goodlen == 0)
13651 /* goodword doesn't change anything; may happen for "the the" changing
13652 * the first "the" to itself. */
13653 return;
13655 if (gap->ga_len == 0)
13656 i = -1;
13657 else
13659 /* Check if the word is already there. Also check the length that is
13660 * being replaced "thes," -> "these" is a different suggestion from
13661 * "thes" -> "these". */
13662 stp = &SUG(*gap, 0);
13663 for (i = gap->ga_len; --i >= 0; ++stp)
13664 if (stp->st_wordlen == goodlen
13665 && stp->st_orglen == badlen
13666 && STRNCMP(stp->st_word, goodword, goodlen) == 0)
13669 * Found it. Remember the word with the lowest score.
13671 if (stp->st_slang == NULL)
13672 stp->st_slang = slang;
13674 new_sug.st_score = score;
13675 new_sug.st_altscore = altscore;
13676 new_sug.st_had_bonus = had_bonus;
13678 if (stp->st_had_bonus != had_bonus)
13680 /* Only one of the two had the soundalike score computed.
13681 * Need to do that for the other one now, otherwise the
13682 * scores can't be compared. This happens because
13683 * suggest_try_change() doesn't compute the soundalike
13684 * word to keep it fast, while some special methods set
13685 * the soundalike score to zero. */
13686 if (had_bonus)
13687 rescore_one(su, stp);
13688 else
13690 new_sug.st_word = stp->st_word;
13691 new_sug.st_wordlen = stp->st_wordlen;
13692 new_sug.st_slang = stp->st_slang;
13693 new_sug.st_orglen = badlen;
13694 rescore_one(su, &new_sug);
13698 if (stp->st_score > new_sug.st_score)
13700 stp->st_score = new_sug.st_score;
13701 stp->st_altscore = new_sug.st_altscore;
13702 stp->st_had_bonus = new_sug.st_had_bonus;
13704 break;
13708 if (i < 0 && ga_grow(gap, 1) == OK)
13710 /* Add a suggestion. */
13711 stp = &SUG(*gap, gap->ga_len);
13712 stp->st_word = vim_strnsave(goodword, goodlen);
13713 if (stp->st_word != NULL)
13715 stp->st_wordlen = goodlen;
13716 stp->st_score = score;
13717 stp->st_altscore = altscore;
13718 stp->st_had_bonus = had_bonus;
13719 stp->st_orglen = badlen;
13720 stp->st_slang = slang;
13721 ++gap->ga_len;
13723 /* If we have too many suggestions now, sort the list and keep
13724 * the best suggestions. */
13725 if (gap->ga_len > SUG_MAX_COUNT(su))
13727 if (maxsf)
13728 su->su_sfmaxscore = cleanup_suggestions(gap,
13729 su->su_sfmaxscore, SUG_CLEAN_COUNT(su));
13730 else
13732 i = su->su_maxscore;
13733 su->su_maxscore = cleanup_suggestions(gap,
13734 su->su_maxscore, SUG_CLEAN_COUNT(su));
13742 * Suggestions may in fact be flagged as errors. Esp. for banned words and
13743 * for split words, such as "the the". Remove these from the list here.
13745 static void
13746 check_suggestions(su, gap)
13747 suginfo_T *su;
13748 garray_T *gap; /* either su_ga or su_sga */
13750 suggest_T *stp;
13751 int i;
13752 char_u longword[MAXWLEN + 1];
13753 int len;
13754 hlf_T attr;
13756 stp = &SUG(*gap, 0);
13757 for (i = gap->ga_len - 1; i >= 0; --i)
13759 /* Need to append what follows to check for "the the". */
13760 STRCPY(longword, stp[i].st_word);
13761 len = stp[i].st_wordlen;
13762 vim_strncpy(longword + len, su->su_badptr + stp[i].st_orglen,
13763 MAXWLEN - len);
13764 attr = HLF_COUNT;
13765 (void)spell_check(curwin, longword, &attr, NULL, FALSE);
13766 if (attr != HLF_COUNT)
13768 /* Remove this entry. */
13769 vim_free(stp[i].st_word);
13770 --gap->ga_len;
13771 if (i < gap->ga_len)
13772 mch_memmove(stp + i, stp + i + 1,
13773 sizeof(suggest_T) * (gap->ga_len - i));
13780 * Add a word to be banned.
13782 static void
13783 add_banned(su, word)
13784 suginfo_T *su;
13785 char_u *word;
13787 char_u *s;
13788 hash_T hash;
13789 hashitem_T *hi;
13791 hash = hash_hash(word);
13792 hi = hash_lookup(&su->su_banned, word, hash);
13793 if (HASHITEM_EMPTY(hi))
13795 s = vim_strsave(word);
13796 if (s != NULL)
13797 hash_add_item(&su->su_banned, hi, s, hash);
13802 * Recompute the score for all suggestions if sound-folding is possible. This
13803 * is slow, thus only done for the final results.
13805 static void
13806 rescore_suggestions(su)
13807 suginfo_T *su;
13809 int i;
13811 if (su->su_sallang != NULL)
13812 for (i = 0; i < su->su_ga.ga_len; ++i)
13813 rescore_one(su, &SUG(su->su_ga, i));
13817 * Recompute the score for one suggestion if sound-folding is possible.
13819 static void
13820 rescore_one(su, stp)
13821 suginfo_T *su;
13822 suggest_T *stp;
13824 slang_T *slang = stp->st_slang;
13825 char_u sal_badword[MAXWLEN];
13826 char_u *p;
13828 /* Only rescore suggestions that have no sal score yet and do have a
13829 * language. */
13830 if (slang != NULL && slang->sl_sal.ga_len > 0 && !stp->st_had_bonus)
13832 if (slang == su->su_sallang)
13833 p = su->su_sal_badword;
13834 else
13836 spell_soundfold(slang, su->su_fbadword, TRUE, sal_badword);
13837 p = sal_badword;
13840 stp->st_altscore = stp_sal_score(stp, su, slang, p);
13841 if (stp->st_altscore == SCORE_MAXMAX)
13842 stp->st_altscore = SCORE_BIG;
13843 stp->st_score = RESCORE(stp->st_score, stp->st_altscore);
13844 stp->st_had_bonus = TRUE;
13848 static int
13849 #ifdef __BORLANDC__
13850 _RTLENTRYF
13851 #endif
13852 sug_compare __ARGS((const void *s1, const void *s2));
13855 * Function given to qsort() to sort the suggestions on st_score.
13856 * First on "st_score", then "st_altscore" then alphabetically.
13858 static int
13859 #ifdef __BORLANDC__
13860 _RTLENTRYF
13861 #endif
13862 sug_compare(s1, s2)
13863 const void *s1;
13864 const void *s2;
13866 suggest_T *p1 = (suggest_T *)s1;
13867 suggest_T *p2 = (suggest_T *)s2;
13868 int n = p1->st_score - p2->st_score;
13870 if (n == 0)
13872 n = p1->st_altscore - p2->st_altscore;
13873 if (n == 0)
13874 n = STRICMP(p1->st_word, p2->st_word);
13876 return n;
13880 * Cleanup the suggestions:
13881 * - Sort on score.
13882 * - Remove words that won't be displayed.
13883 * Returns the maximum score in the list or "maxscore" unmodified.
13885 static int
13886 cleanup_suggestions(gap, maxscore, keep)
13887 garray_T *gap;
13888 int maxscore;
13889 int keep; /* nr of suggestions to keep */
13891 suggest_T *stp = &SUG(*gap, 0);
13892 int i;
13894 /* Sort the list. */
13895 qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T), sug_compare);
13897 /* Truncate the list to the number of suggestions that will be displayed. */
13898 if (gap->ga_len > keep)
13900 for (i = keep; i < gap->ga_len; ++i)
13901 vim_free(stp[i].st_word);
13902 gap->ga_len = keep;
13903 return stp[keep - 1].st_score;
13905 return maxscore;
13908 #if defined(FEAT_EVAL) || defined(PROTO)
13910 * Soundfold a string, for soundfold().
13911 * Result is in allocated memory, NULL for an error.
13913 char_u *
13914 eval_soundfold(word)
13915 char_u *word;
13917 langp_T *lp;
13918 char_u sound[MAXWLEN];
13919 int lpi;
13921 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
13922 /* Use the sound-folding of the first language that supports it. */
13923 for (lpi = 0; lpi < curbuf->b_langp.ga_len; ++lpi)
13925 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
13926 if (lp->lp_slang->sl_sal.ga_len > 0)
13928 /* soundfold the word */
13929 spell_soundfold(lp->lp_slang, word, FALSE, sound);
13930 return vim_strsave(sound);
13934 /* No language with sound folding, return word as-is. */
13935 return vim_strsave(word);
13937 #endif
13940 * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]".
13942 * There are many ways to turn a word into a sound-a-like representation. The
13943 * oldest is Soundex (1918!). A nice overview can be found in "Approximate
13944 * swedish name matching - survey and test of different algorithms" by Klas
13945 * Erikson.
13947 * We support two methods:
13948 * 1. SOFOFROM/SOFOTO do a simple character mapping.
13949 * 2. SAL items define a more advanced sound-folding (and much slower).
13951 static void
13952 spell_soundfold(slang, inword, folded, res)
13953 slang_T *slang;
13954 char_u *inword;
13955 int folded; /* "inword" is already case-folded */
13956 char_u *res;
13958 char_u fword[MAXWLEN];
13959 char_u *word;
13961 if (slang->sl_sofo)
13962 /* SOFOFROM and SOFOTO used */
13963 spell_soundfold_sofo(slang, inword, res);
13964 else
13966 /* SAL items used. Requires the word to be case-folded. */
13967 if (folded)
13968 word = inword;
13969 else
13971 (void)spell_casefold(inword, (int)STRLEN(inword), fword, MAXWLEN);
13972 word = fword;
13975 #ifdef FEAT_MBYTE
13976 if (has_mbyte)
13977 spell_soundfold_wsal(slang, word, res);
13978 else
13979 #endif
13980 spell_soundfold_sal(slang, word, res);
13985 * Perform sound folding of "inword" into "res" according to SOFOFROM and
13986 * SOFOTO lines.
13988 static void
13989 spell_soundfold_sofo(slang, inword, res)
13990 slang_T *slang;
13991 char_u *inword;
13992 char_u *res;
13994 char_u *s;
13995 int ri = 0;
13996 int c;
13998 #ifdef FEAT_MBYTE
13999 if (has_mbyte)
14001 int prevc = 0;
14002 int *ip;
14004 /* The sl_sal_first[] table contains the translation for chars up to
14005 * 255, sl_sal the rest. */
14006 for (s = inword; *s != NUL; )
14008 c = mb_cptr2char_adv(&s);
14009 if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c))
14010 c = ' ';
14011 else if (c < 256)
14012 c = slang->sl_sal_first[c];
14013 else
14015 ip = ((int **)slang->sl_sal.ga_data)[c & 0xff];
14016 if (ip == NULL) /* empty list, can't match */
14017 c = NUL;
14018 else
14019 for (;;) /* find "c" in the list */
14021 if (*ip == 0) /* not found */
14023 c = NUL;
14024 break;
14026 if (*ip == c) /* match! */
14028 c = ip[1];
14029 break;
14031 ip += 2;
14035 if (c != NUL && c != prevc)
14037 ri += mb_char2bytes(c, res + ri);
14038 if (ri + MB_MAXBYTES > MAXWLEN)
14039 break;
14040 prevc = c;
14044 else
14045 #endif
14047 /* The sl_sal_first[] table contains the translation. */
14048 for (s = inword; (c = *s) != NUL; ++s)
14050 if (vim_iswhite(c))
14051 c = ' ';
14052 else
14053 c = slang->sl_sal_first[c];
14054 if (c != NUL && (ri == 0 || res[ri - 1] != c))
14055 res[ri++] = c;
14059 res[ri] = NUL;
14062 static void
14063 spell_soundfold_sal(slang, inword, res)
14064 slang_T *slang;
14065 char_u *inword;
14066 char_u *res;
14068 salitem_T *smp;
14069 char_u word[MAXWLEN];
14070 char_u *s = inword;
14071 char_u *t;
14072 char_u *pf;
14073 int i, j, z;
14074 int reslen;
14075 int n, k = 0;
14076 int z0;
14077 int k0;
14078 int n0;
14079 int c;
14080 int pri;
14081 int p0 = -333;
14082 int c0;
14084 /* Remove accents, if wanted. We actually remove all non-word characters.
14085 * But keep white space. We need a copy, the word may be changed here. */
14086 if (slang->sl_rem_accents)
14088 t = word;
14089 while (*s != NUL)
14091 if (vim_iswhite(*s))
14093 *t++ = ' ';
14094 s = skipwhite(s);
14096 else
14098 if (spell_iswordp_nmw(s))
14099 *t++ = *s;
14100 ++s;
14103 *t = NUL;
14105 else
14106 STRCPY(word, s);
14108 smp = (salitem_T *)slang->sl_sal.ga_data;
14111 * This comes from Aspell phonet.cpp. Converted from C++ to C.
14112 * Changed to keep spaces.
14114 i = reslen = z = 0;
14115 while ((c = word[i]) != NUL)
14117 /* Start with the first rule that has the character in the word. */
14118 n = slang->sl_sal_first[c];
14119 z0 = 0;
14121 if (n >= 0)
14123 /* check all rules for the same letter */
14124 for (; (s = smp[n].sm_lead)[0] == c; ++n)
14126 /* Quickly skip entries that don't match the word. Most
14127 * entries are less then three chars, optimize for that. */
14128 k = smp[n].sm_leadlen;
14129 if (k > 1)
14131 if (word[i + 1] != s[1])
14132 continue;
14133 if (k > 2)
14135 for (j = 2; j < k; ++j)
14136 if (word[i + j] != s[j])
14137 break;
14138 if (j < k)
14139 continue;
14143 if ((pf = smp[n].sm_oneof) != NULL)
14145 /* Check for match with one of the chars in "sm_oneof". */
14146 while (*pf != NUL && *pf != word[i + k])
14147 ++pf;
14148 if (*pf == NUL)
14149 continue;
14150 ++k;
14152 s = smp[n].sm_rules;
14153 pri = 5; /* default priority */
14155 p0 = *s;
14156 k0 = k;
14157 while (*s == '-' && k > 1)
14159 k--;
14160 s++;
14162 if (*s == '<')
14163 s++;
14164 if (VIM_ISDIGIT(*s))
14166 /* determine priority */
14167 pri = *s - '0';
14168 s++;
14170 if (*s == '^' && *(s + 1) == '^')
14171 s++;
14173 if (*s == NUL
14174 || (*s == '^'
14175 && (i == 0 || !(word[i - 1] == ' '
14176 || spell_iswordp(word + i - 1, curbuf)))
14177 && (*(s + 1) != '$'
14178 || (!spell_iswordp(word + i + k0, curbuf))))
14179 || (*s == '$' && i > 0
14180 && spell_iswordp(word + i - 1, curbuf)
14181 && (!spell_iswordp(word + i + k0, curbuf))))
14183 /* search for followup rules, if: */
14184 /* followup and k > 1 and NO '-' in searchstring */
14185 c0 = word[i + k - 1];
14186 n0 = slang->sl_sal_first[c0];
14188 if (slang->sl_followup && k > 1 && n0 >= 0
14189 && p0 != '-' && word[i + k] != NUL)
14191 /* test follow-up rule for "word[i + k]" */
14192 for ( ; (s = smp[n0].sm_lead)[0] == c0; ++n0)
14194 /* Quickly skip entries that don't match the word.
14195 * */
14196 k0 = smp[n0].sm_leadlen;
14197 if (k0 > 1)
14199 if (word[i + k] != s[1])
14200 continue;
14201 if (k0 > 2)
14203 pf = word + i + k + 1;
14204 for (j = 2; j < k0; ++j)
14205 if (*pf++ != s[j])
14206 break;
14207 if (j < k0)
14208 continue;
14211 k0 += k - 1;
14213 if ((pf = smp[n0].sm_oneof) != NULL)
14215 /* Check for match with one of the chars in
14216 * "sm_oneof". */
14217 while (*pf != NUL && *pf != word[i + k0])
14218 ++pf;
14219 if (*pf == NUL)
14220 continue;
14221 ++k0;
14224 p0 = 5;
14225 s = smp[n0].sm_rules;
14226 while (*s == '-')
14228 /* "k0" gets NOT reduced because
14229 * "if (k0 == k)" */
14230 s++;
14232 if (*s == '<')
14233 s++;
14234 if (VIM_ISDIGIT(*s))
14236 p0 = *s - '0';
14237 s++;
14240 if (*s == NUL
14241 /* *s == '^' cuts */
14242 || (*s == '$'
14243 && !spell_iswordp(word + i + k0,
14244 curbuf)))
14246 if (k0 == k)
14247 /* this is just a piece of the string */
14248 continue;
14250 if (p0 < pri)
14251 /* priority too low */
14252 continue;
14253 /* rule fits; stop search */
14254 break;
14258 if (p0 >= pri && smp[n0].sm_lead[0] == c0)
14259 continue;
14262 /* replace string */
14263 s = smp[n].sm_to;
14264 if (s == NULL)
14265 s = (char_u *)"";
14266 pf = smp[n].sm_rules;
14267 p0 = (vim_strchr(pf, '<') != NULL) ? 1 : 0;
14268 if (p0 == 1 && z == 0)
14270 /* rule with '<' is used */
14271 if (reslen > 0 && *s != NUL && (res[reslen - 1] == c
14272 || res[reslen - 1] == *s))
14273 reslen--;
14274 z0 = 1;
14275 z = 1;
14276 k0 = 0;
14277 while (*s != NUL && word[i + k0] != NUL)
14279 word[i + k0] = *s;
14280 k0++;
14281 s++;
14283 if (k > k0)
14284 mch_memmove(word + i + k0, word + i + k,
14285 STRLEN(word + i + k) + 1);
14287 /* new "actual letter" */
14288 c = word[i];
14290 else
14292 /* no '<' rule used */
14293 i += k - 1;
14294 z = 0;
14295 while (*s != NUL && s[1] != NUL && reslen < MAXWLEN)
14297 if (reslen == 0 || res[reslen - 1] != *s)
14298 res[reslen++] = *s;
14299 s++;
14301 /* new "actual letter" */
14302 c = *s;
14303 if (strstr((char *)pf, "^^") != NULL)
14305 if (c != NUL)
14306 res[reslen++] = c;
14307 mch_memmove(word, word + i + 1,
14308 STRLEN(word + i + 1) + 1);
14309 i = 0;
14310 z0 = 1;
14313 break;
14317 else if (vim_iswhite(c))
14319 c = ' ';
14320 k = 1;
14323 if (z0 == 0)
14325 if (k && !p0 && reslen < MAXWLEN && c != NUL
14326 && (!slang->sl_collapse || reslen == 0
14327 || res[reslen - 1] != c))
14328 /* condense only double letters */
14329 res[reslen++] = c;
14331 i++;
14332 z = 0;
14333 k = 0;
14337 res[reslen] = NUL;
14340 #ifdef FEAT_MBYTE
14342 * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]".
14343 * Multi-byte version of spell_soundfold().
14345 static void
14346 spell_soundfold_wsal(slang, inword, res)
14347 slang_T *slang;
14348 char_u *inword;
14349 char_u *res;
14351 salitem_T *smp = (salitem_T *)slang->sl_sal.ga_data;
14352 int word[MAXWLEN];
14353 int wres[MAXWLEN];
14354 int l;
14355 char_u *s;
14356 int *ws;
14357 char_u *t;
14358 int *pf;
14359 int i, j, z;
14360 int reslen;
14361 int n, k = 0;
14362 int z0;
14363 int k0;
14364 int n0;
14365 int c;
14366 int pri;
14367 int p0 = -333;
14368 int c0;
14369 int did_white = FALSE;
14372 * Convert the multi-byte string to a wide-character string.
14373 * Remove accents, if wanted. We actually remove all non-word characters.
14374 * But keep white space.
14376 n = 0;
14377 for (s = inword; *s != NUL; )
14379 t = s;
14380 c = mb_cptr2char_adv(&s);
14381 if (slang->sl_rem_accents)
14383 if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c))
14385 if (did_white)
14386 continue;
14387 c = ' ';
14388 did_white = TRUE;
14390 else
14392 did_white = FALSE;
14393 if (!spell_iswordp_nmw(t))
14394 continue;
14397 word[n++] = c;
14399 word[n] = NUL;
14402 * This comes from Aspell phonet.cpp.
14403 * Converted from C++ to C. Added support for multi-byte chars.
14404 * Changed to keep spaces.
14406 i = reslen = z = 0;
14407 while ((c = word[i]) != NUL)
14409 /* Start with the first rule that has the character in the word. */
14410 n = slang->sl_sal_first[c & 0xff];
14411 z0 = 0;
14413 if (n >= 0)
14415 /* check all rules for the same index byte */
14416 for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff); ++n)
14418 /* Quickly skip entries that don't match the word. Most
14419 * entries are less then three chars, optimize for that. */
14420 if (c != ws[0])
14421 continue;
14422 k = smp[n].sm_leadlen;
14423 if (k > 1)
14425 if (word[i + 1] != ws[1])
14426 continue;
14427 if (k > 2)
14429 for (j = 2; j < k; ++j)
14430 if (word[i + j] != ws[j])
14431 break;
14432 if (j < k)
14433 continue;
14437 if ((pf = smp[n].sm_oneof_w) != NULL)
14439 /* Check for match with one of the chars in "sm_oneof". */
14440 while (*pf != NUL && *pf != word[i + k])
14441 ++pf;
14442 if (*pf == NUL)
14443 continue;
14444 ++k;
14446 s = smp[n].sm_rules;
14447 pri = 5; /* default priority */
14449 p0 = *s;
14450 k0 = k;
14451 while (*s == '-' && k > 1)
14453 k--;
14454 s++;
14456 if (*s == '<')
14457 s++;
14458 if (VIM_ISDIGIT(*s))
14460 /* determine priority */
14461 pri = *s - '0';
14462 s++;
14464 if (*s == '^' && *(s + 1) == '^')
14465 s++;
14467 if (*s == NUL
14468 || (*s == '^'
14469 && (i == 0 || !(word[i - 1] == ' '
14470 || spell_iswordp_w(word + i - 1, curbuf)))
14471 && (*(s + 1) != '$'
14472 || (!spell_iswordp_w(word + i + k0, curbuf))))
14473 || (*s == '$' && i > 0
14474 && spell_iswordp_w(word + i - 1, curbuf)
14475 && (!spell_iswordp_w(word + i + k0, curbuf))))
14477 /* search for followup rules, if: */
14478 /* followup and k > 1 and NO '-' in searchstring */
14479 c0 = word[i + k - 1];
14480 n0 = slang->sl_sal_first[c0 & 0xff];
14482 if (slang->sl_followup && k > 1 && n0 >= 0
14483 && p0 != '-' && word[i + k] != NUL)
14485 /* Test follow-up rule for "word[i + k]"; loop over
14486 * all entries with the same index byte. */
14487 for ( ; ((ws = smp[n0].sm_lead_w)[0] & 0xff)
14488 == (c0 & 0xff); ++n0)
14490 /* Quickly skip entries that don't match the word.
14492 if (c0 != ws[0])
14493 continue;
14494 k0 = smp[n0].sm_leadlen;
14495 if (k0 > 1)
14497 if (word[i + k] != ws[1])
14498 continue;
14499 if (k0 > 2)
14501 pf = word + i + k + 1;
14502 for (j = 2; j < k0; ++j)
14503 if (*pf++ != ws[j])
14504 break;
14505 if (j < k0)
14506 continue;
14509 k0 += k - 1;
14511 if ((pf = smp[n0].sm_oneof_w) != NULL)
14513 /* Check for match with one of the chars in
14514 * "sm_oneof". */
14515 while (*pf != NUL && *pf != word[i + k0])
14516 ++pf;
14517 if (*pf == NUL)
14518 continue;
14519 ++k0;
14522 p0 = 5;
14523 s = smp[n0].sm_rules;
14524 while (*s == '-')
14526 /* "k0" gets NOT reduced because
14527 * "if (k0 == k)" */
14528 s++;
14530 if (*s == '<')
14531 s++;
14532 if (VIM_ISDIGIT(*s))
14534 p0 = *s - '0';
14535 s++;
14538 if (*s == NUL
14539 /* *s == '^' cuts */
14540 || (*s == '$'
14541 && !spell_iswordp_w(word + i + k0,
14542 curbuf)))
14544 if (k0 == k)
14545 /* this is just a piece of the string */
14546 continue;
14548 if (p0 < pri)
14549 /* priority too low */
14550 continue;
14551 /* rule fits; stop search */
14552 break;
14556 if (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff)
14557 == (c0 & 0xff))
14558 continue;
14561 /* replace string */
14562 ws = smp[n].sm_to_w;
14563 s = smp[n].sm_rules;
14564 p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0;
14565 if (p0 == 1 && z == 0)
14567 /* rule with '<' is used */
14568 if (reslen > 0 && ws != NULL && *ws != NUL
14569 && (wres[reslen - 1] == c
14570 || wres[reslen - 1] == *ws))
14571 reslen--;
14572 z0 = 1;
14573 z = 1;
14574 k0 = 0;
14575 if (ws != NULL)
14576 while (*ws != NUL && word[i + k0] != NUL)
14578 word[i + k0] = *ws;
14579 k0++;
14580 ws++;
14582 if (k > k0)
14583 mch_memmove(word + i + k0, word + i + k,
14584 sizeof(int) * (STRLEN(word + i + k) + 1));
14586 /* new "actual letter" */
14587 c = word[i];
14589 else
14591 /* no '<' rule used */
14592 i += k - 1;
14593 z = 0;
14594 if (ws != NULL)
14595 while (*ws != NUL && ws[1] != NUL
14596 && reslen < MAXWLEN)
14598 if (reslen == 0 || wres[reslen - 1] != *ws)
14599 wres[reslen++] = *ws;
14600 ws++;
14602 /* new "actual letter" */
14603 if (ws == NULL)
14604 c = NUL;
14605 else
14606 c = *ws;
14607 if (strstr((char *)s, "^^") != NULL)
14609 if (c != NUL)
14610 wres[reslen++] = c;
14611 mch_memmove(word, word + i + 1,
14612 sizeof(int) * (STRLEN(word + i + 1) + 1));
14613 i = 0;
14614 z0 = 1;
14617 break;
14621 else if (vim_iswhite(c))
14623 c = ' ';
14624 k = 1;
14627 if (z0 == 0)
14629 if (k && !p0 && reslen < MAXWLEN && c != NUL
14630 && (!slang->sl_collapse || reslen == 0
14631 || wres[reslen - 1] != c))
14632 /* condense only double letters */
14633 wres[reslen++] = c;
14635 i++;
14636 z = 0;
14637 k = 0;
14641 /* Convert wide characters in "wres" to a multi-byte string in "res". */
14642 l = 0;
14643 for (n = 0; n < reslen; ++n)
14645 l += mb_char2bytes(wres[n], res + l);
14646 if (l + MB_MAXBYTES > MAXWLEN)
14647 break;
14649 res[l] = NUL;
14651 #endif
14654 * Compute a score for two sound-a-like words.
14655 * This permits up to two inserts/deletes/swaps/etc. to keep things fast.
14656 * Instead of a generic loop we write out the code. That keeps it fast by
14657 * avoiding checks that will not be possible.
14659 static int
14660 soundalike_score(goodstart, badstart)
14661 char_u *goodstart; /* sound-folded good word */
14662 char_u *badstart; /* sound-folded bad word */
14664 char_u *goodsound = goodstart;
14665 char_u *badsound = badstart;
14666 int goodlen;
14667 int badlen;
14668 int n;
14669 char_u *pl, *ps;
14670 char_u *pl2, *ps2;
14671 int score = 0;
14673 /* adding/inserting "*" at the start (word starts with vowel) shouldn't be
14674 * counted so much, vowels halfway the word aren't counted at all. */
14675 if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound)
14677 if (badsound[1] == goodsound[1]
14678 || (badsound[1] != NUL
14679 && goodsound[1] != NUL
14680 && badsound[2] == goodsound[2]))
14682 /* handle like a substitute */
14684 else
14686 score = 2 * SCORE_DEL / 3;
14687 if (*badsound == '*')
14688 ++badsound;
14689 else
14690 ++goodsound;
14694 goodlen = (int)STRLEN(goodsound);
14695 badlen = (int)STRLEN(badsound);
14697 /* Return quickly if the lengths are too different to be fixed by two
14698 * changes. */
14699 n = goodlen - badlen;
14700 if (n < -2 || n > 2)
14701 return SCORE_MAXMAX;
14703 if (n > 0)
14705 pl = goodsound; /* goodsound is longest */
14706 ps = badsound;
14708 else
14710 pl = badsound; /* badsound is longest */
14711 ps = goodsound;
14714 /* Skip over the identical part. */
14715 while (*pl == *ps && *pl != NUL)
14717 ++pl;
14718 ++ps;
14721 switch (n)
14723 case -2:
14724 case 2:
14726 * Must delete two characters from "pl".
14728 ++pl; /* first delete */
14729 while (*pl == *ps)
14731 ++pl;
14732 ++ps;
14734 /* strings must be equal after second delete */
14735 if (STRCMP(pl + 1, ps) == 0)
14736 return score + SCORE_DEL * 2;
14738 /* Failed to compare. */
14739 break;
14741 case -1:
14742 case 1:
14744 * Minimal one delete from "pl" required.
14747 /* 1: delete */
14748 pl2 = pl + 1;
14749 ps2 = ps;
14750 while (*pl2 == *ps2)
14752 if (*pl2 == NUL) /* reached the end */
14753 return score + SCORE_DEL;
14754 ++pl2;
14755 ++ps2;
14758 /* 2: delete then swap, then rest must be equal */
14759 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
14760 && STRCMP(pl2 + 2, ps2 + 2) == 0)
14761 return score + SCORE_DEL + SCORE_SWAP;
14763 /* 3: delete then substitute, then the rest must be equal */
14764 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
14765 return score + SCORE_DEL + SCORE_SUBST;
14767 /* 4: first swap then delete */
14768 if (pl[0] == ps[1] && pl[1] == ps[0])
14770 pl2 = pl + 2; /* swap, skip two chars */
14771 ps2 = ps + 2;
14772 while (*pl2 == *ps2)
14774 ++pl2;
14775 ++ps2;
14777 /* delete a char and then strings must be equal */
14778 if (STRCMP(pl2 + 1, ps2) == 0)
14779 return score + SCORE_SWAP + SCORE_DEL;
14782 /* 5: first substitute then delete */
14783 pl2 = pl + 1; /* substitute, skip one char */
14784 ps2 = ps + 1;
14785 while (*pl2 == *ps2)
14787 ++pl2;
14788 ++ps2;
14790 /* delete a char and then strings must be equal */
14791 if (STRCMP(pl2 + 1, ps2) == 0)
14792 return score + SCORE_SUBST + SCORE_DEL;
14794 /* Failed to compare. */
14795 break;
14797 case 0:
14799 * Lenghts are equal, thus changes must result in same length: An
14800 * insert is only possible in combination with a delete.
14801 * 1: check if for identical strings
14803 if (*pl == NUL)
14804 return score;
14806 /* 2: swap */
14807 if (pl[0] == ps[1] && pl[1] == ps[0])
14809 pl2 = pl + 2; /* swap, skip two chars */
14810 ps2 = ps + 2;
14811 while (*pl2 == *ps2)
14813 if (*pl2 == NUL) /* reached the end */
14814 return score + SCORE_SWAP;
14815 ++pl2;
14816 ++ps2;
14818 /* 3: swap and swap again */
14819 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
14820 && STRCMP(pl2 + 2, ps2 + 2) == 0)
14821 return score + SCORE_SWAP + SCORE_SWAP;
14823 /* 4: swap and substitute */
14824 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
14825 return score + SCORE_SWAP + SCORE_SUBST;
14828 /* 5: substitute */
14829 pl2 = pl + 1;
14830 ps2 = ps + 1;
14831 while (*pl2 == *ps2)
14833 if (*pl2 == NUL) /* reached the end */
14834 return score + SCORE_SUBST;
14835 ++pl2;
14836 ++ps2;
14839 /* 6: substitute and swap */
14840 if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
14841 && STRCMP(pl2 + 2, ps2 + 2) == 0)
14842 return score + SCORE_SUBST + SCORE_SWAP;
14844 /* 7: substitute and substitute */
14845 if (STRCMP(pl2 + 1, ps2 + 1) == 0)
14846 return score + SCORE_SUBST + SCORE_SUBST;
14848 /* 8: insert then delete */
14849 pl2 = pl;
14850 ps2 = ps + 1;
14851 while (*pl2 == *ps2)
14853 ++pl2;
14854 ++ps2;
14856 if (STRCMP(pl2 + 1, ps2) == 0)
14857 return score + SCORE_INS + SCORE_DEL;
14859 /* 9: delete then insert */
14860 pl2 = pl + 1;
14861 ps2 = ps;
14862 while (*pl2 == *ps2)
14864 ++pl2;
14865 ++ps2;
14867 if (STRCMP(pl2, ps2 + 1) == 0)
14868 return score + SCORE_INS + SCORE_DEL;
14870 /* Failed to compare. */
14871 break;
14874 return SCORE_MAXMAX;
14878 * Compute the "edit distance" to turn "badword" into "goodword". The less
14879 * deletes/inserts/substitutes/swaps are required the lower the score.
14881 * The algorithm is described by Du and Chang, 1992.
14882 * The implementation of the algorithm comes from Aspell editdist.cpp,
14883 * edit_distance(). It has been converted from C++ to C and modified to
14884 * support multi-byte characters.
14886 static int
14887 spell_edit_score(slang, badword, goodword)
14888 slang_T *slang;
14889 char_u *badword;
14890 char_u *goodword;
14892 int *cnt;
14893 int badlen, goodlen; /* lengths including NUL */
14894 int j, i;
14895 int t;
14896 int bc, gc;
14897 int pbc, pgc;
14898 #ifdef FEAT_MBYTE
14899 char_u *p;
14900 int wbadword[MAXWLEN];
14901 int wgoodword[MAXWLEN];
14903 if (has_mbyte)
14905 /* Get the characters from the multi-byte strings and put them in an
14906 * int array for easy access. */
14907 for (p = badword, badlen = 0; *p != NUL; )
14908 wbadword[badlen++] = mb_cptr2char_adv(&p);
14909 wbadword[badlen++] = 0;
14910 for (p = goodword, goodlen = 0; *p != NUL; )
14911 wgoodword[goodlen++] = mb_cptr2char_adv(&p);
14912 wgoodword[goodlen++] = 0;
14914 else
14915 #endif
14917 badlen = (int)STRLEN(badword) + 1;
14918 goodlen = (int)STRLEN(goodword) + 1;
14921 /* We use "cnt" as an array: CNT(badword_idx, goodword_idx). */
14922 #define CNT(a, b) cnt[(a) + (b) * (badlen + 1)]
14923 cnt = (int *)lalloc((long_u)(sizeof(int) * (badlen + 1) * (goodlen + 1)),
14924 TRUE);
14925 if (cnt == NULL)
14926 return 0; /* out of memory */
14928 CNT(0, 0) = 0;
14929 for (j = 1; j <= goodlen; ++j)
14930 CNT(0, j) = CNT(0, j - 1) + SCORE_INS;
14932 for (i = 1; i <= badlen; ++i)
14934 CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL;
14935 for (j = 1; j <= goodlen; ++j)
14937 #ifdef FEAT_MBYTE
14938 if (has_mbyte)
14940 bc = wbadword[i - 1];
14941 gc = wgoodword[j - 1];
14943 else
14944 #endif
14946 bc = badword[i - 1];
14947 gc = goodword[j - 1];
14949 if (bc == gc)
14950 CNT(i, j) = CNT(i - 1, j - 1);
14951 else
14953 /* Use a better score when there is only a case difference. */
14954 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
14955 CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1);
14956 else
14958 /* For a similar character use SCORE_SIMILAR. */
14959 if (slang != NULL
14960 && slang->sl_has_map
14961 && similar_chars(slang, gc, bc))
14962 CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1);
14963 else
14964 CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1);
14967 if (i > 1 && j > 1)
14969 #ifdef FEAT_MBYTE
14970 if (has_mbyte)
14972 pbc = wbadword[i - 2];
14973 pgc = wgoodword[j - 2];
14975 else
14976 #endif
14978 pbc = badword[i - 2];
14979 pgc = goodword[j - 2];
14981 if (bc == pgc && pbc == gc)
14983 t = SCORE_SWAP + CNT(i - 2, j - 2);
14984 if (t < CNT(i, j))
14985 CNT(i, j) = t;
14988 t = SCORE_DEL + CNT(i - 1, j);
14989 if (t < CNT(i, j))
14990 CNT(i, j) = t;
14991 t = SCORE_INS + CNT(i, j - 1);
14992 if (t < CNT(i, j))
14993 CNT(i, j) = t;
14998 i = CNT(badlen - 1, goodlen - 1);
14999 vim_free(cnt);
15000 return i;
15003 typedef struct
15005 int badi;
15006 int goodi;
15007 int score;
15008 } limitscore_T;
15011 * Like spell_edit_score(), but with a limit on the score to make it faster.
15012 * May return SCORE_MAXMAX when the score is higher than "limit".
15014 * This uses a stack for the edits still to be tried.
15015 * The idea comes from Aspell leditdist.cpp. Rewritten in C and added support
15016 * for multi-byte characters.
15018 static int
15019 spell_edit_score_limit(slang, badword, goodword, limit)
15020 slang_T *slang;
15021 char_u *badword;
15022 char_u *goodword;
15023 int limit;
15025 limitscore_T stack[10]; /* allow for over 3 * 2 edits */
15026 int stackidx;
15027 int bi, gi;
15028 int bi2, gi2;
15029 int bc, gc;
15030 int score;
15031 int score_off;
15032 int minscore;
15033 int round;
15035 #ifdef FEAT_MBYTE
15036 /* Multi-byte characters require a bit more work, use a different function
15037 * to avoid testing "has_mbyte" quite often. */
15038 if (has_mbyte)
15039 return spell_edit_score_limit_w(slang, badword, goodword, limit);
15040 #endif
15043 * The idea is to go from start to end over the words. So long as
15044 * characters are equal just continue, this always gives the lowest score.
15045 * When there is a difference try several alternatives. Each alternative
15046 * increases "score" for the edit distance. Some of the alternatives are
15047 * pushed unto a stack and tried later, some are tried right away. At the
15048 * end of the word the score for one alternative is known. The lowest
15049 * possible score is stored in "minscore".
15051 stackidx = 0;
15052 bi = 0;
15053 gi = 0;
15054 score = 0;
15055 minscore = limit + 1;
15057 for (;;)
15059 /* Skip over an equal part, score remains the same. */
15060 for (;;)
15062 bc = badword[bi];
15063 gc = goodword[gi];
15064 if (bc != gc) /* stop at a char that's different */
15065 break;
15066 if (bc == NUL) /* both words end */
15068 if (score < minscore)
15069 minscore = score;
15070 goto pop; /* do next alternative */
15072 ++bi;
15073 ++gi;
15076 if (gc == NUL) /* goodword ends, delete badword chars */
15080 if ((score += SCORE_DEL) >= minscore)
15081 goto pop; /* do next alternative */
15082 } while (badword[++bi] != NUL);
15083 minscore = score;
15085 else if (bc == NUL) /* badword ends, insert badword chars */
15089 if ((score += SCORE_INS) >= minscore)
15090 goto pop; /* do next alternative */
15091 } while (goodword[++gi] != NUL);
15092 minscore = score;
15094 else /* both words continue */
15096 /* If not close to the limit, perform a change. Only try changes
15097 * that may lead to a lower score than "minscore".
15098 * round 0: try deleting a char from badword
15099 * round 1: try inserting a char in badword */
15100 for (round = 0; round <= 1; ++round)
15102 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
15103 if (score_off < minscore)
15105 if (score_off + SCORE_EDIT_MIN >= minscore)
15107 /* Near the limit, rest of the words must match. We
15108 * can check that right now, no need to push an item
15109 * onto the stack. */
15110 bi2 = bi + 1 - round;
15111 gi2 = gi + round;
15112 while (goodword[gi2] == badword[bi2])
15114 if (goodword[gi2] == NUL)
15116 minscore = score_off;
15117 break;
15119 ++bi2;
15120 ++gi2;
15123 else
15125 /* try deleting/inserting a character later */
15126 stack[stackidx].badi = bi + 1 - round;
15127 stack[stackidx].goodi = gi + round;
15128 stack[stackidx].score = score_off;
15129 ++stackidx;
15134 if (score + SCORE_SWAP < minscore)
15136 /* If swapping two characters makes a match then the
15137 * substitution is more expensive, thus there is no need to
15138 * try both. */
15139 if (gc == badword[bi + 1] && bc == goodword[gi + 1])
15141 /* Swap two characters, that is: skip them. */
15142 gi += 2;
15143 bi += 2;
15144 score += SCORE_SWAP;
15145 continue;
15149 /* Substitute one character for another which is the same
15150 * thing as deleting a character from both goodword and badword.
15151 * Use a better score when there is only a case difference. */
15152 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15153 score += SCORE_ICASE;
15154 else
15156 /* For a similar character use SCORE_SIMILAR. */
15157 if (slang != NULL
15158 && slang->sl_has_map
15159 && similar_chars(slang, gc, bc))
15160 score += SCORE_SIMILAR;
15161 else
15162 score += SCORE_SUBST;
15165 if (score < minscore)
15167 /* Do the substitution. */
15168 ++gi;
15169 ++bi;
15170 continue;
15173 pop:
15175 * Get here to try the next alternative, pop it from the stack.
15177 if (stackidx == 0) /* stack is empty, finished */
15178 break;
15180 /* pop an item from the stack */
15181 --stackidx;
15182 gi = stack[stackidx].goodi;
15183 bi = stack[stackidx].badi;
15184 score = stack[stackidx].score;
15187 /* When the score goes over "limit" it may actually be much higher.
15188 * Return a very large number to avoid going below the limit when giving a
15189 * bonus. */
15190 if (minscore > limit)
15191 return SCORE_MAXMAX;
15192 return minscore;
15195 #ifdef FEAT_MBYTE
15197 * Multi-byte version of spell_edit_score_limit().
15198 * Keep it in sync with the above!
15200 static int
15201 spell_edit_score_limit_w(slang, badword, goodword, limit)
15202 slang_T *slang;
15203 char_u *badword;
15204 char_u *goodword;
15205 int limit;
15207 limitscore_T stack[10]; /* allow for over 3 * 2 edits */
15208 int stackidx;
15209 int bi, gi;
15210 int bi2, gi2;
15211 int bc, gc;
15212 int score;
15213 int score_off;
15214 int minscore;
15215 int round;
15216 char_u *p;
15217 int wbadword[MAXWLEN];
15218 int wgoodword[MAXWLEN];
15220 /* Get the characters from the multi-byte strings and put them in an
15221 * int array for easy access. */
15222 bi = 0;
15223 for (p = badword; *p != NUL; )
15224 wbadword[bi++] = mb_cptr2char_adv(&p);
15225 wbadword[bi++] = 0;
15226 gi = 0;
15227 for (p = goodword; *p != NUL; )
15228 wgoodword[gi++] = mb_cptr2char_adv(&p);
15229 wgoodword[gi++] = 0;
15232 * The idea is to go from start to end over the words. So long as
15233 * characters are equal just continue, this always gives the lowest score.
15234 * When there is a difference try several alternatives. Each alternative
15235 * increases "score" for the edit distance. Some of the alternatives are
15236 * pushed unto a stack and tried later, some are tried right away. At the
15237 * end of the word the score for one alternative is known. The lowest
15238 * possible score is stored in "minscore".
15240 stackidx = 0;
15241 bi = 0;
15242 gi = 0;
15243 score = 0;
15244 minscore = limit + 1;
15246 for (;;)
15248 /* Skip over an equal part, score remains the same. */
15249 for (;;)
15251 bc = wbadword[bi];
15252 gc = wgoodword[gi];
15254 if (bc != gc) /* stop at a char that's different */
15255 break;
15256 if (bc == NUL) /* both words end */
15258 if (score < minscore)
15259 minscore = score;
15260 goto pop; /* do next alternative */
15262 ++bi;
15263 ++gi;
15266 if (gc == NUL) /* goodword ends, delete badword chars */
15270 if ((score += SCORE_DEL) >= minscore)
15271 goto pop; /* do next alternative */
15272 } while (wbadword[++bi] != NUL);
15273 minscore = score;
15275 else if (bc == NUL) /* badword ends, insert badword chars */
15279 if ((score += SCORE_INS) >= minscore)
15280 goto pop; /* do next alternative */
15281 } while (wgoodword[++gi] != NUL);
15282 minscore = score;
15284 else /* both words continue */
15286 /* If not close to the limit, perform a change. Only try changes
15287 * that may lead to a lower score than "minscore".
15288 * round 0: try deleting a char from badword
15289 * round 1: try inserting a char in badword */
15290 for (round = 0; round <= 1; ++round)
15292 score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
15293 if (score_off < minscore)
15295 if (score_off + SCORE_EDIT_MIN >= minscore)
15297 /* Near the limit, rest of the words must match. We
15298 * can check that right now, no need to push an item
15299 * onto the stack. */
15300 bi2 = bi + 1 - round;
15301 gi2 = gi + round;
15302 while (wgoodword[gi2] == wbadword[bi2])
15304 if (wgoodword[gi2] == NUL)
15306 minscore = score_off;
15307 break;
15309 ++bi2;
15310 ++gi2;
15313 else
15315 /* try deleting a character from badword later */
15316 stack[stackidx].badi = bi + 1 - round;
15317 stack[stackidx].goodi = gi + round;
15318 stack[stackidx].score = score_off;
15319 ++stackidx;
15324 if (score + SCORE_SWAP < minscore)
15326 /* If swapping two characters makes a match then the
15327 * substitution is more expensive, thus there is no need to
15328 * try both. */
15329 if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1])
15331 /* Swap two characters, that is: skip them. */
15332 gi += 2;
15333 bi += 2;
15334 score += SCORE_SWAP;
15335 continue;
15339 /* Substitute one character for another which is the same
15340 * thing as deleting a character from both goodword and badword.
15341 * Use a better score when there is only a case difference. */
15342 if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15343 score += SCORE_ICASE;
15344 else
15346 /* For a similar character use SCORE_SIMILAR. */
15347 if (slang != NULL
15348 && slang->sl_has_map
15349 && similar_chars(slang, gc, bc))
15350 score += SCORE_SIMILAR;
15351 else
15352 score += SCORE_SUBST;
15355 if (score < minscore)
15357 /* Do the substitution. */
15358 ++gi;
15359 ++bi;
15360 continue;
15363 pop:
15365 * Get here to try the next alternative, pop it from the stack.
15367 if (stackidx == 0) /* stack is empty, finished */
15368 break;
15370 /* pop an item from the stack */
15371 --stackidx;
15372 gi = stack[stackidx].goodi;
15373 bi = stack[stackidx].badi;
15374 score = stack[stackidx].score;
15377 /* When the score goes over "limit" it may actually be much higher.
15378 * Return a very large number to avoid going below the limit when giving a
15379 * bonus. */
15380 if (minscore > limit)
15381 return SCORE_MAXMAX;
15382 return minscore;
15384 #endif
15387 * ":spellinfo"
15389 /*ARGSUSED*/
15390 void
15391 ex_spellinfo(eap)
15392 exarg_T *eap;
15394 int lpi;
15395 langp_T *lp;
15396 char_u *p;
15398 if (no_spell_checking(curwin))
15399 return;
15401 msg_start();
15402 for (lpi = 0; lpi < curbuf->b_langp.ga_len && !got_int; ++lpi)
15404 lp = LANGP_ENTRY(curbuf->b_langp, lpi);
15405 msg_puts((char_u *)"file: ");
15406 msg_puts(lp->lp_slang->sl_fname);
15407 msg_putchar('\n');
15408 p = lp->lp_slang->sl_info;
15409 if (p != NULL)
15411 msg_puts(p);
15412 msg_putchar('\n');
15415 msg_end();
15418 #define DUMPFLAG_KEEPCASE 1 /* round 2: keep-case tree */
15419 #define DUMPFLAG_COUNT 2 /* include word count */
15420 #define DUMPFLAG_ICASE 4 /* ignore case when finding matches */
15421 #define DUMPFLAG_ONECAP 8 /* pattern starts with capital */
15422 #define DUMPFLAG_ALLCAP 16 /* pattern is all capitals */
15425 * ":spelldump"
15427 void
15428 ex_spelldump(eap)
15429 exarg_T *eap;
15431 buf_T *buf = curbuf;
15433 if (no_spell_checking(curwin))
15434 return;
15436 /* Create a new empty buffer by splitting the window. */
15437 do_cmdline_cmd((char_u *)"new");
15438 if (!bufempty() || !buf_valid(buf))
15439 return;
15441 spell_dump_compl(buf, NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0);
15443 /* Delete the empty line that we started with. */
15444 if (curbuf->b_ml.ml_line_count > 1)
15445 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
15447 redraw_later(NOT_VALID);
15451 * Go through all possible words and:
15452 * 1. When "pat" is NULL: dump a list of all words in the current buffer.
15453 * "ic" and "dir" are not used.
15454 * 2. When "pat" is not NULL: add matching words to insert mode completion.
15456 void
15457 spell_dump_compl(buf, pat, ic, dir, dumpflags_arg)
15458 buf_T *buf; /* buffer with spell checking */
15459 char_u *pat; /* leading part of the word */
15460 int ic; /* ignore case */
15461 int *dir; /* direction for adding matches */
15462 int dumpflags_arg; /* DUMPFLAG_* */
15464 langp_T *lp;
15465 slang_T *slang;
15466 idx_T arridx[MAXWLEN];
15467 int curi[MAXWLEN];
15468 char_u word[MAXWLEN];
15469 int c;
15470 char_u *byts;
15471 idx_T *idxs;
15472 linenr_T lnum = 0;
15473 int round;
15474 int depth;
15475 int n;
15476 int flags;
15477 char_u *region_names = NULL; /* region names being used */
15478 int do_region = TRUE; /* dump region names and numbers */
15479 char_u *p;
15480 int lpi;
15481 int dumpflags = dumpflags_arg;
15482 int patlen;
15484 /* When ignoring case or when the pattern starts with capital pass this on
15485 * to dump_word(). */
15486 if (pat != NULL)
15488 if (ic)
15489 dumpflags |= DUMPFLAG_ICASE;
15490 else
15492 n = captype(pat, NULL);
15493 if (n == WF_ONECAP)
15494 dumpflags |= DUMPFLAG_ONECAP;
15495 else if (n == WF_ALLCAP
15496 #ifdef FEAT_MBYTE
15497 && (int)STRLEN(pat) > mb_ptr2len(pat)
15498 #else
15499 && (int)STRLEN(pat) > 1
15500 #endif
15502 dumpflags |= DUMPFLAG_ALLCAP;
15506 /* Find out if we can support regions: All languages must support the same
15507 * regions or none at all. */
15508 for (lpi = 0; lpi < buf->b_langp.ga_len; ++lpi)
15510 lp = LANGP_ENTRY(buf->b_langp, lpi);
15511 p = lp->lp_slang->sl_regions;
15512 if (p[0] != 0)
15514 if (region_names == NULL) /* first language with regions */
15515 region_names = p;
15516 else if (STRCMP(region_names, p) != 0)
15518 do_region = FALSE; /* region names are different */
15519 break;
15524 if (do_region && region_names != NULL)
15526 if (pat == NULL)
15528 vim_snprintf((char *)IObuff, IOSIZE, "/regions=%s", region_names);
15529 ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
15532 else
15533 do_region = FALSE;
15536 * Loop over all files loaded for the entries in 'spelllang'.
15538 for (lpi = 0; lpi < buf->b_langp.ga_len; ++lpi)
15540 lp = LANGP_ENTRY(buf->b_langp, lpi);
15541 slang = lp->lp_slang;
15542 if (slang->sl_fbyts == NULL) /* reloading failed */
15543 continue;
15545 if (pat == NULL)
15547 vim_snprintf((char *)IObuff, IOSIZE, "# file: %s", slang->sl_fname);
15548 ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
15551 /* When matching with a pattern and there are no prefixes only use
15552 * parts of the tree that match "pat". */
15553 if (pat != NULL && slang->sl_pbyts == NULL)
15554 patlen = (int)STRLEN(pat);
15555 else
15556 patlen = -1;
15558 /* round 1: case-folded tree
15559 * round 2: keep-case tree */
15560 for (round = 1; round <= 2; ++round)
15562 if (round == 1)
15564 dumpflags &= ~DUMPFLAG_KEEPCASE;
15565 byts = slang->sl_fbyts;
15566 idxs = slang->sl_fidxs;
15568 else
15570 dumpflags |= DUMPFLAG_KEEPCASE;
15571 byts = slang->sl_kbyts;
15572 idxs = slang->sl_kidxs;
15574 if (byts == NULL)
15575 continue; /* array is empty */
15577 depth = 0;
15578 arridx[0] = 0;
15579 curi[0] = 1;
15580 while (depth >= 0 && !got_int
15581 && (pat == NULL || !compl_interrupted))
15583 if (curi[depth] > byts[arridx[depth]])
15585 /* Done all bytes at this node, go up one level. */
15586 --depth;
15587 line_breakcheck();
15588 ins_compl_check_keys(50);
15590 else
15592 /* Do one more byte at this node. */
15593 n = arridx[depth] + curi[depth];
15594 ++curi[depth];
15595 c = byts[n];
15596 if (c == 0)
15598 /* End of word, deal with the word.
15599 * Don't use keep-case words in the fold-case tree,
15600 * they will appear in the keep-case tree.
15601 * Only use the word when the region matches. */
15602 flags = (int)idxs[n];
15603 if ((round == 2 || (flags & WF_KEEPCAP) == 0)
15604 && (flags & WF_NEEDCOMP) == 0
15605 && (do_region
15606 || (flags & WF_REGION) == 0
15607 || (((unsigned)flags >> 16)
15608 & lp->lp_region) != 0))
15610 word[depth] = NUL;
15611 if (!do_region)
15612 flags &= ~WF_REGION;
15614 /* Dump the basic word if there is no prefix or
15615 * when it's the first one. */
15616 c = (unsigned)flags >> 24;
15617 if (c == 0 || curi[depth] == 2)
15619 dump_word(slang, word, pat, dir,
15620 dumpflags, flags, lnum);
15621 if (pat == NULL)
15622 ++lnum;
15625 /* Apply the prefix, if there is one. */
15626 if (c != 0)
15627 lnum = dump_prefixes(slang, word, pat, dir,
15628 dumpflags, flags, lnum);
15631 else
15633 /* Normal char, go one level deeper. */
15634 word[depth++] = c;
15635 arridx[depth] = idxs[n];
15636 curi[depth] = 1;
15638 /* Check if this characters matches with the pattern.
15639 * If not skip the whole tree below it.
15640 * Always ignore case here, dump_word() will check
15641 * proper case later. This isn't exactly right when
15642 * length changes for multi-byte characters with
15643 * ignore case... */
15644 if (depth <= patlen
15645 && MB_STRNICMP(word, pat, depth) != 0)
15646 --depth;
15655 * Dump one word: apply case modifications and append a line to the buffer.
15656 * When "lnum" is zero add insert mode completion.
15658 static void
15659 dump_word(slang, word, pat, dir, dumpflags, wordflags, lnum)
15660 slang_T *slang;
15661 char_u *word;
15662 char_u *pat;
15663 int *dir;
15664 int dumpflags;
15665 int wordflags;
15666 linenr_T lnum;
15668 int keepcap = FALSE;
15669 char_u *p;
15670 char_u *tw;
15671 char_u cword[MAXWLEN];
15672 char_u badword[MAXWLEN + 10];
15673 int i;
15674 int flags = wordflags;
15676 if (dumpflags & DUMPFLAG_ONECAP)
15677 flags |= WF_ONECAP;
15678 if (dumpflags & DUMPFLAG_ALLCAP)
15679 flags |= WF_ALLCAP;
15681 if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0)
15683 /* Need to fix case according to "flags". */
15684 make_case_word(word, cword, flags);
15685 p = cword;
15687 else
15689 p = word;
15690 if ((dumpflags & DUMPFLAG_KEEPCASE)
15691 && ((captype(word, NULL) & WF_KEEPCAP) == 0
15692 || (flags & WF_FIXCAP) != 0))
15693 keepcap = TRUE;
15695 tw = p;
15697 if (pat == NULL)
15699 /* Add flags and regions after a slash. */
15700 if ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap)
15702 STRCPY(badword, p);
15703 STRCAT(badword, "/");
15704 if (keepcap)
15705 STRCAT(badword, "=");
15706 if (flags & WF_BANNED)
15707 STRCAT(badword, "!");
15708 else if (flags & WF_RARE)
15709 STRCAT(badword, "?");
15710 if (flags & WF_REGION)
15711 for (i = 0; i < 7; ++i)
15712 if (flags & (0x10000 << i))
15713 sprintf((char *)badword + STRLEN(badword), "%d", i + 1);
15714 p = badword;
15717 if (dumpflags & DUMPFLAG_COUNT)
15719 hashitem_T *hi;
15721 /* Include the word count for ":spelldump!". */
15722 hi = hash_find(&slang->sl_wordcount, tw);
15723 if (!HASHITEM_EMPTY(hi))
15725 vim_snprintf((char *)IObuff, IOSIZE, "%s\t%d",
15726 tw, HI2WC(hi)->wc_count);
15727 p = IObuff;
15731 ml_append(lnum, p, (colnr_T)0, FALSE);
15733 else if (((dumpflags & DUMPFLAG_ICASE)
15734 ? MB_STRNICMP(p, pat, STRLEN(pat)) == 0
15735 : STRNCMP(p, pat, STRLEN(pat)) == 0)
15736 && ins_compl_add_infercase(p, (int)STRLEN(p),
15737 p_ic, NULL, *dir, 0) == OK)
15738 /* if dir was BACKWARD then honor it just once */
15739 *dir = FORWARD;
15743 * For ":spelldump": Find matching prefixes for "word". Prepend each to
15744 * "word" and append a line to the buffer.
15745 * When "lnum" is zero add insert mode completion.
15746 * Return the updated line number.
15748 static linenr_T
15749 dump_prefixes(slang, word, pat, dir, dumpflags, flags, startlnum)
15750 slang_T *slang;
15751 char_u *word; /* case-folded word */
15752 char_u *pat;
15753 int *dir;
15754 int dumpflags;
15755 int flags; /* flags with prefix ID */
15756 linenr_T startlnum;
15758 idx_T arridx[MAXWLEN];
15759 int curi[MAXWLEN];
15760 char_u prefix[MAXWLEN];
15761 char_u word_up[MAXWLEN];
15762 int has_word_up = FALSE;
15763 int c;
15764 char_u *byts;
15765 idx_T *idxs;
15766 linenr_T lnum = startlnum;
15767 int depth;
15768 int n;
15769 int len;
15770 int i;
15772 /* If the word starts with a lower-case letter make the word with an
15773 * upper-case letter in word_up[]. */
15774 c = PTR2CHAR(word);
15775 if (SPELL_TOUPPER(c) != c)
15777 onecap_copy(word, word_up, TRUE);
15778 has_word_up = TRUE;
15781 byts = slang->sl_pbyts;
15782 idxs = slang->sl_pidxs;
15783 if (byts != NULL) /* array not is empty */
15786 * Loop over all prefixes, building them byte-by-byte in prefix[].
15787 * When at the end of a prefix check that it supports "flags".
15789 depth = 0;
15790 arridx[0] = 0;
15791 curi[0] = 1;
15792 while (depth >= 0 && !got_int)
15794 n = arridx[depth];
15795 len = byts[n];
15796 if (curi[depth] > len)
15798 /* Done all bytes at this node, go up one level. */
15799 --depth;
15800 line_breakcheck();
15802 else
15804 /* Do one more byte at this node. */
15805 n += curi[depth];
15806 ++curi[depth];
15807 c = byts[n];
15808 if (c == 0)
15810 /* End of prefix, find out how many IDs there are. */
15811 for (i = 1; i < len; ++i)
15812 if (byts[n + i] != 0)
15813 break;
15814 curi[depth] += i - 1;
15816 c = valid_word_prefix(i, n, flags, word, slang, FALSE);
15817 if (c != 0)
15819 vim_strncpy(prefix + depth, word, MAXWLEN - depth - 1);
15820 dump_word(slang, prefix, pat, dir, dumpflags,
15821 (c & WF_RAREPFX) ? (flags | WF_RARE)
15822 : flags, lnum);
15823 if (lnum != 0)
15824 ++lnum;
15827 /* Check for prefix that matches the word when the
15828 * first letter is upper-case, but only if the prefix has
15829 * a condition. */
15830 if (has_word_up)
15832 c = valid_word_prefix(i, n, flags, word_up, slang,
15833 TRUE);
15834 if (c != 0)
15836 vim_strncpy(prefix + depth, word_up,
15837 MAXWLEN - depth - 1);
15838 dump_word(slang, prefix, pat, dir, dumpflags,
15839 (c & WF_RAREPFX) ? (flags | WF_RARE)
15840 : flags, lnum);
15841 if (lnum != 0)
15842 ++lnum;
15846 else
15848 /* Normal char, go one level deeper. */
15849 prefix[depth++] = c;
15850 arridx[depth] = idxs[n];
15851 curi[depth] = 1;
15857 return lnum;
15861 * Move "p" to the end of word "start".
15862 * Uses the spell-checking word characters.
15864 char_u *
15865 spell_to_word_end(start, buf)
15866 char_u *start;
15867 buf_T *buf;
15869 char_u *p = start;
15871 while (*p != NUL && spell_iswordp(p, buf))
15872 mb_ptr_adv(p);
15873 return p;
15876 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
15878 * For Insert mode completion CTRL-X s:
15879 * Find start of the word in front of column "startcol".
15880 * We don't check if it is badly spelled, with completion we can only change
15881 * the word in front of the cursor.
15882 * Returns the column number of the word.
15885 spell_word_start(startcol)
15886 int startcol;
15888 char_u *line;
15889 char_u *p;
15890 int col = 0;
15892 if (no_spell_checking(curwin))
15893 return startcol;
15895 /* Find a word character before "startcol". */
15896 line = ml_get_curline();
15897 for (p = line + startcol; p > line; )
15899 mb_ptr_back(line, p);
15900 if (spell_iswordp_nmw(p))
15901 break;
15904 /* Go back to start of the word. */
15905 while (p > line)
15907 col = (int)(p - line);
15908 mb_ptr_back(line, p);
15909 if (!spell_iswordp(p, curbuf))
15910 break;
15911 col = 0;
15914 return col;
15918 * Need to check for 'spellcapcheck' now, the word is removed before
15919 * expand_spelling() is called. Therefore the ugly global variable.
15921 static int spell_expand_need_cap;
15923 void
15924 spell_expand_check_cap(col)
15925 colnr_T col;
15927 spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col);
15931 * Get list of spelling suggestions.
15932 * Used for Insert mode completion CTRL-X ?.
15933 * Returns the number of matches. The matches are in "matchp[]", array of
15934 * allocated strings.
15936 /*ARGSUSED*/
15938 expand_spelling(lnum, col, pat, matchp)
15939 linenr_T lnum;
15940 int col;
15941 char_u *pat;
15942 char_u ***matchp;
15944 garray_T ga;
15946 spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, TRUE);
15947 *matchp = ga.ga_data;
15948 return ga.ga_len;
15950 #endif
15952 #endif /* FEAT_SPELL */