robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
105.2 KiB3410 linesraw
1// Code to handle tags and the tag stack
2
3#include <assert.h>
4#include <ctype.h>
5#include <inttypes.h>
6#include <stdbool.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10
11#include "nvim/ascii_defs.h"
12#include "nvim/autocmd.h"
13#include "nvim/autocmd_defs.h"
14#include "nvim/buffer.h"
15#include "nvim/buffer_defs.h"
16#include "nvim/charset.h"
17#include "nvim/cmdexpand.h"
18#include "nvim/cmdexpand_defs.h"
19#include "nvim/cursor.h"
20#include "nvim/dialog.h"
21#include "nvim/drawscreen.h"
22#include "nvim/errors.h"
23#include "nvim/eval.h"
24#include "nvim/eval/typval.h"
25#include "nvim/eval/vars.h"
26#include "nvim/ex_cmds.h"
27#include "nvim/ex_cmds_defs.h"
28#include "nvim/ex_docmd.h"
29#include "nvim/file_search.h"
30#include "nvim/fileio.h"
31#include "nvim/fold.h"
32#include "nvim/garray.h"
33#include "nvim/garray_defs.h"
34#include "nvim/gettext_defs.h"
35#include "nvim/globals.h"
36#include "nvim/hashtab.h"
37#include "nvim/hashtab_defs.h"
38#include "nvim/help.h"
39#include "nvim/highlight_defs.h"
40#include "nvim/insexpand.h"
41#include "nvim/lua/executor.h"
42#include "nvim/macros_defs.h"
43#include "nvim/mark.h"
44#include "nvim/mark_defs.h"
45#include "nvim/mbyte.h"
46#include "nvim/mbyte_defs.h"
47#include "nvim/memory.h"
48#include "nvim/message.h"
49#include "nvim/move.h"
50#include "nvim/option.h"
51#include "nvim/option_defs.h"
52#include "nvim/option_vars.h"
53#include "nvim/optionstr.h"
54#include "nvim/os/fs.h"
55#include "nvim/os/input.h"
56#include "nvim/os/os_defs.h"
57#include "nvim/os/time.h"
58#include "nvim/path.h"
59#include "nvim/pos_defs.h"
60#include "nvim/quickfix.h"
61#include "nvim/regexp.h"
62#include "nvim/regexp_defs.h"
63#include "nvim/runtime.h"
64#include "nvim/search.h"
65#include "nvim/state_defs.h"
66#include "nvim/strings.h"
67#include "nvim/tag.h"
68#include "nvim/types_defs.h"
69#include "nvim/ui.h"
70#include "nvim/vim_defs.h"
71#include "nvim/window.h"
72
73// Structure to hold pointers to various items in a tag line.
74typedef struct {
75  // filled in by parse_tag_line():
76  char *tagname;        // start of tag name (skip "file:")
77  char *tagname_end;    // char after tag name
78  char *fname;          // first char of file name
79  char *fname_end;      // char after file name
80  char *command;        // first char of command
81  // filled in by parse_match():
82  char *command_end;    // first char after command
83  char *tag_fname;      // file name of the tags file. This is used
84  // when 'tr' is set.
85  char *tagkind;          // "kind:" value
86  char *tagkind_end;      // end of tagkind
87  char *user_data;        // user_data string
88  char *user_data_end;    // end of user_data
89  linenr_T tagline;       // "line:" value
90} tagptrs_T;
91
92// Structure to hold info about the tag pattern being used.
93typedef struct {
94  char *pat;            // the pattern
95  int len;              // length of pat[]
96  char *head;           // start of pattern head
97  int headlen;          // length of head[]
98  regmatch_T regmatch;  // regexp program, may be NULL
99} pat_T;
100
101// The matching tags are first stored in one of the hash tables.  In
102// which one depends on the priority of the match.
103// ht_match[] is used to find duplicates, ga_match[] to keep them in sequence.
104// At the end, the matches from ga_match[] are concatenated, to make a list
105// sorted on priority.
106enum {
107  MT_ST_CUR = 0,  // static match in current file
108  MT_GL_CUR = 1,  // global match in current file
109  MT_GL_OTH = 2,  // global match in other file
110  MT_ST_OTH = 3,  // static match in other file
111  MT_IC_OFF = 4,  // add for icase match
112  MT_RE_OFF = 8,  // add for regexp match
113  MT_MASK = 7,    // mask for printing priority
114  MT_COUNT = 16,
115};
116
117static char *mt_names[MT_COUNT/2] =
118{ "FSC", "F C", "F  ", "FS ", " SC", "  C", "   ", " S " };
119
120#define NOTAGFILE       99              // return value for jumpto_tag
121static char *nofile_fname = NULL;       // fname for NOTAGFILE error
122
123/// Classification of a "cmd" value returned by a tagfunc.
124typedef enum {
125  TAGCMD_INVALID,  ///< cannot be stored in a tag line
126  TAGCMD_ADDRESS,  ///< line number or /pat/ or ?pat? (no "|" needed)
127  TAGCMD_GENERIC,  ///< any other Ex command: needs a "|" terminator
128} tagcmd_T;
129
130/// Return values used when reading lines from a tags file.
131typedef enum {
132  TAGS_READ_SUCCESS = 1,
133  TAGS_READ_EOF,
134  TAGS_READ_IGNORE,
135} tags_read_status_T;
136
137/// States used during a tags search
138typedef enum {
139  TS_START,         ///< at start of file
140  TS_LINEAR,        ///< linear searching forward, till EOF
141  TS_BINARY,        ///< binary searching
142  TS_SKIP_BACK,     ///< skipping backwards
143  TS_STEP_FORWARD,  ///< stepping forwards
144} tagsearch_state_T;
145
146/// Binary search file offsets in a tags file
147typedef struct {
148  off_T low_offset;        ///< offset for first char of first line that
149                           ///< could match
150  off_T high_offset;       ///< offset of char after last line that could
151                           ///< match
152  off_T curr_offset;       ///< Current file offset in search range
153  off_T curr_offset_used;  ///< curr_offset used when skipping back
154  off_T match_offset;      ///< Where the binary search found a tag
155  int low_char;            ///< first char at low_offset
156  int high_char;           ///< first char at high_offset
157} tagsearch_info_T;
158
159/// Return values used when matching tags against a pattern.
160typedef enum {
161  TAG_MATCH_SUCCESS = 1,
162  TAG_MATCH_FAIL,
163  TAG_MATCH_STOP,
164  TAG_MATCH_NEXT,
165} tagmatch_status_T;
166
167/// Arguments used for matching tags read from a tags file against a pattern.
168typedef struct {
169  int matchoff;      ///< tag match offset
170  bool match_re;     ///< true if the tag matches a regexp
171  bool match_no_ic;  ///< true if the tag matches with case
172  bool has_re;       ///< regular expression used
173  bool sortic;       ///< tags file sorted ignoring case (foldcase)
174  bool sort_error;   ///< tags file not sorted
175} findtags_match_args_T;
176
177/// State information used during a tag search
178typedef struct {
179  tagsearch_state_T state;       ///< tag search state
180  bool stop_searching;           ///< stop when match found or error
181  pat_T *orgpat;                 ///< holds unconverted pattern info
182  char *lbuf;                    ///< line buffer
183  int lbuf_size;                 ///< length of lbuf
184  char *tag_fname;               ///< name of the tag file
185  FILE *fp;                      ///< current tags file pointer
186  int flags;                     ///< flags used for tag search
187  int tag_file_sorted;           ///< !_TAG_FILE_SORTED value
188  bool get_searchpat;            ///< used for 'showfulltag'
189  bool help_only;                ///< only search for help tags
190  bool did_open;                 ///< did open a tag file
191  int mincount;                  ///< MAXCOL: find all matches
192                                 ///< other: minimal number of matches
193  bool linear;                   ///< do a linear search
194  vimconv_T vimconv;
195  char help_lang[3];             ///< lang of current tags file
196  int help_pri;                  ///< help language priority
197  char *help_lang_find;          ///< lang to be found
198  bool is_txt;                   ///< flag of file extension
199  int match_count;               ///< number of matches found
200  garray_T ga_match[MT_COUNT];   ///< stores matches in sequence
201  hashtab_T ht_match[MT_COUNT];  ///< stores matches by key
202} findtags_state_T;
203
204#include "tag.c.generated.h"
205
206static const char e_tag_stack_empty[]
207  = N_("E73: Tag stack empty");
208static const char e_tag_not_found_str[]
209  = N_("E426: Tag not found: %s");
210static const char e_at_bottom_of_tag_stack[]
211  = N_("E555: At bottom of tag stack");
212static const char e_at_top_of_tag_stack[]
213  = N_("E556: At top of tag stack");
214static const char e_cannot_modify_tag_stack_within_tagfunc[]
215  = N_("E986: Cannot modify the tag stack within tagfunc");
216static const char e_invalid_return_value_from_tagfunc[]
217  = N_("E987: Invalid return value from tagfunc");
218static const char e_window_unexpectedly_close_while_searching_for_tags[]
219  = N_("E1299: Window unexpectedly closed while searching for tags");
220
221static char *tagmatchname = NULL;   // name of last used tag
222
223// Tag for preview window is remembered separately, to avoid messing up the
224// normal tagstack.
225static taggy_T ptag_entry = { NULL, INIT_FMARK, 0, 0, NULL };
226
227static bool tfu_in_use = false;  // disallow recursive call of tagfunc
228
229// Used instead of NUL to separate tag fields in the growarrays.
230#define TAG_SEP 0x02
231
232#ifdef EXITFREE
233void free_tagfunc_option(void)
234{
235  callback_free(&p_tfu);
236}
237#endif
238
239/// Mark the global 'tagfunc' callback with "copyID" so that it is not garbage
240/// collected.
241bool set_ref_in_tagfunc(int copyID)
242{
243  return set_ref_in_callback(&p_tfu, copyID, NULL, NULL);
244}
245
246/// Jump to tag; handling of tag commands and tag stack
247///
248/// *tag != NUL: ":tag {tag}", jump to new tag, add to tag stack
249///
250/// type == DT_TAG:      ":tag [tag]", jump to newer position or same tag again
251/// type == DT_HELP:     like DT_TAG, but don't use regexp.
252/// type == DT_POP:      ":pop" or CTRL-T, jump to old position
253/// type == DT_NEXT:     jump to next match of same tag
254/// type == DT_PREV:     jump to previous match of same tag
255/// type == DT_FIRST:    jump to first match of same tag
256/// type == DT_LAST:     jump to last match of same tag
257/// type == DT_SELECT:   ":tselect [tag]", select tag from a list of all matches
258/// type == DT_JUMP:     ":tjump [tag]", jump to tag or select tag from a list
259/// type == DT_LTAG:     use location list for displaying tag matches
260/// type == DT_FREE:     free cached matches
261///
262/// @param eap  excmd args (forwarded to Lua); may be NULL when the caller is not an excmd (e.g. `<C-T>`).
263/// @param tag  tag (pattern) to jump to
264/// @param forceit  :ta with !
265/// @param verbose  print "tag not found" message
266void do_tag(exarg_T *eap, char *tag, int type, int count, int forceit, bool verbose)
267{
268  taggy_T *tagstack = curwin->w_tagstack;
269  int tagstackidx = curwin->w_tagstackidx;
270  int tagstacklen = curwin->w_tagstacklen;
271  int cur_match = 0;
272  int cur_fnum = curbuf->b_fnum;
273  int oldtagstackidx = tagstackidx;
274  int prevtagstackidx = tagstackidx;
275  bool new_tag = false;
276  bool no_regexp = false;
277  int error_cur_match = 0;
278  bool save_pos = false;
279  fmark_T saved_fmark;
280  int new_num_matches;
281  char **new_matches;
282  bool use_tagstack;
283  bool skip_msg = false;
284  char *buf_ffname = curbuf->b_ffname;  // name for priority computation
285  bool use_tfu = true;
286  char *tofree = NULL;
287
288  // remember the matches for the last used tag
289  static int num_matches = 0;
290  static int max_num_matches = 0;             // limit used for match search
291  static char **matches = NULL;
292  static int flags;
293
294#ifdef EXITFREE
295  if (type == DT_FREE) {
296    // remove the list of matches
297    FreeWild(num_matches, matches);
298    num_matches = 0;
299    return;
300  }
301#endif
302
303  if (tfu_in_use) {
304    emsg(_(e_cannot_modify_tag_stack_within_tagfunc));
305    return;
306  }
307
308  if (postponed_split == 0 && !check_can_set_curbuf_forceit(forceit)) {
309    return;
310  }
311
312  if (type == DT_HELP) {
313    type = DT_TAG;
314    no_regexp = true;
315    use_tfu = false;
316  }
317
318  int prev_num_matches = num_matches;
319  free_string_option(nofile_fname);
320  nofile_fname = NULL;
321
322  clearpos(&saved_fmark.mark);          // shutup gcc 4.0
323  saved_fmark.fnum = 0;
324  saved_fmark.view = (fmarkv_T)INIT_FMARKV;
325
326  // Don't add a tag to the tagstack if 'tagstack' has been reset.
327  assert(tag != NULL);
328  if (!p_tgst && *tag != NUL) {
329    use_tagstack = false;
330    new_tag = true;
331    if (g_do_tagpreview != 0) {
332      tagstack_clear_entry(&ptag_entry);
333      ptag_entry.tagname = xstrdup(tag);
334    }
335  } else {
336    if (g_do_tagpreview != 0) {
337      use_tagstack = false;
338    } else {
339      use_tagstack = true;
340    }
341
342    // new pattern, add to the tag stack
343    if (*tag != NUL
344        && (type == DT_TAG || type == DT_SELECT || type == DT_JUMP
345            || type == DT_LTAG)) {
346      if (g_do_tagpreview != 0) {
347        if (ptag_entry.tagname != NULL
348            && strcmp(ptag_entry.tagname, tag) == 0) {
349          // Jumping to same tag: keep the current match, so that
350          // the CursorHold autocommand example works.
351          cur_match = ptag_entry.cur_match;
352          cur_fnum = ptag_entry.cur_fnum;
353        } else {
354          tagstack_clear_entry(&ptag_entry);
355          ptag_entry.tagname = xstrdup(tag);
356        }
357      } else {
358        // If the last used entry is not at the top, delete all tag
359        // stack entries above it.
360        while (tagstackidx < tagstacklen) {
361          tagstack_clear_entry(&tagstack[--tagstacklen]);
362        }
363
364        // if the tagstack is full: remove oldest entry
365        if (++tagstacklen > TAGSTACKSIZE) {
366          tagstacklen = TAGSTACKSIZE;
367          tagstack_clear_entry(&tagstack[0]);
368          for (int i = 1; i < tagstacklen; i++) {
369            tagstack[i - 1] = tagstack[i];
370          }
371          tagstack[--tagstackidx].user_data = NULL;
372        }
373
374        // put the tag name in the tag stack
375        tagstack[tagstackidx].tagname = xstrdup(tag);
376
377        curwin->w_tagstacklen = tagstacklen;
378
379        save_pos = true;                // save the cursor position below
380      }
381
382      new_tag = true;
383    } else {
384      if (g_do_tagpreview != 0 ? ptag_entry.tagname == NULL
385                               : tagstacklen == 0) {
386        // empty stack
387        emsg(_(e_tag_stack_empty));
388        goto end_do_tag;
389      }
390
391      if (type == DT_POP) {             // go to older position
392        const bool old_KeyTyped = KeyTyped;
393        if ((tagstackidx -= count) < 0) {
394          emsg(_(e_at_bottom_of_tag_stack));
395          if (tagstackidx + count == 0) {
396            // We did [num]^T from the bottom of the stack
397            tagstackidx = 0;
398            goto end_do_tag;
399          }
400          // We weren't at the bottom of the stack, so jump all the
401          // way to the bottom now.
402          tagstackidx = 0;
403        } else if (tagstackidx >= tagstacklen) {        // count == 0?
404          emsg(_(e_at_top_of_tag_stack));
405          goto end_do_tag;
406        }
407
408        // Make a copy of the fmark, autocommands may invalidate the
409        // tagstack before it's used.
410        saved_fmark = tagstack[tagstackidx].fmark;
411        if (saved_fmark.fnum != curbuf->b_fnum) {
412          // Jump to other file. If this fails (e.g. because the
413          // file was changed) keep original position in tag stack.
414          if (buflist_getfile(saved_fmark.fnum, saved_fmark.mark.lnum,
415                              GETF_SETMARK, forceit) == FAIL) {
416            tagstackidx = oldtagstackidx;              // back to old posn
417            goto end_do_tag;
418          }
419          // A BufReadPost autocommand may jump to the '" mark, but
420          // we don't what that here.
421          curwin->w_cursor.lnum = saved_fmark.mark.lnum;
422        } else {
423          setpcmark();
424          curwin->w_cursor.lnum = saved_fmark.mark.lnum;
425        }
426        curwin->w_cursor.col = saved_fmark.mark.col;
427        curwin->w_set_curswant = true;
428        if (jop_flags & kOptJopFlagView) {
429          mark_view_restore(&saved_fmark);
430        }
431        check_cursor(curwin);
432        if ((fdo_flags & kOptFdoFlagTag) && old_KeyTyped) {
433          foldOpenCursor();
434        }
435
436        // remove the old list of matches
437        FreeWild(num_matches, matches);
438        num_matches = 0;
439        tag_freematch();
440        goto end_do_tag;
441      }
442
443      if (type == DT_TAG
444          || type == DT_LTAG) {
445        if (g_do_tagpreview != 0) {
446          cur_match = ptag_entry.cur_match;
447          cur_fnum = ptag_entry.cur_fnum;
448        } else {
449          // ":tag" (no argument): go to newer pattern
450          save_pos = true;              // save the cursor position below
451          if ((tagstackidx += count - 1) >= tagstacklen) {
452            // Beyond the last one, just give an error message and
453            // go to the last one.  Don't store the cursor
454            // position.
455            tagstackidx = tagstacklen - 1;
456            emsg(_(e_at_top_of_tag_stack));
457            save_pos = false;
458          } else if (tagstackidx < 0) {         // must have been count == 0
459            emsg(_(e_at_bottom_of_tag_stack));
460            tagstackidx = 0;
461            goto end_do_tag;
462          }
463          cur_match = tagstack[tagstackidx].cur_match;
464          cur_fnum = tagstack[tagstackidx].cur_fnum;
465        }
466        new_tag = true;
467      } else {                                // go to other matching tag
468        // Save index for when selection is cancelled.
469        prevtagstackidx = tagstackidx;
470
471        if (g_do_tagpreview != 0) {
472          cur_match = ptag_entry.cur_match;
473          cur_fnum = ptag_entry.cur_fnum;
474        } else {
475          if (--tagstackidx < 0) {
476            tagstackidx = 0;
477          }
478          cur_match = tagstack[tagstackidx].cur_match;
479          cur_fnum = tagstack[tagstackidx].cur_fnum;
480        }
481        switch (type) {
482        case DT_FIRST:
483          cur_match = count - 1; break;
484        case DT_SELECT:
485        case DT_JUMP:
486        case DT_LAST:
487          cur_match = MAXCOL - 1; break;
488        case DT_NEXT:
489          cur_match += count; break;
490        case DT_PREV:
491          cur_match -= count; break;
492        }
493        if (cur_match >= MAXCOL) {
494          cur_match = MAXCOL - 1;
495        } else if (cur_match < 0) {
496          emsg(_("E425: Cannot go before first matching tag"));
497          skip_msg = true;
498          cur_match = 0;
499          cur_fnum = curbuf->b_fnum;
500        }
501      }
502    }
503
504    if (g_do_tagpreview != 0) {
505      if (type != DT_SELECT && type != DT_JUMP) {
506        ptag_entry.cur_match = cur_match;
507        ptag_entry.cur_fnum = cur_fnum;
508      }
509    } else {
510      // For ":tag [arg]" or ":tselect" remember position before the jump.
511      saved_fmark = tagstack[tagstackidx].fmark;
512      if (save_pos) {
513        tagstack[tagstackidx].fmark.mark = curwin->w_cursor;
514        tagstack[tagstackidx].fmark.fnum = curbuf->b_fnum;
515        tagstack[tagstackidx].fmark.view = mark_view_make(curwin, curwin->w_cursor);
516      }
517
518      // Curwin will change in the call to jumpto_tag() if ":stag" was
519      // used or an autocommand jumps to another window; store value of
520      // tagstackidx now.
521      curwin->w_tagstackidx = tagstackidx;
522      if (type != DT_SELECT && type != DT_JUMP) {
523        curwin->w_tagstack[tagstackidx].cur_match = cur_match;
524        curwin->w_tagstack[tagstackidx].cur_fnum = cur_fnum;
525      }
526    }
527  }
528
529  // When not using the current buffer get the name of buffer "cur_fnum".
530  // Makes sure that the tag order doesn't change when using a remembered
531  // position for "cur_match".
532  if (cur_fnum != curbuf->b_fnum) {
533    buf_T *buf = buflist_findnr(cur_fnum);
534
535    if (buf != NULL) {
536      buf_ffname = buf->b_ffname;
537    }
538  }
539
540  // Repeat searching for tags, when a file has not been found.
541  while (true) {
542    char *name;
543
544    // When desired match not found yet, try to find it (and others).
545    if (use_tagstack) {
546      // make a copy, the tagstack may change in 'tagfunc'
547      name = xstrdup(tagstack[tagstackidx].tagname);
548      xfree(tofree);
549      tofree = name;
550    } else if (g_do_tagpreview != 0) {
551      name = ptag_entry.tagname;
552    } else {
553      name = tag;
554    }
555    bool other_name = (tagmatchname == NULL || strcmp(tagmatchname, name) != 0);
556    if (new_tag
557        || (cur_match >= num_matches && max_num_matches != MAXCOL)
558        || other_name) {
559      if (other_name) {
560        xfree(tagmatchname);
561        tagmatchname = xstrdup(name);
562      }
563
564      if (type == DT_SELECT || type == DT_JUMP
565          || type == DT_LTAG) {
566        cur_match = MAXCOL - 1;
567      }
568      max_num_matches = type == DT_TAG ? MAXCOL : cur_match + 1;
569
570      // when the argument starts with '/', use it as a regexp
571      if (!no_regexp && *name == '/') {
572        flags = TAG_REGEXP;
573        name++;
574      } else {
575        flags = TAG_NOIC;
576      }
577
578      flags |= verbose ? TAG_VERBOSE : 0;
579      flags |= !use_tfu ? TAG_NO_TAGFUNC : 0;
580
581      if (find_tags(name, &new_num_matches, &new_matches, flags,
582                    max_num_matches, buf_ffname) == OK
583          && new_num_matches < max_num_matches) {
584        max_num_matches = MAXCOL;  // If less than max_num_matches
585                                   // found: all matches found.
586      }
587
588      // A tag function may do anything, which may cause various
589      // information to become invalid.  At least check for the tagstack
590      // to still be the same.
591      if (tagstack != curwin->w_tagstack) {
592        emsg(_(e_window_unexpectedly_close_while_searching_for_tags));
593        FreeWild(new_num_matches, new_matches);
594        break;
595      }
596
597      // If there already were some matches for the same name, move them
598      // to the start.  Avoids that the order changes when using
599      // ":tnext" and jumping to another file.
600      if (!new_tag && !other_name) {
601        int idx = 0;
602        tagptrs_T tagp, tagp2;
603
604        // Find the position of each old match in the new list.  Need
605        // to use parse_match() to find the tag line.
606        for (int j = 0; j < num_matches; j++) {
607          parse_match(matches[j], &tagp);
608          for (int i = idx; i < new_num_matches; i++) {
609            parse_match(new_matches[i], &tagp2);
610            if (strcmp(tagp.tagname, tagp2.tagname) == 0) {
611              char *p = new_matches[i];
612              for (int k = i; k > idx; k--) {
613                new_matches[k] = new_matches[k - 1];
614              }
615              new_matches[idx++] = p;
616              break;
617            }
618          }
619        }
620      }
621      FreeWild(num_matches, matches);
622      num_matches = new_num_matches;
623      matches = new_matches;
624    }
625
626    if (num_matches <= 0) {
627      if (verbose) {
628        semsg(_(e_tag_not_found_str), name);
629      }
630      g_do_tagpreview = 0;
631    } else {
632      if (type == DT_TAG && *tag != NUL) {
633        // If a count is supplied to the ":tag <name>" command, then
634        // jump to count'th matching tag.
635        cur_match = count > 0 ? count - 1 : 0;
636      } else if (type == DT_SELECT || (type == DT_JUMP && num_matches > 1)) {
637        // Hand off to (async) vim.ui.select(). Roll back any pending tagstack changes.
638        select_tag_match(eap, new_tag, use_tagstack, num_matches, matches, name);
639        if (use_tagstack) {
640          tagstack[tagstackidx].fmark = saved_fmark;
641          tagstackidx = prevtagstackidx;
642        }
643        break;
644      } else if (type == DT_LTAG) {
645        if (add_llist_tags(tag, num_matches, matches) == FAIL) {
646          goto end_do_tag;
647        }
648
649        cur_match = 0;                  // Jump to the first tag
650      }
651
652      if (cur_match >= num_matches) {
653        // Avoid giving this error when a file wasn't found and we're
654        // looking for a match in another file, which wasn't found.
655        // There will be an emsg("file doesn't exist") below then.
656        if ((type == DT_NEXT || type == DT_FIRST)
657            && nofile_fname == NULL) {
658          if (num_matches == 1) {
659            emsg(_("E427: There is only one matching tag"));
660          } else {
661            emsg(_("E428: Cannot go beyond last matching tag"));
662          }
663          skip_msg = true;
664        }
665        cur_match = num_matches - 1;
666      }
667      if (use_tagstack) {
668        tagptrs_T tagp2;
669
670        tagstack[tagstackidx].cur_match = cur_match;
671        tagstack[tagstackidx].cur_fnum = cur_fnum;
672
673        // store user-provided data originating from tagfunc
674        if (use_tfu && parse_match(matches[cur_match], &tagp2) == OK
675            && tagp2.user_data) {
676          XFREE_CLEAR(tagstack[tagstackidx].user_data);
677          tagstack[tagstackidx].user_data =
678            xmemdupz(tagp2.user_data, (size_t)(tagp2.user_data_end - tagp2.user_data));
679        }
680
681        tagstackidx++;
682      } else if (g_do_tagpreview != 0) {
683        ptag_entry.cur_match = cur_match;
684        ptag_entry.cur_fnum = cur_fnum;
685      }
686
687      // Only when going to try the next match, report that the previous
688      // file didn't exist.  Otherwise an emsg() is given below.
689      if (nofile_fname != NULL && error_cur_match != cur_match) {
690        smsg(0, _("File \"%s\" does not exist"), nofile_fname);
691      }
692
693      bool ic = (matches[cur_match][0] & MT_IC_OFF);
694      if (type != DT_TAG && type != DT_SELECT && type != DT_JUMP
695          && (num_matches > 1 || ic)
696          && !skip_msg) {
697        // Give an indication of the number of matching tags
698        snprintf(IObuff, sizeof(IObuff), _("tag %d of %d%s"),
699                 cur_match + 1,
700                 num_matches,
701                 max_num_matches != MAXCOL ? _(" or more") : "");
702        if (ic) {
703          xstrlcat(IObuff, _("  Using tag with different case!"), IOSIZE);
704        }
705        if ((num_matches > prev_num_matches || new_tag)
706            && num_matches > 1) {
707          msg(IObuff, ic ? HLF_W : 0);
708          msg_scroll = true;  // Don't overwrite this message.
709        } else {
710          give_warning(IObuff, ic, true);
711        }
712        if (ic && !msg_scrolled && msg_silent == 0) {
713          msg_delay(1007, true);
714        }
715      }
716
717      // Let the SwapExists event know what tag we are jumping to.
718      size_t IObufflen = vim_snprintf_safelen(IObuff, IOSIZE, ":ta %s\r", name);
719      set_vim_var_string(VV_SWAPCOMMAND, IObuff, (ptrdiff_t)IObufflen);
720
721      // Jump to the desired match.
722      int i = jumpto_tag(matches[cur_match], forceit, true);
723
724      set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
725
726      if (i == NOTAGFILE) {
727        // File not found: try again with another matching tag
728        if ((type == DT_PREV && cur_match > 0)
729            || ((type == DT_TAG || type == DT_NEXT
730                 || type == DT_FIRST)
731                && (max_num_matches != MAXCOL
732                    || cur_match < num_matches - 1))) {
733          error_cur_match = cur_match;
734          if (use_tagstack) {
735            tagstackidx--;
736          }
737          if (type == DT_PREV) {
738            cur_match--;
739          } else {
740            type = DT_NEXT;
741            cur_match++;
742          }
743          continue;
744        }
745        semsg(_("E429: File \"%s\" does not exist"), nofile_fname);
746      } else {
747        // We may have jumped to another window, check that
748        // tagstackidx is still valid.
749        if (use_tagstack && tagstackidx > curwin->w_tagstacklen) {
750          tagstackidx = curwin->w_tagstackidx;
751        }
752      }
753    }
754    break;
755  }
756
757end_do_tag:
758  // Only store the new index when using the tagstack and it's valid.
759  if (use_tagstack && tagstackidx <= curwin->w_tagstacklen) {
760    curwin->w_tagstackidx = tagstackidx;
761  }
762  postponed_split = 0;          // don't split next time
763  g_do_tagpreview = 0;          // don't do tag preview next time
764  xfree(tofree);
765}
766
767/// Let the user pick from `matches`. Delegates to (async) `vim.ui.select()`.
768static void select_tag_match(exarg_T *eap, bool new_tag, bool use_tagstack, int num_matches,
769                             char **matches, const char *name)
770{
771  taggy_T *tagstack = curwin->w_tagstack;
772  int tagstackidx = curwin->w_tagstackidx;
773
774  typval_T items_tv;
775  tv_list_alloc_ret(&items_tv, num_matches);
776
777  for (int i = 0; i < num_matches; i++) {
778    os_breakcheck();
779    if (got_int) {
780      tv_clear(&items_tv);
781      return;
782    }
783    tagptrs_T tagp;
784    parse_match(matches[i], &tagp);
785
786    bool cur = !new_tag
787               && ((g_do_tagpreview != 0 && i == ptag_entry.cur_match)
788                   || (use_tagstack && i == tagstack[tagstackidx].cur_match));
789
790    dict_T *d = tv_dict_alloc();
791    tv_dict_add_str_len(d, S_LEN("tag"), tagp.tagname, (int)(tagp.tagname_end - tagp.tagname));
792    tv_dict_add_str(d, S_LEN("pri"), mt_names[matches[i][0] & MT_MASK]);
793    if (tagp.tagkind != NULL) {
794      tv_dict_add_str_len(d, S_LEN("kind"), tagp.tagkind, (int)(tagp.tagkind_end - tagp.tagkind));
795    }
796    char *fname = tag_full_fname(&tagp);
797    tv_dict_add_str(d, S_LEN("file"), fname != NULL ? fname : "");
798    xfree(fname);
799    tv_dict_add_bool(d, S_LEN("cur"), cur ? kBoolVarTrue : kBoolVarFalse);
800
801    typval_T item = { .v_type = VAR_DICT, .vval.v_dict = d };
802    tv_list_append_tv(items_tv.vval.v_list, &item);
803  }
804
805  // Pass items + tag name as a dict via the `extra` slot of nlua_call_excmd. Lua decides whether
806  // to use `:tag` or `:stag` from `eap.name` (e.g. "tselect" vs "stselect").
807  dict_T *extra_d = tv_dict_alloc();
808  tv_dict_add_list(extra_d, S_LEN("items"), items_tv.vval.v_list);
809  items_tv.vval.v_list->lv_refcount++;  // dict keeps a ref
810  tv_dict_add_str(extra_d, S_LEN("tagname"), name);
811  typval_T extra_tv = { .v_type = VAR_DICT, .vval.v_dict = extra_d };
812
813  nlua_call_excmd("vim._core.tag", "select_tag", eap, &cmdmod, &extra_tv);
814
815  tv_clear(&items_tv);
816  tv_clear(&extra_tv);
817}
818
819/// Add the matching tags to the location list for the current
820/// window.
821static int add_llist_tags(char *tag, int num_matches, char **matches)
822{
823  char tag_name[128 + 1];
824  tagptrs_T tagp;
825
826  char *fname = xmalloc(MAXPATHL + 1);
827  char *cmd = xmalloc(CMDBUFFSIZE + 1);
828  list_T *list = tv_list_alloc(0);
829
830  for (int i = 0; i < num_matches; i++) {
831    dict_T *dict;
832
833    parse_match(matches[i], &tagp);
834
835    // Save the tag name
836    int len = MIN((int)(tagp.tagname_end - tagp.tagname), 128);
837    xmemcpyz(tag_name, tagp.tagname, (size_t)len);
838    tag_name[len] = NUL;
839
840    // Save the tag file name
841    char *p = tag_full_fname(&tagp);
842    if (p == NULL) {
843      continue;
844    }
845    xstrlcpy(fname, p, MAXPATHL);
846    XFREE_CLEAR(p);
847
848    // Get the line number or the search pattern used to locate
849    // the tag.
850    linenr_T lnum = 0;
851    if (isdigit((uint8_t)(*tagp.command))) {
852      // Line number is used to locate the tag
853      lnum = atoi(tagp.command);
854    } else {
855      // Search pattern is used to locate the tag
856
857      // Locate the end of the command
858      char *cmd_start = tagp.command;
859      char *cmd_end = tagp.command_end;
860      if (cmd_end == NULL) {
861        for (p = tagp.command;
862             *p && *p != '\r' && *p != '\n'; p++) {}
863        cmd_end = p;
864      }
865
866      // Now, cmd_end points to the character after the
867      // command. Adjust it to point to the last
868      // character of the command.
869      cmd_end--;
870
871      // Skip the '/' and '?' characters at the
872      // beginning and end of the search pattern.
873      if (*cmd_start == '/' || *cmd_start == '?') {
874        cmd_start++;
875      }
876
877      if (*cmd_end == '/' || *cmd_end == '?') {
878        cmd_end--;
879      }
880
881      len = 0;
882      cmd[0] = NUL;
883
884      // If "^" is present in the tag search pattern, then
885      // copy it first.
886      if (*cmd_start == '^') {
887        STRCPY(cmd, "^");
888        cmd_start++;
889        len++;
890      }
891
892      // Precede the tag pattern with \V to make it very
893      // nomagic.
894      strcat(cmd, "\\V");
895      len += 2;
896
897      int cmd_len = MIN((int)(cmd_end - cmd_start + 1), CMDBUFFSIZE - 5);
898      snprintf(cmd + len, (size_t)(CMDBUFFSIZE + 1 - len),
899               "%.*s", cmd_len, cmd_start);
900      len += cmd_len;
901
902      if (cmd[len - 1] == '$') {
903        // Replace '$' at the end of the search pattern
904        // with '\$'
905        cmd[len - 1] = '\\';
906        cmd[len] = '$';
907        len++;
908      }
909
910      cmd[len] = NUL;
911    }
912
913    dict = tv_dict_alloc();
914    tv_list_append_dict(list, dict);
915
916    tv_dict_add_str(dict, S_LEN("text"), tag_name);
917    tv_dict_add_str(dict, S_LEN("filename"), fname);
918    tv_dict_add_nr(dict, S_LEN("lnum"), lnum);
919    if (lnum == 0) {
920      tv_dict_add_str(dict, S_LEN("pattern"), cmd);
921    }
922  }
923
924  vim_snprintf(IObuff, IOSIZE, "ltag %s", tag);
925  set_errorlist(curwin, list, ' ', IObuff, NULL);
926
927  tv_list_free(list);
928  XFREE_CLEAR(fname);
929  XFREE_CLEAR(cmd);
930
931  return OK;
932}
933
934// Free cached tags.
935void tag_freematch(void)
936{
937  XFREE_CLEAR(tagmatchname);
938}
939
940static void taglen_advance(int l)
941{
942  if (l == MAXCOL) {
943    msg_putchar('\n');
944    msg_advance(24);
945  } else {
946    msg_advance(13 + l);
947  }
948}
949
950// Print the tag stack
951void do_tags(exarg_T *eap)
952{
953  taggy_T *tagstack = curwin->w_tagstack;
954  int tagstackidx = curwin->w_tagstackidx;
955  int tagstacklen = curwin->w_tagstacklen;
956
957  // Highlight title
958  msg_puts_title(_("\n  # TO tag         FROM line  in file/text"));
959  for (int i = 0; i < tagstacklen; i++) {
960    if (tagstack[i].tagname != NULL) {
961      char *name = fm_getname(&(tagstack[i].fmark), 30);
962      if (name == NULL) {           // file name not available
963        continue;
964      }
965
966      msg_putchar('\n');
967      vim_snprintf(IObuff, IOSIZE, "%c%2d %2d %-15s %5" PRIdLINENR "  ",
968                   i == tagstackidx ? '>' : ' ',
969                   i + 1,
970                   tagstack[i].cur_match + 1,
971                   tagstack[i].tagname,
972                   tagstack[i].fmark.mark.lnum);
973      msg_outtrans(IObuff, 0, false);
974      msg_outtrans(name, tagstack[i].fmark.fnum == curbuf->b_fnum ? HLF_D : 0, false);
975      xfree(name);
976    }
977  }
978  if (tagstackidx == tagstacklen) {     // idx at top of stack
979    msg_puts("\n>");
980  }
981}
982
983// Compare two strings, for length "len", ignoring case the ASCII way.
984// return 0 for match, < 0 for smaller, > 0 for bigger
985// Make sure case is folded to uppercase in comparison (like for 'sort -f')
986static int tag_strnicmp(char *s1, char *s2, size_t len)
987{
988  while (len > 0) {
989    int i = TOUPPER_ASC((uint8_t)(*s1)) - TOUPPER_ASC((uint8_t)(*s2));
990    if (i != 0) {
991      return i;                         // this character different
992    }
993    if (*s1 == NUL) {
994      break;                            // strings match until NUL
995    }
996    s1++;
997    s2++;
998    len--;
999  }
1000  return 0;                             // strings match
1001}
1002
1003// Extract info from the tag search pattern "pats->pat".
1004static void prepare_pats(pat_T *pats, bool has_re)
1005{
1006  pats->head = pats->pat;
1007  pats->headlen = pats->len;
1008  if (has_re) {
1009    // When the pattern starts with '^' or "\\<", binary searching can be
1010    // used (much faster).
1011    if (pats->pat[0] == '^') {
1012      pats->head = pats->pat + 1;
1013    } else if (pats->pat[0] == '\\' && pats->pat[1] == '<') {
1014      pats->head = pats->pat + 2;
1015    }
1016    if (pats->head == pats->pat) {
1017      pats->headlen = 0;
1018    } else {
1019      for (pats->headlen = 0; pats->head[pats->headlen] != NUL; pats->headlen++) {
1020        if (vim_strchr(p_magic ? ".[~*\\$" : "\\$",
1021                       (uint8_t)pats->head[pats->headlen]) != NULL) {
1022          break;
1023        }
1024      }
1025    }
1026    if (p_tl != 0 && pats->headlen > p_tl) {    // adjust for 'taglength'
1027      pats->headlen = (int)p_tl;
1028    }
1029  }
1030
1031  if (has_re) {
1032    pats->regmatch.regprog = vim_regcomp(pats->pat, p_magic ? RE_MAGIC : 0);
1033  } else {
1034    pats->regmatch.regprog = NULL;
1035  }
1036}
1037
1038/// Classify "cmd" from a tagfunc result (see tagcmd_T), like a tags file
1039/// address, to decide whether a "|" terminator must be appended before storing
1040/// it in a tag line.
1041static tagcmd_T tagfunc_cmd_kind(char *cmd)
1042{
1043  if (ascii_isdigit(*cmd)) {
1044    return *skipdigits(cmd) == NUL ? TAGCMD_ADDRESS : TAGCMD_INVALID;
1045  }
1046  if (*cmd == '/' || *cmd == '?') {
1047    // A Tab inside the pattern is fine (Universal Ctags emits one for a
1048    // tab-indented line); only trailing content after the closing
1049    // delimiter, which would break the tag line fields, is rejected.
1050    const char *end = skip_regexp(cmd + 1, *cmd, false);
1051    return (*end == *cmd && end[1] == NUL) ? TAGCMD_ADDRESS : TAGCMD_INVALID;
1052  }
1053  if (strpbrk(cmd, "\t\r\n") != NULL) {
1054    return TAGCMD_INVALID;
1055  }
1056  return TAGCMD_GENERIC;
1057}
1058
1059/// Call the user-defined function to generate a list of tags used by
1060/// find_tags().
1061///
1062/// Return OK if at least 1 tag has been successfully found,
1063/// NOTDONE if the function returns v:null, and FAIL otherwise.
1064///
1065/// @param pat  pattern supplied to the user-defined function
1066/// @param ga  the tags will be placed here
1067/// @param match_count  here the number of tags found will be placed
1068/// @param flags  flags from find_tags (TAG_*)
1069/// @param buf_ffname  name of buffer for priority
1070static int find_tagfunc_tags(char *pat, garray_T *ga, int *match_count, int flags, char *buf_ffname)
1071{
1072  int ntags = 0;
1073  typval_T args[4];
1074  typval_T rettv;
1075  char flagString[4];
1076  taggy_T *tag = NULL;
1077
1078  if (curwin->w_tagstacklen > 0) {
1079    if (curwin->w_tagstackidx == curwin->w_tagstacklen) {
1080      tag = &curwin->w_tagstack[curwin->w_tagstackidx - 1];
1081    } else {
1082      tag = &curwin->w_tagstack[curwin->w_tagstackidx];
1083    }
1084  }
1085
1086  if (curbuf->b_p_tfu.type == kCallbackNone) {
1087    return FAIL;
1088  }
1089
1090  args[0].v_type = VAR_STRING;
1091  args[0].vval.v_string = pat;
1092  args[1].v_type = VAR_STRING;
1093  args[1].vval.v_string = flagString;
1094
1095  // create 'info' dict argument
1096  dict_T *const d = tv_dict_alloc_lock(VAR_FIXED);
1097  if (!(flags & TAG_INS_COMP) && tag != NULL && tag->user_data != NULL) {
1098    tv_dict_add_str(d, S_LEN("user_data"), tag->user_data);
1099  }
1100  if (buf_ffname != NULL) {
1101    tv_dict_add_str(d, S_LEN("buf_ffname"), buf_ffname);
1102  }
1103
1104  d->dv_refcount++;
1105  args[2].v_type = VAR_DICT;
1106  args[2].vval.v_dict = d;
1107
1108  args[3].v_type = VAR_UNKNOWN;
1109
1110  vim_snprintf(flagString, sizeof(flagString),
1111               "%s%s%s",
1112               g_tag_at_cursor ? "c" : "",
1113               flags & TAG_INS_COMP ? "i" : "",
1114               flags & TAG_REGEXP ? "r" : "");
1115
1116  pos_T save_pos = curwin->w_cursor;
1117  int result = callback_call(&curbuf->b_p_tfu, 3, args, &rettv);
1118  curwin->w_cursor = save_pos;  // restore the cursor position
1119  check_cursor(curwin);         // make sure cursor position is valid
1120  d->dv_refcount--;
1121
1122  if (result == FAIL) {
1123    return FAIL;
1124  }
1125  if (rettv.v_type == VAR_SPECIAL && rettv.vval.v_special == kSpecialVarNull) {
1126    tv_clear(&rettv);
1127    return NOTDONE;
1128  }
1129  if (rettv.v_type != VAR_LIST || !rettv.vval.v_list) {
1130    tv_clear(&rettv);
1131    emsg(_(e_invalid_return_value_from_tagfunc));
1132    return FAIL;
1133  }
1134  list_T *taglist = rettv.vval.v_list;
1135
1136  TV_LIST_ITER_CONST(taglist, li, {
1137    char *res_name;
1138    char *res_fname;
1139    char *res_cmd;
1140    char *res_kind;
1141    bool has_extra = false;
1142    int name_only = flags & TAG_NAMES;
1143
1144    if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT) {
1145      emsg(_(e_invalid_return_value_from_tagfunc));
1146      break;
1147    }
1148
1149    size_t len = 2;
1150    res_name = NULL;
1151    res_fname = NULL;
1152    res_cmd = NULL;
1153    res_kind = NULL;
1154
1155    TV_DICT_ITER(TV_LIST_ITEM_TV(li)->vval.v_dict, di, {
1156      const char *dict_key = di->di_key;
1157      typval_T *tv = &di->di_tv;
1158
1159      if (tv->v_type != VAR_STRING || tv->vval.v_string == NULL) {
1160        continue;
1161      }
1162
1163      len += strlen(tv->vval.v_string) + 1;   // Space for "\tVALUE"
1164      if (strcmp(dict_key, "name") == 0) {
1165        res_name = tv->vval.v_string;
1166        continue;
1167      }
1168      if (strcmp(dict_key, "filename") == 0) {
1169        res_fname = tv->vval.v_string;
1170        continue;
1171      }
1172      if (strcmp(dict_key, "cmd") == 0) {
1173        res_cmd = tv->vval.v_string;
1174        continue;
1175      }
1176      has_extra = true;
1177      if (strcmp(dict_key, "kind") == 0) {
1178        res_kind = tv->vval.v_string;
1179        continue;
1180      }
1181      // Other elements will be stored as "\tKEY:VALUE"
1182      // Allocate space for the key and the colon
1183      len += strlen(dict_key) + 1;
1184    });
1185
1186    if (has_extra) {
1187      len += 2;  // need space for ;"
1188    }
1189
1190    if (!res_name || !res_fname || !res_cmd) {
1191      emsg(_(e_invalid_return_value_from_tagfunc));
1192      break;
1193    }
1194
1195    tagcmd_T cmdkind = tagfunc_cmd_kind(res_cmd);
1196    if (cmdkind == TAGCMD_INVALID) {
1197      emsg(_(e_invalid_return_value_from_tagfunc));
1198      break;
1199    }
1200    if (cmdkind == TAGCMD_GENERIC) {
1201      len += 3;  // need space for "|;\""
1202    }
1203    char *const mfp = name_only ? xstrdup(res_name) : xmalloc(len + 2);
1204
1205    if (!name_only) {
1206      char *p = mfp;
1207
1208      *p++ = MT_GL_OTH + 1;   // mtt
1209      *p++ = TAG_SEP;     // no tag file name
1210
1211      STRCPY(p, res_name);
1212      p += strlen(p);
1213
1214      *p++ = TAB;
1215      STRCPY(p, res_fname);
1216      p += strlen(p);
1217
1218      *p++ = TAB;
1219      STRCPY(p, res_cmd);
1220      p += strlen(p);
1221
1222      if (cmdkind == TAGCMD_GENERIC) {
1223        *p++ = '|';  // terminate the command
1224      }
1225      if (cmdkind == TAGCMD_GENERIC || has_extra) {
1226        STRCPY(p, ";\"");
1227        p += strlen(p);
1228
1229        if (res_kind) {
1230          *p++ = TAB;
1231          STRCPY(p, res_kind);
1232          p += strlen(p);
1233        }
1234
1235        TV_DICT_ITER(TV_LIST_ITEM_TV(li)->vval.v_dict, di, {
1236          const char *dict_key = di->di_key;
1237          typval_T *tv = &di->di_tv;
1238          if (tv->v_type != VAR_STRING || tv->vval.v_string == NULL) {
1239            continue;
1240          }
1241
1242          if (strcmp(dict_key, "name") == 0) {
1243            continue;
1244          }
1245          if (strcmp(dict_key, "filename") == 0) {
1246            continue;
1247          }
1248          if (strcmp(dict_key, "cmd") == 0) {
1249            continue;
1250          }
1251          if (strcmp(dict_key, "kind") == 0) {
1252            continue;
1253          }
1254
1255          *p++ = TAB;
1256          STRCPY(p, dict_key);
1257          p += strlen(p);
1258          STRCPY(p, ":");
1259          p += strlen(p);
1260          STRCPY(p, tv->vval.v_string);
1261          p += strlen(p);
1262        });
1263      }
1264    }
1265
1266    // Add all matches because tagfunc should do filtering.
1267    ga_grow(ga, 1);
1268    ((char **)(ga->ga_data))[ga->ga_len++] = (char *)mfp;
1269    ntags++;
1270    result = OK;
1271  });
1272
1273  tv_clear(&rettv);
1274
1275  *match_count = ntags;
1276  return result;
1277}
1278
1279/// Initialize the state used by find_tags()
1280static void findtags_state_init(findtags_state_T *st, char *pat, int flags, int mincount)
1281{
1282  st->tag_fname = xmalloc(MAXPATHL + 1);
1283  st->fp = NULL;
1284  st->orgpat = xmalloc(sizeof(pat_T));
1285  st->orgpat->pat = pat;
1286  st->orgpat->len = (int)strlen(pat);
1287  st->orgpat->regmatch.regprog = NULL;
1288  st->flags = flags;
1289  st->tag_file_sorted = NUL;
1290  st->help_lang_find = NULL;
1291  st->is_txt = false;
1292  st->did_open = false;
1293  st->help_only = (flags & TAG_HELP);
1294  st->get_searchpat = false;
1295  st->help_lang[0] = NUL;
1296  st->help_pri = 0;
1297  st->mincount = mincount;
1298  st->lbuf_size = LSIZE;
1299  st->lbuf = xmalloc((size_t)st->lbuf_size);
1300  st->match_count = 0;
1301  st->stop_searching = false;
1302
1303  for (int mtt = 0; mtt < MT_COUNT; mtt++) {
1304    ga_init(&st->ga_match[mtt], sizeof(char *), 100);
1305    hash_init(&st->ht_match[mtt]);
1306  }
1307}
1308
1309/// Free the state used by find_tags()
1310static void findtags_state_free(findtags_state_T *st)
1311{
1312  xfree(st->tag_fname);
1313  xfree(st->lbuf);
1314  vim_regfree(st->orgpat->regmatch.regprog);
1315  xfree(st->orgpat);
1316}
1317
1318/// Initialize the language and priority used for searching tags in a Vim help
1319/// file.
1320/// Returns true to process the help file for tags and false to skip the file.
1321static bool findtags_in_help_init(findtags_state_T *st)
1322{
1323  int i;
1324
1325  // Keep "en" as the language if the file extension is ".txt"
1326  if (st->is_txt) {
1327    STRCPY(st->help_lang, "en");
1328  } else {
1329    // Prefer help tags according to 'helplang'.  Put the two-letter
1330    // language name in help_lang[].
1331    i = (int)strlen(st->tag_fname);
1332    if (i > 3 && st->tag_fname[i - 3] == '-') {
1333      xmemcpyz(st->help_lang, st->tag_fname + i - 2, 2);
1334    } else {
1335      STRCPY(st->help_lang, "en");
1336    }
1337  }
1338  // When searching for a specific language skip tags files for other
1339  // languages.
1340  if (st->help_lang_find != NULL
1341      && STRICMP(st->help_lang, st->help_lang_find) != 0) {
1342    return false;
1343  }
1344
1345  // For CTRL-] in a help file prefer a match with the same language.
1346  if ((st->flags & TAG_KEEP_LANG)
1347      && st->help_lang_find == NULL
1348      && curbuf->b_fname != NULL
1349      && (i = (int)strlen(curbuf->b_fname)) > 4
1350      && curbuf->b_fname[i - 1] == 'x'
1351      && curbuf->b_fname[i - 4] == '.'
1352      && STRNICMP(curbuf->b_fname + i - 3, st->help_lang, 2) == 0) {
1353    st->help_pri = 0;
1354  } else {
1355    st->help_pri = 1;
1356    char *s;
1357    for (s = p_hlg; *s != NUL; s++) {
1358      if (STRNICMP(s, st->help_lang, 2) == 0) {
1359        break;
1360      }
1361      st->help_pri++;
1362      if ((s = vim_strchr(s, ',')) == NULL) {
1363        break;
1364      }
1365    }
1366    if (s == NULL || *s == NUL) {
1367      // Language not in 'helplang': use last, prefer English, unless
1368      // found already.
1369      st->help_pri++;
1370      if (STRICMP(st->help_lang, "en") != 0) {
1371        st->help_pri++;
1372      }
1373    }
1374  }
1375
1376  return true;
1377}
1378
1379/// Use the function set in 'tagfunc' (if configured and enabled) to get the
1380/// tags.
1381/// Return OK if at least 1 tag has been successfully found, NOTDONE if the
1382/// 'tagfunc' is not used, still executing or the 'tagfunc' returned v:null and
1383/// FAIL otherwise.
1384static int findtags_apply_tfu(findtags_state_T *st, char *pat, char *buf_ffname)
1385{
1386  const bool use_tfu = ((st->flags & TAG_NO_TAGFUNC) == 0);
1387
1388  if (!use_tfu || tfu_in_use || curbuf->b_p_tfu.type == kCallbackNone) {
1389    return NOTDONE;
1390  }
1391
1392  tfu_in_use = true;
1393  int retval = find_tagfunc_tags(pat, st->ga_match, &st->match_count,
1394                                 st->flags, buf_ffname);
1395  tfu_in_use = false;
1396
1397  return retval;
1398}
1399
1400/// Read the next line from a tags file.
1401/// Returns TAGS_READ_SUCCESS if a tags line is successfully read and should be
1402/// processed.
1403/// Returns TAGS_READ_EOF if the end of file is reached.
1404/// Returns TAGS_READ_IGNORE if the current line should be ignored (used when
1405/// reached end of a emacs included tags file)
1406static tags_read_status_T findtags_get_next_line(findtags_state_T *st, tagsearch_info_T *sinfo_p)
1407{
1408  bool eof;
1409
1410  // For binary search: compute the next offset to use.
1411  if (st->state == TS_BINARY) {
1412    off_T offset = sinfo_p->low_offset + ((sinfo_p->high_offset - sinfo_p->low_offset) / 2);
1413    if (offset == sinfo_p->curr_offset) {
1414      return TAGS_READ_EOF;  // End the binary search without a match.
1415    } else {
1416      sinfo_p->curr_offset = offset;
1417    }
1418  } else if (st->state == TS_SKIP_BACK) {
1419    // Skipping back (after a match during binary search).
1420    sinfo_p->curr_offset -= st->lbuf_size * 2;
1421    if (sinfo_p->curr_offset < 0) {
1422      sinfo_p->curr_offset = 0;
1423      fseek(st->fp, 0, SEEK_SET);
1424      st->state = TS_STEP_FORWARD;
1425    }
1426  }
1427
1428  // When jumping around in the file, first read a line to find the
1429  // start of the next line.
1430  if (st->state == TS_BINARY || st->state == TS_SKIP_BACK) {
1431    // Adjust the search file offset to the correct position
1432    sinfo_p->curr_offset_used = sinfo_p->curr_offset;
1433    vim_ignored = vim_fseek(st->fp, sinfo_p->curr_offset, SEEK_SET);
1434    eof = vim_fgets(st->lbuf, st->lbuf_size, st->fp);
1435    if (!eof && sinfo_p->curr_offset != 0) {
1436      sinfo_p->curr_offset = vim_ftell(st->fp);
1437      if (sinfo_p->curr_offset == sinfo_p->high_offset) {
1438        // oops, gone a bit too far; try from low offset
1439        vim_ignored = vim_fseek(st->fp, sinfo_p->low_offset, SEEK_SET);
1440        sinfo_p->curr_offset = sinfo_p->low_offset;
1441      }
1442      eof = vim_fgets(st->lbuf, st->lbuf_size, st->fp);
1443    }
1444    // skip empty and blank lines
1445    while (!eof && vim_isblankline(st->lbuf)) {
1446      sinfo_p->curr_offset = vim_ftell(st->fp);
1447      eof = vim_fgets(st->lbuf, st->lbuf_size, st->fp);
1448    }
1449    if (eof) {
1450      // Hit end of file.  Skip backwards.
1451      st->state = TS_SKIP_BACK;
1452      sinfo_p->match_offset = vim_ftell(st->fp);
1453      sinfo_p->curr_offset = sinfo_p->curr_offset_used;
1454      return TAGS_READ_IGNORE;
1455    }
1456  } else {
1457    // Not jumping around in the file: Read the next line.
1458
1459    // skip empty and blank lines
1460    do {
1461      eof = vim_fgets(st->lbuf, st->lbuf_size, st->fp);
1462    } while (!eof && vim_isblankline(st->lbuf));
1463
1464    if (eof) {
1465      return TAGS_READ_EOF;
1466    }
1467  }
1468
1469  return TAGS_READ_SUCCESS;
1470}
1471
1472/// Parse a tags file header line in "st->lbuf".
1473/// Returns true if the current line in st->lbuf is not a tags header line and
1474/// should be parsed as a regular tag line. Returns false if the line is a
1475/// header line and the next header line should be read.
1476static bool findtags_hdr_parse(findtags_state_T *st)
1477{
1478  // Header lines in a tags file start with "!_TAG_"
1479  if (strncmp(st->lbuf, "!_TAG_", 6) != 0) {
1480    // Non-header item before the header, e.g. "!" itself.
1481    return true;
1482  }
1483
1484  // Process the header line.
1485  if (strncmp(st->lbuf, "!_TAG_FILE_SORTED\t", 18) == 0) {
1486    st->tag_file_sorted = (uint8_t)st->lbuf[18];
1487  }
1488  if (strncmp(st->lbuf, "!_TAG_FILE_ENCODING\t", 20) == 0) {
1489    // Prepare to convert every line from the specified encoding to
1490    // 'encoding'.
1491    char *p;
1492    for (p = st->lbuf + 20; *p > ' ' && *p < 127; p++) {}
1493    *p = NUL;
1494    convert_setup(&st->vimconv, st->lbuf + 20, p_enc);
1495  }
1496
1497  // Read the next line.  Unrecognized flags are ignored.
1498  return false;
1499}
1500
1501/// Handler to initialize the state when starting to process a new tags file.
1502/// Called in the TS_START state when finding tags from a tags file.
1503/// Returns true if the line read from the tags file should be parsed and
1504/// false if the line should be ignored.
1505static bool findtags_start_state_handler(findtags_state_T *st, bool *sortic,
1506                                         tagsearch_info_T *sinfo_p)
1507{
1508  const bool noic = (st->flags & TAG_NOIC);
1509
1510  // The header ends when the line sorts below "!_TAG_".  When case is
1511  // folded lower case letters sort before "_".
1512  if (strncmp(st->lbuf, "!_TAG_", 6) <= 0
1513      || (st->lbuf[0] == '!' && ASCII_ISLOWER(st->lbuf[1]))) {
1514    return findtags_hdr_parse(st);
1515  }
1516
1517  // Headers ends.
1518
1519  // When there is no tag head, or ignoring case, need to do a
1520  // linear search.
1521  // When no "!_TAG_" is found, default to binary search.  If
1522  // the tag file isn't sorted, the second loop will find it.
1523  // When "!_TAG_FILE_SORTED" found: start binary search if
1524  // flag set.
1525  if (st->linear) {
1526    st->state = TS_LINEAR;
1527  } else if (st->tag_file_sorted == NUL) {
1528    st->state = TS_BINARY;
1529  } else if (st->tag_file_sorted == '1') {
1530    st->state = TS_BINARY;
1531  } else if (st->tag_file_sorted == '2') {
1532    st->state = TS_BINARY;
1533    *sortic = true;
1534    st->orgpat->regmatch.rm_ic = (p_ic || !noic);
1535  } else {
1536    st->state = TS_LINEAR;
1537  }
1538
1539  if (st->state == TS_BINARY && st->orgpat->regmatch.rm_ic && !*sortic) {
1540    // Binary search won't work for ignoring case, use linear
1541    // search.
1542    st->linear = true;
1543    st->state = TS_LINEAR;
1544  }
1545
1546  // When starting a binary search, get the size of the file and
1547  // compute the first offset.
1548  if (st->state == TS_BINARY) {
1549    if (vim_fseek(st->fp, 0, SEEK_END) != 0) {
1550      // can't seek, don't use binary search
1551      st->state = TS_LINEAR;
1552    } else {
1553      // Get the tag file size.
1554      // Don't use lseek(), it doesn't work
1555      // properly on MacOS Catalina.
1556      const off_T filesize = vim_ftell(st->fp);
1557      vim_ignored = vim_fseek(st->fp, 0, SEEK_SET);
1558
1559      // Calculate the first read offset in the file.  Start
1560      // the search in the middle of the file.
1561      sinfo_p->low_offset = 0;
1562      sinfo_p->low_char = 0;
1563      sinfo_p->high_offset = filesize;
1564      sinfo_p->curr_offset = 0;
1565      sinfo_p->high_char = 0xff;
1566    }
1567    return false;
1568  }
1569
1570  return true;
1571}
1572
1573/// Parse a tag line read from a tags file.
1574/// Also compares the tag name in "tagpp->tagname" with a search pattern in
1575/// "st->orgpat->head" as a quick check if the tag may match.
1576/// Returns:
1577/// - TAG_MATCH_SUCCESS if the tag may match
1578/// - TAG_MATCH_FAIL if the tag doesn't match
1579/// - TAG_MATCH_NEXT to look for the next matching tag (used in a binary search)
1580/// - TAG_MATCH_STOP if all the tags are processed without a match.
1581/// Uses the values in "margs" for doing the comparison.
1582static tagmatch_status_T findtags_parse_line(findtags_state_T *st, tagptrs_T *tagpp,
1583                                             findtags_match_args_T *margs,
1584                                             tagsearch_info_T *sinfo_p)
1585{
1586  int status;
1587
1588  // Figure out where the different strings are in this line.
1589  // For "normal" tags: Do a quick check if the tag matches.
1590  // This speeds up tag searching a lot!
1591  if (st->orgpat->headlen) {
1592    CLEAR_FIELD(*tagpp);
1593    tagpp->tagname = st->lbuf;
1594    tagpp->tagname_end = vim_strchr(st->lbuf, TAB);
1595    if (tagpp->tagname_end == NULL) {
1596      // Corrupted tag line.
1597      return TAG_MATCH_FAIL;
1598    }
1599
1600    // Skip this line if the length of the tag is different and
1601    // there is no regexp, or the tag is too short.
1602    int cmplen = (int)(tagpp->tagname_end - tagpp->tagname);
1603    if (p_tl != 0 && cmplen > p_tl) {  // adjust for 'taglength'
1604      cmplen = (int)p_tl;
1605    }
1606    if ((st->flags & TAG_REGEXP) && st->orgpat->headlen < cmplen) {
1607      cmplen = st->orgpat->headlen;
1608    } else if (st->state == TS_LINEAR && st->orgpat->headlen != cmplen) {
1609      return TAG_MATCH_NEXT;
1610    }
1611
1612    if (st->state == TS_BINARY) {
1613      int tagcmp;
1614      // Simplistic check for unsorted tags file.
1615      int i = (uint8_t)tagpp->tagname[0];
1616      if (margs->sortic) {
1617        i = TOUPPER_ASC(tagpp->tagname[0]);
1618      }
1619      if (i < sinfo_p->low_char || i > sinfo_p->high_char) {
1620        margs->sort_error = true;
1621      }
1622
1623      // Compare the current tag with the searched tag.
1624      if (margs->sortic) {
1625        tagcmp = tag_strnicmp(tagpp->tagname, st->orgpat->head,
1626                              (size_t)cmplen);
1627      } else {
1628        tagcmp = strncmp(tagpp->tagname, st->orgpat->head, (size_t)cmplen);
1629      }
1630
1631      // A match with a shorter tag means to search forward.
1632      // A match with a longer tag means to search backward.
1633      if (tagcmp == 0) {
1634        if (cmplen < st->orgpat->headlen) {
1635          tagcmp = -1;
1636        } else if (cmplen > st->orgpat->headlen) {
1637          tagcmp = 1;
1638        }
1639      }
1640
1641      if (tagcmp == 0) {
1642        // We've located the tag, now skip back and search
1643        // forward until the first matching tag is found.
1644        st->state = TS_SKIP_BACK;
1645        sinfo_p->match_offset = sinfo_p->curr_offset;
1646        return TAG_MATCH_NEXT;
1647      }
1648      if (tagcmp < 0) {
1649        sinfo_p->curr_offset = vim_ftell(st->fp);
1650        if (sinfo_p->curr_offset < sinfo_p->high_offset) {
1651          sinfo_p->low_offset = sinfo_p->curr_offset;
1652          if (margs->sortic) {
1653            sinfo_p->low_char = TOUPPER_ASC(tagpp->tagname[0]);
1654          } else {
1655            sinfo_p->low_char = (uint8_t)tagpp->tagname[0];
1656          }
1657          return TAG_MATCH_NEXT;
1658        }
1659      }
1660      if (tagcmp > 0 && sinfo_p->curr_offset != sinfo_p->high_offset) {
1661        sinfo_p->high_offset = sinfo_p->curr_offset;
1662        if (margs->sortic) {
1663          sinfo_p->high_char = TOUPPER_ASC(tagpp->tagname[0]);
1664        } else {
1665          sinfo_p->high_char = (uint8_t)tagpp->tagname[0];
1666        }
1667        return TAG_MATCH_NEXT;
1668      }
1669
1670      // No match yet and are at the end of the binary search.
1671      return TAG_MATCH_STOP;
1672    } else if (st->state == TS_SKIP_BACK) {
1673      assert(cmplen >= 0);
1674      if (mb_strnicmp(tagpp->tagname, st->orgpat->head, (size_t)cmplen) != 0) {
1675        st->state = TS_STEP_FORWARD;
1676      } else {
1677        // Have to skip back more.  Restore the curr_offset
1678        // used, otherwise we get stuck at a long line.
1679        sinfo_p->curr_offset = sinfo_p->curr_offset_used;
1680      }
1681      return TAG_MATCH_NEXT;
1682    } else if (st->state == TS_STEP_FORWARD) {
1683      assert(cmplen >= 0);
1684      if (mb_strnicmp(tagpp->tagname, st->orgpat->head, (size_t)cmplen) != 0) {
1685        return ((off_T)vim_ftell(st->fp) > sinfo_p->match_offset)
1686               ? TAG_MATCH_STOP   // past last match
1687               : TAG_MATCH_NEXT;  // before first match
1688      }
1689    } else {
1690      // skip this match if it can't match
1691      assert(cmplen >= 0);
1692      if (mb_strnicmp(tagpp->tagname, st->orgpat->head, (size_t)cmplen) != 0) {
1693        return TAG_MATCH_NEXT;
1694      }
1695    }
1696
1697    // Can be a matching tag, isolate the file name and command.
1698    tagpp->fname = tagpp->tagname_end + 1;
1699    tagpp->fname_end = vim_strchr(tagpp->fname, TAB);
1700    if (tagpp->fname_end == NULL) {
1701      status = FAIL;
1702    } else {
1703      tagpp->command = tagpp->fname_end + 1;
1704      status = OK;
1705    }
1706  } else {
1707    status = parse_tag_line(st->lbuf, tagpp);
1708  }
1709
1710  return status == FAIL
1711         ? TAG_MATCH_FAIL
1712         : TAG_MATCH_SUCCESS;
1713}
1714
1715/// Initialize the structure used for tag matching.
1716static void findtags_matchargs_init(findtags_match_args_T *margs, int flags)
1717{
1718  margs->matchoff = 0;                        // match offset
1719  margs->match_re = false;                    // match with regexp
1720  margs->match_no_ic = false;                 // matches with case
1721  margs->has_re = (flags & TAG_REGEXP);       // regexp used
1722  margs->sortic = false;                      // tag file sorted in nocase
1723  margs->sort_error = false;                  // tags file not sorted
1724}
1725
1726/// Compares the tag name in "tagpp->tagname" with a search pattern in
1727/// "st->orgpat->pat".
1728/// Returns true if the tag matches, false if the tag doesn't match.
1729/// Uses the values in "margs" for doing the comparison.
1730static bool findtags_match_tag(findtags_state_T *st, tagptrs_T *tagpp, findtags_match_args_T *margs)
1731{
1732  bool match = false;
1733
1734  // First try matching with the pattern literally (also when it is
1735  // a regexp).
1736  int cmplen = (int)(tagpp->tagname_end - tagpp->tagname);
1737  if (p_tl != 0 && cmplen > p_tl) {           // adjust for 'taglength'
1738    cmplen = (int)p_tl;
1739  }
1740  // if tag length does not match, don't try comparing
1741  if (st->orgpat->len != cmplen) {
1742    match = false;
1743  } else {
1744    if (st->orgpat->regmatch.rm_ic) {
1745      assert(cmplen >= 0);
1746      match = mb_strnicmp(tagpp->tagname, st->orgpat->pat, (size_t)cmplen) == 0;
1747      if (match) {
1748        margs->match_no_ic = strncmp(tagpp->tagname, st->orgpat->pat, (size_t)cmplen) == 0;
1749      }
1750    } else {
1751      match = strncmp(tagpp->tagname, st->orgpat->pat, (size_t)cmplen) == 0;
1752    }
1753  }
1754
1755  // Has a regexp: Also find tags matching regexp.
1756  margs->match_re = false;
1757  if (!match && st->orgpat->regmatch.regprog != NULL) {
1758    char cc = *tagpp->tagname_end;
1759    *tagpp->tagname_end = NUL;
1760    match = vim_regexec(&st->orgpat->regmatch, tagpp->tagname, 0);
1761    if (match) {
1762      margs->matchoff = (int)(st->orgpat->regmatch.startp[0] - tagpp->tagname);
1763      if (st->orgpat->regmatch.rm_ic) {
1764        st->orgpat->regmatch.rm_ic = false;
1765        margs->match_no_ic = vim_regexec(&st->orgpat->regmatch,
1766                                         tagpp->tagname, 0);
1767        st->orgpat->regmatch.rm_ic = true;
1768      }
1769    }
1770    *tagpp->tagname_end = cc;
1771    margs->match_re = true;
1772  }
1773
1774  return match;
1775}
1776
1777/// Convert the encoding of a line read from a tags file in "st->lbuf".
1778/// Converting the pattern from 'enc' to the tags file encoding doesn't work,
1779/// because characters are not recognized. The converted line is saved in
1780/// st->lbuf.
1781static void findtags_string_convert(findtags_state_T *st)
1782{
1783  char *conv_line = string_convert(&st->vimconv, st->lbuf, NULL);
1784  if (conv_line == NULL) {
1785    return;
1786  }
1787
1788  // Copy or swap lbuf and conv_line.
1789  int len = (int)strlen(conv_line) + 1;
1790  if (len > st->lbuf_size) {
1791    xfree(st->lbuf);
1792    st->lbuf = conv_line;
1793    st->lbuf_size = len;
1794  } else {
1795    STRCPY(st->lbuf, conv_line);
1796    xfree(conv_line);
1797  }
1798}
1799
1800/// Add a matching tag found in a tags file to st->ht_match and st->ga_match.
1801static void findtags_add_match(findtags_state_T *st, tagptrs_T *tagpp, findtags_match_args_T *margs,
1802                               char *buf_ffname, hash_T *hash)
1803{
1804  const bool name_only = (st->flags & TAG_NAMES);
1805  size_t len = 0;
1806  size_t mfp_size = 0;
1807  char *mfp;
1808
1809  // Decide in which array to store this match.
1810  bool is_current = test_for_current(tagpp->fname, tagpp->fname_end,
1811                                     st->tag_fname, buf_ffname);
1812
1813  // current tag line is static
1814  bool is_static = test_for_static(tagpp);
1815
1816  // Decide in which of the sixteen tables to store this match.
1817  int mtt = is_static
1818            ? is_current ? MT_ST_CUR : MT_ST_OTH
1819            : is_current ? MT_GL_CUR : MT_GL_OTH;
1820
1821  if (st->orgpat->regmatch.rm_ic && !margs->match_no_ic) {
1822    mtt += MT_IC_OFF;
1823  }
1824  if (margs->match_re) {
1825    mtt += MT_RE_OFF;
1826  }
1827
1828  // Add the found match in ht_match[mtt] and ga_match[mtt].
1829  // Store the info we need later, which depends on the kind of
1830  // tags we are dealing with.
1831  if (st->help_only) {
1832#define ML_EXTRA 3
1833    // Append the help-heuristic number after the tagname, for
1834    // sorting it later.  The heuristic is ignored for
1835    // detecting duplicates.
1836    // The format is {tagname}@{lang}NUL{heuristic}NUL
1837    *tagpp->tagname_end = NUL;
1838    len = (size_t)(tagpp->tagname_end - tagpp->tagname);
1839    mfp_size = sizeof(char) + len + 10 + ML_EXTRA + 1;
1840    mfp = xmalloc(mfp_size);
1841
1842    char *p = mfp;
1843    STRCPY(p, tagpp->tagname);
1844    p[len] = '@';
1845    STRCPY(p + len + 1, st->help_lang);
1846    snprintf(p + len + 1 + ML_EXTRA, mfp_size - (len + 1 + ML_EXTRA), "%06d",
1847             help_heuristic(tagpp->tagname,
1848                            margs->match_re ? margs->matchoff : 0,
1849                            !margs->match_no_ic) + st->help_pri);
1850
1851    *tagpp->tagname_end = TAB;
1852  } else if (name_only) {
1853    if (st->get_searchpat) {
1854      char *temp_end = tagpp->command;
1855
1856      if (*temp_end == '/') {
1857        while (*temp_end && *temp_end != '\r'
1858               && *temp_end != '\n'
1859               && *temp_end != '$') {
1860          temp_end++;
1861        }
1862      }
1863
1864      if (tagpp->command + 2 < temp_end) {
1865        len = (size_t)(temp_end - tagpp->command - 2);
1866        mfp = xmalloc(len + 2);
1867        xmemcpyz(mfp, tagpp->command + 2, len);
1868      } else {
1869        mfp = NULL;
1870      }
1871      st->get_searchpat = false;
1872    } else {
1873      len = (size_t)(tagpp->tagname_end - tagpp->tagname);
1874      mfp = xmalloc(sizeof(char) + len + 1);
1875      xmemcpyz(mfp, tagpp->tagname, len);
1876
1877      // if wanted, re-read line to get long form too
1878      if (State & MODE_INSERT) {
1879        st->get_searchpat = p_sft;
1880      }
1881    }
1882  } else {
1883    size_t tag_fname_len = strlen(st->tag_fname);
1884    // Save the tag in a buffer.
1885    // Use 0x02 to separate fields (Can't use NUL, because the
1886    // hash key is terminated by NUL).
1887    // Emacs tag: <mtt><tag_fname><0x02><ebuf><0x02><lbuf><NUL>
1888    // other tag: <mtt><tag_fname><0x02><0x02><lbuf><NUL>
1889    // without Emacs tags: <mtt><tag_fname><0x02><lbuf><NUL>
1890    // Here <mtt> is the "mtt" value plus 1 to avoid NUL.
1891    len = tag_fname_len + strlen(st->lbuf) + 3;
1892    mfp = xmalloc(sizeof(char) + len + 1);
1893    char *p = mfp;
1894    p[0] = (char)(mtt + 1);
1895    STRCPY(p + 1, st->tag_fname);
1896    p[tag_fname_len + 1] = TAG_SEP;
1897    char *s = p + 1 + tag_fname_len + 1;
1898    STRCPY(s, st->lbuf);
1899  }
1900
1901  if (mfp != NULL) {
1902    hashitem_T *hi;
1903
1904    // Don't add identical matches.
1905    // "mfp" is used as a hash key, there is a NUL byte to end
1906    // the part that matters for comparing, more bytes may
1907    // follow after it.  E.g. help tags store the priority
1908    // after the NUL.
1909    *hash = hash_hash(mfp);
1910    hi = hash_lookup(&st->ht_match[mtt], mfp, strlen(mfp), *hash);
1911    if (HASHITEM_EMPTY(hi)) {
1912      hash_add_item(&st->ht_match[mtt], hi, mfp, *hash);
1913      GA_APPEND(char *, &st->ga_match[mtt], mfp);
1914      st->match_count++;
1915    } else {
1916      // duplicate tag, drop it
1917      xfree(mfp);
1918    }
1919  }
1920}
1921
1922/// Read and get all the tags from file st->tag_fname.
1923/// Sets "st->stop_searching" to true to stop searching for additional tags.
1924static void findtags_get_all_tags(findtags_state_T *st, findtags_match_args_T *margs,
1925                                  char *buf_ffname)
1926{
1927  tagptrs_T tagp;
1928  tagsearch_info_T search_info;
1929  hash_T hash = 0;
1930
1931  // This is only to avoid a compiler warning for using search_info
1932  // uninitialised.
1933  CLEAR_FIELD(search_info);
1934
1935  // Read and parse the lines in the file one by one
1936  while (true) {
1937    // check for CTRL-C typed, more often when jumping around
1938    if (st->state == TS_BINARY || st->state == TS_SKIP_BACK) {
1939      line_breakcheck();
1940    } else {
1941      fast_breakcheck();
1942    }
1943    if ((st->flags & TAG_INS_COMP)) {   // Double brackets for gcc
1944      ins_compl_check_keys(30, false);
1945    }
1946    if (got_int || ins_compl_interrupted()) {
1947      st->stop_searching = true;
1948      break;
1949    }
1950    // When mincount is TAG_MANY, stop when enough matches have been
1951    // found (for completion).
1952    if (st->mincount == TAG_MANY && st->match_count >= TAG_MANY) {
1953      st->stop_searching = true;
1954      break;
1955    }
1956    if (st->get_searchpat) {
1957      goto line_read_in;
1958    }
1959
1960    int retval = (int)findtags_get_next_line(st, &search_info);
1961    if (retval == TAGS_READ_IGNORE) {
1962      continue;
1963    }
1964    if (retval == TAGS_READ_EOF) {
1965      break;
1966    }
1967
1968line_read_in:
1969
1970    if (st->vimconv.vc_type != CONV_NONE) {
1971      findtags_string_convert(st);
1972    }
1973
1974    // When still at the start of the file, check for Emacs tags file
1975    // format, and for "not sorted" flag.
1976    if (st->state == TS_START) {
1977      if (!findtags_start_state_handler(st, &margs->sortic, &search_info)) {
1978        continue;
1979      }
1980    }
1981
1982    // When the line is too long the NUL will not be in the
1983    // last-but-one byte (see vim_fgets()).
1984    // Has been reported for Mozilla JS with extremely long names.
1985    // In that case we need to increase lbuf_size.
1986    if (st->lbuf[st->lbuf_size - 2] != NUL) {
1987      st->lbuf_size *= 2;
1988      xfree(st->lbuf);
1989      st->lbuf = xmalloc((size_t)st->lbuf_size);
1990
1991      if (st->state == TS_STEP_FORWARD || st->state == TS_LINEAR) {
1992        // Seek to the same position to read the same line again
1993        vim_ignored = vim_fseek(st->fp, search_info.curr_offset, SEEK_SET);
1994      }
1995      // this will try the same thing again, make sure the offset is
1996      // different
1997      search_info.curr_offset = 0;
1998      continue;
1999    }
2000
2001    retval = (int)findtags_parse_line(st, &tagp, margs, &search_info);
2002    if (retval == TAG_MATCH_NEXT) {
2003      continue;
2004    }
2005    if (retval == TAG_MATCH_STOP) {
2006      break;
2007    }
2008    if (retval == TAG_MATCH_FAIL) {
2009      semsg(_("E431: Format error in tags file \"%s\""), st->tag_fname);
2010      semsg(_("Before byte %" PRId64), (int64_t)vim_ftell(st->fp));
2011      st->stop_searching = true;
2012      return;
2013    }
2014
2015    // If a match is found, add it to ht_match[] and ga_match[].
2016    if (findtags_match_tag(st, &tagp, margs)) {
2017      findtags_add_match(st, &tagp, margs, buf_ffname, &hash);
2018    }
2019  }  // forever
2020}
2021
2022/// Search for tags matching "st->orgpat.pat" in the "st->tag_fname" tags file.
2023/// Information needed to search for the tags is in the "st" state structure.
2024/// The matching tags are returned in "st". If an error is encountered, then
2025/// "st->stop_searching" is set to true.
2026static void findtags_in_file(findtags_state_T *st, int flags, char *buf_ffname)
2027{
2028  findtags_match_args_T margs;
2029
2030  st->vimconv.vc_type = CONV_NONE;
2031  st->tag_file_sorted = NUL;
2032  st->fp = NULL;
2033  findtags_matchargs_init(&margs, st->flags);
2034
2035  // A file that doesn't exist is silently ignored.  Only when not a
2036  // single file is found, an error message is given (further on).
2037  if (curbuf->b_help) {
2038    if (!findtags_in_help_init(st)) {
2039      return;
2040    }
2041  }
2042
2043  st->fp = os_fopen(st->tag_fname, "r");
2044  if (st->fp == NULL) {
2045    return;
2046  }
2047
2048  if (p_verbose >= 5) {
2049    verbose_enter();
2050    smsg(0, _("Searching tags file %s"), st->tag_fname);
2051    verbose_leave();
2052  }
2053  st->did_open = true;   // remember that we found at least one file
2054
2055  st->state = TS_START;  // we're at the start of the file
2056
2057  // Read and parse the lines in the file one by one
2058  findtags_get_all_tags(st, &margs, buf_ffname);
2059
2060  if (st->fp != NULL) {
2061    fclose(st->fp);
2062    st->fp = NULL;
2063  }
2064  if (st->vimconv.vc_type != CONV_NONE) {
2065    convert_setup(&st->vimconv, NULL, NULL);
2066  }
2067
2068  if (margs.sort_error) {
2069    semsg(_("E432: Tags file not sorted: %s"), st->tag_fname);
2070  }
2071
2072  // Stop searching if sufficient tags have been found.
2073  if (st->match_count >= st->mincount) {
2074    st->stop_searching = true;
2075  }
2076}
2077
2078/// Copy the tags found by find_tags() to "matchesp".
2079/// Returns the number of matches copied.
2080static int findtags_copy_matches(findtags_state_T *st, char ***matchesp)
2081{
2082  const bool name_only = (st->flags & TAG_NAMES);
2083
2084  char **matches = st->match_count > 0
2085                   ? xmalloc((size_t)st->match_count * sizeof(char *))
2086                   : NULL;
2087
2088  st->match_count = 0;
2089  for (int mtt = 0; mtt < MT_COUNT; mtt++) {
2090    for (int i = 0; i < st->ga_match[mtt].ga_len; i++) {
2091      char *mfp = ((char **)(st->ga_match[mtt].ga_data))[i];
2092      if (matches == NULL) {
2093        xfree(mfp);
2094      } else {
2095        if (!name_only) {
2096          // Change mtt back to zero-based.
2097          *mfp = (char)(*mfp - 1);
2098
2099          // change the TAG_SEP back to NUL
2100          for (char *p = mfp + 1; *p != NUL; p++) {
2101            if (*p == TAG_SEP) {
2102              *p = NUL;
2103            }
2104          }
2105        }
2106        matches[st->match_count++] = mfp;
2107      }
2108    }
2109
2110    ga_clear(&st->ga_match[mtt]);
2111    hash_clear(&st->ht_match[mtt]);
2112  }
2113
2114  *matchesp = matches;
2115  return st->match_count;
2116}
2117
2118/// find_tags() - search for tags in tags files
2119///
2120/// Return FAIL if search completely failed (*num_matches will be 0, *matchesp
2121/// will be NULL), OK otherwise.
2122///
2123/// There is a priority in which type of tag is recognized.
2124///
2125///  6.  A static or global tag with a full matching tag for the current file.
2126///  5.  A global tag with a full matching tag for another file.
2127///  4.  A static tag with a full matching tag for another file.
2128///  3.  A static or global tag with an ignore-case matching tag for the
2129///      current file.
2130///  2.  A global tag with an ignore-case matching tag for another file.
2131///  1.  A static tag with an ignore-case matching tag for another file.
2132///
2133/// Tags in an emacs-style tags file are always global.
2134///
2135/// flags:
2136/// TAG_HELP       only search for help tags
2137/// TAG_NAMES      only return name of tag
2138/// TAG_REGEXP     use "pat" as a regexp
2139/// TAG_NOIC       don't always ignore case
2140/// TAG_KEEP_LANG  keep language
2141/// TAG_NO_TAGFUNC do not call the 'tagfunc' function
2142///
2143/// @param pat  pattern to search for
2144/// @param num_matches  return: number of matches found
2145/// @param matchesp  return: array of matches found
2146/// @param mincount  MAXCOL: find all matches
2147///                  other: minimal number of matches
2148/// @param buf_ffname  name of buffer for priority
2149int find_tags(char *pat, int *num_matches, char ***matchesp, int flags, int mincount,
2150              char *buf_ffname)
2151{
2152  findtags_state_T st;
2153  tagname_T tn;                         // info for get_tagfname()
2154  int first_file;                       // trying first tag file
2155  int retval = FAIL;                    // return value
2156
2157  int i;
2158  char *saved_pat = NULL;                // copy of pat[]
2159
2160  int findall = (mincount == MAXCOL || mincount == TAG_MANY);  // find all matching tags
2161  bool has_re = (flags & TAG_REGEXP);            // regexp used
2162  int noic = (flags & TAG_NOIC);
2163  int verbose = (flags & TAG_VERBOSE);
2164  int save_p_ic = p_ic;
2165
2166  // uncrustify:off
2167
2168  // Change the value of 'ignorecase' according to 'tagcase' for the
2169  // duration of this function.
2170  switch (curbuf->b_tc_flags ? curbuf->b_tc_flags : tc_flags) {
2171  case kOptTcFlagFollowic: break;
2172  case kOptTcFlagIgnore:
2173    p_ic = true;
2174    break;
2175  case kOptTcFlagMatch:
2176    p_ic = false;
2177    break;
2178  case kOptTcFlagFollowscs:
2179    p_ic = ignorecase(pat);
2180    break;
2181  case kOptTcFlagSmart:
2182    p_ic = ignorecase_opt(pat, true, true);
2183    break;
2184  default:
2185    abort();
2186  }
2187
2188  // uncrustify:on
2189
2190  const bool help_save = curbuf->b_help;
2191
2192  findtags_state_init(&st, pat, flags, mincount);
2193
2194  // Initialize a few variables
2195  if (st.help_only) {                           // want tags from help file
2196    curbuf->b_help = true;                      // will be restored later
2197  }
2198
2199  if (curbuf->b_help) {
2200    // When "@ab" is specified use only the "ab" language, otherwise
2201    // search all languages.
2202    if (st.orgpat->len > 3 && pat[st.orgpat->len - 3] == '@'
2203        && ASCII_ISALPHA(pat[st.orgpat->len - 2])
2204        && ASCII_ISALPHA(pat[st.orgpat->len - 1])) {
2205      saved_pat = xstrnsave(pat, (size_t)st.orgpat->len - 3);
2206      st.help_lang_find = &pat[st.orgpat->len - 2];
2207      st.orgpat->pat = saved_pat;
2208      st.orgpat->len -= 3;
2209    }
2210  }
2211  if (p_tl != 0 && st.orgpat->len > p_tl) {  // adjust for 'taglength'
2212    st.orgpat->len = (int)p_tl;
2213  }
2214
2215  int save_emsg_off = emsg_off;
2216  emsg_off = true;    // don't want error for invalid RE here
2217  prepare_pats(st.orgpat, has_re);
2218  emsg_off = save_emsg_off;
2219  if (has_re && st.orgpat->regmatch.regprog == NULL) {
2220    goto findtag_end;
2221  }
2222
2223  retval = findtags_apply_tfu(&st, pat, buf_ffname);
2224  if (retval != NOTDONE) {
2225    goto findtag_end;
2226  }
2227
2228  // re-initialize the default return value
2229  retval = FAIL;
2230
2231  // Set a flag if the file extension is .txt
2232  if ((flags & TAG_KEEP_LANG)
2233      && st.help_lang_find == NULL
2234      && curbuf->b_fname != NULL
2235      && (i = (int)strlen(curbuf->b_fname)) > 4
2236      && STRICMP(curbuf->b_fname + i - 4, ".txt") == 0) {
2237    st.is_txt = true;
2238  }
2239
2240  // When finding a specified number of matches, first try with matching
2241  // case, so binary search can be used, and try ignore-case matches in a
2242  // second loop.
2243  // When finding all matches, 'tagbsearch' is off, or there is no fixed
2244  // string to look for, ignore case right away to avoid going though the
2245  // tags files twice.
2246  // When the tag file is case-fold sorted, it is either one or the other.
2247  // Only ignore case when TAG_NOIC not used or 'ignorecase' set.
2248  st.orgpat->regmatch.rm_ic = ((p_ic || !noic)
2249                               && (findall || st.orgpat->headlen == 0 || !p_tbs));
2250  for (int round = 1; round <= 2; round++) {
2251    st.linear = (st.orgpat->headlen == 0 || !p_tbs || round == 2);
2252
2253    // Try tag file names from tags option one by one.
2254    for (first_file = true;
2255         get_tagfname(&tn, first_file, st.tag_fname) == OK;
2256         first_file = false) {
2257      findtags_in_file(&st, flags, buf_ffname);
2258      if (st.stop_searching) {
2259        retval = OK;
2260        break;
2261      }
2262    }   // end of for-each-file loop
2263
2264    tagname_free(&tn);
2265
2266    // stop searching when already did a linear search, or when TAG_NOIC
2267    // used, and 'ignorecase' not set or already did case-ignore search
2268    if (st.stop_searching || st.linear || (!p_ic && noic)
2269        || st.orgpat->regmatch.rm_ic) {
2270      break;
2271    }
2272
2273    // try another time while ignoring case
2274    st.orgpat->regmatch.rm_ic = true;
2275  }
2276
2277  if (!st.stop_searching) {
2278    if (!st.did_open && verbose) {  // never opened any tags file
2279      emsg(_("E433: No tags file"));
2280    }
2281    retval = OK;                // It's OK even when no tag found
2282  }
2283
2284findtag_end:
2285  findtags_state_free(&st);
2286
2287  // Move the matches from the ga_match[] arrays into one list of
2288  // matches.  When retval == FAIL, free the matches.
2289  if (retval == FAIL) {
2290    st.match_count = 0;
2291  }
2292
2293  *num_matches = findtags_copy_matches(&st, matchesp);
2294
2295  curbuf->b_help = help_save;
2296  xfree(saved_pat);
2297
2298  p_ic = save_p_ic;
2299
2300  return retval;
2301}
2302
2303static garray_T tag_fnames = GA_EMPTY_INIT_VALUE;
2304
2305// Callback function for finding all "tags" and "tags-??" files in
2306// 'runtimepath' doc directories.
2307static bool found_tagfile_cb(int num_fnames, char **fnames, bool all, void *cookie)
2308{
2309  for (int i = 0; i < num_fnames; i++) {
2310    char *const tag_fname = xstrdup(fnames[i]);
2311
2312    simplify_filename(tag_fname);
2313    GA_APPEND(char *, &tag_fnames, tag_fname);
2314
2315    if (!all) {
2316      break;
2317    }
2318  }
2319
2320  return num_fnames > 0;
2321}
2322
2323#ifdef EXITFREE
2324void free_tag_stuff(void)
2325{
2326  ga_clear_strings(&tag_fnames);
2327  if (curwin != NULL) {
2328    do_tag(NULL, NULL, DT_FREE, 0, 0, 0);
2329  }
2330  tag_freematch();
2331
2332  tagstack_clear_entry(&ptag_entry);
2333}
2334
2335#endif
2336
2337/// Get the next name of a tag file from the tag file list.
2338/// For help files, use "tags" file only.
2339///
2340/// @param tnp  holds status info
2341/// @param first  true when first file name is wanted
2342/// @param buf  pointer to buffer of MAXPATHL chars
2343///
2344/// @return  FAIL if no more tag file names, OK otherwise.
2345int get_tagfname(tagname_T *tnp, int first, char *buf)
2346{
2347  char *fname = NULL;
2348
2349  if (first) {
2350    CLEAR_POINTER(tnp);
2351  }
2352
2353  if (curbuf->b_help) {
2354    // For help files it's done in a completely different way:
2355    // Find "doc/tags" and "doc/tags-??" in all directories in
2356    // 'runtimepath'.
2357    if (first) {
2358      ga_clear_strings(&tag_fnames);
2359      ga_init(&tag_fnames, (int)sizeof(char *), 10);
2360      do_in_runtimepath("doc/tags doc/tags-??", DIP_ALL,
2361                        found_tagfile_cb, NULL);
2362    }
2363
2364    if (tnp->tn_hf_idx >= tag_fnames.ga_len) {
2365      // Not found in 'runtimepath', use 'helpfile', if it exists and
2366      // wasn't used yet, replacing "help.txt" with "tags".
2367      if (tnp->tn_hf_idx > tag_fnames.ga_len || *p_hf == NUL) {
2368        return FAIL;
2369      }
2370      tnp->tn_hf_idx++;
2371      xstrlcpy(buf, p_hf, MAXPATHL - STRLEN_LITERAL("tags"));
2372      STRCPY(path_tail(buf), "tags");
2373      simplify_filename(buf);
2374
2375      for (int i = 0; i < tag_fnames.ga_len; i++) {
2376        if (strcmp(buf, ((char **)(tag_fnames.ga_data))[i]) == 0) {
2377          return FAIL;  // avoid duplicate file names
2378        }
2379      }
2380    } else {
2381      xstrlcpy(buf, ((char **)(tag_fnames.ga_data))[tnp->tn_hf_idx++], MAXPATHL);
2382    }
2383    return OK;
2384  }
2385
2386  if (first) {
2387    // Init.  We make a copy of 'tags', because autocommands may change
2388    // the value without notifying us.
2389    tnp->tn_tags = xstrdup((*curbuf->b_p_tags != NUL) ? curbuf->b_p_tags : p_tags);
2390    tnp->tn_np = tnp->tn_tags;
2391  }
2392
2393  // Loop until we have found a file name that can be used.
2394  // There are two states:
2395  // tnp->tn_did_filefind_init == false: setup for next part in 'tags'.
2396  // tnp->tn_did_filefind_init == true: find next file in this part.
2397  while (true) {
2398    if (tnp->tn_did_filefind_init) {
2399      fname = vim_findfile(tnp->tn_search_ctx);
2400      if (fname != NULL) {
2401        break;
2402      }
2403
2404      tnp->tn_did_filefind_init = false;
2405    } else {
2406      char *filename = NULL;
2407
2408      // Stop when used all parts of 'tags'.
2409      if (*tnp->tn_np == NUL) {
2410        vim_findfile_cleanup(tnp->tn_search_ctx);
2411        tnp->tn_search_ctx = NULL;
2412        return FAIL;
2413      }
2414
2415      // Copy next file name into buf.
2416      buf[0] = NUL;
2417      copy_option_part(&tnp->tn_np, buf, MAXPATHL - 1, " ,");
2418
2419      char *r_ptr = vim_findfile_stopdir(buf);
2420      // move the filename one char forward and truncate the
2421      // filepath with a NUL
2422      filename = path_tail(buf);
2423      if (r_ptr != NULL) {
2424        STRMOVE(r_ptr + 1, r_ptr);
2425        r_ptr++;
2426      }
2427      STRMOVE(filename + 1, filename);
2428      *filename++ = NUL;
2429
2430      tnp->tn_search_ctx = vim_findfile_init(buf, filename, strlen(filename),
2431                                             r_ptr, 100,
2432                                             false,                   // don't free visited list
2433                                             FINDFILE_FILE,           // we search for a file
2434                                             tnp->tn_search_ctx, true, curbuf->b_ffname);
2435      if (tnp->tn_search_ctx != NULL) {
2436        tnp->tn_did_filefind_init = true;
2437      }
2438    }
2439  }
2440
2441  STRCPY(buf, fname);
2442  xfree(fname);
2443  return OK;
2444}
2445
2446// Free the contents of a tagname_T that was filled by get_tagfname().
2447void tagname_free(tagname_T *tnp)
2448{
2449  xfree(tnp->tn_tags);
2450  vim_findfile_cleanup(tnp->tn_search_ctx);
2451  tnp->tn_search_ctx = NULL;
2452  ga_clear_strings(&tag_fnames);
2453}
2454
2455/// Parse one line from the tags file. Find start/end of tag name, start/end of
2456/// file name and start of search pattern.
2457///
2458/// If is_etag is true, tagp->fname and tagp->fname_end are not set.
2459///
2460/// @param lbuf  line to be parsed
2461///
2462/// @return  FAIL if there is a format error in this line, OK otherwise.
2463static int parse_tag_line(char *lbuf, tagptrs_T *tagp)
2464{
2465  // Isolate the tagname, from lbuf up to the first white
2466  tagp->tagname = lbuf;
2467  char *p = vim_strchr(lbuf, TAB);
2468  if (p == NULL) {
2469    return FAIL;
2470  }
2471  tagp->tagname_end = p;
2472
2473  // Isolate file name, from first to second white space
2474  if (*p != NUL) {
2475    p++;
2476  }
2477  tagp->fname = p;
2478  p = vim_strchr(p, TAB);
2479  if (p == NULL) {
2480    return FAIL;
2481  }
2482  tagp->fname_end = p;
2483
2484  // find start of search command, after second white space
2485  if (*p != NUL) {
2486    p++;
2487  }
2488  if (*p == NUL) {
2489    return FAIL;
2490  }
2491  tagp->command = p;
2492
2493  return OK;
2494}
2495
2496// Check if tagname is a static tag
2497//
2498// Static tags produced by the older ctags program have the format:
2499//      'file:tag  file  /pattern'.
2500// This is only recognized when both occurrence of 'file' are the same, to
2501// avoid recognizing "string::string" or ":exit".
2502//
2503// Static tags produced by the new ctags program have the format:
2504//      'tag  file  /pattern/;"<Tab>file:'          "
2505//
2506// Return true if it is a static tag and adjust *tagname to the real tag.
2507// Return false if it is not a static tag.
2508static bool test_for_static(tagptrs_T *tagp)
2509{
2510  // Check for new style static tag ":...<Tab>file:[<Tab>...]"
2511  char *p = tagp->command;
2512  while ((p = vim_strchr(p, '\t')) != NULL) {
2513    p++;
2514    if (strncmp(p, "file:", 5) == 0) {
2515      return true;
2516    }
2517  }
2518
2519  return false;
2520}
2521
2522/// @return  the length of a matching tag line.
2523static size_t matching_line_len(const char *const lbuf)
2524{
2525  const char *p = lbuf + 1;
2526
2527  // does the same thing as parse_match()
2528  p += strlen(p) + 1;
2529  return (size_t)(p - lbuf) + strlen(p);
2530}
2531
2532/// Parse a line from a matching tag.  Does not change the line itself.
2533///
2534/// The line that we get looks like this:
2535/// Emacs tag: <mtt><tag_fname><NUL><ebuf><NUL><lbuf>
2536/// other tag: <mtt><tag_fname><NUL><NUL><lbuf>
2537/// without Emacs tags: <mtt><tag_fname><NUL><lbuf>
2538///
2539/// @param lbuf  input: matching line
2540/// @param tagp  output: pointers into the line
2541///
2542/// @return  OK or FAIL.
2543static int parse_match(char *lbuf, tagptrs_T *tagp)
2544{
2545  tagp->tag_fname = lbuf + 1;
2546  lbuf += strlen(tagp->tag_fname) + 2;
2547
2548  // Find search pattern and the file name for non-etags.
2549  int retval = parse_tag_line(lbuf, tagp);
2550
2551  tagp->tagkind = NULL;
2552  tagp->user_data = NULL;
2553  tagp->tagline = 0;
2554  tagp->command_end = NULL;
2555
2556  if (retval != OK) {
2557    return retval;
2558  }
2559
2560  // Try to find a kind field: "kind:<kind>" or just "<kind>"
2561  char *p = tagp->command;
2562  if (find_extra(&p) == OK) {
2563    tagp->command_end = p;
2564    if (p > tagp->command && p[-1] == '|') {
2565      tagp->command_end = p - 1;  // drop trailing bar
2566    }
2567    p += 2;  // skip ";\""
2568    if (*p++ == TAB) {
2569      // Accept ASCII alphabetic kind characters and any multi-byte
2570      // character.
2571      while (ASCII_ISALPHA(*p) || utfc_ptr2len(p) > 1) {
2572        if (strncmp(p, "kind:", 5) == 0) {
2573          tagp->tagkind = p + 5;
2574        } else if (strncmp(p, "user_data:", 10) == 0) {
2575          tagp->user_data = p + 10;
2576        } else if (strncmp(p, "line:", 5) == 0) {
2577          tagp->tagline = atoi(p + 5);
2578        }
2579        if (tagp->tagkind != NULL && tagp->user_data != NULL) {
2580          break;
2581        }
2582
2583        char *pc = vim_strchr(p, ':');
2584        char *pt = vim_strchr(p, '\t');
2585        if (pc == NULL || (pt != NULL && pc > pt)) {
2586          tagp->tagkind = p;
2587        }
2588        if (pt == NULL) {
2589          break;
2590        }
2591        p = pt;
2592        MB_PTR_ADV(p);
2593      }
2594    }
2595  }
2596  if (tagp->tagkind != NULL) {
2597    for (p = tagp->tagkind;
2598         *p && *p != '\t' && *p != '\r' && *p != '\n';
2599         MB_PTR_ADV(p)) {}
2600    tagp->tagkind_end = p;
2601  }
2602  if (tagp->user_data != NULL) {
2603    for (p = tagp->user_data;
2604         *p && *p != '\t' && *p != '\r' && *p != '\n';
2605         MB_PTR_ADV(p)) {}
2606    tagp->user_data_end = p;
2607  }
2608  return retval;
2609}
2610
2611// Find out the actual file name of a tag.  Concatenate the tags file name
2612// with the matching tag file name.
2613// Returns an allocated string.
2614static char *tag_full_fname(tagptrs_T *tagp)
2615{
2616  char c = *tagp->fname_end;
2617  *tagp->fname_end = NUL;
2618  char *fullname = expand_tag_fname(tagp->fname, tagp->tag_fname, false);
2619  *tagp->fname_end = c;
2620
2621  return fullname;
2622}
2623
2624/// Jump to a tag that has been found in one of the tag files
2625///
2626/// @param lbuf_arg  line from the tags file for this tag
2627/// @param forceit  :ta with !
2628/// @param keep_help  keep help flag
2629///
2630/// @return  OK for success, NOTAGFILE when file not found, FAIL otherwise.
2631static int jumpto_tag(const char *lbuf_arg, int forceit, bool keep_help)
2632{
2633  if (postponed_split == 0 && !check_can_set_curbuf_forceit(forceit)) {
2634    return FAIL;
2635  }
2636
2637  char *pbuf_end;
2638  char *tofree_fname = NULL;
2639  tagptrs_T tagp;
2640  int retval = FAIL;
2641  int getfile_result = GETFILE_UNUSED;
2642  int search_options;
2643  win_T *curwin_save = NULL;
2644  char *full_fname = NULL;
2645  const bool old_KeyTyped = KeyTyped;       // getting the file may reset it
2646  const int l_g_do_tagpreview = g_do_tagpreview;
2647  const size_t len = matching_line_len(lbuf_arg) + 1;
2648  char *lbuf = xmalloc(len);
2649  memmove(lbuf, lbuf_arg, len);
2650
2651  char *pbuf = xmalloc(LSIZE);  // search pattern buffer
2652
2653  // parse the match line into the tagp structure
2654  if (parse_match(lbuf, &tagp) == FAIL) {
2655    tagp.fname_end = NULL;
2656    goto erret;
2657  }
2658
2659  // truncate the file name, so it can be used as a string
2660  *tagp.fname_end = NUL;
2661  char *fname = tagp.fname;
2662
2663  // copy the command to pbuf[], remove trailing CR/NL
2664  char *str = tagp.command;
2665  for (pbuf_end = pbuf; *str && *str != '\n' && *str != '\r';) {
2666    *pbuf_end++ = *str++;
2667    if (pbuf_end - pbuf + 1 >= LSIZE) {
2668      break;
2669    }
2670  }
2671  *pbuf_end = NUL;
2672
2673  {
2674    // Remove the "<Tab>fieldname:value" stuff; we don't need it here.
2675    str = pbuf;
2676    if (find_extra(&str) == OK) {
2677      // Drop a trailing "|" that terminates a generic Ex command, so it
2678      // is not executed as an empty command separator.
2679      if (str > pbuf && str[-1] == '|') {
2680        pbuf_end = str - 1;
2681      } else {
2682        pbuf_end = str;
2683      }
2684      *pbuf_end = NUL;
2685    }
2686  }
2687
2688  // Expand file name, when needed (for environment variables).
2689  // If 'tagrelative' option set, may change file name.
2690  fname = expand_tag_fname(fname, tagp.tag_fname, true);
2691  tofree_fname = fname;         // free() it later
2692
2693  // Check if the file with the tag exists before abandoning the current
2694  // file.  Also accept a file name for which there is a matching BufReadCmd
2695  // autocommand event (e.g., http://sys/file).
2696  if (!os_path_exists(fname)
2697      && !has_autocmd(EVENT_BUFREADCMD, fname, NULL)) {
2698    retval = NOTAGFILE;
2699    xfree(nofile_fname);
2700    nofile_fname = xstrdup(fname);
2701    goto erret;
2702  }
2703
2704  RedrawingDisabled++;
2705
2706  if (l_g_do_tagpreview != 0) {
2707    postponed_split = 0;        // don't split again below
2708    curwin_save = curwin;       // Save current window
2709
2710    // If we are reusing a window, we may change dir when
2711    // entering it (autocommands) so turn the tag filename
2712    // into a fullpath
2713    if (!curwin->w_p_pvw) {
2714      full_fname = FullName_save(fname, false);
2715      fname = full_fname;
2716
2717      // Make the preview window the current window.
2718      // Open a preview window when needed.
2719      prepare_tagpreview(true, *p_pvp != NUL);
2720    }
2721  }
2722
2723  // If it was a CTRL-W CTRL-] command split window now.  For ":tab tag"
2724  // open a new tab page.
2725  if (postponed_split && (swb_flags & (kOptSwbFlagUseopen | kOptSwbFlagUsetab))) {
2726    buf_T *const existing_buf = buflist_findname_exp(fname);
2727
2728    if (existing_buf != NULL) {
2729      // If 'switchbuf' is set jump to the window containing "buf".
2730      if (swbuf_goto_win_with_buf(existing_buf) != NULL) {
2731        // We've switched to the buffer, the usual loading of the file
2732        // must be skipped.
2733        getfile_result = GETFILE_SAME_FILE;
2734      }
2735    }
2736  }
2737  if (getfile_result == GETFILE_UNUSED
2738      && (postponed_split || cmdmod.cmod_tab != 0)) {
2739    if (swb_flags & kOptSwbFlagVsplit) {
2740      // If 'switchbuf' contains 'vsplit', then use a new vertically
2741      // split window.
2742      cmdmod.cmod_split |= WSP_VERT;
2743    }
2744
2745    if ((swb_flags & kOptSwbFlagNewtab) && cmdmod.cmod_tab == 0) {
2746      // If 'switchbuf' contains 'newtab', then use a new tabpage
2747      cmdmod.cmod_tab = tabpage_index(curtab) + 1;
2748    }
2749
2750    if (win_split(postponed_split > 0 ? postponed_split : 0,
2751                  postponed_split_flags) == FAIL) {
2752      RedrawingDisabled--;
2753      goto erret;
2754    }
2755    RESET_BINDING(curwin);
2756  }
2757
2758  if (keep_help) {
2759    // A :ta from a help file will keep the b_help flag set.  For ":ptag"
2760    // we need to use the flag from the window where we came from.
2761    if (l_g_do_tagpreview != 0) {
2762      keep_help_flag = bt_help(curwin_save->w_buffer);
2763    } else {
2764      keep_help_flag = curbuf->b_help;
2765    }
2766  }
2767
2768  if (getfile_result == GETFILE_UNUSED) {
2769    // Careful: getfile() may trigger autocommands and call jumpto_tag()
2770    // recursively.
2771    getfile_result = getfile(0, fname, NULL, true, 0, forceit);
2772  }
2773  keep_help_flag = false;
2774
2775  if (GETFILE_SUCCESS(getfile_result)) {    // got to the right file
2776    curwin->w_set_curswant = true;
2777    postponed_split = 0;
2778
2779    // Save no_hlsearch: jumping to a tag is not a real search
2780    const bool save_no_hlsearch = Search.no_hlsearch;
2781
2782    // If 'cpoptions' contains 't', store the search pattern for the "n"
2783    // command.  If 'cpoptions' does not contain 't', the search pattern
2784    // is not stored.
2785    if (vim_strchr(p_cpo, kCpoTagpat) != NULL) {
2786      search_options = 0;
2787    } else {
2788      search_options = SEARCH_KEEP;
2789    }
2790
2791    // If the command is a search, try here.
2792    //
2793    // Reset 'smartcase' for the search, since the search pattern was not
2794    // typed by the user.
2795    // Only use do_search() when there is a full search command, without
2796    // anything following.
2797    str = pbuf;
2798    if (pbuf[0] == '/' || pbuf[0] == '?') {
2799      str = skip_regexp(pbuf + 1, pbuf[0], false) + 1;
2800    }
2801    if (str > pbuf_end - 1) {   // search command with nothing following
2802      size_t pbuflen = (size_t)(pbuf_end - pbuf);
2803
2804      bool save_p_ws = p_ws;
2805      int save_p_ic = p_ic;
2806      int save_p_scs = p_scs;
2807      p_ws = true;              // need 'wrapscan' for backward searches
2808      p_ic = false;             // don't ignore case now
2809      p_scs = false;
2810      linenr_T save_lnum = curwin->w_cursor.lnum;
2811
2812      curwin->w_cursor.lnum = tagp.tagline > 0
2813                              // start search before line from "line:" field
2814                              ? tagp.tagline - 1
2815                              // start search before first line
2816                              : 0;
2817
2818      if (do_search(NULL, pbuf[0], pbuf[0], pbuf + 1, pbuflen - 1, 1,
2819                    search_options, false, NULL)) {
2820        retval = OK;
2821      } else {
2822        int found = 1;
2823
2824        // try again, ignore case now
2825        p_ic = true;
2826        if (!do_search(NULL, pbuf[0], pbuf[0], pbuf + 1, pbuflen - 1, 1,
2827                       search_options, false, NULL)) {
2828          // Failed to find pattern, take a guess: "^func  ("
2829          found = 2;
2830          test_for_static(&tagp);
2831          char cc = *tagp.tagname_end;
2832          *tagp.tagname_end = NUL;
2833          pbuflen = (size_t)snprintf(pbuf, LSIZE, "^%s\\s\\*(", tagp.tagname);
2834          if (!do_search(NULL, '/', '/', pbuf, pbuflen, 1, search_options, false, NULL)) {
2835            // Guess again: "^char * \<func  ("
2836            pbuflen = (size_t)snprintf(pbuf, LSIZE, "^\\[#a-zA-Z_]\\.\\*\\<%s\\s\\*(",
2837                                       tagp.tagname);
2838            if (!do_search(NULL, '/', '/', pbuf, pbuflen, 1, search_options, false, NULL)) {
2839              found = 0;
2840            }
2841          }
2842          *tagp.tagname_end = cc;
2843        }
2844        if (found == 0) {
2845          emsg(_("E434: Can't find tag pattern"));
2846          curwin->w_cursor.lnum = save_lnum;
2847        } else {
2848          // Only give a message when really guessed, not when 'ic'
2849          // is set and match found while ignoring case.
2850          if (found == 2 || !save_p_ic) {
2851            msg(_("E435: Couldn't find tag, just guessing!"), 0);
2852            if (!msg_scrolled && msg_silent == 0) {
2853              msg_delay(1010, true);
2854            }
2855          }
2856          retval = OK;
2857        }
2858      }
2859      p_ws = save_p_ws;
2860      p_ic = save_p_ic;
2861      p_scs = save_p_scs;
2862
2863      // A search command may have positioned the cursor beyond the end
2864      // of the line.  May need to correct that here.
2865      check_cursor(curwin);
2866    } else {
2867      const int save_secure = secure;
2868
2869      // Setup the sandbox for executing the command from the tags file.
2870      secure = 1;
2871      sandbox++;
2872      curwin->w_cursor.lnum = 1;  // start command in line 1
2873      curwin->w_cursor.col = 0;
2874      curwin->w_cursor.coladd = 0;
2875      do_cmdline_cmd(pbuf);
2876      retval = OK;
2877
2878      // When the command has done something that is not allowed make sure
2879      // the error message can be seen.
2880      if (secure == 2) {
2881        wait_return(true);
2882      }
2883      secure = save_secure;
2884      sandbox--;
2885    }
2886
2887    // restore no_hlsearch when keeping the old search pattern
2888    if (search_options) {
2889      set_no_hlsearch(save_no_hlsearch);
2890    }
2891
2892    // Return OK if jumped to another file (at least we found the file!).
2893    if (getfile_result == GETFILE_OPEN_OTHER) {
2894      retval = OK;
2895    }
2896
2897    if (retval == OK) {
2898      // For a help buffer: Put the cursor line at the top of the window,
2899      // the help subject will be below it.
2900      if (curbuf->b_help) {
2901        set_topline(curwin, curwin->w_cursor.lnum);
2902      }
2903      if ((fdo_flags & kOptFdoFlagTag) && old_KeyTyped) {
2904        foldOpenCursor();
2905      }
2906    }
2907
2908    if (l_g_do_tagpreview != 0
2909        && curwin != curwin_save && win_valid(curwin_save)) {
2910      // Return cursor to where we were
2911      validate_cursor(curwin);
2912      redraw_later(curwin, UPD_VALID);
2913      win_enter(curwin_save, true);
2914    }
2915
2916    RedrawingDisabled--;
2917  } else {
2918    RedrawingDisabled--;
2919    if (postponed_split) {              // close the window
2920      win_close(curwin, false, false);
2921      postponed_split = 0;
2922    }
2923  }
2924
2925erret:
2926  g_do_tagpreview = 0;  // For next time
2927  xfree(lbuf);
2928  xfree(pbuf);
2929  xfree(tofree_fname);
2930  xfree(full_fname);
2931
2932  return retval;
2933}
2934
2935/// If "expand" is true, expand wildcards in fname.
2936/// If 'tagrelative' option set, change fname (name of file containing tag)
2937/// according to tag_fname (name of tag file containing fname).
2938///
2939/// @return  a pointer to allocated memory.
2940static char *expand_tag_fname(char *fname, char *const tag_fname, const bool expand)
2941  FUNC_ATTR_NONNULL_RET
2942{
2943  char *p;
2944  char *expanded_fname = NULL;
2945  expand_T xpc;
2946
2947  fname = TO_SLASH_SAVE(fname);
2948
2949  // Expand file name (for environment variables) when needed.
2950  // Disallow backticks, they could execute arbitrary shell
2951  // commands.  This is not needed for tag filenames.
2952  if (expand && path_has_wildcard(fname, true) && vim_strchr(fname, '`') == NULL) {
2953    ExpandInit(&xpc);
2954    xpc.xp_context = EXPAND_FILES;
2955    expanded_fname = ExpandOne(&xpc, fname, NULL,
2956                               WILD_LIST_NOTFOUND|WILD_SILENT, WILD_EXPAND_FREE);
2957    if (expanded_fname != NULL) {
2958      xfree(fname);
2959      fname = expanded_fname;
2960    }
2961  }
2962
2963  char *retval;
2964  if ((p_tr || curbuf->b_help)
2965      && !vim_isAbsName(fname)
2966      && (p = path_tail(tag_fname)) != tag_fname) {
2967    retval = xmalloc(MAXPATHL);
2968    STRCPY(retval, tag_fname);
2969    xstrlcpy(retval + (p - tag_fname), fname, (size_t)(MAXPATHL - (p - tag_fname)));
2970    // Translate names like "src/a/../b/file.c" into "src/b/file.c".
2971    simplify_filename(retval);
2972  } else {
2973    retval = xstrdup(fname);
2974  }
2975
2976  xfree(fname);
2977
2978  return retval;
2979}
2980
2981/// Check if we have a tag for the buffer with name "buf_ffname".
2982/// This is a bit slow, because of the full path compare in path_equal().
2983///
2984/// @return  true if tag for file "fname" if tag file "tag_fname" is for current
2985///          file.
2986static int test_for_current(char *fname, char *fname_end, char *tag_fname, char *buf_ffname)
2987{
2988  int retval = false;
2989
2990  if (buf_ffname != NULL) {     // if the buffer has a name
2991    char c;
2992    {
2993      c = *fname_end;
2994      *fname_end = NUL;
2995    }
2996    char *fullname = expand_tag_fname(fname, tag_fname, true);
2997    retval = path_equal(fullname, buf_ffname, kPathCmpExpand | kPathCmpFull);
2998    xfree(fullname);
2999    *fname_end = c;
3000  }
3001
3002  return retval;
3003}
3004
3005// Find the end of the tagaddress.
3006// Return OK if ";\"" is following, FAIL otherwise.
3007static int find_extra(char **pp)
3008{
3009  char *str = *pp;
3010  char first_char = **pp;
3011
3012  // Repeat for addresses separated with ';'
3013  while (true) {
3014    if (ascii_isdigit(*str)) {
3015      str = skipdigits(str + 1);
3016    } else if (*str == '/' || *str == '?') {
3017      str = skip_regexp(str + 1, *str, false);
3018      if (*str != first_char) {
3019        str = NULL;
3020      } else {
3021        str++;
3022      }
3023    } else {
3024      // not a line number or search string, look for terminator.
3025      str = strstr(str, "|;\"");
3026      if (str != NULL) {
3027        str++;
3028        break;
3029      }
3030    }
3031    if (str == NULL || *str != ';'
3032        || !(ascii_isdigit(str[1]) || str[1] == '/' || str[1] == '?')) {
3033      break;
3034    }
3035    str++;  // skip ';'
3036    first_char = *str;
3037  }
3038
3039  if (str != NULL && strncmp(str, ";\"", 2) == 0) {
3040    *pp = str;
3041    return OK;
3042  }
3043  return FAIL;
3044}
3045
3046/// Free a single entry in a tag stack
3047void tagstack_clear_entry(taggy_T *item)
3048{
3049  XFREE_CLEAR(item->tagname);
3050  XFREE_CLEAR(item->user_data);
3051}
3052
3053/// @param tagnames  expand tag names
3054int expand_tags(bool tagnames, char *pat, int *num_file, char ***file)
3055{
3056  size_t name_buf_size = 100;
3057  int ret;
3058
3059  char *name_buf = xmalloc(name_buf_size);
3060
3061  int extra_flag = tagnames ? TAG_NAMES : 0;
3062  if (pat[0] == '/') {
3063    ret = find_tags(pat + 1, num_file, file,
3064                    TAG_REGEXP | extra_flag | TAG_VERBOSE,
3065                    TAG_MANY, curbuf->b_ffname);
3066  } else {
3067    ret = find_tags(pat, num_file, file,
3068                    TAG_REGEXP | extra_flag | TAG_VERBOSE | TAG_NOIC,
3069                    TAG_MANY, curbuf->b_ffname);
3070  }
3071  if (ret == OK && !tagnames) {
3072    // Reorganize the tags for display and matching as strings of:
3073    // "<tagname>\0<kind>\0<filename>\0"
3074    for (int i = 0; i < *num_file; i++) {
3075      tagptrs_T t_p;
3076      parse_match((*file)[i], &t_p);
3077      size_t len = (size_t)(t_p.tagname_end - t_p.tagname);
3078      if (len > name_buf_size - 3) {
3079        name_buf_size = len + 3;
3080        char *buf = xrealloc(name_buf, name_buf_size);
3081        name_buf = buf;
3082      }
3083
3084      memmove(name_buf, t_p.tagname, len);
3085      name_buf[len++] = 0;
3086      name_buf[len++] = (t_p.tagkind != NULL && *t_p.tagkind)
3087                        ? *t_p.tagkind : 'f';
3088      name_buf[len++] = 0;
3089      memmove((*file)[i] + len, t_p.fname, (size_t)(t_p.fname_end - t_p.fname));
3090      (*file)[i][len + (size_t)(t_p.fname_end - t_p.fname)] = 0;
3091      memmove((*file)[i], name_buf, len);
3092    }
3093  }
3094  xfree(name_buf);
3095  return ret;
3096}
3097
3098/// Add a tag field to the dictionary "dict".
3099/// Return OK or FAIL.
3100///
3101/// @param start  start of the value
3102/// @param end  after the value; can be NULL
3103static int add_tag_field(dict_T *dict, const char *field_name, const char *start, const char *end)
3104  FUNC_ATTR_NONNULL_ARG(1, 2)
3105{
3106  // Check that the field name doesn't exist yet.
3107  if (tv_dict_find(dict, field_name, -1) != NULL) {
3108    if (p_verbose > 0) {
3109      verbose_enter();
3110      smsg(0, _("Duplicate field name: %s"), field_name);
3111      verbose_leave();
3112    }
3113    return FAIL;
3114  }
3115  int len = 0;
3116  char *buf = xmalloc(MAXPATHL);
3117  if (start != NULL) {
3118    if (end == NULL) {
3119      end = start + strlen(start);
3120      while (end > start && (end[-1] == '\r' || end[-1] == '\n')) {
3121        end--;
3122      }
3123    }
3124    len = MIN((int)(end - start), MAXPATHL - 1);
3125    xmemcpyz(buf, start, (size_t)len);
3126  }
3127  buf[len] = NUL;
3128  int retval = tv_dict_add_str(dict, field_name, strlen(field_name), buf);
3129  xfree(buf);
3130  return retval;
3131}
3132
3133/// Add the tags matching the specified pattern "pat" to the list "list"
3134/// as a dictionary. Use "buf_fname" for priority, unless NULL.
3135int get_tags(list_T *list, char *pat, char *buf_fname)
3136{
3137  int num_matches;
3138  char **matches;
3139  tagptrs_T tp;
3140
3141  int ret = find_tags(pat, &num_matches, &matches, TAG_REGEXP | TAG_NOIC, MAXCOL, buf_fname);
3142  if (ret != OK || num_matches <= 0) {
3143    return ret;
3144  }
3145
3146  for (int i = 0; i < num_matches; i++) {
3147    if (parse_match(matches[i], &tp) == FAIL) {
3148      xfree(matches[i]);
3149      continue;
3150    }
3151
3152    bool is_static = test_for_static(&tp);
3153
3154    // Skip pseudo-tag lines.
3155    if (strncmp(tp.tagname, "!_TAG_", 6) == 0) {
3156      xfree(matches[i]);
3157      continue;
3158    }
3159
3160    dict_T *dict = tv_dict_alloc();
3161    tv_list_append_dict(list, dict);
3162
3163    char *full_fname = tag_full_fname(&tp);
3164    if (add_tag_field(dict, "name", tp.tagname, tp.tagname_end) == FAIL
3165        || add_tag_field(dict, "filename", full_fname, NULL) == FAIL
3166        || add_tag_field(dict, "cmd", tp.command, tp.command_end) == FAIL
3167        || add_tag_field(dict, "kind", tp.tagkind,
3168                         tp.tagkind ? tp.tagkind_end : NULL) == FAIL
3169        || tv_dict_add_nr(dict, S_LEN("static"), is_static) == FAIL) {
3170      ret = FAIL;
3171    }
3172
3173    xfree(full_fname);
3174
3175    if (tp.command_end != NULL) {
3176      for (char *p = tp.command_end + 3;
3177           *p != NUL && *p != '\n' && *p != '\r';
3178           MB_PTR_ADV(p)) {
3179        if (p == tp.tagkind
3180            || (p + 5 == tp.tagkind && strncmp(p, "kind:", 5) == 0)) {
3181          // skip "kind:<kind>" and "<kind>"
3182          p = tp.tagkind_end - 1;
3183        } else if (strncmp(p, "file:", 5) == 0) {
3184          // skip "file:" (static tag)
3185          p += 4;
3186        } else if (!ascii_iswhite(*p)) {
3187          int len;
3188
3189          // Add extra field as a dict entry.  Fields are
3190          // separated by Tabs.
3191          char *n = p;
3192          while (*p != NUL && *p >= ' ' && *p < 127 && *p != ':') {
3193            p++;
3194          }
3195          len = (int)(p - n);
3196          if (*p == ':' && len > 0) {
3197            char *s = ++p;
3198            while (*p != NUL && (uint8_t)(*p) >= ' ') {
3199              p++;
3200            }
3201            n[len] = NUL;
3202            if (add_tag_field(dict, n, s, p) == FAIL) {
3203              ret = FAIL;
3204            }
3205            n[len] = ':';
3206          } else {
3207            // Skip field without colon.
3208            while (*p != NUL && (uint8_t)(*p) >= ' ') {
3209              p++;
3210            }
3211          }
3212          if (*p == NUL) {
3213            break;
3214          }
3215        }
3216      }
3217    }
3218
3219    xfree(matches[i]);
3220  }
3221  xfree(matches);
3222  return ret;
3223}
3224
3225// Return information about 'tag' in dict 'retdict'.
3226static void get_tag_details(taggy_T *tag, dict_T *retdict)
3227{
3228  tv_dict_add_str(retdict, S_LEN("tagname"), tag->tagname);
3229  tv_dict_add_nr(retdict, S_LEN("matchnr"), tag->cur_match + 1);
3230  tv_dict_add_nr(retdict, S_LEN("bufnr"), tag->cur_fnum);
3231  if (tag->user_data) {
3232    tv_dict_add_str(retdict, S_LEN("user_data"), tag->user_data);
3233  }
3234
3235  list_T *pos = tv_list_alloc(4);
3236  tv_dict_add_list(retdict, S_LEN("from"), pos);
3237
3238  fmark_T *fmark = &tag->fmark;
3239  tv_list_append_number(pos,
3240                        (varnumber_T)(fmark->fnum != -1 ? fmark->fnum : 0));
3241  tv_list_append_number(pos, (varnumber_T)fmark->mark.lnum);
3242  tv_list_append_number(pos, (varnumber_T)(fmark->mark.col == MAXCOL
3243                                           ? MAXCOL : fmark->mark.col + 1));
3244  tv_list_append_number(pos, (varnumber_T)fmark->mark.coladd);
3245}
3246
3247// Return the tag stack entries of the specified window 'wp' in dictionary
3248// 'retdict'.
3249void get_tagstack(win_T *wp, dict_T *retdict)
3250{
3251  tv_dict_add_nr(retdict, S_LEN("length"), wp->w_tagstacklen);
3252  tv_dict_add_nr(retdict, S_LEN("curidx"), wp->w_tagstackidx + 1);
3253  list_T *l = tv_list_alloc(2);
3254  tv_dict_add_list(retdict, S_LEN("items"), l);
3255
3256  for (int i = 0; i < wp->w_tagstacklen; i++) {
3257    dict_T *d = tv_dict_alloc();
3258    tv_list_append_dict(l, d);
3259    get_tag_details(&wp->w_tagstack[i], d);
3260  }
3261}
3262
3263// Free all the entries in the tag stack of the specified window
3264static void tagstack_clear(win_T *wp)
3265{
3266  // Free the current tag stack
3267  for (int i = 0; i < wp->w_tagstacklen; i++) {
3268    tagstack_clear_entry(&wp->w_tagstack[i]);
3269  }
3270  wp->w_tagstacklen = 0;
3271  wp->w_tagstackidx = 0;
3272}
3273
3274// Remove the oldest entry from the tag stack and shift the rest of
3275// the entries to free up the top of the stack.
3276static void tagstack_shift(win_T *wp)
3277{
3278  taggy_T *tagstack = wp->w_tagstack;
3279  tagstack_clear_entry(&tagstack[0]);
3280  for (int i = 1; i < wp->w_tagstacklen; i++) {
3281    tagstack[i - 1] = tagstack[i];
3282  }
3283  wp->w_tagstacklen--;
3284}
3285
3286/// Push a new item to the tag stack
3287static void tagstack_push_item(win_T *wp, char *tagname, int cur_fnum, int cur_match, pos_T mark,
3288                               int fnum, char *user_data)
3289{
3290  taggy_T *tagstack = wp->w_tagstack;
3291  int idx = wp->w_tagstacklen;  // top of the stack
3292
3293  // if the tagstack is full: remove the oldest entry
3294  if (idx >= TAGSTACKSIZE) {
3295    tagstack_shift(wp);
3296    idx = TAGSTACKSIZE - 1;
3297  }
3298
3299  wp->w_tagstacklen++;
3300  tagstack[idx].tagname = tagname;
3301  tagstack[idx].cur_fnum = cur_fnum;
3302  tagstack[idx].cur_match = cur_match;
3303  tagstack[idx].cur_match = MAX(tagstack[idx].cur_match, 0);
3304  tagstack[idx].fmark.mark = mark;
3305  tagstack[idx].fmark.fnum = fnum;
3306  tagstack[idx].fmark.view = (fmarkv_T)INIT_FMARKV;
3307  tagstack[idx].user_data = user_data;
3308}
3309
3310/// Add a list of items to the tag stack in the specified window
3311static void tagstack_push_items(win_T *wp, list_T *l)
3312{
3313  dictitem_T *di;
3314  char *tagname;
3315  pos_T mark;
3316  int fnum;
3317
3318  // Add one entry at a time to the tag stack
3319  for (listitem_T *li = tv_list_first(l); li != NULL; li = TV_LIST_ITEM_NEXT(l, li)) {
3320    if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT
3321        || TV_LIST_ITEM_TV(li)->vval.v_dict == NULL) {
3322      continue;  // Skip non-dict items
3323    }
3324    dict_T *itemdict = TV_LIST_ITEM_TV(li)->vval.v_dict;
3325
3326    // parse 'from' for the cursor position before the tag jump
3327    if ((di = tv_dict_find(itemdict, "from", -1)) == NULL) {
3328      continue;
3329    }
3330    if (list2fpos(&di->di_tv, &mark, &fnum, NULL, false) != OK) {
3331      continue;
3332    }
3333    if ((tagname = tv_dict_get_string(itemdict, "tagname", true)) == NULL) {
3334      continue;
3335    }
3336
3337    if (mark.col > 0) {
3338      mark.col--;
3339    }
3340    tagstack_push_item(wp,
3341                       tagname,
3342                       (int)tv_dict_get_number(itemdict, "bufnr"),
3343                       (int)tv_dict_get_number(itemdict, "matchnr") - 1,
3344                       mark, fnum,
3345                       tv_dict_get_string(itemdict, "user_data", true));
3346  }
3347}
3348
3349// Set the current index in the tag stack. Valid values are between 0
3350// and the stack length (inclusive).
3351static void tagstack_set_curidx(win_T *wp, int curidx)
3352{
3353  wp->w_tagstackidx = curidx;
3354  // sanity check
3355  wp->w_tagstackidx = MIN(MAX(wp->w_tagstackidx, 0), wp->w_tagstacklen);
3356}
3357
3358// Set the tag stack entries of the specified window.
3359// 'action' is set to one of:
3360//    'a' for append
3361//    'r' for replace
3362//    't' for truncate
3363int set_tagstack(win_T *wp, const dict_T *d, int action)
3364  FUNC_ATTR_NONNULL_ARG(1)
3365{
3366  // not allowed to alter the tag stack entries from inside tagfunc
3367  if (tfu_in_use) {
3368    emsg(_(e_cannot_modify_tag_stack_within_tagfunc));
3369    return FAIL;
3370  }
3371
3372  dictitem_T *di;
3373  list_T *l = NULL;
3374
3375  if ((di = tv_dict_find(d, "items", -1)) != NULL) {
3376    if (di->di_tv.v_type != VAR_LIST) {
3377      emsg(_(e_listreq));
3378      return FAIL;
3379    }
3380    l = di->di_tv.vval.v_list;
3381  }
3382
3383  if ((di = tv_dict_find(d, "curidx", -1)) != NULL) {
3384    tagstack_set_curidx(wp, (int)tv_get_number(&di->di_tv) - 1);
3385  }
3386
3387  if (action == 't') {  // truncate the stack
3388    taggy_T *const tagstack = wp->w_tagstack;
3389    const int tagstackidx = wp->w_tagstackidx;
3390    int tagstacklen = wp->w_tagstacklen;
3391
3392    // delete all the tag stack entries above the current entry
3393    while (tagstackidx < tagstacklen) {
3394      tagstack_clear_entry(&tagstack[--tagstacklen]);
3395    }
3396    wp->w_tagstacklen = tagstacklen;
3397  }
3398
3399  if (l != NULL) {
3400    if (action == 'r') {  // replace the stack
3401      tagstack_clear(wp);
3402    }
3403
3404    tagstack_push_items(wp, l);
3405    // set the current index after the last entry
3406    wp->w_tagstackidx = wp->w_tagstacklen;
3407  }
3408
3409  return OK;
3410}