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