xref: /vim-8.2.3635/src/spell.c (revision abfa9efb)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * spell.c: code for spell checking
12  *
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).
16  *
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.
20  *
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".
33  *
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.
37  *
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.
43  *
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
49  *
50  * Matching involves checking the caps type: Onecap ALLCAP KeepCap.
51  *
52  * Why doesn't Vim use aspell/ispell/myspell/etc.?
53  * See ":help develop-spell".
54  */
55 
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
61 
62 /* Use SPELL_COMPRESS_ALLWAYS for debugging: compress the word tree after
63  * adding a word.  Only use it for small word lists! */
64 #if 0
65 # define SPELL_COMPRESS_ALLWAYS
66 #endif
67 
68 /* Use DEBUG_TRIEWALK to print the changes made in suggest_trie_walk() for a
69  * specific word. */
70 #if 0
71 # define DEBUG_TRIEWALK
72 #endif
73 
74 /*
75  * Use this to adjust the score after finding suggestions, based on the
76  * suggested word sounding like the bad word.  This is much faster than doing
77  * it for every possible suggestion.
78  * Disadvantage: When "the" is typed as "hte" it sounds quite different ("@"
79  * vs "ht") and goes down in the list.
80  * Used when 'spellsuggest' is set to "best".
81  */
82 #define RESCORE(word_score, sound_score) ((3 * word_score + sound_score) / 4)
83 
84 /*
85  * Do the opposite: based on a maximum end score and a known sound score,
86  * compute the maximum word score that can be used.
87  */
88 #define MAXSCORE(word_score, sound_score) ((4 * word_score - sound_score) / 3)
89 
90 /*
91  * Vim spell file format: <HEADER>
92  *			  <SECTIONS>
93  *			  <LWORDTREE>
94  *			  <KWORDTREE>
95  *			  <PREFIXTREE>
96  *
97  * <HEADER>: <fileID> <versionnr>
98  *
99  * <fileID>     8 bytes    "VIMspell"
100  * <versionnr>  1 byte	    VIMSPELLVERSION
101  *
102  *
103  * Sections make it possible to add information to the .spl file without
104  * making it incompatible with previous versions.  There are two kinds of
105  * sections:
106  * 1. Not essential for correct spell checking.  E.g. for making suggestions.
107  *    These are skipped when not supported.
108  * 2. Optional information, but essential for spell checking when present.
109  *    E.g. conditions for affixes.  When this section is present but not
110  *    supported an error message is given.
111  *
112  * <SECTIONS>: <section> ... <sectionend>
113  *
114  * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
115  *
116  * <sectionID>	  1 byte    number from 0 to 254 identifying the section
117  *
118  * <sectionflags> 1 byte    SNF_REQUIRED: this section is required for correct
119  *					    spell checking
120  *
121  * <sectionlen>   4 bytes   length of section contents, MSB first
122  *
123  * <sectionend>	  1 byte    SN_END
124  *
125  *
126  * sectionID == SN_INFO: <infotext>
127  * <infotext>	 N bytes    free format text with spell file info (version,
128  *			    website, etc)
129  *
130  * sectionID == SN_REGION: <regionname> ...
131  * <regionname>	 2 bytes    Up to 8 region names: ca, au, etc.  Lower case.
132  *			    First <regionname> is region 1.
133  *
134  * sectionID == SN_CHARFLAGS: <charflagslen> <charflags>
135  *				<folcharslen> <folchars>
136  * <charflagslen> 1 byte    Number of bytes in <charflags> (should be 128).
137  * <charflags>  N bytes     List of flags (first one is for character 128):
138  *			    0x01  word character	CF_WORD
139  *			    0x02  upper-case character	CF_UPPER
140  * <folcharslen>  2 bytes   Number of bytes in <folchars>.
141  * <folchars>     N bytes   Folded characters, first one is for character 128.
142  *
143  * sectionID == SN_MIDWORD: <midword>
144  * <midword>     N bytes    Characters that are word characters only when used
145  *			    in the middle of a word.
146  *
147  * sectionID == SN_PREFCOND: <prefcondcnt> <prefcond> ...
148  * <prefcondcnt> 2 bytes    Number of <prefcond> items following.
149  * <prefcond> : <condlen> <condstr>
150  * <condlen>	1 byte	    Length of <condstr>.
151  * <condstr>	N bytes	    Condition for the prefix.
152  *
153  * sectionID == SN_REP: <repcount> <rep> ...
154  * <repcount>	 2 bytes    number of <rep> items, MSB first.
155  * <rep> : <repfromlen> <repfrom> <reptolen> <repto>
156  * <repfromlen>	 1 byte	    length of <repfrom>
157  * <repfrom>	 N bytes    "from" part of replacement
158  * <reptolen>	 1 byte	    length of <repto>
159  * <repto>	 N bytes    "to" part of replacement
160  *
161  * sectionID == SN_REPSAL: <repcount> <rep> ...
162  *   just like SN_REP but for soundfolded words
163  *
164  * sectionID == SN_SAL: <salflags> <salcount> <sal> ...
165  * <salflags>	 1 byte	    flags for soundsalike conversion:
166  *			    SAL_F0LLOWUP
167  *			    SAL_COLLAPSE
168  *			    SAL_REM_ACCENTS
169  * <salcount>    2 bytes    number of <sal> items following
170  * <sal> : <salfromlen> <salfrom> <saltolen> <salto>
171  * <salfromlen>	 1 byte	    length of <salfrom>
172  * <salfrom>	 N bytes    "from" part of soundsalike
173  * <saltolen>	 1 byte	    length of <salto>
174  * <salto>	 N bytes    "to" part of soundsalike
175  *
176  * sectionID == SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
177  * <sofofromlen> 2 bytes    length of <sofofrom>
178  * <sofofrom>	 N bytes    "from" part of soundfold
179  * <sofotolen>	 2 bytes    length of <sofoto>
180  * <sofoto>	 N bytes    "to" part of soundfold
181  *
182  * sectionID == SN_SUGFILE: <timestamp>
183  * <timestamp>   8 bytes    time in seconds that must match with .sug file
184  *
185  * sectionID == SN_NOSPLITSUGS: nothing
186 	 *
187  * sectionID == SN_NOCOMPOUNDSUGS: nothing
188  *
189  * sectionID == SN_WORDS: <word> ...
190  * <word>	 N bytes    NUL terminated common word
191  *
192  * sectionID == SN_MAP: <mapstr>
193  * <mapstr>	 N bytes    String with sequences of similar characters,
194  *			    separated by slashes.
195  *
196  * sectionID == SN_COMPOUND: <compmax> <compminlen> <compsylmax> <compoptions>
197  *				<comppatcount> <comppattern> ... <compflags>
198  * <compmax>     1 byte	    Maximum nr of words in compound word.
199  * <compminlen>  1 byte	    Minimal word length for compounding.
200  * <compsylmax>  1 byte	    Maximum nr of syllables in compound word.
201  * <compoptions> 2 bytes    COMP_ flags.
202  * <comppatcount> 2 bytes   number of <comppattern> following
203  * <compflags>   N bytes    Flags from COMPOUNDRULE items, separated by
204  *			    slashes.
205  *
206  * <comppattern>: <comppatlen> <comppattext>
207  * <comppatlen>	 1 byte	    length of <comppattext>
208  * <comppattext> N bytes    end or begin chars from CHECKCOMPOUNDPATTERN
209  *
210  * sectionID == SN_NOBREAK: (empty, its presence is what matters)
211  *
212  * sectionID == SN_SYLLABLE: <syllable>
213  * <syllable>    N bytes    String from SYLLABLE item.
214  *
215  * <LWORDTREE>: <wordtree>
216  *
217  * <KWORDTREE>: <wordtree>
218  *
219  * <PREFIXTREE>: <wordtree>
220  *
221  *
222  * <wordtree>: <nodecount> <nodedata> ...
223  *
224  * <nodecount>	4 bytes	    Number of nodes following.  MSB first.
225  *
226  * <nodedata>: <siblingcount> <sibling> ...
227  *
228  * <siblingcount> 1 byte    Number of siblings in this node.  The siblings
229  *			    follow in sorted order.
230  *
231  * <sibling>: <byte> [ <nodeidx> <xbyte>
232  *		      | <flags> [<flags2>] [<region>] [<affixID>]
233  *		      | [<pflags>] <affixID> <prefcondnr> ]
234  *
235  * <byte>	1 byte	    Byte value of the sibling.  Special cases:
236  *			    BY_NOFLAGS: End of word without flags and for all
237  *					regions.
238  *					For PREFIXTREE <affixID> and
239  *					<prefcondnr> follow.
240  *			    BY_FLAGS:   End of word, <flags> follow.
241  *					For PREFIXTREE <pflags>, <affixID>
242  *					and <prefcondnr> follow.
243  *			    BY_FLAGS2:  End of word, <flags> and <flags2>
244  *					follow.  Not used in PREFIXTREE.
245  *			    BY_INDEX:   Child of sibling is shared, <nodeidx>
246  *					and <xbyte> follow.
247  *
248  * <nodeidx>	3 bytes	    Index of child for this sibling, MSB first.
249  *
250  * <xbyte>	1 byte	    byte value of the sibling.
251  *
252  * <flags>	1 byte	    bitmask of:
253  *			    WF_ALLCAP	word must have only capitals
254  *			    WF_ONECAP   first char of word must be capital
255  *			    WF_KEEPCAP	keep-case word
256  *			    WF_FIXCAP   keep-case word, all caps not allowed
257  *			    WF_RARE	rare word
258  *			    WF_BANNED	bad word
259  *			    WF_REGION	<region> follows
260  *			    WF_AFX	<affixID> follows
261  *
262  * <flags2>	1 byte	    Bitmask of:
263  *			    WF_HAS_AFF >> 8   word includes affix
264  *			    WF_NEEDCOMP >> 8  word only valid in compound
265  *			    WF_NOSUGGEST >> 8  word not used for suggestions
266  *			    WF_COMPROOT >> 8  word already a compound
267  *			    WF_NOCOMPBEF >> 8 no compounding before this word
268  *			    WF_NOCOMPAFT >> 8 no compounding after this word
269  *
270  * <pflags>	1 byte	    bitmask of:
271  *			    WFP_RARE	rare prefix
272  *			    WFP_NC	non-combining prefix
273  *			    WFP_UP	letter after prefix made upper case
274  *
275  * <region>	1 byte	    Bitmask for regions in which word is valid.  When
276  *			    omitted it's valid in all regions.
277  *			    Lowest bit is for region 1.
278  *
279  * <affixID>	1 byte	    ID of affix that can be used with this word.  In
280  *			    PREFIXTREE used for the required prefix ID.
281  *
282  * <prefcondnr>	2 bytes	    Prefix condition number, index in <prefcond> list
283  *			    from HEADER.
284  *
285  * All text characters are in 'encoding', but stored as single bytes.
286  */
287 
288 /*
289  * Vim .sug file format:  <SUGHEADER>
290  *			  <SUGWORDTREE>
291  *			  <SUGTABLE>
292  *
293  * <SUGHEADER>: <fileID> <versionnr> <timestamp>
294  *
295  * <fileID>     6 bytes     "VIMsug"
296  * <versionnr>  1 byte      VIMSUGVERSION
297  * <timestamp>  8 bytes     timestamp that must match with .spl file
298  *
299  *
300  * <SUGWORDTREE>: <wordtree>  (see above, no flags or region used)
301  *
302  *
303  * <SUGTABLE>: <sugwcount> <sugline> ...
304  *
305  * <sugwcount>	4 bytes	    number of <sugline> following
306  *
307  * <sugline>: <sugnr> ... NUL
308  *
309  * <sugnr>:     X bytes     word number that results in this soundfolded word,
310  *			    stored as an offset to the previous number in as
311  *			    few bytes as possible, see offset2bytes())
312  */
313 
314 #include "vim.h"
315 
316 #if defined(FEAT_SPELL) || defined(PROTO)
317 
318 #ifndef UNIX		/* it's in os_unix.h for Unix */
319 # include <time.h>	/* for time_t */
320 #endif
321 
322 #define MAXWLEN 254		/* 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.
325 				   Must be >= PFD_NOTSPECIAL. */
326 
327 /* Type used for indexes in the word tree need to be at least 4 bytes.  If int
328  * is 8 bytes we could use something smaller, but what? */
329 #if VIM_SIZEOF_INT > 3
330 typedef int idx_T;
331 #else
332 typedef long idx_T;
333 #endif
334 
335 #ifdef VMS
336 # define SPL_FNAME_TMPL  "%s_%s.spl"
337 # define SPL_FNAME_ADD   "_add."
338 # define SPL_FNAME_ASCII "_ascii."
339 #else
340 # define SPL_FNAME_TMPL  "%s.%s.spl"
341 # define SPL_FNAME_ADD   ".add."
342 # define SPL_FNAME_ASCII ".ascii."
343 #endif
344 
345 /* Flags used for a word.  Only the lowest byte can be used, the region byte
346  * comes above it. */
347 #define WF_REGION   0x01	/* region byte follows */
348 #define WF_ONECAP   0x02	/* word with one capital (or all capitals) */
349 #define WF_ALLCAP   0x04	/* word must be all capitals */
350 #define WF_RARE	    0x08	/* rare word */
351 #define WF_BANNED   0x10	/* bad word */
352 #define WF_AFX	    0x20	/* affix ID follows */
353 #define WF_FIXCAP   0x40	/* keep-case word, allcap not allowed */
354 #define WF_KEEPCAP  0x80	/* keep-case word */
355 
356 /* for <flags2>, shifted up one byte to be used in wn_flags */
357 #define WF_HAS_AFF  0x0100	/* word includes affix */
358 #define WF_NEEDCOMP 0x0200	/* word only valid in compound */
359 #define WF_NOSUGGEST 0x0400	/* word not to be suggested */
360 #define WF_COMPROOT 0x0800	/* already compounded word, COMPOUNDROOT */
361 #define WF_NOCOMPBEF 0x1000	/* no compounding before this word */
362 #define WF_NOCOMPAFT 0x2000	/* no compounding after this word */
363 
364 /* only used for su_badflags */
365 #define WF_MIXCAP   0x20	/* mix of upper and lower case: macaRONI */
366 
367 #define WF_CAPMASK (WF_ONECAP | WF_ALLCAP | WF_KEEPCAP | WF_FIXCAP)
368 
369 /* flags for <pflags> */
370 #define WFP_RARE	    0x01	/* rare prefix */
371 #define WFP_NC		    0x02	/* prefix is not combining */
372 #define WFP_UP		    0x04	/* to-upper prefix */
373 #define WFP_COMPPERMIT	    0x08	/* prefix with COMPOUNDPERMITFLAG */
374 #define WFP_COMPFORBID	    0x10	/* prefix with COMPOUNDFORBIDFLAG */
375 
376 /* Flags for postponed prefixes in "sl_pidxs".  Must be above affixID (one
377  * byte) and prefcondnr (two bytes). */
378 #define WF_RAREPFX  (WFP_RARE << 24)	/* rare postponed prefix */
379 #define WF_PFX_NC   (WFP_NC << 24)	/* non-combining postponed prefix */
380 #define WF_PFX_UP   (WFP_UP << 24)	/* to-upper postponed prefix */
381 #define WF_PFX_COMPPERMIT (WFP_COMPPERMIT << 24) /* postponed prefix with
382 						  * COMPOUNDPERMITFLAG */
383 #define WF_PFX_COMPFORBID (WFP_COMPFORBID << 24) /* postponed prefix with
384 						  * COMPOUNDFORBIDFLAG */
385 
386 
387 /* flags for <compoptions> */
388 #define COMP_CHECKDUP		1	/* CHECKCOMPOUNDDUP */
389 #define COMP_CHECKREP		2	/* CHECKCOMPOUNDREP */
390 #define COMP_CHECKCASE		4	/* CHECKCOMPOUNDCASE */
391 #define COMP_CHECKTRIPLE	8	/* CHECKCOMPOUNDTRIPLE */
392 
393 /* Special byte values for <byte>.  Some are only used in the tree for
394  * postponed prefixes, some only in the other trees.  This is a bit messy... */
395 #define BY_NOFLAGS	0	/* end of word without flags or region; for
396 				 * postponed prefix: no <pflags> */
397 #define BY_INDEX	1	/* child is shared, index follows */
398 #define BY_FLAGS	2	/* end of word, <flags> byte follows; for
399 				 * postponed prefix: <pflags> follows */
400 #define BY_FLAGS2	3	/* end of word, <flags> and <flags2> bytes
401 				 * follow; never used in prefix tree */
402 #define BY_SPECIAL  BY_FLAGS2	/* highest special byte value */
403 
404 /* Info from "REP", "REPSAL" and "SAL" entries in ".aff" file used in si_rep,
405  * si_repsal, sl_rep, and si_sal.  Not for sl_sal!
406  * One replacement: from "ft_from" to "ft_to". */
407 typedef struct fromto_S
408 {
409     char_u	*ft_from;
410     char_u	*ft_to;
411 } fromto_T;
412 
413 /* Info from "SAL" entries in ".aff" file used in sl_sal.
414  * The info is split for quick processing by spell_soundfold().
415  * Note that "sm_oneof" and "sm_rules" point into sm_lead. */
416 typedef struct salitem_S
417 {
418     char_u	*sm_lead;	/* leading letters */
419     int		sm_leadlen;	/* length of "sm_lead" */
420     char_u	*sm_oneof;	/* letters from () or NULL */
421     char_u	*sm_rules;	/* rules like ^, $, priority */
422     char_u	*sm_to;		/* replacement. */
423 #ifdef FEAT_MBYTE
424     int		*sm_lead_w;	/* wide character copy of "sm_lead" */
425     int		*sm_oneof_w;	/* wide character copy of "sm_oneof" */
426     int		*sm_to_w;	/* wide character copy of "sm_to" */
427 #endif
428 } salitem_T;
429 
430 #ifdef FEAT_MBYTE
431 typedef int salfirst_T;
432 #else
433 typedef short salfirst_T;
434 #endif
435 
436 /* Values for SP_*ERROR are negative, positive values are used by
437  * read_cnt_string(). */
438 #define	SP_TRUNCERROR	-1	/* spell file truncated error */
439 #define	SP_FORMERROR	-2	/* format error in spell file */
440 #define SP_OTHERERROR	-3	/* other error while reading spell file */
441 
442 /*
443  * Structure used to store words and other info for one language, loaded from
444  * a .spl file.
445  * The main access is through the tree in "sl_fbyts/sl_fidxs", storing the
446  * case-folded words.  "sl_kbyts/sl_kidxs" is for keep-case words.
447  *
448  * The "byts" array stores the possible bytes in each tree node, preceded by
449  * the number of possible bytes, sorted on byte value:
450  *	<len> <byte1> <byte2> ...
451  * The "idxs" array stores the index of the child node corresponding to the
452  * byte in "byts".
453  * Exception: when the byte is zero, the word may end here and "idxs" holds
454  * the flags, region mask and affixID for the word.  There may be several
455  * zeros in sequence for alternative flag/region/affixID combinations.
456  */
457 typedef struct slang_S slang_T;
458 struct slang_S
459 {
460     slang_T	*sl_next;	/* next language */
461     char_u	*sl_name;	/* language name "en", "en.rare", "nl", etc. */
462     char_u	*sl_fname;	/* name of .spl file */
463     int		sl_add;		/* TRUE if it's a .add file. */
464 
465     char_u	*sl_fbyts;	/* case-folded word bytes */
466     idx_T	*sl_fidxs;	/* case-folded word indexes */
467     char_u	*sl_kbyts;	/* keep-case word bytes */
468     idx_T	*sl_kidxs;	/* keep-case word indexes */
469     char_u	*sl_pbyts;	/* prefix tree word bytes */
470     idx_T	*sl_pidxs;	/* prefix tree word indexes */
471 
472     char_u	*sl_info;	/* infotext string or NULL */
473 
474     char_u	sl_regions[17];	/* table with up to 8 region names plus NUL */
475 
476     char_u	*sl_midword;	/* MIDWORD string or NULL */
477 
478     hashtab_T	sl_wordcount;	/* hashtable with word count, wordcount_T */
479 
480     int		sl_compmax;	/* COMPOUNDWORDMAX (default: MAXWLEN) */
481     int		sl_compminlen;	/* COMPOUNDMIN (default: 0) */
482     int		sl_compsylmax;	/* COMPOUNDSYLMAX (default: MAXWLEN) */
483     int		sl_compoptions;	/* COMP_* flags */
484     garray_T	sl_comppat;	/* CHECKCOMPOUNDPATTERN items */
485     regprog_T	*sl_compprog;	/* COMPOUNDRULE turned into a regexp progrm
486 				 * (NULL when no compounding) */
487     char_u	*sl_comprules;	/* all COMPOUNDRULE concatenated (or NULL) */
488     char_u	*sl_compstartflags; /* flags for first compound word */
489     char_u	*sl_compallflags; /* all flags for compound words */
490     char_u	sl_nobreak;	/* When TRUE: no spaces between words */
491     char_u	*sl_syllable;	/* SYLLABLE repeatable chars or NULL */
492     garray_T	sl_syl_items;	/* syllable items */
493 
494     int		sl_prefixcnt;	/* number of items in "sl_prefprog" */
495     regprog_T	**sl_prefprog;	/* table with regprogs for prefixes */
496 
497     garray_T	sl_rep;		/* list of fromto_T entries from REP lines */
498     short	sl_rep_first[256];  /* indexes where byte first appears, -1 if
499 				       there is none */
500     garray_T	sl_sal;		/* list of salitem_T entries from SAL lines */
501     salfirst_T	sl_sal_first[256];  /* indexes where byte first appears, -1 if
502 				       there is none */
503     int		sl_followup;	/* SAL followup */
504     int		sl_collapse;	/* SAL collapse_result */
505     int		sl_rem_accents;	/* SAL remove_accents */
506     int		sl_sofo;	/* SOFOFROM and SOFOTO instead of SAL items:
507 				 * "sl_sal_first" maps chars, when has_mbyte
508 				 * "sl_sal" is a list of wide char lists. */
509     garray_T	sl_repsal;	/* list of fromto_T entries from REPSAL lines */
510     short	sl_repsal_first[256];  /* sl_rep_first for REPSAL lines */
511     int		sl_nosplitsugs;	/* don't suggest splitting a word */
512     int		sl_nocompoundsugs; /* don't suggest compounding */
513 
514     /* Info from the .sug file.  Loaded on demand. */
515     time_t	sl_sugtime;	/* timestamp for .sug file */
516     char_u	*sl_sbyts;	/* soundfolded word bytes */
517     idx_T	*sl_sidxs;	/* soundfolded word indexes */
518     buf_T	*sl_sugbuf;	/* buffer with word number table */
519     int		sl_sugloaded;	/* TRUE when .sug file was loaded or failed to
520 				   load */
521 
522     int		sl_has_map;	/* TRUE if there is a MAP line */
523 #ifdef FEAT_MBYTE
524     hashtab_T	sl_map_hash;	/* MAP for multi-byte chars */
525     int		sl_map_array[256]; /* MAP for first 256 chars */
526 #else
527     char_u	sl_map_array[256]; /* MAP for first 256 chars */
528 #endif
529     hashtab_T	sl_sounddone;	/* table with soundfolded words that have
530 				   handled, see add_sound_suggest() */
531 };
532 
533 /* First language that is loaded, start of the linked list of loaded
534  * languages. */
535 static slang_T *first_lang = NULL;
536 
537 /* Flags used in .spl file for soundsalike flags. */
538 #define SAL_F0LLOWUP		1
539 #define SAL_COLLAPSE		2
540 #define SAL_REM_ACCENTS		4
541 
542 /*
543  * Structure used in "b_langp", filled from 'spelllang'.
544  */
545 typedef struct langp_S
546 {
547     slang_T	*lp_slang;	/* info for this language */
548     slang_T	*lp_sallang;	/* language used for sound folding or NULL */
549     slang_T	*lp_replang;	/* language used for REP items or NULL */
550     int		lp_region;	/* bitmask for region or REGION_ALL */
551 } langp_T;
552 
553 #define LANGP_ENTRY(ga, i)	(((langp_T *)(ga).ga_data) + (i))
554 
555 #define REGION_ALL 0xff		/* word valid in all regions */
556 
557 #define VIMSPELLMAGIC "VIMspell"  /* string at start of Vim spell file */
558 #define VIMSPELLMAGICL 8
559 #define VIMSPELLVERSION 50
560 
561 #define VIMSUGMAGIC "VIMsug"	/* string at start of Vim .sug file */
562 #define VIMSUGMAGICL 6
563 #define VIMSUGVERSION 1
564 
565 /* Section IDs.  Only renumber them when VIMSPELLVERSION changes! */
566 #define SN_REGION	0	/* <regionname> section */
567 #define SN_CHARFLAGS	1	/* charflags section */
568 #define SN_MIDWORD	2	/* <midword> section */
569 #define SN_PREFCOND	3	/* <prefcond> section */
570 #define SN_REP		4	/* REP items section */
571 #define SN_SAL		5	/* SAL items section */
572 #define SN_SOFO		6	/* soundfolding section */
573 #define SN_MAP		7	/* MAP items section */
574 #define SN_COMPOUND	8	/* compound words section */
575 #define SN_SYLLABLE	9	/* syllable section */
576 #define SN_NOBREAK	10	/* NOBREAK section */
577 #define SN_SUGFILE	11	/* timestamp for .sug file */
578 #define SN_REPSAL	12	/* REPSAL items section */
579 #define SN_WORDS	13	/* common words */
580 #define SN_NOSPLITSUGS	14	/* don't split word for suggestions */
581 #define SN_INFO		15	/* info section */
582 #define SN_NOCOMPOUNDSUGS 16	/* don't compound for suggestions */
583 #define SN_END		255	/* end of sections */
584 
585 #define SNF_REQUIRED	1	/* <sectionflags>: required section */
586 
587 /* Result values.  Lower number is accepted over higher one. */
588 #define SP_BANNED	-1
589 #define SP_OK		0
590 #define SP_RARE		1
591 #define SP_LOCAL	2
592 #define SP_BAD		3
593 
594 /* file used for "zG" and "zW" */
595 static char_u	*int_wordlist = NULL;
596 
597 typedef struct wordcount_S
598 {
599     short_u	wc_count;	    /* nr of times word was seen */
600     char_u	wc_word[1];	    /* word, actually longer */
601 } wordcount_T;
602 
603 static wordcount_T dumwc;
604 #define WC_KEY_OFF  (unsigned)(dumwc.wc_word - (char_u *)&dumwc)
605 #define HI2WC(hi)     ((wordcount_T *)((hi)->hi_key - WC_KEY_OFF))
606 #define MAXWORDCOUNT 0xffff
607 
608 /*
609  * Information used when looking for suggestions.
610  */
611 typedef struct suginfo_S
612 {
613     garray_T	su_ga;		    /* suggestions, contains "suggest_T" */
614     int		su_maxcount;	    /* max. number of suggestions displayed */
615     int		su_maxscore;	    /* maximum score for adding to su_ga */
616     int		su_sfmaxscore;	    /* idem, for when doing soundfold words */
617     garray_T	su_sga;		    /* like su_ga, sound-folded scoring */
618     char_u	*su_badptr;	    /* start of bad word in line */
619     int		su_badlen;	    /* length of detected bad word in line */
620     int		su_badflags;	    /* caps flags for bad word */
621     char_u	su_badword[MAXWLEN]; /* bad word truncated at su_badlen */
622     char_u	su_fbadword[MAXWLEN]; /* su_badword case-folded */
623     char_u	su_sal_badword[MAXWLEN]; /* su_badword soundfolded */
624     hashtab_T	su_banned;	    /* table with banned words */
625     slang_T	*su_sallang;	    /* default language for sound folding */
626 } suginfo_T;
627 
628 /* One word suggestion.  Used in "si_ga". */
629 typedef struct suggest_S
630 {
631     char_u	*st_word;	/* suggested word, allocated string */
632     int		st_wordlen;	/* STRLEN(st_word) */
633     int		st_orglen;	/* length of replaced text */
634     int		st_score;	/* lower is better */
635     int		st_altscore;	/* used when st_score compares equal */
636     int		st_salscore;	/* st_score is for soundalike */
637     int		st_had_bonus;	/* bonus already included in score */
638     slang_T	*st_slang;	/* language used for sound folding */
639 } suggest_T;
640 
641 #define SUG(ga, i) (((suggest_T *)(ga).ga_data)[i])
642 
643 /* TRUE if a word appears in the list of banned words.  */
644 #define WAS_BANNED(su, word) (!HASHITEM_EMPTY(hash_find(&su->su_banned, word)))
645 
646 /* Number of suggestions kept when cleaning up.  We need to keep more than
647  * what is displayed, because when rescore_suggestions() is called the score
648  * may change and wrong suggestions may be removed later. */
649 #define SUG_CLEAN_COUNT(su)    ((su)->su_maxcount < 130 ? 150 : (su)->su_maxcount + 20)
650 
651 /* Threshold for sorting and cleaning up suggestions.  Don't want to keep lots
652  * of suggestions that are not going to be displayed. */
653 #define SUG_MAX_COUNT(su)	(SUG_CLEAN_COUNT(su) + 50)
654 
655 /* score for various changes */
656 #define SCORE_SPLIT	149	/* split bad word */
657 #define SCORE_SPLIT_NO	249	/* split bad word with NOSPLITSUGS */
658 #define SCORE_ICASE	52	/* slightly different case */
659 #define SCORE_REGION	200	/* word is for different region */
660 #define SCORE_RARE	180	/* rare word */
661 #define SCORE_SWAP	75	/* swap two characters */
662 #define SCORE_SWAP3	110	/* swap two characters in three */
663 #define SCORE_REP	65	/* REP replacement */
664 #define SCORE_SUBST	93	/* substitute a character */
665 #define SCORE_SIMILAR	33	/* substitute a similar character */
666 #define SCORE_SUBCOMP	33	/* substitute a composing character */
667 #define SCORE_DEL	94	/* delete a character */
668 #define SCORE_DELDUP	66	/* delete a duplicated character */
669 #define SCORE_DELCOMP	28	/* delete a composing character */
670 #define SCORE_INS	96	/* insert a character */
671 #define SCORE_INSDUP	67	/* insert a duplicate character */
672 #define SCORE_INSCOMP	30	/* insert a composing character */
673 #define SCORE_NONWORD	103	/* change non-word to word char */
674 
675 #define SCORE_FILE	30	/* suggestion from a file */
676 #define SCORE_MAXINIT	350	/* Initial maximum score: higher == slower.
677 				 * 350 allows for about three changes. */
678 
679 #define SCORE_COMMON1	30	/* subtracted for words seen before */
680 #define SCORE_COMMON2	40	/* subtracted for words often seen */
681 #define SCORE_COMMON3	50	/* subtracted for words very often seen */
682 #define SCORE_THRES2	10	/* word count threshold for COMMON2 */
683 #define SCORE_THRES3	100	/* word count threshold for COMMON3 */
684 
685 /* When trying changed soundfold words it becomes slow when trying more than
686  * two changes.  With less then two changes it's slightly faster but we miss a
687  * few good suggestions.  In rare cases we need to try three of four changes.
688  */
689 #define SCORE_SFMAX1	200	/* maximum score for first try */
690 #define SCORE_SFMAX2	300	/* maximum score for second try */
691 #define SCORE_SFMAX3	400	/* maximum score for third try */
692 
693 #define SCORE_BIG	SCORE_INS * 3	/* big difference */
694 #define SCORE_MAXMAX	999999		/* accept any score */
695 #define SCORE_LIMITMAX	350		/* for spell_edit_score_limit() */
696 
697 /* for spell_edit_score_limit() we need to know the minimum value of
698  * SCORE_ICASE, SCORE_SWAP, SCORE_DEL, SCORE_SIMILAR and SCORE_INS */
699 #define SCORE_EDIT_MIN	SCORE_SIMILAR
700 
701 /*
702  * Structure to store info for word matching.
703  */
704 typedef struct matchinf_S
705 {
706     langp_T	*mi_lp;			/* info for language and region */
707 
708     /* pointers to original text to be checked */
709     char_u	*mi_word;		/* start of word being checked */
710     char_u	*mi_end;		/* end of matching word so far */
711     char_u	*mi_fend;		/* next char to be added to mi_fword */
712     char_u	*mi_cend;		/* char after what was used for
713 					   mi_capflags */
714 
715     /* case-folded text */
716     char_u	mi_fword[MAXWLEN + 1];	/* mi_word case-folded */
717     int		mi_fwordlen;		/* nr of valid bytes in mi_fword */
718 
719     /* for when checking word after a prefix */
720     int		mi_prefarridx;		/* index in sl_pidxs with list of
721 					   affixID/condition */
722     int		mi_prefcnt;		/* number of entries at mi_prefarridx */
723     int		mi_prefixlen;		/* byte length of prefix */
724 #ifdef FEAT_MBYTE
725     int		mi_cprefixlen;		/* byte length of prefix in original
726 					   case */
727 #else
728 # define mi_cprefixlen mi_prefixlen	/* it's the same value */
729 #endif
730 
731     /* for when checking a compound word */
732     int		mi_compoff;		/* start of following word offset */
733     char_u	mi_compflags[MAXWLEN];	/* flags for compound words used */
734     int		mi_complen;		/* nr of compound words used */
735     int		mi_compextra;		/* nr of COMPOUNDROOT words */
736 
737     /* others */
738     int		mi_result;		/* result so far: SP_BAD, SP_OK, etc. */
739     int		mi_capflags;		/* WF_ONECAP WF_ALLCAP WF_KEEPCAP */
740     win_T	*mi_win;		/* buffer being checked */
741 
742     /* for NOBREAK */
743     int		mi_result2;		/* "mi_resul" without following word */
744     char_u	*mi_end2;		/* "mi_end" without following word */
745 } matchinf_T;
746 
747 /*
748  * The tables used for recognizing word characters according to spelling.
749  * These are only used for the first 256 characters of 'encoding'.
750  */
751 typedef struct spelltab_S
752 {
753     char_u  st_isw[256];	/* flags: is word char */
754     char_u  st_isu[256];	/* flags: is uppercase char */
755     char_u  st_fold[256];	/* chars: folded case */
756     char_u  st_upper[256];	/* chars: upper case */
757 } spelltab_T;
758 
759 static spelltab_T   spelltab;
760 static int	    did_set_spelltab;
761 
762 #define CF_WORD		0x01
763 #define CF_UPPER	0x02
764 
765 static void clear_spell_chartab __ARGS((spelltab_T *sp));
766 static int set_spell_finish __ARGS((spelltab_T	*new_st));
767 static int spell_iswordp __ARGS((char_u *p, win_T *wp));
768 static int spell_iswordp_nmw __ARGS((char_u *p, win_T *wp));
769 #ifdef FEAT_MBYTE
770 static int spell_mb_isword_class __ARGS((int cl, win_T *wp));
771 static int spell_iswordp_w __ARGS((int *p, win_T *wp));
772 #endif
773 static int write_spell_prefcond __ARGS((FILE *fd, garray_T *gap));
774 
775 /*
776  * For finding suggestions: At each node in the tree these states are tried:
777  */
778 typedef enum
779 {
780     STATE_START = 0,	/* At start of node check for NUL bytes (goodword
781 			 * ends); if badword ends there is a match, otherwise
782 			 * try splitting word. */
783     STATE_NOPREFIX,	/* try without prefix */
784     STATE_SPLITUNDO,	/* Undo splitting. */
785     STATE_ENDNUL,	/* Past NUL bytes at start of the node. */
786     STATE_PLAIN,	/* Use each byte of the node. */
787     STATE_DEL,		/* Delete a byte from the bad word. */
788     STATE_INS_PREP,	/* Prepare for inserting bytes. */
789     STATE_INS,		/* Insert a byte in the bad word. */
790     STATE_SWAP,		/* Swap two bytes. */
791     STATE_UNSWAP,	/* Undo swap two characters. */
792     STATE_SWAP3,	/* Swap two characters over three. */
793     STATE_UNSWAP3,	/* Undo Swap two characters over three. */
794     STATE_UNROT3L,	/* Undo rotate three characters left */
795     STATE_UNROT3R,	/* Undo rotate three characters right */
796     STATE_REP_INI,	/* Prepare for using REP items. */
797     STATE_REP,		/* Use matching REP items from the .aff file. */
798     STATE_REP_UNDO,	/* Undo a REP item replacement. */
799     STATE_FINAL		/* End of this node. */
800 } state_T;
801 
802 /*
803  * Struct to keep the state at each level in suggest_try_change().
804  */
805 typedef struct trystate_S
806 {
807     state_T	ts_state;	/* state at this level, STATE_ */
808     int		ts_score;	/* score */
809     idx_T	ts_arridx;	/* index in tree array, start of node */
810     short	ts_curi;	/* index in list of child nodes */
811     char_u	ts_fidx;	/* index in fword[], case-folded bad word */
812     char_u	ts_fidxtry;	/* ts_fidx at which bytes may be changed */
813     char_u	ts_twordlen;	/* valid length of tword[] */
814     char_u	ts_prefixdepth;	/* stack depth for end of prefix or
815 				 * PFD_PREFIXTREE or PFD_NOPREFIX */
816     char_u	ts_flags;	/* TSF_ flags */
817 #ifdef FEAT_MBYTE
818     char_u	ts_tcharlen;	/* number of bytes in tword character */
819     char_u	ts_tcharidx;	/* current byte index in tword character */
820     char_u	ts_isdiff;	/* DIFF_ values */
821     char_u	ts_fcharstart;	/* index in fword where badword char started */
822 #endif
823     char_u	ts_prewordlen;	/* length of word in "preword[]" */
824     char_u	ts_splitoff;	/* index in "tword" after last split */
825     char_u	ts_splitfidx;	/* "ts_fidx" at word split */
826     char_u	ts_complen;	/* nr of compound words used */
827     char_u	ts_compsplit;	/* index for "compflags" where word was spit */
828     char_u	ts_save_badflags;   /* su_badflags saved here */
829     char_u	ts_delidx;	/* index in fword for char that was deleted,
830 				   valid when "ts_flags" has TSF_DIDDEL */
831 } trystate_T;
832 
833 /* values for ts_isdiff */
834 #define DIFF_NONE	0	/* no different byte (yet) */
835 #define DIFF_YES	1	/* different byte found */
836 #define DIFF_INSERT	2	/* inserting character */
837 
838 /* values for ts_flags */
839 #define TSF_PREFIXOK	1	/* already checked that prefix is OK */
840 #define TSF_DIDSPLIT	2	/* tried split at this point */
841 #define TSF_DIDDEL	4	/* did a delete, "ts_delidx" has index */
842 
843 /* special values ts_prefixdepth */
844 #define PFD_NOPREFIX	0xff	/* not using prefixes */
845 #define PFD_PREFIXTREE	0xfe	/* walking through the prefix tree */
846 #define PFD_NOTSPECIAL	0xfd	/* highest value that's not special */
847 
848 /* mode values for find_word */
849 #define FIND_FOLDWORD	    0	/* find word case-folded */
850 #define FIND_KEEPWORD	    1	/* find keep-case word */
851 #define FIND_PREFIX	    2	/* find word after prefix */
852 #define FIND_COMPOUND	    3	/* find case-folded compound word */
853 #define FIND_KEEPCOMPOUND   4	/* find keep-case compound word */
854 
855 static slang_T *slang_alloc __ARGS((char_u *lang));
856 static void slang_free __ARGS((slang_T *lp));
857 static void slang_clear __ARGS((slang_T *lp));
858 static void slang_clear_sug __ARGS((slang_T *lp));
859 static void find_word __ARGS((matchinf_T *mip, int mode));
860 static int match_checkcompoundpattern __ARGS((char_u *ptr, int wlen, garray_T *gap));
861 static int can_compound __ARGS((slang_T *slang, char_u *word, char_u *flags));
862 static int can_be_compound __ARGS((trystate_T *sp, slang_T *slang, char_u *compflags, int flag));
863 static int match_compoundrule __ARGS((slang_T *slang, char_u *compflags));
864 static int valid_word_prefix __ARGS((int totprefcnt, int arridx, int flags, char_u *word, slang_T *slang, int cond_req));
865 static void find_prefix __ARGS((matchinf_T *mip, int mode));
866 static int fold_more __ARGS((matchinf_T *mip));
867 static int spell_valid_case __ARGS((int wordflags, int treeflags));
868 static int no_spell_checking __ARGS((win_T *wp));
869 static void spell_load_lang __ARGS((char_u *lang));
870 static char_u *spell_enc __ARGS((void));
871 static void int_wordlist_spl __ARGS((char_u *fname));
872 static void spell_load_cb __ARGS((char_u *fname, void *cookie));
873 static slang_T *spell_load_file __ARGS((char_u *fname, char_u *lang, slang_T *old_lp, int silent));
874 static char_u *read_cnt_string __ARGS((FILE *fd, int cnt_bytes, int *lenp));
875 static int read_region_section __ARGS((FILE *fd, slang_T *slang, int len));
876 static int read_charflags_section __ARGS((FILE *fd));
877 static int read_prefcond_section __ARGS((FILE *fd, slang_T *lp));
878 static int read_rep_section __ARGS((FILE *fd, garray_T *gap, short *first));
879 static int read_sal_section __ARGS((FILE *fd, slang_T *slang));
880 static int read_words_section __ARGS((FILE *fd, slang_T *lp, int len));
881 static void count_common_word __ARGS((slang_T *lp, char_u *word, int len, int count));
882 static int score_wordcount_adj __ARGS((slang_T *slang, int score, char_u *word, int split));
883 static int read_sofo_section __ARGS((FILE *fd, slang_T *slang));
884 static int read_compound __ARGS((FILE *fd, slang_T *slang, int len));
885 static int byte_in_str __ARGS((char_u *str, int byte));
886 static int init_syl_tab __ARGS((slang_T *slang));
887 static int count_syllables __ARGS((slang_T *slang, char_u *word));
888 static int set_sofo __ARGS((slang_T *lp, char_u *from, char_u *to));
889 static void set_sal_first __ARGS((slang_T *lp));
890 #ifdef FEAT_MBYTE
891 static int *mb_str2wide __ARGS((char_u *s));
892 #endif
893 static int spell_read_tree __ARGS((FILE *fd, char_u **bytsp, idx_T **idxsp, int prefixtree, int prefixcnt));
894 static idx_T read_tree_node __ARGS((FILE *fd, char_u *byts, idx_T *idxs, int maxidx, idx_T startidx, int prefixtree, int maxprefcondnr));
895 static void clear_midword __ARGS((win_T *buf));
896 static void use_midword __ARGS((slang_T *lp, win_T *buf));
897 static int find_region __ARGS((char_u *rp, char_u *region));
898 static int captype __ARGS((char_u *word, char_u *end));
899 static int badword_captype __ARGS((char_u *word, char_u *end));
900 static void spell_reload_one __ARGS((char_u *fname, int added_word));
901 static void set_spell_charflags __ARGS((char_u *flags, int cnt, char_u *upp));
902 static int set_spell_chartab __ARGS((char_u *fol, char_u *low, char_u *upp));
903 static int spell_casefold __ARGS((char_u *p, int len, char_u *buf, int buflen));
904 static int check_need_cap __ARGS((linenr_T lnum, colnr_T col));
905 static void spell_find_suggest __ARGS((char_u *badptr, int badlen, suginfo_T *su, int maxcount, int banbadword, int need_cap, int interactive));
906 #ifdef FEAT_EVAL
907 static void spell_suggest_expr __ARGS((suginfo_T *su, char_u *expr));
908 #endif
909 static void spell_suggest_file __ARGS((suginfo_T *su, char_u *fname));
910 static void spell_suggest_intern __ARGS((suginfo_T *su, int interactive));
911 static void suggest_load_files __ARGS((void));
912 static void tree_count_words __ARGS((char_u *byts, idx_T *idxs));
913 static void spell_find_cleanup __ARGS((suginfo_T *su));
914 static void onecap_copy __ARGS((char_u *word, char_u *wcopy, int upper));
915 static void allcap_copy __ARGS((char_u *word, char_u *wcopy));
916 static void suggest_try_special __ARGS((suginfo_T *su));
917 static void suggest_try_change __ARGS((suginfo_T *su));
918 static void suggest_trie_walk __ARGS((suginfo_T *su, langp_T *lp, char_u *fword, int soundfold));
919 static void go_deeper __ARGS((trystate_T *stack, int depth, int score_add));
920 #ifdef FEAT_MBYTE
921 static int nofold_len __ARGS((char_u *fword, int flen, char_u *word));
922 #endif
923 static void find_keepcap_word __ARGS((slang_T *slang, char_u *fword, char_u *kword));
924 static void score_comp_sal __ARGS((suginfo_T *su));
925 static void score_combine __ARGS((suginfo_T *su));
926 static int stp_sal_score __ARGS((suggest_T *stp, suginfo_T *su, slang_T *slang, char_u *badsound));
927 static void suggest_try_soundalike_prep __ARGS((void));
928 static void suggest_try_soundalike __ARGS((suginfo_T *su));
929 static void suggest_try_soundalike_finish __ARGS((void));
930 static void add_sound_suggest __ARGS((suginfo_T *su, char_u *goodword, int score, langp_T *lp));
931 static int soundfold_find __ARGS((slang_T *slang, char_u *word));
932 static void make_case_word __ARGS((char_u *fword, char_u *cword, int flags));
933 static void set_map_str __ARGS((slang_T *lp, char_u *map));
934 static int similar_chars __ARGS((slang_T *slang, int c1, int c2));
935 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));
936 static void check_suggestions __ARGS((suginfo_T *su, garray_T *gap));
937 static void add_banned __ARGS((suginfo_T *su, char_u *word));
938 static void rescore_suggestions __ARGS((suginfo_T *su));
939 static void rescore_one __ARGS((suginfo_T *su, suggest_T *stp));
940 static int cleanup_suggestions __ARGS((garray_T *gap, int maxscore, int keep));
941 static void spell_soundfold __ARGS((slang_T *slang, char_u *inword, int folded, char_u *res));
942 static void spell_soundfold_sofo __ARGS((slang_T *slang, char_u *inword, char_u *res));
943 static void spell_soundfold_sal __ARGS((slang_T *slang, char_u *inword, char_u *res));
944 #ifdef FEAT_MBYTE
945 static void spell_soundfold_wsal __ARGS((slang_T *slang, char_u *inword, char_u *res));
946 #endif
947 static int soundalike_score __ARGS((char_u *goodsound, char_u *badsound));
948 static int spell_edit_score __ARGS((slang_T *slang, char_u *badword, char_u *goodword));
949 static int spell_edit_score_limit __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit));
950 #ifdef FEAT_MBYTE
951 static int spell_edit_score_limit_w __ARGS((slang_T *slang, char_u *badword, char_u *goodword, int limit));
952 #endif
953 static void dump_word __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T lnum));
954 static linenr_T dump_prefixes __ARGS((slang_T *slang, char_u *word, char_u *pat, int *dir, int round, int flags, linenr_T startlnum));
955 static buf_T *open_spellbuf __ARGS((void));
956 static void close_spellbuf __ARGS((buf_T *buf));
957 
958 /*
959  * Use our own character-case definitions, because the current locale may
960  * differ from what the .spl file uses.
961  * These must not be called with negative number!
962  */
963 #ifndef FEAT_MBYTE
964 /* Non-multi-byte implementation. */
965 # define SPELL_TOFOLD(c) ((c) < 256 ? (int)spelltab.st_fold[c] : (c))
966 # define SPELL_TOUPPER(c) ((c) < 256 ? (int)spelltab.st_upper[c] : (c))
967 # define SPELL_ISUPPER(c) ((c) < 256 ? spelltab.st_isu[c] : FALSE)
968 #else
969 # if defined(HAVE_WCHAR_H)
970 #  include <wchar.h>	    /* for towupper() and towlower() */
971 # endif
972 /* Multi-byte implementation.  For Unicode we can call utf_*(), but don't do
973  * that for ASCII, because we don't want to use 'casemap' here.  Otherwise use
974  * the "w" library function for characters above 255 if available. */
975 # ifdef HAVE_TOWLOWER
976 #  define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \
977 	    : (c) < 256 ? (int)spelltab.st_fold[c] : (int)towlower(c))
978 # else
979 #  define SPELL_TOFOLD(c) (enc_utf8 && (c) >= 128 ? utf_fold(c) \
980 	    : (c) < 256 ? (int)spelltab.st_fold[c] : (c))
981 # endif
982 
983 # ifdef HAVE_TOWUPPER
984 #  define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \
985 	    : (c) < 256 ? (int)spelltab.st_upper[c] : (int)towupper(c))
986 # else
987 #  define SPELL_TOUPPER(c) (enc_utf8 && (c) >= 128 ? utf_toupper(c) \
988 	    : (c) < 256 ? (int)spelltab.st_upper[c] : (c))
989 # endif
990 
991 # ifdef HAVE_ISWUPPER
992 #  define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \
993 	    : (c) < 256 ? spelltab.st_isu[c] : iswupper(c))
994 # else
995 #  define SPELL_ISUPPER(c) (enc_utf8 && (c) >= 128 ? utf_isupper(c) \
996 	    : (c) < 256 ? spelltab.st_isu[c] : (FALSE))
997 # endif
998 #endif
999 
1000 
1001 static char *e_format = N_("E759: Format error in spell file");
1002 static char *e_spell_trunc = N_("E758: Truncated spell file");
1003 static char *e_afftrailing = N_("Trailing text in %s line %d: %s");
1004 static char *e_affname = N_("Affix name too long in %s line %d: %s");
1005 static char *e_affform = N_("E761: Format error in affix file FOL, LOW or UPP");
1006 static char *e_affrange = N_("E762: Character in FOL, LOW or UPP is out of range");
1007 static char *msg_compressing = N_("Compressing word tree...");
1008 
1009 /* Remember what "z?" replaced. */
1010 static char_u	*repl_from = NULL;
1011 static char_u	*repl_to = NULL;
1012 
1013 /*
1014  * Main spell-checking function.
1015  * "ptr" points to a character that could be the start of a word.
1016  * "*attrp" is set to the highlight index for a badly spelled word.  For a
1017  * non-word or when it's OK it remains unchanged.
1018  * This must only be called when 'spelllang' is not empty.
1019  *
1020  * "capcol" is used to check for a Capitalised word after the end of a
1021  * sentence.  If it's zero then perform the check.  Return the column where to
1022  * check next, or -1 when no sentence end was found.  If it's NULL then don't
1023  * worry.
1024  *
1025  * Returns the length of the word in bytes, also when it's OK, so that the
1026  * caller can skip over the word.
1027  */
1028     int
1029 spell_check(wp, ptr, attrp, capcol, docount)
1030     win_T	*wp;		/* current window */
1031     char_u	*ptr;
1032     hlf_T	*attrp;
1033     int		*capcol;	/* column to check for Capital */
1034     int		docount;	/* count good words */
1035 {
1036     matchinf_T	mi;		/* Most things are put in "mi" so that it can
1037 				   be passed to functions quickly. */
1038     int		nrlen = 0;	/* found a number first */
1039     int		c;
1040     int		wrongcaplen = 0;
1041     int		lpi;
1042     int		count_word = docount;
1043 
1044     /* A word never starts at a space or a control character.  Return quickly
1045      * then, skipping over the character. */
1046     if (*ptr <= ' ')
1047 	return 1;
1048 
1049     /* Return here when loading language files failed. */
1050     if (wp->w_s->b_langp.ga_len == 0)
1051 	return 1;
1052 
1053     vim_memset(&mi, 0, sizeof(matchinf_T));
1054 
1055     /* A number is always OK.  Also skip hexadecimal numbers 0xFF99 and
1056      * 0X99FF.  But always do check spelling to find "3GPP" and "11
1057      * julifeest". */
1058     if (*ptr >= '0' && *ptr <= '9')
1059     {
1060 	if (*ptr == '0' && (ptr[1] == 'b' || ptr[1] == 'B'))
1061 	    mi.mi_end = skipbin(ptr + 2);
1062 	else if (*ptr == '0' && (ptr[1] == 'x' || ptr[1] == 'X'))
1063 	    mi.mi_end = skiphex(ptr + 2);
1064 	else
1065 	    mi.mi_end = skipdigits(ptr);
1066 	nrlen = (int)(mi.mi_end - ptr);
1067     }
1068 
1069     /* Find the normal end of the word (until the next non-word character). */
1070     mi.mi_word = ptr;
1071     mi.mi_fend = ptr;
1072     if (spell_iswordp(mi.mi_fend, wp))
1073     {
1074 	do
1075 	{
1076 	    mb_ptr_adv(mi.mi_fend);
1077 	} while (*mi.mi_fend != NUL && spell_iswordp(mi.mi_fend, wp));
1078 
1079 	if (capcol != NULL && *capcol == 0 && wp->w_s->b_cap_prog != NULL)
1080 	{
1081 	    /* Check word starting with capital letter. */
1082 	    c = PTR2CHAR(ptr);
1083 	    if (!SPELL_ISUPPER(c))
1084 		wrongcaplen = (int)(mi.mi_fend - ptr);
1085 	}
1086     }
1087     if (capcol != NULL)
1088 	*capcol = -1;
1089 
1090     /* We always use the characters up to the next non-word character,
1091      * also for bad words. */
1092     mi.mi_end = mi.mi_fend;
1093 
1094     /* Check caps type later. */
1095     mi.mi_capflags = 0;
1096     mi.mi_cend = NULL;
1097     mi.mi_win = wp;
1098 
1099     /* case-fold the word with one non-word character, so that we can check
1100      * for the word end. */
1101     if (*mi.mi_fend != NUL)
1102 	mb_ptr_adv(mi.mi_fend);
1103 
1104     (void)spell_casefold(ptr, (int)(mi.mi_fend - ptr), mi.mi_fword,
1105 							     MAXWLEN + 1);
1106     mi.mi_fwordlen = (int)STRLEN(mi.mi_fword);
1107 
1108     /* The word is bad unless we recognize it. */
1109     mi.mi_result = SP_BAD;
1110     mi.mi_result2 = SP_BAD;
1111 
1112     /*
1113      * Loop over the languages specified in 'spelllang'.
1114      * We check them all, because a word may be matched longer in another
1115      * language.
1116      */
1117     for (lpi = 0; lpi < wp->w_s->b_langp.ga_len; ++lpi)
1118     {
1119 	mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, lpi);
1120 
1121 	/* If reloading fails the language is still in the list but everything
1122 	 * has been cleared. */
1123 	if (mi.mi_lp->lp_slang->sl_fidxs == NULL)
1124 	    continue;
1125 
1126 	/* Check for a matching word in case-folded words. */
1127 	find_word(&mi, FIND_FOLDWORD);
1128 
1129 	/* Check for a matching word in keep-case words. */
1130 	find_word(&mi, FIND_KEEPWORD);
1131 
1132 	/* Check for matching prefixes. */
1133 	find_prefix(&mi, FIND_FOLDWORD);
1134 
1135 	/* For a NOBREAK language, may want to use a word without a following
1136 	 * word as a backup. */
1137 	if (mi.mi_lp->lp_slang->sl_nobreak && mi.mi_result == SP_BAD
1138 						   && mi.mi_result2 != SP_BAD)
1139 	{
1140 	    mi.mi_result = mi.mi_result2;
1141 	    mi.mi_end = mi.mi_end2;
1142 	}
1143 
1144 	/* Count the word in the first language where it's found to be OK. */
1145 	if (count_word && mi.mi_result == SP_OK)
1146 	{
1147 	    count_common_word(mi.mi_lp->lp_slang, ptr,
1148 						   (int)(mi.mi_end - ptr), 1);
1149 	    count_word = FALSE;
1150 	}
1151     }
1152 
1153     if (mi.mi_result != SP_OK)
1154     {
1155 	/* If we found a number skip over it.  Allows for "42nd".  Do flag
1156 	 * rare and local words, e.g., "3GPP". */
1157 	if (nrlen > 0)
1158 	{
1159 	    if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)
1160 		return nrlen;
1161 	}
1162 
1163 	/* When we are at a non-word character there is no error, just
1164 	 * skip over the character (try looking for a word after it). */
1165 	else if (!spell_iswordp_nmw(ptr, wp))
1166 	{
1167 	    if (capcol != NULL && wp->w_s->b_cap_prog != NULL)
1168 	    {
1169 		regmatch_T	regmatch;
1170 		int		r;
1171 
1172 		/* Check for end of sentence. */
1173 		regmatch.regprog = wp->w_s->b_cap_prog;
1174 		regmatch.rm_ic = FALSE;
1175 		r = vim_regexec(&regmatch, ptr, 0);
1176 		wp->w_s->b_cap_prog = regmatch.regprog;
1177 		if (r)
1178 		    *capcol = (int)(regmatch.endp[0] - ptr);
1179 	    }
1180 
1181 #ifdef FEAT_MBYTE
1182 	    if (has_mbyte)
1183 		return (*mb_ptr2len)(ptr);
1184 #endif
1185 	    return 1;
1186 	}
1187 	else if (mi.mi_end == ptr)
1188 	    /* Always include at least one character.  Required for when there
1189 	     * is a mixup in "midword". */
1190 	    mb_ptr_adv(mi.mi_end);
1191 	else if (mi.mi_result == SP_BAD
1192 		&& LANGP_ENTRY(wp->w_s->b_langp, 0)->lp_slang->sl_nobreak)
1193 	{
1194 	    char_u	*p, *fp;
1195 	    int		save_result = mi.mi_result;
1196 
1197 	    /* First language in 'spelllang' is NOBREAK.  Find first position
1198 	     * at which any word would be valid. */
1199 	    mi.mi_lp = LANGP_ENTRY(wp->w_s->b_langp, 0);
1200 	    if (mi.mi_lp->lp_slang->sl_fidxs != NULL)
1201 	    {
1202 		p = mi.mi_word;
1203 		fp = mi.mi_fword;
1204 		for (;;)
1205 		{
1206 		    mb_ptr_adv(p);
1207 		    mb_ptr_adv(fp);
1208 		    if (p >= mi.mi_end)
1209 			break;
1210 		    mi.mi_compoff = (int)(fp - mi.mi_fword);
1211 		    find_word(&mi, FIND_COMPOUND);
1212 		    if (mi.mi_result != SP_BAD)
1213 		    {
1214 			mi.mi_end = p;
1215 			break;
1216 		    }
1217 		}
1218 		mi.mi_result = save_result;
1219 	    }
1220 	}
1221 
1222 	if (mi.mi_result == SP_BAD || mi.mi_result == SP_BANNED)
1223 	    *attrp = HLF_SPB;
1224 	else if (mi.mi_result == SP_RARE)
1225 	    *attrp = HLF_SPR;
1226 	else
1227 	    *attrp = HLF_SPL;
1228     }
1229 
1230     if (wrongcaplen > 0 && (mi.mi_result == SP_OK || mi.mi_result == SP_RARE))
1231     {
1232 	/* Report SpellCap only when the word isn't badly spelled. */
1233 	*attrp = HLF_SPC;
1234 	return wrongcaplen;
1235     }
1236 
1237     return (int)(mi.mi_end - ptr);
1238 }
1239 
1240 /*
1241  * Check if the word at "mip->mi_word" is in the tree.
1242  * When "mode" is FIND_FOLDWORD check in fold-case word tree.
1243  * When "mode" is FIND_KEEPWORD check in keep-case word tree.
1244  * When "mode" is FIND_PREFIX check for word after prefix in fold-case word
1245  * tree.
1246  *
1247  * For a match mip->mi_result is updated.
1248  */
1249     static void
1250 find_word(mip, mode)
1251     matchinf_T	*mip;
1252     int		mode;
1253 {
1254     idx_T	arridx = 0;
1255     int		endlen[MAXWLEN];    /* length at possible word endings */
1256     idx_T	endidx[MAXWLEN];    /* possible word endings */
1257     int		endidxcnt = 0;
1258     int		len;
1259     int		wlen = 0;
1260     int		flen;
1261     int		c;
1262     char_u	*ptr;
1263     idx_T	lo, hi, m;
1264 #ifdef FEAT_MBYTE
1265     char_u	*s;
1266 #endif
1267     char_u	*p;
1268     int		res = SP_BAD;
1269     slang_T	*slang = mip->mi_lp->lp_slang;
1270     unsigned	flags;
1271     char_u	*byts;
1272     idx_T	*idxs;
1273     int		word_ends;
1274     int		prefix_found;
1275     int		nobreak_result;
1276 
1277     if (mode == FIND_KEEPWORD || mode == FIND_KEEPCOMPOUND)
1278     {
1279 	/* Check for word with matching case in keep-case tree. */
1280 	ptr = mip->mi_word;
1281 	flen = 9999;		    /* no case folding, always enough bytes */
1282 	byts = slang->sl_kbyts;
1283 	idxs = slang->sl_kidxs;
1284 
1285 	if (mode == FIND_KEEPCOMPOUND)
1286 	    /* Skip over the previously found word(s). */
1287 	    wlen += mip->mi_compoff;
1288     }
1289     else
1290     {
1291 	/* Check for case-folded in case-folded tree. */
1292 	ptr = mip->mi_fword;
1293 	flen = mip->mi_fwordlen;    /* available case-folded bytes */
1294 	byts = slang->sl_fbyts;
1295 	idxs = slang->sl_fidxs;
1296 
1297 	if (mode == FIND_PREFIX)
1298 	{
1299 	    /* Skip over the prefix. */
1300 	    wlen = mip->mi_prefixlen;
1301 	    flen -= mip->mi_prefixlen;
1302 	}
1303 	else if (mode == FIND_COMPOUND)
1304 	{
1305 	    /* Skip over the previously found word(s). */
1306 	    wlen = mip->mi_compoff;
1307 	    flen -= mip->mi_compoff;
1308 	}
1309 
1310     }
1311 
1312     if (byts == NULL)
1313 	return;			/* array is empty */
1314 
1315     /*
1316      * Repeat advancing in the tree until:
1317      * - there is a byte that doesn't match,
1318      * - we reach the end of the tree,
1319      * - or we reach the end of the line.
1320      */
1321     for (;;)
1322     {
1323 	if (flen <= 0 && *mip->mi_fend != NUL)
1324 	    flen = fold_more(mip);
1325 
1326 	len = byts[arridx++];
1327 
1328 	/* If the first possible byte is a zero the word could end here.
1329 	 * Remember this index, we first check for the longest word. */
1330 	if (byts[arridx] == 0)
1331 	{
1332 	    if (endidxcnt == MAXWLEN)
1333 	    {
1334 		/* Must be a corrupted spell file. */
1335 		EMSG(_(e_format));
1336 		return;
1337 	    }
1338 	    endlen[endidxcnt] = wlen;
1339 	    endidx[endidxcnt++] = arridx++;
1340 	    --len;
1341 
1342 	    /* Skip over the zeros, there can be several flag/region
1343 	     * combinations. */
1344 	    while (len > 0 && byts[arridx] == 0)
1345 	    {
1346 		++arridx;
1347 		--len;
1348 	    }
1349 	    if (len == 0)
1350 		break;	    /* no children, word must end here */
1351 	}
1352 
1353 	/* Stop looking at end of the line. */
1354 	if (ptr[wlen] == NUL)
1355 	    break;
1356 
1357 	/* Perform a binary search in the list of accepted bytes. */
1358 	c = ptr[wlen];
1359 	if (c == TAB)	    /* <Tab> is handled like <Space> */
1360 	    c = ' ';
1361 	lo = arridx;
1362 	hi = arridx + len - 1;
1363 	while (lo < hi)
1364 	{
1365 	    m = (lo + hi) / 2;
1366 	    if (byts[m] > c)
1367 		hi = m - 1;
1368 	    else if (byts[m] < c)
1369 		lo = m + 1;
1370 	    else
1371 	    {
1372 		lo = hi = m;
1373 		break;
1374 	    }
1375 	}
1376 
1377 	/* Stop if there is no matching byte. */
1378 	if (hi < lo || byts[lo] != c)
1379 	    break;
1380 
1381 	/* Continue at the child (if there is one). */
1382 	arridx = idxs[lo];
1383 	++wlen;
1384 	--flen;
1385 
1386 	/* One space in the good word may stand for several spaces in the
1387 	 * checked word. */
1388 	if (c == ' ')
1389 	{
1390 	    for (;;)
1391 	    {
1392 		if (flen <= 0 && *mip->mi_fend != NUL)
1393 		    flen = fold_more(mip);
1394 		if (ptr[wlen] != ' ' && ptr[wlen] != TAB)
1395 		    break;
1396 		++wlen;
1397 		--flen;
1398 	    }
1399 	}
1400     }
1401 
1402     /*
1403      * Verify that one of the possible endings is valid.  Try the longest
1404      * first.
1405      */
1406     while (endidxcnt > 0)
1407     {
1408 	--endidxcnt;
1409 	arridx = endidx[endidxcnt];
1410 	wlen = endlen[endidxcnt];
1411 
1412 #ifdef FEAT_MBYTE
1413 	if ((*mb_head_off)(ptr, ptr + wlen) > 0)
1414 	    continue;	    /* not at first byte of character */
1415 #endif
1416 	if (spell_iswordp(ptr + wlen, mip->mi_win))
1417 	{
1418 	    if (slang->sl_compprog == NULL && !slang->sl_nobreak)
1419 		continue;	    /* next char is a word character */
1420 	    word_ends = FALSE;
1421 	}
1422 	else
1423 	    word_ends = TRUE;
1424 	/* The prefix flag is before compound flags.  Once a valid prefix flag
1425 	 * has been found we try compound flags. */
1426 	prefix_found = FALSE;
1427 
1428 #ifdef FEAT_MBYTE
1429 	if (mode != FIND_KEEPWORD && has_mbyte)
1430 	{
1431 	    /* Compute byte length in original word, length may change
1432 	     * when folding case.  This can be slow, take a shortcut when the
1433 	     * case-folded word is equal to the keep-case word. */
1434 	    p = mip->mi_word;
1435 	    if (STRNCMP(ptr, p, wlen) != 0)
1436 	    {
1437 		for (s = ptr; s < ptr + wlen; mb_ptr_adv(s))
1438 		    mb_ptr_adv(p);
1439 		wlen = (int)(p - mip->mi_word);
1440 	    }
1441 	}
1442 #endif
1443 
1444 	/* Check flags and region.  For FIND_PREFIX check the condition and
1445 	 * prefix ID.
1446 	 * Repeat this if there are more flags/region alternatives until there
1447 	 * is a match. */
1448 	res = SP_BAD;
1449 	for (len = byts[arridx - 1]; len > 0 && byts[arridx] == 0;
1450 							      --len, ++arridx)
1451 	{
1452 	    flags = idxs[arridx];
1453 
1454 	    /* For the fold-case tree check that the case of the checked word
1455 	     * matches with what the word in the tree requires.
1456 	     * For keep-case tree the case is always right.  For prefixes we
1457 	     * don't bother to check. */
1458 	    if (mode == FIND_FOLDWORD)
1459 	    {
1460 		if (mip->mi_cend != mip->mi_word + wlen)
1461 		{
1462 		    /* mi_capflags was set for a different word length, need
1463 		     * to do it again. */
1464 		    mip->mi_cend = mip->mi_word + wlen;
1465 		    mip->mi_capflags = captype(mip->mi_word, mip->mi_cend);
1466 		}
1467 
1468 		if (mip->mi_capflags == WF_KEEPCAP
1469 				|| !spell_valid_case(mip->mi_capflags, flags))
1470 		    continue;
1471 	    }
1472 
1473 	    /* When mode is FIND_PREFIX the word must support the prefix:
1474 	     * check the prefix ID and the condition.  Do that for the list at
1475 	     * mip->mi_prefarridx that find_prefix() filled. */
1476 	    else if (mode == FIND_PREFIX && !prefix_found)
1477 	    {
1478 		c = valid_word_prefix(mip->mi_prefcnt, mip->mi_prefarridx,
1479 				    flags,
1480 				    mip->mi_word + mip->mi_cprefixlen, slang,
1481 				    FALSE);
1482 		if (c == 0)
1483 		    continue;
1484 
1485 		/* Use the WF_RARE flag for a rare prefix. */
1486 		if (c & WF_RAREPFX)
1487 		    flags |= WF_RARE;
1488 		prefix_found = TRUE;
1489 	    }
1490 
1491 	    if (slang->sl_nobreak)
1492 	    {
1493 		if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND)
1494 			&& (flags & WF_BANNED) == 0)
1495 		{
1496 		    /* NOBREAK: found a valid following word.  That's all we
1497 		     * need to know, so return. */
1498 		    mip->mi_result = SP_OK;
1499 		    break;
1500 		}
1501 	    }
1502 
1503 	    else if ((mode == FIND_COMPOUND || mode == FIND_KEEPCOMPOUND
1504 								|| !word_ends))
1505 	    {
1506 		/* If there is no compound flag or the word is shorter than
1507 		 * COMPOUNDMIN reject it quickly.
1508 		 * Makes you wonder why someone puts a compound flag on a word
1509 		 * that's too short...  Myspell compatibility requires this
1510 		 * anyway. */
1511 		if (((unsigned)flags >> 24) == 0
1512 			     || wlen - mip->mi_compoff < slang->sl_compminlen)
1513 		    continue;
1514 #ifdef FEAT_MBYTE
1515 		/* For multi-byte chars check character length against
1516 		 * COMPOUNDMIN. */
1517 		if (has_mbyte
1518 			&& slang->sl_compminlen > 0
1519 			&& mb_charlen_len(mip->mi_word + mip->mi_compoff,
1520 				wlen - mip->mi_compoff) < slang->sl_compminlen)
1521 			continue;
1522 #endif
1523 
1524 		/* Limit the number of compound words to COMPOUNDWORDMAX if no
1525 		 * maximum for syllables is specified. */
1526 		if (!word_ends && mip->mi_complen + mip->mi_compextra + 2
1527 							   > slang->sl_compmax
1528 					   && slang->sl_compsylmax == MAXWLEN)
1529 		    continue;
1530 
1531 		/* Don't allow compounding on a side where an affix was added,
1532 		 * unless COMPOUNDPERMITFLAG was used. */
1533 		if (mip->mi_complen > 0 && (flags & WF_NOCOMPBEF))
1534 		    continue;
1535 		if (!word_ends && (flags & WF_NOCOMPAFT))
1536 		    continue;
1537 
1538 		/* Quickly check if compounding is possible with this flag. */
1539 		if (!byte_in_str(mip->mi_complen == 0
1540 					? slang->sl_compstartflags
1541 					: slang->sl_compallflags,
1542 					    ((unsigned)flags >> 24)))
1543 		    continue;
1544 
1545 		/* If there is a match with a CHECKCOMPOUNDPATTERN rule
1546 		 * discard the compound word. */
1547 		if (match_checkcompoundpattern(ptr, wlen, &slang->sl_comppat))
1548 		    continue;
1549 
1550 		if (mode == FIND_COMPOUND)
1551 		{
1552 		    int	    capflags;
1553 
1554 		    /* Need to check the caps type of the appended compound
1555 		     * word. */
1556 #ifdef FEAT_MBYTE
1557 		    if (has_mbyte && STRNCMP(ptr, mip->mi_word,
1558 							mip->mi_compoff) != 0)
1559 		    {
1560 			/* case folding may have changed the length */
1561 			p = mip->mi_word;
1562 			for (s = ptr; s < ptr + mip->mi_compoff; mb_ptr_adv(s))
1563 			    mb_ptr_adv(p);
1564 		    }
1565 		    else
1566 #endif
1567 			p = mip->mi_word + mip->mi_compoff;
1568 		    capflags = captype(p, mip->mi_word + wlen);
1569 		    if (capflags == WF_KEEPCAP || (capflags == WF_ALLCAP
1570 						 && (flags & WF_FIXCAP) != 0))
1571 			continue;
1572 
1573 		    if (capflags != WF_ALLCAP)
1574 		    {
1575 			/* When the character before the word is a word
1576 			 * character we do not accept a Onecap word.  We do
1577 			 * accept a no-caps word, even when the dictionary
1578 			 * word specifies ONECAP. */
1579 			mb_ptr_back(mip->mi_word, p);
1580 			if (spell_iswordp_nmw(p, mip->mi_win)
1581 				? capflags == WF_ONECAP
1582 				: (flags & WF_ONECAP) != 0
1583 						     && capflags != WF_ONECAP)
1584 			    continue;
1585 		    }
1586 		}
1587 
1588 		/* If the word ends the sequence of compound flags of the
1589 		 * words must match with one of the COMPOUNDRULE items and
1590 		 * the number of syllables must not be too large. */
1591 		mip->mi_compflags[mip->mi_complen] = ((unsigned)flags >> 24);
1592 		mip->mi_compflags[mip->mi_complen + 1] = NUL;
1593 		if (word_ends)
1594 		{
1595 		    char_u	fword[MAXWLEN];
1596 
1597 		    if (slang->sl_compsylmax < MAXWLEN)
1598 		    {
1599 			/* "fword" is only needed for checking syllables. */
1600 			if (ptr == mip->mi_word)
1601 			    (void)spell_casefold(ptr, wlen, fword, MAXWLEN);
1602 			else
1603 			    vim_strncpy(fword, ptr, endlen[endidxcnt]);
1604 		    }
1605 		    if (!can_compound(slang, fword, mip->mi_compflags))
1606 			continue;
1607 		}
1608 		else if (slang->sl_comprules != NULL
1609 			     && !match_compoundrule(slang, mip->mi_compflags))
1610 		    /* The compound flags collected so far do not match any
1611 		     * COMPOUNDRULE, discard the compounded word. */
1612 		    continue;
1613 	    }
1614 
1615 	    /* Check NEEDCOMPOUND: can't use word without compounding. */
1616 	    else if (flags & WF_NEEDCOMP)
1617 		continue;
1618 
1619 	    nobreak_result = SP_OK;
1620 
1621 	    if (!word_ends)
1622 	    {
1623 		int	save_result = mip->mi_result;
1624 		char_u	*save_end = mip->mi_end;
1625 		langp_T	*save_lp = mip->mi_lp;
1626 		int	lpi;
1627 
1628 		/* Check that a valid word follows.  If there is one and we
1629 		 * are compounding, it will set "mi_result", thus we are
1630 		 * always finished here.  For NOBREAK we only check that a
1631 		 * valid word follows.
1632 		 * Recursive! */
1633 		if (slang->sl_nobreak)
1634 		    mip->mi_result = SP_BAD;
1635 
1636 		/* Find following word in case-folded tree. */
1637 		mip->mi_compoff = endlen[endidxcnt];
1638 #ifdef FEAT_MBYTE
1639 		if (has_mbyte && mode == FIND_KEEPWORD)
1640 		{
1641 		    /* Compute byte length in case-folded word from "wlen":
1642 		     * byte length in keep-case word.  Length may change when
1643 		     * folding case.  This can be slow, take a shortcut when
1644 		     * the case-folded word is equal to the keep-case word. */
1645 		    p = mip->mi_fword;
1646 		    if (STRNCMP(ptr, p, wlen) != 0)
1647 		    {
1648 			for (s = ptr; s < ptr + wlen; mb_ptr_adv(s))
1649 			    mb_ptr_adv(p);
1650 			mip->mi_compoff = (int)(p - mip->mi_fword);
1651 		    }
1652 		}
1653 #endif
1654 		c = mip->mi_compoff;
1655 		++mip->mi_complen;
1656 		if (flags & WF_COMPROOT)
1657 		    ++mip->mi_compextra;
1658 
1659 		/* For NOBREAK we need to try all NOBREAK languages, at least
1660 		 * to find the ".add" file(s). */
1661 		for (lpi = 0; lpi < mip->mi_win->w_s->b_langp.ga_len; ++lpi)
1662 		{
1663 		    if (slang->sl_nobreak)
1664 		    {
1665 			mip->mi_lp = LANGP_ENTRY(mip->mi_win->w_s->b_langp, lpi);
1666 			if (mip->mi_lp->lp_slang->sl_fidxs == NULL
1667 					 || !mip->mi_lp->lp_slang->sl_nobreak)
1668 			    continue;
1669 		    }
1670 
1671 		    find_word(mip, FIND_COMPOUND);
1672 
1673 		    /* When NOBREAK any word that matches is OK.  Otherwise we
1674 		     * need to find the longest match, thus try with keep-case
1675 		     * and prefix too. */
1676 		    if (!slang->sl_nobreak || mip->mi_result == SP_BAD)
1677 		    {
1678 			/* Find following word in keep-case tree. */
1679 			mip->mi_compoff = wlen;
1680 			find_word(mip, FIND_KEEPCOMPOUND);
1681 
1682 #if 0	    /* Disabled, a prefix must not appear halfway a compound word,
1683 	       unless the COMPOUNDPERMITFLAG is used and then it can't be a
1684 	       postponed prefix. */
1685 			if (!slang->sl_nobreak || mip->mi_result == SP_BAD)
1686 			{
1687 			    /* Check for following word with prefix. */
1688 			    mip->mi_compoff = c;
1689 			    find_prefix(mip, FIND_COMPOUND);
1690 			}
1691 #endif
1692 		    }
1693 
1694 		    if (!slang->sl_nobreak)
1695 			break;
1696 		}
1697 		--mip->mi_complen;
1698 		if (flags & WF_COMPROOT)
1699 		    --mip->mi_compextra;
1700 		mip->mi_lp = save_lp;
1701 
1702 		if (slang->sl_nobreak)
1703 		{
1704 		    nobreak_result = mip->mi_result;
1705 		    mip->mi_result = save_result;
1706 		    mip->mi_end = save_end;
1707 		}
1708 		else
1709 		{
1710 		    if (mip->mi_result == SP_OK)
1711 			break;
1712 		    continue;
1713 		}
1714 	    }
1715 
1716 	    if (flags & WF_BANNED)
1717 		res = SP_BANNED;
1718 	    else if (flags & WF_REGION)
1719 	    {
1720 		/* Check region. */
1721 		if ((mip->mi_lp->lp_region & (flags >> 16)) != 0)
1722 		    res = SP_OK;
1723 		else
1724 		    res = SP_LOCAL;
1725 	    }
1726 	    else if (flags & WF_RARE)
1727 		res = SP_RARE;
1728 	    else
1729 		res = SP_OK;
1730 
1731 	    /* Always use the longest match and the best result.  For NOBREAK
1732 	     * we separately keep the longest match without a following good
1733 	     * word as a fall-back. */
1734 	    if (nobreak_result == SP_BAD)
1735 	    {
1736 		if (mip->mi_result2 > res)
1737 		{
1738 		    mip->mi_result2 = res;
1739 		    mip->mi_end2 = mip->mi_word + wlen;
1740 		}
1741 		else if (mip->mi_result2 == res
1742 					&& mip->mi_end2 < mip->mi_word + wlen)
1743 		    mip->mi_end2 = mip->mi_word + wlen;
1744 	    }
1745 	    else if (mip->mi_result > res)
1746 	    {
1747 		mip->mi_result = res;
1748 		mip->mi_end = mip->mi_word + wlen;
1749 	    }
1750 	    else if (mip->mi_result == res && mip->mi_end < mip->mi_word + wlen)
1751 		mip->mi_end = mip->mi_word + wlen;
1752 
1753 	    if (mip->mi_result == SP_OK)
1754 		break;
1755 	}
1756 
1757 	if (mip->mi_result == SP_OK)
1758 	    break;
1759     }
1760 }
1761 
1762 /*
1763  * Return TRUE if there is a match between the word ptr[wlen] and
1764  * CHECKCOMPOUNDPATTERN rules, assuming that we will concatenate with another
1765  * word.
1766  * A match means that the first part of CHECKCOMPOUNDPATTERN matches at the
1767  * end of ptr[wlen] and the second part matches after it.
1768  */
1769     static int
1770 match_checkcompoundpattern(ptr, wlen, gap)
1771     char_u	*ptr;
1772     int		wlen;
1773     garray_T	*gap;  /* &sl_comppat */
1774 {
1775     int		i;
1776     char_u	*p;
1777     int		len;
1778 
1779     for (i = 0; i + 1 < gap->ga_len; i += 2)
1780     {
1781 	p = ((char_u **)gap->ga_data)[i + 1];
1782 	if (STRNCMP(ptr + wlen, p, STRLEN(p)) == 0)
1783 	{
1784 	    /* Second part matches at start of following compound word, now
1785 	     * check if first part matches at end of previous word. */
1786 	    p = ((char_u **)gap->ga_data)[i];
1787 	    len = (int)STRLEN(p);
1788 	    if (len <= wlen && STRNCMP(ptr + wlen - len, p, len) == 0)
1789 		return TRUE;
1790 	}
1791     }
1792     return FALSE;
1793 }
1794 
1795 /*
1796  * Return TRUE if "flags" is a valid sequence of compound flags and "word"
1797  * does not have too many syllables.
1798  */
1799     static int
1800 can_compound(slang, word, flags)
1801     slang_T	*slang;
1802     char_u	*word;
1803     char_u	*flags;
1804 {
1805 #ifdef FEAT_MBYTE
1806     char_u	uflags[MAXWLEN * 2];
1807     int		i;
1808 #endif
1809     char_u	*p;
1810 
1811     if (slang->sl_compprog == NULL)
1812 	return FALSE;
1813 #ifdef FEAT_MBYTE
1814     if (enc_utf8)
1815     {
1816 	/* Need to convert the single byte flags to utf8 characters. */
1817 	p = uflags;
1818 	for (i = 0; flags[i] != NUL; ++i)
1819 	    p += mb_char2bytes(flags[i], p);
1820 	*p = NUL;
1821 	p = uflags;
1822     }
1823     else
1824 #endif
1825 	p = flags;
1826     if (!vim_regexec_prog(&slang->sl_compprog, FALSE, p, 0))
1827 	return FALSE;
1828 
1829     /* Count the number of syllables.  This may be slow, do it last.  If there
1830      * are too many syllables AND the number of compound words is above
1831      * COMPOUNDWORDMAX then compounding is not allowed. */
1832     if (slang->sl_compsylmax < MAXWLEN
1833 		       && count_syllables(slang, word) > slang->sl_compsylmax)
1834 	return (int)STRLEN(flags) < slang->sl_compmax;
1835     return TRUE;
1836 }
1837 
1838 /*
1839  * Return TRUE when the sequence of flags in "compflags" plus "flag" can
1840  * possibly form a valid compounded word.  This also checks the COMPOUNDRULE
1841  * lines if they don't contain wildcards.
1842  */
1843     static int
1844 can_be_compound(sp, slang, compflags, flag)
1845     trystate_T	*sp;
1846     slang_T	*slang;
1847     char_u	*compflags;
1848     int		flag;
1849 {
1850     /* If the flag doesn't appear in sl_compstartflags or sl_compallflags
1851      * then it can't possibly compound. */
1852     if (!byte_in_str(sp->ts_complen == sp->ts_compsplit
1853 		? slang->sl_compstartflags : slang->sl_compallflags, flag))
1854 	return FALSE;
1855 
1856     /* If there are no wildcards, we can check if the flags collected so far
1857      * possibly can form a match with COMPOUNDRULE patterns.  This only
1858      * makes sense when we have two or more words. */
1859     if (slang->sl_comprules != NULL && sp->ts_complen > sp->ts_compsplit)
1860     {
1861 	int v;
1862 
1863 	compflags[sp->ts_complen] = flag;
1864 	compflags[sp->ts_complen + 1] = NUL;
1865 	v = match_compoundrule(slang, compflags + sp->ts_compsplit);
1866 	compflags[sp->ts_complen] = NUL;
1867 	return v;
1868     }
1869 
1870     return TRUE;
1871 }
1872 
1873 
1874 /*
1875  * Return TRUE if the compound flags in compflags[] match the start of any
1876  * compound rule.  This is used to stop trying a compound if the flags
1877  * collected so far can't possibly match any compound rule.
1878  * Caller must check that slang->sl_comprules is not NULL.
1879  */
1880     static int
1881 match_compoundrule(slang, compflags)
1882     slang_T	*slang;
1883     char_u	*compflags;
1884 {
1885     char_u	*p;
1886     int		i;
1887     int		c;
1888 
1889     /* loop over all the COMPOUNDRULE entries */
1890     for (p = slang->sl_comprules; *p != NUL; ++p)
1891     {
1892 	/* loop over the flags in the compound word we have made, match
1893 	 * them against the current rule entry */
1894 	for (i = 0; ; ++i)
1895 	{
1896 	    c = compflags[i];
1897 	    if (c == NUL)
1898 		/* found a rule that matches for the flags we have so far */
1899 		return TRUE;
1900 	    if (*p == '/' || *p == NUL)
1901 		break;  /* end of rule, it's too short */
1902 	    if (*p == '[')
1903 	    {
1904 		int match = FALSE;
1905 
1906 		/* compare against all the flags in [] */
1907 		++p;
1908 		while (*p != ']' && *p != NUL)
1909 		    if (*p++ == c)
1910 			match = TRUE;
1911 		if (!match)
1912 		    break;  /* none matches */
1913 	    }
1914 	    else if (*p != c)
1915 		break;  /* flag of word doesn't match flag in pattern */
1916 	    ++p;
1917 	}
1918 
1919 	/* Skip to the next "/", where the next pattern starts. */
1920 	p = vim_strchr(p, '/');
1921 	if (p == NULL)
1922 	    break;
1923     }
1924 
1925     /* Checked all the rules and none of them match the flags, so there
1926      * can't possibly be a compound starting with these flags. */
1927     return FALSE;
1928 }
1929 
1930 /*
1931  * Return non-zero if the prefix indicated by "arridx" matches with the prefix
1932  * ID in "flags" for the word "word".
1933  * The WF_RAREPFX flag is included in the return value for a rare prefix.
1934  */
1935     static int
1936 valid_word_prefix(totprefcnt, arridx, flags, word, slang, cond_req)
1937     int		totprefcnt;	/* nr of prefix IDs */
1938     int		arridx;		/* idx in sl_pidxs[] */
1939     int		flags;
1940     char_u	*word;
1941     slang_T	*slang;
1942     int		cond_req;	/* only use prefixes with a condition */
1943 {
1944     int		prefcnt;
1945     int		pidx;
1946     regprog_T	**rp;
1947     int		prefid;
1948 
1949     prefid = (unsigned)flags >> 24;
1950     for (prefcnt = totprefcnt - 1; prefcnt >= 0; --prefcnt)
1951     {
1952 	pidx = slang->sl_pidxs[arridx + prefcnt];
1953 
1954 	/* Check the prefix ID. */
1955 	if (prefid != (pidx & 0xff))
1956 	    continue;
1957 
1958 	/* Check if the prefix doesn't combine and the word already has a
1959 	 * suffix. */
1960 	if ((flags & WF_HAS_AFF) && (pidx & WF_PFX_NC))
1961 	    continue;
1962 
1963 	/* Check the condition, if there is one.  The condition index is
1964 	 * stored in the two bytes above the prefix ID byte.  */
1965 	rp = &slang->sl_prefprog[((unsigned)pidx >> 8) & 0xffff];
1966 	if (*rp != NULL)
1967 	{
1968 	    if (!vim_regexec_prog(rp, FALSE, word, 0))
1969 		continue;
1970 	}
1971 	else if (cond_req)
1972 	    continue;
1973 
1974 	/* It's a match!  Return the WF_ flags. */
1975 	return pidx;
1976     }
1977     return 0;
1978 }
1979 
1980 /*
1981  * Check if the word at "mip->mi_word" has a matching prefix.
1982  * If it does, then check the following word.
1983  *
1984  * If "mode" is "FIND_COMPOUND" then do the same after another word, find a
1985  * prefix in a compound word.
1986  *
1987  * For a match mip->mi_result is updated.
1988  */
1989     static void
1990 find_prefix(mip, mode)
1991     matchinf_T	*mip;
1992     int		mode;
1993 {
1994     idx_T	arridx = 0;
1995     int		len;
1996     int		wlen = 0;
1997     int		flen;
1998     int		c;
1999     char_u	*ptr;
2000     idx_T	lo, hi, m;
2001     slang_T	*slang = mip->mi_lp->lp_slang;
2002     char_u	*byts;
2003     idx_T	*idxs;
2004 
2005     byts = slang->sl_pbyts;
2006     if (byts == NULL)
2007 	return;			/* array is empty */
2008 
2009     /* We use the case-folded word here, since prefixes are always
2010      * case-folded. */
2011     ptr = mip->mi_fword;
2012     flen = mip->mi_fwordlen;    /* available case-folded bytes */
2013     if (mode == FIND_COMPOUND)
2014     {
2015 	/* Skip over the previously found word(s). */
2016 	ptr += mip->mi_compoff;
2017 	flen -= mip->mi_compoff;
2018     }
2019     idxs = slang->sl_pidxs;
2020 
2021     /*
2022      * Repeat advancing in the tree until:
2023      * - there is a byte that doesn't match,
2024      * - we reach the end of the tree,
2025      * - or we reach the end of the line.
2026      */
2027     for (;;)
2028     {
2029 	if (flen == 0 && *mip->mi_fend != NUL)
2030 	    flen = fold_more(mip);
2031 
2032 	len = byts[arridx++];
2033 
2034 	/* If the first possible byte is a zero the prefix could end here.
2035 	 * Check if the following word matches and supports the prefix. */
2036 	if (byts[arridx] == 0)
2037 	{
2038 	    /* There can be several prefixes with different conditions.  We
2039 	     * try them all, since we don't know which one will give the
2040 	     * longest match.  The word is the same each time, pass the list
2041 	     * of possible prefixes to find_word(). */
2042 	    mip->mi_prefarridx = arridx;
2043 	    mip->mi_prefcnt = len;
2044 	    while (len > 0 && byts[arridx] == 0)
2045 	    {
2046 		++arridx;
2047 		--len;
2048 	    }
2049 	    mip->mi_prefcnt -= len;
2050 
2051 	    /* Find the word that comes after the prefix. */
2052 	    mip->mi_prefixlen = wlen;
2053 	    if (mode == FIND_COMPOUND)
2054 		/* Skip over the previously found word(s). */
2055 		mip->mi_prefixlen += mip->mi_compoff;
2056 
2057 #ifdef FEAT_MBYTE
2058 	    if (has_mbyte)
2059 	    {
2060 		/* Case-folded length may differ from original length. */
2061 		mip->mi_cprefixlen = nofold_len(mip->mi_fword,
2062 					     mip->mi_prefixlen, mip->mi_word);
2063 	    }
2064 	    else
2065 		mip->mi_cprefixlen = mip->mi_prefixlen;
2066 #endif
2067 	    find_word(mip, FIND_PREFIX);
2068 
2069 
2070 	    if (len == 0)
2071 		break;	    /* no children, word must end here */
2072 	}
2073 
2074 	/* Stop looking at end of the line. */
2075 	if (ptr[wlen] == NUL)
2076 	    break;
2077 
2078 	/* Perform a binary search in the list of accepted bytes. */
2079 	c = ptr[wlen];
2080 	lo = arridx;
2081 	hi = arridx + len - 1;
2082 	while (lo < hi)
2083 	{
2084 	    m = (lo + hi) / 2;
2085 	    if (byts[m] > c)
2086 		hi = m - 1;
2087 	    else if (byts[m] < c)
2088 		lo = m + 1;
2089 	    else
2090 	    {
2091 		lo = hi = m;
2092 		break;
2093 	    }
2094 	}
2095 
2096 	/* Stop if there is no matching byte. */
2097 	if (hi < lo || byts[lo] != c)
2098 	    break;
2099 
2100 	/* Continue at the child (if there is one). */
2101 	arridx = idxs[lo];
2102 	++wlen;
2103 	--flen;
2104     }
2105 }
2106 
2107 /*
2108  * Need to fold at least one more character.  Do until next non-word character
2109  * for efficiency.  Include the non-word character too.
2110  * Return the length of the folded chars in bytes.
2111  */
2112     static int
2113 fold_more(mip)
2114     matchinf_T	*mip;
2115 {
2116     int		flen;
2117     char_u	*p;
2118 
2119     p = mip->mi_fend;
2120     do
2121     {
2122 	mb_ptr_adv(mip->mi_fend);
2123     } while (*mip->mi_fend != NUL && spell_iswordp(mip->mi_fend, mip->mi_win));
2124 
2125     /* Include the non-word character so that we can check for the word end. */
2126     if (*mip->mi_fend != NUL)
2127 	mb_ptr_adv(mip->mi_fend);
2128 
2129     (void)spell_casefold(p, (int)(mip->mi_fend - p),
2130 			     mip->mi_fword + mip->mi_fwordlen,
2131 			     MAXWLEN - mip->mi_fwordlen);
2132     flen = (int)STRLEN(mip->mi_fword + mip->mi_fwordlen);
2133     mip->mi_fwordlen += flen;
2134     return flen;
2135 }
2136 
2137 /*
2138  * Check case flags for a word.  Return TRUE if the word has the requested
2139  * case.
2140  */
2141     static int
2142 spell_valid_case(wordflags, treeflags)
2143     int	    wordflags;	    /* flags for the checked word. */
2144     int	    treeflags;	    /* flags for the word in the spell tree */
2145 {
2146     return ((wordflags == WF_ALLCAP && (treeflags & WF_FIXCAP) == 0)
2147 	    || ((treeflags & (WF_ALLCAP | WF_KEEPCAP)) == 0
2148 		&& ((treeflags & WF_ONECAP) == 0
2149 					   || (wordflags & WF_ONECAP) != 0)));
2150 }
2151 
2152 /*
2153  * Return TRUE if spell checking is not enabled.
2154  */
2155     static int
2156 no_spell_checking(wp)
2157     win_T	*wp;
2158 {
2159     if (!wp->w_p_spell || *wp->w_s->b_p_spl == NUL
2160 					 || wp->w_s->b_langp.ga_len == 0)
2161     {
2162 	EMSG(_("E756: Spell checking is not enabled"));
2163 	return TRUE;
2164     }
2165     return FALSE;
2166 }
2167 
2168 /*
2169  * Move to next spell error.
2170  * "curline" is FALSE for "[s", "]s", "[S" and "]S".
2171  * "curline" is TRUE to find word under/after cursor in the same line.
2172  * For Insert mode completion "dir" is BACKWARD and "curline" is TRUE: move
2173  * to after badly spelled word before the cursor.
2174  * Return 0 if not found, length of the badly spelled word otherwise.
2175  */
2176     int
2177 spell_move_to(wp, dir, allwords, curline, attrp)
2178     win_T	*wp;
2179     int		dir;		/* FORWARD or BACKWARD */
2180     int		allwords;	/* TRUE for "[s"/"]s", FALSE for "[S"/"]S" */
2181     int		curline;
2182     hlf_T	*attrp;		/* return: attributes of bad word or NULL
2183 				   (only when "dir" is FORWARD) */
2184 {
2185     linenr_T	lnum;
2186     pos_T	found_pos;
2187     int		found_len = 0;
2188     char_u	*line;
2189     char_u	*p;
2190     char_u	*endp;
2191     hlf_T	attr;
2192     int		len;
2193 #ifdef FEAT_SYN_HL
2194     int		has_syntax = syntax_present(wp);
2195 #endif
2196     int		col;
2197     int		can_spell;
2198     char_u	*buf = NULL;
2199     int		buflen = 0;
2200     int		skip = 0;
2201     int		capcol = -1;
2202     int		found_one = FALSE;
2203     int		wrapped = FALSE;
2204 
2205     if (no_spell_checking(wp))
2206 	return 0;
2207 
2208     /*
2209      * Start looking for bad word at the start of the line, because we can't
2210      * start halfway a word, we don't know where it starts or ends.
2211      *
2212      * When searching backwards, we continue in the line to find the last
2213      * bad word (in the cursor line: before the cursor).
2214      *
2215      * We concatenate the start of the next line, so that wrapped words work
2216      * (e.g. "et<line-break>cetera").  Doesn't work when searching backwards
2217      * though...
2218      */
2219     lnum = wp->w_cursor.lnum;
2220     clearpos(&found_pos);
2221 
2222     while (!got_int)
2223     {
2224 	line = ml_get_buf(wp->w_buffer, lnum, FALSE);
2225 
2226 	len = (int)STRLEN(line);
2227 	if (buflen < len + MAXWLEN + 2)
2228 	{
2229 	    vim_free(buf);
2230 	    buflen = len + MAXWLEN + 2;
2231 	    buf = alloc(buflen);
2232 	    if (buf == NULL)
2233 		break;
2234 	}
2235 
2236 	/* In first line check first word for Capital. */
2237 	if (lnum == 1)
2238 	    capcol = 0;
2239 
2240 	/* For checking first word with a capital skip white space. */
2241 	if (capcol == 0)
2242 	    capcol = (int)(skipwhite(line) - line);
2243 	else if (curline && wp == curwin)
2244 	{
2245 	    /* For spellbadword(): check if first word needs a capital. */
2246 	    col = (int)(skipwhite(line) - line);
2247 	    if (check_need_cap(lnum, col))
2248 		capcol = col;
2249 
2250 	    /* Need to get the line again, may have looked at the previous
2251 	     * one. */
2252 	    line = ml_get_buf(wp->w_buffer, lnum, FALSE);
2253 	}
2254 
2255 	/* Copy the line into "buf" and append the start of the next line if
2256 	 * possible. */
2257 	STRCPY(buf, line);
2258 	if (lnum < wp->w_buffer->b_ml.ml_line_count)
2259 	    spell_cat_line(buf + STRLEN(buf),
2260 			  ml_get_buf(wp->w_buffer, lnum + 1, FALSE), MAXWLEN);
2261 
2262 	p = buf + skip;
2263 	endp = buf + len;
2264 	while (p < endp)
2265 	{
2266 	    /* When searching backward don't search after the cursor.  Unless
2267 	     * we wrapped around the end of the buffer. */
2268 	    if (dir == BACKWARD
2269 		    && lnum == wp->w_cursor.lnum
2270 		    && !wrapped
2271 		    && (colnr_T)(p - buf) >= wp->w_cursor.col)
2272 		break;
2273 
2274 	    /* start of word */
2275 	    attr = HLF_COUNT;
2276 	    len = spell_check(wp, p, &attr, &capcol, FALSE);
2277 
2278 	    if (attr != HLF_COUNT)
2279 	    {
2280 		/* We found a bad word.  Check the attribute. */
2281 		if (allwords || attr == HLF_SPB)
2282 		{
2283 		    /* When searching forward only accept a bad word after
2284 		     * the cursor. */
2285 		    if (dir == BACKWARD
2286 			    || lnum != wp->w_cursor.lnum
2287 			    || (lnum == wp->w_cursor.lnum
2288 				&& (wrapped
2289 				    || (colnr_T)(curline ? p - buf + len
2290 						     : p - buf)
2291 						  > wp->w_cursor.col)))
2292 		    {
2293 #ifdef FEAT_SYN_HL
2294 			if (has_syntax)
2295 			{
2296 			    col = (int)(p - buf);
2297 			    (void)syn_get_id(wp, lnum, (colnr_T)col,
2298 						    FALSE, &can_spell, FALSE);
2299 			    if (!can_spell)
2300 				attr = HLF_COUNT;
2301 			}
2302 			else
2303 #endif
2304 			    can_spell = TRUE;
2305 
2306 			if (can_spell)
2307 			{
2308 			    found_one = TRUE;
2309 			    found_pos.lnum = lnum;
2310 			    found_pos.col = (int)(p - buf);
2311 #ifdef FEAT_VIRTUALEDIT
2312 			    found_pos.coladd = 0;
2313 #endif
2314 			    if (dir == FORWARD)
2315 			    {
2316 				/* No need to search further. */
2317 				wp->w_cursor = found_pos;
2318 				vim_free(buf);
2319 				if (attrp != NULL)
2320 				    *attrp = attr;
2321 				return len;
2322 			    }
2323 			    else if (curline)
2324 				/* Insert mode completion: put cursor after
2325 				 * the bad word. */
2326 				found_pos.col += len;
2327 			    found_len = len;
2328 			}
2329 		    }
2330 		    else
2331 			found_one = TRUE;
2332 		}
2333 	    }
2334 
2335 	    /* advance to character after the word */
2336 	    p += len;
2337 	    capcol -= len;
2338 	}
2339 
2340 	if (dir == BACKWARD && found_pos.lnum != 0)
2341 	{
2342 	    /* Use the last match in the line (before the cursor). */
2343 	    wp->w_cursor = found_pos;
2344 	    vim_free(buf);
2345 	    return found_len;
2346 	}
2347 
2348 	if (curline)
2349 	    break;	/* only check cursor line */
2350 
2351 	/* Advance to next line. */
2352 	if (dir == BACKWARD)
2353 	{
2354 	    /* If we are back at the starting line and searched it again there
2355 	     * is no match, give up. */
2356 	    if (lnum == wp->w_cursor.lnum && wrapped)
2357 		break;
2358 
2359 	    if (lnum > 1)
2360 		--lnum;
2361 	    else if (!p_ws)
2362 		break;	    /* at first line and 'nowrapscan' */
2363 	    else
2364 	    {
2365 		/* Wrap around to the end of the buffer.  May search the
2366 		 * starting line again and accept the last match. */
2367 		lnum = wp->w_buffer->b_ml.ml_line_count;
2368 		wrapped = TRUE;
2369 		if (!shortmess(SHM_SEARCH))
2370 		    give_warning((char_u *)_(top_bot_msg), TRUE);
2371 	    }
2372 	    capcol = -1;
2373 	}
2374 	else
2375 	{
2376 	    if (lnum < wp->w_buffer->b_ml.ml_line_count)
2377 		++lnum;
2378 	    else if (!p_ws)
2379 		break;	    /* at first line and 'nowrapscan' */
2380 	    else
2381 	    {
2382 		/* Wrap around to the start of the buffer.  May search the
2383 		 * starting line again and accept the first match. */
2384 		lnum = 1;
2385 		wrapped = TRUE;
2386 		if (!shortmess(SHM_SEARCH))
2387 		    give_warning((char_u *)_(bot_top_msg), TRUE);
2388 	    }
2389 
2390 	    /* If we are back at the starting line and there is no match then
2391 	     * give up. */
2392 	    if (lnum == wp->w_cursor.lnum && (!found_one || wrapped))
2393 		break;
2394 
2395 	    /* Skip the characters at the start of the next line that were
2396 	     * included in a match crossing line boundaries. */
2397 	    if (attr == HLF_COUNT)
2398 		skip = (int)(p - endp);
2399 	    else
2400 		skip = 0;
2401 
2402 	    /* Capcol skips over the inserted space. */
2403 	    --capcol;
2404 
2405 	    /* But after empty line check first word in next line */
2406 	    if (*skipwhite(line) == NUL)
2407 		capcol = 0;
2408 	}
2409 
2410 	line_breakcheck();
2411     }
2412 
2413     vim_free(buf);
2414     return 0;
2415 }
2416 
2417 /*
2418  * For spell checking: concatenate the start of the following line "line" into
2419  * "buf", blanking-out special characters.  Copy less then "maxlen" bytes.
2420  * Keep the blanks at the start of the next line, this is used in win_line()
2421  * to skip those bytes if the word was OK.
2422  */
2423     void
2424 spell_cat_line(buf, line, maxlen)
2425     char_u	*buf;
2426     char_u	*line;
2427     int		maxlen;
2428 {
2429     char_u	*p;
2430     int		n;
2431 
2432     p = skipwhite(line);
2433     while (vim_strchr((char_u *)"*#/\"\t", *p) != NULL)
2434 	p = skipwhite(p + 1);
2435 
2436     if (*p != NUL)
2437     {
2438 	/* Only worth concatenating if there is something else than spaces to
2439 	 * concatenate. */
2440 	n = (int)(p - line) + 1;
2441 	if (n < maxlen - 1)
2442 	{
2443 	    vim_memset(buf, ' ', n);
2444 	    vim_strncpy(buf +  n, p, maxlen - 1 - n);
2445 	}
2446     }
2447 }
2448 
2449 /*
2450  * Structure used for the cookie argument of do_in_runtimepath().
2451  */
2452 typedef struct spelload_S
2453 {
2454     char_u  sl_lang[MAXWLEN + 1];	/* language name */
2455     slang_T *sl_slang;			/* resulting slang_T struct */
2456     int	    sl_nobreak;			/* NOBREAK language found */
2457 } spelload_T;
2458 
2459 /*
2460  * Load word list(s) for "lang" from Vim spell file(s).
2461  * "lang" must be the language without the region: e.g., "en".
2462  */
2463     static void
2464 spell_load_lang(lang)
2465     char_u	*lang;
2466 {
2467     char_u	fname_enc[85];
2468     int		r;
2469     spelload_T	sl;
2470 #ifdef FEAT_AUTOCMD
2471     int		round;
2472 #endif
2473 
2474     /* Copy the language name to pass it to spell_load_cb() as a cookie.
2475      * It's truncated when an error is detected. */
2476     STRCPY(sl.sl_lang, lang);
2477     sl.sl_slang = NULL;
2478     sl.sl_nobreak = FALSE;
2479 
2480 #ifdef FEAT_AUTOCMD
2481     /* We may retry when no spell file is found for the language, an
2482      * autocommand may load it then. */
2483     for (round = 1; round <= 2; ++round)
2484 #endif
2485     {
2486 	/*
2487 	 * Find the first spell file for "lang" in 'runtimepath' and load it.
2488 	 */
2489 	vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,
2490 #ifdef VMS
2491 					"spell/%s_%s.spl",
2492 #else
2493 					"spell/%s.%s.spl",
2494 #endif
2495 							   lang, spell_enc());
2496 	r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl);
2497 
2498 	if (r == FAIL && *sl.sl_lang != NUL)
2499 	{
2500 	    /* Try loading the ASCII version. */
2501 	    vim_snprintf((char *)fname_enc, sizeof(fname_enc) - 5,
2502 #ifdef VMS
2503 						  "spell/%s_ascii.spl",
2504 #else
2505 						  "spell/%s.ascii.spl",
2506 #endif
2507 									lang);
2508 	    r = do_in_runtimepath(fname_enc, FALSE, spell_load_cb, &sl);
2509 
2510 #ifdef FEAT_AUTOCMD
2511 	    if (r == FAIL && *sl.sl_lang != NUL && round == 1
2512 		    && apply_autocmds(EVENT_SPELLFILEMISSING, lang,
2513 					      curbuf->b_fname, FALSE, curbuf))
2514 		continue;
2515 	    break;
2516 #endif
2517 	}
2518 #ifdef FEAT_AUTOCMD
2519 	break;
2520 #endif
2521     }
2522 
2523     if (r == FAIL)
2524     {
2525 	smsg((char_u *)
2526 #ifdef VMS
2527 	_("Warning: Cannot find word list \"%s_%s.spl\" or \"%s_ascii.spl\""),
2528 #else
2529 	_("Warning: Cannot find word list \"%s.%s.spl\" or \"%s.ascii.spl\""),
2530 #endif
2531 						     lang, spell_enc(), lang);
2532     }
2533     else if (sl.sl_slang != NULL)
2534     {
2535 	/* At least one file was loaded, now load ALL the additions. */
2536 	STRCPY(fname_enc + STRLEN(fname_enc) - 3, "add.spl");
2537 	do_in_runtimepath(fname_enc, TRUE, spell_load_cb, &sl);
2538     }
2539 }
2540 
2541 /*
2542  * Return the encoding used for spell checking: Use 'encoding', except that we
2543  * use "latin1" for "latin9".  And limit to 60 characters (just in case).
2544  */
2545     static char_u *
2546 spell_enc()
2547 {
2548 
2549 #ifdef FEAT_MBYTE
2550     if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0)
2551 	return p_enc;
2552 #endif
2553     return (char_u *)"latin1";
2554 }
2555 
2556 /*
2557  * Get the name of the .spl file for the internal wordlist into
2558  * "fname[MAXPATHL]".
2559  */
2560     static void
2561 int_wordlist_spl(fname)
2562     char_u	    *fname;
2563 {
2564     vim_snprintf((char *)fname, MAXPATHL, SPL_FNAME_TMPL,
2565 						  int_wordlist, spell_enc());
2566 }
2567 
2568 /*
2569  * Allocate a new slang_T for language "lang".  "lang" can be NULL.
2570  * Caller must fill "sl_next".
2571  */
2572     static slang_T *
2573 slang_alloc(lang)
2574     char_u	*lang;
2575 {
2576     slang_T *lp;
2577 
2578     lp = (slang_T *)alloc_clear(sizeof(slang_T));
2579     if (lp != NULL)
2580     {
2581 	if (lang != NULL)
2582 	    lp->sl_name = vim_strsave(lang);
2583 	ga_init2(&lp->sl_rep, sizeof(fromto_T), 10);
2584 	ga_init2(&lp->sl_repsal, sizeof(fromto_T), 10);
2585 	lp->sl_compmax = MAXWLEN;
2586 	lp->sl_compsylmax = MAXWLEN;
2587 	hash_init(&lp->sl_wordcount);
2588     }
2589 
2590     return lp;
2591 }
2592 
2593 /*
2594  * Free the contents of an slang_T and the structure itself.
2595  */
2596     static void
2597 slang_free(lp)
2598     slang_T	*lp;
2599 {
2600     vim_free(lp->sl_name);
2601     vim_free(lp->sl_fname);
2602     slang_clear(lp);
2603     vim_free(lp);
2604 }
2605 
2606 /*
2607  * Clear an slang_T so that the file can be reloaded.
2608  */
2609     static void
2610 slang_clear(lp)
2611     slang_T	*lp;
2612 {
2613     garray_T	*gap;
2614     fromto_T	*ftp;
2615     salitem_T	*smp;
2616     int		i;
2617     int		round;
2618 
2619     vim_free(lp->sl_fbyts);
2620     lp->sl_fbyts = NULL;
2621     vim_free(lp->sl_kbyts);
2622     lp->sl_kbyts = NULL;
2623     vim_free(lp->sl_pbyts);
2624     lp->sl_pbyts = NULL;
2625 
2626     vim_free(lp->sl_fidxs);
2627     lp->sl_fidxs = NULL;
2628     vim_free(lp->sl_kidxs);
2629     lp->sl_kidxs = NULL;
2630     vim_free(lp->sl_pidxs);
2631     lp->sl_pidxs = NULL;
2632 
2633     for (round = 1; round <= 2; ++round)
2634     {
2635 	gap = round == 1 ? &lp->sl_rep : &lp->sl_repsal;
2636 	while (gap->ga_len > 0)
2637 	{
2638 	    ftp = &((fromto_T *)gap->ga_data)[--gap->ga_len];
2639 	    vim_free(ftp->ft_from);
2640 	    vim_free(ftp->ft_to);
2641 	}
2642 	ga_clear(gap);
2643     }
2644 
2645     gap = &lp->sl_sal;
2646     if (lp->sl_sofo)
2647     {
2648 	/* "ga_len" is set to 1 without adding an item for latin1 */
2649 	if (gap->ga_data != NULL)
2650 	    /* SOFOFROM and SOFOTO items: free lists of wide characters. */
2651 	    for (i = 0; i < gap->ga_len; ++i)
2652 		vim_free(((int **)gap->ga_data)[i]);
2653     }
2654     else
2655 	/* SAL items: free salitem_T items */
2656 	while (gap->ga_len > 0)
2657 	{
2658 	    smp = &((salitem_T *)gap->ga_data)[--gap->ga_len];
2659 	    vim_free(smp->sm_lead);
2660 	    /* Don't free sm_oneof and sm_rules, they point into sm_lead. */
2661 	    vim_free(smp->sm_to);
2662 #ifdef FEAT_MBYTE
2663 	    vim_free(smp->sm_lead_w);
2664 	    vim_free(smp->sm_oneof_w);
2665 	    vim_free(smp->sm_to_w);
2666 #endif
2667 	}
2668     ga_clear(gap);
2669 
2670     for (i = 0; i < lp->sl_prefixcnt; ++i)
2671 	vim_regfree(lp->sl_prefprog[i]);
2672     lp->sl_prefixcnt = 0;
2673     vim_free(lp->sl_prefprog);
2674     lp->sl_prefprog = NULL;
2675 
2676     vim_free(lp->sl_info);
2677     lp->sl_info = NULL;
2678 
2679     vim_free(lp->sl_midword);
2680     lp->sl_midword = NULL;
2681 
2682     vim_regfree(lp->sl_compprog);
2683     vim_free(lp->sl_comprules);
2684     vim_free(lp->sl_compstartflags);
2685     vim_free(lp->sl_compallflags);
2686     lp->sl_compprog = NULL;
2687     lp->sl_comprules = NULL;
2688     lp->sl_compstartflags = NULL;
2689     lp->sl_compallflags = NULL;
2690 
2691     vim_free(lp->sl_syllable);
2692     lp->sl_syllable = NULL;
2693     ga_clear(&lp->sl_syl_items);
2694 
2695     ga_clear_strings(&lp->sl_comppat);
2696 
2697     hash_clear_all(&lp->sl_wordcount, WC_KEY_OFF);
2698     hash_init(&lp->sl_wordcount);
2699 
2700 #ifdef FEAT_MBYTE
2701     hash_clear_all(&lp->sl_map_hash, 0);
2702 #endif
2703 
2704     /* Clear info from .sug file. */
2705     slang_clear_sug(lp);
2706 
2707     lp->sl_compmax = MAXWLEN;
2708     lp->sl_compminlen = 0;
2709     lp->sl_compsylmax = MAXWLEN;
2710     lp->sl_regions[0] = NUL;
2711 }
2712 
2713 /*
2714  * Clear the info from the .sug file in "lp".
2715  */
2716     static void
2717 slang_clear_sug(lp)
2718     slang_T	*lp;
2719 {
2720     vim_free(lp->sl_sbyts);
2721     lp->sl_sbyts = NULL;
2722     vim_free(lp->sl_sidxs);
2723     lp->sl_sidxs = NULL;
2724     close_spellbuf(lp->sl_sugbuf);
2725     lp->sl_sugbuf = NULL;
2726     lp->sl_sugloaded = FALSE;
2727     lp->sl_sugtime = 0;
2728 }
2729 
2730 /*
2731  * Load one spell file and store the info into a slang_T.
2732  * Invoked through do_in_runtimepath().
2733  */
2734     static void
2735 spell_load_cb(fname, cookie)
2736     char_u	*fname;
2737     void	*cookie;
2738 {
2739     spelload_T	*slp = (spelload_T *)cookie;
2740     slang_T	*slang;
2741 
2742     slang = spell_load_file(fname, slp->sl_lang, NULL, FALSE);
2743     if (slang != NULL)
2744     {
2745 	/* When a previously loaded file has NOBREAK also use it for the
2746 	 * ".add" files. */
2747 	if (slp->sl_nobreak && slang->sl_add)
2748 	    slang->sl_nobreak = TRUE;
2749 	else if (slang->sl_nobreak)
2750 	    slp->sl_nobreak = TRUE;
2751 
2752 	slp->sl_slang = slang;
2753     }
2754 }
2755 
2756 /*
2757  * Load one spell file and store the info into a slang_T.
2758  *
2759  * This is invoked in three ways:
2760  * - From spell_load_cb() to load a spell file for the first time.  "lang" is
2761  *   the language name, "old_lp" is NULL.  Will allocate an slang_T.
2762  * - To reload a spell file that was changed.  "lang" is NULL and "old_lp"
2763  *   points to the existing slang_T.
2764  * - Just after writing a .spl file; it's read back to produce the .sug file.
2765  *   "old_lp" is NULL and "lang" is NULL.  Will allocate an slang_T.
2766  *
2767  * Returns the slang_T the spell file was loaded into.  NULL for error.
2768  */
2769     static slang_T *
2770 spell_load_file(fname, lang, old_lp, silent)
2771     char_u	*fname;
2772     char_u	*lang;
2773     slang_T	*old_lp;
2774     int		silent;		/* no error if file doesn't exist */
2775 {
2776     FILE	*fd;
2777     char_u	buf[VIMSPELLMAGICL];
2778     char_u	*p;
2779     int		i;
2780     int		n;
2781     int		len;
2782     char_u	*save_sourcing_name = sourcing_name;
2783     linenr_T	save_sourcing_lnum = sourcing_lnum;
2784     slang_T	*lp = NULL;
2785     int		c = 0;
2786     int		res;
2787 
2788     fd = mch_fopen((char *)fname, "r");
2789     if (fd == NULL)
2790     {
2791 	if (!silent)
2792 	    EMSG2(_(e_notopen), fname);
2793 	else if (p_verbose > 2)
2794 	{
2795 	    verbose_enter();
2796 	    smsg((char_u *)e_notopen, fname);
2797 	    verbose_leave();
2798 	}
2799 	goto endFAIL;
2800     }
2801     if (p_verbose > 2)
2802     {
2803 	verbose_enter();
2804 	smsg((char_u *)_("Reading spell file \"%s\""), fname);
2805 	verbose_leave();
2806     }
2807 
2808     if (old_lp == NULL)
2809     {
2810 	lp = slang_alloc(lang);
2811 	if (lp == NULL)
2812 	    goto endFAIL;
2813 
2814 	/* Remember the file name, used to reload the file when it's updated. */
2815 	lp->sl_fname = vim_strsave(fname);
2816 	if (lp->sl_fname == NULL)
2817 	    goto endFAIL;
2818 
2819 	/* Check for .add.spl (_add.spl for VMS). */
2820 	lp->sl_add = strstr((char *)gettail(fname), SPL_FNAME_ADD) != NULL;
2821     }
2822     else
2823 	lp = old_lp;
2824 
2825     /* Set sourcing_name, so that error messages mention the file name. */
2826     sourcing_name = fname;
2827     sourcing_lnum = 0;
2828 
2829     /*
2830      * <HEADER>: <fileID>
2831      */
2832     for (i = 0; i < VIMSPELLMAGICL; ++i)
2833 	buf[i] = getc(fd);				/* <fileID> */
2834     if (STRNCMP(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0)
2835     {
2836 	EMSG(_("E757: This does not look like a spell file"));
2837 	goto endFAIL;
2838     }
2839     c = getc(fd);					/* <versionnr> */
2840     if (c < VIMSPELLVERSION)
2841     {
2842 	EMSG(_("E771: Old spell file, needs to be updated"));
2843 	goto endFAIL;
2844     }
2845     else if (c > VIMSPELLVERSION)
2846     {
2847 	EMSG(_("E772: Spell file is for newer version of Vim"));
2848 	goto endFAIL;
2849     }
2850 
2851 
2852     /*
2853      * <SECTIONS>: <section> ... <sectionend>
2854      * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
2855      */
2856     for (;;)
2857     {
2858 	n = getc(fd);			    /* <sectionID> or <sectionend> */
2859 	if (n == SN_END)
2860 	    break;
2861 	c = getc(fd);					/* <sectionflags> */
2862 	len = get4c(fd);				/* <sectionlen> */
2863 	if (len < 0)
2864 	    goto truncerr;
2865 
2866 	res = 0;
2867 	switch (n)
2868 	{
2869 	    case SN_INFO:
2870 		lp->sl_info = read_string(fd, len);	/* <infotext> */
2871 		if (lp->sl_info == NULL)
2872 		    goto endFAIL;
2873 		break;
2874 
2875 	    case SN_REGION:
2876 		res = read_region_section(fd, lp, len);
2877 		break;
2878 
2879 	    case SN_CHARFLAGS:
2880 		res = read_charflags_section(fd);
2881 		break;
2882 
2883 	    case SN_MIDWORD:
2884 		lp->sl_midword = read_string(fd, len);	/* <midword> */
2885 		if (lp->sl_midword == NULL)
2886 		    goto endFAIL;
2887 		break;
2888 
2889 	    case SN_PREFCOND:
2890 		res = read_prefcond_section(fd, lp);
2891 		break;
2892 
2893 	    case SN_REP:
2894 		res = read_rep_section(fd, &lp->sl_rep, lp->sl_rep_first);
2895 		break;
2896 
2897 	    case SN_REPSAL:
2898 		res = read_rep_section(fd, &lp->sl_repsal, lp->sl_repsal_first);
2899 		break;
2900 
2901 	    case SN_SAL:
2902 		res = read_sal_section(fd, lp);
2903 		break;
2904 
2905 	    case SN_SOFO:
2906 		res = read_sofo_section(fd, lp);
2907 		break;
2908 
2909 	    case SN_MAP:
2910 		p = read_string(fd, len);		/* <mapstr> */
2911 		if (p == NULL)
2912 		    goto endFAIL;
2913 		set_map_str(lp, p);
2914 		vim_free(p);
2915 		break;
2916 
2917 	    case SN_WORDS:
2918 		res = read_words_section(fd, lp, len);
2919 		break;
2920 
2921 	    case SN_SUGFILE:
2922 		lp->sl_sugtime = get8ctime(fd);		/* <timestamp> */
2923 		break;
2924 
2925 	    case SN_NOSPLITSUGS:
2926 		lp->sl_nosplitsugs = TRUE;
2927 		break;
2928 
2929 	    case SN_NOCOMPOUNDSUGS:
2930 		lp->sl_nocompoundsugs = TRUE;
2931 		break;
2932 
2933 	    case SN_COMPOUND:
2934 		res = read_compound(fd, lp, len);
2935 		break;
2936 
2937 	    case SN_NOBREAK:
2938 		lp->sl_nobreak = TRUE;
2939 		break;
2940 
2941 	    case SN_SYLLABLE:
2942 		lp->sl_syllable = read_string(fd, len);	/* <syllable> */
2943 		if (lp->sl_syllable == NULL)
2944 		    goto endFAIL;
2945 		if (init_syl_tab(lp) == FAIL)
2946 		    goto endFAIL;
2947 		break;
2948 
2949 	    default:
2950 		/* Unsupported section.  When it's required give an error
2951 		 * message.  When it's not required skip the contents. */
2952 		if (c & SNF_REQUIRED)
2953 		{
2954 		    EMSG(_("E770: Unsupported section in spell file"));
2955 		    goto endFAIL;
2956 		}
2957 		while (--len >= 0)
2958 		    if (getc(fd) < 0)
2959 			goto truncerr;
2960 		break;
2961 	}
2962 someerror:
2963 	if (res == SP_FORMERROR)
2964 	{
2965 	    EMSG(_(e_format));
2966 	    goto endFAIL;
2967 	}
2968 	if (res == SP_TRUNCERROR)
2969 	{
2970 truncerr:
2971 	    EMSG(_(e_spell_trunc));
2972 	    goto endFAIL;
2973 	}
2974 	if (res == SP_OTHERERROR)
2975 	    goto endFAIL;
2976     }
2977 
2978     /* <LWORDTREE> */
2979     res = spell_read_tree(fd, &lp->sl_fbyts, &lp->sl_fidxs, FALSE, 0);
2980     if (res != 0)
2981 	goto someerror;
2982 
2983     /* <KWORDTREE> */
2984     res = spell_read_tree(fd, &lp->sl_kbyts, &lp->sl_kidxs, FALSE, 0);
2985     if (res != 0)
2986 	goto someerror;
2987 
2988     /* <PREFIXTREE> */
2989     res = spell_read_tree(fd, &lp->sl_pbyts, &lp->sl_pidxs, TRUE,
2990 							    lp->sl_prefixcnt);
2991     if (res != 0)
2992 	goto someerror;
2993 
2994     /* For a new file link it in the list of spell files. */
2995     if (old_lp == NULL && lang != NULL)
2996     {
2997 	lp->sl_next = first_lang;
2998 	first_lang = lp;
2999     }
3000 
3001     goto endOK;
3002 
3003 endFAIL:
3004     if (lang != NULL)
3005 	/* truncating the name signals the error to spell_load_lang() */
3006 	*lang = NUL;
3007     if (lp != NULL && old_lp == NULL)
3008 	slang_free(lp);
3009     lp = NULL;
3010 
3011 endOK:
3012     if (fd != NULL)
3013 	fclose(fd);
3014     sourcing_name = save_sourcing_name;
3015     sourcing_lnum = save_sourcing_lnum;
3016 
3017     return lp;
3018 }
3019 
3020 /*
3021  * Read a length field from "fd" in "cnt_bytes" bytes.
3022  * Allocate memory, read the string into it and add a NUL at the end.
3023  * Returns NULL when the count is zero.
3024  * Sets "*cntp" to SP_*ERROR when there is an error, length of the result
3025  * otherwise.
3026  */
3027     static char_u *
3028 read_cnt_string(fd, cnt_bytes, cntp)
3029     FILE	*fd;
3030     int		cnt_bytes;
3031     int		*cntp;
3032 {
3033     int		cnt = 0;
3034     int		i;
3035     char_u	*str;
3036 
3037     /* read the length bytes, MSB first */
3038     for (i = 0; i < cnt_bytes; ++i)
3039 	cnt = (cnt << 8) + getc(fd);
3040     if (cnt < 0)
3041     {
3042 	*cntp = SP_TRUNCERROR;
3043 	return NULL;
3044     }
3045     *cntp = cnt;
3046     if (cnt == 0)
3047 	return NULL;	    /* nothing to read, return NULL */
3048 
3049     str = read_string(fd, cnt);
3050     if (str == NULL)
3051 	*cntp = SP_OTHERERROR;
3052     return str;
3053 }
3054 
3055 /*
3056  * Read SN_REGION: <regionname> ...
3057  * Return SP_*ERROR flags.
3058  */
3059     static int
3060 read_region_section(fd, lp, len)
3061     FILE	*fd;
3062     slang_T	*lp;
3063     int		len;
3064 {
3065     int		i;
3066 
3067     if (len > 16)
3068 	return SP_FORMERROR;
3069     for (i = 0; i < len; ++i)
3070 	lp->sl_regions[i] = getc(fd);			/* <regionname> */
3071     lp->sl_regions[len] = NUL;
3072     return 0;
3073 }
3074 
3075 /*
3076  * Read SN_CHARFLAGS section: <charflagslen> <charflags>
3077  *				<folcharslen> <folchars>
3078  * Return SP_*ERROR flags.
3079  */
3080     static int
3081 read_charflags_section(fd)
3082     FILE	*fd;
3083 {
3084     char_u	*flags;
3085     char_u	*fol;
3086     int		flagslen, follen;
3087 
3088     /* <charflagslen> <charflags> */
3089     flags = read_cnt_string(fd, 1, &flagslen);
3090     if (flagslen < 0)
3091 	return flagslen;
3092 
3093     /* <folcharslen> <folchars> */
3094     fol = read_cnt_string(fd, 2, &follen);
3095     if (follen < 0)
3096     {
3097 	vim_free(flags);
3098 	return follen;
3099     }
3100 
3101     /* Set the word-char flags and fill SPELL_ISUPPER() table. */
3102     if (flags != NULL && fol != NULL)
3103 	set_spell_charflags(flags, flagslen, fol);
3104 
3105     vim_free(flags);
3106     vim_free(fol);
3107 
3108     /* When <charflagslen> is zero then <fcharlen> must also be zero. */
3109     if ((flags == NULL) != (fol == NULL))
3110 	return SP_FORMERROR;
3111     return 0;
3112 }
3113 
3114 /*
3115  * Read SN_PREFCOND section.
3116  * Return SP_*ERROR flags.
3117  */
3118     static int
3119 read_prefcond_section(fd, lp)
3120     FILE	*fd;
3121     slang_T	*lp;
3122 {
3123     int		cnt;
3124     int		i;
3125     int		n;
3126     char_u	*p;
3127     char_u	buf[MAXWLEN + 1];
3128 
3129     /* <prefcondcnt> <prefcond> ... */
3130     cnt = get2c(fd);					/* <prefcondcnt> */
3131     if (cnt <= 0)
3132 	return SP_FORMERROR;
3133 
3134     lp->sl_prefprog = (regprog_T **)alloc_clear(
3135 					 (unsigned)sizeof(regprog_T *) * cnt);
3136     if (lp->sl_prefprog == NULL)
3137 	return SP_OTHERERROR;
3138     lp->sl_prefixcnt = cnt;
3139 
3140     for (i = 0; i < cnt; ++i)
3141     {
3142 	/* <prefcond> : <condlen> <condstr> */
3143 	n = getc(fd);					/* <condlen> */
3144 	if (n < 0 || n >= MAXWLEN)
3145 	    return SP_FORMERROR;
3146 
3147 	/* When <condlen> is zero we have an empty condition.  Otherwise
3148 	 * compile the regexp program used to check for the condition. */
3149 	if (n > 0)
3150 	{
3151 	    buf[0] = '^';	    /* always match at one position only */
3152 	    p = buf + 1;
3153 	    while (n-- > 0)
3154 		*p++ = getc(fd);			/* <condstr> */
3155 	    *p = NUL;
3156 	    lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC + RE_STRING);
3157 	}
3158     }
3159     return 0;
3160 }
3161 
3162 /*
3163  * Read REP or REPSAL items section from "fd": <repcount> <rep> ...
3164  * Return SP_*ERROR flags.
3165  */
3166     static int
3167 read_rep_section(fd, gap, first)
3168     FILE	*fd;
3169     garray_T	*gap;
3170     short	*first;
3171 {
3172     int		cnt;
3173     fromto_T	*ftp;
3174     int		i;
3175 
3176     cnt = get2c(fd);					/* <repcount> */
3177     if (cnt < 0)
3178 	return SP_TRUNCERROR;
3179 
3180     if (ga_grow(gap, cnt) == FAIL)
3181 	return SP_OTHERERROR;
3182 
3183     /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */
3184     for (; gap->ga_len < cnt; ++gap->ga_len)
3185     {
3186 	ftp = &((fromto_T *)gap->ga_data)[gap->ga_len];
3187 	ftp->ft_from = read_cnt_string(fd, 1, &i);
3188 	if (i < 0)
3189 	    return i;
3190 	if (i == 0)
3191 	    return SP_FORMERROR;
3192 	ftp->ft_to = read_cnt_string(fd, 1, &i);
3193 	if (i <= 0)
3194 	{
3195 	    vim_free(ftp->ft_from);
3196 	    if (i < 0)
3197 		return i;
3198 	    return SP_FORMERROR;
3199 	}
3200     }
3201 
3202     /* Fill the first-index table. */
3203     for (i = 0; i < 256; ++i)
3204 	first[i] = -1;
3205     for (i = 0; i < gap->ga_len; ++i)
3206     {
3207 	ftp = &((fromto_T *)gap->ga_data)[i];
3208 	if (first[*ftp->ft_from] == -1)
3209 	    first[*ftp->ft_from] = i;
3210     }
3211     return 0;
3212 }
3213 
3214 /*
3215  * Read SN_SAL section: <salflags> <salcount> <sal> ...
3216  * Return SP_*ERROR flags.
3217  */
3218     static int
3219 read_sal_section(fd, slang)
3220     FILE	*fd;
3221     slang_T	*slang;
3222 {
3223     int		i;
3224     int		cnt;
3225     garray_T	*gap;
3226     salitem_T	*smp;
3227     int		ccnt;
3228     char_u	*p;
3229     int		c = NUL;
3230 
3231     slang->sl_sofo = FALSE;
3232 
3233     i = getc(fd);				/* <salflags> */
3234     if (i & SAL_F0LLOWUP)
3235 	slang->sl_followup = TRUE;
3236     if (i & SAL_COLLAPSE)
3237 	slang->sl_collapse = TRUE;
3238     if (i & SAL_REM_ACCENTS)
3239 	slang->sl_rem_accents = TRUE;
3240 
3241     cnt = get2c(fd);				/* <salcount> */
3242     if (cnt < 0)
3243 	return SP_TRUNCERROR;
3244 
3245     gap = &slang->sl_sal;
3246     ga_init2(gap, sizeof(salitem_T), 10);
3247     if (ga_grow(gap, cnt + 1) == FAIL)
3248 	return SP_OTHERERROR;
3249 
3250     /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */
3251     for (; gap->ga_len < cnt; ++gap->ga_len)
3252     {
3253 	smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
3254 	ccnt = getc(fd);			/* <salfromlen> */
3255 	if (ccnt < 0)
3256 	    return SP_TRUNCERROR;
3257 	if ((p = alloc(ccnt + 2)) == NULL)
3258 	    return SP_OTHERERROR;
3259 	smp->sm_lead = p;
3260 
3261 	/* Read up to the first special char into sm_lead. */
3262 	for (i = 0; i < ccnt; ++i)
3263 	{
3264 	    c = getc(fd);			/* <salfrom> */
3265 	    if (vim_strchr((char_u *)"0123456789(-<^$", c) != NULL)
3266 		break;
3267 	    *p++ = c;
3268 	}
3269 	smp->sm_leadlen = (int)(p - smp->sm_lead);
3270 	*p++ = NUL;
3271 
3272 	/* Put (abc) chars in sm_oneof, if any. */
3273 	if (c == '(')
3274 	{
3275 	    smp->sm_oneof = p;
3276 	    for (++i; i < ccnt; ++i)
3277 	    {
3278 		c = getc(fd);			/* <salfrom> */
3279 		if (c == ')')
3280 		    break;
3281 		*p++ = c;
3282 	    }
3283 	    *p++ = NUL;
3284 	    if (++i < ccnt)
3285 		c = getc(fd);
3286 	}
3287 	else
3288 	    smp->sm_oneof = NULL;
3289 
3290 	/* Any following chars go in sm_rules. */
3291 	smp->sm_rules = p;
3292 	if (i < ccnt)
3293 	    /* store the char we got while checking for end of sm_lead */
3294 	    *p++ = c;
3295 	for (++i; i < ccnt; ++i)
3296 	    *p++ = getc(fd);			/* <salfrom> */
3297 	*p++ = NUL;
3298 
3299 	/* <saltolen> <salto> */
3300 	smp->sm_to = read_cnt_string(fd, 1, &ccnt);
3301 	if (ccnt < 0)
3302 	{
3303 	    vim_free(smp->sm_lead);
3304 	    return ccnt;
3305 	}
3306 
3307 #ifdef FEAT_MBYTE
3308 	if (has_mbyte)
3309 	{
3310 	    /* convert the multi-byte strings to wide char strings */
3311 	    smp->sm_lead_w = mb_str2wide(smp->sm_lead);
3312 	    smp->sm_leadlen = mb_charlen(smp->sm_lead);
3313 	    if (smp->sm_oneof == NULL)
3314 		smp->sm_oneof_w = NULL;
3315 	    else
3316 		smp->sm_oneof_w = mb_str2wide(smp->sm_oneof);
3317 	    if (smp->sm_to == NULL)
3318 		smp->sm_to_w = NULL;
3319 	    else
3320 		smp->sm_to_w = mb_str2wide(smp->sm_to);
3321 	    if (smp->sm_lead_w == NULL
3322 		    || (smp->sm_oneof_w == NULL && smp->sm_oneof != NULL)
3323 		    || (smp->sm_to_w == NULL && smp->sm_to != NULL))
3324 	    {
3325 		vim_free(smp->sm_lead);
3326 		vim_free(smp->sm_to);
3327 		vim_free(smp->sm_lead_w);
3328 		vim_free(smp->sm_oneof_w);
3329 		vim_free(smp->sm_to_w);
3330 		return SP_OTHERERROR;
3331 	    }
3332 	}
3333 #endif
3334     }
3335 
3336     if (gap->ga_len > 0)
3337     {
3338 	/* Add one extra entry to mark the end with an empty sm_lead.  Avoids
3339 	 * that we need to check the index every time. */
3340 	smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
3341 	if ((p = alloc(1)) == NULL)
3342 	    return SP_OTHERERROR;
3343 	p[0] = NUL;
3344 	smp->sm_lead = p;
3345 	smp->sm_leadlen = 0;
3346 	smp->sm_oneof = NULL;
3347 	smp->sm_rules = p;
3348 	smp->sm_to = NULL;
3349 #ifdef FEAT_MBYTE
3350 	if (has_mbyte)
3351 	{
3352 	    smp->sm_lead_w = mb_str2wide(smp->sm_lead);
3353 	    smp->sm_leadlen = 0;
3354 	    smp->sm_oneof_w = NULL;
3355 	    smp->sm_to_w = NULL;
3356 	}
3357 #endif
3358 	++gap->ga_len;
3359     }
3360 
3361     /* Fill the first-index table. */
3362     set_sal_first(slang);
3363 
3364     return 0;
3365 }
3366 
3367 /*
3368  * Read SN_WORDS: <word> ...
3369  * Return SP_*ERROR flags.
3370  */
3371     static int
3372 read_words_section(fd, lp, len)
3373     FILE	*fd;
3374     slang_T	*lp;
3375     int		len;
3376 {
3377     int		done = 0;
3378     int		i;
3379     int		c;
3380     char_u	word[MAXWLEN];
3381 
3382     while (done < len)
3383     {
3384 	/* Read one word at a time. */
3385 	for (i = 0; ; ++i)
3386 	{
3387 	    c = getc(fd);
3388 	    if (c == EOF)
3389 		return SP_TRUNCERROR;
3390 	    word[i] = c;
3391 	    if (word[i] == NUL)
3392 		break;
3393 	    if (i == MAXWLEN - 1)
3394 		return SP_FORMERROR;
3395 	}
3396 
3397 	/* Init the count to 10. */
3398 	count_common_word(lp, word, -1, 10);
3399 	done += i + 1;
3400     }
3401     return 0;
3402 }
3403 
3404 /*
3405  * Add a word to the hashtable of common words.
3406  * If it's already there then the counter is increased.
3407  */
3408     static void
3409 count_common_word(lp, word, len, count)
3410     slang_T	*lp;
3411     char_u	*word;
3412     int		len;	    /* word length, -1 for upto NUL */
3413     int		count;	    /* 1 to count once, 10 to init */
3414 {
3415     hash_T	hash;
3416     hashitem_T	*hi;
3417     wordcount_T	*wc;
3418     char_u	buf[MAXWLEN];
3419     char_u	*p;
3420 
3421     if (len == -1)
3422 	p = word;
3423     else
3424     {
3425 	vim_strncpy(buf, word, len);
3426 	p = buf;
3427     }
3428 
3429     hash = hash_hash(p);
3430     hi = hash_lookup(&lp->sl_wordcount, p, hash);
3431     if (HASHITEM_EMPTY(hi))
3432     {
3433 	wc = (wordcount_T *)alloc((unsigned)(sizeof(wordcount_T) + STRLEN(p)));
3434 	if (wc == NULL)
3435 	    return;
3436 	STRCPY(wc->wc_word, p);
3437 	wc->wc_count = count;
3438 	hash_add_item(&lp->sl_wordcount, hi, wc->wc_word, hash);
3439     }
3440     else
3441     {
3442 	wc = HI2WC(hi);
3443 	if ((wc->wc_count += count) < (unsigned)count)	/* check for overflow */
3444 	    wc->wc_count = MAXWORDCOUNT;
3445     }
3446 }
3447 
3448 /*
3449  * Adjust the score of common words.
3450  */
3451     static int
3452 score_wordcount_adj(slang, score, word, split)
3453     slang_T	*slang;
3454     int		score;
3455     char_u	*word;
3456     int		split;	    /* word was split, less bonus */
3457 {
3458     hashitem_T	*hi;
3459     wordcount_T	*wc;
3460     int		bonus;
3461     int		newscore;
3462 
3463     hi = hash_find(&slang->sl_wordcount, word);
3464     if (!HASHITEM_EMPTY(hi))
3465     {
3466 	wc = HI2WC(hi);
3467 	if (wc->wc_count < SCORE_THRES2)
3468 	    bonus = SCORE_COMMON1;
3469 	else if (wc->wc_count < SCORE_THRES3)
3470 	    bonus = SCORE_COMMON2;
3471 	else
3472 	    bonus = SCORE_COMMON3;
3473 	if (split)
3474 	    newscore = score - bonus / 2;
3475 	else
3476 	    newscore = score - bonus;
3477 	if (newscore < 0)
3478 	    return 0;
3479 	return newscore;
3480     }
3481     return score;
3482 }
3483 
3484 /*
3485  * SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
3486  * Return SP_*ERROR flags.
3487  */
3488     static int
3489 read_sofo_section(fd, slang)
3490     FILE	*fd;
3491     slang_T	*slang;
3492 {
3493     int		cnt;
3494     char_u	*from, *to;
3495     int		res;
3496 
3497     slang->sl_sofo = TRUE;
3498 
3499     /* <sofofromlen> <sofofrom> */
3500     from = read_cnt_string(fd, 2, &cnt);
3501     if (cnt < 0)
3502 	return cnt;
3503 
3504     /* <sofotolen> <sofoto> */
3505     to = read_cnt_string(fd, 2, &cnt);
3506     if (cnt < 0)
3507     {
3508 	vim_free(from);
3509 	return cnt;
3510     }
3511 
3512     /* Store the info in slang->sl_sal and/or slang->sl_sal_first. */
3513     if (from != NULL && to != NULL)
3514 	res = set_sofo(slang, from, to);
3515     else if (from != NULL || to != NULL)
3516 	res = SP_FORMERROR;    /* only one of two strings is an error */
3517     else
3518 	res = 0;
3519 
3520     vim_free(from);
3521     vim_free(to);
3522     return res;
3523 }
3524 
3525 /*
3526  * Read the compound section from the .spl file:
3527  *	<compmax> <compminlen> <compsylmax> <compoptions> <compflags>
3528  * Returns SP_*ERROR flags.
3529  */
3530     static int
3531 read_compound(fd, slang, len)
3532     FILE	*fd;
3533     slang_T	*slang;
3534     int		len;
3535 {
3536     int		todo = len;
3537     int		c;
3538     int		atstart;
3539     char_u	*pat;
3540     char_u	*pp;
3541     char_u	*cp;
3542     char_u	*ap;
3543     char_u	*crp;
3544     int		cnt;
3545     garray_T	*gap;
3546 
3547     if (todo < 2)
3548 	return SP_FORMERROR;	/* need at least two bytes */
3549 
3550     --todo;
3551     c = getc(fd);					/* <compmax> */
3552     if (c < 2)
3553 	c = MAXWLEN;
3554     slang->sl_compmax = c;
3555 
3556     --todo;
3557     c = getc(fd);					/* <compminlen> */
3558     if (c < 1)
3559 	c = 0;
3560     slang->sl_compminlen = c;
3561 
3562     --todo;
3563     c = getc(fd);					/* <compsylmax> */
3564     if (c < 1)
3565 	c = MAXWLEN;
3566     slang->sl_compsylmax = c;
3567 
3568     c = getc(fd);					/* <compoptions> */
3569     if (c != 0)
3570 	ungetc(c, fd);	    /* be backwards compatible with Vim 7.0b */
3571     else
3572     {
3573 	--todo;
3574 	c = getc(fd);	    /* only use the lower byte for now */
3575 	--todo;
3576 	slang->sl_compoptions = c;
3577 
3578 	gap = &slang->sl_comppat;
3579 	c = get2c(fd);					/* <comppatcount> */
3580 	todo -= 2;
3581 	ga_init2(gap, sizeof(char_u *), c);
3582 	if (ga_grow(gap, c) == OK)
3583 	    while (--c >= 0)
3584 	    {
3585 		((char_u **)(gap->ga_data))[gap->ga_len++] =
3586 						 read_cnt_string(fd, 1, &cnt);
3587 					    /* <comppatlen> <comppattext> */
3588 		if (cnt < 0)
3589 		    return cnt;
3590 		todo -= cnt + 1;
3591 	    }
3592     }
3593     if (todo < 0)
3594 	return SP_FORMERROR;
3595 
3596     /* Turn the COMPOUNDRULE items into a regexp pattern:
3597      * "a[bc]/a*b+" -> "^\(a[bc]\|a*b\+\)$".
3598      * Inserting backslashes may double the length, "^\(\)$<Nul>" is 7 bytes.
3599      * Conversion to utf-8 may double the size. */
3600     c = todo * 2 + 7;
3601 #ifdef FEAT_MBYTE
3602     if (enc_utf8)
3603 	c += todo * 2;
3604 #endif
3605     pat = alloc((unsigned)c);
3606     if (pat == NULL)
3607 	return SP_OTHERERROR;
3608 
3609     /* We also need a list of all flags that can appear at the start and one
3610      * for all flags. */
3611     cp = alloc(todo + 1);
3612     if (cp == NULL)
3613     {
3614 	vim_free(pat);
3615 	return SP_OTHERERROR;
3616     }
3617     slang->sl_compstartflags = cp;
3618     *cp = NUL;
3619 
3620     ap = alloc(todo + 1);
3621     if (ap == NULL)
3622     {
3623 	vim_free(pat);
3624 	return SP_OTHERERROR;
3625     }
3626     slang->sl_compallflags = ap;
3627     *ap = NUL;
3628 
3629     /* And a list of all patterns in their original form, for checking whether
3630      * compounding may work in match_compoundrule().  This is freed when we
3631      * encounter a wildcard, the check doesn't work then. */
3632     crp = alloc(todo + 1);
3633     slang->sl_comprules = crp;
3634 
3635     pp = pat;
3636     *pp++ = '^';
3637     *pp++ = '\\';
3638     *pp++ = '(';
3639 
3640     atstart = 1;
3641     while (todo-- > 0)
3642     {
3643 	c = getc(fd);					/* <compflags> */
3644 	if (c == EOF)
3645 	{
3646 	    vim_free(pat);
3647 	    return SP_TRUNCERROR;
3648 	}
3649 
3650 	/* Add all flags to "sl_compallflags". */
3651 	if (vim_strchr((char_u *)"?*+[]/", c) == NULL
3652 		&& !byte_in_str(slang->sl_compallflags, c))
3653 	{
3654 	    *ap++ = c;
3655 	    *ap = NUL;
3656 	}
3657 
3658 	if (atstart != 0)
3659 	{
3660 	    /* At start of item: copy flags to "sl_compstartflags".  For a
3661 	     * [abc] item set "atstart" to 2 and copy up to the ']'. */
3662 	    if (c == '[')
3663 		atstart = 2;
3664 	    else if (c == ']')
3665 		atstart = 0;
3666 	    else
3667 	    {
3668 		if (!byte_in_str(slang->sl_compstartflags, c))
3669 		{
3670 		    *cp++ = c;
3671 		    *cp = NUL;
3672 		}
3673 		if (atstart == 1)
3674 		    atstart = 0;
3675 	    }
3676 	}
3677 
3678 	/* Copy flag to "sl_comprules", unless we run into a wildcard. */
3679 	if (crp != NULL)
3680 	{
3681 	    if (c == '?' || c == '+' || c == '*')
3682 	    {
3683 		vim_free(slang->sl_comprules);
3684 		slang->sl_comprules = NULL;
3685 		crp = NULL;
3686 	    }
3687 	    else
3688 		*crp++ = c;
3689 	}
3690 
3691 	if (c == '/')	    /* slash separates two items */
3692 	{
3693 	    *pp++ = '\\';
3694 	    *pp++ = '|';
3695 	    atstart = 1;
3696 	}
3697 	else		    /* normal char, "[abc]" and '*' are copied as-is */
3698 	{
3699 	    if (c == '?' || c == '+' || c == '~')
3700 		*pp++ = '\\';	    /* "a?" becomes "a\?", "a+" becomes "a\+" */
3701 #ifdef FEAT_MBYTE
3702 	    if (enc_utf8)
3703 		pp += mb_char2bytes(c, pp);
3704 	    else
3705 #endif
3706 		*pp++ = c;
3707 	}
3708     }
3709 
3710     *pp++ = '\\';
3711     *pp++ = ')';
3712     *pp++ = '$';
3713     *pp = NUL;
3714 
3715     if (crp != NULL)
3716 	*crp = NUL;
3717 
3718     slang->sl_compprog = vim_regcomp(pat, RE_MAGIC + RE_STRING + RE_STRICT);
3719     vim_free(pat);
3720     if (slang->sl_compprog == NULL)
3721 	return SP_FORMERROR;
3722 
3723     return 0;
3724 }
3725 
3726 /*
3727  * Return TRUE if byte "n" appears in "str".
3728  * Like strchr() but independent of locale.
3729  */
3730     static int
3731 byte_in_str(str, n)
3732     char_u	*str;
3733     int		n;
3734 {
3735     char_u	*p;
3736 
3737     for (p = str; *p != NUL; ++p)
3738 	if (*p == n)
3739 	    return TRUE;
3740     return FALSE;
3741 }
3742 
3743 #define SY_MAXLEN   30
3744 typedef struct syl_item_S
3745 {
3746     char_u	sy_chars[SY_MAXLEN];	    /* the sequence of chars */
3747     int		sy_len;
3748 } syl_item_T;
3749 
3750 /*
3751  * Truncate "slang->sl_syllable" at the first slash and put the following items
3752  * in "slang->sl_syl_items".
3753  */
3754     static int
3755 init_syl_tab(slang)
3756     slang_T	*slang;
3757 {
3758     char_u	*p;
3759     char_u	*s;
3760     int		l;
3761     syl_item_T	*syl;
3762 
3763     ga_init2(&slang->sl_syl_items, sizeof(syl_item_T), 4);
3764     p = vim_strchr(slang->sl_syllable, '/');
3765     while (p != NULL)
3766     {
3767 	*p++ = NUL;
3768 	if (*p == NUL)	    /* trailing slash */
3769 	    break;
3770 	s = p;
3771 	p = vim_strchr(p, '/');
3772 	if (p == NULL)
3773 	    l = (int)STRLEN(s);
3774 	else
3775 	    l = (int)(p - s);
3776 	if (l >= SY_MAXLEN)
3777 	    return SP_FORMERROR;
3778 	if (ga_grow(&slang->sl_syl_items, 1) == FAIL)
3779 	    return SP_OTHERERROR;
3780 	syl = ((syl_item_T *)slang->sl_syl_items.ga_data)
3781 					       + slang->sl_syl_items.ga_len++;
3782 	vim_strncpy(syl->sy_chars, s, l);
3783 	syl->sy_len = l;
3784     }
3785     return OK;
3786 }
3787 
3788 /*
3789  * Count the number of syllables in "word".
3790  * When "word" contains spaces the syllables after the last space are counted.
3791  * Returns zero if syllables are not defines.
3792  */
3793     static int
3794 count_syllables(slang, word)
3795     slang_T	*slang;
3796     char_u	*word;
3797 {
3798     int		cnt = 0;
3799     int		skip = FALSE;
3800     char_u	*p;
3801     int		len;
3802     int		i;
3803     syl_item_T	*syl;
3804     int		c;
3805 
3806     if (slang->sl_syllable == NULL)
3807 	return 0;
3808 
3809     for (p = word; *p != NUL; p += len)
3810     {
3811 	/* When running into a space reset counter. */
3812 	if (*p == ' ')
3813 	{
3814 	    len = 1;
3815 	    cnt = 0;
3816 	    continue;
3817 	}
3818 
3819 	/* Find longest match of syllable items. */
3820 	len = 0;
3821 	for (i = 0; i < slang->sl_syl_items.ga_len; ++i)
3822 	{
3823 	    syl = ((syl_item_T *)slang->sl_syl_items.ga_data) + i;
3824 	    if (syl->sy_len > len
3825 			       && STRNCMP(p, syl->sy_chars, syl->sy_len) == 0)
3826 		len = syl->sy_len;
3827 	}
3828 	if (len != 0)	/* found a match, count syllable  */
3829 	{
3830 	    ++cnt;
3831 	    skip = FALSE;
3832 	}
3833 	else
3834 	{
3835 	    /* No recognized syllable item, at least a syllable char then? */
3836 #ifdef FEAT_MBYTE
3837 	    c = mb_ptr2char(p);
3838 	    len = (*mb_ptr2len)(p);
3839 #else
3840 	    c = *p;
3841 	    len = 1;
3842 #endif
3843 	    if (vim_strchr(slang->sl_syllable, c) == NULL)
3844 		skip = FALSE;	    /* No, search for next syllable */
3845 	    else if (!skip)
3846 	    {
3847 		++cnt;		    /* Yes, count it */
3848 		skip = TRUE;	    /* don't count following syllable chars */
3849 	    }
3850 	}
3851     }
3852     return cnt;
3853 }
3854 
3855 /*
3856  * Set the SOFOFROM and SOFOTO items in language "lp".
3857  * Returns SP_*ERROR flags when there is something wrong.
3858  */
3859     static int
3860 set_sofo(lp, from, to)
3861     slang_T	*lp;
3862     char_u	*from;
3863     char_u	*to;
3864 {
3865     int		i;
3866 
3867 #ifdef FEAT_MBYTE
3868     garray_T	*gap;
3869     char_u	*s;
3870     char_u	*p;
3871     int		c;
3872     int		*inp;
3873 
3874     if (has_mbyte)
3875     {
3876 	/* Use "sl_sal" as an array with 256 pointers to a list of wide
3877 	 * characters.  The index is the low byte of the character.
3878 	 * The list contains from-to pairs with a terminating NUL.
3879 	 * sl_sal_first[] is used for latin1 "from" characters. */
3880 	gap = &lp->sl_sal;
3881 	ga_init2(gap, sizeof(int *), 1);
3882 	if (ga_grow(gap, 256) == FAIL)
3883 	    return SP_OTHERERROR;
3884 	vim_memset(gap->ga_data, 0, sizeof(int *) * 256);
3885 	gap->ga_len = 256;
3886 
3887 	/* First count the number of items for each list.  Temporarily use
3888 	 * sl_sal_first[] for this. */
3889 	for (p = from, s = to; *p != NUL && *s != NUL; )
3890 	{
3891 	    c = mb_cptr2char_adv(&p);
3892 	    mb_cptr_adv(s);
3893 	    if (c >= 256)
3894 		++lp->sl_sal_first[c & 0xff];
3895 	}
3896 	if (*p != NUL || *s != NUL)	    /* lengths differ */
3897 	    return SP_FORMERROR;
3898 
3899 	/* Allocate the lists. */
3900 	for (i = 0; i < 256; ++i)
3901 	    if (lp->sl_sal_first[i] > 0)
3902 	    {
3903 		p = alloc(sizeof(int) * (lp->sl_sal_first[i] * 2 + 1));
3904 		if (p == NULL)
3905 		    return SP_OTHERERROR;
3906 		((int **)gap->ga_data)[i] = (int *)p;
3907 		*(int *)p = 0;
3908 	    }
3909 
3910 	/* Put the characters up to 255 in sl_sal_first[] the rest in a sl_sal
3911 	 * list. */
3912 	vim_memset(lp->sl_sal_first, 0, sizeof(salfirst_T) * 256);
3913 	for (p = from, s = to; *p != NUL && *s != NUL; )
3914 	{
3915 	    c = mb_cptr2char_adv(&p);
3916 	    i = mb_cptr2char_adv(&s);
3917 	    if (c >= 256)
3918 	    {
3919 		/* Append the from-to chars at the end of the list with
3920 		 * the low byte. */
3921 		inp = ((int **)gap->ga_data)[c & 0xff];
3922 		while (*inp != 0)
3923 		    ++inp;
3924 		*inp++ = c;		/* from char */
3925 		*inp++ = i;		/* to char */
3926 		*inp++ = NUL;		/* NUL at the end */
3927 	    }
3928 	    else
3929 		/* mapping byte to char is done in sl_sal_first[] */
3930 		lp->sl_sal_first[c] = i;
3931 	}
3932     }
3933     else
3934 #endif
3935     {
3936 	/* mapping bytes to bytes is done in sl_sal_first[] */
3937 	if (STRLEN(from) != STRLEN(to))
3938 	    return SP_FORMERROR;
3939 
3940 	for (i = 0; to[i] != NUL; ++i)
3941 	    lp->sl_sal_first[from[i]] = to[i];
3942 	lp->sl_sal.ga_len = 1;		/* indicates we have soundfolding */
3943     }
3944 
3945     return 0;
3946 }
3947 
3948 /*
3949  * Fill the first-index table for "lp".
3950  */
3951     static void
3952 set_sal_first(lp)
3953     slang_T	*lp;
3954 {
3955     salfirst_T	*sfirst;
3956     int		i;
3957     salitem_T	*smp;
3958     int		c;
3959     garray_T	*gap = &lp->sl_sal;
3960 
3961     sfirst = lp->sl_sal_first;
3962     for (i = 0; i < 256; ++i)
3963 	sfirst[i] = -1;
3964     smp = (salitem_T *)gap->ga_data;
3965     for (i = 0; i < gap->ga_len; ++i)
3966     {
3967 #ifdef FEAT_MBYTE
3968 	if (has_mbyte)
3969 	    /* Use the lowest byte of the first character.  For latin1 it's
3970 	     * the character, for other encodings it should differ for most
3971 	     * characters. */
3972 	    c = *smp[i].sm_lead_w & 0xff;
3973 	else
3974 #endif
3975 	    c = *smp[i].sm_lead;
3976 	if (sfirst[c] == -1)
3977 	{
3978 	    sfirst[c] = i;
3979 #ifdef FEAT_MBYTE
3980 	    if (has_mbyte)
3981 	    {
3982 		int		n;
3983 
3984 		/* Make sure all entries with this byte are following each
3985 		 * other.  Move the ones that are in the wrong position.  Do
3986 		 * keep the same ordering! */
3987 		while (i + 1 < gap->ga_len
3988 				       && (*smp[i + 1].sm_lead_w & 0xff) == c)
3989 		    /* Skip over entry with same index byte. */
3990 		    ++i;
3991 
3992 		for (n = 1; i + n < gap->ga_len; ++n)
3993 		    if ((*smp[i + n].sm_lead_w & 0xff) == c)
3994 		    {
3995 			salitem_T  tsal;
3996 
3997 			/* Move entry with same index byte after the entries
3998 			 * we already found. */
3999 			++i;
4000 			--n;
4001 			tsal = smp[i + n];
4002 			mch_memmove(smp + i + 1, smp + i,
4003 						       sizeof(salitem_T) * n);
4004 			smp[i] = tsal;
4005 		    }
4006 	    }
4007 #endif
4008 	}
4009     }
4010 }
4011 
4012 #ifdef FEAT_MBYTE
4013 /*
4014  * Turn a multi-byte string into a wide character string.
4015  * Return it in allocated memory (NULL for out-of-memory)
4016  */
4017     static int *
4018 mb_str2wide(s)
4019     char_u	*s;
4020 {
4021     int		*res;
4022     char_u	*p;
4023     int		i = 0;
4024 
4025     res = (int *)alloc(sizeof(int) * (mb_charlen(s) + 1));
4026     if (res != NULL)
4027     {
4028 	for (p = s; *p != NUL; )
4029 	    res[i++] = mb_ptr2char_adv(&p);
4030 	res[i] = NUL;
4031     }
4032     return res;
4033 }
4034 #endif
4035 
4036 /*
4037  * Read a tree from the .spl or .sug file.
4038  * Allocates the memory and stores pointers in "bytsp" and "idxsp".
4039  * This is skipped when the tree has zero length.
4040  * Returns zero when OK, SP_ value for an error.
4041  */
4042     static int
4043 spell_read_tree(fd, bytsp, idxsp, prefixtree, prefixcnt)
4044     FILE	*fd;
4045     char_u	**bytsp;
4046     idx_T	**idxsp;
4047     int		prefixtree;	/* TRUE for the prefix tree */
4048     int		prefixcnt;	/* when "prefixtree" is TRUE: prefix count */
4049 {
4050     int		len;
4051     int		idx;
4052     char_u	*bp;
4053     idx_T	*ip;
4054 
4055     /* The tree size was computed when writing the file, so that we can
4056      * allocate it as one long block. <nodecount> */
4057     len = get4c(fd);
4058     if (len < 0)
4059 	return SP_TRUNCERROR;
4060     if (len > 0)
4061     {
4062 	/* Allocate the byte array. */
4063 	bp = lalloc((long_u)len, TRUE);
4064 	if (bp == NULL)
4065 	    return SP_OTHERERROR;
4066 	*bytsp = bp;
4067 
4068 	/* Allocate the index array. */
4069 	ip = (idx_T *)lalloc_clear((long_u)(len * sizeof(int)), TRUE);
4070 	if (ip == NULL)
4071 	    return SP_OTHERERROR;
4072 	*idxsp = ip;
4073 
4074 	/* Recursively read the tree and store it in the array. */
4075 	idx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt);
4076 	if (idx < 0)
4077 	    return idx;
4078     }
4079     return 0;
4080 }
4081 
4082 /*
4083  * Read one row of siblings from the spell file and store it in the byte array
4084  * "byts" and index array "idxs".  Recursively read the children.
4085  *
4086  * NOTE: The code here must match put_node()!
4087  *
4088  * Returns the index (>= 0) following the siblings.
4089  * Returns SP_TRUNCERROR if the file is shorter than expected.
4090  * Returns SP_FORMERROR if there is a format error.
4091  */
4092     static idx_T
4093 read_tree_node(fd, byts, idxs, maxidx, startidx, prefixtree, maxprefcondnr)
4094     FILE	*fd;
4095     char_u	*byts;
4096     idx_T	*idxs;
4097     int		maxidx;		    /* size of arrays */
4098     idx_T	startidx;	    /* current index in "byts" and "idxs" */
4099     int		prefixtree;	    /* TRUE for reading PREFIXTREE */
4100     int		maxprefcondnr;	    /* maximum for <prefcondnr> */
4101 {
4102     int		len;
4103     int		i;
4104     int		n;
4105     idx_T	idx = startidx;
4106     int		c;
4107     int		c2;
4108 #define SHARED_MASK	0x8000000
4109 
4110     len = getc(fd);					/* <siblingcount> */
4111     if (len <= 0)
4112 	return SP_TRUNCERROR;
4113 
4114     if (startidx + len >= maxidx)
4115 	return SP_FORMERROR;
4116     byts[idx++] = len;
4117 
4118     /* Read the byte values, flag/region bytes and shared indexes. */
4119     for (i = 1; i <= len; ++i)
4120     {
4121 	c = getc(fd);					/* <byte> */
4122 	if (c < 0)
4123 	    return SP_TRUNCERROR;
4124 	if (c <= BY_SPECIAL)
4125 	{
4126 	    if (c == BY_NOFLAGS && !prefixtree)
4127 	    {
4128 		/* No flags, all regions. */
4129 		idxs[idx] = 0;
4130 		c = 0;
4131 	    }
4132 	    else if (c != BY_INDEX)
4133 	    {
4134 		if (prefixtree)
4135 		{
4136 		    /* Read the optional pflags byte, the prefix ID and the
4137 		     * condition nr.  In idxs[] store the prefix ID in the low
4138 		     * byte, the condition index shifted up 8 bits, the flags
4139 		     * shifted up 24 bits. */
4140 		    if (c == BY_FLAGS)
4141 			c = getc(fd) << 24;		/* <pflags> */
4142 		    else
4143 			c = 0;
4144 
4145 		    c |= getc(fd);			/* <affixID> */
4146 
4147 		    n = get2c(fd);			/* <prefcondnr> */
4148 		    if (n >= maxprefcondnr)
4149 			return SP_FORMERROR;
4150 		    c |= (n << 8);
4151 		}
4152 		else /* c must be BY_FLAGS or BY_FLAGS2 */
4153 		{
4154 		    /* Read flags and optional region and prefix ID.  In
4155 		     * idxs[] the flags go in the low two bytes, region above
4156 		     * that and prefix ID above the region. */
4157 		    c2 = c;
4158 		    c = getc(fd);			/* <flags> */
4159 		    if (c2 == BY_FLAGS2)
4160 			c = (getc(fd) << 8) + c;	/* <flags2> */
4161 		    if (c & WF_REGION)
4162 			c = (getc(fd) << 16) + c;	/* <region> */
4163 		    if (c & WF_AFX)
4164 			c = (getc(fd) << 24) + c;	/* <affixID> */
4165 		}
4166 
4167 		idxs[idx] = c;
4168 		c = 0;
4169 	    }
4170 	    else /* c == BY_INDEX */
4171 	    {
4172 							/* <nodeidx> */
4173 		n = get3c(fd);
4174 		if (n < 0 || n >= maxidx)
4175 		    return SP_FORMERROR;
4176 		idxs[idx] = n + SHARED_MASK;
4177 		c = getc(fd);				/* <xbyte> */
4178 	    }
4179 	}
4180 	byts[idx++] = c;
4181     }
4182 
4183     /* Recursively read the children for non-shared siblings.
4184      * Skip the end-of-word ones (zero byte value) and the shared ones (and
4185      * remove SHARED_MASK) */
4186     for (i = 1; i <= len; ++i)
4187 	if (byts[startidx + i] != 0)
4188 	{
4189 	    if (idxs[startidx + i] & SHARED_MASK)
4190 		idxs[startidx + i] &= ~SHARED_MASK;
4191 	    else
4192 	    {
4193 		idxs[startidx + i] = idx;
4194 		idx = read_tree_node(fd, byts, idxs, maxidx, idx,
4195 						     prefixtree, maxprefcondnr);
4196 		if (idx < 0)
4197 		    break;
4198 	    }
4199 	}
4200 
4201     return idx;
4202 }
4203 
4204 /*
4205  * Parse 'spelllang' and set w_s->b_langp accordingly.
4206  * Returns NULL if it's OK, an error message otherwise.
4207  */
4208     char_u *
4209 did_set_spelllang(wp)
4210     win_T	*wp;
4211 {
4212     garray_T	ga;
4213     char_u	*splp;
4214     char_u	*region;
4215     char_u	region_cp[3];
4216     int		filename;
4217     int		region_mask;
4218     slang_T	*slang;
4219     int		c;
4220     char_u	lang[MAXWLEN + 1];
4221     char_u	spf_name[MAXPATHL];
4222     int		len;
4223     char_u	*p;
4224     int		round;
4225     char_u	*spf;
4226     char_u	*use_region = NULL;
4227     int		dont_use_region = FALSE;
4228     int		nobreak = FALSE;
4229     int		i, j;
4230     langp_T	*lp, *lp2;
4231     static int	recursive = FALSE;
4232     char_u	*ret_msg = NULL;
4233     char_u	*spl_copy;
4234 
4235     /* We don't want to do this recursively.  May happen when a language is
4236      * not available and the SpellFileMissing autocommand opens a new buffer
4237      * in which 'spell' is set. */
4238     if (recursive)
4239 	return NULL;
4240     recursive = TRUE;
4241 
4242     ga_init2(&ga, sizeof(langp_T), 2);
4243     clear_midword(wp);
4244 
4245     /* Make a copy of 'spelllang', the SpellFileMissing autocommands may change
4246      * it under our fingers. */
4247     spl_copy = vim_strsave(wp->w_s->b_p_spl);
4248     if (spl_copy == NULL)
4249 	goto theend;
4250 
4251 #ifdef FEAT_MBYTE
4252     wp->w_s->b_cjk = 0;
4253 #endif
4254 
4255     /* Loop over comma separated language names. */
4256     for (splp = spl_copy; *splp != NUL; )
4257     {
4258 	/* Get one language name. */
4259 	copy_option_part(&splp, lang, MAXWLEN, ",");
4260 	region = NULL;
4261 	len = (int)STRLEN(lang);
4262 
4263 	if (STRCMP(lang, "cjk") == 0)
4264 	{
4265 #ifdef FEAT_MBYTE
4266 	    wp->w_s->b_cjk = 1;
4267 #endif
4268 	    continue;
4269 	}
4270 
4271 	/* If the name ends in ".spl" use it as the name of the spell file.
4272 	 * If there is a region name let "region" point to it and remove it
4273 	 * from the name. */
4274 	if (len > 4 && fnamecmp(lang + len - 4, ".spl") == 0)
4275 	{
4276 	    filename = TRUE;
4277 
4278 	    /* Locate a region and remove it from the file name. */
4279 	    p = vim_strchr(gettail(lang), '_');
4280 	    if (p != NULL && ASCII_ISALPHA(p[1]) && ASCII_ISALPHA(p[2])
4281 						      && !ASCII_ISALPHA(p[3]))
4282 	    {
4283 		vim_strncpy(region_cp, p + 1, 2);
4284 		mch_memmove(p, p + 3, len - (p - lang) - 2);
4285 		len -= 3;
4286 		region = region_cp;
4287 	    }
4288 	    else
4289 		dont_use_region = TRUE;
4290 
4291 	    /* Check if we loaded this language before. */
4292 	    for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4293 		if (fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME)
4294 		    break;
4295 	}
4296 	else
4297 	{
4298 	    filename = FALSE;
4299 	    if (len > 3 && lang[len - 3] == '_')
4300 	    {
4301 		region = lang + len - 2;
4302 		len -= 3;
4303 		lang[len] = NUL;
4304 	    }
4305 	    else
4306 		dont_use_region = TRUE;
4307 
4308 	    /* Check if we loaded this language before. */
4309 	    for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4310 		if (STRICMP(lang, slang->sl_name) == 0)
4311 		    break;
4312 	}
4313 
4314 	if (region != NULL)
4315 	{
4316 	    /* If the region differs from what was used before then don't
4317 	     * use it for 'spellfile'. */
4318 	    if (use_region != NULL && STRCMP(region, use_region) != 0)
4319 		dont_use_region = TRUE;
4320 	    use_region = region;
4321 	}
4322 
4323 	/* If not found try loading the language now. */
4324 	if (slang == NULL)
4325 	{
4326 	    if (filename)
4327 		(void)spell_load_file(lang, lang, NULL, FALSE);
4328 	    else
4329 	    {
4330 		spell_load_lang(lang);
4331 #ifdef FEAT_AUTOCMD
4332 		/* SpellFileMissing autocommands may do anything, including
4333 		 * destroying the buffer we are using... */
4334 		if (!buf_valid(wp->w_buffer))
4335 		{
4336 		    ret_msg = (char_u *)"E797: SpellFileMissing autocommand deleted buffer";
4337 		    goto theend;
4338 		}
4339 #endif
4340 	    }
4341 	}
4342 
4343 	/*
4344 	 * Loop over the languages, there can be several files for "lang".
4345 	 */
4346 	for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4347 	    if (filename ? fullpathcmp(lang, slang->sl_fname, FALSE) == FPC_SAME
4348 			 : STRICMP(lang, slang->sl_name) == 0)
4349 	    {
4350 		region_mask = REGION_ALL;
4351 		if (!filename && region != NULL)
4352 		{
4353 		    /* find region in sl_regions */
4354 		    c = find_region(slang->sl_regions, region);
4355 		    if (c == REGION_ALL)
4356 		    {
4357 			if (slang->sl_add)
4358 			{
4359 			    if (*slang->sl_regions != NUL)
4360 				/* This addition file is for other regions. */
4361 				region_mask = 0;
4362 			}
4363 			else
4364 			    /* This is probably an error.  Give a warning and
4365 			     * accept the words anyway. */
4366 			    smsg((char_u *)
4367 				    _("Warning: region %s not supported"),
4368 								      region);
4369 		    }
4370 		    else
4371 			region_mask = 1 << c;
4372 		}
4373 
4374 		if (region_mask != 0)
4375 		{
4376 		    if (ga_grow(&ga, 1) == FAIL)
4377 		    {
4378 			ga_clear(&ga);
4379 			ret_msg = e_outofmem;
4380 			goto theend;
4381 		    }
4382 		    LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;
4383 		    LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
4384 		    ++ga.ga_len;
4385 		    use_midword(slang, wp);
4386 		    if (slang->sl_nobreak)
4387 			nobreak = TRUE;
4388 		}
4389 	    }
4390     }
4391 
4392     /* round 0: load int_wordlist, if possible.
4393      * round 1: load first name in 'spellfile'.
4394      * round 2: load second name in 'spellfile.
4395      * etc. */
4396     spf = curwin->w_s->b_p_spf;
4397     for (round = 0; round == 0 || *spf != NUL; ++round)
4398     {
4399 	if (round == 0)
4400 	{
4401 	    /* Internal wordlist, if there is one. */
4402 	    if (int_wordlist == NULL)
4403 		continue;
4404 	    int_wordlist_spl(spf_name);
4405 	}
4406 	else
4407 	{
4408 	    /* One entry in 'spellfile'. */
4409 	    copy_option_part(&spf, spf_name, MAXPATHL - 5, ",");
4410 	    STRCAT(spf_name, ".spl");
4411 
4412 	    /* If it was already found above then skip it. */
4413 	    for (c = 0; c < ga.ga_len; ++c)
4414 	    {
4415 		p = LANGP_ENTRY(ga, c)->lp_slang->sl_fname;
4416 		if (p != NULL && fullpathcmp(spf_name, p, FALSE) == FPC_SAME)
4417 		    break;
4418 	    }
4419 	    if (c < ga.ga_len)
4420 		continue;
4421 	}
4422 
4423 	/* Check if it was loaded already. */
4424 	for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4425 	    if (fullpathcmp(spf_name, slang->sl_fname, FALSE) == FPC_SAME)
4426 		break;
4427 	if (slang == NULL)
4428 	{
4429 	    /* Not loaded, try loading it now.  The language name includes the
4430 	     * region name, the region is ignored otherwise.  for int_wordlist
4431 	     * use an arbitrary name. */
4432 	    if (round == 0)
4433 		STRCPY(lang, "internal wordlist");
4434 	    else
4435 	    {
4436 		vim_strncpy(lang, gettail(spf_name), MAXWLEN);
4437 		p = vim_strchr(lang, '.');
4438 		if (p != NULL)
4439 		    *p = NUL;	/* truncate at ".encoding.add" */
4440 	    }
4441 	    slang = spell_load_file(spf_name, lang, NULL, TRUE);
4442 
4443 	    /* If one of the languages has NOBREAK we assume the addition
4444 	     * files also have this. */
4445 	    if (slang != NULL && nobreak)
4446 		slang->sl_nobreak = TRUE;
4447 	}
4448 	if (slang != NULL && ga_grow(&ga, 1) == OK)
4449 	{
4450 	    region_mask = REGION_ALL;
4451 	    if (use_region != NULL && !dont_use_region)
4452 	    {
4453 		/* find region in sl_regions */
4454 		c = find_region(slang->sl_regions, use_region);
4455 		if (c != REGION_ALL)
4456 		    region_mask = 1 << c;
4457 		else if (*slang->sl_regions != NUL)
4458 		    /* This spell file is for other regions. */
4459 		    region_mask = 0;
4460 	    }
4461 
4462 	    if (region_mask != 0)
4463 	    {
4464 		LANGP_ENTRY(ga, ga.ga_len)->lp_slang = slang;
4465 		LANGP_ENTRY(ga, ga.ga_len)->lp_sallang = NULL;
4466 		LANGP_ENTRY(ga, ga.ga_len)->lp_replang = NULL;
4467 		LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
4468 		++ga.ga_len;
4469 		use_midword(slang, wp);
4470 	    }
4471 	}
4472     }
4473 
4474     /* Everything is fine, store the new b_langp value. */
4475     ga_clear(&wp->w_s->b_langp);
4476     wp->w_s->b_langp = ga;
4477 
4478     /* For each language figure out what language to use for sound folding and
4479      * REP items.  If the language doesn't support it itself use another one
4480      * with the same name.  E.g. for "en-math" use "en". */
4481     for (i = 0; i < ga.ga_len; ++i)
4482     {
4483 	lp = LANGP_ENTRY(ga, i);
4484 
4485 	/* sound folding */
4486 	if (lp->lp_slang->sl_sal.ga_len > 0)
4487 	    /* language does sound folding itself */
4488 	    lp->lp_sallang = lp->lp_slang;
4489 	else
4490 	    /* find first similar language that does sound folding */
4491 	    for (j = 0; j < ga.ga_len; ++j)
4492 	    {
4493 		lp2 = LANGP_ENTRY(ga, j);
4494 		if (lp2->lp_slang->sl_sal.ga_len > 0
4495 			&& STRNCMP(lp->lp_slang->sl_name,
4496 					      lp2->lp_slang->sl_name, 2) == 0)
4497 		{
4498 		    lp->lp_sallang = lp2->lp_slang;
4499 		    break;
4500 		}
4501 	    }
4502 
4503 	/* REP items */
4504 	if (lp->lp_slang->sl_rep.ga_len > 0)
4505 	    /* language has REP items itself */
4506 	    lp->lp_replang = lp->lp_slang;
4507 	else
4508 	    /* find first similar language that has REP items */
4509 	    for (j = 0; j < ga.ga_len; ++j)
4510 	    {
4511 		lp2 = LANGP_ENTRY(ga, j);
4512 		if (lp2->lp_slang->sl_rep.ga_len > 0
4513 			&& STRNCMP(lp->lp_slang->sl_name,
4514 					      lp2->lp_slang->sl_name, 2) == 0)
4515 		{
4516 		    lp->lp_replang = lp2->lp_slang;
4517 		    break;
4518 		}
4519 	    }
4520     }
4521 
4522 theend:
4523     vim_free(spl_copy);
4524     recursive = FALSE;
4525     redraw_win_later(wp, NOT_VALID);
4526     return ret_msg;
4527 }
4528 
4529 /*
4530  * Clear the midword characters for buffer "buf".
4531  */
4532     static void
4533 clear_midword(wp)
4534     win_T	*wp;
4535 {
4536     vim_memset(wp->w_s->b_spell_ismw, 0, 256);
4537 #ifdef FEAT_MBYTE
4538     vim_free(wp->w_s->b_spell_ismw_mb);
4539     wp->w_s->b_spell_ismw_mb = NULL;
4540 #endif
4541 }
4542 
4543 /*
4544  * Use the "sl_midword" field of language "lp" for buffer "buf".
4545  * They add up to any currently used midword characters.
4546  */
4547     static void
4548 use_midword(lp, wp)
4549     slang_T	*lp;
4550     win_T	*wp;
4551 {
4552     char_u	*p;
4553 
4554     if (lp->sl_midword == NULL)	    /* there aren't any */
4555 	return;
4556 
4557     for (p = lp->sl_midword; *p != NUL; )
4558 #ifdef FEAT_MBYTE
4559 	if (has_mbyte)
4560 	{
4561 	    int	    c, l, n;
4562 	    char_u  *bp;
4563 
4564 	    c = mb_ptr2char(p);
4565 	    l = (*mb_ptr2len)(p);
4566 	    if (c < 256 && l <= 2)
4567 		wp->w_s->b_spell_ismw[c] = TRUE;
4568 	    else if (wp->w_s->b_spell_ismw_mb == NULL)
4569 		/* First multi-byte char in "b_spell_ismw_mb". */
4570 		wp->w_s->b_spell_ismw_mb = vim_strnsave(p, l);
4571 	    else
4572 	    {
4573 		/* Append multi-byte chars to "b_spell_ismw_mb". */
4574 		n = (int)STRLEN(wp->w_s->b_spell_ismw_mb);
4575 		bp = vim_strnsave(wp->w_s->b_spell_ismw_mb, n + l);
4576 		if (bp != NULL)
4577 		{
4578 		    vim_free(wp->w_s->b_spell_ismw_mb);
4579 		    wp->w_s->b_spell_ismw_mb = bp;
4580 		    vim_strncpy(bp + n, p, l);
4581 		}
4582 	    }
4583 	    p += l;
4584 	}
4585 	else
4586 #endif
4587 	    wp->w_s->b_spell_ismw[*p++] = TRUE;
4588 }
4589 
4590 /*
4591  * Find the region "region[2]" in "rp" (points to "sl_regions").
4592  * Each region is simply stored as the two characters of it's name.
4593  * Returns the index if found (first is 0), REGION_ALL if not found.
4594  */
4595     static int
4596 find_region(rp, region)
4597     char_u	*rp;
4598     char_u	*region;
4599 {
4600     int		i;
4601 
4602     for (i = 0; ; i += 2)
4603     {
4604 	if (rp[i] == NUL)
4605 	    return REGION_ALL;
4606 	if (rp[i] == region[0] && rp[i + 1] == region[1])
4607 	    break;
4608     }
4609     return i / 2;
4610 }
4611 
4612 /*
4613  * Return case type of word:
4614  * w word	0
4615  * Word		WF_ONECAP
4616  * W WORD	WF_ALLCAP
4617  * WoRd	wOrd	WF_KEEPCAP
4618  */
4619     static int
4620 captype(word, end)
4621     char_u	*word;
4622     char_u	*end;	    /* When NULL use up to NUL byte. */
4623 {
4624     char_u	*p;
4625     int		c;
4626     int		firstcap;
4627     int		allcap;
4628     int		past_second = FALSE;	/* past second word char */
4629 
4630     /* find first letter */
4631     for (p = word; !spell_iswordp_nmw(p, curwin); mb_ptr_adv(p))
4632 	if (end == NULL ? *p == NUL : p >= end)
4633 	    return 0;	    /* only non-word characters, illegal word */
4634 #ifdef FEAT_MBYTE
4635     if (has_mbyte)
4636 	c = mb_ptr2char_adv(&p);
4637     else
4638 #endif
4639 	c = *p++;
4640     firstcap = allcap = SPELL_ISUPPER(c);
4641 
4642     /*
4643      * Need to check all letters to find a word with mixed upper/lower.
4644      * But a word with an upper char only at start is a ONECAP.
4645      */
4646     for ( ; end == NULL ? *p != NUL : p < end; mb_ptr_adv(p))
4647 	if (spell_iswordp_nmw(p, curwin))
4648 	{
4649 	    c = PTR2CHAR(p);
4650 	    if (!SPELL_ISUPPER(c))
4651 	    {
4652 		/* UUl -> KEEPCAP */
4653 		if (past_second && allcap)
4654 		    return WF_KEEPCAP;
4655 		allcap = FALSE;
4656 	    }
4657 	    else if (!allcap)
4658 		/* UlU -> KEEPCAP */
4659 		return WF_KEEPCAP;
4660 	    past_second = TRUE;
4661 	}
4662 
4663     if (allcap)
4664 	return WF_ALLCAP;
4665     if (firstcap)
4666 	return WF_ONECAP;
4667     return 0;
4668 }
4669 
4670 /*
4671  * Like captype() but for a KEEPCAP word add ONECAP if the word starts with a
4672  * capital.  So that make_case_word() can turn WOrd into Word.
4673  * Add ALLCAP for "WOrD".
4674  */
4675     static int
4676 badword_captype(word, end)
4677     char_u	*word;
4678     char_u	*end;
4679 {
4680     int		flags = captype(word, end);
4681     int		c;
4682     int		l, u;
4683     int		first;
4684     char_u	*p;
4685 
4686     if (flags & WF_KEEPCAP)
4687     {
4688 	/* Count the number of UPPER and lower case letters. */
4689 	l = u = 0;
4690 	first = FALSE;
4691 	for (p = word; p < end; mb_ptr_adv(p))
4692 	{
4693 	    c = PTR2CHAR(p);
4694 	    if (SPELL_ISUPPER(c))
4695 	    {
4696 		++u;
4697 		if (p == word)
4698 		    first = TRUE;
4699 	    }
4700 	    else
4701 		++l;
4702 	}
4703 
4704 	/* If there are more UPPER than lower case letters suggest an
4705 	 * ALLCAP word.  Otherwise, if the first letter is UPPER then
4706 	 * suggest ONECAP.  Exception: "ALl" most likely should be "All",
4707 	 * require three upper case letters. */
4708 	if (u > l && u > 2)
4709 	    flags |= WF_ALLCAP;
4710 	else if (first)
4711 	    flags |= WF_ONECAP;
4712 
4713 	if (u >= 2 && l >= 2)	/* maCARONI maCAroni */
4714 	    flags |= WF_MIXCAP;
4715     }
4716     return flags;
4717 }
4718 
4719 /*
4720  * Delete the internal wordlist and its .spl file.
4721  */
4722     void
4723 spell_delete_wordlist()
4724 {
4725     char_u	fname[MAXPATHL];
4726 
4727     if (int_wordlist != NULL)
4728     {
4729 	mch_remove(int_wordlist);
4730 	int_wordlist_spl(fname);
4731 	mch_remove(fname);
4732 	vim_free(int_wordlist);
4733 	int_wordlist = NULL;
4734     }
4735 }
4736 
4737 #if defined(FEAT_MBYTE) || defined(EXITFREE) || defined(PROTO)
4738 /*
4739  * Free all languages.
4740  */
4741     void
4742 spell_free_all()
4743 {
4744     slang_T	*slang;
4745     buf_T	*buf;
4746 
4747     /* Go through all buffers and handle 'spelllang'. <VN> */
4748     for (buf = firstbuf; buf != NULL; buf = buf->b_next)
4749 	ga_clear(&buf->b_s.b_langp);
4750 
4751     while (first_lang != NULL)
4752     {
4753 	slang = first_lang;
4754 	first_lang = slang->sl_next;
4755 	slang_free(slang);
4756     }
4757 
4758     spell_delete_wordlist();
4759 
4760     vim_free(repl_to);
4761     repl_to = NULL;
4762     vim_free(repl_from);
4763     repl_from = NULL;
4764 }
4765 #endif
4766 
4767 #if defined(FEAT_MBYTE) || defined(PROTO)
4768 /*
4769  * Clear all spelling tables and reload them.
4770  * Used after 'encoding' is set and when ":mkspell" was used.
4771  */
4772     void
4773 spell_reload()
4774 {
4775     win_T	*wp;
4776 
4777     /* Initialize the table for spell_iswordp(). */
4778     init_spell_chartab();
4779 
4780     /* Unload all allocated memory. */
4781     spell_free_all();
4782 
4783     /* Go through all buffers and handle 'spelllang'. */
4784     for (wp = firstwin; wp != NULL; wp = wp->w_next)
4785     {
4786 	/* Only load the wordlists when 'spelllang' is set and there is a
4787 	 * window for this buffer in which 'spell' is set. */
4788 	if (*wp->w_s->b_p_spl != NUL)
4789 	{
4790 		if (wp->w_p_spell)
4791 		{
4792 		    (void)did_set_spelllang(wp);
4793 # ifdef FEAT_WINDOWS
4794 		    break;
4795 # endif
4796 		}
4797 	}
4798     }
4799 }
4800 #endif
4801 
4802 /*
4803  * Reload the spell file "fname" if it's loaded.
4804  */
4805     static void
4806 spell_reload_one(fname, added_word)
4807     char_u	*fname;
4808     int		added_word;	/* invoked through "zg" */
4809 {
4810     slang_T	*slang;
4811     int		didit = FALSE;
4812 
4813     for (slang = first_lang; slang != NULL; slang = slang->sl_next)
4814     {
4815 	if (fullpathcmp(fname, slang->sl_fname, FALSE) == FPC_SAME)
4816 	{
4817 	    slang_clear(slang);
4818 	    if (spell_load_file(fname, NULL, slang, FALSE) == NULL)
4819 		/* reloading failed, clear the language */
4820 		slang_clear(slang);
4821 	    redraw_all_later(SOME_VALID);
4822 	    didit = TRUE;
4823 	}
4824     }
4825 
4826     /* When "zg" was used and the file wasn't loaded yet, should redo
4827      * 'spelllang' to load it now. */
4828     if (added_word && !didit)
4829 	did_set_spelllang(curwin);
4830 }
4831 
4832 
4833 /*
4834  * Functions for ":mkspell".
4835  */
4836 
4837 #define MAXLINELEN  500		/* Maximum length in bytes of a line in a .aff
4838 				   and .dic file. */
4839 /*
4840  * Main structure to store the contents of a ".aff" file.
4841  */
4842 typedef struct afffile_S
4843 {
4844     char_u	*af_enc;	/* "SET", normalized, alloc'ed string or NULL */
4845     int		af_flagtype;	/* AFT_CHAR, AFT_LONG, AFT_NUM or AFT_CAPLONG */
4846     unsigned	af_rare;	/* RARE ID for rare word */
4847     unsigned	af_keepcase;	/* KEEPCASE ID for keep-case word */
4848     unsigned	af_bad;		/* BAD ID for banned word */
4849     unsigned	af_needaffix;	/* NEEDAFFIX ID */
4850     unsigned	af_circumfix;	/* CIRCUMFIX ID */
4851     unsigned	af_needcomp;	/* NEEDCOMPOUND ID */
4852     unsigned	af_comproot;	/* COMPOUNDROOT ID */
4853     unsigned	af_compforbid;	/* COMPOUNDFORBIDFLAG ID */
4854     unsigned	af_comppermit;	/* COMPOUNDPERMITFLAG ID */
4855     unsigned	af_nosuggest;	/* NOSUGGEST ID */
4856     int		af_pfxpostpone;	/* postpone prefixes without chop string and
4857 				   without flags */
4858     int		af_ignoreextra;	/* IGNOREEXTRA present */
4859     hashtab_T	af_pref;	/* hashtable for prefixes, affheader_T */
4860     hashtab_T	af_suff;	/* hashtable for suffixes, affheader_T */
4861     hashtab_T	af_comp;	/* hashtable for compound flags, compitem_T */
4862 } afffile_T;
4863 
4864 #define AFT_CHAR	0	/* flags are one character */
4865 #define AFT_LONG	1	/* flags are two characters */
4866 #define AFT_CAPLONG	2	/* flags are one or two characters */
4867 #define AFT_NUM		3	/* flags are numbers, comma separated */
4868 
4869 typedef struct affentry_S affentry_T;
4870 /* Affix entry from ".aff" file.  Used for prefixes and suffixes. */
4871 struct affentry_S
4872 {
4873     affentry_T	*ae_next;	/* next affix with same name/number */
4874     char_u	*ae_chop;	/* text to chop off basic word (can be NULL) */
4875     char_u	*ae_add;	/* text to add to basic word (can be NULL) */
4876     char_u	*ae_flags;	/* flags on the affix (can be NULL) */
4877     char_u	*ae_cond;	/* condition (NULL for ".") */
4878     regprog_T	*ae_prog;	/* regexp program for ae_cond or NULL */
4879     char	ae_compforbid;	/* COMPOUNDFORBIDFLAG found */
4880     char	ae_comppermit;	/* COMPOUNDPERMITFLAG found */
4881 };
4882 
4883 #ifdef FEAT_MBYTE
4884 # define AH_KEY_LEN 17		/* 2 x 8 bytes + NUL */
4885 #else
4886 # define AH_KEY_LEN 7		/* 6 digits + NUL */
4887 #endif
4888 
4889 /* Affix header from ".aff" file.  Used for af_pref and af_suff. */
4890 typedef struct affheader_S
4891 {
4892     char_u	ah_key[AH_KEY_LEN]; /* key for hashtab == name of affix */
4893     unsigned	ah_flag;	/* affix name as number, uses "af_flagtype" */
4894     int		ah_newID;	/* prefix ID after renumbering; 0 if not used */
4895     int		ah_combine;	/* suffix may combine with prefix */
4896     int		ah_follows;	/* another affix block should be following */
4897     affentry_T	*ah_first;	/* first affix entry */
4898 } affheader_T;
4899 
4900 #define HI2AH(hi)   ((affheader_T *)(hi)->hi_key)
4901 
4902 /* Flag used in compound items. */
4903 typedef struct compitem_S
4904 {
4905     char_u	ci_key[AH_KEY_LEN]; /* key for hashtab == name of compound */
4906     unsigned	ci_flag;	/* affix name as number, uses "af_flagtype" */
4907     int		ci_newID;	/* affix ID after renumbering. */
4908 } compitem_T;
4909 
4910 #define HI2CI(hi)   ((compitem_T *)(hi)->hi_key)
4911 
4912 /*
4913  * Structure that is used to store the items in the word tree.  This avoids
4914  * the need to keep track of each allocated thing, everything is freed all at
4915  * once after ":mkspell" is done.
4916  * Note: "sb_next" must be just before "sb_data" to make sure the alignment of
4917  * "sb_data" is correct for systems where pointers must be aligned on
4918  * pointer-size boundaries and sizeof(pointer) > sizeof(int) (e.g., Sparc).
4919  */
4920 #define  SBLOCKSIZE 16000	/* size of sb_data */
4921 typedef struct sblock_S sblock_T;
4922 struct sblock_S
4923 {
4924     int		sb_used;	/* nr of bytes already in use */
4925     sblock_T	*sb_next;	/* next block in list */
4926     char_u	sb_data[1];	/* data, actually longer */
4927 };
4928 
4929 /*
4930  * A node in the tree.
4931  */
4932 typedef struct wordnode_S wordnode_T;
4933 struct wordnode_S
4934 {
4935     union   /* shared to save space */
4936     {
4937 	char_u	hashkey[6];	/* the hash key, only used while compressing */
4938 	int	index;		/* index in written nodes (valid after first
4939 				   round) */
4940     } wn_u1;
4941     union   /* shared to save space */
4942     {
4943 	wordnode_T *next;	/* next node with same hash key */
4944 	wordnode_T *wnode;	/* parent node that will write this node */
4945     } wn_u2;
4946     wordnode_T	*wn_child;	/* child (next byte in word) */
4947     wordnode_T  *wn_sibling;	/* next sibling (alternate byte in word,
4948 				   always sorted) */
4949     int		wn_refs;	/* Nr. of references to this node.  Only
4950 				   relevant for first node in a list of
4951 				   siblings, in following siblings it is
4952 				   always one. */
4953     char_u	wn_byte;	/* Byte for this node. NUL for word end */
4954 
4955     /* Info for when "wn_byte" is NUL.
4956      * In PREFIXTREE "wn_region" is used for the prefcondnr.
4957      * In the soundfolded word tree "wn_flags" has the MSW of the wordnr and
4958      * "wn_region" the LSW of the wordnr. */
4959     char_u	wn_affixID;	/* supported/required prefix ID or 0 */
4960     short_u	wn_flags;	/* WF_ flags */
4961     short	wn_region;	/* region mask */
4962 
4963 #ifdef SPELL_PRINTTREE
4964     int		wn_nr;		/* sequence nr for printing */
4965 #endif
4966 };
4967 
4968 #define WN_MASK	 0xffff		/* mask relevant bits of "wn_flags" */
4969 
4970 #define HI2WN(hi)    (wordnode_T *)((hi)->hi_key)
4971 
4972 /*
4973  * Info used while reading the spell files.
4974  */
4975 typedef struct spellinfo_S
4976 {
4977     wordnode_T	*si_foldroot;	/* tree with case-folded words */
4978     long	si_foldwcount;	/* nr of words in si_foldroot */
4979 
4980     wordnode_T	*si_keeproot;	/* tree with keep-case words */
4981     long	si_keepwcount;	/* nr of words in si_keeproot */
4982 
4983     wordnode_T	*si_prefroot;	/* tree with postponed prefixes */
4984 
4985     long	si_sugtree;	/* creating the soundfolding trie */
4986 
4987     sblock_T	*si_blocks;	/* memory blocks used */
4988     long	si_blocks_cnt;	/* memory blocks allocated */
4989     int		si_did_emsg;	/* TRUE when ran out of memory */
4990 
4991     long	si_compress_cnt;    /* words to add before lowering
4992 				       compression limit */
4993     wordnode_T	*si_first_free; /* List of nodes that have been freed during
4994 				   compression, linked by "wn_child" field. */
4995     long	si_free_count;	/* number of nodes in si_first_free */
4996 #ifdef SPELL_PRINTTREE
4997     int		si_wordnode_nr;	/* sequence nr for nodes */
4998 #endif
4999     buf_T	*si_spellbuf;	/* buffer used to store soundfold word table */
5000 
5001     int		si_ascii;	/* handling only ASCII words */
5002     int		si_add;		/* addition file */
5003     int		si_clear_chartab;   /* when TRUE clear char tables */
5004     int		si_region;	/* region mask */
5005     vimconv_T	si_conv;	/* for conversion to 'encoding' */
5006     int		si_memtot;	/* runtime memory used */
5007     int		si_verbose;	/* verbose messages */
5008     int		si_msg_count;	/* number of words added since last message */
5009     char_u	*si_info;	/* info text chars or NULL  */
5010     int		si_region_count; /* number of regions supported (1 when there
5011 				    are no regions) */
5012     char_u	si_region_name[17]; /* region names; used only if
5013 				     * si_region_count > 1) */
5014 
5015     garray_T	si_rep;		/* list of fromto_T entries from REP lines */
5016     garray_T	si_repsal;	/* list of fromto_T entries from REPSAL lines */
5017     garray_T	si_sal;		/* list of fromto_T entries from SAL lines */
5018     char_u	*si_sofofr;	/* SOFOFROM text */
5019     char_u	*si_sofoto;	/* SOFOTO text */
5020     int		si_nosugfile;	/* NOSUGFILE item found */
5021     int		si_nosplitsugs;	/* NOSPLITSUGS item found */
5022     int		si_nocompoundsugs; /* NOCOMPOUNDSUGS item found */
5023     int		si_followup;	/* soundsalike: ? */
5024     int		si_collapse;	/* soundsalike: ? */
5025     hashtab_T	si_commonwords;	/* hashtable for common words */
5026     time_t	si_sugtime;	/* timestamp for .sug file */
5027     int		si_rem_accents;	/* soundsalike: remove accents */
5028     garray_T	si_map;		/* MAP info concatenated */
5029     char_u	*si_midword;	/* MIDWORD chars or NULL  */
5030     int		si_compmax;	/* max nr of words for compounding */
5031     int		si_compminlen;	/* minimal length for compounding */
5032     int		si_compsylmax;	/* max nr of syllables for compounding */
5033     int		si_compoptions;	/* COMP_ flags */
5034     garray_T	si_comppat;	/* CHECKCOMPOUNDPATTERN items, each stored as
5035 				   a string */
5036     char_u	*si_compflags;	/* flags used for compounding */
5037     char_u	si_nobreak;	/* NOBREAK */
5038     char_u	*si_syllable;	/* syllable string */
5039     garray_T	si_prefcond;	/* table with conditions for postponed
5040 				 * prefixes, each stored as a string */
5041     int		si_newprefID;	/* current value for ah_newID */
5042     int		si_newcompID;	/* current value for compound ID */
5043 } spellinfo_T;
5044 
5045 static afffile_T *spell_read_aff __ARGS((spellinfo_T *spin, char_u *fname));
5046 static int is_aff_rule __ARGS((char_u **items, int itemcnt, char *rulename, int	 mincount));
5047 static void aff_process_flags __ARGS((afffile_T *affile, affentry_T *entry));
5048 static int spell_info_item __ARGS((char_u *s));
5049 static unsigned affitem2flag __ARGS((int flagtype, char_u *item, char_u	*fname, int lnum));
5050 static unsigned get_affitem __ARGS((int flagtype, char_u **pp));
5051 static void process_compflags __ARGS((spellinfo_T *spin, afffile_T *aff, char_u *compflags));
5052 static void check_renumber __ARGS((spellinfo_T *spin));
5053 static int flag_in_afflist __ARGS((int flagtype, char_u *afflist, unsigned flag));
5054 static void aff_check_number __ARGS((int spinval, int affval, char *name));
5055 static void aff_check_string __ARGS((char_u *spinval, char_u *affval, char *name));
5056 static int str_equal __ARGS((char_u *s1, char_u	*s2));
5057 static void add_fromto __ARGS((spellinfo_T *spin, garray_T *gap, char_u	*from, char_u *to));
5058 static int sal_to_bool __ARGS((char_u *s));
5059 static void spell_free_aff __ARGS((afffile_T *aff));
5060 static int spell_read_dic __ARGS((spellinfo_T *spin, char_u *fname, afffile_T *affile));
5061 static int get_affix_flags __ARGS((afffile_T *affile, char_u *afflist));
5062 static int get_pfxlist __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist));
5063 static void get_compflags __ARGS((afffile_T *affile, char_u *afflist, char_u *store_afflist));
5064 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));
5065 static int spell_read_wordfile __ARGS((spellinfo_T *spin, char_u *fname));
5066 static void *getroom __ARGS((spellinfo_T *spin, size_t len, int align));
5067 static char_u *getroom_save __ARGS((spellinfo_T *spin, char_u *s));
5068 static void free_blocks __ARGS((sblock_T *bl));
5069 static wordnode_T *wordtree_alloc __ARGS((spellinfo_T *spin));
5070 static int store_word __ARGS((spellinfo_T *spin, char_u *word, int flags, int region, char_u *pfxlist, int need_affix));
5071 static int tree_add_word __ARGS((spellinfo_T *spin, char_u *word, wordnode_T *tree, int flags, int region, int affixID));
5072 static wordnode_T *get_wordnode __ARGS((spellinfo_T *spin));
5073 static int deref_wordnode __ARGS((spellinfo_T *spin, wordnode_T *node));
5074 static void free_wordnode __ARGS((spellinfo_T *spin, wordnode_T *n));
5075 static void wordtree_compress __ARGS((spellinfo_T *spin, wordnode_T *root));
5076 static int node_compress __ARGS((spellinfo_T *spin, wordnode_T *node, hashtab_T *ht, int *tot));
5077 static int node_equal __ARGS((wordnode_T *n1, wordnode_T *n2));
5078 static int write_vim_spell __ARGS((spellinfo_T *spin, char_u *fname));
5079 static void clear_node __ARGS((wordnode_T *node));
5080 static int put_node __ARGS((FILE *fd, wordnode_T *node, int idx, int regionmask, int prefixtree));
5081 static void spell_make_sugfile __ARGS((spellinfo_T *spin, char_u *wfname));
5082 static int sug_filltree __ARGS((spellinfo_T *spin, slang_T *slang));
5083 static int sug_maketable __ARGS((spellinfo_T *spin));
5084 static int sug_filltable __ARGS((spellinfo_T *spin, wordnode_T *node, int startwordnr, garray_T *gap));
5085 static int offset2bytes __ARGS((int nr, char_u *buf));
5086 static int bytes2offset __ARGS((char_u **pp));
5087 static void sug_write __ARGS((spellinfo_T *spin, char_u *fname));
5088 static void mkspell __ARGS((int fcount, char_u **fnames, int ascii, int over_write, int added_word));
5089 static void spell_message __ARGS((spellinfo_T *spin, char_u *str));
5090 static void init_spellfile __ARGS((void));
5091 
5092 /* In the postponed prefixes tree wn_flags is used to store the WFP_ flags,
5093  * but it must be negative to indicate the prefix tree to tree_add_word().
5094  * Use a negative number with the lower 8 bits zero. */
5095 #define PFX_FLAGS	-256
5096 
5097 /* flags for "condit" argument of store_aff_word() */
5098 #define CONDIT_COMB	1	/* affix must combine */
5099 #define CONDIT_CFIX	2	/* affix must have CIRCUMFIX flag */
5100 #define CONDIT_SUF	4	/* add a suffix for matching flags */
5101 #define CONDIT_AFF	8	/* word already has an affix */
5102 
5103 /*
5104  * Tunable parameters for when the tree is compressed.  See 'mkspellmem'.
5105  */
5106 static long compress_start = 30000;	/* memory / SBLOCKSIZE */
5107 static long compress_inc = 100;		/* memory / SBLOCKSIZE */
5108 static long compress_added = 500000;	/* word count */
5109 
5110 #ifdef SPELL_PRINTTREE
5111 /*
5112  * For debugging the tree code: print the current tree in a (more or less)
5113  * readable format, so that we can see what happens when adding a word and/or
5114  * compressing the tree.
5115  * Based on code from Olaf Seibert.
5116  */
5117 #define PRINTLINESIZE	1000
5118 #define PRINTWIDTH	6
5119 
5120 #define PRINTSOME(l, depth, fmt, a1, a2) vim_snprintf(l + depth * PRINTWIDTH, \
5121 	    PRINTLINESIZE - PRINTWIDTH * depth, fmt, a1, a2)
5122 
5123 static char line1[PRINTLINESIZE];
5124 static char line2[PRINTLINESIZE];
5125 static char line3[PRINTLINESIZE];
5126 
5127     static void
5128 spell_clear_flags(wordnode_T *node)
5129 {
5130     wordnode_T	*np;
5131 
5132     for (np = node; np != NULL; np = np->wn_sibling)
5133     {
5134 	np->wn_u1.index = FALSE;
5135 	spell_clear_flags(np->wn_child);
5136     }
5137 }
5138 
5139     static void
5140 spell_print_node(wordnode_T *node, int depth)
5141 {
5142     if (node->wn_u1.index)
5143     {
5144 	/* Done this node before, print the reference. */
5145 	PRINTSOME(line1, depth, "(%d)", node->wn_nr, 0);
5146 	PRINTSOME(line2, depth, "    ", 0, 0);
5147 	PRINTSOME(line3, depth, "    ", 0, 0);
5148 	msg((char_u *)line1);
5149 	msg((char_u *)line2);
5150 	msg((char_u *)line3);
5151     }
5152     else
5153     {
5154 	node->wn_u1.index = TRUE;
5155 
5156 	if (node->wn_byte != NUL)
5157 	{
5158 	    if (node->wn_child != NULL)
5159 		PRINTSOME(line1, depth, " %c -> ", node->wn_byte, 0);
5160 	    else
5161 		/* Cannot happen? */
5162 		PRINTSOME(line1, depth, " %c ???", node->wn_byte, 0);
5163 	}
5164 	else
5165 	    PRINTSOME(line1, depth, " $    ", 0, 0);
5166 
5167 	PRINTSOME(line2, depth, "%d/%d    ", node->wn_nr, node->wn_refs);
5168 
5169 	if (node->wn_sibling != NULL)
5170 	    PRINTSOME(line3, depth, " |    ", 0, 0);
5171 	else
5172 	    PRINTSOME(line3, depth, "      ", 0, 0);
5173 
5174 	if (node->wn_byte == NUL)
5175 	{
5176 	    msg((char_u *)line1);
5177 	    msg((char_u *)line2);
5178 	    msg((char_u *)line3);
5179 	}
5180 
5181 	/* do the children */
5182 	if (node->wn_byte != NUL && node->wn_child != NULL)
5183 	    spell_print_node(node->wn_child, depth + 1);
5184 
5185 	/* do the siblings */
5186 	if (node->wn_sibling != NULL)
5187 	{
5188 	    /* get rid of all parent details except | */
5189 	    STRCPY(line1, line3);
5190 	    STRCPY(line2, line3);
5191 	    spell_print_node(node->wn_sibling, depth);
5192 	}
5193     }
5194 }
5195 
5196     static void
5197 spell_print_tree(wordnode_T *root)
5198 {
5199     if (root != NULL)
5200     {
5201 	/* Clear the "wn_u1.index" fields, used to remember what has been
5202 	 * done. */
5203 	spell_clear_flags(root);
5204 
5205 	/* Recursively print the tree. */
5206 	spell_print_node(root, 0);
5207     }
5208 }
5209 #endif /* SPELL_PRINTTREE */
5210 
5211 /*
5212  * Read the affix file "fname".
5213  * Returns an afffile_T, NULL for complete failure.
5214  */
5215     static afffile_T *
5216 spell_read_aff(spin, fname)
5217     spellinfo_T	*spin;
5218     char_u	*fname;
5219 {
5220     FILE	*fd;
5221     afffile_T	*aff;
5222     char_u	rline[MAXLINELEN];
5223     char_u	*line;
5224     char_u	*pc = NULL;
5225 #define MAXITEMCNT  30
5226     char_u	*(items[MAXITEMCNT]);
5227     int		itemcnt;
5228     char_u	*p;
5229     int		lnum = 0;
5230     affheader_T	*cur_aff = NULL;
5231     int		did_postpone_prefix = FALSE;
5232     int		aff_todo = 0;
5233     hashtab_T	*tp;
5234     char_u	*low = NULL;
5235     char_u	*fol = NULL;
5236     char_u	*upp = NULL;
5237     int		do_rep;
5238     int		do_repsal;
5239     int		do_sal;
5240     int		do_mapline;
5241     int		found_map = FALSE;
5242     hashitem_T	*hi;
5243     int		l;
5244     int		compminlen = 0;		/* COMPOUNDMIN value */
5245     int		compsylmax = 0;		/* COMPOUNDSYLMAX value */
5246     int		compoptions = 0;	/* COMP_ flags */
5247     int		compmax = 0;		/* COMPOUNDWORDMAX value */
5248     char_u	*compflags = NULL;	/* COMPOUNDFLAG and COMPOUNDRULE
5249 					   concatenated */
5250     char_u	*midword = NULL;	/* MIDWORD value */
5251     char_u	*syllable = NULL;	/* SYLLABLE value */
5252     char_u	*sofofrom = NULL;	/* SOFOFROM value */
5253     char_u	*sofoto = NULL;		/* SOFOTO value */
5254 
5255     /*
5256      * Open the file.
5257      */
5258     fd = mch_fopen((char *)fname, "r");
5259     if (fd == NULL)
5260     {
5261 	EMSG2(_(e_notopen), fname);
5262 	return NULL;
5263     }
5264 
5265     vim_snprintf((char *)IObuff, IOSIZE, _("Reading affix file %s ..."), fname);
5266     spell_message(spin, IObuff);
5267 
5268     /* Only do REP lines when not done in another .aff file already. */
5269     do_rep = spin->si_rep.ga_len == 0;
5270 
5271     /* Only do REPSAL lines when not done in another .aff file already. */
5272     do_repsal = spin->si_repsal.ga_len == 0;
5273 
5274     /* Only do SAL lines when not done in another .aff file already. */
5275     do_sal = spin->si_sal.ga_len == 0;
5276 
5277     /* Only do MAP lines when not done in another .aff file already. */
5278     do_mapline = spin->si_map.ga_len == 0;
5279 
5280     /*
5281      * Allocate and init the afffile_T structure.
5282      */
5283     aff = (afffile_T *)getroom(spin, sizeof(afffile_T), TRUE);
5284     if (aff == NULL)
5285     {
5286 	fclose(fd);
5287 	return NULL;
5288     }
5289     hash_init(&aff->af_pref);
5290     hash_init(&aff->af_suff);
5291     hash_init(&aff->af_comp);
5292 
5293     /*
5294      * Read all the lines in the file one by one.
5295      */
5296     while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
5297     {
5298 	line_breakcheck();
5299 	++lnum;
5300 
5301 	/* Skip comment lines. */
5302 	if (*rline == '#')
5303 	    continue;
5304 
5305 	/* Convert from "SET" to 'encoding' when needed. */
5306 	vim_free(pc);
5307 #ifdef FEAT_MBYTE
5308 	if (spin->si_conv.vc_type != CONV_NONE)
5309 	{
5310 	    pc = string_convert(&spin->si_conv, rline, NULL);
5311 	    if (pc == NULL)
5312 	    {
5313 		smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
5314 							   fname, lnum, rline);
5315 		continue;
5316 	    }
5317 	    line = pc;
5318 	}
5319 	else
5320 #endif
5321 	{
5322 	    pc = NULL;
5323 	    line = rline;
5324 	}
5325 
5326 	/* Split the line up in white separated items.  Put a NUL after each
5327 	 * item. */
5328 	itemcnt = 0;
5329 	for (p = line; ; )
5330 	{
5331 	    while (*p != NUL && *p <= ' ')  /* skip white space and CR/NL */
5332 		++p;
5333 	    if (*p == NUL)
5334 		break;
5335 	    if (itemcnt == MAXITEMCNT)	    /* too many items */
5336 		break;
5337 	    items[itemcnt++] = p;
5338 	    /* A few items have arbitrary text argument, don't split them. */
5339 	    if (itemcnt == 2 && spell_info_item(items[0]))
5340 		while (*p >= ' ' || *p == TAB)    /* skip until CR/NL */
5341 		    ++p;
5342 	    else
5343 		while (*p > ' ')    /* skip until white space or CR/NL */
5344 		    ++p;
5345 	    if (*p == NUL)
5346 		break;
5347 	    *p++ = NUL;
5348 	}
5349 
5350 	/* Handle non-empty lines. */
5351 	if (itemcnt > 0)
5352 	{
5353 	    if (is_aff_rule(items, itemcnt, "SET", 2) && aff->af_enc == NULL)
5354 	    {
5355 #ifdef FEAT_MBYTE
5356 		/* Setup for conversion from "ENC" to 'encoding'. */
5357 		aff->af_enc = enc_canonize(items[1]);
5358 		if (aff->af_enc != NULL && !spin->si_ascii
5359 			&& convert_setup(&spin->si_conv, aff->af_enc,
5360 							       p_enc) == FAIL)
5361 		    smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
5362 					       fname, aff->af_enc, p_enc);
5363 		spin->si_conv.vc_fail = TRUE;
5364 #else
5365 		    smsg((char_u *)_("Conversion in %s not supported"), fname);
5366 #endif
5367 	    }
5368 	    else if (is_aff_rule(items, itemcnt, "FLAG", 2)
5369 					      && aff->af_flagtype == AFT_CHAR)
5370 	    {
5371 		if (STRCMP(items[1], "long") == 0)
5372 		    aff->af_flagtype = AFT_LONG;
5373 		else if (STRCMP(items[1], "num") == 0)
5374 		    aff->af_flagtype = AFT_NUM;
5375 		else if (STRCMP(items[1], "caplong") == 0)
5376 		    aff->af_flagtype = AFT_CAPLONG;
5377 		else
5378 		    smsg((char_u *)_("Invalid value for FLAG in %s line %d: %s"),
5379 			    fname, lnum, items[1]);
5380 		if (aff->af_rare != 0
5381 			|| aff->af_keepcase != 0
5382 			|| aff->af_bad != 0
5383 			|| aff->af_needaffix != 0
5384 			|| aff->af_circumfix != 0
5385 			|| aff->af_needcomp != 0
5386 			|| aff->af_comproot != 0
5387 			|| aff->af_nosuggest != 0
5388 			|| compflags != NULL
5389 			|| aff->af_suff.ht_used > 0
5390 			|| aff->af_pref.ht_used > 0)
5391 		    smsg((char_u *)_("FLAG after using flags in %s line %d: %s"),
5392 			    fname, lnum, items[1]);
5393 	    }
5394 	    else if (spell_info_item(items[0]))
5395 	    {
5396 		    p = (char_u *)getroom(spin,
5397 			    (spin->si_info == NULL ? 0 : STRLEN(spin->si_info))
5398 			    + STRLEN(items[0])
5399 			    + STRLEN(items[1]) + 3, FALSE);
5400 		    if (p != NULL)
5401 		    {
5402 			if (spin->si_info != NULL)
5403 			{
5404 			    STRCPY(p, spin->si_info);
5405 			    STRCAT(p, "\n");
5406 			}
5407 			STRCAT(p, items[0]);
5408 			STRCAT(p, " ");
5409 			STRCAT(p, items[1]);
5410 			spin->si_info = p;
5411 		    }
5412 	    }
5413 	    else if (is_aff_rule(items, itemcnt, "MIDWORD", 2)
5414 							   && midword == NULL)
5415 	    {
5416 		midword = getroom_save(spin, items[1]);
5417 	    }
5418 	    else if (is_aff_rule(items, itemcnt, "TRY", 2))
5419 	    {
5420 		/* ignored, we look in the tree for what chars may appear */
5421 	    }
5422 	    /* TODO: remove "RAR" later */
5423 	    else if ((is_aff_rule(items, itemcnt, "RAR", 2)
5424 			|| is_aff_rule(items, itemcnt, "RARE", 2))
5425 							 && aff->af_rare == 0)
5426 	    {
5427 		aff->af_rare = affitem2flag(aff->af_flagtype, items[1],
5428 								 fname, lnum);
5429 	    }
5430 	    /* TODO: remove "KEP" later */
5431 	    else if ((is_aff_rule(items, itemcnt, "KEP", 2)
5432 			|| is_aff_rule(items, itemcnt, "KEEPCASE", 2))
5433 						     && aff->af_keepcase == 0)
5434 	    {
5435 		aff->af_keepcase = affitem2flag(aff->af_flagtype, items[1],
5436 								 fname, lnum);
5437 	    }
5438 	    else if ((is_aff_rule(items, itemcnt, "BAD", 2)
5439 			|| is_aff_rule(items, itemcnt, "FORBIDDENWORD", 2))
5440 							  && aff->af_bad == 0)
5441 	    {
5442 		aff->af_bad = affitem2flag(aff->af_flagtype, items[1],
5443 								 fname, lnum);
5444 	    }
5445 	    else if (is_aff_rule(items, itemcnt, "NEEDAFFIX", 2)
5446 						    && aff->af_needaffix == 0)
5447 	    {
5448 		aff->af_needaffix = affitem2flag(aff->af_flagtype, items[1],
5449 								 fname, lnum);
5450 	    }
5451 	    else if (is_aff_rule(items, itemcnt, "CIRCUMFIX", 2)
5452 						    && aff->af_circumfix == 0)
5453 	    {
5454 		aff->af_circumfix = affitem2flag(aff->af_flagtype, items[1],
5455 								 fname, lnum);
5456 	    }
5457 	    else if (is_aff_rule(items, itemcnt, "NOSUGGEST", 2)
5458 						    && aff->af_nosuggest == 0)
5459 	    {
5460 		aff->af_nosuggest = affitem2flag(aff->af_flagtype, items[1],
5461 								 fname, lnum);
5462 	    }
5463 	    else if ((is_aff_rule(items, itemcnt, "NEEDCOMPOUND", 2)
5464 			|| is_aff_rule(items, itemcnt, "ONLYINCOMPOUND", 2))
5465 						     && aff->af_needcomp == 0)
5466 	    {
5467 		aff->af_needcomp = affitem2flag(aff->af_flagtype, items[1],
5468 								 fname, lnum);
5469 	    }
5470 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDROOT", 2)
5471 						     && aff->af_comproot == 0)
5472 	    {
5473 		aff->af_comproot = affitem2flag(aff->af_flagtype, items[1],
5474 								 fname, lnum);
5475 	    }
5476 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDFORBIDFLAG", 2)
5477 						   && aff->af_compforbid == 0)
5478 	    {
5479 		aff->af_compforbid = affitem2flag(aff->af_flagtype, items[1],
5480 								 fname, lnum);
5481 		if (aff->af_pref.ht_used > 0)
5482 		    smsg((char_u *)_("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d"),
5483 			    fname, lnum);
5484 	    }
5485 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDPERMITFLAG", 2)
5486 						   && aff->af_comppermit == 0)
5487 	    {
5488 		aff->af_comppermit = affitem2flag(aff->af_flagtype, items[1],
5489 								 fname, lnum);
5490 		if (aff->af_pref.ht_used > 0)
5491 		    smsg((char_u *)_("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d"),
5492 			    fname, lnum);
5493 	    }
5494 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDFLAG", 2)
5495 							 && compflags == NULL)
5496 	    {
5497 		/* Turn flag "c" into COMPOUNDRULE compatible string "c+",
5498 		 * "Na" into "Na+", "1234" into "1234+". */
5499 		p = getroom(spin, STRLEN(items[1]) + 2, FALSE);
5500 		if (p != NULL)
5501 		{
5502 		    STRCPY(p, items[1]);
5503 		    STRCAT(p, "+");
5504 		    compflags = p;
5505 		}
5506 	    }
5507 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDRULES", 2))
5508 	    {
5509 		/* We don't use the count, but do check that it's a number and
5510 		 * not COMPOUNDRULE mistyped. */
5511 		if (atoi((char *)items[1]) == 0)
5512 		    smsg((char_u *)_("Wrong COMPOUNDRULES value in %s line %d: %s"),
5513 						       fname, lnum, items[1]);
5514 	    }
5515 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDRULE", 2))
5516 	    {
5517 		/* Don't use the first rule if it is a number. */
5518 		if (compflags != NULL || *skipdigits(items[1]) != NUL)
5519 		{
5520 		    /* Concatenate this string to previously defined ones,
5521 		     * using a slash to separate them. */
5522 		    l = (int)STRLEN(items[1]) + 1;
5523 		    if (compflags != NULL)
5524 			l += (int)STRLEN(compflags) + 1;
5525 		    p = getroom(spin, l, FALSE);
5526 		    if (p != NULL)
5527 		    {
5528 			if (compflags != NULL)
5529 			{
5530 			    STRCPY(p, compflags);
5531 			    STRCAT(p, "/");
5532 			}
5533 			STRCAT(p, items[1]);
5534 			compflags = p;
5535 		    }
5536 		}
5537 	    }
5538 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDWORDMAX", 2)
5539 							      && compmax == 0)
5540 	    {
5541 		compmax = atoi((char *)items[1]);
5542 		if (compmax == 0)
5543 		    smsg((char_u *)_("Wrong COMPOUNDWORDMAX value in %s line %d: %s"),
5544 						       fname, lnum, items[1]);
5545 	    }
5546 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDMIN", 2)
5547 							   && compminlen == 0)
5548 	    {
5549 		compminlen = atoi((char *)items[1]);
5550 		if (compminlen == 0)
5551 		    smsg((char_u *)_("Wrong COMPOUNDMIN value in %s line %d: %s"),
5552 						       fname, lnum, items[1]);
5553 	    }
5554 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDSYLMAX", 2)
5555 							   && compsylmax == 0)
5556 	    {
5557 		compsylmax = atoi((char *)items[1]);
5558 		if (compsylmax == 0)
5559 		    smsg((char_u *)_("Wrong COMPOUNDSYLMAX value in %s line %d: %s"),
5560 						       fname, lnum, items[1]);
5561 	    }
5562 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDDUP", 1))
5563 	    {
5564 		compoptions |= COMP_CHECKDUP;
5565 	    }
5566 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDREP", 1))
5567 	    {
5568 		compoptions |= COMP_CHECKREP;
5569 	    }
5570 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDCASE", 1))
5571 	    {
5572 		compoptions |= COMP_CHECKCASE;
5573 	    }
5574 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDTRIPLE", 1))
5575 	    {
5576 		compoptions |= COMP_CHECKTRIPLE;
5577 	    }
5578 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 2))
5579 	    {
5580 		if (atoi((char *)items[1]) == 0)
5581 		    smsg((char_u *)_("Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s"),
5582 						       fname, lnum, items[1]);
5583 	    }
5584 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 3))
5585 	    {
5586 		garray_T    *gap = &spin->si_comppat;
5587 		int	    i;
5588 
5589 		/* Only add the couple if it isn't already there. */
5590 		for (i = 0; i < gap->ga_len - 1; i += 2)
5591 		    if (STRCMP(((char_u **)(gap->ga_data))[i], items[1]) == 0
5592 			    && STRCMP(((char_u **)(gap->ga_data))[i + 1],
5593 							       items[2]) == 0)
5594 			break;
5595 		if (i >= gap->ga_len && ga_grow(gap, 2) == OK)
5596 		{
5597 		    ((char_u **)(gap->ga_data))[gap->ga_len++]
5598 					       = getroom_save(spin, items[1]);
5599 		    ((char_u **)(gap->ga_data))[gap->ga_len++]
5600 					       = getroom_save(spin, items[2]);
5601 		}
5602 	    }
5603 	    else if (is_aff_rule(items, itemcnt, "SYLLABLE", 2)
5604 							  && syllable == NULL)
5605 	    {
5606 		syllable = getroom_save(spin, items[1]);
5607 	    }
5608 	    else if (is_aff_rule(items, itemcnt, "NOBREAK", 1))
5609 	    {
5610 		spin->si_nobreak = TRUE;
5611 	    }
5612 	    else if (is_aff_rule(items, itemcnt, "NOSPLITSUGS", 1))
5613 	    {
5614 		spin->si_nosplitsugs = TRUE;
5615 	    }
5616 	    else if (is_aff_rule(items, itemcnt, "NOCOMPOUNDSUGS", 1))
5617 	    {
5618 		spin->si_nocompoundsugs = TRUE;
5619 	    }
5620 	    else if (is_aff_rule(items, itemcnt, "NOSUGFILE", 1))
5621 	    {
5622 		spin->si_nosugfile = TRUE;
5623 	    }
5624 	    else if (is_aff_rule(items, itemcnt, "PFXPOSTPONE", 1))
5625 	    {
5626 		aff->af_pfxpostpone = TRUE;
5627 	    }
5628 	    else if (is_aff_rule(items, itemcnt, "IGNOREEXTRA", 1))
5629 	    {
5630 		aff->af_ignoreextra = TRUE;
5631 	    }
5632 	    else if ((STRCMP(items[0], "PFX") == 0
5633 					      || STRCMP(items[0], "SFX") == 0)
5634 		    && aff_todo == 0
5635 		    && itemcnt >= 4)
5636 	    {
5637 		int	lasti = 4;
5638 		char_u	key[AH_KEY_LEN];
5639 
5640 		if (*items[0] == 'P')
5641 		    tp = &aff->af_pref;
5642 		else
5643 		    tp = &aff->af_suff;
5644 
5645 		/* Myspell allows the same affix name to be used multiple
5646 		 * times.  The affix files that do this have an undocumented
5647 		 * "S" flag on all but the last block, thus we check for that
5648 		 * and store it in ah_follows. */
5649 		vim_strncpy(key, items[1], AH_KEY_LEN - 1);
5650 		hi = hash_find(tp, key);
5651 		if (!HASHITEM_EMPTY(hi))
5652 		{
5653 		    cur_aff = HI2AH(hi);
5654 		    if (cur_aff->ah_combine != (*items[2] == 'Y'))
5655 			smsg((char_u *)_("Different combining flag in continued affix block in %s line %d: %s"),
5656 						   fname, lnum, items[1]);
5657 		    if (!cur_aff->ah_follows)
5658 			smsg((char_u *)_("Duplicate affix in %s line %d: %s"),
5659 						       fname, lnum, items[1]);
5660 		}
5661 		else
5662 		{
5663 		    /* New affix letter. */
5664 		    cur_aff = (affheader_T *)getroom(spin,
5665 						   sizeof(affheader_T), TRUE);
5666 		    if (cur_aff == NULL)
5667 			break;
5668 		    cur_aff->ah_flag = affitem2flag(aff->af_flagtype, items[1],
5669 								 fname, lnum);
5670 		    if (cur_aff->ah_flag == 0 || STRLEN(items[1]) >= AH_KEY_LEN)
5671 			break;
5672 		    if (cur_aff->ah_flag == aff->af_bad
5673 			    || cur_aff->ah_flag == aff->af_rare
5674 			    || cur_aff->ah_flag == aff->af_keepcase
5675 			    || cur_aff->ah_flag == aff->af_needaffix
5676 			    || cur_aff->ah_flag == aff->af_circumfix
5677 			    || cur_aff->ah_flag == aff->af_nosuggest
5678 			    || cur_aff->ah_flag == aff->af_needcomp
5679 			    || cur_aff->ah_flag == aff->af_comproot)
5680 			smsg((char_u *)_("Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in %s line %d: %s"),
5681 						       fname, lnum, items[1]);
5682 		    STRCPY(cur_aff->ah_key, items[1]);
5683 		    hash_add(tp, cur_aff->ah_key);
5684 
5685 		    cur_aff->ah_combine = (*items[2] == 'Y');
5686 		}
5687 
5688 		/* Check for the "S" flag, which apparently means that another
5689 		 * block with the same affix name is following. */
5690 		if (itemcnt > lasti && STRCMP(items[lasti], "S") == 0)
5691 		{
5692 		    ++lasti;
5693 		    cur_aff->ah_follows = TRUE;
5694 		}
5695 		else
5696 		    cur_aff->ah_follows = FALSE;
5697 
5698 		/* Myspell allows extra text after the item, but that might
5699 		 * mean mistakes go unnoticed.  Require a comment-starter. */
5700 		if (itemcnt > lasti && *items[lasti] != '#')
5701 		    smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]);
5702 
5703 		if (STRCMP(items[2], "Y") != 0 && STRCMP(items[2], "N") != 0)
5704 		    smsg((char_u *)_("Expected Y or N in %s line %d: %s"),
5705 						       fname, lnum, items[2]);
5706 
5707 		if (*items[0] == 'P' && aff->af_pfxpostpone)
5708 		{
5709 		    if (cur_aff->ah_newID == 0)
5710 		    {
5711 			/* Use a new number in the .spl file later, to be able
5712 			 * to handle multiple .aff files. */
5713 			check_renumber(spin);
5714 			cur_aff->ah_newID = ++spin->si_newprefID;
5715 
5716 			/* We only really use ah_newID if the prefix is
5717 			 * postponed.  We know that only after handling all
5718 			 * the items. */
5719 			did_postpone_prefix = FALSE;
5720 		    }
5721 		    else
5722 			/* Did use the ID in a previous block. */
5723 			did_postpone_prefix = TRUE;
5724 		}
5725 
5726 		aff_todo = atoi((char *)items[3]);
5727 	    }
5728 	    else if ((STRCMP(items[0], "PFX") == 0
5729 					      || STRCMP(items[0], "SFX") == 0)
5730 		    && aff_todo > 0
5731 		    && STRCMP(cur_aff->ah_key, items[1]) == 0
5732 		    && itemcnt >= 5)
5733 	    {
5734 		affentry_T	*aff_entry;
5735 		int		upper = FALSE;
5736 		int		lasti = 5;
5737 
5738 		/* Myspell allows extra text after the item, but that might
5739 		 * mean mistakes go unnoticed.  Require a comment-starter,
5740 		 * unless IGNOREEXTRA is used.  Hunspell uses a "-" item. */
5741 		if (itemcnt > lasti
5742 			&& !aff->af_ignoreextra
5743 			&& *items[lasti] != '#'
5744 			&& (STRCMP(items[lasti], "-") != 0
5745 						     || itemcnt != lasti + 1))
5746 		    smsg((char_u *)_(e_afftrailing), fname, lnum, items[lasti]);
5747 
5748 		/* New item for an affix letter. */
5749 		--aff_todo;
5750 		aff_entry = (affentry_T *)getroom(spin,
5751 						    sizeof(affentry_T), TRUE);
5752 		if (aff_entry == NULL)
5753 		    break;
5754 
5755 		if (STRCMP(items[2], "0") != 0)
5756 		    aff_entry->ae_chop = getroom_save(spin, items[2]);
5757 		if (STRCMP(items[3], "0") != 0)
5758 		{
5759 		    aff_entry->ae_add = getroom_save(spin, items[3]);
5760 
5761 		    /* Recognize flags on the affix: abcd/XYZ */
5762 		    aff_entry->ae_flags = vim_strchr(aff_entry->ae_add, '/');
5763 		    if (aff_entry->ae_flags != NULL)
5764 		    {
5765 			*aff_entry->ae_flags++ = NUL;
5766 			aff_process_flags(aff, aff_entry);
5767 		    }
5768 		}
5769 
5770 		/* Don't use an affix entry with non-ASCII characters when
5771 		 * "spin->si_ascii" is TRUE. */
5772 		if (!spin->si_ascii || !(has_non_ascii(aff_entry->ae_chop)
5773 					  || has_non_ascii(aff_entry->ae_add)))
5774 		{
5775 		    aff_entry->ae_next = cur_aff->ah_first;
5776 		    cur_aff->ah_first = aff_entry;
5777 
5778 		    if (STRCMP(items[4], ".") != 0)
5779 		    {
5780 			char_u	buf[MAXLINELEN];
5781 
5782 			aff_entry->ae_cond = getroom_save(spin, items[4]);
5783 			if (*items[0] == 'P')
5784 			    sprintf((char *)buf, "^%s", items[4]);
5785 			else
5786 			    sprintf((char *)buf, "%s$", items[4]);
5787 			aff_entry->ae_prog = vim_regcomp(buf,
5788 					    RE_MAGIC + RE_STRING + RE_STRICT);
5789 			if (aff_entry->ae_prog == NULL)
5790 			    smsg((char_u *)_("Broken condition in %s line %d: %s"),
5791 						       fname, lnum, items[4]);
5792 		    }
5793 
5794 		    /* For postponed prefixes we need an entry in si_prefcond
5795 		     * for the condition.  Use an existing one if possible.
5796 		     * Can't be done for an affix with flags, ignoring
5797 		     * COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG. */
5798 		    if (*items[0] == 'P' && aff->af_pfxpostpone
5799 					       && aff_entry->ae_flags == NULL)
5800 		    {
5801 			/* When the chop string is one lower-case letter and
5802 			 * the add string ends in the upper-case letter we set
5803 			 * the "upper" flag, clear "ae_chop" and remove the
5804 			 * letters from "ae_add".  The condition must either
5805 			 * be empty or start with the same letter. */
5806 			if (aff_entry->ae_chop != NULL
5807 				&& aff_entry->ae_add != NULL
5808 #ifdef FEAT_MBYTE
5809 				&& aff_entry->ae_chop[(*mb_ptr2len)(
5810 						   aff_entry->ae_chop)] == NUL
5811 #else
5812 				&& aff_entry->ae_chop[1] == NUL
5813 #endif
5814 				)
5815 			{
5816 			    int		c, c_up;
5817 
5818 			    c = PTR2CHAR(aff_entry->ae_chop);
5819 			    c_up = SPELL_TOUPPER(c);
5820 			    if (c_up != c
5821 				    && (aff_entry->ae_cond == NULL
5822 					|| PTR2CHAR(aff_entry->ae_cond) == c))
5823 			    {
5824 				p = aff_entry->ae_add
5825 						  + STRLEN(aff_entry->ae_add);
5826 				mb_ptr_back(aff_entry->ae_add, p);
5827 				if (PTR2CHAR(p) == c_up)
5828 				{
5829 				    upper = TRUE;
5830 				    aff_entry->ae_chop = NULL;
5831 				    *p = NUL;
5832 
5833 				    /* The condition is matched with the
5834 				     * actual word, thus must check for the
5835 				     * upper-case letter. */
5836 				    if (aff_entry->ae_cond != NULL)
5837 				    {
5838 					char_u	buf[MAXLINELEN];
5839 #ifdef FEAT_MBYTE
5840 					if (has_mbyte)
5841 					{
5842 					    onecap_copy(items[4], buf, TRUE);
5843 					    aff_entry->ae_cond = getroom_save(
5844 								   spin, buf);
5845 					}
5846 					else
5847 #endif
5848 					    *aff_entry->ae_cond = c_up;
5849 					if (aff_entry->ae_cond != NULL)
5850 					{
5851 					    sprintf((char *)buf, "^%s",
5852 							  aff_entry->ae_cond);
5853 					    vim_regfree(aff_entry->ae_prog);
5854 					    aff_entry->ae_prog = vim_regcomp(
5855 						    buf, RE_MAGIC + RE_STRING);
5856 					}
5857 				    }
5858 				}
5859 			    }
5860 			}
5861 
5862 			if (aff_entry->ae_chop == NULL
5863 					       && aff_entry->ae_flags == NULL)
5864 			{
5865 			    int		idx;
5866 			    char_u	**pp;
5867 			    int		n;
5868 
5869 			    /* Find a previously used condition. */
5870 			    for (idx = spin->si_prefcond.ga_len - 1; idx >= 0;
5871 									--idx)
5872 			    {
5873 				p = ((char_u **)spin->si_prefcond.ga_data)[idx];
5874 				if (str_equal(p, aff_entry->ae_cond))
5875 				    break;
5876 			    }
5877 			    if (idx < 0 && ga_grow(&spin->si_prefcond, 1) == OK)
5878 			    {
5879 				/* Not found, add a new condition. */
5880 				idx = spin->si_prefcond.ga_len++;
5881 				pp = ((char_u **)spin->si_prefcond.ga_data)
5882 									+ idx;
5883 				if (aff_entry->ae_cond == NULL)
5884 				    *pp = NULL;
5885 				else
5886 				    *pp = getroom_save(spin,
5887 							  aff_entry->ae_cond);
5888 			    }
5889 
5890 			    /* Add the prefix to the prefix tree. */
5891 			    if (aff_entry->ae_add == NULL)
5892 				p = (char_u *)"";
5893 			    else
5894 				p = aff_entry->ae_add;
5895 
5896 			    /* PFX_FLAGS is a negative number, so that
5897 			     * tree_add_word() knows this is the prefix tree. */
5898 			    n = PFX_FLAGS;
5899 			    if (!cur_aff->ah_combine)
5900 				n |= WFP_NC;
5901 			    if (upper)
5902 				n |= WFP_UP;
5903 			    if (aff_entry->ae_comppermit)
5904 				n |= WFP_COMPPERMIT;
5905 			    if (aff_entry->ae_compforbid)
5906 				n |= WFP_COMPFORBID;
5907 			    tree_add_word(spin, p, spin->si_prefroot, n,
5908 						      idx, cur_aff->ah_newID);
5909 			    did_postpone_prefix = TRUE;
5910 			}
5911 
5912 			/* Didn't actually use ah_newID, backup si_newprefID. */
5913 			if (aff_todo == 0 && !did_postpone_prefix)
5914 			{
5915 			    --spin->si_newprefID;
5916 			    cur_aff->ah_newID = 0;
5917 			}
5918 		    }
5919 		}
5920 	    }
5921 	    else if (is_aff_rule(items, itemcnt, "FOL", 2) && fol == NULL)
5922 	    {
5923 		fol = vim_strsave(items[1]);
5924 	    }
5925 	    else if (is_aff_rule(items, itemcnt, "LOW", 2) && low == NULL)
5926 	    {
5927 		low = vim_strsave(items[1]);
5928 	    }
5929 	    else if (is_aff_rule(items, itemcnt, "UPP", 2) && upp == NULL)
5930 	    {
5931 		upp = vim_strsave(items[1]);
5932 	    }
5933 	    else if (is_aff_rule(items, itemcnt, "REP", 2)
5934 		     || is_aff_rule(items, itemcnt, "REPSAL", 2))
5935 	    {
5936 		/* Ignore REP/REPSAL count */;
5937 		if (!isdigit(*items[1]))
5938 		    smsg((char_u *)_("Expected REP(SAL) count in %s line %d"),
5939 								 fname, lnum);
5940 	    }
5941 	    else if ((STRCMP(items[0], "REP") == 0
5942 			|| STRCMP(items[0], "REPSAL") == 0)
5943 		    && itemcnt >= 3)
5944 	    {
5945 		/* REP/REPSAL item */
5946 		/* Myspell ignores extra arguments, we require it starts with
5947 		 * # to detect mistakes. */
5948 		if (itemcnt > 3 && items[3][0] != '#')
5949 		    smsg((char_u *)_(e_afftrailing), fname, lnum, items[3]);
5950 		if (items[0][3] == 'S' ? do_repsal : do_rep)
5951 		{
5952 		    /* Replace underscore with space (can't include a space
5953 		     * directly). */
5954 		    for (p = items[1]; *p != NUL; mb_ptr_adv(p))
5955 			if (*p == '_')
5956 			    *p = ' ';
5957 		    for (p = items[2]; *p != NUL; mb_ptr_adv(p))
5958 			if (*p == '_')
5959 			    *p = ' ';
5960 		    add_fromto(spin, items[0][3] == 'S'
5961 					 ? &spin->si_repsal
5962 					 : &spin->si_rep, items[1], items[2]);
5963 		}
5964 	    }
5965 	    else if (is_aff_rule(items, itemcnt, "MAP", 2))
5966 	    {
5967 		/* MAP item or count */
5968 		if (!found_map)
5969 		{
5970 		    /* First line contains the count. */
5971 		    found_map = TRUE;
5972 		    if (!isdigit(*items[1]))
5973 			smsg((char_u *)_("Expected MAP count in %s line %d"),
5974 								 fname, lnum);
5975 		}
5976 		else if (do_mapline)
5977 		{
5978 		    int		c;
5979 
5980 		    /* Check that every character appears only once. */
5981 		    for (p = items[1]; *p != NUL; )
5982 		    {
5983 #ifdef FEAT_MBYTE
5984 			c = mb_ptr2char_adv(&p);
5985 #else
5986 			c = *p++;
5987 #endif
5988 			if ((spin->si_map.ga_len > 0
5989 				    && vim_strchr(spin->si_map.ga_data, c)
5990 								      != NULL)
5991 				|| vim_strchr(p, c) != NULL)
5992 			    smsg((char_u *)_("Duplicate character in MAP in %s line %d"),
5993 								 fname, lnum);
5994 		    }
5995 
5996 		    /* We simply concatenate all the MAP strings, separated by
5997 		     * slashes. */
5998 		    ga_concat(&spin->si_map, items[1]);
5999 		    ga_append(&spin->si_map, '/');
6000 		}
6001 	    }
6002 	    /* Accept "SAL from to" and "SAL from to  #comment". */
6003 	    else if (is_aff_rule(items, itemcnt, "SAL", 3))
6004 	    {
6005 		if (do_sal)
6006 		{
6007 		    /* SAL item (sounds-a-like)
6008 		     * Either one of the known keys or a from-to pair. */
6009 		    if (STRCMP(items[1], "followup") == 0)
6010 			spin->si_followup = sal_to_bool(items[2]);
6011 		    else if (STRCMP(items[1], "collapse_result") == 0)
6012 			spin->si_collapse = sal_to_bool(items[2]);
6013 		    else if (STRCMP(items[1], "remove_accents") == 0)
6014 			spin->si_rem_accents = sal_to_bool(items[2]);
6015 		    else
6016 			/* when "to" is "_" it means empty */
6017 			add_fromto(spin, &spin->si_sal, items[1],
6018 				     STRCMP(items[2], "_") == 0 ? (char_u *)""
6019 								: items[2]);
6020 		}
6021 	    }
6022 	    else if (is_aff_rule(items, itemcnt, "SOFOFROM", 2)
6023 							  && sofofrom == NULL)
6024 	    {
6025 		sofofrom = getroom_save(spin, items[1]);
6026 	    }
6027 	    else if (is_aff_rule(items, itemcnt, "SOFOTO", 2)
6028 							    && sofoto == NULL)
6029 	    {
6030 		sofoto = getroom_save(spin, items[1]);
6031 	    }
6032 	    else if (STRCMP(items[0], "COMMON") == 0)
6033 	    {
6034 		int	i;
6035 
6036 		for (i = 1; i < itemcnt; ++i)
6037 		{
6038 		    if (HASHITEM_EMPTY(hash_find(&spin->si_commonwords,
6039 								   items[i])))
6040 		    {
6041 			p = vim_strsave(items[i]);
6042 			if (p == NULL)
6043 			    break;
6044 			hash_add(&spin->si_commonwords, p);
6045 		    }
6046 		}
6047 	    }
6048 	    else
6049 		smsg((char_u *)_("Unrecognized or duplicate item in %s line %d: %s"),
6050 						       fname, lnum, items[0]);
6051 	}
6052     }
6053 
6054     if (fol != NULL || low != NULL || upp != NULL)
6055     {
6056 	if (spin->si_clear_chartab)
6057 	{
6058 	    /* Clear the char type tables, don't want to use any of the
6059 	     * currently used spell properties. */
6060 	    init_spell_chartab();
6061 	    spin->si_clear_chartab = FALSE;
6062 	}
6063 
6064 	/*
6065 	 * Don't write a word table for an ASCII file, so that we don't check
6066 	 * for conflicts with a word table that matches 'encoding'.
6067 	 * Don't write one for utf-8 either, we use utf_*() and
6068 	 * mb_get_class(), the list of chars in the file will be incomplete.
6069 	 */
6070 	if (!spin->si_ascii
6071 #ifdef FEAT_MBYTE
6072 		&& !enc_utf8
6073 #endif
6074 		)
6075 	{
6076 	    if (fol == NULL || low == NULL || upp == NULL)
6077 		smsg((char_u *)_("Missing FOL/LOW/UPP line in %s"), fname);
6078 	    else
6079 		(void)set_spell_chartab(fol, low, upp);
6080 	}
6081 
6082 	vim_free(fol);
6083 	vim_free(low);
6084 	vim_free(upp);
6085     }
6086 
6087     /* Use compound specifications of the .aff file for the spell info. */
6088     if (compmax != 0)
6089     {
6090 	aff_check_number(spin->si_compmax, compmax, "COMPOUNDWORDMAX");
6091 	spin->si_compmax = compmax;
6092     }
6093 
6094     if (compminlen != 0)
6095     {
6096 	aff_check_number(spin->si_compminlen, compminlen, "COMPOUNDMIN");
6097 	spin->si_compminlen = compminlen;
6098     }
6099 
6100     if (compsylmax != 0)
6101     {
6102 	if (syllable == NULL)
6103 	    smsg((char_u *)_("COMPOUNDSYLMAX used without SYLLABLE"));
6104 	aff_check_number(spin->si_compsylmax, compsylmax, "COMPOUNDSYLMAX");
6105 	spin->si_compsylmax = compsylmax;
6106     }
6107 
6108     if (compoptions != 0)
6109     {
6110 	aff_check_number(spin->si_compoptions, compoptions, "COMPOUND options");
6111 	spin->si_compoptions |= compoptions;
6112     }
6113 
6114     if (compflags != NULL)
6115 	process_compflags(spin, aff, compflags);
6116 
6117     /* Check that we didn't use too many renumbered flags. */
6118     if (spin->si_newcompID < spin->si_newprefID)
6119     {
6120 	if (spin->si_newcompID == 127 || spin->si_newcompID == 255)
6121 	    MSG(_("Too many postponed prefixes"));
6122 	else if (spin->si_newprefID == 0 || spin->si_newprefID == 127)
6123 	    MSG(_("Too many compound flags"));
6124 	else
6125 	    MSG(_("Too many postponed prefixes and/or compound flags"));
6126     }
6127 
6128     if (syllable != NULL)
6129     {
6130 	aff_check_string(spin->si_syllable, syllable, "SYLLABLE");
6131 	spin->si_syllable = syllable;
6132     }
6133 
6134     if (sofofrom != NULL || sofoto != NULL)
6135     {
6136 	if (sofofrom == NULL || sofoto == NULL)
6137 	    smsg((char_u *)_("Missing SOFO%s line in %s"),
6138 				     sofofrom == NULL ? "FROM" : "TO", fname);
6139 	else if (spin->si_sal.ga_len > 0)
6140 	    smsg((char_u *)_("Both SAL and SOFO lines in %s"), fname);
6141 	else
6142 	{
6143 	    aff_check_string(spin->si_sofofr, sofofrom, "SOFOFROM");
6144 	    aff_check_string(spin->si_sofoto, sofoto, "SOFOTO");
6145 	    spin->si_sofofr = sofofrom;
6146 	    spin->si_sofoto = sofoto;
6147 	}
6148     }
6149 
6150     if (midword != NULL)
6151     {
6152 	aff_check_string(spin->si_midword, midword, "MIDWORD");
6153 	spin->si_midword = midword;
6154     }
6155 
6156     vim_free(pc);
6157     fclose(fd);
6158     return aff;
6159 }
6160 
6161 /*
6162  * Return TRUE when items[0] equals "rulename", there are "mincount" items or
6163  * a comment is following after item "mincount".
6164  */
6165     static int
6166 is_aff_rule(items, itemcnt, rulename, mincount)
6167     char_u	**items;
6168     int		itemcnt;
6169     char	*rulename;
6170     int		mincount;
6171 {
6172     return (STRCMP(items[0], rulename) == 0
6173 	    && (itemcnt == mincount
6174 		|| (itemcnt > mincount && items[mincount][0] == '#')));
6175 }
6176 
6177 /*
6178  * For affix "entry" move COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG from
6179  * ae_flags to ae_comppermit and ae_compforbid.
6180  */
6181     static void
6182 aff_process_flags(affile, entry)
6183     afffile_T	*affile;
6184     affentry_T	*entry;
6185 {
6186     char_u	*p;
6187     char_u	*prevp;
6188     unsigned	flag;
6189 
6190     if (entry->ae_flags != NULL
6191 		&& (affile->af_compforbid != 0 || affile->af_comppermit != 0))
6192     {
6193 	for (p = entry->ae_flags; *p != NUL; )
6194 	{
6195 	    prevp = p;
6196 	    flag = get_affitem(affile->af_flagtype, &p);
6197 	    if (flag == affile->af_comppermit || flag == affile->af_compforbid)
6198 	    {
6199 		STRMOVE(prevp, p);
6200 		p = prevp;
6201 		if (flag == affile->af_comppermit)
6202 		    entry->ae_comppermit = TRUE;
6203 		else
6204 		    entry->ae_compforbid = TRUE;
6205 	    }
6206 	    if (affile->af_flagtype == AFT_NUM && *p == ',')
6207 		++p;
6208 	}
6209 	if (*entry->ae_flags == NUL)
6210 	    entry->ae_flags = NULL;	/* nothing left */
6211     }
6212 }
6213 
6214 /*
6215  * Return TRUE if "s" is the name of an info item in the affix file.
6216  */
6217     static int
6218 spell_info_item(s)
6219     char_u	*s;
6220 {
6221     return STRCMP(s, "NAME") == 0
6222 	|| STRCMP(s, "HOME") == 0
6223 	|| STRCMP(s, "VERSION") == 0
6224 	|| STRCMP(s, "AUTHOR") == 0
6225 	|| STRCMP(s, "EMAIL") == 0
6226 	|| STRCMP(s, "COPYRIGHT") == 0;
6227 }
6228 
6229 /*
6230  * Turn an affix flag name into a number, according to the FLAG type.
6231  * returns zero for failure.
6232  */
6233     static unsigned
6234 affitem2flag(flagtype, item, fname, lnum)
6235     int		flagtype;
6236     char_u	*item;
6237     char_u	*fname;
6238     int		lnum;
6239 {
6240     unsigned	res;
6241     char_u	*p = item;
6242 
6243     res = get_affitem(flagtype, &p);
6244     if (res == 0)
6245     {
6246 	if (flagtype == AFT_NUM)
6247 	    smsg((char_u *)_("Flag is not a number in %s line %d: %s"),
6248 							   fname, lnum, item);
6249 	else
6250 	    smsg((char_u *)_("Illegal flag in %s line %d: %s"),
6251 							   fname, lnum, item);
6252     }
6253     if (*p != NUL)
6254     {
6255 	smsg((char_u *)_(e_affname), fname, lnum, item);
6256 	return 0;
6257     }
6258 
6259     return res;
6260 }
6261 
6262 /*
6263  * Get one affix name from "*pp" and advance the pointer.
6264  * Returns zero for an error, still advances the pointer then.
6265  */
6266     static unsigned
6267 get_affitem(flagtype, pp)
6268     int		flagtype;
6269     char_u	**pp;
6270 {
6271     int		res;
6272 
6273     if (flagtype == AFT_NUM)
6274     {
6275 	if (!VIM_ISDIGIT(**pp))
6276 	{
6277 	    ++*pp;	/* always advance, avoid getting stuck */
6278 	    return 0;
6279 	}
6280 	res = getdigits(pp);
6281     }
6282     else
6283     {
6284 #ifdef FEAT_MBYTE
6285 	res = mb_ptr2char_adv(pp);
6286 #else
6287 	res = *(*pp)++;
6288 #endif
6289 	if (flagtype == AFT_LONG || (flagtype == AFT_CAPLONG
6290 						 && res >= 'A' && res <= 'Z'))
6291 	{
6292 	    if (**pp == NUL)
6293 		return 0;
6294 #ifdef FEAT_MBYTE
6295 	    res = mb_ptr2char_adv(pp) + (res << 16);
6296 #else
6297 	    res = *(*pp)++ + (res << 16);
6298 #endif
6299 	}
6300     }
6301     return res;
6302 }
6303 
6304 /*
6305  * Process the "compflags" string used in an affix file and append it to
6306  * spin->si_compflags.
6307  * The processing involves changing the affix names to ID numbers, so that
6308  * they fit in one byte.
6309  */
6310     static void
6311 process_compflags(spin, aff, compflags)
6312     spellinfo_T	*spin;
6313     afffile_T	*aff;
6314     char_u	*compflags;
6315 {
6316     char_u	*p;
6317     char_u	*prevp;
6318     unsigned	flag;
6319     compitem_T	*ci;
6320     int		id;
6321     int		len;
6322     char_u	*tp;
6323     char_u	key[AH_KEY_LEN];
6324     hashitem_T	*hi;
6325 
6326     /* Make room for the old and the new compflags, concatenated with a / in
6327      * between.  Processing it makes it shorter, but we don't know by how
6328      * much, thus allocate the maximum. */
6329     len = (int)STRLEN(compflags) + 1;
6330     if (spin->si_compflags != NULL)
6331 	len += (int)STRLEN(spin->si_compflags) + 1;
6332     p = getroom(spin, len, FALSE);
6333     if (p == NULL)
6334 	return;
6335     if (spin->si_compflags != NULL)
6336     {
6337 	STRCPY(p, spin->si_compflags);
6338 	STRCAT(p, "/");
6339     }
6340     spin->si_compflags = p;
6341     tp = p + STRLEN(p);
6342 
6343     for (p = compflags; *p != NUL; )
6344     {
6345 	if (vim_strchr((char_u *)"/?*+[]", *p) != NULL)
6346 	    /* Copy non-flag characters directly. */
6347 	    *tp++ = *p++;
6348 	else
6349 	{
6350 	    /* First get the flag number, also checks validity. */
6351 	    prevp = p;
6352 	    flag = get_affitem(aff->af_flagtype, &p);
6353 	    if (flag != 0)
6354 	    {
6355 		/* Find the flag in the hashtable.  If it was used before, use
6356 		 * the existing ID.  Otherwise add a new entry. */
6357 		vim_strncpy(key, prevp, p - prevp);
6358 		hi = hash_find(&aff->af_comp, key);
6359 		if (!HASHITEM_EMPTY(hi))
6360 		    id = HI2CI(hi)->ci_newID;
6361 		else
6362 		{
6363 		    ci = (compitem_T *)getroom(spin, sizeof(compitem_T), TRUE);
6364 		    if (ci == NULL)
6365 			break;
6366 		    STRCPY(ci->ci_key, key);
6367 		    ci->ci_flag = flag;
6368 		    /* Avoid using a flag ID that has a special meaning in a
6369 		     * regexp (also inside []). */
6370 		    do
6371 		    {
6372 			check_renumber(spin);
6373 			id = spin->si_newcompID--;
6374 		    } while (vim_strchr((char_u *)"/?*+[]\\-^", id) != NULL);
6375 		    ci->ci_newID = id;
6376 		    hash_add(&aff->af_comp, ci->ci_key);
6377 		}
6378 		*tp++ = id;
6379 	    }
6380 	    if (aff->af_flagtype == AFT_NUM && *p == ',')
6381 		++p;
6382 	}
6383     }
6384 
6385     *tp = NUL;
6386 }
6387 
6388 /*
6389  * Check that the new IDs for postponed affixes and compounding don't overrun
6390  * each other.  We have almost 255 available, but start at 0-127 to avoid
6391  * using two bytes for utf-8.  When the 0-127 range is used up go to 128-255.
6392  * When that is used up an error message is given.
6393  */
6394     static void
6395 check_renumber(spin)
6396     spellinfo_T	*spin;
6397 {
6398     if (spin->si_newprefID == spin->si_newcompID && spin->si_newcompID < 128)
6399     {
6400 	spin->si_newprefID = 127;
6401 	spin->si_newcompID = 255;
6402     }
6403 }
6404 
6405 /*
6406  * Return TRUE if flag "flag" appears in affix list "afflist".
6407  */
6408     static int
6409 flag_in_afflist(flagtype, afflist, flag)
6410     int		flagtype;
6411     char_u	*afflist;
6412     unsigned	flag;
6413 {
6414     char_u	*p;
6415     unsigned	n;
6416 
6417     switch (flagtype)
6418     {
6419 	case AFT_CHAR:
6420 	    return vim_strchr(afflist, flag) != NULL;
6421 
6422 	case AFT_CAPLONG:
6423 	case AFT_LONG:
6424 	    for (p = afflist; *p != NUL; )
6425 	    {
6426 #ifdef FEAT_MBYTE
6427 		n = mb_ptr2char_adv(&p);
6428 #else
6429 		n = *p++;
6430 #endif
6431 		if ((flagtype == AFT_LONG || (n >= 'A' && n <= 'Z'))
6432 								 && *p != NUL)
6433 #ifdef FEAT_MBYTE
6434 		    n = mb_ptr2char_adv(&p) + (n << 16);
6435 #else
6436 		    n = *p++ + (n << 16);
6437 #endif
6438 		if (n == flag)
6439 		    return TRUE;
6440 	    }
6441 	    break;
6442 
6443 	case AFT_NUM:
6444 	    for (p = afflist; *p != NUL; )
6445 	    {
6446 		n = getdigits(&p);
6447 		if (n == flag)
6448 		    return TRUE;
6449 		if (*p != NUL)	/* skip over comma */
6450 		    ++p;
6451 	    }
6452 	    break;
6453     }
6454     return FALSE;
6455 }
6456 
6457 /*
6458  * Give a warning when "spinval" and "affval" numbers are set and not the same.
6459  */
6460     static void
6461 aff_check_number(spinval, affval, name)
6462     int	    spinval;
6463     int	    affval;
6464     char    *name;
6465 {
6466     if (spinval != 0 && spinval != affval)
6467 	smsg((char_u *)_("%s value differs from what is used in another .aff file"), name);
6468 }
6469 
6470 /*
6471  * Give a warning when "spinval" and "affval" strings are set and not the same.
6472  */
6473     static void
6474 aff_check_string(spinval, affval, name)
6475     char_u	*spinval;
6476     char_u	*affval;
6477     char	*name;
6478 {
6479     if (spinval != NULL && STRCMP(spinval, affval) != 0)
6480 	smsg((char_u *)_("%s value differs from what is used in another .aff file"), name);
6481 }
6482 
6483 /*
6484  * Return TRUE if strings "s1" and "s2" are equal.  Also consider both being
6485  * NULL as equal.
6486  */
6487     static int
6488 str_equal(s1, s2)
6489     char_u	*s1;
6490     char_u	*s2;
6491 {
6492     if (s1 == NULL || s2 == NULL)
6493 	return s1 == s2;
6494     return STRCMP(s1, s2) == 0;
6495 }
6496 
6497 /*
6498  * Add a from-to item to "gap".  Used for REP and SAL items.
6499  * They are stored case-folded.
6500  */
6501     static void
6502 add_fromto(spin, gap, from, to)
6503     spellinfo_T	*spin;
6504     garray_T	*gap;
6505     char_u	*from;
6506     char_u	*to;
6507 {
6508     fromto_T	*ftp;
6509     char_u	word[MAXWLEN];
6510 
6511     if (ga_grow(gap, 1) == OK)
6512     {
6513 	ftp = ((fromto_T *)gap->ga_data) + gap->ga_len;
6514 	(void)spell_casefold(from, (int)STRLEN(from), word, MAXWLEN);
6515 	ftp->ft_from = getroom_save(spin, word);
6516 	(void)spell_casefold(to, (int)STRLEN(to), word, MAXWLEN);
6517 	ftp->ft_to = getroom_save(spin, word);
6518 	++gap->ga_len;
6519     }
6520 }
6521 
6522 /*
6523  * Convert a boolean argument in a SAL line to TRUE or FALSE;
6524  */
6525     static int
6526 sal_to_bool(s)
6527     char_u	*s;
6528 {
6529     return STRCMP(s, "1") == 0 || STRCMP(s, "true") == 0;
6530 }
6531 
6532 /*
6533  * Free the structure filled by spell_read_aff().
6534  */
6535     static void
6536 spell_free_aff(aff)
6537     afffile_T	*aff;
6538 {
6539     hashtab_T	*ht;
6540     hashitem_T	*hi;
6541     int		todo;
6542     affheader_T	*ah;
6543     affentry_T	*ae;
6544 
6545     vim_free(aff->af_enc);
6546 
6547     /* All this trouble to free the "ae_prog" items... */
6548     for (ht = &aff->af_pref; ; ht = &aff->af_suff)
6549     {
6550 	todo = (int)ht->ht_used;
6551 	for (hi = ht->ht_array; todo > 0; ++hi)
6552 	{
6553 	    if (!HASHITEM_EMPTY(hi))
6554 	    {
6555 		--todo;
6556 		ah = HI2AH(hi);
6557 		for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
6558 		    vim_regfree(ae->ae_prog);
6559 	    }
6560 	}
6561 	if (ht == &aff->af_suff)
6562 	    break;
6563     }
6564 
6565     hash_clear(&aff->af_pref);
6566     hash_clear(&aff->af_suff);
6567     hash_clear(&aff->af_comp);
6568 }
6569 
6570 /*
6571  * Read dictionary file "fname".
6572  * Returns OK or FAIL;
6573  */
6574     static int
6575 spell_read_dic(spin, fname, affile)
6576     spellinfo_T	*spin;
6577     char_u	*fname;
6578     afffile_T	*affile;
6579 {
6580     hashtab_T	ht;
6581     char_u	line[MAXLINELEN];
6582     char_u	*p;
6583     char_u	*afflist;
6584     char_u	store_afflist[MAXWLEN];
6585     int		pfxlen;
6586     int		need_affix;
6587     char_u	*dw;
6588     char_u	*pc;
6589     char_u	*w;
6590     int		l;
6591     hash_T	hash;
6592     hashitem_T	*hi;
6593     FILE	*fd;
6594     int		lnum = 1;
6595     int		non_ascii = 0;
6596     int		retval = OK;
6597     char_u	message[MAXLINELEN + MAXWLEN];
6598     int		flags;
6599     int		duplicate = 0;
6600 
6601     /*
6602      * Open the file.
6603      */
6604     fd = mch_fopen((char *)fname, "r");
6605     if (fd == NULL)
6606     {
6607 	EMSG2(_(e_notopen), fname);
6608 	return FAIL;
6609     }
6610 
6611     /* The hashtable is only used to detect duplicated words. */
6612     hash_init(&ht);
6613 
6614     vim_snprintf((char *)IObuff, IOSIZE,
6615 				  _("Reading dictionary file %s ..."), fname);
6616     spell_message(spin, IObuff);
6617 
6618     /* start with a message for the first line */
6619     spin->si_msg_count = 999999;
6620 
6621     /* Read and ignore the first line: word count. */
6622     (void)vim_fgets(line, MAXLINELEN, fd);
6623     if (!vim_isdigit(*skipwhite(line)))
6624 	EMSG2(_("E760: No word count in %s"), fname);
6625 
6626     /*
6627      * Read all the lines in the file one by one.
6628      * The words are converted to 'encoding' here, before being added to
6629      * the hashtable.
6630      */
6631     while (!vim_fgets(line, MAXLINELEN, fd) && !got_int)
6632     {
6633 	line_breakcheck();
6634 	++lnum;
6635 	if (line[0] == '#' || line[0] == '/')
6636 	    continue;	/* comment line */
6637 
6638 	/* Remove CR, LF and white space from the end.  White space halfway
6639 	 * the word is kept to allow e.g., "et al.". */
6640 	l = (int)STRLEN(line);
6641 	while (l > 0 && line[l - 1] <= ' ')
6642 	    --l;
6643 	if (l == 0)
6644 	    continue;	/* empty line */
6645 	line[l] = NUL;
6646 
6647 #ifdef FEAT_MBYTE
6648 	/* Convert from "SET" to 'encoding' when needed. */
6649 	if (spin->si_conv.vc_type != CONV_NONE)
6650 	{
6651 	    pc = string_convert(&spin->si_conv, line, NULL);
6652 	    if (pc == NULL)
6653 	    {
6654 		smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
6655 						       fname, lnum, line);
6656 		continue;
6657 	    }
6658 	    w = pc;
6659 	}
6660 	else
6661 #endif
6662 	{
6663 	    pc = NULL;
6664 	    w = line;
6665 	}
6666 
6667 	/* Truncate the word at the "/", set "afflist" to what follows.
6668 	 * Replace "\/" by "/" and "\\" by "\". */
6669 	afflist = NULL;
6670 	for (p = w; *p != NUL; mb_ptr_adv(p))
6671 	{
6672 	    if (*p == '\\' && (p[1] == '\\' || p[1] == '/'))
6673 		STRMOVE(p, p + 1);
6674 	    else if (*p == '/')
6675 	    {
6676 		*p = NUL;
6677 		afflist = p + 1;
6678 		break;
6679 	    }
6680 	}
6681 
6682 	/* Skip non-ASCII words when "spin->si_ascii" is TRUE. */
6683 	if (spin->si_ascii && has_non_ascii(w))
6684 	{
6685 	    ++non_ascii;
6686 	    vim_free(pc);
6687 	    continue;
6688 	}
6689 
6690 	/* This takes time, print a message every 10000 words. */
6691 	if (spin->si_verbose && spin->si_msg_count > 10000)
6692 	{
6693 	    spin->si_msg_count = 0;
6694 	    vim_snprintf((char *)message, sizeof(message),
6695 		    _("line %6d, word %6d - %s"),
6696 		       lnum, spin->si_foldwcount + spin->si_keepwcount, w);
6697 	    msg_start();
6698 	    msg_puts_long_attr(message, 0);
6699 	    msg_clr_eos();
6700 	    msg_didout = FALSE;
6701 	    msg_col = 0;
6702 	    out_flush();
6703 	}
6704 
6705 	/* Store the word in the hashtable to be able to find duplicates. */
6706 	dw = (char_u *)getroom_save(spin, w);
6707 	if (dw == NULL)
6708 	{
6709 	    retval = FAIL;
6710 	    vim_free(pc);
6711 	    break;
6712 	}
6713 
6714 	hash = hash_hash(dw);
6715 	hi = hash_lookup(&ht, dw, hash);
6716 	if (!HASHITEM_EMPTY(hi))
6717 	{
6718 	    if (p_verbose > 0)
6719 		smsg((char_u *)_("Duplicate word in %s line %d: %s"),
6720 							     fname, lnum, dw);
6721 	    else if (duplicate == 0)
6722 		smsg((char_u *)_("First duplicate word in %s line %d: %s"),
6723 							     fname, lnum, dw);
6724 	    ++duplicate;
6725 	}
6726 	else
6727 	    hash_add_item(&ht, hi, dw, hash);
6728 
6729 	flags = 0;
6730 	store_afflist[0] = NUL;
6731 	pfxlen = 0;
6732 	need_affix = FALSE;
6733 	if (afflist != NULL)
6734 	{
6735 	    /* Extract flags from the affix list. */
6736 	    flags |= get_affix_flags(affile, afflist);
6737 
6738 	    if (affile->af_needaffix != 0 && flag_in_afflist(
6739 			  affile->af_flagtype, afflist, affile->af_needaffix))
6740 		need_affix = TRUE;
6741 
6742 	    if (affile->af_pfxpostpone)
6743 		/* Need to store the list of prefix IDs with the word. */
6744 		pfxlen = get_pfxlist(affile, afflist, store_afflist);
6745 
6746 	    if (spin->si_compflags != NULL)
6747 		/* Need to store the list of compound flags with the word.
6748 		 * Concatenate them to the list of prefix IDs. */
6749 		get_compflags(affile, afflist, store_afflist + pfxlen);
6750 	}
6751 
6752 	/* Add the word to the word tree(s). */
6753 	if (store_word(spin, dw, flags, spin->si_region,
6754 					   store_afflist, need_affix) == FAIL)
6755 	    retval = FAIL;
6756 
6757 	if (afflist != NULL)
6758 	{
6759 	    /* Find all matching suffixes and add the resulting words.
6760 	     * Additionally do matching prefixes that combine. */
6761 	    if (store_aff_word(spin, dw, afflist, affile,
6762 			   &affile->af_suff, &affile->af_pref,
6763 			    CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
6764 		retval = FAIL;
6765 
6766 	    /* Find all matching prefixes and add the resulting words. */
6767 	    if (store_aff_word(spin, dw, afflist, affile,
6768 			  &affile->af_pref, NULL,
6769 			    CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
6770 		retval = FAIL;
6771 	}
6772 
6773 	vim_free(pc);
6774     }
6775 
6776     if (duplicate > 0)
6777 	smsg((char_u *)_("%d duplicate word(s) in %s"), duplicate, fname);
6778     if (spin->si_ascii && non_ascii > 0)
6779 	smsg((char_u *)_("Ignored %d word(s) with non-ASCII characters in %s"),
6780 							    non_ascii, fname);
6781     hash_clear(&ht);
6782 
6783     fclose(fd);
6784     return retval;
6785 }
6786 
6787 /*
6788  * Check for affix flags in "afflist" that are turned into word flags.
6789  * Return WF_ flags.
6790  */
6791     static int
6792 get_affix_flags(affile, afflist)
6793     afffile_T	*affile;
6794     char_u	*afflist;
6795 {
6796     int		flags = 0;
6797 
6798     if (affile->af_keepcase != 0 && flag_in_afflist(
6799 			   affile->af_flagtype, afflist, affile->af_keepcase))
6800 	flags |= WF_KEEPCAP | WF_FIXCAP;
6801     if (affile->af_rare != 0 && flag_in_afflist(
6802 			       affile->af_flagtype, afflist, affile->af_rare))
6803 	flags |= WF_RARE;
6804     if (affile->af_bad != 0 && flag_in_afflist(
6805 				affile->af_flagtype, afflist, affile->af_bad))
6806 	flags |= WF_BANNED;
6807     if (affile->af_needcomp != 0 && flag_in_afflist(
6808 			   affile->af_flagtype, afflist, affile->af_needcomp))
6809 	flags |= WF_NEEDCOMP;
6810     if (affile->af_comproot != 0 && flag_in_afflist(
6811 			   affile->af_flagtype, afflist, affile->af_comproot))
6812 	flags |= WF_COMPROOT;
6813     if (affile->af_nosuggest != 0 && flag_in_afflist(
6814 			  affile->af_flagtype, afflist, affile->af_nosuggest))
6815 	flags |= WF_NOSUGGEST;
6816     return flags;
6817 }
6818 
6819 /*
6820  * Get the list of prefix IDs from the affix list "afflist".
6821  * Used for PFXPOSTPONE.
6822  * Put the resulting flags in "store_afflist[MAXWLEN]" with a terminating NUL
6823  * and return the number of affixes.
6824  */
6825     static int
6826 get_pfxlist(affile, afflist, store_afflist)
6827     afffile_T	*affile;
6828     char_u	*afflist;
6829     char_u	*store_afflist;
6830 {
6831     char_u	*p;
6832     char_u	*prevp;
6833     int		cnt = 0;
6834     int		id;
6835     char_u	key[AH_KEY_LEN];
6836     hashitem_T	*hi;
6837 
6838     for (p = afflist; *p != NUL; )
6839     {
6840 	prevp = p;
6841 	if (get_affitem(affile->af_flagtype, &p) != 0)
6842 	{
6843 	    /* A flag is a postponed prefix flag if it appears in "af_pref"
6844 	     * and it's ID is not zero. */
6845 	    vim_strncpy(key, prevp, p - prevp);
6846 	    hi = hash_find(&affile->af_pref, key);
6847 	    if (!HASHITEM_EMPTY(hi))
6848 	    {
6849 		id = HI2AH(hi)->ah_newID;
6850 		if (id != 0)
6851 		    store_afflist[cnt++] = id;
6852 	    }
6853 	}
6854 	if (affile->af_flagtype == AFT_NUM && *p == ',')
6855 	    ++p;
6856     }
6857 
6858     store_afflist[cnt] = NUL;
6859     return cnt;
6860 }
6861 
6862 /*
6863  * Get the list of compound IDs from the affix list "afflist" that are used
6864  * for compound words.
6865  * Puts the flags in "store_afflist[]".
6866  */
6867     static void
6868 get_compflags(affile, afflist, store_afflist)
6869     afffile_T	*affile;
6870     char_u	*afflist;
6871     char_u	*store_afflist;
6872 {
6873     char_u	*p;
6874     char_u	*prevp;
6875     int		cnt = 0;
6876     char_u	key[AH_KEY_LEN];
6877     hashitem_T	*hi;
6878 
6879     for (p = afflist; *p != NUL; )
6880     {
6881 	prevp = p;
6882 	if (get_affitem(affile->af_flagtype, &p) != 0)
6883 	{
6884 	    /* A flag is a compound flag if it appears in "af_comp". */
6885 	    vim_strncpy(key, prevp, p - prevp);
6886 	    hi = hash_find(&affile->af_comp, key);
6887 	    if (!HASHITEM_EMPTY(hi))
6888 		store_afflist[cnt++] = HI2CI(hi)->ci_newID;
6889 	}
6890 	if (affile->af_flagtype == AFT_NUM && *p == ',')
6891 	    ++p;
6892     }
6893 
6894     store_afflist[cnt] = NUL;
6895 }
6896 
6897 /*
6898  * Apply affixes to a word and store the resulting words.
6899  * "ht" is the hashtable with affentry_T that need to be applied, either
6900  * prefixes or suffixes.
6901  * "xht", when not NULL, is the prefix hashtable, to be used additionally on
6902  * the resulting words for combining affixes.
6903  *
6904  * Returns FAIL when out of memory.
6905  */
6906     static int
6907 store_aff_word(spin, word, afflist, affile, ht, xht, condit, flags,
6908 							      pfxlist, pfxlen)
6909     spellinfo_T	*spin;		/* spell info */
6910     char_u	*word;		/* basic word start */
6911     char_u	*afflist;	/* list of names of supported affixes */
6912     afffile_T	*affile;
6913     hashtab_T	*ht;
6914     hashtab_T	*xht;
6915     int		condit;		/* CONDIT_SUF et al. */
6916     int		flags;		/* flags for the word */
6917     char_u	*pfxlist;	/* list of prefix IDs */
6918     int		pfxlen;		/* nr of flags in "pfxlist" for prefixes, rest
6919 				 * is compound flags */
6920 {
6921     int		todo;
6922     hashitem_T	*hi;
6923     affheader_T	*ah;
6924     affentry_T	*ae;
6925     char_u	newword[MAXWLEN];
6926     int		retval = OK;
6927     int		i, j;
6928     char_u	*p;
6929     int		use_flags;
6930     char_u	*use_pfxlist;
6931     int		use_pfxlen;
6932     int		need_affix;
6933     char_u	store_afflist[MAXWLEN];
6934     char_u	pfx_pfxlist[MAXWLEN];
6935     size_t	wordlen = STRLEN(word);
6936     int		use_condit;
6937 
6938     todo = (int)ht->ht_used;
6939     for (hi = ht->ht_array; todo > 0 && retval == OK; ++hi)
6940     {
6941 	if (!HASHITEM_EMPTY(hi))
6942 	{
6943 	    --todo;
6944 	    ah = HI2AH(hi);
6945 
6946 	    /* Check that the affix combines, if required, and that the word
6947 	     * supports this affix. */
6948 	    if (((condit & CONDIT_COMB) == 0 || ah->ah_combine)
6949 		    && flag_in_afflist(affile->af_flagtype, afflist,
6950 								 ah->ah_flag))
6951 	    {
6952 		/* Loop over all affix entries with this name. */
6953 		for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
6954 		{
6955 		    /* Check the condition.  It's not logical to match case
6956 		     * here, but it is required for compatibility with
6957 		     * Myspell.
6958 		     * Another requirement from Myspell is that the chop
6959 		     * string is shorter than the word itself.
6960 		     * For prefixes, when "PFXPOSTPONE" was used, only do
6961 		     * prefixes with a chop string and/or flags.
6962 		     * When a previously added affix had CIRCUMFIX this one
6963 		     * must have it too, if it had not then this one must not
6964 		     * have one either. */
6965 		    if ((xht != NULL || !affile->af_pfxpostpone
6966 				|| ae->ae_chop != NULL
6967 				|| ae->ae_flags != NULL)
6968 			    && (ae->ae_chop == NULL
6969 				|| STRLEN(ae->ae_chop) < wordlen)
6970 			    && (ae->ae_prog == NULL
6971 				|| vim_regexec_prog(&ae->ae_prog, FALSE,
6972 							    word, (colnr_T)0))
6973 			    && (((condit & CONDIT_CFIX) == 0)
6974 				== ((condit & CONDIT_AFF) == 0
6975 				    || ae->ae_flags == NULL
6976 				    || !flag_in_afflist(affile->af_flagtype,
6977 					ae->ae_flags, affile->af_circumfix))))
6978 		    {
6979 			/* Match.  Remove the chop and add the affix. */
6980 			if (xht == NULL)
6981 			{
6982 			    /* prefix: chop/add at the start of the word */
6983 			    if (ae->ae_add == NULL)
6984 				*newword = NUL;
6985 			    else
6986 				vim_strncpy(newword, ae->ae_add, MAXWLEN - 1);
6987 			    p = word;
6988 			    if (ae->ae_chop != NULL)
6989 			    {
6990 				/* Skip chop string. */
6991 #ifdef FEAT_MBYTE
6992 				if (has_mbyte)
6993 				{
6994 				    i = mb_charlen(ae->ae_chop);
6995 				    for ( ; i > 0; --i)
6996 					mb_ptr_adv(p);
6997 				}
6998 				else
6999 #endif
7000 				    p += STRLEN(ae->ae_chop);
7001 			    }
7002 			    STRCAT(newword, p);
7003 			}
7004 			else
7005 			{
7006 			    /* suffix: chop/add at the end of the word */
7007 			    vim_strncpy(newword, word, MAXWLEN - 1);
7008 			    if (ae->ae_chop != NULL)
7009 			    {
7010 				/* Remove chop string. */
7011 				p = newword + STRLEN(newword);
7012 				i = (int)MB_CHARLEN(ae->ae_chop);
7013 				for ( ; i > 0; --i)
7014 				    mb_ptr_back(newword, p);
7015 				*p = NUL;
7016 			    }
7017 			    if (ae->ae_add != NULL)
7018 				STRCAT(newword, ae->ae_add);
7019 			}
7020 
7021 			use_flags = flags;
7022 			use_pfxlist = pfxlist;
7023 			use_pfxlen = pfxlen;
7024 			need_affix = FALSE;
7025 			use_condit = condit | CONDIT_COMB | CONDIT_AFF;
7026 			if (ae->ae_flags != NULL)
7027 			{
7028 			    /* Extract flags from the affix list. */
7029 			    use_flags |= get_affix_flags(affile, ae->ae_flags);
7030 
7031 			    if (affile->af_needaffix != 0 && flag_in_afflist(
7032 					affile->af_flagtype, ae->ae_flags,
7033 							affile->af_needaffix))
7034 				need_affix = TRUE;
7035 
7036 			    /* When there is a CIRCUMFIX flag the other affix
7037 			     * must also have it and we don't add the word
7038 			     * with one affix. */
7039 			    if (affile->af_circumfix != 0 && flag_in_afflist(
7040 					affile->af_flagtype, ae->ae_flags,
7041 							affile->af_circumfix))
7042 			    {
7043 				use_condit |= CONDIT_CFIX;
7044 				if ((condit & CONDIT_CFIX) == 0)
7045 				    need_affix = TRUE;
7046 			    }
7047 
7048 			    if (affile->af_pfxpostpone
7049 						|| spin->si_compflags != NULL)
7050 			    {
7051 				if (affile->af_pfxpostpone)
7052 				    /* Get prefix IDS from the affix list. */
7053 				    use_pfxlen = get_pfxlist(affile,
7054 						 ae->ae_flags, store_afflist);
7055 				else
7056 				    use_pfxlen = 0;
7057 				use_pfxlist = store_afflist;
7058 
7059 				/* Combine the prefix IDs. Avoid adding the
7060 				 * same ID twice. */
7061 				for (i = 0; i < pfxlen; ++i)
7062 				{
7063 				    for (j = 0; j < use_pfxlen; ++j)
7064 					if (pfxlist[i] == use_pfxlist[j])
7065 					    break;
7066 				    if (j == use_pfxlen)
7067 					use_pfxlist[use_pfxlen++] = pfxlist[i];
7068 				}
7069 
7070 				if (spin->si_compflags != NULL)
7071 				    /* Get compound IDS from the affix list. */
7072 				    get_compflags(affile, ae->ae_flags,
7073 						  use_pfxlist + use_pfxlen);
7074 
7075 				/* Combine the list of compound flags.
7076 				 * Concatenate them to the prefix IDs list.
7077 				 * Avoid adding the same ID twice. */
7078 				for (i = pfxlen; pfxlist[i] != NUL; ++i)
7079 				{
7080 				    for (j = use_pfxlen;
7081 						   use_pfxlist[j] != NUL; ++j)
7082 					if (pfxlist[i] == use_pfxlist[j])
7083 					    break;
7084 				    if (use_pfxlist[j] == NUL)
7085 				    {
7086 					use_pfxlist[j++] = pfxlist[i];
7087 					use_pfxlist[j] = NUL;
7088 				    }
7089 				}
7090 			    }
7091 			}
7092 
7093 			/* Obey a "COMPOUNDFORBIDFLAG" of the affix: don't
7094 			 * use the compound flags. */
7095 			if (use_pfxlist != NULL && ae->ae_compforbid)
7096 			{
7097 			    vim_strncpy(pfx_pfxlist, use_pfxlist, use_pfxlen);
7098 			    use_pfxlist = pfx_pfxlist;
7099 			}
7100 
7101 			/* When there are postponed prefixes... */
7102 			if (spin->si_prefroot != NULL
7103 				&& spin->si_prefroot->wn_sibling != NULL)
7104 			{
7105 			    /* ... add a flag to indicate an affix was used. */
7106 			    use_flags |= WF_HAS_AFF;
7107 
7108 			    /* ... don't use a prefix list if combining
7109 			     * affixes is not allowed.  But do use the
7110 			     * compound flags after them. */
7111 			    if (!ah->ah_combine && use_pfxlist != NULL)
7112 				use_pfxlist += use_pfxlen;
7113 			}
7114 
7115 			/* When compounding is supported and there is no
7116 			 * "COMPOUNDPERMITFLAG" then forbid compounding on the
7117 			 * side where the affix is applied. */
7118 			if (spin->si_compflags != NULL && !ae->ae_comppermit)
7119 			{
7120 			    if (xht != NULL)
7121 				use_flags |= WF_NOCOMPAFT;
7122 			    else
7123 				use_flags |= WF_NOCOMPBEF;
7124 			}
7125 
7126 			/* Store the modified word. */
7127 			if (store_word(spin, newword, use_flags,
7128 						 spin->si_region, use_pfxlist,
7129 							  need_affix) == FAIL)
7130 			    retval = FAIL;
7131 
7132 			/* When added a prefix or a first suffix and the affix
7133 			 * has flags may add a(nother) suffix.  RECURSIVE! */
7134 			if ((condit & CONDIT_SUF) && ae->ae_flags != NULL)
7135 			    if (store_aff_word(spin, newword, ae->ae_flags,
7136 					affile, &affile->af_suff, xht,
7137 					   use_condit & (xht == NULL
7138 							? ~0 :  ~CONDIT_SUF),
7139 				      use_flags, use_pfxlist, pfxlen) == FAIL)
7140 				retval = FAIL;
7141 
7142 			/* When added a suffix and combining is allowed also
7143 			 * try adding a prefix additionally.  Both for the
7144 			 * word flags and for the affix flags.  RECURSIVE! */
7145 			if (xht != NULL && ah->ah_combine)
7146 			{
7147 			    if (store_aff_word(spin, newword,
7148 					afflist, affile,
7149 					xht, NULL, use_condit,
7150 					use_flags, use_pfxlist,
7151 					pfxlen) == FAIL
7152 				    || (ae->ae_flags != NULL
7153 					&& store_aff_word(spin, newword,
7154 					    ae->ae_flags, affile,
7155 					    xht, NULL, use_condit,
7156 					    use_flags, use_pfxlist,
7157 					    pfxlen) == FAIL))
7158 				retval = FAIL;
7159 			}
7160 		    }
7161 		}
7162 	    }
7163 	}
7164     }
7165 
7166     return retval;
7167 }
7168 
7169 /*
7170  * Read a file with a list of words.
7171  */
7172     static int
7173 spell_read_wordfile(spin, fname)
7174     spellinfo_T	*spin;
7175     char_u	*fname;
7176 {
7177     FILE	*fd;
7178     long	lnum = 0;
7179     char_u	rline[MAXLINELEN];
7180     char_u	*line;
7181     char_u	*pc = NULL;
7182     char_u	*p;
7183     int		l;
7184     int		retval = OK;
7185     int		did_word = FALSE;
7186     int		non_ascii = 0;
7187     int		flags;
7188     int		regionmask;
7189 
7190     /*
7191      * Open the file.
7192      */
7193     fd = mch_fopen((char *)fname, "r");
7194     if (fd == NULL)
7195     {
7196 	EMSG2(_(e_notopen), fname);
7197 	return FAIL;
7198     }
7199 
7200     vim_snprintf((char *)IObuff, IOSIZE, _("Reading word file %s ..."), fname);
7201     spell_message(spin, IObuff);
7202 
7203     /*
7204      * Read all the lines in the file one by one.
7205      */
7206     while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
7207     {
7208 	line_breakcheck();
7209 	++lnum;
7210 
7211 	/* Skip comment lines. */
7212 	if (*rline == '#')
7213 	    continue;
7214 
7215 	/* Remove CR, LF and white space from the end. */
7216 	l = (int)STRLEN(rline);
7217 	while (l > 0 && rline[l - 1] <= ' ')
7218 	    --l;
7219 	if (l == 0)
7220 	    continue;	/* empty or blank line */
7221 	rline[l] = NUL;
7222 
7223 	/* Convert from "/encoding={encoding}" to 'encoding' when needed. */
7224 	vim_free(pc);
7225 #ifdef FEAT_MBYTE
7226 	if (spin->si_conv.vc_type != CONV_NONE)
7227 	{
7228 	    pc = string_convert(&spin->si_conv, rline, NULL);
7229 	    if (pc == NULL)
7230 	    {
7231 		smsg((char_u *)_("Conversion failure for word in %s line %d: %s"),
7232 							   fname, lnum, rline);
7233 		continue;
7234 	    }
7235 	    line = pc;
7236 	}
7237 	else
7238 #endif
7239 	{
7240 	    pc = NULL;
7241 	    line = rline;
7242 	}
7243 
7244 	if (*line == '/')
7245 	{
7246 	    ++line;
7247 	    if (STRNCMP(line, "encoding=", 9) == 0)
7248 	    {
7249 		if (spin->si_conv.vc_type != CONV_NONE)
7250 		    smsg((char_u *)_("Duplicate /encoding= line ignored in %s line %d: %s"),
7251 						       fname, lnum, line - 1);
7252 		else if (did_word)
7253 		    smsg((char_u *)_("/encoding= line after word ignored in %s line %d: %s"),
7254 						       fname, lnum, line - 1);
7255 		else
7256 		{
7257 #ifdef FEAT_MBYTE
7258 		    char_u	*enc;
7259 
7260 		    /* Setup for conversion to 'encoding'. */
7261 		    line += 9;
7262 		    enc = enc_canonize(line);
7263 		    if (enc != NULL && !spin->si_ascii
7264 			    && convert_setup(&spin->si_conv, enc,
7265 							       p_enc) == FAIL)
7266 			smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
7267 							  fname, line, p_enc);
7268 		    vim_free(enc);
7269 		    spin->si_conv.vc_fail = TRUE;
7270 #else
7271 		    smsg((char_u *)_("Conversion in %s not supported"), fname);
7272 #endif
7273 		}
7274 		continue;
7275 	    }
7276 
7277 	    if (STRNCMP(line, "regions=", 8) == 0)
7278 	    {
7279 		if (spin->si_region_count > 1)
7280 		    smsg((char_u *)_("Duplicate /regions= line ignored in %s line %d: %s"),
7281 						       fname, lnum, line);
7282 		else
7283 		{
7284 		    line += 8;
7285 		    if (STRLEN(line) > 16)
7286 			smsg((char_u *)_("Too many regions in %s line %d: %s"),
7287 						       fname, lnum, line);
7288 		    else
7289 		    {
7290 			spin->si_region_count = (int)STRLEN(line) / 2;
7291 			STRCPY(spin->si_region_name, line);
7292 
7293 			/* Adjust the mask for a word valid in all regions. */
7294 			spin->si_region = (1 << spin->si_region_count) - 1;
7295 		    }
7296 		}
7297 		continue;
7298 	    }
7299 
7300 	    smsg((char_u *)_("/ line ignored in %s line %d: %s"),
7301 						       fname, lnum, line - 1);
7302 	    continue;
7303 	}
7304 
7305 	flags = 0;
7306 	regionmask = spin->si_region;
7307 
7308 	/* Check for flags and region after a slash. */
7309 	p = vim_strchr(line, '/');
7310 	if (p != NULL)
7311 	{
7312 	    *p++ = NUL;
7313 	    while (*p != NUL)
7314 	    {
7315 		if (*p == '=')		/* keep-case word */
7316 		    flags |= WF_KEEPCAP | WF_FIXCAP;
7317 		else if (*p == '!')	/* Bad, bad, wicked word. */
7318 		    flags |= WF_BANNED;
7319 		else if (*p == '?')	/* Rare word. */
7320 		    flags |= WF_RARE;
7321 		else if (VIM_ISDIGIT(*p)) /* region number(s) */
7322 		{
7323 		    if ((flags & WF_REGION) == 0)   /* first one */
7324 			regionmask = 0;
7325 		    flags |= WF_REGION;
7326 
7327 		    l = *p - '0';
7328 		    if (l > spin->si_region_count)
7329 		    {
7330 			smsg((char_u *)_("Invalid region nr in %s line %d: %s"),
7331 							  fname, lnum, p);
7332 			break;
7333 		    }
7334 		    regionmask |= 1 << (l - 1);
7335 		}
7336 		else
7337 		{
7338 		    smsg((char_u *)_("Unrecognized flags in %s line %d: %s"),
7339 							      fname, lnum, p);
7340 		    break;
7341 		}
7342 		++p;
7343 	    }
7344 	}
7345 
7346 	/* Skip non-ASCII words when "spin->si_ascii" is TRUE. */
7347 	if (spin->si_ascii && has_non_ascii(line))
7348 	{
7349 	    ++non_ascii;
7350 	    continue;
7351 	}
7352 
7353 	/* Normal word: store it. */
7354 	if (store_word(spin, line, flags, regionmask, NULL, FALSE) == FAIL)
7355 	{
7356 	    retval = FAIL;
7357 	    break;
7358 	}
7359 	did_word = TRUE;
7360     }
7361 
7362     vim_free(pc);
7363     fclose(fd);
7364 
7365     if (spin->si_ascii && non_ascii > 0)
7366     {
7367 	vim_snprintf((char *)IObuff, IOSIZE,
7368 		  _("Ignored %d words with non-ASCII characters"), non_ascii);
7369 	spell_message(spin, IObuff);
7370     }
7371 
7372     return retval;
7373 }
7374 
7375 /*
7376  * Get part of an sblock_T, "len" bytes long.
7377  * This avoids calling free() for every little struct we use (and keeping
7378  * track of them).
7379  * The memory is cleared to all zeros.
7380  * Returns NULL when out of memory.
7381  */
7382     static void *
7383 getroom(spin, len, align)
7384     spellinfo_T *spin;
7385     size_t	len;		/* length needed */
7386     int		align;		/* align for pointer */
7387 {
7388     char_u	*p;
7389     sblock_T	*bl = spin->si_blocks;
7390 
7391     if (align && bl != NULL)
7392 	/* Round size up for alignment.  On some systems structures need to be
7393 	 * aligned to the size of a pointer (e.g., SPARC). */
7394 	bl->sb_used = (bl->sb_used + sizeof(char *) - 1)
7395 						      & ~(sizeof(char *) - 1);
7396 
7397     if (bl == NULL || bl->sb_used + len > SBLOCKSIZE)
7398     {
7399 	if (len >= SBLOCKSIZE)
7400 	    bl = NULL;
7401 	else
7402 	    /* Allocate a block of memory. It is not freed until much later. */
7403 	    bl = (sblock_T *)alloc_clear(
7404 				   (unsigned)(sizeof(sblock_T) + SBLOCKSIZE));
7405 	if (bl == NULL)
7406 	{
7407 	    if (!spin->si_did_emsg)
7408 	    {
7409 		EMSG(_("E845: Insufficient memory, word list will be incomplete"));
7410 		spin->si_did_emsg = TRUE;
7411 	    }
7412 	    return NULL;
7413 	}
7414 	bl->sb_next = spin->si_blocks;
7415 	spin->si_blocks = bl;
7416 	bl->sb_used = 0;
7417 	++spin->si_blocks_cnt;
7418     }
7419 
7420     p = bl->sb_data + bl->sb_used;
7421     bl->sb_used += (int)len;
7422 
7423     return p;
7424 }
7425 
7426 /*
7427  * Make a copy of a string into memory allocated with getroom().
7428  * Returns NULL when out of memory.
7429  */
7430     static char_u *
7431 getroom_save(spin, s)
7432     spellinfo_T	*spin;
7433     char_u	*s;
7434 {
7435     char_u	*sc;
7436 
7437     sc = (char_u *)getroom(spin, STRLEN(s) + 1, FALSE);
7438     if (sc != NULL)
7439 	STRCPY(sc, s);
7440     return sc;
7441 }
7442 
7443 
7444 /*
7445  * Free the list of allocated sblock_T.
7446  */
7447     static void
7448 free_blocks(bl)
7449     sblock_T	*bl;
7450 {
7451     sblock_T	*next;
7452 
7453     while (bl != NULL)
7454     {
7455 	next = bl->sb_next;
7456 	vim_free(bl);
7457 	bl = next;
7458     }
7459 }
7460 
7461 /*
7462  * Allocate the root of a word tree.
7463  * Returns NULL when out of memory.
7464  */
7465     static wordnode_T *
7466 wordtree_alloc(spin)
7467     spellinfo_T *spin;
7468 {
7469     return (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
7470 }
7471 
7472 /*
7473  * Store a word in the tree(s).
7474  * Always store it in the case-folded tree.  For a keep-case word this is
7475  * useful when the word can also be used with all caps (no WF_FIXCAP flag) and
7476  * used to find suggestions.
7477  * For a keep-case word also store it in the keep-case tree.
7478  * When "pfxlist" is not NULL store the word for each postponed prefix ID and
7479  * compound flag.
7480  */
7481     static int
7482 store_word(spin, word, flags, region, pfxlist, need_affix)
7483     spellinfo_T	*spin;
7484     char_u	*word;
7485     int		flags;		/* extra flags, WF_BANNED */
7486     int		region;		/* supported region(s) */
7487     char_u	*pfxlist;	/* list of prefix IDs or NULL */
7488     int		need_affix;	/* only store word with affix ID */
7489 {
7490     int		len = (int)STRLEN(word);
7491     int		ct = captype(word, word + len);
7492     char_u	foldword[MAXWLEN];
7493     int		res = OK;
7494     char_u	*p;
7495 
7496     (void)spell_casefold(word, len, foldword, MAXWLEN);
7497     for (p = pfxlist; res == OK; ++p)
7498     {
7499 	if (!need_affix || (p != NULL && *p != NUL))
7500 	    res = tree_add_word(spin, foldword, spin->si_foldroot, ct | flags,
7501 						  region, p == NULL ? 0 : *p);
7502 	if (p == NULL || *p == NUL)
7503 	    break;
7504     }
7505     ++spin->si_foldwcount;
7506 
7507     if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP)))
7508     {
7509 	for (p = pfxlist; res == OK; ++p)
7510 	{
7511 	    if (!need_affix || (p != NULL && *p != NUL))
7512 		res = tree_add_word(spin, word, spin->si_keeproot, flags,
7513 						  region, p == NULL ? 0 : *p);
7514 	    if (p == NULL || *p == NUL)
7515 		break;
7516 	}
7517 	++spin->si_keepwcount;
7518     }
7519     return res;
7520 }
7521 
7522 /*
7523  * Add word "word" to a word tree at "root".
7524  * When "flags" < 0 we are adding to the prefix tree where "flags" is used for
7525  * "rare" and "region" is the condition nr.
7526  * Returns FAIL when out of memory.
7527  */
7528     static int
7529 tree_add_word(spin, word, root, flags, region, affixID)
7530     spellinfo_T	*spin;
7531     char_u	*word;
7532     wordnode_T	*root;
7533     int		flags;
7534     int		region;
7535     int		affixID;
7536 {
7537     wordnode_T	*node = root;
7538     wordnode_T	*np;
7539     wordnode_T	*copyp, **copyprev;
7540     wordnode_T	**prev = NULL;
7541     int		i;
7542 
7543     /* Add each byte of the word to the tree, including the NUL at the end. */
7544     for (i = 0; ; ++i)
7545     {
7546 	/* When there is more than one reference to this node we need to make
7547 	 * a copy, so that we can modify it.  Copy the whole list of siblings
7548 	 * (we don't optimize for a partly shared list of siblings). */
7549 	if (node != NULL && node->wn_refs > 1)
7550 	{
7551 	    --node->wn_refs;
7552 	    copyprev = prev;
7553 	    for (copyp = node; copyp != NULL; copyp = copyp->wn_sibling)
7554 	    {
7555 		/* Allocate a new node and copy the info. */
7556 		np = get_wordnode(spin);
7557 		if (np == NULL)
7558 		    return FAIL;
7559 		np->wn_child = copyp->wn_child;
7560 		if (np->wn_child != NULL)
7561 		    ++np->wn_child->wn_refs;	/* child gets extra ref */
7562 		np->wn_byte = copyp->wn_byte;
7563 		if (np->wn_byte == NUL)
7564 		{
7565 		    np->wn_flags = copyp->wn_flags;
7566 		    np->wn_region = copyp->wn_region;
7567 		    np->wn_affixID = copyp->wn_affixID;
7568 		}
7569 
7570 		/* Link the new node in the list, there will be one ref. */
7571 		np->wn_refs = 1;
7572 		if (copyprev != NULL)
7573 		    *copyprev = np;
7574 		copyprev = &np->wn_sibling;
7575 
7576 		/* Let "node" point to the head of the copied list. */
7577 		if (copyp == node)
7578 		    node = np;
7579 	    }
7580 	}
7581 
7582 	/* Look for the sibling that has the same character.  They are sorted
7583 	 * on byte value, thus stop searching when a sibling is found with a
7584 	 * higher byte value.  For zero bytes (end of word) the sorting is
7585 	 * done on flags and then on affixID. */
7586 	while (node != NULL
7587 		&& (node->wn_byte < word[i]
7588 		    || (node->wn_byte == NUL
7589 			&& (flags < 0
7590 			    ? node->wn_affixID < (unsigned)affixID
7591 			    : (node->wn_flags < (unsigned)(flags & WN_MASK)
7592 				|| (node->wn_flags == (flags & WN_MASK)
7593 				    && (spin->si_sugtree
7594 					? (node->wn_region & 0xffff) < region
7595 					: node->wn_affixID
7596 						    < (unsigned)affixID)))))))
7597 	{
7598 	    prev = &node->wn_sibling;
7599 	    node = *prev;
7600 	}
7601 	if (node == NULL
7602 		|| node->wn_byte != word[i]
7603 		|| (word[i] == NUL
7604 		    && (flags < 0
7605 			|| spin->si_sugtree
7606 			|| node->wn_flags != (flags & WN_MASK)
7607 			|| node->wn_affixID != affixID)))
7608 	{
7609 	    /* Allocate a new node. */
7610 	    np = get_wordnode(spin);
7611 	    if (np == NULL)
7612 		return FAIL;
7613 	    np->wn_byte = word[i];
7614 
7615 	    /* If "node" is NULL this is a new child or the end of the sibling
7616 	     * list: ref count is one.  Otherwise use ref count of sibling and
7617 	     * make ref count of sibling one (matters when inserting in front
7618 	     * of the list of siblings). */
7619 	    if (node == NULL)
7620 		np->wn_refs = 1;
7621 	    else
7622 	    {
7623 		np->wn_refs = node->wn_refs;
7624 		node->wn_refs = 1;
7625 	    }
7626 	    if (prev != NULL)
7627 		*prev = np;
7628 	    np->wn_sibling = node;
7629 	    node = np;
7630 	}
7631 
7632 	if (word[i] == NUL)
7633 	{
7634 	    node->wn_flags = flags;
7635 	    node->wn_region |= region;
7636 	    node->wn_affixID = affixID;
7637 	    break;
7638 	}
7639 	prev = &node->wn_child;
7640 	node = *prev;
7641     }
7642 #ifdef SPELL_PRINTTREE
7643     smsg((char_u *)"Added \"%s\"", word);
7644     spell_print_tree(root->wn_sibling);
7645 #endif
7646 
7647     /* count nr of words added since last message */
7648     ++spin->si_msg_count;
7649 
7650     if (spin->si_compress_cnt > 1)
7651     {
7652 	if (--spin->si_compress_cnt == 1)
7653 	    /* Did enough words to lower the block count limit. */
7654 	    spin->si_blocks_cnt += compress_inc;
7655     }
7656 
7657     /*
7658      * When we have allocated lots of memory we need to compress the word tree
7659      * to free up some room.  But compression is slow, and we might actually
7660      * need that room, thus only compress in the following situations:
7661      * 1. When not compressed before (si_compress_cnt == 0): when using
7662      *    "compress_start" blocks.
7663      * 2. When compressed before and used "compress_inc" blocks before
7664      *    adding "compress_added" words (si_compress_cnt > 1).
7665      * 3. When compressed before, added "compress_added" words
7666      *    (si_compress_cnt == 1) and the number of free nodes drops below the
7667      *    maximum word length.
7668      */
7669 #ifndef SPELL_COMPRESS_ALLWAYS
7670     if (spin->si_compress_cnt == 1
7671 	    ? spin->si_free_count < MAXWLEN
7672 	    : spin->si_blocks_cnt >= compress_start)
7673 #endif
7674     {
7675 	/* Decrement the block counter.  The effect is that we compress again
7676 	 * when the freed up room has been used and another "compress_inc"
7677 	 * blocks have been allocated.  Unless "compress_added" words have
7678 	 * been added, then the limit is put back again. */
7679 	spin->si_blocks_cnt -= compress_inc;
7680 	spin->si_compress_cnt = compress_added;
7681 
7682 	if (spin->si_verbose)
7683 	{
7684 	    msg_start();
7685 	    msg_puts((char_u *)_(msg_compressing));
7686 	    msg_clr_eos();
7687 	    msg_didout = FALSE;
7688 	    msg_col = 0;
7689 	    out_flush();
7690 	}
7691 
7692 	/* Compress both trees.  Either they both have many nodes, which makes
7693 	 * compression useful, or one of them is small, which means
7694 	 * compression goes fast.  But when filling the soundfold word tree
7695 	 * there is no keep-case tree. */
7696 	wordtree_compress(spin, spin->si_foldroot);
7697 	if (affixID >= 0)
7698 	    wordtree_compress(spin, spin->si_keeproot);
7699     }
7700 
7701     return OK;
7702 }
7703 
7704 /*
7705  * Check the 'mkspellmem' option.  Return FAIL if it's wrong.
7706  * Sets "sps_flags".
7707  */
7708     int
7709 spell_check_msm()
7710 {
7711     char_u	*p = p_msm;
7712     long	start = 0;
7713     long	incr = 0;
7714     long	added = 0;
7715 
7716     if (!VIM_ISDIGIT(*p))
7717 	return FAIL;
7718     /* block count = (value * 1024) / SBLOCKSIZE (but avoid overflow)*/
7719     start = (getdigits(&p) * 10) / (SBLOCKSIZE / 102);
7720     if (*p != ',')
7721 	return FAIL;
7722     ++p;
7723     if (!VIM_ISDIGIT(*p))
7724 	return FAIL;
7725     incr = (getdigits(&p) * 102) / (SBLOCKSIZE / 10);
7726     if (*p != ',')
7727 	return FAIL;
7728     ++p;
7729     if (!VIM_ISDIGIT(*p))
7730 	return FAIL;
7731     added = getdigits(&p) * 1024;
7732     if (*p != NUL)
7733 	return FAIL;
7734 
7735     if (start == 0 || incr == 0 || added == 0 || incr > start)
7736 	return FAIL;
7737 
7738     compress_start = start;
7739     compress_inc = incr;
7740     compress_added = added;
7741     return OK;
7742 }
7743 
7744 
7745 /*
7746  * Get a wordnode_T, either from the list of previously freed nodes or
7747  * allocate a new one.
7748  * Returns NULL when out of memory.
7749  */
7750     static wordnode_T *
7751 get_wordnode(spin)
7752     spellinfo_T	    *spin;
7753 {
7754     wordnode_T *n;
7755 
7756     if (spin->si_first_free == NULL)
7757 	n = (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
7758     else
7759     {
7760 	n = spin->si_first_free;
7761 	spin->si_first_free = n->wn_child;
7762 	vim_memset(n, 0, sizeof(wordnode_T));
7763 	--spin->si_free_count;
7764     }
7765 #ifdef SPELL_PRINTTREE
7766     if (n != NULL)
7767 	n->wn_nr = ++spin->si_wordnode_nr;
7768 #endif
7769     return n;
7770 }
7771 
7772 /*
7773  * Decrement the reference count on a node (which is the head of a list of
7774  * siblings).  If the reference count becomes zero free the node and its
7775  * siblings.
7776  * Returns the number of nodes actually freed.
7777  */
7778     static int
7779 deref_wordnode(spin, node)
7780     spellinfo_T *spin;
7781     wordnode_T  *node;
7782 {
7783     wordnode_T	*np;
7784     int		cnt = 0;
7785 
7786     if (--node->wn_refs == 0)
7787     {
7788 	for (np = node; np != NULL; np = np->wn_sibling)
7789 	{
7790 	    if (np->wn_child != NULL)
7791 		cnt += deref_wordnode(spin, np->wn_child);
7792 	    free_wordnode(spin, np);
7793 	    ++cnt;
7794 	}
7795 	++cnt;	    /* length field */
7796     }
7797     return cnt;
7798 }
7799 
7800 /*
7801  * Free a wordnode_T for re-use later.
7802  * Only the "wn_child" field becomes invalid.
7803  */
7804     static void
7805 free_wordnode(spin, n)
7806     spellinfo_T	*spin;
7807     wordnode_T  *n;
7808 {
7809     n->wn_child = spin->si_first_free;
7810     spin->si_first_free = n;
7811     ++spin->si_free_count;
7812 }
7813 
7814 /*
7815  * Compress a tree: find tails that are identical and can be shared.
7816  */
7817     static void
7818 wordtree_compress(spin, root)
7819     spellinfo_T	    *spin;
7820     wordnode_T	    *root;
7821 {
7822     hashtab_T	    ht;
7823     int		    n;
7824     int		    tot = 0;
7825     int		    perc;
7826 
7827     /* Skip the root itself, it's not actually used.  The first sibling is the
7828      * start of the tree. */
7829     if (root->wn_sibling != NULL)
7830     {
7831 	hash_init(&ht);
7832 	n = node_compress(spin, root->wn_sibling, &ht, &tot);
7833 
7834 #ifndef SPELL_PRINTTREE
7835 	if (spin->si_verbose || p_verbose > 2)
7836 #endif
7837 	{
7838 	    if (tot > 1000000)
7839 		perc = (tot - n) / (tot / 100);
7840 	    else if (tot == 0)
7841 		perc = 0;
7842 	    else
7843 		perc = (tot - n) * 100 / tot;
7844 	    vim_snprintf((char *)IObuff, IOSIZE,
7845 			  _("Compressed %d of %d nodes; %d (%d%%) remaining"),
7846 						       n, tot, tot - n, perc);
7847 	    spell_message(spin, IObuff);
7848 	}
7849 #ifdef SPELL_PRINTTREE
7850 	spell_print_tree(root->wn_sibling);
7851 #endif
7852 	hash_clear(&ht);
7853     }
7854 }
7855 
7856 /*
7857  * Compress a node, its siblings and its children, depth first.
7858  * Returns the number of compressed nodes.
7859  */
7860     static int
7861 node_compress(spin, node, ht, tot)
7862     spellinfo_T	*spin;
7863     wordnode_T	*node;
7864     hashtab_T	*ht;
7865     int		*tot;	    /* total count of nodes before compressing,
7866 			       incremented while going through the tree */
7867 {
7868     wordnode_T	*np;
7869     wordnode_T	*tp;
7870     wordnode_T	*child;
7871     hash_T	hash;
7872     hashitem_T	*hi;
7873     int		len = 0;
7874     unsigned	nr, n;
7875     int		compressed = 0;
7876 
7877     /*
7878      * Go through the list of siblings.  Compress each child and then try
7879      * finding an identical child to replace it.
7880      * Note that with "child" we mean not just the node that is pointed to,
7881      * but the whole list of siblings of which the child node is the first.
7882      */
7883     for (np = node; np != NULL && !got_int; np = np->wn_sibling)
7884     {
7885 	++len;
7886 	if ((child = np->wn_child) != NULL)
7887 	{
7888 	    /* Compress the child first.  This fills hashkey. */
7889 	    compressed += node_compress(spin, child, ht, tot);
7890 
7891 	    /* Try to find an identical child. */
7892 	    hash = hash_hash(child->wn_u1.hashkey);
7893 	    hi = hash_lookup(ht, child->wn_u1.hashkey, hash);
7894 	    if (!HASHITEM_EMPTY(hi))
7895 	    {
7896 		/* There are children we encountered before with a hash value
7897 		 * identical to the current child.  Now check if there is one
7898 		 * that is really identical. */
7899 		for (tp = HI2WN(hi); tp != NULL; tp = tp->wn_u2.next)
7900 		    if (node_equal(child, tp))
7901 		    {
7902 			/* Found one!  Now use that child in place of the
7903 			 * current one.  This means the current child and all
7904 			 * its siblings is unlinked from the tree. */
7905 			++tp->wn_refs;
7906 			compressed += deref_wordnode(spin, child);
7907 			np->wn_child = tp;
7908 			break;
7909 		    }
7910 		if (tp == NULL)
7911 		{
7912 		    /* No other child with this hash value equals the child of
7913 		     * the node, add it to the linked list after the first
7914 		     * item. */
7915 		    tp = HI2WN(hi);
7916 		    child->wn_u2.next = tp->wn_u2.next;
7917 		    tp->wn_u2.next = child;
7918 		}
7919 	    }
7920 	    else
7921 		/* No other child has this hash value, add it to the
7922 		 * hashtable. */
7923 		hash_add_item(ht, hi, child->wn_u1.hashkey, hash);
7924 	}
7925     }
7926     *tot += len + 1;	/* add one for the node that stores the length */
7927 
7928     /*
7929      * Make a hash key for the node and its siblings, so that we can quickly
7930      * find a lookalike node.  This must be done after compressing the sibling
7931      * list, otherwise the hash key would become invalid by the compression.
7932      */
7933     node->wn_u1.hashkey[0] = len;
7934     nr = 0;
7935     for (np = node; np != NULL; np = np->wn_sibling)
7936     {
7937 	if (np->wn_byte == NUL)
7938 	    /* end node: use wn_flags, wn_region and wn_affixID */
7939 	    n = np->wn_flags + (np->wn_region << 8) + (np->wn_affixID << 16);
7940 	else
7941 	    /* byte node: use the byte value and the child pointer */
7942 	    n = (unsigned)(np->wn_byte + ((long_u)np->wn_child << 8));
7943 	nr = nr * 101 + n;
7944     }
7945 
7946     /* Avoid NUL bytes, it terminates the hash key. */
7947     n = nr & 0xff;
7948     node->wn_u1.hashkey[1] = n == 0 ? 1 : n;
7949     n = (nr >> 8) & 0xff;
7950     node->wn_u1.hashkey[2] = n == 0 ? 1 : n;
7951     n = (nr >> 16) & 0xff;
7952     node->wn_u1.hashkey[3] = n == 0 ? 1 : n;
7953     n = (nr >> 24) & 0xff;
7954     node->wn_u1.hashkey[4] = n == 0 ? 1 : n;
7955     node->wn_u1.hashkey[5] = NUL;
7956 
7957     /* Check for CTRL-C pressed now and then. */
7958     fast_breakcheck();
7959 
7960     return compressed;
7961 }
7962 
7963 /*
7964  * Return TRUE when two nodes have identical siblings and children.
7965  */
7966     static int
7967 node_equal(n1, n2)
7968     wordnode_T	*n1;
7969     wordnode_T	*n2;
7970 {
7971     wordnode_T	*p1;
7972     wordnode_T	*p2;
7973 
7974     for (p1 = n1, p2 = n2; p1 != NULL && p2 != NULL;
7975 				     p1 = p1->wn_sibling, p2 = p2->wn_sibling)
7976 	if (p1->wn_byte != p2->wn_byte
7977 		|| (p1->wn_byte == NUL
7978 		    ? (p1->wn_flags != p2->wn_flags
7979 			|| p1->wn_region != p2->wn_region
7980 			|| p1->wn_affixID != p2->wn_affixID)
7981 		    : (p1->wn_child != p2->wn_child)))
7982 	    break;
7983 
7984     return p1 == NULL && p2 == NULL;
7985 }
7986 
7987 static int
7988 #ifdef __BORLANDC__
7989 _RTLENTRYF
7990 #endif
7991 rep_compare __ARGS((const void *s1, const void *s2));
7992 
7993 /*
7994  * Function given to qsort() to sort the REP items on "from" string.
7995  */
7996     static int
7997 #ifdef __BORLANDC__
7998 _RTLENTRYF
7999 #endif
8000 rep_compare(s1, s2)
8001     const void	*s1;
8002     const void	*s2;
8003 {
8004     fromto_T	*p1 = (fromto_T *)s1;
8005     fromto_T	*p2 = (fromto_T *)s2;
8006 
8007     return STRCMP(p1->ft_from, p2->ft_from);
8008 }
8009 
8010 /*
8011  * Write the Vim .spl file "fname".
8012  * Return FAIL or OK;
8013  */
8014     static int
8015 write_vim_spell(spin, fname)
8016     spellinfo_T	*spin;
8017     char_u	*fname;
8018 {
8019     FILE	*fd;
8020     int		regionmask;
8021     int		round;
8022     wordnode_T	*tree;
8023     int		nodecount;
8024     int		i;
8025     int		l;
8026     garray_T	*gap;
8027     fromto_T	*ftp;
8028     char_u	*p;
8029     int		rr;
8030     int		retval = OK;
8031     size_t	fwv = 1;  /* collect return value of fwrite() to avoid
8032 			     warnings from picky compiler */
8033 
8034     fd = mch_fopen((char *)fname, "w");
8035     if (fd == NULL)
8036     {
8037 	EMSG2(_(e_notopen), fname);
8038 	return FAIL;
8039     }
8040 
8041     /* <HEADER>: <fileID> <versionnr> */
8042 							    /* <fileID> */
8043     fwv &= fwrite(VIMSPELLMAGIC, VIMSPELLMAGICL, (size_t)1, fd);
8044     if (fwv != (size_t)1)
8045 	/* Catch first write error, don't try writing more. */
8046 	goto theend;
8047 
8048     putc(VIMSPELLVERSION, fd);				    /* <versionnr> */
8049 
8050     /*
8051      * <SECTIONS>: <section> ... <sectionend>
8052      */
8053 
8054     /* SN_INFO: <infotext> */
8055     if (spin->si_info != NULL)
8056     {
8057 	putc(SN_INFO, fd);				/* <sectionID> */
8058 	putc(0, fd);					/* <sectionflags> */
8059 
8060 	i = (int)STRLEN(spin->si_info);
8061 	put_bytes(fd, (long_u)i, 4);			/* <sectionlen> */
8062 	fwv &= fwrite(spin->si_info, (size_t)i, (size_t)1, fd); /* <infotext> */
8063     }
8064 
8065     /* SN_REGION: <regionname> ...
8066      * Write the region names only if there is more than one. */
8067     if (spin->si_region_count > 1)
8068     {
8069 	putc(SN_REGION, fd);				/* <sectionID> */
8070 	putc(SNF_REQUIRED, fd);				/* <sectionflags> */
8071 	l = spin->si_region_count * 2;
8072 	put_bytes(fd, (long_u)l, 4);			/* <sectionlen> */
8073 	fwv &= fwrite(spin->si_region_name, (size_t)l, (size_t)1, fd);
8074 							/* <regionname> ... */
8075 	regionmask = (1 << spin->si_region_count) - 1;
8076     }
8077     else
8078 	regionmask = 0;
8079 
8080     /* SN_CHARFLAGS: <charflagslen> <charflags> <folcharslen> <folchars>
8081      *
8082      * The table with character flags and the table for case folding.
8083      * This makes sure the same characters are recognized as word characters
8084      * when generating an when using a spell file.
8085      * Skip this for ASCII, the table may conflict with the one used for
8086      * 'encoding'.
8087      * Also skip this for an .add.spl file, the main spell file must contain
8088      * the table (avoids that it conflicts).  File is shorter too.
8089      */
8090     if (!spin->si_ascii && !spin->si_add)
8091     {
8092 	char_u	folchars[128 * 8];
8093 	int	flags;
8094 
8095 	putc(SN_CHARFLAGS, fd);				/* <sectionID> */
8096 	putc(SNF_REQUIRED, fd);				/* <sectionflags> */
8097 
8098 	/* Form the <folchars> string first, we need to know its length. */
8099 	l = 0;
8100 	for (i = 128; i < 256; ++i)
8101 	{
8102 #ifdef FEAT_MBYTE
8103 	    if (has_mbyte)
8104 		l += mb_char2bytes(spelltab.st_fold[i], folchars + l);
8105 	    else
8106 #endif
8107 		folchars[l++] = spelltab.st_fold[i];
8108 	}
8109 	put_bytes(fd, (long_u)(1 + 128 + 2 + l), 4);	/* <sectionlen> */
8110 
8111 	fputc(128, fd);					/* <charflagslen> */
8112 	for (i = 128; i < 256; ++i)
8113 	{
8114 	    flags = 0;
8115 	    if (spelltab.st_isw[i])
8116 		flags |= CF_WORD;
8117 	    if (spelltab.st_isu[i])
8118 		flags |= CF_UPPER;
8119 	    fputc(flags, fd);				/* <charflags> */
8120 	}
8121 
8122 	put_bytes(fd, (long_u)l, 2);			/* <folcharslen> */
8123 	fwv &= fwrite(folchars, (size_t)l, (size_t)1, fd); /* <folchars> */
8124     }
8125 
8126     /* SN_MIDWORD: <midword> */
8127     if (spin->si_midword != NULL)
8128     {
8129 	putc(SN_MIDWORD, fd);				/* <sectionID> */
8130 	putc(SNF_REQUIRED, fd);				/* <sectionflags> */
8131 
8132 	i = (int)STRLEN(spin->si_midword);
8133 	put_bytes(fd, (long_u)i, 4);			/* <sectionlen> */
8134 	fwv &= fwrite(spin->si_midword, (size_t)i, (size_t)1, fd);
8135 							/* <midword> */
8136     }
8137 
8138     /* SN_PREFCOND: <prefcondcnt> <prefcond> ... */
8139     if (spin->si_prefcond.ga_len > 0)
8140     {
8141 	putc(SN_PREFCOND, fd);				/* <sectionID> */
8142 	putc(SNF_REQUIRED, fd);				/* <sectionflags> */
8143 
8144 	l = write_spell_prefcond(NULL, &spin->si_prefcond);
8145 	put_bytes(fd, (long_u)l, 4);			/* <sectionlen> */
8146 
8147 	write_spell_prefcond(fd, &spin->si_prefcond);
8148     }
8149 
8150     /* SN_REP: <repcount> <rep> ...
8151      * SN_SAL: <salflags> <salcount> <sal> ...
8152      * SN_REPSAL: <repcount> <rep> ... */
8153 
8154     /* round 1: SN_REP section
8155      * round 2: SN_SAL section (unless SN_SOFO is used)
8156      * round 3: SN_REPSAL section */
8157     for (round = 1; round <= 3; ++round)
8158     {
8159 	if (round == 1)
8160 	    gap = &spin->si_rep;
8161 	else if (round == 2)
8162 	{
8163 	    /* Don't write SN_SAL when using a SN_SOFO section */
8164 	    if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
8165 		continue;
8166 	    gap = &spin->si_sal;
8167 	}
8168 	else
8169 	    gap = &spin->si_repsal;
8170 
8171 	/* Don't write the section if there are no items. */
8172 	if (gap->ga_len == 0)
8173 	    continue;
8174 
8175 	/* Sort the REP/REPSAL items. */
8176 	if (round != 2)
8177 	    qsort(gap->ga_data, (size_t)gap->ga_len,
8178 					       sizeof(fromto_T), rep_compare);
8179 
8180 	i = round == 1 ? SN_REP : (round == 2 ? SN_SAL : SN_REPSAL);
8181 	putc(i, fd);					/* <sectionID> */
8182 
8183 	/* This is for making suggestions, section is not required. */
8184 	putc(0, fd);					/* <sectionflags> */
8185 
8186 	/* Compute the length of what follows. */
8187 	l = 2;	    /* count <repcount> or <salcount> */
8188 	for (i = 0; i < gap->ga_len; ++i)
8189 	{
8190 	    ftp = &((fromto_T *)gap->ga_data)[i];
8191 	    l += 1 + (int)STRLEN(ftp->ft_from);  /* count <*fromlen> and <*from> */
8192 	    l += 1 + (int)STRLEN(ftp->ft_to);    /* count <*tolen> and <*to> */
8193 	}
8194 	if (round == 2)
8195 	    ++l;	/* count <salflags> */
8196 	put_bytes(fd, (long_u)l, 4);			/* <sectionlen> */
8197 
8198 	if (round == 2)
8199 	{
8200 	    i = 0;
8201 	    if (spin->si_followup)
8202 		i |= SAL_F0LLOWUP;
8203 	    if (spin->si_collapse)
8204 		i |= SAL_COLLAPSE;
8205 	    if (spin->si_rem_accents)
8206 		i |= SAL_REM_ACCENTS;
8207 	    putc(i, fd);			/* <salflags> */
8208 	}
8209 
8210 	put_bytes(fd, (long_u)gap->ga_len, 2);	/* <repcount> or <salcount> */
8211 	for (i = 0; i < gap->ga_len; ++i)
8212 	{
8213 	    /* <rep> : <repfromlen> <repfrom> <reptolen> <repto> */
8214 	    /* <sal> : <salfromlen> <salfrom> <saltolen> <salto> */
8215 	    ftp = &((fromto_T *)gap->ga_data)[i];
8216 	    for (rr = 1; rr <= 2; ++rr)
8217 	    {
8218 		p = rr == 1 ? ftp->ft_from : ftp->ft_to;
8219 		l = (int)STRLEN(p);
8220 		putc(l, fd);
8221 		if (l > 0)
8222 		    fwv &= fwrite(p, l, (size_t)1, fd);
8223 	    }
8224 	}
8225 
8226     }
8227 
8228     /* SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
8229      * This is for making suggestions, section is not required. */
8230     if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
8231     {
8232 	putc(SN_SOFO, fd);				/* <sectionID> */
8233 	putc(0, fd);					/* <sectionflags> */
8234 
8235 	l = (int)STRLEN(spin->si_sofofr);
8236 	put_bytes(fd, (long_u)(l + STRLEN(spin->si_sofoto) + 4), 4);
8237 							/* <sectionlen> */
8238 
8239 	put_bytes(fd, (long_u)l, 2);			/* <sofofromlen> */
8240 	fwv &= fwrite(spin->si_sofofr, l, (size_t)1, fd); /* <sofofrom> */
8241 
8242 	l = (int)STRLEN(spin->si_sofoto);
8243 	put_bytes(fd, (long_u)l, 2);			/* <sofotolen> */
8244 	fwv &= fwrite(spin->si_sofoto, l, (size_t)1, fd); /* <sofoto> */
8245     }
8246 
8247     /* SN_WORDS: <word> ...
8248      * This is for making suggestions, section is not required. */
8249     if (spin->si_commonwords.ht_used > 0)
8250     {
8251 	putc(SN_WORDS, fd);				/* <sectionID> */
8252 	putc(0, fd);					/* <sectionflags> */
8253 
8254 	/* round 1: count the bytes
8255 	 * round 2: write the bytes */
8256 	for (round = 1; round <= 2; ++round)
8257 	{
8258 	    int		todo;
8259 	    int		len = 0;
8260 	    hashitem_T	*hi;
8261 
8262 	    todo = (int)spin->si_commonwords.ht_used;
8263 	    for (hi = spin->si_commonwords.ht_array; todo > 0; ++hi)
8264 		if (!HASHITEM_EMPTY(hi))
8265 		{
8266 		    l = (int)STRLEN(hi->hi_key) + 1;
8267 		    len += l;
8268 		    if (round == 2)			/* <word> */
8269 			fwv &= fwrite(hi->hi_key, (size_t)l, (size_t)1, fd);
8270 		    --todo;
8271 		}
8272 	    if (round == 1)
8273 		put_bytes(fd, (long_u)len, 4);		/* <sectionlen> */
8274 	}
8275     }
8276 
8277     /* SN_MAP: <mapstr>
8278      * This is for making suggestions, section is not required. */
8279     if (spin->si_map.ga_len > 0)
8280     {
8281 	putc(SN_MAP, fd);				/* <sectionID> */
8282 	putc(0, fd);					/* <sectionflags> */
8283 	l = spin->si_map.ga_len;
8284 	put_bytes(fd, (long_u)l, 4);			/* <sectionlen> */
8285 	fwv &= fwrite(spin->si_map.ga_data, (size_t)l, (size_t)1, fd);
8286 							/* <mapstr> */
8287     }
8288 
8289     /* SN_SUGFILE: <timestamp>
8290      * This is used to notify that a .sug file may be available and at the
8291      * same time allows for checking that a .sug file that is found matches
8292      * with this .spl file.  That's because the word numbers must be exactly
8293      * right. */
8294     if (!spin->si_nosugfile
8295 	    && (spin->si_sal.ga_len > 0
8296 		     || (spin->si_sofofr != NULL && spin->si_sofoto != NULL)))
8297     {
8298 	putc(SN_SUGFILE, fd);				/* <sectionID> */
8299 	putc(0, fd);					/* <sectionflags> */
8300 	put_bytes(fd, (long_u)8, 4);			/* <sectionlen> */
8301 
8302 	/* Set si_sugtime and write it to the file. */
8303 	spin->si_sugtime = time(NULL);
8304 	put_time(fd, spin->si_sugtime);			/* <timestamp> */
8305     }
8306 
8307     /* SN_NOSPLITSUGS: nothing
8308      * This is used to notify that no suggestions with word splits are to be
8309      * made. */
8310     if (spin->si_nosplitsugs)
8311     {
8312 	putc(SN_NOSPLITSUGS, fd);			/* <sectionID> */
8313 	putc(0, fd);					/* <sectionflags> */
8314 	put_bytes(fd, (long_u)0, 4);			/* <sectionlen> */
8315     }
8316 
8317     /* SN_NOCOMPUNDSUGS: nothing
8318      * This is used to notify that no suggestions with compounds are to be
8319      * made. */
8320     if (spin->si_nocompoundsugs)
8321     {
8322 	putc(SN_NOCOMPOUNDSUGS, fd);			/* <sectionID> */
8323 	putc(0, fd);					/* <sectionflags> */
8324 	put_bytes(fd, (long_u)0, 4);			/* <sectionlen> */
8325     }
8326 
8327     /* SN_COMPOUND: compound info.
8328      * We don't mark it required, when not supported all compound words will
8329      * be bad words. */
8330     if (spin->si_compflags != NULL)
8331     {
8332 	putc(SN_COMPOUND, fd);				/* <sectionID> */
8333 	putc(0, fd);					/* <sectionflags> */
8334 
8335 	l = (int)STRLEN(spin->si_compflags);
8336 	for (i = 0; i < spin->si_comppat.ga_len; ++i)
8337 	    l += (int)STRLEN(((char_u **)(spin->si_comppat.ga_data))[i]) + 1;
8338 	put_bytes(fd, (long_u)(l + 7), 4);		/* <sectionlen> */
8339 
8340 	putc(spin->si_compmax, fd);			/* <compmax> */
8341 	putc(spin->si_compminlen, fd);			/* <compminlen> */
8342 	putc(spin->si_compsylmax, fd);			/* <compsylmax> */
8343 	putc(0, fd);		/* for Vim 7.0b compatibility */
8344 	putc(spin->si_compoptions, fd);			/* <compoptions> */
8345 	put_bytes(fd, (long_u)spin->si_comppat.ga_len, 2);
8346 							/* <comppatcount> */
8347 	for (i = 0; i < spin->si_comppat.ga_len; ++i)
8348 	{
8349 	    p = ((char_u **)(spin->si_comppat.ga_data))[i];
8350 	    putc((int)STRLEN(p), fd);			/* <comppatlen> */
8351 	    fwv &= fwrite(p, (size_t)STRLEN(p), (size_t)1, fd);
8352 							/* <comppattext> */
8353 	}
8354 							/* <compflags> */
8355 	fwv &= fwrite(spin->si_compflags, (size_t)STRLEN(spin->si_compflags),
8356 							       (size_t)1, fd);
8357     }
8358 
8359     /* SN_NOBREAK: NOBREAK flag */
8360     if (spin->si_nobreak)
8361     {
8362 	putc(SN_NOBREAK, fd);				/* <sectionID> */
8363 	putc(0, fd);					/* <sectionflags> */
8364 
8365 	/* It's empty, the presence of the section flags the feature. */
8366 	put_bytes(fd, (long_u)0, 4);			/* <sectionlen> */
8367     }
8368 
8369     /* SN_SYLLABLE: syllable info.
8370      * We don't mark it required, when not supported syllables will not be
8371      * counted. */
8372     if (spin->si_syllable != NULL)
8373     {
8374 	putc(SN_SYLLABLE, fd);				/* <sectionID> */
8375 	putc(0, fd);					/* <sectionflags> */
8376 
8377 	l = (int)STRLEN(spin->si_syllable);
8378 	put_bytes(fd, (long_u)l, 4);			/* <sectionlen> */
8379 	fwv &= fwrite(spin->si_syllable, (size_t)l, (size_t)1, fd);
8380 							/* <syllable> */
8381     }
8382 
8383     /* end of <SECTIONS> */
8384     putc(SN_END, fd);					/* <sectionend> */
8385 
8386 
8387     /*
8388      * <LWORDTREE>  <KWORDTREE>  <PREFIXTREE>
8389      */
8390     spin->si_memtot = 0;
8391     for (round = 1; round <= 3; ++round)
8392     {
8393 	if (round == 1)
8394 	    tree = spin->si_foldroot->wn_sibling;
8395 	else if (round == 2)
8396 	    tree = spin->si_keeproot->wn_sibling;
8397 	else
8398 	    tree = spin->si_prefroot->wn_sibling;
8399 
8400 	/* Clear the index and wnode fields in the tree. */
8401 	clear_node(tree);
8402 
8403 	/* Count the number of nodes.  Needed to be able to allocate the
8404 	 * memory when reading the nodes.  Also fills in index for shared
8405 	 * nodes. */
8406 	nodecount = put_node(NULL, tree, 0, regionmask, round == 3);
8407 
8408 	/* number of nodes in 4 bytes */
8409 	put_bytes(fd, (long_u)nodecount, 4);	/* <nodecount> */
8410 	spin->si_memtot += nodecount + nodecount * sizeof(int);
8411 
8412 	/* Write the nodes. */
8413 	(void)put_node(fd, tree, 0, regionmask, round == 3);
8414     }
8415 
8416     /* Write another byte to check for errors (file system full). */
8417     if (putc(0, fd) == EOF)
8418 	retval = FAIL;
8419 theend:
8420     if (fclose(fd) == EOF)
8421 	retval = FAIL;
8422 
8423     if (fwv != (size_t)1)
8424 	retval = FAIL;
8425     if (retval == FAIL)
8426 	EMSG(_(e_write));
8427 
8428     return retval;
8429 }
8430 
8431 /*
8432  * Clear the index and wnode fields of "node", it siblings and its
8433  * children.  This is needed because they are a union with other items to save
8434  * space.
8435  */
8436     static void
8437 clear_node(node)
8438     wordnode_T	*node;
8439 {
8440     wordnode_T	*np;
8441 
8442     if (node != NULL)
8443 	for (np = node; np != NULL; np = np->wn_sibling)
8444 	{
8445 	    np->wn_u1.index = 0;
8446 	    np->wn_u2.wnode = NULL;
8447 
8448 	    if (np->wn_byte != NUL)
8449 		clear_node(np->wn_child);
8450 	}
8451 }
8452 
8453 
8454 /*
8455  * Dump a word tree at node "node".
8456  *
8457  * This first writes the list of possible bytes (siblings).  Then for each
8458  * byte recursively write the children.
8459  *
8460  * NOTE: The code here must match the code in read_tree_node(), since
8461  * assumptions are made about the indexes (so that we don't have to write them
8462  * in the file).
8463  *
8464  * Returns the number of nodes used.
8465  */
8466     static int
8467 put_node(fd, node, idx, regionmask, prefixtree)
8468     FILE	*fd;		/* NULL when only counting */
8469     wordnode_T	*node;
8470     int		idx;
8471     int		regionmask;
8472     int		prefixtree;	/* TRUE for PREFIXTREE */
8473 {
8474     int		newindex = idx;
8475     int		siblingcount = 0;
8476     wordnode_T	*np;
8477     int		flags;
8478 
8479     /* If "node" is zero the tree is empty. */
8480     if (node == NULL)
8481 	return 0;
8482 
8483     /* Store the index where this node is written. */
8484     node->wn_u1.index = idx;
8485 
8486     /* Count the number of siblings. */
8487     for (np = node; np != NULL; np = np->wn_sibling)
8488 	++siblingcount;
8489 
8490     /* Write the sibling count. */
8491     if (fd != NULL)
8492 	putc(siblingcount, fd);				/* <siblingcount> */
8493 
8494     /* Write each sibling byte and optionally extra info. */
8495     for (np = node; np != NULL; np = np->wn_sibling)
8496     {
8497 	if (np->wn_byte == 0)
8498 	{
8499 	    if (fd != NULL)
8500 	    {
8501 		/* For a NUL byte (end of word) write the flags etc. */
8502 		if (prefixtree)
8503 		{
8504 		    /* In PREFIXTREE write the required affixID and the
8505 		     * associated condition nr (stored in wn_region).  The
8506 		     * byte value is misused to store the "rare" and "not
8507 		     * combining" flags */
8508 		    if (np->wn_flags == (short_u)PFX_FLAGS)
8509 			putc(BY_NOFLAGS, fd);		/* <byte> */
8510 		    else
8511 		    {
8512 			putc(BY_FLAGS, fd);		/* <byte> */
8513 			putc(np->wn_flags, fd);		/* <pflags> */
8514 		    }
8515 		    putc(np->wn_affixID, fd);		/* <affixID> */
8516 		    put_bytes(fd, (long_u)np->wn_region, 2); /* <prefcondnr> */
8517 		}
8518 		else
8519 		{
8520 		    /* For word trees we write the flag/region items. */
8521 		    flags = np->wn_flags;
8522 		    if (regionmask != 0 && np->wn_region != regionmask)
8523 			flags |= WF_REGION;
8524 		    if (np->wn_affixID != 0)
8525 			flags |= WF_AFX;
8526 		    if (flags == 0)
8527 		    {
8528 			/* word without flags or region */
8529 			putc(BY_NOFLAGS, fd);			/* <byte> */
8530 		    }
8531 		    else
8532 		    {
8533 			if (np->wn_flags >= 0x100)
8534 			{
8535 			    putc(BY_FLAGS2, fd);		/* <byte> */
8536 			    putc(flags, fd);			/* <flags> */
8537 			    putc((unsigned)flags >> 8, fd);	/* <flags2> */
8538 			}
8539 			else
8540 			{
8541 			    putc(BY_FLAGS, fd);			/* <byte> */
8542 			    putc(flags, fd);			/* <flags> */
8543 			}
8544 			if (flags & WF_REGION)
8545 			    putc(np->wn_region, fd);		/* <region> */
8546 			if (flags & WF_AFX)
8547 			    putc(np->wn_affixID, fd);		/* <affixID> */
8548 		    }
8549 		}
8550 	    }
8551 	}
8552 	else
8553 	{
8554 	    if (np->wn_child->wn_u1.index != 0
8555 					 && np->wn_child->wn_u2.wnode != node)
8556 	    {
8557 		/* The child is written elsewhere, write the reference. */
8558 		if (fd != NULL)
8559 		{
8560 		    putc(BY_INDEX, fd);			/* <byte> */
8561 							/* <nodeidx> */
8562 		    put_bytes(fd, (long_u)np->wn_child->wn_u1.index, 3);
8563 		}
8564 	    }
8565 	    else if (np->wn_child->wn_u2.wnode == NULL)
8566 		/* We will write the child below and give it an index. */
8567 		np->wn_child->wn_u2.wnode = node;
8568 
8569 	    if (fd != NULL)
8570 		if (putc(np->wn_byte, fd) == EOF) /* <byte> or <xbyte> */
8571 		{
8572 		    EMSG(_(e_write));
8573 		    return 0;
8574 		}
8575 	}
8576     }
8577 
8578     /* Space used in the array when reading: one for each sibling and one for
8579      * the count. */
8580     newindex += siblingcount + 1;
8581 
8582     /* Recursively dump the children of each sibling. */
8583     for (np = node; np != NULL; np = np->wn_sibling)
8584 	if (np->wn_byte != 0 && np->wn_child->wn_u2.wnode == node)
8585 	    newindex = put_node(fd, np->wn_child, newindex, regionmask,
8586 								  prefixtree);
8587 
8588     return newindex;
8589 }
8590 
8591 
8592 /*
8593  * ":mkspell [-ascii] outfile  infile ..."
8594  * ":mkspell [-ascii] addfile"
8595  */
8596     void
8597 ex_mkspell(eap)
8598     exarg_T *eap;
8599 {
8600     int		fcount;
8601     char_u	**fnames;
8602     char_u	*arg = eap->arg;
8603     int		ascii = FALSE;
8604 
8605     if (STRNCMP(arg, "-ascii", 6) == 0)
8606     {
8607 	ascii = TRUE;
8608 	arg = skipwhite(arg + 6);
8609     }
8610 
8611     /* Expand all the remaining arguments (e.g., $VIMRUNTIME). */
8612     if (get_arglist_exp(arg, &fcount, &fnames, FALSE) == OK)
8613     {
8614 	mkspell(fcount, fnames, ascii, eap->forceit, FALSE);
8615 	FreeWild(fcount, fnames);
8616     }
8617 }
8618 
8619 /*
8620  * Create the .sug file.
8621  * Uses the soundfold info in "spin".
8622  * Writes the file with the name "wfname", with ".spl" changed to ".sug".
8623  */
8624     static void
8625 spell_make_sugfile(spin, wfname)
8626     spellinfo_T	*spin;
8627     char_u	*wfname;
8628 {
8629     char_u	*fname = NULL;
8630     int		len;
8631     slang_T	*slang;
8632     int		free_slang = FALSE;
8633 
8634     /*
8635      * Read back the .spl file that was written.  This fills the required
8636      * info for soundfolding.  This also uses less memory than the
8637      * pointer-linked version of the trie.  And it avoids having two versions
8638      * of the code for the soundfolding stuff.
8639      * It might have been done already by spell_reload_one().
8640      */
8641     for (slang = first_lang; slang != NULL; slang = slang->sl_next)
8642 	if (fullpathcmp(wfname, slang->sl_fname, FALSE) == FPC_SAME)
8643 	    break;
8644     if (slang == NULL)
8645     {
8646 	spell_message(spin, (char_u *)_("Reading back spell file..."));
8647 	slang = spell_load_file(wfname, NULL, NULL, FALSE);
8648 	if (slang == NULL)
8649 	    return;
8650 	free_slang = TRUE;
8651     }
8652 
8653     /*
8654      * Clear the info in "spin" that is used.
8655      */
8656     spin->si_blocks = NULL;
8657     spin->si_blocks_cnt = 0;
8658     spin->si_compress_cnt = 0;	    /* will stay at 0 all the time*/
8659     spin->si_free_count = 0;
8660     spin->si_first_free = NULL;
8661     spin->si_foldwcount = 0;
8662 
8663     /*
8664      * Go through the trie of good words, soundfold each word and add it to
8665      * the soundfold trie.
8666      */
8667     spell_message(spin, (char_u *)_("Performing soundfolding..."));
8668     if (sug_filltree(spin, slang) == FAIL)
8669 	goto theend;
8670 
8671     /*
8672      * Create the table which links each soundfold word with a list of the
8673      * good words it may come from.  Creates buffer "spin->si_spellbuf".
8674      * This also removes the wordnr from the NUL byte entries to make
8675      * compression possible.
8676      */
8677     if (sug_maketable(spin) == FAIL)
8678 	goto theend;
8679 
8680     smsg((char_u *)_("Number of words after soundfolding: %ld"),
8681 				 (long)spin->si_spellbuf->b_ml.ml_line_count);
8682 
8683     /*
8684      * Compress the soundfold trie.
8685      */
8686     spell_message(spin, (char_u *)_(msg_compressing));
8687     wordtree_compress(spin, spin->si_foldroot);
8688 
8689     /*
8690      * Write the .sug file.
8691      * Make the file name by changing ".spl" to ".sug".
8692      */
8693     fname = alloc(MAXPATHL);
8694     if (fname == NULL)
8695 	goto theend;
8696     vim_strncpy(fname, wfname, MAXPATHL - 1);
8697     len = (int)STRLEN(fname);
8698     fname[len - 2] = 'u';
8699     fname[len - 1] = 'g';
8700     sug_write(spin, fname);
8701 
8702 theend:
8703     vim_free(fname);
8704     if (free_slang)
8705 	slang_free(slang);
8706     free_blocks(spin->si_blocks);
8707     close_spellbuf(spin->si_spellbuf);
8708 }
8709 
8710 /*
8711  * Build the soundfold trie for language "slang".
8712  */
8713     static int
8714 sug_filltree(spin, slang)
8715     spellinfo_T	*spin;
8716     slang_T	*slang;
8717 {
8718     char_u	*byts;
8719     idx_T	*idxs;
8720     int		depth;
8721     idx_T	arridx[MAXWLEN];
8722     int		curi[MAXWLEN];
8723     char_u	tword[MAXWLEN];
8724     char_u	tsalword[MAXWLEN];
8725     int		c;
8726     idx_T	n;
8727     unsigned	words_done = 0;
8728     int		wordcount[MAXWLEN];
8729 
8730     /* We use si_foldroot for the soundfolded trie. */
8731     spin->si_foldroot = wordtree_alloc(spin);
8732     if (spin->si_foldroot == NULL)
8733 	return FAIL;
8734 
8735     /* let tree_add_word() know we're adding to the soundfolded tree */
8736     spin->si_sugtree = TRUE;
8737 
8738     /*
8739      * Go through the whole case-folded tree, soundfold each word and put it
8740      * in the trie.
8741      */
8742     byts = slang->sl_fbyts;
8743     idxs = slang->sl_fidxs;
8744 
8745     arridx[0] = 0;
8746     curi[0] = 1;
8747     wordcount[0] = 0;
8748 
8749     depth = 0;
8750     while (depth >= 0 && !got_int)
8751     {
8752 	if (curi[depth] > byts[arridx[depth]])
8753 	{
8754 	    /* Done all bytes at this node, go up one level. */
8755 	    idxs[arridx[depth]] = wordcount[depth];
8756 	    if (depth > 0)
8757 		wordcount[depth - 1] += wordcount[depth];
8758 
8759 	    --depth;
8760 	    line_breakcheck();
8761 	}
8762 	else
8763 	{
8764 
8765 	    /* Do one more byte at this node. */
8766 	    n = arridx[depth] + curi[depth];
8767 	    ++curi[depth];
8768 
8769 	    c = byts[n];
8770 	    if (c == 0)
8771 	    {
8772 		/* Sound-fold the word. */
8773 		tword[depth] = NUL;
8774 		spell_soundfold(slang, tword, TRUE, tsalword);
8775 
8776 		/* We use the "flags" field for the MSB of the wordnr,
8777 		 * "region" for the LSB of the wordnr.  */
8778 		if (tree_add_word(spin, tsalword, spin->si_foldroot,
8779 				words_done >> 16, words_done & 0xffff,
8780 							   0) == FAIL)
8781 		    return FAIL;
8782 
8783 		++words_done;
8784 		++wordcount[depth];
8785 
8786 		/* Reset the block count each time to avoid compression
8787 		 * kicking in. */
8788 		spin->si_blocks_cnt = 0;
8789 
8790 		/* Skip over any other NUL bytes (same word with different
8791 		 * flags). */
8792 		while (byts[n + 1] == 0)
8793 		{
8794 		    ++n;
8795 		    ++curi[depth];
8796 		}
8797 	    }
8798 	    else
8799 	    {
8800 		/* Normal char, go one level deeper. */
8801 		tword[depth++] = c;
8802 		arridx[depth] = idxs[n];
8803 		curi[depth] = 1;
8804 		wordcount[depth] = 0;
8805 	    }
8806 	}
8807     }
8808 
8809     smsg((char_u *)_("Total number of words: %d"), words_done);
8810 
8811     return OK;
8812 }
8813 
8814 /*
8815  * Make the table that links each word in the soundfold trie to the words it
8816  * can be produced from.
8817  * This is not unlike lines in a file, thus use a memfile to be able to access
8818  * the table efficiently.
8819  * Returns FAIL when out of memory.
8820  */
8821     static int
8822 sug_maketable(spin)
8823     spellinfo_T	*spin;
8824 {
8825     garray_T	ga;
8826     int		res = OK;
8827 
8828     /* Allocate a buffer, open a memline for it and create the swap file
8829      * (uses a temp file, not a .swp file). */
8830     spin->si_spellbuf = open_spellbuf();
8831     if (spin->si_spellbuf == NULL)
8832 	return FAIL;
8833 
8834     /* Use a buffer to store the line info, avoids allocating many small
8835      * pieces of memory. */
8836     ga_init2(&ga, 1, 100);
8837 
8838     /* recursively go through the tree */
8839     if (sug_filltable(spin, spin->si_foldroot->wn_sibling, 0, &ga) == -1)
8840 	res = FAIL;
8841 
8842     ga_clear(&ga);
8843     return res;
8844 }
8845 
8846 /*
8847  * Fill the table for one node and its children.
8848  * Returns the wordnr at the start of the node.
8849  * Returns -1 when out of memory.
8850  */
8851     static int
8852 sug_filltable(spin, node, startwordnr, gap)
8853     spellinfo_T	*spin;
8854     wordnode_T	*node;
8855     int		startwordnr;
8856     garray_T	*gap;	    /* place to store line of numbers */
8857 {
8858     wordnode_T	*p, *np;
8859     int		wordnr = startwordnr;
8860     int		nr;
8861     int		prev_nr;
8862 
8863     for (p = node; p != NULL; p = p->wn_sibling)
8864     {
8865 	if (p->wn_byte == NUL)
8866 	{
8867 	    gap->ga_len = 0;
8868 	    prev_nr = 0;
8869 	    for (np = p; np != NULL && np->wn_byte == NUL; np = np->wn_sibling)
8870 	    {
8871 		if (ga_grow(gap, 10) == FAIL)
8872 		    return -1;
8873 
8874 		nr = (np->wn_flags << 16) + (np->wn_region & 0xffff);
8875 		/* Compute the offset from the previous nr and store the
8876 		 * offset in a way that it takes a minimum number of bytes.
8877 		 * It's a bit like utf-8, but without the need to mark
8878 		 * following bytes. */
8879 		nr -= prev_nr;
8880 		prev_nr += nr;
8881 		gap->ga_len += offset2bytes(nr,
8882 					 (char_u *)gap->ga_data + gap->ga_len);
8883 	    }
8884 
8885 	    /* add the NUL byte */
8886 	    ((char_u *)gap->ga_data)[gap->ga_len++] = NUL;
8887 
8888 	    if (ml_append_buf(spin->si_spellbuf, (linenr_T)wordnr,
8889 				     gap->ga_data, gap->ga_len, TRUE) == FAIL)
8890 		return -1;
8891 	    ++wordnr;
8892 
8893 	    /* Remove extra NUL entries, we no longer need them. We don't
8894 	     * bother freeing the nodes, the won't be reused anyway. */
8895 	    while (p->wn_sibling != NULL && p->wn_sibling->wn_byte == NUL)
8896 		p->wn_sibling = p->wn_sibling->wn_sibling;
8897 
8898 	    /* Clear the flags on the remaining NUL node, so that compression
8899 	     * works a lot better. */
8900 	    p->wn_flags = 0;
8901 	    p->wn_region = 0;
8902 	}
8903 	else
8904 	{
8905 	    wordnr = sug_filltable(spin, p->wn_child, wordnr, gap);
8906 	    if (wordnr == -1)
8907 		return -1;
8908 	}
8909     }
8910     return wordnr;
8911 }
8912 
8913 /*
8914  * Convert an offset into a minimal number of bytes.
8915  * Similar to utf_char2byters, but use 8 bits in followup bytes and avoid NUL
8916  * bytes.
8917  */
8918     static int
8919 offset2bytes(nr, buf)
8920     int	    nr;
8921     char_u  *buf;
8922 {
8923     int	    rem;
8924     int	    b1, b2, b3, b4;
8925 
8926     /* Split the number in parts of base 255.  We need to avoid NUL bytes. */
8927     b1 = nr % 255 + 1;
8928     rem = nr / 255;
8929     b2 = rem % 255 + 1;
8930     rem = rem / 255;
8931     b3 = rem % 255 + 1;
8932     b4 = rem / 255 + 1;
8933 
8934     if (b4 > 1 || b3 > 0x1f)	/* 4 bytes */
8935     {
8936 	buf[0] = 0xe0 + b4;
8937 	buf[1] = b3;
8938 	buf[2] = b2;
8939 	buf[3] = b1;
8940 	return 4;
8941     }
8942     if (b3 > 1 || b2 > 0x3f )	/* 3 bytes */
8943     {
8944 	buf[0] = 0xc0 + b3;
8945 	buf[1] = b2;
8946 	buf[2] = b1;
8947 	return 3;
8948     }
8949     if (b2 > 1 || b1 > 0x7f )	/* 2 bytes */
8950     {
8951 	buf[0] = 0x80 + b2;
8952 	buf[1] = b1;
8953 	return 2;
8954     }
8955 				/* 1 byte */
8956     buf[0] = b1;
8957     return 1;
8958 }
8959 
8960 /*
8961  * Opposite of offset2bytes().
8962  * "pp" points to the bytes and is advanced over it.
8963  * Returns the offset.
8964  */
8965     static int
8966 bytes2offset(pp)
8967     char_u	**pp;
8968 {
8969     char_u	*p = *pp;
8970     int		nr;
8971     int		c;
8972 
8973     c = *p++;
8974     if ((c & 0x80) == 0x00)		/* 1 byte */
8975     {
8976 	nr = c - 1;
8977     }
8978     else if ((c & 0xc0) == 0x80)	/* 2 bytes */
8979     {
8980 	nr = (c & 0x3f) - 1;
8981 	nr = nr * 255 + (*p++ - 1);
8982     }
8983     else if ((c & 0xe0) == 0xc0)	/* 3 bytes */
8984     {
8985 	nr = (c & 0x1f) - 1;
8986 	nr = nr * 255 + (*p++ - 1);
8987 	nr = nr * 255 + (*p++ - 1);
8988     }
8989     else				/* 4 bytes */
8990     {
8991 	nr = (c & 0x0f) - 1;
8992 	nr = nr * 255 + (*p++ - 1);
8993 	nr = nr * 255 + (*p++ - 1);
8994 	nr = nr * 255 + (*p++ - 1);
8995     }
8996 
8997     *pp = p;
8998     return nr;
8999 }
9000 
9001 /*
9002  * Write the .sug file in "fname".
9003  */
9004     static void
9005 sug_write(spin, fname)
9006     spellinfo_T	*spin;
9007     char_u	*fname;
9008 {
9009     FILE	*fd;
9010     wordnode_T	*tree;
9011     int		nodecount;
9012     int		wcount;
9013     char_u	*line;
9014     linenr_T	lnum;
9015     int		len;
9016 
9017     /* Create the file.  Note that an existing file is silently overwritten! */
9018     fd = mch_fopen((char *)fname, "w");
9019     if (fd == NULL)
9020     {
9021 	EMSG2(_(e_notopen), fname);
9022 	return;
9023     }
9024 
9025     vim_snprintf((char *)IObuff, IOSIZE,
9026 				  _("Writing suggestion file %s ..."), fname);
9027     spell_message(spin, IObuff);
9028 
9029     /*
9030      * <SUGHEADER>: <fileID> <versionnr> <timestamp>
9031      */
9032     if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) /* <fileID> */
9033     {
9034 	EMSG(_(e_write));
9035 	goto theend;
9036     }
9037     putc(VIMSUGVERSION, fd);				/* <versionnr> */
9038 
9039     /* Write si_sugtime to the file. */
9040     put_time(fd, spin->si_sugtime);			/* <timestamp> */
9041 
9042     /*
9043      * <SUGWORDTREE>
9044      */
9045     spin->si_memtot = 0;
9046     tree = spin->si_foldroot->wn_sibling;
9047 
9048     /* Clear the index and wnode fields in the tree. */
9049     clear_node(tree);
9050 
9051     /* Count the number of nodes.  Needed to be able to allocate the
9052      * memory when reading the nodes.  Also fills in index for shared
9053      * nodes. */
9054     nodecount = put_node(NULL, tree, 0, 0, FALSE);
9055 
9056     /* number of nodes in 4 bytes */
9057     put_bytes(fd, (long_u)nodecount, 4);	/* <nodecount> */
9058     spin->si_memtot += nodecount + nodecount * sizeof(int);
9059 
9060     /* Write the nodes. */
9061     (void)put_node(fd, tree, 0, 0, FALSE);
9062 
9063     /*
9064      * <SUGTABLE>: <sugwcount> <sugline> ...
9065      */
9066     wcount = spin->si_spellbuf->b_ml.ml_line_count;
9067     put_bytes(fd, (long_u)wcount, 4);	/* <sugwcount> */
9068 
9069     for (lnum = 1; lnum <= (linenr_T)wcount; ++lnum)
9070     {
9071 	/* <sugline>: <sugnr> ... NUL */
9072 	line = ml_get_buf(spin->si_spellbuf, lnum, FALSE);
9073 	len = (int)STRLEN(line) + 1;
9074 	if (fwrite(line, (size_t)len, (size_t)1, fd) == 0)
9075 	{
9076 	    EMSG(_(e_write));
9077 	    goto theend;
9078 	}
9079 	spin->si_memtot += len;
9080     }
9081 
9082     /* Write another byte to check for errors. */
9083     if (putc(0, fd) == EOF)
9084 	EMSG(_(e_write));
9085 
9086     vim_snprintf((char *)IObuff, IOSIZE,
9087 		 _("Estimated runtime memory use: %d bytes"), spin->si_memtot);
9088     spell_message(spin, IObuff);
9089 
9090 theend:
9091     /* close the file */
9092     fclose(fd);
9093 }
9094 
9095 /*
9096  * Open a spell buffer.  This is a nameless buffer that is not in the buffer
9097  * list and only contains text lines.  Can use a swapfile to reduce memory
9098  * use.
9099  * Most other fields are invalid!  Esp. watch out for string options being
9100  * NULL and there is no undo info.
9101  * Returns NULL when out of memory.
9102  */
9103     static buf_T *
9104 open_spellbuf()
9105 {
9106     buf_T	*buf;
9107 
9108     buf = (buf_T *)alloc_clear(sizeof(buf_T));
9109     if (buf != NULL)
9110     {
9111 	buf->b_spell = TRUE;
9112 	buf->b_p_swf = TRUE;	/* may create a swap file */
9113 #ifdef FEAT_CRYPT
9114 	buf->b_p_key = empty_option;
9115 #endif
9116 	ml_open(buf);
9117 	ml_open_file(buf);	/* create swap file now */
9118     }
9119     return buf;
9120 }
9121 
9122 /*
9123  * Close the buffer used for spell info.
9124  */
9125     static void
9126 close_spellbuf(buf)
9127     buf_T	*buf;
9128 {
9129     if (buf != NULL)
9130     {
9131 	ml_close(buf, TRUE);
9132 	vim_free(buf);
9133     }
9134 }
9135 
9136 
9137 /*
9138  * Create a Vim spell file from one or more word lists.
9139  * "fnames[0]" is the output file name.
9140  * "fnames[fcount - 1]" is the last input file name.
9141  * Exception: when "fnames[0]" ends in ".add" it's used as the input file name
9142  * and ".spl" is appended to make the output file name.
9143  */
9144     static void
9145 mkspell(fcount, fnames, ascii, over_write, added_word)
9146     int		fcount;
9147     char_u	**fnames;
9148     int		ascii;		    /* -ascii argument given */
9149     int		over_write;	    /* overwrite existing output file */
9150     int		added_word;	    /* invoked through "zg" */
9151 {
9152     char_u	*fname = NULL;
9153     char_u	*wfname;
9154     char_u	**innames;
9155     int		incount;
9156     afffile_T	*(afile[8]);
9157     int		i;
9158     int		len;
9159     struct stat	st;
9160     int		error = FALSE;
9161     spellinfo_T spin;
9162 
9163     vim_memset(&spin, 0, sizeof(spin));
9164     spin.si_verbose = !added_word;
9165     spin.si_ascii = ascii;
9166     spin.si_followup = TRUE;
9167     spin.si_rem_accents = TRUE;
9168     ga_init2(&spin.si_rep, (int)sizeof(fromto_T), 20);
9169     ga_init2(&spin.si_repsal, (int)sizeof(fromto_T), 20);
9170     ga_init2(&spin.si_sal, (int)sizeof(fromto_T), 20);
9171     ga_init2(&spin.si_map, (int)sizeof(char_u), 100);
9172     ga_init2(&spin.si_comppat, (int)sizeof(char_u *), 20);
9173     ga_init2(&spin.si_prefcond, (int)sizeof(char_u *), 50);
9174     hash_init(&spin.si_commonwords);
9175     spin.si_newcompID = 127;	/* start compound ID at first maximum */
9176 
9177     /* default: fnames[0] is output file, following are input files */
9178     innames = &fnames[1];
9179     incount = fcount - 1;
9180 
9181     wfname = alloc(MAXPATHL);
9182     if (wfname == NULL)
9183 	return;
9184 
9185     if (fcount >= 1)
9186     {
9187 	len = (int)STRLEN(fnames[0]);
9188 	if (fcount == 1 && len > 4 && STRCMP(fnames[0] + len - 4, ".add") == 0)
9189 	{
9190 	    /* For ":mkspell path/en.latin1.add" output file is
9191 	     * "path/en.latin1.add.spl". */
9192 	    innames = &fnames[0];
9193 	    incount = 1;
9194 	    vim_snprintf((char *)wfname, MAXPATHL, "%s.spl", fnames[0]);
9195 	}
9196 	else if (fcount == 1)
9197 	{
9198 	    /* For ":mkspell path/vim" output file is "path/vim.latin1.spl". */
9199 	    innames = &fnames[0];
9200 	    incount = 1;
9201 	    vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL,
9202 		  fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc());
9203 	}
9204 	else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0)
9205 	{
9206 	    /* Name ends in ".spl", use as the file name. */
9207 	    vim_strncpy(wfname, fnames[0], MAXPATHL - 1);
9208 	}
9209 	else
9210 	    /* Name should be language, make the file name from it. */
9211 	    vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL,
9212 		  fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc());
9213 
9214 	/* Check for .ascii.spl. */
9215 	if (strstr((char *)gettail(wfname), SPL_FNAME_ASCII) != NULL)
9216 	    spin.si_ascii = TRUE;
9217 
9218 	/* Check for .add.spl. */
9219 	if (strstr((char *)gettail(wfname), SPL_FNAME_ADD) != NULL)
9220 	    spin.si_add = TRUE;
9221     }
9222 
9223     if (incount <= 0)
9224 	EMSG(_(e_invarg));	/* need at least output and input names */
9225     else if (vim_strchr(gettail(wfname), '_') != NULL)
9226 	EMSG(_("E751: Output file name must not have region name"));
9227     else if (incount > 8)
9228 	EMSG(_("E754: Only up to 8 regions supported"));
9229     else
9230     {
9231 	/* Check for overwriting before doing things that may take a lot of
9232 	 * time. */
9233 	if (!over_write && mch_stat((char *)wfname, &st) >= 0)
9234 	{
9235 	    EMSG(_(e_exists));
9236 	    goto theend;
9237 	}
9238 	if (mch_isdir(wfname))
9239 	{
9240 	    EMSG2(_(e_isadir2), wfname);
9241 	    goto theend;
9242 	}
9243 
9244 	fname = alloc(MAXPATHL);
9245 	if (fname == NULL)
9246 	    goto theend;
9247 
9248 	/*
9249 	 * Init the aff and dic pointers.
9250 	 * Get the region names if there are more than 2 arguments.
9251 	 */
9252 	for (i = 0; i < incount; ++i)
9253 	{
9254 	    afile[i] = NULL;
9255 
9256 	    if (incount > 1)
9257 	    {
9258 		len = (int)STRLEN(innames[i]);
9259 		if (STRLEN(gettail(innames[i])) < 5
9260 						|| innames[i][len - 3] != '_')
9261 		{
9262 		    EMSG2(_("E755: Invalid region in %s"), innames[i]);
9263 		    goto theend;
9264 		}
9265 		spin.si_region_name[i * 2] = TOLOWER_ASC(innames[i][len - 2]);
9266 		spin.si_region_name[i * 2 + 1] =
9267 					     TOLOWER_ASC(innames[i][len - 1]);
9268 	    }
9269 	}
9270 	spin.si_region_count = incount;
9271 
9272 	spin.si_foldroot = wordtree_alloc(&spin);
9273 	spin.si_keeproot = wordtree_alloc(&spin);
9274 	spin.si_prefroot = wordtree_alloc(&spin);
9275 	if (spin.si_foldroot == NULL
9276 		|| spin.si_keeproot == NULL
9277 		|| spin.si_prefroot == NULL)
9278 	{
9279 	    free_blocks(spin.si_blocks);
9280 	    goto theend;
9281 	}
9282 
9283 	/* When not producing a .add.spl file clear the character table when
9284 	 * we encounter one in the .aff file.  This means we dump the current
9285 	 * one in the .spl file if the .aff file doesn't define one.  That's
9286 	 * better than guessing the contents, the table will match a
9287 	 * previously loaded spell file. */
9288 	if (!spin.si_add)
9289 	    spin.si_clear_chartab = TRUE;
9290 
9291 	/*
9292 	 * Read all the .aff and .dic files.
9293 	 * Text is converted to 'encoding'.
9294 	 * Words are stored in the case-folded and keep-case trees.
9295 	 */
9296 	for (i = 0; i < incount && !error; ++i)
9297 	{
9298 	    spin.si_conv.vc_type = CONV_NONE;
9299 	    spin.si_region = 1 << i;
9300 
9301 	    vim_snprintf((char *)fname, MAXPATHL, "%s.aff", innames[i]);
9302 	    if (mch_stat((char *)fname, &st) >= 0)
9303 	    {
9304 		/* Read the .aff file.  Will init "spin->si_conv" based on the
9305 		 * "SET" line. */
9306 		afile[i] = spell_read_aff(&spin, fname);
9307 		if (afile[i] == NULL)
9308 		    error = TRUE;
9309 		else
9310 		{
9311 		    /* Read the .dic file and store the words in the trees. */
9312 		    vim_snprintf((char *)fname, MAXPATHL, "%s.dic",
9313 								  innames[i]);
9314 		    if (spell_read_dic(&spin, fname, afile[i]) == FAIL)
9315 			error = TRUE;
9316 		}
9317 	    }
9318 	    else
9319 	    {
9320 		/* No .aff file, try reading the file as a word list.  Store
9321 		 * the words in the trees. */
9322 		if (spell_read_wordfile(&spin, innames[i]) == FAIL)
9323 		    error = TRUE;
9324 	    }
9325 
9326 #ifdef FEAT_MBYTE
9327 	    /* Free any conversion stuff. */
9328 	    convert_setup(&spin.si_conv, NULL, NULL);
9329 #endif
9330 	}
9331 
9332 	if (spin.si_compflags != NULL && spin.si_nobreak)
9333 	    MSG(_("Warning: both compounding and NOBREAK specified"));
9334 
9335 	if (!error && !got_int)
9336 	{
9337 	    /*
9338 	     * Combine tails in the tree.
9339 	     */
9340 	    spell_message(&spin, (char_u *)_(msg_compressing));
9341 	    wordtree_compress(&spin, spin.si_foldroot);
9342 	    wordtree_compress(&spin, spin.si_keeproot);
9343 	    wordtree_compress(&spin, spin.si_prefroot);
9344 	}
9345 
9346 	if (!error && !got_int)
9347 	{
9348 	    /*
9349 	     * Write the info in the spell file.
9350 	     */
9351 	    vim_snprintf((char *)IObuff, IOSIZE,
9352 				      _("Writing spell file %s ..."), wfname);
9353 	    spell_message(&spin, IObuff);
9354 
9355 	    error = write_vim_spell(&spin, wfname) == FAIL;
9356 
9357 	    spell_message(&spin, (char_u *)_("Done!"));
9358 	    vim_snprintf((char *)IObuff, IOSIZE,
9359 		 _("Estimated runtime memory use: %d bytes"), spin.si_memtot);
9360 	    spell_message(&spin, IObuff);
9361 
9362 	    /*
9363 	     * If the file is loaded need to reload it.
9364 	     */
9365 	    if (!error)
9366 		spell_reload_one(wfname, added_word);
9367 	}
9368 
9369 	/* Free the allocated memory. */
9370 	ga_clear(&spin.si_rep);
9371 	ga_clear(&spin.si_repsal);
9372 	ga_clear(&spin.si_sal);
9373 	ga_clear(&spin.si_map);
9374 	ga_clear(&spin.si_comppat);
9375 	ga_clear(&spin.si_prefcond);
9376 	hash_clear_all(&spin.si_commonwords, 0);
9377 
9378 	/* Free the .aff file structures. */
9379 	for (i = 0; i < incount; ++i)
9380 	    if (afile[i] != NULL)
9381 		spell_free_aff(afile[i]);
9382 
9383 	/* Free all the bits and pieces at once. */
9384 	free_blocks(spin.si_blocks);
9385 
9386 	/*
9387 	 * If there is soundfolding info and no NOSUGFILE item create the
9388 	 * .sug file with the soundfolded word trie.
9389 	 */
9390 	if (spin.si_sugtime != 0 && !error && !got_int)
9391 	    spell_make_sugfile(&spin, wfname);
9392 
9393     }
9394 
9395 theend:
9396     vim_free(fname);
9397     vim_free(wfname);
9398 }
9399 
9400 /*
9401  * Display a message for spell file processing when 'verbose' is set or using
9402  * ":mkspell".  "str" can be IObuff.
9403  */
9404     static void
9405 spell_message(spin, str)
9406     spellinfo_T *spin;
9407     char_u	*str;
9408 {
9409     if (spin->si_verbose || p_verbose > 2)
9410     {
9411 	if (!spin->si_verbose)
9412 	    verbose_enter();
9413 	MSG(str);
9414 	out_flush();
9415 	if (!spin->si_verbose)
9416 	    verbose_leave();
9417     }
9418 }
9419 
9420 /*
9421  * ":[count]spellgood  {word}"
9422  * ":[count]spellwrong  {word}"
9423  * ":[count]spellundo  {word}"
9424  */
9425     void
9426 ex_spell(eap)
9427     exarg_T *eap;
9428 {
9429     spell_add_word(eap->arg, (int)STRLEN(eap->arg), eap->cmdidx == CMD_spellwrong,
9430 				   eap->forceit ? 0 : (int)eap->line2,
9431 				   eap->cmdidx == CMD_spellundo);
9432 }
9433 
9434 /*
9435  * Add "word[len]" to 'spellfile' as a good or bad word.
9436  */
9437     void
9438 spell_add_word(word, len, bad, idx, undo)
9439     char_u	*word;
9440     int		len;
9441     int		bad;
9442     int		idx;	    /* "zG" and "zW": zero, otherwise index in
9443 			       'spellfile' */
9444     int		undo;	    /* TRUE for "zug", "zuG", "zuw" and "zuW" */
9445 {
9446     FILE	*fd = NULL;
9447     buf_T	*buf = NULL;
9448     int		new_spf = FALSE;
9449     char_u	*fname;
9450     char_u	*fnamebuf = NULL;
9451     char_u	line[MAXWLEN * 2];
9452     long	fpos, fpos_next = 0;
9453     int		i;
9454     char_u	*spf;
9455 
9456     if (idx == 0)	    /* use internal wordlist */
9457     {
9458 	if (int_wordlist == NULL)
9459 	{
9460 	    int_wordlist = vim_tempname('s', FALSE);
9461 	    if (int_wordlist == NULL)
9462 		return;
9463 	}
9464 	fname = int_wordlist;
9465     }
9466     else
9467     {
9468 	/* If 'spellfile' isn't set figure out a good default value. */
9469 	if (*curwin->w_s->b_p_spf == NUL)
9470 	{
9471 	    init_spellfile();
9472 	    new_spf = TRUE;
9473 	}
9474 
9475 	if (*curwin->w_s->b_p_spf == NUL)
9476 	{
9477 	    EMSG2(_(e_notset), "spellfile");
9478 	    return;
9479 	}
9480 	fnamebuf = alloc(MAXPATHL);
9481 	if (fnamebuf == NULL)
9482 	    return;
9483 
9484 	for (spf = curwin->w_s->b_p_spf, i = 1; *spf != NUL; ++i)
9485 	{
9486 	    copy_option_part(&spf, fnamebuf, MAXPATHL, ",");
9487 	    if (i == idx)
9488 		break;
9489 	    if (*spf == NUL)
9490 	    {
9491 		EMSGN(_("E765: 'spellfile' does not have %ld entries"), idx);
9492 		vim_free(fnamebuf);
9493 		return;
9494 	    }
9495 	}
9496 
9497 	/* Check that the user isn't editing the .add file somewhere. */
9498 	buf = buflist_findname_exp(fnamebuf);
9499 	if (buf != NULL && buf->b_ml.ml_mfp == NULL)
9500 	    buf = NULL;
9501 	if (buf != NULL && bufIsChanged(buf))
9502 	{
9503 	    EMSG(_(e_bufloaded));
9504 	    vim_free(fnamebuf);
9505 	    return;
9506 	}
9507 
9508 	fname = fnamebuf;
9509     }
9510 
9511     if (bad || undo)
9512     {
9513 	/* When the word appears as good word we need to remove that one,
9514 	 * since its flags sort before the one with WF_BANNED. */
9515 	fd = mch_fopen((char *)fname, "r");
9516 	if (fd != NULL)
9517 	{
9518 	    while (!vim_fgets(line, MAXWLEN * 2, fd))
9519 	    {
9520 		fpos = fpos_next;
9521 		fpos_next = ftell(fd);
9522 		if (STRNCMP(word, line, len) == 0
9523 			&& (line[len] == '/' || line[len] < ' '))
9524 		{
9525 		    /* Found duplicate word.  Remove it by writing a '#' at
9526 		     * the start of the line.  Mixing reading and writing
9527 		     * doesn't work for all systems, close the file first. */
9528 		    fclose(fd);
9529 		    fd = mch_fopen((char *)fname, "r+");
9530 		    if (fd == NULL)
9531 			break;
9532 		    if (fseek(fd, fpos, SEEK_SET) == 0)
9533 		    {
9534 			fputc('#', fd);
9535 			if (undo)
9536 			{
9537 			    home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
9538 			    smsg((char_u *)_("Word '%.*s' removed from %s"),
9539 							 len, word, NameBuff);
9540 			}
9541 		    }
9542 		    fseek(fd, fpos_next, SEEK_SET);
9543 		}
9544 	    }
9545 	    if (fd != NULL)
9546 		fclose(fd);
9547 	}
9548     }
9549 
9550     if (!undo)
9551     {
9552 	fd = mch_fopen((char *)fname, "a");
9553 	if (fd == NULL && new_spf)
9554 	{
9555 	    char_u *p;
9556 
9557 	    /* We just initialized the 'spellfile' option and can't open the
9558 	     * file.  We may need to create the "spell" directory first.  We
9559 	     * already checked the runtime directory is writable in
9560 	     * init_spellfile(). */
9561 	    if (!dir_of_file_exists(fname) && (p = gettail_sep(fname)) != fname)
9562 	    {
9563 		int c = *p;
9564 
9565 		/* The directory doesn't exist.  Try creating it and opening
9566 		 * the file again. */
9567 		*p = NUL;
9568 		vim_mkdir(fname, 0755);
9569 		*p = c;
9570 		fd = mch_fopen((char *)fname, "a");
9571 	    }
9572 	}
9573 
9574 	if (fd == NULL)
9575 	    EMSG2(_(e_notopen), fname);
9576 	else
9577 	{
9578 	    if (bad)
9579 		fprintf(fd, "%.*s/!\n", len, word);
9580 	    else
9581 		fprintf(fd, "%.*s\n", len, word);
9582 	    fclose(fd);
9583 
9584 	    home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
9585 	    smsg((char_u *)_("Word '%.*s' added to %s"), len, word, NameBuff);
9586 	}
9587     }
9588 
9589     if (fd != NULL)
9590     {
9591 	/* Update the .add.spl file. */
9592 	mkspell(1, &fname, FALSE, TRUE, TRUE);
9593 
9594 	/* If the .add file is edited somewhere, reload it. */
9595 	if (buf != NULL)
9596 	    buf_reload(buf, buf->b_orig_mode);
9597 
9598 	redraw_all_later(SOME_VALID);
9599     }
9600     vim_free(fnamebuf);
9601 }
9602 
9603 /*
9604  * Initialize 'spellfile' for the current buffer.
9605  */
9606     static void
9607 init_spellfile()
9608 {
9609     char_u	*buf;
9610     int		l;
9611     char_u	*fname;
9612     char_u	*rtp;
9613     char_u	*lend;
9614     int		aspath = FALSE;
9615     char_u	*lstart = curbuf->b_s.b_p_spl;
9616 
9617     if (*curwin->w_s->b_p_spl != NUL && curwin->w_s->b_langp.ga_len > 0)
9618     {
9619 	buf = alloc(MAXPATHL);
9620 	if (buf == NULL)
9621 	    return;
9622 
9623 	/* Find the end of the language name.  Exclude the region.  If there
9624 	 * is a path separator remember the start of the tail. */
9625 	for (lend = curwin->w_s->b_p_spl; *lend != NUL
9626 			&& vim_strchr((char_u *)",._", *lend) == NULL; ++lend)
9627 	    if (vim_ispathsep(*lend))
9628 	    {
9629 		aspath = TRUE;
9630 		lstart = lend + 1;
9631 	    }
9632 
9633 	/* Loop over all entries in 'runtimepath'.  Use the first one where we
9634 	 * are allowed to write. */
9635 	rtp = p_rtp;
9636 	while (*rtp != NUL)
9637 	{
9638 	    if (aspath)
9639 		/* Use directory of an entry with path, e.g., for
9640 		 * "/dir/lg.utf-8.spl" use "/dir". */
9641 		vim_strncpy(buf, curbuf->b_s.b_p_spl,
9642 					    lstart - curbuf->b_s.b_p_spl - 1);
9643 	    else
9644 		/* Copy the path from 'runtimepath' to buf[]. */
9645 		copy_option_part(&rtp, buf, MAXPATHL, ",");
9646 	    if (filewritable(buf) == 2)
9647 	    {
9648 		/* Use the first language name from 'spelllang' and the
9649 		 * encoding used in the first loaded .spl file. */
9650 		if (aspath)
9651 		    vim_strncpy(buf, curbuf->b_s.b_p_spl,
9652 						  lend - curbuf->b_s.b_p_spl);
9653 		else
9654 		{
9655 		    /* Create the "spell" directory if it doesn't exist yet. */
9656 		    l = (int)STRLEN(buf);
9657 		    vim_snprintf((char *)buf + l, MAXPATHL - l, "/spell");
9658 		    if (filewritable(buf) != 2)
9659 			vim_mkdir(buf, 0755);
9660 
9661 		    l = (int)STRLEN(buf);
9662 		    vim_snprintf((char *)buf + l, MAXPATHL - l,
9663 				 "/%.*s", (int)(lend - lstart), lstart);
9664 		}
9665 		l = (int)STRLEN(buf);
9666 		fname = LANGP_ENTRY(curwin->w_s->b_langp, 0)
9667 							 ->lp_slang->sl_fname;
9668 		vim_snprintf((char *)buf + l, MAXPATHL - l, ".%s.add",
9669 			fname != NULL
9670 			  && strstr((char *)gettail(fname), ".ascii.") != NULL
9671 				       ? (char_u *)"ascii" : spell_enc());
9672 		set_option_value((char_u *)"spellfile", 0L, buf, OPT_LOCAL);
9673 		break;
9674 	    }
9675 	    aspath = FALSE;
9676 	}
9677 
9678 	vim_free(buf);
9679     }
9680 }
9681 
9682 
9683 /*
9684  * Init the chartab used for spelling for ASCII.
9685  * EBCDIC is not supported!
9686  */
9687     static void
9688 clear_spell_chartab(sp)
9689     spelltab_T	*sp;
9690 {
9691     int		i;
9692 
9693     /* Init everything to FALSE. */
9694     vim_memset(sp->st_isw, FALSE, sizeof(sp->st_isw));
9695     vim_memset(sp->st_isu, FALSE, sizeof(sp->st_isu));
9696     for (i = 0; i < 256; ++i)
9697     {
9698 	sp->st_fold[i] = i;
9699 	sp->st_upper[i] = i;
9700     }
9701 
9702     /* We include digits.  A word shouldn't start with a digit, but handling
9703      * that is done separately. */
9704     for (i = '0'; i <= '9'; ++i)
9705 	sp->st_isw[i] = TRUE;
9706     for (i = 'A'; i <= 'Z'; ++i)
9707     {
9708 	sp->st_isw[i] = TRUE;
9709 	sp->st_isu[i] = TRUE;
9710 	sp->st_fold[i] = i + 0x20;
9711     }
9712     for (i = 'a'; i <= 'z'; ++i)
9713     {
9714 	sp->st_isw[i] = TRUE;
9715 	sp->st_upper[i] = i - 0x20;
9716     }
9717 }
9718 
9719 /*
9720  * Init the chartab used for spelling.  Only depends on 'encoding'.
9721  * Called once while starting up and when 'encoding' changes.
9722  * The default is to use isalpha(), but the spell file should define the word
9723  * characters to make it possible that 'encoding' differs from the current
9724  * locale.  For utf-8 we don't use isalpha() but our own functions.
9725  */
9726     void
9727 init_spell_chartab()
9728 {
9729     int	    i;
9730 
9731     did_set_spelltab = FALSE;
9732     clear_spell_chartab(&spelltab);
9733 #ifdef FEAT_MBYTE
9734     if (enc_dbcs)
9735     {
9736 	/* DBCS: assume double-wide characters are word characters. */
9737 	for (i = 128; i <= 255; ++i)
9738 	    if (MB_BYTE2LEN(i) == 2)
9739 		spelltab.st_isw[i] = TRUE;
9740     }
9741     else if (enc_utf8)
9742     {
9743 	for (i = 128; i < 256; ++i)
9744 	{
9745 	    int f = utf_fold(i);
9746 	    int u = utf_toupper(i);
9747 
9748 	    spelltab.st_isu[i] = utf_isupper(i);
9749 	    spelltab.st_isw[i] = spelltab.st_isu[i] || utf_islower(i);
9750 	    /* The folded/upper-cased value is different between latin1 and
9751 	     * utf8 for 0xb5, causing E763 for no good reason.  Use the latin1
9752 	     * value for utf-8 to avoid this. */
9753 	    spelltab.st_fold[i] = (f < 256) ? f : i;
9754 	    spelltab.st_upper[i] = (u < 256) ? u : i;
9755 	}
9756     }
9757     else
9758 #endif
9759     {
9760 	/* Rough guess: use locale-dependent library functions. */
9761 	for (i = 128; i < 256; ++i)
9762 	{
9763 	    if (MB_ISUPPER(i))
9764 	    {
9765 		spelltab.st_isw[i] = TRUE;
9766 		spelltab.st_isu[i] = TRUE;
9767 		spelltab.st_fold[i] = MB_TOLOWER(i);
9768 	    }
9769 	    else if (MB_ISLOWER(i))
9770 	    {
9771 		spelltab.st_isw[i] = TRUE;
9772 		spelltab.st_upper[i] = MB_TOUPPER(i);
9773 	    }
9774 	}
9775     }
9776 }
9777 
9778 /*
9779  * Set the spell character tables from strings in the affix file.
9780  */
9781     static int
9782 set_spell_chartab(fol, low, upp)
9783     char_u	*fol;
9784     char_u	*low;
9785     char_u	*upp;
9786 {
9787     /* We build the new tables here first, so that we can compare with the
9788      * previous one. */
9789     spelltab_T	new_st;
9790     char_u	*pf = fol, *pl = low, *pu = upp;
9791     int		f, l, u;
9792 
9793     clear_spell_chartab(&new_st);
9794 
9795     while (*pf != NUL)
9796     {
9797 	if (*pl == NUL || *pu == NUL)
9798 	{
9799 	    EMSG(_(e_affform));
9800 	    return FAIL;
9801 	}
9802 #ifdef FEAT_MBYTE
9803 	f = mb_ptr2char_adv(&pf);
9804 	l = mb_ptr2char_adv(&pl);
9805 	u = mb_ptr2char_adv(&pu);
9806 #else
9807 	f = *pf++;
9808 	l = *pl++;
9809 	u = *pu++;
9810 #endif
9811 	/* Every character that appears is a word character. */
9812 	if (f < 256)
9813 	    new_st.st_isw[f] = TRUE;
9814 	if (l < 256)
9815 	    new_st.st_isw[l] = TRUE;
9816 	if (u < 256)
9817 	    new_st.st_isw[u] = TRUE;
9818 
9819 	/* if "LOW" and "FOL" are not the same the "LOW" char needs
9820 	 * case-folding */
9821 	if (l < 256 && l != f)
9822 	{
9823 	    if (f >= 256)
9824 	    {
9825 		EMSG(_(e_affrange));
9826 		return FAIL;
9827 	    }
9828 	    new_st.st_fold[l] = f;
9829 	}
9830 
9831 	/* if "UPP" and "FOL" are not the same the "UPP" char needs
9832 	 * case-folding, it's upper case and the "UPP" is the upper case of
9833 	 * "FOL" . */
9834 	if (u < 256 && u != f)
9835 	{
9836 	    if (f >= 256)
9837 	    {
9838 		EMSG(_(e_affrange));
9839 		return FAIL;
9840 	    }
9841 	    new_st.st_fold[u] = f;
9842 	    new_st.st_isu[u] = TRUE;
9843 	    new_st.st_upper[f] = u;
9844 	}
9845     }
9846 
9847     if (*pl != NUL || *pu != NUL)
9848     {
9849 	EMSG(_(e_affform));
9850 	return FAIL;
9851     }
9852 
9853     return set_spell_finish(&new_st);
9854 }
9855 
9856 /*
9857  * Set the spell character tables from strings in the .spl file.
9858  */
9859     static void
9860 set_spell_charflags(flags, cnt, fol)
9861     char_u	*flags;
9862     int		cnt;	    /* length of "flags" */
9863     char_u	*fol;
9864 {
9865     /* We build the new tables here first, so that we can compare with the
9866      * previous one. */
9867     spelltab_T	new_st;
9868     int		i;
9869     char_u	*p = fol;
9870     int		c;
9871 
9872     clear_spell_chartab(&new_st);
9873 
9874     for (i = 0; i < 128; ++i)
9875     {
9876 	if (i < cnt)
9877 	{
9878 	    new_st.st_isw[i + 128] = (flags[i] & CF_WORD) != 0;
9879 	    new_st.st_isu[i + 128] = (flags[i] & CF_UPPER) != 0;
9880 	}
9881 
9882 	if (*p != NUL)
9883 	{
9884 #ifdef FEAT_MBYTE
9885 	    c = mb_ptr2char_adv(&p);
9886 #else
9887 	    c = *p++;
9888 #endif
9889 	    new_st.st_fold[i + 128] = c;
9890 	    if (i + 128 != c && new_st.st_isu[i + 128] && c < 256)
9891 		new_st.st_upper[c] = i + 128;
9892 	}
9893     }
9894 
9895     (void)set_spell_finish(&new_st);
9896 }
9897 
9898     static int
9899 set_spell_finish(new_st)
9900     spelltab_T	*new_st;
9901 {
9902     int		i;
9903 
9904     if (did_set_spelltab)
9905     {
9906 	/* check that it's the same table */
9907 	for (i = 0; i < 256; ++i)
9908 	{
9909 	    if (spelltab.st_isw[i] != new_st->st_isw[i]
9910 		    || spelltab.st_isu[i] != new_st->st_isu[i]
9911 		    || spelltab.st_fold[i] != new_st->st_fold[i]
9912 		    || spelltab.st_upper[i] != new_st->st_upper[i])
9913 	    {
9914 		EMSG(_("E763: Word characters differ between spell files"));
9915 		return FAIL;
9916 	    }
9917 	}
9918     }
9919     else
9920     {
9921 	/* copy the new spelltab into the one being used */
9922 	spelltab = *new_st;
9923 	did_set_spelltab = TRUE;
9924     }
9925 
9926     return OK;
9927 }
9928 
9929 /*
9930  * Return TRUE if "p" points to a word character.
9931  * As a special case we see "midword" characters as word character when it is
9932  * followed by a word character.  This finds they'there but not 'they there'.
9933  * Thus this only works properly when past the first character of the word.
9934  */
9935     static int
9936 spell_iswordp(p, wp)
9937     char_u	*p;
9938     win_T	*wp;	    /* buffer used */
9939 {
9940 #ifdef FEAT_MBYTE
9941     char_u	*s;
9942     int		l;
9943     int		c;
9944 
9945     if (has_mbyte)
9946     {
9947 	l = MB_BYTE2LEN(*p);
9948 	s = p;
9949 	if (l == 1)
9950 	{
9951 	    /* be quick for ASCII */
9952 	    if (wp->w_s->b_spell_ismw[*p])
9953 		s = p + 1;		/* skip a mid-word character */
9954 	}
9955 	else
9956 	{
9957 	    c = mb_ptr2char(p);
9958 	    if (c < 256 ? wp->w_s->b_spell_ismw[c]
9959 		    : (wp->w_s->b_spell_ismw_mb != NULL
9960 			   && vim_strchr(wp->w_s->b_spell_ismw_mb, c) != NULL))
9961 		s = p + l;
9962 	}
9963 
9964 	c = mb_ptr2char(s);
9965 	if (c > 255)
9966 	    return spell_mb_isword_class(mb_get_class(s), wp);
9967 	return spelltab.st_isw[c];
9968     }
9969 #endif
9970 
9971     return spelltab.st_isw[wp->w_s->b_spell_ismw[*p] ? p[1] : p[0]];
9972 }
9973 
9974 /*
9975  * Return TRUE if "p" points to a word character.
9976  * Unlike spell_iswordp() this doesn't check for "midword" characters.
9977  */
9978     static int
9979 spell_iswordp_nmw(p, wp)
9980     char_u	*p;
9981     win_T	*wp;
9982 {
9983 #ifdef FEAT_MBYTE
9984     int		c;
9985 
9986     if (has_mbyte)
9987     {
9988 	c = mb_ptr2char(p);
9989 	if (c > 255)
9990 	    return spell_mb_isword_class(mb_get_class(p), wp);
9991 	return spelltab.st_isw[c];
9992     }
9993 #endif
9994     return spelltab.st_isw[*p];
9995 }
9996 
9997 #ifdef FEAT_MBYTE
9998 /*
9999  * Return TRUE if word class indicates a word character.
10000  * Only for characters above 255.
10001  * Unicode subscript and superscript are not considered word characters.
10002  * See also dbcs_class() and utf_class() in mbyte.c.
10003  */
10004     static int
10005 spell_mb_isword_class(cl, wp)
10006     int		cl;
10007     win_T	*wp;
10008 {
10009     if (wp->w_s->b_cjk)
10010 	/* East Asian characters are not considered word characters. */
10011 	return cl == 2 || cl == 0x2800;
10012     return cl >= 2 && cl != 0x2070 && cl != 0x2080;
10013 }
10014 
10015 /*
10016  * Return TRUE if "p" points to a word character.
10017  * Wide version of spell_iswordp().
10018  */
10019     static int
10020 spell_iswordp_w(p, wp)
10021     int		*p;
10022     win_T	*wp;
10023 {
10024     int		*s;
10025 
10026     if (*p < 256 ? wp->w_s->b_spell_ismw[*p]
10027 		 : (wp->w_s->b_spell_ismw_mb != NULL
10028 			     && vim_strchr(wp->w_s->b_spell_ismw_mb, *p) != NULL))
10029 	s = p + 1;
10030     else
10031 	s = p;
10032 
10033     if (*s > 255)
10034     {
10035 	if (enc_utf8)
10036 	    return spell_mb_isword_class(utf_class(*s), wp);
10037 	if (enc_dbcs)
10038 	    return spell_mb_isword_class(
10039 				dbcs_class((unsigned)*s >> 8, *s & 0xff), wp);
10040 	return 0;
10041     }
10042     return spelltab.st_isw[*s];
10043 }
10044 #endif
10045 
10046 /*
10047  * Write the table with prefix conditions to the .spl file.
10048  * When "fd" is NULL only count the length of what is written.
10049  */
10050     static int
10051 write_spell_prefcond(fd, gap)
10052     FILE	*fd;
10053     garray_T	*gap;
10054 {
10055     int		i;
10056     char_u	*p;
10057     int		len;
10058     int		totlen;
10059     size_t	x = 1;  /* collect return value of fwrite() */
10060 
10061     if (fd != NULL)
10062 	put_bytes(fd, (long_u)gap->ga_len, 2);	    /* <prefcondcnt> */
10063 
10064     totlen = 2 + gap->ga_len; /* length of <prefcondcnt> and <condlen> bytes */
10065 
10066     for (i = 0; i < gap->ga_len; ++i)
10067     {
10068 	/* <prefcond> : <condlen> <condstr> */
10069 	p = ((char_u **)gap->ga_data)[i];
10070 	if (p != NULL)
10071 	{
10072 	    len = (int)STRLEN(p);
10073 	    if (fd != NULL)
10074 	    {
10075 		fputc(len, fd);
10076 		x &= fwrite(p, (size_t)len, (size_t)1, fd);
10077 	    }
10078 	    totlen += len;
10079 	}
10080 	else if (fd != NULL)
10081 	    fputc(0, fd);
10082     }
10083 
10084     return totlen;
10085 }
10086 
10087 /*
10088  * Case-fold "str[len]" into "buf[buflen]".  The result is NUL terminated.
10089  * Uses the character definitions from the .spl file.
10090  * When using a multi-byte 'encoding' the length may change!
10091  * Returns FAIL when something wrong.
10092  */
10093     static int
10094 spell_casefold(str, len, buf, buflen)
10095     char_u	*str;
10096     int		len;
10097     char_u	*buf;
10098     int		buflen;
10099 {
10100     int		i;
10101 
10102     if (len >= buflen)
10103     {
10104 	buf[0] = NUL;
10105 	return FAIL;		/* result will not fit */
10106     }
10107 
10108 #ifdef FEAT_MBYTE
10109     if (has_mbyte)
10110     {
10111 	int	outi = 0;
10112 	char_u	*p;
10113 	int	c;
10114 
10115 	/* Fold one character at a time. */
10116 	for (p = str; p < str + len; )
10117 	{
10118 	    if (outi + MB_MAXBYTES > buflen)
10119 	    {
10120 		buf[outi] = NUL;
10121 		return FAIL;
10122 	    }
10123 	    c = mb_cptr2char_adv(&p);
10124 	    outi += mb_char2bytes(SPELL_TOFOLD(c), buf + outi);
10125 	}
10126 	buf[outi] = NUL;
10127     }
10128     else
10129 #endif
10130     {
10131 	/* Be quick for non-multibyte encodings. */
10132 	for (i = 0; i < len; ++i)
10133 	    buf[i] = spelltab.st_fold[str[i]];
10134 	buf[i] = NUL;
10135     }
10136 
10137     return OK;
10138 }
10139 
10140 /* values for sps_flags */
10141 #define SPS_BEST    1
10142 #define SPS_FAST    2
10143 #define SPS_DOUBLE  4
10144 
10145 static int sps_flags = SPS_BEST;	/* flags from 'spellsuggest' */
10146 static int sps_limit = 9999;		/* max nr of suggestions given */
10147 
10148 /*
10149  * Check the 'spellsuggest' option.  Return FAIL if it's wrong.
10150  * Sets "sps_flags" and "sps_limit".
10151  */
10152     int
10153 spell_check_sps()
10154 {
10155     char_u	*p;
10156     char_u	*s;
10157     char_u	buf[MAXPATHL];
10158     int		f;
10159 
10160     sps_flags = 0;
10161     sps_limit = 9999;
10162 
10163     for (p = p_sps; *p != NUL; )
10164     {
10165 	copy_option_part(&p, buf, MAXPATHL, ",");
10166 
10167 	f = 0;
10168 	if (VIM_ISDIGIT(*buf))
10169 	{
10170 	    s = buf;
10171 	    sps_limit = getdigits(&s);
10172 	    if (*s != NUL && !VIM_ISDIGIT(*s))
10173 		f = -1;
10174 	}
10175 	else if (STRCMP(buf, "best") == 0)
10176 	    f = SPS_BEST;
10177 	else if (STRCMP(buf, "fast") == 0)
10178 	    f = SPS_FAST;
10179 	else if (STRCMP(buf, "double") == 0)
10180 	    f = SPS_DOUBLE;
10181 	else if (STRNCMP(buf, "expr:", 5) != 0
10182 		&& STRNCMP(buf, "file:", 5) != 0)
10183 	    f = -1;
10184 
10185 	if (f == -1 || (sps_flags != 0 && f != 0))
10186 	{
10187 	    sps_flags = SPS_BEST;
10188 	    sps_limit = 9999;
10189 	    return FAIL;
10190 	}
10191 	if (f != 0)
10192 	    sps_flags = f;
10193     }
10194 
10195     if (sps_flags == 0)
10196 	sps_flags = SPS_BEST;
10197 
10198     return OK;
10199 }
10200 
10201 /*
10202  * "z=": Find badly spelled word under or after the cursor.
10203  * Give suggestions for the properly spelled word.
10204  * In Visual mode use the highlighted word as the bad word.
10205  * When "count" is non-zero use that suggestion.
10206  */
10207     void
10208 spell_suggest(count)
10209     int		count;
10210 {
10211     char_u	*line;
10212     pos_T	prev_cursor = curwin->w_cursor;
10213     char_u	wcopy[MAXWLEN + 2];
10214     char_u	*p;
10215     int		i;
10216     int		c;
10217     suginfo_T	sug;
10218     suggest_T	*stp;
10219     int		mouse_used;
10220     int		need_cap;
10221     int		limit;
10222     int		selected = count;
10223     int		badlen = 0;
10224     int		msg_scroll_save = msg_scroll;
10225 
10226     if (no_spell_checking(curwin))
10227 	return;
10228 
10229     if (VIsual_active)
10230     {
10231 	/* Use the Visually selected text as the bad word.  But reject
10232 	 * a multi-line selection. */
10233 	if (curwin->w_cursor.lnum != VIsual.lnum)
10234 	{
10235 	    vim_beep(BO_SPELL);
10236 	    return;
10237 	}
10238 	badlen = (int)curwin->w_cursor.col - (int)VIsual.col;
10239 	if (badlen < 0)
10240 	    badlen = -badlen;
10241 	else
10242 	    curwin->w_cursor.col = VIsual.col;
10243 	++badlen;
10244 	end_visual_mode();
10245     }
10246     /* Find the start of the badly spelled word. */
10247     else if (spell_move_to(curwin, FORWARD, TRUE, TRUE, NULL) == 0
10248 	    || curwin->w_cursor.col > prev_cursor.col)
10249     {
10250 	/* No bad word or it starts after the cursor: use the word under the
10251 	 * cursor. */
10252 	curwin->w_cursor = prev_cursor;
10253 	line = ml_get_curline();
10254 	p = line + curwin->w_cursor.col;
10255 	/* Backup to before start of word. */
10256 	while (p > line && spell_iswordp_nmw(p, curwin))
10257 	    mb_ptr_back(line, p);
10258 	/* Forward to start of word. */
10259 	while (*p != NUL && !spell_iswordp_nmw(p, curwin))
10260 	    mb_ptr_adv(p);
10261 
10262 	if (!spell_iswordp_nmw(p, curwin))		/* No word found. */
10263 	{
10264 	    beep_flush();
10265 	    return;
10266 	}
10267 	curwin->w_cursor.col = (colnr_T)(p - line);
10268     }
10269 
10270     /* Get the word and its length. */
10271 
10272     /* Figure out if the word should be capitalised. */
10273     need_cap = check_need_cap(curwin->w_cursor.lnum, curwin->w_cursor.col);
10274 
10275     /* Make a copy of current line since autocommands may free the line. */
10276     line = vim_strsave(ml_get_curline());
10277     if (line == NULL)
10278 	goto skip;
10279 
10280     /* Get the list of suggestions.  Limit to 'lines' - 2 or the number in
10281      * 'spellsuggest', whatever is smaller. */
10282     if (sps_limit > (int)Rows - 2)
10283 	limit = (int)Rows - 2;
10284     else
10285 	limit = sps_limit;
10286     spell_find_suggest(line + curwin->w_cursor.col, badlen, &sug, limit,
10287 							TRUE, need_cap, TRUE);
10288 
10289     if (sug.su_ga.ga_len == 0)
10290 	MSG(_("Sorry, no suggestions"));
10291     else if (count > 0)
10292     {
10293 	if (count > sug.su_ga.ga_len)
10294 	    smsg((char_u *)_("Sorry, only %ld suggestions"),
10295 						      (long)sug.su_ga.ga_len);
10296     }
10297     else
10298     {
10299 	vim_free(repl_from);
10300 	repl_from = NULL;
10301 	vim_free(repl_to);
10302 	repl_to = NULL;
10303 
10304 #ifdef FEAT_RIGHTLEFT
10305 	/* When 'rightleft' is set the list is drawn right-left. */
10306 	cmdmsg_rl = curwin->w_p_rl;
10307 	if (cmdmsg_rl)
10308 	    msg_col = Columns - 1;
10309 #endif
10310 
10311 	/* List the suggestions. */
10312 	msg_start();
10313 	msg_row = Rows - 1;	/* for when 'cmdheight' > 1 */
10314 	lines_left = Rows;	/* avoid more prompt */
10315 	vim_snprintf((char *)IObuff, IOSIZE, _("Change \"%.*s\" to:"),
10316 						sug.su_badlen, sug.su_badptr);
10317 #ifdef FEAT_RIGHTLEFT
10318 	if (cmdmsg_rl && STRNCMP(IObuff, "Change", 6) == 0)
10319 	{
10320 	    /* And now the rabbit from the high hat: Avoid showing the
10321 	     * untranslated message rightleft. */
10322 	    vim_snprintf((char *)IObuff, IOSIZE, ":ot \"%.*s\" egnahC",
10323 						sug.su_badlen, sug.su_badptr);
10324 	}
10325 #endif
10326 	msg_puts(IObuff);
10327 	msg_clr_eos();
10328 	msg_putchar('\n');
10329 
10330 	msg_scroll = TRUE;
10331 	for (i = 0; i < sug.su_ga.ga_len; ++i)
10332 	{
10333 	    stp = &SUG(sug.su_ga, i);
10334 
10335 	    /* The suggested word may replace only part of the bad word, add
10336 	     * the not replaced part. */
10337 	    vim_strncpy(wcopy, stp->st_word, MAXWLEN);
10338 	    if (sug.su_badlen > stp->st_orglen)
10339 		vim_strncpy(wcopy + stp->st_wordlen,
10340 					       sug.su_badptr + stp->st_orglen,
10341 					      sug.su_badlen - stp->st_orglen);
10342 	    vim_snprintf((char *)IObuff, IOSIZE, "%2d", i + 1);
10343 #ifdef FEAT_RIGHTLEFT
10344 	    if (cmdmsg_rl)
10345 		rl_mirror(IObuff);
10346 #endif
10347 	    msg_puts(IObuff);
10348 
10349 	    vim_snprintf((char *)IObuff, IOSIZE, " \"%s\"", wcopy);
10350 	    msg_puts(IObuff);
10351 
10352 	    /* The word may replace more than "su_badlen". */
10353 	    if (sug.su_badlen < stp->st_orglen)
10354 	    {
10355 		vim_snprintf((char *)IObuff, IOSIZE, _(" < \"%.*s\""),
10356 					       stp->st_orglen, sug.su_badptr);
10357 		msg_puts(IObuff);
10358 	    }
10359 
10360 	    if (p_verbose > 0)
10361 	    {
10362 		/* Add the score. */
10363 		if (sps_flags & (SPS_DOUBLE | SPS_BEST))
10364 		    vim_snprintf((char *)IObuff, IOSIZE, " (%s%d - %d)",
10365 			stp->st_salscore ? "s " : "",
10366 			stp->st_score, stp->st_altscore);
10367 		else
10368 		    vim_snprintf((char *)IObuff, IOSIZE, " (%d)",
10369 			    stp->st_score);
10370 #ifdef FEAT_RIGHTLEFT
10371 		if (cmdmsg_rl)
10372 		    /* Mirror the numbers, but keep the leading space. */
10373 		    rl_mirror(IObuff + 1);
10374 #endif
10375 		msg_advance(30);
10376 		msg_puts(IObuff);
10377 	    }
10378 	    msg_putchar('\n');
10379 	}
10380 
10381 #ifdef FEAT_RIGHTLEFT
10382 	cmdmsg_rl = FALSE;
10383 	msg_col = 0;
10384 #endif
10385 	/* Ask for choice. */
10386 	selected = prompt_for_number(&mouse_used);
10387 	if (mouse_used)
10388 	    selected -= lines_left;
10389 	lines_left = Rows;		/* avoid more prompt */
10390 	/* don't delay for 'smd' in normal_cmd() */
10391 	msg_scroll = msg_scroll_save;
10392     }
10393 
10394     if (selected > 0 && selected <= sug.su_ga.ga_len && u_save_cursor() == OK)
10395     {
10396 	/* Save the from and to text for :spellrepall. */
10397 	stp = &SUG(sug.su_ga, selected - 1);
10398 	if (sug.su_badlen > stp->st_orglen)
10399 	{
10400 	    /* Replacing less than "su_badlen", append the remainder to
10401 	     * repl_to. */
10402 	    repl_from = vim_strnsave(sug.su_badptr, sug.su_badlen);
10403 	    vim_snprintf((char *)IObuff, IOSIZE, "%s%.*s", stp->st_word,
10404 		    sug.su_badlen - stp->st_orglen,
10405 					      sug.su_badptr + stp->st_orglen);
10406 	    repl_to = vim_strsave(IObuff);
10407 	}
10408 	else
10409 	{
10410 	    /* Replacing su_badlen or more, use the whole word. */
10411 	    repl_from = vim_strnsave(sug.su_badptr, stp->st_orglen);
10412 	    repl_to = vim_strsave(stp->st_word);
10413 	}
10414 
10415 	/* Replace the word. */
10416 	p = alloc((unsigned)STRLEN(line) - stp->st_orglen
10417 						       + stp->st_wordlen + 1);
10418 	if (p != NULL)
10419 	{
10420 	    c = (int)(sug.su_badptr - line);
10421 	    mch_memmove(p, line, c);
10422 	    STRCPY(p + c, stp->st_word);
10423 	    STRCAT(p, sug.su_badptr + stp->st_orglen);
10424 	    ml_replace(curwin->w_cursor.lnum, p, FALSE);
10425 	    curwin->w_cursor.col = c;
10426 
10427 	    /* For redo we use a change-word command. */
10428 	    ResetRedobuff();
10429 	    AppendToRedobuff((char_u *)"ciw");
10430 	    AppendToRedobuffLit(p + c,
10431 			    stp->st_wordlen + sug.su_badlen - stp->st_orglen);
10432 	    AppendCharToRedobuff(ESC);
10433 
10434 	    /* After this "p" may be invalid. */
10435 	    changed_bytes(curwin->w_cursor.lnum, c);
10436 	}
10437     }
10438     else
10439 	curwin->w_cursor = prev_cursor;
10440 
10441     spell_find_cleanup(&sug);
10442 skip:
10443     vim_free(line);
10444 }
10445 
10446 /*
10447  * Check if the word at line "lnum" column "col" is required to start with a
10448  * capital.  This uses 'spellcapcheck' of the current buffer.
10449  */
10450     static int
10451 check_need_cap(lnum, col)
10452     linenr_T	lnum;
10453     colnr_T	col;
10454 {
10455     int		need_cap = FALSE;
10456     char_u	*line;
10457     char_u	*line_copy = NULL;
10458     char_u	*p;
10459     colnr_T	endcol;
10460     regmatch_T	regmatch;
10461 
10462     if (curwin->w_s->b_cap_prog == NULL)
10463 	return FALSE;
10464 
10465     line = ml_get_curline();
10466     endcol = 0;
10467     if ((int)(skipwhite(line) - line) >= (int)col)
10468     {
10469 	/* At start of line, check if previous line is empty or sentence
10470 	 * ends there. */
10471 	if (lnum == 1)
10472 	    need_cap = TRUE;
10473 	else
10474 	{
10475 	    line = ml_get(lnum - 1);
10476 	    if (*skipwhite(line) == NUL)
10477 		need_cap = TRUE;
10478 	    else
10479 	    {
10480 		/* Append a space in place of the line break. */
10481 		line_copy = concat_str(line, (char_u *)" ");
10482 		line = line_copy;
10483 		endcol = (colnr_T)STRLEN(line);
10484 	    }
10485 	}
10486     }
10487     else
10488 	endcol = col;
10489 
10490     if (endcol > 0)
10491     {
10492 	/* Check if sentence ends before the bad word. */
10493 	regmatch.regprog = curwin->w_s->b_cap_prog;
10494 	regmatch.rm_ic = FALSE;
10495 	p = line + endcol;
10496 	for (;;)
10497 	{
10498 	    mb_ptr_back(line, p);
10499 	    if (p == line || spell_iswordp_nmw(p, curwin))
10500 		break;
10501 	    if (vim_regexec(&regmatch, p, 0)
10502 					 && regmatch.endp[0] == line + endcol)
10503 	    {
10504 		need_cap = TRUE;
10505 		break;
10506 	    }
10507 	}
10508 	curwin->w_s->b_cap_prog = regmatch.regprog;
10509     }
10510 
10511     vim_free(line_copy);
10512 
10513     return need_cap;
10514 }
10515 
10516 
10517 /*
10518  * ":spellrepall"
10519  */
10520     void
10521 ex_spellrepall(eap)
10522     exarg_T *eap UNUSED;
10523 {
10524     pos_T	pos = curwin->w_cursor;
10525     char_u	*frompat;
10526     int		addlen;
10527     char_u	*line;
10528     char_u	*p;
10529     int		save_ws = p_ws;
10530     linenr_T	prev_lnum = 0;
10531 
10532     if (repl_from == NULL || repl_to == NULL)
10533     {
10534 	EMSG(_("E752: No previous spell replacement"));
10535 	return;
10536     }
10537     addlen = (int)(STRLEN(repl_to) - STRLEN(repl_from));
10538 
10539     frompat = alloc((unsigned)STRLEN(repl_from) + 7);
10540     if (frompat == NULL)
10541 	return;
10542     sprintf((char *)frompat, "\\V\\<%s\\>", repl_from);
10543     p_ws = FALSE;
10544 
10545     sub_nsubs = 0;
10546     sub_nlines = 0;
10547     curwin->w_cursor.lnum = 0;
10548     while (!got_int)
10549     {
10550 	if (do_search(NULL, '/', frompat, 1L, SEARCH_KEEP, NULL) == 0
10551 						   || u_save_cursor() == FAIL)
10552 	    break;
10553 
10554 	/* Only replace when the right word isn't there yet.  This happens
10555 	 * when changing "etc" to "etc.". */
10556 	line = ml_get_curline();
10557 	if (addlen <= 0 || STRNCMP(line + curwin->w_cursor.col,
10558 					       repl_to, STRLEN(repl_to)) != 0)
10559 	{
10560 	    p = alloc((unsigned)STRLEN(line) + addlen + 1);
10561 	    if (p == NULL)
10562 		break;
10563 	    mch_memmove(p, line, curwin->w_cursor.col);
10564 	    STRCPY(p + curwin->w_cursor.col, repl_to);
10565 	    STRCAT(p, line + curwin->w_cursor.col + STRLEN(repl_from));
10566 	    ml_replace(curwin->w_cursor.lnum, p, FALSE);
10567 	    changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
10568 
10569 	    if (curwin->w_cursor.lnum != prev_lnum)
10570 	    {
10571 		++sub_nlines;
10572 		prev_lnum = curwin->w_cursor.lnum;
10573 	    }
10574 	    ++sub_nsubs;
10575 	}
10576 	curwin->w_cursor.col += (colnr_T)STRLEN(repl_to);
10577     }
10578 
10579     p_ws = save_ws;
10580     curwin->w_cursor = pos;
10581     vim_free(frompat);
10582 
10583     if (sub_nsubs == 0)
10584 	EMSG2(_("E753: Not found: %s"), repl_from);
10585     else
10586 	do_sub_msg(FALSE);
10587 }
10588 
10589 /*
10590  * Find spell suggestions for "word".  Return them in the growarray "*gap" as
10591  * a list of allocated strings.
10592  */
10593     void
10594 spell_suggest_list(gap, word, maxcount, need_cap, interactive)
10595     garray_T	*gap;
10596     char_u	*word;
10597     int		maxcount;	/* maximum nr of suggestions */
10598     int		need_cap;	/* 'spellcapcheck' matched */
10599     int		interactive;
10600 {
10601     suginfo_T	sug;
10602     int		i;
10603     suggest_T	*stp;
10604     char_u	*wcopy;
10605 
10606     spell_find_suggest(word, 0, &sug, maxcount, FALSE, need_cap, interactive);
10607 
10608     /* Make room in "gap". */
10609     ga_init2(gap, sizeof(char_u *), sug.su_ga.ga_len + 1);
10610     if (ga_grow(gap, sug.su_ga.ga_len) == OK)
10611     {
10612 	for (i = 0; i < sug.su_ga.ga_len; ++i)
10613 	{
10614 	    stp = &SUG(sug.su_ga, i);
10615 
10616 	    /* The suggested word may replace only part of "word", add the not
10617 	     * replaced part. */
10618 	    wcopy = alloc(stp->st_wordlen
10619 		      + (unsigned)STRLEN(sug.su_badptr + stp->st_orglen) + 1);
10620 	    if (wcopy == NULL)
10621 		break;
10622 	    STRCPY(wcopy, stp->st_word);
10623 	    STRCPY(wcopy + stp->st_wordlen, sug.su_badptr + stp->st_orglen);
10624 	    ((char_u **)gap->ga_data)[gap->ga_len++] = wcopy;
10625 	}
10626     }
10627 
10628     spell_find_cleanup(&sug);
10629 }
10630 
10631 /*
10632  * Find spell suggestions for the word at the start of "badptr".
10633  * Return the suggestions in "su->su_ga".
10634  * The maximum number of suggestions is "maxcount".
10635  * Note: does use info for the current window.
10636  * This is based on the mechanisms of Aspell, but completely reimplemented.
10637  */
10638     static void
10639 spell_find_suggest(badptr, badlen, su, maxcount, banbadword, need_cap, interactive)
10640     char_u	*badptr;
10641     int		badlen;		/* length of bad word or 0 if unknown */
10642     suginfo_T	*su;
10643     int		maxcount;
10644     int		banbadword;	/* don't include badword in suggestions */
10645     int		need_cap;	/* word should start with capital */
10646     int		interactive;
10647 {
10648     hlf_T	attr = HLF_COUNT;
10649     char_u	buf[MAXPATHL];
10650     char_u	*p;
10651     int		do_combine = FALSE;
10652     char_u	*sps_copy;
10653 #ifdef FEAT_EVAL
10654     static int	expr_busy = FALSE;
10655 #endif
10656     int		c;
10657     int		i;
10658     langp_T	*lp;
10659 
10660     /*
10661      * Set the info in "*su".
10662      */
10663     vim_memset(su, 0, sizeof(suginfo_T));
10664     ga_init2(&su->su_ga, (int)sizeof(suggest_T), 10);
10665     ga_init2(&su->su_sga, (int)sizeof(suggest_T), 10);
10666     if (*badptr == NUL)
10667 	return;
10668     hash_init(&su->su_banned);
10669 
10670     su->su_badptr = badptr;
10671     if (badlen != 0)
10672 	su->su_badlen = badlen;
10673     else
10674 	su->su_badlen = spell_check(curwin, su->su_badptr, &attr, NULL, FALSE);
10675     su->su_maxcount = maxcount;
10676     su->su_maxscore = SCORE_MAXINIT;
10677 
10678     if (su->su_badlen >= MAXWLEN)
10679 	su->su_badlen = MAXWLEN - 1;	/* just in case */
10680     vim_strncpy(su->su_badword, su->su_badptr, su->su_badlen);
10681     (void)spell_casefold(su->su_badptr, su->su_badlen,
10682 						    su->su_fbadword, MAXWLEN);
10683     /* get caps flags for bad word */
10684     su->su_badflags = badword_captype(su->su_badptr,
10685 					       su->su_badptr + su->su_badlen);
10686     if (need_cap)
10687 	su->su_badflags |= WF_ONECAP;
10688 
10689     /* Find the default language for sound folding.  We simply use the first
10690      * one in 'spelllang' that supports sound folding.  That's good for when
10691      * using multiple files for one language, it's not that bad when mixing
10692      * languages (e.g., "pl,en"). */
10693     for (i = 0; i < curbuf->b_s.b_langp.ga_len; ++i)
10694     {
10695 	lp = LANGP_ENTRY(curbuf->b_s.b_langp, i);
10696 	if (lp->lp_sallang != NULL)
10697 	{
10698 	    su->su_sallang = lp->lp_sallang;
10699 	    break;
10700 	}
10701     }
10702 
10703     /* Soundfold the bad word with the default sound folding, so that we don't
10704      * have to do this many times. */
10705     if (su->su_sallang != NULL)
10706 	spell_soundfold(su->su_sallang, su->su_fbadword, TRUE,
10707 							  su->su_sal_badword);
10708 
10709     /* If the word is not capitalised and spell_check() doesn't consider the
10710      * word to be bad then it might need to be capitalised.  Add a suggestion
10711      * for that. */
10712     c = PTR2CHAR(su->su_badptr);
10713     if (!SPELL_ISUPPER(c) && attr == HLF_COUNT)
10714     {
10715 	make_case_word(su->su_badword, buf, WF_ONECAP);
10716 	add_suggestion(su, &su->su_ga, buf, su->su_badlen, SCORE_ICASE,
10717 					      0, TRUE, su->su_sallang, FALSE);
10718     }
10719 
10720     /* Ban the bad word itself.  It may appear in another region. */
10721     if (banbadword)
10722 	add_banned(su, su->su_badword);
10723 
10724     /* Make a copy of 'spellsuggest', because the expression may change it. */
10725     sps_copy = vim_strsave(p_sps);
10726     if (sps_copy == NULL)
10727 	return;
10728 
10729     /* Loop over the items in 'spellsuggest'. */
10730     for (p = sps_copy; *p != NUL; )
10731     {
10732 	copy_option_part(&p, buf, MAXPATHL, ",");
10733 
10734 	if (STRNCMP(buf, "expr:", 5) == 0)
10735 	{
10736 #ifdef FEAT_EVAL
10737 	    /* Evaluate an expression.  Skip this when called recursively,
10738 	     * when using spellsuggest() in the expression. */
10739 	    if (!expr_busy)
10740 	    {
10741 		expr_busy = TRUE;
10742 		spell_suggest_expr(su, buf + 5);
10743 		expr_busy = FALSE;
10744 	    }
10745 #endif
10746 	}
10747 	else if (STRNCMP(buf, "file:", 5) == 0)
10748 	    /* Use list of suggestions in a file. */
10749 	    spell_suggest_file(su, buf + 5);
10750 	else
10751 	{
10752 	    /* Use internal method. */
10753 	    spell_suggest_intern(su, interactive);
10754 	    if (sps_flags & SPS_DOUBLE)
10755 		do_combine = TRUE;
10756 	}
10757     }
10758 
10759     vim_free(sps_copy);
10760 
10761     if (do_combine)
10762 	/* Combine the two list of suggestions.  This must be done last,
10763 	 * because sorting changes the order again. */
10764 	score_combine(su);
10765 }
10766 
10767 #ifdef FEAT_EVAL
10768 /*
10769  * Find suggestions by evaluating expression "expr".
10770  */
10771     static void
10772 spell_suggest_expr(su, expr)
10773     suginfo_T	*su;
10774     char_u	*expr;
10775 {
10776     list_T	*list;
10777     listitem_T	*li;
10778     int		score;
10779     char_u	*p;
10780 
10781     /* The work is split up in a few parts to avoid having to export
10782      * suginfo_T.
10783      * First evaluate the expression and get the resulting list. */
10784     list = eval_spell_expr(su->su_badword, expr);
10785     if (list != NULL)
10786     {
10787 	/* Loop over the items in the list. */
10788 	for (li = list->lv_first; li != NULL; li = li->li_next)
10789 	    if (li->li_tv.v_type == VAR_LIST)
10790 	    {
10791 		/* Get the word and the score from the items. */
10792 		score = get_spellword(li->li_tv.vval.v_list, &p);
10793 		if (score >= 0 && score <= su->su_maxscore)
10794 		    add_suggestion(su, &su->su_ga, p, su->su_badlen,
10795 				       score, 0, TRUE, su->su_sallang, FALSE);
10796 	    }
10797 	list_unref(list);
10798     }
10799 
10800     /* Remove bogus suggestions, sort and truncate at "maxcount". */
10801     check_suggestions(su, &su->su_ga);
10802     (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10803 }
10804 #endif
10805 
10806 /*
10807  * Find suggestions in file "fname".  Used for "file:" in 'spellsuggest'.
10808  */
10809     static void
10810 spell_suggest_file(su, fname)
10811     suginfo_T	*su;
10812     char_u	*fname;
10813 {
10814     FILE	*fd;
10815     char_u	line[MAXWLEN * 2];
10816     char_u	*p;
10817     int		len;
10818     char_u	cword[MAXWLEN];
10819 
10820     /* Open the file. */
10821     fd = mch_fopen((char *)fname, "r");
10822     if (fd == NULL)
10823     {
10824 	EMSG2(_(e_notopen), fname);
10825 	return;
10826     }
10827 
10828     /* Read it line by line. */
10829     while (!vim_fgets(line, MAXWLEN * 2, fd) && !got_int)
10830     {
10831 	line_breakcheck();
10832 
10833 	p = vim_strchr(line, '/');
10834 	if (p == NULL)
10835 	    continue;	    /* No Tab found, just skip the line. */
10836 	*p++ = NUL;
10837 	if (STRICMP(su->su_badword, line) == 0)
10838 	{
10839 	    /* Match!  Isolate the good word, until CR or NL. */
10840 	    for (len = 0; p[len] >= ' '; ++len)
10841 		;
10842 	    p[len] = NUL;
10843 
10844 	    /* If the suggestion doesn't have specific case duplicate the case
10845 	     * of the bad word. */
10846 	    if (captype(p, NULL) == 0)
10847 	    {
10848 		make_case_word(p, cword, su->su_badflags);
10849 		p = cword;
10850 	    }
10851 
10852 	    add_suggestion(su, &su->su_ga, p, su->su_badlen,
10853 				  SCORE_FILE, 0, TRUE, su->su_sallang, FALSE);
10854 	}
10855     }
10856 
10857     fclose(fd);
10858 
10859     /* Remove bogus suggestions, sort and truncate at "maxcount". */
10860     check_suggestions(su, &su->su_ga);
10861     (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10862 }
10863 
10864 /*
10865  * Find suggestions for the internal method indicated by "sps_flags".
10866  */
10867     static void
10868 spell_suggest_intern(su, interactive)
10869     suginfo_T	*su;
10870     int		interactive;
10871 {
10872     /*
10873      * Load the .sug file(s) that are available and not done yet.
10874      */
10875     suggest_load_files();
10876 
10877     /*
10878      * 1. Try special cases, such as repeating a word: "the the" -> "the".
10879      *
10880      * Set a maximum score to limit the combination of operations that is
10881      * tried.
10882      */
10883     suggest_try_special(su);
10884 
10885     /*
10886      * 2. Try inserting/deleting/swapping/changing a letter, use REP entries
10887      *    from the .aff file and inserting a space (split the word).
10888      */
10889     suggest_try_change(su);
10890 
10891     /* For the resulting top-scorers compute the sound-a-like score. */
10892     if (sps_flags & SPS_DOUBLE)
10893 	score_comp_sal(su);
10894 
10895     /*
10896      * 3. Try finding sound-a-like words.
10897      */
10898     if ((sps_flags & SPS_FAST) == 0)
10899     {
10900 	if (sps_flags & SPS_BEST)
10901 	    /* Adjust the word score for the suggestions found so far for how
10902 	     * they sounds like. */
10903 	    rescore_suggestions(su);
10904 
10905 	/*
10906 	 * While going through the soundfold tree "su_maxscore" is the score
10907 	 * for the soundfold word, limits the changes that are being tried,
10908 	 * and "su_sfmaxscore" the rescored score, which is set by
10909 	 * cleanup_suggestions().
10910 	 * First find words with a small edit distance, because this is much
10911 	 * faster and often already finds the top-N suggestions.  If we didn't
10912 	 * find many suggestions try again with a higher edit distance.
10913 	 * "sl_sounddone" is used to avoid doing the same word twice.
10914 	 */
10915 	suggest_try_soundalike_prep();
10916 	su->su_maxscore = SCORE_SFMAX1;
10917 	su->su_sfmaxscore = SCORE_MAXINIT * 3;
10918 	suggest_try_soundalike(su);
10919 	if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
10920 	{
10921 	    /* We didn't find enough matches, try again, allowing more
10922 	     * changes to the soundfold word. */
10923 	    su->su_maxscore = SCORE_SFMAX2;
10924 	    suggest_try_soundalike(su);
10925 	    if (su->su_ga.ga_len < SUG_CLEAN_COUNT(su))
10926 	    {
10927 		/* Still didn't find enough matches, try again, allowing even
10928 		 * more changes to the soundfold word. */
10929 		su->su_maxscore = SCORE_SFMAX3;
10930 		suggest_try_soundalike(su);
10931 	    }
10932 	}
10933 	su->su_maxscore = su->su_sfmaxscore;
10934 	suggest_try_soundalike_finish();
10935     }
10936 
10937     /* When CTRL-C was hit while searching do show the results.  Only clear
10938      * got_int when using a command, not for spellsuggest(). */
10939     ui_breakcheck();
10940     if (interactive && got_int)
10941     {
10942 	(void)vgetc();
10943 	got_int = FALSE;
10944     }
10945 
10946     if ((sps_flags & SPS_DOUBLE) == 0 && su->su_ga.ga_len != 0)
10947     {
10948 	if (sps_flags & SPS_BEST)
10949 	    /* Adjust the word score for how it sounds like. */
10950 	    rescore_suggestions(su);
10951 
10952 	/* Remove bogus suggestions, sort and truncate at "maxcount". */
10953 	check_suggestions(su, &su->su_ga);
10954 	(void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
10955     }
10956 }
10957 
10958 /*
10959  * Load the .sug files for languages that have one and weren't loaded yet.
10960  */
10961     static void
10962 suggest_load_files()
10963 {
10964     langp_T	*lp;
10965     int		lpi;
10966     slang_T	*slang;
10967     char_u	*dotp;
10968     FILE	*fd;
10969     char_u	buf[MAXWLEN];
10970     int		i;
10971     time_t	timestamp;
10972     int		wcount;
10973     int		wordnr;
10974     garray_T	ga;
10975     int		c;
10976 
10977     /* Do this for all languages that support sound folding. */
10978     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
10979     {
10980 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
10981 	slang = lp->lp_slang;
10982 	if (slang->sl_sugtime != 0 && !slang->sl_sugloaded)
10983 	{
10984 	    /* Change ".spl" to ".sug" and open the file.  When the file isn't
10985 	     * found silently skip it.  Do set "sl_sugloaded" so that we
10986 	     * don't try again and again. */
10987 	    slang->sl_sugloaded = TRUE;
10988 
10989 	    dotp = vim_strrchr(slang->sl_fname, '.');
10990 	    if (dotp == NULL || fnamecmp(dotp, ".spl") != 0)
10991 		continue;
10992 	    STRCPY(dotp, ".sug");
10993 	    fd = mch_fopen((char *)slang->sl_fname, "r");
10994 	    if (fd == NULL)
10995 		goto nextone;
10996 
10997 	    /*
10998 	     * <SUGHEADER>: <fileID> <versionnr> <timestamp>
10999 	     */
11000 	    for (i = 0; i < VIMSUGMAGICL; ++i)
11001 		buf[i] = getc(fd);			/* <fileID> */
11002 	    if (STRNCMP(buf, VIMSUGMAGIC, VIMSUGMAGICL) != 0)
11003 	    {
11004 		EMSG2(_("E778: This does not look like a .sug file: %s"),
11005 							     slang->sl_fname);
11006 		goto nextone;
11007 	    }
11008 	    c = getc(fd);				/* <versionnr> */
11009 	    if (c < VIMSUGVERSION)
11010 	    {
11011 		EMSG2(_("E779: Old .sug file, needs to be updated: %s"),
11012 							     slang->sl_fname);
11013 		goto nextone;
11014 	    }
11015 	    else if (c > VIMSUGVERSION)
11016 	    {
11017 		EMSG2(_("E780: .sug file is for newer version of Vim: %s"),
11018 							     slang->sl_fname);
11019 		goto nextone;
11020 	    }
11021 
11022 	    /* Check the timestamp, it must be exactly the same as the one in
11023 	     * the .spl file.  Otherwise the word numbers won't match. */
11024 	    timestamp = get8ctime(fd);			/* <timestamp> */
11025 	    if (timestamp != slang->sl_sugtime)
11026 	    {
11027 		EMSG2(_("E781: .sug file doesn't match .spl file: %s"),
11028 							     slang->sl_fname);
11029 		goto nextone;
11030 	    }
11031 
11032 	    /*
11033 	     * <SUGWORDTREE>: <wordtree>
11034 	     * Read the trie with the soundfolded words.
11035 	     */
11036 	    if (spell_read_tree(fd, &slang->sl_sbyts, &slang->sl_sidxs,
11037 							       FALSE, 0) != 0)
11038 	    {
11039 someerror:
11040 		EMSG2(_("E782: error while reading .sug file: %s"),
11041 							     slang->sl_fname);
11042 		slang_clear_sug(slang);
11043 		goto nextone;
11044 	    }
11045 
11046 	    /*
11047 	     * <SUGTABLE>: <sugwcount> <sugline> ...
11048 	     *
11049 	     * Read the table with word numbers.  We use a file buffer for
11050 	     * this, because it's so much like a file with lines.  Makes it
11051 	     * possible to swap the info and save on memory use.
11052 	     */
11053 	    slang->sl_sugbuf = open_spellbuf();
11054 	    if (slang->sl_sugbuf == NULL)
11055 		goto someerror;
11056 							    /* <sugwcount> */
11057 	    wcount = get4c(fd);
11058 	    if (wcount < 0)
11059 		goto someerror;
11060 
11061 	    /* Read all the wordnr lists into the buffer, one NUL terminated
11062 	     * list per line. */
11063 	    ga_init2(&ga, 1, 100);
11064 	    for (wordnr = 0; wordnr < wcount; ++wordnr)
11065 	    {
11066 		ga.ga_len = 0;
11067 		for (;;)
11068 		{
11069 		    c = getc(fd);			    /* <sugline> */
11070 		    if (c < 0 || ga_grow(&ga, 1) == FAIL)
11071 			goto someerror;
11072 		    ((char_u *)ga.ga_data)[ga.ga_len++] = c;
11073 		    if (c == NUL)
11074 			break;
11075 		}
11076 		if (ml_append_buf(slang->sl_sugbuf, (linenr_T)wordnr,
11077 					 ga.ga_data, ga.ga_len, TRUE) == FAIL)
11078 		    goto someerror;
11079 	    }
11080 	    ga_clear(&ga);
11081 
11082 	    /*
11083 	     * Need to put word counts in the word tries, so that we can find
11084 	     * a word by its number.
11085 	     */
11086 	    tree_count_words(slang->sl_fbyts, slang->sl_fidxs);
11087 	    tree_count_words(slang->sl_sbyts, slang->sl_sidxs);
11088 
11089 nextone:
11090 	    if (fd != NULL)
11091 		fclose(fd);
11092 	    STRCPY(dotp, ".spl");
11093 	}
11094     }
11095 }
11096 
11097 
11098 /*
11099  * Fill in the wordcount fields for a trie.
11100  * Returns the total number of words.
11101  */
11102     static void
11103 tree_count_words(byts, idxs)
11104     char_u	*byts;
11105     idx_T	*idxs;
11106 {
11107     int		depth;
11108     idx_T	arridx[MAXWLEN];
11109     int		curi[MAXWLEN];
11110     int		c;
11111     idx_T	n;
11112     int		wordcount[MAXWLEN];
11113 
11114     arridx[0] = 0;
11115     curi[0] = 1;
11116     wordcount[0] = 0;
11117     depth = 0;
11118     while (depth >= 0 && !got_int)
11119     {
11120 	if (curi[depth] > byts[arridx[depth]])
11121 	{
11122 	    /* Done all bytes at this node, go up one level. */
11123 	    idxs[arridx[depth]] = wordcount[depth];
11124 	    if (depth > 0)
11125 		wordcount[depth - 1] += wordcount[depth];
11126 
11127 	    --depth;
11128 	    fast_breakcheck();
11129 	}
11130 	else
11131 	{
11132 	    /* Do one more byte at this node. */
11133 	    n = arridx[depth] + curi[depth];
11134 	    ++curi[depth];
11135 
11136 	    c = byts[n];
11137 	    if (c == 0)
11138 	    {
11139 		/* End of word, count it. */
11140 		++wordcount[depth];
11141 
11142 		/* Skip over any other NUL bytes (same word with different
11143 		 * flags). */
11144 		while (byts[n + 1] == 0)
11145 		{
11146 		    ++n;
11147 		    ++curi[depth];
11148 		}
11149 	    }
11150 	    else
11151 	    {
11152 		/* Normal char, go one level deeper to count the words. */
11153 		++depth;
11154 		arridx[depth] = idxs[n];
11155 		curi[depth] = 1;
11156 		wordcount[depth] = 0;
11157 	    }
11158 	}
11159     }
11160 }
11161 
11162 /*
11163  * Free the info put in "*su" by spell_find_suggest().
11164  */
11165     static void
11166 spell_find_cleanup(su)
11167     suginfo_T	*su;
11168 {
11169     int		i;
11170 
11171     /* Free the suggestions. */
11172     for (i = 0; i < su->su_ga.ga_len; ++i)
11173 	vim_free(SUG(su->su_ga, i).st_word);
11174     ga_clear(&su->su_ga);
11175     for (i = 0; i < su->su_sga.ga_len; ++i)
11176 	vim_free(SUG(su->su_sga, i).st_word);
11177     ga_clear(&su->su_sga);
11178 
11179     /* Free the banned words. */
11180     hash_clear_all(&su->su_banned, 0);
11181 }
11182 
11183 /*
11184  * Make a copy of "word", with the first letter upper or lower cased, to
11185  * "wcopy[MAXWLEN]".  "word" must not be empty.
11186  * The result is NUL terminated.
11187  */
11188     static void
11189 onecap_copy(word, wcopy, upper)
11190     char_u	*word;
11191     char_u	*wcopy;
11192     int		upper;	    /* TRUE: first letter made upper case */
11193 {
11194     char_u	*p;
11195     int		c;
11196     int		l;
11197 
11198     p = word;
11199 #ifdef FEAT_MBYTE
11200     if (has_mbyte)
11201 	c = mb_cptr2char_adv(&p);
11202     else
11203 #endif
11204 	c = *p++;
11205     if (upper)
11206 	c = SPELL_TOUPPER(c);
11207     else
11208 	c = SPELL_TOFOLD(c);
11209 #ifdef FEAT_MBYTE
11210     if (has_mbyte)
11211 	l = mb_char2bytes(c, wcopy);
11212     else
11213 #endif
11214     {
11215 	l = 1;
11216 	wcopy[0] = c;
11217     }
11218     vim_strncpy(wcopy + l, p, MAXWLEN - l - 1);
11219 }
11220 
11221 /*
11222  * Make a copy of "word" with all the letters upper cased into
11223  * "wcopy[MAXWLEN]".  The result is NUL terminated.
11224  */
11225     static void
11226 allcap_copy(word, wcopy)
11227     char_u	*word;
11228     char_u	*wcopy;
11229 {
11230     char_u	*s;
11231     char_u	*d;
11232     int		c;
11233 
11234     d = wcopy;
11235     for (s = word; *s != NUL; )
11236     {
11237 #ifdef FEAT_MBYTE
11238 	if (has_mbyte)
11239 	    c = mb_cptr2char_adv(&s);
11240 	else
11241 #endif
11242 	    c = *s++;
11243 
11244 #ifdef FEAT_MBYTE
11245 	/* We only change 0xdf to SS when we are certain latin1 is used.  It
11246 	 * would cause weird errors in other 8-bit encodings. */
11247 	if (enc_latin1like && c == 0xdf)
11248 	{
11249 	    c = 'S';
11250 	    if (d - wcopy >= MAXWLEN - 1)
11251 		break;
11252 	    *d++ = c;
11253 	}
11254 	else
11255 #endif
11256 	    c = SPELL_TOUPPER(c);
11257 
11258 #ifdef FEAT_MBYTE
11259 	if (has_mbyte)
11260 	{
11261 	    if (d - wcopy >= MAXWLEN - MB_MAXBYTES)
11262 		break;
11263 	    d += mb_char2bytes(c, d);
11264 	}
11265 	else
11266 #endif
11267 	{
11268 	    if (d - wcopy >= MAXWLEN - 1)
11269 		break;
11270 	    *d++ = c;
11271 	}
11272     }
11273     *d = NUL;
11274 }
11275 
11276 /*
11277  * Try finding suggestions by recognizing specific situations.
11278  */
11279     static void
11280 suggest_try_special(su)
11281     suginfo_T	*su;
11282 {
11283     char_u	*p;
11284     size_t	len;
11285     int		c;
11286     char_u	word[MAXWLEN];
11287 
11288     /*
11289      * Recognize a word that is repeated: "the the".
11290      */
11291     p = skiptowhite(su->su_fbadword);
11292     len = p - su->su_fbadword;
11293     p = skipwhite(p);
11294     if (STRLEN(p) == len && STRNCMP(su->su_fbadword, p, len) == 0)
11295     {
11296 	/* Include badflags: if the badword is onecap or allcap
11297 	 * use that for the goodword too: "The the" -> "The". */
11298 	c = su->su_fbadword[len];
11299 	su->su_fbadword[len] = NUL;
11300 	make_case_word(su->su_fbadword, word, su->su_badflags);
11301 	su->su_fbadword[len] = c;
11302 
11303 	/* Give a soundalike score of 0, compute the score as if deleting one
11304 	 * character. */
11305 	add_suggestion(su, &su->su_ga, word, su->su_badlen,
11306 		       RESCORE(SCORE_REP, 0), 0, TRUE, su->su_sallang, FALSE);
11307     }
11308 }
11309 
11310 /*
11311  * Change the 0 to 1 to measure how much time is spent in each state.
11312  * Output is dumped in "suggestprof".
11313  */
11314 #if 0
11315 # define SUGGEST_PROFILE
11316 proftime_T current;
11317 proftime_T total;
11318 proftime_T times[STATE_FINAL + 1];
11319 long counts[STATE_FINAL + 1];
11320 
11321     static void
11322 prof_init(void)
11323 {
11324     for (int i = 0; i <= STATE_FINAL; ++i)
11325     {
11326 	profile_zero(&times[i]);
11327 	counts[i] = 0;
11328     }
11329     profile_start(&current);
11330     profile_start(&total);
11331 }
11332 
11333 /* call before changing state */
11334     static void
11335 prof_store(state_T state)
11336 {
11337     profile_end(&current);
11338     profile_add(&times[state], &current);
11339     ++counts[state];
11340     profile_start(&current);
11341 }
11342 # define PROF_STORE(state) prof_store(state);
11343 
11344     static void
11345 prof_report(char *name)
11346 {
11347     FILE *fd = fopen("suggestprof", "a");
11348 
11349     profile_end(&total);
11350     fprintf(fd, "-----------------------\n");
11351     fprintf(fd, "%s: %s\n", name, profile_msg(&total));
11352     for (int i = 0; i <= STATE_FINAL; ++i)
11353 	fprintf(fd, "%d: %s (%ld)\n", i, profile_msg(&times[i]), counts[i]);
11354     fclose(fd);
11355 }
11356 #else
11357 # define PROF_STORE(state)
11358 #endif
11359 
11360 /*
11361  * Try finding suggestions by adding/removing/swapping letters.
11362  */
11363     static void
11364 suggest_try_change(su)
11365     suginfo_T	*su;
11366 {
11367     char_u	fword[MAXWLEN];	    /* copy of the bad word, case-folded */
11368     int		n;
11369     char_u	*p;
11370     int		lpi;
11371     langp_T	*lp;
11372 
11373     /* We make a copy of the case-folded bad word, so that we can modify it
11374      * to find matches (esp. REP items).  Append some more text, changing
11375      * chars after the bad word may help. */
11376     STRCPY(fword, su->su_fbadword);
11377     n = (int)STRLEN(fword);
11378     p = su->su_badptr + su->su_badlen;
11379     (void)spell_casefold(p, (int)STRLEN(p), fword + n, MAXWLEN - n);
11380 
11381     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
11382     {
11383 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
11384 
11385 	/* If reloading a spell file fails it's still in the list but
11386 	 * everything has been cleared. */
11387 	if (lp->lp_slang->sl_fbyts == NULL)
11388 	    continue;
11389 
11390 	/* Try it for this language.  Will add possible suggestions. */
11391 #ifdef SUGGEST_PROFILE
11392 	prof_init();
11393 #endif
11394 	suggest_trie_walk(su, lp, fword, FALSE);
11395 #ifdef SUGGEST_PROFILE
11396 	prof_report("try_change");
11397 #endif
11398     }
11399 }
11400 
11401 /* Check the maximum score, if we go over it we won't try this change. */
11402 #define TRY_DEEPER(su, stack, depth, add) \
11403 		(stack[depth].ts_score + (add) < su->su_maxscore)
11404 
11405 /*
11406  * Try finding suggestions by adding/removing/swapping letters.
11407  *
11408  * This uses a state machine.  At each node in the tree we try various
11409  * operations.  When trying if an operation works "depth" is increased and the
11410  * stack[] is used to store info.  This allows combinations, thus insert one
11411  * character, replace one and delete another.  The number of changes is
11412  * limited by su->su_maxscore.
11413  *
11414  * After implementing this I noticed an article by Kemal Oflazer that
11415  * describes something similar: "Error-tolerant Finite State Recognition with
11416  * Applications to Morphological Analysis and Spelling Correction" (1996).
11417  * The implementation in the article is simplified and requires a stack of
11418  * unknown depth.  The implementation here only needs a stack depth equal to
11419  * the length of the word.
11420  *
11421  * This is also used for the sound-folded word, "soundfold" is TRUE then.
11422  * The mechanism is the same, but we find a match with a sound-folded word
11423  * that comes from one or more original words.  Each of these words may be
11424  * added, this is done by add_sound_suggest().
11425  * Don't use:
11426  *	the prefix tree or the keep-case tree
11427  *	"su->su_badlen"
11428  *	anything to do with upper and lower case
11429  *	anything to do with word or non-word characters ("spell_iswordp()")
11430  *	banned words
11431  *	word flags (rare, region, compounding)
11432  *	word splitting for now
11433  *	"similar_chars()"
11434  *	use "slang->sl_repsal" instead of "lp->lp_replang->sl_rep"
11435  */
11436     static void
11437 suggest_trie_walk(su, lp, fword, soundfold)
11438     suginfo_T	*su;
11439     langp_T	*lp;
11440     char_u	*fword;
11441     int		soundfold;
11442 {
11443     char_u	tword[MAXWLEN];	    /* good word collected so far */
11444     trystate_T	stack[MAXWLEN];
11445     char_u	preword[MAXWLEN * 3]; /* word found with proper case;
11446 				       * concatenation of prefix compound
11447 				       * words and split word.  NUL terminated
11448 				       * when going deeper but not when coming
11449 				       * back. */
11450     char_u	compflags[MAXWLEN];	/* compound flags, one for each word */
11451     trystate_T	*sp;
11452     int		newscore;
11453     int		score;
11454     char_u	*byts, *fbyts, *pbyts;
11455     idx_T	*idxs, *fidxs, *pidxs;
11456     int		depth;
11457     int		c, c2, c3;
11458     int		n = 0;
11459     int		flags;
11460     garray_T	*gap;
11461     idx_T	arridx;
11462     int		len;
11463     char_u	*p;
11464     fromto_T	*ftp;
11465     int		fl = 0, tl;
11466     int		repextra = 0;	    /* extra bytes in fword[] from REP item */
11467     slang_T	*slang = lp->lp_slang;
11468     int		fword_ends;
11469     int		goodword_ends;
11470 #ifdef DEBUG_TRIEWALK
11471     /* Stores the name of the change made at each level. */
11472     char_u	changename[MAXWLEN][80];
11473 #endif
11474     int		breakcheckcount = 1000;
11475     int		compound_ok;
11476 
11477     /*
11478      * Go through the whole case-fold tree, try changes at each node.
11479      * "tword[]" contains the word collected from nodes in the tree.
11480      * "fword[]" the word we are trying to match with (initially the bad
11481      * word).
11482      */
11483     depth = 0;
11484     sp = &stack[0];
11485     vim_memset(sp, 0, sizeof(trystate_T));
11486     sp->ts_curi = 1;
11487 
11488     if (soundfold)
11489     {
11490 	/* Going through the soundfold tree. */
11491 	byts = fbyts = slang->sl_sbyts;
11492 	idxs = fidxs = slang->sl_sidxs;
11493 	pbyts = NULL;
11494 	pidxs = NULL;
11495 	sp->ts_prefixdepth = PFD_NOPREFIX;
11496 	sp->ts_state = STATE_START;
11497     }
11498     else
11499     {
11500 	/*
11501 	 * When there are postponed prefixes we need to use these first.  At
11502 	 * the end of the prefix we continue in the case-fold tree.
11503 	 */
11504 	fbyts = slang->sl_fbyts;
11505 	fidxs = slang->sl_fidxs;
11506 	pbyts = slang->sl_pbyts;
11507 	pidxs = slang->sl_pidxs;
11508 	if (pbyts != NULL)
11509 	{
11510 	    byts = pbyts;
11511 	    idxs = pidxs;
11512 	    sp->ts_prefixdepth = PFD_PREFIXTREE;
11513 	    sp->ts_state = STATE_NOPREFIX;	/* try without prefix first */
11514 	}
11515 	else
11516 	{
11517 	    byts = fbyts;
11518 	    idxs = fidxs;
11519 	    sp->ts_prefixdepth = PFD_NOPREFIX;
11520 	    sp->ts_state = STATE_START;
11521 	}
11522     }
11523 
11524     /*
11525      * Loop to find all suggestions.  At each round we either:
11526      * - For the current state try one operation, advance "ts_curi",
11527      *   increase "depth".
11528      * - When a state is done go to the next, set "ts_state".
11529      * - When all states are tried decrease "depth".
11530      */
11531     while (depth >= 0 && !got_int)
11532     {
11533 	sp = &stack[depth];
11534 	switch (sp->ts_state)
11535 	{
11536 	case STATE_START:
11537 	case STATE_NOPREFIX:
11538 	    /*
11539 	     * Start of node: Deal with NUL bytes, which means
11540 	     * tword[] may end here.
11541 	     */
11542 	    arridx = sp->ts_arridx;	    /* current node in the tree */
11543 	    len = byts[arridx];		    /* bytes in this node */
11544 	    arridx += sp->ts_curi;	    /* index of current byte */
11545 
11546 	    if (sp->ts_prefixdepth == PFD_PREFIXTREE)
11547 	    {
11548 		/* Skip over the NUL bytes, we use them later. */
11549 		for (n = 0; n < len && byts[arridx + n] == 0; ++n)
11550 		    ;
11551 		sp->ts_curi += n;
11552 
11553 		/* Always past NUL bytes now. */
11554 		n = (int)sp->ts_state;
11555 		PROF_STORE(sp->ts_state)
11556 		sp->ts_state = STATE_ENDNUL;
11557 		sp->ts_save_badflags = su->su_badflags;
11558 
11559 		/* At end of a prefix or at start of prefixtree: check for
11560 		 * following word. */
11561 		if (byts[arridx] == 0 || n == (int)STATE_NOPREFIX)
11562 		{
11563 		    /* Set su->su_badflags to the caps type at this position.
11564 		     * Use the caps type until here for the prefix itself. */
11565 #ifdef FEAT_MBYTE
11566 		    if (has_mbyte)
11567 			n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
11568 		    else
11569 #endif
11570 			n = sp->ts_fidx;
11571 		    flags = badword_captype(su->su_badptr, su->su_badptr + n);
11572 		    su->su_badflags = badword_captype(su->su_badptr + n,
11573 					       su->su_badptr + su->su_badlen);
11574 #ifdef DEBUG_TRIEWALK
11575 		    sprintf(changename[depth], "prefix");
11576 #endif
11577 		    go_deeper(stack, depth, 0);
11578 		    ++depth;
11579 		    sp = &stack[depth];
11580 		    sp->ts_prefixdepth = depth - 1;
11581 		    byts = fbyts;
11582 		    idxs = fidxs;
11583 		    sp->ts_arridx = 0;
11584 
11585 		    /* Move the prefix to preword[] with the right case
11586 		     * and make find_keepcap_word() works. */
11587 		    tword[sp->ts_twordlen] = NUL;
11588 		    make_case_word(tword + sp->ts_splitoff,
11589 					  preword + sp->ts_prewordlen, flags);
11590 		    sp->ts_prewordlen = (char_u)STRLEN(preword);
11591 		    sp->ts_splitoff = sp->ts_twordlen;
11592 		}
11593 		break;
11594 	    }
11595 
11596 	    if (sp->ts_curi > len || byts[arridx] != 0)
11597 	    {
11598 		/* Past bytes in node and/or past NUL bytes. */
11599 		PROF_STORE(sp->ts_state)
11600 		sp->ts_state = STATE_ENDNUL;
11601 		sp->ts_save_badflags = su->su_badflags;
11602 		break;
11603 	    }
11604 
11605 	    /*
11606 	     * End of word in tree.
11607 	     */
11608 	    ++sp->ts_curi;		/* eat one NUL byte */
11609 
11610 	    flags = (int)idxs[arridx];
11611 
11612 	    /* Skip words with the NOSUGGEST flag. */
11613 	    if (flags & WF_NOSUGGEST)
11614 		break;
11615 
11616 	    fword_ends = (fword[sp->ts_fidx] == NUL
11617 			   || (soundfold
11618 			       ? vim_iswhite(fword[sp->ts_fidx])
11619 			       : !spell_iswordp(fword + sp->ts_fidx, curwin)));
11620 	    tword[sp->ts_twordlen] = NUL;
11621 
11622 	    if (sp->ts_prefixdepth <= PFD_NOTSPECIAL
11623 					&& (sp->ts_flags & TSF_PREFIXOK) == 0)
11624 	    {
11625 		/* There was a prefix before the word.  Check that the prefix
11626 		 * can be used with this word. */
11627 		/* Count the length of the NULs in the prefix.  If there are
11628 		 * none this must be the first try without a prefix.  */
11629 		n = stack[sp->ts_prefixdepth].ts_arridx;
11630 		len = pbyts[n++];
11631 		for (c = 0; c < len && pbyts[n + c] == 0; ++c)
11632 		    ;
11633 		if (c > 0)
11634 		{
11635 		    c = valid_word_prefix(c, n, flags,
11636 				       tword + sp->ts_splitoff, slang, FALSE);
11637 		    if (c == 0)
11638 			break;
11639 
11640 		    /* Use the WF_RARE flag for a rare prefix. */
11641 		    if (c & WF_RAREPFX)
11642 			flags |= WF_RARE;
11643 
11644 		    /* Tricky: when checking for both prefix and compounding
11645 		     * we run into the prefix flag first.
11646 		     * Remember that it's OK, so that we accept the prefix
11647 		     * when arriving at a compound flag. */
11648 		    sp->ts_flags |= TSF_PREFIXOK;
11649 		}
11650 	    }
11651 
11652 	    /* Check NEEDCOMPOUND: can't use word without compounding.  Do try
11653 	     * appending another compound word below. */
11654 	    if (sp->ts_complen == sp->ts_compsplit && fword_ends
11655 						     && (flags & WF_NEEDCOMP))
11656 		goodword_ends = FALSE;
11657 	    else
11658 		goodword_ends = TRUE;
11659 
11660 	    p = NULL;
11661 	    compound_ok = TRUE;
11662 	    if (sp->ts_complen > sp->ts_compsplit)
11663 	    {
11664 		if (slang->sl_nobreak)
11665 		{
11666 		    /* There was a word before this word.  When there was no
11667 		     * change in this word (it was correct) add the first word
11668 		     * as a suggestion.  If this word was corrected too, we
11669 		     * need to check if a correct word follows. */
11670 		    if (sp->ts_fidx - sp->ts_splitfidx
11671 					  == sp->ts_twordlen - sp->ts_splitoff
11672 			    && STRNCMP(fword + sp->ts_splitfidx,
11673 					tword + sp->ts_splitoff,
11674 					 sp->ts_fidx - sp->ts_splitfidx) == 0)
11675 		    {
11676 			preword[sp->ts_prewordlen] = NUL;
11677 			newscore = score_wordcount_adj(slang, sp->ts_score,
11678 						 preword + sp->ts_prewordlen,
11679 						 sp->ts_prewordlen > 0);
11680 			/* Add the suggestion if the score isn't too bad. */
11681 			if (newscore <= su->su_maxscore)
11682 			    add_suggestion(su, &su->su_ga, preword,
11683 				    sp->ts_splitfidx - repextra,
11684 				    newscore, 0, FALSE,
11685 				    lp->lp_sallang, FALSE);
11686 			break;
11687 		    }
11688 		}
11689 		else
11690 		{
11691 		    /* There was a compound word before this word.  If this
11692 		     * word does not support compounding then give up
11693 		     * (splitting is tried for the word without compound
11694 		     * flag). */
11695 		    if (((unsigned)flags >> 24) == 0
11696 			    || sp->ts_twordlen - sp->ts_splitoff
11697 						       < slang->sl_compminlen)
11698 			break;
11699 #ifdef FEAT_MBYTE
11700 		    /* For multi-byte chars check character length against
11701 		     * COMPOUNDMIN. */
11702 		    if (has_mbyte
11703 			    && slang->sl_compminlen > 0
11704 			    && mb_charlen(tword + sp->ts_splitoff)
11705 						       < slang->sl_compminlen)
11706 			break;
11707 #endif
11708 
11709 		    compflags[sp->ts_complen] = ((unsigned)flags >> 24);
11710 		    compflags[sp->ts_complen + 1] = NUL;
11711 		    vim_strncpy(preword + sp->ts_prewordlen,
11712 			    tword + sp->ts_splitoff,
11713 			    sp->ts_twordlen - sp->ts_splitoff);
11714 
11715 		    /* Verify CHECKCOMPOUNDPATTERN  rules. */
11716 		    if (match_checkcompoundpattern(preword,  sp->ts_prewordlen,
11717 							  &slang->sl_comppat))
11718 			compound_ok = FALSE;
11719 
11720 		    if (compound_ok)
11721 		    {
11722 			p = preword;
11723 			while (*skiptowhite(p) != NUL)
11724 			    p = skipwhite(skiptowhite(p));
11725 			if (fword_ends && !can_compound(slang, p,
11726 						compflags + sp->ts_compsplit))
11727 			    /* Compound is not allowed.  But it may still be
11728 			     * possible if we add another (short) word. */
11729 			    compound_ok = FALSE;
11730 		    }
11731 
11732 		    /* Get pointer to last char of previous word. */
11733 		    p = preword + sp->ts_prewordlen;
11734 		    mb_ptr_back(preword, p);
11735 		}
11736 	    }
11737 
11738 	    /*
11739 	     * Form the word with proper case in preword.
11740 	     * If there is a word from a previous split, append.
11741 	     * For the soundfold tree don't change the case, simply append.
11742 	     */
11743 	    if (soundfold)
11744 		STRCPY(preword + sp->ts_prewordlen, tword + sp->ts_splitoff);
11745 	    else if (flags & WF_KEEPCAP)
11746 		/* Must find the word in the keep-case tree. */
11747 		find_keepcap_word(slang, tword + sp->ts_splitoff,
11748 						 preword + sp->ts_prewordlen);
11749 	    else
11750 	    {
11751 		/* Include badflags: If the badword is onecap or allcap
11752 		 * use that for the goodword too.  But if the badword is
11753 		 * allcap and it's only one char long use onecap. */
11754 		c = su->su_badflags;
11755 		if ((c & WF_ALLCAP)
11756 #ifdef FEAT_MBYTE
11757 			&& su->su_badlen == (*mb_ptr2len)(su->su_badptr)
11758 #else
11759 			&& su->su_badlen == 1
11760 #endif
11761 			)
11762 		    c = WF_ONECAP;
11763 		c |= flags;
11764 
11765 		/* When appending a compound word after a word character don't
11766 		 * use Onecap. */
11767 		if (p != NULL && spell_iswordp_nmw(p, curwin))
11768 		    c &= ~WF_ONECAP;
11769 		make_case_word(tword + sp->ts_splitoff,
11770 					      preword + sp->ts_prewordlen, c);
11771 	    }
11772 
11773 	    if (!soundfold)
11774 	    {
11775 		/* Don't use a banned word.  It may appear again as a good
11776 		 * word, thus remember it. */
11777 		if (flags & WF_BANNED)
11778 		{
11779 		    add_banned(su, preword + sp->ts_prewordlen);
11780 		    break;
11781 		}
11782 		if ((sp->ts_complen == sp->ts_compsplit
11783 			    && WAS_BANNED(su, preword + sp->ts_prewordlen))
11784 						   || WAS_BANNED(su, preword))
11785 		{
11786 		    if (slang->sl_compprog == NULL)
11787 			break;
11788 		    /* the word so far was banned but we may try compounding */
11789 		    goodword_ends = FALSE;
11790 		}
11791 	    }
11792 
11793 	    newscore = 0;
11794 	    if (!soundfold)	/* soundfold words don't have flags */
11795 	    {
11796 		if ((flags & WF_REGION)
11797 			    && (((unsigned)flags >> 16) & lp->lp_region) == 0)
11798 		    newscore += SCORE_REGION;
11799 		if (flags & WF_RARE)
11800 		    newscore += SCORE_RARE;
11801 
11802 		if (!spell_valid_case(su->su_badflags,
11803 				  captype(preword + sp->ts_prewordlen, NULL)))
11804 		    newscore += SCORE_ICASE;
11805 	    }
11806 
11807 	    /* TODO: how about splitting in the soundfold tree? */
11808 	    if (fword_ends
11809 		    && goodword_ends
11810 		    && sp->ts_fidx >= sp->ts_fidxtry
11811 		    && compound_ok)
11812 	    {
11813 		/* The badword also ends: add suggestions. */
11814 #ifdef DEBUG_TRIEWALK
11815 		if (soundfold && STRCMP(preword, "smwrd") == 0)
11816 		{
11817 		    int	    j;
11818 
11819 		    /* print the stack of changes that brought us here */
11820 		    smsg("------ %s -------", fword);
11821 		    for (j = 0; j < depth; ++j)
11822 			smsg("%s", changename[j]);
11823 		}
11824 #endif
11825 		if (soundfold)
11826 		{
11827 		    /* For soundfolded words we need to find the original
11828 		     * words, the edit distance and then add them. */
11829 		    add_sound_suggest(su, preword, sp->ts_score, lp);
11830 		}
11831 		else if (sp->ts_fidx > 0)
11832 		{
11833 		    /* Give a penalty when changing non-word char to word
11834 		     * char, e.g., "thes," -> "these". */
11835 		    p = fword + sp->ts_fidx;
11836 		    mb_ptr_back(fword, p);
11837 		    if (!spell_iswordp(p, curwin))
11838 		    {
11839 			p = preword + STRLEN(preword);
11840 			mb_ptr_back(preword, p);
11841 			if (spell_iswordp(p, curwin))
11842 			    newscore += SCORE_NONWORD;
11843 		    }
11844 
11845 		    /* Give a bonus to words seen before. */
11846 		    score = score_wordcount_adj(slang,
11847 						sp->ts_score + newscore,
11848 						preword + sp->ts_prewordlen,
11849 						sp->ts_prewordlen > 0);
11850 
11851 		    /* Add the suggestion if the score isn't too bad. */
11852 		    if (score <= su->su_maxscore)
11853 		    {
11854 			add_suggestion(su, &su->su_ga, preword,
11855 				    sp->ts_fidx - repextra,
11856 				    score, 0, FALSE, lp->lp_sallang, FALSE);
11857 
11858 			if (su->su_badflags & WF_MIXCAP)
11859 			{
11860 			    /* We really don't know if the word should be
11861 			     * upper or lower case, add both. */
11862 			    c = captype(preword, NULL);
11863 			    if (c == 0 || c == WF_ALLCAP)
11864 			    {
11865 				make_case_word(tword + sp->ts_splitoff,
11866 					      preword + sp->ts_prewordlen,
11867 						      c == 0 ? WF_ALLCAP : 0);
11868 
11869 				add_suggestion(su, &su->su_ga, preword,
11870 					sp->ts_fidx - repextra,
11871 					score + SCORE_ICASE, 0, FALSE,
11872 					lp->lp_sallang, FALSE);
11873 			    }
11874 			}
11875 		    }
11876 		}
11877 	    }
11878 
11879 	    /*
11880 	     * Try word split and/or compounding.
11881 	     */
11882 	    if ((sp->ts_fidx >= sp->ts_fidxtry || fword_ends)
11883 #ifdef FEAT_MBYTE
11884 		    /* Don't split halfway a character. */
11885 		    && (!has_mbyte || sp->ts_tcharlen == 0)
11886 #endif
11887 		    )
11888 	    {
11889 		int	try_compound;
11890 		int	try_split;
11891 
11892 		/* If past the end of the bad word don't try a split.
11893 		 * Otherwise try changing the next word.  E.g., find
11894 		 * suggestions for "the the" where the second "the" is
11895 		 * different.  It's done like a split.
11896 		 * TODO: word split for soundfold words */
11897 		try_split = (sp->ts_fidx - repextra < su->su_badlen)
11898 								&& !soundfold;
11899 
11900 		/* Get here in several situations:
11901 		 * 1. The word in the tree ends:
11902 		 *    If the word allows compounding try that.  Otherwise try
11903 		 *    a split by inserting a space.  For both check that a
11904 		 *    valid words starts at fword[sp->ts_fidx].
11905 		 *    For NOBREAK do like compounding to be able to check if
11906 		 *    the next word is valid.
11907 		 * 2. The badword does end, but it was due to a change (e.g.,
11908 		 *    a swap).  No need to split, but do check that the
11909 		 *    following word is valid.
11910 		 * 3. The badword and the word in the tree end.  It may still
11911 		 *    be possible to compound another (short) word.
11912 		 */
11913 		try_compound = FALSE;
11914 		if (!soundfold
11915 			&& !slang->sl_nocompoundsugs
11916 			&& slang->sl_compprog != NULL
11917 			&& ((unsigned)flags >> 24) != 0
11918 			&& sp->ts_twordlen - sp->ts_splitoff
11919 						       >= slang->sl_compminlen
11920 #ifdef FEAT_MBYTE
11921 			&& (!has_mbyte
11922 			    || slang->sl_compminlen == 0
11923 			    || mb_charlen(tword + sp->ts_splitoff)
11924 						      >= slang->sl_compminlen)
11925 #endif
11926 			&& (slang->sl_compsylmax < MAXWLEN
11927 			    || sp->ts_complen + 1 - sp->ts_compsplit
11928 							  < slang->sl_compmax)
11929 			&& (can_be_compound(sp, slang,
11930 					 compflags, ((unsigned)flags >> 24))))
11931 
11932 		{
11933 		    try_compound = TRUE;
11934 		    compflags[sp->ts_complen] = ((unsigned)flags >> 24);
11935 		    compflags[sp->ts_complen + 1] = NUL;
11936 		}
11937 
11938 		/* For NOBREAK we never try splitting, it won't make any word
11939 		 * valid. */
11940 		if (slang->sl_nobreak && !slang->sl_nocompoundsugs)
11941 		    try_compound = TRUE;
11942 
11943 		/* If we could add a compound word, and it's also possible to
11944 		 * split at this point, do the split first and set
11945 		 * TSF_DIDSPLIT to avoid doing it again. */
11946 		else if (!fword_ends
11947 			&& try_compound
11948 			&& (sp->ts_flags & TSF_DIDSPLIT) == 0)
11949 		{
11950 		    try_compound = FALSE;
11951 		    sp->ts_flags |= TSF_DIDSPLIT;
11952 		    --sp->ts_curi;	    /* do the same NUL again */
11953 		    compflags[sp->ts_complen] = NUL;
11954 		}
11955 		else
11956 		    sp->ts_flags &= ~TSF_DIDSPLIT;
11957 
11958 		if (try_split || try_compound)
11959 		{
11960 		    if (!try_compound && (!fword_ends || !goodword_ends))
11961 		    {
11962 			/* If we're going to split need to check that the
11963 			 * words so far are valid for compounding.  If there
11964 			 * is only one word it must not have the NEEDCOMPOUND
11965 			 * flag. */
11966 			if (sp->ts_complen == sp->ts_compsplit
11967 						     && (flags & WF_NEEDCOMP))
11968 			    break;
11969 			p = preword;
11970 			while (*skiptowhite(p) != NUL)
11971 			    p = skipwhite(skiptowhite(p));
11972 			if (sp->ts_complen > sp->ts_compsplit
11973 				&& !can_compound(slang, p,
11974 						compflags + sp->ts_compsplit))
11975 			    break;
11976 
11977 			if (slang->sl_nosplitsugs)
11978 			    newscore += SCORE_SPLIT_NO;
11979 			else
11980 			    newscore += SCORE_SPLIT;
11981 
11982 			/* Give a bonus to words seen before. */
11983 			newscore = score_wordcount_adj(slang, newscore,
11984 					   preword + sp->ts_prewordlen, TRUE);
11985 		    }
11986 
11987 		    if (TRY_DEEPER(su, stack, depth, newscore))
11988 		    {
11989 			go_deeper(stack, depth, newscore);
11990 #ifdef DEBUG_TRIEWALK
11991 			if (!try_compound && !fword_ends)
11992 			    sprintf(changename[depth], "%.*s-%s: split",
11993 				 sp->ts_twordlen, tword, fword + sp->ts_fidx);
11994 			else
11995 			    sprintf(changename[depth], "%.*s-%s: compound",
11996 				 sp->ts_twordlen, tword, fword + sp->ts_fidx);
11997 #endif
11998 			/* Save things to be restored at STATE_SPLITUNDO. */
11999 			sp->ts_save_badflags = su->su_badflags;
12000 			PROF_STORE(sp->ts_state)
12001 			sp->ts_state = STATE_SPLITUNDO;
12002 
12003 			++depth;
12004 			sp = &stack[depth];
12005 
12006 			/* Append a space to preword when splitting. */
12007 			if (!try_compound && !fword_ends)
12008 			    STRCAT(preword, " ");
12009 			sp->ts_prewordlen = (char_u)STRLEN(preword);
12010 			sp->ts_splitoff = sp->ts_twordlen;
12011 			sp->ts_splitfidx = sp->ts_fidx;
12012 
12013 			/* If the badword has a non-word character at this
12014 			 * position skip it.  That means replacing the
12015 			 * non-word character with a space.  Always skip a
12016 			 * character when the word ends.  But only when the
12017 			 * good word can end. */
12018 			if (((!try_compound && !spell_iswordp_nmw(fword
12019 							       + sp->ts_fidx,
12020 							       curwin))
12021 				    || fword_ends)
12022 				&& fword[sp->ts_fidx] != NUL
12023 				&& goodword_ends)
12024 			{
12025 			    int	    l;
12026 
12027 #ifdef FEAT_MBYTE
12028 			    if (has_mbyte)
12029 				l = MB_BYTE2LEN(fword[sp->ts_fidx]);
12030 			    else
12031 #endif
12032 				l = 1;
12033 			    if (fword_ends)
12034 			    {
12035 				/* Copy the skipped character to preword. */
12036 				mch_memmove(preword + sp->ts_prewordlen,
12037 						      fword + sp->ts_fidx, l);
12038 				sp->ts_prewordlen += l;
12039 				preword[sp->ts_prewordlen] = NUL;
12040 			    }
12041 			    else
12042 				sp->ts_score -= SCORE_SPLIT - SCORE_SUBST;
12043 			    sp->ts_fidx += l;
12044 			}
12045 
12046 			/* When compounding include compound flag in
12047 			 * compflags[] (already set above).  When splitting we
12048 			 * may start compounding over again.  */
12049 			if (try_compound)
12050 			    ++sp->ts_complen;
12051 			else
12052 			    sp->ts_compsplit = sp->ts_complen;
12053 			sp->ts_prefixdepth = PFD_NOPREFIX;
12054 
12055 			/* set su->su_badflags to the caps type at this
12056 			 * position */
12057 #ifdef FEAT_MBYTE
12058 			if (has_mbyte)
12059 			    n = nofold_len(fword, sp->ts_fidx, su->su_badptr);
12060 			else
12061 #endif
12062 			    n = sp->ts_fidx;
12063 			su->su_badflags = badword_captype(su->su_badptr + n,
12064 					       su->su_badptr + su->su_badlen);
12065 
12066 			/* Restart at top of the tree. */
12067 			sp->ts_arridx = 0;
12068 
12069 			/* If there are postponed prefixes, try these too. */
12070 			if (pbyts != NULL)
12071 			{
12072 			    byts = pbyts;
12073 			    idxs = pidxs;
12074 			    sp->ts_prefixdepth = PFD_PREFIXTREE;
12075 			    PROF_STORE(sp->ts_state)
12076 			    sp->ts_state = STATE_NOPREFIX;
12077 			}
12078 		    }
12079 		}
12080 	    }
12081 	    break;
12082 
12083 	case STATE_SPLITUNDO:
12084 	    /* Undo the changes done for word split or compound word. */
12085 	    su->su_badflags = sp->ts_save_badflags;
12086 
12087 	    /* Continue looking for NUL bytes. */
12088 	    PROF_STORE(sp->ts_state)
12089 	    sp->ts_state = STATE_START;
12090 
12091 	    /* In case we went into the prefix tree. */
12092 	    byts = fbyts;
12093 	    idxs = fidxs;
12094 	    break;
12095 
12096 	case STATE_ENDNUL:
12097 	    /* Past the NUL bytes in the node. */
12098 	    su->su_badflags = sp->ts_save_badflags;
12099 	    if (fword[sp->ts_fidx] == NUL
12100 #ifdef FEAT_MBYTE
12101 		    && sp->ts_tcharlen == 0
12102 #endif
12103 	       )
12104 	    {
12105 		/* The badword ends, can't use STATE_PLAIN. */
12106 		PROF_STORE(sp->ts_state)
12107 		sp->ts_state = STATE_DEL;
12108 		break;
12109 	    }
12110 	    PROF_STORE(sp->ts_state)
12111 	    sp->ts_state = STATE_PLAIN;
12112 	    /*FALLTHROUGH*/
12113 
12114 	case STATE_PLAIN:
12115 	    /*
12116 	     * Go over all possible bytes at this node, add each to tword[]
12117 	     * and use child node.  "ts_curi" is the index.
12118 	     */
12119 	    arridx = sp->ts_arridx;
12120 	    if (sp->ts_curi > byts[arridx])
12121 	    {
12122 		/* Done all bytes at this node, do next state.  When still at
12123 		 * already changed bytes skip the other tricks. */
12124 		PROF_STORE(sp->ts_state)
12125 		if (sp->ts_fidx >= sp->ts_fidxtry)
12126 		    sp->ts_state = STATE_DEL;
12127 		else
12128 		    sp->ts_state = STATE_FINAL;
12129 	    }
12130 	    else
12131 	    {
12132 		arridx += sp->ts_curi++;
12133 		c = byts[arridx];
12134 
12135 		/* Normal byte, go one level deeper.  If it's not equal to the
12136 		 * byte in the bad word adjust the score.  But don't even try
12137 		 * when the byte was already changed.  And don't try when we
12138 		 * just deleted this byte, accepting it is always cheaper than
12139 		 * delete + substitute. */
12140 		if (c == fword[sp->ts_fidx]
12141 #ifdef FEAT_MBYTE
12142 			|| (sp->ts_tcharlen > 0 && sp->ts_isdiff != DIFF_NONE)
12143 #endif
12144 			)
12145 		    newscore = 0;
12146 		else
12147 		    newscore = SCORE_SUBST;
12148 		if ((newscore == 0
12149 			    || (sp->ts_fidx >= sp->ts_fidxtry
12150 				&& ((sp->ts_flags & TSF_DIDDEL) == 0
12151 				    || c != fword[sp->ts_delidx])))
12152 			&& TRY_DEEPER(su, stack, depth, newscore))
12153 		{
12154 		    go_deeper(stack, depth, newscore);
12155 #ifdef DEBUG_TRIEWALK
12156 		    if (newscore > 0)
12157 			sprintf(changename[depth], "%.*s-%s: subst %c to %c",
12158 				sp->ts_twordlen, tword, fword + sp->ts_fidx,
12159 				fword[sp->ts_fidx], c);
12160 		    else
12161 			sprintf(changename[depth], "%.*s-%s: accept %c",
12162 				sp->ts_twordlen, tword, fword + sp->ts_fidx,
12163 				fword[sp->ts_fidx]);
12164 #endif
12165 		    ++depth;
12166 		    sp = &stack[depth];
12167 		    ++sp->ts_fidx;
12168 		    tword[sp->ts_twordlen++] = c;
12169 		    sp->ts_arridx = idxs[arridx];
12170 #ifdef FEAT_MBYTE
12171 		    if (newscore == SCORE_SUBST)
12172 			sp->ts_isdiff = DIFF_YES;
12173 		    if (has_mbyte)
12174 		    {
12175 			/* Multi-byte characters are a bit complicated to
12176 			 * handle: They differ when any of the bytes differ
12177 			 * and then their length may also differ. */
12178 			if (sp->ts_tcharlen == 0)
12179 			{
12180 			    /* First byte. */
12181 			    sp->ts_tcharidx = 0;
12182 			    sp->ts_tcharlen = MB_BYTE2LEN(c);
12183 			    sp->ts_fcharstart = sp->ts_fidx - 1;
12184 			    sp->ts_isdiff = (newscore != 0)
12185 						       ? DIFF_YES : DIFF_NONE;
12186 			}
12187 			else if (sp->ts_isdiff == DIFF_INSERT)
12188 			    /* When inserting trail bytes don't advance in the
12189 			     * bad word. */
12190 			    --sp->ts_fidx;
12191 			if (++sp->ts_tcharidx == sp->ts_tcharlen)
12192 			{
12193 			    /* Last byte of character. */
12194 			    if (sp->ts_isdiff == DIFF_YES)
12195 			    {
12196 				/* Correct ts_fidx for the byte length of the
12197 				 * character (we didn't check that before). */
12198 				sp->ts_fidx = sp->ts_fcharstart
12199 					    + MB_BYTE2LEN(
12200 						    fword[sp->ts_fcharstart]);
12201 
12202 				/* For changing a composing character adjust
12203 				 * the score from SCORE_SUBST to
12204 				 * SCORE_SUBCOMP. */
12205 				if (enc_utf8
12206 					&& utf_iscomposing(
12207 					    mb_ptr2char(tword
12208 						+ sp->ts_twordlen
12209 							   - sp->ts_tcharlen))
12210 					&& utf_iscomposing(
12211 					    mb_ptr2char(fword
12212 							+ sp->ts_fcharstart)))
12213 				    sp->ts_score -=
12214 						  SCORE_SUBST - SCORE_SUBCOMP;
12215 
12216 				/* For a similar character adjust score from
12217 				 * SCORE_SUBST to SCORE_SIMILAR. */
12218 				else if (!soundfold
12219 					&& slang->sl_has_map
12220 					&& similar_chars(slang,
12221 					    mb_ptr2char(tword
12222 						+ sp->ts_twordlen
12223 							   - sp->ts_tcharlen),
12224 					    mb_ptr2char(fword
12225 							+ sp->ts_fcharstart)))
12226 				    sp->ts_score -=
12227 						  SCORE_SUBST - SCORE_SIMILAR;
12228 			    }
12229 			    else if (sp->ts_isdiff == DIFF_INSERT
12230 					 && sp->ts_twordlen > sp->ts_tcharlen)
12231 			    {
12232 				p = tword + sp->ts_twordlen - sp->ts_tcharlen;
12233 				c = mb_ptr2char(p);
12234 				if (enc_utf8 && utf_iscomposing(c))
12235 				{
12236 				    /* Inserting a composing char doesn't
12237 				     * count that much. */
12238 				    sp->ts_score -= SCORE_INS - SCORE_INSCOMP;
12239 				}
12240 				else
12241 				{
12242 				    /* If the previous character was the same,
12243 				     * thus doubling a character, give a bonus
12244 				     * to the score.  Also for the soundfold
12245 				     * tree (might seem illogical but does
12246 				     * give better scores). */
12247 				    mb_ptr_back(tword, p);
12248 				    if (c == mb_ptr2char(p))
12249 					sp->ts_score -= SCORE_INS
12250 							       - SCORE_INSDUP;
12251 				}
12252 			    }
12253 
12254 			    /* Starting a new char, reset the length. */
12255 			    sp->ts_tcharlen = 0;
12256 			}
12257 		    }
12258 		    else
12259 #endif
12260 		    {
12261 			/* If we found a similar char adjust the score.
12262 			 * We do this after calling go_deeper() because
12263 			 * it's slow. */
12264 			if (newscore != 0
12265 				&& !soundfold
12266 				&& slang->sl_has_map
12267 				&& similar_chars(slang,
12268 						   c, fword[sp->ts_fidx - 1]))
12269 			    sp->ts_score -= SCORE_SUBST - SCORE_SIMILAR;
12270 		    }
12271 		}
12272 	    }
12273 	    break;
12274 
12275 	case STATE_DEL:
12276 #ifdef FEAT_MBYTE
12277 	    /* When past the first byte of a multi-byte char don't try
12278 	     * delete/insert/swap a character. */
12279 	    if (has_mbyte && sp->ts_tcharlen > 0)
12280 	    {
12281 		PROF_STORE(sp->ts_state)
12282 		sp->ts_state = STATE_FINAL;
12283 		break;
12284 	    }
12285 #endif
12286 	    /*
12287 	     * Try skipping one character in the bad word (delete it).
12288 	     */
12289 	    PROF_STORE(sp->ts_state)
12290 	    sp->ts_state = STATE_INS_PREP;
12291 	    sp->ts_curi = 1;
12292 	    if (soundfold && sp->ts_fidx == 0 && fword[sp->ts_fidx] == '*')
12293 		/* Deleting a vowel at the start of a word counts less, see
12294 		 * soundalike_score(). */
12295 		newscore = 2 * SCORE_DEL / 3;
12296 	    else
12297 		newscore = SCORE_DEL;
12298 	    if (fword[sp->ts_fidx] != NUL
12299 				    && TRY_DEEPER(su, stack, depth, newscore))
12300 	    {
12301 		go_deeper(stack, depth, newscore);
12302 #ifdef DEBUG_TRIEWALK
12303 		sprintf(changename[depth], "%.*s-%s: delete %c",
12304 			sp->ts_twordlen, tword, fword + sp->ts_fidx,
12305 			fword[sp->ts_fidx]);
12306 #endif
12307 		++depth;
12308 
12309 		/* Remember what character we deleted, so that we can avoid
12310 		 * inserting it again. */
12311 		stack[depth].ts_flags |= TSF_DIDDEL;
12312 		stack[depth].ts_delidx = sp->ts_fidx;
12313 
12314 		/* Advance over the character in fword[].  Give a bonus to the
12315 		 * score if the same character is following "nn" -> "n".  It's
12316 		 * a bit illogical for soundfold tree but it does give better
12317 		 * results. */
12318 #ifdef FEAT_MBYTE
12319 		if (has_mbyte)
12320 		{
12321 		    c = mb_ptr2char(fword + sp->ts_fidx);
12322 		    stack[depth].ts_fidx += MB_BYTE2LEN(fword[sp->ts_fidx]);
12323 		    if (enc_utf8 && utf_iscomposing(c))
12324 			stack[depth].ts_score -= SCORE_DEL - SCORE_DELCOMP;
12325 		    else if (c == mb_ptr2char(fword + stack[depth].ts_fidx))
12326 			stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
12327 		}
12328 		else
12329 #endif
12330 		{
12331 		    ++stack[depth].ts_fidx;
12332 		    if (fword[sp->ts_fidx] == fword[sp->ts_fidx + 1])
12333 			stack[depth].ts_score -= SCORE_DEL - SCORE_DELDUP;
12334 		}
12335 		break;
12336 	    }
12337 	    /*FALLTHROUGH*/
12338 
12339 	case STATE_INS_PREP:
12340 	    if (sp->ts_flags & TSF_DIDDEL)
12341 	    {
12342 		/* If we just deleted a byte then inserting won't make sense,
12343 		 * a substitute is always cheaper. */
12344 		PROF_STORE(sp->ts_state)
12345 		sp->ts_state = STATE_SWAP;
12346 		break;
12347 	    }
12348 
12349 	    /* skip over NUL bytes */
12350 	    n = sp->ts_arridx;
12351 	    for (;;)
12352 	    {
12353 		if (sp->ts_curi > byts[n])
12354 		{
12355 		    /* Only NUL bytes at this node, go to next state. */
12356 		    PROF_STORE(sp->ts_state)
12357 		    sp->ts_state = STATE_SWAP;
12358 		    break;
12359 		}
12360 		if (byts[n + sp->ts_curi] != NUL)
12361 		{
12362 		    /* Found a byte to insert. */
12363 		    PROF_STORE(sp->ts_state)
12364 		    sp->ts_state = STATE_INS;
12365 		    break;
12366 		}
12367 		++sp->ts_curi;
12368 	    }
12369 	    break;
12370 
12371 	    /*FALLTHROUGH*/
12372 
12373 	case STATE_INS:
12374 	    /* Insert one byte.  Repeat this for each possible byte at this
12375 	     * node. */
12376 	    n = sp->ts_arridx;
12377 	    if (sp->ts_curi > byts[n])
12378 	    {
12379 		/* Done all bytes at this node, go to next state. */
12380 		PROF_STORE(sp->ts_state)
12381 		sp->ts_state = STATE_SWAP;
12382 		break;
12383 	    }
12384 
12385 	    /* Do one more byte at this node, but:
12386 	     * - Skip NUL bytes.
12387 	     * - Skip the byte if it's equal to the byte in the word,
12388 	     *   accepting that byte is always better.
12389 	     */
12390 	    n += sp->ts_curi++;
12391 	    c = byts[n];
12392 	    if (soundfold && sp->ts_twordlen == 0 && c == '*')
12393 		/* Inserting a vowel at the start of a word counts less,
12394 		 * see soundalike_score(). */
12395 		newscore = 2 * SCORE_INS / 3;
12396 	    else
12397 		newscore = SCORE_INS;
12398 	    if (c != fword[sp->ts_fidx]
12399 				    && TRY_DEEPER(su, stack, depth, newscore))
12400 	    {
12401 		go_deeper(stack, depth, newscore);
12402 #ifdef DEBUG_TRIEWALK
12403 		sprintf(changename[depth], "%.*s-%s: insert %c",
12404 			sp->ts_twordlen, tword, fword + sp->ts_fidx,
12405 			c);
12406 #endif
12407 		++depth;
12408 		sp = &stack[depth];
12409 		tword[sp->ts_twordlen++] = c;
12410 		sp->ts_arridx = idxs[n];
12411 #ifdef FEAT_MBYTE
12412 		if (has_mbyte)
12413 		{
12414 		    fl = MB_BYTE2LEN(c);
12415 		    if (fl > 1)
12416 		    {
12417 			/* There are following bytes for the same character.
12418 			 * We must find all bytes before trying
12419 			 * delete/insert/swap/etc. */
12420 			sp->ts_tcharlen = fl;
12421 			sp->ts_tcharidx = 1;
12422 			sp->ts_isdiff = DIFF_INSERT;
12423 		    }
12424 		}
12425 		else
12426 		    fl = 1;
12427 		if (fl == 1)
12428 #endif
12429 		{
12430 		    /* If the previous character was the same, thus doubling a
12431 		     * character, give a bonus to the score.  Also for
12432 		     * soundfold words (illogical but does give a better
12433 		     * score). */
12434 		    if (sp->ts_twordlen >= 2
12435 					   && tword[sp->ts_twordlen - 2] == c)
12436 			sp->ts_score -= SCORE_INS - SCORE_INSDUP;
12437 		}
12438 	    }
12439 	    break;
12440 
12441 	case STATE_SWAP:
12442 	    /*
12443 	     * Swap two bytes in the bad word: "12" -> "21".
12444 	     * We change "fword" here, it's changed back afterwards at
12445 	     * STATE_UNSWAP.
12446 	     */
12447 	    p = fword + sp->ts_fidx;
12448 	    c = *p;
12449 	    if (c == NUL)
12450 	    {
12451 		/* End of word, can't swap or replace. */
12452 		PROF_STORE(sp->ts_state)
12453 		sp->ts_state = STATE_FINAL;
12454 		break;
12455 	    }
12456 
12457 	    /* Don't swap if the first character is not a word character.
12458 	     * SWAP3 etc. also don't make sense then. */
12459 	    if (!soundfold && !spell_iswordp(p, curwin))
12460 	    {
12461 		PROF_STORE(sp->ts_state)
12462 		sp->ts_state = STATE_REP_INI;
12463 		break;
12464 	    }
12465 
12466 #ifdef FEAT_MBYTE
12467 	    if (has_mbyte)
12468 	    {
12469 		n = mb_cptr2len(p);
12470 		c = mb_ptr2char(p);
12471 		if (p[n] == NUL)
12472 		    c2 = NUL;
12473 		else if (!soundfold && !spell_iswordp(p + n, curwin))
12474 		    c2 = c; /* don't swap non-word char */
12475 		else
12476 		    c2 = mb_ptr2char(p + n);
12477 	    }
12478 	    else
12479 #endif
12480 	    {
12481 		if (p[1] == NUL)
12482 		    c2 = NUL;
12483 		else if (!soundfold && !spell_iswordp(p + 1, curwin))
12484 		    c2 = c; /* don't swap non-word char */
12485 		else
12486 		    c2 = p[1];
12487 	    }
12488 
12489 	    /* When the second character is NUL we can't swap. */
12490 	    if (c2 == NUL)
12491 	    {
12492 		PROF_STORE(sp->ts_state)
12493 		sp->ts_state = STATE_REP_INI;
12494 		break;
12495 	    }
12496 
12497 	    /* When characters are identical, swap won't do anything.
12498 	     * Also get here if the second char is not a word character. */
12499 	    if (c == c2)
12500 	    {
12501 		PROF_STORE(sp->ts_state)
12502 		sp->ts_state = STATE_SWAP3;
12503 		break;
12504 	    }
12505 	    if (c2 != NUL && TRY_DEEPER(su, stack, depth, SCORE_SWAP))
12506 	    {
12507 		go_deeper(stack, depth, SCORE_SWAP);
12508 #ifdef DEBUG_TRIEWALK
12509 		sprintf(changename[depth], "%.*s-%s: swap %c and %c",
12510 			sp->ts_twordlen, tword, fword + sp->ts_fidx,
12511 			c, c2);
12512 #endif
12513 		PROF_STORE(sp->ts_state)
12514 		sp->ts_state = STATE_UNSWAP;
12515 		++depth;
12516 #ifdef FEAT_MBYTE
12517 		if (has_mbyte)
12518 		{
12519 		    fl = mb_char2len(c2);
12520 		    mch_memmove(p, p + n, fl);
12521 		    mb_char2bytes(c, p + fl);
12522 		    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
12523 		}
12524 		else
12525 #endif
12526 		{
12527 		    p[0] = c2;
12528 		    p[1] = c;
12529 		    stack[depth].ts_fidxtry = sp->ts_fidx + 2;
12530 		}
12531 	    }
12532 	    else
12533 	    {
12534 		/* If this swap doesn't work then SWAP3 won't either. */
12535 		PROF_STORE(sp->ts_state)
12536 		sp->ts_state = STATE_REP_INI;
12537 	    }
12538 	    break;
12539 
12540 	case STATE_UNSWAP:
12541 	    /* Undo the STATE_SWAP swap: "21" -> "12". */
12542 	    p = fword + sp->ts_fidx;
12543 #ifdef FEAT_MBYTE
12544 	    if (has_mbyte)
12545 	    {
12546 		n = MB_BYTE2LEN(*p);
12547 		c = mb_ptr2char(p + n);
12548 		mch_memmove(p + MB_BYTE2LEN(p[n]), p, n);
12549 		mb_char2bytes(c, p);
12550 	    }
12551 	    else
12552 #endif
12553 	    {
12554 		c = *p;
12555 		*p = p[1];
12556 		p[1] = c;
12557 	    }
12558 	    /*FALLTHROUGH*/
12559 
12560 	case STATE_SWAP3:
12561 	    /* Swap two bytes, skipping one: "123" -> "321".  We change
12562 	     * "fword" here, it's changed back afterwards at STATE_UNSWAP3. */
12563 	    p = fword + sp->ts_fidx;
12564 #ifdef FEAT_MBYTE
12565 	    if (has_mbyte)
12566 	    {
12567 		n = mb_cptr2len(p);
12568 		c = mb_ptr2char(p);
12569 		fl = mb_cptr2len(p + n);
12570 		c2 = mb_ptr2char(p + n);
12571 		if (!soundfold && !spell_iswordp(p + n + fl, curwin))
12572 		    c3 = c;	/* don't swap non-word char */
12573 		else
12574 		    c3 = mb_ptr2char(p + n + fl);
12575 	    }
12576 	    else
12577 #endif
12578 	    {
12579 		c = *p;
12580 		c2 = p[1];
12581 		if (!soundfold && !spell_iswordp(p + 2, curwin))
12582 		    c3 = c;	/* don't swap non-word char */
12583 		else
12584 		    c3 = p[2];
12585 	    }
12586 
12587 	    /* When characters are identical: "121" then SWAP3 result is
12588 	     * identical, ROT3L result is same as SWAP: "211", ROT3L result is
12589 	     * same as SWAP on next char: "112".  Thus skip all swapping.
12590 	     * Also skip when c3 is NUL.
12591 	     * Also get here when the third character is not a word character.
12592 	     * Second character may any char: "a.b" -> "b.a" */
12593 	    if (c == c3 || c3 == NUL)
12594 	    {
12595 		PROF_STORE(sp->ts_state)
12596 		sp->ts_state = STATE_REP_INI;
12597 		break;
12598 	    }
12599 	    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12600 	    {
12601 		go_deeper(stack, depth, SCORE_SWAP3);
12602 #ifdef DEBUG_TRIEWALK
12603 		sprintf(changename[depth], "%.*s-%s: swap3 %c and %c",
12604 			sp->ts_twordlen, tword, fword + sp->ts_fidx,
12605 			c, c3);
12606 #endif
12607 		PROF_STORE(sp->ts_state)
12608 		sp->ts_state = STATE_UNSWAP3;
12609 		++depth;
12610 #ifdef FEAT_MBYTE
12611 		if (has_mbyte)
12612 		{
12613 		    tl = mb_char2len(c3);
12614 		    mch_memmove(p, p + n + fl, tl);
12615 		    mb_char2bytes(c2, p + tl);
12616 		    mb_char2bytes(c, p + fl + tl);
12617 		    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl + tl;
12618 		}
12619 		else
12620 #endif
12621 		{
12622 		    p[0] = p[2];
12623 		    p[2] = c;
12624 		    stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12625 		}
12626 	    }
12627 	    else
12628 	    {
12629 		PROF_STORE(sp->ts_state)
12630 		sp->ts_state = STATE_REP_INI;
12631 	    }
12632 	    break;
12633 
12634 	case STATE_UNSWAP3:
12635 	    /* Undo STATE_SWAP3: "321" -> "123" */
12636 	    p = fword + sp->ts_fidx;
12637 #ifdef FEAT_MBYTE
12638 	    if (has_mbyte)
12639 	    {
12640 		n = MB_BYTE2LEN(*p);
12641 		c2 = mb_ptr2char(p + n);
12642 		fl = MB_BYTE2LEN(p[n]);
12643 		c = mb_ptr2char(p + n + fl);
12644 		tl = MB_BYTE2LEN(p[n + fl]);
12645 		mch_memmove(p + fl + tl, p, n);
12646 		mb_char2bytes(c, p);
12647 		mb_char2bytes(c2, p + tl);
12648 		p = p + tl;
12649 	    }
12650 	    else
12651 #endif
12652 	    {
12653 		c = *p;
12654 		*p = p[2];
12655 		p[2] = c;
12656 		++p;
12657 	    }
12658 
12659 	    if (!soundfold && !spell_iswordp(p, curwin))
12660 	    {
12661 		/* Middle char is not a word char, skip the rotate.  First and
12662 		 * third char were already checked at swap and swap3. */
12663 		PROF_STORE(sp->ts_state)
12664 		sp->ts_state = STATE_REP_INI;
12665 		break;
12666 	    }
12667 
12668 	    /* Rotate three characters left: "123" -> "231".  We change
12669 	     * "fword" here, it's changed back afterwards at STATE_UNROT3L. */
12670 	    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12671 	    {
12672 		go_deeper(stack, depth, SCORE_SWAP3);
12673 #ifdef DEBUG_TRIEWALK
12674 		p = fword + sp->ts_fidx;
12675 		sprintf(changename[depth], "%.*s-%s: rotate left %c%c%c",
12676 			sp->ts_twordlen, tword, fword + sp->ts_fidx,
12677 			p[0], p[1], p[2]);
12678 #endif
12679 		PROF_STORE(sp->ts_state)
12680 		sp->ts_state = STATE_UNROT3L;
12681 		++depth;
12682 		p = fword + sp->ts_fidx;
12683 #ifdef FEAT_MBYTE
12684 		if (has_mbyte)
12685 		{
12686 		    n = mb_cptr2len(p);
12687 		    c = mb_ptr2char(p);
12688 		    fl = mb_cptr2len(p + n);
12689 		    fl += mb_cptr2len(p + n + fl);
12690 		    mch_memmove(p, p + n, fl);
12691 		    mb_char2bytes(c, p + fl);
12692 		    stack[depth].ts_fidxtry = sp->ts_fidx + n + fl;
12693 		}
12694 		else
12695 #endif
12696 		{
12697 		    c = *p;
12698 		    *p = p[1];
12699 		    p[1] = p[2];
12700 		    p[2] = c;
12701 		    stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12702 		}
12703 	    }
12704 	    else
12705 	    {
12706 		PROF_STORE(sp->ts_state)
12707 		sp->ts_state = STATE_REP_INI;
12708 	    }
12709 	    break;
12710 
12711 	case STATE_UNROT3L:
12712 	    /* Undo ROT3L: "231" -> "123" */
12713 	    p = fword + sp->ts_fidx;
12714 #ifdef FEAT_MBYTE
12715 	    if (has_mbyte)
12716 	    {
12717 		n = MB_BYTE2LEN(*p);
12718 		n += MB_BYTE2LEN(p[n]);
12719 		c = mb_ptr2char(p + n);
12720 		tl = MB_BYTE2LEN(p[n]);
12721 		mch_memmove(p + tl, p, n);
12722 		mb_char2bytes(c, p);
12723 	    }
12724 	    else
12725 #endif
12726 	    {
12727 		c = p[2];
12728 		p[2] = p[1];
12729 		p[1] = *p;
12730 		*p = c;
12731 	    }
12732 
12733 	    /* Rotate three bytes right: "123" -> "312".  We change "fword"
12734 	     * here, it's changed back afterwards at STATE_UNROT3R. */
12735 	    if (TRY_DEEPER(su, stack, depth, SCORE_SWAP3))
12736 	    {
12737 		go_deeper(stack, depth, SCORE_SWAP3);
12738 #ifdef DEBUG_TRIEWALK
12739 		p = fword + sp->ts_fidx;
12740 		sprintf(changename[depth], "%.*s-%s: rotate right %c%c%c",
12741 			sp->ts_twordlen, tword, fword + sp->ts_fidx,
12742 			p[0], p[1], p[2]);
12743 #endif
12744 		PROF_STORE(sp->ts_state)
12745 		sp->ts_state = STATE_UNROT3R;
12746 		++depth;
12747 		p = fword + sp->ts_fidx;
12748 #ifdef FEAT_MBYTE
12749 		if (has_mbyte)
12750 		{
12751 		    n = mb_cptr2len(p);
12752 		    n += mb_cptr2len(p + n);
12753 		    c = mb_ptr2char(p + n);
12754 		    tl = mb_cptr2len(p + n);
12755 		    mch_memmove(p + tl, p, n);
12756 		    mb_char2bytes(c, p);
12757 		    stack[depth].ts_fidxtry = sp->ts_fidx + n + tl;
12758 		}
12759 		else
12760 #endif
12761 		{
12762 		    c = p[2];
12763 		    p[2] = p[1];
12764 		    p[1] = *p;
12765 		    *p = c;
12766 		    stack[depth].ts_fidxtry = sp->ts_fidx + 3;
12767 		}
12768 	    }
12769 	    else
12770 	    {
12771 		PROF_STORE(sp->ts_state)
12772 		sp->ts_state = STATE_REP_INI;
12773 	    }
12774 	    break;
12775 
12776 	case STATE_UNROT3R:
12777 	    /* Undo ROT3R: "312" -> "123" */
12778 	    p = fword + sp->ts_fidx;
12779 #ifdef FEAT_MBYTE
12780 	    if (has_mbyte)
12781 	    {
12782 		c = mb_ptr2char(p);
12783 		tl = MB_BYTE2LEN(*p);
12784 		n = MB_BYTE2LEN(p[tl]);
12785 		n += MB_BYTE2LEN(p[tl + n]);
12786 		mch_memmove(p, p + tl, n);
12787 		mb_char2bytes(c, p + n);
12788 	    }
12789 	    else
12790 #endif
12791 	    {
12792 		c = *p;
12793 		*p = p[1];
12794 		p[1] = p[2];
12795 		p[2] = c;
12796 	    }
12797 	    /*FALLTHROUGH*/
12798 
12799 	case STATE_REP_INI:
12800 	    /* Check if matching with REP items from the .aff file would work.
12801 	     * Quickly skip if:
12802 	     * - there are no REP items and we are not in the soundfold trie
12803 	     * - the score is going to be too high anyway
12804 	     * - already applied a REP item or swapped here  */
12805 	    if ((lp->lp_replang == NULL && !soundfold)
12806 		    || sp->ts_score + SCORE_REP >= su->su_maxscore
12807 		    || sp->ts_fidx < sp->ts_fidxtry)
12808 	    {
12809 		PROF_STORE(sp->ts_state)
12810 		sp->ts_state = STATE_FINAL;
12811 		break;
12812 	    }
12813 
12814 	    /* Use the first byte to quickly find the first entry that may
12815 	     * match.  If the index is -1 there is none. */
12816 	    if (soundfold)
12817 		sp->ts_curi = slang->sl_repsal_first[fword[sp->ts_fidx]];
12818 	    else
12819 		sp->ts_curi = lp->lp_replang->sl_rep_first[fword[sp->ts_fidx]];
12820 
12821 	    if (sp->ts_curi < 0)
12822 	    {
12823 		PROF_STORE(sp->ts_state)
12824 		sp->ts_state = STATE_FINAL;
12825 		break;
12826 	    }
12827 
12828 	    PROF_STORE(sp->ts_state)
12829 	    sp->ts_state = STATE_REP;
12830 	    /*FALLTHROUGH*/
12831 
12832 	case STATE_REP:
12833 	    /* Try matching with REP items from the .aff file.  For each match
12834 	     * replace the characters and check if the resulting word is
12835 	     * valid. */
12836 	    p = fword + sp->ts_fidx;
12837 
12838 	    if (soundfold)
12839 		gap = &slang->sl_repsal;
12840 	    else
12841 		gap = &lp->lp_replang->sl_rep;
12842 	    while (sp->ts_curi < gap->ga_len)
12843 	    {
12844 		ftp = (fromto_T *)gap->ga_data + sp->ts_curi++;
12845 		if (*ftp->ft_from != *p)
12846 		{
12847 		    /* past possible matching entries */
12848 		    sp->ts_curi = gap->ga_len;
12849 		    break;
12850 		}
12851 		if (STRNCMP(ftp->ft_from, p, STRLEN(ftp->ft_from)) == 0
12852 			&& TRY_DEEPER(su, stack, depth, SCORE_REP))
12853 		{
12854 		    go_deeper(stack, depth, SCORE_REP);
12855 #ifdef DEBUG_TRIEWALK
12856 		    sprintf(changename[depth], "%.*s-%s: replace %s with %s",
12857 			    sp->ts_twordlen, tword, fword + sp->ts_fidx,
12858 			    ftp->ft_from, ftp->ft_to);
12859 #endif
12860 		    /* Need to undo this afterwards. */
12861 		    PROF_STORE(sp->ts_state)
12862 		    sp->ts_state = STATE_REP_UNDO;
12863 
12864 		    /* Change the "from" to the "to" string. */
12865 		    ++depth;
12866 		    fl = (int)STRLEN(ftp->ft_from);
12867 		    tl = (int)STRLEN(ftp->ft_to);
12868 		    if (fl != tl)
12869 		    {
12870 			STRMOVE(p + tl, p + fl);
12871 			repextra += tl - fl;
12872 		    }
12873 		    mch_memmove(p, ftp->ft_to, tl);
12874 		    stack[depth].ts_fidxtry = sp->ts_fidx + tl;
12875 #ifdef FEAT_MBYTE
12876 		    stack[depth].ts_tcharlen = 0;
12877 #endif
12878 		    break;
12879 		}
12880 	    }
12881 
12882 	    if (sp->ts_curi >= gap->ga_len && sp->ts_state == STATE_REP)
12883 	    {
12884 		/* No (more) matches. */
12885 		PROF_STORE(sp->ts_state)
12886 		sp->ts_state = STATE_FINAL;
12887 	    }
12888 
12889 	    break;
12890 
12891 	case STATE_REP_UNDO:
12892 	    /* Undo a REP replacement and continue with the next one. */
12893 	    if (soundfold)
12894 		gap = &slang->sl_repsal;
12895 	    else
12896 		gap = &lp->lp_replang->sl_rep;
12897 	    ftp = (fromto_T *)gap->ga_data + sp->ts_curi - 1;
12898 	    fl = (int)STRLEN(ftp->ft_from);
12899 	    tl = (int)STRLEN(ftp->ft_to);
12900 	    p = fword + sp->ts_fidx;
12901 	    if (fl != tl)
12902 	    {
12903 		STRMOVE(p + fl, p + tl);
12904 		repextra -= tl - fl;
12905 	    }
12906 	    mch_memmove(p, ftp->ft_from, fl);
12907 	    PROF_STORE(sp->ts_state)
12908 	    sp->ts_state = STATE_REP;
12909 	    break;
12910 
12911 	default:
12912 	    /* Did all possible states at this level, go up one level. */
12913 	    --depth;
12914 
12915 	    if (depth >= 0 && stack[depth].ts_prefixdepth == PFD_PREFIXTREE)
12916 	    {
12917 		/* Continue in or go back to the prefix tree. */
12918 		byts = pbyts;
12919 		idxs = pidxs;
12920 	    }
12921 
12922 	    /* Don't check for CTRL-C too often, it takes time. */
12923 	    if (--breakcheckcount == 0)
12924 	    {
12925 		ui_breakcheck();
12926 		breakcheckcount = 1000;
12927 	    }
12928 	}
12929     }
12930 }
12931 
12932 
12933 /*
12934  * Go one level deeper in the tree.
12935  */
12936     static void
12937 go_deeper(stack, depth, score_add)
12938     trystate_T	*stack;
12939     int		depth;
12940     int		score_add;
12941 {
12942     stack[depth + 1] = stack[depth];
12943     stack[depth + 1].ts_state = STATE_START;
12944     stack[depth + 1].ts_score = stack[depth].ts_score + score_add;
12945     stack[depth + 1].ts_curi = 1;	/* start just after length byte */
12946     stack[depth + 1].ts_flags = 0;
12947 }
12948 
12949 #ifdef FEAT_MBYTE
12950 /*
12951  * Case-folding may change the number of bytes: Count nr of chars in
12952  * fword[flen] and return the byte length of that many chars in "word".
12953  */
12954     static int
12955 nofold_len(fword, flen, word)
12956     char_u	*fword;
12957     int		flen;
12958     char_u	*word;
12959 {
12960     char_u	*p;
12961     int		i = 0;
12962 
12963     for (p = fword; p < fword + flen; mb_ptr_adv(p))
12964 	++i;
12965     for (p = word; i > 0; mb_ptr_adv(p))
12966 	--i;
12967     return (int)(p - word);
12968 }
12969 #endif
12970 
12971 /*
12972  * "fword" is a good word with case folded.  Find the matching keep-case
12973  * words and put it in "kword".
12974  * Theoretically there could be several keep-case words that result in the
12975  * same case-folded word, but we only find one...
12976  */
12977     static void
12978 find_keepcap_word(slang, fword, kword)
12979     slang_T	*slang;
12980     char_u	*fword;
12981     char_u	*kword;
12982 {
12983     char_u	uword[MAXWLEN];		/* "fword" in upper-case */
12984     int		depth;
12985     idx_T	tryidx;
12986 
12987     /* The following arrays are used at each depth in the tree. */
12988     idx_T	arridx[MAXWLEN];
12989     int		round[MAXWLEN];
12990     int		fwordidx[MAXWLEN];
12991     int		uwordidx[MAXWLEN];
12992     int		kwordlen[MAXWLEN];
12993 
12994     int		flen, ulen;
12995     int		l;
12996     int		len;
12997     int		c;
12998     idx_T	lo, hi, m;
12999     char_u	*p;
13000     char_u	*byts = slang->sl_kbyts;    /* array with bytes of the words */
13001     idx_T	*idxs = slang->sl_kidxs;    /* array with indexes */
13002 
13003     if (byts == NULL)
13004     {
13005 	/* array is empty: "cannot happen" */
13006 	*kword = NUL;
13007 	return;
13008     }
13009 
13010     /* Make an all-cap version of "fword". */
13011     allcap_copy(fword, uword);
13012 
13013     /*
13014      * Each character needs to be tried both case-folded and upper-case.
13015      * All this gets very complicated if we keep in mind that changing case
13016      * may change the byte length of a multi-byte character...
13017      */
13018     depth = 0;
13019     arridx[0] = 0;
13020     round[0] = 0;
13021     fwordidx[0] = 0;
13022     uwordidx[0] = 0;
13023     kwordlen[0] = 0;
13024     while (depth >= 0)
13025     {
13026 	if (fword[fwordidx[depth]] == NUL)
13027 	{
13028 	    /* We are at the end of "fword".  If the tree allows a word to end
13029 	     * here we have found a match. */
13030 	    if (byts[arridx[depth] + 1] == 0)
13031 	    {
13032 		kword[kwordlen[depth]] = NUL;
13033 		return;
13034 	    }
13035 
13036 	    /* kword is getting too long, continue one level up */
13037 	    --depth;
13038 	}
13039 	else if (++round[depth] > 2)
13040 	{
13041 	    /* tried both fold-case and upper-case character, continue one
13042 	     * level up */
13043 	    --depth;
13044 	}
13045 	else
13046 	{
13047 	    /*
13048 	     * round[depth] == 1: Try using the folded-case character.
13049 	     * round[depth] == 2: Try using the upper-case character.
13050 	     */
13051 #ifdef FEAT_MBYTE
13052 	    if (has_mbyte)
13053 	    {
13054 		flen = mb_cptr2len(fword + fwordidx[depth]);
13055 		ulen = mb_cptr2len(uword + uwordidx[depth]);
13056 	    }
13057 	    else
13058 #endif
13059 		ulen = flen = 1;
13060 	    if (round[depth] == 1)
13061 	    {
13062 		p = fword + fwordidx[depth];
13063 		l = flen;
13064 	    }
13065 	    else
13066 	    {
13067 		p = uword + uwordidx[depth];
13068 		l = ulen;
13069 	    }
13070 
13071 	    for (tryidx = arridx[depth]; l > 0; --l)
13072 	    {
13073 		/* Perform a binary search in the list of accepted bytes. */
13074 		len = byts[tryidx++];
13075 		c = *p++;
13076 		lo = tryidx;
13077 		hi = tryidx + len - 1;
13078 		while (lo < hi)
13079 		{
13080 		    m = (lo + hi) / 2;
13081 		    if (byts[m] > c)
13082 			hi = m - 1;
13083 		    else if (byts[m] < c)
13084 			lo = m + 1;
13085 		    else
13086 		    {
13087 			lo = hi = m;
13088 			break;
13089 		    }
13090 		}
13091 
13092 		/* Stop if there is no matching byte. */
13093 		if (hi < lo || byts[lo] != c)
13094 		    break;
13095 
13096 		/* Continue at the child (if there is one). */
13097 		tryidx = idxs[lo];
13098 	    }
13099 
13100 	    if (l == 0)
13101 	    {
13102 		/*
13103 		 * Found the matching char.  Copy it to "kword" and go a
13104 		 * level deeper.
13105 		 */
13106 		if (round[depth] == 1)
13107 		{
13108 		    STRNCPY(kword + kwordlen[depth], fword + fwordidx[depth],
13109 									flen);
13110 		    kwordlen[depth + 1] = kwordlen[depth] + flen;
13111 		}
13112 		else
13113 		{
13114 		    STRNCPY(kword + kwordlen[depth], uword + uwordidx[depth],
13115 									ulen);
13116 		    kwordlen[depth + 1] = kwordlen[depth] + ulen;
13117 		}
13118 		fwordidx[depth + 1] = fwordidx[depth] + flen;
13119 		uwordidx[depth + 1] = uwordidx[depth] + ulen;
13120 
13121 		++depth;
13122 		arridx[depth] = tryidx;
13123 		round[depth] = 0;
13124 	    }
13125 	}
13126     }
13127 
13128     /* Didn't find it: "cannot happen". */
13129     *kword = NUL;
13130 }
13131 
13132 /*
13133  * Compute the sound-a-like score for suggestions in su->su_ga and add them to
13134  * su->su_sga.
13135  */
13136     static void
13137 score_comp_sal(su)
13138     suginfo_T	*su;
13139 {
13140     langp_T	*lp;
13141     char_u	badsound[MAXWLEN];
13142     int		i;
13143     suggest_T   *stp;
13144     suggest_T   *sstp;
13145     int		score;
13146     int		lpi;
13147 
13148     if (ga_grow(&su->su_sga, su->su_ga.ga_len) == FAIL)
13149 	return;
13150 
13151     /*	Use the sound-folding of the first language that supports it. */
13152     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
13153     {
13154 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
13155 	if (lp->lp_slang->sl_sal.ga_len > 0)
13156 	{
13157 	    /* soundfold the bad word */
13158 	    spell_soundfold(lp->lp_slang, su->su_fbadword, TRUE, badsound);
13159 
13160 	    for (i = 0; i < su->su_ga.ga_len; ++i)
13161 	    {
13162 		stp = &SUG(su->su_ga, i);
13163 
13164 		/* Case-fold the suggested word, sound-fold it and compute the
13165 		 * sound-a-like score. */
13166 		score = stp_sal_score(stp, su, lp->lp_slang, badsound);
13167 		if (score < SCORE_MAXMAX)
13168 		{
13169 		    /* Add the suggestion. */
13170 		    sstp = &SUG(su->su_sga, su->su_sga.ga_len);
13171 		    sstp->st_word = vim_strsave(stp->st_word);
13172 		    if (sstp->st_word != NULL)
13173 		    {
13174 			sstp->st_wordlen = stp->st_wordlen;
13175 			sstp->st_score = score;
13176 			sstp->st_altscore = 0;
13177 			sstp->st_orglen = stp->st_orglen;
13178 			++su->su_sga.ga_len;
13179 		    }
13180 		}
13181 	    }
13182 	    break;
13183 	}
13184     }
13185 }
13186 
13187 /*
13188  * Combine the list of suggestions in su->su_ga and su->su_sga.
13189  * They are entwined.
13190  */
13191     static void
13192 score_combine(su)
13193     suginfo_T	*su;
13194 {
13195     int		i;
13196     int		j;
13197     garray_T	ga;
13198     garray_T	*gap;
13199     langp_T	*lp;
13200     suggest_T	*stp;
13201     char_u	*p;
13202     char_u	badsound[MAXWLEN];
13203     int		round;
13204     int		lpi;
13205     slang_T	*slang = NULL;
13206 
13207     /* Add the alternate score to su_ga. */
13208     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
13209     {
13210 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
13211 	if (lp->lp_slang->sl_sal.ga_len > 0)
13212 	{
13213 	    /* soundfold the bad word */
13214 	    slang = lp->lp_slang;
13215 	    spell_soundfold(slang, su->su_fbadword, TRUE, badsound);
13216 
13217 	    for (i = 0; i < su->su_ga.ga_len; ++i)
13218 	    {
13219 		stp = &SUG(su->su_ga, i);
13220 		stp->st_altscore = stp_sal_score(stp, su, slang, badsound);
13221 		if (stp->st_altscore == SCORE_MAXMAX)
13222 		    stp->st_score = (stp->st_score * 3 + SCORE_BIG) / 4;
13223 		else
13224 		    stp->st_score = (stp->st_score * 3
13225 						  + stp->st_altscore) / 4;
13226 		stp->st_salscore = FALSE;
13227 	    }
13228 	    break;
13229 	}
13230     }
13231 
13232     if (slang == NULL)	/* Using "double" without sound folding. */
13233     {
13234 	(void)cleanup_suggestions(&su->su_ga, su->su_maxscore,
13235 							     su->su_maxcount);
13236 	return;
13237     }
13238 
13239     /* Add the alternate score to su_sga. */
13240     for (i = 0; i < su->su_sga.ga_len; ++i)
13241     {
13242 	stp = &SUG(su->su_sga, i);
13243 	stp->st_altscore = spell_edit_score(slang,
13244 						su->su_badword, stp->st_word);
13245 	if (stp->st_score == SCORE_MAXMAX)
13246 	    stp->st_score = (SCORE_BIG * 7 + stp->st_altscore) / 8;
13247 	else
13248 	    stp->st_score = (stp->st_score * 7 + stp->st_altscore) / 8;
13249 	stp->st_salscore = TRUE;
13250     }
13251 
13252     /* Remove bad suggestions, sort the suggestions and truncate at "maxcount"
13253      * for both lists. */
13254     check_suggestions(su, &su->su_ga);
13255     (void)cleanup_suggestions(&su->su_ga, su->su_maxscore, su->su_maxcount);
13256     check_suggestions(su, &su->su_sga);
13257     (void)cleanup_suggestions(&su->su_sga, su->su_maxscore, su->su_maxcount);
13258 
13259     ga_init2(&ga, (int)sizeof(suginfo_T), 1);
13260     if (ga_grow(&ga, su->su_ga.ga_len + su->su_sga.ga_len) == FAIL)
13261 	return;
13262 
13263     stp = &SUG(ga, 0);
13264     for (i = 0; i < su->su_ga.ga_len || i < su->su_sga.ga_len; ++i)
13265     {
13266 	/* round 1: get a suggestion from su_ga
13267 	 * round 2: get a suggestion from su_sga */
13268 	for (round = 1; round <= 2; ++round)
13269 	{
13270 	    gap = round == 1 ? &su->su_ga : &su->su_sga;
13271 	    if (i < gap->ga_len)
13272 	    {
13273 		/* Don't add a word if it's already there. */
13274 		p = SUG(*gap, i).st_word;
13275 		for (j = 0; j < ga.ga_len; ++j)
13276 		    if (STRCMP(stp[j].st_word, p) == 0)
13277 			break;
13278 		if (j == ga.ga_len)
13279 		    stp[ga.ga_len++] = SUG(*gap, i);
13280 		else
13281 		    vim_free(p);
13282 	    }
13283 	}
13284     }
13285 
13286     ga_clear(&su->su_ga);
13287     ga_clear(&su->su_sga);
13288 
13289     /* Truncate the list to the number of suggestions that will be displayed. */
13290     if (ga.ga_len > su->su_maxcount)
13291     {
13292 	for (i = su->su_maxcount; i < ga.ga_len; ++i)
13293 	    vim_free(stp[i].st_word);
13294 	ga.ga_len = su->su_maxcount;
13295     }
13296 
13297     su->su_ga = ga;
13298 }
13299 
13300 /*
13301  * For the goodword in "stp" compute the soundalike score compared to the
13302  * badword.
13303  */
13304     static int
13305 stp_sal_score(stp, su, slang, badsound)
13306     suggest_T	*stp;
13307     suginfo_T	*su;
13308     slang_T	*slang;
13309     char_u	*badsound;	/* sound-folded badword */
13310 {
13311     char_u	*p;
13312     char_u	*pbad;
13313     char_u	*pgood;
13314     char_u	badsound2[MAXWLEN];
13315     char_u	fword[MAXWLEN];
13316     char_u	goodsound[MAXWLEN];
13317     char_u	goodword[MAXWLEN];
13318     int		lendiff;
13319 
13320     lendiff = (int)(su->su_badlen - stp->st_orglen);
13321     if (lendiff >= 0)
13322 	pbad = badsound;
13323     else
13324     {
13325 	/* soundfold the bad word with more characters following */
13326 	(void)spell_casefold(su->su_badptr, stp->st_orglen, fword, MAXWLEN);
13327 
13328 	/* When joining two words the sound often changes a lot.  E.g., "t he"
13329 	 * sounds like "t h" while "the" sounds like "@".  Avoid that by
13330 	 * removing the space.  Don't do it when the good word also contains a
13331 	 * space. */
13332 	if (vim_iswhite(su->su_badptr[su->su_badlen])
13333 					 && *skiptowhite(stp->st_word) == NUL)
13334 	    for (p = fword; *(p = skiptowhite(p)) != NUL; )
13335 		STRMOVE(p, p + 1);
13336 
13337 	spell_soundfold(slang, fword, TRUE, badsound2);
13338 	pbad = badsound2;
13339     }
13340 
13341     if (lendiff > 0 && stp->st_wordlen + lendiff < MAXWLEN)
13342     {
13343 	/* Add part of the bad word to the good word, so that we soundfold
13344 	 * what replaces the bad word. */
13345 	STRCPY(goodword, stp->st_word);
13346 	vim_strncpy(goodword + stp->st_wordlen,
13347 			    su->su_badptr + su->su_badlen - lendiff, lendiff);
13348 	pgood = goodword;
13349     }
13350     else
13351 	pgood = stp->st_word;
13352 
13353     /* Sound-fold the word and compute the score for the difference. */
13354     spell_soundfold(slang, pgood, FALSE, goodsound);
13355 
13356     return soundalike_score(goodsound, pbad);
13357 }
13358 
13359 /* structure used to store soundfolded words that add_sound_suggest() has
13360  * handled already. */
13361 typedef struct
13362 {
13363     short	sft_score;	/* lowest score used */
13364     char_u	sft_word[1];    /* soundfolded word, actually longer */
13365 } sftword_T;
13366 
13367 static sftword_T dumsft;
13368 #define HIKEY2SFT(p)  ((sftword_T *)(p - (dumsft.sft_word - (char_u *)&dumsft)))
13369 #define HI2SFT(hi)     HIKEY2SFT((hi)->hi_key)
13370 
13371 /*
13372  * Prepare for calling suggest_try_soundalike().
13373  */
13374     static void
13375 suggest_try_soundalike_prep()
13376 {
13377     langp_T	*lp;
13378     int		lpi;
13379     slang_T	*slang;
13380 
13381     /* Do this for all languages that support sound folding and for which a
13382      * .sug file has been loaded. */
13383     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
13384     {
13385 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
13386 	slang = lp->lp_slang;
13387 	if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13388 	    /* prepare the hashtable used by add_sound_suggest() */
13389 	    hash_init(&slang->sl_sounddone);
13390     }
13391 }
13392 
13393 /*
13394  * Find suggestions by comparing the word in a sound-a-like form.
13395  * Note: This doesn't support postponed prefixes.
13396  */
13397     static void
13398 suggest_try_soundalike(su)
13399     suginfo_T	*su;
13400 {
13401     char_u	salword[MAXWLEN];
13402     langp_T	*lp;
13403     int		lpi;
13404     slang_T	*slang;
13405 
13406     /* Do this for all languages that support sound folding and for which a
13407      * .sug file has been loaded. */
13408     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
13409     {
13410 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
13411 	slang = lp->lp_slang;
13412 	if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13413 	{
13414 	    /* soundfold the bad word */
13415 	    spell_soundfold(slang, su->su_fbadword, TRUE, salword);
13416 
13417 	    /* try all kinds of inserts/deletes/swaps/etc. */
13418 	    /* TODO: also soundfold the next words, so that we can try joining
13419 	     * and splitting */
13420 #ifdef SUGGEST_PROFILE
13421 	prof_init();
13422 #endif
13423 	    suggest_trie_walk(su, lp, salword, TRUE);
13424 #ifdef SUGGEST_PROFILE
13425 	prof_report("soundalike");
13426 #endif
13427 	}
13428     }
13429 }
13430 
13431 /*
13432  * Finish up after calling suggest_try_soundalike().
13433  */
13434     static void
13435 suggest_try_soundalike_finish()
13436 {
13437     langp_T	*lp;
13438     int		lpi;
13439     slang_T	*slang;
13440     int		todo;
13441     hashitem_T	*hi;
13442 
13443     /* Do this for all languages that support sound folding and for which a
13444      * .sug file has been loaded. */
13445     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
13446     {
13447 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
13448 	slang = lp->lp_slang;
13449 	if (slang->sl_sal.ga_len > 0 && slang->sl_sbyts != NULL)
13450 	{
13451 	    /* Free the info about handled words. */
13452 	    todo = (int)slang->sl_sounddone.ht_used;
13453 	    for (hi = slang->sl_sounddone.ht_array; todo > 0; ++hi)
13454 		if (!HASHITEM_EMPTY(hi))
13455 		{
13456 		    vim_free(HI2SFT(hi));
13457 		    --todo;
13458 		}
13459 
13460 	    /* Clear the hashtable, it may also be used by another region. */
13461 	    hash_clear(&slang->sl_sounddone);
13462 	    hash_init(&slang->sl_sounddone);
13463 	}
13464     }
13465 }
13466 
13467 /*
13468  * A match with a soundfolded word is found.  Add the good word(s) that
13469  * produce this soundfolded word.
13470  */
13471     static void
13472 add_sound_suggest(su, goodword, score, lp)
13473     suginfo_T	*su;
13474     char_u	*goodword;
13475     int		score;		/* soundfold score  */
13476     langp_T	*lp;
13477 {
13478     slang_T	*slang = lp->lp_slang;	/* language for sound folding */
13479     int		sfwordnr;
13480     char_u	*nrline;
13481     int		orgnr;
13482     char_u	theword[MAXWLEN];
13483     int		i;
13484     int		wlen;
13485     char_u	*byts;
13486     idx_T	*idxs;
13487     int		n;
13488     int		wordcount;
13489     int		wc;
13490     int		goodscore;
13491     hash_T	hash;
13492     hashitem_T  *hi;
13493     sftword_T	*sft;
13494     int		bc, gc;
13495     int		limit;
13496 
13497     /*
13498      * It's very well possible that the same soundfold word is found several
13499      * times with different scores.  Since the following is quite slow only do
13500      * the words that have a better score than before.  Use a hashtable to
13501      * remember the words that have been done.
13502      */
13503     hash = hash_hash(goodword);
13504     hi = hash_lookup(&slang->sl_sounddone, goodword, hash);
13505     if (HASHITEM_EMPTY(hi))
13506     {
13507 	sft = (sftword_T *)alloc((unsigned)(sizeof(sftword_T)
13508 							 + STRLEN(goodword)));
13509 	if (sft != NULL)
13510 	{
13511 	    sft->sft_score = score;
13512 	    STRCPY(sft->sft_word, goodword);
13513 	    hash_add_item(&slang->sl_sounddone, hi, sft->sft_word, hash);
13514 	}
13515     }
13516     else
13517     {
13518 	sft = HI2SFT(hi);
13519 	if (score >= sft->sft_score)
13520 	    return;
13521 	sft->sft_score = score;
13522     }
13523 
13524     /*
13525      * Find the word nr in the soundfold tree.
13526      */
13527     sfwordnr = soundfold_find(slang, goodword);
13528     if (sfwordnr < 0)
13529     {
13530 	EMSG2(_(e_intern2), "add_sound_suggest()");
13531 	return;
13532     }
13533 
13534     /*
13535      * go over the list of good words that produce this soundfold word
13536      */
13537     nrline = ml_get_buf(slang->sl_sugbuf, (linenr_T)(sfwordnr + 1), FALSE);
13538     orgnr = 0;
13539     while (*nrline != NUL)
13540     {
13541 	/* The wordnr was stored in a minimal nr of bytes as an offset to the
13542 	 * previous wordnr. */
13543 	orgnr += bytes2offset(&nrline);
13544 
13545 	byts = slang->sl_fbyts;
13546 	idxs = slang->sl_fidxs;
13547 
13548 	/* Lookup the word "orgnr" one of the two tries. */
13549 	n = 0;
13550 	wordcount = 0;
13551 	for (wlen = 0; wlen < MAXWLEN - 3; ++wlen)
13552 	{
13553 	    i = 1;
13554 	    if (wordcount == orgnr && byts[n + 1] == NUL)
13555 		break;	/* found end of word */
13556 
13557 	    if (byts[n + 1] == NUL)
13558 		++wordcount;
13559 
13560 	    /* skip over the NUL bytes */
13561 	    for ( ; byts[n + i] == NUL; ++i)
13562 		if (i > byts[n])	/* safety check */
13563 		{
13564 		    STRCPY(theword + wlen, "BAD");
13565 		    wlen += 3;
13566 		    goto badword;
13567 		}
13568 
13569 	    /* One of the siblings must have the word. */
13570 	    for ( ; i < byts[n]; ++i)
13571 	    {
13572 		wc = idxs[idxs[n + i]];	/* nr of words under this byte */
13573 		if (wordcount + wc > orgnr)
13574 		    break;
13575 		wordcount += wc;
13576 	    }
13577 
13578 	    theword[wlen] = byts[n + i];
13579 	    n = idxs[n + i];
13580 	}
13581 badword:
13582 	theword[wlen] = NUL;
13583 
13584 	/* Go over the possible flags and regions. */
13585 	for (; i <= byts[n] && byts[n + i] == NUL; ++i)
13586 	{
13587 	    char_u	cword[MAXWLEN];
13588 	    char_u	*p;
13589 	    int		flags = (int)idxs[n + i];
13590 
13591 	    /* Skip words with the NOSUGGEST flag */
13592 	    if (flags & WF_NOSUGGEST)
13593 		continue;
13594 
13595 	    if (flags & WF_KEEPCAP)
13596 	    {
13597 		/* Must find the word in the keep-case tree. */
13598 		find_keepcap_word(slang, theword, cword);
13599 		p = cword;
13600 	    }
13601 	    else
13602 	    {
13603 		flags |= su->su_badflags;
13604 		if ((flags & WF_CAPMASK) != 0)
13605 		{
13606 		    /* Need to fix case according to "flags". */
13607 		    make_case_word(theword, cword, flags);
13608 		    p = cword;
13609 		}
13610 		else
13611 		    p = theword;
13612 	    }
13613 
13614 	    /* Add the suggestion. */
13615 	    if (sps_flags & SPS_DOUBLE)
13616 	    {
13617 		/* Add the suggestion if the score isn't too bad. */
13618 		if (score <= su->su_maxscore)
13619 		    add_suggestion(su, &su->su_sga, p, su->su_badlen,
13620 					       score, 0, FALSE, slang, FALSE);
13621 	    }
13622 	    else
13623 	    {
13624 		/* Add a penalty for words in another region. */
13625 		if ((flags & WF_REGION)
13626 			    && (((unsigned)flags >> 16) & lp->lp_region) == 0)
13627 		    goodscore = SCORE_REGION;
13628 		else
13629 		    goodscore = 0;
13630 
13631 		/* Add a small penalty for changing the first letter from
13632 		 * lower to upper case.  Helps for "tath" -> "Kath", which is
13633 		 * less common than "tath" -> "path".  Don't do it when the
13634 		 * letter is the same, that has already been counted. */
13635 		gc = PTR2CHAR(p);
13636 		if (SPELL_ISUPPER(gc))
13637 		{
13638 		    bc = PTR2CHAR(su->su_badword);
13639 		    if (!SPELL_ISUPPER(bc)
13640 				      && SPELL_TOFOLD(bc) != SPELL_TOFOLD(gc))
13641 			goodscore += SCORE_ICASE / 2;
13642 		}
13643 
13644 		/* Compute the score for the good word.  This only does letter
13645 		 * insert/delete/swap/replace.  REP items are not considered,
13646 		 * which may make the score a bit higher.
13647 		 * Use a limit for the score to make it work faster.  Use
13648 		 * MAXSCORE(), because RESCORE() will change the score.
13649 		 * If the limit is very high then the iterative method is
13650 		 * inefficient, using an array is quicker. */
13651 		limit = MAXSCORE(su->su_sfmaxscore - goodscore, score);
13652 		if (limit > SCORE_LIMITMAX)
13653 		    goodscore += spell_edit_score(slang, su->su_badword, p);
13654 		else
13655 		    goodscore += spell_edit_score_limit(slang, su->su_badword,
13656 								    p, limit);
13657 
13658 		/* When going over the limit don't bother to do the rest. */
13659 		if (goodscore < SCORE_MAXMAX)
13660 		{
13661 		    /* Give a bonus to words seen before. */
13662 		    goodscore = score_wordcount_adj(slang, goodscore, p, FALSE);
13663 
13664 		    /* Add the suggestion if the score isn't too bad. */
13665 		    goodscore = RESCORE(goodscore, score);
13666 		    if (goodscore <= su->su_sfmaxscore)
13667 			add_suggestion(su, &su->su_ga, p, su->su_badlen,
13668 					 goodscore, score, TRUE, slang, TRUE);
13669 		}
13670 	    }
13671 	}
13672 	/* smsg("word %s (%d): %s (%d)", sftword, sftnr, theword, orgnr); */
13673     }
13674 }
13675 
13676 /*
13677  * Find word "word" in fold-case tree for "slang" and return the word number.
13678  */
13679     static int
13680 soundfold_find(slang, word)
13681     slang_T	*slang;
13682     char_u	*word;
13683 {
13684     idx_T	arridx = 0;
13685     int		len;
13686     int		wlen = 0;
13687     int		c;
13688     char_u	*ptr = word;
13689     char_u	*byts;
13690     idx_T	*idxs;
13691     int		wordnr = 0;
13692 
13693     byts = slang->sl_sbyts;
13694     idxs = slang->sl_sidxs;
13695 
13696     for (;;)
13697     {
13698 	/* First byte is the number of possible bytes. */
13699 	len = byts[arridx++];
13700 
13701 	/* If the first possible byte is a zero the word could end here.
13702 	 * If the word ends we found the word.  If not skip the NUL bytes. */
13703 	c = ptr[wlen];
13704 	if (byts[arridx] == NUL)
13705 	{
13706 	    if (c == NUL)
13707 		break;
13708 
13709 	    /* Skip over the zeros, there can be several. */
13710 	    while (len > 0 && byts[arridx] == NUL)
13711 	    {
13712 		++arridx;
13713 		--len;
13714 	    }
13715 	    if (len == 0)
13716 		return -1;    /* no children, word should have ended here */
13717 	    ++wordnr;
13718 	}
13719 
13720 	/* If the word ends we didn't find it. */
13721 	if (c == NUL)
13722 	    return -1;
13723 
13724 	/* Perform a binary search in the list of accepted bytes. */
13725 	if (c == TAB)	    /* <Tab> is handled like <Space> */
13726 	    c = ' ';
13727 	while (byts[arridx] < c)
13728 	{
13729 	    /* The word count is in the first idxs[] entry of the child. */
13730 	    wordnr += idxs[idxs[arridx]];
13731 	    ++arridx;
13732 	    if (--len == 0)	/* end of the bytes, didn't find it */
13733 		return -1;
13734 	}
13735 	if (byts[arridx] != c)	/* didn't find the byte */
13736 	    return -1;
13737 
13738 	/* Continue at the child (if there is one). */
13739 	arridx = idxs[arridx];
13740 	++wlen;
13741 
13742 	/* One space in the good word may stand for several spaces in the
13743 	 * checked word. */
13744 	if (c == ' ')
13745 	    while (ptr[wlen] == ' ' || ptr[wlen] == TAB)
13746 		++wlen;
13747     }
13748 
13749     return wordnr;
13750 }
13751 
13752 /*
13753  * Copy "fword" to "cword", fixing case according to "flags".
13754  */
13755     static void
13756 make_case_word(fword, cword, flags)
13757     char_u	*fword;
13758     char_u	*cword;
13759     int		flags;
13760 {
13761     if (flags & WF_ALLCAP)
13762 	/* Make it all upper-case */
13763 	allcap_copy(fword, cword);
13764     else if (flags & WF_ONECAP)
13765 	/* Make the first letter upper-case */
13766 	onecap_copy(fword, cword, TRUE);
13767     else
13768 	/* Use goodword as-is. */
13769 	STRCPY(cword, fword);
13770 }
13771 
13772 /*
13773  * Use map string "map" for languages "lp".
13774  */
13775     static void
13776 set_map_str(lp, map)
13777     slang_T	*lp;
13778     char_u	*map;
13779 {
13780     char_u	*p;
13781     int		headc = 0;
13782     int		c;
13783     int		i;
13784 
13785     if (*map == NUL)
13786     {
13787 	lp->sl_has_map = FALSE;
13788 	return;
13789     }
13790     lp->sl_has_map = TRUE;
13791 
13792     /* Init the array and hash tables empty. */
13793     for (i = 0; i < 256; ++i)
13794 	lp->sl_map_array[i] = 0;
13795 #ifdef FEAT_MBYTE
13796     hash_init(&lp->sl_map_hash);
13797 #endif
13798 
13799     /*
13800      * The similar characters are stored separated with slashes:
13801      * "aaa/bbb/ccc/".  Fill sl_map_array[c] with the character before c and
13802      * before the same slash.  For characters above 255 sl_map_hash is used.
13803      */
13804     for (p = map; *p != NUL; )
13805     {
13806 #ifdef FEAT_MBYTE
13807 	c = mb_cptr2char_adv(&p);
13808 #else
13809 	c = *p++;
13810 #endif
13811 	if (c == '/')
13812 	    headc = 0;
13813 	else
13814 	{
13815 	    if (headc == 0)
13816 		 headc = c;
13817 
13818 #ifdef FEAT_MBYTE
13819 	    /* Characters above 255 don't fit in sl_map_array[], put them in
13820 	     * the hash table.  Each entry is the char, a NUL the headchar and
13821 	     * a NUL. */
13822 	    if (c >= 256)
13823 	    {
13824 		int	    cl = mb_char2len(c);
13825 		int	    headcl = mb_char2len(headc);
13826 		char_u	    *b;
13827 		hash_T	    hash;
13828 		hashitem_T  *hi;
13829 
13830 		b = alloc((unsigned)(cl + headcl + 2));
13831 		if (b == NULL)
13832 		    return;
13833 		mb_char2bytes(c, b);
13834 		b[cl] = NUL;
13835 		mb_char2bytes(headc, b + cl + 1);
13836 		b[cl + 1 + headcl] = NUL;
13837 		hash = hash_hash(b);
13838 		hi = hash_lookup(&lp->sl_map_hash, b, hash);
13839 		if (HASHITEM_EMPTY(hi))
13840 		    hash_add_item(&lp->sl_map_hash, hi, b, hash);
13841 		else
13842 		{
13843 		    /* This should have been checked when generating the .spl
13844 		     * file. */
13845 		    EMSG(_("E783: duplicate char in MAP entry"));
13846 		    vim_free(b);
13847 		}
13848 	    }
13849 	    else
13850 #endif
13851 		lp->sl_map_array[c] = headc;
13852 	}
13853     }
13854 }
13855 
13856 /*
13857  * Return TRUE if "c1" and "c2" are similar characters according to the MAP
13858  * lines in the .aff file.
13859  */
13860     static int
13861 similar_chars(slang, c1, c2)
13862     slang_T	*slang;
13863     int		c1;
13864     int		c2;
13865 {
13866     int		m1, m2;
13867 #ifdef FEAT_MBYTE
13868     char_u	buf[MB_MAXBYTES + 1];
13869     hashitem_T  *hi;
13870 
13871     if (c1 >= 256)
13872     {
13873 	buf[mb_char2bytes(c1, buf)] = 0;
13874 	hi = hash_find(&slang->sl_map_hash, buf);
13875 	if (HASHITEM_EMPTY(hi))
13876 	    m1 = 0;
13877 	else
13878 	    m1 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
13879     }
13880     else
13881 #endif
13882 	m1 = slang->sl_map_array[c1];
13883     if (m1 == 0)
13884 	return FALSE;
13885 
13886 
13887 #ifdef FEAT_MBYTE
13888     if (c2 >= 256)
13889     {
13890 	buf[mb_char2bytes(c2, buf)] = 0;
13891 	hi = hash_find(&slang->sl_map_hash, buf);
13892 	if (HASHITEM_EMPTY(hi))
13893 	    m2 = 0;
13894 	else
13895 	    m2 = mb_ptr2char(hi->hi_key + STRLEN(hi->hi_key) + 1);
13896     }
13897     else
13898 #endif
13899 	m2 = slang->sl_map_array[c2];
13900 
13901     return m1 == m2;
13902 }
13903 
13904 /*
13905  * Add a suggestion to the list of suggestions.
13906  * For a suggestion that is already in the list the lowest score is remembered.
13907  */
13908     static void
13909 add_suggestion(su, gap, goodword, badlenarg, score, altscore, had_bonus,
13910 								 slang, maxsf)
13911     suginfo_T	*su;
13912     garray_T	*gap;		/* either su_ga or su_sga */
13913     char_u	*goodword;
13914     int		badlenarg;	/* len of bad word replaced with "goodword" */
13915     int		score;
13916     int		altscore;
13917     int		had_bonus;	/* value for st_had_bonus */
13918     slang_T	*slang;		/* language for sound folding */
13919     int		maxsf;		/* su_maxscore applies to soundfold score,
13920 				   su_sfmaxscore to the total score. */
13921 {
13922     int		goodlen;	/* len of goodword changed */
13923     int		badlen;		/* len of bad word changed */
13924     suggest_T   *stp;
13925     suggest_T   new_sug;
13926     int		i;
13927     char_u	*pgood, *pbad;
13928 
13929     /* Minimize "badlen" for consistency.  Avoids that changing "the the" to
13930      * "thee the" is added next to changing the first "the" the "thee".  */
13931     pgood = goodword + STRLEN(goodword);
13932     pbad = su->su_badptr + badlenarg;
13933     for (;;)
13934     {
13935 	goodlen = (int)(pgood - goodword);
13936 	badlen = (int)(pbad - su->su_badptr);
13937 	if (goodlen <= 0 || badlen <= 0)
13938 	    break;
13939 	mb_ptr_back(goodword, pgood);
13940 	mb_ptr_back(su->su_badptr, pbad);
13941 #ifdef FEAT_MBYTE
13942 	if (has_mbyte)
13943 	{
13944 	    if (mb_ptr2char(pgood) != mb_ptr2char(pbad))
13945 		break;
13946 	}
13947 	else
13948 #endif
13949 	    if (*pgood != *pbad)
13950 		break;
13951     }
13952 
13953     if (badlen == 0 && goodlen == 0)
13954 	/* goodword doesn't change anything; may happen for "the the" changing
13955 	 * the first "the" to itself. */
13956 	return;
13957 
13958     if (gap->ga_len == 0)
13959 	i = -1;
13960     else
13961     {
13962 	/* Check if the word is already there.  Also check the length that is
13963 	 * being replaced "thes," -> "these" is a different suggestion from
13964 	 * "thes" -> "these". */
13965 	stp = &SUG(*gap, 0);
13966 	for (i = gap->ga_len; --i >= 0; ++stp)
13967 	    if (stp->st_wordlen == goodlen
13968 		    && stp->st_orglen == badlen
13969 		    && STRNCMP(stp->st_word, goodword, goodlen) == 0)
13970 	    {
13971 		/*
13972 		 * Found it.  Remember the word with the lowest score.
13973 		 */
13974 		if (stp->st_slang == NULL)
13975 		    stp->st_slang = slang;
13976 
13977 		new_sug.st_score = score;
13978 		new_sug.st_altscore = altscore;
13979 		new_sug.st_had_bonus = had_bonus;
13980 
13981 		if (stp->st_had_bonus != had_bonus)
13982 		{
13983 		    /* Only one of the two had the soundalike score computed.
13984 		     * Need to do that for the other one now, otherwise the
13985 		     * scores can't be compared.  This happens because
13986 		     * suggest_try_change() doesn't compute the soundalike
13987 		     * word to keep it fast, while some special methods set
13988 		     * the soundalike score to zero. */
13989 		    if (had_bonus)
13990 			rescore_one(su, stp);
13991 		    else
13992 		    {
13993 			new_sug.st_word = stp->st_word;
13994 			new_sug.st_wordlen = stp->st_wordlen;
13995 			new_sug.st_slang = stp->st_slang;
13996 			new_sug.st_orglen = badlen;
13997 			rescore_one(su, &new_sug);
13998 		    }
13999 		}
14000 
14001 		if (stp->st_score > new_sug.st_score)
14002 		{
14003 		    stp->st_score = new_sug.st_score;
14004 		    stp->st_altscore = new_sug.st_altscore;
14005 		    stp->st_had_bonus = new_sug.st_had_bonus;
14006 		}
14007 		break;
14008 	    }
14009     }
14010 
14011     if (i < 0 && ga_grow(gap, 1) == OK)
14012     {
14013 	/* Add a suggestion. */
14014 	stp = &SUG(*gap, gap->ga_len);
14015 	stp->st_word = vim_strnsave(goodword, goodlen);
14016 	if (stp->st_word != NULL)
14017 	{
14018 	    stp->st_wordlen = goodlen;
14019 	    stp->st_score = score;
14020 	    stp->st_altscore = altscore;
14021 	    stp->st_had_bonus = had_bonus;
14022 	    stp->st_orglen = badlen;
14023 	    stp->st_slang = slang;
14024 	    ++gap->ga_len;
14025 
14026 	    /* If we have too many suggestions now, sort the list and keep
14027 	     * the best suggestions. */
14028 	    if (gap->ga_len > SUG_MAX_COUNT(su))
14029 	    {
14030 		if (maxsf)
14031 		    su->su_sfmaxscore = cleanup_suggestions(gap,
14032 				      su->su_sfmaxscore, SUG_CLEAN_COUNT(su));
14033 		else
14034 		    su->su_maxscore = cleanup_suggestions(gap,
14035 					su->su_maxscore, SUG_CLEAN_COUNT(su));
14036 	    }
14037 	}
14038     }
14039 }
14040 
14041 /*
14042  * Suggestions may in fact be flagged as errors.  Esp. for banned words and
14043  * for split words, such as "the the".  Remove these from the list here.
14044  */
14045     static void
14046 check_suggestions(su, gap)
14047     suginfo_T	*su;
14048     garray_T	*gap;		    /* either su_ga or su_sga */
14049 {
14050     suggest_T   *stp;
14051     int		i;
14052     char_u	longword[MAXWLEN + 1];
14053     int		len;
14054     hlf_T	attr;
14055 
14056     stp = &SUG(*gap, 0);
14057     for (i = gap->ga_len - 1; i >= 0; --i)
14058     {
14059 	/* Need to append what follows to check for "the the". */
14060 	vim_strncpy(longword, stp[i].st_word, MAXWLEN);
14061 	len = stp[i].st_wordlen;
14062 	vim_strncpy(longword + len, su->su_badptr + stp[i].st_orglen,
14063 							       MAXWLEN - len);
14064 	attr = HLF_COUNT;
14065 	(void)spell_check(curwin, longword, &attr, NULL, FALSE);
14066 	if (attr != HLF_COUNT)
14067 	{
14068 	    /* Remove this entry. */
14069 	    vim_free(stp[i].st_word);
14070 	    --gap->ga_len;
14071 	    if (i < gap->ga_len)
14072 		mch_memmove(stp + i, stp + i + 1,
14073 				       sizeof(suggest_T) * (gap->ga_len - i));
14074 	}
14075     }
14076 }
14077 
14078 
14079 /*
14080  * Add a word to be banned.
14081  */
14082     static void
14083 add_banned(su, word)
14084     suginfo_T	*su;
14085     char_u	*word;
14086 {
14087     char_u	*s;
14088     hash_T	hash;
14089     hashitem_T	*hi;
14090 
14091     hash = hash_hash(word);
14092     hi = hash_lookup(&su->su_banned, word, hash);
14093     if (HASHITEM_EMPTY(hi))
14094     {
14095 	s = vim_strsave(word);
14096 	if (s != NULL)
14097 	    hash_add_item(&su->su_banned, hi, s, hash);
14098     }
14099 }
14100 
14101 /*
14102  * Recompute the score for all suggestions if sound-folding is possible.  This
14103  * is slow, thus only done for the final results.
14104  */
14105     static void
14106 rescore_suggestions(su)
14107     suginfo_T	*su;
14108 {
14109     int		i;
14110 
14111     if (su->su_sallang != NULL)
14112 	for (i = 0; i < su->su_ga.ga_len; ++i)
14113 	    rescore_one(su, &SUG(su->su_ga, i));
14114 }
14115 
14116 /*
14117  * Recompute the score for one suggestion if sound-folding is possible.
14118  */
14119     static void
14120 rescore_one(su, stp)
14121     suginfo_T	*su;
14122     suggest_T	*stp;
14123 {
14124     slang_T	*slang = stp->st_slang;
14125     char_u	sal_badword[MAXWLEN];
14126     char_u	*p;
14127 
14128     /* Only rescore suggestions that have no sal score yet and do have a
14129      * language. */
14130     if (slang != NULL && slang->sl_sal.ga_len > 0 && !stp->st_had_bonus)
14131     {
14132 	if (slang == su->su_sallang)
14133 	    p = su->su_sal_badword;
14134 	else
14135 	{
14136 	    spell_soundfold(slang, su->su_fbadword, TRUE, sal_badword);
14137 	    p = sal_badword;
14138 	}
14139 
14140 	stp->st_altscore = stp_sal_score(stp, su, slang, p);
14141 	if (stp->st_altscore == SCORE_MAXMAX)
14142 	    stp->st_altscore = SCORE_BIG;
14143 	stp->st_score = RESCORE(stp->st_score, stp->st_altscore);
14144 	stp->st_had_bonus = TRUE;
14145     }
14146 }
14147 
14148 static int
14149 #ifdef __BORLANDC__
14150 _RTLENTRYF
14151 #endif
14152 sug_compare __ARGS((const void *s1, const void *s2));
14153 
14154 /*
14155  * Function given to qsort() to sort the suggestions on st_score.
14156  * First on "st_score", then "st_altscore" then alphabetically.
14157  */
14158     static int
14159 #ifdef __BORLANDC__
14160 _RTLENTRYF
14161 #endif
14162 sug_compare(s1, s2)
14163     const void	*s1;
14164     const void	*s2;
14165 {
14166     suggest_T	*p1 = (suggest_T *)s1;
14167     suggest_T	*p2 = (suggest_T *)s2;
14168     int		n = p1->st_score - p2->st_score;
14169 
14170     if (n == 0)
14171     {
14172 	n = p1->st_altscore - p2->st_altscore;
14173 	if (n == 0)
14174 	    n = STRICMP(p1->st_word, p2->st_word);
14175     }
14176     return n;
14177 }
14178 
14179 /*
14180  * Cleanup the suggestions:
14181  * - Sort on score.
14182  * - Remove words that won't be displayed.
14183  * Returns the maximum score in the list or "maxscore" unmodified.
14184  */
14185     static int
14186 cleanup_suggestions(gap, maxscore, keep)
14187     garray_T	*gap;
14188     int		maxscore;
14189     int		keep;		/* nr of suggestions to keep */
14190 {
14191     suggest_T   *stp = &SUG(*gap, 0);
14192     int		i;
14193 
14194     /* Sort the list. */
14195     qsort(gap->ga_data, (size_t)gap->ga_len, sizeof(suggest_T), sug_compare);
14196 
14197     /* Truncate the list to the number of suggestions that will be displayed. */
14198     if (gap->ga_len > keep)
14199     {
14200 	for (i = keep; i < gap->ga_len; ++i)
14201 	    vim_free(stp[i].st_word);
14202 	gap->ga_len = keep;
14203 	return stp[keep - 1].st_score;
14204     }
14205     return maxscore;
14206 }
14207 
14208 #if defined(FEAT_EVAL) || defined(PROTO)
14209 /*
14210  * Soundfold a string, for soundfold().
14211  * Result is in allocated memory, NULL for an error.
14212  */
14213     char_u *
14214 eval_soundfold(word)
14215     char_u	*word;
14216 {
14217     langp_T	*lp;
14218     char_u	sound[MAXWLEN];
14219     int		lpi;
14220 
14221     if (curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
14222 	/* Use the sound-folding of the first language that supports it. */
14223 	for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
14224 	{
14225 	    lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
14226 	    if (lp->lp_slang->sl_sal.ga_len > 0)
14227 	    {
14228 		/* soundfold the word */
14229 		spell_soundfold(lp->lp_slang, word, FALSE, sound);
14230 		return vim_strsave(sound);
14231 	    }
14232 	}
14233 
14234     /* No language with sound folding, return word as-is. */
14235     return vim_strsave(word);
14236 }
14237 #endif
14238 
14239 /*
14240  * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]".
14241  *
14242  * There are many ways to turn a word into a sound-a-like representation.  The
14243  * oldest is Soundex (1918!).   A nice overview can be found in "Approximate
14244  * swedish name matching - survey and test of different algorithms" by Klas
14245  * Erikson.
14246  *
14247  * We support two methods:
14248  * 1. SOFOFROM/SOFOTO do a simple character mapping.
14249  * 2. SAL items define a more advanced sound-folding (and much slower).
14250  */
14251     static void
14252 spell_soundfold(slang, inword, folded, res)
14253     slang_T	*slang;
14254     char_u	*inword;
14255     int		folded;	    /* "inword" is already case-folded */
14256     char_u	*res;
14257 {
14258     char_u	fword[MAXWLEN];
14259     char_u	*word;
14260 
14261     if (slang->sl_sofo)
14262 	/* SOFOFROM and SOFOTO used */
14263 	spell_soundfold_sofo(slang, inword, res);
14264     else
14265     {
14266 	/* SAL items used.  Requires the word to be case-folded. */
14267 	if (folded)
14268 	    word = inword;
14269 	else
14270 	{
14271 	    (void)spell_casefold(inword, (int)STRLEN(inword), fword, MAXWLEN);
14272 	    word = fword;
14273 	}
14274 
14275 #ifdef FEAT_MBYTE
14276 	if (has_mbyte)
14277 	    spell_soundfold_wsal(slang, word, res);
14278 	else
14279 #endif
14280 	    spell_soundfold_sal(slang, word, res);
14281     }
14282 }
14283 
14284 /*
14285  * Perform sound folding of "inword" into "res" according to SOFOFROM and
14286  * SOFOTO lines.
14287  */
14288     static void
14289 spell_soundfold_sofo(slang, inword, res)
14290     slang_T	*slang;
14291     char_u	*inword;
14292     char_u	*res;
14293 {
14294     char_u	*s;
14295     int		ri = 0;
14296     int		c;
14297 
14298 #ifdef FEAT_MBYTE
14299     if (has_mbyte)
14300     {
14301 	int	prevc = 0;
14302 	int	*ip;
14303 
14304 	/* The sl_sal_first[] table contains the translation for chars up to
14305 	 * 255, sl_sal the rest. */
14306 	for (s = inword; *s != NUL; )
14307 	{
14308 	    c = mb_cptr2char_adv(&s);
14309 	    if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c))
14310 		c = ' ';
14311 	    else if (c < 256)
14312 		c = slang->sl_sal_first[c];
14313 	    else
14314 	    {
14315 		ip = ((int **)slang->sl_sal.ga_data)[c & 0xff];
14316 		if (ip == NULL)		/* empty list, can't match */
14317 		    c = NUL;
14318 		else
14319 		    for (;;)		/* find "c" in the list */
14320 		    {
14321 			if (*ip == 0)	/* not found */
14322 			{
14323 			    c = NUL;
14324 			    break;
14325 			}
14326 			if (*ip == c)	/* match! */
14327 			{
14328 			    c = ip[1];
14329 			    break;
14330 			}
14331 			ip += 2;
14332 		    }
14333 	    }
14334 
14335 	    if (c != NUL && c != prevc)
14336 	    {
14337 		ri += mb_char2bytes(c, res + ri);
14338 		if (ri + MB_MAXBYTES > MAXWLEN)
14339 		    break;
14340 		prevc = c;
14341 	    }
14342 	}
14343     }
14344     else
14345 #endif
14346     {
14347 	/* The sl_sal_first[] table contains the translation. */
14348 	for (s = inword; (c = *s) != NUL; ++s)
14349 	{
14350 	    if (vim_iswhite(c))
14351 		c = ' ';
14352 	    else
14353 		c = slang->sl_sal_first[c];
14354 	    if (c != NUL && (ri == 0 || res[ri - 1] != c))
14355 		res[ri++] = c;
14356 	}
14357     }
14358 
14359     res[ri] = NUL;
14360 }
14361 
14362     static void
14363 spell_soundfold_sal(slang, inword, res)
14364     slang_T	*slang;
14365     char_u	*inword;
14366     char_u	*res;
14367 {
14368     salitem_T	*smp;
14369     char_u	word[MAXWLEN];
14370     char_u	*s = inword;
14371     char_u	*t;
14372     char_u	*pf;
14373     int		i, j, z;
14374     int		reslen;
14375     int		n, k = 0;
14376     int		z0;
14377     int		k0;
14378     int		n0;
14379     int		c;
14380     int		pri;
14381     int		p0 = -333;
14382     int		c0;
14383 
14384     /* Remove accents, if wanted.  We actually remove all non-word characters.
14385      * But keep white space.  We need a copy, the word may be changed here. */
14386     if (slang->sl_rem_accents)
14387     {
14388 	t = word;
14389 	while (*s != NUL)
14390 	{
14391 	    if (vim_iswhite(*s))
14392 	    {
14393 		*t++ = ' ';
14394 		s = skipwhite(s);
14395 	    }
14396 	    else
14397 	    {
14398 		if (spell_iswordp_nmw(s, curwin))
14399 		    *t++ = *s;
14400 		++s;
14401 	    }
14402 	}
14403 	*t = NUL;
14404     }
14405     else
14406 	vim_strncpy(word, s, MAXWLEN - 1);
14407 
14408     smp = (salitem_T *)slang->sl_sal.ga_data;
14409 
14410     /*
14411      * This comes from Aspell phonet.cpp.  Converted from C++ to C.
14412      * Changed to keep spaces.
14413      */
14414     i = reslen = z = 0;
14415     while ((c = word[i]) != NUL)
14416     {
14417 	/* Start with the first rule that has the character in the word. */
14418 	n = slang->sl_sal_first[c];
14419 	z0 = 0;
14420 
14421 	if (n >= 0)
14422 	{
14423 	    /* check all rules for the same letter */
14424 	    for (; (s = smp[n].sm_lead)[0] == c; ++n)
14425 	    {
14426 		/* Quickly skip entries that don't match the word.  Most
14427 		 * entries are less then three chars, optimize for that. */
14428 		k = smp[n].sm_leadlen;
14429 		if (k > 1)
14430 		{
14431 		    if (word[i + 1] != s[1])
14432 			continue;
14433 		    if (k > 2)
14434 		    {
14435 			for (j = 2; j < k; ++j)
14436 			    if (word[i + j] != s[j])
14437 				break;
14438 			if (j < k)
14439 			    continue;
14440 		    }
14441 		}
14442 
14443 		if ((pf = smp[n].sm_oneof) != NULL)
14444 		{
14445 		    /* Check for match with one of the chars in "sm_oneof". */
14446 		    while (*pf != NUL && *pf != word[i + k])
14447 			++pf;
14448 		    if (*pf == NUL)
14449 			continue;
14450 		    ++k;
14451 		}
14452 		s = smp[n].sm_rules;
14453 		pri = 5;    /* default priority */
14454 
14455 		p0 = *s;
14456 		k0 = k;
14457 		while (*s == '-' && k > 1)
14458 		{
14459 		    k--;
14460 		    s++;
14461 		}
14462 		if (*s == '<')
14463 		    s++;
14464 		if (VIM_ISDIGIT(*s))
14465 		{
14466 		    /* determine priority */
14467 		    pri = *s - '0';
14468 		    s++;
14469 		}
14470 		if (*s == '^' && *(s + 1) == '^')
14471 		    s++;
14472 
14473 		if (*s == NUL
14474 			|| (*s == '^'
14475 			    && (i == 0 || !(word[i - 1] == ' '
14476 				      || spell_iswordp(word + i - 1, curwin)))
14477 			    && (*(s + 1) != '$'
14478 				|| (!spell_iswordp(word + i + k0, curwin))))
14479 			|| (*s == '$' && i > 0
14480 			    && spell_iswordp(word + i - 1, curwin)
14481 			    && (!spell_iswordp(word + i + k0, curwin))))
14482 		{
14483 		    /* search for followup rules, if:    */
14484 		    /* followup and k > 1  and  NO '-' in searchstring */
14485 		    c0 = word[i + k - 1];
14486 		    n0 = slang->sl_sal_first[c0];
14487 
14488 		    if (slang->sl_followup && k > 1 && n0 >= 0
14489 					   && p0 != '-' && word[i + k] != NUL)
14490 		    {
14491 			/* test follow-up rule for "word[i + k]" */
14492 			for ( ; (s = smp[n0].sm_lead)[0] == c0; ++n0)
14493 			{
14494 			    /* Quickly skip entries that don't match the word.
14495 			     * */
14496 			    k0 = smp[n0].sm_leadlen;
14497 			    if (k0 > 1)
14498 			    {
14499 				if (word[i + k] != s[1])
14500 				    continue;
14501 				if (k0 > 2)
14502 				{
14503 				    pf = word + i + k + 1;
14504 				    for (j = 2; j < k0; ++j)
14505 					if (*pf++ != s[j])
14506 					    break;
14507 				    if (j < k0)
14508 					continue;
14509 				}
14510 			    }
14511 			    k0 += k - 1;
14512 
14513 			    if ((pf = smp[n0].sm_oneof) != NULL)
14514 			    {
14515 				/* Check for match with one of the chars in
14516 				 * "sm_oneof". */
14517 				while (*pf != NUL && *pf != word[i + k0])
14518 				    ++pf;
14519 				if (*pf == NUL)
14520 				    continue;
14521 				++k0;
14522 			    }
14523 
14524 			    p0 = 5;
14525 			    s = smp[n0].sm_rules;
14526 			    while (*s == '-')
14527 			    {
14528 				/* "k0" gets NOT reduced because
14529 				 * "if (k0 == k)" */
14530 				s++;
14531 			    }
14532 			    if (*s == '<')
14533 				s++;
14534 			    if (VIM_ISDIGIT(*s))
14535 			    {
14536 				p0 = *s - '0';
14537 				s++;
14538 			    }
14539 
14540 			    if (*s == NUL
14541 				    /* *s == '^' cuts */
14542 				    || (*s == '$'
14543 					    && !spell_iswordp(word + i + k0,
14544 								     curwin)))
14545 			    {
14546 				if (k0 == k)
14547 				    /* this is just a piece of the string */
14548 				    continue;
14549 
14550 				if (p0 < pri)
14551 				    /* priority too low */
14552 				    continue;
14553 				/* rule fits; stop search */
14554 				break;
14555 			    }
14556 			}
14557 
14558 			if (p0 >= pri && smp[n0].sm_lead[0] == c0)
14559 			    continue;
14560 		    }
14561 
14562 		    /* replace string */
14563 		    s = smp[n].sm_to;
14564 		    if (s == NULL)
14565 			s = (char_u *)"";
14566 		    pf = smp[n].sm_rules;
14567 		    p0 = (vim_strchr(pf, '<') != NULL) ? 1 : 0;
14568 		    if (p0 == 1 && z == 0)
14569 		    {
14570 			/* rule with '<' is used */
14571 			if (reslen > 0 && *s != NUL && (res[reslen - 1] == c
14572 						    || res[reslen - 1] == *s))
14573 			    reslen--;
14574 			z0 = 1;
14575 			z = 1;
14576 			k0 = 0;
14577 			while (*s != NUL && word[i + k0] != NUL)
14578 			{
14579 			    word[i + k0] = *s;
14580 			    k0++;
14581 			    s++;
14582 			}
14583 			if (k > k0)
14584 			    STRMOVE(word + i + k0, word + i + k);
14585 
14586 			/* new "actual letter" */
14587 			c = word[i];
14588 		    }
14589 		    else
14590 		    {
14591 			/* no '<' rule used */
14592 			i += k - 1;
14593 			z = 0;
14594 			while (*s != NUL && s[1] != NUL && reslen < MAXWLEN)
14595 			{
14596 			    if (reslen == 0 || res[reslen - 1] != *s)
14597 				res[reslen++] = *s;
14598 			    s++;
14599 			}
14600 			/* new "actual letter" */
14601 			c = *s;
14602 			if (strstr((char *)pf, "^^") != NULL)
14603 			{
14604 			    if (c != NUL)
14605 				res[reslen++] = c;
14606 			    STRMOVE(word, word + i + 1);
14607 			    i = 0;
14608 			    z0 = 1;
14609 			}
14610 		    }
14611 		    break;
14612 		}
14613 	    }
14614 	}
14615 	else if (vim_iswhite(c))
14616 	{
14617 	    c = ' ';
14618 	    k = 1;
14619 	}
14620 
14621 	if (z0 == 0)
14622 	{
14623 	    if (k && !p0 && reslen < MAXWLEN && c != NUL
14624 		    && (!slang->sl_collapse || reslen == 0
14625 						     || res[reslen - 1] != c))
14626 		/* condense only double letters */
14627 		res[reslen++] = c;
14628 
14629 	    i++;
14630 	    z = 0;
14631 	    k = 0;
14632 	}
14633     }
14634 
14635     res[reslen] = NUL;
14636 }
14637 
14638 #ifdef FEAT_MBYTE
14639 /*
14640  * Turn "inword" into its sound-a-like equivalent in "res[MAXWLEN]".
14641  * Multi-byte version of spell_soundfold().
14642  */
14643     static void
14644 spell_soundfold_wsal(slang, inword, res)
14645     slang_T	*slang;
14646     char_u	*inword;
14647     char_u	*res;
14648 {
14649     salitem_T	*smp = (salitem_T *)slang->sl_sal.ga_data;
14650     int		word[MAXWLEN];
14651     int		wres[MAXWLEN];
14652     int		l;
14653     char_u	*s;
14654     int		*ws;
14655     char_u	*t;
14656     int		*pf;
14657     int		i, j, z;
14658     int		reslen;
14659     int		n, k = 0;
14660     int		z0;
14661     int		k0;
14662     int		n0;
14663     int		c;
14664     int		pri;
14665     int		p0 = -333;
14666     int		c0;
14667     int		did_white = FALSE;
14668     int		wordlen;
14669 
14670 
14671     /*
14672      * Convert the multi-byte string to a wide-character string.
14673      * Remove accents, if wanted.  We actually remove all non-word characters.
14674      * But keep white space.
14675      */
14676     wordlen = 0;
14677     for (s = inword; *s != NUL; )
14678     {
14679 	t = s;
14680 	c = mb_cptr2char_adv(&s);
14681 	if (slang->sl_rem_accents)
14682 	{
14683 	    if (enc_utf8 ? utf_class(c) == 0 : vim_iswhite(c))
14684 	    {
14685 		if (did_white)
14686 		    continue;
14687 		c = ' ';
14688 		did_white = TRUE;
14689 	    }
14690 	    else
14691 	    {
14692 		did_white = FALSE;
14693 		if (!spell_iswordp_nmw(t, curwin))
14694 		    continue;
14695 	    }
14696 	}
14697 	word[wordlen++] = c;
14698     }
14699     word[wordlen] = NUL;
14700 
14701     /*
14702      * This algorithm comes from Aspell phonet.cpp.
14703      * Converted from C++ to C.  Added support for multi-byte chars.
14704      * Changed to keep spaces.
14705      */
14706     i = reslen = z = 0;
14707     while ((c = word[i]) != NUL)
14708     {
14709 	/* Start with the first rule that has the character in the word. */
14710 	n = slang->sl_sal_first[c & 0xff];
14711 	z0 = 0;
14712 
14713 	if (n >= 0)
14714 	{
14715 	    /* Check all rules for the same index byte.
14716 	     * If c is 0x300 need extra check for the end of the array, as
14717 	     * (c & 0xff) is NUL. */
14718 	    for (; ((ws = smp[n].sm_lead_w)[0] & 0xff) == (c & 0xff)
14719 							 && ws[0] != NUL; ++n)
14720 	    {
14721 		/* Quickly skip entries that don't match the word.  Most
14722 		 * entries are less then three chars, optimize for that. */
14723 		if (c != ws[0])
14724 		    continue;
14725 		k = smp[n].sm_leadlen;
14726 		if (k > 1)
14727 		{
14728 		    if (word[i + 1] != ws[1])
14729 			continue;
14730 		    if (k > 2)
14731 		    {
14732 			for (j = 2; j < k; ++j)
14733 			    if (word[i + j] != ws[j])
14734 				break;
14735 			if (j < k)
14736 			    continue;
14737 		    }
14738 		}
14739 
14740 		if ((pf = smp[n].sm_oneof_w) != NULL)
14741 		{
14742 		    /* Check for match with one of the chars in "sm_oneof". */
14743 		    while (*pf != NUL && *pf != word[i + k])
14744 			++pf;
14745 		    if (*pf == NUL)
14746 			continue;
14747 		    ++k;
14748 		}
14749 		s = smp[n].sm_rules;
14750 		pri = 5;    /* default priority */
14751 
14752 		p0 = *s;
14753 		k0 = k;
14754 		while (*s == '-' && k > 1)
14755 		{
14756 		    k--;
14757 		    s++;
14758 		}
14759 		if (*s == '<')
14760 		    s++;
14761 		if (VIM_ISDIGIT(*s))
14762 		{
14763 		    /* determine priority */
14764 		    pri = *s - '0';
14765 		    s++;
14766 		}
14767 		if (*s == '^' && *(s + 1) == '^')
14768 		    s++;
14769 
14770 		if (*s == NUL
14771 			|| (*s == '^'
14772 			    && (i == 0 || !(word[i - 1] == ' '
14773 				    || spell_iswordp_w(word + i - 1, curwin)))
14774 			    && (*(s + 1) != '$'
14775 				|| (!spell_iswordp_w(word + i + k0, curwin))))
14776 			|| (*s == '$' && i > 0
14777 			    && spell_iswordp_w(word + i - 1, curwin)
14778 			    && (!spell_iswordp_w(word + i + k0, curwin))))
14779 		{
14780 		    /* search for followup rules, if:    */
14781 		    /* followup and k > 1  and  NO '-' in searchstring */
14782 		    c0 = word[i + k - 1];
14783 		    n0 = slang->sl_sal_first[c0 & 0xff];
14784 
14785 		    if (slang->sl_followup && k > 1 && n0 >= 0
14786 					   && p0 != '-' && word[i + k] != NUL)
14787 		    {
14788 			/* Test follow-up rule for "word[i + k]"; loop over
14789 			 * all entries with the same index byte. */
14790 			for ( ; ((ws = smp[n0].sm_lead_w)[0] & 0xff)
14791 							 == (c0 & 0xff); ++n0)
14792 			{
14793 			    /* Quickly skip entries that don't match the word.
14794 			     */
14795 			    if (c0 != ws[0])
14796 				continue;
14797 			    k0 = smp[n0].sm_leadlen;
14798 			    if (k0 > 1)
14799 			    {
14800 				if (word[i + k] != ws[1])
14801 				    continue;
14802 				if (k0 > 2)
14803 				{
14804 				    pf = word + i + k + 1;
14805 				    for (j = 2; j < k0; ++j)
14806 					if (*pf++ != ws[j])
14807 					    break;
14808 				    if (j < k0)
14809 					continue;
14810 				}
14811 			    }
14812 			    k0 += k - 1;
14813 
14814 			    if ((pf = smp[n0].sm_oneof_w) != NULL)
14815 			    {
14816 				/* Check for match with one of the chars in
14817 				 * "sm_oneof". */
14818 				while (*pf != NUL && *pf != word[i + k0])
14819 				    ++pf;
14820 				if (*pf == NUL)
14821 				    continue;
14822 				++k0;
14823 			    }
14824 
14825 			    p0 = 5;
14826 			    s = smp[n0].sm_rules;
14827 			    while (*s == '-')
14828 			    {
14829 				/* "k0" gets NOT reduced because
14830 				 * "if (k0 == k)" */
14831 				s++;
14832 			    }
14833 			    if (*s == '<')
14834 				s++;
14835 			    if (VIM_ISDIGIT(*s))
14836 			    {
14837 				p0 = *s - '0';
14838 				s++;
14839 			    }
14840 
14841 			    if (*s == NUL
14842 				    /* *s == '^' cuts */
14843 				    || (*s == '$'
14844 					 && !spell_iswordp_w(word + i + k0,
14845 								     curwin)))
14846 			    {
14847 				if (k0 == k)
14848 				    /* this is just a piece of the string */
14849 				    continue;
14850 
14851 				if (p0 < pri)
14852 				    /* priority too low */
14853 				    continue;
14854 				/* rule fits; stop search */
14855 				break;
14856 			    }
14857 			}
14858 
14859 			if (p0 >= pri && (smp[n0].sm_lead_w[0] & 0xff)
14860 							       == (c0 & 0xff))
14861 			    continue;
14862 		    }
14863 
14864 		    /* replace string */
14865 		    ws = smp[n].sm_to_w;
14866 		    s = smp[n].sm_rules;
14867 		    p0 = (vim_strchr(s, '<') != NULL) ? 1 : 0;
14868 		    if (p0 == 1 && z == 0)
14869 		    {
14870 			/* rule with '<' is used */
14871 			if (reslen > 0 && ws != NULL && *ws != NUL
14872 				&& (wres[reslen - 1] == c
14873 						    || wres[reslen - 1] == *ws))
14874 			    reslen--;
14875 			z0 = 1;
14876 			z = 1;
14877 			k0 = 0;
14878 			if (ws != NULL)
14879 			    while (*ws != NUL && word[i + k0] != NUL)
14880 			    {
14881 				word[i + k0] = *ws;
14882 				k0++;
14883 				ws++;
14884 			    }
14885 			if (k > k0)
14886 			    mch_memmove(word + i + k0, word + i + k,
14887 				    sizeof(int) * (wordlen - (i + k) + 1));
14888 
14889 			/* new "actual letter" */
14890 			c = word[i];
14891 		    }
14892 		    else
14893 		    {
14894 			/* no '<' rule used */
14895 			i += k - 1;
14896 			z = 0;
14897 			if (ws != NULL)
14898 			    while (*ws != NUL && ws[1] != NUL
14899 							  && reslen < MAXWLEN)
14900 			    {
14901 				if (reslen == 0 || wres[reslen - 1] != *ws)
14902 				    wres[reslen++] = *ws;
14903 				ws++;
14904 			    }
14905 			/* new "actual letter" */
14906 			if (ws == NULL)
14907 			    c = NUL;
14908 			else
14909 			    c = *ws;
14910 			if (strstr((char *)s, "^^") != NULL)
14911 			{
14912 			    if (c != NUL)
14913 				wres[reslen++] = c;
14914 			    mch_memmove(word, word + i + 1,
14915 				       sizeof(int) * (wordlen - (i + 1) + 1));
14916 			    i = 0;
14917 			    z0 = 1;
14918 			}
14919 		    }
14920 		    break;
14921 		}
14922 	    }
14923 	}
14924 	else if (vim_iswhite(c))
14925 	{
14926 	    c = ' ';
14927 	    k = 1;
14928 	}
14929 
14930 	if (z0 == 0)
14931 	{
14932 	    if (k && !p0 && reslen < MAXWLEN && c != NUL
14933 		    && (!slang->sl_collapse || reslen == 0
14934 						     || wres[reslen - 1] != c))
14935 		/* condense only double letters */
14936 		wres[reslen++] = c;
14937 
14938 	    i++;
14939 	    z = 0;
14940 	    k = 0;
14941 	}
14942     }
14943 
14944     /* Convert wide characters in "wres" to a multi-byte string in "res". */
14945     l = 0;
14946     for (n = 0; n < reslen; ++n)
14947     {
14948 	l += mb_char2bytes(wres[n], res + l);
14949 	if (l + MB_MAXBYTES > MAXWLEN)
14950 	    break;
14951     }
14952     res[l] = NUL;
14953 }
14954 #endif
14955 
14956 /*
14957  * Compute a score for two sound-a-like words.
14958  * This permits up to two inserts/deletes/swaps/etc. to keep things fast.
14959  * Instead of a generic loop we write out the code.  That keeps it fast by
14960  * avoiding checks that will not be possible.
14961  */
14962     static int
14963 soundalike_score(goodstart, badstart)
14964     char_u	*goodstart;	/* sound-folded good word */
14965     char_u	*badstart;	/* sound-folded bad word */
14966 {
14967     char_u	*goodsound = goodstart;
14968     char_u	*badsound = badstart;
14969     int		goodlen;
14970     int		badlen;
14971     int		n;
14972     char_u	*pl, *ps;
14973     char_u	*pl2, *ps2;
14974     int		score = 0;
14975 
14976     /* Adding/inserting "*" at the start (word starts with vowel) shouldn't be
14977      * counted so much, vowels halfway the word aren't counted at all. */
14978     if ((*badsound == '*' || *goodsound == '*') && *badsound != *goodsound)
14979     {
14980 	if ((badsound[0] == NUL && goodsound[1] == NUL)
14981 	    || (goodsound[0] == NUL && badsound[1] == NUL))
14982 	    /* changing word with vowel to word without a sound */
14983 	    return SCORE_DEL;
14984 	if (badsound[0] == NUL || goodsound[0] == NUL)
14985 	    /* more than two changes */
14986 	    return SCORE_MAXMAX;
14987 
14988 	if (badsound[1] == goodsound[1]
14989 		|| (badsound[1] != NUL
14990 		    && goodsound[1] != NUL
14991 		    && badsound[2] == goodsound[2]))
14992 	{
14993 	    /* handle like a substitute */
14994 	}
14995 	else
14996 	{
14997 	    score = 2 * SCORE_DEL / 3;
14998 	    if (*badsound == '*')
14999 		++badsound;
15000 	    else
15001 		++goodsound;
15002 	}
15003     }
15004 
15005     goodlen = (int)STRLEN(goodsound);
15006     badlen = (int)STRLEN(badsound);
15007 
15008     /* Return quickly if the lengths are too different to be fixed by two
15009      * changes. */
15010     n = goodlen - badlen;
15011     if (n < -2 || n > 2)
15012 	return SCORE_MAXMAX;
15013 
15014     if (n > 0)
15015     {
15016 	pl = goodsound;	    /* goodsound is longest */
15017 	ps = badsound;
15018     }
15019     else
15020     {
15021 	pl = badsound;	    /* badsound is longest */
15022 	ps = goodsound;
15023     }
15024 
15025     /* Skip over the identical part. */
15026     while (*pl == *ps && *pl != NUL)
15027     {
15028 	++pl;
15029 	++ps;
15030     }
15031 
15032     switch (n)
15033     {
15034 	case -2:
15035 	case 2:
15036 	    /*
15037 	     * Must delete two characters from "pl".
15038 	     */
15039 	    ++pl;	/* first delete */
15040 	    while (*pl == *ps)
15041 	    {
15042 		++pl;
15043 		++ps;
15044 	    }
15045 	    /* strings must be equal after second delete */
15046 	    if (STRCMP(pl + 1, ps) == 0)
15047 		return score + SCORE_DEL * 2;
15048 
15049 	    /* Failed to compare. */
15050 	    break;
15051 
15052 	case -1:
15053 	case 1:
15054 	    /*
15055 	     * Minimal one delete from "pl" required.
15056 	     */
15057 
15058 	    /* 1: delete */
15059 	    pl2 = pl + 1;
15060 	    ps2 = ps;
15061 	    while (*pl2 == *ps2)
15062 	    {
15063 		if (*pl2 == NUL)	/* reached the end */
15064 		    return score + SCORE_DEL;
15065 		++pl2;
15066 		++ps2;
15067 	    }
15068 
15069 	    /* 2: delete then swap, then rest must be equal */
15070 	    if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
15071 					     && STRCMP(pl2 + 2, ps2 + 2) == 0)
15072 		return score + SCORE_DEL + SCORE_SWAP;
15073 
15074 	    /* 3: delete then substitute, then the rest must be equal */
15075 	    if (STRCMP(pl2 + 1, ps2 + 1) == 0)
15076 		return score + SCORE_DEL + SCORE_SUBST;
15077 
15078 	    /* 4: first swap then delete */
15079 	    if (pl[0] == ps[1] && pl[1] == ps[0])
15080 	    {
15081 		pl2 = pl + 2;	    /* swap, skip two chars */
15082 		ps2 = ps + 2;
15083 		while (*pl2 == *ps2)
15084 		{
15085 		    ++pl2;
15086 		    ++ps2;
15087 		}
15088 		/* delete a char and then strings must be equal */
15089 		if (STRCMP(pl2 + 1, ps2) == 0)
15090 		    return score + SCORE_SWAP + SCORE_DEL;
15091 	    }
15092 
15093 	    /* 5: first substitute then delete */
15094 	    pl2 = pl + 1;	    /* substitute, skip one char */
15095 	    ps2 = ps + 1;
15096 	    while (*pl2 == *ps2)
15097 	    {
15098 		++pl2;
15099 		++ps2;
15100 	    }
15101 	    /* delete a char and then strings must be equal */
15102 	    if (STRCMP(pl2 + 1, ps2) == 0)
15103 		return score + SCORE_SUBST + SCORE_DEL;
15104 
15105 	    /* Failed to compare. */
15106 	    break;
15107 
15108 	case 0:
15109 	    /*
15110 	     * Lengths are equal, thus changes must result in same length: An
15111 	     * insert is only possible in combination with a delete.
15112 	     * 1: check if for identical strings
15113 	     */
15114 	    if (*pl == NUL)
15115 		return score;
15116 
15117 	    /* 2: swap */
15118 	    if (pl[0] == ps[1] && pl[1] == ps[0])
15119 	    {
15120 		pl2 = pl + 2;	    /* swap, skip two chars */
15121 		ps2 = ps + 2;
15122 		while (*pl2 == *ps2)
15123 		{
15124 		    if (*pl2 == NUL)	/* reached the end */
15125 			return score + SCORE_SWAP;
15126 		    ++pl2;
15127 		    ++ps2;
15128 		}
15129 		/* 3: swap and swap again */
15130 		if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
15131 					     && STRCMP(pl2 + 2, ps2 + 2) == 0)
15132 		    return score + SCORE_SWAP + SCORE_SWAP;
15133 
15134 		/* 4: swap and substitute */
15135 		if (STRCMP(pl2 + 1, ps2 + 1) == 0)
15136 		    return score + SCORE_SWAP + SCORE_SUBST;
15137 	    }
15138 
15139 	    /* 5: substitute */
15140 	    pl2 = pl + 1;
15141 	    ps2 = ps + 1;
15142 	    while (*pl2 == *ps2)
15143 	    {
15144 		if (*pl2 == NUL)	/* reached the end */
15145 		    return score + SCORE_SUBST;
15146 		++pl2;
15147 		++ps2;
15148 	    }
15149 
15150 	    /* 6: substitute and swap */
15151 	    if (pl2[0] == ps2[1] && pl2[1] == ps2[0]
15152 					     && STRCMP(pl2 + 2, ps2 + 2) == 0)
15153 		return score + SCORE_SUBST + SCORE_SWAP;
15154 
15155 	    /* 7: substitute and substitute */
15156 	    if (STRCMP(pl2 + 1, ps2 + 1) == 0)
15157 		return score + SCORE_SUBST + SCORE_SUBST;
15158 
15159 	    /* 8: insert then delete */
15160 	    pl2 = pl;
15161 	    ps2 = ps + 1;
15162 	    while (*pl2 == *ps2)
15163 	    {
15164 		++pl2;
15165 		++ps2;
15166 	    }
15167 	    if (STRCMP(pl2 + 1, ps2) == 0)
15168 		return score + SCORE_INS + SCORE_DEL;
15169 
15170 	    /* 9: delete then insert */
15171 	    pl2 = pl + 1;
15172 	    ps2 = ps;
15173 	    while (*pl2 == *ps2)
15174 	    {
15175 		++pl2;
15176 		++ps2;
15177 	    }
15178 	    if (STRCMP(pl2, ps2 + 1) == 0)
15179 		return score + SCORE_INS + SCORE_DEL;
15180 
15181 	    /* Failed to compare. */
15182 	    break;
15183     }
15184 
15185     return SCORE_MAXMAX;
15186 }
15187 
15188 /*
15189  * Compute the "edit distance" to turn "badword" into "goodword".  The less
15190  * deletes/inserts/substitutes/swaps are required the lower the score.
15191  *
15192  * The algorithm is described by Du and Chang, 1992.
15193  * The implementation of the algorithm comes from Aspell editdist.cpp,
15194  * edit_distance().  It has been converted from C++ to C and modified to
15195  * support multi-byte characters.
15196  */
15197     static int
15198 spell_edit_score(slang, badword, goodword)
15199     slang_T	*slang;
15200     char_u	*badword;
15201     char_u	*goodword;
15202 {
15203     int		*cnt;
15204     int		badlen, goodlen;	/* lengths including NUL */
15205     int		j, i;
15206     int		t;
15207     int		bc, gc;
15208     int		pbc, pgc;
15209 #ifdef FEAT_MBYTE
15210     char_u	*p;
15211     int		wbadword[MAXWLEN];
15212     int		wgoodword[MAXWLEN];
15213 
15214     if (has_mbyte)
15215     {
15216 	/* Get the characters from the multi-byte strings and put them in an
15217 	 * int array for easy access. */
15218 	for (p = badword, badlen = 0; *p != NUL; )
15219 	    wbadword[badlen++] = mb_cptr2char_adv(&p);
15220 	wbadword[badlen++] = 0;
15221 	for (p = goodword, goodlen = 0; *p != NUL; )
15222 	    wgoodword[goodlen++] = mb_cptr2char_adv(&p);
15223 	wgoodword[goodlen++] = 0;
15224     }
15225     else
15226 #endif
15227     {
15228 	badlen = (int)STRLEN(badword) + 1;
15229 	goodlen = (int)STRLEN(goodword) + 1;
15230     }
15231 
15232     /* We use "cnt" as an array: CNT(badword_idx, goodword_idx). */
15233 #define CNT(a, b)   cnt[(a) + (b) * (badlen + 1)]
15234     cnt = (int *)lalloc((long_u)(sizeof(int) * (badlen + 1) * (goodlen + 1)),
15235 									TRUE);
15236     if (cnt == NULL)
15237 	return 0;	/* out of memory */
15238 
15239     CNT(0, 0) = 0;
15240     for (j = 1; j <= goodlen; ++j)
15241 	CNT(0, j) = CNT(0, j - 1) + SCORE_INS;
15242 
15243     for (i = 1; i <= badlen; ++i)
15244     {
15245 	CNT(i, 0) = CNT(i - 1, 0) + SCORE_DEL;
15246 	for (j = 1; j <= goodlen; ++j)
15247 	{
15248 #ifdef FEAT_MBYTE
15249 	    if (has_mbyte)
15250 	    {
15251 		bc = wbadword[i - 1];
15252 		gc = wgoodword[j - 1];
15253 	    }
15254 	    else
15255 #endif
15256 	    {
15257 		bc = badword[i - 1];
15258 		gc = goodword[j - 1];
15259 	    }
15260 	    if (bc == gc)
15261 		CNT(i, j) = CNT(i - 1, j - 1);
15262 	    else
15263 	    {
15264 		/* Use a better score when there is only a case difference. */
15265 		if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15266 		    CNT(i, j) = SCORE_ICASE + CNT(i - 1, j - 1);
15267 		else
15268 		{
15269 		    /* For a similar character use SCORE_SIMILAR. */
15270 		    if (slang != NULL
15271 			    && slang->sl_has_map
15272 			    && similar_chars(slang, gc, bc))
15273 			CNT(i, j) = SCORE_SIMILAR + CNT(i - 1, j - 1);
15274 		    else
15275 			CNT(i, j) = SCORE_SUBST + CNT(i - 1, j - 1);
15276 		}
15277 
15278 		if (i > 1 && j > 1)
15279 		{
15280 #ifdef FEAT_MBYTE
15281 		    if (has_mbyte)
15282 		    {
15283 			pbc = wbadword[i - 2];
15284 			pgc = wgoodword[j - 2];
15285 		    }
15286 		    else
15287 #endif
15288 		    {
15289 			pbc = badword[i - 2];
15290 			pgc = goodword[j - 2];
15291 		    }
15292 		    if (bc == pgc && pbc == gc)
15293 		    {
15294 			t = SCORE_SWAP + CNT(i - 2, j - 2);
15295 			if (t < CNT(i, j))
15296 			    CNT(i, j) = t;
15297 		    }
15298 		}
15299 		t = SCORE_DEL + CNT(i - 1, j);
15300 		if (t < CNT(i, j))
15301 		    CNT(i, j) = t;
15302 		t = SCORE_INS + CNT(i, j - 1);
15303 		if (t < CNT(i, j))
15304 		    CNT(i, j) = t;
15305 	    }
15306 	}
15307     }
15308 
15309     i = CNT(badlen - 1, goodlen - 1);
15310     vim_free(cnt);
15311     return i;
15312 }
15313 
15314 typedef struct
15315 {
15316     int		badi;
15317     int		goodi;
15318     int		score;
15319 } limitscore_T;
15320 
15321 /*
15322  * Like spell_edit_score(), but with a limit on the score to make it faster.
15323  * May return SCORE_MAXMAX when the score is higher than "limit".
15324  *
15325  * This uses a stack for the edits still to be tried.
15326  * The idea comes from Aspell leditdist.cpp.  Rewritten in C and added support
15327  * for multi-byte characters.
15328  */
15329     static int
15330 spell_edit_score_limit(slang, badword, goodword, limit)
15331     slang_T	*slang;
15332     char_u	*badword;
15333     char_u	*goodword;
15334     int		limit;
15335 {
15336     limitscore_T    stack[10];		/* allow for over 3 * 2 edits */
15337     int		    stackidx;
15338     int		    bi, gi;
15339     int		    bi2, gi2;
15340     int		    bc, gc;
15341     int		    score;
15342     int		    score_off;
15343     int		    minscore;
15344     int		    round;
15345 
15346 #ifdef FEAT_MBYTE
15347     /* Multi-byte characters require a bit more work, use a different function
15348      * to avoid testing "has_mbyte" quite often. */
15349     if (has_mbyte)
15350 	return spell_edit_score_limit_w(slang, badword, goodword, limit);
15351 #endif
15352 
15353     /*
15354      * The idea is to go from start to end over the words.  So long as
15355      * characters are equal just continue, this always gives the lowest score.
15356      * When there is a difference try several alternatives.  Each alternative
15357      * increases "score" for the edit distance.  Some of the alternatives are
15358      * pushed unto a stack and tried later, some are tried right away.  At the
15359      * end of the word the score for one alternative is known.  The lowest
15360      * possible score is stored in "minscore".
15361      */
15362     stackidx = 0;
15363     bi = 0;
15364     gi = 0;
15365     score = 0;
15366     minscore = limit + 1;
15367 
15368     for (;;)
15369     {
15370 	/* Skip over an equal part, score remains the same. */
15371 	for (;;)
15372 	{
15373 	    bc = badword[bi];
15374 	    gc = goodword[gi];
15375 	    if (bc != gc)	/* stop at a char that's different */
15376 		break;
15377 	    if (bc == NUL)	/* both words end */
15378 	    {
15379 		if (score < minscore)
15380 		    minscore = score;
15381 		goto pop;	/* do next alternative */
15382 	    }
15383 	    ++bi;
15384 	    ++gi;
15385 	}
15386 
15387 	if (gc == NUL)    /* goodword ends, delete badword chars */
15388 	{
15389 	    do
15390 	    {
15391 		if ((score += SCORE_DEL) >= minscore)
15392 		    goto pop;	    /* do next alternative */
15393 	    } while (badword[++bi] != NUL);
15394 	    minscore = score;
15395 	}
15396 	else if (bc == NUL) /* badword ends, insert badword chars */
15397 	{
15398 	    do
15399 	    {
15400 		if ((score += SCORE_INS) >= minscore)
15401 		    goto pop;	    /* do next alternative */
15402 	    } while (goodword[++gi] != NUL);
15403 	    minscore = score;
15404 	}
15405 	else			/* both words continue */
15406 	{
15407 	    /* If not close to the limit, perform a change.  Only try changes
15408 	     * that may lead to a lower score than "minscore".
15409 	     * round 0: try deleting a char from badword
15410 	     * round 1: try inserting a char in badword */
15411 	    for (round = 0; round <= 1; ++round)
15412 	    {
15413 		score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
15414 		if (score_off < minscore)
15415 		{
15416 		    if (score_off + SCORE_EDIT_MIN >= minscore)
15417 		    {
15418 			/* Near the limit, rest of the words must match.  We
15419 			 * can check that right now, no need to push an item
15420 			 * onto the stack. */
15421 			bi2 = bi + 1 - round;
15422 			gi2 = gi + round;
15423 			while (goodword[gi2] == badword[bi2])
15424 			{
15425 			    if (goodword[gi2] == NUL)
15426 			    {
15427 				minscore = score_off;
15428 				break;
15429 			    }
15430 			    ++bi2;
15431 			    ++gi2;
15432 			}
15433 		    }
15434 		    else
15435 		    {
15436 			/* try deleting/inserting a character later */
15437 			stack[stackidx].badi = bi + 1 - round;
15438 			stack[stackidx].goodi = gi + round;
15439 			stack[stackidx].score = score_off;
15440 			++stackidx;
15441 		    }
15442 		}
15443 	    }
15444 
15445 	    if (score + SCORE_SWAP < minscore)
15446 	    {
15447 		/* If swapping two characters makes a match then the
15448 		 * substitution is more expensive, thus there is no need to
15449 		 * try both. */
15450 		if (gc == badword[bi + 1] && bc == goodword[gi + 1])
15451 		{
15452 		    /* Swap two characters, that is: skip them. */
15453 		    gi += 2;
15454 		    bi += 2;
15455 		    score += SCORE_SWAP;
15456 		    continue;
15457 		}
15458 	    }
15459 
15460 	    /* Substitute one character for another which is the same
15461 	     * thing as deleting a character from both goodword and badword.
15462 	     * Use a better score when there is only a case difference. */
15463 	    if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15464 		score += SCORE_ICASE;
15465 	    else
15466 	    {
15467 		/* For a similar character use SCORE_SIMILAR. */
15468 		if (slang != NULL
15469 			&& slang->sl_has_map
15470 			&& similar_chars(slang, gc, bc))
15471 		    score += SCORE_SIMILAR;
15472 		else
15473 		    score += SCORE_SUBST;
15474 	    }
15475 
15476 	    if (score < minscore)
15477 	    {
15478 		/* Do the substitution. */
15479 		++gi;
15480 		++bi;
15481 		continue;
15482 	    }
15483 	}
15484 pop:
15485 	/*
15486 	 * Get here to try the next alternative, pop it from the stack.
15487 	 */
15488 	if (stackidx == 0)		/* stack is empty, finished */
15489 	    break;
15490 
15491 	/* pop an item from the stack */
15492 	--stackidx;
15493 	gi = stack[stackidx].goodi;
15494 	bi = stack[stackidx].badi;
15495 	score = stack[stackidx].score;
15496     }
15497 
15498     /* When the score goes over "limit" it may actually be much higher.
15499      * Return a very large number to avoid going below the limit when giving a
15500      * bonus. */
15501     if (minscore > limit)
15502 	return SCORE_MAXMAX;
15503     return minscore;
15504 }
15505 
15506 #ifdef FEAT_MBYTE
15507 /*
15508  * Multi-byte version of spell_edit_score_limit().
15509  * Keep it in sync with the above!
15510  */
15511     static int
15512 spell_edit_score_limit_w(slang, badword, goodword, limit)
15513     slang_T	*slang;
15514     char_u	*badword;
15515     char_u	*goodword;
15516     int		limit;
15517 {
15518     limitscore_T    stack[10];		/* allow for over 3 * 2 edits */
15519     int		    stackidx;
15520     int		    bi, gi;
15521     int		    bi2, gi2;
15522     int		    bc, gc;
15523     int		    score;
15524     int		    score_off;
15525     int		    minscore;
15526     int		    round;
15527     char_u	    *p;
15528     int		    wbadword[MAXWLEN];
15529     int		    wgoodword[MAXWLEN];
15530 
15531     /* Get the characters from the multi-byte strings and put them in an
15532      * int array for easy access. */
15533     bi = 0;
15534     for (p = badword; *p != NUL; )
15535 	wbadword[bi++] = mb_cptr2char_adv(&p);
15536     wbadword[bi++] = 0;
15537     gi = 0;
15538     for (p = goodword; *p != NUL; )
15539 	wgoodword[gi++] = mb_cptr2char_adv(&p);
15540     wgoodword[gi++] = 0;
15541 
15542     /*
15543      * The idea is to go from start to end over the words.  So long as
15544      * characters are equal just continue, this always gives the lowest score.
15545      * When there is a difference try several alternatives.  Each alternative
15546      * increases "score" for the edit distance.  Some of the alternatives are
15547      * pushed unto a stack and tried later, some are tried right away.  At the
15548      * end of the word the score for one alternative is known.  The lowest
15549      * possible score is stored in "minscore".
15550      */
15551     stackidx = 0;
15552     bi = 0;
15553     gi = 0;
15554     score = 0;
15555     minscore = limit + 1;
15556 
15557     for (;;)
15558     {
15559 	/* Skip over an equal part, score remains the same. */
15560 	for (;;)
15561 	{
15562 	    bc = wbadword[bi];
15563 	    gc = wgoodword[gi];
15564 
15565 	    if (bc != gc)	/* stop at a char that's different */
15566 		break;
15567 	    if (bc == NUL)	/* both words end */
15568 	    {
15569 		if (score < minscore)
15570 		    minscore = score;
15571 		goto pop;	/* do next alternative */
15572 	    }
15573 	    ++bi;
15574 	    ++gi;
15575 	}
15576 
15577 	if (gc == NUL)    /* goodword ends, delete badword chars */
15578 	{
15579 	    do
15580 	    {
15581 		if ((score += SCORE_DEL) >= minscore)
15582 		    goto pop;	    /* do next alternative */
15583 	    } while (wbadword[++bi] != NUL);
15584 	    minscore = score;
15585 	}
15586 	else if (bc == NUL) /* badword ends, insert badword chars */
15587 	{
15588 	    do
15589 	    {
15590 		if ((score += SCORE_INS) >= minscore)
15591 		    goto pop;	    /* do next alternative */
15592 	    } while (wgoodword[++gi] != NUL);
15593 	    minscore = score;
15594 	}
15595 	else			/* both words continue */
15596 	{
15597 	    /* If not close to the limit, perform a change.  Only try changes
15598 	     * that may lead to a lower score than "minscore".
15599 	     * round 0: try deleting a char from badword
15600 	     * round 1: try inserting a char in badword */
15601 	    for (round = 0; round <= 1; ++round)
15602 	    {
15603 		score_off = score + (round == 0 ? SCORE_DEL : SCORE_INS);
15604 		if (score_off < minscore)
15605 		{
15606 		    if (score_off + SCORE_EDIT_MIN >= minscore)
15607 		    {
15608 			/* Near the limit, rest of the words must match.  We
15609 			 * can check that right now, no need to push an item
15610 			 * onto the stack. */
15611 			bi2 = bi + 1 - round;
15612 			gi2 = gi + round;
15613 			while (wgoodword[gi2] == wbadword[bi2])
15614 			{
15615 			    if (wgoodword[gi2] == NUL)
15616 			    {
15617 				minscore = score_off;
15618 				break;
15619 			    }
15620 			    ++bi2;
15621 			    ++gi2;
15622 			}
15623 		    }
15624 		    else
15625 		    {
15626 			/* try deleting a character from badword later */
15627 			stack[stackidx].badi = bi + 1 - round;
15628 			stack[stackidx].goodi = gi + round;
15629 			stack[stackidx].score = score_off;
15630 			++stackidx;
15631 		    }
15632 		}
15633 	    }
15634 
15635 	    if (score + SCORE_SWAP < minscore)
15636 	    {
15637 		/* If swapping two characters makes a match then the
15638 		 * substitution is more expensive, thus there is no need to
15639 		 * try both. */
15640 		if (gc == wbadword[bi + 1] && bc == wgoodword[gi + 1])
15641 		{
15642 		    /* Swap two characters, that is: skip them. */
15643 		    gi += 2;
15644 		    bi += 2;
15645 		    score += SCORE_SWAP;
15646 		    continue;
15647 		}
15648 	    }
15649 
15650 	    /* Substitute one character for another which is the same
15651 	     * thing as deleting a character from both goodword and badword.
15652 	     * Use a better score when there is only a case difference. */
15653 	    if (SPELL_TOFOLD(bc) == SPELL_TOFOLD(gc))
15654 		score += SCORE_ICASE;
15655 	    else
15656 	    {
15657 		/* For a similar character use SCORE_SIMILAR. */
15658 		if (slang != NULL
15659 			&& slang->sl_has_map
15660 			&& similar_chars(slang, gc, bc))
15661 		    score += SCORE_SIMILAR;
15662 		else
15663 		    score += SCORE_SUBST;
15664 	    }
15665 
15666 	    if (score < minscore)
15667 	    {
15668 		/* Do the substitution. */
15669 		++gi;
15670 		++bi;
15671 		continue;
15672 	    }
15673 	}
15674 pop:
15675 	/*
15676 	 * Get here to try the next alternative, pop it from the stack.
15677 	 */
15678 	if (stackidx == 0)		/* stack is empty, finished */
15679 	    break;
15680 
15681 	/* pop an item from the stack */
15682 	--stackidx;
15683 	gi = stack[stackidx].goodi;
15684 	bi = stack[stackidx].badi;
15685 	score = stack[stackidx].score;
15686     }
15687 
15688     /* When the score goes over "limit" it may actually be much higher.
15689      * Return a very large number to avoid going below the limit when giving a
15690      * bonus. */
15691     if (minscore > limit)
15692 	return SCORE_MAXMAX;
15693     return minscore;
15694 }
15695 #endif
15696 
15697 /*
15698  * ":spellinfo"
15699  */
15700     void
15701 ex_spellinfo(eap)
15702     exarg_T *eap UNUSED;
15703 {
15704     int		lpi;
15705     langp_T	*lp;
15706     char_u	*p;
15707 
15708     if (no_spell_checking(curwin))
15709 	return;
15710 
15711     msg_start();
15712     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len && !got_int; ++lpi)
15713     {
15714 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
15715 	msg_puts((char_u *)"file: ");
15716 	msg_puts(lp->lp_slang->sl_fname);
15717 	msg_putchar('\n');
15718 	p = lp->lp_slang->sl_info;
15719 	if (p != NULL)
15720 	{
15721 	    msg_puts(p);
15722 	    msg_putchar('\n');
15723 	}
15724     }
15725     msg_end();
15726 }
15727 
15728 #define DUMPFLAG_KEEPCASE   1	/* round 2: keep-case tree */
15729 #define DUMPFLAG_COUNT	    2	/* include word count */
15730 #define DUMPFLAG_ICASE	    4	/* ignore case when finding matches */
15731 #define DUMPFLAG_ONECAP	    8	/* pattern starts with capital */
15732 #define DUMPFLAG_ALLCAP	    16	/* pattern is all capitals */
15733 
15734 /*
15735  * ":spelldump"
15736  */
15737     void
15738 ex_spelldump(eap)
15739     exarg_T *eap;
15740 {
15741     char_u  *spl;
15742     long    dummy;
15743 
15744     if (no_spell_checking(curwin))
15745 	return;
15746     get_option_value((char_u*)"spl", &dummy, &spl, OPT_LOCAL);
15747 
15748     /* Create a new empty buffer in a new window. */
15749     do_cmdline_cmd((char_u *)"new");
15750 
15751     /* enable spelling locally in the new window */
15752     set_option_value((char_u*)"spell", TRUE, (char_u*)"", OPT_LOCAL);
15753     set_option_value((char_u*)"spl",  dummy, spl, OPT_LOCAL);
15754     vim_free(spl);
15755 
15756     if (!bufempty() || !buf_valid(curbuf))
15757 	return;
15758 
15759     spell_dump_compl(NULL, 0, NULL, eap->forceit ? DUMPFLAG_COUNT : 0);
15760 
15761     /* Delete the empty line that we started with. */
15762     if (curbuf->b_ml.ml_line_count > 1)
15763 	ml_delete(curbuf->b_ml.ml_line_count, FALSE);
15764 
15765     redraw_later(NOT_VALID);
15766 }
15767 
15768 /*
15769  * Go through all possible words and:
15770  * 1. When "pat" is NULL: dump a list of all words in the current buffer.
15771  *	"ic" and "dir" are not used.
15772  * 2. When "pat" is not NULL: add matching words to insert mode completion.
15773  */
15774     void
15775 spell_dump_compl(pat, ic, dir, dumpflags_arg)
15776     char_u	*pat;	    /* leading part of the word */
15777     int		ic;	    /* ignore case */
15778     int		*dir;	    /* direction for adding matches */
15779     int		dumpflags_arg;	/* DUMPFLAG_* */
15780 {
15781     langp_T	*lp;
15782     slang_T	*slang;
15783     idx_T	arridx[MAXWLEN];
15784     int		curi[MAXWLEN];
15785     char_u	word[MAXWLEN];
15786     int		c;
15787     char_u	*byts;
15788     idx_T	*idxs;
15789     linenr_T	lnum = 0;
15790     int		round;
15791     int		depth;
15792     int		n;
15793     int		flags;
15794     char_u	*region_names = NULL;	    /* region names being used */
15795     int		do_region = TRUE;	    /* dump region names and numbers */
15796     char_u	*p;
15797     int		lpi;
15798     int		dumpflags = dumpflags_arg;
15799     int		patlen;
15800 
15801     /* When ignoring case or when the pattern starts with capital pass this on
15802      * to dump_word(). */
15803     if (pat != NULL)
15804     {
15805 	if (ic)
15806 	    dumpflags |= DUMPFLAG_ICASE;
15807 	else
15808 	{
15809 	    n = captype(pat, NULL);
15810 	    if (n == WF_ONECAP)
15811 		dumpflags |= DUMPFLAG_ONECAP;
15812 	    else if (n == WF_ALLCAP
15813 #ifdef FEAT_MBYTE
15814 		    && (int)STRLEN(pat) > mb_ptr2len(pat)
15815 #else
15816 		    && (int)STRLEN(pat) > 1
15817 #endif
15818 		    )
15819 		dumpflags |= DUMPFLAG_ALLCAP;
15820 	}
15821     }
15822 
15823     /* Find out if we can support regions: All languages must support the same
15824      * regions or none at all. */
15825     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
15826     {
15827 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
15828 	p = lp->lp_slang->sl_regions;
15829 	if (p[0] != 0)
15830 	{
15831 	    if (region_names == NULL)	    /* first language with regions */
15832 		region_names = p;
15833 	    else if (STRCMP(region_names, p) != 0)
15834 	    {
15835 		do_region = FALSE;	    /* region names are different */
15836 		break;
15837 	    }
15838 	}
15839     }
15840 
15841     if (do_region && region_names != NULL)
15842     {
15843 	if (pat == NULL)
15844 	{
15845 	    vim_snprintf((char *)IObuff, IOSIZE, "/regions=%s", region_names);
15846 	    ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
15847 	}
15848     }
15849     else
15850 	do_region = FALSE;
15851 
15852     /*
15853      * Loop over all files loaded for the entries in 'spelllang'.
15854      */
15855     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
15856     {
15857 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
15858 	slang = lp->lp_slang;
15859 	if (slang->sl_fbyts == NULL)	    /* reloading failed */
15860 	    continue;
15861 
15862 	if (pat == NULL)
15863 	{
15864 	    vim_snprintf((char *)IObuff, IOSIZE, "# file: %s", slang->sl_fname);
15865 	    ml_append(lnum++, IObuff, (colnr_T)0, FALSE);
15866 	}
15867 
15868 	/* When matching with a pattern and there are no prefixes only use
15869 	 * parts of the tree that match "pat". */
15870 	if (pat != NULL && slang->sl_pbyts == NULL)
15871 	    patlen = (int)STRLEN(pat);
15872 	else
15873 	    patlen = -1;
15874 
15875 	/* round 1: case-folded tree
15876 	 * round 2: keep-case tree */
15877 	for (round = 1; round <= 2; ++round)
15878 	{
15879 	    if (round == 1)
15880 	    {
15881 		dumpflags &= ~DUMPFLAG_KEEPCASE;
15882 		byts = slang->sl_fbyts;
15883 		idxs = slang->sl_fidxs;
15884 	    }
15885 	    else
15886 	    {
15887 		dumpflags |= DUMPFLAG_KEEPCASE;
15888 		byts = slang->sl_kbyts;
15889 		idxs = slang->sl_kidxs;
15890 	    }
15891 	    if (byts == NULL)
15892 		continue;		/* array is empty */
15893 
15894 	    depth = 0;
15895 	    arridx[0] = 0;
15896 	    curi[0] = 1;
15897 	    while (depth >= 0 && !got_int
15898 				       && (pat == NULL || !compl_interrupted))
15899 	    {
15900 		if (curi[depth] > byts[arridx[depth]])
15901 		{
15902 		    /* Done all bytes at this node, go up one level. */
15903 		    --depth;
15904 		    line_breakcheck();
15905 		    ins_compl_check_keys(50);
15906 		}
15907 		else
15908 		{
15909 		    /* Do one more byte at this node. */
15910 		    n = arridx[depth] + curi[depth];
15911 		    ++curi[depth];
15912 		    c = byts[n];
15913 		    if (c == 0)
15914 		    {
15915 			/* End of word, deal with the word.
15916 			 * Don't use keep-case words in the fold-case tree,
15917 			 * they will appear in the keep-case tree.
15918 			 * Only use the word when the region matches. */
15919 			flags = (int)idxs[n];
15920 			if ((round == 2 || (flags & WF_KEEPCAP) == 0)
15921 				&& (flags & WF_NEEDCOMP) == 0
15922 				&& (do_region
15923 				    || (flags & WF_REGION) == 0
15924 				    || (((unsigned)flags >> 16)
15925 						       & lp->lp_region) != 0))
15926 			{
15927 			    word[depth] = NUL;
15928 			    if (!do_region)
15929 				flags &= ~WF_REGION;
15930 
15931 			    /* Dump the basic word if there is no prefix or
15932 			     * when it's the first one. */
15933 			    c = (unsigned)flags >> 24;
15934 			    if (c == 0 || curi[depth] == 2)
15935 			    {
15936 				dump_word(slang, word, pat, dir,
15937 						      dumpflags, flags, lnum);
15938 				if (pat == NULL)
15939 				    ++lnum;
15940 			    }
15941 
15942 			    /* Apply the prefix, if there is one. */
15943 			    if (c != 0)
15944 				lnum = dump_prefixes(slang, word, pat, dir,
15945 						      dumpflags, flags, lnum);
15946 			}
15947 		    }
15948 		    else
15949 		    {
15950 			/* Normal char, go one level deeper. */
15951 			word[depth++] = c;
15952 			arridx[depth] = idxs[n];
15953 			curi[depth] = 1;
15954 
15955 			/* Check if this characters matches with the pattern.
15956 			 * If not skip the whole tree below it.
15957 			 * Always ignore case here, dump_word() will check
15958 			 * proper case later.  This isn't exactly right when
15959 			 * length changes for multi-byte characters with
15960 			 * ignore case... */
15961 			if (depth <= patlen
15962 					&& MB_STRNICMP(word, pat, depth) != 0)
15963 			    --depth;
15964 		    }
15965 		}
15966 	    }
15967 	}
15968     }
15969 }
15970 
15971 /*
15972  * Dump one word: apply case modifications and append a line to the buffer.
15973  * When "lnum" is zero add insert mode completion.
15974  */
15975     static void
15976 dump_word(slang, word, pat, dir, dumpflags, wordflags, lnum)
15977     slang_T	*slang;
15978     char_u	*word;
15979     char_u	*pat;
15980     int		*dir;
15981     int		dumpflags;
15982     int		wordflags;
15983     linenr_T	lnum;
15984 {
15985     int		keepcap = FALSE;
15986     char_u	*p;
15987     char_u	*tw;
15988     char_u	cword[MAXWLEN];
15989     char_u	badword[MAXWLEN + 10];
15990     int		i;
15991     int		flags = wordflags;
15992 
15993     if (dumpflags & DUMPFLAG_ONECAP)
15994 	flags |= WF_ONECAP;
15995     if (dumpflags & DUMPFLAG_ALLCAP)
15996 	flags |= WF_ALLCAP;
15997 
15998     if ((dumpflags & DUMPFLAG_KEEPCASE) == 0 && (flags & WF_CAPMASK) != 0)
15999     {
16000 	/* Need to fix case according to "flags". */
16001 	make_case_word(word, cword, flags);
16002 	p = cword;
16003     }
16004     else
16005     {
16006 	p = word;
16007 	if ((dumpflags & DUMPFLAG_KEEPCASE)
16008 		&& ((captype(word, NULL) & WF_KEEPCAP) == 0
16009 						 || (flags & WF_FIXCAP) != 0))
16010 	    keepcap = TRUE;
16011     }
16012     tw = p;
16013 
16014     if (pat == NULL)
16015     {
16016 	/* Add flags and regions after a slash. */
16017 	if ((flags & (WF_BANNED | WF_RARE | WF_REGION)) || keepcap)
16018 	{
16019 	    STRCPY(badword, p);
16020 	    STRCAT(badword, "/");
16021 	    if (keepcap)
16022 		STRCAT(badword, "=");
16023 	    if (flags & WF_BANNED)
16024 		STRCAT(badword, "!");
16025 	    else if (flags & WF_RARE)
16026 		STRCAT(badword, "?");
16027 	    if (flags & WF_REGION)
16028 		for (i = 0; i < 7; ++i)
16029 		    if (flags & (0x10000 << i))
16030 			sprintf((char *)badword + STRLEN(badword), "%d", i + 1);
16031 	    p = badword;
16032 	}
16033 
16034 	if (dumpflags & DUMPFLAG_COUNT)
16035 	{
16036 	    hashitem_T  *hi;
16037 
16038 	    /* Include the word count for ":spelldump!". */
16039 	    hi = hash_find(&slang->sl_wordcount, tw);
16040 	    if (!HASHITEM_EMPTY(hi))
16041 	    {
16042 		vim_snprintf((char *)IObuff, IOSIZE, "%s\t%d",
16043 						     tw, HI2WC(hi)->wc_count);
16044 		p = IObuff;
16045 	    }
16046 	}
16047 
16048 	ml_append(lnum, p, (colnr_T)0, FALSE);
16049     }
16050     else if (((dumpflags & DUMPFLAG_ICASE)
16051 		    ? MB_STRNICMP(p, pat, STRLEN(pat)) == 0
16052 		    : STRNCMP(p, pat, STRLEN(pat)) == 0)
16053 		&& ins_compl_add_infercase(p, (int)STRLEN(p),
16054 					  p_ic, NULL, *dir, 0) == OK)
16055 	/* if dir was BACKWARD then honor it just once */
16056 	*dir = FORWARD;
16057 }
16058 
16059 /*
16060  * For ":spelldump": Find matching prefixes for "word".  Prepend each to
16061  * "word" and append a line to the buffer.
16062  * When "lnum" is zero add insert mode completion.
16063  * Return the updated line number.
16064  */
16065     static linenr_T
16066 dump_prefixes(slang, word, pat, dir, dumpflags, flags, startlnum)
16067     slang_T	*slang;
16068     char_u	*word;	    /* case-folded word */
16069     char_u	*pat;
16070     int		*dir;
16071     int		dumpflags;
16072     int		flags;	    /* flags with prefix ID */
16073     linenr_T	startlnum;
16074 {
16075     idx_T	arridx[MAXWLEN];
16076     int		curi[MAXWLEN];
16077     char_u	prefix[MAXWLEN];
16078     char_u	word_up[MAXWLEN];
16079     int		has_word_up = FALSE;
16080     int		c;
16081     char_u	*byts;
16082     idx_T	*idxs;
16083     linenr_T	lnum = startlnum;
16084     int		depth;
16085     int		n;
16086     int		len;
16087     int		i;
16088 
16089     /* If the word starts with a lower-case letter make the word with an
16090      * upper-case letter in word_up[]. */
16091     c = PTR2CHAR(word);
16092     if (SPELL_TOUPPER(c) != c)
16093     {
16094 	onecap_copy(word, word_up, TRUE);
16095 	has_word_up = TRUE;
16096     }
16097 
16098     byts = slang->sl_pbyts;
16099     idxs = slang->sl_pidxs;
16100     if (byts != NULL)		/* array not is empty */
16101     {
16102 	/*
16103 	 * Loop over all prefixes, building them byte-by-byte in prefix[].
16104 	 * When at the end of a prefix check that it supports "flags".
16105 	 */
16106 	depth = 0;
16107 	arridx[0] = 0;
16108 	curi[0] = 1;
16109 	while (depth >= 0 && !got_int)
16110 	{
16111 	    n = arridx[depth];
16112 	    len = byts[n];
16113 	    if (curi[depth] > len)
16114 	    {
16115 		/* Done all bytes at this node, go up one level. */
16116 		--depth;
16117 		line_breakcheck();
16118 	    }
16119 	    else
16120 	    {
16121 		/* Do one more byte at this node. */
16122 		n += curi[depth];
16123 		++curi[depth];
16124 		c = byts[n];
16125 		if (c == 0)
16126 		{
16127 		    /* End of prefix, find out how many IDs there are. */
16128 		    for (i = 1; i < len; ++i)
16129 			if (byts[n + i] != 0)
16130 			    break;
16131 		    curi[depth] += i - 1;
16132 
16133 		    c = valid_word_prefix(i, n, flags, word, slang, FALSE);
16134 		    if (c != 0)
16135 		    {
16136 			vim_strncpy(prefix + depth, word, MAXWLEN - depth - 1);
16137 			dump_word(slang, prefix, pat, dir, dumpflags,
16138 				(c & WF_RAREPFX) ? (flags | WF_RARE)
16139 							       : flags, lnum);
16140 			if (lnum != 0)
16141 			    ++lnum;
16142 		    }
16143 
16144 		    /* Check for prefix that matches the word when the
16145 		     * first letter is upper-case, but only if the prefix has
16146 		     * a condition. */
16147 		    if (has_word_up)
16148 		    {
16149 			c = valid_word_prefix(i, n, flags, word_up, slang,
16150 									TRUE);
16151 			if (c != 0)
16152 			{
16153 			    vim_strncpy(prefix + depth, word_up,
16154 							 MAXWLEN - depth - 1);
16155 			    dump_word(slang, prefix, pat, dir, dumpflags,
16156 				    (c & WF_RAREPFX) ? (flags | WF_RARE)
16157 							       : flags, lnum);
16158 			    if (lnum != 0)
16159 				++lnum;
16160 			}
16161 		    }
16162 		}
16163 		else
16164 		{
16165 		    /* Normal char, go one level deeper. */
16166 		    prefix[depth++] = c;
16167 		    arridx[depth] = idxs[n];
16168 		    curi[depth] = 1;
16169 		}
16170 	    }
16171 	}
16172     }
16173 
16174     return lnum;
16175 }
16176 
16177 /*
16178  * Move "p" to the end of word "start".
16179  * Uses the spell-checking word characters.
16180  */
16181     char_u *
16182 spell_to_word_end(start, win)
16183     char_u  *start;
16184     win_T   *win;
16185 {
16186     char_u  *p = start;
16187 
16188     while (*p != NUL && spell_iswordp(p, win))
16189 	mb_ptr_adv(p);
16190     return p;
16191 }
16192 
16193 #if defined(FEAT_INS_EXPAND) || defined(PROTO)
16194 /*
16195  * For Insert mode completion CTRL-X s:
16196  * Find start of the word in front of column "startcol".
16197  * We don't check if it is badly spelled, with completion we can only change
16198  * the word in front of the cursor.
16199  * Returns the column number of the word.
16200  */
16201     int
16202 spell_word_start(startcol)
16203     int		startcol;
16204 {
16205     char_u	*line;
16206     char_u	*p;
16207     int		col = 0;
16208 
16209     if (no_spell_checking(curwin))
16210 	return startcol;
16211 
16212     /* Find a word character before "startcol". */
16213     line = ml_get_curline();
16214     for (p = line + startcol; p > line; )
16215     {
16216 	mb_ptr_back(line, p);
16217 	if (spell_iswordp_nmw(p, curwin))
16218 	    break;
16219     }
16220 
16221     /* Go back to start of the word. */
16222     while (p > line)
16223     {
16224 	col = (int)(p - line);
16225 	mb_ptr_back(line, p);
16226 	if (!spell_iswordp(p, curwin))
16227 	    break;
16228 	col = 0;
16229     }
16230 
16231     return col;
16232 }
16233 
16234 /*
16235  * Need to check for 'spellcapcheck' now, the word is removed before
16236  * expand_spelling() is called.  Therefore the ugly global variable.
16237  */
16238 static int spell_expand_need_cap;
16239 
16240     void
16241 spell_expand_check_cap(col)
16242     colnr_T col;
16243 {
16244     spell_expand_need_cap = check_need_cap(curwin->w_cursor.lnum, col);
16245 }
16246 
16247 /*
16248  * Get list of spelling suggestions.
16249  * Used for Insert mode completion CTRL-X ?.
16250  * Returns the number of matches.  The matches are in "matchp[]", array of
16251  * allocated strings.
16252  */
16253     int
16254 expand_spelling(lnum, pat, matchp)
16255     linenr_T	lnum UNUSED;
16256     char_u	*pat;
16257     char_u	***matchp;
16258 {
16259     garray_T	ga;
16260 
16261     spell_suggest_list(&ga, pat, 100, spell_expand_need_cap, TRUE);
16262     *matchp = ga.ga_data;
16263     return ga.ga_len;
16264 }
16265 #endif
16266 
16267 #endif  /* FEAT_SPELL */
16268