robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
35.4 KiB1210 linesraw
1// match.c: functions for highlighting matches
2
3#include <assert.h>
4#include <inttypes.h>
5#include <stdbool.h>
6#include <stdio.h>
7#include <string.h>
8
9#include "nvim/ascii_defs.h"
10#include "nvim/buffer_defs.h"
11#include "nvim/charset.h"
12#include "nvim/drawscreen.h"
13#include "nvim/errors.h"
14#include "nvim/eval/funcs.h"
15#include "nvim/eval/typval.h"
16#include "nvim/eval/window.h"
17#include "nvim/ex_cmds_defs.h"
18#include "nvim/ex_docmd.h"
19#include "nvim/fold.h"
20#include "nvim/gettext_defs.h"
21#include "nvim/globals.h"
22#include "nvim/highlight.h"
23#include "nvim/highlight_defs.h"
24#include "nvim/highlight_group.h"
25#include "nvim/macros_defs.h"
26#include "nvim/match.h"
27#include "nvim/mbyte.h"
28#include "nvim/mbyte_defs.h"
29#include "nvim/memline.h"
30#include "nvim/memory.h"
31#include "nvim/message.h"
32#include "nvim/option_vars.h"
33#include "nvim/pos_defs.h"
34#include "nvim/profile.h"
35#include "nvim/regexp.h"
36#include "nvim/strings.h"
37#include "nvim/types_defs.h"
38#include "nvim/vim_defs.h"
39
40#include "match.c.generated.h"
41
42#define SEARCH_HL_PRIORITY 0
43
44/// Add match to the match list of window "wp".
45/// If "pat" is not NULL the pattern will be highlighted with the group "grp"
46/// with priority "prio".
47/// If "pos_list" is not NULL the list of positions defines the highlights.
48/// Optionally, a desired ID "id" can be specified (greater than or equal to 1).
49/// If no particular ID is desired, -1 must be specified for "id".
50///
51/// @param[in] conceal_char pointer to conceal replacement char
52/// @return ID of added match, -1 on failure.
53static int match_add(win_T *wp, const char *const grp, const char *const pat, int prio, int id,
54                     list_T *pos_list, const char *const conceal_char)
55  FUNC_ATTR_NONNULL_ARG(1, 2)
56{
57  int hlg_id;
58  regprog_T *regprog = NULL;
59  int rtype = UPD_SOME_VALID;
60
61  if (*grp == NUL || (pat != NULL && *pat == NUL)) {
62    return -1;
63  }
64  if (id < -1 || id == 0) {
65    semsg(_("E799: Invalid ID: %" PRId64
66            " (must be greater than or equal to 1)"),
67          (int64_t)id);
68    return -1;
69  }
70  if (id == -1) {
71    // use the next available match ID
72    id = wp->w_next_match_id++;
73  } else {
74    // check the given ID is not already in use
75    for (matchitem_T *cur = wp->w_match_head; cur != NULL; cur = cur->mit_next) {
76      if (cur->mit_id == id) {
77        semsg(_("E801: ID already taken: %" PRId64), (int64_t)id);
78        return -1;
79      }
80    }
81
82    // Make sure the next match ID is always higher than the highest
83    // manually selected ID.  Add some extra in case a few more IDs are
84    // added soon.
85    if (wp->w_next_match_id < id + 100) {
86      wp->w_next_match_id = id + 100;
87    }
88  }
89
90  if ((hlg_id = syn_check_group(grp, strlen(grp))) == 0) {
91    return -1;
92  }
93  if (pat != NULL && (regprog = vim_regcomp(pat, RE_MAGIC)) == NULL) {
94    semsg(_(e_invarg2), pat);
95    return -1;
96  }
97
98  // Build new match.
99  matchitem_T *m = xcalloc(1, sizeof(matchitem_T));
100  if (tv_list_len(pos_list) > 0) {
101    m->mit_pos_array = xcalloc((size_t)tv_list_len(pos_list), sizeof(llpos_T));
102    m->mit_pos_count = tv_list_len(pos_list);
103  }
104  m->mit_id = id;
105  m->mit_priority = prio;
106  m->mit_pattern = pat == NULL ? NULL : xstrdup(pat);
107  m->mit_hlg_id = hlg_id;
108  m->mit_match.regprog = regprog;
109  m->mit_match.rmm_ic = false;
110  m->mit_match.rmm_maxcol = 0;
111  m->mit_conceal_char = 0;
112  if (conceal_char != NULL) {
113    m->mit_conceal_char = utf_ptr2char(conceal_char);
114  }
115
116  // Set up position matches
117  if (pos_list != NULL) {
118    linenr_T toplnum = 0;
119    linenr_T botlnum = 0;
120
121    int i = 0;
122    TV_LIST_ITER(pos_list, li, {
123      linenr_T lnum = 0;
124      colnr_T col = 0;
125      int len = 1;
126      bool error = false;
127
128      if (TV_LIST_ITEM_TV(li)->v_type == VAR_LIST) {
129        const list_T *const subl = TV_LIST_ITEM_TV(li)->vval.v_list;
130        const listitem_T *subli = tv_list_first(subl);
131        if (subli == NULL) {
132          semsg(_("E5030: Empty list at position %d"),
133                (int)tv_list_idx_of_item(pos_list, li));
134          goto fail;
135        }
136        lnum = (linenr_T)tv_get_number_chk(TV_LIST_ITEM_TV(subli), &error);
137        if (error) {
138          goto fail;
139        }
140        if (lnum <= 0) {
141          continue;
142        }
143        m->mit_pos_array[i].lnum = lnum;
144        subli = TV_LIST_ITEM_NEXT(subl, subli);
145        if (subli != NULL) {
146          col = (colnr_T)tv_get_number_chk(TV_LIST_ITEM_TV(subli), &error);
147          if (error) {
148            goto fail;
149          }
150          if (col < 0) {
151            continue;
152          }
153          subli = TV_LIST_ITEM_NEXT(subl, subli);
154          if (subli != NULL) {
155            len = (colnr_T)tv_get_number_chk(TV_LIST_ITEM_TV(subli), &error);
156            if (len < 0) {
157              continue;
158            }
159            if (error) {
160              goto fail;
161            }
162          }
163        }
164        m->mit_pos_array[i].col = col;
165        m->mit_pos_array[i].len = len;
166      } else if (TV_LIST_ITEM_TV(li)->v_type == VAR_NUMBER) {
167        if (TV_LIST_ITEM_TV(li)->vval.v_number <= 0) {
168          continue;
169        }
170        m->mit_pos_array[i].lnum = (linenr_T)TV_LIST_ITEM_TV(li)->vval.v_number;
171        m->mit_pos_array[i].col = 0;
172        m->mit_pos_array[i].len = 0;
173      } else {
174        semsg(_("E5031: List or number required at position %d"),
175              (int)tv_list_idx_of_item(pos_list, li));
176        goto fail;
177      }
178      if (toplnum == 0 || lnum < toplnum) {
179        toplnum = lnum;
180      }
181      if (botlnum == 0 || lnum >= botlnum) {
182        botlnum = lnum + 1;
183      }
184      i++;
185    });
186
187    // Calculate top and bottom lines for redrawing area
188    if (toplnum != 0) {
189      redraw_win_range_later(wp, toplnum, botlnum);
190      m->mit_toplnum = toplnum;
191      m->mit_botlnum = botlnum;
192      rtype = UPD_VALID;
193    }
194  }
195
196  // Insert new match.  The match list is in ascending order with regard to
197  // the match priorities.
198  matchitem_T *cur = wp->w_match_head;
199  matchitem_T *prev = cur;
200  while (cur != NULL && prio >= cur->mit_priority) {
201    prev = cur;
202    cur = cur->mit_next;
203  }
204  if (cur == prev) {
205    wp->w_match_head = m;
206  } else {
207    prev->mit_next = m;
208  }
209  m->mit_next = cur;
210
211  redraw_later(wp, rtype);
212  return id;
213
214fail:
215  vim_regfree(regprog);
216  xfree(m->mit_pattern);
217  xfree(m->mit_pos_array);
218  xfree(m);
219  return -1;
220}
221
222/// Delete match with ID 'id' in the match list of window 'wp'.
223///
224/// @param perr  print error messages if true.
225static int match_delete(win_T *wp, int id, bool perr)
226{
227  matchitem_T *cur = wp->w_match_head;
228  matchitem_T *prev = cur;
229  int rtype = UPD_SOME_VALID;
230
231  if (id < 1) {
232    if (perr) {
233      semsg(_("E802: Invalid ID: %" PRId64 " (must be greater than or equal to 1)"),
234            (int64_t)id);
235    }
236    return -1;
237  }
238  while (cur != NULL && cur->mit_id != id) {
239    prev = cur;
240    cur = cur->mit_next;
241  }
242  if (cur == NULL) {
243    if (perr) {
244      semsg(_("E803: ID not found: %" PRId64), (int64_t)id);
245    }
246    return -1;
247  }
248  if (cur == prev) {
249    wp->w_match_head = cur->mit_next;
250  } else {
251    prev->mit_next = cur->mit_next;
252  }
253  vim_regfree(cur->mit_match.regprog);
254  xfree(cur->mit_pattern);
255  if (cur->mit_toplnum != 0) {
256    redraw_win_range_later(wp, cur->mit_toplnum, cur->mit_botlnum);
257    rtype = UPD_VALID;
258  }
259  xfree(cur->mit_pos_array);
260  xfree(cur);
261  redraw_later(wp, rtype);
262  return 0;
263}
264
265/// Delete all matches in the match list of window 'wp'.
266void clear_matches(win_T *wp)
267{
268  while (wp->w_match_head != NULL) {
269    matchitem_T *m = wp->w_match_head->mit_next;
270    vim_regfree(wp->w_match_head->mit_match.regprog);
271    xfree(wp->w_match_head->mit_pattern);
272    xfree(wp->w_match_head->mit_pos_array);
273    xfree(wp->w_match_head);
274    wp->w_match_head = m;
275  }
276  redraw_later(wp, UPD_SOME_VALID);
277}
278
279/// Get match from ID 'id' in window 'wp'.
280/// Return NULL if match not found.
281static matchitem_T *get_match(win_T *wp, int id)
282{
283  matchitem_T *cur = wp->w_match_head;
284
285  while (cur != NULL && cur->mit_id != id) {
286    cur = cur->mit_next;
287  }
288  return cur;
289}
290
291/// Init for calling prepare_search_hl().
292void init_search_hl(win_T *wp, match_T *search_hl)
293  FUNC_ATTR_NONNULL_ALL
294{
295  // Setup for match and 'hlsearch' highlighting.  Disable any previous
296  // match
297  matchitem_T *cur = wp->w_match_head;
298  while (cur != NULL) {
299    cur->mit_hl.rm = cur->mit_match;
300    if (cur->mit_hlg_id == 0) {
301      cur->mit_hl.attr = 0;
302    } else {
303      cur->mit_hl.attr = syn_id2attr(cur->mit_hlg_id);
304    }
305    cur->mit_hl.buf = wp->w_buffer;
306    cur->mit_hl.lnum = 0;
307    cur->mit_hl.first_lnum = 0;
308    // Set the time limit to 'redrawtime'.
309    cur->mit_hl.tm = profile_setlimit(p_rdt);
310    cur = cur->mit_next;
311  }
312  search_hl->buf = wp->w_buffer;
313  search_hl->lnum = 0;
314  search_hl->first_lnum = 0;
315  search_hl->attr = win_hl_attr(wp, HLF_L);
316
317  // time limit is set at the toplevel, for all windows
318}
319
320/// @param shl       points to a match. Fill on match.
321/// @param posmatch  match item with positions
322/// @param mincol    minimal column for a match
323///
324/// @return one on match, otherwise return zero.
325static int next_search_hl_pos(match_T *shl, linenr_T lnum, matchitem_T *match, colnr_T mincol)
326  FUNC_ATTR_NONNULL_ALL
327{
328  int found = -1;
329
330  shl->lnum = 0;
331  for (int i = match->mit_pos_cur; i < match->mit_pos_count; i++) {
332    llpos_T *pos = &match->mit_pos_array[i];
333
334    if (pos->lnum == 0) {
335      break;
336    }
337    if (pos->len == 0 && pos->col < mincol) {
338      continue;
339    }
340    if (pos->lnum == lnum) {
341      if (found >= 0) {
342        // if this match comes before the one at "found" then swap them
343        if (pos->col < match->mit_pos_array[found].col) {
344          llpos_T tmp = *pos;
345
346          *pos = match->mit_pos_array[found];
347          match->mit_pos_array[found] = tmp;
348        }
349      } else {
350        found = i;
351      }
352    }
353  }
354  match->mit_pos_cur = 0;
355  if (found >= 0) {
356    colnr_T start = match->mit_pos_array[found].col == 0
357                    ? 0 : match->mit_pos_array[found].col - 1;
358    colnr_T end = match->mit_pos_array[found].col == 0
359                  ? MAXCOL : start + match->mit_pos_array[found].len;
360
361    shl->lnum = lnum;
362    shl->rm.startpos[0].lnum = 0;
363    shl->rm.startpos[0].col = start;
364    shl->rm.endpos[0].lnum = 0;
365    shl->rm.endpos[0].col = end;
366    shl->is_addpos = true;
367    shl->has_cursor = false;
368    match->mit_pos_cur = found + 1;
369    return 1;
370  }
371  return 0;
372}
373
374/// Search for a next 'hlsearch' or match.
375/// Uses shl->buf.
376/// Sets shl->lnum and shl->rm contents.
377/// Note: Assumes a previous match is always before "lnum", unless
378/// shl->lnum is zero.
379/// Careful: Any pointers for buffer lines will become invalid.
380///
381/// @param shl     points to search_hl or a match
382/// @param mincol  minimal column for a match
383/// @param cur     to retrieve match positions if any
384static void next_search_hl(win_T *win, match_T *search_hl, match_T *shl, linenr_T lnum,
385                           colnr_T mincol, matchitem_T *cur)
386  FUNC_ATTR_NONNULL_ARG(2)
387{
388  colnr_T matchcol;
389  int nmatched = 0;
390  const int called_emsg_before = called_emsg;
391
392  // for :{range}s/pat only highlight inside the range
393  if ((lnum < Search.first_line || lnum > Search.last_line) && cur == NULL) {
394    shl->lnum = 0;
395    return;
396  }
397
398  if (shl->lnum != 0) {
399    // Check for three situations:
400    // 1. If the "lnum" is below a previous match, start a new search.
401    // 2. If the previous match includes "mincol", use it.
402    // 3. Continue after the previous match.
403    linenr_T l = shl->lnum + shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum;
404    if (lnum > l) {
405      shl->lnum = 0;
406    } else if (lnum < l || shl->rm.endpos[0].col > mincol) {
407      return;
408    }
409  }
410
411  // Repeat searching for a match until one is found that includes "mincol"
412  // or none is found in this line.
413  while (true) {
414    // Stop searching after passing the time limit.
415    if (profile_passed_limit(shl->tm)) {
416      shl->lnum = 0;                    // no match found in time
417      break;
418    }
419    // Three situations:
420    // 1. No useful previous match: search from start of line.
421    // 2. Not Vi compatible or empty match: continue at next character.
422    //    Break the loop if this is beyond the end of the line.
423    // 3. Vi compatible searching: continue at end of previous match.
424    if (shl->lnum == 0) {
425      matchcol = 0;
426    } else if (vim_strchr(p_cpo, kCpoSearch) == NULL
427               || (shl->rm.endpos[0].lnum == 0
428                   && shl->rm.endpos[0].col <= shl->rm.startpos[0].col)) {
429      matchcol = shl->rm.startpos[0].col;
430      char *ml = ml_get_buf(shl->buf, lnum) + matchcol;
431      if (*ml == NUL) {
432        matchcol++;
433        shl->lnum = 0;
434        break;
435      }
436      matchcol += utfc_ptr2len(ml);
437    } else {
438      matchcol = shl->rm.endpos[0].col;
439    }
440
441    shl->lnum = lnum;
442    if (shl->rm.regprog != NULL) {
443      // Remember whether shl->rm is using a copy of the regprog in
444      // cur->mit_match.
445      bool regprog_is_copy = (shl != search_hl && cur != NULL
446                              && shl == &cur->mit_hl
447                              && cur->mit_match.regprog == cur->mit_hl.rm.regprog);
448      int timed_out = false;
449
450      nmatched = vim_regexec_multi(&shl->rm, win, shl->buf, lnum, matchcol,
451                                   &(shl->tm), &timed_out);
452      // Copy the regprog, in case it got freed and recompiled.
453      if (regprog_is_copy) {
454        cur->mit_match.regprog = cur->mit_hl.rm.regprog;
455      }
456      if (called_emsg > called_emsg_before || got_int || timed_out) {
457        // Error while handling regexp: stop using this regexp.
458        if (shl == search_hl) {
459          // don't free regprog in the match list, it's a copy
460          vim_regfree(shl->rm.regprog);
461          set_no_hlsearch(true);
462        }
463        shl->rm.regprog = NULL;
464        shl->lnum = 0;
465        got_int = false;  // avoid the "Type :quit to exit Vim" message
466        break;
467      }
468    } else if (cur != NULL) {
469      nmatched = next_search_hl_pos(shl, lnum, cur, matchcol);
470    }
471    if (nmatched == 0) {
472      shl->lnum = 0;                    // no match found
473      break;
474    }
475    if (shl->rm.startpos[0].lnum > 0
476        || shl->rm.startpos[0].col >= mincol
477        || nmatched > 1
478        || shl->rm.endpos[0].col > mincol) {
479      shl->lnum += shl->rm.startpos[0].lnum;
480      break;                            // useful match found
481    }
482  }
483}
484
485/// Advance to the match in window "wp" line "lnum" or past it.
486void prepare_search_hl(win_T *wp, match_T *search_hl, linenr_T lnum)
487  FUNC_ATTR_NONNULL_ALL
488{
489  matchitem_T *cur = wp->w_match_head;  // points to the match list
490  match_T *shl;       // points to search_hl or a match
491  bool shl_flag = false;  // flag to indicate whether search_hl has been processed or not
492
493  // When using a multi-line pattern, start searching at the top
494  // of the window or just after a closed fold.
495  // Do this both for search_hl and the match list.
496  while (cur != NULL || shl_flag == false) {
497    if (shl_flag == false) {
498      shl = search_hl;
499      shl_flag = true;
500    } else {
501      shl = &cur->mit_hl;
502    }
503    if (shl->rm.regprog != NULL
504        && shl->lnum == 0
505        && re_multiline(shl->rm.regprog)) {
506      if (shl->first_lnum == 0) {
507        for (shl->first_lnum = lnum;
508             shl->first_lnum > wp->w_topline;
509             shl->first_lnum--) {
510          if (hasFolding(wp, shl->first_lnum - 1, NULL, NULL)) {
511            break;
512          }
513        }
514      }
515      if (cur != NULL) {
516        cur->mit_pos_cur = 0;
517      }
518      bool pos_inprogress = true;  // mark that a position match search is
519                                   // in progress
520      int n = 0;
521      while (shl->first_lnum < lnum && (shl->rm.regprog != NULL
522                                        || (cur != NULL && pos_inprogress))) {
523        next_search_hl(wp, search_hl, shl, shl->first_lnum, (colnr_T)n,
524                       shl == search_hl ? NULL : cur);
525        pos_inprogress = !(cur == NULL || cur->mit_pos_cur == 0);
526        if (shl->lnum != 0) {
527          shl->first_lnum = shl->lnum
528                            + shl->rm.endpos[0].lnum
529                            - shl->rm.startpos[0].lnum;
530          n = shl->rm.endpos[0].col;
531        } else {
532          shl->first_lnum++;
533          n = 0;
534        }
535      }
536    }
537    if (shl != search_hl && cur != NULL) {
538      cur = cur->mit_next;
539    }
540  }
541}
542
543/// Update "shl->has_cursor" based on the match in "shl" and the cursor
544/// position.
545static void check_cur_search_hl(win_T *wp, match_T *shl)
546{
547  linenr_T linecount = shl->rm.endpos[0].lnum - shl->rm.startpos[0].lnum;
548
549  if (wp->w_cursor.lnum >= shl->lnum
550      && wp->w_cursor.lnum <= shl->lnum + linecount
551      && (wp->w_cursor.lnum > shl->lnum || wp->w_cursor.col >= shl->rm.startpos[0].col)
552      && (wp->w_cursor.lnum < shl->lnum + linecount || wp->w_cursor.col < shl->rm.endpos[0].col)) {
553    shl->has_cursor = true;
554  } else {
555    shl->has_cursor = false;
556  }
557}
558
559/// Prepare for 'hlsearch' and match highlighting in one window line.
560///
561/// @return  true if there is such highlighting and set "search_attr" to the
562///          current highlight attribute.
563bool prepare_search_hl_line(win_T *wp, linenr_T lnum, colnr_T mincol, char **line,
564                            match_T *search_hl, int *search_attr, bool *search_attr_from_match)
565{
566  matchitem_T *cur = wp->w_match_head;  // points to the match list
567  match_T *shl;                     // points to search_hl or a match
568  bool shl_flag = false;        // flag to indicate whether search_hl
569                                // has been processed or not
570  bool area_highlighting = false;
571
572  // Handle highlighting the last used search pattern and matches.
573  // Do this for both search_hl and the match list.
574  while (cur != NULL || !shl_flag) {
575    if (!shl_flag) {
576      shl = search_hl;
577      shl_flag = true;
578    } else {
579      shl = &cur->mit_hl;
580    }
581    shl->startcol = MAXCOL;
582    shl->endcol = MAXCOL;
583    shl->attr_cur = 0;
584    shl->is_addpos = false;
585    shl->has_cursor = false;
586    if (cur != NULL) {
587      cur->mit_pos_cur = 0;
588    }
589    next_search_hl(wp, search_hl, shl, lnum, mincol,
590                   shl == search_hl ? NULL : cur);
591
592    // Need to get the line again, a multi-line regexp may have made it
593    // invalid.
594    *line = ml_get_buf(wp->w_buffer, lnum);
595
596    if (shl->lnum != 0 && shl->lnum <= lnum) {
597      if (shl->lnum == lnum) {
598        shl->startcol = shl->rm.startpos[0].col;
599      } else {
600        shl->startcol = 0;
601      }
602      if (lnum == shl->lnum + shl->rm.endpos[0].lnum
603          - shl->rm.startpos[0].lnum) {
604        shl->endcol = shl->rm.endpos[0].col;
605      } else {
606        shl->endcol = MAXCOL;
607      }
608
609      // check if the cursor is in the match before changing the columns
610      if (shl == search_hl) {
611        check_cur_search_hl(wp, shl);
612      }
613
614      // Highlight one character for an empty match.
615      if (shl->startcol == shl->endcol) {
616        if ((*line)[shl->endcol] != NUL) {
617          shl->endcol += utfc_ptr2len(*line + shl->endcol);
618        } else {
619          shl->endcol++;
620        }
621      }
622      if (shl->startcol < mincol) {   // match at leftcol
623        shl->attr_cur = shl->attr;
624        *search_attr = shl->attr;
625        *search_attr_from_match = shl != search_hl;
626      }
627      area_highlighting = true;
628    }
629    if (shl != search_hl && cur != NULL) {
630      cur = cur->mit_next;
631    }
632  }
633  return area_highlighting;
634}
635
636/// For a position in a line: Check for start/end of 'hlsearch' and other
637/// matches.
638/// After end, check for start/end of next match.
639/// When another match, have to check for start again.
640/// Watch out for matching an empty string!
641/// "on_last_col" is set to true with non-zero search_attr and the next column
642/// is endcol.
643/// Return the updated search_attr.
644int update_search_hl(win_T *wp, linenr_T lnum, colnr_T col, char **line, match_T *search_hl,
645                     int *has_match_conc, int *match_conc, bool lcs_eol_todo, bool *on_last_col,
646                     bool *search_attr_from_match)
647{
648  matchitem_T *cur = wp->w_match_head;  // points to the match list
649  match_T *shl;                     // points to search_hl or a match
650  bool shl_flag = false;        // flag to indicate whether search_hl
651                                // has been processed or not
652  int search_attr = 0;
653
654  // Do this for 'search_hl' and the match list (ordered by priority).
655  while (cur != NULL || !shl_flag) {
656    if (!shl_flag
657        && (cur == NULL || cur->mit_priority > SEARCH_HL_PRIORITY)) {
658      shl = search_hl;
659      shl_flag = true;
660    } else {
661      shl = &cur->mit_hl;
662    }
663    if (cur != NULL) {
664      cur->mit_pos_cur = 0;
665    }
666    bool pos_inprogress = true;  // mark that a position match search is
667                                 // in progress
668    while (shl->rm.regprog != NULL
669           || (cur != NULL && pos_inprogress)) {
670      if (shl->startcol != MAXCOL
671          && col >= shl->startcol
672          && col < shl->endcol) {
673        int next_col = col + utfc_ptr2len(*line + col);
674
675        if (shl->endcol < next_col) {
676          shl->endcol = next_col;
677        }
678        // Highlight the match were the cursor is using the CurSearch
679        // group.
680        if (shl == search_hl && shl->has_cursor) {
681          shl->attr_cur = win_hl_attr(wp, HLF_LC);
682          if (shl->attr_cur != shl->attr) {
683            search_hl_has_cursor_lnum = lnum;
684          }
685        } else {
686          shl->attr_cur = shl->attr;
687        }
688        // Match with the "Conceal" group results in hiding
689        // the match.
690        if (cur != NULL
691            && shl != search_hl
692            && syn_name2id("Conceal") == cur->mit_hlg_id) {
693          *has_match_conc = col == shl->startcol ? 2 : 1;
694          *match_conc = cur->mit_conceal_char;
695        } else {
696          *has_match_conc = 0;
697        }
698      } else if (col == shl->endcol) {
699        shl->attr_cur = 0;
700
701        next_search_hl(wp, search_hl, shl, lnum, col,
702                       shl == search_hl ? NULL : cur);
703        pos_inprogress = !(cur == NULL || cur->mit_pos_cur == 0);
704
705        // Need to get the line again, a multi-line regexp
706        // may have made it invalid.
707        *line = ml_get_buf(wp->w_buffer, lnum);
708
709        if (shl->lnum == lnum) {
710          shl->startcol = shl->rm.startpos[0].col;
711          if (shl->rm.endpos[0].lnum == 0) {
712            shl->endcol = shl->rm.endpos[0].col;
713          } else {
714            shl->endcol = MAXCOL;
715          }
716
717          // check if the cursor is in the match
718          if (shl == search_hl) {
719            check_cur_search_hl(wp, shl);
720          }
721
722          if (shl->startcol == shl->endcol) {
723            // highlight empty match, try again after it
724            char *p = *line + shl->endcol;
725
726            if (*p == NUL) {
727              shl->endcol++;
728            } else {
729              shl->endcol += utfc_ptr2len(p);
730            }
731          }
732
733          // Loop to check if the match starts at the
734          // current position
735          continue;
736        }
737      }
738      break;
739    }
740    if (shl != search_hl && cur != NULL) {
741      cur = cur->mit_next;
742    }
743  }
744
745  // Use attributes from match with highest priority among 'search_hl' and
746  // the match list.
747  *search_attr_from_match = false;
748  search_attr = search_hl->attr_cur;
749  cur = wp->w_match_head;
750  shl_flag = false;
751  while (cur != NULL || !shl_flag) {
752    if (!shl_flag
753        && (cur == NULL || cur->mit_priority > SEARCH_HL_PRIORITY)) {
754      shl = search_hl;
755      shl_flag = true;
756    } else {
757      shl = &cur->mit_hl;
758    }
759    if (shl->attr_cur != 0) {
760      search_attr = shl->attr_cur;
761      *on_last_col = col + 1 >= shl->endcol;
762      *search_attr_from_match = shl != search_hl;
763    }
764    if (shl != search_hl && cur != NULL) {
765      cur = cur->mit_next;
766    }
767  }
768  // Only highlight one character after the last column.
769  if (*(*line + col) == NUL && (wp->w_p_list && !lcs_eol_todo)) {
770    search_attr = 0;
771  }
772  return search_attr;
773}
774
775bool get_prevcol_hl_flag(win_T *wp, match_T *search_hl, colnr_T curcol)
776{
777  colnr_T prevcol = curcol;
778
779  // we're not really at that column when skipping some text
780  if ((wp->w_p_wrap ? wp->w_skipcol : wp->w_leftcol) > prevcol) {
781    prevcol++;
782  }
783
784  // Highlight a character after the end of the line if the match started
785  // at the end of the line or when the match continues in the next line
786  // (match includes the line break).
787  if (!search_hl->is_addpos && (prevcol == search_hl->startcol
788                                || (prevcol > search_hl->startcol
789                                    && search_hl->endcol == MAXCOL))) {
790    return true;
791  }
792  matchitem_T *cur = wp->w_match_head;  // points to the match list
793  while (cur != NULL) {
794    if (!cur->mit_hl.is_addpos && (prevcol == cur->mit_hl.startcol
795                                   || (prevcol > cur->mit_hl.startcol
796                                       && cur->mit_hl.endcol == MAXCOL))) {
797      return true;
798    }
799    cur = cur->mit_next;
800  }
801
802  return false;
803}
804
805/// Get highlighting for the char after the text in "char_attr" from 'hlsearch'
806/// or match highlighting.
807void get_search_match_hl(win_T *wp, match_T *search_hl, colnr_T col, int *char_attr)
808{
809  matchitem_T *cur = wp->w_match_head;  // points to the match list
810  match_T *shl;                     // points to search_hl or a match
811  bool shl_flag = false;        // flag to indicate whether search_hl
812                                // has been processed or not
813
814  while (cur != NULL || !shl_flag) {
815    if (!shl_flag
816        && (cur == NULL || cur->mit_priority > SEARCH_HL_PRIORITY)) {
817      shl = search_hl;
818      shl_flag = true;
819    } else {
820      shl = &cur->mit_hl;
821    }
822    if (col - 1 == shl->startcol
823        && (shl == search_hl || !shl->is_addpos)) {
824      *char_attr = shl->attr;
825    }
826    if (shl != search_hl && cur != NULL) {
827      cur = cur->mit_next;
828    }
829  }
830}
831
832static int matchadd_dict_arg(typval_T *tv, const char **conceal_char, win_T **win)
833{
834  dictitem_T *di;
835
836  if (tv->v_type != VAR_DICT) {
837    emsg(_(e_dictreq));
838    return FAIL;
839  }
840
841  if ((di = tv_dict_find(tv->vval.v_dict, S_LEN("conceal"))) != NULL) {
842    *conceal_char = tv_get_string(&di->di_tv);
843  }
844
845  if ((di = tv_dict_find(tv->vval.v_dict, S_LEN("window"))) == NULL) {
846    return OK;
847  }
848
849  *win = find_win_by_nr_or_id(&di->di_tv);
850  if (*win == NULL) {
851    emsg(_(e_invalwindow));
852    return FAIL;
853  }
854
855  return OK;
856}
857
858/// "clearmatches()" function
859void f_clearmatches(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
860{
861  win_T *win = get_optional_window(argvars, 0);
862
863  if (win != NULL) {
864    clear_matches(win);
865  }
866}
867
868/// "getmatches()" function
869void f_getmatches(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
870{
871  win_T *win = get_optional_window(argvars, 0);
872
873  tv_list_alloc_ret(rettv, kListLenMayKnow);
874  if (win == NULL) {
875    return;
876  }
877
878  matchitem_T *cur = win->w_match_head;
879  while (cur != NULL) {
880    dict_T *dict = tv_dict_alloc();
881    if (cur->mit_match.regprog == NULL) {
882      // match added with matchaddpos()
883      for (int i = 0; i < cur->mit_pos_count; i++) {
884        llpos_T *llpos;
885        char buf[30];  // use 30 to avoid compiler warning
886
887        llpos = &cur->mit_pos_array[i];
888        if (llpos->lnum == 0) {
889          break;
890        }
891        list_T *const l = tv_list_alloc(1 + (llpos->col > 0 ? 2 : 0));
892        tv_list_append_number(l, (varnumber_T)llpos->lnum);
893        if (llpos->col > 0) {
894          tv_list_append_number(l, (varnumber_T)llpos->col);
895          tv_list_append_number(l, (varnumber_T)llpos->len);
896        }
897        int len = snprintf(buf, sizeof(buf), "pos%d", i + 1);
898        assert((size_t)len < sizeof(buf));
899        tv_dict_add_list(dict, buf, (size_t)len, l);
900      }
901    } else {
902      tv_dict_add_str(dict, S_LEN("pattern"), cur->mit_pattern);
903    }
904    tv_dict_add_str(dict, S_LEN("group"), syn_id2name(cur->mit_hlg_id));
905    tv_dict_add_nr(dict, S_LEN("priority"), (varnumber_T)cur->mit_priority);
906    tv_dict_add_nr(dict, S_LEN("id"), (varnumber_T)cur->mit_id);
907
908    if (cur->mit_conceal_char) {
909      char buf[MB_MAXCHAR + 1];
910      int buflen = utf_char2bytes(cur->mit_conceal_char, buf);
911      buf[buflen] = NUL;
912      tv_dict_add_str_len(dict, S_LEN("conceal"), buf, buflen);
913    }
914
915    tv_list_append_dict(rettv->vval.v_list, dict);
916    cur = cur->mit_next;
917  }
918}
919
920/// "setmatches()" function
921void f_setmatches(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
922{
923  dict_T *d;
924  list_T *s = NULL;
925  win_T *win = get_optional_window(argvars, 1);
926
927  rettv->vval.v_number = -1;
928  if (argvars[0].v_type != VAR_LIST) {
929    emsg(_(e_listreq));
930    return;
931  }
932  if (win == NULL) {
933    return;
934  }
935
936  list_T *const l = argvars[0].vval.v_list;
937  // To some extent make sure that we are dealing with a list from
938  // "getmatches()".
939  int li_idx = 0;
940  TV_LIST_ITER_CONST(l, li, {
941    if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT
942        || (d = TV_LIST_ITEM_TV(li)->vval.v_dict) == NULL) {
943      semsg(_("E474: List item %d is either not a dictionary "
944              "or an empty one"), li_idx);
945      return;
946    }
947    if (!(tv_dict_find(d, S_LEN("group")) != NULL
948          && (tv_dict_find(d, S_LEN("pattern")) != NULL
949              || tv_dict_find(d, S_LEN("pos1")) != NULL)
950          && tv_dict_find(d, S_LEN("priority")) != NULL
951          && tv_dict_find(d, S_LEN("id")) != NULL)) {
952      semsg(_("E474: List item %d is missing one of the required keys"),
953            li_idx);
954      return;
955    }
956    li_idx++;
957  });
958
959  clear_matches(win);
960  bool match_add_failed = false;
961  TV_LIST_ITER_CONST(l, li, {
962    int i = 0;
963
964    d = TV_LIST_ITEM_TV(li)->vval.v_dict;
965    dictitem_T *const di = tv_dict_find(d, S_LEN("pattern"));
966    if (di == NULL) {
967      if (s == NULL) {
968        s = tv_list_alloc(9);
969        tv_list_ref(s);
970      }
971
972      // match from matchaddpos()
973      for (i = 1; i < 9; i++) {
974        char buf[30];  // use 30 to avoid compiler warning
975        snprintf(buf, sizeof(buf), "pos%d", i);
976        dictitem_T *const pos_di = tv_dict_find(d, buf, -1);
977        if (pos_di != NULL) {
978          if (pos_di->di_tv.v_type != VAR_LIST) {
979            tv_list_unref(s);
980            return;
981          }
982
983          tv_list_append_tv(s, &pos_di->di_tv);
984        } else {
985          break;
986        }
987      }
988    }
989
990    // Note: there are three number buffers involved:
991    // - group_buf below.
992    // - numbuf in tv_dict_get_string().
993    // - mybuf in tv_get_string().
994    //
995    // If you change this code make sure that buffers will not get
996    // accidentally reused.
997    char group_buf[NUMBUFLEN];
998    const char *const group = tv_dict_get_string_buf(d, "group", group_buf);
999    const int priority = (int)tv_dict_get_number(d, "priority");
1000    const int id = (int)tv_dict_get_number(d, "id");
1001    dictitem_T *const conceal_di = tv_dict_find(d, S_LEN("conceal"));
1002    const char *const conceal = (conceal_di != NULL
1003                                 ? tv_get_string(&conceal_di->di_tv)
1004                                 : NULL);
1005    if (i == 0) {
1006      if (match_add(win, group,
1007                    tv_dict_get_string(d, "pattern", false),
1008                    priority, id, NULL, conceal) != id) {
1009        match_add_failed = true;
1010      }
1011    } else {
1012      if (match_add(win, group, NULL, priority, id, s, conceal) != id) {
1013        match_add_failed = true;
1014      }
1015      tv_list_unref(s);
1016      s = NULL;
1017    }
1018  });
1019  if (!match_add_failed) {
1020    rettv->vval.v_number = 0;
1021  }
1022}
1023
1024/// "matchadd()" function
1025void f_matchadd(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1026{
1027  char grpbuf[NUMBUFLEN];
1028  char patbuf[NUMBUFLEN];
1029  // group
1030  const char *const grp = tv_get_string_buf_chk(&argvars[0], grpbuf);
1031  // pattern
1032  const char *const pat = tv_get_string_buf_chk(&argvars[1], patbuf);
1033  // default priority
1034  int prio = 10;
1035  int id = -1;
1036  bool error = false;
1037  const char *conceal_char = NULL;
1038  win_T *win = curwin;
1039
1040  rettv->vval.v_number = -1;
1041
1042  if (grp == NULL || pat == NULL) {
1043    return;
1044  }
1045  if (argvars[2].v_type != VAR_UNKNOWN) {
1046    prio = (int)tv_get_number_chk(&argvars[2], &error);
1047    if (argvars[3].v_type != VAR_UNKNOWN) {
1048      id = (int)tv_get_number_chk(&argvars[3], &error);
1049      if (argvars[4].v_type != VAR_UNKNOWN
1050          && matchadd_dict_arg(&argvars[4], &conceal_char, &win) == FAIL) {
1051        return;
1052      }
1053    }
1054  }
1055  if (error) {
1056    return;
1057  }
1058  if (id >= 1 && id <= 3) {
1059    semsg(_("E798: ID is reserved for \":match\": %d"), id);
1060    return;
1061  }
1062
1063  rettv->vval.v_number = match_add(win, grp, pat, prio, id, NULL, conceal_char);
1064}
1065
1066/// "matchaddpo()" function
1067void f_matchaddpos(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1068{
1069  rettv->vval.v_number = -1;
1070
1071  char buf[NUMBUFLEN];
1072  const char *const group = tv_get_string_buf_chk(&argvars[0], buf);
1073  if (group == NULL) {
1074    return;
1075  }
1076
1077  if (argvars[1].v_type != VAR_LIST) {
1078    semsg(_(e_listarg), "matchaddpos()");
1079    return;
1080  }
1081
1082  list_T *l;
1083  l = argvars[1].vval.v_list;
1084  if (tv_list_len(l) == 0) {
1085    return;
1086  }
1087
1088  bool error = false;
1089  int prio = 10;
1090  int id = -1;
1091  const char *conceal_char = NULL;
1092  win_T *win = curwin;
1093
1094  if (argvars[2].v_type != VAR_UNKNOWN) {
1095    prio = (int)tv_get_number_chk(&argvars[2], &error);
1096    if (argvars[3].v_type != VAR_UNKNOWN) {
1097      id = (int)tv_get_number_chk(&argvars[3], &error);
1098      if (argvars[4].v_type != VAR_UNKNOWN
1099          && matchadd_dict_arg(&argvars[4], &conceal_char, &win) == FAIL) {
1100        return;
1101      }
1102    }
1103  }
1104  if (error == true) {
1105    return;
1106  }
1107
1108  // id == 3 is ok because matchaddpos() is supposed to substitute :3match
1109  if (id == 1 || id == 2) {
1110    semsg(_("E798: ID is reserved for \"match\": %d"), id);
1111    return;
1112  }
1113
1114  rettv->vval.v_number = match_add(win, group, NULL, prio, id, l, conceal_char);
1115}
1116
1117/// "matcharg()" function
1118void f_matcharg(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1119{
1120  const int id = (int)tv_get_number(&argvars[0]);
1121
1122  tv_list_alloc_ret(rettv, (id >= 1 && id <= 3
1123                            ? 2
1124                            : 0));
1125
1126  if (id >= 1 && id <= 3) {
1127    matchitem_T *const m = get_match(curwin, id);
1128
1129    if (m != NULL) {
1130      tv_list_append_string(rettv->vval.v_list, syn_id2name(m->mit_hlg_id), -1);
1131      tv_list_append_string(rettv->vval.v_list, m->mit_pattern, -1);
1132    } else {
1133      tv_list_append_string(rettv->vval.v_list, NULL, 0);
1134      tv_list_append_string(rettv->vval.v_list, NULL, 0);
1135    }
1136  }
1137}
1138
1139/// "matchdelete()" function
1140void f_matchdelete(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
1141{
1142  win_T *win = get_optional_window(argvars, 1);
1143  if (win == NULL) {
1144    rettv->vval.v_number = -1;
1145  } else {
1146    rettv->vval.v_number = match_delete(win,
1147                                        (int)tv_get_number(&argvars[0]), true);
1148  }
1149}
1150
1151/// ":[N]match {group} {pattern}"
1152/// Sets nextcmd to the start of the next command, if any.  Also called when
1153/// skipping commands to find the next command.
1154void ex_match(exarg_T *eap)
1155{
1156  char *g = NULL;
1157  char *end;
1158  int id;
1159
1160  if (eap->line2 <= 3) {
1161    id = (int)eap->line2;
1162  } else {
1163    emsg(e_invcmd);
1164    return;
1165  }
1166
1167  // First clear any old pattern.
1168  if (!eap->skip) {
1169    match_delete(curwin, id, false);
1170  }
1171
1172  if (ends_excmd(*eap->arg)) {
1173    end = eap->arg;
1174  } else if ((STRNICMP(eap->arg, "none", 4) == 0
1175              && (ascii_iswhite(eap->arg[4]) || ends_excmd(eap->arg[4])))) {
1176    end = eap->arg + 4;
1177  } else {
1178    char *p = skiptowhite(eap->arg);
1179    if (!eap->skip) {
1180      g = xmemdupz(eap->arg, (size_t)(p - eap->arg));
1181    }
1182    p = skipwhite(p);
1183    if (*p == NUL) {
1184      // There must be two arguments.
1185      xfree(g);
1186      semsg(_(e_invarg2), eap->arg);
1187      return;
1188    }
1189    end = skip_regexp(p + 1, *p, true);
1190    if (!eap->skip) {
1191      if (*end != NUL && !ends_excmd(*skipwhite(end + 1))) {
1192        xfree(g);
1193        eap->errmsg = ex_errmsg(e_trailing_arg, end);
1194        return;
1195      }
1196      if (*end != *p) {
1197        xfree(g);
1198        semsg(_(e_invarg2), p);
1199        return;
1200      }
1201
1202      int c = (uint8_t)(*end);
1203      *end = NUL;
1204      match_add(curwin, g, p + 1, 10, id, NULL, NULL);
1205      xfree(g);
1206      *end = (char)c;
1207    }
1208  }
1209  eap->nextcmd = find_nextcmd(end);
1210}