robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
184.4 KiB5889 linesraw
1// syntax.c: code for syntax highlighting
2
3#include <assert.h>
4#include <inttypes.h>
5#include <stdbool.h>
6#include <stddef.h>
7#include <stdlib.h>
8#include <string.h>
9
10#include "nvim/ascii_defs.h"
11#include "nvim/autocmd.h"
12#include "nvim/autocmd_defs.h"
13#include "nvim/buffer.h"
14#include "nvim/buffer_defs.h"
15#include "nvim/charset.h"
16#include "nvim/cmdexpand_defs.h"
17#include "nvim/drawscreen.h"
18#include "nvim/errors.h"
19#include "nvim/eval/typval_defs.h"
20#include "nvim/eval/vars.h"
21#include "nvim/ex_cmds_defs.h"
22#include "nvim/ex_docmd.h"
23#include "nvim/fold.h"
24#include "nvim/garray.h"
25#include "nvim/garray_defs.h"
26#include "nvim/gettext_defs.h"
27#include "nvim/globals.h"
28#include "nvim/hashtab.h"
29#include "nvim/hashtab_defs.h"
30#include "nvim/highlight_defs.h"
31#include "nvim/highlight_group.h"
32#include "nvim/indent_c.h"
33#include "nvim/macros_defs.h"
34#include "nvim/mbyte.h"
35#include "nvim/memline.h"
36#include "nvim/memory.h"
37#include "nvim/message.h"
38#include "nvim/option_vars.h"
39#include "nvim/optionstr.h"
40#include "nvim/os/input.h"
41#include "nvim/path.h"
42#include "nvim/pos_defs.h"
43#include "nvim/profile.h"
44#include "nvim/regexp.h"
45#include "nvim/regexp_defs.h"
46#include "nvim/runtime.h"
47#include "nvim/strings.h"
48#include "nvim/syntax.h"
49#include "nvim/types_defs.h"
50#include "nvim/vim_defs.h"
51
52static bool did_syntax_onoff = false;
53
54// different types of offsets that are possible
55#define SPO_MS_OFF      0       // match  start offset
56#define SPO_ME_OFF      1       // match  end   offset
57#define SPO_HS_OFF      2       // highl. start offset
58#define SPO_HE_OFF      3       // highl. end   offset
59#define SPO_RS_OFF      4       // region start offset
60#define SPO_RE_OFF      5       // region end   offset
61#define SPO_LC_OFF      6       // leading context offset
62#define SPO_COUNT       7
63
64static const char e_illegal_arg[] = N_("E390: Illegal argument: %s");
65static const char e_contains_argument_not_accepted_here[]
66  = N_("E395: Contains argument not accepted here");
67static const char e_invalid_cchar_value[]
68  = N_("E844: Invalid cchar value");
69static const char e_trailing_char_after_rsb_str_str[]
70  = N_("E890: Trailing char after ']': %s]%s");
71
72// The patterns that are being searched for are stored in a syn_pattern.
73// A match item consists of one pattern.
74// A start/end item consists of n start patterns and m end patterns.
75// A start/skip/end item consists of n start patterns, one skip pattern and m
76// end patterns.
77// For the latter two, the patterns are always consecutive: start-skip-end.
78//
79// A character offset can be given for the matched text (_m_start and _m_end)
80// and for the actually highlighted text (_h_start and _h_end).
81//
82// Note that ordering of members is optimized to reduce padding.
83typedef struct {
84  char sp_type;                         // see SPTYPE_ defines below
85  bool sp_syncing;                      // this item used for syncing
86  int16_t sp_syn_match_id;              // highlight group ID of pattern
87  int16_t sp_off_flags;                 // see below
88  int sp_offsets[SPO_COUNT];            // offsets
89  int sp_flags;                         // see HL_ defines below
90  int sp_cchar;                         // conceal substitute character
91  int sp_ic;                            // ignore-case flag for sp_prog
92  int sp_sync_idx;                      // sync item index (syncing only)
93  int sp_line_id;                       // ID of last line where tried
94  int sp_startcol;                      // next match in sp_line_id line
95  int16_t *sp_cont_list;                // cont. group IDs, if non-zero
96  int16_t *sp_next_list;                // next group IDs, if non-zero
97  struct sp_syn sp_syn;                 // struct passed to in_id_list()
98  char *sp_pattern;                     // regexp to match, pattern
99  regprog_T *sp_prog;                   // regexp to match, program
100  syn_time_T sp_time;
101} synpat_T;
102
103typedef struct {
104  char *scl_name;           // syntax cluster name
105  char *scl_name_u;         // uppercase of scl_name
106  int16_t *scl_list;        // IDs in this syntax cluster
107} syn_cluster_T;
108
109// For the current state we need to remember more than just the idx.
110// When si_m_endpos.lnum is 0, the items other than si_idx are unknown.
111// (The end positions have the column number of the next char)
112typedef struct {
113  int si_idx;                           // index of syntax pattern or
114                                        // KEYWORD_IDX
115  int si_id;                            // highlight group ID for keywords
116  int si_trans_id;                      // idem, transparency removed
117  int si_m_lnum;                        // lnum of the match
118  int si_m_startcol;                    // starting column of the match
119  lpos_T si_m_endpos;                   // just after end posn of the match
120  lpos_T si_h_startpos;                 // start position of the highlighting
121  lpos_T si_h_endpos;                   // end position of the highlighting
122  lpos_T si_eoe_pos;                    // end position of end pattern
123  int si_end_idx;                       // group ID for end pattern or zero
124  int si_ends;                          // if match ends before si_m_endpos
125  int si_attr;                          // attributes in this state
126  int si_flags;                         // HL_HAS_EOL flag in this state, and
127                                        // HL_SKIP* for si_next_list
128  int si_seqnr;                         // sequence number
129  int si_cchar;                         // substitution character for conceal
130  int16_t *si_cont_list;                // list of contained groups
131  int16_t *si_next_list;                // nextgroup IDs after this item ends
132  reg_extmatch_T *si_extmatch;          // \z(...\) matches from start
133                                        // pattern
134} stateitem_T;
135
136// Struct to reduce the number of arguments to get_syn_options(), it's used
137// very often.
138typedef struct {
139  int flags;                   // flags for contained and transparent
140  bool keyword;                // true for ":syn keyword"
141  int *sync_idx;               // syntax item for "grouphere" argument, NULL
142                               // if not allowed
143  bool has_cont_list;          // true if "cont_list" can be used
144  int16_t *cont_list;          // group IDs for "contains" argument
145  int16_t *cont_in_list;       // group IDs for "containedin" argument
146  int16_t *next_list;          // group IDs for "nextgroup" argument
147} syn_opt_arg_T;
148
149typedef struct {
150  int16_t *idl_key;    ///< the list this entry resolves (NULL when empty)
151  int16_t *idl_ids;    ///< sorted, cluster-expanded group IDs (allocated)
152  int idl_count;       ///< number of IDs in idl_ids
153  int16_t idl_marker;  ///< leading ALLBUT/TOP/CONTAINED item, or 0
154  bool idl_usable;     ///< false: not cacheable, use the slow path
155} idl_entry_T;
156
157typedef struct {
158  proftime_T total;
159  int count;
160  int match;
161  proftime_T slowest;
162  proftime_T average;
163  int id;
164  char *pattern;
165} time_entry_T;
166
167#include "syntax.c.generated.h"
168
169static char *(spo_name_tab[SPO_COUNT]) =
170{ "ms=", "me=", "hs=", "he=", "rs=", "re=", "lc=" };
171
172// The sp_off_flags are computed like this:
173// offset from the start of the matched text: (1 << SPO_XX_OFF)
174// offset from the end   of the matched text: (1 << (SPO_XX_OFF + SPO_COUNT))
175// When both are present, only one is used.
176
177#define SPTYPE_MATCH    1       // match keyword with this group ID
178#define SPTYPE_START    2       // match a regexp, start of item
179#define SPTYPE_END      3       // match a regexp, end of item
180#define SPTYPE_SKIP     4       // match a regexp, skip within item
181
182#define SYN_ITEMS(buf)  ((synpat_T *)((buf)->b_syn_patterns.ga_data))
183
184#define NONE_IDX        (-2)    // value of sp_sync_idx for "NONE"
185
186// Flags for b_syn_sync_flags:
187#define SF_CCOMMENT     0x01    // sync on a C-style comment
188#define SF_MATCH        0x02    // sync by matching a pattern
189
190#define SYN_STATE_P(ssp)    ((bufstate_T *)((ssp)->ga_data))
191
192#define MAXKEYWLEN      80          // maximum length of a keyword
193
194// The attributes of the syntax item that has been recognized.
195static int current_attr = 0;        // attr of current syntax word
196static int current_id = 0;          // ID of current char for syn_get_id()
197static int current_trans_id = 0;    // idem, transparency removed
198static int current_flags = 0;
199static int current_seqnr = 0;
200static int current_sub_char = 0;
201
202// Methods of combining two clusters
203#define CLUSTER_REPLACE     1   // replace first list with second
204#define CLUSTER_ADD         2   // add second list to first
205#define CLUSTER_SUBTRACT    3   // subtract second list from first
206
207#define SYN_CLSTR(buf)  ((syn_cluster_T *)((buf)->b_syn_clusters.ga_data))
208
209// Syntax group IDs have different types:
210//     0 - 19999  normal syntax groups
211// 20000 - 20999  ALLBUT indicator (current_syn_inc_tag added)
212// 21000 - 21999  TOP indicator (current_syn_inc_tag added)
213// 22000 - 22999  CONTAINED indicator (current_syn_inc_tag added)
214// 23000 - 32767  cluster IDs (subtract SYNID_CLUSTER for the cluster ID)
215#define SYNID_ALLBUT    MAX_HL_ID   // syntax group ID for contains=ALLBUT
216#define SYNID_TOP       21000       // syntax group ID for contains=TOP
217#define SYNID_CONTAINED 22000       // syntax group ID for contains=CONTAINED
218#define SYNID_CLUSTER   23000       // first syntax group ID for clusters
219
220#define MAX_SYN_INC_TAG 999         // maximum before the above overflow
221#define MAX_CLUSTER_ID  (32767 - SYNID_CLUSTER)
222
223// Annoying Hack(TM):  ":syn include" needs this pointer to pass to
224// expand_filename().  Most of the other syntax commands don't need it, so
225// instead of passing it to them, we stow it here.
226static char **syn_cmdlinep;
227
228// Another Annoying Hack(TM):  To prevent rules from other ":syn include"'d
229// files from leaking into ALLBUT lists, we assign a unique ID to the
230// rules in each ":syn include"'d file.
231static int current_syn_inc_tag = 0;
232static int running_syn_inc_tag = 0;
233
234// In a hashtable item "hi_key" points to "keyword" in a keyentry.
235// This avoids adding a pointer to the hashtable item.
236// KE2HIKEY() converts a var pointer to a hashitem key pointer.
237// HIKEY2KE() converts a hashitem key pointer to a var pointer.
238// HI2KE() converts a hashitem pointer to a var pointer.
239#define KE2HIKEY(kp)  ((kp)->keyword)
240#define HIKEY2KE(p)   ((keyentry_T *)((p) - offsetof(keyentry_T, keyword)))
241#define HI2KE(hi)      HIKEY2KE((hi)->hi_key)
242
243// To reduce the time spent in keepend(), remember at which level in the state
244// stack the first item with "keepend" is present.  When "-1", there is no
245// "keepend" on the stack.
246static int keepend_level = -1;
247
248static char msg_no_items[] = N_("No Syntax items defined for this buffer");
249
250// value of si_idx for keywords
251#define KEYWORD_IDX     (-1)
252// valid of si_cont_list for containing all but contained groups
253#define ID_LIST_ALL     ((int16_t *)-1)
254
255static int next_seqnr = 1;              // value to use for si_seqnr
256
257// The next possible match in the current line for any pattern is remembered,
258// to avoid having to try for a match in each column.
259// If next_match_idx == -1, not tried (in this line) yet.
260// If next_match_col == MAXCOL, no match found in this line.
261// (All end positions have the column of the char after the end)
262static int next_match_col;              // column for start of next match
263static lpos_T next_match_m_endpos;      // position for end of next match
264static lpos_T next_match_h_startpos;    // pos. for highl. start of next match
265static lpos_T next_match_h_endpos;      // pos. for highl. end of next match
266static int next_match_idx;              // index of matched item
267static int next_match_flags;            // flags for next match
268static lpos_T next_match_eos_pos;       // end of start pattn (start region)
269static lpos_T next_match_eoe_pos;       // pos. for end of end pattern
270static int next_match_end_idx;          // ID of group for end pattn or zero
271static reg_extmatch_T *next_match_extmatch = NULL;
272
273// A state stack is an array of integers or stateitem_T, stored in a
274// garray_T.  A state stack is invalid if its itemsize entry is zero.
275#define INVALID_STATE(ssp)  ((ssp)->ga_itemsize == 0)
276#define VALID_STATE(ssp)    ((ssp)->ga_itemsize != 0)
277
278// The current state (within the line) of the recognition engine.
279// When current_state.ga_itemsize is 0 the current state is invalid.
280static win_T *syn_win;                  // current window for highlighting
281static buf_T *syn_buf;                  // current buffer for highlighting
282static synblock_T *syn_block;              // current buffer for highlighting
283static proftime_T *syn_tm;                 // timeout limit
284static linenr_T current_lnum = 0;          // lnum of current state
285static colnr_T current_col = 0;            // column of current state
286static bool current_state_stored = false;  // true if stored current state
287                                           // after setting current_finished
288static bool current_finished = false;      // current line has been finished
289static garray_T current_state              // current stack of state_items
290  = GA_EMPTY_INIT_VALUE;
291static int16_t *current_next_list = NULL;  // when non-zero, nextgroup list
292static int current_next_flags = 0;         // flags for current_next_list
293static int current_line_id = 0;            // unique number for current line
294
295#define CUR_STATE(idx)  ((stateitem_T *)(current_state.ga_data))[idx]
296
297static bool syn_time_on = false;
298#define IF_SYN_TIME(p) (p)
299
300// Set the timeout used for syntax highlighting.
301// Use NULL to reset, no timeout.
302void syn_set_timeout(proftime_T *tm)
303{
304  syn_tm = tm;
305}
306
307// Start the syntax recognition for a line.  This function is normally called
308// from the screen updating, once for each displayed line.
309// The buffer is remembered in syn_buf, because get_syntax_attr() doesn't get
310// it.  Careful: curbuf and curwin are likely to point to another buffer and
311// window.
312void syntax_start(win_T *wp, linenr_T lnum)
313{
314  synstate_T *last_valid = NULL;
315  synstate_T *last_min_valid = NULL;
316  synstate_T *sp;
317  synstate_T *prev = NULL;
318  linenr_T first_stored;
319  int dist;
320  static varnumber_T changedtick = 0;  // remember the last change ID
321
322  current_sub_char = NUL;
323
324  // After switching buffers, invalidate current_state.
325  // Also do this when a change was made, the current state may be invalid
326  // then.
327  if (syn_block != wp->w_s
328      || syn_buf != wp->w_buffer
329      || changedtick != buf_get_changedtick(syn_buf)) {
330    invalidate_current_state();
331    syn_buf = wp->w_buffer;
332    syn_block = wp->w_s;
333  }
334  changedtick = buf_get_changedtick(syn_buf);
335  syn_win = wp;
336
337  // Allocate syntax stack when needed.
338  syn_stack_alloc();
339  if (syn_block->b_sst_array == NULL) {
340    return;             // out of memory
341  }
342  syn_block->b_sst_lasttick = display_tick;
343
344  // If the state of the end of the previous line is useful, store it.
345  if (VALID_STATE(&current_state)
346      && current_lnum < lnum
347      && current_lnum < syn_buf->b_ml.ml_line_count) {
348    syn_finish_line(false);
349    if (!current_state_stored) {
350      current_lnum++;
351      store_current_state();
352    }
353
354    // If the current_lnum is now the same as "lnum", keep the current
355    // state (this happens very often!).  Otherwise invalidate
356    // current_state and figure it out below.
357    if (current_lnum != lnum) {
358      invalidate_current_state();
359    }
360  } else {
361    invalidate_current_state();
362  }
363
364  // Try to synchronize from a saved state in b_sst_array[].
365  // Only do this if lnum is not before and not to far beyond a saved state.
366  if (INVALID_STATE(&current_state) && syn_block->b_sst_array != NULL) {
367    // Find last valid saved state before start_lnum.
368    for (synstate_T *p = syn_block->b_sst_first; p != NULL; p = p->sst_next) {
369      if (p->sst_lnum > lnum) {
370        break;
371      }
372      if (p->sst_change_lnum == 0) {
373        last_valid = p;
374        if (p->sst_lnum >= lnum - syn_block->b_syn_sync_minlines) {
375          last_min_valid = p;
376        }
377      }
378    }
379    if (last_min_valid != NULL) {
380      load_current_state(last_min_valid);
381    }
382  }
383
384  // If "lnum" is before or far beyond a line with a saved state, need to
385  // re-synchronize.
386  if (INVALID_STATE(&current_state)) {
387    syn_sync(wp, lnum, last_valid);
388    if (current_lnum == 1) {
389      // First line is always valid, no matter "minlines".
390      first_stored = 1;
391    } else {
392      // Need to parse "minlines" lines before state can be considered
393      // valid to store.
394      first_stored = current_lnum + syn_block->b_syn_sync_minlines;
395    }
396  } else {
397    first_stored = current_lnum;
398  }
399
400  // Advance from the sync point or saved state until the current line.
401  // Save some entries for syncing with later on.
402  if (syn_block->b_sst_len <= Rows) {
403    dist = 999999;
404  } else {
405    dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1;
406  }
407  while (current_lnum < lnum) {
408    syn_start_line();
409    syn_finish_line(false);
410    current_lnum++;
411
412    // If we parsed at least "minlines" lines or started at a valid
413    // state, the current state is considered valid.
414    if (current_lnum >= first_stored) {
415      // Check if the saved state entry is for the current line and is
416      // equal to the current state.  If so, then validate all saved
417      // states that depended on a change before the parsed line.
418      if (prev == NULL) {
419        prev = syn_stack_find_entry(current_lnum - 1);
420      }
421      if (prev == NULL) {
422        sp = syn_block->b_sst_first;
423      } else {
424        sp = prev;
425      }
426      while (sp != NULL && sp->sst_lnum < current_lnum) {
427        sp = sp->sst_next;
428      }
429      if (sp != NULL
430          && sp->sst_lnum == current_lnum
431          && syn_stack_equal(sp)) {
432        linenr_T parsed_lnum = current_lnum;
433        prev = sp;
434        while (sp != NULL && sp->sst_change_lnum <= parsed_lnum) {
435          if (sp->sst_lnum <= lnum) {
436            // valid state before desired line, use this one
437            prev = sp;
438          } else if (sp->sst_change_lnum == 0) {
439            // past saved states depending on change, break here.
440            break;
441          }
442          sp->sst_change_lnum = 0;
443          sp = sp->sst_next;
444        }
445        load_current_state(prev);
446      } else if (prev == NULL
447                 // Store the state at this line when it's the first one, the line
448                 // where we start parsing, or some distance from the previously
449                 // saved state.  But only when parsed at least 'minlines'.
450                 || current_lnum == lnum
451                 || current_lnum >= prev->sst_lnum + dist) {
452        prev = store_current_state();
453      }
454    }
455
456    // This can take a long time: break when CTRL-C pressed.  The current
457    // state will be wrong then.
458    line_breakcheck();
459    if (got_int) {
460      current_lnum = lnum;
461      break;
462    }
463  }
464
465  syn_start_line();
466}
467
468// We cannot simply discard growarrays full of state_items or buf_states; we
469// have to manually release their extmatch pointers first.
470static void clear_syn_state(synstate_T *p)
471{
472  if (p->sst_stacksize > SST_FIX_STATES) {
473#define UNREF_BUFSTATE_EXTMATCH(bs) unref_extmatch((bs)->bs_extmatch)
474    GA_DEEP_CLEAR(&(p->sst_union.sst_ga), bufstate_T, UNREF_BUFSTATE_EXTMATCH);
475  } else {
476    for (int i = 0; i < p->sst_stacksize; i++) {
477      unref_extmatch(p->sst_union.sst_stack[i].bs_extmatch);
478    }
479  }
480}
481
482// Cleanup the current_state stack.
483static void clear_current_state(void)
484{
485#define UNREF_STATEITEM_EXTMATCH(si) unref_extmatch((si)->si_extmatch)
486  GA_DEEP_CLEAR(&current_state, stateitem_T, UNREF_STATEITEM_EXTMATCH);
487}
488
489// Try to find a synchronisation point for line "lnum".
490//
491// This sets current_lnum and the current state.  One of three methods is
492// used:
493// 1. Search backwards for the end of a C-comment.
494// 2. Search backwards for given sync patterns.
495// 3. Simply start on a given number of lines above "lnum".
496static void syn_sync(win_T *wp, linenr_T start_lnum, synstate_T *last_valid)
497{
498  pos_T cursor_save;
499  linenr_T lnum;
500  linenr_T break_lnum;
501  stateitem_T *cur_si;
502  synpat_T *spp;
503  int found_flags = 0;
504  int found_match_idx = 0;
505  linenr_T found_current_lnum = 0;
506  int found_current_col = 0;
507  lpos_T found_m_endpos;
508
509  // Clear any current state that might be hanging around.
510  invalidate_current_state();
511
512  // Start at least "minlines" back.  Default starting point for parsing is
513  // there.
514  // Start further back, to avoid that scrolling backwards will result in
515  // resyncing for every line.  Now it resyncs only one out of N lines,
516  // where N is minlines * 1.5, or minlines * 2 if minlines is small.
517  // Watch out for overflow when minlines is MAXLNUM.
518  if (syn_block->b_syn_sync_minlines > start_lnum) {
519    start_lnum = 1;
520  } else {
521    if (syn_block->b_syn_sync_minlines == 1) {
522      lnum = 1;
523    } else if (syn_block->b_syn_sync_minlines < 10) {
524      lnum = syn_block->b_syn_sync_minlines * 2;
525    } else {
526      lnum = syn_block->b_syn_sync_minlines * 3 / 2;
527    }
528    if (syn_block->b_syn_sync_maxlines != 0
529        && lnum > syn_block->b_syn_sync_maxlines) {
530      lnum = syn_block->b_syn_sync_maxlines;
531    }
532    if (lnum >= start_lnum) {
533      start_lnum = 1;
534    } else {
535      start_lnum -= lnum;
536    }
537  }
538  current_lnum = start_lnum;
539
540  // 1. Search backwards for the end of a C-style comment.
541  if (syn_block->b_syn_sync_flags & SF_CCOMMENT) {
542    // Need to make syn_buf the current buffer for a moment, to be able to
543    // use find_start_comment().
544    win_T *curwin_save = curwin;
545    curwin = wp;
546    buf_T *curbuf_save = curbuf;
547    curbuf = syn_buf;
548
549    // Skip lines that end in a backslash.
550    for (; start_lnum > 1; start_lnum--) {
551      char *l = ml_get(start_lnum - 1);
552      if (*l == NUL || *(l + ml_get_len(start_lnum - 1) - 1) != '\\') {
553        break;
554      }
555    }
556    current_lnum = start_lnum;
557
558    // set cursor to start of search
559    cursor_save = wp->w_cursor;
560    wp->w_cursor.lnum = start_lnum;
561    wp->w_cursor.col = 0;
562
563    // If the line is inside a comment, need to find the syntax item that
564    // defines the comment.
565    // Restrict the search for the end of a comment to b_syn_sync_maxlines.
566    if (find_start_comment((int)syn_block->b_syn_sync_maxlines) != NULL) {
567      for (int idx = syn_block->b_syn_patterns.ga_len; --idx >= 0;) {
568        if (SYN_ITEMS(syn_block)[idx].sp_syn.id
569            == syn_block->b_syn_sync_id
570            && SYN_ITEMS(syn_block)[idx].sp_type == SPTYPE_START) {
571          validate_current_state();
572          push_current_state(idx);
573          update_si_attr(current_state.ga_len - 1);
574          break;
575        }
576      }
577    }
578
579    // restore cursor and buffer
580    wp->w_cursor = cursor_save;
581    curwin = curwin_save;
582    curbuf = curbuf_save;
583  } else if (syn_block->b_syn_sync_flags & SF_MATCH) {
584    // 2. Search backwards for given sync patterns.
585    if (syn_block->b_syn_sync_maxlines != 0
586        && start_lnum > syn_block->b_syn_sync_maxlines) {
587      break_lnum = start_lnum - syn_block->b_syn_sync_maxlines;
588    } else {
589      break_lnum = 0;
590    }
591
592    found_m_endpos.lnum = 0;
593    found_m_endpos.col = 0;
594    linenr_T end_lnum = start_lnum;
595    lnum = start_lnum;
596    while (--lnum > break_lnum) {
597      // This can take a long time: break when CTRL-C pressed.
598      line_breakcheck();
599      if (got_int) {
600        invalidate_current_state();
601        current_lnum = start_lnum;
602        break;
603      }
604
605      // Check if we have run into a valid saved state stack now.
606      if (last_valid != NULL && lnum == last_valid->sst_lnum) {
607        load_current_state(last_valid);
608        break;
609      }
610
611      // Check if the previous line has the line-continuation pattern.
612      if (lnum > 1 && syn_match_linecont(lnum - 1)) {
613        continue;
614      }
615
616      // Start with nothing on the state stack
617      validate_current_state();
618
619      for (current_lnum = lnum; current_lnum < end_lnum; current_lnum++) {
620        syn_start_line();
621        while (true) {
622          bool had_sync_point = syn_finish_line(true);
623          // When a sync point has been found, remember where, and
624          // continue to look for another one, further on in the line.
625          if (had_sync_point && current_state.ga_len) {
626            cur_si = &CUR_STATE(current_state.ga_len - 1);
627            if (cur_si->si_m_endpos.lnum > start_lnum) {
628              // ignore match that goes to after where started
629              current_lnum = end_lnum;
630              break;
631            }
632            if (cur_si->si_idx < 0) {
633              // Cannot happen?
634              found_flags = 0;
635              found_match_idx = KEYWORD_IDX;
636            } else {
637              spp = &(SYN_ITEMS(syn_block)[cur_si->si_idx]);
638              found_flags = spp->sp_flags;
639              found_match_idx = spp->sp_sync_idx;
640            }
641            found_current_lnum = current_lnum;
642            found_current_col = current_col;
643            found_m_endpos = cur_si->si_m_endpos;
644            // Continue after the match (be aware of a zero-length
645            // match).
646            if (found_m_endpos.lnum > current_lnum) {
647              current_lnum = found_m_endpos.lnum;
648              current_col = found_m_endpos.col;
649              if (current_lnum >= end_lnum) {
650                break;
651              }
652            } else if (found_m_endpos.col > current_col) {
653              current_col = found_m_endpos.col;
654            } else {
655              current_col++;
656            }
657
658            // syn_current_attr() will have skipped the check for
659            // an item that ends here, need to do that now.  Be
660            // careful not to go past the NUL.
661            colnr_T prev_current_col = current_col;
662            if (syn_getcurline()[current_col] != NUL) {
663              current_col++;
664            }
665            check_state_ends();
666            current_col = prev_current_col;
667          } else {
668            break;
669          }
670        }
671      }
672
673      // If a sync point was encountered, break here.
674      if (found_flags) {
675        // Put the item that was specified by the sync point on the
676        // state stack.  If there was no item specified, make the
677        // state stack empty.
678        clear_current_state();
679        if (found_match_idx >= 0) {
680          push_current_state(found_match_idx);
681          update_si_attr(current_state.ga_len - 1);
682        }
683
684        // When using "grouphere", continue from the sync point
685        // match, until the end of the line.  Parsing starts at
686        // the next line.
687        // For "groupthere" the parsing starts at start_lnum.
688        if (found_flags & HL_SYNC_HERE) {
689          current_lnum = found_m_endpos.lnum;
690          current_col = found_m_endpos.col;
691          if (!GA_EMPTY(&current_state)) {
692            cur_si = &CUR_STATE(current_state.ga_len - 1);
693            cur_si->si_h_startpos.lnum = found_current_lnum;
694            cur_si->si_h_startpos.col = found_current_col;
695            update_si_end(cur_si, (int)current_col, true);
696            check_keepend();
697          }
698          syn_finish_line(false);
699          current_lnum++;
700        } else {
701          current_lnum = start_lnum;
702        }
703
704        break;
705      }
706
707      end_lnum = lnum;
708      invalidate_current_state();
709    }
710
711    // Ran into start of the file or exceeded maximum number of lines
712    if (lnum <= break_lnum) {
713      invalidate_current_state();
714      current_lnum = break_lnum + 1;
715    }
716  }
717
718  validate_current_state();
719}
720
721static void save_chartab(char *chartab)
722{
723  if (syn_block->b_syn_isk == empty_string_option) {
724    return;
725  }
726
727  // TODO(bfredl): what really now?
728  memmove(chartab, syn_buf->b_chartab, (size_t)32);
729  memmove(syn_buf->b_chartab, syn_win->w_s->b_syn_chartab, (size_t)32);
730}
731
732static void restore_chartab(char *chartab)
733{
734  if (syn_win->w_s->b_syn_isk != empty_string_option) {
735    memmove(syn_buf->b_chartab, chartab, (size_t)32);
736  }
737}
738
739/// Return true if the line-continuation pattern matches in line "lnum".
740static int syn_match_linecont(linenr_T lnum)
741{
742  if (syn_block->b_syn_linecont_prog == NULL) {
743    return false;
744  }
745
746  regmmatch_T regmatch;
747  // chartab array for syn iskeyword
748  char buf_chartab[32];
749  save_chartab(buf_chartab);
750
751  regmatch.rmm_ic = syn_block->b_syn_linecont_ic;
752  regmatch.regprog = syn_block->b_syn_linecont_prog;
753  int r = syn_regexec(&regmatch, lnum, 0,
754                      IF_SYN_TIME(&syn_block->b_syn_linecont_time));
755  syn_block->b_syn_linecont_prog = regmatch.regprog;
756
757  restore_chartab(buf_chartab);
758  return r;
759}
760
761// Prepare the current state for the start of a line.
762static void syn_start_line(void)
763{
764  current_finished = false;
765  current_col = 0;
766
767  // Need to update the end of a start/skip/end that continues from the
768  // previous line and regions that have "keepend".
769  if (!GA_EMPTY(&current_state)) {
770    syn_update_ends(true);
771    check_state_ends();
772  }
773
774  next_match_idx = -1;
775  current_line_id++;
776  next_seqnr = 1;
777}
778
779/// Check for items in the stack that need their end updated.
780///
781/// @param startofline  if true the last item is always updated.
782///                     if false the item with "keepend" is forcefully updated.
783static void syn_update_ends(bool startofline)
784{
785  stateitem_T *cur_si;
786
787  if (startofline) {
788    // Check for a match carried over from a previous line with a
789    // contained region.  The match ends as soon as the region ends.
790    for (int i = 0; i < current_state.ga_len; i++) {
791      cur_si = &CUR_STATE(i);
792      if (cur_si->si_idx >= 0
793          && (SYN_ITEMS(syn_block)[cur_si->si_idx]).sp_type
794          == SPTYPE_MATCH
795          && cur_si->si_m_endpos.lnum < current_lnum) {
796        cur_si->si_flags |= HL_MATCHCONT;
797        cur_si->si_m_endpos.lnum = 0;
798        cur_si->si_m_endpos.col = 0;
799        cur_si->si_h_endpos = cur_si->si_m_endpos;
800        cur_si->si_ends = true;
801      }
802    }
803  }
804
805  // Need to update the end of a start/skip/end that continues from the
806  // previous line.  And regions that have "keepend", because they may
807  // influence contained items.  If we've just removed "extend"
808  // (startofline == 0) then we should update ends of normal regions
809  // contained inside "keepend" because "extend" could have extended
810  // these "keepend" regions as well as contained normal regions.
811  // Then check for items ending in column 0.
812  int i = current_state.ga_len - 1;
813  if (keepend_level >= 0) {
814    for (; i > keepend_level; i--) {
815      if (CUR_STATE(i).si_flags & HL_EXTEND) {
816        break;
817      }
818    }
819  }
820
821  bool seen_keepend = false;
822  for (; i < current_state.ga_len; i++) {
823    cur_si = &CUR_STATE(i);
824    if ((cur_si->si_flags & HL_KEEPEND)
825        || (seen_keepend && !startofline)
826        || (i == current_state.ga_len - 1 && startofline)) {
827      cur_si->si_h_startpos.col = 0;            // start highl. in col 0
828      cur_si->si_h_startpos.lnum = current_lnum;
829
830      if (!(cur_si->si_flags & HL_MATCHCONT)) {
831        update_si_end(cur_si, (int)current_col, !startofline);
832      }
833
834      if (!startofline && (cur_si->si_flags & HL_KEEPEND)) {
835        seen_keepend = true;
836      }
837    }
838  }
839  check_keepend();
840}
841
842/////////////////////////////////////////
843// Handling of the state stack cache.
844
845// EXPLANATION OF THE SYNTAX STATE STACK CACHE
846//
847// To speed up syntax highlighting, the state stack for the start of some
848// lines is cached.  These entries can be used to start parsing at that point.
849//
850// The stack is kept in b_sst_array[] for each buffer.  There is a list of
851// valid entries.  b_sst_first points to the first one, then follow sst_next.
852// The entries are sorted on line number.  The first entry is often for line 2
853// (line 1 always starts with an empty stack).
854// There is also a list for free entries.  This construction is used to avoid
855// having to allocate and free memory blocks too often.
856//
857// When making changes to the buffer, this is logged in b_mod_*.  When calling
858// update_screen() to update the display, it will call
859// syn_stack_apply_changes() for each displayed buffer to adjust the cached
860// entries.  The entries which are inside the changed area are removed,
861// because they must be recomputed.  Entries below the changed have their line
862// number adjusted for deleted/inserted lines, and have their sst_change_lnum
863// set to indicate that a check must be made if the changed lines would change
864// the cached entry.
865//
866// When later displaying lines, an entry is stored for each line.  Displayed
867// lines are likely to be displayed again, in which case the state at the
868// start of the line is needed.
869// For not displayed lines, an entry is stored for every so many lines.  These
870// entries will be used e.g., when scrolling backwards.  The distance between
871// entries depends on the number of lines in the buffer.  For small buffers
872// the distance is fixed at SST_DIST, for large buffers there is a fixed
873// number of entries SST_MAX_ENTRIES, and the distance is computed.
874
875static void syn_stack_free_block(synblock_T *block)
876{
877  // Syntax definitions may have changed: drop the in_id_list() cache.
878  idl_cache_clear(block);
879
880  if (block->b_sst_array == NULL) {
881    return;
882  }
883
884  for (synstate_T *p = block->b_sst_first; p != NULL; p = p->sst_next) {
885    clear_syn_state(p);
886  }
887  XFREE_CLEAR(block->b_sst_array);
888  block->b_sst_first = NULL;
889  block->b_sst_search = NULL;
890  block->b_sst_len = 0;
891}
892// Free b_sst_array[] for buffer "buf".
893// Used when syntax items changed to force resyncing everywhere.
894void syn_stack_free_all(synblock_T *block)
895{
896  syn_stack_free_block(block);
897
898  // When using "syntax" fold method, must update all folds.
899  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
900    if (wp->w_s == block && foldmethodIsSyntax(wp)) {
901      foldUpdateAll(wp);
902    }
903  }
904}
905
906// Allocate the syntax state stack for syn_buf when needed.
907// If the number of entries in b_sst_array[] is much too big or a bit too
908// small, reallocate it.
909// Also used to allocate b_sst_array[] for the first time.
910static void syn_stack_alloc(void)
911{
912  int len = syn_buf->b_ml.ml_line_count / SST_DIST + Rows * 2;
913  if (len < SST_MIN_ENTRIES) {
914    len = SST_MIN_ENTRIES;
915  } else if (len > SST_MAX_ENTRIES) {
916    len = SST_MAX_ENTRIES;
917  }
918  if (syn_block->b_sst_len > len * 2 || syn_block->b_sst_len < len) {
919    // Allocate 50% too much, to avoid reallocating too often.
920    len = syn_buf->b_ml.ml_line_count;
921    len = (len + len / 2) / SST_DIST + Rows * 2;
922    if (len < SST_MIN_ENTRIES) {
923      len = SST_MIN_ENTRIES;
924    } else if (len > SST_MAX_ENTRIES) {
925      len = SST_MAX_ENTRIES;
926    }
927
928    if (syn_block->b_sst_array != NULL) {
929      // When shrinking the array, cleanup the existing stack.
930      // Make sure that all valid entries fit in the new array.
931      while (syn_block->b_sst_len - syn_block->b_sst_freecount + 2 > len
932             && syn_stack_cleanup()) {}
933      if (len < syn_block->b_sst_len - syn_block->b_sst_freecount + 2) {
934        len = syn_block->b_sst_len - syn_block->b_sst_freecount + 2;
935      }
936    }
937
938    assert(len >= 0);
939    synstate_T *sstp = xcalloc((size_t)len, sizeof(synstate_T));
940
941    synstate_T *to = sstp - 1;
942    if (syn_block->b_sst_array != NULL) {
943      // Move the states from the old array to the new one.
944      for (synstate_T *from = syn_block->b_sst_first; from != NULL;
945           from = from->sst_next) {
946        to++;
947        *to = *from;
948        to->sst_next = to + 1;
949      }
950    }
951    if (to != sstp - 1) {
952      to->sst_next = NULL;
953      syn_block->b_sst_first = sstp;
954      syn_block->b_sst_freecount = len - (int)(to - sstp) - 1;
955    } else {
956      syn_block->b_sst_first = NULL;
957      syn_block->b_sst_freecount = len;
958    }
959
960    // Create the list of free entries.
961    syn_block->b_sst_firstfree = to + 1;
962    while (++to < sstp + len) {
963      to->sst_next = to + 1;
964    }
965    (sstp + len - 1)->sst_next = NULL;
966
967    xfree(syn_block->b_sst_array);
968    syn_block->b_sst_array = sstp;
969    syn_block->b_sst_len = len;
970    // The entries were moved to a new array, drop the stale pointer.
971    syn_block->b_sst_search = NULL;
972  }
973}
974
975// Check for changes in a buffer to affect stored syntax states.  Uses the
976// b_mod_* fields.
977// Called from update_screen(), before screen is being updated, once for each
978// displayed buffer.
979void syn_stack_apply_changes(buf_T *buf)
980{
981  syn_stack_apply_changes_block(&buf->b_s, buf);
982
983  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
984    if ((wp->w_buffer == buf) && (wp->w_s != &buf->b_s)) {
985      syn_stack_apply_changes_block(wp->w_s, buf);
986    }
987  }
988}
989
990static void syn_stack_apply_changes_block(synblock_T *block, buf_T *buf)
991{
992  synstate_T *prev = NULL;
993  for (synstate_T *p = block->b_sst_first; p != NULL;) {
994    if (p->sst_lnum + block->b_syn_sync_linebreaks > buf->b_mod_top) {
995      linenr_T n = p->sst_lnum + buf->b_mod_xlines;
996      if (n <= buf->b_mod_bot) {
997        // this state is inside the changed area, remove it
998        synstate_T *np = p->sst_next;
999        if (prev == NULL) {
1000          block->b_sst_first = np;
1001        } else {
1002          prev->sst_next = np;
1003        }
1004        syn_stack_free_entry(block, p);
1005        p = np;
1006        continue;
1007      }
1008      // This state is below the changed area.  Remember the line
1009      // that needs to be parsed before this entry can be made valid
1010      // again.
1011      if (p->sst_change_lnum != 0 && p->sst_change_lnum > buf->b_mod_top) {
1012        if (p->sst_change_lnum + buf->b_mod_xlines > buf->b_mod_top) {
1013          p->sst_change_lnum += buf->b_mod_xlines;
1014        } else {
1015          p->sst_change_lnum = buf->b_mod_top;
1016        }
1017      }
1018      if (p->sst_change_lnum == 0
1019          || p->sst_change_lnum < buf->b_mod_bot) {
1020        p->sst_change_lnum = buf->b_mod_bot;
1021      }
1022
1023      p->sst_lnum = n;
1024    }
1025    prev = p;
1026    p = p->sst_next;
1027  }
1028}
1029
1030/// Reduce the number of entries in the state stack for syn_buf.
1031///
1032/// @return  true if at least one entry was freed.
1033static bool syn_stack_cleanup(void)
1034{
1035  synstate_T *prev;
1036  disptick_T tick;
1037  int dist;
1038  bool retval = false;
1039
1040  if (syn_block->b_sst_first == NULL) {
1041    return retval;
1042  }
1043
1044  // Compute normal distance between non-displayed entries.
1045  if (syn_block->b_sst_len <= Rows) {
1046    dist = 999999;
1047  } else {
1048    dist = syn_buf->b_ml.ml_line_count / (syn_block->b_sst_len - Rows) + 1;
1049  }
1050
1051  // Go through the list to find the "tick" for the oldest entry that can
1052  // be removed.  Set "above" when the "tick" for the oldest entry is above
1053  // "b_sst_lasttick" (the display tick wraps around).
1054  tick = syn_block->b_sst_lasttick;
1055  bool above = false;
1056  prev = syn_block->b_sst_first;
1057  for (synstate_T *p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) {
1058    if (prev->sst_lnum + dist > p->sst_lnum) {
1059      if (p->sst_tick > syn_block->b_sst_lasttick) {
1060        if (!above || p->sst_tick < tick) {
1061          tick = p->sst_tick;
1062        }
1063        above = true;
1064      } else if (!above && p->sst_tick < tick) {
1065        tick = p->sst_tick;
1066      }
1067    }
1068  }
1069
1070  // Go through the list to make the entries for the oldest tick at an
1071  // interval of several lines.
1072  prev = syn_block->b_sst_first;
1073  for (synstate_T *p = prev->sst_next; p != NULL; prev = p, p = p->sst_next) {
1074    if (p->sst_tick == tick && prev->sst_lnum + dist > p->sst_lnum) {
1075      // Move this entry from used list to free list
1076      prev->sst_next = p->sst_next;
1077      syn_stack_free_entry(syn_block, p);
1078      p = prev;
1079      retval = true;
1080    }
1081  }
1082  return retval;
1083}
1084
1085// Free the allocated memory for a syn_state item.
1086// Move the entry into the free list.
1087static void syn_stack_free_entry(synblock_T *block, synstate_T *p)
1088{
1089  if (block->b_sst_search == p) {
1090    block->b_sst_search = NULL;
1091  }
1092  clear_syn_state(p);
1093  p->sst_next = block->b_sst_firstfree;
1094  block->b_sst_firstfree = p;
1095  block->b_sst_freecount++;
1096}
1097
1098// Find an entry in the list of state stacks at or before "lnum".
1099// Returns NULL when there is no entry or the first entry is after "lnum".
1100static synstate_T *syn_stack_find_entry(linenr_T lnum)
1101{
1102  synstate_T *prev = NULL;
1103  synstate_T *p = syn_block->b_sst_first;
1104
1105  // The list is sorted by line number and lookups while parsing advance
1106  // monotonically, so resume from the last returned entry instead of
1107  // rescanning from the start whenever it is at or before "lnum".
1108  if (syn_block->b_sst_search != NULL && syn_block->b_sst_search->sst_lnum <= lnum) {
1109    p = syn_block->b_sst_search;
1110  }
1111
1112  for (; p != NULL; prev = p, p = p->sst_next) {
1113    if (p->sst_lnum == lnum) {
1114      syn_block->b_sst_search = p;
1115      return p;
1116    }
1117    if (p->sst_lnum > lnum) {
1118      break;
1119    }
1120  }
1121  if (prev != NULL) {
1122    syn_block->b_sst_search = prev;
1123  }
1124  return prev;
1125}
1126
1127// Try saving the current state in b_sst_array[].
1128// The current state must be valid for the start of the current_lnum line!
1129static synstate_T *store_current_state(void)
1130{
1131  int i;
1132  synstate_T *p;
1133  bufstate_T *bp;
1134  stateitem_T *cur_si;
1135  synstate_T *sp = syn_stack_find_entry(current_lnum);
1136
1137  // If the current state contains a start or end pattern that continues
1138  // from the previous line, we can't use it.  Don't store it then.
1139  for (i = current_state.ga_len - 1; i >= 0; i--) {
1140    cur_si = &CUR_STATE(i);
1141    if (cur_si->si_h_startpos.lnum >= current_lnum
1142        || cur_si->si_m_endpos.lnum >= current_lnum
1143        || cur_si->si_h_endpos.lnum >= current_lnum
1144        || (cur_si->si_end_idx
1145            && cur_si->si_eoe_pos.lnum >= current_lnum)) {
1146      break;
1147    }
1148  }
1149  if (i >= 0) {
1150    if (sp != NULL) {
1151      // find "sp" in the list and remove it
1152      if (syn_block->b_sst_first == sp) {
1153        // it's the first entry
1154        syn_block->b_sst_first = sp->sst_next;
1155      } else {
1156        // find the entry just before this one to adjust sst_next
1157        for (p = syn_block->b_sst_first; p != NULL; p = p->sst_next) {
1158          if (p->sst_next == sp) {
1159            break;
1160          }
1161        }
1162        if (p != NULL) {        // just in case
1163          p->sst_next = sp->sst_next;
1164        }
1165      }
1166      syn_stack_free_entry(syn_block, sp);
1167      sp = NULL;
1168    }
1169  } else if (sp == NULL || sp->sst_lnum != current_lnum) {
1170    // Add a new entry
1171    // If no free items, cleanup the array first.
1172    if (syn_block->b_sst_freecount == 0) {
1173      syn_stack_cleanup();
1174      // "sp" may have been moved to the freelist now
1175      sp = syn_stack_find_entry(current_lnum);
1176    }
1177    // Still no free items?  Must be a strange problem...
1178    if (syn_block->b_sst_freecount == 0) {
1179      sp = NULL;
1180    } else {
1181      // Take the first item from the free list and put it in the used
1182      // list, after *sp
1183      p = syn_block->b_sst_firstfree;
1184      syn_block->b_sst_firstfree = p->sst_next;
1185      syn_block->b_sst_freecount--;
1186      if (sp == NULL) {
1187        // Insert in front of the list
1188        p->sst_next = syn_block->b_sst_first;
1189        syn_block->b_sst_first = p;
1190      } else {
1191        // insert in list after *sp
1192        p->sst_next = sp->sst_next;
1193        sp->sst_next = p;
1194      }
1195      sp = p;
1196      sp->sst_stacksize = 0;
1197      sp->sst_lnum = current_lnum;
1198      // Resume the next forward lookup from the entry just stored.
1199      syn_block->b_sst_search = sp;
1200    }
1201  }
1202  if (sp != NULL) {
1203    // When overwriting an existing state stack, clear it first
1204    clear_syn_state(sp);
1205    sp->sst_stacksize = current_state.ga_len;
1206    if (current_state.ga_len > SST_FIX_STATES) {
1207      // Need to clear it, might be something remaining from when the
1208      // length was less than SST_FIX_STATES.
1209      ga_init(&sp->sst_union.sst_ga, (int)sizeof(bufstate_T), 1);
1210      ga_grow(&sp->sst_union.sst_ga, current_state.ga_len);
1211      sp->sst_union.sst_ga.ga_len = current_state.ga_len;
1212      bp = SYN_STATE_P(&(sp->sst_union.sst_ga));
1213    } else {
1214      bp = sp->sst_union.sst_stack;
1215    }
1216    for (i = 0; i < sp->sst_stacksize; i++) {
1217      bp[i].bs_idx = CUR_STATE(i).si_idx;
1218      bp[i].bs_flags = CUR_STATE(i).si_flags;
1219      bp[i].bs_seqnr = CUR_STATE(i).si_seqnr;
1220      bp[i].bs_cchar = CUR_STATE(i).si_cchar;
1221      bp[i].bs_extmatch = ref_extmatch(CUR_STATE(i).si_extmatch);
1222    }
1223    sp->sst_next_flags = current_next_flags;
1224    sp->sst_next_list = current_next_list;
1225    sp->sst_tick = display_tick;
1226    sp->sst_change_lnum = 0;
1227  }
1228  current_state_stored = true;
1229  return sp;
1230}
1231
1232// Copy a state stack from "from" in b_sst_array[] to current_state;
1233static void load_current_state(synstate_T *from)
1234{
1235  bufstate_T *bp;
1236
1237  clear_current_state();
1238  validate_current_state();
1239  keepend_level = -1;
1240  if (from->sst_stacksize) {
1241    ga_grow(&current_state, from->sst_stacksize);
1242    if (from->sst_stacksize > SST_FIX_STATES) {
1243      bp = SYN_STATE_P(&(from->sst_union.sst_ga));
1244    } else {
1245      bp = from->sst_union.sst_stack;
1246    }
1247    for (int i = 0; i < from->sst_stacksize; i++) {
1248      CUR_STATE(i).si_idx = bp[i].bs_idx;
1249      CUR_STATE(i).si_flags = bp[i].bs_flags;
1250      CUR_STATE(i).si_seqnr = bp[i].bs_seqnr;
1251      CUR_STATE(i).si_cchar = bp[i].bs_cchar;
1252      CUR_STATE(i).si_extmatch = ref_extmatch(bp[i].bs_extmatch);
1253      if (keepend_level < 0 && (CUR_STATE(i).si_flags & HL_KEEPEND)) {
1254        keepend_level = i;
1255      }
1256      CUR_STATE(i).si_ends = false;
1257      CUR_STATE(i).si_m_lnum = 0;
1258      if (CUR_STATE(i).si_idx >= 0) {
1259        CUR_STATE(i).si_next_list =
1260          (SYN_ITEMS(syn_block)[CUR_STATE(i).si_idx]).sp_next_list;
1261      } else {
1262        CUR_STATE(i).si_next_list = NULL;
1263      }
1264      update_si_attr(i);
1265    }
1266    current_state.ga_len = from->sst_stacksize;
1267  }
1268  current_next_list = from->sst_next_list;
1269  current_next_flags = from->sst_next_flags;
1270  current_lnum = from->sst_lnum;
1271}
1272
1273/// Compare saved state stack "*sp" with the current state.
1274///
1275/// @return  true when they are equal.
1276static bool syn_stack_equal(synstate_T *sp)
1277{
1278  bufstate_T *bp;
1279
1280  // First a quick check if the stacks have the same size end nextlist.
1281  if (sp->sst_stacksize != current_state.ga_len
1282      || sp->sst_next_list != current_next_list) {
1283    return false;
1284  }
1285
1286  // Need to compare all states on both stacks.
1287  if (sp->sst_stacksize > SST_FIX_STATES) {
1288    bp = SYN_STATE_P(&(sp->sst_union.sst_ga));
1289  } else {
1290    bp = sp->sst_union.sst_stack;
1291  }
1292
1293  int i;
1294  for (i = current_state.ga_len; --i >= 0;) {
1295    // If the item has another index the state is different.
1296    if (bp[i].bs_idx != CUR_STATE(i).si_idx) {
1297      break;
1298    }
1299    if (bp[i].bs_extmatch == CUR_STATE(i).si_extmatch) {
1300      continue;
1301    }
1302    // When the extmatch pointers are different, the strings in them can
1303    // still be the same.  Check if the extmatch references are equal.
1304    reg_extmatch_T *bsx = bp[i].bs_extmatch;
1305    reg_extmatch_T *six = CUR_STATE(i).si_extmatch;
1306    // If one of the extmatch pointers is NULL the states are different.
1307    if (bsx == NULL || six == NULL) {
1308      break;
1309    }
1310    int j;
1311    for (j = 0; j < NSUBEXP; j++) {
1312      // Check each referenced match string. They must all be equal.
1313      if (bsx->matches[j] != six->matches[j]) {
1314        // If the pointer is different it can still be the same text.
1315        // Compare the strings, ignore case when the start item has the
1316        // sp_ic flag set.
1317        if (bsx->matches[j] == NULL || six->matches[j] == NULL) {
1318          break;
1319        }
1320        if (mb_strcmp_ic((SYN_ITEMS(syn_block)[CUR_STATE(i).si_idx]).sp_ic,
1321                         (const char *)bsx->matches[j],
1322                         (const char *)six->matches[j]) != 0) {
1323          break;
1324        }
1325      }
1326    }
1327    if (j != NSUBEXP) {
1328      break;
1329    }
1330  }
1331  return i < 0 ? true : false;
1332}
1333
1334// We stop parsing syntax above line "lnum".  If the stored state at or below
1335// this line depended on a change before it, it now depends on the line below
1336// the last parsed line.
1337// The window looks like this:
1338//          line which changed
1339//          displayed line
1340//          displayed line
1341// lnum ->  line below window
1342void syntax_end_parsing(win_T *wp, linenr_T lnum)
1343{
1344  synstate_T *sp;
1345
1346  if (syn_block != wp->w_s) {
1347    return;  // not the right window
1348  }
1349  sp = syn_stack_find_entry(lnum);
1350  if (sp != NULL && sp->sst_lnum < lnum) {
1351    sp = sp->sst_next;
1352  }
1353
1354  if (sp != NULL && sp->sst_change_lnum != 0) {
1355    sp->sst_change_lnum = lnum;
1356  }
1357}
1358
1359// End of handling of the state stack.
1360// **************************************
1361
1362static void invalidate_current_state(void)
1363{
1364  clear_current_state();
1365  current_state.ga_itemsize = 0;        // mark current_state invalid
1366  current_next_list = NULL;
1367  keepend_level = -1;
1368}
1369
1370static void validate_current_state(void)
1371{
1372  current_state.ga_itemsize = sizeof(stateitem_T);
1373  ga_set_growsize(&current_state, 3);
1374}
1375
1376/// This will only be called just after get_syntax_attr() for the previous
1377/// line, to check if the next line needs to be redrawn too.
1378///
1379/// @return  true if the syntax at start of lnum changed since last time.
1380bool syntax_check_changed(linenr_T lnum)
1381{
1382  bool retval = true;
1383  synstate_T *sp;
1384
1385  // Check the state stack when:
1386  // - lnum is just below the previously syntaxed line.
1387  // - lnum is not before the lines with saved states.
1388  // - lnum is not past the lines with saved states.
1389  // - lnum is at or before the last changed line.
1390  if (VALID_STATE(&current_state) && lnum == current_lnum + 1) {
1391    sp = syn_stack_find_entry(lnum);
1392    if (sp != NULL && sp->sst_lnum == lnum) {
1393      // finish the previous line (needed when not all of the line was
1394      // drawn)
1395      syn_finish_line(false);
1396
1397      // Compare the current state with the previously saved state of
1398      // the line.
1399      if (syn_stack_equal(sp)) {
1400        retval = false;
1401      }
1402
1403      // Store the current state in b_sst_array[] for later use.
1404      current_lnum++;
1405      store_current_state();
1406    }
1407  }
1408
1409  return retval;
1410}
1411
1412/// Finish the current line.
1413/// This doesn't return any attributes, it only gets the state at the end of
1414/// the line.  It can start anywhere in the line, as long as the current state
1415/// is valid.
1416///
1417/// @param syncing  called for syncing
1418static bool syn_finish_line(const bool syncing)
1419{
1420  while (!current_finished) {
1421    syn_current_attr(syncing, false, NULL, false);
1422
1423    // When syncing, and found some item, need to check the item.
1424    if (syncing && current_state.ga_len) {
1425      // Check for match with sync item.
1426      const stateitem_T *const cur_si = &CUR_STATE(current_state.ga_len - 1);
1427      if (cur_si->si_idx >= 0
1428          && (SYN_ITEMS(syn_block)[cur_si->si_idx].sp_flags
1429              & (HL_SYNC_HERE|HL_SYNC_THERE))) {
1430        return true;
1431      }
1432
1433      // syn_current_attr() will have skipped the check for an item
1434      // that ends here, need to do that now.  Be careful not to go
1435      // past the NUL.
1436      const colnr_T prev_current_col = current_col;
1437      if (syn_getcurline()[current_col] != NUL) {
1438        current_col++;
1439      }
1440      check_state_ends();
1441      current_col = prev_current_col;
1442    }
1443    current_col++;
1444  }
1445  return false;
1446}
1447
1448/// Gets highlight attributes for next character.
1449/// Must first call syntax_start() once for the line.
1450/// "col" is normally 0 for the first use in a line, and increments by one each
1451/// time.  It's allowed to skip characters and to stop before the end of the
1452/// line.  But only a "col" after a previously used column is allowed.
1453/// When "can_spell" is not NULL set it to true when spell-checking should be
1454/// done.
1455///
1456/// @param keep_state  keep state of char at "col"
1457///
1458/// @return            highlight attributes for next character.
1459int get_syntax_attr(const colnr_T col, bool *const can_spell, const bool keep_state)
1460{
1461  int attr = 0;
1462
1463  if (can_spell != NULL) {
1464    // Default: Only do spelling when there is no @Spell cluster or when
1465    // ":syn spell toplevel" was used.
1466    *can_spell = syn_block->b_syn_spell == SYNSPL_DEFAULT
1467                 ? (syn_block->b_spell_cluster_id == 0)
1468                 : (syn_block->b_syn_spell == SYNSPL_TOP);
1469  }
1470
1471  // check for out of memory situation
1472  if (syn_block->b_sst_array == NULL) {
1473    return 0;
1474  }
1475
1476  // After 'synmaxcol' the attribute is always zero.
1477  if (syn_buf->b_p_smc > 0 && col >= (colnr_T)syn_buf->b_p_smc) {
1478    clear_current_state();
1479    current_id = 0;
1480    current_trans_id = 0;
1481    current_flags = 0;
1482    current_seqnr = 0;
1483    return 0;
1484  }
1485
1486  // Make sure current_state is valid
1487  if (INVALID_STATE(&current_state)) {
1488    validate_current_state();
1489  }
1490
1491  // Skip from the current column to "col", get the attributes for "col".
1492  while (current_col <= col) {
1493    attr = syn_current_attr(false, true, can_spell,
1494                            current_col == col ? keep_state : false);
1495    current_col++;
1496  }
1497
1498  return attr;
1499}
1500
1501/// Get syntax attributes for current_lnum, current_col.
1502///
1503/// @param syncing     When true: called for syncing
1504/// @param displaying  result will be displayed
1505/// @param can_spell   return: do spell checking
1506/// @param keep_state  keep syntax stack afterwards
1507static int syn_current_attr(const bool syncing, const bool displaying, bool *const can_spell,
1508                            const bool keep_state)
1509{
1510  lpos_T endpos;
1511  lpos_T hl_startpos;
1512  lpos_T hl_endpos;
1513  lpos_T eos_pos;               // end-of-start match (start region)
1514  lpos_T eoe_pos;               // end-of-end pattern
1515  int end_idx;                  // group ID for end pattern
1516  stateitem_T *cur_si;
1517  stateitem_T *sip = NULL;
1518  int startcol;
1519  int endcol;
1520  int flags;
1521  int cchar;
1522  int16_t *next_list;
1523  bool found_match;                         // found usable match
1524  static bool try_next_column = false;      // must try in next col
1525  regmmatch_T regmatch;
1526  lpos_T pos;
1527  reg_extmatch_T *cur_extmatch = NULL;
1528  char buf_chartab[32];    // chartab array for syn iskeyword
1529  char *line;              // current line.  NOTE: becomes invalid after
1530                           // looking for a pattern match!
1531
1532  // variables for zero-width matches that have a "nextgroup" argument
1533  bool keep_next_list;
1534  bool zero_width_next_list = false;
1535  garray_T zero_width_next_ga;
1536
1537  // No character, no attributes!  Past end of line?
1538  // Do try matching with an empty line (could be the start of a region).
1539  line = syn_getcurline();
1540  if (line[current_col] == NUL && current_col != 0) {
1541    // If we found a match after the last column, use it.
1542    if (next_match_idx >= 0 && next_match_col >= (int)current_col
1543        && next_match_col != MAXCOL) {
1544      push_next_match();
1545    }
1546
1547    current_finished = true;
1548    current_state_stored = false;
1549    return 0;
1550  }
1551
1552  // if the current or next character is NUL, we will finish the line now
1553  if (line[current_col] == NUL || line[current_col + 1] == NUL) {
1554    current_finished = true;
1555    current_state_stored = false;
1556  }
1557
1558  // When in the previous column there was a match but it could not be used
1559  // (empty match or already matched in this column) need to try again in
1560  // the next column.
1561  if (try_next_column) {
1562    next_match_idx = -1;
1563    try_next_column = false;
1564  }
1565
1566  // Only check for keywords when not syncing and there are some.
1567  const bool do_keywords = !syncing
1568                           && (syn_block->b_keywtab.ht_used > 0
1569                               || syn_block->b_keywtab_ic.ht_used > 0);
1570
1571  // Init the list of zero-width matches with a nextlist.  This is used to
1572  // avoid matching the same item in the same position twice.
1573  ga_init(&zero_width_next_ga, (int)sizeof(int), 10);
1574
1575  // use syntax iskeyword option
1576  save_chartab(buf_chartab);
1577
1578  // Repeat matching keywords and patterns, to find contained items at the
1579  // same column.  This stops when there are no extra matches at the current
1580  // column.
1581  do {
1582    found_match = false;
1583    keep_next_list = false;
1584    int syn_id = 0;
1585
1586    // 1. Check for a current state.
1587    //    Only when there is no current state, or if the current state may
1588    //    contain other things, we need to check for keywords and patterns.
1589    //    Always need to check for contained items if some item has the
1590    //    "containedin" argument (takes extra time!).
1591    if (current_state.ga_len) {
1592      cur_si = &CUR_STATE(current_state.ga_len - 1);
1593    } else {
1594      cur_si = NULL;
1595    }
1596
1597    if (syn_block->b_syn_containedin || cur_si == NULL
1598        || cur_si->si_cont_list != NULL) {
1599      // 2. Check for keywords, if on a keyword char after a non-keyword
1600      //          char.  Don't do this when syncing.
1601      if (do_keywords) {
1602        line = syn_getcurline();
1603        const char *cur_pos = line + current_col;
1604        if (vim_iswordp_buf(cur_pos, syn_buf)
1605            && (current_col == 0
1606                || !vim_iswordp_buf(cur_pos - 1 -
1607                                    utf_head_off(line, cur_pos - 1),
1608                                    syn_buf))) {
1609          syn_id = check_keyword_id(line, (int)current_col, &endcol, &flags,
1610                                    &next_list, cur_si, &cchar);
1611          if (syn_id != 0) {
1612            push_current_state(KEYWORD_IDX);
1613            {
1614              cur_si = &CUR_STATE(current_state.ga_len - 1);
1615              cur_si->si_m_startcol = current_col;
1616              cur_si->si_h_startpos.lnum = current_lnum;
1617              cur_si->si_h_startpos.col = 0;            // starts right away
1618              cur_si->si_m_endpos.lnum = current_lnum;
1619              cur_si->si_m_endpos.col = endcol;
1620              cur_si->si_h_endpos.lnum = current_lnum;
1621              cur_si->si_h_endpos.col = endcol;
1622              cur_si->si_ends = true;
1623              cur_si->si_end_idx = 0;
1624              cur_si->si_flags = flags;
1625              cur_si->si_seqnr = next_seqnr++;
1626              cur_si->si_cchar = cchar;
1627              if (current_state.ga_len > 1) {
1628                cur_si->si_flags |=
1629                  CUR_STATE(current_state.ga_len - 2).si_flags
1630                  & HL_CONCEAL;
1631              }
1632              cur_si->si_id = syn_id;
1633              cur_si->si_trans_id = syn_id;
1634              if (flags & HL_TRANSP) {
1635                if (current_state.ga_len < 2) {
1636                  cur_si->si_attr = 0;
1637                  cur_si->si_trans_id = 0;
1638                } else {
1639                  cur_si->si_attr = CUR_STATE(current_state.ga_len - 2).si_attr;
1640                  cur_si->si_trans_id = CUR_STATE(current_state.ga_len - 2).si_trans_id;
1641                }
1642              } else {
1643                cur_si->si_attr = syn_id2attr(syn_id);
1644              }
1645              cur_si->si_cont_list = NULL;
1646              cur_si->si_next_list = next_list;
1647              check_keepend();
1648            }
1649          }
1650        }
1651      }
1652
1653      // 3. Check for patterns (only if no keyword found).
1654      if (syn_id == 0 && syn_block->b_syn_patterns.ga_len) {
1655        // If we didn't check for a match yet, or we are past it, check
1656        // for any match with a pattern.
1657        if (next_match_idx < 0 || next_match_col < (int)current_col) {
1658          // Check all relevant patterns for a match at this
1659          // position.  This is complicated, because matching with a
1660          // pattern takes quite a bit of time, thus we want to
1661          // avoid doing it when it's not needed.
1662          next_match_idx = 0;                   // no match in this line yet
1663          next_match_col = MAXCOL;
1664          for (int idx = syn_block->b_syn_patterns.ga_len; --idx >= 0;) {
1665            synpat_T *const spp = &(SYN_ITEMS(syn_block)[idx]);
1666            if (spp->sp_syncing == syncing
1667                && (displaying || !(spp->sp_flags & HL_DISPLAY))
1668                && (spp->sp_type == SPTYPE_MATCH
1669                    || spp->sp_type == SPTYPE_START)
1670                && (current_next_list != NULL
1671                    ? in_id_list(NULL, current_next_list, &spp->sp_syn, 0)
1672                    : (cur_si == NULL
1673                       ? !(spp->sp_flags & HL_CONTAINED)
1674                       : in_id_list(cur_si,
1675                                    cur_si->si_cont_list, &spp->sp_syn,
1676                                    spp->sp_flags)))) {
1677              // If we already tried matching in this line, and
1678              // there isn't a match before next_match_col, skip
1679              // this item.
1680              if (spp->sp_line_id == current_line_id
1681                  && spp->sp_startcol >= next_match_col) {
1682                continue;
1683              }
1684              spp->sp_line_id = current_line_id;
1685
1686              colnr_T lc_col = current_col - spp->sp_offsets[SPO_LC_OFF];
1687              if (lc_col < 0) {
1688                lc_col = 0;
1689              }
1690
1691              regmatch.rmm_ic = spp->sp_ic;
1692              regmatch.regprog = spp->sp_prog;
1693              int r = syn_regexec(&regmatch, current_lnum, lc_col,
1694                                  IF_SYN_TIME(&spp->sp_time));
1695              spp->sp_prog = regmatch.regprog;
1696              if (!r) {
1697                // no match in this line, try another one
1698                spp->sp_startcol = MAXCOL;
1699                continue;
1700              }
1701
1702              // Compute the first column of the match.
1703              syn_add_start_off(&pos, &regmatch,
1704                                spp, SPO_MS_OFF, -1);
1705              if (pos.lnum > current_lnum) {
1706                // must have used end of match in a next line,
1707                // we can't handle that
1708                spp->sp_startcol = MAXCOL;
1709                continue;
1710              }
1711              startcol = pos.col;
1712
1713              // remember the next column where this pattern
1714              // matches in the current line
1715              spp->sp_startcol = startcol;
1716
1717              // If a previously found match starts at a lower
1718              // column number, don't use this one.
1719              if (startcol >= next_match_col) {
1720                continue;
1721              }
1722
1723              // If we matched this pattern at this position
1724              // before, skip it.  Must retry in the next
1725              // column, because it may match from there.
1726              if (did_match_already(idx, &zero_width_next_ga)) {
1727                try_next_column = true;
1728                continue;
1729              }
1730
1731              endpos.lnum = regmatch.endpos[0].lnum;
1732              endpos.col = regmatch.endpos[0].col;
1733
1734              // Compute the highlight start.
1735              syn_add_start_off(&hl_startpos, &regmatch,
1736                                spp, SPO_HS_OFF, -1);
1737
1738              // Compute the region start.
1739              // Default is to use the end of the match.
1740              syn_add_end_off(&eos_pos, &regmatch,
1741                              spp, SPO_RS_OFF, 0);
1742
1743              // Grab the external submatches before they get
1744              // overwritten.  Reference count doesn't change.
1745              unref_extmatch(cur_extmatch);
1746              cur_extmatch = re_extmatch_out;
1747              re_extmatch_out = NULL;
1748
1749              flags = 0;
1750              eoe_pos.lnum = 0;                 // avoid warning
1751              eoe_pos.col = 0;
1752              end_idx = 0;
1753              hl_endpos.lnum = 0;
1754
1755              // For a "oneline" the end must be found in the
1756              // same line too.  Search for it after the end of
1757              // the match with the start pattern.  Set the
1758              // resulting end positions at the same time.
1759              if (spp->sp_type == SPTYPE_START
1760                  && (spp->sp_flags & HL_ONELINE)) {
1761                lpos_T startpos;
1762
1763                startpos = endpos;
1764                find_endpos(idx, &startpos, &endpos, &hl_endpos,
1765                            &flags, &eoe_pos, &end_idx, cur_extmatch);
1766                if (endpos.lnum == 0) {
1767                  continue;                         // not found
1768                }
1769              } else if (spp->sp_type == SPTYPE_MATCH) {
1770                // For a "match" the size must be > 0 after the
1771                // end offset needs has been added.  Except when
1772                // syncing.
1773                syn_add_end_off(&hl_endpos, &regmatch, spp,
1774                                SPO_HE_OFF, 0);
1775                syn_add_end_off(&endpos, &regmatch, spp,
1776                                SPO_ME_OFF, 0);
1777                if (endpos.lnum == current_lnum
1778                    && (int)endpos.col + syncing < startcol) {
1779                  // If an empty string is matched, may need
1780                  // to try matching again at next column.
1781                  if (regmatch.startpos[0].col == regmatch.endpos[0].col) {
1782                    try_next_column = true;
1783                  }
1784                  continue;
1785                }
1786              }
1787
1788              // keep the best match so far in next_match_*
1789
1790              // Highlighting must start after startpos and end
1791              // before endpos.
1792              if (hl_startpos.lnum == current_lnum
1793                  && (int)hl_startpos.col < startcol) {
1794                hl_startpos.col = startcol;
1795              }
1796              limit_pos_zero(&hl_endpos, &endpos);
1797
1798              next_match_idx = idx;
1799              next_match_col = startcol;
1800              next_match_m_endpos = endpos;
1801              next_match_h_endpos = hl_endpos;
1802              next_match_h_startpos = hl_startpos;
1803              next_match_flags = flags;
1804              next_match_eos_pos = eos_pos;
1805              next_match_eoe_pos = eoe_pos;
1806              next_match_end_idx = end_idx;
1807              unref_extmatch(next_match_extmatch);
1808              next_match_extmatch = cur_extmatch;
1809              cur_extmatch = NULL;
1810            }
1811          }
1812        }
1813
1814        // If we found a match at the current column, use it.
1815        if (next_match_idx >= 0 && next_match_col == (int)current_col) {
1816          synpat_T *lspp;
1817
1818          // When a zero-width item matched which has a nextgroup,
1819          // don't push the item but set nextgroup.
1820          lspp = &(SYN_ITEMS(syn_block)[next_match_idx]);
1821          if (next_match_m_endpos.lnum == current_lnum
1822              && next_match_m_endpos.col == current_col
1823              && lspp->sp_next_list != NULL) {
1824            current_next_list = lspp->sp_next_list;
1825            current_next_flags = lspp->sp_flags;
1826            keep_next_list = true;
1827            zero_width_next_list = true;
1828
1829            // Add the index to a list, so that we can check
1830            // later that we don't match it again (and cause an
1831            // endless loop).
1832            GA_APPEND(int, &zero_width_next_ga, next_match_idx);
1833            next_match_idx = -1;
1834          } else {
1835            cur_si = push_next_match();
1836          }
1837          found_match = true;
1838        }
1839      }
1840    }
1841
1842    // Handle searching for nextgroup match.
1843    if (current_next_list != NULL && !keep_next_list) {
1844      // If a nextgroup was not found, continue looking for one if:
1845      // - this is an empty line and the "skipempty" option was given
1846      // - we are on white space and the "skipwhite" option was given
1847      if (!found_match) {
1848        line = syn_getcurline();
1849        if (((current_next_flags & HL_SKIPWHITE)
1850             && ascii_iswhite(line[current_col]))
1851            || ((current_next_flags & HL_SKIPEMPTY)
1852                && *line == NUL)) {
1853          break;
1854        }
1855      }
1856
1857      // If a nextgroup was found: Use it, and continue looking for
1858      // contained matches.
1859      // If a nextgroup was not found: Continue looking for a normal
1860      // match.
1861      // When did set current_next_list for a zero-width item and no
1862      // match was found don't loop (would get stuck).
1863      current_next_list = NULL;
1864      next_match_idx = -1;
1865      if (!zero_width_next_list) {
1866        found_match = true;
1867      }
1868    }
1869  } while (found_match);
1870
1871  restore_chartab(buf_chartab);
1872
1873  // Use attributes from the current state, if within its highlighting.
1874  // If not, use attributes from the current-but-one state, etc.
1875  current_attr = 0;
1876  current_id = 0;
1877  current_trans_id = 0;
1878  current_flags = 0;
1879  current_seqnr = 0;
1880  if (cur_si != NULL) {
1881    for (int idx = current_state.ga_len - 1; idx >= 0; idx--) {
1882      sip = &CUR_STATE(idx);
1883      if ((current_lnum > sip->si_h_startpos.lnum
1884           || (current_lnum == sip->si_h_startpos.lnum
1885               && current_col >= sip->si_h_startpos.col))
1886          && (sip->si_h_endpos.lnum == 0
1887              || current_lnum < sip->si_h_endpos.lnum
1888              || (current_lnum == sip->si_h_endpos.lnum
1889                  && current_col < sip->si_h_endpos.col))) {
1890        current_attr = sip->si_attr;
1891        current_id = sip->si_id;
1892        current_trans_id = sip->si_trans_id;
1893        current_flags = sip->si_flags;
1894        current_seqnr = sip->si_seqnr;
1895        current_sub_char = sip->si_cchar;
1896        break;
1897      }
1898    }
1899
1900    if (can_spell != NULL) {
1901      struct sp_syn sps;
1902
1903      // set "can_spell" to true if spell checking is supposed to be
1904      // done in the current item.
1905      if (syn_block->b_spell_cluster_id == 0) {
1906        // There is no @Spell cluster: Do spelling for items without
1907        // @NoSpell cluster.
1908        if (syn_block->b_nospell_cluster_id == 0
1909            || current_trans_id == 0) {
1910          *can_spell = (syn_block->b_syn_spell != SYNSPL_NOTOP);
1911        } else {
1912          sps.inc_tag = 0;
1913          sps.id = (int16_t)syn_block->b_nospell_cluster_id;
1914          sps.cont_in_list = NULL;
1915          *can_spell = !in_id_list(sip, sip->si_cont_list, &sps, 0);
1916        }
1917      } else {
1918        // The @Spell cluster is defined: Do spelling in items with
1919        // the @Spell cluster.  But not when @NoSpell is also there.
1920        // At the toplevel only spell check when ":syn spell toplevel"
1921        // was used.
1922        if (current_trans_id == 0) {
1923          *can_spell = (syn_block->b_syn_spell == SYNSPL_TOP);
1924        } else {
1925          sps.inc_tag = 0;
1926          sps.id = (int16_t)syn_block->b_spell_cluster_id;
1927          sps.cont_in_list = NULL;
1928          *can_spell = in_id_list(sip, sip->si_cont_list, &sps, 0);
1929
1930          if (syn_block->b_nospell_cluster_id != 0) {
1931            sps.id = (int16_t)syn_block->b_nospell_cluster_id;
1932            if (in_id_list(sip, sip->si_cont_list, &sps, 0)) {
1933              *can_spell = false;
1934            }
1935          }
1936        }
1937      }
1938    }
1939
1940    // Check for end of current state (and the states before it) at the
1941    // next column.  Don't do this for syncing, because we would miss a
1942    // single character match.
1943    // First check if the current state ends at the current column.  It
1944    // may be for an empty match and a containing item might end in the
1945    // current column.
1946    if (!syncing && !keep_state) {
1947      check_state_ends();
1948      if (!GA_EMPTY(&current_state)
1949          && syn_getcurline()[current_col] != NUL) {
1950        current_col++;
1951        check_state_ends();
1952        current_col--;
1953      }
1954    }
1955  } else if (can_spell != NULL) {
1956    // Default: Only do spelling when there is no @Spell cluster or when
1957    // ":syn spell toplevel" was used.
1958    *can_spell = syn_block->b_syn_spell == SYNSPL_DEFAULT
1959                 ? (syn_block->b_spell_cluster_id == 0)
1960                 : (syn_block->b_syn_spell == SYNSPL_TOP);
1961  }
1962
1963  // nextgroup ends at end of line, unless "skipnl" or "skipempty" present
1964  if (current_next_list != NULL
1965      && (line = syn_getcurline())[current_col] != NUL
1966      && line[current_col + 1] == NUL
1967      && !(current_next_flags & (HL_SKIPNL | HL_SKIPEMPTY))) {
1968    current_next_list = NULL;
1969  }
1970
1971  if (!GA_EMPTY(&zero_width_next_ga)) {
1972    ga_clear(&zero_width_next_ga);
1973  }
1974
1975  // No longer need external matches.  But keep next_match_extmatch.
1976  unref_extmatch(re_extmatch_out);
1977  re_extmatch_out = NULL;
1978  unref_extmatch(cur_extmatch);
1979
1980  return current_attr;
1981}
1982
1983/// @return  true if we already matched pattern "idx" at the current column.
1984static bool did_match_already(int idx, garray_T *gap)
1985{
1986  for (int i = current_state.ga_len; --i >= 0;) {
1987    if (CUR_STATE(i).si_m_startcol == (int)current_col
1988        && CUR_STATE(i).si_m_lnum == (int)current_lnum
1989        && CUR_STATE(i).si_idx == idx) {
1990      return true;
1991    }
1992  }
1993
1994  // Zero-width matches with a nextgroup argument are not put on the syntax
1995  // stack, and can only be matched once anyway.
1996  for (int i = gap->ga_len; --i >= 0;) {
1997    if (((int *)(gap->ga_data))[i] == idx) {
1998      return true;
1999    }
2000  }
2001
2002  return false;
2003}
2004
2005// Push the next match onto the stack.
2006static stateitem_T *push_next_match(void)
2007{
2008  stateitem_T *cur_si;
2009  synpat_T *spp;
2010  int save_flags;
2011
2012  spp = &(SYN_ITEMS(syn_block)[next_match_idx]);
2013
2014  // Push the item in current_state stack;
2015  push_current_state(next_match_idx);
2016  {
2017    // If it's a start-skip-end type that crosses lines, figure out how
2018    // much it continues in this line.  Otherwise just fill in the length.
2019    cur_si = &CUR_STATE(current_state.ga_len - 1);
2020    cur_si->si_h_startpos = next_match_h_startpos;
2021    cur_si->si_m_startcol = current_col;
2022    cur_si->si_m_lnum = current_lnum;
2023    cur_si->si_flags = spp->sp_flags;
2024    cur_si->si_seqnr = next_seqnr++;
2025    cur_si->si_cchar = spp->sp_cchar;
2026    if (current_state.ga_len > 1) {
2027      cur_si->si_flags |=
2028        CUR_STATE(current_state.ga_len - 2).si_flags & HL_CONCEAL;
2029    }
2030    cur_si->si_next_list = spp->sp_next_list;
2031    cur_si->si_extmatch = ref_extmatch(next_match_extmatch);
2032    if (spp->sp_type == SPTYPE_START && !(spp->sp_flags & HL_ONELINE)) {
2033      // Try to find the end pattern in the current line
2034      update_si_end(cur_si, (int)(next_match_m_endpos.col), true);
2035      check_keepend();
2036    } else {
2037      cur_si->si_m_endpos = next_match_m_endpos;
2038      cur_si->si_h_endpos = next_match_h_endpos;
2039      cur_si->si_ends = true;
2040      cur_si->si_flags |= next_match_flags;
2041      cur_si->si_eoe_pos = next_match_eoe_pos;
2042      cur_si->si_end_idx = next_match_end_idx;
2043    }
2044    if (keepend_level < 0 && (cur_si->si_flags & HL_KEEPEND)) {
2045      keepend_level = current_state.ga_len - 1;
2046    }
2047    check_keepend();
2048    update_si_attr(current_state.ga_len - 1);
2049
2050    save_flags = cur_si->si_flags & (HL_CONCEAL | HL_CONCEALENDS);
2051    // If the start pattern has another highlight group, push another item
2052    // on the stack for the start pattern.
2053    if (spp->sp_type == SPTYPE_START && spp->sp_syn_match_id != 0) {
2054      push_current_state(next_match_idx);
2055      cur_si = &CUR_STATE(current_state.ga_len - 1);
2056      cur_si->si_h_startpos = next_match_h_startpos;
2057      cur_si->si_m_startcol = current_col;
2058      cur_si->si_m_lnum = current_lnum;
2059      cur_si->si_m_endpos = next_match_eos_pos;
2060      cur_si->si_h_endpos = next_match_eos_pos;
2061      cur_si->si_ends = true;
2062      cur_si->si_end_idx = 0;
2063      cur_si->si_flags = HL_MATCH;
2064      cur_si->si_seqnr = next_seqnr++;
2065      cur_si->si_flags |= save_flags;
2066      if (cur_si->si_flags & HL_CONCEALENDS) {
2067        cur_si->si_flags |= HL_CONCEAL;
2068      }
2069      cur_si->si_next_list = NULL;
2070      check_keepend();
2071      update_si_attr(current_state.ga_len - 1);
2072    }
2073  }
2074
2075  next_match_idx = -1;          // try other match next time
2076
2077  return cur_si;
2078}
2079
2080// Check for end of current state (and the states before it).
2081static void check_state_ends(void)
2082{
2083  stateitem_T *cur_si;
2084  int had_extend;
2085
2086  cur_si = &CUR_STATE(current_state.ga_len - 1);
2087  while (true) {
2088    if (cur_si->si_ends
2089        && (cur_si->si_m_endpos.lnum < current_lnum
2090            || (cur_si->si_m_endpos.lnum == current_lnum
2091                && cur_si->si_m_endpos.col <= current_col))) {
2092      // If there is an end pattern group ID, highlight the end pattern
2093      // now.  No need to pop the current item from the stack.
2094      // Only do this if the end pattern continues beyond the current
2095      // position.
2096      if (cur_si->si_end_idx
2097          && (cur_si->si_eoe_pos.lnum > current_lnum
2098              || (cur_si->si_eoe_pos.lnum == current_lnum
2099                  && cur_si->si_eoe_pos.col > current_col))) {
2100        cur_si->si_idx = cur_si->si_end_idx;
2101        cur_si->si_end_idx = 0;
2102        cur_si->si_m_endpos = cur_si->si_eoe_pos;
2103        cur_si->si_h_endpos = cur_si->si_eoe_pos;
2104        cur_si->si_flags |= HL_MATCH;
2105        cur_si->si_seqnr = next_seqnr++;
2106        if (cur_si->si_flags & HL_CONCEALENDS) {
2107          cur_si->si_flags |= HL_CONCEAL;
2108        }
2109        update_si_attr(current_state.ga_len - 1);
2110
2111        // nextgroup= should not match in the end pattern
2112        current_next_list = NULL;
2113
2114        // what matches next may be different now, clear it
2115        next_match_idx = 0;
2116        next_match_col = MAXCOL;
2117        break;
2118      }
2119
2120      // handle next_list, unless at end of line and no "skipnl" or
2121      // "skipempty"
2122      current_next_list = cur_si->si_next_list;
2123      current_next_flags = cur_si->si_flags;
2124      if (!(current_next_flags & (HL_SKIPNL | HL_SKIPEMPTY))
2125          && syn_getcurline()[current_col] == NUL) {
2126        current_next_list = NULL;
2127      }
2128
2129      // When the ended item has "extend", another item with
2130      // "keepend" now needs to check for its end.
2131      had_extend = (cur_si->si_flags & HL_EXTEND);
2132
2133      pop_current_state();
2134
2135      if (GA_EMPTY(&current_state)) {
2136        break;
2137      }
2138
2139      if (had_extend && keepend_level >= 0) {
2140        syn_update_ends(false);
2141        if (GA_EMPTY(&current_state)) {
2142          break;
2143        }
2144      }
2145
2146      cur_si = &CUR_STATE(current_state.ga_len - 1);
2147
2148      // Only for a region the search for the end continues after
2149      // the end of the contained item.  If the contained match
2150      // included the end-of-line, break here, the region continues.
2151      // Don't do this when:
2152      // - "keepend" is used for the contained item
2153      // - not at the end of the line (could be end="x$"me=e-1).
2154      // - "excludenl" is used (HL_HAS_EOL won't be set)
2155      if (cur_si->si_idx >= 0
2156          && SYN_ITEMS(syn_block)[cur_si->si_idx].sp_type == SPTYPE_START
2157          && !(cur_si->si_flags & (HL_MATCH | HL_KEEPEND))) {
2158        update_si_end(cur_si, (int)current_col, true);
2159        check_keepend();
2160        if ((current_next_flags & HL_HAS_EOL)
2161            && keepend_level < 0
2162            && syn_getcurline()[current_col] == NUL) {
2163          break;
2164        }
2165      }
2166    } else {
2167      break;
2168    }
2169  }
2170}
2171
2172// Update an entry in the current_state stack for a match or region.  This
2173// fills in si_attr, si_next_list and si_cont_list.
2174static void update_si_attr(int idx)
2175{
2176  stateitem_T *sip = &CUR_STATE(idx);
2177  synpat_T *spp;
2178
2179  // This should not happen...
2180  if (sip->si_idx < 0) {
2181    return;
2182  }
2183
2184  spp = &(SYN_ITEMS(syn_block)[sip->si_idx]);
2185  if (sip->si_flags & HL_MATCH) {
2186    sip->si_id = spp->sp_syn_match_id;
2187  } else {
2188    sip->si_id = spp->sp_syn.id;
2189  }
2190  sip->si_attr = syn_id2attr(sip->si_id);
2191  sip->si_trans_id = sip->si_id;
2192  if (sip->si_flags & HL_MATCH) {
2193    sip->si_cont_list = NULL;
2194  } else {
2195    sip->si_cont_list = spp->sp_cont_list;
2196  }
2197
2198  // For transparent items, take attr from outer item.
2199  // Also take cont_list, if there is none.
2200  // Don't do this for the matchgroup of a start or end pattern.
2201  if ((spp->sp_flags & HL_TRANSP) && !(sip->si_flags & HL_MATCH)) {
2202    if (idx == 0) {
2203      sip->si_attr = 0;
2204      sip->si_trans_id = 0;
2205      if (sip->si_cont_list == NULL) {
2206        sip->si_cont_list = ID_LIST_ALL;
2207      }
2208    } else {
2209      sip->si_attr = CUR_STATE(idx - 1).si_attr;
2210      sip->si_trans_id = CUR_STATE(idx - 1).si_trans_id;
2211      if (sip->si_cont_list == NULL) {
2212        sip->si_flags |= HL_TRANS_CONT;
2213        sip->si_cont_list = CUR_STATE(idx - 1).si_cont_list;
2214      }
2215    }
2216  }
2217}
2218
2219// Check the current stack for patterns with "keepend" flag.
2220// Propagate the match-end to contained items, until a "skipend" item is found.
2221static void check_keepend(void)
2222{
2223  int i;
2224  lpos_T maxpos;
2225  lpos_T maxpos_h;
2226  stateitem_T *sip;
2227
2228  // This check can consume a lot of time; only do it from the level where
2229  // there really is a keepend.
2230  if (keepend_level < 0) {
2231    return;
2232  }
2233
2234  // Find the last index of an "extend" item.  "keepend" items before that
2235  // won't do anything.  If there is no "extend" item "i" will be
2236  // "keepend_level" and all "keepend" items will work normally.
2237  for (i = current_state.ga_len - 1; i > keepend_level; i--) {
2238    if (CUR_STATE(i).si_flags & HL_EXTEND) {
2239      break;
2240    }
2241  }
2242
2243  maxpos.lnum = 0;
2244  maxpos.col = 0;
2245  maxpos_h.lnum = 0;
2246  maxpos_h.col = 0;
2247  for (; i < current_state.ga_len; i++) {
2248    sip = &CUR_STATE(i);
2249    if (maxpos.lnum != 0) {
2250      limit_pos_zero(&sip->si_m_endpos, &maxpos);
2251      limit_pos_zero(&sip->si_h_endpos, &maxpos_h);
2252      limit_pos_zero(&sip->si_eoe_pos, &maxpos);
2253      sip->si_ends = true;
2254    }
2255    if (sip->si_ends && (sip->si_flags & HL_KEEPEND)) {
2256      if (maxpos.lnum == 0
2257          || maxpos.lnum > sip->si_m_endpos.lnum
2258          || (maxpos.lnum == sip->si_m_endpos.lnum
2259              && maxpos.col > sip->si_m_endpos.col)) {
2260        maxpos = sip->si_m_endpos;
2261      }
2262      if (maxpos_h.lnum == 0
2263          || maxpos_h.lnum > sip->si_h_endpos.lnum
2264          || (maxpos_h.lnum == sip->si_h_endpos.lnum
2265              && maxpos_h.col > sip->si_h_endpos.col)) {
2266        maxpos_h = sip->si_h_endpos;
2267      }
2268    }
2269  }
2270}
2271
2272/// Update an entry in the current_state stack for a start-skip-end pattern.
2273/// This finds the end of the current item, if it's in the current line.
2274///
2275/// @param startcol  where to start searching for the end
2276/// @param force     when true overrule a previous end
2277///
2278/// @return          the flags for the matched END.
2279static void update_si_end(stateitem_T *sip, int startcol, bool force)
2280{
2281  lpos_T hl_endpos;
2282  lpos_T end_endpos;
2283
2284  // return quickly for a keyword
2285  if (sip->si_idx < 0) {
2286    return;
2287  }
2288
2289  // Don't update when it's already done.  Can be a match of an end pattern
2290  // that started in a previous line.  Watch out: can also be a "keepend"
2291  // from a containing item.
2292  if (!force && sip->si_m_endpos.lnum >= current_lnum) {
2293    return;
2294  }
2295
2296  // We need to find the end of the region.  It may continue in the next
2297  // line.
2298  int end_idx = 0;
2299  lpos_T startpos = {
2300    .lnum = current_lnum,
2301    .col = startcol,
2302  };
2303  lpos_T endpos = { 0 };
2304  find_endpos(sip->si_idx, &startpos, &endpos, &hl_endpos,
2305              &(sip->si_flags), &end_endpos, &end_idx, sip->si_extmatch);
2306
2307  if (endpos.lnum == 0) {
2308    // No end pattern matched.
2309    if (SYN_ITEMS(syn_block)[sip->si_idx].sp_flags & HL_ONELINE) {
2310      // a "oneline" never continues in the next line
2311      sip->si_ends = true;
2312      sip->si_m_endpos.lnum = current_lnum;
2313      sip->si_m_endpos.col = syn_getcurline_len();
2314    } else {
2315      // continues in the next line
2316      sip->si_ends = false;
2317      sip->si_m_endpos.lnum = 0;
2318    }
2319    sip->si_h_endpos = sip->si_m_endpos;
2320  } else {
2321    // match within this line
2322    sip->si_m_endpos = endpos;
2323    sip->si_h_endpos = hl_endpos;
2324    sip->si_eoe_pos = end_endpos;
2325    sip->si_ends = true;
2326    sip->si_end_idx = end_idx;
2327  }
2328}
2329
2330// Add a new state to the current state stack.
2331// It is cleared and the index set to "idx".
2332static void push_current_state(int idx)
2333{
2334  stateitem_T *p = GA_APPEND_VIA_PTR(stateitem_T, &current_state);
2335  CLEAR_POINTER(p);
2336  p->si_idx = idx;
2337}
2338
2339// Remove a state from the current_state stack.
2340static void pop_current_state(void)
2341{
2342  if (!GA_EMPTY(&current_state)) {
2343    unref_extmatch(CUR_STATE(current_state.ga_len - 1).si_extmatch);
2344    current_state.ga_len--;
2345  }
2346  // after the end of a pattern, try matching a keyword or pattern
2347  next_match_idx = -1;
2348
2349  // if first state with "keepend" is popped, reset keepend_level
2350  if (keepend_level >= current_state.ga_len) {
2351    keepend_level = -1;
2352  }
2353}
2354
2355/// Find the end of a start/skip/end syntax region after "startpos".
2356/// Only checks one line.
2357/// Also handles a match item that continued from a previous line.
2358/// If not found, the syntax item continues in the next line.  m_endpos->lnum
2359/// will be 0.
2360/// If found, the end of the region and the end of the highlighting is
2361/// computed.
2362///
2363/// @param idx         index of the pattern
2364/// @param startpos    where to start looking for an END match
2365/// @param m_endpos    return: end of match
2366/// @param hl_endpos   return: end of highlighting
2367/// @param flagsp      return: flags of matching END
2368/// @param end_endpos  return: end of end pattern match
2369/// @param end_idx     return: group ID for end pat. match, or 0
2370/// @param start_ext   submatches from the start pattern
2371static void find_endpos(int idx, lpos_T *startpos, lpos_T *m_endpos, lpos_T *hl_endpos, int *flagsp,
2372                        lpos_T *end_endpos, int *end_idx, reg_extmatch_T *start_ext)
2373{
2374  synpat_T *spp_skip;
2375  int best_idx;
2376  regmmatch_T regmatch;
2377  regmmatch_T best_regmatch;        // startpos/endpos of best match
2378  lpos_T pos;
2379  bool had_match = false;
2380  char buf_chartab[32];  // chartab array for syn option iskeyword
2381
2382  // just in case we are invoked for a keyword
2383  if (idx < 0) {
2384    return;
2385  }
2386
2387  // Check for being called with a START pattern.
2388  // Can happen with a match that continues to the next line, because it
2389  // contained a region.
2390  synpat_T *spp = &(SYN_ITEMS(syn_block)[idx]);
2391  if (spp->sp_type != SPTYPE_START) {
2392    *hl_endpos = *startpos;
2393    return;
2394  }
2395
2396  // Find the SKIP or first END pattern after the last START pattern.
2397  while (true) {
2398    spp = &(SYN_ITEMS(syn_block)[idx]);
2399    if (spp->sp_type != SPTYPE_START) {
2400      break;
2401    }
2402    idx++;
2403  }
2404
2405  //    Lookup the SKIP pattern (if present)
2406  if (spp->sp_type == SPTYPE_SKIP) {
2407    spp_skip = spp;
2408    idx++;
2409  } else {
2410    spp_skip = NULL;
2411  }
2412
2413  // Setup external matches for syn_regexec().
2414  unref_extmatch(re_extmatch_in);
2415  re_extmatch_in = ref_extmatch(start_ext);
2416
2417  colnr_T matchcol = startpos->col;     // start looking for a match at sstart
2418  int start_idx = idx;              // remember the first END pattern.
2419  best_regmatch.startpos[0].col = 0;            // avoid compiler warning
2420
2421  // use syntax iskeyword option
2422  save_chartab(buf_chartab);
2423
2424  while (true) {
2425    // Find end pattern that matches first after "matchcol".
2426    best_idx = -1;
2427    for (idx = start_idx; idx < syn_block->b_syn_patterns.ga_len; idx++) {
2428      int lc_col = matchcol;
2429
2430      spp = &(SYN_ITEMS(syn_block)[idx]);
2431      if (spp->sp_type != SPTYPE_END) {         // past last END pattern
2432        break;
2433      }
2434      lc_col -= spp->sp_offsets[SPO_LC_OFF];
2435      if (lc_col < 0) {
2436        lc_col = 0;
2437      }
2438
2439      regmatch.rmm_ic = spp->sp_ic;
2440      regmatch.regprog = spp->sp_prog;
2441      bool r = syn_regexec(&regmatch, startpos->lnum, lc_col,
2442                           IF_SYN_TIME(&spp->sp_time));
2443      spp->sp_prog = regmatch.regprog;
2444      if (r) {
2445        if (best_idx == -1 || regmatch.startpos[0].col
2446            < best_regmatch.startpos[0].col) {
2447          best_idx = idx;
2448          best_regmatch.startpos[0] = regmatch.startpos[0];
2449          best_regmatch.endpos[0] = regmatch.endpos[0];
2450        }
2451      }
2452    }
2453
2454    // If all end patterns have been tried, and there is no match, the
2455    // item continues until end-of-line.
2456    if (best_idx == -1) {
2457      break;
2458    }
2459
2460    // If the skip pattern matches before the end pattern,
2461    // continue searching after the skip pattern.
2462    if (spp_skip != NULL) {
2463      int lc_col = matchcol - spp_skip->sp_offsets[SPO_LC_OFF];
2464
2465      if (lc_col < 0) {
2466        lc_col = 0;
2467      }
2468      regmatch.rmm_ic = spp_skip->sp_ic;
2469      regmatch.regprog = spp_skip->sp_prog;
2470      int r = syn_regexec(&regmatch, startpos->lnum, lc_col,
2471                          IF_SYN_TIME(&spp_skip->sp_time));
2472      spp_skip->sp_prog = regmatch.regprog;
2473      if (r && regmatch.startpos[0].col <= best_regmatch.startpos[0].col) {
2474        // Add offset to skip pattern match
2475        syn_add_end_off(&pos, &regmatch, spp_skip, SPO_ME_OFF, 1);
2476
2477        // If the skip pattern goes on to the next line, there is no
2478        // match with an end pattern in this line.
2479        if (pos.lnum > startpos->lnum) {
2480          break;
2481        }
2482
2483        int line_len = ml_get_buf_len(syn_buf, startpos->lnum);
2484
2485        // take care of an empty match or negative offset
2486        if (pos.col <= matchcol) {
2487          matchcol++;
2488        } else if (pos.col <= regmatch.endpos[0].col) {
2489          matchcol = pos.col;
2490        } else {
2491          // Be careful not to jump over the NUL at the end-of-line
2492          for (matchcol = regmatch.endpos[0].col;
2493               matchcol < line_len && matchcol < pos.col;
2494               matchcol++) {}
2495        }
2496
2497        // if the skip pattern includes end-of-line, break here
2498        if (matchcol >= line_len) {
2499          break;
2500        }
2501
2502        continue;  // start with first end pattern again
2503      }
2504    }
2505
2506    // Match from start pattern to end pattern.
2507    // Correct for match and highlight offset of end pattern.
2508    spp = &(SYN_ITEMS(syn_block)[best_idx]);
2509    syn_add_end_off(m_endpos, &best_regmatch, spp, SPO_ME_OFF, 1);
2510    // can't end before the start
2511    if (m_endpos->lnum == startpos->lnum && m_endpos->col < startpos->col) {
2512      m_endpos->col = startpos->col;
2513    }
2514
2515    syn_add_end_off(end_endpos, &best_regmatch, spp, SPO_HE_OFF, 1);
2516    // can't end before the start
2517    if (end_endpos->lnum == startpos->lnum
2518        && end_endpos->col < startpos->col) {
2519      end_endpos->col = startpos->col;
2520    }
2521    // can't end after the match
2522    limit_pos(end_endpos, m_endpos);
2523
2524    // If the end group is highlighted differently, adjust the pointers.
2525    if (spp->sp_syn_match_id != spp->sp_syn.id && spp->sp_syn_match_id != 0) {
2526      *end_idx = best_idx;
2527      if (spp->sp_off_flags & (1 << (SPO_RE_OFF + SPO_COUNT))) {
2528        hl_endpos->lnum = best_regmatch.endpos[0].lnum;
2529        hl_endpos->col = best_regmatch.endpos[0].col;
2530      } else {
2531        hl_endpos->lnum = best_regmatch.startpos[0].lnum;
2532        hl_endpos->col = best_regmatch.startpos[0].col;
2533      }
2534      hl_endpos->col += spp->sp_offsets[SPO_RE_OFF];
2535
2536      // can't end before the start
2537      if (hl_endpos->lnum == startpos->lnum
2538          && hl_endpos->col < startpos->col) {
2539        hl_endpos->col = startpos->col;
2540      }
2541      limit_pos(hl_endpos, m_endpos);
2542
2543      // now the match ends where the highlighting ends, it is turned
2544      // into the matchgroup for the end
2545      *m_endpos = *hl_endpos;
2546    } else {
2547      *end_idx = 0;
2548      *hl_endpos = *end_endpos;
2549    }
2550
2551    *flagsp = spp->sp_flags;
2552
2553    had_match = true;
2554    break;
2555  }
2556
2557  // no match for an END pattern in this line
2558  if (!had_match) {
2559    m_endpos->lnum = 0;
2560  }
2561
2562  restore_chartab(buf_chartab);
2563
2564  // Remove external matches.
2565  unref_extmatch(re_extmatch_in);
2566  re_extmatch_in = NULL;
2567}
2568
2569// Limit "pos" not to be after "limit".
2570static void limit_pos(lpos_T *pos, lpos_T *limit)
2571{
2572  if (pos->lnum > limit->lnum) {
2573    *pos = *limit;
2574  } else if (pos->lnum == limit->lnum && pos->col > limit->col) {
2575    pos->col = limit->col;
2576  }
2577}
2578
2579// Limit "pos" not to be after "limit", unless pos->lnum is zero.
2580static void limit_pos_zero(lpos_T *pos, lpos_T *limit)
2581{
2582  if (pos->lnum == 0) {
2583    *pos = *limit;
2584  } else {
2585    limit_pos(pos, limit);
2586  }
2587}
2588
2589/// Add offset to matched text for end of match or highlight.
2590///
2591/// @param result    returned position
2592/// @param regmatch  start/end of match
2593/// @param spp       matched pattern
2594/// @param idx       index of offset
2595/// @param extra     extra chars for offset to start
2596static void syn_add_end_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *spp, int idx,
2597                            int extra)
2598{
2599  int col;
2600  int off;
2601  char *base;
2602  char *p;
2603
2604  if (spp->sp_off_flags & (1 << idx)) {
2605    result->lnum = regmatch->startpos[0].lnum;
2606    col = regmatch->startpos[0].col;
2607    off = spp->sp_offsets[idx] + extra;
2608  } else {
2609    result->lnum = regmatch->endpos[0].lnum;
2610    col = regmatch->endpos[0].col;
2611    off = spp->sp_offsets[idx];
2612  }
2613  // Don't go past the end of the line.  Matters for "rs=e+2" when there
2614  // is a matchgroup. Watch out for match with last NL in the buffer.
2615  if (result->lnum > syn_buf->b_ml.ml_line_count) {
2616    col = 0;
2617  } else if (off != 0) {
2618    base = ml_get_buf(syn_buf, result->lnum);
2619    p = base + col;
2620    if (off > 0) {
2621      while (off-- > 0 && *p != NUL) {
2622        MB_PTR_ADV(p);
2623      }
2624    } else {
2625      while (off++ < 0 && base < p) {
2626        MB_PTR_BACK(base, p);
2627      }
2628    }
2629    col = (int)(p - base);
2630  }
2631  result->col = col;
2632}
2633
2634/// Add offset to matched text for start of match or highlight.
2635/// Avoid resulting column to become negative.
2636///
2637/// @param result    returned position
2638/// @param regmatch  start/end of match
2639/// @param extra     extra chars for offset to end
2640static void syn_add_start_off(lpos_T *result, regmmatch_T *regmatch, synpat_T *spp, int idx,
2641                              int extra)
2642{
2643  int col;
2644  int off;
2645  char *base;
2646  char *p;
2647
2648  if (spp->sp_off_flags & (1 << (idx + SPO_COUNT))) {
2649    result->lnum = regmatch->endpos[0].lnum;
2650    col = regmatch->endpos[0].col;
2651    off = spp->sp_offsets[idx] + extra;
2652  } else {
2653    result->lnum = regmatch->startpos[0].lnum;
2654    col = regmatch->startpos[0].col;
2655    off = spp->sp_offsets[idx];
2656  }
2657  if (result->lnum > syn_buf->b_ml.ml_line_count) {
2658    // a "\n" at the end of the pattern may take us below the last line
2659    result->lnum = syn_buf->b_ml.ml_line_count;
2660    col = ml_get_buf_len(syn_buf, result->lnum);
2661  }
2662  if (off != 0) {
2663    base = ml_get_buf(syn_buf, result->lnum);
2664    p = base + col;
2665    if (off > 0) {
2666      while (off-- && *p != NUL) {
2667        MB_PTR_ADV(p);
2668      }
2669    } else {
2670      while (off++ && base < p) {
2671        MB_PTR_BACK(base, p);
2672      }
2673    }
2674    col = (int)(p - base);
2675  }
2676  result->col = col;
2677}
2678
2679/// Get current line in syntax buffer.
2680static char *syn_getcurline(void)
2681{
2682  return ml_get_buf(syn_buf, current_lnum);
2683}
2684
2685/// Get length of current line in syntax buffer.
2686static colnr_T syn_getcurline_len(void)
2687{
2688  return ml_get_buf_len(syn_buf, current_lnum);
2689}
2690
2691// Call vim_regexec() to find a match with "rmp" in "syn_buf".
2692// Returns true when there is a match.
2693static bool syn_regexec(regmmatch_T *rmp, linenr_T lnum, colnr_T col, syn_time_T *st)
2694{
2695  int timed_out = 0;
2696  proftime_T pt;
2697  const bool l_syn_time_on = syn_time_on;
2698
2699  if (l_syn_time_on) {
2700    pt = profile_start();
2701  }
2702
2703  if (rmp->regprog == NULL) {
2704    // This can happen if a previous call to vim_regexec_multi() tried to
2705    // use the NFA engine, which resulted in NFA_TOO_EXPENSIVE, and
2706    // compiling the pattern with the other engine fails.
2707    return false;
2708  }
2709
2710  rmp->rmm_maxcol = (colnr_T)syn_buf->b_p_smc;
2711  int r = vim_regexec_multi(rmp, syn_win, syn_buf, lnum, col, syn_tm, &timed_out);
2712
2713  if (l_syn_time_on) {
2714    pt = profile_end(pt);
2715    st->total = profile_add(st->total, pt);
2716    if (profile_cmp(pt, st->slowest) < 0) {
2717      st->slowest = pt;
2718    }
2719    st->count++;
2720    if (r > 0) {
2721      st->match++;
2722    }
2723  }
2724  if (timed_out && !syn_win->w_s->b_syn_slow) {
2725    syn_win->w_s->b_syn_slow = true;
2726    msg(_("'redrawtime' exceeded, syntax highlighting disabled"), 0);
2727  }
2728
2729  if (r > 0) {
2730    rmp->startpos[0].lnum += lnum;
2731    rmp->endpos[0].lnum += lnum;
2732    return true;
2733  }
2734  return false;
2735}
2736
2737/// Check one position in a line for a matching keyword.
2738/// The caller must check if a keyword can start at startcol.
2739/// Return its ID if found, 0 otherwise.
2740///
2741/// @param startcol    position in line to check for keyword
2742/// @param endcolp     return: character after found keyword
2743/// @param flagsp      return: flags of matching keyword
2744/// @param next_listp  return: next_list of matching keyword
2745/// @param cur_si      item at the top of the stack
2746/// @param ccharp      conceal substitution char
2747static int check_keyword_id(char *const line, const int startcol, int *const endcolp,
2748                            int *const flagsp, int16_t **const next_listp,
2749                            stateitem_T *const cur_si, int *const ccharp)
2750{
2751  // Find first character after the keyword.  First character was already
2752  // checked.
2753  char *const kwp = line + startcol;
2754  int kwlen = 0;
2755  do {
2756    kwlen += utfc_ptr2len(kwp + kwlen);
2757  } while (vim_iswordp_buf(kwp + kwlen, syn_buf));
2758
2759  if (kwlen > MAXKEYWLEN) {
2760    return 0;
2761  }
2762
2763  // Must make a copy of the keyword, so we can add a NUL and make it
2764  // lowercase.
2765  char keyword[MAXKEYWLEN + 1];         // assume max. keyword len is 80
2766  xmemcpyz(keyword, kwp, (size_t)kwlen);
2767
2768  keyentry_T *kp = NULL;
2769
2770  // matching case
2771  if (syn_block->b_keywtab.ht_used != 0) {
2772    kp = match_keyword(keyword, &syn_block->b_keywtab, cur_si);
2773  }
2774
2775  // ignoring case
2776  if (kp == NULL && syn_block->b_keywtab_ic.ht_used != 0) {
2777    str_foldcase(kwp, kwlen, keyword, MAXKEYWLEN + 1);
2778    kp = match_keyword(keyword, &syn_block->b_keywtab_ic, cur_si);
2779  }
2780
2781  if (kp != NULL) {
2782    *endcolp = startcol + kwlen;
2783    *flagsp = kp->flags;
2784    *next_listp = kp->next_list;
2785    *ccharp = kp->k_char;
2786    return kp->k_syn.id;
2787  }
2788
2789  return 0;
2790}
2791
2792/// Find keywords that match.  There can be several with different
2793/// attributes.
2794/// When current_next_list is non-zero accept only that group, otherwise:
2795///  Accept a not-contained keyword at toplevel.
2796///  Accept a keyword at other levels only if it is in the contains list.
2797static keyentry_T *match_keyword(char *keyword, hashtab_T *ht, stateitem_T *cur_si)
2798{
2799  hashitem_T *hi = hash_find(ht, keyword);
2800  if (!HASHITEM_EMPTY(hi)) {
2801    for (keyentry_T *kp = HI2KE(hi); kp != NULL; kp = kp->ke_next) {
2802      if (current_next_list != 0
2803          ? in_id_list(NULL, current_next_list, &kp->k_syn, 0)
2804          : (cur_si == NULL
2805             ? !(kp->flags & HL_CONTAINED)
2806             : in_id_list(cur_si, cur_si->si_cont_list,
2807                          &kp->k_syn, kp->flags))) {
2808        return kp;
2809      }
2810    }
2811  }
2812  return NULL;
2813}
2814
2815// Handle ":syntax conceal" command.
2816static void syn_cmd_conceal(exarg_T *eap, int syncing)
2817{
2818  char *arg = eap->arg;
2819  char *next;
2820
2821  eap->nextcmd = find_nextcmd(arg);
2822  if (eap->skip) {
2823    return;
2824  }
2825
2826  next = skiptowhite(arg);
2827  if (*arg == NUL) {
2828    if (curwin->w_s->b_syn_conceal) {
2829      msg("syntax conceal on", 0);
2830    } else {
2831      msg("syntax conceal off", 0);
2832    }
2833  } else if (STRNICMP(arg, "on", 2) == 0 && next - arg == 2) {
2834    curwin->w_s->b_syn_conceal = true;
2835  } else if (STRNICMP(arg, "off", 3) == 0 && next - arg == 3) {
2836    curwin->w_s->b_syn_conceal = false;
2837  } else {
2838    semsg(_(e_illegal_arg), arg);
2839  }
2840}
2841
2842/// Handle ":syntax case" command.
2843static void syn_cmd_case(exarg_T *eap, int syncing)
2844{
2845  char *arg = eap->arg;
2846  char *next;
2847
2848  eap->nextcmd = find_nextcmd(arg);
2849  if (eap->skip) {
2850    return;
2851  }
2852
2853  next = skiptowhite(arg);
2854  if (*arg == NUL) {
2855    if (curwin->w_s->b_syn_ic) {
2856      msg("syntax case ignore", 0);
2857    } else {
2858      msg("syntax case match", 0);
2859    }
2860  } else if (STRNICMP(arg, "match", 5) == 0 && next - arg == 5) {
2861    curwin->w_s->b_syn_ic = false;
2862  } else if (STRNICMP(arg, "ignore", 6) == 0 && next - arg == 6) {
2863    curwin->w_s->b_syn_ic = true;
2864  } else {
2865    semsg(_(e_illegal_arg), arg);
2866  }
2867}
2868
2869/// Handle ":syntax foldlevel" command.
2870static void syn_cmd_foldlevel(exarg_T *eap, int syncing)
2871{
2872  char *arg = eap->arg;
2873  char *arg_end;
2874
2875  eap->nextcmd = find_nextcmd(arg);
2876  if (eap->skip) {
2877    return;
2878  }
2879
2880  if (*arg == NUL) {
2881    switch (curwin->w_s->b_syn_foldlevel) {
2882    case SYNFLD_START:
2883      msg("syntax foldlevel start", 0);   break;
2884    case SYNFLD_MINIMUM:
2885      msg("syntax foldlevel minimum", 0); break;
2886    default:
2887      break;
2888    }
2889    return;
2890  }
2891
2892  arg_end = skiptowhite(arg);
2893  if (STRNICMP(arg, "start", 5) == 0 && arg_end - arg == 5) {
2894    curwin->w_s->b_syn_foldlevel = SYNFLD_START;
2895  } else if (STRNICMP(arg, "minimum", 7) == 0 && arg_end - arg == 7) {
2896    curwin->w_s->b_syn_foldlevel = SYNFLD_MINIMUM;
2897  } else {
2898    semsg(_(e_illegal_arg), arg);
2899    return;
2900  }
2901
2902  arg = skipwhite(arg_end);
2903  if (*arg != NUL) {
2904    semsg(_(e_illegal_arg), arg);
2905  }
2906}
2907
2908/// Handle ":syntax spell" command.
2909static void syn_cmd_spell(exarg_T *eap, int syncing)
2910{
2911  char *arg = eap->arg;
2912  char *next;
2913
2914  eap->nextcmd = find_nextcmd(arg);
2915  if (eap->skip) {
2916    return;
2917  }
2918
2919  next = skiptowhite(arg);
2920  if (*arg == NUL) {
2921    if (curwin->w_s->b_syn_spell == SYNSPL_TOP) {
2922      msg("syntax spell toplevel", 0);
2923    } else if (curwin->w_s->b_syn_spell == SYNSPL_NOTOP) {
2924      msg("syntax spell notoplevel", 0);
2925    } else {
2926      msg("syntax spell default", 0);
2927    }
2928  } else if (STRNICMP(arg, "toplevel", 8) == 0 && next - arg == 8) {
2929    curwin->w_s->b_syn_spell = SYNSPL_TOP;
2930  } else if (STRNICMP(arg, "notoplevel", 10) == 0 && next - arg == 10) {
2931    curwin->w_s->b_syn_spell = SYNSPL_NOTOP;
2932  } else if (STRNICMP(arg, "default", 7) == 0 && next - arg == 7) {
2933    curwin->w_s->b_syn_spell = SYNSPL_DEFAULT;
2934  } else {
2935    semsg(_(e_illegal_arg), arg);
2936    return;
2937  }
2938
2939  // assume spell checking changed, force a redraw
2940  redraw_later(curwin, UPD_NOT_VALID);
2941}
2942
2943/// Handle ":syntax iskeyword" command.
2944static void syn_cmd_iskeyword(exarg_T *eap, int syncing)
2945{
2946  char *arg = eap->arg;
2947
2948  if (eap->skip) {
2949    return;
2950  }
2951
2952  arg = skipwhite(arg);
2953  if (*arg == NUL) {
2954    msg_puts("\n");
2955    if (curwin->w_s->b_syn_isk != empty_string_option) {
2956      msg_puts("syntax iskeyword ");
2957      msg_outtrans(curwin->w_s->b_syn_isk, 0, false);
2958    } else {
2959      msg_outtrans(_("syntax iskeyword not set"), 0, false);
2960    }
2961  } else {
2962    if (STRNICMP(arg, "clear", 5) == 0) {
2963      memmove(curwin->w_s->b_syn_chartab, curbuf->b_chartab, (size_t)32);
2964      clear_string_option(&curwin->w_s->b_syn_isk);
2965    } else {
2966      if (check_isopt(arg) == FAIL) {
2967        emsg(_(e_invarg));
2968        return;
2969      }
2970      clear_string_option(&curwin->w_s->b_syn_isk);
2971      curwin->w_s->b_syn_isk = xstrdup(arg);
2972      parse_isopt(curwin->w_s->b_syn_isk, curwin->w_s->b_syn_chartab);
2973    }
2974  }
2975  redraw_later(curwin, UPD_NOT_VALID);
2976}
2977
2978// Clear all syntax info for one buffer.
2979void syntax_clear(synblock_T *block)
2980{
2981  block->b_syn_error = false;           // clear previous error
2982  block->b_syn_slow = false;            // clear previous timeout
2983  block->b_syn_ic = false;              // Use case, by default
2984  block->b_syn_foldlevel = SYNFLD_START;
2985  block->b_syn_spell = SYNSPL_DEFAULT;  // default spell checking
2986  block->b_syn_containedin = false;
2987  block->b_syn_conceal = false;
2988
2989  // free the keywords
2990  clear_keywtab(&block->b_keywtab);
2991  clear_keywtab(&block->b_keywtab_ic);
2992
2993  // free the syntax patterns
2994  for (int i = block->b_syn_patterns.ga_len; --i >= 0;) {
2995    syn_clear_pattern(block, i);
2996  }
2997  ga_clear(&block->b_syn_patterns);
2998
2999  // free the syntax clusters
3000  for (int i = block->b_syn_clusters.ga_len; --i >= 0;) {
3001    syn_clear_cluster(block, i);
3002  }
3003  ga_clear(&block->b_syn_clusters);
3004  block->b_spell_cluster_id = 0;
3005  block->b_nospell_cluster_id = 0;
3006
3007  block->b_syn_sync_flags = 0;
3008  block->b_syn_sync_minlines = 0;
3009  block->b_syn_sync_maxlines = 0;
3010  block->b_syn_sync_linebreaks = 0;
3011
3012  vim_regfree(block->b_syn_linecont_prog);
3013  block->b_syn_linecont_prog = NULL;
3014  XFREE_CLEAR(block->b_syn_linecont_pat);
3015  block->b_syn_folditems = 0;
3016  clear_string_option(&block->b_syn_isk);
3017
3018  // free the stored states
3019  syn_stack_free_all(block);
3020  invalidate_current_state();
3021
3022  // Reset the counter for ":syn include"
3023  running_syn_inc_tag = 0;
3024}
3025
3026// Get rid of ownsyntax for window "wp".
3027void reset_synblock(win_T *wp)
3028{
3029  if (wp->w_s != &wp->w_buffer->b_s) {
3030    syntax_clear(wp->w_s);
3031    xfree(wp->w_s);
3032    wp->w_s = &wp->w_buffer->b_s;
3033  }
3034}
3035
3036// Clear syncing info for one buffer.
3037static void syntax_sync_clear(void)
3038{
3039  // free the syntax patterns
3040  for (int i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0;) {
3041    if (SYN_ITEMS(curwin->w_s)[i].sp_syncing) {
3042      syn_remove_pattern(curwin->w_s, i);
3043    }
3044  }
3045
3046  curwin->w_s->b_syn_sync_flags = 0;
3047  curwin->w_s->b_syn_sync_minlines = 0;
3048  curwin->w_s->b_syn_sync_maxlines = 0;
3049  curwin->w_s->b_syn_sync_linebreaks = 0;
3050
3051  vim_regfree(curwin->w_s->b_syn_linecont_prog);
3052  curwin->w_s->b_syn_linecont_prog = NULL;
3053  XFREE_CLEAR(curwin->w_s->b_syn_linecont_pat);
3054  clear_string_option(&curwin->w_s->b_syn_isk);
3055
3056  syn_stack_free_all(curwin->w_s);              // Need to recompute all syntax.
3057}
3058
3059// Remove one pattern from the buffer's pattern list.
3060static void syn_remove_pattern(synblock_T *block, int idx)
3061{
3062  synpat_T *spp;
3063
3064  spp = &(SYN_ITEMS(block)[idx]);
3065  if (spp->sp_flags & HL_FOLD) {
3066    block->b_syn_folditems--;
3067  }
3068  syn_clear_pattern(block, idx);
3069  memmove(spp, spp + 1, sizeof(synpat_T) * (size_t)(block->b_syn_patterns.ga_len - idx - 1));
3070  block->b_syn_patterns.ga_len--;
3071}
3072
3073// Clear and free one syntax pattern.  When clearing all, must be called from
3074// last to first!
3075static void syn_clear_pattern(synblock_T *block, int i)
3076{
3077  xfree(SYN_ITEMS(block)[i].sp_pattern);
3078  vim_regfree(SYN_ITEMS(block)[i].sp_prog);
3079  // Only free sp_cont_list and sp_next_list of first start pattern
3080  if (i == 0 || SYN_ITEMS(block)[i - 1].sp_type != SPTYPE_START) {
3081    xfree(SYN_ITEMS(block)[i].sp_cont_list);
3082    xfree(SYN_ITEMS(block)[i].sp_next_list);
3083    xfree(SYN_ITEMS(block)[i].sp_syn.cont_in_list);
3084  }
3085}
3086
3087// Clear and free one syntax cluster.
3088static void syn_clear_cluster(synblock_T *block, int i)
3089{
3090  xfree(SYN_CLSTR(block)[i].scl_name);
3091  xfree(SYN_CLSTR(block)[i].scl_name_u);
3092  xfree(SYN_CLSTR(block)[i].scl_list);
3093}
3094
3095/// Handle ":syntax clear" command.
3096static void syn_cmd_clear(exarg_T *eap, int syncing)
3097{
3098  char *arg = eap->arg;
3099  char *arg_end;
3100  int id;
3101
3102  eap->nextcmd = find_nextcmd(arg);
3103  if (eap->skip) {
3104    return;
3105  }
3106
3107  // We have to disable this within ":syn include @group filename",
3108  // because otherwise @group would get deleted.
3109  // Only required for Vim 5.x syntax files, 6.0 ones don't contain ":syn
3110  // clear".
3111  if (curwin->w_s->b_syn_topgrp != 0) {
3112    return;
3113  }
3114
3115  if (ends_excmd(*arg)) {
3116    // No argument: Clear all syntax items.
3117    if (syncing) {
3118      syntax_sync_clear();
3119    } else {
3120      syntax_clear(curwin->w_s);
3121      if (curwin->w_s == &curwin->w_buffer->b_s) {
3122        do_unlet(S_LEN("b:current_syntax"), true);
3123      }
3124      do_unlet(S_LEN("w:current_syntax"), true);
3125    }
3126  } else {
3127    // Clear the group IDs that are in the argument.
3128    while (!ends_excmd(*arg)) {
3129      arg_end = skiptowhite(arg);
3130      if (*arg == '@') {
3131        id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1));
3132        if (id == 0) {
3133          semsg(_("E391: No such syntax cluster: %s"), arg);
3134          break;
3135        }
3136        // We can't physically delete a cluster without changing
3137        // the IDs of other clusters, so we do the next best thing
3138        // and make it empty.
3139        int scl_id = id - SYNID_CLUSTER;
3140
3141        XFREE_CLEAR(SYN_CLSTR(curwin->w_s)[scl_id].scl_list);
3142      } else {
3143        id = syn_name2id_len(arg, (size_t)(arg_end - arg));
3144        if (id == 0) {
3145          semsg(_(e_nogroup), arg);
3146          break;
3147        }
3148        syn_clear_one(id, syncing);
3149      }
3150      arg = skipwhite(arg_end);
3151    }
3152  }
3153  redraw_curbuf_later(UPD_SOME_VALID);
3154  syn_stack_free_all(curwin->w_s);              // Need to recompute all syntax.
3155}
3156
3157// Clear one syntax group for the current buffer.
3158static void syn_clear_one(const int id, const bool syncing)
3159{
3160  synpat_T *spp;
3161
3162  // Clear keywords only when not ":syn sync clear group-name"
3163  if (!syncing) {
3164    syn_clear_keyword(id, &curwin->w_s->b_keywtab);
3165    syn_clear_keyword(id, &curwin->w_s->b_keywtab_ic);
3166  }
3167
3168  // clear the patterns for "id"
3169  for (int idx = curwin->w_s->b_syn_patterns.ga_len; --idx >= 0;) {
3170    spp = &(SYN_ITEMS(curwin->w_s)[idx]);
3171    if (spp->sp_syn.id != id || spp->sp_syncing != syncing) {
3172      continue;
3173    }
3174    syn_remove_pattern(curwin->w_s, idx);
3175  }
3176}
3177
3178// Handle ":syntax on" command.
3179static void syn_cmd_on(exarg_T *eap, int syncing)
3180{
3181  syn_cmd_onoff(eap, "syntax");
3182}
3183
3184// Handle ":syntax reset" command.
3185// It actually resets highlighting, not syntax.
3186static void syn_cmd_reset(exarg_T *eap, int syncing)
3187{
3188  eap->nextcmd = check_nextcmd(eap->arg);
3189  if (!eap->skip) {
3190    init_highlight(true, true);
3191  }
3192}
3193
3194// Handle ":syntax manual" command.
3195static void syn_cmd_manual(exarg_T *eap, int syncing)
3196{
3197  syn_cmd_onoff(eap, "manual");
3198}
3199
3200// Handle ":syntax off" command.
3201static void syn_cmd_off(exarg_T *eap, int syncing)
3202{
3203  syn_cmd_onoff(eap, "nosyntax");
3204}
3205
3206static void syn_cmd_onoff(exarg_T *eap, char *name)
3207  FUNC_ATTR_NONNULL_ALL
3208{
3209  eap->nextcmd = check_nextcmd(eap->arg);
3210  if (!eap->skip) {
3211    did_syntax_onoff = true;
3212    char buf[100];
3213    memcpy(buf, "so ", 4);
3214    vim_snprintf(buf + 3, sizeof(buf) - 3, SYNTAX_FNAME, name);
3215    do_cmdline_cmd(buf);
3216  }
3217}
3218
3219void syn_maybe_enable(void)
3220{
3221  if (!did_syntax_onoff) {
3222    exarg_T ea;
3223    ea.arg = "";
3224    ea.skip = false;
3225    syn_cmd_on(&ea, false);
3226  }
3227}
3228
3229/// Handle ":syntax [list]" command: list current syntax words.
3230///
3231/// @param syncing  when true: list syncing items
3232static void syn_cmd_list(exarg_T *eap, int syncing)
3233{
3234  char *arg = eap->arg;
3235  char *arg_end;
3236
3237  eap->nextcmd = find_nextcmd(arg);
3238  if (eap->skip) {
3239    return;
3240  }
3241
3242  msg_ext_set_kind("list_cmd");
3243  if (!syntax_present(curwin)) {
3244    msg(_(msg_no_items), 0);
3245    return;
3246  }
3247
3248  if (syncing) {
3249    if (curwin->w_s->b_syn_sync_flags & SF_CCOMMENT) {
3250      msg_puts(_("syncing on C-style comments"));
3251      syn_lines_msg();
3252      syn_match_msg();
3253    } else if (curwin->w_s->b_syn_sync_flags & SF_MATCH) {
3254      msg_puts_title(_("\n--- Syntax sync items ---"));
3255      if (curwin->w_s->b_syn_sync_minlines > 0
3256          || curwin->w_s->b_syn_sync_maxlines > 0
3257          || curwin->w_s->b_syn_sync_linebreaks > 0) {
3258        msg_puts(_("\nsyncing on items"));
3259        syn_lines_msg();
3260        syn_match_msg();
3261      }
3262      for (int id = 1; id <= highlight_num_groups() && !got_int; id++) {
3263        syn_list_one(id, syncing, false);
3264      }
3265    } else {
3266      if (curwin->w_s->b_syn_sync_minlines == 0) {
3267        msg_puts(_("no syncing"));
3268      } else {
3269        if (curwin->w_s->b_syn_sync_minlines == MAXLNUM) {
3270          msg_puts(_("syncing starts at the first line"));
3271        } else {
3272          msg_puts(_("syncing starts "));
3273          msg_outnum(curwin->w_s->b_syn_sync_minlines);
3274          msg_puts(_(" lines before top line"));
3275        }
3276        syn_match_msg();
3277      }
3278    }
3279    return;
3280  }
3281
3282  msg_puts_title(_("\n--- Syntax items ---"));
3283  if (ends_excmd(*arg)) {
3284    // No argument: List all group IDs and all syntax clusters.
3285    for (int id = 1; id <= highlight_num_groups() && !got_int; id++) {
3286      syn_list_one(id, syncing, false);
3287    }
3288    for (int id = 0; id < curwin->w_s->b_syn_clusters.ga_len && !got_int; id++) {
3289      syn_list_cluster(id);
3290    }
3291  } else {
3292    // List the group IDs and syntax clusters that are in the argument.
3293    while (!ends_excmd(*arg) && !got_int) {
3294      arg_end = skiptowhite(arg);
3295      if (*arg == '@') {
3296        int id = syn_scl_namen2id(arg + 1, (int)(arg_end - arg - 1));
3297        if (id == 0) {
3298          semsg(_("E392: No such syntax cluster: %s"), arg);
3299        } else {
3300          syn_list_cluster(id - SYNID_CLUSTER);
3301        }
3302      } else {
3303        int id = syn_name2id_len(arg, (size_t)(arg_end - arg));
3304        if (id == 0) {
3305          semsg(_(e_nogroup), arg);
3306        } else {
3307          syn_list_one(id, syncing, true);
3308        }
3309      }
3310      arg = skipwhite(arg_end);
3311    }
3312  }
3313  eap->nextcmd = check_nextcmd(arg);
3314}
3315
3316static void syn_lines_msg(void)
3317{
3318  if (curwin->w_s->b_syn_sync_maxlines > 0
3319      || curwin->w_s->b_syn_sync_minlines > 0) {
3320    msg_puts("; ");
3321    if (curwin->w_s->b_syn_sync_minlines == MAXLNUM) {
3322      msg_puts(_("from the first line"));
3323    } else {
3324      if (curwin->w_s->b_syn_sync_minlines > 0) {
3325        msg_puts(_("minimal "));
3326        msg_outnum(curwin->w_s->b_syn_sync_minlines);
3327        if (curwin->w_s->b_syn_sync_maxlines) {
3328          msg_puts(", ");
3329        }
3330      }
3331      if (curwin->w_s->b_syn_sync_maxlines > 0) {
3332        msg_puts(_("maximal "));
3333        msg_outnum(curwin->w_s->b_syn_sync_maxlines);
3334      }
3335      msg_puts(_(" lines before top line"));
3336    }
3337  }
3338}
3339
3340static void syn_match_msg(void)
3341{
3342  if (curwin->w_s->b_syn_sync_linebreaks > 0) {
3343    msg_puts(_("; match "));
3344    msg_outnum(curwin->w_s->b_syn_sync_linebreaks);
3345    msg_puts(_(" line breaks"));
3346  }
3347}
3348
3349static int last_matchgroup;
3350
3351/// List one syntax item, for ":syntax" or "syntax list syntax_name".
3352///
3353/// @param syncing    when true: list syncing items
3354/// @param link_only  when true; list link-only too
3355static void syn_list_one(const int id, const bool syncing, const bool link_only)
3356{
3357  bool did_header = false;
3358  static keyvalue_T namelist1[] = {
3359    KEYVALUE_ENTRY(HL_DISPLAY, "display"),
3360    KEYVALUE_ENTRY(HL_CONTAINED, "contained"),
3361    KEYVALUE_ENTRY(HL_ONELINE, "oneline"),
3362    KEYVALUE_ENTRY(HL_KEEPEND, "keepend"),
3363    KEYVALUE_ENTRY(HL_EXTEND, "extend"),
3364    KEYVALUE_ENTRY(HL_EXCLUDENL, "excludenl"),
3365    KEYVALUE_ENTRY(HL_TRANSP, "transparent"),
3366    KEYVALUE_ENTRY(HL_FOLD, "fold"),
3367    KEYVALUE_ENTRY(HL_CONCEAL, "conceal"),
3368    KEYVALUE_ENTRY(HL_CONCEALENDS, "concealends"),
3369  };
3370  static keyvalue_T namelist2[] = {
3371    KEYVALUE_ENTRY(HL_SKIPWHITE, "skipwhite"),
3372    KEYVALUE_ENTRY(HL_SKIPNL, "skipnl"),
3373    KEYVALUE_ENTRY(HL_SKIPEMPTY, "skipempty"),
3374  };
3375
3376  const int hl_id = HLF_D;      // highlight like directories
3377
3378  // list the keywords for "id"
3379  if (!syncing) {
3380    did_header = syn_list_keywords(id, &curwin->w_s->b_keywtab, false, hl_id);
3381    did_header = syn_list_keywords(id, &curwin->w_s->b_keywtab_ic, did_header, hl_id);
3382  }
3383
3384  // list the patterns for "id"
3385  for (int idx = 0;
3386       idx < curwin->w_s->b_syn_patterns.ga_len && !got_int;
3387       idx++) {
3388    const synpat_T *const spp = &(SYN_ITEMS(curwin->w_s)[idx]);
3389    if (spp->sp_syn.id != id || spp->sp_syncing != syncing) {
3390      continue;
3391    }
3392
3393    syn_list_header(did_header, 0, id, true);
3394    did_header = true;
3395    last_matchgroup = 0;
3396    if (spp->sp_type == SPTYPE_MATCH) {
3397      put_pattern("match", ' ', spp, hl_id);
3398      msg_putchar(' ');
3399    } else if (spp->sp_type == SPTYPE_START) {
3400      while (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_START) {
3401        put_pattern("start", '=', &SYN_ITEMS(curwin->w_s)[idx++], hl_id);
3402      }
3403      if (SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_SKIP) {
3404        put_pattern("skip", '=', &SYN_ITEMS(curwin->w_s)[idx++], hl_id);
3405      }
3406      while (idx < curwin->w_s->b_syn_patterns.ga_len
3407             && SYN_ITEMS(curwin->w_s)[idx].sp_type == SPTYPE_END) {
3408        put_pattern("end", '=', &SYN_ITEMS(curwin->w_s)[idx++], hl_id);
3409      }
3410      idx--;
3411      msg_putchar(' ');
3412    }
3413    syn_list_flags(namelist1, ARRAY_SIZE(namelist1), spp->sp_flags, hl_id);
3414
3415    if (spp->sp_cont_list != NULL) {
3416      put_id_list("contains", spp->sp_cont_list, hl_id);
3417    }
3418
3419    if (spp->sp_syn.cont_in_list != NULL) {
3420      put_id_list("containedin", spp->sp_syn.cont_in_list, hl_id);
3421    }
3422
3423    if (spp->sp_next_list != NULL) {
3424      put_id_list("nextgroup", spp->sp_next_list, hl_id);
3425      syn_list_flags(namelist2, ARRAY_SIZE(namelist2), spp->sp_flags, hl_id);
3426    }
3427    if (spp->sp_flags & (HL_SYNC_HERE|HL_SYNC_THERE)) {
3428      if (spp->sp_flags & HL_SYNC_HERE) {
3429        msg_puts_hl("grouphere", hl_id, false);
3430      } else {
3431        msg_puts_hl("groupthere", hl_id, false);
3432      }
3433      msg_putchar(' ');
3434      if (spp->sp_sync_idx >= 0) {
3435        msg_outtrans(highlight_group_name(SYN_ITEMS(curwin->w_s)
3436                                          [spp->sp_sync_idx].sp_syn.id - 1), 0, false);
3437      } else {
3438        msg_puts("NONE");
3439      }
3440      msg_putchar(' ');
3441    }
3442  }
3443
3444  // list the link, if there is one
3445  if (highlight_link_id(id - 1) && (did_header || link_only) && !got_int) {
3446    syn_list_header(did_header, 0, id, true);
3447    msg_puts_hl("links to", hl_id, false);
3448    msg_putchar(' ');
3449    msg_outtrans(highlight_group_name(highlight_link_id(id - 1) - 1), 0, false);
3450  }
3451}
3452
3453static void syn_list_flags(keyvalue_T *nlist, size_t nr_entries, int flags, int hl_id)
3454{
3455  for (size_t i = 0; i < nr_entries; i++) {
3456    if (flags & nlist[i].key) {
3457      msg_puts_hl(nlist[i].value, hl_id, false);
3458      msg_putchar(' ');
3459    }
3460  }
3461}
3462
3463// List one syntax cluster, for ":syntax" or "syntax list syntax_name".
3464static void syn_list_cluster(int id)
3465{
3466  int endcol = 15;
3467
3468  // slight hack:  roughly duplicate the guts of syn_list_header()
3469  msg_putchar('\n');
3470  msg_outtrans(SYN_CLSTR(curwin->w_s)[id].scl_name, 0, false);
3471
3472  if (msg_col >= endcol) {      // output at least one space
3473    endcol = msg_col + 1;
3474  }
3475  if (Columns <= endcol) {      // avoid hang for tiny window
3476    endcol = Columns - 1;
3477  }
3478
3479  msg_advance(endcol);
3480  if (SYN_CLSTR(curwin->w_s)[id].scl_list != NULL) {
3481    put_id_list("cluster", SYN_CLSTR(curwin->w_s)[id].scl_list, HLF_D);
3482  } else {
3483    msg_puts_hl("cluster", HLF_D, false);
3484    msg_puts("=NONE");
3485  }
3486}
3487
3488static void put_id_list(const char *const name, const int16_t *const list, const int hl_id)
3489{
3490  msg_puts_hl(name, hl_id, false);
3491  msg_putchar('=');
3492  for (const int16_t *p = list; *p; p++) {
3493    if (*p >= SYNID_ALLBUT && *p < SYNID_TOP) {
3494      if (p[1]) {
3495        msg_puts("ALLBUT");
3496      } else {
3497        msg_puts("ALL");
3498      }
3499    } else if (*p >= SYNID_TOP && *p < SYNID_CONTAINED) {
3500      msg_puts("TOP");
3501    } else if (*p >= SYNID_CONTAINED && *p < SYNID_CLUSTER) {
3502      msg_puts("CONTAINED");
3503    } else if (*p >= SYNID_CLUSTER) {
3504      int scl_id = *p - SYNID_CLUSTER;
3505
3506      msg_putchar('@');
3507      msg_outtrans(SYN_CLSTR(curwin->w_s)[scl_id].scl_name, 0, false);
3508    } else {
3509      msg_outtrans(highlight_group_name(*p - 1), 0, false);
3510    }
3511    if (p[1]) {
3512      msg_putchar(',');
3513    }
3514  }
3515  msg_putchar(' ');
3516}
3517
3518static void put_pattern(const char *const s, const int c, const synpat_T *const spp,
3519                        const int hl_id)
3520{
3521  static const char *const sepchars = "/+=-#@\"|'^&";
3522  int i;
3523
3524  // May have to write "matchgroup=group"
3525  if (last_matchgroup != spp->sp_syn_match_id) {
3526    last_matchgroup = spp->sp_syn_match_id;
3527    msg_puts_hl("matchgroup", hl_id, false);
3528    msg_putchar('=');
3529    if (last_matchgroup == 0) {
3530      msg_outtrans("NONE", 0, false);
3531    } else {
3532      msg_outtrans(highlight_group_name(last_matchgroup - 1), 0, false);
3533    }
3534    msg_putchar(' ');
3535  }
3536
3537  // Output the name of the pattern and an '=' or ' '.
3538  msg_puts_hl(s, hl_id, false);
3539  msg_putchar(c);
3540
3541  // output the pattern, in between a char that is not in the pattern
3542  for (i = 0; vim_strchr(spp->sp_pattern, (uint8_t)sepchars[i]) != NULL;) {
3543    if (sepchars[++i] == NUL) {
3544      i = 0;            // no good char found, just use the first one
3545      break;
3546    }
3547  }
3548  msg_putchar(sepchars[i]);
3549  msg_outtrans(spp->sp_pattern, 0, false);
3550  msg_putchar(sepchars[i]);
3551
3552  // output any pattern options
3553  bool first = true;
3554  for (i = 0; i < SPO_COUNT; i++) {
3555    const int mask = (1 << i);
3556    if (!(spp->sp_off_flags & (mask + (mask << SPO_COUNT)))) {
3557      continue;
3558    }
3559    if (!first) {
3560      msg_putchar(',');  // Separate with commas.
3561    }
3562    msg_puts(spo_name_tab[i]);
3563    const int n = spp->sp_offsets[i];
3564    if (i != SPO_LC_OFF) {
3565      if (spp->sp_off_flags & mask) {
3566        msg_putchar('s');
3567      } else {
3568        msg_putchar('e');
3569      }
3570      if (n > 0) {
3571        msg_putchar('+');
3572      }
3573    }
3574    if (n || i == SPO_LC_OFF) {
3575      msg_outnum(n);
3576    }
3577    first = false;
3578  }
3579  msg_putchar(' ');
3580}
3581
3582/// List or clear the keywords for one syntax group.
3583///
3584/// @param did_header  header has already been printed
3585///
3586/// @return            true if the header has been printed.
3587static bool syn_list_keywords(const int id, const hashtab_T *const ht, bool did_header,
3588                              const int hl_id)
3589{
3590  int prev_contained = 0;
3591  const int16_t *prev_next_list = NULL;
3592  const int16_t *prev_cont_in_list = NULL;
3593  int prev_skipnl = 0;
3594  int prev_skipwhite = 0;
3595  int prev_skipempty = 0;
3596
3597  // Unfortunately, this list of keywords is not sorted on alphabet but on
3598  // hash value...
3599  size_t todo = ht->ht_used;
3600  for (const hashitem_T *hi = ht->ht_array; todo > 0 && !got_int; hi++) {
3601    if (HASHITEM_EMPTY(hi)) {
3602      continue;
3603    }
3604    todo--;
3605    for (keyentry_T *kp = HI2KE(hi); kp != NULL && !got_int; kp = kp->ke_next) {
3606      if (kp->k_syn.id == id) {
3607        int outlen = 0;
3608        bool force_newline = false;
3609        if (prev_contained != (kp->flags & HL_CONTAINED)
3610            || prev_skipnl != (kp->flags & HL_SKIPNL)
3611            || prev_skipwhite != (kp->flags & HL_SKIPWHITE)
3612            || prev_skipempty != (kp->flags & HL_SKIPEMPTY)
3613            || prev_cont_in_list != kp->k_syn.cont_in_list
3614            || prev_next_list != kp->next_list) {
3615          force_newline = true;
3616        } else {
3617          outlen = (int)strlen(kp->keyword);
3618        }
3619        // output "contained" and "nextgroup" on each line
3620        if (syn_list_header(did_header, outlen, id, force_newline)) {
3621          prev_contained = 0;
3622          prev_next_list = NULL;
3623          prev_cont_in_list = NULL;
3624          prev_skipnl = 0;
3625          prev_skipwhite = 0;
3626          prev_skipempty = 0;
3627        }
3628        did_header = true;
3629        if (prev_contained != (kp->flags & HL_CONTAINED)) {
3630          msg_puts_hl("contained", hl_id, false);
3631          msg_putchar(' ');
3632          prev_contained = (kp->flags & HL_CONTAINED);
3633        }
3634        if (kp->k_syn.cont_in_list != prev_cont_in_list) {
3635          put_id_list("containedin", kp->k_syn.cont_in_list, hl_id);
3636          msg_putchar(' ');
3637          prev_cont_in_list = kp->k_syn.cont_in_list;
3638        }
3639        if (kp->next_list != prev_next_list) {
3640          put_id_list("nextgroup", kp->next_list, hl_id);
3641          msg_putchar(' ');
3642          prev_next_list = kp->next_list;
3643          if (kp->flags & HL_SKIPNL) {
3644            msg_puts_hl("skipnl", hl_id, false);
3645            msg_putchar(' ');
3646            prev_skipnl = (kp->flags & HL_SKIPNL);
3647          }
3648          if (kp->flags & HL_SKIPWHITE) {
3649            msg_puts_hl("skipwhite", hl_id, false);
3650            msg_putchar(' ');
3651            prev_skipwhite = (kp->flags & HL_SKIPWHITE);
3652          }
3653          if (kp->flags & HL_SKIPEMPTY) {
3654            msg_puts_hl("skipempty", hl_id, false);
3655            msg_putchar(' ');
3656            prev_skipempty = (kp->flags & HL_SKIPEMPTY);
3657          }
3658        }
3659        msg_outtrans(kp->keyword, 0, false);
3660      }
3661    }
3662  }
3663
3664  return did_header;
3665}
3666
3667static void syn_clear_keyword(int id, hashtab_T *ht)
3668{
3669  hash_lock(ht);
3670  int todo = (int)ht->ht_used;
3671  for (hashitem_T *hi = ht->ht_array; todo > 0; hi++) {
3672    if (HASHITEM_EMPTY(hi)) {
3673      continue;
3674    }
3675    todo--;
3676    keyentry_T *kp_prev = NULL;
3677    for (keyentry_T *kp = HI2KE(hi); kp != NULL;) {
3678      if (kp->k_syn.id == id) {
3679        keyentry_T *kp_next = kp->ke_next;
3680        if (kp_prev == NULL) {
3681          if (kp_next == NULL) {
3682            hash_remove(ht, hi);
3683          } else {
3684            hi->hi_key = KE2HIKEY(kp_next);
3685          }
3686        } else {
3687          kp_prev->ke_next = kp_next;
3688        }
3689        xfree(kp->next_list);
3690        xfree(kp->k_syn.cont_in_list);
3691        xfree(kp);
3692        kp = kp_next;
3693      } else {
3694        kp_prev = kp;
3695        kp = kp->ke_next;
3696      }
3697    }
3698  }
3699  hash_unlock(ht);
3700}
3701
3702// Clear a whole keyword table.
3703static void clear_keywtab(hashtab_T *ht)
3704{
3705  keyentry_T *kp_next;
3706
3707  int todo = (int)ht->ht_used;
3708  for (hashitem_T *hi = ht->ht_array; todo > 0; hi++) {
3709    if (!HASHITEM_EMPTY(hi)) {
3710      todo--;
3711      for (keyentry_T *kp = HI2KE(hi); kp != NULL; kp = kp_next) {
3712        kp_next = kp->ke_next;
3713        xfree(kp->next_list);
3714        xfree(kp->k_syn.cont_in_list);
3715        xfree(kp);
3716      }
3717    }
3718  }
3719  hash_clear(ht);
3720  hash_init(ht);
3721}
3722
3723/// Add a keyword to the list of keywords.
3724///
3725/// @param name name of keyword
3726/// @param id group ID for this keyword
3727/// @param flags flags for this keyword
3728/// @param cont_in_list containedin for this keyword
3729/// @param next_list nextgroup for this keyword
3730static void add_keyword(char *const name, size_t namelen, const int id, const int flags,
3731                        int16_t *const cont_in_list, int16_t *const next_list,
3732                        const int conceal_char)
3733{
3734  char name_folded[MAXKEYWLEN + 1];
3735  const char *name_ic;
3736  size_t name_iclen;
3737  if (curwin->w_s->b_syn_ic) {
3738    name_ic = str_foldcase(name, (int)namelen, name_folded, MAXKEYWLEN + 1);
3739    name_iclen = strlen(name_ic);
3740  } else {
3741    name_ic = name;
3742    name_iclen = namelen;
3743  }
3744
3745  keyentry_T *const kp = xmalloc(offsetof(keyentry_T, keyword) + name_iclen + 1);
3746  STRCPY(kp->keyword, name_ic);
3747  kp->k_syn.id = (int16_t)id;
3748  kp->k_syn.inc_tag = current_syn_inc_tag;
3749  kp->flags = flags;
3750  kp->k_char = conceal_char;
3751  kp->k_syn.cont_in_list = copy_id_list(cont_in_list);
3752  if (cont_in_list != NULL) {
3753    curwin->w_s->b_syn_containedin = true;
3754  }
3755  kp->next_list = copy_id_list(next_list);
3756
3757  const hash_T hash = hash_hash(kp->keyword);
3758  hashtab_T *const ht = (curwin->w_s->b_syn_ic)
3759                        ? &curwin->w_s->b_keywtab_ic
3760                        : &curwin->w_s->b_keywtab;
3761  hashitem_T *const hi = hash_lookup(ht, kp->keyword,
3762                                     strlen(kp->keyword), hash);
3763
3764  // even though it looks like only the kp->keyword member is
3765  // being used here, vim uses some pointer trickery to get the original
3766  // struct again later by using knowledge of the offset of the keyword
3767  // field in the struct. See the definition of the HI2KE macro.
3768  if (HASHITEM_EMPTY(hi)) {
3769    // new keyword, add to hashtable
3770    kp->ke_next = NULL;
3771    hash_add_item(ht, hi, kp->keyword, hash);
3772  } else {
3773    // keyword already exists, prepend to list
3774    kp->ke_next = HI2KE(hi);
3775    hi->hi_key = KE2HIKEY(kp);
3776  }
3777}
3778
3779/// Get the start and end of the group name argument.
3780///
3781/// @param arg       start of the argument
3782/// @param name_end  pointer to end of the name
3783///
3784/// @return          a pointer to the first argument.
3785///                  Return NULL if the end of the command was found instead of further args.
3786static char *get_group_name(char *arg, char **name_end)
3787{
3788  *name_end = skiptowhite(arg);
3789  char *rest = skipwhite(*name_end);
3790
3791  // Check if there are enough arguments.  The first argument may be a
3792  // pattern, where '|' is allowed, so only check for NUL.
3793  if (ends_excmd(*arg) || *rest == NUL) {
3794    return NULL;
3795  }
3796  return rest;
3797}
3798
3799/// Check for syntax command option arguments.
3800/// This can be called at any place in the list of arguments, and just picks
3801/// out the arguments that are known.  Can be called several times in a row to
3802/// collect all options in between other arguments.
3803///
3804/// @param arg   next argument to be checked
3805/// @param opt   various things
3806/// @param skip  true if skipping over command
3807///
3808/// @return      a pointer to the next argument (which isn't an option).
3809///              Return NULL for any error;
3810static char *get_syn_options(char *arg, syn_opt_arg_T *opt, int *conceal_char, int skip)
3811{
3812  int len = 0;
3813  int fidx;
3814  static const struct flag {
3815    char *name;
3816    int argtype;
3817    int flags;
3818  } flagtab[] = { { "cCoOnNtTaAiInNeEdD",      0,      HL_CONTAINED },
3819                  { "oOnNeElLiInNeE",          0,      HL_ONELINE },
3820                  { "kKeEeEpPeEnNdD",          0,      HL_KEEPEND },
3821                  { "eExXtTeEnNdD",            0,      HL_EXTEND },
3822                  { "eExXcClLuUdDeEnNlL",      0,      HL_EXCLUDENL },
3823                  { "tTrRaAnNsSpPaArReEnNtT",  0,      HL_TRANSP },
3824                  { "sSkKiIpPnNlL",            0,      HL_SKIPNL },
3825                  { "sSkKiIpPwWhHiItTeE",      0,      HL_SKIPWHITE },
3826                  { "sSkKiIpPeEmMpPtTyY",      0,      HL_SKIPEMPTY },
3827                  { "gGrRoOuUpPhHeErReE",      0,      HL_SYNC_HERE },
3828                  { "gGrRoOuUpPtThHeErReE",    0,      HL_SYNC_THERE },
3829                  { "dDiIsSpPlLaAyY",          0,      HL_DISPLAY },
3830                  { "fFoOlLdD",                0,      HL_FOLD },
3831                  { "cCoOnNcCeEaAlL",          0,      HL_CONCEAL },
3832                  { "cCoOnNcCeEaAlLeEnNdDsS",  0,      HL_CONCEALENDS },
3833                  { "cCcChHaArR",              11,     0 },
3834                  { "cCoOnNtTaAiInNsS",        1,      0 },
3835                  { "cCoOnNtTaAiInNeEdDiInN",  2,      0 },
3836                  { "nNeExXtTgGrRoOuUpP",      3,      0 }, };
3837  static const char *const first_letters = "cCoOkKeEtTsSgGdDfFnN";
3838
3839  if (arg == NULL) {            // already detected error
3840    return NULL;
3841  }
3842
3843  if (curwin->w_s->b_syn_conceal) {
3844    opt->flags |= HL_CONCEAL;
3845  }
3846
3847  while (true) {
3848    // This is used very often when a large number of keywords is defined.
3849    // Need to skip quickly when no option name is found.
3850    // Also avoid tolower(), it's slow.
3851    if (strchr(first_letters, *arg) == NULL) {
3852      break;
3853    }
3854
3855    for (fidx = ARRAY_SIZE(flagtab); --fidx >= 0;) {
3856      char *p = flagtab[fidx].name;
3857      int i;
3858      for (i = 0, len = 0; p[i] != NUL; i += 2, len++) {
3859        if (arg[len] != p[i] && arg[len] != p[i + 1]) {
3860          break;
3861        }
3862      }
3863      if (p[i] == NUL && (ascii_iswhite(arg[len])
3864                          || (flagtab[fidx].argtype > 0
3865                              ? arg[len] == '='
3866                              : ends_excmd(arg[len])))) {
3867        if (opt->keyword
3868            && (flagtab[fidx].flags == HL_DISPLAY
3869                || flagtab[fidx].flags == HL_FOLD
3870                || flagtab[fidx].flags == HL_EXTEND)) {
3871          // treat "display", "fold" and "extend" as a keyword
3872          fidx = -1;
3873        }
3874        break;
3875      }
3876    }
3877    if (fidx < 0) {         // no match found
3878      break;
3879    }
3880
3881    if (flagtab[fidx].argtype == 1) {
3882      if (!opt->has_cont_list) {
3883        emsg(_(e_contains_argument_not_accepted_here));
3884        return NULL;
3885      }
3886      if (get_id_list(&arg, 8, &opt->cont_list, skip) == FAIL) {
3887        return NULL;
3888      }
3889    } else if (flagtab[fidx].argtype == 2) {
3890      if (get_id_list(&arg, 11, &opt->cont_in_list, skip) == FAIL) {
3891        return NULL;
3892      }
3893    } else if (flagtab[fidx].argtype == 3) {
3894      if (get_id_list(&arg, 9, &opt->next_list, skip) == FAIL) {
3895        return NULL;
3896      }
3897    } else if (flagtab[fidx].argtype == 11 && arg[5] == '=') {
3898      // cchar=?
3899      *conceal_char = utf_ptr2char(arg + 6);
3900      arg += utfc_ptr2len(arg + 6) - 1;
3901      if (!vim_isprintc(*conceal_char)) {
3902        emsg(_(e_invalid_cchar_value));
3903        return NULL;
3904      }
3905      arg = skipwhite(arg + 7);
3906    } else {
3907      opt->flags |= flagtab[fidx].flags;
3908      arg = skipwhite(arg + len);
3909
3910      if (flagtab[fidx].flags == HL_SYNC_HERE
3911          || flagtab[fidx].flags == HL_SYNC_THERE) {
3912        if (opt->sync_idx == NULL) {
3913          emsg(_("E393: group[t]here not accepted here"));
3914          return NULL;
3915        }
3916        char *gname_start = arg;
3917        arg = skiptowhite(arg);
3918        if (gname_start == arg) {
3919          return NULL;
3920        }
3921        char *gname = xstrnsave(gname_start, (size_t)(arg - gname_start));
3922        if (strcmp(gname, "NONE") == 0) {
3923          *opt->sync_idx = NONE_IDX;
3924        } else {
3925          int syn_id = syn_name2id(gname);
3926          int i;
3927          for (i = curwin->w_s->b_syn_patterns.ga_len; --i >= 0;) {
3928            if (SYN_ITEMS(curwin->w_s)[i].sp_syn.id == syn_id
3929                && SYN_ITEMS(curwin->w_s)[i].sp_type == SPTYPE_START) {
3930              *opt->sync_idx = i;
3931              break;
3932            }
3933          }
3934          if (i < 0) {
3935            semsg(_("E394: Didn't find region item for %s"), gname);
3936            xfree(gname);
3937            return NULL;
3938          }
3939        }
3940
3941        xfree(gname);
3942        arg = skipwhite(arg);
3943      } else if (flagtab[fidx].flags == HL_FOLD
3944                 && foldmethodIsSyntax(curwin)) {
3945        // Need to update folds later.
3946        foldUpdateAll(curwin);
3947      }
3948    }
3949  }
3950
3951  return arg;
3952}
3953
3954// Adjustments to syntax item when declared in a ":syn include"'d file.
3955// Set the contained flag, and if the item is not already contained, add it
3956// to the specified top-level group, if any.
3957static void syn_incl_toplevel(int id, int *flagsp)
3958{
3959  if ((*flagsp & HL_CONTAINED) || curwin->w_s->b_syn_topgrp == 0) {
3960    return;
3961  }
3962  *flagsp |= HL_CONTAINED | HL_INCLUDED_TOPLEVEL;
3963  if (curwin->w_s->b_syn_topgrp >= SYNID_CLUSTER) {
3964    // We have to alloc this, because syn_combine_list() will free it.
3965    int16_t *grp_list = xmalloc(2 * sizeof(*grp_list));
3966    int tlg_id = curwin->w_s->b_syn_topgrp - SYNID_CLUSTER;
3967
3968    grp_list[0] = (int16_t)id;
3969    grp_list[1] = 0;
3970    syn_combine_list(&SYN_CLSTR(curwin->w_s)[tlg_id].scl_list, &grp_list,
3971                     CLUSTER_ADD);
3972  }
3973}
3974
3975// Handle ":syntax include [@{group-name}] filename" command.
3976static void syn_cmd_include(exarg_T *eap, int syncing)
3977{
3978  char *arg = eap->arg;
3979  int sgl_id = 1;
3980  char *group_name_end;
3981  const char *errormsg = NULL;
3982  bool source = false;
3983
3984  eap->nextcmd = find_nextcmd(arg);
3985  if (eap->skip) {
3986    return;
3987  }
3988
3989  if (arg[0] == '@') {
3990    arg++;
3991    char *rest = get_group_name(arg, &group_name_end);
3992    if (rest == NULL) {
3993      emsg(_("E397: Filename required"));
3994      return;
3995    }
3996    sgl_id = syn_check_cluster(arg, (int)(group_name_end - arg));
3997    if (sgl_id == 0) {
3998      return;
3999    }
4000    // separate_nextcmd() and expand_filename() depend on this
4001    eap->arg = rest;
4002  }
4003
4004  // Everything that's left, up to the next command, should be the
4005  // filename to include.
4006  eap->argt |= (EX_XFILE | EX_NOSPC);
4007  separate_nextcmd(eap);
4008  if (*eap->arg == '<' || *eap->arg == '$' || path_is_absolute(eap->arg)) {
4009    // For an absolute path, "$VIM/..." or "<sfile>.." we ":source" the
4010    // file.  Need to expand the file name first.  In other cases
4011    // ":runtime!" is used.
4012    source = true;
4013    if (expand_filename(eap, syn_cmdlinep, &errormsg) == FAIL) {
4014      if (errormsg != NULL) {
4015        emsg(errormsg);
4016      }
4017      return;
4018    }
4019  } else {
4020    TO_SLASH(eap->arg);
4021  }
4022
4023  // Save and restore the existing top-level grouplist id and ":syn
4024  // include" tag around the actual inclusion.
4025  if (running_syn_inc_tag >= MAX_SYN_INC_TAG) {
4026    emsg(_("E847: Too many syntax includes"));
4027    return;
4028  }
4029  int prev_syn_inc_tag = current_syn_inc_tag;
4030  current_syn_inc_tag = ++running_syn_inc_tag;
4031  int prev_toplvl_grp = curwin->w_s->b_syn_topgrp;
4032  curwin->w_s->b_syn_topgrp = sgl_id;
4033  if (source
4034      ? do_source(eap->arg, false, DOSO_NONE, NULL) == FAIL
4035      : source_runtime(eap->arg, DIP_ALL) == FAIL) {
4036    semsg(_(e_notopen), eap->arg);
4037  }
4038  curwin->w_s->b_syn_topgrp = prev_toplvl_grp;
4039  current_syn_inc_tag = prev_syn_inc_tag;
4040}
4041
4042// Handle ":syntax keyword {group-name} [{option}] keyword .." command.
4043static void syn_cmd_keyword(exarg_T *eap, int syncing)
4044{
4045  char *arg = eap->arg;
4046  char *group_name_end;
4047  int syn_id;
4048  char *keyword_copy = NULL;
4049  syn_opt_arg_T syn_opt_arg;
4050  int conceal_char = NUL;
4051
4052  char *rest = get_group_name(arg, &group_name_end);
4053
4054  if (rest != NULL) {
4055    if (eap->skip) {
4056      syn_id = -1;
4057    } else {
4058      syn_id = syn_check_group(arg, (size_t)(group_name_end - arg));
4059    }
4060    if (syn_id != 0) {
4061      // Allocate a buffer, for removing backslashes in the keyword.
4062      keyword_copy = xmalloc(strlen(rest) + 1);
4063    }
4064    if (keyword_copy != NULL) {
4065      syn_opt_arg.flags = 0;
4066      syn_opt_arg.keyword = true;
4067      syn_opt_arg.sync_idx = NULL;
4068      syn_opt_arg.has_cont_list = false;
4069      syn_opt_arg.cont_in_list = NULL;
4070      syn_opt_arg.next_list = NULL;
4071
4072      // The options given apply to ALL keywords, so all options must be
4073      // found before keywords can be created.
4074      // 1: collect the options and copy the keywords to keyword_copy.
4075      int cnt = 0;
4076      char *p = keyword_copy;
4077      for (; rest != NULL && !ends_excmd(*rest); rest = skipwhite(rest)) {
4078        rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip);
4079        if (rest == NULL || ends_excmd(*rest)) {
4080          break;
4081        }
4082        // Copy the keyword, removing backslashes, and add a NUL.
4083        while (*rest != NUL && !ascii_iswhite(*rest)) {
4084          if (*rest == '\\' && rest[1] != NUL) {
4085            rest++;
4086          }
4087          *p++ = *rest++;
4088        }
4089        *p++ = NUL;
4090        cnt++;
4091      }
4092
4093      if (!eap->skip) {
4094        // Adjust flags for use of ":syn include".
4095        syn_incl_toplevel(syn_id, &syn_opt_arg.flags);
4096
4097        // 2: Add an entry for each keyword.
4098        size_t kwlen = 0;
4099        for (char *kw = keyword_copy; --cnt >= 0; kw += kwlen + 1) {
4100          for (p = vim_strchr(kw, '[');;) {
4101            if (p == NULL) {
4102              kwlen = strlen(kw);
4103            } else {
4104              *p = NUL;
4105              kwlen = (size_t)(p - kw);
4106            }
4107            add_keyword(kw, kwlen, syn_id, syn_opt_arg.flags,
4108                        syn_opt_arg.cont_in_list,
4109                        syn_opt_arg.next_list, conceal_char);
4110            if (p == NULL) {
4111              break;
4112            }
4113            if (p[1] == NUL) {
4114              semsg(_("E789: Missing ']': %s"), kw);
4115              goto error;
4116            }
4117            if (p[1] == ']') {
4118              if (p[2] != NUL) {
4119                semsg(_(e_trailing_char_after_rsb_str_str), kw, &p[2]);
4120                goto error;
4121              }
4122              kw = p + 1;
4123              kwlen = 1;
4124              break;   // skip over the "]"
4125            }
4126            const int l = utfc_ptr2len(p + 1);
4127
4128            memmove(p, p + 1, (size_t)l);
4129            p += l;
4130          }
4131        }
4132      }
4133
4134error:
4135      xfree(keyword_copy);
4136      xfree(syn_opt_arg.cont_in_list);
4137      xfree(syn_opt_arg.next_list);
4138    }
4139  }
4140
4141  if (rest != NULL) {
4142    eap->nextcmd = check_nextcmd(rest);
4143  } else {
4144    semsg(_(e_invarg2), arg);
4145  }
4146
4147  redraw_curbuf_later(UPD_SOME_VALID);
4148  syn_stack_free_all(curwin->w_s);              // Need to recompute all syntax.
4149}
4150
4151/// Handle ":syntax match {name} [{options}] {pattern} [{options}]".
4152///
4153/// Also ":syntax sync match {name} [[grouphere | groupthere] {group-name}] .."
4154///
4155/// @param syncing  true for ":syntax sync match .. "
4156static void syn_cmd_match(exarg_T *eap, int syncing)
4157{
4158  char *arg = eap->arg;
4159  char *group_name_end;
4160  synpat_T item;                // the item found in the line
4161  int syn_id;
4162  syn_opt_arg_T syn_opt_arg;
4163  int sync_idx = 0;
4164  int conceal_char = NUL;
4165
4166  // Isolate the group name, check for validity
4167  char *rest = get_group_name(arg, &group_name_end);
4168
4169  // Get options before the pattern
4170  syn_opt_arg.flags = 0;
4171  syn_opt_arg.keyword = false;
4172  syn_opt_arg.sync_idx = syncing ? &sync_idx : NULL;
4173  syn_opt_arg.has_cont_list = true;
4174  syn_opt_arg.cont_list = NULL;
4175  syn_opt_arg.cont_in_list = NULL;
4176  syn_opt_arg.next_list = NULL;
4177  rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip);
4178
4179  // get the pattern.
4180  init_syn_patterns();
4181  CLEAR_FIELD(item);
4182  rest = get_syn_pattern(rest, &item);
4183  if (vim_regcomp_had_eol() && !(syn_opt_arg.flags & HL_EXCLUDENL)) {
4184    syn_opt_arg.flags |= HL_HAS_EOL;
4185  }
4186
4187  // Get options after the pattern
4188  rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip);
4189
4190  if (rest != NULL) {           // all arguments are valid
4191    // Check for trailing command and illegal trailing arguments.
4192    eap->nextcmd = check_nextcmd(rest);
4193    if (!ends_excmd(*rest) || eap->skip) {
4194      rest = NULL;
4195    } else {
4196      if ((syn_id = syn_check_group(arg, (size_t)(group_name_end - arg))) != 0) {
4197        syn_incl_toplevel(syn_id, &syn_opt_arg.flags);
4198        // Store the pattern in the syn_items list
4199        synpat_T *spp = GA_APPEND_VIA_PTR(synpat_T,
4200                                          &curwin->w_s->b_syn_patterns);
4201        *spp = item;
4202        spp->sp_syncing = syncing;
4203        spp->sp_type = SPTYPE_MATCH;
4204        spp->sp_syn.id = (int16_t)syn_id;
4205        spp->sp_syn.inc_tag = current_syn_inc_tag;
4206        spp->sp_flags = syn_opt_arg.flags;
4207        spp->sp_sync_idx = sync_idx;
4208        spp->sp_cont_list = syn_opt_arg.cont_list;
4209        spp->sp_syn.cont_in_list = syn_opt_arg.cont_in_list;
4210        spp->sp_cchar = conceal_char;
4211        if (syn_opt_arg.cont_in_list != NULL) {
4212          curwin->w_s->b_syn_containedin = true;
4213        }
4214        spp->sp_next_list = syn_opt_arg.next_list;
4215
4216        // remember that we found a match for syncing on
4217        if (syn_opt_arg.flags & (HL_SYNC_HERE|HL_SYNC_THERE)) {
4218          curwin->w_s->b_syn_sync_flags |= SF_MATCH;
4219        }
4220        if (syn_opt_arg.flags & HL_FOLD) {
4221          curwin->w_s->b_syn_folditems++;
4222        }
4223
4224        redraw_curbuf_later(UPD_SOME_VALID);
4225        syn_stack_free_all(curwin->w_s);          // Need to recompute all syntax.
4226        return;           // don't free the progs and patterns now
4227      }
4228    }
4229  }
4230
4231  // Something failed, free the allocated memory.
4232  vim_regfree(item.sp_prog);
4233  xfree(item.sp_pattern);
4234  xfree(syn_opt_arg.cont_list);
4235  xfree(syn_opt_arg.cont_in_list);
4236  xfree(syn_opt_arg.next_list);
4237
4238  if (rest == NULL) {
4239    semsg(_(e_invarg2), arg);
4240  }
4241}
4242
4243/// Handle ":syntax region {group-name} [matchgroup={group-name}]
4244///              start {start} .. [skip {skip}] end {end} .. [{options}]".
4245///
4246/// @param syncing  true for ":syntax sync region .."
4247static void syn_cmd_region(exarg_T *eap, int syncing)
4248{
4249  char *arg = eap->arg;
4250  char *group_name_end;
4251  char *rest;                    // next arg, NULL on error
4252  char *key_end;
4253  char *key = NULL;
4254  int item;
4255#define ITEM_START          0
4256#define ITEM_SKIP           1
4257#define ITEM_END            2
4258#define ITEM_MATCHGROUP     3
4259  struct pat_ptr {
4260    synpat_T *pp_synp;                   // pointer to syn_pattern
4261    int pp_matchgroup_id;                       // matchgroup ID
4262    struct pat_ptr *pp_next;                   // pointer to next pat_ptr
4263  }                   *(pat_ptrs[3]);
4264  // patterns found in the line
4265  struct pat_ptr *ppp;
4266  struct pat_ptr *ppp_next;
4267  int pat_count = 0;                            // nr of syn_patterns found
4268  int syn_id;
4269  int matchgroup_id = 0;
4270  bool not_enough = false;                      // not enough arguments
4271  bool illegal = false;                         // illegal arguments
4272  bool success = false;
4273  syn_opt_arg_T syn_opt_arg;
4274  int conceal_char = NUL;
4275
4276  // Isolate the group name, check for validity
4277  rest = get_group_name(arg, &group_name_end);
4278
4279  pat_ptrs[0] = NULL;
4280  pat_ptrs[1] = NULL;
4281  pat_ptrs[2] = NULL;
4282
4283  init_syn_patterns();
4284
4285  syn_opt_arg.flags = 0;
4286  syn_opt_arg.keyword = false;
4287  syn_opt_arg.sync_idx = NULL;
4288  syn_opt_arg.has_cont_list = true;
4289  syn_opt_arg.cont_list = NULL;
4290  syn_opt_arg.cont_in_list = NULL;
4291  syn_opt_arg.next_list = NULL;
4292
4293  // get the options, patterns and matchgroup.
4294  while (rest != NULL && !ends_excmd(*rest)) {
4295    // Check for option arguments
4296    rest = get_syn_options(rest, &syn_opt_arg, &conceal_char, eap->skip);
4297    if (rest == NULL || ends_excmd(*rest)) {
4298      break;
4299    }
4300
4301    // must be a pattern or matchgroup then
4302    key_end = rest;
4303    while (*key_end && !ascii_iswhite(*key_end) && *key_end != '=') {
4304      key_end++;
4305    }
4306    xfree(key);
4307    key = vim_strnsave_up(rest, (size_t)(key_end - rest));
4308    if (strcmp(key, "MATCHGROUP") == 0) {
4309      item = ITEM_MATCHGROUP;
4310    } else if (strcmp(key, "START") == 0) {
4311      item = ITEM_START;
4312    } else if (strcmp(key, "END") == 0) {
4313      item = ITEM_END;
4314    } else if (strcmp(key, "SKIP") == 0) {
4315      if (pat_ptrs[ITEM_SKIP] != NULL) {  // One skip pattern allowed.
4316        illegal = true;
4317        break;
4318      }
4319      item = ITEM_SKIP;
4320    } else {
4321      break;
4322    }
4323    rest = skipwhite(key_end);
4324    if (*rest != '=') {
4325      rest = NULL;
4326      semsg(_("E398: Missing '=': %s"), arg);
4327      break;
4328    }
4329    rest = skipwhite(rest + 1);
4330    if (*rest == NUL) {
4331      not_enough = true;
4332      break;
4333    }
4334
4335    if (item == ITEM_MATCHGROUP) {
4336      char *p = skiptowhite(rest);
4337      if ((p - rest == 4 && strncmp(rest, "NONE", 4) == 0) || eap->skip) {
4338        matchgroup_id = 0;
4339      } else {
4340        matchgroup_id = syn_check_group(rest, (size_t)(p - rest));
4341        if (matchgroup_id == 0) {
4342          illegal = true;
4343          break;
4344        }
4345      }
4346      rest = skipwhite(p);
4347    } else {
4348      // Allocate room for a syn_pattern, and link it in the list of
4349      // syn_patterns for this item, at the start (because the list is
4350      // used from end to start).
4351      ppp = xmalloc(sizeof(struct pat_ptr));
4352      ppp->pp_next = pat_ptrs[item];
4353      pat_ptrs[item] = ppp;
4354      ppp->pp_synp = xcalloc(1, sizeof(synpat_T));
4355
4356      // Get the syntax pattern and the following offset(s).
4357
4358      // Enable the appropriate \z specials.
4359      if (item == ITEM_START) {
4360        reg_do_extmatch = REX_SET;
4361      } else {
4362        assert(item == ITEM_SKIP || item == ITEM_END);
4363        reg_do_extmatch = REX_USE;
4364      }
4365      rest = get_syn_pattern(rest, ppp->pp_synp);
4366      reg_do_extmatch = 0;
4367      if (item == ITEM_END && vim_regcomp_had_eol()
4368          && !(syn_opt_arg.flags & HL_EXCLUDENL)) {
4369        ppp->pp_synp->sp_flags |= HL_HAS_EOL;
4370      }
4371      ppp->pp_matchgroup_id = matchgroup_id;
4372      pat_count++;
4373    }
4374  }
4375  xfree(key);
4376  if (illegal || not_enough) {
4377    rest = NULL;
4378  }
4379
4380  // Must have a "start" and "end" pattern.
4381  if (rest != NULL && (pat_ptrs[ITEM_START] == NULL
4382                       || pat_ptrs[ITEM_END] == NULL)) {
4383    not_enough = true;
4384    rest = NULL;
4385  }
4386
4387  if (rest != NULL) {
4388    // Check for trailing garbage or command.
4389    // If OK, add the item.
4390    eap->nextcmd = check_nextcmd(rest);
4391    if (!ends_excmd(*rest) || eap->skip) {
4392      rest = NULL;
4393    } else {
4394      ga_grow(&(curwin->w_s->b_syn_patterns), pat_count);
4395      if ((syn_id = syn_check_group(arg, (size_t)(group_name_end - arg))) != 0) {
4396        syn_incl_toplevel(syn_id, &syn_opt_arg.flags);
4397        // Store the start/skip/end in the syn_items list
4398        int idx = curwin->w_s->b_syn_patterns.ga_len;
4399        for (item = ITEM_START; item <= ITEM_END; item++) {
4400          for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp->pp_next) {
4401            SYN_ITEMS(curwin->w_s)[idx] = *(ppp->pp_synp);
4402            SYN_ITEMS(curwin->w_s)[idx].sp_syncing = syncing;
4403            SYN_ITEMS(curwin->w_s)[idx].sp_type =
4404              (item == ITEM_START) ? SPTYPE_START
4405                                   : (item == ITEM_SKIP) ? SPTYPE_SKIP : SPTYPE_END;
4406            SYN_ITEMS(curwin->w_s)[idx].sp_flags |= syn_opt_arg.flags;
4407            SYN_ITEMS(curwin->w_s)[idx].sp_syn.id = (int16_t)syn_id;
4408            SYN_ITEMS(curwin->w_s)[idx].sp_syn.inc_tag =
4409              current_syn_inc_tag;
4410            SYN_ITEMS(curwin->w_s)[idx].sp_syn_match_id = (int16_t)ppp->pp_matchgroup_id;
4411            SYN_ITEMS(curwin->w_s)[idx].sp_cchar = conceal_char;
4412            if (item == ITEM_START) {
4413              SYN_ITEMS(curwin->w_s)[idx].sp_cont_list =
4414                syn_opt_arg.cont_list;
4415              SYN_ITEMS(curwin->w_s)[idx].sp_syn.cont_in_list =
4416                syn_opt_arg.cont_in_list;
4417              if (syn_opt_arg.cont_in_list != NULL) {
4418                curwin->w_s->b_syn_containedin = true;
4419              }
4420              SYN_ITEMS(curwin->w_s)[idx].sp_next_list =
4421                syn_opt_arg.next_list;
4422            }
4423            curwin->w_s->b_syn_patterns.ga_len++;
4424            idx++;
4425            if (syn_opt_arg.flags & HL_FOLD) {
4426              curwin->w_s->b_syn_folditems++;
4427            }
4428          }
4429        }
4430
4431        redraw_curbuf_later(UPD_SOME_VALID);
4432        syn_stack_free_all(curwin->w_s);  // Need to recompute all syntax.
4433        success = true;                   // don't free the progs and patterns now
4434      }
4435    }
4436  }
4437
4438  // Free the allocated memory.
4439  for (item = ITEM_START; item <= ITEM_END; item++) {
4440    for (ppp = pat_ptrs[item]; ppp != NULL; ppp = ppp_next) {
4441      if (!success && ppp->pp_synp != NULL) {
4442        vim_regfree(ppp->pp_synp->sp_prog);
4443        xfree(ppp->pp_synp->sp_pattern);
4444      }
4445      xfree(ppp->pp_synp);
4446      ppp_next = ppp->pp_next;
4447      xfree(ppp);
4448    }
4449  }
4450
4451  if (!success) {
4452    xfree(syn_opt_arg.cont_list);
4453    xfree(syn_opt_arg.cont_in_list);
4454    xfree(syn_opt_arg.next_list);
4455    if (not_enough) {
4456      semsg(_("E399: Not enough arguments: syntax region %s"), arg);
4457    } else if (illegal || rest == NULL) {
4458      semsg(_(e_invarg2), arg);
4459    }
4460  }
4461}
4462
4463// A simple syntax group ID comparison function suitable for use in qsort()
4464static int syn_compare_stub(const void *const v1, const void *const v2)
4465{
4466  const int16_t *const s1 = v1;
4467  const int16_t *const s2 = v2;
4468
4469  return *s1 > *s2 ? 1 : *s1 < *s2 ? -1 : 0;
4470}
4471
4472// Combines lists of syntax clusters.
4473// *clstr1 and *clstr2 must both be allocated memory; they will be consumed.
4474static void syn_combine_list(int16_t **const clstr1, int16_t **const clstr2, const int list_op)
4475{
4476  size_t count1 = 0;
4477  size_t count2 = 0;
4478  const int16_t *g1;
4479  const int16_t *g2;
4480  int16_t *clstr = NULL;
4481
4482  // Handle degenerate cases.
4483  if (*clstr2 == NULL) {
4484    return;
4485  }
4486  if (*clstr1 == NULL || list_op == CLUSTER_REPLACE) {
4487    if (list_op == CLUSTER_REPLACE) {
4488      xfree(*clstr1);
4489    }
4490    if (list_op == CLUSTER_REPLACE || list_op == CLUSTER_ADD) {
4491      *clstr1 = *clstr2;
4492    } else {
4493      xfree(*clstr2);
4494    }
4495    return;
4496  }
4497
4498  for (g1 = *clstr1; *g1; g1++) {
4499    count1++;
4500  }
4501  for (g2 = *clstr2; *g2; g2++) {
4502    count2++;
4503  }
4504
4505  // For speed purposes, sort both lists.
4506  qsort(*clstr1, count1, sizeof(**clstr1), syn_compare_stub);
4507  qsort(*clstr2, count2, sizeof(**clstr2), syn_compare_stub);
4508
4509  // We proceed in two passes; in round 1, we count the elements to place
4510  // in the new list, and in round 2, we allocate and populate the new
4511  // list.  For speed, we use a mergesort-like method, adding the smaller
4512  // of the current elements in each list to the new list.
4513  for (int round = 1; round <= 2; round++) {
4514    g1 = *clstr1;
4515    g2 = *clstr2;
4516    int count = 0;
4517
4518    // First, loop through the lists until one of them is empty.
4519    while (*g1 && *g2) {
4520      // We always want to add from the first list.
4521      if (*g1 < *g2) {
4522        if (round == 2) {
4523          clstr[count] = *g1;
4524        }
4525        count++;
4526        g1++;
4527        continue;
4528      }
4529      // We only want to add from the second list if we're adding the
4530      // lists.
4531      if (list_op == CLUSTER_ADD) {
4532        if (round == 2) {
4533          clstr[count] = *g2;
4534        }
4535        count++;
4536      }
4537      if (*g1 == *g2) {
4538        g1++;
4539      }
4540      g2++;
4541    }
4542
4543    // Now add the leftovers from whichever list didn't get finished
4544    // first.  As before, we only want to add from the second list if
4545    // we're adding the lists.
4546    for (; *g1; g1++, count++) {
4547      if (round == 2) {
4548        clstr[count] = *g1;
4549      }
4550    }
4551    if (list_op == CLUSTER_ADD) {
4552      for (; *g2; g2++, count++) {
4553        if (round == 2) {
4554          clstr[count] = *g2;
4555        }
4556      }
4557    }
4558
4559    if (round == 1) {
4560      // If the group ended up empty, we don't need to allocate any
4561      // space for it.
4562      if (count == 0) {
4563        clstr = NULL;
4564        break;
4565      }
4566      clstr = xmalloc(((size_t)count + 1) * sizeof(*clstr));
4567      clstr[count] = 0;
4568    }
4569  }
4570
4571  // Finally, put the new list in place.
4572  xfree(*clstr1);
4573  xfree(*clstr2);
4574  *clstr1 = clstr;
4575}
4576
4577/// Lookup a syntax cluster name and return its ID.
4578/// If it is not found, 0 is returned.
4579static int syn_scl_name2id(char *name)
4580{
4581  // Avoid using stricmp() too much, it's slow on some systems
4582  char *name_u = vim_strsave_up(name);
4583  int i;
4584  for (i = curwin->w_s->b_syn_clusters.ga_len; --i >= 0;) {
4585    if (SYN_CLSTR(curwin->w_s)[i].scl_name_u != NULL
4586        && strcmp(name_u, SYN_CLSTR(curwin->w_s)[i].scl_name_u) == 0) {
4587      break;
4588    }
4589  }
4590  xfree(name_u);
4591  return i < 0 ? 0 : i + SYNID_CLUSTER;
4592}
4593
4594/// Like syn_scl_name2id(), but take a pointer + length argument.
4595static int syn_scl_namen2id(char *linep, int len)
4596{
4597  char *name = xstrnsave(linep, (size_t)len);
4598  int id = syn_scl_name2id(name);
4599  xfree(name);
4600
4601  return id;
4602}
4603
4604/// Find syntax cluster name in the table and return its ID.
4605/// The argument is a pointer to the name and the length of the name.
4606/// If it doesn't exist yet, a new entry is created.
4607///
4608/// @return  0 for failure.
4609static int syn_check_cluster(char *pp, int len)
4610{
4611  char *name = xstrnsave(pp, (size_t)len);
4612  int id = syn_scl_name2id(name);
4613  if (id == 0) {                        // doesn't exist yet
4614    id = syn_add_cluster(name);
4615  } else {
4616    xfree(name);
4617  }
4618  return id;
4619}
4620
4621/// Add new syntax cluster and return its ID.
4622/// "name" must be an allocated string, it will be consumed.
4623///
4624/// @return  0 for failure.
4625static int syn_add_cluster(char *name)
4626{
4627  // First call for this growarray: init growing array.
4628  if (curwin->w_s->b_syn_clusters.ga_data == NULL) {
4629    curwin->w_s->b_syn_clusters.ga_itemsize = sizeof(syn_cluster_T);
4630    ga_set_growsize(&curwin->w_s->b_syn_clusters, 10);
4631  }
4632
4633  int len = curwin->w_s->b_syn_clusters.ga_len;
4634  if (len >= MAX_CLUSTER_ID) {
4635    emsg(_("E848: Too many syntax clusters"));
4636    xfree(name);
4637    return 0;
4638  }
4639
4640  syn_cluster_T *scp = GA_APPEND_VIA_PTR(syn_cluster_T,
4641                                         &curwin->w_s->b_syn_clusters);
4642  CLEAR_POINTER(scp);
4643  scp->scl_name = name;
4644  scp->scl_name_u = vim_strsave_up(name);
4645  scp->scl_list = NULL;
4646
4647  if (STRICMP(name, "Spell") == 0) {
4648    curwin->w_s->b_spell_cluster_id = len + SYNID_CLUSTER;
4649  }
4650  if (STRICMP(name, "NoSpell") == 0) {
4651    curwin->w_s->b_nospell_cluster_id = len + SYNID_CLUSTER;
4652  }
4653
4654  return len + SYNID_CLUSTER;
4655}
4656
4657// Handle ":syntax cluster {cluster-name} [contains={groupname},..]
4658//              [add={groupname},..] [remove={groupname},..]".
4659static void syn_cmd_cluster(exarg_T *eap, int syncing)
4660{
4661  char *arg = eap->arg;
4662  char *group_name_end;
4663  bool got_clstr = false;
4664  int opt_len;
4665  int list_op;
4666
4667  eap->nextcmd = find_nextcmd(arg);
4668  if (eap->skip) {
4669    return;
4670  }
4671
4672  char *rest = get_group_name(arg, &group_name_end);
4673
4674  if (rest != NULL) {
4675    int scl_id = syn_check_cluster(arg, (int)(group_name_end - arg));
4676    if (scl_id == 0) {
4677      return;
4678    }
4679    scl_id -= SYNID_CLUSTER;
4680
4681    while (true) {
4682      if (STRNICMP(rest, "add", 3) == 0
4683          && (ascii_iswhite(rest[3]) || rest[3] == '=')) {
4684        opt_len = 3;
4685        list_op = CLUSTER_ADD;
4686      } else if (STRNICMP(rest, "remove", 6) == 0
4687                 && (ascii_iswhite(rest[6]) || rest[6] == '=')) {
4688        opt_len = 6;
4689        list_op = CLUSTER_SUBTRACT;
4690      } else if (STRNICMP(rest, "contains", 8) == 0
4691                 && (ascii_iswhite(rest[8]) || rest[8] == '=')) {
4692        opt_len = 8;
4693        list_op = CLUSTER_REPLACE;
4694      } else {
4695        break;
4696      }
4697
4698      int16_t *clstr_list = NULL;
4699      if (get_id_list(&rest, opt_len, &clstr_list, eap->skip) == FAIL) {
4700        semsg(_(e_invarg2), rest);
4701        break;
4702      }
4703      if (scl_id >= 0) {
4704        syn_combine_list(&SYN_CLSTR(curwin->w_s)[scl_id].scl_list,
4705                         &clstr_list, list_op);
4706      } else {
4707        xfree(clstr_list);
4708      }
4709      got_clstr = true;
4710    }
4711
4712    if (got_clstr) {
4713      redraw_curbuf_later(UPD_SOME_VALID);
4714      syn_stack_free_all(curwin->w_s);          // Need to recompute all.
4715    }
4716  }
4717
4718  if (!got_clstr) {
4719    emsg(_("E400: No cluster specified"));
4720  }
4721  if (rest == NULL || !ends_excmd(*rest)) {
4722    semsg(_(e_invarg2), arg);
4723  }
4724}
4725
4726// On first call for current buffer: Init growing array.
4727static void init_syn_patterns(void)
4728{
4729  curwin->w_s->b_syn_patterns.ga_itemsize = sizeof(synpat_T);
4730  ga_set_growsize(&curwin->w_s->b_syn_patterns, 10);
4731}
4732
4733/// Get one pattern for a ":syntax match" or ":syntax region" command.
4734/// Stores the pattern and program in a synpat_T.
4735///
4736/// @return  a pointer to the next argument, or NULL in case of an error.
4737static char *get_syn_pattern(char *arg, synpat_T *ci)
4738{
4739  int idx;
4740
4741  // need at least three chars
4742  if (arg == NULL || arg[0] == NUL || arg[1] == NUL || arg[2] == NUL) {
4743    return NULL;
4744  }
4745
4746  char *end = skip_regexp(arg + 1, *arg, true);
4747  if (*end != *arg) {                       // end delimiter not found
4748    semsg(_("E401: Pattern delimiter not found: %s"), arg);
4749    return NULL;
4750  }
4751  // store the pattern and compiled regexp program
4752  ci->sp_pattern = xstrnsave(arg + 1, (size_t)(end - arg) - 1);
4753
4754  // Make 'cpoptions' empty, to avoid the 'l' flag
4755  char *cpo_save = p_cpo;
4756  p_cpo = empty_string_option;
4757  ci->sp_prog = vim_regcomp(ci->sp_pattern, RE_MAGIC);
4758  p_cpo = cpo_save;
4759
4760  if (ci->sp_prog == NULL) {
4761    return NULL;
4762  }
4763  ci->sp_ic = curwin->w_s->b_syn_ic;
4764  syn_clear_time(&ci->sp_time);
4765
4766  // Check for a match, highlight or region offset.
4767  end++;
4768  do {
4769    for (idx = SPO_COUNT; --idx >= 0;) {
4770      if (strncmp(end, spo_name_tab[idx], 3) == 0) {
4771        break;
4772      }
4773    }
4774    if (idx >= 0) {
4775      int *p = &(ci->sp_offsets[idx]);
4776      if (idx != SPO_LC_OFF) {
4777        switch (end[3]) {
4778        case 's':
4779          break;
4780        case 'b':
4781          break;
4782        case 'e':
4783          idx += SPO_COUNT; break;
4784        default:
4785          idx = -1; break;
4786        }
4787      }
4788      if (idx >= 0) {
4789        ci->sp_off_flags |= (int16_t)(1 << idx);
4790        if (idx == SPO_LC_OFF) {            // lc=99
4791          end += 3;
4792          *p = getdigits_int(&end, true, 0);
4793
4794          // "lc=" offset automatically sets "ms=" offset
4795          if (!(ci->sp_off_flags & (1 << SPO_MS_OFF))) {
4796            ci->sp_off_flags |= (1 << SPO_MS_OFF);
4797            ci->sp_offsets[SPO_MS_OFF] = *p;
4798          }
4799        } else {                          // yy=x+99
4800          end += 4;
4801          if (*end == '+') {
4802            end++;
4803            *p = getdigits_int(&end, true, 0);    // positive offset
4804          } else if (*end == '-') {
4805            end++;
4806            *p = -getdigits_int(&end, true, 0);   // negative offset
4807          }
4808        }
4809        if (*end != ',') {
4810          break;
4811        }
4812        end++;
4813      }
4814    }
4815  } while (idx >= 0);
4816
4817  if (!ends_excmd(*end) && !ascii_iswhite(*end)) {
4818    semsg(_("E402: Garbage after pattern: %s"), arg);
4819    return NULL;
4820  }
4821  return skipwhite(end);
4822}
4823
4824/// Handle ":syntax sync .." command.
4825static void syn_cmd_sync(exarg_T *eap, int syncing)
4826{
4827  char *arg_start = eap->arg;
4828  char *key = NULL;
4829  bool illegal = false;
4830  bool finished = false;
4831
4832  if (ends_excmd(*arg_start)) {
4833    syn_cmd_list(eap, true);
4834    return;
4835  }
4836
4837  while (!ends_excmd(*arg_start)) {
4838    char *arg_end = skiptowhite(arg_start);
4839    char *next_arg = skipwhite(arg_end);
4840    xfree(key);
4841    key = vim_strnsave_up(arg_start, (size_t)(arg_end - arg_start));
4842    if (strcmp(key, "CCOMMENT") == 0) {
4843      if (!eap->skip) {
4844        curwin->w_s->b_syn_sync_flags |= SF_CCOMMENT;
4845      }
4846      if (!ends_excmd(*next_arg)) {
4847        arg_end = skiptowhite(next_arg);
4848        if (!eap->skip) {
4849          curwin->w_s->b_syn_sync_id =
4850            (int16_t)syn_check_group(next_arg, (size_t)(arg_end - next_arg));
4851        }
4852        next_arg = skipwhite(arg_end);
4853      } else if (!eap->skip) {
4854        curwin->w_s->b_syn_sync_id = (int16_t)syn_name2id("Comment");
4855      }
4856    } else if (strncmp(key, "LINES", 5) == 0
4857               || strncmp(key, "MINLINES", 8) == 0
4858               || strncmp(key, "MAXLINES", 8) == 0
4859               || strncmp(key, "LINEBREAKS", 10) == 0) {
4860      if (key[4] == 'S') {
4861        arg_end = key + 6;
4862      } else if (key[0] == 'L') {
4863        arg_end = key + 11;
4864      } else {
4865        arg_end = key + 9;
4866      }
4867      if (arg_end[-1] != '=' || !ascii_isdigit(*arg_end)) {
4868        illegal = true;
4869        break;
4870      }
4871      linenr_T n = getdigits_int32(&arg_end, false, 0);
4872      if (!eap->skip) {
4873        if (key[4] == 'B') {
4874          curwin->w_s->b_syn_sync_linebreaks = n;
4875        } else if (key[1] == 'A') {
4876          curwin->w_s->b_syn_sync_maxlines = n;
4877        } else {
4878          curwin->w_s->b_syn_sync_minlines = n;
4879        }
4880      }
4881    } else if (strcmp(key, "FROMSTART") == 0) {
4882      if (!eap->skip) {
4883        curwin->w_s->b_syn_sync_minlines = MAXLNUM;
4884        curwin->w_s->b_syn_sync_maxlines = 0;
4885      }
4886    } else if (strcmp(key, "LINECONT") == 0) {
4887      if (*next_arg == NUL) {  // missing pattern
4888        illegal = true;
4889        break;
4890      }
4891      if (curwin->w_s->b_syn_linecont_pat != NULL) {
4892        emsg(_("E403: syntax sync: line continuations pattern specified twice"));
4893        finished = true;
4894        break;
4895      }
4896      arg_end = skip_regexp(next_arg + 1, *next_arg, true);
4897      if (*arg_end != *next_arg) {          // end delimiter not found
4898        illegal = true;
4899        break;
4900      }
4901
4902      if (!eap->skip) {
4903        // store the pattern and compiled regexp program
4904        curwin->w_s->b_syn_linecont_pat =
4905          xstrnsave(next_arg + 1, (size_t)(arg_end - next_arg) - 1);
4906        curwin->w_s->b_syn_linecont_ic = curwin->w_s->b_syn_ic;
4907
4908        // Make 'cpoptions' empty, to avoid the 'l' flag
4909        char *cpo_save = p_cpo;
4910        p_cpo = empty_string_option;
4911        curwin->w_s->b_syn_linecont_prog =
4912          vim_regcomp(curwin->w_s->b_syn_linecont_pat, RE_MAGIC);
4913        p_cpo = cpo_save;
4914        syn_clear_time(&curwin->w_s->b_syn_linecont_time);
4915
4916        if (curwin->w_s->b_syn_linecont_prog == NULL) {
4917          XFREE_CLEAR(curwin->w_s->b_syn_linecont_pat);
4918          finished = true;
4919          break;
4920        }
4921      }
4922      next_arg = skipwhite(arg_end + 1);
4923    } else {
4924      eap->arg = next_arg;
4925      if (strcmp(key, "MATCH") == 0) {
4926        syn_cmd_match(eap, true);
4927      } else if (strcmp(key, "REGION") == 0) {
4928        syn_cmd_region(eap, true);
4929      } else if (strcmp(key, "CLEAR") == 0) {
4930        syn_cmd_clear(eap, true);
4931      } else {
4932        illegal = true;
4933      }
4934      finished = true;
4935      break;
4936    }
4937    arg_start = next_arg;
4938  }
4939  xfree(key);
4940  if (illegal) {
4941    semsg(_("E404: Illegal arguments: %s"), arg_start);
4942  } else if (!finished) {
4943    eap->nextcmd = check_nextcmd(arg_start);
4944    redraw_curbuf_later(UPD_SOME_VALID);
4945    syn_stack_free_all(curwin->w_s);            // Need to recompute all syntax.
4946  }
4947}
4948
4949/// Convert a line of highlight group names into a list of group ID numbers.
4950/// "arg" should point to the "contains" or "nextgroup" keyword.
4951/// "arg" is advanced to after the last group name.
4952/// Careful: the argument is modified (NULs added).
4953///
4954/// @param keylen  length of keyword
4955/// @param list    where to store the resulting list, if not NULL, the list is silently skipped!
4956///
4957/// @return        FAIL for some error, OK for success.
4958static int get_id_list(char **const arg, const int keylen, int16_t **const list, const bool skip)
4959{
4960  char *p = NULL;
4961  char *end;
4962  int total_count = 0;
4963  int16_t *retval = NULL;
4964  regmatch_T regmatch;
4965  int id;
4966  bool failed = false;
4967
4968  // We parse the list twice:
4969  // round == 1: count the number of items, allocate the array.
4970  // round == 2: fill the array with the items.
4971  // In round 1 new groups may be added, causing the number of items to
4972  // grow when a regexp is used.  In that case round 1 is done once again.
4973  for (int round = 1; round <= 2; round++) {
4974    // skip "contains"
4975    p = skipwhite(*arg + keylen);
4976    if (*p != '=') {
4977      semsg(_("E405: Missing equal sign: %s"), *arg);
4978      break;
4979    }
4980    p = skipwhite(p + 1);
4981    if (ends_excmd(*p)) {
4982      semsg(_("E406: Empty argument: %s"), *arg);
4983      break;
4984    }
4985
4986    // parse the arguments after "contains"
4987    int count = 0;
4988    do {
4989      for (end = p; *end && !ascii_iswhite(*end) && *end != ','; end++) {}
4990      char *const name = xmalloc((size_t)(end - p) + 3);   // leave room for "^$"
4991      xmemcpyz(name + 1, p, (size_t)(end - p));
4992      if (strcmp(name + 1, "ALLBUT") == 0
4993          || strcmp(name + 1, "ALL") == 0
4994          || strcmp(name + 1, "TOP") == 0
4995          || strcmp(name + 1, "CONTAINED") == 0) {
4996        if (TOUPPER_ASC(**arg) != 'C') {
4997          semsg(_("E407: %s not allowed here"), name + 1);
4998          failed = true;
4999          xfree(name);
5000          break;
5001        }
5002        if (count != 0) {
5003          semsg(_("E408: %s must be first in contains list"),
5004                name + 1);
5005          failed = true;
5006          xfree(name);
5007          break;
5008        }
5009        if (name[1] == 'A') {
5010          id = SYNID_ALLBUT;
5011        } else if (name[1] == 'T') {
5012          id = SYNID_TOP;
5013        } else {
5014          id = SYNID_CONTAINED;
5015        }
5016        id += current_syn_inc_tag;
5017      } else if (name[1] == '@') {
5018        if (skip) {
5019          id = -1;
5020        } else {
5021          id = syn_check_cluster(name + 2, (int)(end - p - 1));
5022        }
5023      } else {
5024        // Handle full group name.
5025        if (strpbrk(name + 1, "\\.*^$~[") == NULL) {
5026          id = syn_check_group((name + 1), (size_t)(end - p));
5027        } else {
5028          // Handle match of regexp with group names.
5029          *name = '^';
5030          strcat(name, "$");
5031          regmatch.regprog = vim_regcomp(name, RE_MAGIC);
5032          if (regmatch.regprog == NULL) {
5033            failed = true;
5034            xfree(name);
5035            break;
5036          }
5037
5038          regmatch.rm_ic = true;
5039          id = 0;
5040          for (int i = highlight_num_groups(); --i >= 0;) {
5041            if (vim_regexec(&regmatch, highlight_group_name(i), 0)) {
5042              if (round == 2) {
5043                // Got more items than expected; can happen
5044                // when adding items that match:
5045                // "contains=a.*b,axb".
5046                // Go back to first round.
5047                if (count >= total_count) {
5048                  xfree(retval);
5049                  round = 1;
5050                } else {
5051                  retval[count] = (int16_t)(i + 1);
5052                }
5053              }
5054              count++;
5055              id = -1;  // Remember that we found one.
5056            }
5057          }
5058          vim_regfree(regmatch.regprog);
5059        }
5060      }
5061      xfree(name);
5062      if (id == 0) {
5063        semsg(_("E409: Unknown group name: %s"), p);
5064        failed = true;
5065        break;
5066      }
5067      if (id > 0) {
5068        if (round == 2) {
5069          // Got more items than expected, go back to first round.
5070          if (count >= total_count) {
5071            xfree(retval);
5072            round = 1;
5073          } else {
5074            retval[count] = (int16_t)id;
5075          }
5076        }
5077        count++;
5078      }
5079      p = skipwhite(end);
5080      if (*p != ',') {
5081        break;
5082      }
5083      p = skipwhite(p + 1);             // skip comma in between arguments
5084    } while (!ends_excmd(*p));
5085    if (failed) {
5086      break;
5087    }
5088    if (round == 1) {
5089      retval = xmalloc(((size_t)count + 1) * sizeof(*retval));
5090      retval[count] = 0;            // zero means end of the list
5091      total_count = count;
5092    }
5093  }
5094
5095  *arg = p;
5096  if (failed || retval == NULL) {
5097    xfree(retval);
5098    return FAIL;
5099  }
5100
5101  if (*list == NULL) {
5102    *list = retval;
5103  } else {
5104    xfree(retval);           // list already found, don't overwrite it
5105  }
5106  return OK;
5107}
5108
5109// Make a copy of an ID list.
5110static int16_t *copy_id_list(const int16_t *const list)
5111{
5112  if (list == NULL) {
5113    return NULL;
5114  }
5115
5116  int count;
5117  for (count = 0; list[count]; count++) {}
5118  const size_t len = ((size_t)count + 1) * sizeof(int16_t);
5119  int16_t *const retval = xmalloc(len);
5120  memmove(retval, list, len);
5121
5122  return retval;
5123}
5124
5125/// Cache for in_id_list() {{{
5126///
5127/// A "contains"/cluster list is otherwise scanned with recursive cluster
5128/// expansion on every check.  Each distinct list is resolved once into a
5129/// cluster-expanded, sorted set of group IDs so membership becomes a binary
5130/// search.  The cache lives in the synblock and is cleared by
5131/// syn_stack_free_block() when syntax definitions change (which also covers
5132/// list pointer reuse).
5133#define IDL_CACHE_SIZE 16
5134
5135typedef struct {
5136  idl_entry_T ent[IDL_CACHE_SIZE];
5137  int round;  ///< round-robin replacement index
5138  int last;   ///< index of the last returned entry (fast path)
5139} idl_cache_T;
5140
5141/// Collect the explicit group IDs of "list" into "ga", expanding clusters.
5142/// "seen" records visited clusters to break cycles and avoid duplicate work.
5143/// Return false when the list cannot be represented as a plain set (a nested
5144/// ALLBUT/TOP/CONTAINED marker) or on out of memory.
5145static bool idl_collect(int16_t *list, garray_T *ga, garray_T *seen)
5146{
5147  if (list == NULL || list == ID_LIST_ALL) {
5148    return false;
5149  }
5150  for (int16_t item = *list; item != 0; item = *++list) {
5151    if (item >= SYNID_ALLBUT && item < SYNID_CLUSTER) {
5152      return false;  // nested ALLBUT/TOP/CONTAINED: not cacheable
5153    }
5154    if (item >= SYNID_CLUSTER) {
5155      bool seen_it = false;
5156
5157      for (int i = 0; i < seen->ga_len; i++) {
5158        if (((int16_t *)seen->ga_data)[i] == item) {
5159          seen_it = true;
5160          break;
5161        }
5162      }
5163      if (seen_it) {
5164        continue;
5165      }
5166      GA_APPEND(int16_t, seen, item);
5167      // Record the cluster id itself, not just its members: the slow
5168      // path matches "item == id" for a cluster id present in the list.
5169      GA_APPEND(int16_t, ga, item);
5170      int16_t *scl_list = SYN_CLSTR(syn_block)[item - SYNID_CLUSTER].scl_list;
5171      if (scl_list != NULL && !idl_collect(scl_list, ga, seen)) {
5172        return false;
5173      }
5174    } else {
5175      GA_APPEND(int16_t, ga, item);
5176    }
5177  }
5178  return true;
5179}
5180
5181static int idl_id_cmp(const void *a, const void *b)
5182{
5183  return (int)(*(const int16_t *)a) - (int)(*(const int16_t *)b);
5184}
5185
5186/// Get the cache entry that resolves "list", building it if needed.
5187/// Returns NULL only on allocation failure.
5188static idl_entry_T *idl_get_entry(int16_t *list)
5189{
5190  idl_cache_T *cache = (idl_cache_T *)syn_block->b_idlist_cache;
5191
5192  if (cache == NULL) {
5193    cache = xcalloc(1, sizeof(idl_cache_T));
5194    syn_block->b_idlist_cache = cache;
5195  }
5196  // Fast path: the same list is usually queried many times in a row.
5197  if (cache->ent[cache->last].idl_key == list) {
5198    return &cache->ent[cache->last];
5199  }
5200  for (int i = 0; i < IDL_CACHE_SIZE; i++) {
5201    if (cache->ent[i].idl_key == list) {
5202      cache->last = i;
5203      return &cache->ent[i];
5204    }
5205  }
5206
5207  // Build a new entry, replacing one in round-robin order.
5208  cache->last = cache->round;
5209  idl_entry_T *e = &cache->ent[cache->round];
5210  cache->round = (cache->round + 1) % IDL_CACHE_SIZE;
5211  XFREE_CLEAR(e->idl_ids);
5212  e->idl_count = 0;
5213  e->idl_key = list;
5214  e->idl_marker = 0;
5215  e->idl_usable = true;
5216
5217  // A leading ALLBUT/TOP/CONTAINED marker is kept aside; the rest is the set.
5218  if (*list >= SYNID_ALLBUT && *list < SYNID_CLUSTER) {
5219    e->idl_marker = *list;
5220    list++;
5221  }
5222
5223  garray_T ga, seen;
5224  ga_init(&ga, sizeof(int16_t), 50);
5225  ga_init(&seen, sizeof(int16_t), 10);
5226  if (!idl_collect(list, &ga, &seen)) {
5227    e->idl_usable = false;
5228    ga_clear(&ga);
5229    ga_clear(&seen);
5230    return e;
5231  }
5232  ga_clear(&seen);
5233  if (ga.ga_len > 0) {
5234    qsort(ga.ga_data, (size_t)ga.ga_len, sizeof(int16_t), idl_id_cmp);
5235    e->idl_ids = (int16_t *)ga.ga_data;  // take ownership
5236    e->idl_count = ga.ga_len;
5237  } else {
5238    ga_clear(&ga);
5239  }
5240  return e;
5241}
5242
5243/// Return true if "id" is in the resolved set of cache entry "e".
5244static bool idl_contains(idl_entry_T *e, int16_t id)
5245{
5246  int lo = 0;
5247  int hi = e->idl_count - 1;
5248
5249  while (lo <= hi) {
5250    int mid = (lo + hi) / 2;
5251    int16_t v = e->idl_ids[mid];
5252
5253    if (v == id) {
5254      return true;
5255    }
5256    if (v < id) {
5257      lo = mid + 1;
5258    } else {
5259      hi = mid - 1;
5260    }
5261  }
5262  return false;
5263}
5264
5265static void idl_cache_clear(synblock_T *block)
5266{
5267  idl_cache_T *cache = (idl_cache_T *)block->b_idlist_cache;
5268
5269  if (cache == NULL) {
5270    return;
5271  }
5272  for (int i = 0; i < IDL_CACHE_SIZE; i++) {
5273    xfree(cache->ent[i].idl_ids);
5274  }
5275  xfree(cache);
5276  block->b_idlist_cache = NULL;
5277}
5278// }}}
5279
5280/// Check if syntax group "ssp" is in the ID list "list" of "cur_si".
5281/// "cur_si" can be NULL if not checking the "containedin" list.
5282/// Used to check if a syntax item is in the "contains" or "nextgroup" list of
5283/// the current item.
5284/// This function is called very often, keep it fast!!
5285///
5286/// @param cur_si     current item or NULL
5287/// @param list       id list
5288/// @param ssp        group id and ":syn include" tag of group
5289/// @param flags      group flags
5290static int in_id_list(stateitem_T *cur_si, int16_t *list, struct sp_syn *ssp, int flags)
5291{
5292  int retval;
5293  int16_t id = ssp->id;
5294  static int depth = 0;
5295
5296  // If ssp has a "containedin" list and "cur_si" is in it, return true.
5297  if (cur_si != NULL && ssp->cont_in_list != NULL
5298      && !(cur_si->si_flags & HL_MATCH)) {
5299    // Ignore transparent items without a contains argument.  Double check
5300    // that we don't go back past the first one.
5301    while ((cur_si->si_flags & HL_TRANS_CONT)
5302           && cur_si > (stateitem_T *)(current_state.ga_data)) {
5303      cur_si--;
5304    }
5305    // cur_si->si_idx is -1 for keywords, these never contain anything.
5306    if (cur_si->si_idx >= 0 && in_id_list(NULL, ssp->cont_in_list,
5307                                          &(SYN_ITEMS(syn_block)[cur_si->si_idx].sp_syn),
5308                                          SYN_ITEMS(syn_block)[cur_si->si_idx].sp_flags)) {
5309      return true;
5310    }
5311  }
5312
5313  if (list == NULL) {
5314    return false;
5315  }
5316
5317  // If list is ID_LIST_ALL, we are in a transparent item that isn't
5318  // inside anything.  Only allow not-contained groups.
5319  if (list == ID_LIST_ALL) {
5320    return !(flags & HL_CONTAINED);
5321  }
5322
5323  // Is this top-level (i.e. not 'contained') in the file it was declared in?
5324  // For included files, this is different from HL_CONTAINED, which is set
5325  // unconditionally.
5326  bool toplevel = !(flags & HL_CONTAINED) || (flags & HL_INCLUDED_TOPLEVEL);
5327
5328  // Fast path: use the resolved, sorted set cached for this list.  Only the
5329  // leading ALLBUT/TOP/CONTAINED gate depends on "ssp"/"flags", so it is
5330  // applied here; membership itself is a binary search.
5331  idl_entry_T *e = idl_get_entry(list);
5332  if (e != NULL && e->idl_usable) {
5333    if (e->idl_marker != 0) {
5334      int16_t item = e->idl_marker;
5335      if (item < SYNID_TOP) {
5336        if (item - SYNID_ALLBUT != ssp->inc_tag) {
5337          return false;
5338        }
5339      } else if (item < SYNID_CONTAINED) {
5340        if (item - SYNID_TOP != ssp->inc_tag || !toplevel) {
5341          return false;
5342        }
5343      } else {
5344        if (item - SYNID_CONTAINED != ssp->inc_tag || toplevel) {
5345          return false;
5346        }
5347      }
5348      retval = false;
5349    } else {
5350      retval = true;
5351    }
5352    return idl_contains(e, id) ? retval : !retval;
5353  }
5354
5355  // Slow path (uncacheable list, e.g. a nested ALLBUT).
5356  // If the first item is "ALLBUT", return true if "id" is NOT in the
5357  // contains list.  We also require that "id" is at the same ":syn include"
5358  // level as the list.
5359  int16_t item = *list;
5360  if (item >= SYNID_ALLBUT && item < SYNID_CLUSTER) {
5361    if (item < SYNID_TOP) {
5362      // ALL or ALLBUT: accept all groups in the same file
5363      if (item - SYNID_ALLBUT != ssp->inc_tag) {
5364        return false;
5365      }
5366    } else if (item < SYNID_CONTAINED) {
5367      // TOP: accept all not-contained groups in the same file
5368      if (item - SYNID_TOP != ssp->inc_tag || !toplevel) {
5369        return false;
5370      }
5371    } else {
5372      // CONTAINED: accept all contained groups in the same file
5373      if (item - SYNID_CONTAINED != ssp->inc_tag || toplevel) {
5374        return false;
5375      }
5376    }
5377    item = *++list;
5378    retval = false;
5379  } else {
5380    retval = true;
5381  }
5382
5383  // Return "retval" if id is in the contains list.
5384  while (item != 0) {
5385    if (item == id) {
5386      return retval;
5387    }
5388    if (item >= SYNID_CLUSTER) {
5389      int16_t *scl_list = SYN_CLSTR(syn_block)[item - SYNID_CLUSTER].scl_list;
5390      // restrict recursiveness to 30 to avoid an endless loop for a
5391      // cluster that includes itself (indirectly)
5392      if (scl_list != NULL && depth < 30) {
5393        depth++;
5394        int r = in_id_list(NULL, scl_list, ssp, flags);
5395        depth--;
5396        if (r) {
5397          return retval;
5398        }
5399      }
5400    }
5401    item = *++list;
5402  }
5403  return !retval;
5404}
5405
5406struct subcommand {
5407  char *name;                                // subcommand name
5408  void (*func)(exarg_T *, int);              // function to call
5409};
5410
5411static struct subcommand subcommands[] = {
5412  { "case",      syn_cmd_case },
5413  { "clear",     syn_cmd_clear },
5414  { "cluster",   syn_cmd_cluster },
5415  { "conceal",   syn_cmd_conceal },
5416  { "enable",    syn_cmd_on },
5417  { "foldlevel", syn_cmd_foldlevel },
5418  { "include",   syn_cmd_include },
5419  { "iskeyword", syn_cmd_iskeyword },
5420  { "keyword",   syn_cmd_keyword },
5421  { "list",      syn_cmd_list },
5422  { "manual",    syn_cmd_manual },
5423  { "match",     syn_cmd_match },
5424  { "on",        syn_cmd_on },
5425  { "off",       syn_cmd_off },
5426  { "region",    syn_cmd_region },
5427  { "reset",     syn_cmd_reset },
5428  { "spell",     syn_cmd_spell },
5429  { "sync",      syn_cmd_sync },
5430  { "",          syn_cmd_list },
5431};
5432
5433/// ":syntax".
5434/// This searches the subcommands[] table for the subcommand name, and calls a
5435/// syntax_subcommand() function to do the rest.
5436void ex_syntax(exarg_T *eap)
5437{
5438  char *arg = eap->arg;
5439  char *subcmd_end;
5440
5441  syn_cmdlinep = eap->cmdlinep;
5442
5443  // isolate subcommand name
5444  for (subcmd_end = arg; ASCII_ISALPHA(*subcmd_end); subcmd_end++) {}
5445  char *const subcmd_name = xstrnsave(arg, (size_t)(subcmd_end - arg));
5446  if (eap->skip) {  // skip error messages for all subcommands
5447    emsg_skip++;
5448  }
5449  size_t i;
5450  for (i = 0; i < ARRAY_SIZE(subcommands); i++) {
5451    if (strcmp(subcmd_name, subcommands[i].name) == 0) {
5452      eap->arg = skipwhite(subcmd_end);
5453      (subcommands[i].func)(eap, false);
5454      break;
5455    }
5456  }
5457
5458  if (i == ARRAY_SIZE(subcommands)) {
5459    semsg(_("E410: Invalid :syntax subcommand: %s"), subcmd_name);
5460  }
5461
5462  xfree(subcmd_name);
5463  if (eap->skip) {
5464    emsg_skip--;
5465  }
5466}
5467
5468/// @deprecated
5469void ex_ownsyntax(exarg_T *eap)
5470{
5471  if (curwin->w_s == &curwin->w_buffer->b_s) {
5472    curwin->w_s = xcalloc(1, sizeof(synblock_T));
5473    hash_init(&curwin->w_s->b_keywtab);
5474    hash_init(&curwin->w_s->b_keywtab_ic);
5475    // TODO(vim): Keep the spell checking as it was.
5476    curwin->w_p_spell = false;  // No spell checking
5477    // make sure option values are "empty_string_option" instead of NULL
5478    clear_string_option(&curwin->w_s->b_p_spc);
5479    clear_string_option(&curwin->w_s->b_p_spf);
5480    clear_string_option(&curwin->w_s->b_p_spl);
5481    clear_string_option(&curwin->w_s->b_p_spo);
5482    clear_string_option(&curwin->w_s->b_syn_isk);
5483  }
5484
5485  // Save value of b:current_syntax.
5486  char *old_value = get_var_value("b:current_syntax");
5487  if (old_value != NULL) {
5488    old_value = xstrdup(old_value);
5489  }
5490
5491  // Apply the "syntax" autocommand event, this finds and loads the syntax file.
5492  apply_autocmds(EVENT_SYNTAX, eap->arg, curbuf->b_fname, true, curbuf);
5493
5494  // Move value of b:current_syntax to w:current_syntax.
5495  char *new_value = get_var_value("b:current_syntax");
5496  if (new_value != NULL) {
5497    set_internal_string_var("w:current_syntax", new_value);
5498  }
5499
5500  // Restore value of b:current_syntax.
5501  if (old_value == NULL) {
5502    do_unlet(S_LEN("b:current_syntax"), true);
5503  } else {
5504    set_internal_string_var("b:current_syntax", old_value);
5505    xfree(old_value);
5506  }
5507}
5508
5509bool syntax_present(win_T *win)
5510{
5511  return win->w_s->b_syn_patterns.ga_len != 0
5512         || win->w_s->b_syn_clusters.ga_len != 0
5513         || win->w_s->b_keywtab.ht_used > 0
5514         || win->w_s->b_keywtab_ic.ht_used > 0;
5515}
5516
5517static enum {
5518  EXP_SUBCMD,       // expand ":syn" sub-commands
5519  EXP_CASE,         // expand ":syn case" arguments
5520  EXP_SPELL,        // expand ":syn spell" arguments
5521  EXP_SYNC,         // expand ":syn sync" arguments
5522  EXP_CLUSTER,      // expand ":syn list @cluster" arguments
5523} expand_what;
5524
5525// Reset include_link, include_default, include_none to 0.
5526// Called when we are done expanding.
5527void reset_expand_highlight(void)
5528{
5529  include_link = include_default = include_none = 0;
5530}
5531
5532// Handle command line completion for :match and :echohl command: Add "None"
5533// as highlight group.
5534void set_context_in_echohl_cmd(expand_T *xp, const char *arg)
5535{
5536  xp->xp_context = EXPAND_HIGHLIGHT;
5537  xp->xp_pattern = (char *)arg;
5538  include_none = 1;
5539}
5540
5541// Handle command line completion for :syntax command.
5542void set_context_in_syntax_cmd(expand_T *xp, const char *arg)
5543{
5544  // Default: expand subcommands.
5545  xp->xp_context = EXPAND_SYNTAX;
5546  expand_what = EXP_SUBCMD;
5547  xp->xp_pattern = (char *)arg;
5548  include_link = 0;
5549  include_default = 0;
5550
5551  if (*arg == NUL) {
5552    return;
5553  }
5554
5555  // (part of) subcommand already typed
5556  const char *p = skiptowhite(arg);
5557  if (*p == NUL) {
5558    return;
5559  }
5560
5561  // past first world
5562  xp->xp_pattern = skipwhite(p);
5563  if (*skiptowhite(xp->xp_pattern) != NUL) {
5564    xp->xp_context = EXPAND_NOTHING;
5565  } else if (STRNICMP(arg, "case", (size_t)(p - arg)) == 0) {
5566    expand_what = EXP_CASE;
5567  } else if (STRNICMP(arg, "spell", (size_t)(p - arg)) == 0) {
5568    expand_what = EXP_SPELL;
5569  } else if (STRNICMP(arg, "sync", (size_t)(p - arg)) == 0) {
5570    expand_what = EXP_SYNC;
5571  } else if (STRNICMP(arg, "list", (size_t)(p - arg)) == 0) {
5572    p = skipwhite(p);
5573    if (*p == '@') {
5574      expand_what = EXP_CLUSTER;
5575    } else {
5576      xp->xp_context = EXPAND_HIGHLIGHT;
5577    }
5578  } else if (STRNICMP(arg, "keyword", (size_t)(p - arg)) == 0
5579             || STRNICMP(arg, "region", (size_t)(p - arg)) == 0
5580             || STRNICMP(arg, "match", (size_t)(p - arg)) == 0) {
5581    xp->xp_context = EXPAND_HIGHLIGHT;
5582  } else {
5583    xp->xp_context = EXPAND_NOTHING;
5584  }
5585}
5586
5587// Function given to ExpandGeneric() to obtain the list syntax names for
5588// expansion.
5589char *get_syntax_name(expand_T *xp, int idx)
5590{
5591  switch (expand_what) {
5592  case EXP_SUBCMD:
5593    if (idx < 0 || idx >= (int)ARRAY_SIZE(subcommands)) {
5594      return NULL;
5595    }
5596    return subcommands[idx].name;
5597  case EXP_CASE: {
5598    static char *case_args[] = { "match", "ignore", NULL };
5599    return case_args[idx];
5600  }
5601  case EXP_SPELL: {
5602    static char *spell_args[] =
5603    { "toplevel", "notoplevel", "default", NULL };
5604    return spell_args[idx];
5605  }
5606  case EXP_SYNC: {
5607    static char *sync_args[] =
5608    { "ccomment", "clear", "fromstart",
5609      "linebreaks=", "linecont", "lines=", "match",
5610      "maxlines=", "minlines=", "region", NULL };
5611    return sync_args[idx];
5612  }
5613  case EXP_CLUSTER:
5614    if (idx < curwin->w_s->b_syn_clusters.ga_len) {
5615      vim_snprintf(xp->xp_buf, EXPAND_BUF_LEN, "@%s",
5616                   SYN_CLSTR(curwin->w_s)[idx].scl_name);
5617      return xp->xp_buf;
5618    } else {
5619      return NULL;
5620    }
5621  }
5622  return NULL;
5623}
5624
5625/// Function called for expression evaluation: get syntax ID at file position.
5626///
5627/// @param trans       remove transparency
5628/// @param spellp      return: can do spell checking
5629/// @param keep_state  keep state of char at "col"
5630int syn_get_id(win_T *wp, linenr_T lnum, colnr_T col, int trans, bool *spellp, int keep_state)
5631{
5632  // When the position is not after the current position and in the same
5633  // line of the same window with the same buffer, need to restart parsing.
5634  if (wp != syn_win || wp->w_buffer != syn_buf || lnum != current_lnum || col < current_col) {
5635    syntax_start(wp, lnum);
5636  } else if (col > current_col) {
5637    // next_match may not be correct when moving around, e.g. with the
5638    // "skip" expression in searchpair()
5639    next_match_idx = -1;
5640  }
5641
5642  get_syntax_attr(col, spellp, keep_state);
5643
5644  return trans ? current_trans_id : current_id;
5645}
5646
5647// Get extra information about the syntax item.  Must be called right after
5648// get_syntax_attr().
5649// Stores the current item sequence nr in "*seqnrp".
5650// Returns the current flags.
5651int get_syntax_info(int *seqnrp)
5652{
5653  *seqnrp = current_seqnr;
5654  return current_flags;
5655}
5656
5657/// Get the sequence number of the concealed file position.
5658///
5659/// @return seqnr if the file position is concealed, 0 otherwise.
5660int syn_get_concealed_id(win_T *wp, linenr_T lnum, colnr_T col)
5661{
5662  int seqnr;
5663
5664  syn_get_id(wp, lnum, col, false, NULL, false);
5665  int syntax_flags = get_syntax_info(&seqnr);
5666
5667  if (syntax_flags & HL_CONCEAL) {
5668    return seqnr;
5669  }
5670  return 0;
5671}
5672
5673// Return conceal substitution character
5674int syn_get_sub_char(void)
5675{
5676  return current_sub_char;
5677}
5678
5679// Return the syntax ID at position "i" in the current stack.
5680// The caller must have called syn_get_id() before to fill the stack.
5681// Returns -1 when "i" is out of range.
5682int syn_get_stack_item(int i)
5683{
5684  if (i >= current_state.ga_len) {
5685    // Need to invalidate the state, because we didn't properly finish it
5686    // for the last character, "keep_state" was true.
5687    invalidate_current_state();
5688    current_col = MAXCOL;
5689    return -1;
5690  }
5691  return CUR_STATE(i).si_id;
5692}
5693
5694static int syn_cur_foldlevel(void)
5695{
5696  int level = 0;
5697  for (int i = 0; i < current_state.ga_len; i++) {
5698    if (CUR_STATE(i).si_flags & HL_FOLD) {
5699      level++;
5700    }
5701  }
5702  return level;
5703}
5704
5705/// Function called to get folding level for line "lnum" in window "wp".
5706int syn_get_foldlevel(win_T *wp, linenr_T lnum)
5707{
5708  int level = 0;
5709
5710  // Return quickly when there are no fold items at all.
5711  if (wp->w_s->b_syn_folditems != 0
5712      && !wp->w_s->b_syn_error
5713      && !wp->w_s->b_syn_slow) {
5714    syntax_start(wp, lnum);
5715
5716    // Start with the fold level at the start of the line.
5717    level = syn_cur_foldlevel();
5718
5719    if (wp->w_s->b_syn_foldlevel == SYNFLD_MINIMUM) {
5720      // Find the lowest fold level that is followed by a higher one.
5721      int cur_level = level;
5722      int low_level = cur_level;
5723      while (!current_finished) {
5724        syn_current_attr(false, false, NULL, false);
5725        cur_level = syn_cur_foldlevel();
5726        if (cur_level < low_level) {
5727          low_level = cur_level;
5728        } else if (cur_level > low_level) {
5729          level = low_level;
5730        }
5731        current_col++;
5732      }
5733    }
5734  }
5735  if (level > wp->w_p_fdn) {
5736    level = (int)wp->w_p_fdn;
5737    if (level < 0) {
5738      level = 0;
5739    }
5740  }
5741  return level;
5742}
5743
5744// ":syntime".
5745void ex_syntime(exarg_T *eap)
5746{
5747  if (strcmp(eap->arg, "on") == 0) {
5748    syn_time_on = true;
5749  } else if (strcmp(eap->arg, "off") == 0) {
5750    syn_time_on = false;
5751  } else if (strcmp(eap->arg, "clear") == 0) {
5752    syntime_clear();
5753  } else if (strcmp(eap->arg, "report") == 0) {
5754    syntime_report();
5755  } else {
5756    semsg(_(e_invarg2), eap->arg);
5757  }
5758}
5759
5760static void syn_clear_time(syn_time_T *st)
5761{
5762  st->total = profile_zero();
5763  st->slowest = profile_zero();
5764  st->count = 0;
5765  st->match = 0;
5766}
5767
5768// Clear the syntax timing for the current buffer.
5769static void syntime_clear(void)
5770{
5771  synpat_T *spp;
5772
5773  if (!syntax_present(curwin)) {
5774    msg(_(msg_no_items), 0);
5775    return;
5776  }
5777  for (int idx = 0; idx < curwin->w_s->b_syn_patterns.ga_len; idx++) {
5778    spp = &(SYN_ITEMS(curwin->w_s)[idx]);
5779    syn_clear_time(&spp->sp_time);
5780  }
5781}
5782
5783// Function given to ExpandGeneric() to obtain the possible arguments of the
5784// ":syntime {on,off,clear,report}" command.
5785char *get_syntime_arg(expand_T *xp, int idx)
5786{
5787  switch (idx) {
5788  case 0:
5789    return "on";
5790  case 1:
5791    return "off";
5792  case 2:
5793    return "clear";
5794  case 3:
5795    return "report";
5796  }
5797  return NULL;
5798}
5799
5800static int syn_compare_syntime(const void *v1, const void *v2)
5801{
5802  const time_entry_T *s1 = v1;
5803  const time_entry_T *s2 = v2;
5804
5805  return profile_cmp(s1->total, s2->total);
5806}
5807
5808// Clear the syntax timing for the current buffer.
5809static void syntime_report(void)
5810{
5811  if (!syntax_present(curwin)) {
5812    msg(_(msg_no_items), 0);
5813    return;
5814  }
5815
5816  garray_T ga;
5817  ga_init(&ga, sizeof(time_entry_T), 50);
5818
5819  proftime_T total_total = profile_zero();
5820  int total_count = 0;
5821  time_entry_T *p;
5822  for (int idx = 0; idx < curwin->w_s->b_syn_patterns.ga_len; idx++) {
5823    synpat_T *spp = &(SYN_ITEMS(curwin->w_s)[idx]);
5824    if (spp->sp_time.count > 0) {
5825      p = GA_APPEND_VIA_PTR(time_entry_T, &ga);
5826      p->total = spp->sp_time.total;
5827      total_total = profile_add(total_total, spp->sp_time.total);
5828      p->count = spp->sp_time.count;
5829      p->match = spp->sp_time.match;
5830      total_count += spp->sp_time.count;
5831      p->slowest = spp->sp_time.slowest;
5832      proftime_T tm = profile_divide(spp->sp_time.total, spp->sp_time.count);
5833      p->average = tm;
5834      p->id = spp->sp_syn.id;
5835      p->pattern = spp->sp_pattern;
5836    }
5837  }
5838
5839  // Sort on total time. Skip if there are no items to avoid passing NULL
5840  // pointer to qsort().
5841  if (ga.ga_len > 1) {
5842    qsort(ga.ga_data, (size_t)ga.ga_len, sizeof(time_entry_T),
5843          syn_compare_syntime);
5844  }
5845
5846  msg_puts_title(_("  TOTAL      COUNT  MATCH   SLOWEST     AVERAGE   NAME               PATTERN"));
5847  msg_puts("\n");
5848  for (int idx = 0; idx < ga.ga_len && !got_int; idx++) {
5849    p = ((time_entry_T *)ga.ga_data) + idx;
5850
5851    msg_puts(profile_msg(p->total));
5852    msg_puts(" ");     // make sure there is always a separating space
5853    msg_advance(13);
5854    msg_outnum(p->count);
5855    msg_puts(" ");
5856    msg_advance(20);
5857    msg_outnum(p->match);
5858    msg_puts(" ");
5859    msg_advance(26);
5860    msg_puts(profile_msg(p->slowest));
5861    msg_puts(" ");
5862    msg_advance(38);
5863    msg_puts(profile_msg(p->average));
5864    msg_puts(" ");
5865    msg_advance(50);
5866    msg_outtrans(highlight_group_name(p->id - 1), 0, false);
5867    msg_puts(" ");
5868
5869    msg_advance(69);
5870    int len;
5871    if (Columns < 80) {
5872      len = 20;       // will wrap anyway
5873    } else {
5874      len = Columns - 70;
5875    }
5876    int patlen = (int)strlen(p->pattern);
5877    len = MIN(len, patlen);
5878    msg_outtrans_len(p->pattern, len, 0, false);
5879    msg_puts("\n");
5880  }
5881  ga_clear(&ga);
5882  if (!got_int) {
5883    msg_puts("\n");
5884    msg_puts(profile_msg(total_total));
5885    msg_advance(13);
5886    msg_outnum(total_count);
5887    msg_puts("\n");
5888  }
5889}