xref: /vim-8.2.3635/src/spellfile.c (revision ed37d9b3)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * spellfile.c: code for reading and writing spell files.
12  *
13  * See spell.c for information about spell checking.
14  */
15 
16 /*
17  * Vim spell file format: <HEADER>
18  *			  <SECTIONS>
19  *			  <LWORDTREE>
20  *			  <KWORDTREE>
21  *			  <PREFIXTREE>
22  *
23  * <HEADER>: <fileID> <versionnr>
24  *
25  * <fileID>     8 bytes    "VIMspell"
26  * <versionnr>  1 byte	    VIMSPELLVERSION
27  *
28  *
29  * Sections make it possible to add information to the .spl file without
30  * making it incompatible with previous versions.  There are two kinds of
31  * sections:
32  * 1. Not essential for correct spell checking.  E.g. for making suggestions.
33  *    These are skipped when not supported.
34  * 2. Optional information, but essential for spell checking when present.
35  *    E.g. conditions for affixes.  When this section is present but not
36  *    supported an error message is given.
37  *
38  * <SECTIONS>: <section> ... <sectionend>
39  *
40  * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
41  *
42  * <sectionID>	  1 byte    number from 0 to 254 identifying the section
43  *
44  * <sectionflags> 1 byte    SNF_REQUIRED: this section is required for correct
45  *					    spell checking
46  *
47  * <sectionlen>   4 bytes   length of section contents, MSB first
48  *
49  * <sectionend>	  1 byte    SN_END
50  *
51  *
52  * sectionID == SN_INFO: <infotext>
53  * <infotext>	 N bytes    free format text with spell file info (version,
54  *			    website, etc)
55  *
56  * sectionID == SN_REGION: <regionname> ...
57  * <regionname>	 2 bytes    Up to MAXREGIONS region names: ca, au, etc.  Lower
58  *			    case.  First <regionname> is region 1.
59  *
60  * sectionID == SN_CHARFLAGS: <charflagslen> <charflags>
61  *				<folcharslen> <folchars>
62  * <charflagslen> 1 byte    Number of bytes in <charflags> (should be 128).
63  * <charflags>  N bytes     List of flags (first one is for character 128):
64  *			    0x01  word character	CF_WORD
65  *			    0x02  upper-case character	CF_UPPER
66  * <folcharslen>  2 bytes   Number of bytes in <folchars>.
67  * <folchars>     N bytes   Folded characters, first one is for character 128.
68  *
69  * sectionID == SN_MIDWORD: <midword>
70  * <midword>     N bytes    Characters that are word characters only when used
71  *			    in the middle of a word.
72  *
73  * sectionID == SN_PREFCOND: <prefcondcnt> <prefcond> ...
74  * <prefcondcnt> 2 bytes    Number of <prefcond> items following.
75  * <prefcond> : <condlen> <condstr>
76  * <condlen>	1 byte	    Length of <condstr>.
77  * <condstr>	N bytes	    Condition for the prefix.
78  *
79  * sectionID == SN_REP: <repcount> <rep> ...
80  * <repcount>	 2 bytes    number of <rep> items, MSB first.
81  * <rep> : <repfromlen> <repfrom> <reptolen> <repto>
82  * <repfromlen>	 1 byte	    length of <repfrom>
83  * <repfrom>	 N bytes    "from" part of replacement
84  * <reptolen>	 1 byte	    length of <repto>
85  * <repto>	 N bytes    "to" part of replacement
86  *
87  * sectionID == SN_REPSAL: <repcount> <rep> ...
88  *   just like SN_REP but for soundfolded words
89  *
90  * sectionID == SN_SAL: <salflags> <salcount> <sal> ...
91  * <salflags>	 1 byte	    flags for soundsalike conversion:
92  *			    SAL_F0LLOWUP
93  *			    SAL_COLLAPSE
94  *			    SAL_REM_ACCENTS
95  * <salcount>    2 bytes    number of <sal> items following
96  * <sal> : <salfromlen> <salfrom> <saltolen> <salto>
97  * <salfromlen>	 1 byte	    length of <salfrom>
98  * <salfrom>	 N bytes    "from" part of soundsalike
99  * <saltolen>	 1 byte	    length of <salto>
100  * <salto>	 N bytes    "to" part of soundsalike
101  *
102  * sectionID == SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
103  * <sofofromlen> 2 bytes    length of <sofofrom>
104  * <sofofrom>	 N bytes    "from" part of soundfold
105  * <sofotolen>	 2 bytes    length of <sofoto>
106  * <sofoto>	 N bytes    "to" part of soundfold
107  *
108  * sectionID == SN_SUGFILE: <timestamp>
109  * <timestamp>   8 bytes    time in seconds that must match with .sug file
110  *
111  * sectionID == SN_NOSPLITSUGS: nothing
112 	 *
113  * sectionID == SN_NOCOMPOUNDSUGS: nothing
114  *
115  * sectionID == SN_WORDS: <word> ...
116  * <word>	 N bytes    NUL terminated common word
117  *
118  * sectionID == SN_MAP: <mapstr>
119  * <mapstr>	 N bytes    String with sequences of similar characters,
120  *			    separated by slashes.
121  *
122  * sectionID == SN_COMPOUND: <compmax> <compminlen> <compsylmax> <compoptions>
123  *				<comppatcount> <comppattern> ... <compflags>
124  * <compmax>     1 byte	    Maximum nr of words in compound word.
125  * <compminlen>  1 byte	    Minimal word length for compounding.
126  * <compsylmax>  1 byte	    Maximum nr of syllables in compound word.
127  * <compoptions> 2 bytes    COMP_ flags.
128  * <comppatcount> 2 bytes   number of <comppattern> following
129  * <compflags>   N bytes    Flags from COMPOUNDRULE items, separated by
130  *			    slashes.
131  *
132  * <comppattern>: <comppatlen> <comppattext>
133  * <comppatlen>	 1 byte	    length of <comppattext>
134  * <comppattext> N bytes    end or begin chars from CHECKCOMPOUNDPATTERN
135  *
136  * sectionID == SN_NOBREAK: (empty, its presence is what matters)
137  *
138  * sectionID == SN_SYLLABLE: <syllable>
139  * <syllable>    N bytes    String from SYLLABLE item.
140  *
141  * <LWORDTREE>: <wordtree>
142  *
143  * <KWORDTREE>: <wordtree>
144  *
145  * <PREFIXTREE>: <wordtree>
146  *
147  *
148  * <wordtree>: <nodecount> <nodedata> ...
149  *
150  * <nodecount>	4 bytes	    Number of nodes following.  MSB first.
151  *
152  * <nodedata>: <siblingcount> <sibling> ...
153  *
154  * <siblingcount> 1 byte    Number of siblings in this node.  The siblings
155  *			    follow in sorted order.
156  *
157  * <sibling>: <byte> [ <nodeidx> <xbyte>
158  *		      | <flags> [<flags2>] [<region>] [<affixID>]
159  *		      | [<pflags>] <affixID> <prefcondnr> ]
160  *
161  * <byte>	1 byte	    Byte value of the sibling.  Special cases:
162  *			    BY_NOFLAGS: End of word without flags and for all
163  *					regions.
164  *					For PREFIXTREE <affixID> and
165  *					<prefcondnr> follow.
166  *			    BY_FLAGS:   End of word, <flags> follow.
167  *					For PREFIXTREE <pflags>, <affixID>
168  *					and <prefcondnr> follow.
169  *			    BY_FLAGS2:  End of word, <flags> and <flags2>
170  *					follow.  Not used in PREFIXTREE.
171  *			    BY_INDEX:   Child of sibling is shared, <nodeidx>
172  *					and <xbyte> follow.
173  *
174  * <nodeidx>	3 bytes	    Index of child for this sibling, MSB first.
175  *
176  * <xbyte>	1 byte	    byte value of the sibling.
177  *
178  * <flags>	1 byte	    bitmask of:
179  *			    WF_ALLCAP	word must have only capitals
180  *			    WF_ONECAP   first char of word must be capital
181  *			    WF_KEEPCAP	keep-case word
182  *			    WF_FIXCAP   keep-case word, all caps not allowed
183  *			    WF_RARE	rare word
184  *			    WF_BANNED	bad word
185  *			    WF_REGION	<region> follows
186  *			    WF_AFX	<affixID> follows
187  *
188  * <flags2>	1 byte	    Bitmask of:
189  *			    WF_HAS_AFF >> 8   word includes affix
190  *			    WF_NEEDCOMP >> 8  word only valid in compound
191  *			    WF_NOSUGGEST >> 8  word not used for suggestions
192  *			    WF_COMPROOT >> 8  word already a compound
193  *			    WF_NOCOMPBEF >> 8 no compounding before this word
194  *			    WF_NOCOMPAFT >> 8 no compounding after this word
195  *
196  * <pflags>	1 byte	    bitmask of:
197  *			    WFP_RARE	rare prefix
198  *			    WFP_NC	non-combining prefix
199  *			    WFP_UP	letter after prefix made upper case
200  *
201  * <region>	1 byte	    Bitmask for regions in which word is valid.  When
202  *			    omitted it's valid in all regions.
203  *			    Lowest bit is for region 1.
204  *
205  * <affixID>	1 byte	    ID of affix that can be used with this word.  In
206  *			    PREFIXTREE used for the required prefix ID.
207  *
208  * <prefcondnr>	2 bytes	    Prefix condition number, index in <prefcond> list
209  *			    from HEADER.
210  *
211  * All text characters are in 'encoding', but stored as single bytes.
212  */
213 
214 /*
215  * Vim .sug file format:  <SUGHEADER>
216  *			  <SUGWORDTREE>
217  *			  <SUGTABLE>
218  *
219  * <SUGHEADER>: <fileID> <versionnr> <timestamp>
220  *
221  * <fileID>     6 bytes     "VIMsug"
222  * <versionnr>  1 byte      VIMSUGVERSION
223  * <timestamp>  8 bytes     timestamp that must match with .spl file
224  *
225  *
226  * <SUGWORDTREE>: <wordtree>  (see above, no flags or region used)
227  *
228  *
229  * <SUGTABLE>: <sugwcount> <sugline> ...
230  *
231  * <sugwcount>	4 bytes	    number of <sugline> following
232  *
233  * <sugline>: <sugnr> ... NUL
234  *
235  * <sugnr>:     X bytes     word number that results in this soundfolded word,
236  *			    stored as an offset to the previous number in as
237  *			    few bytes as possible, see offset2bytes())
238  */
239 
240 #include "vim.h"
241 
242 #if defined(FEAT_SPELL) || defined(PROTO)
243 
244 #ifndef UNIX		// it's in os_unix.h for Unix
245 # include <time.h>	// for time_t
246 #endif
247 
248 #ifndef UNIX		// it's in os_unix.h for Unix
249 # include <time.h>	// for time_t
250 #endif
251 
252 // Special byte values for <byte>.  Some are only used in the tree for
253 // postponed prefixes, some only in the other trees.  This is a bit messy...
254 #define BY_NOFLAGS	0	// end of word without flags or region; for
255 				// postponed prefix: no <pflags>
256 #define BY_INDEX	1	// child is shared, index follows
257 #define BY_FLAGS	2	// end of word, <flags> byte follows; for
258 				// postponed prefix: <pflags> follows
259 #define BY_FLAGS2	3	// end of word, <flags> and <flags2> bytes
260 				// follow; never used in prefix tree
261 #define BY_SPECIAL  BY_FLAGS2	// highest special byte value
262 
263 #define ZERO_FLAG	65009	// used when flag is zero: "0"
264 
265 // Flags used in .spl file for soundsalike flags.
266 #define SAL_F0LLOWUP		1
267 #define SAL_COLLAPSE		2
268 #define SAL_REM_ACCENTS		4
269 
270 #define VIMSPELLMAGIC "VIMspell"  // string at start of Vim spell file
271 #define VIMSPELLMAGICL 8
272 #define VIMSPELLVERSION 50
273 
274 // Section IDs.  Only renumber them when VIMSPELLVERSION changes!
275 #define SN_REGION	0	// <regionname> section
276 #define SN_CHARFLAGS	1	// charflags section
277 #define SN_MIDWORD	2	// <midword> section
278 #define SN_PREFCOND	3	// <prefcond> section
279 #define SN_REP		4	// REP items section
280 #define SN_SAL		5	// SAL items section
281 #define SN_SOFO		6	// soundfolding section
282 #define SN_MAP		7	// MAP items section
283 #define SN_COMPOUND	8	// compound words section
284 #define SN_SYLLABLE	9	// syllable section
285 #define SN_NOBREAK	10	// NOBREAK section
286 #define SN_SUGFILE	11	// timestamp for .sug file
287 #define SN_REPSAL	12	// REPSAL items section
288 #define SN_WORDS	13	// common words
289 #define SN_NOSPLITSUGS	14	// don't split word for suggestions
290 #define SN_INFO		15	// info section
291 #define SN_NOCOMPOUNDSUGS 16	// don't compound for suggestions
292 #define SN_END		255	// end of sections
293 
294 #define SNF_REQUIRED	1	// <sectionflags>: required section
295 
296 #define CF_WORD		0x01
297 #define CF_UPPER	0x02
298 
299 /*
300  * Loop through all the siblings of a node (including the node)
301  */
302 #define FOR_ALL_NODE_SIBLINGS(node, np) \
303     for ((np) = (node); (np) != NULL; (np) = (np)->wn_sibling)
304 
305 static int set_spell_finish(spelltab_T	*new_st);
306 static int write_spell_prefcond(FILE *fd, garray_T *gap);
307 static int read_region_section(FILE *fd, slang_T *slang, int len);
308 static int read_charflags_section(FILE *fd);
309 static int read_prefcond_section(FILE *fd, slang_T *lp);
310 static int read_rep_section(FILE *fd, garray_T *gap, short *first);
311 static int read_sal_section(FILE *fd, slang_T *slang);
312 static int read_words_section(FILE *fd, slang_T *lp, int len);
313 static int read_sofo_section(FILE *fd, slang_T *slang);
314 static int read_compound(FILE *fd, slang_T *slang, int len);
315 static int set_sofo(slang_T *lp, char_u *from, char_u *to);
316 static void set_sal_first(slang_T *lp);
317 static int *mb_str2wide(char_u *s);
318 static int spell_read_tree(FILE *fd, char_u **bytsp, idx_T **idxsp, int prefixtree, int prefixcnt);
319 static idx_T read_tree_node(FILE *fd, char_u *byts, idx_T *idxs, int maxidx, idx_T startidx, int prefixtree, int maxprefcondnr);
320 static void set_spell_charflags(char_u *flags, int cnt, char_u *upp);
321 static int set_spell_chartab(char_u *fol, char_u *low, char_u *upp);
322 static void set_map_str(slang_T *lp, char_u *map);
323 
324 
325 static char *e_spell_trunc = N_("E758: Truncated spell file");
326 static char *e_afftrailing = N_("Trailing text in %s line %d: %s");
327 static char *e_affname = N_("Affix name too long in %s line %d: %s");
328 static char *e_affform = N_("E761: Format error in affix file FOL, LOW or UPP");
329 static char *e_affrange = N_("E762: Character in FOL, LOW or UPP is out of range");
330 static char *msg_compressing = N_("Compressing word tree...");
331 
332 /*
333  * Load one spell file and store the info into a slang_T.
334  *
335  * This is invoked in three ways:
336  * - From spell_load_cb() to load a spell file for the first time.  "lang" is
337  *   the language name, "old_lp" is NULL.  Will allocate an slang_T.
338  * - To reload a spell file that was changed.  "lang" is NULL and "old_lp"
339  *   points to the existing slang_T.
340  * - Just after writing a .spl file; it's read back to produce the .sug file.
341  *   "old_lp" is NULL and "lang" is NULL.  Will allocate an slang_T.
342  *
343  * Returns the slang_T the spell file was loaded into.  NULL for error.
344  */
345     slang_T *
346 spell_load_file(
347     char_u	*fname,
348     char_u	*lang,
349     slang_T	*old_lp,
350     int		silent)		// no error if file doesn't exist
351 {
352     FILE	*fd;
353     char_u	buf[VIMSPELLMAGICL];
354     char_u	*p;
355     int		i;
356     int		n;
357     int		len;
358     slang_T	*lp = NULL;
359     int		c = 0;
360     int		res;
361     int		did_estack_push = FALSE;
362     ESTACK_CHECK_DECLARATION
363 
364     fd = mch_fopen((char *)fname, "r");
365     if (fd == NULL)
366     {
367 	if (!silent)
368 	    semsg(_(e_notopen), fname);
369 	else if (p_verbose > 2)
370 	{
371 	    verbose_enter();
372 	    smsg((const char *)e_notopen, fname);
373 	    verbose_leave();
374 	}
375 	goto endFAIL;
376     }
377     if (p_verbose > 2)
378     {
379 	verbose_enter();
380 	smsg(_("Reading spell file \"%s\""), fname);
381 	verbose_leave();
382     }
383 
384     if (old_lp == NULL)
385     {
386 	lp = slang_alloc(lang);
387 	if (lp == NULL)
388 	    goto endFAIL;
389 
390 	// Remember the file name, used to reload the file when it's updated.
391 	lp->sl_fname = vim_strsave(fname);
392 	if (lp->sl_fname == NULL)
393 	    goto endFAIL;
394 
395 	// Check for .add.spl (_add.spl for VMS).
396 	lp->sl_add = strstr((char *)gettail(fname), SPL_FNAME_ADD) != NULL;
397     }
398     else
399 	lp = old_lp;
400 
401     // Set sourcing_name, so that error messages mention the file name.
402     estack_push(ETYPE_SPELL, fname, 0);
403     ESTACK_CHECK_SETUP
404     did_estack_push = TRUE;
405 
406     /*
407      * <HEADER>: <fileID>
408      */
409     for (i = 0; i < VIMSPELLMAGICL; ++i)
410 	buf[i] = getc(fd);				// <fileID>
411     if (STRNCMP(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0)
412     {
413 	emsg(_("E757: This does not look like a spell file"));
414 	goto endFAIL;
415     }
416     c = getc(fd);					// <versionnr>
417     if (c < VIMSPELLVERSION)
418     {
419 	emsg(_("E771: Old spell file, needs to be updated"));
420 	goto endFAIL;
421     }
422     else if (c > VIMSPELLVERSION)
423     {
424 	emsg(_("E772: Spell file is for newer version of Vim"));
425 	goto endFAIL;
426     }
427 
428 
429     /*
430      * <SECTIONS>: <section> ... <sectionend>
431      * <section>: <sectionID> <sectionflags> <sectionlen> (section contents)
432      */
433     for (;;)
434     {
435 	n = getc(fd);			    // <sectionID> or <sectionend>
436 	if (n == SN_END)
437 	    break;
438 	c = getc(fd);					// <sectionflags>
439 	len = get4c(fd);				// <sectionlen>
440 	if (len < 0)
441 	    goto truncerr;
442 
443 	res = 0;
444 	switch (n)
445 	{
446 	    case SN_INFO:
447 		lp->sl_info = read_string(fd, len);	// <infotext>
448 		if (lp->sl_info == NULL)
449 		    goto endFAIL;
450 		break;
451 
452 	    case SN_REGION:
453 		res = read_region_section(fd, lp, len);
454 		break;
455 
456 	    case SN_CHARFLAGS:
457 		res = read_charflags_section(fd);
458 		break;
459 
460 	    case SN_MIDWORD:
461 		lp->sl_midword = read_string(fd, len);	// <midword>
462 		if (lp->sl_midword == NULL)
463 		    goto endFAIL;
464 		break;
465 
466 	    case SN_PREFCOND:
467 		res = read_prefcond_section(fd, lp);
468 		break;
469 
470 	    case SN_REP:
471 		res = read_rep_section(fd, &lp->sl_rep, lp->sl_rep_first);
472 		break;
473 
474 	    case SN_REPSAL:
475 		res = read_rep_section(fd, &lp->sl_repsal, lp->sl_repsal_first);
476 		break;
477 
478 	    case SN_SAL:
479 		res = read_sal_section(fd, lp);
480 		break;
481 
482 	    case SN_SOFO:
483 		res = read_sofo_section(fd, lp);
484 		break;
485 
486 	    case SN_MAP:
487 		p = read_string(fd, len);		// <mapstr>
488 		if (p == NULL)
489 		    goto endFAIL;
490 		set_map_str(lp, p);
491 		vim_free(p);
492 		break;
493 
494 	    case SN_WORDS:
495 		res = read_words_section(fd, lp, len);
496 		break;
497 
498 	    case SN_SUGFILE:
499 		lp->sl_sugtime = get8ctime(fd);		// <timestamp>
500 		break;
501 
502 	    case SN_NOSPLITSUGS:
503 		lp->sl_nosplitsugs = TRUE;
504 		break;
505 
506 	    case SN_NOCOMPOUNDSUGS:
507 		lp->sl_nocompoundsugs = TRUE;
508 		break;
509 
510 	    case SN_COMPOUND:
511 		res = read_compound(fd, lp, len);
512 		break;
513 
514 	    case SN_NOBREAK:
515 		lp->sl_nobreak = TRUE;
516 		break;
517 
518 	    case SN_SYLLABLE:
519 		lp->sl_syllable = read_string(fd, len);	// <syllable>
520 		if (lp->sl_syllable == NULL)
521 		    goto endFAIL;
522 		if (init_syl_tab(lp) == FAIL)
523 		    goto endFAIL;
524 		break;
525 
526 	    default:
527 		// Unsupported section.  When it's required give an error
528 		// message.  When it's not required skip the contents.
529 		if (c & SNF_REQUIRED)
530 		{
531 		    emsg(_("E770: Unsupported section in spell file"));
532 		    goto endFAIL;
533 		}
534 		while (--len >= 0)
535 		    if (getc(fd) < 0)
536 			goto truncerr;
537 		break;
538 	}
539 someerror:
540 	if (res == SP_FORMERROR)
541 	{
542 	    emsg(_(e_format));
543 	    goto endFAIL;
544 	}
545 	if (res == SP_TRUNCERROR)
546 	{
547 truncerr:
548 	    emsg(_(e_spell_trunc));
549 	    goto endFAIL;
550 	}
551 	if (res == SP_OTHERERROR)
552 	    goto endFAIL;
553     }
554 
555     // <LWORDTREE>
556     res = spell_read_tree(fd, &lp->sl_fbyts, &lp->sl_fidxs, FALSE, 0);
557     if (res != 0)
558 	goto someerror;
559 
560     // <KWORDTREE>
561     res = spell_read_tree(fd, &lp->sl_kbyts, &lp->sl_kidxs, FALSE, 0);
562     if (res != 0)
563 	goto someerror;
564 
565     // <PREFIXTREE>
566     res = spell_read_tree(fd, &lp->sl_pbyts, &lp->sl_pidxs, TRUE,
567 							    lp->sl_prefixcnt);
568     if (res != 0)
569 	goto someerror;
570 
571     // For a new file link it in the list of spell files.
572     if (old_lp == NULL && lang != NULL)
573     {
574 	lp->sl_next = first_lang;
575 	first_lang = lp;
576     }
577 
578     goto endOK;
579 
580 endFAIL:
581     if (lang != NULL)
582 	// truncating the name signals the error to spell_load_lang()
583 	*lang = NUL;
584     if (lp != NULL && old_lp == NULL)
585 	slang_free(lp);
586     lp = NULL;
587 
588 endOK:
589     if (fd != NULL)
590 	fclose(fd);
591     if (did_estack_push)
592     {
593 	ESTACK_CHECK_NOW
594 	estack_pop();
595     }
596 
597     return lp;
598 }
599 
600 /*
601  * Fill in the wordcount fields for a trie.
602  * Returns the total number of words.
603  */
604     static void
605 tree_count_words(char_u *byts, idx_T *idxs)
606 {
607     int		depth;
608     idx_T	arridx[MAXWLEN];
609     int		curi[MAXWLEN];
610     int		c;
611     idx_T	n;
612     int		wordcount[MAXWLEN];
613 
614     arridx[0] = 0;
615     curi[0] = 1;
616     wordcount[0] = 0;
617     depth = 0;
618     while (depth >= 0 && !got_int)
619     {
620 	if (curi[depth] > byts[arridx[depth]])
621 	{
622 	    // Done all bytes at this node, go up one level.
623 	    idxs[arridx[depth]] = wordcount[depth];
624 	    if (depth > 0)
625 		wordcount[depth - 1] += wordcount[depth];
626 
627 	    --depth;
628 	    fast_breakcheck();
629 	}
630 	else
631 	{
632 	    // Do one more byte at this node.
633 	    n = arridx[depth] + curi[depth];
634 	    ++curi[depth];
635 
636 	    c = byts[n];
637 	    if (c == 0)
638 	    {
639 		// End of word, count it.
640 		++wordcount[depth];
641 
642 		// Skip over any other NUL bytes (same word with different
643 		// flags).
644 		while (byts[n + 1] == 0)
645 		{
646 		    ++n;
647 		    ++curi[depth];
648 		}
649 	    }
650 	    else
651 	    {
652 		// Normal char, go one level deeper to count the words.
653 		++depth;
654 		arridx[depth] = idxs[n];
655 		curi[depth] = 1;
656 		wordcount[depth] = 0;
657 	    }
658 	}
659     }
660 }
661 
662 /*
663  * Load the .sug files for languages that have one and weren't loaded yet.
664  */
665     void
666 suggest_load_files(void)
667 {
668     langp_T	*lp;
669     int		lpi;
670     slang_T	*slang;
671     char_u	*dotp;
672     FILE	*fd;
673     char_u	buf[MAXWLEN];
674     int		i;
675     time_t	timestamp;
676     int		wcount;
677     int		wordnr;
678     garray_T	ga;
679     int		c;
680 
681     // Do this for all languages that support sound folding.
682     for (lpi = 0; lpi < curwin->w_s->b_langp.ga_len; ++lpi)
683     {
684 	lp = LANGP_ENTRY(curwin->w_s->b_langp, lpi);
685 	slang = lp->lp_slang;
686 	if (slang->sl_sugtime != 0 && !slang->sl_sugloaded)
687 	{
688 	    // Change ".spl" to ".sug" and open the file.  When the file isn't
689 	    // found silently skip it.  Do set "sl_sugloaded" so that we
690 	    // don't try again and again.
691 	    slang->sl_sugloaded = TRUE;
692 
693 	    dotp = vim_strrchr(slang->sl_fname, '.');
694 	    if (dotp == NULL || fnamecmp(dotp, ".spl") != 0)
695 		continue;
696 	    STRCPY(dotp, ".sug");
697 	    fd = mch_fopen((char *)slang->sl_fname, "r");
698 	    if (fd == NULL)
699 		goto nextone;
700 
701 	    /*
702 	     * <SUGHEADER>: <fileID> <versionnr> <timestamp>
703 	     */
704 	    for (i = 0; i < VIMSUGMAGICL; ++i)
705 		buf[i] = getc(fd);			// <fileID>
706 	    if (STRNCMP(buf, VIMSUGMAGIC, VIMSUGMAGICL) != 0)
707 	    {
708 		semsg(_("E778: This does not look like a .sug file: %s"),
709 							     slang->sl_fname);
710 		goto nextone;
711 	    }
712 	    c = getc(fd);				// <versionnr>
713 	    if (c < VIMSUGVERSION)
714 	    {
715 		semsg(_("E779: Old .sug file, needs to be updated: %s"),
716 							     slang->sl_fname);
717 		goto nextone;
718 	    }
719 	    else if (c > VIMSUGVERSION)
720 	    {
721 		semsg(_("E780: .sug file is for newer version of Vim: %s"),
722 							     slang->sl_fname);
723 		goto nextone;
724 	    }
725 
726 	    // Check the timestamp, it must be exactly the same as the one in
727 	    // the .spl file.  Otherwise the word numbers won't match.
728 	    timestamp = get8ctime(fd);			// <timestamp>
729 	    if (timestamp != slang->sl_sugtime)
730 	    {
731 		semsg(_("E781: .sug file doesn't match .spl file: %s"),
732 							     slang->sl_fname);
733 		goto nextone;
734 	    }
735 
736 	    /*
737 	     * <SUGWORDTREE>: <wordtree>
738 	     * Read the trie with the soundfolded words.
739 	     */
740 	    if (spell_read_tree(fd, &slang->sl_sbyts, &slang->sl_sidxs,
741 							       FALSE, 0) != 0)
742 	    {
743 someerror:
744 		semsg(_("E782: error while reading .sug file: %s"),
745 							     slang->sl_fname);
746 		slang_clear_sug(slang);
747 		goto nextone;
748 	    }
749 
750 	    /*
751 	     * <SUGTABLE>: <sugwcount> <sugline> ...
752 	     *
753 	     * Read the table with word numbers.  We use a file buffer for
754 	     * this, because it's so much like a file with lines.  Makes it
755 	     * possible to swap the info and save on memory use.
756 	     */
757 	    slang->sl_sugbuf = open_spellbuf();
758 	    if (slang->sl_sugbuf == NULL)
759 		goto someerror;
760 							    // <sugwcount>
761 	    wcount = get4c(fd);
762 	    if (wcount < 0)
763 		goto someerror;
764 
765 	    // Read all the wordnr lists into the buffer, one NUL terminated
766 	    // list per line.
767 	    ga_init2(&ga, 1, 100);
768 	    for (wordnr = 0; wordnr < wcount; ++wordnr)
769 	    {
770 		ga.ga_len = 0;
771 		for (;;)
772 		{
773 		    c = getc(fd);			    // <sugline>
774 		    if (c < 0 || ga_grow(&ga, 1) == FAIL)
775 			goto someerror;
776 		    ((char_u *)ga.ga_data)[ga.ga_len++] = c;
777 		    if (c == NUL)
778 			break;
779 		}
780 		if (ml_append_buf(slang->sl_sugbuf, (linenr_T)wordnr,
781 					 ga.ga_data, ga.ga_len, TRUE) == FAIL)
782 		    goto someerror;
783 	    }
784 	    ga_clear(&ga);
785 
786 	    /*
787 	     * Need to put word counts in the word tries, so that we can find
788 	     * a word by its number.
789 	     */
790 	    tree_count_words(slang->sl_fbyts, slang->sl_fidxs);
791 	    tree_count_words(slang->sl_sbyts, slang->sl_sidxs);
792 
793 nextone:
794 	    if (fd != NULL)
795 		fclose(fd);
796 	    STRCPY(dotp, ".spl");
797 	}
798     }
799 }
800 
801 
802 /*
803  * Read a length field from "fd" in "cnt_bytes" bytes.
804  * Allocate memory, read the string into it and add a NUL at the end.
805  * Returns NULL when the count is zero.
806  * Sets "*cntp" to SP_*ERROR when there is an error, length of the result
807  * otherwise.
808  */
809     static char_u *
810 read_cnt_string(FILE *fd, int cnt_bytes, int *cntp)
811 {
812     int		cnt = 0;
813     int		i;
814     char_u	*str;
815 
816     // read the length bytes, MSB first
817     for (i = 0; i < cnt_bytes; ++i)
818 	cnt = (cnt << 8) + getc(fd);
819     if (cnt < 0)
820     {
821 	*cntp = SP_TRUNCERROR;
822 	return NULL;
823     }
824     *cntp = cnt;
825     if (cnt == 0)
826 	return NULL;	    // nothing to read, return NULL
827 
828     str = read_string(fd, cnt);
829     if (str == NULL)
830 	*cntp = SP_OTHERERROR;
831     return str;
832 }
833 
834 /*
835  * Read SN_REGION: <regionname> ...
836  * Return SP_*ERROR flags.
837  */
838     static int
839 read_region_section(FILE *fd, slang_T *lp, int len)
840 {
841     int		i;
842 
843     if (len > MAXREGIONS * 2)
844 	return SP_FORMERROR;
845     for (i = 0; i < len; ++i)
846 	lp->sl_regions[i] = getc(fd);			// <regionname>
847     lp->sl_regions[len] = NUL;
848     return 0;
849 }
850 
851 /*
852  * Read SN_CHARFLAGS section: <charflagslen> <charflags>
853  *				<folcharslen> <folchars>
854  * Return SP_*ERROR flags.
855  */
856     static int
857 read_charflags_section(FILE *fd)
858 {
859     char_u	*flags;
860     char_u	*fol;
861     int		flagslen, follen;
862 
863     // <charflagslen> <charflags>
864     flags = read_cnt_string(fd, 1, &flagslen);
865     if (flagslen < 0)
866 	return flagslen;
867 
868     // <folcharslen> <folchars>
869     fol = read_cnt_string(fd, 2, &follen);
870     if (follen < 0)
871     {
872 	vim_free(flags);
873 	return follen;
874     }
875 
876     // Set the word-char flags and fill SPELL_ISUPPER() table.
877     if (flags != NULL && fol != NULL)
878 	set_spell_charflags(flags, flagslen, fol);
879 
880     vim_free(flags);
881     vim_free(fol);
882 
883     // When <charflagslen> is zero then <fcharlen> must also be zero.
884     if ((flags == NULL) != (fol == NULL))
885 	return SP_FORMERROR;
886     return 0;
887 }
888 
889 /*
890  * Read SN_PREFCOND section.
891  * Return SP_*ERROR flags.
892  */
893     static int
894 read_prefcond_section(FILE *fd, slang_T *lp)
895 {
896     int		cnt;
897     int		i;
898     int		n;
899     char_u	*p;
900     char_u	buf[MAXWLEN + 1];
901 
902     // <prefcondcnt> <prefcond> ...
903     cnt = get2c(fd);					// <prefcondcnt>
904     if (cnt <= 0)
905 	return SP_FORMERROR;
906 
907     lp->sl_prefprog = ALLOC_CLEAR_MULT(regprog_T *, cnt);
908     if (lp->sl_prefprog == NULL)
909 	return SP_OTHERERROR;
910     lp->sl_prefixcnt = cnt;
911 
912     for (i = 0; i < cnt; ++i)
913     {
914 	// <prefcond> : <condlen> <condstr>
915 	n = getc(fd);					// <condlen>
916 	if (n < 0 || n >= MAXWLEN)
917 	    return SP_FORMERROR;
918 
919 	// When <condlen> is zero we have an empty condition.  Otherwise
920 	// compile the regexp program used to check for the condition.
921 	if (n > 0)
922 	{
923 	    buf[0] = '^';	    // always match at one position only
924 	    p = buf + 1;
925 	    while (n-- > 0)
926 		*p++ = getc(fd);			// <condstr>
927 	    *p = NUL;
928 	    lp->sl_prefprog[i] = vim_regcomp(buf, RE_MAGIC + RE_STRING);
929 	}
930     }
931     return 0;
932 }
933 
934 /*
935  * Read REP or REPSAL items section from "fd": <repcount> <rep> ...
936  * Return SP_*ERROR flags.
937  */
938     static int
939 read_rep_section(FILE *fd, garray_T *gap, short *first)
940 {
941     int		cnt;
942     fromto_T	*ftp;
943     int		i;
944 
945     cnt = get2c(fd);					// <repcount>
946     if (cnt < 0)
947 	return SP_TRUNCERROR;
948 
949     if (ga_grow(gap, cnt) == FAIL)
950 	return SP_OTHERERROR;
951 
952     // <rep> : <repfromlen> <repfrom> <reptolen> <repto>
953     for (; gap->ga_len < cnt; ++gap->ga_len)
954     {
955 	ftp = &((fromto_T *)gap->ga_data)[gap->ga_len];
956 	ftp->ft_from = read_cnt_string(fd, 1, &i);
957 	if (i < 0)
958 	    return i;
959 	if (i == 0)
960 	    return SP_FORMERROR;
961 	ftp->ft_to = read_cnt_string(fd, 1, &i);
962 	if (i <= 0)
963 	{
964 	    vim_free(ftp->ft_from);
965 	    if (i < 0)
966 		return i;
967 	    return SP_FORMERROR;
968 	}
969     }
970 
971     // Fill the first-index table.
972     for (i = 0; i < 256; ++i)
973 	first[i] = -1;
974     for (i = 0; i < gap->ga_len; ++i)
975     {
976 	ftp = &((fromto_T *)gap->ga_data)[i];
977 	if (first[*ftp->ft_from] == -1)
978 	    first[*ftp->ft_from] = i;
979     }
980     return 0;
981 }
982 
983 /*
984  * Read SN_SAL section: <salflags> <salcount> <sal> ...
985  * Return SP_*ERROR flags.
986  */
987     static int
988 read_sal_section(FILE *fd, slang_T *slang)
989 {
990     int		i;
991     int		cnt;
992     garray_T	*gap;
993     salitem_T	*smp;
994     int		ccnt;
995     char_u	*p;
996     int		c = NUL;
997 
998     slang->sl_sofo = FALSE;
999 
1000     i = getc(fd);				// <salflags>
1001     if (i & SAL_F0LLOWUP)
1002 	slang->sl_followup = TRUE;
1003     if (i & SAL_COLLAPSE)
1004 	slang->sl_collapse = TRUE;
1005     if (i & SAL_REM_ACCENTS)
1006 	slang->sl_rem_accents = TRUE;
1007 
1008     cnt = get2c(fd);				// <salcount>
1009     if (cnt < 0)
1010 	return SP_TRUNCERROR;
1011 
1012     gap = &slang->sl_sal;
1013     ga_init2(gap, sizeof(salitem_T), 10);
1014     if (ga_grow(gap, cnt + 1) == FAIL)
1015 	return SP_OTHERERROR;
1016 
1017     // <sal> : <salfromlen> <salfrom> <saltolen> <salto>
1018     for (; gap->ga_len < cnt; ++gap->ga_len)
1019     {
1020 	smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
1021 	ccnt = getc(fd);			// <salfromlen>
1022 	if (ccnt < 0)
1023 	    return SP_TRUNCERROR;
1024 	if ((p = alloc(ccnt + 2)) == NULL)
1025 	    return SP_OTHERERROR;
1026 	smp->sm_lead = p;
1027 
1028 	// Read up to the first special char into sm_lead.
1029 	for (i = 0; i < ccnt; ++i)
1030 	{
1031 	    c = getc(fd);			// <salfrom>
1032 	    if (vim_strchr((char_u *)"0123456789(-<^$", c) != NULL)
1033 		break;
1034 	    *p++ = c;
1035 	}
1036 	smp->sm_leadlen = (int)(p - smp->sm_lead);
1037 	*p++ = NUL;
1038 
1039 	// Put (abc) chars in sm_oneof, if any.
1040 	if (c == '(')
1041 	{
1042 	    smp->sm_oneof = p;
1043 	    for (++i; i < ccnt; ++i)
1044 	    {
1045 		c = getc(fd);			// <salfrom>
1046 		if (c == ')')
1047 		    break;
1048 		*p++ = c;
1049 	    }
1050 	    *p++ = NUL;
1051 	    if (++i < ccnt)
1052 		c = getc(fd);
1053 	}
1054 	else
1055 	    smp->sm_oneof = NULL;
1056 
1057 	// Any following chars go in sm_rules.
1058 	smp->sm_rules = p;
1059 	if (i < ccnt)
1060 	    // store the char we got while checking for end of sm_lead
1061 	    *p++ = c;
1062 	for (++i; i < ccnt; ++i)
1063 	    *p++ = getc(fd);			// <salfrom>
1064 	*p++ = NUL;
1065 
1066 	// <saltolen> <salto>
1067 	smp->sm_to = read_cnt_string(fd, 1, &ccnt);
1068 	if (ccnt < 0)
1069 	{
1070 	    vim_free(smp->sm_lead);
1071 	    return ccnt;
1072 	}
1073 
1074 	if (has_mbyte)
1075 	{
1076 	    // convert the multi-byte strings to wide char strings
1077 	    smp->sm_lead_w = mb_str2wide(smp->sm_lead);
1078 	    smp->sm_leadlen = mb_charlen(smp->sm_lead);
1079 	    if (smp->sm_oneof == NULL)
1080 		smp->sm_oneof_w = NULL;
1081 	    else
1082 		smp->sm_oneof_w = mb_str2wide(smp->sm_oneof);
1083 	    if (smp->sm_to == NULL)
1084 		smp->sm_to_w = NULL;
1085 	    else
1086 		smp->sm_to_w = mb_str2wide(smp->sm_to);
1087 	    if (smp->sm_lead_w == NULL
1088 		    || (smp->sm_oneof_w == NULL && smp->sm_oneof != NULL)
1089 		    || (smp->sm_to_w == NULL && smp->sm_to != NULL))
1090 	    {
1091 		vim_free(smp->sm_lead);
1092 		vim_free(smp->sm_to);
1093 		vim_free(smp->sm_lead_w);
1094 		vim_free(smp->sm_oneof_w);
1095 		vim_free(smp->sm_to_w);
1096 		return SP_OTHERERROR;
1097 	    }
1098 	}
1099     }
1100 
1101     if (gap->ga_len > 0)
1102     {
1103 	// Add one extra entry to mark the end with an empty sm_lead.  Avoids
1104 	// that we need to check the index every time.
1105 	smp = &((salitem_T *)gap->ga_data)[gap->ga_len];
1106 	if ((p = alloc(1)) == NULL)
1107 	    return SP_OTHERERROR;
1108 	p[0] = NUL;
1109 	smp->sm_lead = p;
1110 	smp->sm_leadlen = 0;
1111 	smp->sm_oneof = NULL;
1112 	smp->sm_rules = p;
1113 	smp->sm_to = NULL;
1114 	if (has_mbyte)
1115 	{
1116 	    smp->sm_lead_w = mb_str2wide(smp->sm_lead);
1117 	    smp->sm_leadlen = 0;
1118 	    smp->sm_oneof_w = NULL;
1119 	    smp->sm_to_w = NULL;
1120 	}
1121 	++gap->ga_len;
1122     }
1123 
1124     // Fill the first-index table.
1125     set_sal_first(slang);
1126 
1127     return 0;
1128 }
1129 
1130 /*
1131  * Read SN_WORDS: <word> ...
1132  * Return SP_*ERROR flags.
1133  */
1134     static int
1135 read_words_section(FILE *fd, slang_T *lp, int len)
1136 {
1137     int		done = 0;
1138     int		i;
1139     int		c;
1140     char_u	word[MAXWLEN];
1141 
1142     while (done < len)
1143     {
1144 	// Read one word at a time.
1145 	for (i = 0; ; ++i)
1146 	{
1147 	    c = getc(fd);
1148 	    if (c == EOF)
1149 		return SP_TRUNCERROR;
1150 	    word[i] = c;
1151 	    if (word[i] == NUL)
1152 		break;
1153 	    if (i == MAXWLEN - 1)
1154 		return SP_FORMERROR;
1155 	}
1156 
1157 	// Init the count to 10.
1158 	count_common_word(lp, word, -1, 10);
1159 	done += i + 1;
1160     }
1161     return 0;
1162 }
1163 
1164 /*
1165  * SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
1166  * Return SP_*ERROR flags.
1167  */
1168     static int
1169 read_sofo_section(FILE *fd, slang_T *slang)
1170 {
1171     int		cnt;
1172     char_u	*from, *to;
1173     int		res;
1174 
1175     slang->sl_sofo = TRUE;
1176 
1177     // <sofofromlen> <sofofrom>
1178     from = read_cnt_string(fd, 2, &cnt);
1179     if (cnt < 0)
1180 	return cnt;
1181 
1182     // <sofotolen> <sofoto>
1183     to = read_cnt_string(fd, 2, &cnt);
1184     if (cnt < 0)
1185     {
1186 	vim_free(from);
1187 	return cnt;
1188     }
1189 
1190     // Store the info in slang->sl_sal and/or slang->sl_sal_first.
1191     if (from != NULL && to != NULL)
1192 	res = set_sofo(slang, from, to);
1193     else if (from != NULL || to != NULL)
1194 	res = SP_FORMERROR;    // only one of two strings is an error
1195     else
1196 	res = 0;
1197 
1198     vim_free(from);
1199     vim_free(to);
1200     return res;
1201 }
1202 
1203 /*
1204  * Read the compound section from the .spl file:
1205  *	<compmax> <compminlen> <compsylmax> <compoptions> <compflags>
1206  * Returns SP_*ERROR flags.
1207  */
1208     static int
1209 read_compound(FILE *fd, slang_T *slang, int len)
1210 {
1211     int		todo = len;
1212     int		c;
1213     int		atstart;
1214     char_u	*pat;
1215     char_u	*pp;
1216     char_u	*cp;
1217     char_u	*ap;
1218     char_u	*crp;
1219     int		cnt;
1220     garray_T	*gap;
1221 
1222     if (todo < 2)
1223 	return SP_FORMERROR;	// need at least two bytes
1224 
1225     --todo;
1226     c = getc(fd);					// <compmax>
1227     if (c < 2)
1228 	c = MAXWLEN;
1229     slang->sl_compmax = c;
1230 
1231     --todo;
1232     c = getc(fd);					// <compminlen>
1233     if (c < 1)
1234 	c = 0;
1235     slang->sl_compminlen = c;
1236 
1237     --todo;
1238     c = getc(fd);					// <compsylmax>
1239     if (c < 1)
1240 	c = MAXWLEN;
1241     slang->sl_compsylmax = c;
1242 
1243     c = getc(fd);					// <compoptions>
1244     if (c != 0)
1245 	ungetc(c, fd);	    // be backwards compatible with Vim 7.0b
1246     else
1247     {
1248 	--todo;
1249 	c = getc(fd);	    // only use the lower byte for now
1250 	--todo;
1251 	slang->sl_compoptions = c;
1252 
1253 	gap = &slang->sl_comppat;
1254 	c = get2c(fd);					// <comppatcount>
1255 	todo -= 2;
1256 	ga_init2(gap, sizeof(char_u *), c);
1257 	if (ga_grow(gap, c) == OK)
1258 	    while (--c >= 0)
1259 	    {
1260 		((char_u **)(gap->ga_data))[gap->ga_len++] =
1261 						 read_cnt_string(fd, 1, &cnt);
1262 					    // <comppatlen> <comppattext>
1263 		if (cnt < 0)
1264 		    return cnt;
1265 		todo -= cnt + 1;
1266 	    }
1267     }
1268     if (todo < 0)
1269 	return SP_FORMERROR;
1270 
1271     // Turn the COMPOUNDRULE items into a regexp pattern:
1272     // "a[bc]/a*b+" -> "^\(a[bc]\|a*b\+\)$".
1273     // Inserting backslashes may double the length, "^\(\)$<Nul>" is 7 bytes.
1274     // Conversion to utf-8 may double the size.
1275     c = todo * 2 + 7;
1276     if (enc_utf8)
1277 	c += todo * 2;
1278     pat = alloc(c);
1279     if (pat == NULL)
1280 	return SP_OTHERERROR;
1281 
1282     // We also need a list of all flags that can appear at the start and one
1283     // for all flags.
1284     cp = alloc(todo + 1);
1285     if (cp == NULL)
1286     {
1287 	vim_free(pat);
1288 	return SP_OTHERERROR;
1289     }
1290     slang->sl_compstartflags = cp;
1291     *cp = NUL;
1292 
1293     ap = alloc(todo + 1);
1294     if (ap == NULL)
1295     {
1296 	vim_free(pat);
1297 	return SP_OTHERERROR;
1298     }
1299     slang->sl_compallflags = ap;
1300     *ap = NUL;
1301 
1302     // And a list of all patterns in their original form, for checking whether
1303     // compounding may work in match_compoundrule().  This is freed when we
1304     // encounter a wildcard, the check doesn't work then.
1305     crp = alloc(todo + 1);
1306     slang->sl_comprules = crp;
1307 
1308     pp = pat;
1309     *pp++ = '^';
1310     *pp++ = '\\';
1311     *pp++ = '(';
1312 
1313     atstart = 1;
1314     while (todo-- > 0)
1315     {
1316 	c = getc(fd);					// <compflags>
1317 	if (c == EOF)
1318 	{
1319 	    vim_free(pat);
1320 	    return SP_TRUNCERROR;
1321 	}
1322 
1323 	// Add all flags to "sl_compallflags".
1324 	if (vim_strchr((char_u *)"?*+[]/", c) == NULL
1325 		&& !byte_in_str(slang->sl_compallflags, c))
1326 	{
1327 	    *ap++ = c;
1328 	    *ap = NUL;
1329 	}
1330 
1331 	if (atstart != 0)
1332 	{
1333 	    // At start of item: copy flags to "sl_compstartflags".  For a
1334 	    // [abc] item set "atstart" to 2 and copy up to the ']'.
1335 	    if (c == '[')
1336 		atstart = 2;
1337 	    else if (c == ']')
1338 		atstart = 0;
1339 	    else
1340 	    {
1341 		if (!byte_in_str(slang->sl_compstartflags, c))
1342 		{
1343 		    *cp++ = c;
1344 		    *cp = NUL;
1345 		}
1346 		if (atstart == 1)
1347 		    atstart = 0;
1348 	    }
1349 	}
1350 
1351 	// Copy flag to "sl_comprules", unless we run into a wildcard.
1352 	if (crp != NULL)
1353 	{
1354 	    if (c == '?' || c == '+' || c == '*')
1355 	    {
1356 		VIM_CLEAR(slang->sl_comprules);
1357 		crp = NULL;
1358 	    }
1359 	    else
1360 		*crp++ = c;
1361 	}
1362 
1363 	if (c == '/')	    // slash separates two items
1364 	{
1365 	    *pp++ = '\\';
1366 	    *pp++ = '|';
1367 	    atstart = 1;
1368 	}
1369 	else		    // normal char, "[abc]" and '*' are copied as-is
1370 	{
1371 	    if (c == '?' || c == '+' || c == '~')
1372 		*pp++ = '\\';	    // "a?" becomes "a\?", "a+" becomes "a\+"
1373 	    if (enc_utf8)
1374 		pp += mb_char2bytes(c, pp);
1375 	    else
1376 		*pp++ = c;
1377 	}
1378     }
1379 
1380     *pp++ = '\\';
1381     *pp++ = ')';
1382     *pp++ = '$';
1383     *pp = NUL;
1384 
1385     if (crp != NULL)
1386 	*crp = NUL;
1387 
1388     slang->sl_compprog = vim_regcomp(pat, RE_MAGIC + RE_STRING + RE_STRICT);
1389     vim_free(pat);
1390     if (slang->sl_compprog == NULL)
1391 	return SP_FORMERROR;
1392 
1393     return 0;
1394 }
1395 
1396 /*
1397  * Set the SOFOFROM and SOFOTO items in language "lp".
1398  * Returns SP_*ERROR flags when there is something wrong.
1399  */
1400     static int
1401 set_sofo(slang_T *lp, char_u *from, char_u *to)
1402 {
1403     int		i;
1404 
1405     garray_T	*gap;
1406     char_u	*s;
1407     char_u	*p;
1408     int		c;
1409     int		*inp;
1410 
1411     if (has_mbyte)
1412     {
1413 	// Use "sl_sal" as an array with 256 pointers to a list of wide
1414 	// characters.  The index is the low byte of the character.
1415 	// The list contains from-to pairs with a terminating NUL.
1416 	// sl_sal_first[] is used for latin1 "from" characters.
1417 	gap = &lp->sl_sal;
1418 	ga_init2(gap, sizeof(int *), 1);
1419 	if (ga_grow(gap, 256) == FAIL)
1420 	    return SP_OTHERERROR;
1421 	vim_memset(gap->ga_data, 0, sizeof(int *) * 256);
1422 	gap->ga_len = 256;
1423 
1424 	// First count the number of items for each list.  Temporarily use
1425 	// sl_sal_first[] for this.
1426 	for (p = from, s = to; *p != NUL && *s != NUL; )
1427 	{
1428 	    c = mb_cptr2char_adv(&p);
1429 	    MB_CPTR_ADV(s);
1430 	    if (c >= 256)
1431 		++lp->sl_sal_first[c & 0xff];
1432 	}
1433 	if (*p != NUL || *s != NUL)	    // lengths differ
1434 	    return SP_FORMERROR;
1435 
1436 	// Allocate the lists.
1437 	for (i = 0; i < 256; ++i)
1438 	    if (lp->sl_sal_first[i] > 0)
1439 	    {
1440 		p = alloc(sizeof(int) * (lp->sl_sal_first[i] * 2 + 1));
1441 		if (p == NULL)
1442 		    return SP_OTHERERROR;
1443 		((int **)gap->ga_data)[i] = (int *)p;
1444 		*(int *)p = 0;
1445 	    }
1446 
1447 	// Put the characters up to 255 in sl_sal_first[] the rest in a sl_sal
1448 	// list.
1449 	vim_memset(lp->sl_sal_first, 0, sizeof(salfirst_T) * 256);
1450 	for (p = from, s = to; *p != NUL && *s != NUL; )
1451 	{
1452 	    c = mb_cptr2char_adv(&p);
1453 	    i = mb_cptr2char_adv(&s);
1454 	    if (c >= 256)
1455 	    {
1456 		// Append the from-to chars at the end of the list with
1457 		// the low byte.
1458 		inp = ((int **)gap->ga_data)[c & 0xff];
1459 		while (*inp != 0)
1460 		    ++inp;
1461 		*inp++ = c;		// from char
1462 		*inp++ = i;		// to char
1463 		*inp++ = NUL;		// NUL at the end
1464 	    }
1465 	    else
1466 		// mapping byte to char is done in sl_sal_first[]
1467 		lp->sl_sal_first[c] = i;
1468 	}
1469     }
1470     else
1471     {
1472 	// mapping bytes to bytes is done in sl_sal_first[]
1473 	if (STRLEN(from) != STRLEN(to))
1474 	    return SP_FORMERROR;
1475 
1476 	for (i = 0; to[i] != NUL; ++i)
1477 	    lp->sl_sal_first[from[i]] = to[i];
1478 	lp->sl_sal.ga_len = 1;		// indicates we have soundfolding
1479     }
1480 
1481     return 0;
1482 }
1483 
1484 /*
1485  * Fill the first-index table for "lp".
1486  */
1487     static void
1488 set_sal_first(slang_T *lp)
1489 {
1490     salfirst_T	*sfirst;
1491     int		i;
1492     salitem_T	*smp;
1493     int		c;
1494     garray_T	*gap = &lp->sl_sal;
1495 
1496     sfirst = lp->sl_sal_first;
1497     for (i = 0; i < 256; ++i)
1498 	sfirst[i] = -1;
1499     smp = (salitem_T *)gap->ga_data;
1500     for (i = 0; i < gap->ga_len; ++i)
1501     {
1502 	if (has_mbyte)
1503 	    // Use the lowest byte of the first character.  For latin1 it's
1504 	    // the character, for other encodings it should differ for most
1505 	    // characters.
1506 	    c = *smp[i].sm_lead_w & 0xff;
1507 	else
1508 	    c = *smp[i].sm_lead;
1509 	if (sfirst[c] == -1)
1510 	{
1511 	    sfirst[c] = i;
1512 	    if (has_mbyte)
1513 	    {
1514 		int		n;
1515 
1516 		// Make sure all entries with this byte are following each
1517 		// other.  Move the ones that are in the wrong position.  Do
1518 		// keep the same ordering!
1519 		while (i + 1 < gap->ga_len
1520 				       && (*smp[i + 1].sm_lead_w & 0xff) == c)
1521 		    // Skip over entry with same index byte.
1522 		    ++i;
1523 
1524 		for (n = 1; i + n < gap->ga_len; ++n)
1525 		    if ((*smp[i + n].sm_lead_w & 0xff) == c)
1526 		    {
1527 			salitem_T  tsal;
1528 
1529 			// Move entry with same index byte after the entries
1530 			// we already found.
1531 			++i;
1532 			--n;
1533 			tsal = smp[i + n];
1534 			mch_memmove(smp + i + 1, smp + i,
1535 						       sizeof(salitem_T) * n);
1536 			smp[i] = tsal;
1537 		    }
1538 	    }
1539 	}
1540     }
1541 }
1542 
1543 /*
1544  * Turn a multi-byte string into a wide character string.
1545  * Return it in allocated memory (NULL for out-of-memory)
1546  */
1547     static int *
1548 mb_str2wide(char_u *s)
1549 {
1550     int		*res;
1551     char_u	*p;
1552     int		i = 0;
1553 
1554     res = ALLOC_MULT(int, mb_charlen(s) + 1);
1555     if (res != NULL)
1556     {
1557 	for (p = s; *p != NUL; )
1558 	    res[i++] = mb_ptr2char_adv(&p);
1559 	res[i] = NUL;
1560     }
1561     return res;
1562 }
1563 
1564 /*
1565  * Read a tree from the .spl or .sug file.
1566  * Allocates the memory and stores pointers in "bytsp" and "idxsp".
1567  * This is skipped when the tree has zero length.
1568  * Returns zero when OK, SP_ value for an error.
1569  */
1570     static int
1571 spell_read_tree(
1572     FILE	*fd,
1573     char_u	**bytsp,
1574     idx_T	**idxsp,
1575     int		prefixtree,	// TRUE for the prefix tree
1576     int		prefixcnt)	// when "prefixtree" is TRUE: prefix count
1577 {
1578     long	len;
1579     int		idx;
1580     char_u	*bp;
1581     idx_T	*ip;
1582 
1583     // The tree size was computed when writing the file, so that we can
1584     // allocate it as one long block. <nodecount>
1585     len = get4c(fd);
1586     if (len < 0)
1587 	return SP_TRUNCERROR;
1588     if (len >= LONG_MAX / (long)sizeof(int))
1589 	// Invalid length, multiply with sizeof(int) would overflow.
1590 	return SP_FORMERROR;
1591     if (len > 0)
1592     {
1593 	// Allocate the byte array.
1594 	bp = alloc(len);
1595 	if (bp == NULL)
1596 	    return SP_OTHERERROR;
1597 	*bytsp = bp;
1598 
1599 	// Allocate the index array.
1600 	ip = lalloc_clear(len * sizeof(int), TRUE);
1601 	if (ip == NULL)
1602 	    return SP_OTHERERROR;
1603 	*idxsp = ip;
1604 
1605 	// Recursively read the tree and store it in the array.
1606 	idx = read_tree_node(fd, bp, ip, len, 0, prefixtree, prefixcnt);
1607 	if (idx < 0)
1608 	    return idx;
1609     }
1610     return 0;
1611 }
1612 
1613 /*
1614  * Read one row of siblings from the spell file and store it in the byte array
1615  * "byts" and index array "idxs".  Recursively read the children.
1616  *
1617  * NOTE: The code here must match put_node()!
1618  *
1619  * Returns the index (>= 0) following the siblings.
1620  * Returns SP_TRUNCERROR if the file is shorter than expected.
1621  * Returns SP_FORMERROR if there is a format error.
1622  */
1623     static idx_T
1624 read_tree_node(
1625     FILE	*fd,
1626     char_u	*byts,
1627     idx_T	*idxs,
1628     int		maxidx,		    // size of arrays
1629     idx_T	startidx,	    // current index in "byts" and "idxs"
1630     int		prefixtree,	    // TRUE for reading PREFIXTREE
1631     int		maxprefcondnr)	    // maximum for <prefcondnr>
1632 {
1633     int		len;
1634     int		i;
1635     int		n;
1636     idx_T	idx = startidx;
1637     int		c;
1638     int		c2;
1639 #define SHARED_MASK	0x8000000
1640 
1641     len = getc(fd);					// <siblingcount>
1642     if (len <= 0)
1643 	return SP_TRUNCERROR;
1644 
1645     if (startidx + len >= maxidx)
1646 	return SP_FORMERROR;
1647     byts[idx++] = len;
1648 
1649     // Read the byte values, flag/region bytes and shared indexes.
1650     for (i = 1; i <= len; ++i)
1651     {
1652 	c = getc(fd);					// <byte>
1653 	if (c < 0)
1654 	    return SP_TRUNCERROR;
1655 	if (c <= BY_SPECIAL)
1656 	{
1657 	    if (c == BY_NOFLAGS && !prefixtree)
1658 	    {
1659 		// No flags, all regions.
1660 		idxs[idx] = 0;
1661 		c = 0;
1662 	    }
1663 	    else if (c != BY_INDEX)
1664 	    {
1665 		if (prefixtree)
1666 		{
1667 		    // Read the optional pflags byte, the prefix ID and the
1668 		    // condition nr.  In idxs[] store the prefix ID in the low
1669 		    // byte, the condition index shifted up 8 bits, the flags
1670 		    // shifted up 24 bits.
1671 		    if (c == BY_FLAGS)
1672 			c = getc(fd) << 24;		// <pflags>
1673 		    else
1674 			c = 0;
1675 
1676 		    c |= getc(fd);			// <affixID>
1677 
1678 		    n = get2c(fd);			// <prefcondnr>
1679 		    if (n >= maxprefcondnr)
1680 			return SP_FORMERROR;
1681 		    c |= (n << 8);
1682 		}
1683 		else // c must be BY_FLAGS or BY_FLAGS2
1684 		{
1685 		    // Read flags and optional region and prefix ID.  In
1686 		    // idxs[] the flags go in the low two bytes, region above
1687 		    // that and prefix ID above the region.
1688 		    c2 = c;
1689 		    c = getc(fd);			// <flags>
1690 		    if (c2 == BY_FLAGS2)
1691 			c = (getc(fd) << 8) + c;	// <flags2>
1692 		    if (c & WF_REGION)
1693 			c = (getc(fd) << 16) + c;	// <region>
1694 		    if (c & WF_AFX)
1695 			c = (getc(fd) << 24) + c;	// <affixID>
1696 		}
1697 
1698 		idxs[idx] = c;
1699 		c = 0;
1700 	    }
1701 	    else // c == BY_INDEX
1702 	    {
1703 							// <nodeidx>
1704 		n = get3c(fd);
1705 		if (n < 0 || n >= maxidx)
1706 		    return SP_FORMERROR;
1707 		idxs[idx] = n + SHARED_MASK;
1708 		c = getc(fd);				// <xbyte>
1709 	    }
1710 	}
1711 	byts[idx++] = c;
1712     }
1713 
1714     // Recursively read the children for non-shared siblings.
1715     // Skip the end-of-word ones (zero byte value) and the shared ones (and
1716     // remove SHARED_MASK)
1717     for (i = 1; i <= len; ++i)
1718 	if (byts[startidx + i] != 0)
1719 	{
1720 	    if (idxs[startidx + i] & SHARED_MASK)
1721 		idxs[startidx + i] &= ~SHARED_MASK;
1722 	    else
1723 	    {
1724 		idxs[startidx + i] = idx;
1725 		idx = read_tree_node(fd, byts, idxs, maxidx, idx,
1726 						     prefixtree, maxprefcondnr);
1727 		if (idx < 0)
1728 		    break;
1729 	    }
1730 	}
1731 
1732     return idx;
1733 }
1734 
1735 /*
1736  * Reload the spell file "fname" if it's loaded.
1737  */
1738     static void
1739 spell_reload_one(
1740     char_u	*fname,
1741     int		added_word)	// invoked through "zg"
1742 {
1743     slang_T	*slang;
1744     int		didit = FALSE;
1745 
1746     FOR_ALL_SPELL_LANGS(slang)
1747     {
1748 	if (fullpathcmp(fname, slang->sl_fname, FALSE, TRUE) == FPC_SAME)
1749 	{
1750 	    slang_clear(slang);
1751 	    if (spell_load_file(fname, NULL, slang, FALSE) == NULL)
1752 		// reloading failed, clear the language
1753 		slang_clear(slang);
1754 	    redraw_all_later(SOME_VALID);
1755 	    didit = TRUE;
1756 	}
1757     }
1758 
1759     // When "zg" was used and the file wasn't loaded yet, should redo
1760     // 'spelllang' to load it now.
1761     if (added_word && !didit)
1762 	did_set_spelllang(curwin);
1763 }
1764 
1765 
1766 /*
1767  * Functions for ":mkspell".
1768  */
1769 
1770 #define MAXLINELEN  500		// Maximum length in bytes of a line in a .aff
1771 				// and .dic file.
1772 /*
1773  * Main structure to store the contents of a ".aff" file.
1774  */
1775 typedef struct afffile_S
1776 {
1777     char_u	*af_enc;	// "SET", normalized, alloc'ed string or NULL
1778     int		af_flagtype;	// AFT_CHAR, AFT_LONG, AFT_NUM or AFT_CAPLONG
1779     unsigned	af_rare;	// RARE ID for rare word
1780     unsigned	af_keepcase;	// KEEPCASE ID for keep-case word
1781     unsigned	af_bad;		// BAD ID for banned word
1782     unsigned	af_needaffix;	// NEEDAFFIX ID
1783     unsigned	af_circumfix;	// CIRCUMFIX ID
1784     unsigned	af_needcomp;	// NEEDCOMPOUND ID
1785     unsigned	af_comproot;	// COMPOUNDROOT ID
1786     unsigned	af_compforbid;	// COMPOUNDFORBIDFLAG ID
1787     unsigned	af_comppermit;	// COMPOUNDPERMITFLAG ID
1788     unsigned	af_nosuggest;	// NOSUGGEST ID
1789     int		af_pfxpostpone;	// postpone prefixes without chop string and
1790 				// without flags
1791     int		af_ignoreextra;	// IGNOREEXTRA present
1792     hashtab_T	af_pref;	// hashtable for prefixes, affheader_T
1793     hashtab_T	af_suff;	// hashtable for suffixes, affheader_T
1794     hashtab_T	af_comp;	// hashtable for compound flags, compitem_T
1795 } afffile_T;
1796 
1797 #define AFT_CHAR	0	// flags are one character
1798 #define AFT_LONG	1	// flags are two characters
1799 #define AFT_CAPLONG	2	// flags are one or two characters
1800 #define AFT_NUM		3	// flags are numbers, comma separated
1801 
1802 typedef struct affentry_S affentry_T;
1803 // Affix entry from ".aff" file.  Used for prefixes and suffixes.
1804 struct affentry_S
1805 {
1806     affentry_T	*ae_next;	// next affix with same name/number
1807     char_u	*ae_chop;	// text to chop off basic word (can be NULL)
1808     char_u	*ae_add;	// text to add to basic word (can be NULL)
1809     char_u	*ae_flags;	// flags on the affix (can be NULL)
1810     char_u	*ae_cond;	// condition (NULL for ".")
1811     regprog_T	*ae_prog;	// regexp program for ae_cond or NULL
1812     char	ae_compforbid;	// COMPOUNDFORBIDFLAG found
1813     char	ae_comppermit;	// COMPOUNDPERMITFLAG found
1814 };
1815 
1816 #define AH_KEY_LEN 17		// 2 x 8 bytes + NUL
1817 
1818 // Affix header from ".aff" file.  Used for af_pref and af_suff.
1819 typedef struct affheader_S
1820 {
1821     char_u	ah_key[AH_KEY_LEN]; // key for hashtab == name of affix
1822     unsigned	ah_flag;	// affix name as number, uses "af_flagtype"
1823     int		ah_newID;	// prefix ID after renumbering; 0 if not used
1824     int		ah_combine;	// suffix may combine with prefix
1825     int		ah_follows;	// another affix block should be following
1826     affentry_T	*ah_first;	// first affix entry
1827 } affheader_T;
1828 
1829 #define HI2AH(hi)   ((affheader_T *)(hi)->hi_key)
1830 
1831 // Flag used in compound items.
1832 typedef struct compitem_S
1833 {
1834     char_u	ci_key[AH_KEY_LEN]; // key for hashtab == name of compound
1835     unsigned	ci_flag;	// affix name as number, uses "af_flagtype"
1836     int		ci_newID;	// affix ID after renumbering.
1837 } compitem_T;
1838 
1839 #define HI2CI(hi)   ((compitem_T *)(hi)->hi_key)
1840 
1841 /*
1842  * Structure that is used to store the items in the word tree.  This avoids
1843  * the need to keep track of each allocated thing, everything is freed all at
1844  * once after ":mkspell" is done.
1845  * Note: "sb_next" must be just before "sb_data" to make sure the alignment of
1846  * "sb_data" is correct for systems where pointers must be aligned on
1847  * pointer-size boundaries and sizeof(pointer) > sizeof(int) (e.g., Sparc).
1848  */
1849 #define  SBLOCKSIZE 16000	// size of sb_data
1850 typedef struct sblock_S sblock_T;
1851 struct sblock_S
1852 {
1853     int		sb_used;	// nr of bytes already in use
1854     sblock_T	*sb_next;	// next block in list
1855     char_u	sb_data[1];	// data, actually longer
1856 };
1857 
1858 /*
1859  * A node in the tree.
1860  */
1861 typedef struct wordnode_S wordnode_T;
1862 struct wordnode_S
1863 {
1864     union   // shared to save space
1865     {
1866 	char_u	hashkey[6];	// the hash key, only used while compressing
1867 	int	index;		// index in written nodes (valid after first
1868 				// round)
1869     } wn_u1;
1870     union   // shared to save space
1871     {
1872 	wordnode_T *next;	// next node with same hash key
1873 	wordnode_T *wnode;	// parent node that will write this node
1874     } wn_u2;
1875     wordnode_T	*wn_child;	// child (next byte in word)
1876     wordnode_T  *wn_sibling;	// next sibling (alternate byte in word,
1877 				// always sorted)
1878     int		wn_refs;	// Nr. of references to this node.  Only
1879 				// relevant for first node in a list of
1880 				// siblings, in following siblings it is
1881 				// always one.
1882     char_u	wn_byte;	// Byte for this node. NUL for word end
1883 
1884     // Info for when "wn_byte" is NUL.
1885     // In PREFIXTREE "wn_region" is used for the prefcondnr.
1886     // In the soundfolded word tree "wn_flags" has the MSW of the wordnr and
1887     // "wn_region" the LSW of the wordnr.
1888     char_u	wn_affixID;	// supported/required prefix ID or 0
1889     short_u	wn_flags;	// WF_ flags
1890     short	wn_region;	// region mask
1891 
1892 #ifdef SPELL_PRINTTREE
1893     int		wn_nr;		// sequence nr for printing
1894 #endif
1895 };
1896 
1897 #define WN_MASK	 0xffff		// mask relevant bits of "wn_flags"
1898 
1899 #define HI2WN(hi)    (wordnode_T *)((hi)->hi_key)
1900 
1901 /*
1902  * Info used while reading the spell files.
1903  */
1904 typedef struct spellinfo_S
1905 {
1906     wordnode_T	*si_foldroot;	// tree with case-folded words
1907     long	si_foldwcount;	// nr of words in si_foldroot
1908 
1909     wordnode_T	*si_keeproot;	// tree with keep-case words
1910     long	si_keepwcount;	// nr of words in si_keeproot
1911 
1912     wordnode_T	*si_prefroot;	// tree with postponed prefixes
1913 
1914     long	si_sugtree;	// creating the soundfolding trie
1915 
1916     sblock_T	*si_blocks;	// memory blocks used
1917     long	si_blocks_cnt;	// memory blocks allocated
1918     int		si_did_emsg;	// TRUE when ran out of memory
1919 
1920     long	si_compress_cnt;    // words to add before lowering
1921 				    // compression limit
1922     wordnode_T	*si_first_free; // List of nodes that have been freed during
1923 				// compression, linked by "wn_child" field.
1924     long	si_free_count;	// number of nodes in si_first_free
1925 #ifdef SPELL_PRINTTREE
1926     int		si_wordnode_nr;	// sequence nr for nodes
1927 #endif
1928     buf_T	*si_spellbuf;	// buffer used to store soundfold word table
1929 
1930     int		si_ascii;	// handling only ASCII words
1931     int		si_add;		// addition file
1932     int		si_clear_chartab;   // when TRUE clear char tables
1933     int		si_region;	// region mask
1934     vimconv_T	si_conv;	// for conversion to 'encoding'
1935     int		si_memtot;	// runtime memory used
1936     int		si_verbose;	// verbose messages
1937     int		si_msg_count;	// number of words added since last message
1938     char_u	*si_info;	// info text chars or NULL
1939     int		si_region_count; // number of regions supported (1 when there
1940 				 // are no regions)
1941     char_u	si_region_name[MAXREGIONS * 2 + 1];
1942 				// region names; used only if
1943 				// si_region_count > 1)
1944 
1945     garray_T	si_rep;		// list of fromto_T entries from REP lines
1946     garray_T	si_repsal;	// list of fromto_T entries from REPSAL lines
1947     garray_T	si_sal;		// list of fromto_T entries from SAL lines
1948     char_u	*si_sofofr;	// SOFOFROM text
1949     char_u	*si_sofoto;	// SOFOTO text
1950     int		si_nosugfile;	// NOSUGFILE item found
1951     int		si_nosplitsugs;	// NOSPLITSUGS item found
1952     int		si_nocompoundsugs; // NOCOMPOUNDSUGS item found
1953     int		si_followup;	// soundsalike: ?
1954     int		si_collapse;	// soundsalike: ?
1955     hashtab_T	si_commonwords;	// hashtable for common words
1956     time_t	si_sugtime;	// timestamp for .sug file
1957     int		si_rem_accents;	// soundsalike: remove accents
1958     garray_T	si_map;		// MAP info concatenated
1959     char_u	*si_midword;	// MIDWORD chars or NULL
1960     int		si_compmax;	// max nr of words for compounding
1961     int		si_compminlen;	// minimal length for compounding
1962     int		si_compsylmax;	// max nr of syllables for compounding
1963     int		si_compoptions;	// COMP_ flags
1964     garray_T	si_comppat;	// CHECKCOMPOUNDPATTERN items, each stored as
1965 				// a string
1966     char_u	*si_compflags;	// flags used for compounding
1967     char_u	si_nobreak;	// NOBREAK
1968     char_u	*si_syllable;	// syllable string
1969     garray_T	si_prefcond;	// table with conditions for postponed
1970 				// prefixes, each stored as a string
1971     int		si_newprefID;	// current value for ah_newID
1972     int		si_newcompID;	// current value for compound ID
1973 } spellinfo_T;
1974 
1975 static int is_aff_rule(char_u **items, int itemcnt, char *rulename, int	 mincount);
1976 static void aff_process_flags(afffile_T *affile, affentry_T *entry);
1977 static int spell_info_item(char_u *s);
1978 static unsigned affitem2flag(int flagtype, char_u *item, char_u	*fname, int lnum);
1979 static unsigned get_affitem(int flagtype, char_u **pp);
1980 static void process_compflags(spellinfo_T *spin, afffile_T *aff, char_u *compflags);
1981 static void check_renumber(spellinfo_T *spin);
1982 static void aff_check_number(int spinval, int affval, char *name);
1983 static void aff_check_string(char_u *spinval, char_u *affval, char *name);
1984 static int str_equal(char_u *s1, char_u	*s2);
1985 static void add_fromto(spellinfo_T *spin, garray_T *gap, char_u	*from, char_u *to);
1986 static int sal_to_bool(char_u *s);
1987 static int get_affix_flags(afffile_T *affile, char_u *afflist);
1988 static int get_pfxlist(afffile_T *affile, char_u *afflist, char_u *store_afflist);
1989 static void get_compflags(afffile_T *affile, char_u *afflist, char_u *store_afflist);
1990 static int store_aff_word(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);
1991 static void *getroom(spellinfo_T *spin, size_t len, int align);
1992 static char_u *getroom_save(spellinfo_T *spin, char_u *s);
1993 static int store_word(spellinfo_T *spin, char_u *word, int flags, int region, char_u *pfxlist, int need_affix);
1994 static int tree_add_word(spellinfo_T *spin, char_u *word, wordnode_T *tree, int flags, int region, int affixID);
1995 static wordnode_T *get_wordnode(spellinfo_T *spin);
1996 static void free_wordnode(spellinfo_T *spin, wordnode_T *n);
1997 static void wordtree_compress(spellinfo_T *spin, wordnode_T *root);
1998 static int node_compress(spellinfo_T *spin, wordnode_T *node, hashtab_T *ht, int *tot);
1999 static int node_equal(wordnode_T *n1, wordnode_T *n2);
2000 static void clear_node(wordnode_T *node);
2001 static int put_node(FILE *fd, wordnode_T *node, int idx, int regionmask, int prefixtree);
2002 static int sug_filltree(spellinfo_T *spin, slang_T *slang);
2003 static int sug_maketable(spellinfo_T *spin);
2004 static int sug_filltable(spellinfo_T *spin, wordnode_T *node, int startwordnr, garray_T *gap);
2005 static int offset2bytes(int nr, char_u *buf);
2006 static void sug_write(spellinfo_T *spin, char_u *fname);
2007 static void spell_message(spellinfo_T *spin, char_u *str);
2008 static void init_spellfile(void);
2009 
2010 // In the postponed prefixes tree wn_flags is used to store the WFP_ flags,
2011 // but it must be negative to indicate the prefix tree to tree_add_word().
2012 // Use a negative number with the lower 8 bits zero.
2013 #define PFX_FLAGS	-256
2014 
2015 // flags for "condit" argument of store_aff_word()
2016 #define CONDIT_COMB	1	// affix must combine
2017 #define CONDIT_CFIX	2	// affix must have CIRCUMFIX flag
2018 #define CONDIT_SUF	4	// add a suffix for matching flags
2019 #define CONDIT_AFF	8	// word already has an affix
2020 
2021 /*
2022  * Tunable parameters for when the tree is compressed.  See 'mkspellmem'.
2023  */
2024 static long compress_start = 30000;	// memory / SBLOCKSIZE
2025 static long compress_inc = 100;		// memory / SBLOCKSIZE
2026 static long compress_added = 500000;	// word count
2027 
2028 /*
2029  * Check the 'mkspellmem' option.  Return FAIL if it's wrong.
2030  * Sets "sps_flags".
2031  */
2032     int
2033 spell_check_msm(void)
2034 {
2035     char_u	*p = p_msm;
2036     long	start = 0;
2037     long	incr = 0;
2038     long	added = 0;
2039 
2040     if (!VIM_ISDIGIT(*p))
2041 	return FAIL;
2042     // block count = (value * 1024) / SBLOCKSIZE (but avoid overflow)
2043     start = (getdigits(&p) * 10) / (SBLOCKSIZE / 102);
2044     if (*p != ',')
2045 	return FAIL;
2046     ++p;
2047     if (!VIM_ISDIGIT(*p))
2048 	return FAIL;
2049     incr = (getdigits(&p) * 102) / (SBLOCKSIZE / 10);
2050     if (*p != ',')
2051 	return FAIL;
2052     ++p;
2053     if (!VIM_ISDIGIT(*p))
2054 	return FAIL;
2055     added = getdigits(&p) * 1024;
2056     if (*p != NUL)
2057 	return FAIL;
2058 
2059     if (start == 0 || incr == 0 || added == 0 || incr > start)
2060 	return FAIL;
2061 
2062     compress_start = start;
2063     compress_inc = incr;
2064     compress_added = added;
2065     return OK;
2066 }
2067 
2068 #ifdef SPELL_PRINTTREE
2069 /*
2070  * For debugging the tree code: print the current tree in a (more or less)
2071  * readable format, so that we can see what happens when adding a word and/or
2072  * compressing the tree.
2073  * Based on code from Olaf Seibert.
2074  */
2075 #define PRINTLINESIZE	1000
2076 #define PRINTWIDTH	6
2077 
2078 #define PRINTSOME(l, depth, fmt, a1, a2) vim_snprintf(l + depth * PRINTWIDTH, \
2079 	    PRINTLINESIZE - PRINTWIDTH * depth, fmt, a1, a2)
2080 
2081 static char line1[PRINTLINESIZE];
2082 static char line2[PRINTLINESIZE];
2083 static char line3[PRINTLINESIZE];
2084 
2085     static void
2086 spell_clear_flags(wordnode_T *node)
2087 {
2088     wordnode_T	*np;
2089 
2090     FOR_ALL_NODE_SIBLINGS(node, np)
2091     {
2092 	np->wn_u1.index = FALSE;
2093 	spell_clear_flags(np->wn_child);
2094     }
2095 }
2096 
2097     static void
2098 spell_print_node(wordnode_T *node, int depth)
2099 {
2100     if (node->wn_u1.index)
2101     {
2102 	// Done this node before, print the reference.
2103 	PRINTSOME(line1, depth, "(%d)", node->wn_nr, 0);
2104 	PRINTSOME(line2, depth, "    ", 0, 0);
2105 	PRINTSOME(line3, depth, "    ", 0, 0);
2106 	msg(line1);
2107 	msg(line2);
2108 	msg(line3);
2109     }
2110     else
2111     {
2112 	node->wn_u1.index = TRUE;
2113 
2114 	if (node->wn_byte != NUL)
2115 	{
2116 	    if (node->wn_child != NULL)
2117 		PRINTSOME(line1, depth, " %c -> ", node->wn_byte, 0);
2118 	    else
2119 		// Cannot happen?
2120 		PRINTSOME(line1, depth, " %c ???", node->wn_byte, 0);
2121 	}
2122 	else
2123 	    PRINTSOME(line1, depth, " $    ", 0, 0);
2124 
2125 	PRINTSOME(line2, depth, "%d/%d    ", node->wn_nr, node->wn_refs);
2126 
2127 	if (node->wn_sibling != NULL)
2128 	    PRINTSOME(line3, depth, " |    ", 0, 0);
2129 	else
2130 	    PRINTSOME(line3, depth, "      ", 0, 0);
2131 
2132 	if (node->wn_byte == NUL)
2133 	{
2134 	    msg(line1);
2135 	    msg(line2);
2136 	    msg(line3);
2137 	}
2138 
2139 	// do the children
2140 	if (node->wn_byte != NUL && node->wn_child != NULL)
2141 	    spell_print_node(node->wn_child, depth + 1);
2142 
2143 	// do the siblings
2144 	if (node->wn_sibling != NULL)
2145 	{
2146 	    // get rid of all parent details except |
2147 	    STRCPY(line1, line3);
2148 	    STRCPY(line2, line3);
2149 	    spell_print_node(node->wn_sibling, depth);
2150 	}
2151     }
2152 }
2153 
2154     static void
2155 spell_print_tree(wordnode_T *root)
2156 {
2157     if (root != NULL)
2158     {
2159 	// Clear the "wn_u1.index" fields, used to remember what has been
2160 	// done.
2161 	spell_clear_flags(root);
2162 
2163 	// Recursively print the tree.
2164 	spell_print_node(root, 0);
2165     }
2166 }
2167 #endif // SPELL_PRINTTREE
2168 
2169 /*
2170  * Read the affix file "fname".
2171  * Returns an afffile_T, NULL for complete failure.
2172  */
2173     static afffile_T *
2174 spell_read_aff(spellinfo_T *spin, char_u *fname)
2175 {
2176     FILE	*fd;
2177     afffile_T	*aff;
2178     char_u	rline[MAXLINELEN];
2179     char_u	*line;
2180     char_u	*pc = NULL;
2181 #define MAXITEMCNT  30
2182     char_u	*(items[MAXITEMCNT]);
2183     int		itemcnt;
2184     char_u	*p;
2185     int		lnum = 0;
2186     affheader_T	*cur_aff = NULL;
2187     int		did_postpone_prefix = FALSE;
2188     int		aff_todo = 0;
2189     hashtab_T	*tp;
2190     char_u	*low = NULL;
2191     char_u	*fol = NULL;
2192     char_u	*upp = NULL;
2193     int		do_rep;
2194     int		do_repsal;
2195     int		do_sal;
2196     int		do_mapline;
2197     int		found_map = FALSE;
2198     hashitem_T	*hi;
2199     int		l;
2200     int		compminlen = 0;		// COMPOUNDMIN value
2201     int		compsylmax = 0;		// COMPOUNDSYLMAX value
2202     int		compoptions = 0;	// COMP_ flags
2203     int		compmax = 0;		// COMPOUNDWORDMAX value
2204     char_u	*compflags = NULL;	// COMPOUNDFLAG and COMPOUNDRULE
2205 					// concatenated
2206     char_u	*midword = NULL;	// MIDWORD value
2207     char_u	*syllable = NULL;	// SYLLABLE value
2208     char_u	*sofofrom = NULL;	// SOFOFROM value
2209     char_u	*sofoto = NULL;		// SOFOTO value
2210 
2211     /*
2212      * Open the file.
2213      */
2214     fd = mch_fopen((char *)fname, "r");
2215     if (fd == NULL)
2216     {
2217 	semsg(_(e_notopen), fname);
2218 	return NULL;
2219     }
2220 
2221     vim_snprintf((char *)IObuff, IOSIZE, _("Reading affix file %s..."), fname);
2222     spell_message(spin, IObuff);
2223 
2224     // Only do REP lines when not done in another .aff file already.
2225     do_rep = spin->si_rep.ga_len == 0;
2226 
2227     // Only do REPSAL lines when not done in another .aff file already.
2228     do_repsal = spin->si_repsal.ga_len == 0;
2229 
2230     // Only do SAL lines when not done in another .aff file already.
2231     do_sal = spin->si_sal.ga_len == 0;
2232 
2233     // Only do MAP lines when not done in another .aff file already.
2234     do_mapline = spin->si_map.ga_len == 0;
2235 
2236     /*
2237      * Allocate and init the afffile_T structure.
2238      */
2239     aff = (afffile_T *)getroom(spin, sizeof(afffile_T), TRUE);
2240     if (aff == NULL)
2241     {
2242 	fclose(fd);
2243 	return NULL;
2244     }
2245     hash_init(&aff->af_pref);
2246     hash_init(&aff->af_suff);
2247     hash_init(&aff->af_comp);
2248 
2249     /*
2250      * Read all the lines in the file one by one.
2251      */
2252     while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
2253     {
2254 	line_breakcheck();
2255 	++lnum;
2256 
2257 	// Skip comment lines.
2258 	if (*rline == '#')
2259 	    continue;
2260 
2261 	// Convert from "SET" to 'encoding' when needed.
2262 	vim_free(pc);
2263 	if (spin->si_conv.vc_type != CONV_NONE)
2264 	{
2265 	    pc = string_convert(&spin->si_conv, rline, NULL);
2266 	    if (pc == NULL)
2267 	    {
2268 		smsg(_("Conversion failure for word in %s line %d: %s"),
2269 							   fname, lnum, rline);
2270 		continue;
2271 	    }
2272 	    line = pc;
2273 	}
2274 	else
2275 	{
2276 	    pc = NULL;
2277 	    line = rline;
2278 	}
2279 
2280 	// Split the line up in white separated items.  Put a NUL after each
2281 	// item.
2282 	itemcnt = 0;
2283 	for (p = line; ; )
2284 	{
2285 	    while (*p != NUL && *p <= ' ')  // skip white space and CR/NL
2286 		++p;
2287 	    if (*p == NUL)
2288 		break;
2289 	    if (itemcnt == MAXITEMCNT)	    // too many items
2290 		break;
2291 	    items[itemcnt++] = p;
2292 	    // A few items have arbitrary text argument, don't split them.
2293 	    if (itemcnt == 2 && spell_info_item(items[0]))
2294 		while (*p >= ' ' || *p == TAB)    // skip until CR/NL
2295 		    ++p;
2296 	    else
2297 		while (*p > ' ')    // skip until white space or CR/NL
2298 		    ++p;
2299 	    if (*p == NUL)
2300 		break;
2301 	    *p++ = NUL;
2302 	}
2303 
2304 	// Handle non-empty lines.
2305 	if (itemcnt > 0)
2306 	{
2307 	    if (is_aff_rule(items, itemcnt, "SET", 2) && aff->af_enc == NULL)
2308 	    {
2309 		// Setup for conversion from "ENC" to 'encoding'.
2310 		aff->af_enc = enc_canonize(items[1]);
2311 		if (aff->af_enc != NULL && !spin->si_ascii
2312 			&& convert_setup(&spin->si_conv, aff->af_enc,
2313 							       p_enc) == FAIL)
2314 		    smsg(_("Conversion in %s not supported: from %s to %s"),
2315 					       fname, aff->af_enc, p_enc);
2316 		spin->si_conv.vc_fail = TRUE;
2317 	    }
2318 	    else if (is_aff_rule(items, itemcnt, "FLAG", 2)
2319 					      && aff->af_flagtype == AFT_CHAR)
2320 	    {
2321 		if (STRCMP(items[1], "long") == 0)
2322 		    aff->af_flagtype = AFT_LONG;
2323 		else if (STRCMP(items[1], "num") == 0)
2324 		    aff->af_flagtype = AFT_NUM;
2325 		else if (STRCMP(items[1], "caplong") == 0)
2326 		    aff->af_flagtype = AFT_CAPLONG;
2327 		else
2328 		    smsg(_("Invalid value for FLAG in %s line %d: %s"),
2329 			    fname, lnum, items[1]);
2330 		if (aff->af_rare != 0
2331 			|| aff->af_keepcase != 0
2332 			|| aff->af_bad != 0
2333 			|| aff->af_needaffix != 0
2334 			|| aff->af_circumfix != 0
2335 			|| aff->af_needcomp != 0
2336 			|| aff->af_comproot != 0
2337 			|| aff->af_nosuggest != 0
2338 			|| compflags != NULL
2339 			|| aff->af_suff.ht_used > 0
2340 			|| aff->af_pref.ht_used > 0)
2341 		    smsg(_("FLAG after using flags in %s line %d: %s"),
2342 			    fname, lnum, items[1]);
2343 	    }
2344 	    else if (spell_info_item(items[0]))
2345 	    {
2346 		    p = (char_u *)getroom(spin,
2347 			    (spin->si_info == NULL ? 0 : STRLEN(spin->si_info))
2348 			    + STRLEN(items[0])
2349 			    + STRLEN(items[1]) + 3, FALSE);
2350 		    if (p != NULL)
2351 		    {
2352 			if (spin->si_info != NULL)
2353 			{
2354 			    STRCPY(p, spin->si_info);
2355 			    STRCAT(p, "\n");
2356 			}
2357 			STRCAT(p, items[0]);
2358 			STRCAT(p, " ");
2359 			STRCAT(p, items[1]);
2360 			spin->si_info = p;
2361 		    }
2362 	    }
2363 	    else if (is_aff_rule(items, itemcnt, "MIDWORD", 2)
2364 							   && midword == NULL)
2365 	    {
2366 		midword = getroom_save(spin, items[1]);
2367 	    }
2368 	    else if (is_aff_rule(items, itemcnt, "TRY", 2))
2369 	    {
2370 		// ignored, we look in the tree for what chars may appear
2371 	    }
2372 	    // TODO: remove "RAR" later
2373 	    else if ((is_aff_rule(items, itemcnt, "RAR", 2)
2374 			|| is_aff_rule(items, itemcnt, "RARE", 2))
2375 							 && aff->af_rare == 0)
2376 	    {
2377 		aff->af_rare = affitem2flag(aff->af_flagtype, items[1],
2378 								 fname, lnum);
2379 	    }
2380 	    // TODO: remove "KEP" later
2381 	    else if ((is_aff_rule(items, itemcnt, "KEP", 2)
2382 			|| is_aff_rule(items, itemcnt, "KEEPCASE", 2))
2383 						     && aff->af_keepcase == 0)
2384 	    {
2385 		aff->af_keepcase = affitem2flag(aff->af_flagtype, items[1],
2386 								 fname, lnum);
2387 	    }
2388 	    else if ((is_aff_rule(items, itemcnt, "BAD", 2)
2389 			|| is_aff_rule(items, itemcnt, "FORBIDDENWORD", 2))
2390 							  && aff->af_bad == 0)
2391 	    {
2392 		aff->af_bad = affitem2flag(aff->af_flagtype, items[1],
2393 								 fname, lnum);
2394 	    }
2395 	    else if (is_aff_rule(items, itemcnt, "NEEDAFFIX", 2)
2396 						    && aff->af_needaffix == 0)
2397 	    {
2398 		aff->af_needaffix = affitem2flag(aff->af_flagtype, items[1],
2399 								 fname, lnum);
2400 	    }
2401 	    else if (is_aff_rule(items, itemcnt, "CIRCUMFIX", 2)
2402 						    && aff->af_circumfix == 0)
2403 	    {
2404 		aff->af_circumfix = affitem2flag(aff->af_flagtype, items[1],
2405 								 fname, lnum);
2406 	    }
2407 	    else if (is_aff_rule(items, itemcnt, "NOSUGGEST", 2)
2408 						    && aff->af_nosuggest == 0)
2409 	    {
2410 		aff->af_nosuggest = affitem2flag(aff->af_flagtype, items[1],
2411 								 fname, lnum);
2412 	    }
2413 	    else if ((is_aff_rule(items, itemcnt, "NEEDCOMPOUND", 2)
2414 			|| is_aff_rule(items, itemcnt, "ONLYINCOMPOUND", 2))
2415 						     && aff->af_needcomp == 0)
2416 	    {
2417 		aff->af_needcomp = affitem2flag(aff->af_flagtype, items[1],
2418 								 fname, lnum);
2419 	    }
2420 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDROOT", 2)
2421 						     && aff->af_comproot == 0)
2422 	    {
2423 		aff->af_comproot = affitem2flag(aff->af_flagtype, items[1],
2424 								 fname, lnum);
2425 	    }
2426 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDFORBIDFLAG", 2)
2427 						   && aff->af_compforbid == 0)
2428 	    {
2429 		aff->af_compforbid = affitem2flag(aff->af_flagtype, items[1],
2430 								 fname, lnum);
2431 		if (aff->af_pref.ht_used > 0)
2432 		    smsg(_("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d"),
2433 			    fname, lnum);
2434 	    }
2435 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDPERMITFLAG", 2)
2436 						   && aff->af_comppermit == 0)
2437 	    {
2438 		aff->af_comppermit = affitem2flag(aff->af_flagtype, items[1],
2439 								 fname, lnum);
2440 		if (aff->af_pref.ht_used > 0)
2441 		    smsg(_("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d"),
2442 			    fname, lnum);
2443 	    }
2444 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDFLAG", 2)
2445 							 && compflags == NULL)
2446 	    {
2447 		// Turn flag "c" into COMPOUNDRULE compatible string "c+",
2448 		// "Na" into "Na+", "1234" into "1234+".
2449 		p = getroom(spin, STRLEN(items[1]) + 2, FALSE);
2450 		if (p != NULL)
2451 		{
2452 		    STRCPY(p, items[1]);
2453 		    STRCAT(p, "+");
2454 		    compflags = p;
2455 		}
2456 	    }
2457 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDRULES", 2))
2458 	    {
2459 		// We don't use the count, but do check that it's a number and
2460 		// not COMPOUNDRULE mistyped.
2461 		if (atoi((char *)items[1]) == 0)
2462 		    smsg(_("Wrong COMPOUNDRULES value in %s line %d: %s"),
2463 						       fname, lnum, items[1]);
2464 	    }
2465 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDRULE", 2))
2466 	    {
2467 		// Don't use the first rule if it is a number.
2468 		if (compflags != NULL || *skipdigits(items[1]) != NUL)
2469 		{
2470 		    // Concatenate this string to previously defined ones,
2471 		    // using a slash to separate them.
2472 		    l = (int)STRLEN(items[1]) + 1;
2473 		    if (compflags != NULL)
2474 			l += (int)STRLEN(compflags) + 1;
2475 		    p = getroom(spin, l, FALSE);
2476 		    if (p != NULL)
2477 		    {
2478 			if (compflags != NULL)
2479 			{
2480 			    STRCPY(p, compflags);
2481 			    STRCAT(p, "/");
2482 			}
2483 			STRCAT(p, items[1]);
2484 			compflags = p;
2485 		    }
2486 		}
2487 	    }
2488 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDWORDMAX", 2)
2489 							      && compmax == 0)
2490 	    {
2491 		compmax = atoi((char *)items[1]);
2492 		if (compmax == 0)
2493 		    smsg(_("Wrong COMPOUNDWORDMAX value in %s line %d: %s"),
2494 						       fname, lnum, items[1]);
2495 	    }
2496 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDMIN", 2)
2497 							   && compminlen == 0)
2498 	    {
2499 		compminlen = atoi((char *)items[1]);
2500 		if (compminlen == 0)
2501 		    smsg(_("Wrong COMPOUNDMIN value in %s line %d: %s"),
2502 						       fname, lnum, items[1]);
2503 	    }
2504 	    else if (is_aff_rule(items, itemcnt, "COMPOUNDSYLMAX", 2)
2505 							   && compsylmax == 0)
2506 	    {
2507 		compsylmax = atoi((char *)items[1]);
2508 		if (compsylmax == 0)
2509 		    smsg(_("Wrong COMPOUNDSYLMAX value in %s line %d: %s"),
2510 						       fname, lnum, items[1]);
2511 	    }
2512 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDDUP", 1))
2513 	    {
2514 		compoptions |= COMP_CHECKDUP;
2515 	    }
2516 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDREP", 1))
2517 	    {
2518 		compoptions |= COMP_CHECKREP;
2519 	    }
2520 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDCASE", 1))
2521 	    {
2522 		compoptions |= COMP_CHECKCASE;
2523 	    }
2524 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDTRIPLE", 1))
2525 	    {
2526 		compoptions |= COMP_CHECKTRIPLE;
2527 	    }
2528 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 2))
2529 	    {
2530 		if (atoi((char *)items[1]) == 0)
2531 		    smsg(_("Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s"),
2532 						       fname, lnum, items[1]);
2533 	    }
2534 	    else if (is_aff_rule(items, itemcnt, "CHECKCOMPOUNDPATTERN", 3))
2535 	    {
2536 		garray_T    *gap = &spin->si_comppat;
2537 		int	    i;
2538 
2539 		// Only add the couple if it isn't already there.
2540 		for (i = 0; i < gap->ga_len - 1; i += 2)
2541 		    if (STRCMP(((char_u **)(gap->ga_data))[i], items[1]) == 0
2542 			    && STRCMP(((char_u **)(gap->ga_data))[i + 1],
2543 							       items[2]) == 0)
2544 			break;
2545 		if (i >= gap->ga_len && ga_grow(gap, 2) == OK)
2546 		{
2547 		    ((char_u **)(gap->ga_data))[gap->ga_len++]
2548 					       = getroom_save(spin, items[1]);
2549 		    ((char_u **)(gap->ga_data))[gap->ga_len++]
2550 					       = getroom_save(spin, items[2]);
2551 		}
2552 	    }
2553 	    else if (is_aff_rule(items, itemcnt, "SYLLABLE", 2)
2554 							  && syllable == NULL)
2555 	    {
2556 		syllable = getroom_save(spin, items[1]);
2557 	    }
2558 	    else if (is_aff_rule(items, itemcnt, "NOBREAK", 1))
2559 	    {
2560 		spin->si_nobreak = TRUE;
2561 	    }
2562 	    else if (is_aff_rule(items, itemcnt, "NOSPLITSUGS", 1))
2563 	    {
2564 		spin->si_nosplitsugs = TRUE;
2565 	    }
2566 	    else if (is_aff_rule(items, itemcnt, "NOCOMPOUNDSUGS", 1))
2567 	    {
2568 		spin->si_nocompoundsugs = TRUE;
2569 	    }
2570 	    else if (is_aff_rule(items, itemcnt, "NOSUGFILE", 1))
2571 	    {
2572 		spin->si_nosugfile = TRUE;
2573 	    }
2574 	    else if (is_aff_rule(items, itemcnt, "PFXPOSTPONE", 1))
2575 	    {
2576 		aff->af_pfxpostpone = TRUE;
2577 	    }
2578 	    else if (is_aff_rule(items, itemcnt, "IGNOREEXTRA", 1))
2579 	    {
2580 		aff->af_ignoreextra = TRUE;
2581 	    }
2582 	    else if ((STRCMP(items[0], "PFX") == 0
2583 					      || STRCMP(items[0], "SFX") == 0)
2584 		    && aff_todo == 0
2585 		    && itemcnt >= 4)
2586 	    {
2587 		int	lasti = 4;
2588 		char_u	key[AH_KEY_LEN];
2589 
2590 		if (*items[0] == 'P')
2591 		    tp = &aff->af_pref;
2592 		else
2593 		    tp = &aff->af_suff;
2594 
2595 		// Myspell allows the same affix name to be used multiple
2596 		// times.  The affix files that do this have an undocumented
2597 		// "S" flag on all but the last block, thus we check for that
2598 		// and store it in ah_follows.
2599 		vim_strncpy(key, items[1], AH_KEY_LEN - 1);
2600 		hi = hash_find(tp, key);
2601 		if (!HASHITEM_EMPTY(hi))
2602 		{
2603 		    cur_aff = HI2AH(hi);
2604 		    if (cur_aff->ah_combine != (*items[2] == 'Y'))
2605 			smsg(_("Different combining flag in continued affix block in %s line %d: %s"),
2606 						   fname, lnum, items[1]);
2607 		    if (!cur_aff->ah_follows)
2608 			smsg(_("Duplicate affix in %s line %d: %s"),
2609 						       fname, lnum, items[1]);
2610 		}
2611 		else
2612 		{
2613 		    // New affix letter.
2614 		    cur_aff = (affheader_T *)getroom(spin,
2615 						   sizeof(affheader_T), TRUE);
2616 		    if (cur_aff == NULL)
2617 			break;
2618 		    cur_aff->ah_flag = affitem2flag(aff->af_flagtype, items[1],
2619 								 fname, lnum);
2620 		    if (cur_aff->ah_flag == 0 || STRLEN(items[1]) >= AH_KEY_LEN)
2621 			break;
2622 		    if (cur_aff->ah_flag == aff->af_bad
2623 			    || cur_aff->ah_flag == aff->af_rare
2624 			    || cur_aff->ah_flag == aff->af_keepcase
2625 			    || cur_aff->ah_flag == aff->af_needaffix
2626 			    || cur_aff->ah_flag == aff->af_circumfix
2627 			    || cur_aff->ah_flag == aff->af_nosuggest
2628 			    || cur_aff->ah_flag == aff->af_needcomp
2629 			    || cur_aff->ah_flag == aff->af_comproot)
2630 			smsg(_("Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST in %s line %d: %s"),
2631 						       fname, lnum, items[1]);
2632 		    STRCPY(cur_aff->ah_key, items[1]);
2633 		    hash_add(tp, cur_aff->ah_key);
2634 
2635 		    cur_aff->ah_combine = (*items[2] == 'Y');
2636 		}
2637 
2638 		// Check for the "S" flag, which apparently means that another
2639 		// block with the same affix name is following.
2640 		if (itemcnt > lasti && STRCMP(items[lasti], "S") == 0)
2641 		{
2642 		    ++lasti;
2643 		    cur_aff->ah_follows = TRUE;
2644 		}
2645 		else
2646 		    cur_aff->ah_follows = FALSE;
2647 
2648 		// Myspell allows extra text after the item, but that might
2649 		// mean mistakes go unnoticed.  Require a comment-starter.
2650 		if (itemcnt > lasti && *items[lasti] != '#')
2651 		    smsg(_(e_afftrailing), fname, lnum, items[lasti]);
2652 
2653 		if (STRCMP(items[2], "Y") != 0 && STRCMP(items[2], "N") != 0)
2654 		    smsg(_("Expected Y or N in %s line %d: %s"),
2655 						       fname, lnum, items[2]);
2656 
2657 		if (*items[0] == 'P' && aff->af_pfxpostpone)
2658 		{
2659 		    if (cur_aff->ah_newID == 0)
2660 		    {
2661 			// Use a new number in the .spl file later, to be able
2662 			// to handle multiple .aff files.
2663 			check_renumber(spin);
2664 			cur_aff->ah_newID = ++spin->si_newprefID;
2665 
2666 			// We only really use ah_newID if the prefix is
2667 			// postponed.  We know that only after handling all
2668 			// the items.
2669 			did_postpone_prefix = FALSE;
2670 		    }
2671 		    else
2672 			// Did use the ID in a previous block.
2673 			did_postpone_prefix = TRUE;
2674 		}
2675 
2676 		aff_todo = atoi((char *)items[3]);
2677 	    }
2678 	    else if ((STRCMP(items[0], "PFX") == 0
2679 					      || STRCMP(items[0], "SFX") == 0)
2680 		    && aff_todo > 0
2681 		    && STRCMP(cur_aff->ah_key, items[1]) == 0
2682 		    && itemcnt >= 5)
2683 	    {
2684 		affentry_T	*aff_entry;
2685 		int		upper = FALSE;
2686 		int		lasti = 5;
2687 
2688 		// Myspell allows extra text after the item, but that might
2689 		// mean mistakes go unnoticed.  Require a comment-starter,
2690 		// unless IGNOREEXTRA is used.  Hunspell uses a "-" item.
2691 		if (itemcnt > lasti
2692 			&& !aff->af_ignoreextra
2693 			&& *items[lasti] != '#'
2694 			&& (STRCMP(items[lasti], "-") != 0
2695 						     || itemcnt != lasti + 1))
2696 		    smsg(_(e_afftrailing), fname, lnum, items[lasti]);
2697 
2698 		// New item for an affix letter.
2699 		--aff_todo;
2700 		aff_entry = (affentry_T *)getroom(spin,
2701 						    sizeof(affentry_T), TRUE);
2702 		if (aff_entry == NULL)
2703 		    break;
2704 
2705 		if (STRCMP(items[2], "0") != 0)
2706 		    aff_entry->ae_chop = getroom_save(spin, items[2]);
2707 		if (STRCMP(items[3], "0") != 0)
2708 		{
2709 		    aff_entry->ae_add = getroom_save(spin, items[3]);
2710 
2711 		    // Recognize flags on the affix: abcd/XYZ
2712 		    aff_entry->ae_flags = vim_strchr(aff_entry->ae_add, '/');
2713 		    if (aff_entry->ae_flags != NULL)
2714 		    {
2715 			*aff_entry->ae_flags++ = NUL;
2716 			aff_process_flags(aff, aff_entry);
2717 		    }
2718 		}
2719 
2720 		// Don't use an affix entry with non-ASCII characters when
2721 		// "spin->si_ascii" is TRUE.
2722 		if (!spin->si_ascii || !(has_non_ascii(aff_entry->ae_chop)
2723 					  || has_non_ascii(aff_entry->ae_add)))
2724 		{
2725 		    aff_entry->ae_next = cur_aff->ah_first;
2726 		    cur_aff->ah_first = aff_entry;
2727 
2728 		    if (STRCMP(items[4], ".") != 0)
2729 		    {
2730 			char_u	buf[MAXLINELEN];
2731 
2732 			aff_entry->ae_cond = getroom_save(spin, items[4]);
2733 			if (*items[0] == 'P')
2734 			    sprintf((char *)buf, "^%s", items[4]);
2735 			else
2736 			    sprintf((char *)buf, "%s$", items[4]);
2737 			aff_entry->ae_prog = vim_regcomp(buf,
2738 					    RE_MAGIC + RE_STRING + RE_STRICT);
2739 			if (aff_entry->ae_prog == NULL)
2740 			    smsg(_("Broken condition in %s line %d: %s"),
2741 						       fname, lnum, items[4]);
2742 		    }
2743 
2744 		    // For postponed prefixes we need an entry in si_prefcond
2745 		    // for the condition.  Use an existing one if possible.
2746 		    // Can't be done for an affix with flags, ignoring
2747 		    // COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG.
2748 		    if (*items[0] == 'P' && aff->af_pfxpostpone
2749 					       && aff_entry->ae_flags == NULL)
2750 		    {
2751 			// When the chop string is one lower-case letter and
2752 			// the add string ends in the upper-case letter we set
2753 			// the "upper" flag, clear "ae_chop" and remove the
2754 			// letters from "ae_add".  The condition must either
2755 			// be empty or start with the same letter.
2756 			if (aff_entry->ae_chop != NULL
2757 				&& aff_entry->ae_add != NULL
2758 				&& aff_entry->ae_chop[(*mb_ptr2len)(
2759 						   aff_entry->ae_chop)] == NUL)
2760 			{
2761 			    int		c, c_up;
2762 
2763 			    c = PTR2CHAR(aff_entry->ae_chop);
2764 			    c_up = SPELL_TOUPPER(c);
2765 			    if (c_up != c
2766 				    && (aff_entry->ae_cond == NULL
2767 					|| PTR2CHAR(aff_entry->ae_cond) == c))
2768 			    {
2769 				p = aff_entry->ae_add
2770 						  + STRLEN(aff_entry->ae_add);
2771 				MB_PTR_BACK(aff_entry->ae_add, p);
2772 				if (PTR2CHAR(p) == c_up)
2773 				{
2774 				    upper = TRUE;
2775 				    aff_entry->ae_chop = NULL;
2776 				    *p = NUL;
2777 
2778 				    // The condition is matched with the
2779 				    // actual word, thus must check for the
2780 				    // upper-case letter.
2781 				    if (aff_entry->ae_cond != NULL)
2782 				    {
2783 					char_u	buf[MAXLINELEN];
2784 
2785 					if (has_mbyte)
2786 					{
2787 					    onecap_copy(items[4], buf, TRUE);
2788 					    aff_entry->ae_cond = getroom_save(
2789 								   spin, buf);
2790 					}
2791 					else
2792 					    *aff_entry->ae_cond = c_up;
2793 					if (aff_entry->ae_cond != NULL)
2794 					{
2795 					    sprintf((char *)buf, "^%s",
2796 							  aff_entry->ae_cond);
2797 					    vim_regfree(aff_entry->ae_prog);
2798 					    aff_entry->ae_prog = vim_regcomp(
2799 						    buf, RE_MAGIC + RE_STRING);
2800 					}
2801 				    }
2802 				}
2803 			    }
2804 			}
2805 
2806 			if (aff_entry->ae_chop == NULL
2807 					       && aff_entry->ae_flags == NULL)
2808 			{
2809 			    int		idx;
2810 			    char_u	**pp;
2811 			    int		n;
2812 
2813 			    // Find a previously used condition.
2814 			    for (idx = spin->si_prefcond.ga_len - 1; idx >= 0;
2815 									--idx)
2816 			    {
2817 				p = ((char_u **)spin->si_prefcond.ga_data)[idx];
2818 				if (str_equal(p, aff_entry->ae_cond))
2819 				    break;
2820 			    }
2821 			    if (idx < 0 && ga_grow(&spin->si_prefcond, 1) == OK)
2822 			    {
2823 				// Not found, add a new condition.
2824 				idx = spin->si_prefcond.ga_len++;
2825 				pp = ((char_u **)spin->si_prefcond.ga_data)
2826 									+ idx;
2827 				if (aff_entry->ae_cond == NULL)
2828 				    *pp = NULL;
2829 				else
2830 				    *pp = getroom_save(spin,
2831 							  aff_entry->ae_cond);
2832 			    }
2833 
2834 			    // Add the prefix to the prefix tree.
2835 			    if (aff_entry->ae_add == NULL)
2836 				p = (char_u *)"";
2837 			    else
2838 				p = aff_entry->ae_add;
2839 
2840 			    // PFX_FLAGS is a negative number, so that
2841 			    // tree_add_word() knows this is the prefix tree.
2842 			    n = PFX_FLAGS;
2843 			    if (!cur_aff->ah_combine)
2844 				n |= WFP_NC;
2845 			    if (upper)
2846 				n |= WFP_UP;
2847 			    if (aff_entry->ae_comppermit)
2848 				n |= WFP_COMPPERMIT;
2849 			    if (aff_entry->ae_compforbid)
2850 				n |= WFP_COMPFORBID;
2851 			    tree_add_word(spin, p, spin->si_prefroot, n,
2852 						      idx, cur_aff->ah_newID);
2853 			    did_postpone_prefix = TRUE;
2854 			}
2855 
2856 			// Didn't actually use ah_newID, backup si_newprefID.
2857 			if (aff_todo == 0 && !did_postpone_prefix)
2858 			{
2859 			    --spin->si_newprefID;
2860 			    cur_aff->ah_newID = 0;
2861 			}
2862 		    }
2863 		}
2864 	    }
2865 	    else if (is_aff_rule(items, itemcnt, "FOL", 2) && fol == NULL)
2866 	    {
2867 		fol = vim_strsave(items[1]);
2868 	    }
2869 	    else if (is_aff_rule(items, itemcnt, "LOW", 2) && low == NULL)
2870 	    {
2871 		low = vim_strsave(items[1]);
2872 	    }
2873 	    else if (is_aff_rule(items, itemcnt, "UPP", 2) && upp == NULL)
2874 	    {
2875 		upp = vim_strsave(items[1]);
2876 	    }
2877 	    else if (is_aff_rule(items, itemcnt, "REP", 2)
2878 		     || is_aff_rule(items, itemcnt, "REPSAL", 2))
2879 	    {
2880 		// Ignore REP/REPSAL count
2881 		if (!isdigit(*items[1]))
2882 		    smsg(_("Expected REP(SAL) count in %s line %d"),
2883 								 fname, lnum);
2884 	    }
2885 	    else if ((STRCMP(items[0], "REP") == 0
2886 			|| STRCMP(items[0], "REPSAL") == 0)
2887 		    && itemcnt >= 3)
2888 	    {
2889 		// REP/REPSAL item
2890 		// Myspell ignores extra arguments, we require it starts with
2891 		// # to detect mistakes.
2892 		if (itemcnt > 3 && items[3][0] != '#')
2893 		    smsg(_(e_afftrailing), fname, lnum, items[3]);
2894 		if (items[0][3] == 'S' ? do_repsal : do_rep)
2895 		{
2896 		    // Replace underscore with space (can't include a space
2897 		    // directly).
2898 		    for (p = items[1]; *p != NUL; MB_PTR_ADV(p))
2899 			if (*p == '_')
2900 			    *p = ' ';
2901 		    for (p = items[2]; *p != NUL; MB_PTR_ADV(p))
2902 			if (*p == '_')
2903 			    *p = ' ';
2904 		    add_fromto(spin, items[0][3] == 'S'
2905 					 ? &spin->si_repsal
2906 					 : &spin->si_rep, items[1], items[2]);
2907 		}
2908 	    }
2909 	    else if (is_aff_rule(items, itemcnt, "MAP", 2))
2910 	    {
2911 		// MAP item or count
2912 		if (!found_map)
2913 		{
2914 		    // First line contains the count.
2915 		    found_map = TRUE;
2916 		    if (!isdigit(*items[1]))
2917 			smsg(_("Expected MAP count in %s line %d"),
2918 								 fname, lnum);
2919 		}
2920 		else if (do_mapline)
2921 		{
2922 		    int		c;
2923 
2924 		    // Check that every character appears only once.
2925 		    for (p = items[1]; *p != NUL; )
2926 		    {
2927 			c = mb_ptr2char_adv(&p);
2928 			if ((spin->si_map.ga_len > 0
2929 				    && vim_strchr(spin->si_map.ga_data, c)
2930 								      != NULL)
2931 				|| vim_strchr(p, c) != NULL)
2932 			    smsg(_("Duplicate character in MAP in %s line %d"),
2933 								 fname, lnum);
2934 		    }
2935 
2936 		    // We simply concatenate all the MAP strings, separated by
2937 		    // slashes.
2938 		    ga_concat(&spin->si_map, items[1]);
2939 		    ga_append(&spin->si_map, '/');
2940 		}
2941 	    }
2942 	    // Accept "SAL from to" and "SAL from to  #comment".
2943 	    else if (is_aff_rule(items, itemcnt, "SAL", 3))
2944 	    {
2945 		if (do_sal)
2946 		{
2947 		    // SAL item (sounds-a-like)
2948 		    // Either one of the known keys or a from-to pair.
2949 		    if (STRCMP(items[1], "followup") == 0)
2950 			spin->si_followup = sal_to_bool(items[2]);
2951 		    else if (STRCMP(items[1], "collapse_result") == 0)
2952 			spin->si_collapse = sal_to_bool(items[2]);
2953 		    else if (STRCMP(items[1], "remove_accents") == 0)
2954 			spin->si_rem_accents = sal_to_bool(items[2]);
2955 		    else
2956 			// when "to" is "_" it means empty
2957 			add_fromto(spin, &spin->si_sal, items[1],
2958 				     STRCMP(items[2], "_") == 0 ? (char_u *)""
2959 								: items[2]);
2960 		}
2961 	    }
2962 	    else if (is_aff_rule(items, itemcnt, "SOFOFROM", 2)
2963 							  && sofofrom == NULL)
2964 	    {
2965 		sofofrom = getroom_save(spin, items[1]);
2966 	    }
2967 	    else if (is_aff_rule(items, itemcnt, "SOFOTO", 2)
2968 							    && sofoto == NULL)
2969 	    {
2970 		sofoto = getroom_save(spin, items[1]);
2971 	    }
2972 	    else if (STRCMP(items[0], "COMMON") == 0)
2973 	    {
2974 		int	i;
2975 
2976 		for (i = 1; i < itemcnt; ++i)
2977 		{
2978 		    if (HASHITEM_EMPTY(hash_find(&spin->si_commonwords,
2979 								   items[i])))
2980 		    {
2981 			p = vim_strsave(items[i]);
2982 			if (p == NULL)
2983 			    break;
2984 			hash_add(&spin->si_commonwords, p);
2985 		    }
2986 		}
2987 	    }
2988 	    else
2989 		smsg(_("Unrecognized or duplicate item in %s line %d: %s"),
2990 						       fname, lnum, items[0]);
2991 	}
2992     }
2993 
2994     if (fol != NULL || low != NULL || upp != NULL)
2995     {
2996 	if (spin->si_clear_chartab)
2997 	{
2998 	    // Clear the char type tables, don't want to use any of the
2999 	    // currently used spell properties.
3000 	    init_spell_chartab();
3001 	    spin->si_clear_chartab = FALSE;
3002 	}
3003 
3004 	/*
3005 	 * Don't write a word table for an ASCII file, so that we don't check
3006 	 * for conflicts with a word table that matches 'encoding'.
3007 	 * Don't write one for utf-8 either, we use utf_*() and
3008 	 * mb_get_class(), the list of chars in the file will be incomplete.
3009 	 */
3010 	if (!spin->si_ascii && !enc_utf8)
3011 	{
3012 	    if (fol == NULL || low == NULL || upp == NULL)
3013 		smsg(_("Missing FOL/LOW/UPP line in %s"), fname);
3014 	    else
3015 		(void)set_spell_chartab(fol, low, upp);
3016 	}
3017 
3018 	vim_free(fol);
3019 	vim_free(low);
3020 	vim_free(upp);
3021     }
3022 
3023     // Use compound specifications of the .aff file for the spell info.
3024     if (compmax != 0)
3025     {
3026 	aff_check_number(spin->si_compmax, compmax, "COMPOUNDWORDMAX");
3027 	spin->si_compmax = compmax;
3028     }
3029 
3030     if (compminlen != 0)
3031     {
3032 	aff_check_number(spin->si_compminlen, compminlen, "COMPOUNDMIN");
3033 	spin->si_compminlen = compminlen;
3034     }
3035 
3036     if (compsylmax != 0)
3037     {
3038 	if (syllable == NULL)
3039 	    smsg(_("COMPOUNDSYLMAX used without SYLLABLE"));
3040 	aff_check_number(spin->si_compsylmax, compsylmax, "COMPOUNDSYLMAX");
3041 	spin->si_compsylmax = compsylmax;
3042     }
3043 
3044     if (compoptions != 0)
3045     {
3046 	aff_check_number(spin->si_compoptions, compoptions, "COMPOUND options");
3047 	spin->si_compoptions |= compoptions;
3048     }
3049 
3050     if (compflags != NULL)
3051 	process_compflags(spin, aff, compflags);
3052 
3053     // Check that we didn't use too many renumbered flags.
3054     if (spin->si_newcompID < spin->si_newprefID)
3055     {
3056 	if (spin->si_newcompID == 127 || spin->si_newcompID == 255)
3057 	    msg(_("Too many postponed prefixes"));
3058 	else if (spin->si_newprefID == 0 || spin->si_newprefID == 127)
3059 	    msg(_("Too many compound flags"));
3060 	else
3061 	    msg(_("Too many postponed prefixes and/or compound flags"));
3062     }
3063 
3064     if (syllable != NULL)
3065     {
3066 	aff_check_string(spin->si_syllable, syllable, "SYLLABLE");
3067 	spin->si_syllable = syllable;
3068     }
3069 
3070     if (sofofrom != NULL || sofoto != NULL)
3071     {
3072 	if (sofofrom == NULL || sofoto == NULL)
3073 	    smsg(_("Missing SOFO%s line in %s"),
3074 				     sofofrom == NULL ? "FROM" : "TO", fname);
3075 	else if (spin->si_sal.ga_len > 0)
3076 	    smsg(_("Both SAL and SOFO lines in %s"), fname);
3077 	else
3078 	{
3079 	    aff_check_string(spin->si_sofofr, sofofrom, "SOFOFROM");
3080 	    aff_check_string(spin->si_sofoto, sofoto, "SOFOTO");
3081 	    spin->si_sofofr = sofofrom;
3082 	    spin->si_sofoto = sofoto;
3083 	}
3084     }
3085 
3086     if (midword != NULL)
3087     {
3088 	aff_check_string(spin->si_midword, midword, "MIDWORD");
3089 	spin->si_midword = midword;
3090     }
3091 
3092     vim_free(pc);
3093     fclose(fd);
3094     return aff;
3095 }
3096 
3097 /*
3098  * Return TRUE when items[0] equals "rulename", there are "mincount" items or
3099  * a comment is following after item "mincount".
3100  */
3101     static int
3102 is_aff_rule(
3103     char_u	**items,
3104     int		itemcnt,
3105     char	*rulename,
3106     int		mincount)
3107 {
3108     return (STRCMP(items[0], rulename) == 0
3109 	    && (itemcnt == mincount
3110 		|| (itemcnt > mincount && items[mincount][0] == '#')));
3111 }
3112 
3113 /*
3114  * For affix "entry" move COMPOUNDFORBIDFLAG and COMPOUNDPERMITFLAG from
3115  * ae_flags to ae_comppermit and ae_compforbid.
3116  */
3117     static void
3118 aff_process_flags(afffile_T *affile, affentry_T *entry)
3119 {
3120     char_u	*p;
3121     char_u	*prevp;
3122     unsigned	flag;
3123 
3124     if (entry->ae_flags != NULL
3125 		&& (affile->af_compforbid != 0 || affile->af_comppermit != 0))
3126     {
3127 	for (p = entry->ae_flags; *p != NUL; )
3128 	{
3129 	    prevp = p;
3130 	    flag = get_affitem(affile->af_flagtype, &p);
3131 	    if (flag == affile->af_comppermit || flag == affile->af_compforbid)
3132 	    {
3133 		STRMOVE(prevp, p);
3134 		p = prevp;
3135 		if (flag == affile->af_comppermit)
3136 		    entry->ae_comppermit = TRUE;
3137 		else
3138 		    entry->ae_compforbid = TRUE;
3139 	    }
3140 	    if (affile->af_flagtype == AFT_NUM && *p == ',')
3141 		++p;
3142 	}
3143 	if (*entry->ae_flags == NUL)
3144 	    entry->ae_flags = NULL;	// nothing left
3145     }
3146 }
3147 
3148 /*
3149  * Return TRUE if "s" is the name of an info item in the affix file.
3150  */
3151     static int
3152 spell_info_item(char_u *s)
3153 {
3154     return STRCMP(s, "NAME") == 0
3155 	|| STRCMP(s, "HOME") == 0
3156 	|| STRCMP(s, "VERSION") == 0
3157 	|| STRCMP(s, "AUTHOR") == 0
3158 	|| STRCMP(s, "EMAIL") == 0
3159 	|| STRCMP(s, "COPYRIGHT") == 0;
3160 }
3161 
3162 /*
3163  * Turn an affix flag name into a number, according to the FLAG type.
3164  * returns zero for failure.
3165  */
3166     static unsigned
3167 affitem2flag(
3168     int		flagtype,
3169     char_u	*item,
3170     char_u	*fname,
3171     int		lnum)
3172 {
3173     unsigned	res;
3174     char_u	*p = item;
3175 
3176     res = get_affitem(flagtype, &p);
3177     if (res == 0)
3178     {
3179 	if (flagtype == AFT_NUM)
3180 	    smsg(_("Flag is not a number in %s line %d: %s"),
3181 							   fname, lnum, item);
3182 	else
3183 	    smsg(_("Illegal flag in %s line %d: %s"),
3184 							   fname, lnum, item);
3185     }
3186     if (*p != NUL)
3187     {
3188 	smsg(_(e_affname), fname, lnum, item);
3189 	return 0;
3190     }
3191 
3192     return res;
3193 }
3194 
3195 /*
3196  * Get one affix name from "*pp" and advance the pointer.
3197  * Returns ZERO_FLAG for "0".
3198  * Returns zero for an error, still advances the pointer then.
3199  */
3200     static unsigned
3201 get_affitem(int flagtype, char_u **pp)
3202 {
3203     int		res;
3204 
3205     if (flagtype == AFT_NUM)
3206     {
3207 	if (!VIM_ISDIGIT(**pp))
3208 	{
3209 	    ++*pp;	// always advance, avoid getting stuck
3210 	    return 0;
3211 	}
3212 	res = getdigits(pp);
3213 	if (res == 0)
3214 	    res = ZERO_FLAG;
3215     }
3216     else
3217     {
3218 	res = mb_ptr2char_adv(pp);
3219 	if (flagtype == AFT_LONG || (flagtype == AFT_CAPLONG
3220 						 && res >= 'A' && res <= 'Z'))
3221 	{
3222 	    if (**pp == NUL)
3223 		return 0;
3224 	    res = mb_ptr2char_adv(pp) + (res << 16);
3225 	}
3226     }
3227     return res;
3228 }
3229 
3230 /*
3231  * Process the "compflags" string used in an affix file and append it to
3232  * spin->si_compflags.
3233  * The processing involves changing the affix names to ID numbers, so that
3234  * they fit in one byte.
3235  */
3236     static void
3237 process_compflags(
3238     spellinfo_T	*spin,
3239     afffile_T	*aff,
3240     char_u	*compflags)
3241 {
3242     char_u	*p;
3243     char_u	*prevp;
3244     unsigned	flag;
3245     compitem_T	*ci;
3246     int		id;
3247     int		len;
3248     char_u	*tp;
3249     char_u	key[AH_KEY_LEN];
3250     hashitem_T	*hi;
3251 
3252     // Make room for the old and the new compflags, concatenated with a / in
3253     // between.  Processing it makes it shorter, but we don't know by how
3254     // much, thus allocate the maximum.
3255     len = (int)STRLEN(compflags) + 1;
3256     if (spin->si_compflags != NULL)
3257 	len += (int)STRLEN(spin->si_compflags) + 1;
3258     p = getroom(spin, len, FALSE);
3259     if (p == NULL)
3260 	return;
3261     if (spin->si_compflags != NULL)
3262     {
3263 	STRCPY(p, spin->si_compflags);
3264 	STRCAT(p, "/");
3265     }
3266     spin->si_compflags = p;
3267     tp = p + STRLEN(p);
3268 
3269     for (p = compflags; *p != NUL; )
3270     {
3271 	if (vim_strchr((char_u *)"/?*+[]", *p) != NULL)
3272 	    // Copy non-flag characters directly.
3273 	    *tp++ = *p++;
3274 	else
3275 	{
3276 	    // First get the flag number, also checks validity.
3277 	    prevp = p;
3278 	    flag = get_affitem(aff->af_flagtype, &p);
3279 	    if (flag != 0)
3280 	    {
3281 		// Find the flag in the hashtable.  If it was used before, use
3282 		// the existing ID.  Otherwise add a new entry.
3283 		vim_strncpy(key, prevp, p - prevp);
3284 		hi = hash_find(&aff->af_comp, key);
3285 		if (!HASHITEM_EMPTY(hi))
3286 		    id = HI2CI(hi)->ci_newID;
3287 		else
3288 		{
3289 		    ci = (compitem_T *)getroom(spin, sizeof(compitem_T), TRUE);
3290 		    if (ci == NULL)
3291 			break;
3292 		    STRCPY(ci->ci_key, key);
3293 		    ci->ci_flag = flag;
3294 		    // Avoid using a flag ID that has a special meaning in a
3295 		    // regexp (also inside []).
3296 		    do
3297 		    {
3298 			check_renumber(spin);
3299 			id = spin->si_newcompID--;
3300 		    } while (vim_strchr((char_u *)"/?*+[]\\-^", id) != NULL);
3301 		    ci->ci_newID = id;
3302 		    hash_add(&aff->af_comp, ci->ci_key);
3303 		}
3304 		*tp++ = id;
3305 	    }
3306 	    if (aff->af_flagtype == AFT_NUM && *p == ',')
3307 		++p;
3308 	}
3309     }
3310 
3311     *tp = NUL;
3312 }
3313 
3314 /*
3315  * Check that the new IDs for postponed affixes and compounding don't overrun
3316  * each other.  We have almost 255 available, but start at 0-127 to avoid
3317  * using two bytes for utf-8.  When the 0-127 range is used up go to 128-255.
3318  * When that is used up an error message is given.
3319  */
3320     static void
3321 check_renumber(spellinfo_T *spin)
3322 {
3323     if (spin->si_newprefID == spin->si_newcompID && spin->si_newcompID < 128)
3324     {
3325 	spin->si_newprefID = 127;
3326 	spin->si_newcompID = 255;
3327     }
3328 }
3329 
3330 /*
3331  * Return TRUE if flag "flag" appears in affix list "afflist".
3332  */
3333     static int
3334 flag_in_afflist(int flagtype, char_u *afflist, unsigned flag)
3335 {
3336     char_u	*p;
3337     unsigned	n;
3338 
3339     switch (flagtype)
3340     {
3341 	case AFT_CHAR:
3342 	    return vim_strchr(afflist, flag) != NULL;
3343 
3344 	case AFT_CAPLONG:
3345 	case AFT_LONG:
3346 	    for (p = afflist; *p != NUL; )
3347 	    {
3348 		n = mb_ptr2char_adv(&p);
3349 		if ((flagtype == AFT_LONG || (n >= 'A' && n <= 'Z'))
3350 								 && *p != NUL)
3351 		    n = mb_ptr2char_adv(&p) + (n << 16);
3352 		if (n == flag)
3353 		    return TRUE;
3354 	    }
3355 	    break;
3356 
3357 	case AFT_NUM:
3358 	    for (p = afflist; *p != NUL; )
3359 	    {
3360 		n = getdigits(&p);
3361 		if (n == 0)
3362 		    n = ZERO_FLAG;
3363 		if (n == flag)
3364 		    return TRUE;
3365 		if (*p != NUL)	// skip over comma
3366 		    ++p;
3367 	    }
3368 	    break;
3369     }
3370     return FALSE;
3371 }
3372 
3373 /*
3374  * Give a warning when "spinval" and "affval" numbers are set and not the same.
3375  */
3376     static void
3377 aff_check_number(int spinval, int affval, char *name)
3378 {
3379     if (spinval != 0 && spinval != affval)
3380 	smsg(_("%s value differs from what is used in another .aff file"), name);
3381 }
3382 
3383 /*
3384  * Give a warning when "spinval" and "affval" strings are set and not the same.
3385  */
3386     static void
3387 aff_check_string(char_u *spinval, char_u *affval, char *name)
3388 {
3389     if (spinval != NULL && STRCMP(spinval, affval) != 0)
3390 	smsg(_("%s value differs from what is used in another .aff file"), name);
3391 }
3392 
3393 /*
3394  * Return TRUE if strings "s1" and "s2" are equal.  Also consider both being
3395  * NULL as equal.
3396  */
3397     static int
3398 str_equal(char_u *s1, char_u *s2)
3399 {
3400     if (s1 == NULL || s2 == NULL)
3401 	return s1 == s2;
3402     return STRCMP(s1, s2) == 0;
3403 }
3404 
3405 /*
3406  * Add a from-to item to "gap".  Used for REP and SAL items.
3407  * They are stored case-folded.
3408  */
3409     static void
3410 add_fromto(
3411     spellinfo_T	*spin,
3412     garray_T	*gap,
3413     char_u	*from,
3414     char_u	*to)
3415 {
3416     fromto_T	*ftp;
3417     char_u	word[MAXWLEN];
3418 
3419     if (ga_grow(gap, 1) == OK)
3420     {
3421 	ftp = ((fromto_T *)gap->ga_data) + gap->ga_len;
3422 	(void)spell_casefold(from, (int)STRLEN(from), word, MAXWLEN);
3423 	ftp->ft_from = getroom_save(spin, word);
3424 	(void)spell_casefold(to, (int)STRLEN(to), word, MAXWLEN);
3425 	ftp->ft_to = getroom_save(spin, word);
3426 	++gap->ga_len;
3427     }
3428 }
3429 
3430 /*
3431  * Convert a boolean argument in a SAL line to TRUE or FALSE;
3432  */
3433     static int
3434 sal_to_bool(char_u *s)
3435 {
3436     return STRCMP(s, "1") == 0 || STRCMP(s, "true") == 0;
3437 }
3438 
3439 /*
3440  * Free the structure filled by spell_read_aff().
3441  */
3442     static void
3443 spell_free_aff(afffile_T *aff)
3444 {
3445     hashtab_T	*ht;
3446     hashitem_T	*hi;
3447     int		todo;
3448     affheader_T	*ah;
3449     affentry_T	*ae;
3450 
3451     vim_free(aff->af_enc);
3452 
3453     // All this trouble to free the "ae_prog" items...
3454     for (ht = &aff->af_pref; ; ht = &aff->af_suff)
3455     {
3456 	todo = (int)ht->ht_used;
3457 	for (hi = ht->ht_array; todo > 0; ++hi)
3458 	{
3459 	    if (!HASHITEM_EMPTY(hi))
3460 	    {
3461 		--todo;
3462 		ah = HI2AH(hi);
3463 		for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
3464 		    vim_regfree(ae->ae_prog);
3465 	    }
3466 	}
3467 	if (ht == &aff->af_suff)
3468 	    break;
3469     }
3470 
3471     hash_clear(&aff->af_pref);
3472     hash_clear(&aff->af_suff);
3473     hash_clear(&aff->af_comp);
3474 }
3475 
3476 /*
3477  * Read dictionary file "fname".
3478  * Returns OK or FAIL;
3479  */
3480     static int
3481 spell_read_dic(spellinfo_T *spin, char_u *fname, afffile_T *affile)
3482 {
3483     hashtab_T	ht;
3484     char_u	line[MAXLINELEN];
3485     char_u	*p;
3486     char_u	*afflist;
3487     char_u	store_afflist[MAXWLEN];
3488     int		pfxlen;
3489     int		need_affix;
3490     char_u	*dw;
3491     char_u	*pc;
3492     char_u	*w;
3493     int		l;
3494     hash_T	hash;
3495     hashitem_T	*hi;
3496     FILE	*fd;
3497     int		lnum = 1;
3498     int		non_ascii = 0;
3499     int		retval = OK;
3500     char_u	message[MAXLINELEN + MAXWLEN];
3501     int		flags;
3502     int		duplicate = 0;
3503 
3504     /*
3505      * Open the file.
3506      */
3507     fd = mch_fopen((char *)fname, "r");
3508     if (fd == NULL)
3509     {
3510 	semsg(_(e_notopen), fname);
3511 	return FAIL;
3512     }
3513 
3514     // The hashtable is only used to detect duplicated words.
3515     hash_init(&ht);
3516 
3517     vim_snprintf((char *)IObuff, IOSIZE,
3518 				  _("Reading dictionary file %s..."), fname);
3519     spell_message(spin, IObuff);
3520 
3521     // start with a message for the first line
3522     spin->si_msg_count = 999999;
3523 
3524     // Read and ignore the first line: word count.
3525     (void)vim_fgets(line, MAXLINELEN, fd);
3526     if (!vim_isdigit(*skipwhite(line)))
3527 	semsg(_("E760: No word count in %s"), fname);
3528 
3529     /*
3530      * Read all the lines in the file one by one.
3531      * The words are converted to 'encoding' here, before being added to
3532      * the hashtable.
3533      */
3534     while (!vim_fgets(line, MAXLINELEN, fd) && !got_int)
3535     {
3536 	line_breakcheck();
3537 	++lnum;
3538 	if (line[0] == '#' || line[0] == '/')
3539 	    continue;	// comment line
3540 
3541 	// Remove CR, LF and white space from the end.  White space halfway
3542 	// the word is kept to allow e.g., "et al.".
3543 	l = (int)STRLEN(line);
3544 	while (l > 0 && line[l - 1] <= ' ')
3545 	    --l;
3546 	if (l == 0)
3547 	    continue;	// empty line
3548 	line[l] = NUL;
3549 
3550 	// Convert from "SET" to 'encoding' when needed.
3551 	if (spin->si_conv.vc_type != CONV_NONE)
3552 	{
3553 	    pc = string_convert(&spin->si_conv, line, NULL);
3554 	    if (pc == NULL)
3555 	    {
3556 		smsg(_("Conversion failure for word in %s line %d: %s"),
3557 						       fname, lnum, line);
3558 		continue;
3559 	    }
3560 	    w = pc;
3561 	}
3562 	else
3563 	{
3564 	    pc = NULL;
3565 	    w = line;
3566 	}
3567 
3568 	// Truncate the word at the "/", set "afflist" to what follows.
3569 	// Replace "\/" by "/" and "\\" by "\".
3570 	afflist = NULL;
3571 	for (p = w; *p != NUL; MB_PTR_ADV(p))
3572 	{
3573 	    if (*p == '\\' && (p[1] == '\\' || p[1] == '/'))
3574 		STRMOVE(p, p + 1);
3575 	    else if (*p == '/')
3576 	    {
3577 		*p = NUL;
3578 		afflist = p + 1;
3579 		break;
3580 	    }
3581 	}
3582 
3583 	// Skip non-ASCII words when "spin->si_ascii" is TRUE.
3584 	if (spin->si_ascii && has_non_ascii(w))
3585 	{
3586 	    ++non_ascii;
3587 	    vim_free(pc);
3588 	    continue;
3589 	}
3590 
3591 	// This takes time, print a message every 10000 words.
3592 	if (spin->si_verbose && spin->si_msg_count > 10000)
3593 	{
3594 	    spin->si_msg_count = 0;
3595 	    vim_snprintf((char *)message, sizeof(message),
3596 		    _("line %6d, word %6ld - %s"),
3597 		       lnum, spin->si_foldwcount + spin->si_keepwcount, w);
3598 	    msg_start();
3599 	    msg_outtrans_long_attr(message, 0);
3600 	    msg_clr_eos();
3601 	    msg_didout = FALSE;
3602 	    msg_col = 0;
3603 	    out_flush();
3604 	}
3605 
3606 	// Store the word in the hashtable to be able to find duplicates.
3607 	dw = (char_u *)getroom_save(spin, w);
3608 	if (dw == NULL)
3609 	{
3610 	    retval = FAIL;
3611 	    vim_free(pc);
3612 	    break;
3613 	}
3614 
3615 	hash = hash_hash(dw);
3616 	hi = hash_lookup(&ht, dw, hash);
3617 	if (!HASHITEM_EMPTY(hi))
3618 	{
3619 	    if (p_verbose > 0)
3620 		smsg(_("Duplicate word in %s line %d: %s"),
3621 							     fname, lnum, dw);
3622 	    else if (duplicate == 0)
3623 		smsg(_("First duplicate word in %s line %d: %s"),
3624 							     fname, lnum, dw);
3625 	    ++duplicate;
3626 	}
3627 	else
3628 	    hash_add_item(&ht, hi, dw, hash);
3629 
3630 	flags = 0;
3631 	store_afflist[0] = NUL;
3632 	pfxlen = 0;
3633 	need_affix = FALSE;
3634 	if (afflist != NULL)
3635 	{
3636 	    // Extract flags from the affix list.
3637 	    flags |= get_affix_flags(affile, afflist);
3638 
3639 	    if (affile->af_needaffix != 0 && flag_in_afflist(
3640 			  affile->af_flagtype, afflist, affile->af_needaffix))
3641 		need_affix = TRUE;
3642 
3643 	    if (affile->af_pfxpostpone)
3644 		// Need to store the list of prefix IDs with the word.
3645 		pfxlen = get_pfxlist(affile, afflist, store_afflist);
3646 
3647 	    if (spin->si_compflags != NULL)
3648 		// Need to store the list of compound flags with the word.
3649 		// Concatenate them to the list of prefix IDs.
3650 		get_compflags(affile, afflist, store_afflist + pfxlen);
3651 	}
3652 
3653 	// Add the word to the word tree(s).
3654 	if (store_word(spin, dw, flags, spin->si_region,
3655 					   store_afflist, need_affix) == FAIL)
3656 	    retval = FAIL;
3657 
3658 	if (afflist != NULL)
3659 	{
3660 	    // Find all matching suffixes and add the resulting words.
3661 	    // Additionally do matching prefixes that combine.
3662 	    if (store_aff_word(spin, dw, afflist, affile,
3663 			   &affile->af_suff, &affile->af_pref,
3664 			    CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
3665 		retval = FAIL;
3666 
3667 	    // Find all matching prefixes and add the resulting words.
3668 	    if (store_aff_word(spin, dw, afflist, affile,
3669 			  &affile->af_pref, NULL,
3670 			    CONDIT_SUF, flags, store_afflist, pfxlen) == FAIL)
3671 		retval = FAIL;
3672 	}
3673 
3674 	vim_free(pc);
3675     }
3676 
3677     if (duplicate > 0)
3678 	smsg(_("%d duplicate word(s) in %s"), duplicate, fname);
3679     if (spin->si_ascii && non_ascii > 0)
3680 	smsg(_("Ignored %d word(s) with non-ASCII characters in %s"),
3681 							    non_ascii, fname);
3682     hash_clear(&ht);
3683 
3684     fclose(fd);
3685     return retval;
3686 }
3687 
3688 /*
3689  * Check for affix flags in "afflist" that are turned into word flags.
3690  * Return WF_ flags.
3691  */
3692     static int
3693 get_affix_flags(afffile_T *affile, char_u *afflist)
3694 {
3695     int		flags = 0;
3696 
3697     if (affile->af_keepcase != 0 && flag_in_afflist(
3698 			   affile->af_flagtype, afflist, affile->af_keepcase))
3699 	flags |= WF_KEEPCAP | WF_FIXCAP;
3700     if (affile->af_rare != 0 && flag_in_afflist(
3701 			       affile->af_flagtype, afflist, affile->af_rare))
3702 	flags |= WF_RARE;
3703     if (affile->af_bad != 0 && flag_in_afflist(
3704 				affile->af_flagtype, afflist, affile->af_bad))
3705 	flags |= WF_BANNED;
3706     if (affile->af_needcomp != 0 && flag_in_afflist(
3707 			   affile->af_flagtype, afflist, affile->af_needcomp))
3708 	flags |= WF_NEEDCOMP;
3709     if (affile->af_comproot != 0 && flag_in_afflist(
3710 			   affile->af_flagtype, afflist, affile->af_comproot))
3711 	flags |= WF_COMPROOT;
3712     if (affile->af_nosuggest != 0 && flag_in_afflist(
3713 			  affile->af_flagtype, afflist, affile->af_nosuggest))
3714 	flags |= WF_NOSUGGEST;
3715     return flags;
3716 }
3717 
3718 /*
3719  * Get the list of prefix IDs from the affix list "afflist".
3720  * Used for PFXPOSTPONE.
3721  * Put the resulting flags in "store_afflist[MAXWLEN]" with a terminating NUL
3722  * and return the number of affixes.
3723  */
3724     static int
3725 get_pfxlist(
3726     afffile_T	*affile,
3727     char_u	*afflist,
3728     char_u	*store_afflist)
3729 {
3730     char_u	*p;
3731     char_u	*prevp;
3732     int		cnt = 0;
3733     int		id;
3734     char_u	key[AH_KEY_LEN];
3735     hashitem_T	*hi;
3736 
3737     for (p = afflist; *p != NUL; )
3738     {
3739 	prevp = p;
3740 	if (get_affitem(affile->af_flagtype, &p) != 0)
3741 	{
3742 	    // A flag is a postponed prefix flag if it appears in "af_pref"
3743 	    // and its ID is not zero.
3744 	    vim_strncpy(key, prevp, p - prevp);
3745 	    hi = hash_find(&affile->af_pref, key);
3746 	    if (!HASHITEM_EMPTY(hi))
3747 	    {
3748 		id = HI2AH(hi)->ah_newID;
3749 		if (id != 0)
3750 		    store_afflist[cnt++] = id;
3751 	    }
3752 	}
3753 	if (affile->af_flagtype == AFT_NUM && *p == ',')
3754 	    ++p;
3755     }
3756 
3757     store_afflist[cnt] = NUL;
3758     return cnt;
3759 }
3760 
3761 /*
3762  * Get the list of compound IDs from the affix list "afflist" that are used
3763  * for compound words.
3764  * Puts the flags in "store_afflist[]".
3765  */
3766     static void
3767 get_compflags(
3768     afffile_T	*affile,
3769     char_u	*afflist,
3770     char_u	*store_afflist)
3771 {
3772     char_u	*p;
3773     char_u	*prevp;
3774     int		cnt = 0;
3775     char_u	key[AH_KEY_LEN];
3776     hashitem_T	*hi;
3777 
3778     for (p = afflist; *p != NUL; )
3779     {
3780 	prevp = p;
3781 	if (get_affitem(affile->af_flagtype, &p) != 0)
3782 	{
3783 	    // A flag is a compound flag if it appears in "af_comp".
3784 	    vim_strncpy(key, prevp, p - prevp);
3785 	    hi = hash_find(&affile->af_comp, key);
3786 	    if (!HASHITEM_EMPTY(hi))
3787 		store_afflist[cnt++] = HI2CI(hi)->ci_newID;
3788 	}
3789 	if (affile->af_flagtype == AFT_NUM && *p == ',')
3790 	    ++p;
3791     }
3792 
3793     store_afflist[cnt] = NUL;
3794 }
3795 
3796 /*
3797  * Apply affixes to a word and store the resulting words.
3798  * "ht" is the hashtable with affentry_T that need to be applied, either
3799  * prefixes or suffixes.
3800  * "xht", when not NULL, is the prefix hashtable, to be used additionally on
3801  * the resulting words for combining affixes.
3802  *
3803  * Returns FAIL when out of memory.
3804  */
3805     static int
3806 store_aff_word(
3807     spellinfo_T	*spin,		// spell info
3808     char_u	*word,		// basic word start
3809     char_u	*afflist,	// list of names of supported affixes
3810     afffile_T	*affile,
3811     hashtab_T	*ht,
3812     hashtab_T	*xht,
3813     int		condit,		// CONDIT_SUF et al.
3814     int		flags,		// flags for the word
3815     char_u	*pfxlist,	// list of prefix IDs
3816     int		pfxlen)		// nr of flags in "pfxlist" for prefixes, rest
3817 				// is compound flags
3818 {
3819     int		todo;
3820     hashitem_T	*hi;
3821     affheader_T	*ah;
3822     affentry_T	*ae;
3823     char_u	newword[MAXWLEN];
3824     int		retval = OK;
3825     int		i, j;
3826     char_u	*p;
3827     int		use_flags;
3828     char_u	*use_pfxlist;
3829     int		use_pfxlen;
3830     int		need_affix;
3831     char_u	store_afflist[MAXWLEN];
3832     char_u	pfx_pfxlist[MAXWLEN];
3833     size_t	wordlen = STRLEN(word);
3834     int		use_condit;
3835 
3836     todo = (int)ht->ht_used;
3837     for (hi = ht->ht_array; todo > 0 && retval == OK; ++hi)
3838     {
3839 	if (!HASHITEM_EMPTY(hi))
3840 	{
3841 	    --todo;
3842 	    ah = HI2AH(hi);
3843 
3844 	    // Check that the affix combines, if required, and that the word
3845 	    // supports this affix.
3846 	    if (((condit & CONDIT_COMB) == 0 || ah->ah_combine)
3847 		    && flag_in_afflist(affile->af_flagtype, afflist,
3848 								 ah->ah_flag))
3849 	    {
3850 		// Loop over all affix entries with this name.
3851 		for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
3852 		{
3853 		    // Check the condition.  It's not logical to match case
3854 		    // here, but it is required for compatibility with
3855 		    // Myspell.
3856 		    // Another requirement from Myspell is that the chop
3857 		    // string is shorter than the word itself.
3858 		    // For prefixes, when "PFXPOSTPONE" was used, only do
3859 		    // prefixes with a chop string and/or flags.
3860 		    // When a previously added affix had CIRCUMFIX this one
3861 		    // must have it too, if it had not then this one must not
3862 		    // have one either.
3863 		    if ((xht != NULL || !affile->af_pfxpostpone
3864 				|| ae->ae_chop != NULL
3865 				|| ae->ae_flags != NULL)
3866 			    && (ae->ae_chop == NULL
3867 				|| STRLEN(ae->ae_chop) < wordlen)
3868 			    && (ae->ae_prog == NULL
3869 				|| vim_regexec_prog(&ae->ae_prog, FALSE,
3870 							    word, (colnr_T)0))
3871 			    && (((condit & CONDIT_CFIX) == 0)
3872 				== ((condit & CONDIT_AFF) == 0
3873 				    || ae->ae_flags == NULL
3874 				    || !flag_in_afflist(affile->af_flagtype,
3875 					ae->ae_flags, affile->af_circumfix))))
3876 		    {
3877 			// Match.  Remove the chop and add the affix.
3878 			if (xht == NULL)
3879 			{
3880 			    // prefix: chop/add at the start of the word
3881 			    if (ae->ae_add == NULL)
3882 				*newword = NUL;
3883 			    else
3884 				vim_strncpy(newword, ae->ae_add, MAXWLEN - 1);
3885 			    p = word;
3886 			    if (ae->ae_chop != NULL)
3887 			    {
3888 				// Skip chop string.
3889 				if (has_mbyte)
3890 				{
3891 				    i = mb_charlen(ae->ae_chop);
3892 				    for ( ; i > 0; --i)
3893 					MB_PTR_ADV(p);
3894 				}
3895 				else
3896 				    p += STRLEN(ae->ae_chop);
3897 			    }
3898 			    STRCAT(newword, p);
3899 			}
3900 			else
3901 			{
3902 			    // suffix: chop/add at the end of the word
3903 			    vim_strncpy(newword, word, MAXWLEN - 1);
3904 			    if (ae->ae_chop != NULL)
3905 			    {
3906 				// Remove chop string.
3907 				p = newword + STRLEN(newword);
3908 				i = (int)MB_CHARLEN(ae->ae_chop);
3909 				for ( ; i > 0; --i)
3910 				    MB_PTR_BACK(newword, p);
3911 				*p = NUL;
3912 			    }
3913 			    if (ae->ae_add != NULL)
3914 				STRCAT(newword, ae->ae_add);
3915 			}
3916 
3917 			use_flags = flags;
3918 			use_pfxlist = pfxlist;
3919 			use_pfxlen = pfxlen;
3920 			need_affix = FALSE;
3921 			use_condit = condit | CONDIT_COMB | CONDIT_AFF;
3922 			if (ae->ae_flags != NULL)
3923 			{
3924 			    // Extract flags from the affix list.
3925 			    use_flags |= get_affix_flags(affile, ae->ae_flags);
3926 
3927 			    if (affile->af_needaffix != 0 && flag_in_afflist(
3928 					affile->af_flagtype, ae->ae_flags,
3929 							affile->af_needaffix))
3930 				need_affix = TRUE;
3931 
3932 			    // When there is a CIRCUMFIX flag the other affix
3933 			    // must also have it and we don't add the word
3934 			    // with one affix.
3935 			    if (affile->af_circumfix != 0 && flag_in_afflist(
3936 					affile->af_flagtype, ae->ae_flags,
3937 							affile->af_circumfix))
3938 			    {
3939 				use_condit |= CONDIT_CFIX;
3940 				if ((condit & CONDIT_CFIX) == 0)
3941 				    need_affix = TRUE;
3942 			    }
3943 
3944 			    if (affile->af_pfxpostpone
3945 						|| spin->si_compflags != NULL)
3946 			    {
3947 				if (affile->af_pfxpostpone)
3948 				    // Get prefix IDS from the affix list.
3949 				    use_pfxlen = get_pfxlist(affile,
3950 						 ae->ae_flags, store_afflist);
3951 				else
3952 				    use_pfxlen = 0;
3953 				use_pfxlist = store_afflist;
3954 
3955 				// Combine the prefix IDs. Avoid adding the
3956 				// same ID twice.
3957 				for (i = 0; i < pfxlen; ++i)
3958 				{
3959 				    for (j = 0; j < use_pfxlen; ++j)
3960 					if (pfxlist[i] == use_pfxlist[j])
3961 					    break;
3962 				    if (j == use_pfxlen)
3963 					use_pfxlist[use_pfxlen++] = pfxlist[i];
3964 				}
3965 
3966 				if (spin->si_compflags != NULL)
3967 				    // Get compound IDS from the affix list.
3968 				    get_compflags(affile, ae->ae_flags,
3969 						  use_pfxlist + use_pfxlen);
3970 
3971 				// Combine the list of compound flags.
3972 				// Concatenate them to the prefix IDs list.
3973 				// Avoid adding the same ID twice.
3974 				for (i = pfxlen; pfxlist[i] != NUL; ++i)
3975 				{
3976 				    for (j = use_pfxlen;
3977 						   use_pfxlist[j] != NUL; ++j)
3978 					if (pfxlist[i] == use_pfxlist[j])
3979 					    break;
3980 				    if (use_pfxlist[j] == NUL)
3981 				    {
3982 					use_pfxlist[j++] = pfxlist[i];
3983 					use_pfxlist[j] = NUL;
3984 				    }
3985 				}
3986 			    }
3987 			}
3988 
3989 			// Obey a "COMPOUNDFORBIDFLAG" of the affix: don't
3990 			// use the compound flags.
3991 			if (use_pfxlist != NULL && ae->ae_compforbid)
3992 			{
3993 			    vim_strncpy(pfx_pfxlist, use_pfxlist, use_pfxlen);
3994 			    use_pfxlist = pfx_pfxlist;
3995 			}
3996 
3997 			// When there are postponed prefixes...
3998 			if (spin->si_prefroot != NULL
3999 				&& spin->si_prefroot->wn_sibling != NULL)
4000 			{
4001 			    // ... add a flag to indicate an affix was used.
4002 			    use_flags |= WF_HAS_AFF;
4003 
4004 			    // ... don't use a prefix list if combining
4005 			    // affixes is not allowed.  But do use the
4006 			    // compound flags after them.
4007 			    if (!ah->ah_combine && use_pfxlist != NULL)
4008 				use_pfxlist += use_pfxlen;
4009 			}
4010 
4011 			// When compounding is supported and there is no
4012 			// "COMPOUNDPERMITFLAG" then forbid compounding on the
4013 			// side where the affix is applied.
4014 			if (spin->si_compflags != NULL && !ae->ae_comppermit)
4015 			{
4016 			    if (xht != NULL)
4017 				use_flags |= WF_NOCOMPAFT;
4018 			    else
4019 				use_flags |= WF_NOCOMPBEF;
4020 			}
4021 
4022 			// Store the modified word.
4023 			if (store_word(spin, newword, use_flags,
4024 						 spin->si_region, use_pfxlist,
4025 							  need_affix) == FAIL)
4026 			    retval = FAIL;
4027 
4028 			// When added a prefix or a first suffix and the affix
4029 			// has flags may add a(nother) suffix.  RECURSIVE!
4030 			if ((condit & CONDIT_SUF) && ae->ae_flags != NULL)
4031 			    if (store_aff_word(spin, newword, ae->ae_flags,
4032 					affile, &affile->af_suff, xht,
4033 					   use_condit & (xht == NULL
4034 							? ~0 :  ~CONDIT_SUF),
4035 				      use_flags, use_pfxlist, pfxlen) == FAIL)
4036 				retval = FAIL;
4037 
4038 			// When added a suffix and combining is allowed also
4039 			// try adding a prefix additionally.  Both for the
4040 			// word flags and for the affix flags.  RECURSIVE!
4041 			if (xht != NULL && ah->ah_combine)
4042 			{
4043 			    if (store_aff_word(spin, newword,
4044 					afflist, affile,
4045 					xht, NULL, use_condit,
4046 					use_flags, use_pfxlist,
4047 					pfxlen) == FAIL
4048 				    || (ae->ae_flags != NULL
4049 					&& store_aff_word(spin, newword,
4050 					    ae->ae_flags, affile,
4051 					    xht, NULL, use_condit,
4052 					    use_flags, use_pfxlist,
4053 					    pfxlen) == FAIL))
4054 				retval = FAIL;
4055 			}
4056 		    }
4057 		}
4058 	    }
4059 	}
4060     }
4061 
4062     return retval;
4063 }
4064 
4065 /*
4066  * Read a file with a list of words.
4067  */
4068     static int
4069 spell_read_wordfile(spellinfo_T *spin, char_u *fname)
4070 {
4071     FILE	*fd;
4072     long	lnum = 0;
4073     char_u	rline[MAXLINELEN];
4074     char_u	*line;
4075     char_u	*pc = NULL;
4076     char_u	*p;
4077     int		l;
4078     int		retval = OK;
4079     int		did_word = FALSE;
4080     int		non_ascii = 0;
4081     int		flags;
4082     int		regionmask;
4083 
4084     /*
4085      * Open the file.
4086      */
4087     fd = mch_fopen((char *)fname, "r");
4088     if (fd == NULL)
4089     {
4090 	semsg(_(e_notopen), fname);
4091 	return FAIL;
4092     }
4093 
4094     vim_snprintf((char *)IObuff, IOSIZE, _("Reading word file %s..."), fname);
4095     spell_message(spin, IObuff);
4096 
4097     /*
4098      * Read all the lines in the file one by one.
4099      */
4100     while (!vim_fgets(rline, MAXLINELEN, fd) && !got_int)
4101     {
4102 	line_breakcheck();
4103 	++lnum;
4104 
4105 	// Skip comment lines.
4106 	if (*rline == '#')
4107 	    continue;
4108 
4109 	// Remove CR, LF and white space from the end.
4110 	l = (int)STRLEN(rline);
4111 	while (l > 0 && rline[l - 1] <= ' ')
4112 	    --l;
4113 	if (l == 0)
4114 	    continue;	// empty or blank line
4115 	rline[l] = NUL;
4116 
4117 	// Convert from "/encoding={encoding}" to 'encoding' when needed.
4118 	vim_free(pc);
4119 	if (spin->si_conv.vc_type != CONV_NONE)
4120 	{
4121 	    pc = string_convert(&spin->si_conv, rline, NULL);
4122 	    if (pc == NULL)
4123 	    {
4124 		smsg(_("Conversion failure for word in %s line %ld: %s"),
4125 							   fname, lnum, rline);
4126 		continue;
4127 	    }
4128 	    line = pc;
4129 	}
4130 	else
4131 	{
4132 	    pc = NULL;
4133 	    line = rline;
4134 	}
4135 
4136 	if (*line == '/')
4137 	{
4138 	    ++line;
4139 	    if (STRNCMP(line, "encoding=", 9) == 0)
4140 	    {
4141 		if (spin->si_conv.vc_type != CONV_NONE)
4142 		    smsg(_("Duplicate /encoding= line ignored in %s line %ld: %s"),
4143 						       fname, lnum, line - 1);
4144 		else if (did_word)
4145 		    smsg(_("/encoding= line after word ignored in %s line %ld: %s"),
4146 						       fname, lnum, line - 1);
4147 		else
4148 		{
4149 		    char_u	*enc;
4150 
4151 		    // Setup for conversion to 'encoding'.
4152 		    line += 9;
4153 		    enc = enc_canonize(line);
4154 		    if (enc != NULL && !spin->si_ascii
4155 			    && convert_setup(&spin->si_conv, enc,
4156 							       p_enc) == FAIL)
4157 			smsg(_("Conversion in %s not supported: from %s to %s"),
4158 							  fname, line, p_enc);
4159 		    vim_free(enc);
4160 		    spin->si_conv.vc_fail = TRUE;
4161 		}
4162 		continue;
4163 	    }
4164 
4165 	    if (STRNCMP(line, "regions=", 8) == 0)
4166 	    {
4167 		if (spin->si_region_count > 1)
4168 		    smsg(_("Duplicate /regions= line ignored in %s line %ld: %s"),
4169 						       fname, lnum, line);
4170 		else
4171 		{
4172 		    line += 8;
4173 		    if (STRLEN(line) > MAXREGIONS * 2)
4174 			smsg(_("Too many regions in %s line %ld: %s"),
4175 						       fname, lnum, line);
4176 		    else
4177 		    {
4178 			spin->si_region_count = (int)STRLEN(line) / 2;
4179 			STRCPY(spin->si_region_name, line);
4180 
4181 			// Adjust the mask for a word valid in all regions.
4182 			spin->si_region = (1 << spin->si_region_count) - 1;
4183 		    }
4184 		}
4185 		continue;
4186 	    }
4187 
4188 	    smsg(_("/ line ignored in %s line %ld: %s"),
4189 						       fname, lnum, line - 1);
4190 	    continue;
4191 	}
4192 
4193 	flags = 0;
4194 	regionmask = spin->si_region;
4195 
4196 	// Check for flags and region after a slash.
4197 	p = vim_strchr(line, '/');
4198 	if (p != NULL)
4199 	{
4200 	    *p++ = NUL;
4201 	    while (*p != NUL)
4202 	    {
4203 		if (*p == '=')		// keep-case word
4204 		    flags |= WF_KEEPCAP | WF_FIXCAP;
4205 		else if (*p == '!')	// Bad, bad, wicked word.
4206 		    flags |= WF_BANNED;
4207 		else if (*p == '?')	// Rare word.
4208 		    flags |= WF_RARE;
4209 		else if (VIM_ISDIGIT(*p)) // region number(s)
4210 		{
4211 		    if ((flags & WF_REGION) == 0)   // first one
4212 			regionmask = 0;
4213 		    flags |= WF_REGION;
4214 
4215 		    l = *p - '0';
4216 		    if (l == 0 || l > spin->si_region_count)
4217 		    {
4218 			smsg(_("Invalid region nr in %s line %ld: %s"),
4219 							  fname, lnum, p);
4220 			break;
4221 		    }
4222 		    regionmask |= 1 << (l - 1);
4223 		}
4224 		else
4225 		{
4226 		    smsg(_("Unrecognized flags in %s line %ld: %s"),
4227 							      fname, lnum, p);
4228 		    break;
4229 		}
4230 		++p;
4231 	    }
4232 	}
4233 
4234 	// Skip non-ASCII words when "spin->si_ascii" is TRUE.
4235 	if (spin->si_ascii && has_non_ascii(line))
4236 	{
4237 	    ++non_ascii;
4238 	    continue;
4239 	}
4240 
4241 	// Normal word: store it.
4242 	if (store_word(spin, line, flags, regionmask, NULL, FALSE) == FAIL)
4243 	{
4244 	    retval = FAIL;
4245 	    break;
4246 	}
4247 	did_word = TRUE;
4248     }
4249 
4250     vim_free(pc);
4251     fclose(fd);
4252 
4253     if (spin->si_ascii && non_ascii > 0)
4254     {
4255 	vim_snprintf((char *)IObuff, IOSIZE,
4256 		  _("Ignored %d words with non-ASCII characters"), non_ascii);
4257 	spell_message(spin, IObuff);
4258     }
4259 
4260     return retval;
4261 }
4262 
4263 /*
4264  * Get part of an sblock_T, "len" bytes long.
4265  * This avoids calling free() for every little struct we use (and keeping
4266  * track of them).
4267  * The memory is cleared to all zeros.
4268  * Returns NULL when out of memory.
4269  */
4270     static void *
4271 getroom(
4272     spellinfo_T *spin,
4273     size_t	len,		// length needed
4274     int		align)		// align for pointer
4275 {
4276     char_u	*p;
4277     sblock_T	*bl = spin->si_blocks;
4278 
4279     if (align && bl != NULL)
4280 	// Round size up for alignment.  On some systems structures need to be
4281 	// aligned to the size of a pointer (e.g., SPARC).
4282 	bl->sb_used = (bl->sb_used + sizeof(char *) - 1)
4283 						      & ~(sizeof(char *) - 1);
4284 
4285     if (bl == NULL || bl->sb_used + len > SBLOCKSIZE)
4286     {
4287 	if (len >= SBLOCKSIZE)
4288 	    bl = NULL;
4289 	else
4290 	    // Allocate a block of memory. It is not freed until much later.
4291 	    bl = alloc_clear(sizeof(sblock_T) + SBLOCKSIZE);
4292 	if (bl == NULL)
4293 	{
4294 	    if (!spin->si_did_emsg)
4295 	    {
4296 		emsg(_("E845: Insufficient memory, word list will be incomplete"));
4297 		spin->si_did_emsg = TRUE;
4298 	    }
4299 	    return NULL;
4300 	}
4301 	bl->sb_next = spin->si_blocks;
4302 	spin->si_blocks = bl;
4303 	bl->sb_used = 0;
4304 	++spin->si_blocks_cnt;
4305     }
4306 
4307     p = bl->sb_data + bl->sb_used;
4308     bl->sb_used += (int)len;
4309 
4310     return p;
4311 }
4312 
4313 /*
4314  * Make a copy of a string into memory allocated with getroom().
4315  * Returns NULL when out of memory.
4316  */
4317     static char_u *
4318 getroom_save(spellinfo_T *spin, char_u *s)
4319 {
4320     char_u	*sc;
4321 
4322     sc = (char_u *)getroom(spin, STRLEN(s) + 1, FALSE);
4323     if (sc != NULL)
4324 	STRCPY(sc, s);
4325     return sc;
4326 }
4327 
4328 
4329 /*
4330  * Free the list of allocated sblock_T.
4331  */
4332     static void
4333 free_blocks(sblock_T *bl)
4334 {
4335     sblock_T	*next;
4336 
4337     while (bl != NULL)
4338     {
4339 	next = bl->sb_next;
4340 	vim_free(bl);
4341 	bl = next;
4342     }
4343 }
4344 
4345 /*
4346  * Allocate the root of a word tree.
4347  * Returns NULL when out of memory.
4348  */
4349     static wordnode_T *
4350 wordtree_alloc(spellinfo_T *spin)
4351 {
4352     return (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
4353 }
4354 
4355 /*
4356  * Store a word in the tree(s).
4357  * Always store it in the case-folded tree.  For a keep-case word this is
4358  * useful when the word can also be used with all caps (no WF_FIXCAP flag) and
4359  * used to find suggestions.
4360  * For a keep-case word also store it in the keep-case tree.
4361  * When "pfxlist" is not NULL store the word for each postponed prefix ID and
4362  * compound flag.
4363  */
4364     static int
4365 store_word(
4366     spellinfo_T	*spin,
4367     char_u	*word,
4368     int		flags,		// extra flags, WF_BANNED
4369     int		region,		// supported region(s)
4370     char_u	*pfxlist,	// list of prefix IDs or NULL
4371     int		need_affix)	// only store word with affix ID
4372 {
4373     int		len = (int)STRLEN(word);
4374     int		ct = captype(word, word + len);
4375     char_u	foldword[MAXWLEN];
4376     int		res = OK;
4377     char_u	*p;
4378 
4379     (void)spell_casefold(word, len, foldword, MAXWLEN);
4380     for (p = pfxlist; res == OK; ++p)
4381     {
4382 	if (!need_affix || (p != NULL && *p != NUL))
4383 	    res = tree_add_word(spin, foldword, spin->si_foldroot, ct | flags,
4384 						  region, p == NULL ? 0 : *p);
4385 	if (p == NULL || *p == NUL)
4386 	    break;
4387     }
4388     ++spin->si_foldwcount;
4389 
4390     if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP)))
4391     {
4392 	for (p = pfxlist; res == OK; ++p)
4393 	{
4394 	    if (!need_affix || (p != NULL && *p != NUL))
4395 		res = tree_add_word(spin, word, spin->si_keeproot, flags,
4396 						  region, p == NULL ? 0 : *p);
4397 	    if (p == NULL || *p == NUL)
4398 		break;
4399 	}
4400 	++spin->si_keepwcount;
4401     }
4402     return res;
4403 }
4404 
4405 /*
4406  * Add word "word" to a word tree at "root".
4407  * When "flags" < 0 we are adding to the prefix tree where "flags" is used for
4408  * "rare" and "region" is the condition nr.
4409  * Returns FAIL when out of memory.
4410  */
4411     static int
4412 tree_add_word(
4413     spellinfo_T	*spin,
4414     char_u	*word,
4415     wordnode_T	*root,
4416     int		flags,
4417     int		region,
4418     int		affixID)
4419 {
4420     wordnode_T	*node = root;
4421     wordnode_T	*np;
4422     wordnode_T	*copyp, **copyprev;
4423     wordnode_T	**prev = NULL;
4424     int		i;
4425 
4426     // Add each byte of the word to the tree, including the NUL at the end.
4427     for (i = 0; ; ++i)
4428     {
4429 	// When there is more than one reference to this node we need to make
4430 	// a copy, so that we can modify it.  Copy the whole list of siblings
4431 	// (we don't optimize for a partly shared list of siblings).
4432 	if (node != NULL && node->wn_refs > 1)
4433 	{
4434 	    --node->wn_refs;
4435 	    copyprev = prev;
4436 	    FOR_ALL_NODE_SIBLINGS(node, copyp)
4437 	    {
4438 		// Allocate a new node and copy the info.
4439 		np = get_wordnode(spin);
4440 		if (np == NULL)
4441 		    return FAIL;
4442 		np->wn_child = copyp->wn_child;
4443 		if (np->wn_child != NULL)
4444 		    ++np->wn_child->wn_refs;	// child gets extra ref
4445 		np->wn_byte = copyp->wn_byte;
4446 		if (np->wn_byte == NUL)
4447 		{
4448 		    np->wn_flags = copyp->wn_flags;
4449 		    np->wn_region = copyp->wn_region;
4450 		    np->wn_affixID = copyp->wn_affixID;
4451 		}
4452 
4453 		// Link the new node in the list, there will be one ref.
4454 		np->wn_refs = 1;
4455 		if (copyprev != NULL)
4456 		    *copyprev = np;
4457 		copyprev = &np->wn_sibling;
4458 
4459 		// Let "node" point to the head of the copied list.
4460 		if (copyp == node)
4461 		    node = np;
4462 	    }
4463 	}
4464 
4465 	// Look for the sibling that has the same character.  They are sorted
4466 	// on byte value, thus stop searching when a sibling is found with a
4467 	// higher byte value.  For zero bytes (end of word) the sorting is
4468 	// done on flags and then on affixID.
4469 	while (node != NULL
4470 		&& (node->wn_byte < word[i]
4471 		    || (node->wn_byte == NUL
4472 			&& (flags < 0
4473 			    ? node->wn_affixID < (unsigned)affixID
4474 			    : (node->wn_flags < (unsigned)(flags & WN_MASK)
4475 				|| (node->wn_flags == (flags & WN_MASK)
4476 				    && (spin->si_sugtree
4477 					? (node->wn_region & 0xffff) < region
4478 					: node->wn_affixID
4479 						    < (unsigned)affixID)))))))
4480 	{
4481 	    prev = &node->wn_sibling;
4482 	    node = *prev;
4483 	}
4484 	if (node == NULL
4485 		|| node->wn_byte != word[i]
4486 		|| (word[i] == NUL
4487 		    && (flags < 0
4488 			|| spin->si_sugtree
4489 			|| node->wn_flags != (flags & WN_MASK)
4490 			|| node->wn_affixID != affixID)))
4491 	{
4492 	    // Allocate a new node.
4493 	    np = get_wordnode(spin);
4494 	    if (np == NULL)
4495 		return FAIL;
4496 	    np->wn_byte = word[i];
4497 
4498 	    // If "node" is NULL this is a new child or the end of the sibling
4499 	    // list: ref count is one.  Otherwise use ref count of sibling and
4500 	    // make ref count of sibling one (matters when inserting in front
4501 	    // of the list of siblings).
4502 	    if (node == NULL)
4503 		np->wn_refs = 1;
4504 	    else
4505 	    {
4506 		np->wn_refs = node->wn_refs;
4507 		node->wn_refs = 1;
4508 	    }
4509 	    if (prev != NULL)
4510 		*prev = np;
4511 	    np->wn_sibling = node;
4512 	    node = np;
4513 	}
4514 
4515 	if (word[i] == NUL)
4516 	{
4517 	    node->wn_flags = flags;
4518 	    node->wn_region |= region;
4519 	    node->wn_affixID = affixID;
4520 	    break;
4521 	}
4522 	prev = &node->wn_child;
4523 	node = *prev;
4524     }
4525 #ifdef SPELL_PRINTTREE
4526     smsg("Added \"%s\"", word);
4527     spell_print_tree(root->wn_sibling);
4528 #endif
4529 
4530     // count nr of words added since last message
4531     ++spin->si_msg_count;
4532 
4533     if (spin->si_compress_cnt > 1)
4534     {
4535 	if (--spin->si_compress_cnt == 1)
4536 	    // Did enough words to lower the block count limit.
4537 	    spin->si_blocks_cnt += compress_inc;
4538     }
4539 
4540     /*
4541      * When we have allocated lots of memory we need to compress the word tree
4542      * to free up some room.  But compression is slow, and we might actually
4543      * need that room, thus only compress in the following situations:
4544      * 1. When not compressed before (si_compress_cnt == 0): when using
4545      *    "compress_start" blocks.
4546      * 2. When compressed before and used "compress_inc" blocks before
4547      *    adding "compress_added" words (si_compress_cnt > 1).
4548      * 3. When compressed before, added "compress_added" words
4549      *    (si_compress_cnt == 1) and the number of free nodes drops below the
4550      *    maximum word length.
4551      */
4552 #ifndef SPELL_COMPRESS_ALLWAYS
4553     if (spin->si_compress_cnt == 1
4554 	    ? spin->si_free_count < MAXWLEN
4555 	    : spin->si_blocks_cnt >= compress_start)
4556 #endif
4557     {
4558 	// Decrement the block counter.  The effect is that we compress again
4559 	// when the freed up room has been used and another "compress_inc"
4560 	// blocks have been allocated.  Unless "compress_added" words have
4561 	// been added, then the limit is put back again.
4562 	spin->si_blocks_cnt -= compress_inc;
4563 	spin->si_compress_cnt = compress_added;
4564 
4565 	if (spin->si_verbose)
4566 	{
4567 	    msg_start();
4568 	    msg_puts(_(msg_compressing));
4569 	    msg_clr_eos();
4570 	    msg_didout = FALSE;
4571 	    msg_col = 0;
4572 	    out_flush();
4573 	}
4574 
4575 	// Compress both trees.  Either they both have many nodes, which makes
4576 	// compression useful, or one of them is small, which means
4577 	// compression goes fast.  But when filling the soundfold word tree
4578 	// there is no keep-case tree.
4579 	wordtree_compress(spin, spin->si_foldroot);
4580 	if (affixID >= 0)
4581 	    wordtree_compress(spin, spin->si_keeproot);
4582     }
4583 
4584     return OK;
4585 }
4586 
4587 /*
4588  * Get a wordnode_T, either from the list of previously freed nodes or
4589  * allocate a new one.
4590  * Returns NULL when out of memory.
4591  */
4592     static wordnode_T *
4593 get_wordnode(spellinfo_T *spin)
4594 {
4595     wordnode_T *n;
4596 
4597     if (spin->si_first_free == NULL)
4598 	n = (wordnode_T *)getroom(spin, sizeof(wordnode_T), TRUE);
4599     else
4600     {
4601 	n = spin->si_first_free;
4602 	spin->si_first_free = n->wn_child;
4603 	CLEAR_POINTER(n);
4604 	--spin->si_free_count;
4605     }
4606 #ifdef SPELL_PRINTTREE
4607     if (n != NULL)
4608 	n->wn_nr = ++spin->si_wordnode_nr;
4609 #endif
4610     return n;
4611 }
4612 
4613 /*
4614  * Decrement the reference count on a node (which is the head of a list of
4615  * siblings).  If the reference count becomes zero free the node and its
4616  * siblings.
4617  * Returns the number of nodes actually freed.
4618  */
4619     static int
4620 deref_wordnode(spellinfo_T *spin, wordnode_T *node)
4621 {
4622     wordnode_T	*np;
4623     int		cnt = 0;
4624 
4625     if (--node->wn_refs == 0)
4626     {
4627 	FOR_ALL_NODE_SIBLINGS(node, np)
4628 	{
4629 	    if (np->wn_child != NULL)
4630 		cnt += deref_wordnode(spin, np->wn_child);
4631 	    free_wordnode(spin, np);
4632 	    ++cnt;
4633 	}
4634 	++cnt;	    // length field
4635     }
4636     return cnt;
4637 }
4638 
4639 /*
4640  * Free a wordnode_T for re-use later.
4641  * Only the "wn_child" field becomes invalid.
4642  */
4643     static void
4644 free_wordnode(spellinfo_T *spin, wordnode_T *n)
4645 {
4646     n->wn_child = spin->si_first_free;
4647     spin->si_first_free = n;
4648     ++spin->si_free_count;
4649 }
4650 
4651 /*
4652  * Compress a tree: find tails that are identical and can be shared.
4653  */
4654     static void
4655 wordtree_compress(spellinfo_T *spin, wordnode_T *root)
4656 {
4657     hashtab_T	    ht;
4658     int		    n;
4659     int		    tot = 0;
4660     int		    perc;
4661 
4662     // Skip the root itself, it's not actually used.  The first sibling is the
4663     // start of the tree.
4664     if (root->wn_sibling != NULL)
4665     {
4666 	hash_init(&ht);
4667 	n = node_compress(spin, root->wn_sibling, &ht, &tot);
4668 
4669 #ifndef SPELL_PRINTTREE
4670 	if (spin->si_verbose || p_verbose > 2)
4671 #endif
4672 	{
4673 	    if (tot > 1000000)
4674 		perc = (tot - n) / (tot / 100);
4675 	    else if (tot == 0)
4676 		perc = 0;
4677 	    else
4678 		perc = (tot - n) * 100 / tot;
4679 	    vim_snprintf((char *)IObuff, IOSIZE,
4680 			  _("Compressed %d of %d nodes; %d (%d%%) remaining"),
4681 						       n, tot, tot - n, perc);
4682 	    spell_message(spin, IObuff);
4683 	}
4684 #ifdef SPELL_PRINTTREE
4685 	spell_print_tree(root->wn_sibling);
4686 #endif
4687 	hash_clear(&ht);
4688     }
4689 }
4690 
4691 /*
4692  * Compress a node, its siblings and its children, depth first.
4693  * Returns the number of compressed nodes.
4694  */
4695     static int
4696 node_compress(
4697     spellinfo_T	*spin,
4698     wordnode_T	*node,
4699     hashtab_T	*ht,
4700     int		*tot)	    // total count of nodes before compressing,
4701 			    // incremented while going through the tree
4702 {
4703     wordnode_T	*np;
4704     wordnode_T	*tp;
4705     wordnode_T	*child;
4706     hash_T	hash;
4707     hashitem_T	*hi;
4708     int		len = 0;
4709     unsigned	nr, n;
4710     int		compressed = 0;
4711 
4712     /*
4713      * Go through the list of siblings.  Compress each child and then try
4714      * finding an identical child to replace it.
4715      * Note that with "child" we mean not just the node that is pointed to,
4716      * but the whole list of siblings of which the child node is the first.
4717      */
4718     for (np = node; np != NULL && !got_int; np = np->wn_sibling)
4719     {
4720 	++len;
4721 	if ((child = np->wn_child) != NULL)
4722 	{
4723 	    // Compress the child first.  This fills hashkey.
4724 	    compressed += node_compress(spin, child, ht, tot);
4725 
4726 	    // Try to find an identical child.
4727 	    hash = hash_hash(child->wn_u1.hashkey);
4728 	    hi = hash_lookup(ht, child->wn_u1.hashkey, hash);
4729 	    if (!HASHITEM_EMPTY(hi))
4730 	    {
4731 		// There are children we encountered before with a hash value
4732 		// identical to the current child.  Now check if there is one
4733 		// that is really identical.
4734 		for (tp = HI2WN(hi); tp != NULL; tp = tp->wn_u2.next)
4735 		    if (node_equal(child, tp))
4736 		    {
4737 			// Found one!  Now use that child in place of the
4738 			// current one.  This means the current child and all
4739 			// its siblings is unlinked from the tree.
4740 			++tp->wn_refs;
4741 			compressed += deref_wordnode(spin, child);
4742 			np->wn_child = tp;
4743 			break;
4744 		    }
4745 		if (tp == NULL)
4746 		{
4747 		    // No other child with this hash value equals the child of
4748 		    // the node, add it to the linked list after the first
4749 		    // item.
4750 		    tp = HI2WN(hi);
4751 		    child->wn_u2.next = tp->wn_u2.next;
4752 		    tp->wn_u2.next = child;
4753 		}
4754 	    }
4755 	    else
4756 		// No other child has this hash value, add it to the
4757 		// hashtable.
4758 		hash_add_item(ht, hi, child->wn_u1.hashkey, hash);
4759 	}
4760     }
4761     *tot += len + 1;	// add one for the node that stores the length
4762 
4763     /*
4764      * Make a hash key for the node and its siblings, so that we can quickly
4765      * find a lookalike node.  This must be done after compressing the sibling
4766      * list, otherwise the hash key would become invalid by the compression.
4767      */
4768     node->wn_u1.hashkey[0] = len;
4769     nr = 0;
4770     FOR_ALL_NODE_SIBLINGS(node, np)
4771     {
4772 	if (np->wn_byte == NUL)
4773 	    // end node: use wn_flags, wn_region and wn_affixID
4774 	    n = np->wn_flags + (np->wn_region << 8) + (np->wn_affixID << 16);
4775 	else
4776 	    // byte node: use the byte value and the child pointer
4777 	    n = (unsigned)(np->wn_byte + ((long_u)np->wn_child << 8));
4778 	nr = nr * 101 + n;
4779     }
4780 
4781     // Avoid NUL bytes, it terminates the hash key.
4782     n = nr & 0xff;
4783     node->wn_u1.hashkey[1] = n == 0 ? 1 : n;
4784     n = (nr >> 8) & 0xff;
4785     node->wn_u1.hashkey[2] = n == 0 ? 1 : n;
4786     n = (nr >> 16) & 0xff;
4787     node->wn_u1.hashkey[3] = n == 0 ? 1 : n;
4788     n = (nr >> 24) & 0xff;
4789     node->wn_u1.hashkey[4] = n == 0 ? 1 : n;
4790     node->wn_u1.hashkey[5] = NUL;
4791 
4792     // Check for CTRL-C pressed now and then.
4793     fast_breakcheck();
4794 
4795     return compressed;
4796 }
4797 
4798 /*
4799  * Return TRUE when two nodes have identical siblings and children.
4800  */
4801     static int
4802 node_equal(wordnode_T *n1, wordnode_T *n2)
4803 {
4804     wordnode_T	*p1;
4805     wordnode_T	*p2;
4806 
4807     for (p1 = n1, p2 = n2; p1 != NULL && p2 != NULL;
4808 				     p1 = p1->wn_sibling, p2 = p2->wn_sibling)
4809 	if (p1->wn_byte != p2->wn_byte
4810 		|| (p1->wn_byte == NUL
4811 		    ? (p1->wn_flags != p2->wn_flags
4812 			|| p1->wn_region != p2->wn_region
4813 			|| p1->wn_affixID != p2->wn_affixID)
4814 		    : (p1->wn_child != p2->wn_child)))
4815 	    break;
4816 
4817     return p1 == NULL && p2 == NULL;
4818 }
4819 
4820 static int rep_compare(const void *s1, const void *s2);
4821 
4822 /*
4823  * Function given to qsort() to sort the REP items on "from" string.
4824  */
4825     static int
4826 rep_compare(const void *s1, const void *s2)
4827 {
4828     fromto_T	*p1 = (fromto_T *)s1;
4829     fromto_T	*p2 = (fromto_T *)s2;
4830 
4831     return STRCMP(p1->ft_from, p2->ft_from);
4832 }
4833 
4834 /*
4835  * Write the Vim .spl file "fname".
4836  * Return FAIL or OK;
4837  */
4838     static int
4839 write_vim_spell(spellinfo_T *spin, char_u *fname)
4840 {
4841     FILE	*fd;
4842     int		regionmask;
4843     int		round;
4844     wordnode_T	*tree;
4845     int		nodecount;
4846     int		i;
4847     int		l;
4848     garray_T	*gap;
4849     fromto_T	*ftp;
4850     char_u	*p;
4851     int		rr;
4852     int		retval = OK;
4853     size_t	fwv = 1;  // collect return value of fwrite() to avoid
4854 			  // warnings from picky compiler
4855 
4856     fd = mch_fopen((char *)fname, "w");
4857     if (fd == NULL)
4858     {
4859 	semsg(_(e_notopen), fname);
4860 	return FAIL;
4861     }
4862 
4863     // <HEADER>: <fileID> <versionnr>
4864 							    // <fileID>
4865     fwv &= fwrite(VIMSPELLMAGIC, VIMSPELLMAGICL, (size_t)1, fd);
4866     if (fwv != (size_t)1)
4867 	// Catch first write error, don't try writing more.
4868 	goto theend;
4869 
4870     putc(VIMSPELLVERSION, fd);				    // <versionnr>
4871 
4872     /*
4873      * <SECTIONS>: <section> ... <sectionend>
4874      */
4875 
4876     // SN_INFO: <infotext>
4877     if (spin->si_info != NULL)
4878     {
4879 	putc(SN_INFO, fd);				// <sectionID>
4880 	putc(0, fd);					// <sectionflags>
4881 
4882 	i = (int)STRLEN(spin->si_info);
4883 	put_bytes(fd, (long_u)i, 4);			// <sectionlen>
4884 	fwv &= fwrite(spin->si_info, (size_t)i, (size_t)1, fd); // <infotext>
4885     }
4886 
4887     // SN_REGION: <regionname> ...
4888     // Write the region names only if there is more than one.
4889     if (spin->si_region_count > 1)
4890     {
4891 	putc(SN_REGION, fd);				// <sectionID>
4892 	putc(SNF_REQUIRED, fd);				// <sectionflags>
4893 	l = spin->si_region_count * 2;
4894 	put_bytes(fd, (long_u)l, 4);			// <sectionlen>
4895 	fwv &= fwrite(spin->si_region_name, (size_t)l, (size_t)1, fd);
4896 							// <regionname> ...
4897 	regionmask = (1 << spin->si_region_count) - 1;
4898     }
4899     else
4900 	regionmask = 0;
4901 
4902     // SN_CHARFLAGS: <charflagslen> <charflags> <folcharslen> <folchars>
4903     //
4904     // The table with character flags and the table for case folding.
4905     // This makes sure the same characters are recognized as word characters
4906     // when generating an when using a spell file.
4907     // Skip this for ASCII, the table may conflict with the one used for
4908     // 'encoding'.
4909     // Also skip this for an .add.spl file, the main spell file must contain
4910     // the table (avoids that it conflicts).  File is shorter too.
4911     if (!spin->si_ascii && !spin->si_add)
4912     {
4913 	char_u	folchars[128 * 8];
4914 	int	flags;
4915 
4916 	putc(SN_CHARFLAGS, fd);				// <sectionID>
4917 	putc(SNF_REQUIRED, fd);				// <sectionflags>
4918 
4919 	// Form the <folchars> string first, we need to know its length.
4920 	l = 0;
4921 	for (i = 128; i < 256; ++i)
4922 	{
4923 	    if (has_mbyte)
4924 		l += mb_char2bytes(spelltab.st_fold[i], folchars + l);
4925 	    else
4926 		folchars[l++] = spelltab.st_fold[i];
4927 	}
4928 	put_bytes(fd, (long_u)(1 + 128 + 2 + l), 4);	// <sectionlen>
4929 
4930 	fputc(128, fd);					// <charflagslen>
4931 	for (i = 128; i < 256; ++i)
4932 	{
4933 	    flags = 0;
4934 	    if (spelltab.st_isw[i])
4935 		flags |= CF_WORD;
4936 	    if (spelltab.st_isu[i])
4937 		flags |= CF_UPPER;
4938 	    fputc(flags, fd);				// <charflags>
4939 	}
4940 
4941 	put_bytes(fd, (long_u)l, 2);			// <folcharslen>
4942 	fwv &= fwrite(folchars, (size_t)l, (size_t)1, fd); // <folchars>
4943     }
4944 
4945     // SN_MIDWORD: <midword>
4946     if (spin->si_midword != NULL)
4947     {
4948 	putc(SN_MIDWORD, fd);				// <sectionID>
4949 	putc(SNF_REQUIRED, fd);				// <sectionflags>
4950 
4951 	i = (int)STRLEN(spin->si_midword);
4952 	put_bytes(fd, (long_u)i, 4);			// <sectionlen>
4953 	fwv &= fwrite(spin->si_midword, (size_t)i, (size_t)1, fd);
4954 							// <midword>
4955     }
4956 
4957     // SN_PREFCOND: <prefcondcnt> <prefcond> ...
4958     if (spin->si_prefcond.ga_len > 0)
4959     {
4960 	putc(SN_PREFCOND, fd);				// <sectionID>
4961 	putc(SNF_REQUIRED, fd);				// <sectionflags>
4962 
4963 	l = write_spell_prefcond(NULL, &spin->si_prefcond);
4964 	put_bytes(fd, (long_u)l, 4);			// <sectionlen>
4965 
4966 	write_spell_prefcond(fd, &spin->si_prefcond);
4967     }
4968 
4969     // SN_REP: <repcount> <rep> ...
4970     // SN_SAL: <salflags> <salcount> <sal> ...
4971     // SN_REPSAL: <repcount> <rep> ...
4972 
4973     // round 1: SN_REP section
4974     // round 2: SN_SAL section (unless SN_SOFO is used)
4975     // round 3: SN_REPSAL section
4976     for (round = 1; round <= 3; ++round)
4977     {
4978 	if (round == 1)
4979 	    gap = &spin->si_rep;
4980 	else if (round == 2)
4981 	{
4982 	    // Don't write SN_SAL when using a SN_SOFO section
4983 	    if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
4984 		continue;
4985 	    gap = &spin->si_sal;
4986 	}
4987 	else
4988 	    gap = &spin->si_repsal;
4989 
4990 	// Don't write the section if there are no items.
4991 	if (gap->ga_len == 0)
4992 	    continue;
4993 
4994 	// Sort the REP/REPSAL items.
4995 	if (round != 2)
4996 	    qsort(gap->ga_data, (size_t)gap->ga_len,
4997 					       sizeof(fromto_T), rep_compare);
4998 
4999 	i = round == 1 ? SN_REP : (round == 2 ? SN_SAL : SN_REPSAL);
5000 	putc(i, fd);					// <sectionID>
5001 
5002 	// This is for making suggestions, section is not required.
5003 	putc(0, fd);					// <sectionflags>
5004 
5005 	// Compute the length of what follows.
5006 	l = 2;	    // count <repcount> or <salcount>
5007 	for (i = 0; i < gap->ga_len; ++i)
5008 	{
5009 	    ftp = &((fromto_T *)gap->ga_data)[i];
5010 	    l += 1 + (int)STRLEN(ftp->ft_from);  // count <*fromlen> and <*from>
5011 	    l += 1 + (int)STRLEN(ftp->ft_to);    // count <*tolen> and <*to>
5012 	}
5013 	if (round == 2)
5014 	    ++l;	// count <salflags>
5015 	put_bytes(fd, (long_u)l, 4);			// <sectionlen>
5016 
5017 	if (round == 2)
5018 	{
5019 	    i = 0;
5020 	    if (spin->si_followup)
5021 		i |= SAL_F0LLOWUP;
5022 	    if (spin->si_collapse)
5023 		i |= SAL_COLLAPSE;
5024 	    if (spin->si_rem_accents)
5025 		i |= SAL_REM_ACCENTS;
5026 	    putc(i, fd);			// <salflags>
5027 	}
5028 
5029 	put_bytes(fd, (long_u)gap->ga_len, 2);	// <repcount> or <salcount>
5030 	for (i = 0; i < gap->ga_len; ++i)
5031 	{
5032 	    // <rep> : <repfromlen> <repfrom> <reptolen> <repto>
5033 	    // <sal> : <salfromlen> <salfrom> <saltolen> <salto>
5034 	    ftp = &((fromto_T *)gap->ga_data)[i];
5035 	    for (rr = 1; rr <= 2; ++rr)
5036 	    {
5037 		p = rr == 1 ? ftp->ft_from : ftp->ft_to;
5038 		l = (int)STRLEN(p);
5039 		putc(l, fd);
5040 		if (l > 0)
5041 		    fwv &= fwrite(p, l, (size_t)1, fd);
5042 	    }
5043 	}
5044 
5045     }
5046 
5047     // SN_SOFO: <sofofromlen> <sofofrom> <sofotolen> <sofoto>
5048     // This is for making suggestions, section is not required.
5049     if (spin->si_sofofr != NULL && spin->si_sofoto != NULL)
5050     {
5051 	putc(SN_SOFO, fd);				// <sectionID>
5052 	putc(0, fd);					// <sectionflags>
5053 
5054 	l = (int)STRLEN(spin->si_sofofr);
5055 	put_bytes(fd, (long_u)(l + STRLEN(spin->si_sofoto) + 4), 4);
5056 							// <sectionlen>
5057 
5058 	put_bytes(fd, (long_u)l, 2);			// <sofofromlen>
5059 	fwv &= fwrite(spin->si_sofofr, l, (size_t)1, fd); // <sofofrom>
5060 
5061 	l = (int)STRLEN(spin->si_sofoto);
5062 	put_bytes(fd, (long_u)l, 2);			// <sofotolen>
5063 	fwv &= fwrite(spin->si_sofoto, l, (size_t)1, fd); // <sofoto>
5064     }
5065 
5066     // SN_WORDS: <word> ...
5067     // This is for making suggestions, section is not required.
5068     if (spin->si_commonwords.ht_used > 0)
5069     {
5070 	putc(SN_WORDS, fd);				// <sectionID>
5071 	putc(0, fd);					// <sectionflags>
5072 
5073 	// round 1: count the bytes
5074 	// round 2: write the bytes
5075 	for (round = 1; round <= 2; ++round)
5076 	{
5077 	    int		todo;
5078 	    int		len = 0;
5079 	    hashitem_T	*hi;
5080 
5081 	    todo = (int)spin->si_commonwords.ht_used;
5082 	    for (hi = spin->si_commonwords.ht_array; todo > 0; ++hi)
5083 		if (!HASHITEM_EMPTY(hi))
5084 		{
5085 		    l = (int)STRLEN(hi->hi_key) + 1;
5086 		    len += l;
5087 		    if (round == 2)			// <word>
5088 			fwv &= fwrite(hi->hi_key, (size_t)l, (size_t)1, fd);
5089 		    --todo;
5090 		}
5091 	    if (round == 1)
5092 		put_bytes(fd, (long_u)len, 4);		// <sectionlen>
5093 	}
5094     }
5095 
5096     // SN_MAP: <mapstr>
5097     // This is for making suggestions, section is not required.
5098     if (spin->si_map.ga_len > 0)
5099     {
5100 	putc(SN_MAP, fd);				// <sectionID>
5101 	putc(0, fd);					// <sectionflags>
5102 	l = spin->si_map.ga_len;
5103 	put_bytes(fd, (long_u)l, 4);			// <sectionlen>
5104 	fwv &= fwrite(spin->si_map.ga_data, (size_t)l, (size_t)1, fd);
5105 							// <mapstr>
5106     }
5107 
5108     // SN_SUGFILE: <timestamp>
5109     // This is used to notify that a .sug file may be available and at the
5110     // same time allows for checking that a .sug file that is found matches
5111     // with this .spl file.  That's because the word numbers must be exactly
5112     // right.
5113     if (!spin->si_nosugfile
5114 	    && (spin->si_sal.ga_len > 0
5115 		     || (spin->si_sofofr != NULL && spin->si_sofoto != NULL)))
5116     {
5117 	putc(SN_SUGFILE, fd);				// <sectionID>
5118 	putc(0, fd);					// <sectionflags>
5119 	put_bytes(fd, (long_u)8, 4);			// <sectionlen>
5120 
5121 	// Set si_sugtime and write it to the file.
5122 	spin->si_sugtime = time(NULL);
5123 	put_time(fd, spin->si_sugtime);			// <timestamp>
5124     }
5125 
5126     // SN_NOSPLITSUGS: nothing
5127     // This is used to notify that no suggestions with word splits are to be
5128     // made.
5129     if (spin->si_nosplitsugs)
5130     {
5131 	putc(SN_NOSPLITSUGS, fd);			// <sectionID>
5132 	putc(0, fd);					// <sectionflags>
5133 	put_bytes(fd, (long_u)0, 4);			// <sectionlen>
5134     }
5135 
5136     // SN_NOCOMPUNDSUGS: nothing
5137     // This is used to notify that no suggestions with compounds are to be
5138     // made.
5139     if (spin->si_nocompoundsugs)
5140     {
5141 	putc(SN_NOCOMPOUNDSUGS, fd);			// <sectionID>
5142 	putc(0, fd);					// <sectionflags>
5143 	put_bytes(fd, (long_u)0, 4);			// <sectionlen>
5144     }
5145 
5146     // SN_COMPOUND: compound info.
5147     // We don't mark it required, when not supported all compound words will
5148     // be bad words.
5149     if (spin->si_compflags != NULL)
5150     {
5151 	putc(SN_COMPOUND, fd);				// <sectionID>
5152 	putc(0, fd);					// <sectionflags>
5153 
5154 	l = (int)STRLEN(spin->si_compflags);
5155 	for (i = 0; i < spin->si_comppat.ga_len; ++i)
5156 	    l += (int)STRLEN(((char_u **)(spin->si_comppat.ga_data))[i]) + 1;
5157 	put_bytes(fd, (long_u)(l + 7), 4);		// <sectionlen>
5158 
5159 	putc(spin->si_compmax, fd);			// <compmax>
5160 	putc(spin->si_compminlen, fd);			// <compminlen>
5161 	putc(spin->si_compsylmax, fd);			// <compsylmax>
5162 	putc(0, fd);		// for Vim 7.0b compatibility
5163 	putc(spin->si_compoptions, fd);			// <compoptions>
5164 	put_bytes(fd, (long_u)spin->si_comppat.ga_len, 2);
5165 							// <comppatcount>
5166 	for (i = 0; i < spin->si_comppat.ga_len; ++i)
5167 	{
5168 	    p = ((char_u **)(spin->si_comppat.ga_data))[i];
5169 	    putc((int)STRLEN(p), fd);			// <comppatlen>
5170 	    fwv &= fwrite(p, (size_t)STRLEN(p), (size_t)1, fd);
5171 							// <comppattext>
5172 	}
5173 							// <compflags>
5174 	fwv &= fwrite(spin->si_compflags, (size_t)STRLEN(spin->si_compflags),
5175 							       (size_t)1, fd);
5176     }
5177 
5178     // SN_NOBREAK: NOBREAK flag
5179     if (spin->si_nobreak)
5180     {
5181 	putc(SN_NOBREAK, fd);				// <sectionID>
5182 	putc(0, fd);					// <sectionflags>
5183 
5184 	// It's empty, the presence of the section flags the feature.
5185 	put_bytes(fd, (long_u)0, 4);			// <sectionlen>
5186     }
5187 
5188     // SN_SYLLABLE: syllable info.
5189     // We don't mark it required, when not supported syllables will not be
5190     // counted.
5191     if (spin->si_syllable != NULL)
5192     {
5193 	putc(SN_SYLLABLE, fd);				// <sectionID>
5194 	putc(0, fd);					// <sectionflags>
5195 
5196 	l = (int)STRLEN(spin->si_syllable);
5197 	put_bytes(fd, (long_u)l, 4);			// <sectionlen>
5198 	fwv &= fwrite(spin->si_syllable, (size_t)l, (size_t)1, fd);
5199 							// <syllable>
5200     }
5201 
5202     // end of <SECTIONS>
5203     putc(SN_END, fd);					// <sectionend>
5204 
5205 
5206     /*
5207      * <LWORDTREE>  <KWORDTREE>  <PREFIXTREE>
5208      */
5209     spin->si_memtot = 0;
5210     for (round = 1; round <= 3; ++round)
5211     {
5212 	if (round == 1)
5213 	    tree = spin->si_foldroot->wn_sibling;
5214 	else if (round == 2)
5215 	    tree = spin->si_keeproot->wn_sibling;
5216 	else
5217 	    tree = spin->si_prefroot->wn_sibling;
5218 
5219 	// Clear the index and wnode fields in the tree.
5220 	clear_node(tree);
5221 
5222 	// Count the number of nodes.  Needed to be able to allocate the
5223 	// memory when reading the nodes.  Also fills in index for shared
5224 	// nodes.
5225 	nodecount = put_node(NULL, tree, 0, regionmask, round == 3);
5226 
5227 	// number of nodes in 4 bytes
5228 	put_bytes(fd, (long_u)nodecount, 4);	// <nodecount>
5229 	spin->si_memtot += nodecount + nodecount * sizeof(int);
5230 
5231 	// Write the nodes.
5232 	(void)put_node(fd, tree, 0, regionmask, round == 3);
5233     }
5234 
5235     // Write another byte to check for errors (file system full).
5236     if (putc(0, fd) == EOF)
5237 	retval = FAIL;
5238 theend:
5239     if (fclose(fd) == EOF)
5240 	retval = FAIL;
5241 
5242     if (fwv != (size_t)1)
5243 	retval = FAIL;
5244     if (retval == FAIL)
5245 	emsg(_(e_write));
5246 
5247     return retval;
5248 }
5249 
5250 /*
5251  * Clear the index and wnode fields of "node", it siblings and its
5252  * children.  This is needed because they are a union with other items to save
5253  * space.
5254  */
5255     static void
5256 clear_node(wordnode_T *node)
5257 {
5258     wordnode_T	*np;
5259 
5260     if (node != NULL)
5261 	FOR_ALL_NODE_SIBLINGS(node, np)
5262 	{
5263 	    np->wn_u1.index = 0;
5264 	    np->wn_u2.wnode = NULL;
5265 
5266 	    if (np->wn_byte != NUL)
5267 		clear_node(np->wn_child);
5268 	}
5269 }
5270 
5271 
5272 /*
5273  * Dump a word tree at node "node".
5274  *
5275  * This first writes the list of possible bytes (siblings).  Then for each
5276  * byte recursively write the children.
5277  *
5278  * NOTE: The code here must match the code in read_tree_node(), since
5279  * assumptions are made about the indexes (so that we don't have to write them
5280  * in the file).
5281  *
5282  * Returns the number of nodes used.
5283  */
5284     static int
5285 put_node(
5286     FILE	*fd,		// NULL when only counting
5287     wordnode_T	*node,
5288     int		idx,
5289     int		regionmask,
5290     int		prefixtree)	// TRUE for PREFIXTREE
5291 {
5292     int		newindex = idx;
5293     int		siblingcount = 0;
5294     wordnode_T	*np;
5295     int		flags;
5296 
5297     // If "node" is zero the tree is empty.
5298     if (node == NULL)
5299 	return 0;
5300 
5301     // Store the index where this node is written.
5302     node->wn_u1.index = idx;
5303 
5304     // Count the number of siblings.
5305     FOR_ALL_NODE_SIBLINGS(node, np)
5306 	++siblingcount;
5307 
5308     // Write the sibling count.
5309     if (fd != NULL)
5310 	putc(siblingcount, fd);				// <siblingcount>
5311 
5312     // Write each sibling byte and optionally extra info.
5313     FOR_ALL_NODE_SIBLINGS(node, np)
5314     {
5315 	if (np->wn_byte == 0)
5316 	{
5317 	    if (fd != NULL)
5318 	    {
5319 		// For a NUL byte (end of word) write the flags etc.
5320 		if (prefixtree)
5321 		{
5322 		    // In PREFIXTREE write the required affixID and the
5323 		    // associated condition nr (stored in wn_region).  The
5324 		    // byte value is misused to store the "rare" and "not
5325 		    // combining" flags
5326 		    if (np->wn_flags == (short_u)PFX_FLAGS)
5327 			putc(BY_NOFLAGS, fd);		// <byte>
5328 		    else
5329 		    {
5330 			putc(BY_FLAGS, fd);		// <byte>
5331 			putc(np->wn_flags, fd);		// <pflags>
5332 		    }
5333 		    putc(np->wn_affixID, fd);		// <affixID>
5334 		    put_bytes(fd, (long_u)np->wn_region, 2); // <prefcondnr>
5335 		}
5336 		else
5337 		{
5338 		    // For word trees we write the flag/region items.
5339 		    flags = np->wn_flags;
5340 		    if (regionmask != 0 && np->wn_region != regionmask)
5341 			flags |= WF_REGION;
5342 		    if (np->wn_affixID != 0)
5343 			flags |= WF_AFX;
5344 		    if (flags == 0)
5345 		    {
5346 			// word without flags or region
5347 			putc(BY_NOFLAGS, fd);			// <byte>
5348 		    }
5349 		    else
5350 		    {
5351 			if (np->wn_flags >= 0x100)
5352 			{
5353 			    putc(BY_FLAGS2, fd);		// <byte>
5354 			    putc(flags, fd);			// <flags>
5355 			    putc((unsigned)flags >> 8, fd);	// <flags2>
5356 			}
5357 			else
5358 			{
5359 			    putc(BY_FLAGS, fd);			// <byte>
5360 			    putc(flags, fd);			// <flags>
5361 			}
5362 			if (flags & WF_REGION)
5363 			    putc(np->wn_region, fd);		// <region>
5364 			if (flags & WF_AFX)
5365 			    putc(np->wn_affixID, fd);		// <affixID>
5366 		    }
5367 		}
5368 	    }
5369 	}
5370 	else
5371 	{
5372 	    if (np->wn_child->wn_u1.index != 0
5373 					 && np->wn_child->wn_u2.wnode != node)
5374 	    {
5375 		// The child is written elsewhere, write the reference.
5376 		if (fd != NULL)
5377 		{
5378 		    putc(BY_INDEX, fd);			// <byte>
5379 							// <nodeidx>
5380 		    put_bytes(fd, (long_u)np->wn_child->wn_u1.index, 3);
5381 		}
5382 	    }
5383 	    else if (np->wn_child->wn_u2.wnode == NULL)
5384 		// We will write the child below and give it an index.
5385 		np->wn_child->wn_u2.wnode = node;
5386 
5387 	    if (fd != NULL)
5388 		if (putc(np->wn_byte, fd) == EOF) // <byte> or <xbyte>
5389 		{
5390 		    emsg(_(e_write));
5391 		    return 0;
5392 		}
5393 	}
5394     }
5395 
5396     // Space used in the array when reading: one for each sibling and one for
5397     // the count.
5398     newindex += siblingcount + 1;
5399 
5400     // Recursively dump the children of each sibling.
5401     FOR_ALL_NODE_SIBLINGS(node, np)
5402 	if (np->wn_byte != 0 && np->wn_child->wn_u2.wnode == node)
5403 	    newindex = put_node(fd, np->wn_child, newindex, regionmask,
5404 								  prefixtree);
5405 
5406     return newindex;
5407 }
5408 
5409 
5410 /*
5411  * ":mkspell [-ascii] outfile  infile ..."
5412  * ":mkspell [-ascii] addfile"
5413  */
5414     void
5415 ex_mkspell(exarg_T *eap)
5416 {
5417     int		fcount;
5418     char_u	**fnames;
5419     char_u	*arg = eap->arg;
5420     int		ascii = FALSE;
5421 
5422     if (STRNCMP(arg, "-ascii", 6) == 0)
5423     {
5424 	ascii = TRUE;
5425 	arg = skipwhite(arg + 6);
5426     }
5427 
5428     // Expand all the remaining arguments (e.g., $VIMRUNTIME).
5429     if (get_arglist_exp(arg, &fcount, &fnames, FALSE) == OK)
5430     {
5431 	mkspell(fcount, fnames, ascii, eap->forceit, FALSE);
5432 	FreeWild(fcount, fnames);
5433     }
5434 }
5435 
5436 /*
5437  * Create the .sug file.
5438  * Uses the soundfold info in "spin".
5439  * Writes the file with the name "wfname", with ".spl" changed to ".sug".
5440  */
5441     static void
5442 spell_make_sugfile(spellinfo_T *spin, char_u *wfname)
5443 {
5444     char_u	*fname = NULL;
5445     int		len;
5446     slang_T	*slang;
5447     int		free_slang = FALSE;
5448 
5449     /*
5450      * Read back the .spl file that was written.  This fills the required
5451      * info for soundfolding.  This also uses less memory than the
5452      * pointer-linked version of the trie.  And it avoids having two versions
5453      * of the code for the soundfolding stuff.
5454      * It might have been done already by spell_reload_one().
5455      */
5456     FOR_ALL_SPELL_LANGS(slang)
5457 	if (fullpathcmp(wfname, slang->sl_fname, FALSE, TRUE) == FPC_SAME)
5458 	    break;
5459     if (slang == NULL)
5460     {
5461 	spell_message(spin, (char_u *)_("Reading back spell file..."));
5462 	slang = spell_load_file(wfname, NULL, NULL, FALSE);
5463 	if (slang == NULL)
5464 	    return;
5465 	free_slang = TRUE;
5466     }
5467 
5468     /*
5469      * Clear the info in "spin" that is used.
5470      */
5471     spin->si_blocks = NULL;
5472     spin->si_blocks_cnt = 0;
5473     spin->si_compress_cnt = 0;	    // will stay at 0 all the time
5474     spin->si_free_count = 0;
5475     spin->si_first_free = NULL;
5476     spin->si_foldwcount = 0;
5477 
5478     /*
5479      * Go through the trie of good words, soundfold each word and add it to
5480      * the soundfold trie.
5481      */
5482     spell_message(spin, (char_u *)_("Performing soundfolding..."));
5483     if (sug_filltree(spin, slang) == FAIL)
5484 	goto theend;
5485 
5486     /*
5487      * Create the table which links each soundfold word with a list of the
5488      * good words it may come from.  Creates buffer "spin->si_spellbuf".
5489      * This also removes the wordnr from the NUL byte entries to make
5490      * compression possible.
5491      */
5492     if (sug_maketable(spin) == FAIL)
5493 	goto theend;
5494 
5495     smsg(_("Number of words after soundfolding: %ld"),
5496 				 (long)spin->si_spellbuf->b_ml.ml_line_count);
5497 
5498     /*
5499      * Compress the soundfold trie.
5500      */
5501     spell_message(spin, (char_u *)_(msg_compressing));
5502     wordtree_compress(spin, spin->si_foldroot);
5503 
5504     /*
5505      * Write the .sug file.
5506      * Make the file name by changing ".spl" to ".sug".
5507      */
5508     fname = alloc(MAXPATHL);
5509     if (fname == NULL)
5510 	goto theend;
5511     vim_strncpy(fname, wfname, MAXPATHL - 1);
5512     len = (int)STRLEN(fname);
5513     fname[len - 2] = 'u';
5514     fname[len - 1] = 'g';
5515     sug_write(spin, fname);
5516 
5517 theend:
5518     vim_free(fname);
5519     if (free_slang)
5520 	slang_free(slang);
5521     free_blocks(spin->si_blocks);
5522     close_spellbuf(spin->si_spellbuf);
5523 }
5524 
5525 /*
5526  * Build the soundfold trie for language "slang".
5527  */
5528     static int
5529 sug_filltree(spellinfo_T *spin, slang_T *slang)
5530 {
5531     char_u	*byts;
5532     idx_T	*idxs;
5533     int		depth;
5534     idx_T	arridx[MAXWLEN];
5535     int		curi[MAXWLEN];
5536     char_u	tword[MAXWLEN];
5537     char_u	tsalword[MAXWLEN];
5538     int		c;
5539     idx_T	n;
5540     unsigned	words_done = 0;
5541     int		wordcount[MAXWLEN];
5542 
5543     // We use si_foldroot for the soundfolded trie.
5544     spin->si_foldroot = wordtree_alloc(spin);
5545     if (spin->si_foldroot == NULL)
5546 	return FAIL;
5547 
5548     // let tree_add_word() know we're adding to the soundfolded tree
5549     spin->si_sugtree = TRUE;
5550 
5551     /*
5552      * Go through the whole case-folded tree, soundfold each word and put it
5553      * in the trie.
5554      */
5555     byts = slang->sl_fbyts;
5556     idxs = slang->sl_fidxs;
5557 
5558     arridx[0] = 0;
5559     curi[0] = 1;
5560     wordcount[0] = 0;
5561 
5562     depth = 0;
5563     while (depth >= 0 && !got_int)
5564     {
5565 	if (curi[depth] > byts[arridx[depth]])
5566 	{
5567 	    // Done all bytes at this node, go up one level.
5568 	    idxs[arridx[depth]] = wordcount[depth];
5569 	    if (depth > 0)
5570 		wordcount[depth - 1] += wordcount[depth];
5571 
5572 	    --depth;
5573 	    line_breakcheck();
5574 	}
5575 	else
5576 	{
5577 
5578 	    // Do one more byte at this node.
5579 	    n = arridx[depth] + curi[depth];
5580 	    ++curi[depth];
5581 
5582 	    c = byts[n];
5583 	    if (c == 0)
5584 	    {
5585 		// Sound-fold the word.
5586 		tword[depth] = NUL;
5587 		spell_soundfold(slang, tword, TRUE, tsalword);
5588 
5589 		// We use the "flags" field for the MSB of the wordnr,
5590 		// "region" for the LSB of the wordnr.
5591 		if (tree_add_word(spin, tsalword, spin->si_foldroot,
5592 				words_done >> 16, words_done & 0xffff,
5593 							   0) == FAIL)
5594 		    return FAIL;
5595 
5596 		++words_done;
5597 		++wordcount[depth];
5598 
5599 		// Reset the block count each time to avoid compression
5600 		// kicking in.
5601 		spin->si_blocks_cnt = 0;
5602 
5603 		// Skip over any other NUL bytes (same word with different
5604 		// flags).
5605 		while (byts[n + 1] == 0)
5606 		{
5607 		    ++n;
5608 		    ++curi[depth];
5609 		}
5610 	    }
5611 	    else
5612 	    {
5613 		// Normal char, go one level deeper.
5614 		tword[depth++] = c;
5615 		arridx[depth] = idxs[n];
5616 		curi[depth] = 1;
5617 		wordcount[depth] = 0;
5618 	    }
5619 	}
5620     }
5621 
5622     smsg(_("Total number of words: %d"), words_done);
5623 
5624     return OK;
5625 }
5626 
5627 /*
5628  * Make the table that links each word in the soundfold trie to the words it
5629  * can be produced from.
5630  * This is not unlike lines in a file, thus use a memfile to be able to access
5631  * the table efficiently.
5632  * Returns FAIL when out of memory.
5633  */
5634     static int
5635 sug_maketable(spellinfo_T *spin)
5636 {
5637     garray_T	ga;
5638     int		res = OK;
5639 
5640     // Allocate a buffer, open a memline for it and create the swap file
5641     // (uses a temp file, not a .swp file).
5642     spin->si_spellbuf = open_spellbuf();
5643     if (spin->si_spellbuf == NULL)
5644 	return FAIL;
5645 
5646     // Use a buffer to store the line info, avoids allocating many small
5647     // pieces of memory.
5648     ga_init2(&ga, 1, 100);
5649 
5650     // recursively go through the tree
5651     if (sug_filltable(spin, spin->si_foldroot->wn_sibling, 0, &ga) == -1)
5652 	res = FAIL;
5653 
5654     ga_clear(&ga);
5655     return res;
5656 }
5657 
5658 /*
5659  * Fill the table for one node and its children.
5660  * Returns the wordnr at the start of the node.
5661  * Returns -1 when out of memory.
5662  */
5663     static int
5664 sug_filltable(
5665     spellinfo_T	*spin,
5666     wordnode_T	*node,
5667     int		startwordnr,
5668     garray_T	*gap)	    // place to store line of numbers
5669 {
5670     wordnode_T	*p, *np;
5671     int		wordnr = startwordnr;
5672     int		nr;
5673     int		prev_nr;
5674 
5675     FOR_ALL_NODE_SIBLINGS(node, p)
5676     {
5677 	if (p->wn_byte == NUL)
5678 	{
5679 	    gap->ga_len = 0;
5680 	    prev_nr = 0;
5681 	    for (np = p; np != NULL && np->wn_byte == NUL; np = np->wn_sibling)
5682 	    {
5683 		if (ga_grow(gap, 10) == FAIL)
5684 		    return -1;
5685 
5686 		nr = (np->wn_flags << 16) + (np->wn_region & 0xffff);
5687 		// Compute the offset from the previous nr and store the
5688 		// offset in a way that it takes a minimum number of bytes.
5689 		// It's a bit like utf-8, but without the need to mark
5690 		// following bytes.
5691 		nr -= prev_nr;
5692 		prev_nr += nr;
5693 		gap->ga_len += offset2bytes(nr,
5694 					 (char_u *)gap->ga_data + gap->ga_len);
5695 	    }
5696 
5697 	    // add the NUL byte
5698 	    ((char_u *)gap->ga_data)[gap->ga_len++] = NUL;
5699 
5700 	    if (ml_append_buf(spin->si_spellbuf, (linenr_T)wordnr,
5701 				     gap->ga_data, gap->ga_len, TRUE) == FAIL)
5702 		return -1;
5703 	    ++wordnr;
5704 
5705 	    // Remove extra NUL entries, we no longer need them. We don't
5706 	    // bother freeing the nodes, the won't be reused anyway.
5707 	    while (p->wn_sibling != NULL && p->wn_sibling->wn_byte == NUL)
5708 		p->wn_sibling = p->wn_sibling->wn_sibling;
5709 
5710 	    // Clear the flags on the remaining NUL node, so that compression
5711 	    // works a lot better.
5712 	    p->wn_flags = 0;
5713 	    p->wn_region = 0;
5714 	}
5715 	else
5716 	{
5717 	    wordnr = sug_filltable(spin, p->wn_child, wordnr, gap);
5718 	    if (wordnr == -1)
5719 		return -1;
5720 	}
5721     }
5722     return wordnr;
5723 }
5724 
5725 /*
5726  * Convert an offset into a minimal number of bytes.
5727  * Similar to utf_char2byters, but use 8 bits in followup bytes and avoid NUL
5728  * bytes.
5729  */
5730     static int
5731 offset2bytes(int nr, char_u *buf)
5732 {
5733     int	    rem;
5734     int	    b1, b2, b3, b4;
5735 
5736     // Split the number in parts of base 255.  We need to avoid NUL bytes.
5737     b1 = nr % 255 + 1;
5738     rem = nr / 255;
5739     b2 = rem % 255 + 1;
5740     rem = rem / 255;
5741     b3 = rem % 255 + 1;
5742     b4 = rem / 255 + 1;
5743 
5744     if (b4 > 1 || b3 > 0x1f)	// 4 bytes
5745     {
5746 	buf[0] = 0xe0 + b4;
5747 	buf[1] = b3;
5748 	buf[2] = b2;
5749 	buf[3] = b1;
5750 	return 4;
5751     }
5752     if (b3 > 1 || b2 > 0x3f )	// 3 bytes
5753     {
5754 	buf[0] = 0xc0 + b3;
5755 	buf[1] = b2;
5756 	buf[2] = b1;
5757 	return 3;
5758     }
5759     if (b2 > 1 || b1 > 0x7f )	// 2 bytes
5760     {
5761 	buf[0] = 0x80 + b2;
5762 	buf[1] = b1;
5763 	return 2;
5764     }
5765 				// 1 byte
5766     buf[0] = b1;
5767     return 1;
5768 }
5769 
5770 /*
5771  * Write the .sug file in "fname".
5772  */
5773     static void
5774 sug_write(spellinfo_T *spin, char_u *fname)
5775 {
5776     FILE	*fd;
5777     wordnode_T	*tree;
5778     int		nodecount;
5779     int		wcount;
5780     char_u	*line;
5781     linenr_T	lnum;
5782     int		len;
5783 
5784     // Create the file.  Note that an existing file is silently overwritten!
5785     fd = mch_fopen((char *)fname, "w");
5786     if (fd == NULL)
5787     {
5788 	semsg(_(e_notopen), fname);
5789 	return;
5790     }
5791 
5792     vim_snprintf((char *)IObuff, IOSIZE,
5793 				  _("Writing suggestion file %s..."), fname);
5794     spell_message(spin, IObuff);
5795 
5796     /*
5797      * <SUGHEADER>: <fileID> <versionnr> <timestamp>
5798      */
5799     if (fwrite(VIMSUGMAGIC, VIMSUGMAGICL, (size_t)1, fd) != 1) // <fileID>
5800     {
5801 	emsg(_(e_write));
5802 	goto theend;
5803     }
5804     putc(VIMSUGVERSION, fd);				// <versionnr>
5805 
5806     // Write si_sugtime to the file.
5807     put_time(fd, spin->si_sugtime);			// <timestamp>
5808 
5809     /*
5810      * <SUGWORDTREE>
5811      */
5812     spin->si_memtot = 0;
5813     tree = spin->si_foldroot->wn_sibling;
5814 
5815     // Clear the index and wnode fields in the tree.
5816     clear_node(tree);
5817 
5818     // Count the number of nodes.  Needed to be able to allocate the
5819     // memory when reading the nodes.  Also fills in index for shared
5820     // nodes.
5821     nodecount = put_node(NULL, tree, 0, 0, FALSE);
5822 
5823     // number of nodes in 4 bytes
5824     put_bytes(fd, (long_u)nodecount, 4);	// <nodecount>
5825     spin->si_memtot += nodecount + nodecount * sizeof(int);
5826 
5827     // Write the nodes.
5828     (void)put_node(fd, tree, 0, 0, FALSE);
5829 
5830     /*
5831      * <SUGTABLE>: <sugwcount> <sugline> ...
5832      */
5833     wcount = spin->si_spellbuf->b_ml.ml_line_count;
5834     put_bytes(fd, (long_u)wcount, 4);	// <sugwcount>
5835 
5836     for (lnum = 1; lnum <= (linenr_T)wcount; ++lnum)
5837     {
5838 	// <sugline>: <sugnr> ... NUL
5839 	line = ml_get_buf(spin->si_spellbuf, lnum, FALSE);
5840 	len = (int)STRLEN(line) + 1;
5841 	if (fwrite(line, (size_t)len, (size_t)1, fd) == 0)
5842 	{
5843 	    emsg(_(e_write));
5844 	    goto theend;
5845 	}
5846 	spin->si_memtot += len;
5847     }
5848 
5849     // Write another byte to check for errors.
5850     if (putc(0, fd) == EOF)
5851 	emsg(_(e_write));
5852 
5853     vim_snprintf((char *)IObuff, IOSIZE,
5854 		 _("Estimated runtime memory use: %d bytes"), spin->si_memtot);
5855     spell_message(spin, IObuff);
5856 
5857 theend:
5858     // close the file
5859     fclose(fd);
5860 }
5861 
5862 
5863 /*
5864  * Create a Vim spell file from one or more word lists.
5865  * "fnames[0]" is the output file name.
5866  * "fnames[fcount - 1]" is the last input file name.
5867  * Exception: when "fnames[0]" ends in ".add" it's used as the input file name
5868  * and ".spl" is appended to make the output file name.
5869  */
5870     void
5871 mkspell(
5872     int		fcount,
5873     char_u	**fnames,
5874     int		ascii,		    // -ascii argument given
5875     int		over_write,	    // overwrite existing output file
5876     int		added_word)	    // invoked through "zg"
5877 {
5878     char_u	*fname = NULL;
5879     char_u	*wfname;
5880     char_u	**innames;
5881     int		incount;
5882     afffile_T	*(afile[MAXREGIONS]);
5883     int		i;
5884     int		len;
5885     stat_T	st;
5886     int		error = FALSE;
5887     spellinfo_T spin;
5888 
5889     CLEAR_FIELD(spin);
5890     spin.si_verbose = !added_word;
5891     spin.si_ascii = ascii;
5892     spin.si_followup = TRUE;
5893     spin.si_rem_accents = TRUE;
5894     ga_init2(&spin.si_rep, (int)sizeof(fromto_T), 20);
5895     ga_init2(&spin.si_repsal, (int)sizeof(fromto_T), 20);
5896     ga_init2(&spin.si_sal, (int)sizeof(fromto_T), 20);
5897     ga_init2(&spin.si_map, (int)sizeof(char_u), 100);
5898     ga_init2(&spin.si_comppat, (int)sizeof(char_u *), 20);
5899     ga_init2(&spin.si_prefcond, (int)sizeof(char_u *), 50);
5900     hash_init(&spin.si_commonwords);
5901     spin.si_newcompID = 127;	// start compound ID at first maximum
5902 
5903     // default: fnames[0] is output file, following are input files
5904     innames = &fnames[1];
5905     incount = fcount - 1;
5906 
5907     wfname = alloc(MAXPATHL);
5908     if (wfname == NULL)
5909 	return;
5910 
5911     if (fcount >= 1)
5912     {
5913 	len = (int)STRLEN(fnames[0]);
5914 	if (fcount == 1 && len > 4 && STRCMP(fnames[0] + len - 4, ".add") == 0)
5915 	{
5916 	    // For ":mkspell path/en.latin1.add" output file is
5917 	    // "path/en.latin1.add.spl".
5918 	    innames = &fnames[0];
5919 	    incount = 1;
5920 	    vim_snprintf((char *)wfname, MAXPATHL, "%s.spl", fnames[0]);
5921 	}
5922 	else if (fcount == 1)
5923 	{
5924 	    // For ":mkspell path/vim" output file is "path/vim.latin1.spl".
5925 	    innames = &fnames[0];
5926 	    incount = 1;
5927 	    vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL,
5928 		  fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc());
5929 	}
5930 	else if (len > 4 && STRCMP(fnames[0] + len - 4, ".spl") == 0)
5931 	{
5932 	    // Name ends in ".spl", use as the file name.
5933 	    vim_strncpy(wfname, fnames[0], MAXPATHL - 1);
5934 	}
5935 	else
5936 	    // Name should be language, make the file name from it.
5937 	    vim_snprintf((char *)wfname, MAXPATHL, SPL_FNAME_TMPL,
5938 		  fnames[0], spin.si_ascii ? (char_u *)"ascii" : spell_enc());
5939 
5940 	// Check for .ascii.spl.
5941 	if (strstr((char *)gettail(wfname), SPL_FNAME_ASCII) != NULL)
5942 	    spin.si_ascii = TRUE;
5943 
5944 	// Check for .add.spl.
5945 	if (strstr((char *)gettail(wfname), SPL_FNAME_ADD) != NULL)
5946 	    spin.si_add = TRUE;
5947     }
5948 
5949     if (incount <= 0)
5950 	emsg(_(e_invarg));	// need at least output and input names
5951     else if (vim_strchr(gettail(wfname), '_') != NULL)
5952 	emsg(_("E751: Output file name must not have region name"));
5953     else if (incount > MAXREGIONS)
5954 	semsg(_("E754: Only up to %d regions supported"), MAXREGIONS);
5955     else
5956     {
5957 	// Check for overwriting before doing things that may take a lot of
5958 	// time.
5959 	if (!over_write && mch_stat((char *)wfname, &st) >= 0)
5960 	{
5961 	    emsg(_(e_exists));
5962 	    goto theend;
5963 	}
5964 	if (mch_isdir(wfname))
5965 	{
5966 	    semsg(_(e_isadir2), wfname);
5967 	    goto theend;
5968 	}
5969 
5970 	fname = alloc(MAXPATHL);
5971 	if (fname == NULL)
5972 	    goto theend;
5973 
5974 	/*
5975 	 * Init the aff and dic pointers.
5976 	 * Get the region names if there are more than 2 arguments.
5977 	 */
5978 	for (i = 0; i < incount; ++i)
5979 	{
5980 	    afile[i] = NULL;
5981 
5982 	    if (incount > 1)
5983 	    {
5984 		len = (int)STRLEN(innames[i]);
5985 		if (STRLEN(gettail(innames[i])) < 5
5986 						|| innames[i][len - 3] != '_')
5987 		{
5988 		    semsg(_("E755: Invalid region in %s"), innames[i]);
5989 		    goto theend;
5990 		}
5991 		spin.si_region_name[i * 2] = TOLOWER_ASC(innames[i][len - 2]);
5992 		spin.si_region_name[i * 2 + 1] =
5993 					     TOLOWER_ASC(innames[i][len - 1]);
5994 	    }
5995 	}
5996 	spin.si_region_count = incount;
5997 
5998 	spin.si_foldroot = wordtree_alloc(&spin);
5999 	spin.si_keeproot = wordtree_alloc(&spin);
6000 	spin.si_prefroot = wordtree_alloc(&spin);
6001 	if (spin.si_foldroot == NULL
6002 		|| spin.si_keeproot == NULL
6003 		|| spin.si_prefroot == NULL)
6004 	{
6005 	    free_blocks(spin.si_blocks);
6006 	    goto theend;
6007 	}
6008 
6009 	// When not producing a .add.spl file clear the character table when
6010 	// we encounter one in the .aff file.  This means we dump the current
6011 	// one in the .spl file if the .aff file doesn't define one.  That's
6012 	// better than guessing the contents, the table will match a
6013 	// previously loaded spell file.
6014 	if (!spin.si_add)
6015 	    spin.si_clear_chartab = TRUE;
6016 
6017 	/*
6018 	 * Read all the .aff and .dic files.
6019 	 * Text is converted to 'encoding'.
6020 	 * Words are stored in the case-folded and keep-case trees.
6021 	 */
6022 	for (i = 0; i < incount && !error; ++i)
6023 	{
6024 	    spin.si_conv.vc_type = CONV_NONE;
6025 	    spin.si_region = 1 << i;
6026 
6027 	    vim_snprintf((char *)fname, MAXPATHL, "%s.aff", innames[i]);
6028 	    if (mch_stat((char *)fname, &st) >= 0)
6029 	    {
6030 		// Read the .aff file.  Will init "spin->si_conv" based on the
6031 		// "SET" line.
6032 		afile[i] = spell_read_aff(&spin, fname);
6033 		if (afile[i] == NULL)
6034 		    error = TRUE;
6035 		else
6036 		{
6037 		    // Read the .dic file and store the words in the trees.
6038 		    vim_snprintf((char *)fname, MAXPATHL, "%s.dic",
6039 								  innames[i]);
6040 		    if (spell_read_dic(&spin, fname, afile[i]) == FAIL)
6041 			error = TRUE;
6042 		}
6043 	    }
6044 	    else
6045 	    {
6046 		// No .aff file, try reading the file as a word list.  Store
6047 		// the words in the trees.
6048 		if (spell_read_wordfile(&spin, innames[i]) == FAIL)
6049 		    error = TRUE;
6050 	    }
6051 
6052 	    // Free any conversion stuff.
6053 	    convert_setup(&spin.si_conv, NULL, NULL);
6054 	}
6055 
6056 	if (spin.si_compflags != NULL && spin.si_nobreak)
6057 	    msg(_("Warning: both compounding and NOBREAK specified"));
6058 
6059 	if (!error && !got_int)
6060 	{
6061 	    /*
6062 	     * Combine tails in the tree.
6063 	     */
6064 	    spell_message(&spin, (char_u *)_(msg_compressing));
6065 	    wordtree_compress(&spin, spin.si_foldroot);
6066 	    wordtree_compress(&spin, spin.si_keeproot);
6067 	    wordtree_compress(&spin, spin.si_prefroot);
6068 	}
6069 
6070 	if (!error && !got_int)
6071 	{
6072 	    /*
6073 	     * Write the info in the spell file.
6074 	     */
6075 	    vim_snprintf((char *)IObuff, IOSIZE,
6076 				      _("Writing spell file %s..."), wfname);
6077 	    spell_message(&spin, IObuff);
6078 
6079 	    error = write_vim_spell(&spin, wfname) == FAIL;
6080 
6081 	    spell_message(&spin, (char_u *)_("Done!"));
6082 	    vim_snprintf((char *)IObuff, IOSIZE,
6083 		 _("Estimated runtime memory use: %d bytes"), spin.si_memtot);
6084 	    spell_message(&spin, IObuff);
6085 
6086 	    /*
6087 	     * If the file is loaded need to reload it.
6088 	     */
6089 	    if (!error)
6090 		spell_reload_one(wfname, added_word);
6091 	}
6092 
6093 	// Free the allocated memory.
6094 	ga_clear(&spin.si_rep);
6095 	ga_clear(&spin.si_repsal);
6096 	ga_clear(&spin.si_sal);
6097 	ga_clear(&spin.si_map);
6098 	ga_clear(&spin.si_comppat);
6099 	ga_clear(&spin.si_prefcond);
6100 	hash_clear_all(&spin.si_commonwords, 0);
6101 
6102 	// Free the .aff file structures.
6103 	for (i = 0; i < incount; ++i)
6104 	    if (afile[i] != NULL)
6105 		spell_free_aff(afile[i]);
6106 
6107 	// Free all the bits and pieces at once.
6108 	free_blocks(spin.si_blocks);
6109 
6110 	/*
6111 	 * If there is soundfolding info and no NOSUGFILE item create the
6112 	 * .sug file with the soundfolded word trie.
6113 	 */
6114 	if (spin.si_sugtime != 0 && !error && !got_int)
6115 	    spell_make_sugfile(&spin, wfname);
6116 
6117     }
6118 
6119 theend:
6120     vim_free(fname);
6121     vim_free(wfname);
6122 }
6123 
6124 /*
6125  * Display a message for spell file processing when 'verbose' is set or using
6126  * ":mkspell".  "str" can be IObuff.
6127  */
6128     static void
6129 spell_message(spellinfo_T *spin, char_u *str)
6130 {
6131     if (spin->si_verbose || p_verbose > 2)
6132     {
6133 	if (!spin->si_verbose)
6134 	    verbose_enter();
6135 	msg((char *)str);
6136 	out_flush();
6137 	if (!spin->si_verbose)
6138 	    verbose_leave();
6139     }
6140 }
6141 
6142 /*
6143  * ":[count]spellgood  {word}"
6144  * ":[count]spellwrong {word}"
6145  * ":[count]spellundo  {word}"
6146  * ":[count]spellrare  {word}"
6147  */
6148     void
6149 ex_spell(exarg_T *eap)
6150 {
6151     spell_add_word(eap->arg, (int)STRLEN(eap->arg),
6152 		eap->cmdidx == CMD_spellwrong ? SPELL_ADD_BAD :
6153 		eap->cmdidx == CMD_spellrare ? SPELL_ADD_RARE : SPELL_ADD_GOOD,
6154 				   eap->forceit ? 0 : (int)eap->line2,
6155 				   eap->cmdidx == CMD_spellundo);
6156 }
6157 
6158 /*
6159  * Add "word[len]" to 'spellfile' as a good, rare or bad word.
6160  */
6161     void
6162 spell_add_word(
6163     char_u	*word,
6164     int		len,
6165     int		what,	    // SPELL_ADD_ values
6166     int		idx,	    // "zG" and "zW": zero, otherwise index in
6167 			    // 'spellfile'
6168     int		undo)	    // TRUE for "zug", "zuG", "zuw" and "zuW"
6169 {
6170     FILE	*fd = NULL;
6171     buf_T	*buf = NULL;
6172     int		new_spf = FALSE;
6173     char_u	*fname;
6174     char_u	*fnamebuf = NULL;
6175     char_u	line[MAXWLEN * 2];
6176     long	fpos, fpos_next = 0;
6177     int		i;
6178     char_u	*spf;
6179 
6180     if (idx == 0)	    // use internal wordlist
6181     {
6182 	if (int_wordlist == NULL)
6183 	{
6184 	    int_wordlist = vim_tempname('s', FALSE);
6185 	    if (int_wordlist == NULL)
6186 		return;
6187 	}
6188 	fname = int_wordlist;
6189     }
6190     else
6191     {
6192 	// If 'spellfile' isn't set figure out a good default value.
6193 	if (*curwin->w_s->b_p_spf == NUL)
6194 	{
6195 	    init_spellfile();
6196 	    new_spf = TRUE;
6197 	}
6198 
6199 	if (*curwin->w_s->b_p_spf == NUL)
6200 	{
6201 	    semsg(_(e_notset), "spellfile");
6202 	    return;
6203 	}
6204 	fnamebuf = alloc(MAXPATHL);
6205 	if (fnamebuf == NULL)
6206 	    return;
6207 
6208 	for (spf = curwin->w_s->b_p_spf, i = 1; *spf != NUL; ++i)
6209 	{
6210 	    copy_option_part(&spf, fnamebuf, MAXPATHL, ",");
6211 	    if (i == idx)
6212 		break;
6213 	    if (*spf == NUL)
6214 	    {
6215 		semsg(_("E765: 'spellfile' does not have %d entries"), idx);
6216 		vim_free(fnamebuf);
6217 		return;
6218 	    }
6219 	}
6220 
6221 	// Check that the user isn't editing the .add file somewhere.
6222 	buf = buflist_findname_exp(fnamebuf);
6223 	if (buf != NULL && buf->b_ml.ml_mfp == NULL)
6224 	    buf = NULL;
6225 	if (buf != NULL && bufIsChanged(buf))
6226 	{
6227 	    emsg(_(e_bufloaded));
6228 	    vim_free(fnamebuf);
6229 	    return;
6230 	}
6231 
6232 	fname = fnamebuf;
6233     }
6234 
6235     if (what == SPELL_ADD_BAD || undo)
6236     {
6237 	// When the word appears as good word we need to remove that one,
6238 	// since its flags sort before the one with WF_BANNED.
6239 	fd = mch_fopen((char *)fname, "r");
6240 	if (fd != NULL)
6241 	{
6242 	    while (!vim_fgets(line, MAXWLEN * 2, fd))
6243 	    {
6244 		fpos = fpos_next;
6245 		fpos_next = ftell(fd);
6246 		if (STRNCMP(word, line, len) == 0
6247 			&& (line[len] == '/' || line[len] < ' '))
6248 		{
6249 		    // Found duplicate word.  Remove it by writing a '#' at
6250 		    // the start of the line.  Mixing reading and writing
6251 		    // doesn't work for all systems, close the file first.
6252 		    fclose(fd);
6253 		    fd = mch_fopen((char *)fname, "r+");
6254 		    if (fd == NULL)
6255 			break;
6256 		    if (fseek(fd, fpos, SEEK_SET) == 0)
6257 		    {
6258 			fputc('#', fd);
6259 			if (undo)
6260 			{
6261 			    home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
6262 			    smsg(_("Word '%.*s' removed from %s"),
6263 							 len, word, NameBuff);
6264 			}
6265 		    }
6266 		    fseek(fd, fpos_next, SEEK_SET);
6267 		}
6268 	    }
6269 	    if (fd != NULL)
6270 		fclose(fd);
6271 	}
6272     }
6273 
6274     if (!undo)
6275     {
6276 	fd = mch_fopen((char *)fname, "a");
6277 	if (fd == NULL && new_spf)
6278 	{
6279 	    char_u *p;
6280 
6281 	    // We just initialized the 'spellfile' option and can't open the
6282 	    // file.  We may need to create the "spell" directory first.  We
6283 	    // already checked the runtime directory is writable in
6284 	    // init_spellfile().
6285 	    if (!dir_of_file_exists(fname) && (p = gettail_sep(fname)) != fname)
6286 	    {
6287 		int c = *p;
6288 
6289 		// The directory doesn't exist.  Try creating it and opening
6290 		// the file again.
6291 		*p = NUL;
6292 		vim_mkdir(fname, 0755);
6293 		*p = c;
6294 		fd = mch_fopen((char *)fname, "a");
6295 	    }
6296 	}
6297 
6298 	if (fd == NULL)
6299 	    semsg(_(e_notopen), fname);
6300 	else
6301 	{
6302 	    if (what == SPELL_ADD_BAD)
6303 		fprintf(fd, "%.*s/!\n", len, word);
6304 	    else if (what == SPELL_ADD_RARE)
6305 		fprintf(fd, "%.*s/?\n", len, word);
6306 	    else
6307 		fprintf(fd, "%.*s\n", len, word);
6308 	    fclose(fd);
6309 
6310 	    home_replace(NULL, fname, NameBuff, MAXPATHL, TRUE);
6311 	    smsg(_("Word '%.*s' added to %s"), len, word, NameBuff);
6312 	}
6313     }
6314 
6315     if (fd != NULL)
6316     {
6317 	// Update the .add.spl file.
6318 	mkspell(1, &fname, FALSE, TRUE, TRUE);
6319 
6320 	// If the .add file is edited somewhere, reload it.
6321 	if (buf != NULL)
6322 	    buf_reload(buf, buf->b_orig_mode);
6323 
6324 	redraw_all_later(SOME_VALID);
6325     }
6326     vim_free(fnamebuf);
6327 }
6328 
6329 /*
6330  * Initialize 'spellfile' for the current buffer.
6331  */
6332     static void
6333 init_spellfile(void)
6334 {
6335     char_u	*buf;
6336     int		l;
6337     char_u	*fname;
6338     char_u	*rtp;
6339     char_u	*lend;
6340     int		aspath = FALSE;
6341     char_u	*lstart = curbuf->b_s.b_p_spl;
6342 
6343     if (*curwin->w_s->b_p_spl != NUL && curwin->w_s->b_langp.ga_len > 0)
6344     {
6345 	buf = alloc(MAXPATHL);
6346 	if (buf == NULL)
6347 	    return;
6348 
6349 	// Find the end of the language name.  Exclude the region.  If there
6350 	// is a path separator remember the start of the tail.
6351 	for (lend = curwin->w_s->b_p_spl; *lend != NUL
6352 			&& vim_strchr((char_u *)",._", *lend) == NULL; ++lend)
6353 	    if (vim_ispathsep(*lend))
6354 	    {
6355 		aspath = TRUE;
6356 		lstart = lend + 1;
6357 	    }
6358 
6359 	// Loop over all entries in 'runtimepath'.  Use the first one where we
6360 	// are allowed to write.
6361 	rtp = p_rtp;
6362 	while (*rtp != NUL)
6363 	{
6364 	    if (aspath)
6365 		// Use directory of an entry with path, e.g., for
6366 		// "/dir/lg.utf-8.spl" use "/dir".
6367 		vim_strncpy(buf, curbuf->b_s.b_p_spl,
6368 					    lstart - curbuf->b_s.b_p_spl - 1);
6369 	    else
6370 		// Copy the path from 'runtimepath' to buf[].
6371 		copy_option_part(&rtp, buf, MAXPATHL, ",");
6372 	    if (filewritable(buf) == 2)
6373 	    {
6374 		// Use the first language name from 'spelllang' and the
6375 		// encoding used in the first loaded .spl file.
6376 		if (aspath)
6377 		    vim_strncpy(buf, curbuf->b_s.b_p_spl,
6378 						  lend - curbuf->b_s.b_p_spl);
6379 		else
6380 		{
6381 		    // Create the "spell" directory if it doesn't exist yet.
6382 		    l = (int)STRLEN(buf);
6383 		    vim_snprintf((char *)buf + l, MAXPATHL - l, "/spell");
6384 		    if (filewritable(buf) != 2)
6385 			vim_mkdir(buf, 0755);
6386 
6387 		    l = (int)STRLEN(buf);
6388 		    vim_snprintf((char *)buf + l, MAXPATHL - l,
6389 				 "/%.*s", (int)(lend - lstart), lstart);
6390 		}
6391 		l = (int)STRLEN(buf);
6392 		fname = LANGP_ENTRY(curwin->w_s->b_langp, 0)
6393 							 ->lp_slang->sl_fname;
6394 		vim_snprintf((char *)buf + l, MAXPATHL - l, ".%s.add",
6395 			fname != NULL
6396 			  && strstr((char *)gettail(fname), ".ascii.") != NULL
6397 				       ? (char_u *)"ascii" : spell_enc());
6398 		set_option_value((char_u *)"spellfile", 0L, buf, OPT_LOCAL);
6399 		break;
6400 	    }
6401 	    aspath = FALSE;
6402 	}
6403 
6404 	vim_free(buf);
6405     }
6406 }
6407 
6408 
6409 
6410 /*
6411  * Set the spell character tables from strings in the affix file.
6412  */
6413     static int
6414 set_spell_chartab(char_u *fol, char_u *low, char_u *upp)
6415 {
6416     // We build the new tables here first, so that we can compare with the
6417     // previous one.
6418     spelltab_T	new_st;
6419     char_u	*pf = fol, *pl = low, *pu = upp;
6420     int		f, l, u;
6421 
6422     clear_spell_chartab(&new_st);
6423 
6424     while (*pf != NUL)
6425     {
6426 	if (*pl == NUL || *pu == NUL)
6427 	{
6428 	    emsg(_(e_affform));
6429 	    return FAIL;
6430 	}
6431 	f = mb_ptr2char_adv(&pf);
6432 	l = mb_ptr2char_adv(&pl);
6433 	u = mb_ptr2char_adv(&pu);
6434 
6435 	// Every character that appears is a word character.
6436 	if (f < 256)
6437 	    new_st.st_isw[f] = TRUE;
6438 	if (l < 256)
6439 	    new_st.st_isw[l] = TRUE;
6440 	if (u < 256)
6441 	    new_st.st_isw[u] = TRUE;
6442 
6443 	// if "LOW" and "FOL" are not the same the "LOW" char needs
6444 	// case-folding
6445 	if (l < 256 && l != f)
6446 	{
6447 	    if (f >= 256)
6448 	    {
6449 		emsg(_(e_affrange));
6450 		return FAIL;
6451 	    }
6452 	    new_st.st_fold[l] = f;
6453 	}
6454 
6455 	// if "UPP" and "FOL" are not the same the "UPP" char needs
6456 	// case-folding, it's upper case and the "UPP" is the upper case of
6457 	// "FOL" .
6458 	if (u < 256 && u != f)
6459 	{
6460 	    if (f >= 256)
6461 	    {
6462 		emsg(_(e_affrange));
6463 		return FAIL;
6464 	    }
6465 	    new_st.st_fold[u] = f;
6466 	    new_st.st_isu[u] = TRUE;
6467 	    new_st.st_upper[f] = u;
6468 	}
6469     }
6470 
6471     if (*pl != NUL || *pu != NUL)
6472     {
6473 	emsg(_(e_affform));
6474 	return FAIL;
6475     }
6476 
6477     return set_spell_finish(&new_st);
6478 }
6479 
6480 /*
6481  * Set the spell character tables from strings in the .spl file.
6482  */
6483     static void
6484 set_spell_charflags(
6485     char_u	*flags,
6486     int		cnt,	    // length of "flags"
6487     char_u	*fol)
6488 {
6489     // We build the new tables here first, so that we can compare with the
6490     // previous one.
6491     spelltab_T	new_st;
6492     int		i;
6493     char_u	*p = fol;
6494     int		c;
6495 
6496     clear_spell_chartab(&new_st);
6497 
6498     for (i = 0; i < 128; ++i)
6499     {
6500 	if (i < cnt)
6501 	{
6502 	    new_st.st_isw[i + 128] = (flags[i] & CF_WORD) != 0;
6503 	    new_st.st_isu[i + 128] = (flags[i] & CF_UPPER) != 0;
6504 	}
6505 
6506 	if (*p != NUL)
6507 	{
6508 	    c = mb_ptr2char_adv(&p);
6509 	    new_st.st_fold[i + 128] = c;
6510 	    if (i + 128 != c && new_st.st_isu[i + 128] && c < 256)
6511 		new_st.st_upper[c] = i + 128;
6512 	}
6513     }
6514 
6515     (void)set_spell_finish(&new_st);
6516 }
6517 
6518     static int
6519 set_spell_finish(spelltab_T *new_st)
6520 {
6521     int		i;
6522 
6523     if (did_set_spelltab)
6524     {
6525 	// check that it's the same table
6526 	for (i = 0; i < 256; ++i)
6527 	{
6528 	    if (spelltab.st_isw[i] != new_st->st_isw[i]
6529 		    || spelltab.st_isu[i] != new_st->st_isu[i]
6530 		    || spelltab.st_fold[i] != new_st->st_fold[i]
6531 		    || spelltab.st_upper[i] != new_st->st_upper[i])
6532 	    {
6533 		emsg(_("E763: Word characters differ between spell files"));
6534 		return FAIL;
6535 	    }
6536 	}
6537     }
6538     else
6539     {
6540 	// copy the new spelltab into the one being used
6541 	spelltab = *new_st;
6542 	did_set_spelltab = TRUE;
6543     }
6544 
6545     return OK;
6546 }
6547 
6548 /*
6549  * Write the table with prefix conditions to the .spl file.
6550  * When "fd" is NULL only count the length of what is written.
6551  */
6552     static int
6553 write_spell_prefcond(FILE *fd, garray_T *gap)
6554 {
6555     int		i;
6556     char_u	*p;
6557     int		len;
6558     int		totlen;
6559     size_t	x = 1;  // collect return value of fwrite()
6560 
6561     if (fd != NULL)
6562 	put_bytes(fd, (long_u)gap->ga_len, 2);	    // <prefcondcnt>
6563 
6564     totlen = 2 + gap->ga_len; // length of <prefcondcnt> and <condlen> bytes
6565 
6566     for (i = 0; i < gap->ga_len; ++i)
6567     {
6568 	// <prefcond> : <condlen> <condstr>
6569 	p = ((char_u **)gap->ga_data)[i];
6570 	if (p != NULL)
6571 	{
6572 	    len = (int)STRLEN(p);
6573 	    if (fd != NULL)
6574 	    {
6575 		fputc(len, fd);
6576 		x &= fwrite(p, (size_t)len, (size_t)1, fd);
6577 	    }
6578 	    totlen += len;
6579 	}
6580 	else if (fd != NULL)
6581 	    fputc(0, fd);
6582     }
6583 
6584     return totlen;
6585 }
6586 
6587 
6588 /*
6589  * Use map string "map" for languages "lp".
6590  */
6591     static void
6592 set_map_str(slang_T *lp, char_u *map)
6593 {
6594     char_u	*p;
6595     int		headc = 0;
6596     int		c;
6597     int		i;
6598 
6599     if (*map == NUL)
6600     {
6601 	lp->sl_has_map = FALSE;
6602 	return;
6603     }
6604     lp->sl_has_map = TRUE;
6605 
6606     // Init the array and hash tables empty.
6607     for (i = 0; i < 256; ++i)
6608 	lp->sl_map_array[i] = 0;
6609     hash_init(&lp->sl_map_hash);
6610 
6611     /*
6612      * The similar characters are stored separated with slashes:
6613      * "aaa/bbb/ccc/".  Fill sl_map_array[c] with the character before c and
6614      * before the same slash.  For characters above 255 sl_map_hash is used.
6615      */
6616     for (p = map; *p != NUL; )
6617     {
6618 	c = mb_cptr2char_adv(&p);
6619 	if (c == '/')
6620 	    headc = 0;
6621 	else
6622 	{
6623 	    if (headc == 0)
6624 		 headc = c;
6625 
6626 	    // Characters above 255 don't fit in sl_map_array[], put them in
6627 	    // the hash table.  Each entry is the char, a NUL the headchar and
6628 	    // a NUL.
6629 	    if (c >= 256)
6630 	    {
6631 		int	    cl = mb_char2len(c);
6632 		int	    headcl = mb_char2len(headc);
6633 		char_u	    *b;
6634 		hash_T	    hash;
6635 		hashitem_T  *hi;
6636 
6637 		b = alloc(cl + headcl + 2);
6638 		if (b == NULL)
6639 		    return;
6640 		mb_char2bytes(c, b);
6641 		b[cl] = NUL;
6642 		mb_char2bytes(headc, b + cl + 1);
6643 		b[cl + 1 + headcl] = NUL;
6644 		hash = hash_hash(b);
6645 		hi = hash_lookup(&lp->sl_map_hash, b, hash);
6646 		if (HASHITEM_EMPTY(hi))
6647 		    hash_add_item(&lp->sl_map_hash, hi, b, hash);
6648 		else
6649 		{
6650 		    // This should have been checked when generating the .spl
6651 		    // file.
6652 		    emsg(_("E783: duplicate char in MAP entry"));
6653 		    vim_free(b);
6654 		}
6655 	    }
6656 	    else
6657 		lp->sl_map_array[c] = headc;
6658 	}
6659     }
6660 }
6661 
6662 
6663 #endif  // FEAT_SPELL
6664