robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

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