robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 285BY_NOFLAGS = 0 ,// end of word without flags or region; for postponed prefix: no <pflags> 286BY_INDEX = 1 ,// child is shared, index follows 287BY_FLAGS = 2 ,// end of word, <flags> byte follows; for postponed prefix: <pflags> follows 288BY_FLAGS2 = 3 ,// end of word, <flags> and <flags2> bytes follow; never used in prefix tree 289BY_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 { 296SAL_F0LLOWUP = 1 , 297SAL_COLLAPSE = 2 , 298SAL_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 { 307SN_REGION = 0 ,// <regionname> section 308SN_CHARFLAGS = 1 ,// charflags section 309SN_MIDWORD = 2 ,// <midword> section 310SN_PREFCOND = 3 ,// <prefcond> section 311SN_REP = 4 ,// REP items section 312SN_SAL = 5 ,// SAL items section 313SN_SOFO = 6 ,// soundfolding section 314SN_MAP = 7 ,// MAP items section 315SN_COMPOUND = 8 ,// compound words section 316SN_SYLLABLE = 9 ,// syllable section 317SN_NOBREAK = 10 ,// NOBREAK section 318SN_SUGFILE = 11 ,// timestamp for .sug file 319SN_REPSAL = 12 ,// REPSAL items section 320SN_WORDS = 13 ,// common words 321SN_NOSPLITSUGS = 14 ,// don't split word for suggestions 322SN_INFO = 15 ,// info section 323SN_NOCOMPOUNDSUGS = 16 ,// don't compound for suggestions 324SN_END = 255 ,// end of sections 325}; 326 327#define SNF_REQUIRED 1 // <sectionflags>: required section 328 329enum { 330CF_WORD = 0x01 , 331CF_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 { 351char * af_enc ;// "SET", normalized, alloc'ed string or NULL 352int af_flagtype ;// AFT_CHAR, AFT_LONG, AFT_NUM or AFT_CAPLONG 353unsigned af_rare ;// RARE ID for rare word 354unsigned af_keepcase ;// KEEPCASE ID for keep-case word 355unsigned af_bad ;// BAD ID for banned word 356unsigned af_needaffix ;// NEEDAFFIX ID 357unsigned af_circumfix ;// CIRCUMFIX ID 358unsigned af_needcomp ;// NEEDCOMPOUND ID 359unsigned af_comproot ;// COMPOUNDROOT ID 360unsigned af_compforbid ;// COMPOUNDFORBIDFLAG ID 361unsigned af_comppermit ;// COMPOUNDPERMITFLAG ID 362unsigned af_nosuggest ;// NOSUGGEST ID 363int af_pfxpostpone ;// postpone prefixes without chop string and 364// without flags 365bool af_ignoreextra ;// IGNOREEXTRA present 366hashtab_T af_pref ;// hashtable for prefixes, affheader_T 367hashtab_T af_suff ;// hashtable for suffixes, affheader_T 368hashtab_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 { 379affentry_T * ae_next ;// next affix with same name/number 380char * ae_chop ;// text to chop off basic word (can be NULL) 381char * ae_add ;// text to add to basic word (can be NULL) 382char * ae_flags ;// flags on the affix (can be NULL) 383char * ae_cond ;// condition (NULL for ".") 384regprog_T * ae_prog ;// regexp program for ae_cond or NULL 385char ae_compforbid ;// COMPOUNDFORBIDFLAG found 386char 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 { 393char ah_key [AH_KEY_LEN ];// key for hashtab == name of affix 394unsigned ah_flag ;// affix name as number, uses "af_flagtype" 395int ah_newID ;// prefix ID after renumbering; 0 if not used 396int ah_combine ;// suffix may combine with prefix 397int ah_follows ;// another affix block should be following 398affentry_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 { 405char ci_key [AH_KEY_LEN ];// key for hashtab == name of compound 406unsigned ci_flag ;// affix name as number, uses "af_flagtype" 407int 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 { 421int sb_used ;// nr of bytes already in use 422sblock_T * sb_next ;// next block in list 423char sb_data [];// data 424}; 425 426// A node in the tree. 427typedef struct wordnode_S wordnode_T ; 428struct wordnode_S { 429union {// shared to save space 430uint8_t hashkey [6 ];// the hash key, only used while compressing 431int index ;// index in written nodes (valid after first 432// round) 433 }wn_u1 ; 434union {// shared to save space 435wordnode_T * next ;// next node with same hash key 436wordnode_T * wnode ;// parent node that will write this node 437 }wn_u2 ; 438wordnode_T * wn_child ;// child (next byte in word) 439wordnode_T * wn_sibling ;// next sibling (alternate byte in word, 440// always sorted) 441int 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. 445uint8_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. 451uint8_t wn_affixID ;// supported/required prefix ID or 0 452uint16_t wn_flags ;// WF_ flags 453int16_t wn_region ;// region mask 454 455#ifdef SPELL_PRINTTREE 456int 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 { 466wordnode_T * si_foldroot ;// tree with case-folded words 467int si_foldwcount ;// nr of words in si_foldroot 468 469wordnode_T * si_keeproot ;// tree with keep-case words 470int si_keepwcount ;// nr of words in si_keeproot 471 472wordnode_T * si_prefroot ;// tree with postponed prefixes 473 474int si_sugtree ;// creating the soundfolding trie 475 476sblock_T * si_blocks ;// memory blocks used 477int si_blocks_cnt ;// memory blocks allocated 478int si_did_emsg ;// true when ran out of memory 479 480int si_compress_cnt ;// words to add before lowering 481// compression limit 482wordnode_T * si_first_free ;// List of nodes that have been freed during 483// compression, linked by "wn_child" field. 484int si_free_count ;// number of nodes in si_first_free 485#ifdef SPELL_PRINTTREE 486int si_wordnode_nr ;// sequence nr for nodes 487#endif 488buf_T * si_spellbuf ;// buffer used to store soundfold word table 489 490int si_ascii ;// handling only ASCII words 491int si_add ;// addition file 492int si_clear_chartab ;// when true clear char tables 493int si_region ;// region mask 494vimconv_T si_conv ;// for conversion to 'encoding' 495int si_memtot ;// runtime memory used 496int si_verbose ;// verbose messages 497int si_msg_count ;// number of words added since last message 498char * si_info ;// info text chars or NULL 499int si_region_count ;// number of regions supported (1 when there 500// are no regions) 501char si_region_name [MAXREGIONS * 2 + 1 ]; 502// region names; used only if 503// si_region_count > 1) 504 505garray_T si_rep ;// list of fromto_T entries from REP lines 506garray_T si_repsal ;// list of fromto_T entries from REPSAL lines 507garray_T si_sal ;// list of fromto_T entries from SAL lines 508char * si_sofofr ;// SOFOFROM text 509char * si_sofoto ;// SOFOTO text 510int si_nosugfile ;// NOSUGFILE item found 511int si_nosplitsugs ;// NOSPLITSUGS item found 512int si_nocompoundsugs ;// NOCOMPOUNDSUGS item found 513int si_followup ;// soundsalike: ? 514int si_collapse ;// soundsalike: ? 515hashtab_T si_commonwords ;// hashtable for common words 516time_t si_sugtime ;// timestamp for .sug file 517int si_rem_accents ;// soundsalike: remove accents 518garray_T si_map ;// MAP info concatenated 519char * si_midword ;// MIDWORD chars or NULL 520int si_compmax ;// max nr of words for compounding 521int si_compminlen ;// minimal length for compounding 522int si_compsylmax ;// max nr of syllables for compounding 523int si_compoptions ;// COMP_ flags 524garray_T si_comppat ;// CHECKCOMPOUNDPATTERN items, each stored as 525// a string 526char * si_compflags ;// flags used for compounding 527char si_nobreak ;// NOBREAK 528char * si_syllable ;// syllable string 529garray_T si_prefcond ;// table with conditions for postponed 530// prefixes, each stored as a string 531int si_newprefID ;// current value for ah_newID 532int 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 ) 585FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_ALWAYS_INLINE 586{ 587char buf [VIMSPELLMAGICL ]; 588SPELL_READ_BYTES (buf ,VIMSPELLMAGICL ,fd ,; ); 589if (memcmp (buf ,VIMSPELLMAGIC ,VIMSPELLMAGICL )!= 0 ) { 590return SP_FORMERROR ; 591 } 592return 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{ 610char * p ; 611slang_T * lp = NULL ; 612int res ; 613bool did_estack_push = false; 614ESTACK_CHECK_DECLARATION ; 615 616FILE * fd = os_fopen (fname ,"r" ); 617if (fd == NULL ) { 618if (!silent ) { 619semsg (_ (e_notopen ),fname ); 620 }else if (p_verbose > 2 ) { 621verbose_enter (); 622smsg (0 ,e_notopen ,fname ); 623verbose_leave (); 624 } 625 gotoendFAIL ; 626 } 627if (p_verbose > 2 ) { 628verbose_enter (); 629smsg (0 ,_ ("Reading spell file \"%s\"" ),fname ); 630verbose_leave (); 631 } 632 633if (old_lp == NULL ) { 634lp = slang_alloc (lang ); 635 636// Remember the file name, used to reload the file when it's updated. 637lp -> sl_fname = xstrdup (fname ); 638 639// Check for .add.spl. 640lp -> sl_add = strstr (path_tail (fname ),SPL_FNAME_ADD )!= NULL ; 641 }else { 642lp = old_lp ; 643 } 644 645// Set sourcing_name, so that error messages mention the file name. 646estack_push (ETYPE_SPELL ,fname ,0 ); 647ESTACK_CHECK_SETUP ; 648did_estack_push = true; 649 650// <HEADER>: <fileID> 651const int scms_ret = spell_check_magic_string (fd ); 652switch (scms_ret ) { 653case SP_FORMERROR : 654case SP_TRUNCERROR : 655semsg ("%s" ,_ ("E757: This does not look like a spell file" )); 656 gotoendFAIL ; 657case SP_OTHERERROR : 658semsg (_ ("E5042: Failed to read spell file %s: %s" ), 659fname ,strerror (ferror (fd ))); 660 gotoendFAIL ; 661case 0 : 662break ; 663 } 664int c = getc (fd );// <versionnr> 665if (c < VIMSPELLVERSION ) { 666emsg (_ ("E771: Old spell file, needs to be updated" )); 667 gotoendFAIL ; 668 }else if (c > VIMSPELLVERSION ) { 669emsg (_ ("E772: Spell file is for newer version of Vim" )); 670 gotoendFAIL ; 671 } 672 673// <SECTIONS>: <section> ... <sectionend> 674// <section>: <sectionID> <sectionflags> <sectionlen> (section contents) 675while (true) { 676int n = getc (fd );// <sectionID> or <sectionend> 677if (n == SN_END ) { 678break ; 679 } 680c = getc (fd );// <sectionflags> 681int len = get4c (fd );// <sectionlen> 682if (len < 0 ) { 683 gototruncerr ; 684 } 685 686res = 0 ; 687switch (n ) { 688case SN_INFO : 689XFREE_CLEAR (lp -> sl_info ); 690lp -> sl_info = read_string (fd , (size_t )len );// <infotext> 691if (lp -> sl_info == NULL ) { 692 gotoendFAIL ; 693 } 694break ; 695 696case SN_REGION : 697res = read_region_section (fd ,lp ,len ); 698break ; 699 700case SN_CHARFLAGS : 701res = read_charflags_section (fd ); 702break ; 703 704case SN_MIDWORD : 705XFREE_CLEAR (lp -> sl_midword ); 706lp -> sl_midword = read_string (fd , (size_t )len );// <midword> 707if (lp -> sl_midword == NULL ) { 708 gotoendFAIL ; 709 } 710break ; 711 712case SN_PREFCOND : 713res = read_prefcond_section (fd ,lp ); 714break ; 715 716case SN_REP : 717res = read_rep_section (fd ,& lp -> sl_rep ,lp -> sl_rep_first ); 718break ; 719 720case SN_REPSAL : 721res = read_rep_section (fd ,& lp -> sl_repsal ,lp -> sl_repsal_first ); 722break ; 723 724case SN_SAL : 725res = read_sal_section (fd ,lp ); 726break ; 727 728case SN_SOFO : 729res = read_sofo_section (fd ,lp ); 730break ; 731 732case SN_MAP : 733p = read_string (fd , (size_t )len );// <mapstr> 734if (p == NULL ) { 735 gotoendFAIL ; 736 } 737set_map_str (lp ,p ); 738xfree (p ); 739break ; 740 741case SN_WORDS : 742res = read_words_section (fd ,lp ,len ); 743break ; 744 745case SN_SUGFILE : 746lp -> sl_sugtime = get8ctime (fd );// <timestamp> 747break ; 748 749case SN_NOSPLITSUGS : 750lp -> sl_nosplitsugs = true; 751break ; 752 753case SN_NOCOMPOUNDSUGS : 754lp -> sl_nocompoundsugs = true; 755break ; 756 757case SN_COMPOUND : 758res = read_compound (fd ,lp ,len ); 759break ; 760 761case SN_NOBREAK : 762lp -> sl_nobreak = true; 763break ; 764 765case SN_SYLLABLE : 766XFREE_CLEAR (lp -> sl_syllable ); 767lp -> sl_syllable = read_string (fd , (size_t )len );// <syllable> 768if (lp -> sl_syllable == NULL ) { 769 gotoendFAIL ; 770 } 771if (init_syl_tab (lp )!= OK ) { 772 gotoendFAIL ; 773 } 774break ; 775 776default : 777// Unsupported section. When it's required give an error 778// message. When it's not required skip the contents. 779if (c & SNF_REQUIRED ) { 780emsg (_ ("E770: Unsupported section in spell file" )); 781 gotoendFAIL ; 782 } 783while (-- len >=0 ) { 784if (getc (fd )< 0 ) { 785 gototruncerr ; 786 } 787 } 788break ; 789 } 790someerror : 791if (res == SP_FORMERROR ) { 792emsg (_ (e_format )); 793 gotoendFAIL ; 794 } 795if (res == SP_TRUNCERROR ) { 796truncerr : 797emsg (_ (e_spell_trunc )); 798 gotoendFAIL ; 799 } 800if (res == SP_OTHERERROR ) { 801 gotoendFAIL ; 802 } 803 } 804 805// <LWORDTREE> 806res = spell_read_tree (fd ,& lp -> sl_fbyts ,& lp -> sl_fbyts_len , 807& lp -> sl_fidxs , false,0 ); 808if (res != 0 ) { 809 gotosomeerror ; 810 } 811 812// <KWORDTREE> 813res = spell_read_tree (fd ,& lp -> sl_kbyts ,NULL ,& lp -> sl_kidxs , false,0 ); 814if (res != 0 ) { 815 gotosomeerror ; 816 } 817 818// <PREFIXTREE> 819res = spell_read_tree (fd ,& lp -> sl_pbyts ,NULL ,& lp -> sl_pidxs , true, 820lp -> sl_prefixcnt ); 821if (res != 0 ) { 822 gotosomeerror ; 823 } 824 825// For a new file link it in the list of spell files. 826if (old_lp == NULL && lang != NULL ) { 827lp -> sl_next = first_lang ; 828first_lang = lp ; 829 } 830 831 gotoendOK ; 832 833endFAIL : 834if (lang != NULL ) { 835// truncating the name signals the error to spell_load_lang() 836* lang = NUL ; 837 } 838if (lp != NULL && old_lp == NULL ) { 839slang_free (lp ); 840 } 841lp = NULL ; 842 843endOK : 844if (fd != NULL ) { 845fclose (fd ); 846 } 847if (did_estack_push ) { 848ESTACK_CHECK_NOW ; 849estack_pop (); 850 } 851 852return 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{ 859idx_T arridx [MAXWLEN ]; 860int curi [MAXWLEN ]; 861int wordcount [MAXWLEN ]; 862 863arridx [0 ]= 0 ; 864curi [0 ]= 1 ; 865wordcount [0 ]= 0 ; 866int depth = 0 ; 867while (depth >=0 && !got_int ) { 868if (curi [depth ]> byts [arridx [depth ]]) { 869// Done all bytes at this node, go up one level. 870idxs [arridx [depth ]]= wordcount [depth ]; 871if (depth > 0 ) { 872wordcount [depth - 1 ]+= wordcount [depth ]; 873 } 874 875depth -- ; 876fast_breakcheck (); 877 }else { 878// Do one more byte at this node. 879idx_T n = arridx [depth ]+ curi [depth ]; 880curi [depth ]++ ; 881 882int c = byts [n ]; 883if (c == 0 ) { 884// End of word, count it. 885wordcount [depth ]++ ; 886 887// Skip over any other NUL bytes (same word with different 888// flags). But don't go over the end. 889while (n + 1 < byts_len && byts [n + 1 ]== 0 ) { 890n ++ ; 891curi [depth ]++ ; 892 } 893 }else if (depth < MAXWLEN - 1 ) { 894// Normal char, go one level deeper to count the words. 895depth ++ ; 896arridx [depth ]= idxs [n ]; 897curi [depth ]= 1 ; 898wordcount [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{ 907char buf [MAXWLEN ]; 908garray_T ga ; 909 910// Do this for all languages that support sound folding. 911for (int lpi = 0 ;lpi < curwin -> w_s -> b_langp .ga_len ;lpi ++ ) { 912langp_T * lp = LANGP_ENTRY (curwin -> w_s -> b_langp ,lpi ); 913slang_T * slang = lp -> lp_slang ; 914if (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. 918slang -> sl_sugloaded = true; 919 920char * dotp = strrchr (slang -> sl_fname ,'.' ); 921if (dotp == NULL || !path_equal (dotp ,".spl" ,kPathCmpLiteral )) { 922continue ; 923 } 924STRCPY (dotp ,".sug" ); 925FILE * fd = os_fopen (slang -> sl_fname ,"r" ); 926if (fd == NULL ) { 927 gotonextone ; 928 } 929 930// <SUGHEADER>: <fileID> <versionnr> <timestamp> 931for (int i = 0 ;i < VIMSUGMAGICL ;i ++ ) { 932buf [i ]= (char )getc (fd );// <fileID> 933 } 934if (strncmp (buf ,VIMSUGMAGIC ,VIMSUGMAGICL )!= 0 ) { 935semsg (_ ("E778: This does not look like a .sug file: %s" ), 936slang -> sl_fname ); 937 gotonextone ; 938 } 939int c = getc (fd );// <versionnr> 940if (c < VIMSUGVERSION ) { 941semsg (_ ("E779: Old .sug file, needs to be updated: %s" ), 942slang -> sl_fname ); 943 gotonextone ; 944 }else if (c > VIMSUGVERSION ) { 945semsg (_ ("E780: .sug file is for newer version of Vim: %s" ), 946slang -> sl_fname ); 947 gotonextone ; 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. 952time_t timestamp = get8ctime (fd );// <timestamp> 953if (timestamp != slang -> sl_sugtime ) { 954semsg (_ ("E781: .sug file doesn't match .spl file: %s" ), 955slang -> sl_fname ); 956 gotonextone ; 957 } 958 959// <SUGWORDTREE>: <wordtree> 960// Read the trie with the soundfolded words. 961if (spell_read_tree (fd ,& slang -> sl_sbyts ,& slang -> sl_sbyts_len , 962& slang -> sl_sidxs , false,0 )!= 0 ) { 963someerror : 964semsg (_ (e_error_while_reading_sug_file_str ), 965slang -> sl_fname ); 966slang_clear_sug (slang ); 967 gotonextone ; 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. 975slang -> sl_sugbuf = open_spellbuf (); 976 977// <sugwcount> 978int wcount = get4c (fd ); 979if (wcount < 0 ) { 980 gotosomeerror ; 981 } 982 983// Read all the wordnr lists into the buffer, one NUL terminated 984// list per line. 985ga_init (& ga ,1 ,100 ); 986for (int wordnr = 0 ;wordnr < wcount ;wordnr ++ ) { 987ga .ga_len = 0 ; 988while (true) { 989c = getc (fd );// <sugline> 990if (c < 0 ) { 991 gotosomeerror ; 992 } 993GA_APPEND (uint8_t ,& ga , (uint8_t )c ); 994if (c == NUL ) { 995break ; 996 } 997 } 998if (ml_append_buf (slang -> sl_sugbuf , (linenr_T )wordnr , 999ga .ga_data ,ga .ga_len , true)== FAIL ) { 1000 gotosomeerror ; 1001 } 1002 } 1003ga_clear (& ga ); 1004 1005// Need to put word counts in the word tries, so that we can find 1006// a word by its number. 1007tree_count_words (slang -> sl_fbyts ,slang -> sl_fbyts_len ,slang -> sl_fidxs ); 1008tree_count_words (slang -> sl_sbyts ,slang -> sl_sbyts_len ,slang -> sl_sidxs ); 1009 1010nextone : 1011if (fd != NULL ) { 1012fclose (fd ); 1013 } 1014STRCPY (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{ 1026int cnt = 0 ; 1027 1028// read the length bytes, MSB first 1029for (int i = 0 ;i < cnt_bytes ;i ++ ) { 1030const int c = getc (fd ); 1031 1032if (c == EOF ) { 1033* cntp = SP_TRUNCERROR ; 1034return NULL ; 1035 } 1036cnt = (int )(((unsigned )cnt <<8 )+ (unsigned )c ); 1037 } 1038* cntp = cnt ; 1039if (cnt == 0 ) { 1040return NULL ;// nothing to read, return NULL 1041 } 1042char * str = read_string (fd , (size_t )cnt ); 1043if (str == NULL ) { 1044* cntp = SP_OTHERERROR ; 1045 } 1046return 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{ 1053if (len > MAXREGIONS * 2 ) { 1054return SP_FORMERROR ; 1055 } 1056SPELL_READ_NONNUL_BYTES (lp -> sl_regions , (size_t )len ,fd ,; ); 1057lp -> sl_regions [len ]= NUL ; 1058return 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{ 1066int flagslen ,follen ; 1067 1068// <charflagslen> <charflags> 1069char * flags = read_cnt_string (fd ,1 ,& flagslen ); 1070if (flagslen < 0 ) { 1071return flagslen ; 1072 } 1073 1074// <folcharslen> <folchars> 1075char * fol = read_cnt_string (fd ,2 ,& follen ); 1076if (follen < 0 ) { 1077xfree (flags ); 1078return follen ; 1079 } 1080 1081// Set the word-char flags and fill SPELL_ISUPPER() table. 1082if (flags != NULL && fol != NULL ) { 1083set_spell_charflags (flags ,flagslen ,fol ); 1084 } 1085 1086xfree (flags ); 1087xfree (fol ); 1088 1089// When <charflagslen> is zero then <fcharlen> must also be zero. 1090if ((flags == NULL )!= (fol == NULL )) { 1091return SP_FORMERROR ; 1092 } 1093return 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> ... 1101const int cnt = get2c (fd );// <prefcondcnt> 1102if (cnt <=0 ) { 1103return SP_FORMERROR ; 1104 } 1105 1106lp -> sl_prefprog = xcalloc ((size_t )cnt ,sizeof (regprog_T * )); 1107lp -> sl_prefixcnt = cnt ; 1108 1109for (int i = 0 ;i < cnt ;i ++ ) { 1110// <prefcond> : <condlen> <condstr> 1111const int n = getc (fd );// <condlen> 1112if (n < 0 || n >=MAXWLEN ) { 1113return 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. 1118if (n > 0 ) { 1119char buf [MAXWLEN + 1 ]; 1120buf [0 ]= '^' ;// always match at one position only 1121SPELL_READ_NONNUL_BYTES (buf + 1 , (size_t )n ,fd ,; ); 1122buf [n + 1 ]= NUL ; 1123lp -> sl_prefprog [i ]= vim_regcomp (buf ,RE_MAGIC |RE_STRING ); 1124 } 1125 } 1126return 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{ 1133fromto_T * ftp ; 1134 1135int cnt = get2c (fd );// <repcount> 1136if (cnt < 0 ) { 1137return SP_TRUNCERROR ; 1138 } 1139 1140ga_grow (gap ,cnt ); 1141 1142// <rep> : <repfromlen> <repfrom> <reptolen> <repto> 1143for (;gap -> ga_len < cnt ;gap -> ga_len ++ ) { 1144int c ; 1145ftp = & ((fromto_T * )gap -> ga_data )[gap -> ga_len ]; 1146ftp -> ft_from = read_cnt_string (fd ,1 ,& c ); 1147if (c < 0 ) { 1148return c ; 1149 } 1150if (c == 0 ) { 1151return SP_FORMERROR ; 1152 } 1153ftp -> ft_to = read_cnt_string (fd ,1 ,& c ); 1154if (c <=0 ) { 1155xfree (ftp -> ft_from ); 1156if (c < 0 ) { 1157return c ; 1158 } 1159return SP_FORMERROR ; 1160 } 1161 } 1162 1163// Fill the first-index table. 1164for (int i = 0 ;i < 256 ;i ++ ) { 1165first [i ]= -1 ; 1166 } 1167for (int i = 0 ;i < gap -> ga_len ;i ++ ) { 1168ftp = & ((fromto_T * )gap -> ga_data )[i ]; 1169if (first [(uint8_t )(* ftp -> ft_from )]== -1 ) { 1170first [(uint8_t )(* ftp -> ft_from )]= (int16_t )i ; 1171 } 1172 } 1173return 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{ 1180slang -> sl_sofo = false; 1181 1182const int flags = getc (fd );// <salflags> 1183if (flags & SAL_F0LLOWUP ) { 1184slang -> sl_followup = true; 1185 } 1186if (flags & SAL_COLLAPSE ) { 1187slang -> sl_collapse = true; 1188 } 1189if (flags & SAL_REM_ACCENTS ) { 1190slang -> sl_rem_accents = true; 1191 } 1192 1193int cnt = get2c (fd );// <salcount> 1194if (cnt < 0 ) { 1195return SP_TRUNCERROR ; 1196 } 1197 1198garray_T * gap = & slang -> sl_sal ; 1199ga_init (gap ,sizeof (salitem_T ),10 ); 1200ga_grow (gap ,cnt + 1 ); 1201 1202// <sal> : <salfromlen> <salfrom> <saltolen> <salto> 1203for (;gap -> ga_len < cnt ;gap -> ga_len ++ ) { 1204int c = NUL ; 1205 1206salitem_T * smp = & ((salitem_T * )gap -> ga_data )[gap -> ga_len ]; 1207int ccnt = getc (fd );// <salfromlen> 1208if (ccnt < 0 ) { 1209return SP_TRUNCERROR ; 1210 } 1211char * p = xmalloc ((size_t )ccnt + 2 ); 1212smp -> sm_lead = p ; 1213 1214// Read up to the first special char into sm_lead. 1215int i = 0 ; 1216for (;i < ccnt ;i ++ ) { 1217c = getc (fd );// <salfrom> 1218if (vim_strchr ("0123456789(-<^$" ,c )!= NULL ) { 1219break ; 1220 } 1221* p ++ = (char )(uint8_t )c ; 1222 } 1223smp -> sm_leadlen = (int )(p - smp -> sm_lead ); 1224* p ++ = NUL ; 1225 1226// Put (abc) chars in sm_oneof, if any. 1227if (c == '(' ) { 1228smp -> sm_oneof = p ; 1229for (++ i ;i < ccnt ;i ++ ) { 1230c = getc (fd );// <salfrom> 1231if (c == ')' ) { 1232break ; 1233 } 1234* p ++ = (char )(uint8_t )c ; 1235 } 1236* p ++ = NUL ; 1237if (++ i < ccnt ) { 1238c = getc (fd ); 1239 } 1240 }else { 1241smp -> sm_oneof = NULL ; 1242 } 1243 1244// Any following chars go in sm_rules. 1245smp -> sm_rules = p ; 1246if (i < ccnt ) { 1247// store the char we got while checking for end of sm_lead 1248* p ++ = (char )(uint8_t )c ; 1249 } 1250i ++ ; 1251if (i < ccnt ) { 1252SPELL_READ_NONNUL_BYTES (// <salfrom> 1253p , (size_t )(ccnt - i ),fd , 1254xfree (smp -> sm_lead )); 1255p += (ccnt - i ); 1256 } 1257* p ++ = NUL ; 1258 1259// <saltolen> <salto> 1260smp -> sm_to = read_cnt_string (fd ,1 ,& ccnt ); 1261if (ccnt < 0 ) { 1262xfree (smp -> sm_lead ); 1263return ccnt ; 1264 } 1265 1266// convert the multi-byte strings to wide char strings 1267smp -> sm_lead_w = mb_str2wide (smp -> sm_lead ); 1268smp -> sm_leadlen = mb_charlen (smp -> sm_lead ); 1269if (smp -> sm_oneof == NULL ) { 1270smp -> sm_oneof_w = NULL ; 1271 }else { 1272smp -> sm_oneof_w = mb_str2wide (smp -> sm_oneof ); 1273 } 1274if (smp -> sm_to == NULL ) { 1275smp -> sm_to_w = NULL ; 1276 }else { 1277smp -> sm_to_w = mb_str2wide (smp -> sm_to ); 1278 } 1279 } 1280 1281if (!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. 1284salitem_T * smp = & ((salitem_T * )gap -> ga_data )[gap -> ga_len ]; 1285char * p = xmalloc (1 ); 1286p [0 ]= NUL ; 1287smp -> sm_lead = p ; 1288smp -> sm_lead_w = mb_str2wide (smp -> sm_lead ); 1289smp -> sm_leadlen = 0 ; 1290smp -> sm_oneof = NULL ; 1291smp -> sm_oneof_w = NULL ; 1292smp -> sm_rules = p ; 1293smp -> sm_to = NULL ; 1294smp -> sm_to_w = NULL ; 1295gap -> ga_len ++ ; 1296 } 1297 1298// Fill the first-index table. 1299set_sal_first (slang ); 1300 1301return 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{ 1308int done = 0 ; 1309int i ; 1310uint8_t word [MAXWLEN ]; 1311 1312while (done < len ) { 1313// Read one word at a time. 1314for (i = 0 ;;i ++ ) { 1315int c = getc (fd ); 1316if (c == EOF ) { 1317return SP_TRUNCERROR ; 1318 } 1319word [i ]= (uint8_t )c ; 1320if (word [i ]== NUL ) { 1321break ; 1322 } 1323if (i == MAXWLEN - 1 ) { 1324return SP_FORMERROR ; 1325 } 1326 } 1327 1328// Init the count to 10. 1329count_common_word (lp , (char * )word ,-1 ,10 ); 1330done += i + 1 ; 1331 } 1332return 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{ 1339int cnt ; 1340int res ; 1341 1342// <sofofromlen> <sofofrom> 1343char * from = read_cnt_string (fd ,2 ,& cnt ); 1344if (cnt < 0 ) { 1345return cnt ; 1346 } 1347 1348// <sofotolen> <sofoto> 1349char * to = read_cnt_string (fd ,2 ,& cnt ); 1350if (cnt < 0 ) { 1351xfree (from ); 1352return cnt ; 1353 } 1354 1355// Store the info in slang->sl_sal and/or slang->sl_sal_first. 1356if (from != NULL && to != NULL ) { 1357res = set_sofo (slang ,from ,to ); 1358 }else if (from != NULL || to != NULL ) { 1359res = SP_FORMERROR ;// only one of two strings is an error 1360 }else { 1361res = 0 ; 1362 } 1363 1364xfree (from ); 1365xfree (to ); 1366return 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{ 1374int todo = len ; 1375int cnt ; 1376 1377if (todo < 2 ) { 1378return SP_FORMERROR ;// need at least two bytes 1379 } 1380todo -- ; 1381int c = getc (fd );// <compmax> 1382if (c < 2 ) { 1383c = MAXWLEN ; 1384 } 1385slang -> sl_compmax = c ; 1386 1387todo -- ; 1388c = getc (fd );// <compminlen> 1389if (c < 1 ) { 1390c = 0 ; 1391 } 1392slang -> sl_compminlen = c ; 1393 1394todo -- ; 1395c = getc (fd );// <compsylmax> 1396if (c < 1 ) { 1397c = MAXWLEN ; 1398 } 1399slang -> sl_compsylmax = c ; 1400 1401c = getc (fd );// <compoptions> 1402if (c != 0 ) { 1403ungetc (c ,fd );// be backwards compatible with Vim 7.0b 1404 }else { 1405todo -- ; 1406c = getc (fd );// only use the lower byte for now 1407todo -- ; 1408slang -> sl_compoptions = c ; 1409 1410garray_T * gap = & slang -> sl_comppat ; 1411c = get2c (fd );// <comppatcount> 1412if (c < 0 ) { 1413return SP_TRUNCERROR ; 1414 } 1415todo -= 2 ; 1416ga_init (gap ,sizeof (char * ),c ); 1417ga_grow (gap ,c ); 1418while (-- c >=0 ) { 1419 ((char ** )(gap -> ga_data ))[gap -> ga_len ++ ]= read_cnt_string (fd ,1 ,& cnt ); 1420// <comppatlen> <comppattext> 1421if (cnt < 0 ) { 1422return cnt ; 1423 } 1424todo -= cnt + 1 ; 1425 } 1426 } 1427if (todo < 0 ) { 1428return 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. 1435if ((size_t )todo > COMPOUND_MAX_LEN ) { 1436return SP_FORMERROR ; 1437 } 1438size_t patsize = (size_t )todo * 2 + 7 ; 1439patsize += (size_t )todo * 2 ; 1440size_t flagsize = (size_t )todo + 1 ; 1441char * 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. 1445uint8_t * cp = xmalloc (flagsize ); 1446slang -> sl_compstartflags = cp ; 1447* cp = NUL ; 1448 1449uint8_t * ap = xmalloc (flagsize ); 1450slang -> 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. 1456uint8_t * crp = xmalloc (flagsize ); 1457slang -> sl_comprules = crp ; 1458 1459char * pp = pat ; 1460* pp ++ = '^' ; 1461* pp ++ = '\\' ; 1462* pp ++ = '(' ; 1463 1464int atstart = 1 ; 1465while (todo -- > 0 ) { 1466c = getc (fd );// <compflags> 1467if (c == EOF ) { 1468xfree (pat ); 1469return SP_TRUNCERROR ; 1470 } 1471 1472// Add all flags to "sl_compallflags". 1473if (vim_strchr ("?*+[]/" ,c )== NULL 1474&& !byte_in_str (slang -> sl_compallflags ,c )) { 1475* ap ++ = (uint8_t )c ; 1476* ap = NUL ; 1477 } 1478 1479if (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 ']'. 1482if (c == '[' ) { 1483atstart = 2 ; 1484 }else if (c == ']' ) { 1485atstart = 0 ; 1486 }else { 1487if (!byte_in_str (slang -> sl_compstartflags ,c )) { 1488* cp ++ = (uint8_t )c ; 1489* cp = NUL ; 1490 } 1491if (atstart == 1 ) { 1492atstart = 0 ; 1493 } 1494 } 1495 } 1496 1497// Copy flag to "sl_comprules", unless we run into a wildcard. 1498if (crp != NULL ) { 1499if (c == '?' || c == '+' || c == '*' ) { 1500XFREE_CLEAR (slang -> sl_comprules ); 1501crp = NULL ; 1502 }else { 1503* crp ++ = (uint8_t )c ; 1504 } 1505 } 1506 1507if (c == '/' ) {// slash separates two items 1508* pp ++ = '\\' ; 1509* pp ++ = '|' ; 1510atstart = 1 ; 1511 }else {// normal char, "[abc]" and '*' are copied as-is 1512if (c == '?' || c == '+' || c == '~' ) { 1513* pp ++ = '\\' ;// "a?" becomes "a\?", "a+" becomes "a\+" 1514 } 1515pp += utf_char2bytes (c ,pp ); 1516 } 1517 } 1518 1519* pp ++ = '\\' ; 1520* pp ++ = ')' ; 1521* pp ++ = '$' ; 1522* pp = NUL ; 1523 1524if (crp != NULL ) { 1525* crp = NUL ; 1526 } 1527 1528slang -> sl_compprog = vim_regcomp (pat ,RE_MAGIC + RE_STRING + RE_STRICT ); 1529xfree (pat ); 1530if (slang -> sl_compprog == NULL ) { 1531return SP_FORMERROR ; 1532 } 1533 1534return 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{ 1541const char * s ; 1542const char * p ; 1543 1544free_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. 1550garray_T * gap = & lp -> sl_sal ; 1551ga_init (gap ,sizeof (int * ),1 ); 1552ga_grow (gap ,256 ); 1553memset (gap -> ga_data ,0 ,sizeof (int * )* 256 ); 1554gap -> ga_len = 256 ; 1555lp -> 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(). 1560memset (lp -> sl_sal_first ,0 ,sizeof (salfirst_T )* 256 ); 1561for (p = from ,s = to ;* p != NUL && * s != NUL ;) { 1562const int c = mb_cptr2char_adv (& p ); 1563s += utf_ptr2len (s ); 1564if (c >=256 ) { 1565lp -> sl_sal_first [c & 0xff ]++ ; 1566 } 1567 } 1568if (* p != NUL || * s != NUL ) {// lengths differ 1569return SP_FORMERROR ; 1570 } 1571 1572// Allocate the lists. 1573for (int i = 0 ;i < 256 ;i ++ ) { 1574if (lp -> sl_sal_first [i ]> 0 ) { 1575p = 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. 1583memset (lp -> sl_sal_first ,0 ,sizeof (salfirst_T )* 256 ); 1584for (p = from ,s = to ;* p != NUL && * s != NUL ;) { 1585const int c = mb_cptr2char_adv (& p ); 1586const int i = mb_cptr2char_adv (& s ); 1587if (c >=256 ) { 1588// Append the from-to chars at the end of the list with 1589// the low byte. 1590int * inp = ((int ** )gap -> ga_data )[c & 0xff ]; 1591while (* inp != 0 ) { 1592inp ++ ; 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[] 1599lp -> sl_sal_first [c ]= i ; 1600 } 1601 } 1602 1603return 0 ; 1604} 1605 1606// Fill the first-index table for "lp". 1607static void set_sal_first (slang_T * lp ) 1608{ 1609garray_T * gap = & lp -> sl_sal ; 1610 1611salfirst_T * sfirst = lp -> sl_sal_first ; 1612for (int i = 0 ;i < 256 ;i ++ ) { 1613sfirst [i ]= -1 ; 1614 } 1615salitem_T * smp = (salitem_T * )gap -> ga_data ; 1616for (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. 1620int c = * smp [i ].sm_lead_w & 0xff ; 1621if (sfirst [c ]== -1 ) { 1622sfirst [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! 1627while (i + 1 < gap -> ga_len 1628&& (* smp [i + 1 ].sm_lead_w & 0xff )== c ) { 1629// Skip over entry with same index byte. 1630i ++ ; 1631 } 1632 1633for (int n = 1 ;i + n < gap -> ga_len ;n ++ ) { 1634if ((* smp [i + n ].sm_lead_w & 0xff )== c ) { 1635salitem_T tsal ; 1636 1637// Move entry with same index byte after the entries 1638// we already found. 1639i ++ ; 1640n -- ; 1641tsal = smp [i + n ]; 1642memmove (smp + i + 1 ,smp + i ,sizeof (salitem_T )* (size_t )n ); 1643smp [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{ 1654int i = 0 ; 1655 1656int * res = xmalloc (((size_t )mb_charlen (s )+ 1 )* sizeof (int )); 1657for (const char * p = s ;* p != NUL ;) { 1658res [i ++ ]= mb_ptr2char_adv (& p ); 1659 } 1660res [i ]= NUL ; 1661 1662return 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 , 1674bool prefixtree ,int prefixcnt ) 1675FUNC_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> 1679int len = get4c (fd ); 1680if (len < 0 ) { 1681return SP_TRUNCERROR ; 1682 } 1683if ((size_t )len > SIZE_MAX /sizeof (int )) { 1684// Invalid length, multiply with sizeof(int) would overflow. 1685return SP_FORMERROR ; 1686 } 1687if (len <=0 ) { 1688return 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. 1695uint8_t * bp = xcalloc (1 , (size_t )len ); 1696* bytsp = bp ; 1697if (bytsp_len != NULL ) { 1698* bytsp_len = len ; 1699 } 1700 1701// Allocate the index array. 1702idx_T * ip = xcalloc ((size_t )len ,sizeof (* ip )); 1703* idxsp = ip ; 1704 1705// Recursively read the tree and store it in the array. 1706int idx = read_tree_node (fd ,bp ,ip ,len ,0 ,prefixtree ,prefixcnt ,0 ); 1707if (idx < 0 ) { 1708return idx ; 1709 } 1710if (idx != len ) { 1711return SP_FORMERROR ; 1712 } 1713return 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 , 1731bool prefixtree ,int maxprefcondnr ,int depth ) 1732{ 1733idx_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. 1739if (depth > MAXWLEN ) { 1740return SP_FORMERROR ; 1741 } 1742 1743int len = getc (fd );// <siblingcount> 1744if (len <=0 ) { 1745return SP_TRUNCERROR ; 1746 } 1747 1748if (len >=maxidx - startidx ) { 1749return SP_FORMERROR ; 1750 } 1751byts [idx ++ ]= (uint8_t )len ; 1752 1753// Read the byte values, flag/region bytes and shared indexes. 1754for (int i = 1 ;i <=len ;i ++ ) { 1755int c = getc (fd );// <byte> 1756if (c < 0 ) { 1757return SP_TRUNCERROR ; 1758 } 1759if (c <=BY_SPECIAL ) { 1760if (c == BY_NOFLAGS && !prefixtree ) { 1761// No flags, all regions. 1762idxs [idx ]= 0 ; 1763 }else if (c != BY_INDEX ) { 1764if (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. 1769if (c == BY_FLAGS ) { 1770int n = getc (fd );// <pflags> 1771if (n < 0 ) { 1772return SP_TRUNCERROR ; 1773 } 1774c = n <<24 ; 1775 }else { 1776c = 0 ; 1777 } 1778 1779int n = getc (fd );// <affixID> 1780if (n < 0 ) { 1781return SP_TRUNCERROR ; 1782 } 1783c |=n ; 1784 1785n = get2c (fd );// <prefcondnr> 1786if (n < 0 || n >=maxprefcondnr ) { 1787return SP_FORMERROR ; 1788 } 1789c |= (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. 1794int c2 = c ; 1795c = getc (fd );// <flags> 1796if (c < 0 ) { 1797return SP_TRUNCERROR ; 1798 } 1799if (c2 == BY_FLAGS2 ) { 1800int n = getc (fd );// <flags2> 1801if (n < 0 ) { 1802return SP_TRUNCERROR ; 1803 } 1804c = (n <<8 )+ c ; 1805 } 1806if (c & WF_REGION ) { 1807int n = getc (fd );// <region> 1808if (n < 0 ) { 1809return SP_TRUNCERROR ; 1810 } 1811c = (n <<16 )+ c ; 1812 } 1813if (c & WF_AFX ) { 1814int n = getc (fd );// <affixID> 1815if (n < 0 ) { 1816return SP_TRUNCERROR ; 1817 } 1818c = (int )((unsigned )n <<24 )+ c ; 1819 } 1820 } 1821 1822idxs [idx ]= c ; 1823c = 0 ; 1824 }else {// c == BY_INDEX 1825// <nodeidx> 1826int n = get3c (fd ); 1827if (n < 0 || n >=maxidx ) { 1828return SP_FORMERROR ; 1829 } 1830idxs [idx ]= n + SHARED_MASK ; 1831c = getc (fd );// <xbyte> 1832 } 1833 } 1834byts [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) 1840for (int i = 1 ;i <=len ;i ++ ) { 1841if (byts [startidx + i ]!= 0 ) { 1842if (idxs [startidx + i ]& SHARED_MASK ) { 1843idxs [startidx + i ] &= ~SHARED_MASK ; 1844 }else { 1845idxs [startidx + i ]= idx ; 1846idx = read_tree_node (fd ,byts ,idxs ,maxidx ,idx , 1847prefixtree ,maxprefcondnr ,depth + 1 ); 1848if (idx < 0 ) { 1849break ; 1850 } 1851 } 1852 } 1853 } 1854 1855return 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{ 1863bool didit = false; 1864 1865for (slang_T * slang = first_lang ;slang != NULL ;slang = slang -> sl_next ) { 1866if (path_equal (fname ,slang -> sl_fname ,kPathCmpExpand )) { 1867slang_clear (slang ); 1868if (spell_load_file (fname ,NULL ,slang , false)== NULL ) { 1869// reloading failed, clear the language 1870slang_clear (slang ); 1871 } 1872redraw_all_later (UPD_SOME_VALID ); 1873didit = true; 1874 } 1875 } 1876 1877// When "zg" was used and the file wasn't loaded yet, should redo 1878// 'spelllang' to load it now. 1879if (added_word && !didit ) { 1880parse_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{ 1907char * p = value ; 1908 1909if (!ascii_isdigit (* p )) { 1910return FAIL ; 1911 } 1912// block count = (value * 1024) / SBLOCKSIZE (but avoid overflow) 1913int start = (getdigits_int (& p , true,0 )* 10 ) / (SBLOCKSIZE /102 ); 1914if (* p != ',' ) { 1915return FAIL ; 1916 } 1917p ++ ; 1918if (!ascii_isdigit (* p )) { 1919return FAIL ; 1920 } 1921int incr = (getdigits_int (& p , true,0 )* 102 ) / (SBLOCKSIZE /10 ); 1922if (* p != ',' ) { 1923return FAIL ; 1924 } 1925p ++ ; 1926if (!ascii_isdigit (* p )) { 1927return FAIL ; 1928 } 1929int added = getdigits_int (& p , true,0 )* 1024 ; 1930if (* p != NUL ) { 1931return FAIL ; 1932 } 1933 1934if (start == 0 || incr == 0 || added == 0 || incr > start ) { 1935return FAIL ; 1936 } 1937 1938if (apply ) { 1939compress_start = start ; 1940compress_inc = incr ; 1941compress_added = added ; 1942 } 1943return 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{ 1964wordnode_T * np ; 1965 1966for (np = node ;np != NULL ;np = np -> wn_sibling ) { 1967np -> wn_u1 .index = false; 1968spell_clear_flags (np -> wn_child ); 1969 } 1970} 1971 1972static void spell_print_node (wordnode_T * node ,int depth ) 1973{ 1974if (node -> wn_u1 .index ) { 1975// Done this node before, print the reference. 1976PRINTSOME (line1 ,depth ,"(%d)" ,node -> wn_nr ,0 ); 1977PRINTSOME (line2 ,depth ," " ,0 ,0 ); 1978PRINTSOME (line3 ,depth ," " ,0 ,0 ); 1979msg (line1 ,0 ); 1980msg (line2 ,0 ); 1981msg (line3 ,0 ); 1982 }else { 1983node -> wn_u1 .index = true; 1984 1985if (node -> wn_byte != NUL ) { 1986if (node -> wn_child != NULL ) { 1987PRINTSOME (line1 ,depth ," %c -> " ,node -> wn_byte ,0 ); 1988 }else { 1989// Cannot happen? 1990PRINTSOME (line1 ,depth ," %c ???" ,node -> wn_byte ,0 ); 1991 } 1992 }else { 1993PRINTSOME (line1 ,depth ," $ " ,0 ,0 ); 1994 } 1995 1996PRINTSOME (line2 ,depth ,"%d/%d " ,node -> wn_nr ,node -> wn_refs ); 1997 1998if (node -> wn_sibling != NULL ) { 1999PRINTSOME (line3 ,depth ," | " ,0 ,0 ); 2000 }else { 2001PRINTSOME (line3 ,depth ," " ,0 ,0 ); 2002 } 2003 2004if (node -> wn_byte == NUL ) { 2005msg (line1 ,0 ); 2006msg (line2 ,0 ); 2007msg (line3 ,0 ); 2008 } 2009 2010// do the children 2011if (node -> wn_byte != NUL && node -> wn_child != NULL ) { 2012spell_print_node (node -> wn_child ,depth + 1 ); 2013 } 2014 2015// do the siblings 2016if (node -> wn_sibling != NULL ) { 2017// get rid of all parent details except | 2018STRCPY (line1 ,line3 ); 2019STRCPY (line2 ,line3 ); 2020spell_print_node (node -> wn_sibling ,depth ); 2021 } 2022 } 2023} 2024 2025static void spell_print_tree (wordnode_T * root ) 2026{ 2027if (root == NULL ) { 2028return ; 2029 } 2030 2031// Clear the "wn_u1.index" fields, used to remember what has been done. 2032spell_clear_flags (root ); 2033 2034// Recursively print the tree. 2035spell_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{ 2044char rline [MAXLINELEN ]; 2045char * line ; 2046char * pc = NULL ; 2047#define MAXITEMCNT 30 2048char * (items [MAXITEMCNT ]); 2049char * p ; 2050int lnum = 0 ; 2051affheader_T * cur_aff = NULL ; 2052bool did_postpone_prefix = false; 2053int aff_todo = 0 ; 2054hashtab_T * tp ; 2055char * low = NULL ; 2056char * fol = NULL ; 2057char * upp = NULL ; 2058bool found_map = false; 2059hashitem_T * hi ; 2060int compminlen = 0 ;// COMPOUNDMIN value 2061int compsylmax = 0 ;// COMPOUNDSYLMAX value 2062int compoptions = 0 ;// COMP_ flags 2063int compmax = 0 ;// COMPOUNDWORDMAX value 2064char * compflags = NULL ;// COMPOUNDFLAG and COMPOUNDRULE 2065// concatenated 2066char * midword = NULL ;// MIDWORD value 2067char * syllable = NULL ;// SYLLABLE value 2068char * sofofrom = NULL ;// SOFOFROM value 2069char * sofoto = NULL ;// SOFOTO value 2070 2071// Open the file. 2072FILE * fd = os_fopen (fname ,"r" ); 2073if (fd == NULL ) { 2074semsg (_ (e_notopen ),fname ); 2075return NULL ; 2076 } 2077 2078vim_snprintf (IObuff ,IOSIZE ,_ ("Reading affix file %s..." ),fname ); 2079spell_message (spin ,IObuff ); 2080 2081// Only do REP lines when not done in another .aff file already. 2082bool do_rep = GA_EMPTY (& spin -> si_rep ); 2083 2084// Only do REPSAL lines when not done in another .aff file already. 2085bool do_repsal = GA_EMPTY (& spin -> si_repsal ); 2086 2087// Only do SAL lines when not done in another .aff file already. 2088bool do_sal = GA_EMPTY (& spin -> si_sal ); 2089 2090// Only do MAP lines when not done in another .aff file already. 2091bool do_mapline = GA_EMPTY (& spin -> si_map ); 2092 2093// Allocate and init the afffile_T structure. 2094afffile_T * aff = getroom (spin ,sizeof (* aff ), true); 2095hash_init (& aff -> af_pref ); 2096hash_init (& aff -> af_suff ); 2097hash_init (& aff -> af_comp ); 2098 2099// Read all the lines in the file one by one. 2100while (!vim_fgets (rline ,MAXLINELEN ,fd )&& !got_int ) { 2101line_breakcheck (); 2102lnum ++ ; 2103 2104// Skip comment lines. 2105if (* rline == '#' ) { 2106continue ; 2107 } 2108 2109// Convert from "SET" to 'encoding' when needed. 2110xfree (pc ); 2111if (spin -> si_conv .vc_type != CONV_NONE ) { 2112pc = string_convert (& spin -> si_conv ,rline ,NULL ); 2113if (pc == NULL ) { 2114smsg (0 ,_ ("Conversion failure for word in %s line %d: %s" ), 2115fname ,lnum ,rline ); 2116continue ; 2117 } 2118line = pc ; 2119 }else { 2120pc = NULL ; 2121line = rline ; 2122 } 2123 2124// Split the line up in white separated items. Put a NUL after each 2125// item. 2126int itemcnt = 0 ; 2127for (p = line ;;) { 2128while (* p != NUL && (uint8_t )(* p ) <=' ' ) {// skip white space and CR/NL 2129p ++ ; 2130 } 2131if (* p == NUL ) { 2132break ; 2133 } 2134if (itemcnt == MAXITEMCNT ) {// too many items 2135break ; 2136 } 2137items [itemcnt ++ ]= p ; 2138// A few items have arbitrary text argument, don't split them. 2139if (itemcnt == 2 && spell_info_item (items [0 ])) { 2140while ((uint8_t )(* p ) >=' ' || * p == TAB ) {// skip until CR/NL 2141p ++ ; 2142 } 2143 }else { 2144while ((uint8_t )(* p )> ' ' ) {// skip until white space or CR/NL 2145p ++ ; 2146 } 2147 } 2148if (* p == NUL ) { 2149break ; 2150 } 2151* p ++ = NUL ; 2152 } 2153 2154// Handle non-empty lines. 2155if (itemcnt > 0 ) { 2156if (is_aff_rule (items ,itemcnt ,"SET" ,2 )&& aff -> af_enc == NULL ) { 2157// Setup for conversion from "ENC" to 'encoding'. 2158aff -> af_enc = enc_canonize (items [1 ]); 2159if (!spin -> si_ascii 2160&& convert_setup (& spin -> si_conv ,aff -> af_enc ,p_enc )== FAIL ) { 2161smsg (0 ,_ ("Conversion in %s not supported: from %s to %s" ), 2162fname ,aff -> af_enc ,p_enc ); 2163 } 2164spin -> si_conv .vc_fail = true; 2165 }else if (is_aff_rule (items ,itemcnt ,"FLAG" ,2 ) 2166&& aff -> af_flagtype == AFT_CHAR ) { 2167if (strcmp (items [1 ],"long" )== 0 ) { 2168aff -> af_flagtype = AFT_LONG ; 2169 }else if (strcmp (items [1 ],"num" )== 0 ) { 2170aff -> af_flagtype = AFT_NUM ; 2171 }else if (strcmp (items [1 ],"caplong" )== 0 ) { 2172aff -> af_flagtype = AFT_CAPLONG ; 2173 }else { 2174smsg (0 ,_ ("Invalid value for FLAG in %s line %d: %s" ), 2175fname ,lnum ,items [1 ]); 2176 } 2177if (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 ) { 2188smsg (0 ,_ ("FLAG after using flags in %s line %d: %s" ), 2189fname ,lnum ,items [1 ]); 2190 } 2191 }else if (spell_info_item (items [0 ])&& itemcnt > 1 ) { 2192p = getroom (spin , 2193 (spin -> si_info == NULL ?0 :strlen (spin -> si_info )) 2194+ strlen (items [0 ]) 2195+ strlen (items [1 ])+ 3 , false); 2196if (spin -> si_info != NULL ) { 2197STRCPY (p ,spin -> si_info ); 2198strcat (p ,"\n" ); 2199 } 2200strcat (p ,items [0 ]); 2201strcat (p ," " ); 2202strcat (p ,items [1 ]); 2203spin -> si_info = p ; 2204 }else if (is_aff_rule (items ,itemcnt ,"MIDWORD" ,2 )&& midword == NULL ) { 2205midword = 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 ) { 2211aff -> 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 ) { 2215aff -> 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 ) { 2219aff -> 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 ) { 2222aff -> 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 ) { 2225aff -> 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 ) { 2228aff -> 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 ) { 2232aff -> 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 ) { 2235aff -> 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 ) { 2238aff -> af_compforbid = affitem2flag (aff -> af_flagtype ,items [1 ],fname ,lnum ); 2239if (aff -> af_pref .ht_used > 0 ) { 2240smsg (0 , 2241_ ("Defining COMPOUNDFORBIDFLAG after PFX item may give wrong results in %s line %d" ), 2242fname ,lnum ); 2243 } 2244 }else if (is_aff_rule (items ,itemcnt ,"COMPOUNDPERMITFLAG" ,2 ) 2245&& aff -> af_comppermit == 0 ) { 2246aff -> af_comppermit = affitem2flag (aff -> af_flagtype ,items [1 ],fname ,lnum ); 2247if (aff -> af_pref .ht_used > 0 ) { 2248smsg (0 , 2249_ ("Defining COMPOUNDPERMITFLAG after PFX item may give wrong results in %s line %d" ), 2250fname ,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+". 2256p = getroom (spin ,strlen (items [1 ])+ 2 , false); 2257STRCPY (p ,items [1 ]); 2258strcat (p ,"+" ); 2259compflags = 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. 2263if (atoi (items [1 ])== 0 ) { 2264smsg (0 ,_ ("Wrong COMPOUNDRULES value in %s line %d: %s" ), 2265fname ,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. 2269if (compflags != NULL || * skipdigits (items [1 ])!= NUL ) { 2270// Concatenate this string to previously defined ones, 2271// using a slash to separate them. 2272int l = (int )strlen (items [1 ])+ 1 ; 2273if (compflags != NULL ) { 2274l += (int )strlen (compflags )+ 1 ; 2275 } 2276p = getroom (spin , (size_t )l , false); 2277if (compflags != NULL ) { 2278STRCPY (p ,compflags ); 2279strcat (p ,"/" ); 2280 } 2281strcat (p ,items [1 ]); 2282compflags = p ; 2283 } 2284 }else if (is_aff_rule (items ,itemcnt ,"COMPOUNDWORDMAX" ,2 ) 2285&& compmax == 0 ) { 2286compmax = atoi (items [1 ]); 2287if (compmax == 0 ) { 2288smsg (0 ,_ ("Wrong COMPOUNDWORDMAX value in %s line %d: %s" ), 2289fname ,lnum ,items [1 ]); 2290 } 2291 }else if (is_aff_rule (items ,itemcnt ,"COMPOUNDMIN" ,2 ) 2292&& compminlen == 0 ) { 2293compminlen = atoi (items [1 ]); 2294if (compminlen == 0 ) { 2295smsg (0 ,_ ("Wrong COMPOUNDMIN value in %s line %d: %s" ), 2296fname ,lnum ,items [1 ]); 2297 } 2298 }else if (is_aff_rule (items ,itemcnt ,"COMPOUNDSYLMAX" ,2 ) 2299&& compsylmax == 0 ) { 2300compsylmax = atoi (items [1 ]); 2301if (compsylmax == 0 ) { 2302smsg (0 ,_ ("Wrong COMPOUNDSYLMAX value in %s line %d: %s" ), 2303fname ,lnum ,items [1 ]); 2304 } 2305 }else if (is_aff_rule (items ,itemcnt ,"CHECKCOMPOUNDDUP" ,1 )) { 2306compoptions |=COMP_CHECKDUP ; 2307 }else if (is_aff_rule (items ,itemcnt ,"CHECKCOMPOUNDREP" ,1 )) { 2308compoptions |=COMP_CHECKREP ; 2309 }else if (is_aff_rule (items ,itemcnt ,"CHECKCOMPOUNDCASE" ,1 )) { 2310compoptions |=COMP_CHECKCASE ; 2311 }else if (is_aff_rule (items ,itemcnt ,"CHECKCOMPOUNDTRIPLE" ,1 )) { 2312compoptions |=COMP_CHECKTRIPLE ; 2313 }else if (is_aff_rule (items ,itemcnt ,"CHECKCOMPOUNDPATTERN" ,2 )) { 2314if (atoi (items [1 ])== 0 ) { 2315smsg (0 ,_ ("Wrong CHECKCOMPOUNDPATTERN value in %s line %d: %s" ), 2316fname ,lnum ,items [1 ]); 2317 } 2318 }else if (is_aff_rule (items ,itemcnt ,"CHECKCOMPOUNDPATTERN" ,3 )) { 2319garray_T * gap = & spin -> si_comppat ; 2320int i ; 2321 2322// Only add the couple if it isn't already there. 2323for (i = 0 ;i < gap -> ga_len - 1 ;i += 2 ) { 2324if (strcmp (((char ** )(gap -> ga_data ))[i ],items [1 ])== 0 2325&& strcmp (((char ** )(gap -> ga_data ))[i + 1 ],items [2 ])== 0 ) { 2326break ; 2327 } 2328 } 2329if (i >=gap -> ga_len ) { 2330ga_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 ) { 2336syllable = getroom_save (spin ,items [1 ]); 2337 }else if (is_aff_rule (items ,itemcnt ,"NOBREAK" ,1 )) { 2338spin -> si_nobreak = true; 2339 }else if (is_aff_rule (items ,itemcnt ,"NOSPLITSUGS" ,1 )) { 2340spin -> si_nosplitsugs = true; 2341 }else if (is_aff_rule (items ,itemcnt ,"NOCOMPOUNDSUGS" ,1 )) { 2342spin -> si_nocompoundsugs = true; 2343 }else if (is_aff_rule (items ,itemcnt ,"NOSUGFILE" ,1 )) { 2344spin -> si_nosugfile = true; 2345 }else if (is_aff_rule (items ,itemcnt ,"PFXPOSTPONE" ,1 )) { 2346aff -> af_pfxpostpone = true; 2347 }else if (is_aff_rule (items ,itemcnt ,"IGNOREEXTRA" ,1 )) { 2348aff -> af_ignoreextra = true; 2349 }else if ((strcmp (items [0 ],"PFX" )== 0 2350|| strcmp (items [0 ],"SFX" )== 0 ) 2351&& aff_todo == 0 2352&& itemcnt >=4 ) { 2353int lasti = 4 ; 2354char key [AH_KEY_LEN ]; 2355 2356if (* items [0 ]== 'P' ) { 2357tp = & aff -> af_pref ; 2358 }else { 2359tp = & 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. 2366xstrlcpy (key ,items [1 ],AH_KEY_LEN ); 2367hi = hash_find (tp ,key ); 2368if (!HASHITEM_EMPTY (hi )) { 2369cur_aff = HI2AH (hi ); 2370if (cur_aff -> ah_combine != (* items [2 ]== 'Y' )) { 2371smsg (0 ,_ ("Different combining flag in continued affix block in %s line %d: %s" ), 2372fname ,lnum ,items [1 ]); 2373 } 2374if (!cur_aff -> ah_follows ) { 2375smsg (0 ,_ ("Duplicate affix in %s line %d: %s" ), 2376fname ,lnum ,items [1 ]); 2377 } 2378 }else { 2379// New affix letter. 2380cur_aff = getroom (spin ,sizeof (* cur_aff ), true); 2381cur_aff -> ah_flag = affitem2flag (aff -> af_flagtype ,items [1 ],fname ,lnum ); 2382if (cur_aff -> ah_flag == 0 || strlen (items [1 ]) >=AH_KEY_LEN ) { 2383break ; 2384 } 2385if (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 ) { 2393smsg (0 ,_ ("Affix also used for BAD/RARE/KEEPCASE/NEEDAFFIX/NEEDCOMPOUND/NOSUGGEST " 2394"in %s line %d: %s" ), 2395fname ,lnum ,items [1 ]); 2396 } 2397STRCPY (cur_aff -> ah_key ,items [1 ]); 2398hash_add (tp ,cur_aff -> ah_key ); 2399 2400cur_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. 2405if (itemcnt > lasti && strcmp (items [lasti ],"S" )== 0 ) { 2406lasti ++ ; 2407cur_aff -> ah_follows = true; 2408 }else { 2409cur_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. 2415if (itemcnt > lasti 2416&& !aff -> af_ignoreextra 2417&& * items [lasti ]!= '#' ) { 2418smsg (0 ,_ (e_afftrailing ),fname ,lnum ,items [lasti ]); 2419 } 2420 2421if (strcmp (items [2 ],"Y" )!= 0 && strcmp (items [2 ],"N" )!= 0 ) { 2422smsg (0 ,_ ("Expected Y or N in %s line %d: %s" ), 2423fname ,lnum ,items [2 ]); 2424 } 2425 2426if (* items [0 ]== 'P' && aff -> af_pfxpostpone ) { 2427if (cur_aff -> ah_newID == 0 ) { 2428// Use a new number in the .spl file later, to be able 2429// to handle multiple .aff files. 2430check_renumber (spin ); 2431cur_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. 2436did_postpone_prefix = false; 2437 }else { 2438// Did use the ID in a previous block. 2439did_postpone_prefix = true; 2440 } 2441 } 2442 2443aff_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 ) { 2449affentry_T * aff_entry ; 2450int 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. 2455if (itemcnt > lasti && * items [lasti ]!= '#' 2456&& (strcmp (items [lasti ],"-" )!= 0 2457|| itemcnt != lasti + 1 )) { 2458smsg (0 ,_ (e_afftrailing ),fname ,lnum ,items [lasti ]); 2459 } 2460 2461// New item for an affix letter. 2462aff_todo -- ; 2463aff_entry = getroom (spin ,sizeof (* aff_entry ), true); 2464 2465if (strcmp (items [2 ],"0" )!= 0 ) { 2466aff_entry -> ae_chop = getroom_save (spin ,items [2 ]); 2467 } 2468if (strcmp (items [3 ],"0" )!= 0 ) { 2469aff_entry -> ae_add = getroom_save (spin ,items [3 ]); 2470 2471// Recognize flags on the affix: abcd/XYZ 2472aff_entry -> ae_flags = vim_strchr (aff_entry -> ae_add ,'/' ); 2473if (aff_entry -> ae_flags != NULL ) { 2474* aff_entry -> ae_flags ++ = NUL ; 2475aff_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. 2481if (!spin -> si_ascii || !(has_non_ascii (aff_entry -> ae_chop ) 2482|| has_non_ascii (aff_entry -> ae_add ))) { 2483aff_entry -> ae_next = cur_aff -> ah_first ; 2484cur_aff -> ah_first = aff_entry ; 2485 2486if (strcmp (items [4 ],"." )!= 0 ) { 2487char buf [MAXLINELEN ]; 2488 2489aff_entry -> ae_cond = getroom_save (spin ,items [4 ]); 2490// Note: this silently truncates the buffer, but this should 2491// not happen in practice 2492snprintf (buf ,sizeof (buf ),* items [0 ]== 'P' ?"^%s" :"%s$" ,items [4 ]); 2493aff_entry -> ae_prog = vim_regcomp (buf ,RE_MAGIC + RE_STRING + RE_STRICT ); 2494if (aff_entry -> ae_prog == NULL ) { 2495smsg (0 ,_ ("Broken condition in %s line %d: %s" ), 2496fname ,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. 2504if (* items [0 ]== 'P' && aff -> af_pfxpostpone 2505&& aff_entry -> ae_flags == NULL ) { 2506bool 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. 2512if (aff_entry -> ae_chop != NULL 2513&& aff_entry -> ae_add != NULL 2514&& aff_entry -> ae_chop [utfc_ptr2len (aff_entry -> ae_chop )]== 2515NUL ) { 2516int c = utf_ptr2char (aff_entry -> ae_chop ); 2517int c_up = SPELL_TOUPPER (c ); 2518if (c_up != c 2519&& (aff_entry -> ae_cond == NULL 2520|| utf_ptr2char (aff_entry -> ae_cond )== c )) { 2521p = aff_entry -> ae_add + strlen (aff_entry -> ae_add ); 2522MB_PTR_BACK (aff_entry -> ae_add ,p ); 2523if (utf_ptr2char (p )== c_up ) { 2524upper = true; 2525aff_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. 2531if (aff_entry -> ae_cond != NULL ) { 2532char buf [MAXLINELEN ]; 2533onecap_copy (items [4 ],buf , true); 2534aff_entry -> ae_cond = getroom_save (spin ,buf ); 2535if (aff_entry -> ae_cond != NULL ) { 2536snprintf (buf ,MAXLINELEN ,"^%s" ,aff_entry -> ae_cond ); 2537vim_regfree (aff_entry -> ae_prog ); 2538aff_entry -> ae_prog = vim_regcomp (buf ,RE_MAGIC + RE_STRING ); 2539 } 2540 } 2541 } 2542 } 2543 } 2544 2545if (aff_entry -> ae_chop == NULL ) { 2546int idx ; 2547 2548// Find a previously used condition. 2549for (idx = spin -> si_prefcond .ga_len - 1 ;idx >=0 ;idx -- ) { 2550p = ((char ** )spin -> si_prefcond .ga_data )[idx ]; 2551if (str_equal (p ,aff_entry -> ae_cond )) { 2552break ; 2553 } 2554 } 2555if (idx < 0 ) { 2556// Not found, add a new condition. 2557idx = spin -> si_prefcond .ga_len ; 2558char ** 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. 2564if (aff_entry -> ae_add == NULL ) { 2565p = "" ; 2566 }else { 2567p = 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. 2572int n = PFX_FLAGS ; 2573if (!cur_aff -> ah_combine ) { 2574n |=WFP_NC ; 2575 } 2576if (upper ) { 2577n |=WFP_UP ; 2578 } 2579if (aff_entry -> ae_comppermit ) { 2580n |=WFP_COMPPERMIT ; 2581 } 2582if (aff_entry -> ae_compforbid ) { 2583n |=WFP_COMPFORBID ; 2584 } 2585tree_add_word (spin ,p ,spin -> si_prefroot ,n , 2586idx ,cur_aff -> ah_newID ); 2587did_postpone_prefix = true; 2588 } 2589 2590// Didn't actually use ah_newID, backup si_newprefID. 2591if (aff_todo == 0 && !did_postpone_prefix ) { 2592spin -> si_newprefID -- ; 2593cur_aff -> ah_newID = 0 ; 2594 } 2595 } 2596 } 2597 }else if (is_aff_rule (items ,itemcnt ,"FOL" ,2 )&& fol == NULL ) { 2598fol = xstrdup (items [1 ]); 2599 }else if (is_aff_rule (items ,itemcnt ,"LOW" ,2 )&& low == NULL ) { 2600low = xstrdup (items [1 ]); 2601 }else if (is_aff_rule (items ,itemcnt ,"UPP" ,2 )&& upp == NULL ) { 2602upp = 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 2606if (!isdigit ((uint8_t )(* items [1 ]))) { 2607smsg (0 ,_ ("Expected REP(SAL) count in %s line %d" ), 2608fname ,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. 2616if (itemcnt > 3 && items [3 ][0 ]!= '#' ) { 2617smsg (0 ,_ (e_afftrailing ),fname ,lnum ,items [3 ]); 2618 } 2619if (items [0 ][3 ]== 'S' ?do_repsal :do_rep ) { 2620// Replace underscore with space (can't include a space 2621// directly). 2622for (p = items [1 ];* p != NUL ;MB_PTR_ADV (p )) { 2623if (* p == '_' ) { 2624* p = ' ' ; 2625 } 2626 } 2627for (p = items [2 ];* p != NUL ;MB_PTR_ADV (p )) { 2628if (* p == '_' ) { 2629* p = ' ' ; 2630 } 2631 } 2632add_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 2638if (!found_map ) { 2639// First line contains the count. 2640found_map = true; 2641if (!isdigit ((uint8_t )(* items [1 ]))) { 2642smsg (0 ,_ ("Expected MAP count in %s line %d" ), 2643fname ,lnum ); 2644 } 2645 }else if (do_mapline ) { 2646// Check that every character appears only once. 2647for (p = items [1 ];* p != NUL ;) { 2648int c = mb_ptr2char_adv ((const char ** )& p ); 2649if ((!GA_EMPTY (& spin -> si_map ) 2650&& vim_strchr (spin -> si_map .ga_data ,c ) 2651!= NULL ) 2652|| vim_strchr (p ,c )!= NULL ) { 2653smsg (0 ,_ ("Duplicate character in MAP in %s line %d" ), 2654fname ,lnum ); 2655 } 2656 } 2657 2658// We simply concatenate all the MAP strings, separated by 2659// slashes. 2660ga_concat (& spin -> si_map ,items [1 ]); 2661ga_append (& spin -> si_map ,'/' ); 2662 } 2663 } 2664// Accept "SAL from to" and "SAL from to #comment". 2665else if (is_aff_rule (items ,itemcnt ,"SAL" ,3 )) { 2666if (do_sal ) { 2667// SAL item (sounds-a-like) 2668// Either one of the known keys or a from-to pair. 2669if (strcmp (items [1 ],"followup" )== 0 ) { 2670spin -> si_followup = sal_to_bool (items [2 ]); 2671 }else if (strcmp (items [1 ],"collapse_result" )== 0 ) { 2672spin -> si_collapse = sal_to_bool (items [2 ]); 2673 }else if (strcmp (items [1 ],"remove_accents" )== 0 ) { 2674spin -> si_rem_accents = sal_to_bool (items [2 ]); 2675 }else { 2676// when "to" is "_" it means empty 2677add_fromto (spin ,& spin -> si_sal ,items [1 ], 2678strcmp (items [2 ],"_" )== 0 ?"" 2679 :items [2 ]); 2680 } 2681 } 2682 }else if (is_aff_rule (items ,itemcnt ,"SOFOFROM" ,2 ) 2683&& sofofrom == NULL ) { 2684sofofrom = getroom_save (spin ,items [1 ]); 2685 }else if (is_aff_rule (items ,itemcnt ,"SOFOTO" ,2 ) 2686&& sofoto == NULL ) { 2687sofoto = getroom_save (spin ,items [1 ]); 2688 }else if (strcmp (items [0 ],"COMMON" )== 0 ) { 2689for (int i = 1 ;i < itemcnt ;i ++ ) { 2690if (HASHITEM_EMPTY (hash_find (& spin -> si_commonwords ,items [i ]))) { 2691p = xstrdup (items [i ]); 2692hash_add (& spin -> si_commonwords ,p ); 2693 } 2694 } 2695 }else { 2696smsg (0 ,_ ("Unrecognized or duplicate item in %s line %d: %s" ), 2697fname ,lnum ,items [0 ]); 2698 } 2699 } 2700 } 2701 2702if (fol != NULL || low != NULL || upp != NULL ) { 2703if (spin -> si_clear_chartab ) { 2704// Clear the char type tables, don't want to use any of the 2705// currently used spell properties. 2706init_spell_chartab (); 2707spin -> si_clear_chartab = false; 2708 } 2709 2710xfree (fol ); 2711xfree (low ); 2712xfree (upp ); 2713 } 2714 2715// Use compound specifications of the .aff file for the spell info. 2716if (compmax != 0 ) { 2717aff_check_number (spin -> si_compmax ,compmax ,"COMPOUNDWORDMAX" ); 2718spin -> si_compmax = compmax ; 2719 } 2720 2721if (compminlen != 0 ) { 2722aff_check_number (spin -> si_compminlen ,compminlen ,"COMPOUNDMIN" ); 2723spin -> si_compminlen = compminlen ; 2724 } 2725 2726if (compsylmax != 0 ) { 2727if (syllable == NULL ) { 2728smsg (0 ,"%s" ,_ ("COMPOUNDSYLMAX used without SYLLABLE" )); 2729 } 2730aff_check_number (spin -> si_compsylmax ,compsylmax ,"COMPOUNDSYLMAX" ); 2731spin -> si_compsylmax = compsylmax ; 2732 } 2733 2734if (compoptions != 0 ) { 2735aff_check_number (spin -> si_compoptions ,compoptions ,"COMPOUND options" ); 2736spin -> si_compoptions |=compoptions ; 2737 } 2738 2739if (compflags != NULL ) { 2740process_compflags (spin ,aff ,compflags ); 2741 } 2742 2743// Check that we didn't use too many renumbered flags. 2744if (spin -> si_newcompID < spin -> si_newprefID ) { 2745if (spin -> si_newcompID == 127 || spin -> si_newcompID == 255 ) { 2746msg (_ ("Too many postponed prefixes" ),0 ); 2747 }else if (spin -> si_newprefID == 0 || spin -> si_newprefID == 127 ) { 2748msg (_ ("Too many compound flags" ),0 ); 2749 }else { 2750msg (_ ("Too many postponed prefixes and/or compound flags" ),0 ); 2751 } 2752 } 2753 2754if (syllable != NULL ) { 2755aff_check_string (spin -> si_syllable ,syllable ,"SYLLABLE" ); 2756spin -> si_syllable = syllable ; 2757 } 2758 2759if (sofofrom != NULL || sofoto != NULL ) { 2760if (sofofrom == NULL || sofoto == NULL ) { 2761smsg (0 ,_ ("Missing SOFO%s line in %s" ), 2762sofofrom == NULL ?"FROM" :"TO" ,fname ); 2763 }else if (!GA_EMPTY (& spin -> si_sal )) { 2764smsg (0 ,_ ("Both SAL and SOFO lines in %s" ),fname ); 2765 }else { 2766aff_check_string (spin -> si_sofofr ,sofofrom ,"SOFOFROM" ); 2767aff_check_string (spin -> si_sofoto ,sofoto ,"SOFOTO" ); 2768spin -> si_sofofr = sofofrom ; 2769spin -> si_sofoto = sofoto ; 2770 } 2771 } 2772 2773if (midword != NULL ) { 2774aff_check_string (spin -> si_midword ,midword ,"MIDWORD" ); 2775spin -> si_midword = midword ; 2776 } 2777 2778xfree (pc ); 2779fclose (fd ); 2780return 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{ 2787return 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{ 2796if (entry -> ae_flags != NULL 2797&& (affile -> af_compforbid != 0 || affile -> af_comppermit != 0 )) { 2798for (char * p = entry -> ae_flags ;* p != NUL ;) { 2799char * prevp = p ; 2800unsigned flag = get_affitem (affile -> af_flagtype ,& p ); 2801if (flag == affile -> af_comppermit || flag == affile -> af_compforbid ) { 2802STRMOVE (prevp ,p ); 2803p = prevp ; 2804if (flag == affile -> af_comppermit ) { 2805entry -> ae_comppermit = true; 2806 }else { 2807entry -> ae_compforbid = true; 2808 } 2809 } 2810if (affile -> af_flagtype == AFT_NUM && * p == ',' ) { 2811p ++ ; 2812 } 2813 } 2814if (* entry -> ae_flags == NUL ) { 2815entry -> 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{ 2823return 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{ 2835char * p = item ; 2836 2837unsigned res = get_affitem (flagtype ,& p ); 2838if (res == 0 ) { 2839if (flagtype == AFT_NUM ) { 2840smsg (0 ,_ ("Flag is not a number in %s line %d: %s" ), 2841fname ,lnum ,item ); 2842 }else { 2843smsg (0 ,_ ("Illegal flag in %s line %d: %s" ), 2844fname ,lnum ,item ); 2845 } 2846 } 2847if (* p != NUL ) { 2848smsg (0 ,_ (e_affname ),fname ,lnum ,item ); 2849return 0 ; 2850 } 2851 2852return 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{ 2860int res ; 2861 2862if (flagtype == AFT_NUM ) { 2863if (!ascii_isdigit (** pp )) { 2864 (* pp )++ ;// always advance, avoid getting stuck 2865return 0 ; 2866 } 2867res = getdigits_int (pp , true,0 ); 2868if (res == 0 ) { 2869res = ZERO_FLAG ; 2870 } 2871 }else { 2872res = mb_ptr2char_adv ((const char ** )pp ); 2873if (flagtype == AFT_LONG || (flagtype == AFT_CAPLONG 2874&& res >='A' && res <='Z' )) { 2875if (** pp == NUL ) { 2876return 0 ; 2877 } 2878res = mb_ptr2char_adv ((const char ** )pp )+ (res <<16 ); 2879 } 2880 } 2881return (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{ 2890compitem_T * ci ; 2891int id ; 2892char 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. 2897int len = (int )strlen (compflags )+ 1 ; 2898if (spin -> si_compflags != NULL ) { 2899len += (int )strlen (spin -> si_compflags )+ 1 ; 2900 } 2901char * p = getroom (spin , (size_t )len , false); 2902if (spin -> si_compflags != NULL ) { 2903STRCPY (p ,spin -> si_compflags ); 2904strcat (p ,"/" ); 2905 } 2906spin -> si_compflags = p ; 2907uint8_t * tp = (uint8_t * )p + strlen (p ); 2908 2909for (p = compflags ;* p != NUL ;) { 2910if (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. 2915char * prevp = p ; 2916unsigned flag = get_affitem (aff -> af_flagtype ,& p ); 2917if (flag != 0 ) { 2918// Find the flag in the hashtable. If it was used before, use 2919// the existing ID. Otherwise add a new entry. 2920xmemcpyz (key ,prevp , (size_t )(p - prevp )); 2921hashitem_T * hi = hash_find (& aff -> af_comp ,key ); 2922if (!HASHITEM_EMPTY (hi )) { 2923id = HI2CI (hi )-> ci_newID ; 2924 }else { 2925ci = getroom (spin ,sizeof (compitem_T ), true); 2926STRCPY (ci -> ci_key ,key ); 2927ci -> ci_flag = flag ; 2928// Avoid using a flag ID that has a special meaning in a 2929// regexp (also inside []). 2930do { 2931check_renumber (spin ); 2932id = spin -> si_newcompID -- ; 2933 }while (vim_strchr ("/?*+[]\\-^" ,id )!= NULL ); 2934ci -> ci_newID = id ; 2935hash_add (& aff -> af_comp ,ci -> ci_key ); 2936 } 2937* tp ++ = (uint8_t )id ; 2938 } 2939if (aff -> af_flagtype == AFT_NUM && * p == ',' ) { 2940p ++ ; 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{ 2954if (spin -> si_newprefID == spin -> si_newcompID && spin -> si_newcompID < 128 ) { 2955spin -> si_newprefID = 127 ; 2956spin -> 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{ 2964if (* cntp >=MAXWLEN - 1 ) { 2965emsg (_ (e_too_many_postponed_prefixes_spell )); 2966return FAIL ; 2967 } 2968store_afflist [(* cntp )++ ]= (char )(uint8_t )id ; 2969store_afflist [* cntp ]= NUL ; 2970return 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{ 2976switch (flagtype ) { 2977case AFT_CHAR : 2978return vim_strchr (afflist , (int )flag )!= NULL ; 2979 2980case AFT_CAPLONG : 2981case AFT_LONG : 2982for (char * p = afflist ;* p != NUL ;) { 2983unsigned n = (unsigned )mb_ptr2char_adv ((const char ** )& p ); 2984if ((flagtype == AFT_LONG || (n >='A' && n <='Z' )) 2985&& * p != NUL ) { 2986n = (unsigned )mb_ptr2char_adv ((const char ** )& p )+ (n <<16 ); 2987 } 2988if (n == flag ) { 2989return true; 2990 } 2991 } 2992break ; 2993 2994case AFT_NUM : 2995for (char * p = afflist ;* p != NUL ;) { 2996int digits = getdigits_int (& p , true,0 ); 2997assert (digits >=0 ); 2998unsigned n = (unsigned )digits ; 2999if (n == 0 ) { 3000n = ZERO_FLAG ; 3001 } 3002if (n == flag ) { 3003return true; 3004 } 3005if (* p != NUL ) {// skip over comma 3006p ++ ; 3007 } 3008 } 3009break ; 3010 } 3011return 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{ 3017if (spinval != 0 && spinval != affval ) { 3018smsg (0 ,_ ("%s value differs from what is used in another .aff file" ), 3019name ); 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{ 3026if (spinval != NULL && strcmp (spinval ,affval )!= 0 ) { 3027smsg (0 ,_ ("%s value differs from what is used in another .aff file" ), 3028name ); 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{ 3036if (s1 == NULL || s2 == NULL ) { 3037return s1 == s2 ; 3038 } 3039return 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{ 3046char word [MAXWLEN ]; 3047 3048fromto_T * ftp = GA_APPEND_VIA_PTR (fromto_T ,gap ); 3049spell_casefold (curwin ,from , (int )strlen (from ),word ,MAXWLEN ); 3050ftp -> ft_from = getroom_save (spin ,word ); 3051spell_casefold (curwin ,to , (int )strlen (to ),word ,MAXWLEN ); 3052ftp -> 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{ 3058return 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{ 3064xfree (aff -> af_enc ); 3065 3066// All this trouble to free the "ae_prog" items... 3067for (hashtab_T * ht = & aff -> af_pref ;;ht = & aff -> af_suff ) { 3068int todo = (int )ht -> ht_used ; 3069for (hashitem_T * hi = ht -> ht_array ;todo > 0 ;hi ++ ) { 3070if (!HASHITEM_EMPTY (hi )) { 3071todo -- ; 3072affheader_T * ah = HI2AH (hi ); 3073for (affentry_T * ae = ah -> ah_first ;ae != NULL ;ae = ae -> ae_next ) { 3074vim_regfree (ae -> ae_prog ); 3075 } 3076 } 3077 } 3078if (ht == & aff -> af_suff ) { 3079break ; 3080 } 3081 } 3082 3083hash_clear (& aff -> af_pref ); 3084hash_clear (& aff -> af_suff ); 3085hash_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{ 3092hashtab_T ht ; 3093char line [MAXLINELEN ]; 3094char store_afflist [MAXWLEN ]; 3095char * pc ; 3096char * w ; 3097int lnum = 1 ; 3098int non_ascii = 0 ; 3099int retval = OK ; 3100char message [MAXLINELEN + MAXWLEN ]; 3101int duplicate = 0 ; 3102Timestamp last_msg_time = 0 ; 3103 3104// Open the file. 3105FILE * fd = os_fopen (fname ,"r" ); 3106if (fd == NULL ) { 3107semsg (_ (e_notopen ),fname ); 3108return FAIL ; 3109 } 3110 3111// The hashtable is only used to detect duplicated words. 3112hash_init (& ht ); 3113 3114vim_snprintf (IObuff ,IOSIZE , 3115_ ("Reading dictionary file %s..." ),fname ); 3116spell_message (spin ,IObuff ); 3117 3118// start with a message for the first line 3119spin -> si_msg_count = 999999 ; 3120 3121// Read and ignore the first line: word count. 3122if (vim_fgets (line ,MAXLINELEN ,fd )|| !ascii_isdigit (* skipwhite (line ))) { 3123semsg (_ ("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. 3129while (!vim_fgets (line ,MAXLINELEN ,fd )&& !got_int ) { 3130line_breakcheck (); 3131lnum ++ ; 3132if (line [0 ]== '#' || line [0 ]== '/' ) { 3133continue ;// 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.". 3137int l = (int )strlen (line ); 3138while (l > 0 && (uint8_t )line [l - 1 ] <=' ' ) { 3139l -- ; 3140 } 3141if (l == 0 ) { 3142continue ;// empty line 3143 } 3144line [l ]= NUL ; 3145 3146// Convert from "SET" to 'encoding' when needed. 3147if (spin -> si_conv .vc_type != CONV_NONE ) { 3148pc = string_convert (& spin -> si_conv ,line ,NULL ); 3149if (pc == NULL ) { 3150smsg (0 ,_ ("Conversion failure for word in %s line %d: %s" ), 3151fname ,lnum ,line ); 3152continue ; 3153 } 3154w = pc ; 3155 }else { 3156pc = NULL ; 3157w = line ; 3158 } 3159 3160// Truncate the word at the "/", set "afflist" to what follows. 3161// Replace "\/" by "/" and "\\" by "\". 3162char * afflist = NULL ; 3163for (char * p = w ;* p != NUL ;MB_PTR_ADV (p )) { 3164if (* p == '\\' && (p [1 ]== '\\' || p [1 ]== '/' )) { 3165STRMOVE (p ,p + 1 ); 3166 }else if (* p == '/' ) { 3167* p = NUL ; 3168afflist = p + 1 ; 3169break ; 3170 } 3171 } 3172 3173// Skip non-ASCII words when "spin->si_ascii" is true. 3174if (spin -> si_ascii && has_non_ascii (w )) { 3175non_ascii ++ ; 3176xfree (pc ); 3177continue ; 3178 } 3179 3180// This takes time, print a message every 10000 words, but not more 3181// often than once per second. 3182if (spin -> si_verbose && spin -> si_msg_count > 10000 ) { 3183spin -> si_msg_count = 0 ; 3184if (os_time ()> last_msg_time ) { 3185last_msg_time = os_time (); 3186vim_snprintf (message ,sizeof (message ), 3187_ ("line %6d, word %6d - %s" ), 3188lnum ,spin -> si_foldwcount + spin -> si_keepwcount ,w ); 3189msg_start (); 3190msg_outtrans_long (message ,0 ); 3191msg_clr_eos (); 3192msg_didout = false; 3193msg_col = 0 ; 3194ui_flush (); 3195 } 3196 } 3197 3198// Store the word in the hashtable to be able to find duplicates. 3199char * dw = getroom_save (spin ,w ); 3200if (dw == NULL ) { 3201retval = FAIL ; 3202xfree (pc ); 3203break ; 3204 } 3205 3206hash_T hash = hash_hash (dw ); 3207hashitem_T * hi = hash_lookup (& ht ,dw ,strlen (dw ),hash ); 3208if (!HASHITEM_EMPTY (hi )) { 3209if (p_verbose > 0 ) { 3210smsg (0 ,_ ("Duplicate word in %s line %d: %s" ), 3211fname ,lnum ,dw ); 3212 }else if (duplicate == 0 ) { 3213smsg (0 ,_ ("First duplicate word in %s line %d: %s" ), 3214fname ,lnum ,dw ); 3215 } 3216duplicate ++ ; 3217 }else { 3218hash_add_item (& ht ,hi ,dw ,hash ); 3219 } 3220 3221int flags = 0 ; 3222store_afflist [0 ]= NUL ; 3223int pfxlen = 0 ; 3224int totlen = 0 ; 3225bool need_affix = false; 3226if (afflist != NULL ) { 3227// Extract flags from the affix list. 3228flags |=get_affix_flags (affile ,afflist ); 3229 3230if (affile -> af_needaffix != 0 3231&& flag_in_afflist (affile -> af_flagtype ,afflist , 3232affile -> af_needaffix )) { 3233need_affix = true; 3234 } 3235 3236if (affile -> af_pfxpostpone ) { 3237// Need to store the list of prefix IDs with the word. 3238if (get_pfxlist (affile ,afflist ,store_afflist ,& totlen )== FAIL ) { 3239retval = FAIL ; 3240xfree (pc ); 3241break ; 3242 } 3243pfxlen = totlen ; 3244 } 3245 3246if (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. 3249if (get_compflags (affile ,afflist ,store_afflist ,& totlen )== FAIL ) { 3250retval = FAIL ; 3251xfree (pc ); 3252break ; 3253 } 3254 } 3255 } 3256 3257// Add the word to the word tree(s). 3258if (store_word (spin ,dw ,flags ,spin -> si_region , 3259store_afflist ,need_affix )== FAIL ) { 3260retval = FAIL ; 3261 } 3262 3263if (afflist != NULL ) { 3264// Find all matching suffixes and add the resulting words. 3265// Additionally do matching prefixes that combine. 3266if (store_aff_word (spin ,dw ,afflist ,affile , 3267& affile -> af_suff ,& affile -> af_pref , 3268CONDIT_SUF ,flags ,store_afflist ,pfxlen )== FAIL ) { 3269retval = FAIL ; 3270 } 3271 3272// Find all matching prefixes and add the resulting words. 3273if (store_aff_word (spin ,dw ,afflist ,affile , 3274& affile -> af_pref ,NULL , 3275CONDIT_SUF ,flags ,store_afflist ,pfxlen )== FAIL ) { 3276retval = FAIL ; 3277 } 3278 } 3279 3280xfree (pc ); 3281 } 3282 3283if (duplicate > 0 ) { 3284smsg (0 ,_ ("%d duplicate word(s) in %s" ),duplicate ,fname ); 3285 } 3286if (spin -> si_ascii && non_ascii > 0 ) { 3287smsg (0 ,_ ("Ignored %d word(s) with non-ASCII characters in %s" ), 3288non_ascii ,fname ); 3289 } 3290hash_clear (& ht ); 3291 3292fclose (fd ); 3293return 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{ 3300int flags = 0 ; 3301 3302if (affile -> af_keepcase != 0 3303&& flag_in_afflist (affile -> af_flagtype ,afflist , 3304affile -> af_keepcase )) { 3305flags |=WF_KEEPCAP |WF_FIXCAP ; 3306 } 3307if (affile -> af_rare != 0 3308&& flag_in_afflist (affile -> af_flagtype ,afflist ,affile -> af_rare )) { 3309flags |=WF_RARE ; 3310 } 3311if (affile -> af_bad != 0 3312&& flag_in_afflist (affile -> af_flagtype ,afflist ,affile -> af_bad )) { 3313flags |=WF_BANNED ; 3314 } 3315if (affile -> af_needcomp != 0 3316&& flag_in_afflist (affile -> af_flagtype ,afflist , 3317affile -> af_needcomp )) { 3318flags |=WF_NEEDCOMP ; 3319 } 3320if (affile -> af_comproot != 0 3321&& flag_in_afflist (affile -> af_flagtype ,afflist , 3322affile -> af_comproot )) { 3323flags |=WF_COMPROOT ; 3324 } 3325if (affile -> af_nosuggest != 0 3326&& flag_in_afflist (affile -> af_flagtype ,afflist , 3327affile -> af_nosuggest )) { 3328flags |=WF_NOSUGGEST ; 3329 } 3330return 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{ 3339char key [AH_KEY_LEN ]; 3340 3341for (char * p = afflist ;* p != NUL ;) { 3342char * prevp = p ; 3343if (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. 3346xmemcpyz (key ,prevp , (size_t )(p - prevp )); 3347hashitem_T * hi = hash_find (& affile -> af_pref ,key ); 3348if (!HASHITEM_EMPTY (hi )) { 3349int id = HI2AH (hi )-> ah_newID ; 3350if (id != 0 && store_afflist_add (store_afflist ,cntp ,id )== FAIL ) { 3351return FAIL ; 3352 } 3353 } 3354 } 3355if (affile -> af_flagtype == AFT_NUM && * p == ',' ) { 3356p ++ ; 3357 } 3358 } 3359 3360return 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{ 3369char key [AH_KEY_LEN ]; 3370 3371for (char * p = afflist ;* p != NUL ;) { 3372char * prevp = p ; 3373if (get_affitem (affile -> af_flagtype ,& p )!= 0 ) { 3374// A flag is a compound flag if it appears in "af_comp". 3375xmemcpyz (key ,prevp , (size_t )(p - prevp )); 3376hashitem_T * hi = hash_find (& affile -> af_comp ,key ); 3377if (!HASHITEM_EMPTY (hi ) 3378&& store_afflist_add (store_afflist ,cntp ,HI2CI (hi )-> ci_newID )== FAIL ) { 3379return FAIL ; 3380 } 3381 } 3382if (affile -> af_flagtype == AFT_NUM && * p == ',' ) { 3383p ++ ; 3384 } 3385 } 3386 3387return 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 , 3406hashtab_T * ht ,hashtab_T * xht ,int condit ,int flags ,char * pfxlist , 3407int pfxlen ) 3408{ 3409affentry_T * ae ; 3410char newword [MAXWLEN ]; 3411int retval = OK ; 3412int j ; 3413char store_afflist [MAXWLEN ]; 3414char pfx_pfxlist [MAXWLEN ]; 3415size_t wordlen = strlen (word ); 3416 3417int todo = (int )ht -> ht_used ; 3418for (hashitem_T * hi = ht -> ht_array ;todo > 0 && retval == OK ;hi ++ ) { 3419if (!HASHITEM_EMPTY (hi )) { 3420todo -- ; 3421affheader_T * ah = HI2AH (hi ); 3422 3423// Check that the affix combines, if required, and that the word 3424// supports this affix. 3425if (((condit & CONDIT_COMB )== 0 || ah -> ah_combine ) 3426&& flag_in_afflist (affile -> af_flagtype ,afflist , 3427ah -> ah_flag )) { 3428// Loop over all affix entries with this name. 3429for (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. 3440if ((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 , 3451ae -> ae_flags ,affile -> af_circumfix )))) { 3452// Match. Remove the chop and add the affix. 3453if (xht == NULL ) { 3454// prefix: chop/add at the start of the word 3455if (ae -> ae_add == NULL ) { 3456* newword = NUL ; 3457 }else { 3458xstrlcpy (newword ,ae -> ae_add ,MAXWLEN ); 3459 } 3460char * p = word ; 3461if (ae -> ae_chop != NULL ) { 3462// Skip chop string. 3463int i = mb_charlen (ae -> ae_chop ); 3464for (;i > 0 ;i -- ) { 3465MB_PTR_ADV (p ); 3466 } 3467 } 3468// Note: this silently truncates the buffer, but this should 3469// not happen in practice 3470xstrlcat (newword ,p ,MAXWLEN ); 3471 }else { 3472// suffix: chop/add at the end of the word 3473xstrlcpy (newword ,word ,MAXWLEN ); 3474if (ae -> ae_chop != NULL ) { 3475// Remove chop string. 3476char * p = newword + strlen (newword ); 3477int i = mb_charlen (ae -> ae_chop ); 3478for (;i > 0 ;i -- ) { 3479MB_PTR_BACK (newword ,p ); 3480 } 3481* p = NUL ; 3482 } 3483if (ae -> ae_add != NULL ) { 3484// Note: this silently truncates the buffer, but this should 3485// not happen in practice 3486xstrlcat (newword ,ae -> ae_add ,MAXWLEN ); 3487 } 3488 } 3489 3490int use_flags = flags ; 3491char * use_pfxlist = pfxlist ; 3492int use_pfxlen = pfxlen ; 3493bool need_affix = false; 3494int use_condit = condit |CONDIT_COMB |CONDIT_AFF ; 3495if (ae -> ae_flags != NULL ) { 3496// Extract flags from the affix list. 3497use_flags |=get_affix_flags (affile ,ae -> ae_flags ); 3498 3499if (affile -> af_needaffix != 0 3500&& flag_in_afflist (affile -> af_flagtype ,ae -> ae_flags , 3501affile -> af_needaffix )) { 3502need_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. 3508if (affile -> af_circumfix != 0 3509&& flag_in_afflist (affile -> af_flagtype ,ae -> ae_flags , 3510affile -> af_circumfix )) { 3511use_condit |=CONDIT_CFIX ; 3512if ((condit & CONDIT_CFIX )== 0 ) { 3513need_affix = true; 3514 } 3515 } 3516 3517if (affile -> af_pfxpostpone 3518|| spin -> si_compflags != NULL ) { 3519int listlen = 0 ; 3520 3521if (affile -> af_pfxpostpone ) { 3522// Get prefix IDS from the affix list. 3523if (get_pfxlist (affile ,ae -> ae_flags , 3524store_afflist ,& listlen )== FAIL ) { 3525retval = FAIL ; 3526break ; 3527 } 3528use_pfxlen = listlen ; 3529 }else { 3530use_pfxlen = 0 ; 3531 } 3532use_pfxlist = store_afflist ; 3533 3534// Combine the prefix IDs. Avoid adding the 3535// same ID twice. 3536for (int i = 0 ;i < pfxlen ;i ++ ) { 3537for (j = 0 ;j < use_pfxlen ;j ++ ) { 3538if (pfxlist [i ]== use_pfxlist [j ]) { 3539break ; 3540 } 3541 } 3542if (j == use_pfxlen 3543&& store_afflist_add (use_pfxlist ,& listlen ,pfxlist [i ])== FAIL ) { 3544retval = FAIL ; 3545break ; 3546 } 3547use_pfxlen = listlen ; 3548 } 3549if (retval == FAIL ) { 3550break ; 3551 } 3552 3553if (spin -> si_compflags != NULL ) { 3554// Get compound IDS from the affix list. 3555if (get_compflags (affile ,ae -> ae_flags , 3556use_pfxlist ,& listlen )== FAIL ) { 3557retval = FAIL ; 3558break ; 3559 } 3560 }else { 3561use_pfxlist [use_pfxlen ]= NUL ; 3562 } 3563if (retval == FAIL ) { 3564break ; 3565 } 3566 3567// Combine the list of compound flags. 3568// Concatenate them to the prefix IDs list. 3569// Avoid adding the same ID twice. 3570for (int i = pfxlen ;pfxlist [i ]!= NUL ;i ++ ) { 3571for (j = use_pfxlen ;use_pfxlist [j ]!= NUL ;j ++ ) { 3572if (pfxlist [i ]== use_pfxlist [j ]) { 3573break ; 3574 } 3575 } 3576if (use_pfxlist [j ]== NUL 3577&& store_afflist_add (use_pfxlist ,& listlen ,pfxlist [i ])== FAIL ) { 3578retval = FAIL ; 3579break ; 3580 } 3581 } 3582if (retval == FAIL ) { 3583break ; 3584 } 3585 } 3586 } 3587 3588// Obey a "COMPOUNDFORBIDFLAG" of the affix: don't 3589// use the compound flags. 3590if (use_pfxlist != NULL && ae -> ae_compforbid ) { 3591xmemcpyz (pfx_pfxlist ,use_pfxlist , (size_t )use_pfxlen ); 3592use_pfxlist = pfx_pfxlist ; 3593 } 3594 3595// When there are postponed prefixes... 3596if (spin -> si_prefroot != NULL 3597&& spin -> si_prefroot -> wn_sibling != NULL ) { 3598// ... add a flag to indicate an affix was used. 3599use_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. 3604if (!ah -> ah_combine && use_pfxlist != NULL ) { 3605use_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. 3612if (spin -> si_compflags != NULL && !ae -> ae_comppermit ) { 3613if (xht != NULL ) { 3614use_flags |=WF_NOCOMPAFT ; 3615 }else { 3616use_flags |=WF_NOCOMPBEF ; 3617 } 3618 } 3619 3620// Store the modified word. 3621if (store_word (spin ,newword ,use_flags , 3622spin -> si_region ,use_pfxlist , 3623need_affix )== FAIL ) { 3624retval = FAIL ; 3625 } 3626 3627// When added a prefix or a first suffix and the affix 3628// has flags may add a(nother) suffix. RECURSIVE! 3629if ((condit & CONDIT_SUF )&& ae -> ae_flags != NULL ) { 3630if (store_aff_word (spin ,newword ,ae -> ae_flags , 3631affile ,& affile -> af_suff ,xht , 3632use_condit & (xht == NULL 3633 ? ~0 : ~CONDIT_SUF ), 3634use_flags ,use_pfxlist ,pfxlen )== FAIL ) { 3635retval = 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! 3642if (xht != NULL && ah -> ah_combine ) { 3643if (store_aff_word (spin ,newword , 3644afflist ,affile , 3645xht ,NULL ,use_condit , 3646use_flags ,use_pfxlist , 3647pfxlen )== FAIL 3648|| (ae -> ae_flags != NULL 3649&& store_aff_word (spin ,newword , 3650ae -> ae_flags ,affile , 3651xht ,NULL ,use_condit , 3652use_flags ,use_pfxlist , 3653pfxlen )== FAIL )) { 3654retval = FAIL ; 3655 } 3656 } 3657 } 3658 } 3659 } 3660 } 3661 } 3662 3663return retval ; 3664} 3665 3666// Read a file with a list of words. 3667static int spell_read_wordfile (spellinfo_T * spin ,char * fname ) 3668{ 3669linenr_T lnum = 0 ; 3670char rline [MAXLINELEN ]; 3671char * line ; 3672char * pc = NULL ; 3673int retval = OK ; 3674bool did_word = false; 3675int non_ascii = 0 ; 3676 3677// Open the file. 3678FILE * fd = os_fopen (fname ,"r" ); 3679if (fd == NULL ) { 3680semsg (_ (e_notopen ),fname ); 3681return FAIL ; 3682 } 3683 3684vim_snprintf (IObuff ,IOSIZE ,_ ("Reading word file %s..." ),fname ); 3685spell_message (spin ,IObuff ); 3686 3687// Read all the lines in the file one by one. 3688while (!vim_fgets (rline ,MAXLINELEN ,fd )&& !got_int ) { 3689line_breakcheck (); 3690lnum ++ ; 3691 3692// Skip comment lines. 3693if (* rline == '#' ) { 3694continue ; 3695 } 3696 3697// Remove CR, LF and white space from the end. 3698int l = (int )strlen (rline ); 3699while (l > 0 && (uint8_t )rline [l - 1 ] <=' ' ) { 3700l -- ; 3701 } 3702if (l == 0 ) { 3703continue ;// empty or blank line 3704 } 3705rline [l ]= NUL ; 3706 3707// Convert from "/encoding={encoding}" to 'encoding' when needed. 3708xfree (pc ); 3709if (spin -> si_conv .vc_type != CONV_NONE ) { 3710pc = string_convert (& spin -> si_conv ,rline ,NULL ); 3711if (pc == NULL ) { 3712smsg (0 ,_ ("Conversion failure for word in %s line %" PRIdLINENR ": %s" ), 3713fname ,lnum ,rline ); 3714continue ; 3715 } 3716line = pc ; 3717 }else { 3718pc = NULL ; 3719line = rline ; 3720 } 3721 3722if (* line == '/' ) { 3723line ++ ; 3724if (strncmp (line ,"encoding=" ,9 )== 0 ) { 3725if (spin -> si_conv .vc_type != CONV_NONE ) { 3726smsg (0 ,_ ("Duplicate /encoding= line ignored in %s line %" PRIdLINENR ": %s" ), 3727fname ,lnum ,line - 1 ); 3728 }else if (did_word ) { 3729smsg (0 ,_ ("/encoding= line after word ignored in %s line %" PRIdLINENR ": %s" ), 3730fname ,lnum ,line - 1 ); 3731 }else { 3732// Setup for conversion to 'encoding'. 3733line += 9 ; 3734char * enc = enc_canonize (line ); 3735if (!spin -> si_ascii 3736&& convert_setup (& spin -> si_conv ,enc ,p_enc )== FAIL ) { 3737smsg (0 ,_ ("Conversion in %s not supported: from %s to %s" ), 3738fname ,line ,p_enc ); 3739 } 3740xfree (enc ); 3741spin -> si_conv .vc_fail = true; 3742 } 3743continue ; 3744 } 3745 3746if (strncmp (line ,"regions=" ,8 )== 0 ) { 3747if (spin -> si_region_count > 1 ) { 3748smsg (0 ,_ ("Duplicate /regions= line ignored in %s line %" PRIdLINENR ": %s" ), 3749fname ,lnum ,line ); 3750 }else { 3751line += 8 ; 3752if (strlen (line )> MAXREGIONS * 2 ) { 3753smsg (0 ,_ ("Too many regions in %s line %" PRIdLINENR ": %s" ), 3754fname ,lnum ,line ); 3755 }else { 3756spin -> si_region_count = (int )strlen (line ) /2 ; 3757STRCPY (spin -> si_region_name ,line ); 3758 3759// Adjust the mask for a word valid in all regions. 3760spin -> si_region = (1 <<spin -> si_region_count )- 1 ; 3761 } 3762 } 3763continue ; 3764 } 3765 3766smsg (0 ,_ ("/ line ignored in %s line %" PRIdLINENR ": %s" ), 3767fname ,lnum ,line - 1 ); 3768continue ; 3769 } 3770 3771int flags = 0 ; 3772int regionmask = spin -> si_region ; 3773 3774// Check for flags and region after a slash. 3775char * p = vim_strchr (line ,'/' ); 3776if (p != NULL ) { 3777* p ++ = NUL ; 3778while (* p != NUL ) { 3779if (* p == '=' ) {// keep-case word 3780flags |=WF_KEEPCAP |WF_FIXCAP ; 3781 }else if (* p == '!' ) {// Bad, bad, wicked word. 3782flags |=WF_BANNED ; 3783 }else if (* p == '?' ) {// Rare word. 3784flags |=WF_RARE ; 3785 }else if (ascii_isdigit ((uint8_t )(* p ))) {// region number(s) 3786if ((flags & WF_REGION )== 0 ) {// first one 3787regionmask = 0 ; 3788 } 3789flags |=WF_REGION ; 3790 3791l = (uint8_t )(* p )- '0' ; 3792if (l == 0 || l > spin -> si_region_count ) { 3793smsg (0 ,_ ("Invalid region nr in %s line %" PRIdLINENR ": %s" ), 3794fname ,lnum ,p ); 3795break ; 3796 } 3797regionmask |=1 << (l - 1 ); 3798 }else { 3799smsg (0 ,_ ("Unrecognized flags in %s line %" PRIdLINENR ": %s" ), 3800fname ,lnum ,p ); 3801break ; 3802 } 3803p ++ ; 3804 } 3805 } 3806 3807// Skip non-ASCII words when "spin->si_ascii" is true. 3808if (spin -> si_ascii && has_non_ascii (line )) { 3809non_ascii ++ ; 3810continue ; 3811 } 3812 3813// Normal word: store it. 3814if (store_word (spin ,line ,flags ,regionmask ,NULL , false)== FAIL ) { 3815retval = FAIL ; 3816break ; 3817 } 3818did_word = true; 3819 } 3820 3821xfree (pc ); 3822fclose (fd ); 3823 3824if (spin -> si_ascii && non_ascii > 0 ) { 3825vim_snprintf (IObuff ,IOSIZE , 3826_ ("Ignored %d words with non-ASCII characters" ),non_ascii ); 3827spell_message (spin ,IObuff ); 3828 } 3829 3830return 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 ) 3842FUNC_ATTR_NONNULL_RET 3843{ 3844sblock_T * bl = spin -> si_blocks ; 3845 3846assert (len <=SBLOCKSIZE ); 3847 3848if (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). 3851bl -> sb_used = (int )(((size_t )bl -> sb_used + sizeof (char * )- 1 )& ~(sizeof (char * )- 1 )); 3852 } 3853 3854if (bl == NULL || (size_t )bl -> sb_used + len > SBLOCKSIZE ) { 3855// Allocate a block of memory. It is not freed until much later. 3856bl = xcalloc (1 , offsetof(sblock_T ,sb_data )+ SBLOCKSIZE + 1 ); 3857bl -> sb_next = spin -> si_blocks ; 3858spin -> si_blocks = bl ; 3859bl -> sb_used = 0 ; 3860spin -> si_blocks_cnt ++ ; 3861 } 3862 3863char * p = bl -> sb_data + bl -> sb_used ; 3864bl -> sb_used += (int )len ; 3865 3866return 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{ 3874const size_t s_size = strlen (s )+ 1 ; 3875return 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{ 3881while (bl != NULL ) { 3882sblock_T * next = bl -> sb_next ; 3883xfree (bl ); 3884bl = 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 ) 3891FUNC_ATTR_NONNULL_RET 3892{ 3893return (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{ 3900if (!utf_valid_string (word ,end )) { 3901return false; 3902 } 3903for (const char * p = word ;* p != NUL && p < end ;p += utfc_ptr2len (p )) { 3904if ((uint8_t )(* p )< ' ' || (p [0 ]== '/' && p [1 ]== NUL )) { 3905return false; 3906 } 3907 } 3908return 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 , 3924bool need_affix ) 3925{ 3926int len = (int )strlen (word ); 3927int ct = captype (word ,word + len ); 3928char foldword [MAXWLEN ]; 3929int res = OK ; 3930 3931// Avoid adding illegal bytes to the word tree. 3932if (!valid_spell_word (word ,word + len )) { 3933return FAIL ; 3934 } 3935 3936spell_casefold (curwin ,word ,len ,foldword ,MAXWLEN ); 3937for (const char * p = pfxlist ;res == OK ;p ++ ) { 3938if (!need_affix || (p != NULL && * p != NUL )) { 3939res = tree_add_word (spin ,foldword ,spin -> si_foldroot ,ct |flags , 3940region ,p == NULL ?0 :* p ); 3941 } 3942if (p == NULL || * p == NUL ) { 3943break ; 3944 } 3945 } 3946spin -> si_foldwcount ++ ; 3947 3948if (res == OK && (ct == WF_KEEPCAP || (flags & WF_KEEPCAP ))) { 3949for (const char * p = pfxlist ;res == OK ;p ++ ) { 3950if (!need_affix || (p != NULL && * p != NUL )) { 3951res = tree_add_word (spin ,word ,spin -> si_keeproot ,flags , 3952region ,p == NULL ?0 :* p ); 3953 } 3954if (p == NULL || * p == NUL ) { 3955break ; 3956 } 3957 } 3958spin -> si_keepwcount ++ ; 3959 } 3960return 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 , 3968int region ,int affixID ) 3969{ 3970wordnode_T * node = root ; 3971wordnode_T ** prev = NULL ; 3972 3973// Add each byte of the word to the tree, including the NUL at the end. 3974for (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). 3978if (node != NULL && node -> wn_refs > 1 ) { 3979node -> wn_refs -- ; 3980wordnode_T ** copyprev = prev ; 3981for (wordnode_T * copyp = node ;copyp != NULL ;copyp = copyp -> wn_sibling ) { 3982// Allocate a new node and copy the info. 3983wordnode_T * np = get_wordnode (spin ); 3984if (np == NULL ) { 3985return FAIL ; 3986 } 3987np -> wn_child = copyp -> wn_child ; 3988if (np -> wn_child != NULL ) { 3989np -> wn_child -> wn_refs ++ ;// child gets extra ref 3990 } 3991np -> wn_byte = copyp -> wn_byte ; 3992if (np -> wn_byte == NUL ) { 3993np -> wn_flags = copyp -> wn_flags ; 3994np -> wn_region = copyp -> wn_region ; 3995np -> wn_affixID = copyp -> wn_affixID ; 3996 } 3997 3998// Link the new node in the list, there will be one ref. 3999np -> wn_refs = 1 ; 4000if (copyprev != NULL ) { 4001* copyprev = np ; 4002 } 4003copyprev = & np -> wn_sibling ; 4004 4005// Let "node" point to the head of the copied list. 4006if (copyp == node ) { 4007node = 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. 4016while (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 ))))))) { 4027prev = & node -> wn_sibling ; 4028node = * prev ; 4029 } 4030if (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. 4038wordnode_T * np = get_wordnode (spin ); 4039if (np == NULL ) { 4040return FAIL ; 4041 } 4042np -> 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). 4048if (node == NULL ) { 4049np -> wn_refs = 1 ; 4050 }else { 4051np -> wn_refs = node -> wn_refs ; 4052node -> wn_refs = 1 ; 4053 } 4054if (prev != NULL ) { 4055* prev = np ; 4056 } 4057np -> wn_sibling = node ; 4058node = np ; 4059 } 4060 4061if (word [i ]== NUL ) { 4062node -> wn_flags = (uint16_t )flags ; 4063node -> wn_region |= (int16_t )region ; 4064node -> wn_affixID = (uint8_t )affixID ; 4065break ; 4066 } 4067prev = & node -> wn_child ; 4068node = * prev ; 4069 } 4070#ifdef SPELL_PRINTTREE 4071smsg (0 ,"Added \"%s\"" ,word ); 4072spell_print_tree (root -> wn_sibling ); 4073#endif 4074 4075// count nr of words added since last message 4076spin -> si_msg_count ++ ; 4077 4078if (spin -> si_compress_cnt > 1 ) { 4079if (-- spin -> si_compress_cnt == 1 ) { 4080// Did enough words to lower the block count limit. 4081spin -> 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 4096if (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. 4105spin -> si_blocks_cnt -= compress_inc ; 4106spin -> si_compress_cnt = compress_added ; 4107 4108if (spin -> si_verbose ) { 4109msg_start (); 4110msg_puts (_ (msg_compressing )); 4111msg_clr_eos (); 4112msg_didout = false; 4113msg_col = 0 ; 4114ui_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. 4121wordtree_compress (spin ,spin -> si_foldroot ,"case-folded" ); 4122if (affixID >=0 ) { 4123wordtree_compress (spin ,spin -> si_keeproot ,"keep-case" ); 4124 } 4125 } 4126 4127return 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{ 4135wordnode_T * n ; 4136 4137if (spin -> si_first_free == NULL ) { 4138n = (wordnode_T * )getroom (spin ,sizeof (wordnode_T ), true); 4139 }else { 4140n = spin -> si_first_free ; 4141spin -> si_first_free = n -> wn_child ; 4142CLEAR_POINTER (n ); 4143spin -> si_free_count -- ; 4144 } 4145#ifdef SPELL_PRINTTREE 4146if (n != NULL ) { 4147n -> wn_nr = ++ spin -> si_wordnode_nr ; 4148 } 4149#endif 4150return 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 ) 4158FUNC_ATTR_NONNULL_ALL 4159{ 4160int cnt = 0 ; 4161 4162if (-- node -> wn_refs == 0 ) { 4163for (wordnode_T * np = node ;np != NULL ;np = np -> wn_sibling ) { 4164if (np -> wn_child != NULL ) { 4165cnt += deref_wordnode (spin ,np -> wn_child ); 4166 } 4167free_wordnode (spin ,np ); 4168cnt ++ ; 4169 } 4170cnt ++ ;// length field 4171 } 4172return 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 ) 4178FUNC_ATTR_NONNULL_ALL 4179{ 4180n -> wn_child = spin -> si_first_free ; 4181spin -> si_first_free = n ; 4182spin -> 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 ) 4187FUNC_ATTR_NONNULL_ALL 4188{ 4189hashtab_T ht ; 4190int tot = 0 ; 4191long perc ; 4192 4193// Skip the root itself, it's not actually used. The first sibling is the 4194// start of the tree. 4195if (root -> wn_sibling == NULL ) { 4196return ; 4197 } 4198 4199hash_init (& ht ); 4200const int n = node_compress (spin ,root -> wn_sibling ,& ht ,& tot ); 4201 4202#ifndef SPELL_PRINTTREE 4203if (spin -> si_verbose || p_verbose > 2 ) 4204#endif 4205 { 4206if (tot > 1000000 ) { 4207perc = (tot - n ) / (tot /100 ); 4208 }else if (tot == 0 ) { 4209perc = 0 ; 4210 }else { 4211perc = (tot - n )* 100 /tot ; 4212 } 4213vim_snprintf (IObuff ,IOSIZE , 4214_ ("Compressed %s: %d of %d nodes; %d (%ld%%) remaining" ), 4215name ,n ,tot ,tot - n ,perc ); 4216spell_message (spin ,IObuff ); 4217 } 4218#ifdef SPELL_PRINTTREE 4219spell_print_tree (root -> wn_sibling ); 4220#endif 4221hash_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 ) 4229FUNC_ATTR_NONNULL_ALL 4230{ 4231wordnode_T * tp ; 4232wordnode_T * child ; 4233int len = 0 ; 4234unsigned n ; 4235int 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. 4241for (wordnode_T * np = node ;np != NULL && !got_int ;np = np -> wn_sibling ) { 4242len ++ ; 4243if ((child = np -> wn_child )!= NULL ) { 4244// Compress the child first. This fills hashkey. 4245compressed += node_compress (spin ,child ,ht ,tot ); 4246 4247// Try to find an identical child. 4248hash_T hash = hash_hash ((char * )child -> wn_u1 .hashkey ); 4249hashitem_T * hi = hash_lookup (ht , (const char * )child -> wn_u1 .hashkey , 4250strlen ((char * )child -> wn_u1 .hashkey ),hash ); 4251if (!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. 4255for (tp = HI2WN (hi );tp != NULL ;tp = tp -> wn_u2 .next ) { 4256if (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. 4260tp -> wn_refs ++ ; 4261compressed += deref_wordnode (spin ,child ); 4262np -> wn_child = tp ; 4263break ; 4264 } 4265 } 4266if (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. 4270tp = HI2WN (hi ); 4271child -> wn_u2 .next = tp -> wn_u2 .next ; 4272tp -> wn_u2 .next = child ; 4273 } 4274 }else { 4275// No other child has this hash value, add it to the 4276// hashtable. 4277hash_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. 4286node -> wn_u1 .hashkey [0 ]= (uint8_t )len ; 4287unsigned nr = 0 ; 4288for (wordnode_T * np = node ;np != NULL ;np = np -> wn_sibling ) { 4289if (np -> wn_byte == NUL ) { 4290// end node: use wn_flags, wn_region and wn_affixID 4291n = (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 4294n = (unsigned )(np -> wn_byte + ((uintptr_t )np -> wn_child <<8 )); 4295 } 4296nr = nr * 101 + n ; 4297 } 4298 4299// Avoid NUL bytes, it terminates the hash key. 4300n = nr & 0xff ; 4301node -> wn_u1 .hashkey [1 ]= n == 0 ?1 : (uint8_t )n ; 4302n = (nr >>8 )& 0xff ; 4303node -> wn_u1 .hashkey [2 ]= n == 0 ?1 : (uint8_t )n ; 4304n = (nr >>16 )& 0xff ; 4305node -> wn_u1 .hashkey [3 ]= n == 0 ?1 : (uint8_t )n ; 4306n = (nr >>24 )& 0xff ; 4307node -> wn_u1 .hashkey [4 ]= n == 0 ?1 : (uint8_t )n ; 4308node -> wn_u1 .hashkey [5 ]= NUL ; 4309 4310// Check for CTRL-C pressed now and then. 4311veryfast_breakcheck (); 4312 4313return 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{ 4319wordnode_T * p1 ; 4320wordnode_T * p2 ; 4321 4322for (p1 = n1 ,p2 = n2 ;p1 != NULL && p2 != NULL ; 4323p1 = p1 -> wn_sibling ,p2 = p2 -> wn_sibling ) { 4324if (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 ))) { 4330break ; 4331 } 4332 } 4333 4334return 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{ 4340fromto_T * p1 = (fromto_T * )s1 ; 4341fromto_T * p2 = (fromto_T * )s2 ; 4342 4343return 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{ 4351int retval = OK ; 4352int regionmask ; 4353 4354FILE * fd = os_fopen (fname ,"w" ); 4355if (fd == NULL ) { 4356semsg (_ (e_notopen ),fname ); 4357return FAIL ; 4358 } 4359 4360// <HEADER>: <fileID> <versionnr> 4361// <fileID> 4362size_t fwv = fwrite (VIMSPELLMAGIC ,VIMSPELLMAGICL ,1 ,fd ); 4363if (fwv != 1 ) { 4364// Catch first write error, don't try writing more. 4365 gototheend ; 4366 } 4367 4368putc (VIMSPELLVERSION ,fd );// <versionnr> 4369 4370// <SECTIONS>: <section> ... <sectionend> 4371 4372// SN_INFO: <infotext> 4373if (spin -> si_info != NULL ) { 4374putc (SN_INFO ,fd );// <sectionID> 4375putc (0 ,fd );// <sectionflags> 4376size_t i = strlen (spin -> si_info ); 4377put_bytes (fd ,i ,4 );// <sectionlen> 4378fwv &=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. 4383if (spin -> si_region_count > 1 ) { 4384putc (SN_REGION ,fd );// <sectionID> 4385putc (SNF_REQUIRED ,fd );// <sectionflags> 4386size_t l = (size_t )spin -> si_region_count * 2 ; 4387put_bytes (fd ,l ,4 );// <sectionlen> 4388fwv &=fwrite (spin -> si_region_name ,l ,1 ,fd ); 4389// <regionname> ... 4390regionmask = (1 <<spin -> si_region_count )- 1 ; 4391 }else { 4392regionmask = 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. 4404if (!spin -> si_ascii && !spin -> si_add ) { 4405char folchars [128 * 8 ]; 4406 4407putc (SN_CHARFLAGS ,fd );// <sectionID> 4408putc (SNF_REQUIRED ,fd );// <sectionflags> 4409 4410// Form the <folchars> string first, we need to know its length. 4411size_t l = 0 ; 4412for (size_t i = 128 ;i < 256 ;i ++ ) { 4413l += (size_t )utf_char2bytes (spelltab .st_fold [i ],folchars + l ); 4414 } 4415put_bytes (fd ,1 + 128 + 2 + l ,4 );// <sectionlen> 4416 4417fputc (128 ,fd );// <charflagslen> 4418for (size_t i = 128 ;i < 256 ;i ++ ) { 4419int flags = 0 ; 4420if (spelltab .st_isw [i ]) { 4421flags |=CF_WORD ; 4422 } 4423if (spelltab .st_isu [i ]) { 4424flags |=CF_UPPER ; 4425 } 4426fputc (flags ,fd );// <charflags> 4427 } 4428 4429put_bytes (fd ,l ,2 );// <folcharslen> 4430fwv &=fwrite (folchars ,l ,1 ,fd );// <folchars> 4431 } 4432 4433// SN_MIDWORD: <midword> 4434if (spin -> si_midword != NULL ) { 4435putc (SN_MIDWORD ,fd );// <sectionID> 4436putc (SNF_REQUIRED ,fd );// <sectionflags> 4437 4438size_t i = strlen (spin -> si_midword ); 4439put_bytes (fd ,i ,4 );// <sectionlen> 4440fwv &=fwrite (spin -> si_midword ,i ,1 ,fd ); 4441// <midword> 4442 } 4443 4444// SN_PREFCOND: <prefcondcnt> <prefcond> ... 4445if (!GA_EMPTY (& spin -> si_prefcond )) { 4446putc (SN_PREFCOND ,fd );// <sectionID> 4447putc (SNF_REQUIRED ,fd );// <sectionflags> 4448 4449size_t l = (size_t )write_spell_prefcond (NULL ,& spin -> si_prefcond ,& fwv ); 4450put_bytes (fd ,l ,4 );// <sectionlen> 4451 4452write_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 4462for (unsigned round = 1 ;round <=3 ;round ++ ) { 4463garray_T * gap ; 4464if (round == 1 ) { 4465gap = & spin -> si_rep ; 4466 }else if (round == 2 ) { 4467// Don't write SN_SAL when using a SN_SOFO section 4468if (spin -> si_sofofr != NULL && spin -> si_sofoto != NULL ) { 4469continue ; 4470 } 4471gap = & spin -> si_sal ; 4472 }else { 4473gap = & spin -> si_repsal ; 4474 } 4475 4476// Don't write the section if there are no items. 4477if (GA_EMPTY (gap )) { 4478continue ; 4479 } 4480 4481// Sort the REP/REPSAL items. 4482if (round != 2 ) { 4483qsort (gap -> ga_data , (size_t )gap -> ga_len , 4484sizeof (fromto_T ),rep_compare ); 4485 } 4486 4487int sect_id = round == 1 ?SN_REP : (round == 2 ?SN_SAL :SN_REPSAL ); 4488putc (sect_id ,fd );// <sectionID> 4489 4490// This is for making suggestions, section is not required. 4491putc (0 ,fd );// <sectionflags> 4492 4493// Compute the length of what follows. 4494size_t l = 2 ;// count <repcount> or <salcount> 4495assert (gap -> ga_len >=0 ); 4496for (size_t i = 0 ;i < (size_t )gap -> ga_len ;i ++ ) { 4497fromto_T * ftp = & ((fromto_T * )gap -> ga_data )[i ]; 4498l += 1 + strlen (ftp -> ft_from );// count <*fromlen> and <*from> 4499l += 1 + strlen (ftp -> ft_to );// count <*tolen> and <*to> 4500 } 4501if (round == 2 ) { 4502l ++ ;// count <salflags> 4503 } 4504put_bytes (fd ,l ,4 );// <sectionlen> 4505 4506if (round == 2 ) { 4507int i = 0 ; 4508if (spin -> si_followup ) { 4509i |=SAL_F0LLOWUP ; 4510 } 4511if (spin -> si_collapse ) { 4512i |=SAL_COLLAPSE ; 4513 } 4514if (spin -> si_rem_accents ) { 4515i |=SAL_REM_ACCENTS ; 4516 } 4517putc (i ,fd );// <salflags> 4518 } 4519 4520put_bytes (fd , (uintmax_t )gap -> ga_len ,2 );// <repcount> or <salcount> 4521for (size_t i = 0 ;i < (size_t )gap -> ga_len ;i ++ ) { 4522// <rep> : <repfromlen> <repfrom> <reptolen> <repto> 4523// <sal> : <salfromlen> <salfrom> <saltolen> <salto> 4524fromto_T * ftp = & ((fromto_T * )gap -> ga_data )[i ]; 4525for (unsigned rr = 1 ;rr <=2 ;rr ++ ) { 4526char * p = rr == 1 ?ftp -> ft_from :ftp -> ft_to ; 4527l = strlen (p ); 4528assert (l < INT_MAX ); 4529putc ((int )l ,fd ); 4530if (l > 0 ) { 4531fwv &=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. 4539if (spin -> si_sofofr != NULL && spin -> si_sofoto != NULL ) { 4540putc (SN_SOFO ,fd );// <sectionID> 4541putc (0 ,fd );// <sectionflags> 4542 4543size_t l = strlen (spin -> si_sofofr ); 4544put_bytes (fd ,l + strlen (spin -> si_sofoto )+ 4 ,4 );// <sectionlen> 4545 4546put_bytes (fd ,l ,2 );// <sofofromlen> 4547fwv &=fwrite (spin -> si_sofofr ,l ,1 ,fd );// <sofofrom> 4548 4549l = strlen (spin -> si_sofoto ); 4550put_bytes (fd ,l ,2 );// <sofotolen> 4551fwv &=fwrite (spin -> si_sofoto ,l ,1 ,fd );// <sofoto> 4552 } 4553 4554// SN_WORDS: <word> ... 4555// This is for making suggestions, section is not required. 4556if (spin -> si_commonwords .ht_used > 0 ) { 4557putc (SN_WORDS ,fd );// <sectionID> 4558putc (0 ,fd );// <sectionflags> 4559 4560// round 1: count the bytes 4561// round 2: write the bytes 4562for (unsigned round = 1 ;round <=2 ;round ++ ) { 4563size_t todo ; 4564size_t len = 0 ; 4565hashitem_T * hi ; 4566 4567todo = spin -> si_commonwords .ht_used ; 4568for (hi = spin -> si_commonwords .ht_array ;todo > 0 ;hi ++ ) { 4569if (!HASHITEM_EMPTY (hi )) { 4570size_t l = strlen (hi -> hi_key )+ 1 ; 4571len += l ; 4572if (round == 2 ) {// <word> 4573fwv &=fwrite (hi -> hi_key ,l ,1 ,fd ); 4574 } 4575todo -- ; 4576 } 4577 } 4578if (round == 1 ) { 4579put_bytes (fd ,len ,4 );// <sectionlen> 4580 } 4581 } 4582 } 4583 4584// SN_MAP: <mapstr> 4585// This is for making suggestions, section is not required. 4586if (!GA_EMPTY (& spin -> si_map )) { 4587putc (SN_MAP ,fd );// <sectionID> 4588putc (0 ,fd );// <sectionflags> 4589size_t l = (size_t )spin -> si_map .ga_len ; 4590put_bytes (fd ,l ,4 );// <sectionlen> 4591fwv &=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. 4599if (!spin -> si_nosugfile 4600&& (!GA_EMPTY (& spin -> si_sal ) 4601|| (spin -> si_sofofr != NULL && spin -> si_sofoto != NULL ))) { 4602putc (SN_SUGFILE ,fd );// <sectionID> 4603putc (0 ,fd );// <sectionflags> 4604put_bytes (fd ,8 ,4 );// <sectionlen> 4605 4606// Set si_sugtime and write it to the file. 4607spin -> si_sugtime = time (NULL ); 4608put_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. 4614if (spin -> si_nosplitsugs ) { 4615putc (SN_NOSPLITSUGS ,fd );// <sectionID> 4616putc (0 ,fd );// <sectionflags> 4617put_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. 4623if (spin -> si_nocompoundsugs ) { 4624putc (SN_NOCOMPOUNDSUGS ,fd );// <sectionID> 4625putc (0 ,fd );// <sectionflags> 4626put_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. 4632if (spin -> si_compflags != NULL ) { 4633putc (SN_COMPOUND ,fd );// <sectionID> 4634putc (0 ,fd );// <sectionflags> 4635 4636size_t l = strlen (spin -> si_compflags ); 4637assert (spin -> si_comppat .ga_len >=0 ); 4638for (size_t i = 0 ;i < (size_t )spin -> si_comppat .ga_len ;i ++ ) { 4639l += strlen (((char ** )(spin -> si_comppat .ga_data ))[i ])+ 1 ; 4640 } 4641put_bytes (fd ,l + 7 ,4 );// <sectionlen> 4642 4643putc (spin -> si_compmax ,fd );// <compmax> 4644putc (spin -> si_compminlen ,fd );// <compminlen> 4645putc (spin -> si_compsylmax ,fd );// <compsylmax> 4646putc (0 ,fd );// for Vim 7.0b compatibility 4647putc (spin -> si_compoptions ,fd );// <compoptions> 4648put_bytes (fd , (uintmax_t )spin -> si_comppat .ga_len ,2 );// <comppatcount> 4649for (size_t i = 0 ;i < (size_t )spin -> si_comppat .ga_len ;i ++ ) { 4650char * p = ((char ** )(spin -> si_comppat .ga_data ))[i ]; 4651assert (strlen (p )< INT_MAX ); 4652putc ((int )strlen (p ),fd );// <comppatlen> 4653fwv &=fwrite (p ,strlen (p ),1 ,fd );// <comppattext> 4654 } 4655// <compflags> 4656fwv &=fwrite (spin -> si_compflags ,strlen (spin -> si_compflags ),1 ,fd ); 4657 } 4658 4659// SN_NOBREAK: NOBREAK flag 4660if (spin -> si_nobreak ) { 4661putc (SN_NOBREAK ,fd );// <sectionID> 4662putc (0 ,fd );// <sectionflags> 4663 4664// It's empty, the presence of the section flags the feature. 4665put_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. 4671if (spin -> si_syllable != NULL ) { 4672putc (SN_SYLLABLE ,fd );// <sectionID> 4673putc (0 ,fd );// <sectionflags> 4674 4675size_t l = strlen (spin -> si_syllable ); 4676put_bytes (fd ,l ,4 );// <sectionlen> 4677fwv &=fwrite (spin -> si_syllable ,l ,1 ,fd );// <syllable> 4678 } 4679 4680// end of <SECTIONS> 4681putc (SN_END ,fd );// <sectionend> 4682 4683// <LWORDTREE> <KWORDTREE> <PREFIXTREE> 4684spin -> si_memtot = 0 ; 4685for (unsigned round = 1 ;round <=3 ;round ++ ) { 4686wordnode_T * tree ; 4687if (round == 1 ) { 4688tree = spin -> si_foldroot -> wn_sibling ; 4689 }else if (round == 2 ) { 4690tree = spin -> si_keeproot -> wn_sibling ; 4691 }else { 4692tree = spin -> si_prefroot -> wn_sibling ; 4693 } 4694 4695// Clear the index and wnode fields in the tree. 4696clear_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. 4701size_t nodecount = (size_t )put_node (NULL ,tree ,0 ,regionmask ,round == 3 ); 4702 4703// number of nodes in 4 bytes 4704put_bytes (fd ,nodecount ,4 );// <nodecount> 4705assert (nodecount + nodecount * sizeof (int )< INT_MAX ); 4706spin -> si_memtot += (int )(nodecount + nodecount * sizeof (int )); 4707 4708// Write the nodes. 4709put_node (fd ,tree ,0 ,regionmask ,round == 3 ); 4710 } 4711 4712// Write another byte to check for errors (file system full). 4713if (putc (0 ,fd )== EOF ) { 4714retval = FAIL ; 4715 } 4716theend : 4717if (fclose (fd )== EOF ) { 4718retval = FAIL ; 4719 } 4720 4721if (fwv != 1 ) { 4722retval = FAIL ; 4723 } 4724if (retval == FAIL ) { 4725emsg (_ (e_write )); 4726 } 4727 4728return 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{ 4736if (node != NULL ) { 4737for (wordnode_T * np = node ;np != NULL ;np = np -> wn_sibling ) { 4738np -> wn_u1 .index = 0 ; 4739np -> wn_u2 .wnode = NULL ; 4740 4741if (np -> wn_byte != NUL ) { 4742clear_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. 4764if (node == NULL ) { 4765return 0 ; 4766 } 4767 4768// Store the index where this node is written. 4769node -> wn_u1 .index = idx ; 4770 4771// Count the number of siblings. 4772int siblingcount = 0 ; 4773for (wordnode_T * np = node ;np != NULL ;np = np -> wn_sibling ) { 4774siblingcount ++ ; 4775 } 4776 4777// Write the sibling count. 4778if (fd != NULL ) { 4779putc (siblingcount ,fd );// <siblingcount> 4780 } 4781// Write each sibling byte and optionally extra info. 4782for (wordnode_T * np = node ;np != NULL ;np = np -> wn_sibling ) { 4783if (np -> wn_byte == 0 ) { 4784if (fd != NULL ) { 4785// For a NUL byte (end of word) write the flags etc. 4786if (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 4791if (np -> wn_flags == (uint16_t )PFX_FLAGS ) { 4792putc (BY_NOFLAGS ,fd );// <byte> 4793 }else { 4794putc (BY_FLAGS ,fd );// <byte> 4795putc (np -> wn_flags ,fd );// <pflags> 4796 } 4797putc (np -> wn_affixID ,fd );// <affixID> 4798put_bytes (fd , (uintmax_t )np -> wn_region ,2 );// <prefcondnr> 4799 }else { 4800// For word trees we write the flag/region items. 4801int flags = np -> wn_flags ; 4802if (regionmask != 0 && np -> wn_region != regionmask ) { 4803flags |=WF_REGION ; 4804 } 4805if (np -> wn_affixID != 0 ) { 4806flags |=WF_AFX ; 4807 } 4808if (flags == 0 ) { 4809// word without flags or region 4810putc (BY_NOFLAGS ,fd );// <byte> 4811 }else { 4812if (np -> wn_flags >=0x100 ) { 4813putc (BY_FLAGS2 ,fd );// <byte> 4814putc (flags ,fd );// <flags> 4815putc ((int )((unsigned )flags >>8 ),fd );// <flags2> 4816 }else { 4817putc (BY_FLAGS ,fd );// <byte> 4818putc (flags ,fd );// <flags> 4819 } 4820if (flags & WF_REGION ) { 4821putc (np -> wn_region ,fd );// <region> 4822 } 4823if (flags & WF_AFX ) { 4824putc (np -> wn_affixID ,fd );// <affixID> 4825 } 4826 } 4827 } 4828 } 4829 }else { 4830if (np -> wn_child -> wn_u1 .index != 0 4831&& np -> wn_child -> wn_u2 .wnode != node ) { 4832// The child is written elsewhere, write the reference. 4833if (fd != NULL ) { 4834putc (BY_INDEX ,fd );// <byte> 4835put_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. 4839np -> wn_child -> wn_u2 .wnode = node ; 4840 } 4841 4842if (fd != NULL ) { 4843if (putc (np -> wn_byte ,fd )== EOF ) {// <byte> or <xbyte> 4844emsg (_ (e_write )); 4845return 0 ; 4846 } 4847 } 4848 } 4849 } 4850 4851// Space used in the array when reading: one for each sibling and one for 4852// the count. 4853int newindex = idx + siblingcount + 1 ; 4854 4855// Recursively dump the children of each sibling. 4856for (wordnode_T * np = node ;np != NULL ;np = np -> wn_sibling ) { 4857if (np -> wn_byte != 0 && np -> wn_child -> wn_u2 .wnode == node ) { 4858newindex = put_node (fd ,np -> wn_child ,newindex ,regionmask , 4859prefixtree ); 4860 } 4861 } 4862 4863return newindex ; 4864} 4865 4866// ":mkspell [-ascii] outfile infile ..." 4867// ":mkspell [-ascii] addfile" 4868void ex_mkspell (exarg_T * eap ) 4869{ 4870int fcount ; 4871char ** fnames ; 4872char * arg = eap -> arg ; 4873bool ascii = false; 4874 4875if (strncmp (arg ,"-ascii" ,6 )== 0 ) { 4876ascii = true; 4877arg = skipwhite (arg + 6 ); 4878 } 4879 4880// Expand all the remaining arguments (e.g., $VIMRUNTIME). 4881if (get_arglist_exp (arg ,& fcount ,& fnames , false)!= OK ) { 4882return ; 4883 } 4884 4885mkspell (fcount ,fnames ,ascii ,eap -> forceit , false); 4886FreeWild (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{ 4894char * fname = NULL ; 4895slang_T * slang ; 4896bool 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(). 4903for (slang = first_lang ;slang != NULL ;slang = slang -> sl_next ) { 4904if (path_equal (wfname ,slang -> sl_fname ,kPathCmpExpand )) { 4905break ; 4906 } 4907 } 4908if (slang == NULL ) { 4909spell_message (spin ,_ ("Reading back spell file..." )); 4910slang = spell_load_file (wfname ,NULL ,NULL , false); 4911if (slang == NULL ) { 4912return ; 4913 } 4914free_slang = true; 4915 } 4916 4917// Clear the info in "spin" that is used. 4918spin -> si_blocks = NULL ; 4919spin -> si_blocks_cnt = 0 ; 4920spin -> si_compress_cnt = 0 ;// will stay at 0 all the time 4921spin -> si_free_count = 0 ; 4922spin -> si_first_free = NULL ; 4923spin -> si_foldwcount = 0 ; 4924 4925// Go through the trie of good words, soundfold each word and add it to 4926// the soundfold trie. 4927spell_message (spin ,_ ("Performing soundfolding..." )); 4928if (sug_filltree (spin ,slang )== FAIL ) { 4929 gototheend ; 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. 4936if (sug_maketable (spin )== FAIL ) { 4937 gototheend ; 4938 } 4939 4940smsg (0 ,_ ("Number of words after soundfolding: %" PRId64 ), 4941 (int64_t )spin -> si_spellbuf -> b_ml .ml_line_count ); 4942 4943// Compress the soundfold trie. 4944spell_message (spin ,_ (msg_compressing )); 4945wordtree_compress (spin ,spin -> si_foldroot ,"case-folded" ); 4946 4947// Write the .sug file. 4948// Make the file name by changing ".spl" to ".sug". 4949fname = xmalloc (MAXPATHL ); 4950xstrlcpy (fname ,wfname ,MAXPATHL ); 4951int len = (int )strlen (fname ); 4952fname [len - 2 ]= 'u' ; 4953fname [len - 1 ]= 'g' ; 4954sug_write (spin ,fname ); 4955 4956theend : 4957xfree (fname ); 4958if (free_slang ) { 4959slang_free (slang ); 4960 } 4961free_blocks (spin -> si_blocks ); 4962close_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{ 4968idx_T arridx [MAXWLEN ]; 4969int curi [MAXWLEN ]; 4970char tword [MAXWLEN ]; 4971char tsalword [MAXWLEN ]; 4972unsigned words_done = 0 ; 4973int wordcount [MAXWLEN ]; 4974 4975// We use si_foldroot for the soundfolded trie. 4976spin -> si_foldroot = wordtree_alloc (spin ); 4977 4978// Let tree_add_word() know we're adding to the soundfolded tree 4979spin -> 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. 4983uint8_t * byts = slang -> sl_fbyts ; 4984idx_T * idxs = slang -> sl_fidxs ; 4985if (byts == NULL || idxs == NULL ) { 4986return FAIL ; 4987 } 4988 4989arridx [0 ]= 0 ; 4990curi [0 ]= 1 ; 4991wordcount [0 ]= 0 ; 4992 4993int depth = 0 ; 4994while (depth >=0 && !got_int ) { 4995if (curi [depth ]> byts [arridx [depth ]]) { 4996// Done all bytes at this node, go up one level. 4997idxs [arridx [depth ]]= wordcount [depth ]; 4998if (depth > 0 ) { 4999wordcount [depth - 1 ]+= wordcount [depth ]; 5000 } 5001 5002depth -- ; 5003line_breakcheck (); 5004 }else { 5005// Do one more byte at this node. 5006idx_T n = arridx [depth ]+ curi [depth ]; 5007curi [depth ]++ ; 5008 5009int c = byts [n ]; 5010if (c == 0 ) { 5011// Sound-fold the word. 5012tword [depth ]= NUL ; 5013spell_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. 5017if (tree_add_word (spin ,tsalword ,spin -> si_foldroot , 5018 (int )(words_done >>16 ),words_done & 0xffff , 50190 )== FAIL ) { 5020return FAIL ; 5021 } 5022 5023words_done ++ ; 5024wordcount [depth ]++ ; 5025 5026// Reset the block count each time to avoid compression 5027// kicking in. 5028spin -> 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. 5032while (n + 1 < slang -> sl_fbyts_len && byts [n + 1 ]== 0 ) { 5033n ++ ; 5034curi [depth ]++ ; 5035 } 5036 }else if (depth < MAXWLEN - 1 ) { 5037// Normal char, go one level deeper. 5038tword [depth ++ ]= (char )(uint8_t )c ; 5039arridx [depth ]= idxs [n ]; 5040curi [depth ]= 1 ; 5041wordcount [depth ]= 0 ; 5042 } 5043 } 5044 } 5045 5046smsg (0 ,_ ("Total number of words: %d" ),words_done ); 5047 5048return 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{ 5058garray_T ga ; 5059int 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). 5063spin -> si_spellbuf = open_spellbuf (); 5064 5065// Use a buffer to store the line info, avoids allocating many small 5066// pieces of memory. 5067ga_init (& ga ,1 ,100 ); 5068 5069// recursively go through the tree 5070if (sug_filltable (spin ,spin -> si_foldroot -> wn_sibling ,0 ,& ga )== -1 ) { 5071res = FAIL ; 5072 } 5073 5074ga_clear (& ga ); 5075return 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{ 5085int wordnr = startwordnr ; 5086 5087for (wordnode_T * p = node ;p != NULL ;p = p -> wn_sibling ) { 5088if (p -> wn_byte == NUL ) { 5089gap -> ga_len = 0 ; 5090int prev_nr = 0 ; 5091for (wordnode_T * np = p ;np != NULL && np -> wn_byte == NUL ;np = np -> wn_sibling ) { 5092ga_grow (gap ,10 ); 5093 5094int 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. 5099nr -= prev_nr ; 5100prev_nr += nr ; 5101gap -> 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 5107if (ml_append_buf (spin -> si_spellbuf , (linenr_T )wordnr , 5108gap -> ga_data ,gap -> ga_len , true)== FAIL ) { 5109return -1 ; 5110 } 5111wordnr ++ ; 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. 5115while (p -> wn_sibling != NULL && p -> wn_sibling -> wn_byte == NUL ) { 5116p -> 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. 5121p -> wn_flags = 0 ; 5122p -> wn_region = 0 ; 5123 }else { 5124wordnr = sug_filltable (spin ,p -> wn_child ,wordnr ,gap ); 5125if (wordnr == -1 ) { 5126return -1 ; 5127 } 5128 } 5129 } 5130return 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{ 5138uint8_t * buf = (uint8_t * )buf_in ; 5139 5140// Split the number in parts of base 255. We need to avoid NUL bytes. 5141int b1 = nr %255 + 1 ; 5142int rem = nr /255 ; 5143int b2 = rem %255 + 1 ; 5144rem = rem /255 ; 5145int b3 = rem %255 + 1 ; 5146int b4 = rem /255 + 1 ; 5147 5148if (b4 > 1 || b3 > 0x1f ) {// 4 bytes 5149buf [0 ]= (uint8_t )(0xe0 + b4 ); 5150buf [1 ]= (uint8_t )b3 ; 5151buf [2 ]= (uint8_t )b2 ; 5152buf [3 ]= (uint8_t )b1 ; 5153return 4 ; 5154 } 5155if (b3 > 1 || b2 > 0x3f ) {// 3 bytes 5156buf [0 ]= (uint8_t )(0xc0 + b3 ); 5157buf [1 ]= (uint8_t )b2 ; 5158buf [2 ]= (uint8_t )b1 ; 5159return 3 ; 5160 } 5161if (b2 > 1 || b1 > 0x7f ) {// 2 bytes 5162buf [0 ]= (uint8_t )(0x80 + b2 ); 5163buf [1 ]= (uint8_t )b1 ; 5164return 2 ; 5165 } 5166// 1 byte 5167buf [0 ]= (uint8_t )b1 ; 5168return 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! 5175FILE * fd = os_fopen (fname ,"w" ); 5176if (fd == NULL ) { 5177semsg (_ (e_notopen ),fname ); 5178return ; 5179 } 5180 5181vim_snprintf (IObuff ,IOSIZE , 5182_ ("Writing suggestion file %s..." ),fname ); 5183spell_message (spin ,IObuff ); 5184 5185// <SUGHEADER>: <fileID> <versionnr> <timestamp> 5186if (fwrite (VIMSUGMAGIC ,VIMSUGMAGICL ,1 ,fd )!= 1 ) {// <fileID> 5187emsg (_ (e_write )); 5188 gototheend ; 5189 } 5190putc (VIMSUGVERSION ,fd );// <versionnr> 5191 5192// Write si_sugtime to the file. 5193put_time (fd ,spin -> si_sugtime );// <timestamp> 5194 5195// <SUGWORDTREE> 5196spin -> si_memtot = 0 ; 5197wordnode_T * tree = spin -> si_foldroot -> wn_sibling ; 5198 5199// Clear the index and wnode fields in the tree. 5200clear_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. 5205size_t nodecount = (size_t )put_node (NULL ,tree ,0 ,0 , false); 5206 5207// number of nodes in 4 bytes 5208put_bytes (fd ,nodecount ,4 );// <nodecount> 5209assert (nodecount + nodecount * sizeof (int )< INT_MAX ); 5210spin -> si_memtot += (int )(nodecount + nodecount * sizeof (int )); 5211 5212// Write the nodes. 5213put_node (fd ,tree ,0 ,0 , false); 5214 5215// <SUGTABLE>: <sugwcount> <sugline> ... 5216linenr_T wcount = spin -> si_spellbuf -> b_ml .ml_line_count ; 5217assert (wcount >=0 ); 5218put_bytes (fd , (uintmax_t )wcount ,4 );// <sugwcount> 5219 5220for (linenr_T lnum = 1 ;lnum <=wcount ;lnum ++ ) { 5221// <sugline>: <sugnr> ... NUL 5222char * line = ml_get_buf (spin -> si_spellbuf ,lnum ); 5223int len = ml_get_buf_len (spin -> si_spellbuf ,lnum )+ 1 ; 5224if (fwrite (line , (size_t )len ,1 ,fd )== 0 ) { 5225emsg (_ (e_write )); 5226 gototheend ; 5227 } 5228spin -> si_memtot += len ; 5229 } 5230 5231// Write another byte to check for errors. 5232if (putc (0 ,fd )== EOF ) { 5233emsg (_ (e_write )); 5234 } 5235 5236vim_snprintf (IObuff ,IOSIZE , 5237_ ("Estimated runtime memory use: %d bytes" ),spin -> si_memtot ); 5238spell_message (spin ,IObuff ); 5239 5240theend : 5241// close the file 5242fclose (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{ 5256char * fname = NULL ; 5257afffile_T * (afile [MAXREGIONS ]); 5258bool error = false; 5259spellinfo_T spin ; 5260 5261// Only spell-file generation needs the derived 'mkspellmem' limits. 5262spell_check_msm (p_msm , true); 5263 5264CLEAR_FIELD (spin ); 5265spin .si_verbose = !added_word ; 5266spin .si_ascii = ascii ; 5267spin .si_followup = true; 5268spin .si_rem_accents = true; 5269ga_init (& spin .si_rep , (int )sizeof (fromto_T ),20 ); 5270ga_init (& spin .si_repsal , (int )sizeof (fromto_T ),20 ); 5271ga_init (& spin .si_sal , (int )sizeof (fromto_T ),20 ); 5272ga_init (& spin .si_map , (int )sizeof (char ),100 ); 5273ga_init (& spin .si_comppat , (int )sizeof (char * ),20 ); 5274ga_init (& spin .si_prefcond , (int )sizeof (char * ),50 ); 5275hash_init (& spin .si_commonwords ); 5276spin .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. 5280char ** innames = & fnames [fcount == 1 ?0 :1 ]; 5281int incount = fcount - 1 ; 5282 5283char * wfname = xmalloc (MAXPATHL ); 5284 5285if (fcount >=1 ) { 5286int len = (int )strlen (fnames [0 ]); 5287if (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". 5290incount = 1 ; 5291vim_snprintf (wfname ,MAXPATHL ,"%s.spl" ,fnames [0 ]); 5292 }else if (fcount == 1 ) { 5293// For ":mkspell path/vim" output file is "path/vim.latin1.spl". 5294incount = 1 ; 5295vim_snprintf (wfname ,MAXPATHL ,SPL_FNAME_TMPL , 5296fnames [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. 5299xstrlcpy (wfname ,fnames [0 ],MAXPATHL ); 5300 }else { 5301// Name should be language, make the file name from it. 5302vim_snprintf (wfname ,MAXPATHL ,SPL_FNAME_TMPL , 5303fnames [0 ],spin .si_ascii ?"ascii" :spell_enc ()); 5304 } 5305 5306// Check for .ascii.spl. 5307if (strstr (path_tail (wfname ),SPL_FNAME_ASCII )!= NULL ) { 5308spin .si_ascii = true; 5309 } 5310 5311// Check for .add.spl. 5312if (strstr (path_tail (wfname ),SPL_FNAME_ADD )!= NULL ) { 5313spin .si_add = true; 5314 } 5315 } 5316 5317if (incount <=0 ) { 5318emsg (_ (e_invarg ));// need at least output and input names 5319 }else if (vim_strchr (path_tail (wfname ),'_' )!= NULL ) { 5320emsg (_ ("E751: Output file name must not have region name" )); 5321 }else if (incount > MAXREGIONS ) { 5322semsg (_ ("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. 5326if (!over_write && os_path_exists (wfname )) { 5327emsg (_ (e_exists )); 5328 gototheend ; 5329 } 5330if (os_isdir (wfname )) { 5331semsg (_ (e_isadir2 ),wfname ); 5332 gototheend ; 5333 } 5334 5335fname = xmalloc (MAXPATHL ); 5336 5337// Init the aff and dic pointers. 5338// Get the region names if there are more than 2 arguments. 5339for (int i = 0 ;i < incount ;i ++ ) { 5340afile [i ]= NULL ; 5341 5342if (incount > 1 ) { 5343int len = (int )strlen (innames [i ]); 5344if (strlen (path_tail (innames [i ]))< 5 5345|| innames [i ][len - 3 ]!= '_' ) { 5346semsg (_ ("E755: Invalid region in %s" ),innames [i ]); 5347 gototheend ; 5348 } 5349spin .si_region_name [i * 2 ]= (char )(uint8_t )TOLOWER_ASC (innames [i ][len - 2 ]); 5350spin .si_region_name [i * 2 + 1 ]= (char )(uint8_t )TOLOWER_ASC (innames [i ][len - 1 ]); 5351 } 5352 } 5353spin .si_region_count = incount ; 5354 5355spin .si_foldroot = wordtree_alloc (& spin ); 5356spin .si_keeproot = wordtree_alloc (& spin ); 5357spin .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. 5364if (!spin .si_add ) { 5365spin .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. 5371for (int i = 0 ;i < incount && !error ;i ++ ) { 5372spin .si_conv .vc_type = CONV_NONE ; 5373spin .si_region = 1 <<i ; 5374 5375vim_snprintf (fname ,MAXPATHL ,"%s.aff" ,innames [i ]); 5376if (os_path_exists (fname )) { 5377// Read the .aff file. Will init "spin->si_conv" based on the 5378// "SET" line. 5379afile [i ]= spell_read_aff (& spin ,fname ); 5380if (afile [i ]== NULL ) { 5381error = true; 5382 }else { 5383// Read the .dic file and store the words in the trees. 5384vim_snprintf (fname ,MAXPATHL ,"%s.dic" ,innames [i ]); 5385if (spell_read_dic (& spin ,fname ,afile [i ])== FAIL ) { 5386error = true; 5387 } 5388 } 5389 }else { 5390// No .aff file, try reading the file as a word list. Store 5391// the words in the trees. 5392if (spell_read_wordfile (& spin ,innames [i ])== FAIL ) { 5393error = true; 5394 } 5395 } 5396 5397// Free any conversion stuff. 5398convert_setup (& spin .si_conv ,NULL ,NULL ); 5399 } 5400 5401if (spin .si_compflags != NULL && spin .si_nobreak ) { 5402msg (_ ("Warning: both compounding and NOBREAK specified" ),0 ); 5403 } 5404 5405if (!error && !got_int ) { 5406// Combine tails in the tree. 5407spell_message (& spin ,_ (msg_compressing )); 5408wordtree_compress (& spin ,spin .si_foldroot ,"case-folded" ); 5409wordtree_compress (& spin ,spin .si_keeproot ,"keep-case" ); 5410wordtree_compress (& spin ,spin .si_prefroot ,"prefixes" ); 5411 } 5412 5413if (!error && !got_int ) { 5414// Write the info in the spell file. 5415vim_snprintf (IObuff ,IOSIZE , 5416_ ("Writing spell file %s..." ),wfname ); 5417spell_message (& spin ,IObuff ); 5418 5419error = write_vim_spell (& spin ,wfname )== FAIL ; 5420 5421spell_message (& spin ,_ ("Done!" )); 5422vim_snprintf (IObuff ,IOSIZE , 5423_ ("Estimated runtime memory use: %d bytes" ),spin .si_memtot ); 5424spell_message (& spin ,IObuff ); 5425 5426// If the file is loaded need to reload it. 5427if (!error ) { 5428spell_reload_one (wfname ,added_word ); 5429 } 5430 } 5431 5432// Free the allocated memory. 5433ga_clear (& spin .si_rep ); 5434ga_clear (& spin .si_repsal ); 5435ga_clear (& spin .si_sal ); 5436ga_clear (& spin .si_map ); 5437ga_clear (& spin .si_comppat ); 5438ga_clear (& spin .si_prefcond ); 5439hash_clear_all (& spin .si_commonwords ,0 ); 5440 5441// Free the .aff file structures. 5442for (int i = 0 ;i < incount ;i ++ ) { 5443if (afile [i ]!= NULL ) { 5444spell_free_aff (afile [i ]); 5445 } 5446 } 5447 5448// Free all the bits and pieces at once. 5449free_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. 5453if (spin .si_sugtime != 0 && !error && !got_int ) { 5454spell_make_sugfile (& spin ,wfname ); 5455 } 5456 } 5457 5458theend : 5459xfree (fname ); 5460xfree (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 ) 5466FUNC_ATTR_NONNULL_ALL 5467{ 5468if (spin -> si_verbose || p_verbose > 2 ) { 5469if (!spin -> si_verbose ) { 5470verbose_enter (); 5471 } 5472msg (str ,0 ); 5473ui_flush (); 5474if (!spin -> si_verbose ) { 5475verbose_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{ 5486spell_add_word (eap -> arg , (int )strlen (eap -> arg ), 5487eap -> cmdidx == CMD_spellwrong 5488 ?SPELL_ADD_BAD 5489 :eap -> cmdidx == CMD_spellrare ?SPELL_ADD_RARE :SPELL_ADD_GOOD , 5490eap -> forceit ?0 : (int )eap -> line2 , 5491eap -> 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{ 5501FILE * fd = NULL ; 5502buf_T * buf = NULL ; 5503bool new_spf = false; 5504char * fname ; 5505char * fnamebuf = NULL ; 5506char line [MAXWLEN * 2 ]; 5507char * spf ; 5508 5509if (!valid_spell_word (word ,word + len )) { 5510emsg (_ (e_illegal_character_in_word )); 5511return ; 5512 } 5513 5514if (idx == 0 ) {// use internal wordlist 5515if (int_wordlist == NULL ) { 5516int_wordlist = vim_tempname (); 5517if (int_wordlist == NULL ) { 5518return ; 5519 } 5520 } 5521fname = int_wordlist ; 5522 }else { 5523int i ; 5524// If 'spellfile' isn't set figure out a good default value. 5525if (* curwin -> w_s -> b_p_spf == NUL ) { 5526init_spellfile (); 5527new_spf = true; 5528 } 5529 5530if (* curwin -> w_s -> b_p_spf == NUL ) { 5531semsg (_ (e_notset ),"spellfile" ); 5532return ; 5533 } 5534fnamebuf = xmalloc (MAXPATHL ); 5535 5536for (spf = curwin -> w_s -> b_p_spf ,i = 1 ;* spf != NUL ;i ++ ) { 5537copy_option_part (& spf ,fnamebuf ,MAXPATHL ,"," ); 5538if (i == idx ) { 5539break ; 5540 } 5541if (* spf == NUL ) { 5542semsg (_ ("E765: 'spellfile' does not have %d entries" ),idx ); 5543xfree (fnamebuf ); 5544return ; 5545 } 5546 } 5547 5548// Check that the user isn't editing the .add file somewhere. 5549buf = buflist_findname_exp (fnamebuf ); 5550if (buf != NULL && buf -> b_ml .ml_mfp == NULL ) { 5551buf = NULL ; 5552 } 5553if (buf != NULL && bufIsChanged (buf )) { 5554emsg (_ (e_bufloaded )); 5555xfree (fnamebuf ); 5556return ; 5557 } 5558 5559fname = fnamebuf ; 5560 } 5561 5562if (what == SPELL_ADD_BAD || undo ) { 5563int fpos_next = 0 ; 5564int 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. 5567fd = os_fopen (fname ,"r" ); 5568if (fd != NULL ) { 5569while (!vim_fgets (line ,MAXWLEN * 2 ,fd )) { 5570fpos = fpos_next ; 5571fpos_next = (int )ftell (fd ); 5572if (fpos_next < 0 ) { 5573break ;// should never happen 5574 } 5575size_t linelen = strlen (line ); 5576if (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. 5582fclose (fd ); 5583fd = os_fopen (fname ,"r+" ); 5584if (fd == NULL ) { 5585break ; 5586 } 5587if (fseek (fd ,fpos ,SEEK_SET )== 0 ) { 5588fputc ('#' ,fd ); 5589if (undo ) { 5590home_replace (NULL ,fname ,NameBuff ,MAXPATHL , true); 5591smsg (0 ,_ ("Word '%.*s' removed from %s" ),len ,word ,NameBuff ); 5592 } 5593 } 5594if (fseek (fd ,fpos_next ,SEEK_SET )!= 0 ) { 5595PERROR (_ ("Seek error in spellfile" )); 5596break ; 5597 } 5598 } 5599 } 5600if (fd != NULL ) { 5601fclose (fd ); 5602 } 5603 } 5604 } 5605 5606if (!undo ) { 5607fd = os_fopen (fname ,"a" ); 5608if (fd == NULL && new_spf ) { 5609char * 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(). 5615if (!dir_of_file_exists (fname ) 5616&& (p = path_tail_with_sep (fname ))!= fname ) { 5617char c = * p ; 5618 5619// The directory doesn't exist. Try creating it and opening 5620// the file again. 5621* p = NUL ; 5622os_mkdir (fname ,0755 ); 5623* p = c ; 5624fd = os_fopen (fname ,"a" ); 5625 } 5626 } 5627 5628if (fd == NULL ) { 5629semsg (_ (e_notopen ),fname ); 5630 }else { 5631if (what == SPELL_ADD_BAD ) { 5632fprintf (fd ,"%.*s/!\n" ,len ,word ); 5633 }else if (what == SPELL_ADD_RARE ) { 5634fprintf (fd ,"%.*s/?\n" ,len ,word ); 5635 }else { 5636fprintf (fd ,"%.*s\n" ,len ,word ); 5637 } 5638fclose (fd ); 5639 5640home_replace (NULL ,fname ,NameBuff ,MAXPATHL , true); 5641smsg (0 ,_ ("Word '%.*s' added to %s" ),len ,word ,NameBuff ); 5642 } 5643 } 5644 5645if (fd != NULL ) { 5646// Update the .add.spl file. 5647mkspell (1 ,& fname , false, true, true); 5648 5649// If the .add file is edited somewhere, reload it. 5650if (buf != NULL ) { 5651buf_reload (buf ,buf -> b_orig_mode , false); 5652 } 5653 5654redraw_all_later (UPD_SOME_VALID ); 5655 } 5656xfree (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{ 5665char * lend ; 5666bool aspath = false; 5667char * lstart = curbuf -> b_s .b_p_spl ; 5668 5669if (* curwin -> w_s -> b_p_spl == NUL || GA_EMPTY (& curwin -> w_s -> b_langp )) { 5670return ; 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. 5675for (lend = curwin -> w_s -> b_p_spl ;* lend != NUL 5676&& vim_strchr (",._" , (uint8_t )(* lend ))== NULL ;lend ++ ) { 5677if (vim_ispathsep (* lend )) { 5678aspath = true; 5679lstart = lend + 1 ; 5680 } 5681 } 5682 5683char * buf = xmalloc (MAXPATHL ); 5684size_t buf_len = MAXPATHL ; 5685 5686if (!aspath ) { 5687char * xdg_path = get_xdg_home (kXDGDataHome ); 5688xstrlcpy (buf ,xdg_path ,buf_len ); 5689xfree (xdg_path ); 5690 5691xstrlcat (buf ,"/site/spell" ,buf_len ); 5692 5693char * failed_dir ; 5694if (os_mkdir_recurse (buf ,0755 ,& failed_dir ,NULL )!= 0 ) { 5695xfree (buf ); 5696xfree (failed_dir ); 5697return ; 5698 } 5699 }else { 5700if ((size_t )(lend - curbuf -> b_s .b_p_spl ) >=buf_len ) { 5701xfree (buf ); 5702return ; 5703 } 5704xmemcpyz (buf ,curbuf -> b_s .b_p_spl , (size_t )(lend - curbuf -> b_s .b_p_spl )); 5705 } 5706 5707// Append spelllang 5708vim_snprintf (buf + strlen (buf ),buf_len - strlen (buf ),"/%.*s" , (int )(lend - lstart ),lstart ); 5709 5710// Append ".ascii.add" or ".{enc}.add" 5711char * fname = LANGP_ENTRY (curwin -> w_s -> b_langp ,0 )-> lp_slang -> sl_fname ; 5712const char * enc_suffix = 5713 (fname != NULL && strstr (path_tail (fname ),".ascii." )!= NULL ) ?"ascii" :spell_enc (); 5714vim_snprintf (buf + strlen (buf ),buf_len - strlen (buf ),".%s.add" ,enc_suffix ); 5715 5716set_option_value_give_err (kOptSpellfile ,CSTR_AS_OBJ (buf ),OPT_LOCAL ); 5717xfree (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{ 5725const 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. 5728spelltab_T new_st ; 5729const char * p = fol ; 5730 5731clear_spell_chartab (& new_st ); 5732 5733for (int i = 0 ;i < 128 ;i ++ ) { 5734if (i < cnt ) { 5735new_st .st_isw [i + 128 ]= (flags [i ]& CF_WORD )!= 0 ; 5736new_st .st_isu [i + 128 ]= (flags [i ]& CF_UPPER )!= 0 ; 5737 } 5738 5739if (* p != NUL ) { 5740int c = mb_ptr2char_adv (& p ); 5741new_st .st_fold [i + 128 ]= (uint8_t )c ; 5742if (i + 128 != c && new_st .st_isu [i + 128 ]&& c < 256 ) { 5743new_st .st_upper [c ]= (uint8_t )(i + 128 ); 5744 } 5745 } 5746 } 5747 5748set_spell_finish (& new_st ); 5749} 5750 5751static int set_spell_finish (spelltab_T * new_st ) 5752{ 5753if (did_set_spelltab ) { 5754// check that it's the same table 5755for (int i = 0 ;i < 256 ;i ++ ) { 5756if (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 ]) { 5760emsg (_ ("E763: Word characters differ between spell files" )); 5761return FAIL ; 5762 } 5763 } 5764 }else { 5765// copy the new spelltab into the one being used 5766spelltab = * new_st ; 5767did_set_spelltab = true; 5768 } 5769 5770return 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{ 5777assert (gap -> ga_len >=0 ); 5778 5779if (fd != NULL ) { 5780put_bytes (fd , (uintmax_t )gap -> ga_len ,2 );// <prefcondcnt> 5781 } 5782size_t totlen = 2 + (size_t )gap -> ga_len ;// <prefcondcnt> and <condlen> bytes 5783for (int i = 0 ;i < gap -> ga_len ;i ++ ) { 5784// <prefcond> : <condlen> <condstr> 5785char * p = ((char ** )gap -> ga_data )[i ]; 5786if (p != NULL ) { 5787size_t len = strlen (p ); 5788if (fd != NULL ) { 5789assert (len <=INT_MAX ); 5790fputc ((int )len ,fd ); 5791* fwv &=fwrite (p ,len ,1 ,fd ); 5792 } 5793totlen += len ; 5794 }else if (fd != NULL ) { 5795fputc (0 ,fd ); 5796 } 5797 } 5798 5799assert (totlen <=INT_MAX ); 5800return (int )totlen ; 5801} 5802 5803// Use map string "map" for languages "lp". 5804static void set_map_str (slang_T * lp ,const char * map ) 5805{ 5806int headc = 0 ; 5807 5808if (* map == NUL ) { 5809lp -> sl_has_map = false; 5810return ; 5811 } 5812lp -> sl_has_map = true; 5813 5814// Init the array and hash tables empty. 5815for (int i = 0 ;i < 256 ;i ++ ) { 5816lp -> sl_map_array [i ]= 0 ; 5817 } 5818hash_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. 5823for (const char * p = map ;* p != NUL ;) { 5824int c = mb_cptr2char_adv (& p ); 5825if (c == '/' ) { 5826headc = 0 ; 5827 }else { 5828if (headc == 0 ) { 5829headc = 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. 5835if (c >=256 ) { 5836int cl = utf_char2len (c ); 5837int headcl = utf_char2len (headc ); 5838hash_T hash ; 5839hashitem_T * hi ; 5840 5841char * b = xmalloc ((size_t )(cl + headcl )+ 2 ); 5842utf_char2bytes (c ,b ); 5843b [cl ]= NUL ; 5844utf_char2bytes (headc ,b + cl + 1 ); 5845b [cl + 1 + headcl ]= NUL ; 5846hash = hash_hash (b ); 5847hi = hash_lookup (& lp -> sl_map_hash ,b ,strlen (b ),hash ); 5848if (HASHITEM_EMPTY (hi )) { 5849hash_add_item (& lp -> sl_map_hash ,hi ,b ,hash ); 5850 }else { 5851// This should have been checked when generating the .spl 5852// file. 5853emsg (_ (e_duplicate_char_in_map_entry )); 5854xfree (b ); 5855 } 5856 }else { 5857lp -> sl_map_array [c ]= headc ; 5858 } 5859 } 5860 } 5861}