robin/laufey

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

bfredlMerge pull request #41212 from bfredl/unmagic8a0eb8f10b

master
224.2 KiB7839 linesraw
1// quickfix.c: functions for quickfix mode, using a file with error messages
2
3#include <assert.h>
4#include <errno.h>
5#include <inttypes.h>
6#include <limits.h>
7#include <stdbool.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <time.h>
12
13#include "nvim/arglist.h"
14#include "nvim/ascii_defs.h"
15#include "nvim/autocmd.h"
16#include "nvim/autocmd_defs.h"
17#include "nvim/buffer.h"
18#include "nvim/buffer_defs.h"
19#include "nvim/change.h"
20#include "nvim/charset.h"
21#include "nvim/context.h"
22#include "nvim/cursor.h"
23#include "nvim/drawscreen.h"
24#include "nvim/errors.h"
25#include "nvim/eval.h"
26#include "nvim/eval/typval.h"
27#include "nvim/eval/vars.h"
28#include "nvim/eval/window.h"
29#include "nvim/ex_cmds.h"
30#include "nvim/ex_cmds2.h"
31#include "nvim/ex_cmds_defs.h"
32#include "nvim/ex_docmd.h"
33#include "nvim/ex_eval.h"
34#include "nvim/ex_eval_defs.h"
35#include "nvim/ex_getln.h"
36#include "nvim/extmark.h"
37#include "nvim/fileio.h"
38#include "nvim/fold.h"
39#include "nvim/fuzzy.h"
40#include "nvim/garray.h"
41#include "nvim/garray_defs.h"
42#include "nvim/gettext_defs.h"
43#include "nvim/globals.h"
44#include "nvim/help.h"
45#include "nvim/highlight_defs.h"
46#include "nvim/highlight_group.h"
47#include "nvim/insert.h"
48#include "nvim/macros_defs.h"
49#include "nvim/mark.h"
50#include "nvim/mbyte.h"
51#include "nvim/mbyte_defs.h"
52#include "nvim/memline.h"
53#include "nvim/memline_defs.h"
54#include "nvim/memory.h"
55#include "nvim/message.h"
56#include "nvim/move.h"
57#include "nvim/normal.h"
58#include "nvim/ops.h"
59#include "nvim/option.h"
60#include "nvim/option_defs.h"
61#include "nvim/option_vars.h"
62#include "nvim/optionstr.h"
63#include "nvim/os/fs.h"
64#include "nvim/os/fs_defs.h"
65#include "nvim/os/input.h"
66#include "nvim/os/os.h"
67#include "nvim/os/os_defs.h"
68#include "nvim/path.h"
69#include "nvim/pos_defs.h"
70#include "nvim/quickfix.h"
71#include "nvim/regexp.h"
72#include "nvim/regexp_defs.h"
73#include "nvim/search.h"
74#include "nvim/strings.h"
75#include "nvim/types_defs.h"
76#include "nvim/ui.h"
77#include "nvim/undo.h"
78#include "nvim/vim_defs.h"
79#include "nvim/window.h"
80
81struct dir_stack_T {
82  struct dir_stack_T *next;
83  char *dirname;
84};
85
86// For each error the next struct is allocated and linked in a list.
87typedef struct qfline_S qfline_T;
88struct qfline_S {
89  qfline_T *qf_next;      ///< pointer to next error in the list
90  qfline_T *qf_prev;      ///< pointer to previous error in the list
91  linenr_T qf_lnum;       ///< line number where the error occurred
92  linenr_T qf_end_lnum;   ///< line number when the error has range or zero
93
94  int qf_fnum;            ///< file number for the line
95  int qf_col;             ///< column where the error occurred
96  int qf_end_col;         ///< column when the error has range or zero
97  int qf_nr;              ///< error number
98  char *qf_module;        ///< module name for this error
99  char *qf_fname;         ///< different filename if there're hard links
100  char *qf_pattern;       ///< search pattern for the error
101  char *qf_text;          ///< description of the error
102  char qf_viscol;         ///< set to true if qf_col and qf_end_col is screen column
103  char qf_cleared;        ///< set to true if line has been deleted
104  char qf_type;           ///< type of the error (mostly 'E'); 1 for :helpgrep
105  typval_T qf_user_data;  ///< custom user data associated with this item
106  char qf_valid;          ///< valid error message detected
107};
108
109// There is a stack of error lists.
110#define INVALID_QFIDX (-1)
111#define INVALID_QFBUFNR (0)
112
113/// Quickfix list type.
114typedef enum {
115  QFLT_QUICKFIX,  ///< Quickfix list - global list
116  QFLT_LOCATION,  ///< Location list - per window list
117  QFLT_INTERNAL,  ///< Internal - Temporary list used by
118  //   getqflist()/getloclist()
119} qfltype_T;
120
121/// Quickfix/Location list definition
122///
123/// Usually the list contains one or more entries. But an empty list can be
124/// created using setqflist()/setloclist() with a title and/or user context
125/// information and entries can be added later using setqflist()/setloclist().
126typedef struct {
127  unsigned qf_id;         ///< Unique identifier for this list
128  qfltype_T qfl_type;
129  qfline_T *qf_start;     ///< pointer to the first error
130  qfline_T *qf_last;      ///< pointer to the last error
131  qfline_T *qf_ptr;       ///< pointer to the current error
132  int qf_count;           ///< number of errors (0 means empty list)
133  int qf_index;           ///< current index in the error list
134  bool qf_nonevalid;      ///< true if not a single valid entry found
135  bool qf_has_user_data;  ///< true if at least one item has user_data attached
136  char *qf_title;         ///< title derived from the command that created
137                          ///< the error list or set by setqflist
138  typval_T *qf_ctx;       ///< context set by setqflist/setloclist
139  Callback qf_qftf_cb;    ///< 'quickfixtextfunc' callback function
140
141  struct dir_stack_T *qf_dir_stack;
142  char *qf_directory;
143  struct dir_stack_T *qf_file_stack;
144  char *qf_currfile;
145  bool qf_multiline;
146  bool qf_multiignore;
147  bool qf_multiscan;
148  int qf_changedtick;
149} qf_list_T;
150
151/// Quickfix/Location list stack definition
152/// Contains a list of quickfix/location lists (qf_list_T)
153struct qf_info_S {
154  // Count of references to this list. Used only for location lists.
155  // When a location list window reference this list, qf_refcount
156  // will be 2. Otherwise, qf_refcount will be 1. When qf_refcount
157  // reaches 0, the list is freed.
158  int qf_refcount;
159  int qf_listcount;                 // current number of lists
160  int qf_curlist;                   // current error list
161  int qf_maxcount;                  // maximum number of lists
162  qf_list_T *qf_lists;
163  qfltype_T qfl_type;  // type of list
164  int qf_bufnr;                     // quickfix window buffer number
165};
166
167static qf_info_T ql_info_actual;  // global quickfix list
168static qf_info_T *ql_info;        // points to ql_info_actual after allocation
169static unsigned last_qf_id = 0;   // Last Used quickfix list id
170
171#define FMT_PATTERNS 14           // maximum number of % recognized
172
173// Structure used to hold the info of one part of 'errorformat'
174typedef struct efm_S efm_T;
175struct efm_S {
176  regprog_T *prog;        // pre-formatted part of 'errorformat'
177  efm_T *next;        // pointer to next (NULL if last)
178  char addr[FMT_PATTERNS];    // indices of used % patterns
179  char prefix;                // prefix of this format line:
180                              // 'D' enter directory
181                              // 'X' leave directory
182                              // 'A' start of multi-line message
183                              // 'E' error message
184                              // 'W' warning message
185                              // 'I' informational message
186                              // 'N' note message
187                              // 'C' continuation line
188                              // 'Z' end of multi-line message
189                              // 'G' general, unspecific message
190                              // 'P' push file (partial) message
191                              // 'Q' pop/quit file (partial) message
192                              // 'O' overread (partial) message
193  char flags;                 // additional flags given in prefix
194                              // '-' do not include this line
195                              // '+' include whole line in message
196  int conthere;                 // %> used
197};
198
199/// List of location lists to be deleted.
200/// Used to delay the deletion of locations lists by autocmds.
201typedef struct qf_delq_S {
202  struct qf_delq_S *next;
203  qf_info_T *qi;
204} qf_delq_T;
205
206enum {
207  QF_FAIL = 0,
208  QF_OK = 1,
209  QF_END_OF_INPUT = 2,
210  QF_NOMEM = 3,
211  QF_IGNORE_LINE = 4,
212  QF_MULTISCAN = 5,
213  QF_ABORT = 6,
214};
215
216/// State information used to parse lines and add entries to a quickfix/location
217/// list.
218typedef struct {
219  char *linebuf;
220  size_t linelen;
221  char *growbuf;
222  size_t growbufsiz;
223  FILE *fd;
224  typval_T *tv;
225  char *p_str;
226  list_T *p_list;
227  listitem_T *p_li;
228  buf_T *buf;
229  linenr_T buflnum;
230  linenr_T lnumlast;
231  vimconv_T vc;
232} qfstate_T;
233
234typedef struct {
235  char *namebuf;
236  int bnr;
237  char *module;
238  char *errmsg;
239  size_t errmsglen;
240  linenr_T lnum;
241  linenr_T end_lnum;
242  int col;
243  int end_col;
244  bool use_viscol;
245  char *pattern;
246  int enr;
247  char type;
248  typval_T *user_data;
249  bool valid;
250} qffields_T;
251
252/// :vimgrep command arguments
253typedef struct {
254  int tomatch;          ///< maximum number of matches to find
255  char *spat;          ///< search pattern
256  int flags;             ///< search modifier
257  char **fnames;       ///< list of files to search
258  int fcount;            ///< number of files
259  regmmatch_T regmatch;  ///< compiled search pattern
260  char *qf_title;      ///< quickfix list title
261} vgr_args_T;
262
263#include "quickfix.c.generated.h"
264
265static const char *e_no_more_items = N_("E553: No more items");
266static const char *e_current_quickfix_list_was_changed =
267  N_("E925: Current quickfix list was changed");
268static const char *e_current_location_list_was_changed =
269  N_("E926: Current location list was changed");
270
271enum { QF_WINHEIGHT = 10, };  ///< default height for quickfix window
272
273// Quickfix window check helper macro
274#define IS_QF_WINDOW(wp) (bt_quickfix((wp)->w_buffer) && (wp)->w_llist_ref == NULL)
275// Location list window check helper macro
276#define IS_LL_WINDOW(wp) (bt_quickfix((wp)->w_buffer) && (wp)->w_llist_ref != NULL)
277
278// Quickfix and location list stack check helper macros
279#define IS_QF_STACK(qi)       ((qi)->qfl_type == QFLT_QUICKFIX)
280#define IS_LL_STACK(qi)       ((qi)->qfl_type == QFLT_LOCATION)
281#define IS_QF_LIST(qfl)       ((qfl)->qfl_type == QFLT_QUICKFIX)
282#define IS_LL_LIST(qfl)       ((qfl)->qfl_type == QFLT_LOCATION)
283
284// Return location list for window 'wp'
285// For location list window, return the referenced location list
286#define GET_LOC_LIST(wp) (IS_LL_WINDOW(wp) ? (wp)->w_llist_ref : (wp)->w_llist)
287
288// Macro to loop through all the items in a quickfix list
289// Quickfix item index starts from 1, so i below starts at 1
290#define FOR_ALL_QFL_ITEMS(qfl, qfp, i) \
291  for ((i) = 1, (qfp) = (qfl)->qf_start; \
292       !got_int && (i) <= (qfl)->qf_count && (qfp) != NULL; \
293       (i)++, (qfp) = (qfp)->qf_next)
294
295// Looking up a buffer can be slow if there are many.  Remember the last one
296// to make this a lot faster if there are multiple matches in the same file.
297static char *qf_last_bufname = NULL;
298static bufref_T qf_last_bufref = { NULL, 0, 0 };
299
300static garray_T qfga;
301
302/// Get a growarray to buffer text in.  Shared between various commands to avoid
303/// many alloc/free calls.
304static garray_T *qfga_get(void)
305{
306  static bool initialized = false;
307
308  if (!initialized) {
309    initialized = true;
310    ga_init(&qfga, 1, 256);
311  }
312
313  // Reset the length to zero.  Retain ga_data from previous use to avoid
314  // many alloc/free calls.
315  qfga.ga_len = 0;
316
317  return &qfga;
318}
319
320/// The "qfga" grow array buffer is reused across multiple quickfix commands as
321/// a temporary buffer to reduce the number of alloc/free calls.  But if the
322/// buffer size is large, then to avoid holding on to that memory, clear the
323/// grow array.  Otherwise just reset the grow array length.
324static void qfga_clear(void)
325{
326  if (qfga.ga_maxlen > 1000) {
327    ga_clear(&qfga);
328  } else {
329    qfga.ga_len = 0;
330  }
331}
332
333// Counter to prevent autocmds from freeing up location lists when they are
334// still being used.
335static int quickfix_busy = 0;
336static qf_delq_T *qf_delq_head = NULL;
337
338/// Process the next line from a file/buffer/list/string and add it
339/// to the quickfix list 'qfl'.
340static int qf_init_process_nextline(qf_list_T *qfl, efm_T *fmt_first, qfstate_T *state,
341                                    qffields_T *fields)
342{
343  // Get the next line from a file/buffer/list/string
344  int status = qf_get_nextline(state);
345  if (status != QF_OK) {
346    return status;
347  }
348
349  status = qf_parse_line(qfl, state->linebuf, state->linelen,
350                         fmt_first, fields);
351  if (status != QF_OK) {
352    return status;
353  }
354
355  return qf_add_entry(qfl,
356                      qfl->qf_directory,
357                      (*fields->namebuf || qfl->qf_directory != NULL)
358                      ? fields->namebuf
359                      : ((qfl->qf_currfile != NULL && fields->valid)
360                         ? qfl->qf_currfile : NULL),
361                      fields->module,
362                      fields->bnr,
363                      fields->errmsg,
364                      fields->lnum,
365                      fields->end_lnum,
366                      fields->col,
367                      fields->end_col,
368                      fields->use_viscol,
369                      fields->pattern,
370                      fields->enr,
371                      fields->type,
372                      fields->user_data,
373                      fields->valid);
374}
375
376/// Read the errorfile "efile" into memory, line by line, building the error
377/// list. Set the error list's title to qf_title.
378///
379/// @params  wp  If non-NULL, make a location list
380/// @params  efile  If non-NULL, errorfile to parse
381/// @params  errorformat  'errorformat' string used to parse the error lines
382/// @params  newlist  If true, create a new error list
383/// @params  qf_title  If non-NULL, title of the error list
384/// @params  enc  If non-NULL, encoding used to parse errors
385///
386/// @returns -1 for error, number of errors for success.
387int qf_init(win_T *wp, const char *restrict efile, char *restrict errorformat, int newlist,
388            const char *restrict qf_title, char *restrict enc)
389{
390  qf_info_T *qi = wp == NULL ? ql_info : ll_get_or_alloc_list(wp);
391  assert(qi != NULL);
392
393  return qf_init_ext(qi, qi->qf_curlist, efile, curbuf, NULL, errorformat,
394                     newlist, 0, 0, qf_title, enc);
395}
396
397// Maximum number of bytes allowed per line while reading an errorfile.
398static const size_t LINE_MAXLEN = 4096;
399
400/// Patterns used.  Keep in sync with qf_parse_fmt[].
401static struct fmtpattern {
402  char convchar;
403  char *pattern;
404} fmt_pat[FMT_PATTERNS] = {
405  { 'f', ".\\+" },      // only used when at end
406  { 'b', "\\d\\+" },    // 1
407  { 'n', "\\d\\+" },    // 2
408  { 'l', "\\d\\+" },    // 3
409  { 'e', "\\d\\+" },    // 4
410  { 'c', "\\d\\+" },    // 5
411  { 'k', "\\d\\+" },    // 6
412  { 't', "." },         // 7
413#define FMT_PATTERN_M 8
414  { 'm', ".\\+" },      // 8
415#define FMT_PATTERN_R 9
416  { 'r', ".*" },        // 9
417  { 'p', "[-\t .]*" },  // 10
418  { 'v', "\\d\\+" },    // 11
419  { 's', ".\\+" },      // 12
420  { 'o', ".\\+" }       // 13
421};
422
423/// Convert an errorformat pattern to a regular expression pattern.
424/// See fmt_pat definition above for the list of supported patterns.  The
425/// pattern specifier is supplied in "efmpat".  The converted pattern is stored
426/// in "regpat".  Returns a pointer to the location after the pattern.
427static char *efmpat_to_regpat(const char *efmpat, char *regpat, efm_T *efminfo, int idx, int round)
428  FUNC_ATTR_NONNULL_ALL
429{
430  if (efminfo->addr[idx]) {
431    // Each errorformat pattern can occur only once
432    semsg(_("E372: Too many %%%c in format string"), *efmpat);
433    return NULL;
434  }
435  if ((idx && idx < FMT_PATTERN_R
436       && vim_strchr("DXOPQ", (uint8_t)efminfo->prefix) != NULL)
437      || (idx == FMT_PATTERN_R
438          && vim_strchr("OPQ", (uint8_t)efminfo->prefix) == NULL)) {
439    semsg(_("E373: Unexpected %%%c in format string"), *efmpat);
440    return NULL;
441  }
442  efminfo->addr[idx] = (char)++round;
443  *regpat++ = '\\';
444  *regpat++ = '(';
445#ifdef BACKSLASH_IN_FILENAME
446  if (*efmpat == 'f') {
447    // Also match "c:" in the file name, even when
448    // checking for a colon next: "%f:".
449    // "\%(\a:\)\="
450    STRCPY(regpat, "\\%(\\a:\\)\\=");
451    regpat += 10;
452  }
453#endif
454  if (*efmpat == 'f' && efmpat[1] != NUL) {
455    if (efmpat[1] != '\\' && efmpat[1] != '%') {
456      // A file name may contain spaces, but this isn't
457      // in "\f".  For "%f:%l:%m" there may be a ":" in
458      // the file name.  Use ".\{-1,}x" instead (x is
459      // the next character), the requirement that :999:
460      // follows should work.
461      STRCPY(regpat, ".\\{-1,}");
462      regpat += 7;
463    } else {
464      // File name followed by '\\' or '%': include as
465      // many file name chars as possible.
466      STRCPY(regpat, "\\f\\+");
467      regpat += 4;
468    }
469  } else {
470    char *srcptr = fmt_pat[idx].pattern;
471    while ((*regpat = *srcptr++) != NUL) {
472      regpat++;
473    }
474  }
475  *regpat++ = '\\';
476  *regpat++ = ')';
477
478  return regpat;
479}
480
481/// Convert a scanf like format in 'errorformat' to a regular expression.
482/// Returns a pointer to the location after the pattern.
483static char *scanf_fmt_to_regpat(const char **pefmp, const char *efm, int len, char *regpat)
484  FUNC_ATTR_NONNULL_ALL
485{
486  const char *efmp = *pefmp;
487
488  if (*efmp == '[' || *efmp == '\\') {
489    if ((*regpat++ = *efmp) == '[') {  // %*[^a-z0-9] etc.
490      if (efmp[1] == '^') {
491        *regpat++ = *++efmp;
492      }
493      if (efmp < efm + len) {
494        *regpat++ = *++efmp;  // could be ']'
495        while (efmp < efm + len && (*regpat++ = *++efmp) != ']') {}
496        if (efmp == efm + len) {
497          emsg(_("E374: Missing ] in format string"));
498          return NULL;
499        }
500      }
501    } else if (efmp < efm + len) {  // %*\D, %*\s etc.
502      *regpat++ = *++efmp;
503    }
504    *regpat++ = '\\';
505    *regpat++ = '+';
506  } else {
507    semsg(_("E375: Unsupported %%%c in format string"), *efmp);
508    return NULL;
509  }
510
511  *pefmp = efmp;
512
513  return regpat;
514}
515
516/// Analyze/parse an errorformat prefix.
517static const char *efm_analyze_prefix(const char *efmp, efm_T *efminfo)
518  FUNC_ATTR_NONNULL_ALL
519{
520  if (vim_strchr("+-", (uint8_t)(*efmp)) != NULL) {
521    efminfo->flags = *efmp++;
522  }
523  if (vim_strchr("DXAEWINCZGOPQ", (uint8_t)(*efmp)) != NULL) {
524    efminfo->prefix = *efmp;
525  } else {
526    semsg(_("E376: Invalid %%%c in format string prefix"), *efmp);
527    return NULL;
528  }
529
530  return efmp;
531}
532
533// Converts a 'errorformat' string to regular expression pattern
534static int efm_to_regpat(const char *efm, int len, efm_T *fmt_ptr, char *regpat)
535  FUNC_ATTR_NONNULL_ALL
536{
537  // Build regexp pattern from current 'errorformat' option
538  char *ptr = regpat;
539  *ptr++ = '^';
540  int round = 0;
541  for (const char *efmp = efm; efmp < efm + len; efmp++) {
542    if (*efmp == '%') {
543      efmp++;
544      int idx;
545      for (idx = 0; idx < FMT_PATTERNS; idx++) {
546        if (fmt_pat[idx].convchar == *efmp) {
547          break;
548        }
549      }
550      if (idx < FMT_PATTERNS) {
551        ptr = efmpat_to_regpat(efmp, ptr, fmt_ptr, idx, round);
552        if (ptr == NULL) {
553          return FAIL;
554        }
555        round++;
556      } else if (*efmp == '*') {
557        efmp++;
558        ptr = scanf_fmt_to_regpat(&efmp, efm, len, ptr);
559        if (ptr == NULL) {
560          return FAIL;
561        }
562      } else if (vim_strchr("%\\.^$~[", (uint8_t)(*efmp)) != NULL) {
563        *ptr++ = *efmp;  // regexp magic characters
564      } else if (*efmp == '#') {
565        *ptr++ = '*';
566      } else if (*efmp == '>') {
567        fmt_ptr->conthere = true;
568      } else if (efmp == efm + 1) {             // analyse prefix
569        // prefix is allowed only at the beginning of the errorformat
570        // option part
571        efmp = efm_analyze_prefix(efmp, fmt_ptr);
572        if (efmp == NULL) {
573          return FAIL;
574        }
575      } else {
576        semsg(_("E377: Invalid %%%c in format string"), *efmp);
577        return FAIL;
578      }
579    } else {                    // copy normal character
580      if (*efmp == '\\' && efmp + 1 < efm + len) {
581        efmp++;
582      } else if (vim_strchr(".*^$~[", (uint8_t)(*efmp)) != NULL) {
583        *ptr++ = '\\';  // escape regexp atoms
584      }
585      if (*efmp) {
586        *ptr++ = *efmp;
587      }
588    }
589  }
590  *ptr++ = '$';
591  *ptr = NUL;
592
593  return OK;
594}
595
596static efm_T *fmt_start = NULL;  // cached across qf_parse_line() calls
597
598static void free_efm_list(efm_T **efm_first)
599{
600  for (efm_T *efm_ptr = *efm_first; efm_ptr != NULL; efm_ptr = *efm_first) {
601    *efm_first = efm_ptr->next;
602    vim_regfree(efm_ptr->prog);
603    xfree(efm_ptr);
604  }
605
606  fmt_start = NULL;
607}
608
609/// Compute the size of the buffer used to convert a 'errorformat' pattern into
610/// a regular expression pattern.
611static size_t efm_regpat_bufsz(char *efm)
612{
613  size_t sz = (FMT_PATTERNS * 3) + (strlen(efm) << 2);
614  for (int i = FMT_PATTERNS - 1; i >= 0;) {
615    sz += strlen(fmt_pat[i--].pattern);
616  }
617#ifdef BACKSLASH_IN_FILENAME
618  sz += 12;  // "%f" can become twelve chars longer (see efm_to_regpat)
619#else
620  sz += 2;  // "%f" can become two chars longer
621#endif
622
623  return sz;
624}
625
626/// Return the length of a 'errorformat' option part (separated by ",").
627static int efm_option_part_len(const char *efm)
628{
629  int len;
630
631  for (len = 0; efm[len] != NUL && efm[len] != ','; len++) {
632    if (efm[len] == '\\' && efm[len + 1] != NUL) {
633      len++;
634    }
635  }
636
637  return len;
638}
639
640/// Parse the 'errorformat' option. Multiple parts in the 'errorformat' option
641/// are parsed and converted to regular expressions. Returns information about
642/// the parsed 'errorformat' option.
643static efm_T *parse_efm_option(char *efm)
644{
645  efm_T *fmt_first = NULL;
646  efm_T *fmt_last = NULL;
647
648  // Get some space to modify the format string into.
649  size_t sz = efm_regpat_bufsz(efm);
650  char *fmtstr = xmalloc(sz);
651
652  while (efm[0] != NUL) {
653    // Allocate a new eformat structure and put it at the end of the list
654    efm_T *fmt_ptr = (efm_T *)xcalloc(1, sizeof(efm_T));
655    if (fmt_first == NULL) {        // first one
656      fmt_first = fmt_ptr;
657    } else {
658      fmt_last->next = fmt_ptr;
659    }
660    fmt_last = fmt_ptr;
661
662    // Isolate one part in the 'errorformat' option
663    int len = efm_option_part_len(efm);
664
665    if (efm_to_regpat(efm, len, fmt_ptr, fmtstr) == FAIL) {
666      goto parse_efm_error;
667    }
668    if ((fmt_ptr->prog = vim_regcomp(fmtstr, RE_MAGIC + RE_STRING)) == NULL) {
669      goto parse_efm_error;
670    }
671    // Advance to next part
672    efm = skip_to_option_part(efm + len);       // skip comma and spaces
673  }
674
675  if (fmt_first == NULL) {      // nothing found
676    emsg(_("E378: 'errorformat' contains no pattern"));
677  }
678
679  goto parse_efm_end;
680
681parse_efm_error:
682  free_efm_list(&fmt_first);
683
684parse_efm_end:
685  xfree(fmtstr);
686
687  return fmt_first;
688}
689
690/// Allocate more memory for the line buffer used for parsing lines.
691static char *qf_grow_linebuf(qfstate_T *state, size_t newsz)
692{
693  // If the line exceeds LINE_MAXLEN exclude the last
694  // byte since it's not a NL character.
695  state->linelen = newsz > LINE_MAXLEN ? LINE_MAXLEN - 1 : newsz;
696  if (state->growbuf == NULL) {
697    state->growbuf = xmalloc(state->linelen + 1);
698    state->growbufsiz = state->linelen;
699  } else if (state->linelen > state->growbufsiz) {
700    state->growbuf = xrealloc(state->growbuf, state->linelen + 1);
701    state->growbufsiz = state->linelen;
702  }
703  return state->growbuf;
704}
705
706/// Get the next string (separated by newline) from state->p_str.
707static int qf_get_next_str_line(qfstate_T *state)
708{
709  // Get the next line from the supplied string
710  char *p_str = state->p_str;
711
712  if (*p_str == NUL) {  // Reached the end of the string
713    return QF_END_OF_INPUT;
714  }
715
716  char *p = vim_strchr(p_str, '\n');
717  size_t len = (p != NULL) ? (size_t)(p - p_str) + 1 : strlen(p_str);
718
719  if (len > IOSIZE - 2) {
720    state->linebuf = qf_grow_linebuf(state, len);
721  } else {
722    state->linebuf = IObuff;
723    state->linelen = len;
724  }
725  memcpy(state->linebuf, p_str, state->linelen);
726  state->linebuf[state->linelen] = NUL;
727
728  // Increment using len in order to discard the rest of the line if it
729  // exceeds LINE_MAXLEN.
730  p_str += len;
731  state->p_str = p_str;
732
733  return QF_OK;
734}
735
736/// Get the next string from the List item state->p_li.
737static int qf_get_next_list_line(qfstate_T *state)
738{
739  listitem_T *p_li = state->p_li;
740
741  // Get the next line from the supplied list
742  while (p_li != NULL
743         && (TV_LIST_ITEM_TV(p_li)->v_type != VAR_STRING
744             || TV_LIST_ITEM_TV(p_li)->vval.v_string == NULL)) {
745    p_li = TV_LIST_ITEM_NEXT(state->p_list, p_li);  // Skip non-string items.
746  }
747
748  if (p_li == NULL) {  // End of the list.
749    state->p_li = NULL;
750    return QF_END_OF_INPUT;
751  }
752
753  size_t len = strlen(TV_LIST_ITEM_TV(p_li)->vval.v_string);
754  if (len > IOSIZE - 2) {
755    state->linebuf = qf_grow_linebuf(state, len);
756  } else {
757    state->linebuf = IObuff;
758    state->linelen = len;
759  }
760
761  xstrlcpy(state->linebuf, TV_LIST_ITEM_TV(p_li)->vval.v_string,
762           state->linelen + 1);
763
764  state->p_li = TV_LIST_ITEM_NEXT(state->p_list, p_li);
765  return QF_OK;
766}
767
768/// Get the next string from state->buf.
769static int qf_get_next_buf_line(qfstate_T *state)
770{
771  // Get the next line from the supplied buffer
772  if (state->buflnum > state->lnumlast) {
773    return QF_END_OF_INPUT;
774  }
775  char *p_buf = ml_get_buf(state->buf, state->buflnum);
776  size_t len = (size_t)ml_get_buf_len(state->buf, state->buflnum);
777  state->buflnum += 1;
778
779  if (len > IOSIZE - 2) {
780    state->linebuf = qf_grow_linebuf(state, len);
781  } else {
782    state->linebuf = IObuff;
783    state->linelen = len;
784  }
785  xstrlcpy(state->linebuf, p_buf, state->linelen + 1);
786
787  return QF_OK;
788}
789
790/// Get the next string from file state->fd.
791static int qf_get_next_file_line(qfstate_T *state)
792{
793retry:
794  errno = 0;
795  if (fgets(IObuff, IOSIZE, state->fd) == NULL) {
796    if (errno == EINTR) {
797      goto retry;
798    }
799    return QF_END_OF_INPUT;
800  }
801
802  bool discard = false;
803  state->linelen = strlen(IObuff);
804  if (state->linelen == IOSIZE - 1
805      && !(IObuff[state->linelen - 1] == '\n')) {
806    // The current line exceeds IObuff, continue reading using growbuf
807    // until EOL or LINE_MAXLEN bytes is read.
808    if (state->growbuf == NULL) {
809      state->growbufsiz = 2 * (IOSIZE - 1);
810      state->growbuf = xmalloc(state->growbufsiz);
811    }
812
813    // Copy the read part of the line, excluding null-terminator
814    memcpy(state->growbuf, IObuff, IOSIZE - 1);
815    size_t growbuflen = state->linelen;
816    state->growbuf[growbuflen] = NUL;
817
818    while (true) {
819      errno = 0;
820      if (fgets(state->growbuf + growbuflen,
821                (int)(state->growbufsiz - growbuflen), state->fd) == NULL) {
822        if (errno == EINTR) {
823          continue;
824        }
825        break;
826      }
827      state->linelen = strlen(state->growbuf + growbuflen);
828      growbuflen += state->linelen;
829      if (state->growbuf[growbuflen - 1] == '\n') {
830        break;
831      }
832      if (state->growbufsiz == LINE_MAXLEN) {
833        discard = true;
834        break;
835      }
836
837      state->growbufsiz = MIN(2 * state->growbufsiz, LINE_MAXLEN);
838      state->growbuf = xrealloc(state->growbuf, state->growbufsiz);
839    }
840
841    while (discard) {
842      // The current line is longer than LINE_MAXLEN, continue reading but
843      // discard everything until EOL or EOF is reached.
844      errno = 0;
845      if (fgets(IObuff, IOSIZE, state->fd) == NULL) {
846        if (errno == EINTR) {
847          continue;
848        }
849        break;
850      }
851      if (strlen(IObuff) < IOSIZE - 1 || IObuff[IOSIZE - 2] == '\n') {
852        break;
853      }
854    }
855
856    state->linebuf = state->growbuf;
857    state->linelen = growbuflen;
858  } else {
859    state->linebuf = IObuff;
860  }
861
862  // Convert a line if it contains a non-ASCII character
863  if (state->vc.vc_type != CONV_NONE && has_non_ascii(state->linebuf)) {
864    char *line = string_convert(&state->vc, state->linebuf, &state->linelen);
865    if (line != NULL) {
866      if (state->linelen < IOSIZE) {
867        xstrlcpy(state->linebuf, line, state->linelen + 1);
868        xfree(line);
869      } else {
870        xfree(state->growbuf);
871        state->linebuf = line;
872        state->growbuf = line;
873        state->growbufsiz = MIN(state->linelen, LINE_MAXLEN);
874      }
875    }
876  }
877  return QF_OK;
878}
879
880/// Get the next string from a file/buffer/list/string.
881static int qf_get_nextline(qfstate_T *state)
882{
883  int status = QF_FAIL;
884
885  if (state->fd == NULL) {
886    if (state->tv != NULL) {
887      if (state->tv->v_type == VAR_STRING) {
888        // Get the next line from the supplied string
889        status = qf_get_next_str_line(state);
890      } else if (state->tv->v_type == VAR_LIST) {
891        // Get the next line from the supplied list
892        status = qf_get_next_list_line(state);
893      }
894    } else {
895      // Get the next line from the supplied buffer
896      status = qf_get_next_buf_line(state);
897    }
898  } else {
899    // Get the next line from the supplied file
900    status = qf_get_next_file_line(state);
901  }
902
903  if (status != QF_OK) {
904    return status;
905  }
906
907  if (state->linelen > 0 && state->linebuf[state->linelen - 1] == '\n') {
908    state->linebuf[state->linelen - 1] = NUL;
909#ifdef USE_CRNL
910    if (state->linelen > 1 && state->linebuf[state->linelen - 2] == '\r') {
911      state->linebuf[state->linelen - 2] = NUL;
912    }
913#endif
914  }
915
916  remove_bom(state->linebuf);
917
918  return QF_OK;
919}
920
921/// Returns true if the specified quickfix/location stack is empty
922static bool qf_stack_empty(const qf_info_T *qi)
923  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
924{
925  return qi == NULL || qi->qf_listcount <= 0;
926}
927
928/// Returns true if the specified quickfix/location list is empty.
929static bool qf_list_empty(qf_list_T *qfl)
930  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
931{
932  return qfl == NULL || qfl->qf_count <= 0;
933}
934
935/// Returns true if the specified quickfix/location list is not empty and
936/// has valid entries.
937static bool qf_list_has_valid_entries(qf_list_T *qfl)
938{
939  return !qf_list_empty(qfl) && !qfl->qf_nonevalid;
940}
941
942/// Return a pointer to a list in the specified quickfix stack
943static qf_list_T *qf_get_list(qf_info_T *qi, int idx)
944  FUNC_ATTR_NONNULL_ALL
945{
946  return &qi->qf_lists[idx];
947}
948
949/// Parse a line and get the quickfix fields.
950/// Return the QF_ status.
951static int qf_parse_line(qf_list_T *qfl, char *linebuf, size_t linelen, efm_T *fmt_first,
952                         qffields_T *fields)
953{
954  efm_T *fmt_ptr;
955  int idx = 0;
956  char *tail = NULL;
957  int status;
958
959restofline:
960  // If there was no %> item start at the first pattern
961  if (fmt_start == NULL) {
962    fmt_ptr = fmt_first;
963  } else {
964    // Otherwise start from the last used pattern.
965    fmt_ptr = fmt_start;
966    fmt_start = NULL;
967  }
968
969  // Try to match each part of 'errorformat' until we find a complete
970  // match or no match.
971  fields->valid = true;
972  for (; fmt_ptr != NULL; fmt_ptr = fmt_ptr->next) {
973    idx = (uint8_t)fmt_ptr->prefix;
974    status = qf_parse_get_fields(linebuf, linelen, fmt_ptr, fields,
975                                 qfl->qf_multiline, qfl->qf_multiscan,
976                                 &tail);
977    if (status == QF_NOMEM) {
978      return status;
979    }
980    if (status == QF_OK) {
981      break;
982    }
983  }
984  qfl->qf_multiscan = false;
985
986  if (fmt_ptr == NULL || idx == 'D' || idx == 'X') {
987    if (fmt_ptr != NULL) {
988      // 'D' and 'X' directory specifiers.
989      status = qf_parse_dir_pfx(idx, fields, qfl);
990      if (status != QF_OK) {
991        return status;
992      }
993    }
994    status = qf_parse_line_nomatch(linebuf, linelen, fields);
995    if (status != QF_OK) {
996      return status;
997    }
998    if (fmt_ptr == NULL) {
999      qfl->qf_multiline = qfl->qf_multiignore = false;
1000    }
1001  } else {
1002    // honor %> item
1003    if (fmt_ptr->conthere) {
1004      fmt_start = fmt_ptr;
1005    }
1006
1007    if (vim_strchr("AEWIN", idx) != NULL) {
1008      qfl->qf_multiline = true;     // start of a multi-line message
1009      qfl->qf_multiignore = false;  // reset continuation
1010    } else if (vim_strchr("CZ", idx) != NULL) {
1011      // continuation of multi-line msg
1012      status = qf_parse_multiline_pfx(idx, qfl, fields);
1013      if (status != QF_OK) {
1014        return status;
1015      }
1016    } else if (vim_strchr("OPQ", idx) != NULL) {
1017      // global file names
1018      status = qf_parse_file_pfx(idx, fields, qfl, tail);
1019      if (status == QF_MULTISCAN) {
1020        char *s = skipwhite(tail);
1021        size_t new_linelen = strlen(s);
1022        if (new_linelen >= linelen) {
1023          return QF_IGNORE_LINE;
1024        }
1025        linebuf = s;
1026        linelen = new_linelen;
1027        goto restofline;
1028      }
1029    }
1030    if (fmt_ptr->flags == '-') {  // generally exclude this line
1031      if (qfl->qf_multiline) {
1032        // also exclude continuation lines
1033        qfl->qf_multiignore = true;
1034      }
1035      return QF_IGNORE_LINE;
1036    }
1037  }
1038
1039  return QF_OK;
1040}
1041
1042// Allocate the fields used for parsing lines and populating a quickfix list.
1043static void qf_alloc_fields(qffields_T *pfields)
1044  FUNC_ATTR_NONNULL_ALL
1045{
1046  pfields->namebuf = xmalloc(CMDBUFFSIZE + 1);
1047  pfields->module = xmalloc(CMDBUFFSIZE + 1);
1048  pfields->errmsglen = CMDBUFFSIZE + 1;
1049  pfields->errmsg = xmalloc(pfields->errmsglen);
1050  pfields->pattern = xmalloc(CMDBUFFSIZE + 1);
1051}
1052
1053// Free the fields used for parsing lines and populating a quickfix list.
1054static void qf_free_fields(qffields_T *pfields)
1055  FUNC_ATTR_NONNULL_ALL
1056{
1057  xfree(pfields->namebuf);
1058  xfree(pfields->module);
1059  xfree(pfields->errmsg);
1060  xfree(pfields->pattern);
1061}
1062
1063// Setup the state information used for parsing lines and populating a
1064// quickfix list.
1065static int qf_setup_state(qfstate_T *pstate, char *restrict enc, const char *restrict efile,
1066                          typval_T *tv, buf_T *buf, linenr_T lnumfirst, linenr_T lnumlast)
1067  FUNC_ATTR_NONNULL_ARG(1)
1068{
1069  pstate->vc.vc_type = CONV_NONE;
1070  if (enc != NULL && *enc != NUL) {
1071    convert_setup(&pstate->vc, enc, p_enc);
1072  }
1073
1074  if (efile != NULL
1075      && (pstate->fd = (strequal(efile, "-")
1076                        ? fdopen(os_open_stdin_fd(), "r")
1077                        : os_fopen(efile, "r"))) == NULL) {
1078    semsg(_(e_openerrf), efile);
1079    return FAIL;
1080  }
1081
1082  if (tv != NULL) {
1083    if (tv->v_type == VAR_STRING) {
1084      pstate->p_str = tv->vval.v_string;
1085    } else if (tv->v_type == VAR_LIST) {
1086      pstate->p_li = tv_list_first(tv->vval.v_list);
1087    }
1088    pstate->tv = tv;
1089  }
1090  pstate->buf = buf;
1091  pstate->buflnum = lnumfirst;
1092  pstate->lnumlast = lnumlast;
1093
1094  return OK;
1095}
1096
1097// Cleanup the state information used for parsing lines and populating a
1098// quickfix list.
1099static void qf_cleanup_state(qfstate_T *pstate)
1100  FUNC_ATTR_NONNULL_ALL
1101{
1102  if (pstate->fd != NULL) {
1103    fclose(pstate->fd);
1104  }
1105  xfree(pstate->growbuf);
1106  if (pstate->vc.vc_type != CONV_NONE) {
1107    convert_setup(&pstate->vc, NULL, NULL);
1108  }
1109}
1110
1111/// Read the errorfile "efile" into memory, line by line, building the error
1112/// list.
1113/// Alternative: when "efile" is NULL read errors from buffer "buf".
1114/// Alternative: when "tv" is not NULL get errors from the string or list.
1115/// Always use 'errorformat' from "buf" if there is a local value.
1116/// Then "lnumfirst" and "lnumlast" specify the range of lines to use.
1117/// Set the title of the list to "qf_title".
1118///
1119/// @param newlist  true: start a new error list
1120/// @param lnumfirst  first line number to use
1121/// @param lnumlast  last line number to use
1122///
1123/// @return  -1 for error, number of errors for success.
1124static int qf_init_ext(qf_info_T *qi, int qf_idx, const char *restrict efile, buf_T *buf,
1125                       typval_T *tv, char *restrict errorformat, bool newlist, linenr_T lnumfirst,
1126                       linenr_T lnumlast, const char *restrict qf_title, char *restrict enc)
1127  FUNC_ATTR_NONNULL_ARG(1)
1128{
1129  qfstate_T state = { 0 };
1130  qffields_T fields = { 0 };
1131  qfline_T *old_last = NULL;
1132  static efm_T *fmt_first = NULL;
1133  static char *last_efm = NULL;
1134  int retval = -1;                      // default: return error flag
1135
1136  // Do not used the cached buffer, it may have been wiped out.
1137  XFREE_CLEAR(qf_last_bufname);
1138
1139  qf_alloc_fields(&fields);
1140  if (qf_setup_state(&state, enc, efile, tv, buf, lnumfirst, lnumlast) == FAIL) {
1141    goto qf_init_end;
1142  }
1143
1144  qf_list_T *qfl;
1145  bool adding = false;
1146  if (newlist || qf_idx == qi->qf_listcount) {
1147    // make place for a new list
1148    qf_new_list(qi, qf_title);
1149    qf_idx = qi->qf_curlist;
1150    qfl = qf_get_list(qi, qf_idx);
1151  } else {
1152    // Adding to existing list, use last entry.
1153    adding = true;
1154    qfl = qf_get_list(qi, qf_idx);
1155    if (!qf_list_empty(qfl)) {
1156      old_last = qfl->qf_last;
1157    }
1158  }
1159
1160  // Use the local value of 'errorformat' if it's set.
1161  char *efm = (errorformat == p_efm && tv == NULL && buf && *buf->b_p_efm != NUL)
1162              ? buf->b_p_efm
1163              : errorformat;
1164
1165  // If the errorformat didn't change between calls, then reuse the previously
1166  // parsed values.
1167  if (last_efm == NULL || (strcmp(last_efm, efm) != 0)) {
1168    // free the previously parsed data
1169    XFREE_CLEAR(last_efm);
1170    free_efm_list(&fmt_first);
1171
1172    // parse the current 'efm'
1173    fmt_first = parse_efm_option(efm);
1174    if (fmt_first != NULL) {
1175      last_efm = xstrdup(efm);
1176    }
1177  }
1178
1179  if (fmt_first == NULL) {      // nothing found
1180    goto error2;
1181  }
1182
1183  // got_int is reset here, because it was probably set when killing the
1184  // ":make" command, but we still want to read the errorfile then.
1185  got_int = false;
1186
1187  // Read the lines in the error file one by one.
1188  // Try to recognize one of the error formats in each line.
1189  while (!got_int) {
1190    int status = qf_init_process_nextline(qfl, fmt_first, &state, &fields);
1191    if (status == QF_END_OF_INPUT) {  // end of input
1192      break;
1193    }
1194    if (status == QF_FAIL) {
1195      goto error2;
1196    }
1197
1198    line_breakcheck();
1199  }
1200  if (state.fd == NULL || !ferror(state.fd)) {
1201    if (qfl->qf_index == 0) {
1202      // no valid entry found
1203      qfl->qf_ptr = qfl->qf_start;
1204      qfl->qf_index = 1;
1205      qfl->qf_nonevalid = true;
1206    } else {
1207      qfl->qf_nonevalid = false;
1208      if (qfl->qf_ptr == NULL) {
1209        qfl->qf_ptr = qfl->qf_start;
1210      }
1211    }
1212    // return number of matches
1213    retval = qfl->qf_count;
1214    goto qf_init_end;
1215  }
1216  emsg(_(e_readerrf));
1217error2:
1218  if (!adding) {
1219    // Error when creating a new list. Free the new list
1220    qf_free(qfl);
1221    qi->qf_listcount--;
1222    if (qi->qf_curlist > 0) {
1223      qi->qf_curlist--;
1224    }
1225  }
1226qf_init_end:
1227  if (qf_idx == qi->qf_curlist) {
1228    qf_update_buffer(qi, old_last);
1229  }
1230  qf_cleanup_state(&state);
1231  qf_free_fields(&fields);
1232
1233  return retval;
1234}
1235
1236/// Set the title of the specified quickfix list. Frees the previous title.
1237/// Prepends ':' to the title.
1238static void qf_store_title(qf_list_T *qfl, const char *title)
1239  FUNC_ATTR_NONNULL_ARG(1)
1240{
1241  XFREE_CLEAR(qfl->qf_title);
1242
1243  if (title == NULL) {
1244    return;
1245  }
1246
1247  size_t len = strlen(title) + 1;
1248  char *p = xmallocz(len);
1249
1250  qfl->qf_title = p;
1251  xstrlcpy(p, title, len + 1);
1252}
1253
1254/// The title of a quickfix/location list is set, by default, to the command
1255/// that created the quickfix list with the ":" prefix.
1256/// Create a quickfix list title string by prepending ":" to a user command.
1257/// Returns a pointer to a static buffer with the title.
1258static char *qf_cmdtitle(const char *cmd)
1259  FUNC_ATTR_NONNULL_ALL
1260{
1261  static char qftitle_str[IOSIZE];
1262
1263  snprintf(qftitle_str, IOSIZE, ":%s", cmd);
1264
1265  return qftitle_str;
1266}
1267
1268/// Return a pointer to the current list in the specified quickfix stack
1269static qf_list_T *qf_get_curlist(qf_info_T *qi)
1270  FUNC_ATTR_NONNULL_ALL
1271{
1272  return qf_get_list(qi, qi->qf_curlist);
1273}
1274
1275/// Pop a quickfix list from the quickfix/location list stack
1276/// Automatically adjust qf_curlist so that it stays pointed
1277/// to the same list, unless it is deleted, if so then use the
1278/// newest created list instead. qf_listcount will be set correctly.
1279/// The above will only happen if <adjust> is true.
1280static void qf_pop_stack(qf_info_T *qi, bool adjust)
1281{
1282  qf_free(&qi->qf_lists[0]);
1283  for (int i = 1; i < qi->qf_listcount; i++) {
1284    qi->qf_lists[i - 1] = qi->qf_lists[i];
1285  }
1286
1287  // fill with zeroes now unused list at the top
1288  memset(qi->qf_lists + qi->qf_listcount - 1, 0, sizeof(*qi->qf_lists));
1289
1290  if (adjust) {
1291    qi->qf_listcount--;
1292    if (qi->qf_curlist == 0) {
1293      qi->qf_curlist = qi->qf_listcount - 1;
1294    } else {
1295      qi->qf_curlist--;
1296    }
1297  }
1298}
1299
1300/// Prepare for adding a new quickfix list. If the current list is in the
1301/// middle of the stack, then all the following lists are freed and then
1302/// the new list is added.
1303static void qf_new_list(qf_info_T *qi, const char *qf_title)
1304{
1305  // If the current entry is not the last entry, delete entries beyond
1306  // the current entry.  This makes it possible to browse in a tree-like
1307  // way with ":grep".
1308  while (qi->qf_listcount > qi->qf_curlist + 1) {
1309    qf_free(&qi->qf_lists[--qi->qf_listcount]);
1310  }
1311
1312  // When the stack is full, remove to oldest entry
1313  // Otherwise, add a new entry.
1314  if (qi->qf_listcount == qi->qf_maxcount) {
1315    qf_pop_stack(qi, false);
1316    qi->qf_curlist = qi->qf_listcount - 1;  // point to new empty list
1317  } else {
1318    qi->qf_curlist = qi->qf_listcount++;
1319  }
1320
1321  qf_list_T *qfl = qf_get_curlist(qi);
1322  CLEAR_POINTER(qfl);
1323  qf_store_title(qfl, qf_title);
1324  qfl->qfl_type = qi->qfl_type;
1325  qfl->qf_id = ++last_qf_id;
1326  qfl->qf_has_user_data = false;
1327}
1328
1329/// Parse the match for filename ('%f') pattern in regmatch.
1330/// Return the matched value in "fields->namebuf".
1331static int qf_parse_fmt_f(regmatch_T *rmp, int midx, qffields_T *fields, int prefix)
1332{
1333  if (rmp->startp[midx] == NULL || rmp->endp[midx] == NULL) {
1334    return QF_FAIL;
1335  }
1336
1337  // Expand ~/file and $HOME/file to full path.
1338  char c = *rmp->endp[midx];
1339  *rmp->endp[midx] = NUL;
1340  expand_env(rmp->startp[midx], fields->namebuf, CMDBUFFSIZE);
1341  *rmp->endp[midx] = c;
1342
1343  // For separate filename patterns (%O, %P and %Q), the specified file
1344  // should exist.
1345  if (vim_strchr("OPQ", prefix) != NULL
1346      && !os_path_exists(fields->namebuf)) {
1347    return QF_FAIL;
1348  }
1349
1350  return QF_OK;
1351}
1352
1353/// Parse the match for buffer number ('%b') pattern in regmatch.
1354/// Return the matched value in "fields->bnr".
1355static int qf_parse_fmt_b(regmatch_T *rmp, int midx, qffields_T *fields)
1356{
1357  if (rmp->startp[midx] == NULL) {
1358    return QF_FAIL;
1359  }
1360  int bnr = (int)atol(rmp->startp[midx]);
1361  if (buflist_findnr(bnr) == NULL) {
1362    return QF_FAIL;
1363  }
1364  fields->bnr = bnr;
1365  return QF_OK;
1366}
1367
1368/// Parse the match for error number ('%n') pattern in regmatch.
1369/// Return the matched value in "fields->enr".
1370static int qf_parse_fmt_n(regmatch_T *rmp, int midx, qffields_T *fields)
1371{
1372  if (rmp->startp[midx] == NULL) {
1373    return QF_FAIL;
1374  }
1375  fields->enr = (int)atol(rmp->startp[midx]);
1376  return QF_OK;
1377}
1378
1379/// Parse the match for line number ('%l') pattern in regmatch.
1380/// Return the matched value in "fields->lnum".
1381static int qf_parse_fmt_l(regmatch_T *rmp, int midx, qffields_T *fields)
1382{
1383  if (rmp->startp[midx] == NULL) {
1384    return QF_FAIL;
1385  }
1386  fields->lnum = (linenr_T)atol(rmp->startp[midx]);
1387  return QF_OK;
1388}
1389
1390/// Parse the match for end line number ('%e') pattern in regmatch.
1391/// Return the matched value in "fields->end_lnum".
1392static int qf_parse_fmt_e(regmatch_T *rmp, int midx, qffields_T *fields)
1393{
1394  if (rmp->startp[midx] == NULL) {
1395    return QF_FAIL;
1396  }
1397  fields->end_lnum = (linenr_T)atol(rmp->startp[midx]);
1398  return QF_OK;
1399}
1400
1401/// Parse the match for column number ('%c') pattern in regmatch.
1402/// Return the matched value in "fields->col".
1403static int qf_parse_fmt_c(regmatch_T *rmp, int midx, qffields_T *fields)
1404{
1405  if (rmp->startp[midx] == NULL) {
1406    return QF_FAIL;
1407  }
1408  fields->col = (int)atol(rmp->startp[midx]);
1409  return QF_OK;
1410}
1411
1412/// Parse the match for end line number ('%e') pattern in regmatch.
1413/// Return the matched value in "fields->end_lnum".
1414static int qf_parse_fmt_k(regmatch_T *rmp, int midx, qffields_T *fields)
1415{
1416  if (rmp->startp[midx] == NULL) {
1417    return QF_FAIL;
1418  }
1419  fields->end_col = (int)atol(rmp->startp[midx]);
1420  return QF_OK;
1421}
1422
1423/// Parse the match for error type ('%t') pattern in regmatch.
1424/// Return the matched value in "fields->type".
1425static int qf_parse_fmt_t(regmatch_T *rmp, int midx, qffields_T *fields)
1426{
1427  if (rmp->startp[midx] == NULL) {
1428    return QF_FAIL;
1429  }
1430  fields->type = *rmp->startp[midx];
1431  return QF_OK;
1432}
1433
1434/// Copy a non-error line into the error string.  Return the matched line in
1435/// "fields->errmsg".
1436static int copy_nonerror_line(const char *linebuf, size_t linelen, qffields_T *fields)
1437  FUNC_ATTR_NONNULL_ALL
1438{
1439  if (linelen >= fields->errmsglen) {
1440    // linelen + null terminator
1441    fields->errmsg = xrealloc(fields->errmsg, linelen + 1);
1442    fields->errmsglen = linelen + 1;
1443  }
1444  // copy whole line to error message
1445  xstrlcpy(fields->errmsg, linebuf, linelen + 1);
1446
1447  return QF_OK;
1448}
1449
1450/// Parse the match for error message ('%m') pattern in regmatch.
1451/// Return the matched value in "fields->errmsg".
1452static int qf_parse_fmt_m(regmatch_T *rmp, int midx, qffields_T *fields)
1453{
1454  if (rmp->startp[midx] == NULL || rmp->endp[midx] == NULL) {
1455    return QF_FAIL;
1456  }
1457  size_t len = (size_t)(rmp->endp[midx] - rmp->startp[midx]);
1458  if (len >= fields->errmsglen) {
1459    // len + null terminator
1460    fields->errmsg = xrealloc(fields->errmsg, len + 1);
1461    fields->errmsglen = len + 1;
1462  }
1463  xstrlcpy(fields->errmsg, rmp->startp[midx], len + 1);
1464  return QF_OK;
1465}
1466
1467/// Parse the match for rest of a single-line file message ('%r') pattern.
1468/// Return the matched value in "tail".
1469static int qf_parse_fmt_r(regmatch_T *rmp, int midx, char **tail)
1470{
1471  if (rmp->startp[midx] == NULL) {
1472    return QF_FAIL;
1473  }
1474  *tail = rmp->startp[midx];
1475  return QF_OK;
1476}
1477
1478/// Parse the match for the pointer line ('%p') pattern in regmatch.
1479/// Return the matched value in "fields->col".
1480static int qf_parse_fmt_p(regmatch_T *rmp, int midx, qffields_T *fields)
1481{
1482  if (rmp->startp[midx] == NULL || rmp->endp[midx] == NULL) {
1483    return QF_FAIL;
1484  }
1485  fields->col = 0;
1486  for (char *match_ptr = rmp->startp[midx]; match_ptr != rmp->endp[midx];
1487       match_ptr++) {
1488    fields->col++;
1489    if (*match_ptr == TAB) {
1490      fields->col += 7;
1491      fields->col -= fields->col % 8;
1492    }
1493  }
1494  fields->col++;
1495  fields->use_viscol = true;
1496  return QF_OK;
1497}
1498
1499/// Parse the match for the virtual column number ('%v') pattern in regmatch.
1500/// Return the matched value in "fields->col".
1501static int qf_parse_fmt_v(regmatch_T *rmp, int midx, qffields_T *fields)
1502{
1503  if (rmp->startp[midx] == NULL) {
1504    return QF_FAIL;
1505  }
1506  fields->col = (int)atol(rmp->startp[midx]);
1507  fields->use_viscol = true;
1508  return QF_OK;
1509}
1510
1511/// Parse the match for the search text ('%s') pattern in regmatch.
1512/// Return the matched value in "fields->pattern".
1513static int qf_parse_fmt_s(regmatch_T *rmp, int midx, qffields_T *fields)
1514{
1515  if (rmp->startp[midx] == NULL || rmp->endp[midx] == NULL) {
1516    return QF_FAIL;
1517  }
1518  size_t len = (size_t)(rmp->endp[midx] - rmp->startp[midx]);
1519  len = MIN(len, CMDBUFFSIZE - 5);
1520  STRCPY(fields->pattern, "^\\V");
1521  xstrlcat(fields->pattern, rmp->startp[midx], len + 4);
1522  fields->pattern[len + 3] = '\\';
1523  fields->pattern[len + 4] = '$';
1524  fields->pattern[len + 5] = NUL;
1525  return QF_OK;
1526}
1527
1528/// Parse the match for the module ('%o') pattern in regmatch.
1529/// Return the matched value in "fields->module".
1530static int qf_parse_fmt_o(regmatch_T *rmp, int midx, qffields_T *fields)
1531{
1532  if (rmp->startp[midx] == NULL || rmp->endp[midx] == NULL) {
1533    return QF_FAIL;
1534  }
1535  size_t len = (size_t)(rmp->endp[midx] - rmp->startp[midx]);
1536  size_t dsize = strlen(fields->module) + len + 1;
1537  dsize = MIN(dsize, CMDBUFFSIZE);
1538  xstrlcat(fields->module, rmp->startp[midx], dsize);
1539  return QF_OK;
1540}
1541
1542/// 'errorformat' format pattern parser functions.
1543/// The '%f' and '%r' formats are parsed differently from other formats.
1544/// See qf_parse_match() for details.
1545/// Keep in sync with fmt_pat[].
1546static int (*qf_parse_fmt[FMT_PATTERNS])(regmatch_T *, int, qffields_T *) = {
1547  NULL,  // %f
1548  qf_parse_fmt_b,
1549  qf_parse_fmt_n,
1550  qf_parse_fmt_l,
1551  qf_parse_fmt_e,
1552  qf_parse_fmt_c,
1553  qf_parse_fmt_k,
1554  qf_parse_fmt_t,
1555  qf_parse_fmt_m,
1556  NULL,  // %r
1557  qf_parse_fmt_p,
1558  qf_parse_fmt_v,
1559  qf_parse_fmt_s,
1560  qf_parse_fmt_o
1561};
1562
1563/// Parse the error format matches in 'regmatch' and set the values in 'fields'.
1564/// fmt_ptr contains the 'efm' format specifiers/prefixes that have a match.
1565/// Returns QF_OK if all the matches are successfully parsed. On failure,
1566/// returns QF_FAIL or QF_NOMEM.
1567static int qf_parse_match(char *linebuf, size_t linelen, efm_T *fmt_ptr, regmatch_T *regmatch,
1568                          qffields_T *fields, int qf_multiline, int qf_multiscan, char **tail)
1569{
1570  char idx = fmt_ptr->prefix;
1571
1572  if ((idx == 'C' || idx == 'Z') && !qf_multiline) {
1573    return QF_FAIL;
1574  }
1575  if (vim_strchr("EWIN", (uint8_t)idx) != NULL) {
1576    fields->type = idx;
1577  } else {
1578    fields->type = 0;
1579  }
1580
1581  // Extract error message data from matched line.
1582  // We check for an actual submatch, because "\[" and "\]" in
1583  // the 'errorformat' may cause the wrong submatch to be used.
1584  for (int i = 0; i < FMT_PATTERNS; i++) {
1585    int status = QF_OK;
1586    int midx = (int)fmt_ptr->addr[i];
1587    if (i == 0 && midx > 0) {  // %f
1588      status = qf_parse_fmt_f(regmatch, midx, fields, idx);
1589    } else if (i == FMT_PATTERN_M) {
1590      if (fmt_ptr->flags == '+' && !qf_multiscan) {  // %+
1591        status = copy_nonerror_line(linebuf, linelen, fields);
1592      } else if (midx > 0) {  // %m
1593        status = qf_parse_fmt_m(regmatch, midx, fields);
1594      }
1595    } else if (i == FMT_PATTERN_R && midx > 0) {  // %r
1596      status = qf_parse_fmt_r(regmatch, midx, tail);
1597    } else if (midx > 0) {  // others
1598      status = (qf_parse_fmt[i])(regmatch, midx, fields);
1599    }
1600
1601    if (status != QF_OK) {
1602      return status;
1603    }
1604  }
1605
1606  return QF_OK;
1607}
1608
1609/// Parse an error line in 'linebuf' using a single error format string in
1610/// 'fmt_ptr->prog' and return the matching values in 'fields'.
1611/// Returns QF_OK if the efm format matches completely and the fields are
1612/// successfully copied. Otherwise returns QF_FAIL or QF_NOMEM.
1613static int qf_parse_get_fields(char *linebuf, size_t linelen, efm_T *fmt_ptr, qffields_T *fields,
1614                               int qf_multiline, int qf_multiscan, char **tail)
1615{
1616  if (qf_multiscan && vim_strchr("OPQ", (uint8_t)fmt_ptr->prefix) == NULL) {
1617    return QF_FAIL;
1618  }
1619
1620  fields->namebuf[0] = NUL;
1621  fields->bnr = 0;
1622  fields->module[0] = NUL;
1623  fields->pattern[0] = NUL;
1624  if (!qf_multiscan) {
1625    fields->errmsg[0] = NUL;
1626  }
1627  fields->lnum = 0;
1628  fields->end_lnum = 0;
1629  fields->col = 0;
1630  fields->end_col = 0;
1631  fields->use_viscol = false;
1632  fields->enr = -1;
1633  fields->type = 0;
1634  *tail = NULL;
1635
1636  regmatch_T regmatch;
1637  // Always ignore case when looking for a matching error.
1638  regmatch.rm_ic = true;
1639  regmatch.regprog = fmt_ptr->prog;
1640  bool r = vim_regexec(&regmatch, linebuf, 0);
1641  fmt_ptr->prog = regmatch.regprog;
1642  int status = QF_FAIL;
1643  if (r) {
1644    status = qf_parse_match(linebuf, linelen, fmt_ptr, &regmatch, fields,
1645                            qf_multiline, qf_multiscan, tail);
1646  }
1647
1648  return status;
1649}
1650
1651/// Parse directory error format prefixes (%D and %X).
1652/// Push and pop directories from the directory stack when scanning directory
1653/// names.
1654static int qf_parse_dir_pfx(int idx, qffields_T *fields, qf_list_T *qfl)
1655{
1656  if (idx == 'D') {  // enter directory
1657    if (*fields->namebuf == NUL) {
1658      emsg(_("E379: Missing or empty directory name"));
1659      return QF_FAIL;
1660    }
1661    qfl->qf_directory = qf_push_dir(fields->namebuf, &qfl->qf_dir_stack, false);
1662    if (qfl->qf_directory == NULL) {
1663      return QF_FAIL;
1664    }
1665  } else if (idx == 'X') {  // leave directory
1666    qfl->qf_directory = qf_pop_dir(&qfl->qf_dir_stack);
1667  }
1668
1669  return QF_OK;
1670}
1671
1672/// Parse global file name error format prefixes (%O, %P and %Q).
1673static int qf_parse_file_pfx(int idx, qffields_T *fields, qf_list_T *qfl, const char *tail)
1674{
1675  fields->valid = false;
1676  if (*fields->namebuf == NUL || os_path_exists(fields->namebuf)) {
1677    if (*fields->namebuf && idx == 'P') {
1678      qfl->qf_currfile = qf_push_dir(fields->namebuf, &qfl->qf_file_stack, true);
1679    } else if (idx == 'Q') {
1680      qfl->qf_currfile = qf_pop_dir(&qfl->qf_file_stack);
1681    }
1682    *fields->namebuf = NUL;
1683    if (tail && *tail) {
1684      qfl->qf_multiscan = true;
1685      return QF_MULTISCAN;
1686    }
1687  }
1688
1689  return QF_OK;
1690}
1691
1692/// Parse a non-error line (a line which doesn't match any of the error
1693/// format in 'efm').
1694static int qf_parse_line_nomatch(char *linebuf, size_t linelen, qffields_T *fields)
1695{
1696  fields->namebuf[0] = NUL;   // no match found, remove file name
1697  fields->lnum = 0;           // don't jump to this line
1698  fields->valid = false;
1699
1700  return copy_nonerror_line(linebuf, linelen, fields);
1701}
1702
1703/// Parse multi-line error format prefixes (%C and %Z)
1704static int qf_parse_multiline_pfx(int idx, qf_list_T *qfl, qffields_T *fields)
1705{
1706  if (!qfl->qf_multiignore) {
1707    qfline_T *qfprev = qfl->qf_last;
1708
1709    if (qfprev == NULL) {
1710      return QF_FAIL;
1711    }
1712    if (*fields->errmsg) {
1713      size_t textlen = strlen(qfprev->qf_text);
1714      size_t errlen = strlen(fields->errmsg);
1715      qfprev->qf_text = xrealloc(qfprev->qf_text, textlen + errlen + 2);
1716      qfprev->qf_text[textlen] = '\n';
1717      STRCPY(qfprev->qf_text + textlen + 1, fields->errmsg);
1718    }
1719    if (qfprev->qf_nr == -1) {
1720      qfprev->qf_nr = fields->enr;
1721    }
1722    if (vim_isprintc(fields->type) && !qfprev->qf_type) {
1723      // only printable chars allowed
1724      qfprev->qf_type = fields->type;
1725    }
1726
1727    if (!qfprev->qf_lnum) {
1728      qfprev->qf_lnum = fields->lnum;
1729    }
1730    if (!qfprev->qf_end_lnum) {
1731      qfprev->qf_end_lnum = fields->end_lnum;
1732    }
1733    if (!qfprev->qf_col) {
1734      qfprev->qf_col = fields->col;
1735      qfprev->qf_viscol = fields->use_viscol;
1736    }
1737    if (!qfprev->qf_end_col) {
1738      qfprev->qf_end_col = fields->end_col;
1739    }
1740    if (!qfprev->qf_fnum) {
1741      qfprev->qf_fnum = qf_get_fnum(qfl, qfl->qf_directory,
1742                                    *fields->namebuf || qfl->qf_directory
1743                                    ? fields->namebuf
1744                                    : qfl->qf_currfile && fields->valid
1745                                    ? qfl->qf_currfile : 0);
1746    }
1747  }
1748  if (idx == 'Z') {
1749    qfl->qf_multiline = qfl->qf_multiignore = false;
1750  }
1751  line_breakcheck();
1752
1753  return QF_IGNORE_LINE;
1754}
1755
1756/// Queue location list stack delete request.
1757static void locstack_queue_delreq(qf_info_T *qi)
1758{
1759  qf_delq_T *q = xmalloc(sizeof(qf_delq_T));
1760  q->qi = qi;
1761  q->next = qf_delq_head;
1762  qf_delq_head = q;
1763}
1764
1765/// Return the global quickfix stack window buffer number.
1766int qf_stack_get_bufnr(void)
1767{
1768  assert(ql_info != NULL);
1769  return ql_info->qf_bufnr;
1770}
1771
1772/// Wipe the quickfix window buffer (if present) for the specified
1773/// quickfix/location list.
1774static void wipe_qf_buffer(qf_info_T *qi)
1775  FUNC_ATTR_NONNULL_ALL
1776{
1777  if (qi->qf_bufnr == INVALID_QFBUFNR) {
1778    return;
1779  }
1780
1781  buf_T *const qfbuf = buflist_findnr(qi->qf_bufnr);
1782  if (qfbuf != NULL && qfbuf->b_nwindows == 0) {
1783    bool buf_was_null = false;
1784    // Can happen when curwin is closing (e.g: w_buffer was unloaded in
1785    // win_close()) and we are now closing the window-related location list
1786    // buffer from win_free().  close_buffer() calls CHECK_CURBUF() and
1787    // requires curwin->w_buffer == curbuf.  Should be OK to not increment
1788    // b_nwindows, especially as autocmds are blocked in win_free().
1789    if (curwin->w_buffer == NULL) {
1790      curwin->w_buffer = curbuf;
1791      buf_was_null = true;
1792    }
1793
1794    // If the quickfix buffer is not loaded in any window, then
1795    // wipe the buffer.
1796    close_buffer(NULL, qfbuf, DOBUF_WIPE, false, false, false);
1797    qi->qf_bufnr = INVALID_QFBUFNR;
1798    if (buf_was_null) {
1799      curwin->w_buffer = NULL;
1800    }
1801  }
1802}
1803
1804/// Free all lists in the stack (not including the stack)
1805static void qf_free_list_stack_items(qf_info_T *qi)
1806{
1807  for (int i = 0; i < qi->qf_listcount; i++) {
1808    qf_free(qf_get_list(qi, i));
1809  }
1810}
1811
1812/// Free a qf_info_T struct completely
1813static void qf_free_lists(qf_info_T *qi)
1814{
1815  qf_free_list_stack_items(qi);
1816
1817  xfree(qi->qf_lists);
1818  xfree(qi);
1819}
1820
1821/// Free a location list stack
1822static void ll_free_all(qf_info_T **pqi)
1823{
1824  qf_info_T *qi = *pqi;
1825  if (qi == NULL) {
1826    return;
1827  }
1828  *pqi = NULL;          // Remove reference to this list
1829
1830  // If the location list is still in use, then queue the delete request
1831  // to be processed later.
1832  if (quickfix_busy > 0) {
1833    locstack_queue_delreq(qi);
1834    return;
1835  }
1836
1837  qi->qf_refcount--;
1838  if (qi->qf_refcount < 1) {
1839    // No references to this location list.
1840    // If the quickfix window buffer is loaded, then wipe it
1841    wipe_qf_buffer(qi);
1842
1843    qf_free_lists(qi);
1844  }
1845}
1846
1847/// Free all the quickfix/location lists in the stack.
1848void qf_free_all(win_T *wp)
1849{
1850  qf_info_T *qi = ql_info;
1851
1852  if (wp != NULL) {
1853    // location list
1854    ll_free_all(&wp->w_llist);
1855    ll_free_all(&wp->w_llist_ref);
1856  } else if (qi != NULL) {
1857    qf_free_list_stack_items(qi);  // quickfix list
1858  }
1859}
1860
1861/// Delay freeing of location list stacks when the quickfix code is running.
1862/// Used to avoid problems with autocmds freeing location list stacks when the
1863/// quickfix code is still referencing the stack.
1864/// Must always call decr_quickfix_busy() exactly once after this.
1865static void incr_quickfix_busy(void)
1866{
1867  quickfix_busy++;
1868}
1869
1870/// Safe to free location list stacks. Process any delayed delete requests.
1871static void decr_quickfix_busy(void)
1872{
1873  quickfix_busy--;
1874  if (quickfix_busy == 0) {
1875    // No longer referencing the location lists. Process all the pending
1876    // delete requests.
1877    while (qf_delq_head != NULL) {
1878      qf_delq_T *q = qf_delq_head;
1879
1880      qf_delq_head = q->next;
1881      ll_free_all(&q->qi);
1882      xfree(q);
1883    }
1884  }
1885#ifdef ABORT_ON_INTERNAL_ERROR
1886  if (quickfix_busy < 0) {
1887    emsg("quickfix_busy has become negative");
1888    abort();
1889  }
1890#endif
1891}
1892
1893#ifdef EXITFREE
1894void check_quickfix_busy(void)
1895{
1896  if (quickfix_busy != 0) {
1897    semsg("quickfix_busy not zero on exit: %" PRId64, (int64_t)quickfix_busy);
1898# ifdef ABORT_ON_INTERNAL_ERROR
1899    abort();
1900# endif
1901  }
1902}
1903#endif
1904
1905/// Add an entry to the end of the list of errors.
1906///
1907/// @param  qfl      quickfix list entry
1908/// @param  dir      optional directory name
1909/// @param  fname    file name or NULL
1910/// @param  module   module name or NULL
1911/// @param  bufnum   buffer number or zero
1912/// @param  mesg     message
1913/// @param  lnum     line number
1914/// @param  end_lnum  line number for end
1915/// @param  col      column
1916/// @param  end_col  column for end
1917/// @param  vis_col  using visual column
1918/// @param  pattern  search pattern
1919/// @param  nr       error number
1920/// @param  type     type character
1921/// @param  user_data  custom user data or NULL
1922/// @param  valid    valid entry
1923///
1924/// @return  QF_OK on success or QF_FAIL on failure.
1925static int qf_add_entry(qf_list_T *qfl, char *dir, char *fname, char *module, int bufnum,
1926                        char *mesg, linenr_T lnum, linenr_T end_lnum, int col, int end_col,
1927                        char vis_col, char *pattern, int nr, char type, typval_T *user_data,
1928                        char valid)
1929{
1930  buf_T *buf;
1931  qfline_T *qfp = xmalloc(sizeof(qfline_T));
1932  char *fullname = NULL;
1933  char *p = NULL;
1934
1935  if (bufnum != 0) {
1936    buf = buflist_findnr(bufnum);
1937    qfp->qf_fnum = bufnum;
1938    if (buf != NULL) {
1939      buf->b_has_qf_entry |=
1940        IS_QF_LIST(qfl) ? BUF_HAS_QF_ENTRY : BUF_HAS_LL_ENTRY;
1941    }
1942  } else {
1943    qfp->qf_fnum = qf_get_fnum(qfl, dir, fname);
1944    buf = buflist_findnr(qfp->qf_fnum);
1945  }
1946  if (fname != NULL) {
1947    fullname = fix_fname(fname);
1948  }
1949  qfp->qf_fname = NULL;
1950  if (buf != NULL && buf->b_ffname != NULL && fullname != NULL) {
1951    if (!path_equal(fullname, buf->b_ffname, kPathCmpLiteral)) {
1952      p = path_try_shorten_fname(fullname);
1953      if (p != NULL) {
1954        qfp->qf_fname = xstrdup(p);
1955      }
1956    }
1957  }
1958  xfree(fullname);
1959  qfp->qf_text = xstrdup(mesg);
1960  qfp->qf_lnum = lnum;
1961  qfp->qf_end_lnum = end_lnum;
1962  qfp->qf_col = col;
1963  qfp->qf_end_col = end_col;
1964  qfp->qf_viscol = vis_col;
1965  if (user_data == NULL || user_data->v_type == VAR_UNKNOWN) {
1966    qfp->qf_user_data.v_type = VAR_UNKNOWN;
1967  } else {
1968    tv_copy(user_data, &qfp->qf_user_data);
1969    qfl->qf_has_user_data = true;
1970  }
1971  if (pattern == NULL || *pattern == NUL) {
1972    qfp->qf_pattern = NULL;
1973  } else {
1974    qfp->qf_pattern = xstrdup(pattern);
1975  }
1976  if (module == NULL || *module == NUL) {
1977    qfp->qf_module = NULL;
1978  } else {
1979    qfp->qf_module = xstrdup(module);
1980  }
1981  qfp->qf_nr = nr;
1982  if (type != 1 && !vim_isprintc(type)) {  // only printable chars allowed
1983    type = 0;
1984  }
1985  qfp->qf_type = type;
1986  qfp->qf_valid = valid;
1987
1988  qfline_T **lastp = &qfl->qf_last;
1989  if (qf_list_empty(qfl)) {
1990    // first element in the list
1991    qfl->qf_start = qfp;
1992    qfl->qf_ptr = qfp;
1993    qfl->qf_index = 0;
1994    qfp->qf_prev = NULL;
1995  } else {
1996    assert(*lastp);
1997    qfp->qf_prev = *lastp;
1998    (*lastp)->qf_next = qfp;
1999  }
2000  qfp->qf_next = NULL;
2001  qfp->qf_cleared = false;
2002  *lastp = qfp;
2003  qfl->qf_count++;
2004  if (qfl->qf_index == 0 && qfp->qf_valid) {
2005    // first valid entry
2006    qfl->qf_index = qfl->qf_count;
2007    qfl->qf_ptr = qfp;
2008  }
2009
2010  return QF_OK;
2011}
2012
2013/// Resize quickfix stack to be able to hold n amount of lists.
2014void qf_resize_stack(int n)
2015{
2016  assert(ql_info != NULL);
2017  qf_resize_stack_base(ql_info, n);
2018}
2019
2020/// Resize location list stack for window 'wp' to be able to hold n amount of lists.
2021void ll_resize_stack(win_T *wp, int n)
2022{
2023  // check if given window is a location list window;
2024  // if so then sync its 'lhistory' to the parent window or vice versa
2025  if (IS_LL_WINDOW(wp)) {
2026    qf_sync_llw_to_win(wp);
2027  } else {
2028    qf_sync_win_to_llw(wp);
2029  }
2030
2031  qf_info_T *qi = ll_get_or_alloc_list(wp);
2032  qf_resize_stack_base(qi, n);
2033}
2034
2035/// Resize quickfix/location lists stack to be able to hold n amount of lists.
2036static void qf_resize_stack_base(qf_info_T *qi, int n)
2037  FUNC_ATTR_NONNULL_ALL
2038{
2039  int amount_to_rm = 0;
2040  size_t lsz = sizeof(*qi->qf_lists);
2041
2042  if (n == qi->qf_maxcount) {
2043    return;
2044  } else if (n < qi->qf_maxcount && n < qi->qf_listcount) {
2045    // We have too many lists to store them all in the new stack,
2046    // pop lists until we can fit them all in the newly resized stack
2047    amount_to_rm = qi->qf_listcount - n;
2048
2049    for (int i = 0; i < amount_to_rm; i++) {
2050      qf_pop_stack(qi, true);
2051    }
2052  }
2053
2054  qf_list_T *new = xrealloc(qi->qf_lists, lsz * (size_t)n);
2055
2056  // fill with zeroes any newly allocated memory
2057  if (n > qi->qf_maxcount) {
2058    memset(new + qi->qf_maxcount, 0, lsz * (size_t)(n - qi->qf_maxcount));
2059  }
2060
2061  qi->qf_lists = new;
2062  qi->qf_maxcount = n;
2063
2064  qf_update_buffer(qi, NULL);
2065}
2066
2067/// Initialize quickfix list, should only be called once.
2068void qf_init_stack(void)
2069{
2070  ql_info = qf_alloc_stack(QFLT_QUICKFIX, (int)p_chi);
2071}
2072
2073/// Sync a location list window's 'lhistory' value to the parent window
2074static void qf_sync_llw_to_win(win_T *llw)
2075{
2076  win_T *wp = qf_find_win_with_loclist(llw->w_llist_ref);
2077
2078  if (wp != NULL) {
2079    wp->w_p_lhi = llw->w_p_lhi;
2080  }
2081}
2082
2083/// Sync a window's 'lhistory' value to its location list window, if any
2084static void qf_sync_win_to_llw(win_T *pwp)
2085{
2086  qf_info_T *llw = pwp->w_llist;
2087
2088  if (llw != NULL) {
2089    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2090      if (wp->w_llist_ref == llw && bt_quickfix(wp->w_buffer)) {
2091        wp->w_p_lhi = pwp->w_p_lhi;
2092        return;
2093      }
2094    }
2095  }
2096}
2097
2098/// Allocate a new quickfix/location list stack that is able to hold
2099/// up to n amount of lists
2100static qf_info_T *qf_alloc_stack(qfltype_T qfltype, int n)
2101  FUNC_ATTR_NONNULL_RET
2102{
2103  qf_info_T *qi;
2104  if (qfltype == QFLT_QUICKFIX) {
2105    qi = &ql_info_actual;
2106  } else {
2107    qi = xcalloc(1, sizeof(qf_info_T));
2108    qi->qf_refcount++;
2109  }
2110  qi->qfl_type = qfltype;
2111  qi->qf_bufnr = INVALID_QFBUFNR;
2112  qi->qf_lists = qf_alloc_list_stack(n);
2113  qi->qf_maxcount = n;
2114
2115  return qi;
2116}
2117
2118/// Allocate memory for qf_lists member of qf_info_T struct.
2119static qf_list_T *qf_alloc_list_stack(int n)
2120  FUNC_ATTR_NONNULL_RET
2121{
2122  return xcalloc((size_t)n, sizeof(qf_list_T));
2123}
2124
2125/// Return the location list stack for window 'wp'.
2126/// If not present, allocate a location list stack
2127static qf_info_T *ll_get_or_alloc_list(win_T *wp)
2128  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
2129{
2130  if (IS_LL_WINDOW(wp)) {
2131    // For a location list window, use the referenced location list
2132    return wp->w_llist_ref;
2133  }
2134
2135  // For a non-location list window, w_llist_ref should not point to a
2136  // location list.
2137  ll_free_all(&wp->w_llist_ref);
2138
2139  if (wp->w_llist == NULL) {
2140    // new location list
2141    wp->w_llist = qf_alloc_stack(QFLT_LOCATION, (int)wp->w_p_lhi);
2142  }
2143
2144  return wp->w_llist;
2145}
2146
2147/// Get the quickfix/location list stack to use for the specified Ex command.
2148/// For a location list command, returns the stack for the current window.  If
2149/// the location list is not found, then returns NULL and prints an error
2150/// message if 'print_emsg' is true.
2151static qf_info_T *qf_cmd_get_stack(exarg_T *eap, bool print_emsg)
2152{
2153  qf_info_T *qi = ql_info;
2154  assert(qi != NULL);
2155
2156  if (is_loclist_cmd(eap->cmdidx)) {
2157    qi = GET_LOC_LIST(curwin);
2158    if (qi == NULL) {
2159      if (print_emsg) {
2160        emsg(_(e_loclist));
2161      }
2162      return NULL;
2163    }
2164  }
2165
2166  return qi;
2167}
2168
2169/// Get the quickfix/location list stack to use for the specified Ex command.
2170/// For a location list command, returns the stack for the current window.
2171/// If the location list is not present, then allocates a new one.
2172/// For a location list command, sets 'pwinp' to curwin.
2173static qf_info_T *qf_cmd_get_or_alloc_stack(const exarg_T *eap, win_T **pwinp)
2174  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
2175{
2176  qf_info_T *qi = ql_info;
2177
2178  if (is_loclist_cmd(eap->cmdidx)) {
2179    qi = ll_get_or_alloc_list(curwin);
2180    *pwinp = curwin;
2181  }
2182
2183  return qi;
2184}
2185
2186/// Copy location list entries from 'from_qfl' to 'to_qfl'.
2187static int copy_loclist_entries(const qf_list_T *from_qfl, qf_list_T *to_qfl)
2188  FUNC_ATTR_NONNULL_ALL
2189{
2190  int i;
2191  qfline_T *from_qfp;
2192
2193  // copy all the location entries in this list
2194  FOR_ALL_QFL_ITEMS(from_qfl, from_qfp, i) {
2195    if (qf_add_entry(to_qfl,
2196                     NULL,
2197                     NULL,
2198                     from_qfp->qf_module,
2199                     0,
2200                     from_qfp->qf_text,
2201                     from_qfp->qf_lnum,
2202                     from_qfp->qf_end_lnum,
2203                     from_qfp->qf_col,
2204                     from_qfp->qf_end_col,
2205                     from_qfp->qf_viscol,
2206                     from_qfp->qf_pattern,
2207                     from_qfp->qf_nr,
2208                     0,
2209                     &from_qfp->qf_user_data,
2210                     from_qfp->qf_valid) == QF_FAIL) {
2211      return FAIL;
2212    }
2213
2214    // qf_add_entry() will not set the qf_num field, as the
2215    // directory and file names are not supplied. So the qf_fnum
2216    // field is copied here.
2217    qfline_T *const prevp = to_qfl->qf_last;
2218    prevp->qf_fnum = from_qfp->qf_fnum;  // file number
2219    prevp->qf_type = from_qfp->qf_type;  // error type
2220    if (from_qfl->qf_ptr == from_qfp) {
2221      to_qfl->qf_ptr = prevp;  // current location
2222    }
2223  }
2224
2225  return OK;
2226}
2227
2228/// Copy the specified location list 'from_qfl' to 'to_qfl'.
2229static int copy_loclist(qf_list_T *from_qfl, qf_list_T *to_qfl)
2230  FUNC_ATTR_NONNULL_ALL
2231{
2232  // Some of the fields are populated by qf_add_entry()
2233  to_qfl->qfl_type = from_qfl->qfl_type;
2234  to_qfl->qf_nonevalid = from_qfl->qf_nonevalid;
2235  to_qfl->qf_has_user_data = from_qfl->qf_has_user_data;
2236  to_qfl->qf_count = 0;
2237  to_qfl->qf_index = 0;
2238  to_qfl->qf_start = NULL;
2239  to_qfl->qf_last = NULL;
2240  to_qfl->qf_ptr = NULL;
2241  if (from_qfl->qf_title != NULL) {
2242    to_qfl->qf_title = xstrdup(from_qfl->qf_title);
2243  } else {
2244    to_qfl->qf_title = NULL;
2245  }
2246  if (from_qfl->qf_ctx != NULL) {
2247    to_qfl->qf_ctx = xcalloc(1, sizeof(*to_qfl->qf_ctx));
2248    tv_copy(from_qfl->qf_ctx, to_qfl->qf_ctx);
2249  } else {
2250    to_qfl->qf_ctx = NULL;
2251  }
2252  callback_copy(&to_qfl->qf_qftf_cb, &from_qfl->qf_qftf_cb);
2253
2254  if (from_qfl->qf_count) {
2255    if (copy_loclist_entries(from_qfl, to_qfl) == FAIL) {
2256      return FAIL;
2257    }
2258  }
2259
2260  to_qfl->qf_index = from_qfl->qf_index;  // current index in the list
2261
2262  // Assign a new ID for the location list
2263  to_qfl->qf_id = ++last_qf_id;
2264  to_qfl->qf_changedtick = 0;
2265
2266  // When no valid entries are present in the list, qf_ptr points to
2267  // the first item in the list
2268  if (to_qfl->qf_nonevalid) {
2269    to_qfl->qf_ptr = to_qfl->qf_start;
2270    to_qfl->qf_index = 1;
2271  }
2272
2273  return OK;
2274}
2275
2276// Copy the location list stack 'from' window to 'to' window.
2277void copy_loclist_stack(win_T *from, win_T *to)
2278  FUNC_ATTR_NONNULL_ALL
2279{
2280  // When copying from a location list window, copy the referenced
2281  // location list. For other windows, copy the location list for
2282  // that window.
2283  qf_info_T *qi = IS_LL_WINDOW(from) ? from->w_llist_ref : from->w_llist;
2284
2285  if (qi == NULL) {                 // no location list to copy
2286    return;
2287  }
2288
2289  // allocate a new location list, set size of stack to 'from' window value
2290  to->w_llist = qf_alloc_stack(QFLT_LOCATION, (int)from->w_p_lhi);
2291  // set 'to' lhi to reflect new value
2292  to->w_p_lhi = to->w_llist->qf_maxcount;
2293
2294  to->w_llist->qf_listcount = qi->qf_listcount;
2295
2296  // Copy the location lists one at a time
2297  for (int idx = 0; idx < qi->qf_listcount; idx++) {
2298    to->w_llist->qf_curlist = idx;
2299
2300    if (copy_loclist(qf_get_list(qi, idx),
2301                     qf_get_list(to->w_llist, idx)) == FAIL) {
2302      qf_free_all(to);
2303      return;
2304    }
2305  }
2306
2307  to->w_llist->qf_curlist = qi->qf_curlist;  // current list
2308}
2309
2310/// Get buffer number for file "directory/fname".
2311/// Also sets the b_has_qf_entry flag.
2312static int qf_get_fnum(qf_list_T *qfl, char *directory, char *fname)
2313{
2314  String ptr = STRING_INIT;
2315  String bufname;
2316  buf_T *buf;
2317  if (fname == NULL || *fname == NUL) {         // no file name
2318    return 0;
2319  }
2320
2321  String fname_str = cstr_as_string(fname);
2322  if (directory != NULL && !vim_isAbsName(fname)) {
2323    ptr = concat_fnames(cstr_as_string(directory), fname_str, true);
2324    // Here we check if the file really exists.
2325    // This should normally be true, but if make works without
2326    // "leaving directory"-messages we might have missed a
2327    // directory change.
2328    if (!os_path_exists(ptr.data)) {
2329      xfree(ptr.data);
2330      directory = qf_guess_filepath(qfl, fname);
2331      if (directory) {
2332        ptr = concat_fnames(cstr_as_string(directory), fname_str, true);
2333      } else {
2334        ptr = copy_string(fname_str, NULL);
2335      }
2336    }
2337    // Use concatenated directory name and file name.
2338    bufname = ptr;
2339  } else {
2340    bufname = fname_str;
2341  }
2342  TO_SLASH(bufname.data);
2343
2344  if (qf_last_bufname != NULL && strcmp(bufname.data, qf_last_bufname) == 0
2345      && bufref_valid(&qf_last_bufref)) {
2346    buf = qf_last_bufref.br_buf;
2347    xfree(ptr.data);
2348  } else {
2349    xfree(qf_last_bufname);
2350    buf = buflist_new(bufname.data, NULL, 0, BLN_NOOPT);
2351    qf_last_bufname = (bufname.data == ptr.data)
2352                      ? bufname.data : xmemdupz(bufname.data, bufname.size);
2353    set_bufref(&qf_last_bufref, buf);
2354  }
2355  if (buf == NULL) {
2356    return 0;
2357  }
2358  buf->b_has_qf_entry = IS_QF_LIST(qfl) ? BUF_HAS_QF_ENTRY : BUF_HAS_LL_ENTRY;
2359  return buf->b_fnum;
2360}
2361
2362// Push dirbuf onto the directory stack and return pointer to actual dir or
2363// NULL on error.
2364static char *qf_push_dir(char *dirbuf, struct dir_stack_T **stackptr, bool is_file_stack)
2365{
2366  struct dir_stack_T *ds_ptr;
2367
2368  // allocate new stack element
2369  struct dir_stack_T *ds_new = xmalloc(sizeof(struct dir_stack_T));
2370
2371  // push the new element onto the stack
2372  ds_new->next = *stackptr;
2373  *stackptr = ds_new;
2374
2375  // store directory on the stack
2376  if (vim_isAbsName(dirbuf)
2377      || (*stackptr)->next == NULL
2378      || is_file_stack) {
2379    (*stackptr)->dirname = xstrdup(dirbuf);
2380  } else {
2381    // Okay we don't have an absolute path.
2382    // dirbuf must be a subdir of one of the directories on the stack.
2383    // Let's search...
2384    size_t dirbuf_len = strlen(dirbuf);
2385    ds_new = (*stackptr)->next;
2386    (*stackptr)->dirname = NULL;
2387    while (ds_new) {
2388      String dirname = concat_fnames(cstr_as_string(ds_new->dirname),
2389                                     cbuf_as_string(dirbuf, dirbuf_len), true);
2390      if (os_isdir(dirname.data)) {
2391        xfree((*stackptr)->dirname);
2392        (*stackptr)->dirname = dirname.data;
2393        break;
2394      }
2395      xfree(dirname.data);
2396      ds_new = ds_new->next;
2397    }
2398
2399    // clean up all dirs we already left
2400    while ((*stackptr)->next != ds_new) {
2401      ds_ptr = (*stackptr)->next;
2402      (*stackptr)->next = (*stackptr)->next->next;
2403      xfree(ds_ptr->dirname);
2404      xfree(ds_ptr);
2405    }
2406
2407    // Nothing found -> it must be on top level
2408    if (ds_new == NULL) {
2409      xfree((*stackptr)->dirname);
2410      (*stackptr)->dirname = xmemdupz(dirbuf, dirbuf_len);
2411    }
2412  }
2413
2414  if ((*stackptr)->dirname != NULL) {
2415    return (*stackptr)->dirname;
2416  }
2417
2418  // pop the new element from the stack and free it
2419  ds_ptr = *stackptr;
2420  *stackptr = (*stackptr)->next;
2421  xfree(ds_ptr);
2422
2423  return NULL;
2424}
2425
2426// pop dirbuf from the directory stack and return previous directory or NULL if
2427// stack is empty
2428static char *qf_pop_dir(struct dir_stack_T **stackptr)
2429{
2430  // TODO(vim): Should we check if dirbuf is the directory on top of the stack?
2431  // What to do if it isn't?
2432
2433  // pop top element and free it
2434  if (*stackptr != NULL) {
2435    struct dir_stack_T *ds_ptr = *stackptr;
2436    *stackptr = (*stackptr)->next;
2437    xfree(ds_ptr->dirname);
2438    xfree(ds_ptr);
2439  }
2440
2441  // return NEW top element as current dir or NULL if stack is empty
2442  return *stackptr ? (*stackptr)->dirname : NULL;
2443}
2444
2445// clean up directory stack
2446static void qf_clean_dir_stack(struct dir_stack_T **stackptr)
2447{
2448  struct dir_stack_T *ds_ptr;
2449
2450  while ((ds_ptr = *stackptr) != NULL) {
2451    *stackptr = (*stackptr)->next;
2452    xfree(ds_ptr->dirname);
2453    xfree(ds_ptr);
2454  }
2455}
2456
2457/// Check in which directory of the directory stack the given file can be
2458/// found.
2459/// Returns a pointer to the directory name or NULL if not found.
2460/// Cleans up intermediate directory entries.
2461///
2462/// TODO(vim): How to solve the following problem?
2463/// If we have this directory tree:
2464///     ./
2465///     ./aa
2466///     ./aa/bb
2467///     ./bb
2468///     ./bb/x.c
2469/// and make says:
2470///     making all in aa
2471///     making all in bb
2472///     x.c:9: Error
2473/// Then qf_push_dir thinks we are in ./aa/bb, but we are in ./bb.
2474/// qf_guess_filepath will return NULL.
2475static char *qf_guess_filepath(qf_list_T *qfl, char *filename)
2476{
2477  // no dirs on the stack - there's nothing we can do
2478  if (qfl->qf_dir_stack == NULL) {
2479    return NULL;
2480  }
2481
2482  struct dir_stack_T *ds_ptr = qfl->qf_dir_stack->next;
2483  String fullname = STRING_INIT;
2484  String filename_str = cstr_as_string(filename);
2485  while (ds_ptr) {
2486    xfree(fullname.data);
2487    fullname = concat_fnames(cstr_as_string(ds_ptr->dirname), filename_str, true);
2488
2489    if (os_path_exists(fullname.data)) {
2490      break;
2491    }
2492
2493    ds_ptr = ds_ptr->next;
2494  }
2495
2496  xfree(fullname.data);
2497
2498  // clean up all dirs we already left
2499  while (qfl->qf_dir_stack->next != ds_ptr) {
2500    struct dir_stack_T *ds_tmp = qfl->qf_dir_stack->next;
2501    qfl->qf_dir_stack->next = qfl->qf_dir_stack->next->next;
2502    xfree(ds_tmp->dirname);
2503    xfree(ds_tmp);
2504  }
2505
2506  return ds_ptr == NULL ? NULL : ds_ptr->dirname;
2507}
2508
2509/// Returns true, if a quickfix/location list with the given identifier exists.
2510static bool qflist_valid(win_T *wp, unsigned qf_id)
2511{
2512  qf_info_T *qi = ql_info;
2513
2514  if (wp) {
2515    if (!win_valid(wp)) {
2516      return false;
2517    }
2518    qi = GET_LOC_LIST(wp);  // Location list
2519  }
2520  if (!qi) {
2521    return false;
2522  }
2523
2524  for (int i = 0; i < qi->qf_listcount; i++) {
2525    if (qi->qf_lists[i].qf_id == qf_id) {
2526      return true;
2527    }
2528  }
2529
2530  return false;
2531}
2532
2533/// When loading a file from the quickfix, the autocommands may modify it.
2534/// This may invalidate the current quickfix entry.  This function checks
2535/// whether an entry is still present in the quickfix list.
2536/// Similar to location list.
2537static bool is_qf_entry_present(qf_list_T *qfl, qfline_T *qf_ptr)
2538{
2539  qfline_T *qfp;
2540  int i;
2541
2542  // Search for the entry in the current list
2543  FOR_ALL_QFL_ITEMS(qfl, qfp, i) {
2544    if (qfp == qf_ptr) {
2545      break;
2546    }
2547  }
2548
2549  if (i > qfl->qf_count) {  // Entry is not found
2550    return false;
2551  }
2552
2553  return true;
2554}
2555
2556/// Get the next valid entry in the current quickfix/location list. The search
2557/// starts from the current entry. Returns NULL on failure.
2558static qfline_T *get_next_valid_entry(qf_list_T *qfl, qfline_T *qf_ptr, int *qf_index, int dir)
2559{
2560  int idx = *qf_index;
2561  int old_qf_fnum = qf_ptr->qf_fnum;
2562
2563  do {
2564    if (idx == qfl->qf_count || qf_ptr->qf_next == NULL) {
2565      return NULL;
2566    }
2567    idx++;
2568    qf_ptr = qf_ptr->qf_next;
2569  } while ((!qfl->qf_nonevalid && !qf_ptr->qf_valid)
2570           || (dir == FORWARD_FILE && qf_ptr->qf_fnum == old_qf_fnum));
2571
2572  *qf_index = idx;
2573  return qf_ptr;
2574}
2575
2576/// Get the previous valid entry in the current quickfix/location list. The
2577/// search starts from the current entry. Returns NULL on failure.
2578static qfline_T *get_prev_valid_entry(qf_list_T *qfl, qfline_T *qf_ptr, int *qf_index, int dir)
2579{
2580  int idx = *qf_index;
2581  int old_qf_fnum = qf_ptr->qf_fnum;
2582
2583  do {
2584    if (idx == 1 || qf_ptr->qf_prev == NULL) {
2585      return NULL;
2586    }
2587    idx--;
2588    qf_ptr = qf_ptr->qf_prev;
2589  } while ((!qfl->qf_nonevalid && !qf_ptr->qf_valid)
2590           || (dir == BACKWARD_FILE && qf_ptr->qf_fnum == old_qf_fnum));
2591
2592  *qf_index = idx;
2593  return qf_ptr;
2594}
2595
2596/// Get the n'th (errornr) previous/next valid entry from the current entry in
2597/// the quickfix list.
2598///   dir == FORWARD or FORWARD_FILE: next valid entry
2599///   dir == BACKWARD or BACKWARD_FILE: previous valid entry
2600static qfline_T *get_nth_valid_entry(qf_list_T *qfl, int errornr, int dir, int *new_qfidx)
2601{
2602  qfline_T *qf_ptr = qfl->qf_ptr;
2603  int qf_idx = qfl->qf_index;
2604  const char *err = e_no_more_items;
2605
2606  while (errornr--) {
2607    qfline_T *prev_qf_ptr = qf_ptr;
2608    int prev_index = qf_idx;
2609
2610    if (dir == FORWARD || dir == FORWARD_FILE) {
2611      qf_ptr = get_next_valid_entry(qfl, qf_ptr, &qf_idx, dir);
2612    } else {
2613      qf_ptr = get_prev_valid_entry(qfl, qf_ptr, &qf_idx, dir);
2614    }
2615
2616    if (qf_ptr == NULL) {
2617      qf_ptr = prev_qf_ptr;
2618      qf_idx = prev_index;
2619      if (err != NULL) {
2620        emsg(_(err));
2621        return NULL;
2622      }
2623      break;
2624    }
2625
2626    err = NULL;
2627  }
2628
2629  *new_qfidx = qf_idx;
2630  return qf_ptr;
2631}
2632
2633/// Get n'th (errornr) quickfix entry from the current entry in the quickfix
2634/// list 'qfl'. Returns a pointer to the new entry and the index in 'new_qfidx'
2635static qfline_T *get_nth_entry(qf_list_T *qfl, int errornr, int *new_qfidx)
2636{
2637  qfline_T *qf_ptr = qfl->qf_ptr;
2638  int qf_idx = qfl->qf_index;
2639
2640  // New error number is less than the current error number
2641  while (errornr < qf_idx && qf_idx > 1 && qf_ptr->qf_prev != NULL) {
2642    qf_idx--;
2643    qf_ptr = qf_ptr->qf_prev;
2644  }
2645
2646  // New error number is greater than the current error number
2647  while (errornr > qf_idx
2648         && qf_idx < qfl->qf_count
2649         && qf_ptr->qf_next != NULL) {
2650    qf_idx++;
2651    qf_ptr = qf_ptr->qf_next;
2652  }
2653
2654  *new_qfidx = qf_idx;
2655  return qf_ptr;
2656}
2657
2658/// Get a entry specified by 'errornr' and 'dir' from the current
2659/// quickfix/location list. 'errornr' specifies the index of the entry and 'dir'
2660/// specifies the direction (FORWARD/BACKWARD/FORWARD_FILE/BACKWARD_FILE).
2661/// Returns a pointer to the entry and the index of the new entry is stored in
2662/// 'new_qfidx'.
2663static qfline_T *qf_get_entry(qf_list_T *qfl, int errornr, int dir, int *new_qfidx)
2664{
2665  qfline_T *qf_ptr = qfl->qf_ptr;
2666  int qfidx = qfl->qf_index;
2667
2668  if (dir != 0) {  // next/prev valid entry
2669    qf_ptr = get_nth_valid_entry(qfl, errornr, dir, &qfidx);
2670  } else if (errornr != 0) {  // go to specified number
2671    qf_ptr = get_nth_entry(qfl, errornr, &qfidx);
2672  }
2673
2674  *new_qfidx = qfidx;
2675  return qf_ptr;
2676}
2677
2678// Find a window displaying a Vim help file in the current tab page.
2679static win_T *qf_find_help_win(void)
2680  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2681{
2682  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2683    if (bt_help(wp->w_buffer) && !wp->w_config.hide && wp->w_config.focusable) {
2684      return wp;
2685    }
2686  }
2687  return NULL;
2688}
2689
2690/// Set the location list for the specified window to 'qi'.
2691static void win_set_loclist(win_T *wp, qf_info_T *qi)
2692{
2693  wp->w_llist = qi;
2694  qi->qf_refcount++;
2695}
2696
2697/// Find a help window or open one. If 'newwin' is true, then open a new help
2698/// window.
2699static int jump_to_help_window(qf_info_T *qi, bool newwin, bool *opened_window)
2700{
2701  win_T *wp = (cmdmod.cmod_tab != 0 || newwin) ? NULL : qf_find_help_win();
2702
2703  if (wp != NULL && wp->w_buffer->b_nwindows > 0) {
2704    win_enter(wp, true);
2705  } else {
2706    // Split off help window; put it at far top if no position
2707    // specified, the current window is vertically split and narrow.
2708    int flags = WSP_HELP;
2709    if (cmdmod.cmod_split == 0
2710        && curwin->w_width != Columns
2711        && curwin->w_width < 80) {
2712      flags |= WSP_TOP;
2713    }
2714
2715    // If the user asks to open a new window, then copy the location list.
2716    // Otherwise, don't copy the location list.
2717    if (IS_LL_STACK(qi) && !newwin) {
2718      flags |= WSP_NEWLOC;
2719    }
2720
2721    if (win_split(0, flags) == FAIL) {
2722      return FAIL;
2723    }
2724
2725    *opened_window = true;
2726
2727    if (curwin->w_height < p_hh) {
2728      win_setheight((int)p_hh);
2729    }
2730
2731    // When using location list, the new window should use the supplied
2732    // location list. If the user asks to open a new window, then the new
2733    // window will get a copy of the location list.
2734    if (IS_LL_STACK(qi) && !newwin) {
2735      win_set_loclist(curwin, qi);
2736    }
2737  }
2738
2739  restart_edit = 0;  // don't want insert mode in help file
2740
2741  return OK;
2742}
2743
2744/// Find a non-quickfix window using the given location list stack in the
2745/// current tabpage.
2746/// Returns NULL if a matching window is not found.
2747static win_T *qf_find_win_with_loclist(const qf_info_T *ll)
2748  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2749{
2750  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2751    if (wp->w_llist == ll && !bt_quickfix(wp->w_buffer)) {
2752      return wp;
2753    }
2754  }
2755  return NULL;
2756}
2757
2758/// Find a window containing a normal buffer in the current tab page.
2759static win_T *qf_find_win_with_normal_buf(void)
2760  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2761{
2762  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2763    if (bt_normal(wp->w_buffer)) {
2764      return wp;
2765    }
2766  }
2767  return NULL;
2768}
2769
2770// Go to a window in any tabpage containing the specified file.  Returns true
2771// if successfully jumped to the window. Otherwise returns false.
2772static bool qf_goto_tabwin_with_file(int fnum)
2773{
2774  FOR_ALL_TAB_WINDOWS(tp, wp) {
2775    if (wp->w_buffer->b_fnum == fnum) {
2776      goto_tabpage_win(tp, wp);
2777      return true;
2778    }
2779  }
2780  return false;
2781}
2782
2783// Create a new window to show a file above the quickfix window. Called when
2784// only the quickfix window is present.
2785static int qf_open_new_file_win(qf_info_T *ll_ref)
2786{
2787  int flags = WSP_ABOVE;
2788  if (ll_ref != NULL) {
2789    flags |= WSP_NEWLOC;
2790  }
2791  if (win_split(0, flags) == FAIL) {
2792    return FAIL;  // not enough room for window
2793  }
2794  p_swb = empty_string_option;  // don't split again
2795  swb_flags = 0;
2796  RESET_BINDING(curwin);
2797  if (ll_ref != NULL) {
2798    // The new window should use the location list from the
2799    // location list window
2800    win_set_loclist(curwin, ll_ref);
2801  }
2802  return OK;
2803}
2804
2805// Go to a window that shows the right buffer. If the window is not found, go
2806// to the window just above the location list window. This is used for opening
2807// a file from a location window and not from a quickfix window. If some usable
2808// window is previously found, then it is supplied in 'use_win'.
2809static void qf_goto_win_with_ll_file(win_T *use_win, int qf_fnum, qf_info_T *ll_ref)
2810{
2811  win_T *win = use_win;
2812
2813  if (win == NULL) {
2814    // Find the window showing the selected file in the current tab page.
2815    FOR_ALL_WINDOWS_IN_TAB(win2, curtab) {
2816      if (win2->w_buffer->b_fnum == qf_fnum) {
2817        win = win2;
2818        break;
2819      }
2820    }
2821    if (win == NULL) {
2822      // Find a previous usable window
2823      win = curwin;
2824      do {
2825        if (bt_normal(win->w_buffer)) {
2826          break;
2827        }
2828        if (win->w_prev == NULL) {
2829          win = lastwin;      // wrap around the top
2830        } else {
2831          win = win->w_prev;  // go to previous window
2832        }
2833      } while (win != curwin);
2834    }
2835  }
2836  win_goto(win);
2837
2838  // If the location list for the window is not set, then set it
2839  // to the location list from the location window
2840  if (win->w_llist == NULL && ll_ref != NULL) {
2841    // The new window should use the location list from the
2842    // location list window
2843    win_set_loclist(win, ll_ref);
2844  }
2845}
2846
2847// Go to a window that shows the specified file. If a window is not found, go
2848// to the window just above the quickfix window. This is used for opening a
2849// file from a quickfix window and not from a location window.
2850static void qf_goto_win_with_qfl_file(int qf_fnum)
2851{
2852  win_T *win = curwin;
2853  win_T *altwin = NULL;
2854  while (true) {
2855    if (win->w_buffer->b_fnum == qf_fnum) {
2856      break;
2857    }
2858    if (win->w_prev == NULL) {
2859      win = lastwin;      // wrap around the top
2860    } else {
2861      win = win->w_prev;  // go to previous window
2862    }
2863
2864    if (IS_QF_WINDOW(win)) {
2865      // Didn't find it, go to the window before the quickfix
2866      // window, unless 'switchbuf' contains 'uselast': in this case we
2867      // try to jump to the previously used window first.
2868      if ((swb_flags & kOptSwbFlagUselast) && win_valid(prevwin)
2869          && !prevwin->w_p_wfb) {
2870        win = prevwin;
2871      } else if (altwin != NULL) {
2872        win = altwin;
2873      } else if (curwin->w_prev != NULL) {
2874        win = curwin->w_prev;
2875      } else {
2876        win = curwin->w_next;
2877      }
2878      break;
2879    }
2880
2881    // Remember a usable window.
2882    if (altwin == NULL
2883        && !win->w_p_pvw
2884        && !win->w_p_wfb
2885        && bt_normal(win->w_buffer)) {
2886      altwin = win;
2887    }
2888  }
2889
2890  win_goto(win);
2891}
2892
2893// Find a suitable window for opening a file (qf_fnum) from the
2894// quickfix/location list and jump to it.  If the file is already opened in a
2895// window, jump to it. Otherwise open a new window to display the file. If
2896// 'newwin' is true, then always open a new window. This is called from either
2897// a quickfix or a location list window.
2898static int qf_jump_to_usable_window(int qf_fnum, bool newwin, bool *opened_window)
2899{
2900  win_T *usable_wp = NULL;
2901  bool usable_win = false;
2902
2903  // If opening a new window, then don't use the location list referred by
2904  // the current window.  Otherwise two windows will refer to the same
2905  // location list.
2906  qf_info_T *ll_ref = newwin ? NULL : curwin->w_llist_ref;
2907  if (ll_ref != NULL) {
2908    // Find a non-quickfix window with this location list
2909    usable_wp = qf_find_win_with_loclist(ll_ref);
2910    if (usable_wp != NULL) {
2911      usable_win = true;
2912    }
2913  }
2914
2915  if (!usable_win) {
2916    // Locate a window showing a normal buffer
2917    win_T *win = qf_find_win_with_normal_buf();
2918    if (win != NULL) {
2919      usable_win = true;
2920    }
2921  }
2922
2923  // If no usable window is found and 'switchbuf' contains "usetab"
2924  // then search in other tabs.
2925  if (!usable_win && (swb_flags & kOptSwbFlagUsetab)) {
2926    usable_win = qf_goto_tabwin_with_file(qf_fnum);
2927  }
2928
2929  // If there is only one window and it is the quickfix window, create a
2930  // new one above the quickfix window.
2931  if ((ONE_WINDOW && bt_quickfix(curbuf)) || !usable_win || newwin) {
2932    if (qf_open_new_file_win(ll_ref) != OK) {
2933      return FAIL;
2934    }
2935    *opened_window = true;  // close it when fail
2936  } else {
2937    if (curwin->w_llist_ref != NULL) {  // In a location window
2938      qf_goto_win_with_ll_file(usable_wp, qf_fnum, ll_ref);
2939    } else {  // In a quickfix window
2940      qf_goto_win_with_qfl_file(qf_fnum);
2941    }
2942  }
2943
2944  return OK;
2945}
2946
2947/// Edit the selected file or help file.
2948/// @return  OK if successfully edited the file.
2949///          FAIL on failing to open the buffer.
2950///          QF_ABORT if the quickfix/location list was freed by an autocmd
2951///          when opening the buffer.
2952static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, int prev_winid,
2953                               bool *opened_window)
2954{
2955  qf_list_T *qfl = qf_get_curlist(qi);
2956  int old_changetick = qfl->qf_changedtick;
2957  int old_qf_curlist = qi->qf_curlist;
2958  qfltype_T qfl_type = qfl->qfl_type;
2959  int retval = OK;
2960  unsigned save_qfid = qfl->qf_id;
2961
2962  if (qf_ptr->qf_type == 1) {
2963    // Open help file (do_ecmd() will set b_help flag, readfile() will
2964    // set b_p_ro flag).
2965    if (!can_abandon(curbuf, forceit)) {
2966      no_write_message();
2967      return FAIL;
2968    }
2969    retval = do_ecmd(qf_ptr->qf_fnum, NULL, NULL, NULL, 1,
2970                     ECMD_HIDE + ECMD_SET_HELP,
2971                     prev_winid == curwin->handle ? curwin : NULL);
2972  } else {
2973    int fnum = qf_ptr->qf_fnum;
2974
2975    if (!forceit && curwin->w_p_wfb && curbuf->b_fnum != fnum) {
2976      if (qi->qfl_type == QFLT_LOCATION) {
2977        // Location lists cannot split or reassign their window
2978        // so 'winfixbuf' windows must fail
2979        emsg(_(e_winfixbuf_cannot_go_to_buffer));
2980        return FAIL;
2981      }
2982
2983      if (win_valid(prevwin) && !prevwin->w_p_wfb
2984          && !bt_quickfix(prevwin->w_buffer)) {
2985        // 'winfixbuf' is set; attempt to change to a window without it
2986        // that isn't a quickfix/location list window.
2987        win_goto(prevwin);
2988      }
2989      if (curwin->w_p_wfb) {
2990        // Split the window, which will be 'nowinfixbuf', and set curwin
2991        // to that
2992        if (win_split(0, 0) == OK) {
2993          *opened_window = true;
2994        }
2995        if (curwin->w_p_wfb) {
2996          // Autocommands set 'winfixbuf' or sent us to another window
2997          // with it set, or we failed to split the window.  Give up,
2998          // but don't return immediately, as they may have messed
2999          // with the list.
3000          emsg(_(e_winfixbuf_cannot_go_to_buffer));
3001          retval = FAIL;
3002        }
3003      }
3004    }
3005
3006    if (retval == OK) {
3007      retval = buflist_getfile(fnum, 1,
3008                               GETF_SETMARK | GETF_SWITCH, forceit);
3009    }
3010  }
3011  // If a location list, check whether the associated window is still
3012  // present.
3013  if (qfl_type == QFLT_LOCATION) {
3014    win_T *wp = win_id2wp(prev_winid);
3015
3016    if (wp == NULL && curwin->w_llist != qi) {
3017      emsg(_("E924: Current window was closed"));
3018      *opened_window = false;
3019      return QF_ABORT;
3020    }
3021  }
3022
3023  if (qfl_type == QFLT_QUICKFIX && !qflist_valid(NULL, save_qfid)) {
3024    emsg(_(e_current_quickfix_list_was_changed));
3025    return QF_ABORT;
3026  }
3027
3028  if (old_qf_curlist != qi->qf_curlist
3029      || old_changetick != qfl->qf_changedtick
3030      || !is_qf_entry_present(qfl, qf_ptr)) {
3031    if (qfl_type == QFLT_QUICKFIX) {
3032      emsg(_(e_current_quickfix_list_was_changed));
3033    } else {
3034      emsg(_(e_current_location_list_was_changed));
3035    }
3036    return QF_ABORT;
3037  }
3038
3039  return retval;
3040}
3041
3042/// Return the byte index in the current line for screen column "vcol"
3043/// (zero-based).  A <tab> is always counted as 8 screen columns, matching the
3044/// column numbers compilers report for the "%v" item in 'errorformat',
3045/// regardless of the buffer's 'tabstop'.
3046static int qf_screen_col_to_idx(colnr_T vcol)
3047{
3048  const char *line = get_cursor_line_ptr();
3049  const char *p = line;
3050  colnr_T col = 0;
3051
3052  while (*p != NUL && col < vcol) {
3053    if (*p == TAB) {
3054      col += 8 - (col % 8);
3055    } else {
3056      col += ptr2cells(p);
3057    }
3058    if (col > vcol) {
3059      break;
3060    }
3061    MB_PTR_ADV(p);
3062  }
3063  return (int)(p - line);
3064}
3065
3066/// Go to the error line in the current file using either line/column number or
3067/// a search pattern.
3068static void qf_jump_goto_line(linenr_T qf_lnum, int qf_col, char qf_viscol, char *qf_pattern)
3069{
3070  if (qf_pattern == NULL) {
3071    // Go to line with error, unless qf_lnum is 0.
3072    linenr_T i = qf_lnum;
3073    if (i > 0) {
3074      i = MIN(i, curbuf->b_ml.ml_line_count);
3075      curwin->w_cursor.lnum = i;
3076    }
3077    if (qf_col > 0) {
3078      curwin->w_cursor.coladd = 0;
3079      if (qf_viscol == true) {
3080        curwin->w_cursor.col = qf_screen_col_to_idx(qf_col - 1);
3081      } else {
3082        curwin->w_cursor.col = qf_col - 1;
3083      }
3084      curwin->w_set_curswant = true;
3085      check_cursor(curwin);
3086    } else {
3087      beginline(BL_WHITE | BL_FIX);
3088    }
3089  } else {
3090    // Move the cursor to the first line in the buffer
3091    pos_T save_cursor = curwin->w_cursor;
3092    curwin->w_cursor.lnum = 0;
3093    if (!do_search(NULL, '/', '/', qf_pattern, strlen(qf_pattern), 1, SEARCH_KEEP, p_magic, NULL)) {
3094      curwin->w_cursor = save_cursor;
3095    }
3096  }
3097}
3098
3099/// Display quickfix list index and size message
3100static void qf_jump_print_msg(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, buf_T *old_curbuf,
3101                              linenr_T old_lnum)
3102{
3103  garray_T *const gap = qfga_get();
3104
3105  // Update the screen before showing the message, unless messages scrolled.
3106  if (!msg_scrolled) {
3107    update_topline(curwin);
3108    if (must_redraw) {
3109      update_screen();
3110    }
3111  }
3112  size_t IObufflen = vim_snprintf_safelen(IObuff, IOSIZE,
3113                                          _("(%d of %d)%s%s: "), qf_index,
3114                                          qf_get_curlist(qi)->qf_count,
3115                                          qf_ptr->qf_cleared ? _(" (line deleted)") : "",
3116                                          qf_types(qf_ptr->qf_type, qf_ptr->qf_nr));
3117  // Add the message, skipping leading whitespace and newlines.
3118  ga_concat_len(gap, IObuff, IObufflen);
3119  qf_fmt_text(gap, skipwhite(qf_ptr->qf_text));
3120  ga_append(gap, NUL);
3121
3122  // Output the message.  Overwrite to avoid scrolling when the 'O'
3123  // flag is present in 'shortmess'; But when not jumping, print the
3124  // whole message.
3125  linenr_T i = msg_scroll;
3126  if (curbuf == old_curbuf && curwin->w_cursor.lnum == old_lnum) {
3127    msg_scroll = true;
3128  } else if ((msg_scrolled == 0 || (p_ch == 0 && msg_scrolled == 1))
3129             && shortmess(kShmOverall)) {
3130    msg_scroll = false;
3131  }
3132  msg_ext_set_kind("quickfix");
3133  msg_keep(gap->ga_data, 0, true, false);
3134  msg_scroll = (int)i;
3135
3136  qfga_clear();
3137}
3138
3139/// Find a usable window for opening a file from the quickfix/location list. If
3140/// a window is not found then open a new window. If 'newwin' is true, then open
3141/// a new window.
3142/// @return  OK if successfully jumped or opened a window.
3143///          FAIL if not able to jump/open a window.
3144///          NOTDONE if a file is not associated with the entry.
3145///          QF_ABORT if the quickfix/location list was modified by an autocmd.
3146static int qf_jump_open_window(qf_info_T *qi, qfline_T *qf_ptr, bool newwin, bool *opened_window)
3147{
3148  qf_list_T *qfl = qf_get_curlist(qi);
3149  int old_changetick = qfl->qf_changedtick;
3150  int old_qf_curlist = qi->qf_curlist;
3151  qfltype_T qfl_type = qfl->qfl_type;
3152
3153  // For ":helpgrep" find a help window or open one.
3154  if (qf_ptr->qf_type == 1 && (!bt_help(curwin->w_buffer) || cmdmod.cmod_tab != 0)) {
3155    if (jump_to_help_window(qi, newwin, opened_window) == FAIL) {
3156      return FAIL;
3157    }
3158  }
3159  if (old_qf_curlist != qi->qf_curlist
3160      || old_changetick != qfl->qf_changedtick
3161      || !is_qf_entry_present(qfl, qf_ptr)) {
3162    if (qfl_type == QFLT_QUICKFIX) {
3163      emsg(_(e_current_quickfix_list_was_changed));
3164    } else {
3165      emsg(_(e_current_location_list_was_changed));
3166    }
3167    return QF_ABORT;
3168  }
3169
3170  // If currently in the quickfix window, find another window to show the
3171  // file in.
3172  if (bt_quickfix(curbuf) && !*opened_window) {
3173    // If there is no file specified, we don't know where to go.
3174    // But do advance, otherwise ":cn" gets stuck.
3175    if (qf_ptr->qf_fnum == 0) {
3176      return NOTDONE;
3177    }
3178
3179    if (qf_jump_to_usable_window(qf_ptr->qf_fnum, newwin, opened_window)
3180        == FAIL) {
3181      return FAIL;
3182    }
3183  }
3184  if (old_qf_curlist != qi->qf_curlist
3185      || old_changetick != qfl->qf_changedtick
3186      || !is_qf_entry_present(qfl, qf_ptr)) {
3187    if (qfl_type == QFLT_QUICKFIX) {
3188      emsg(_(e_current_quickfix_list_was_changed));
3189    } else {
3190      emsg(_(e_current_location_list_was_changed));
3191    }
3192    return QF_ABORT;
3193  }
3194
3195  return OK;
3196}
3197
3198/// Edit a selected file from the quickfix/location list and jump to a
3199/// particular line/column, adjust the folds and display a message about the
3200/// jump.
3201/// @return  OK on success and FAIL on failing to open the file/buffer.
3202///          QF_ABORT if the quickfix/location list is freed by an autocmd when opening
3203///          the file.
3204static int qf_jump_to_buffer(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, int forceit,
3205                             int prev_winid, bool *opened_window, int openfold, bool print_message)
3206{
3207  // If there is a file name, read the wanted file if needed, and check
3208  // autowrite etc.
3209  buf_T *old_curbuf = curbuf;
3210  linenr_T old_lnum = curwin->w_cursor.lnum;
3211  int retval = OK;
3212
3213  if (qf_ptr->qf_fnum != 0) {
3214    retval = qf_jump_edit_buffer(qi, qf_ptr, forceit, prev_winid,
3215                                 opened_window);
3216    if (retval != OK) {
3217      return retval;
3218    }
3219  }
3220
3221  // When not switched to another buffer, still need to set pc mark
3222  if (curbuf == old_curbuf) {
3223    setpcmark();
3224  }
3225
3226  qf_jump_goto_line(qf_ptr->qf_lnum, qf_ptr->qf_col, qf_ptr->qf_viscol, qf_ptr->qf_pattern);
3227
3228  if ((fdo_flags & kOptFdoFlagQuickfix) && openfold) {
3229    foldOpenCursor();
3230  }
3231  if (print_message) {
3232    qf_jump_print_msg(qi, qf_index, qf_ptr, old_curbuf, old_lnum);
3233  }
3234
3235  return retval;
3236}
3237
3238/// Jump to a quickfix line and try to use an existing window.
3239void qf_jump(qf_info_T *qi, int dir, int errornr, int forceit)
3240{
3241  qf_jump_newwin(qi, dir, errornr, forceit, false);
3242}
3243
3244// Jump to a quickfix line.
3245// If dir == 0 go to entry "errornr".
3246// If dir == FORWARD go "errornr" valid entries forward.
3247// If dir == BACKWARD go "errornr" valid entries backward.
3248// If dir == FORWARD_FILE go "errornr" valid entries files backward.
3249// If dir == BACKWARD_FILE go "errornr" valid entries files backward
3250// else if "errornr" is zero, redisplay the same line
3251// If 'forceit' is true, then can discard changes to the current buffer.
3252// If 'newwin' is true, then open the file in a new window.
3253static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, bool newwin)
3254{
3255  char *old_swb = p_swb;
3256  unsigned old_swb_flags = swb_flags;
3257  const bool old_KeyTyped = KeyTyped;           // getting file may reset it
3258
3259  if (qi == NULL) {
3260    assert(ql_info != NULL);
3261    qi = ql_info;
3262  }
3263
3264  if (qf_stack_empty(qi) || qf_list_empty(qf_get_curlist(qi))) {
3265    emsg(_(e_no_errors));
3266    return;
3267  }
3268
3269  incr_quickfix_busy();
3270
3271  qf_list_T *qfl = qf_get_curlist(qi);
3272
3273  qfline_T *qf_ptr = qfl->qf_ptr;
3274  qfline_T *old_qf_ptr = qf_ptr;
3275  int qf_index = qfl->qf_index;
3276  int old_qf_index = qf_index;
3277
3278  qf_ptr = qf_get_entry(qfl, errornr, dir, &qf_index);
3279  if (qf_ptr == NULL) {
3280    qf_ptr = old_qf_ptr;
3281    qf_index = old_qf_index;
3282    goto theend;
3283  }
3284
3285  qfl->qf_index = qf_index;
3286  qfl->qf_ptr = qf_ptr;
3287
3288  // No need to print the error message if it's visible in the error window
3289  bool print_message = !qf_win_pos_update(qi, old_qf_index);
3290
3291  int prev_winid = curwin->handle;
3292
3293  bool opened_window = false;
3294  int retval = qf_jump_open_window(qi, qf_ptr, newwin, &opened_window);
3295  if (retval == FAIL) {
3296    goto failed;
3297  }
3298  if (retval == QF_ABORT) {
3299    qi = NULL;
3300    qf_ptr = NULL;
3301    goto theend;
3302  }
3303  if (retval == NOTDONE) {
3304    goto theend;
3305  }
3306
3307  retval = qf_jump_to_buffer(qi, qf_index, qf_ptr, forceit, prev_winid,
3308                             &opened_window, old_KeyTyped, print_message);
3309  if (retval == QF_ABORT) {
3310    // Quickfix/location list was modified by an autocmd
3311    qi = NULL;
3312    qf_ptr = NULL;
3313  }
3314
3315  if (retval != OK) {
3316    if (opened_window) {
3317      win_close(curwin, true, false);          // Close opened window
3318    }
3319    if (qf_ptr != NULL && qf_ptr->qf_fnum != 0) {
3320      // Couldn't open file, so put index back where it was.  This could
3321      // happen if the file was readonly and we changed something.
3322failed:
3323      qf_ptr = old_qf_ptr;
3324      qf_index = old_qf_index;
3325    }
3326  }
3327theend:
3328  if (qi != NULL) {
3329    qfl->qf_ptr = qf_ptr;
3330    qfl->qf_index = qf_index;
3331  }
3332  if (p_swb != old_swb && p_swb == empty_string_option) {
3333    // Restore old 'switchbuf' value, but not when an autocommand or
3334    // modeline has changed the value.
3335    p_swb = old_swb;
3336    swb_flags = old_swb_flags;
3337  }
3338  decr_quickfix_busy();
3339}
3340
3341// Highlight ids used for displaying entries from the quickfix list.
3342static int qfFile_hl_id;
3343static int qfSep_hl_id;
3344static int qfLine_hl_id;
3345
3346/// Display information about a single entry from the quickfix/location list.
3347/// Used by ":clist/:llist" commands.
3348/// 'cursel' will be set to true for the currently selected entry in the
3349/// quickfix list.
3350static void qf_list_entry(qfline_T *qfp, int qf_idx, bool cursel)
3351{
3352  char *fname = NULL;
3353  if (qfp->qf_module != NULL && *qfp->qf_module != NUL) {
3354    vim_snprintf(IObuff, IOSIZE, "%2d %s", qf_idx, qfp->qf_module);
3355  } else {
3356    buf_T *buf;
3357    if (qfp->qf_fnum != 0
3358        && (buf = buflist_findnr(qfp->qf_fnum)) != NULL) {
3359      fname = qfp->qf_fname == NULL ? buf->b_fname : qfp->qf_fname;
3360      if (qfp->qf_type == 1) {  // :helpgrep
3361        fname = path_tail(fname);
3362      }
3363    }
3364    if (fname == NULL) {
3365      snprintf(IObuff, IOSIZE, "%2d", qf_idx);
3366    } else {
3367      vim_snprintf(IObuff, IOSIZE, "%2d %s", qf_idx, fname);
3368    }
3369  }
3370
3371  // Support for filtering entries using :filter /pat/ clist
3372  // Match against the module name, file name, search pattern and
3373  // text of the entry.
3374  bool filter_entry = true;
3375  if (qfp->qf_module != NULL && *qfp->qf_module != NUL) {
3376    filter_entry &= message_filtered(qfp->qf_module);
3377  }
3378  if (filter_entry && fname != NULL) {
3379    filter_entry &= message_filtered(fname);
3380  }
3381  if (filter_entry && qfp->qf_pattern != NULL) {
3382    filter_entry &= message_filtered(qfp->qf_pattern);
3383  }
3384  if (filter_entry) {
3385    filter_entry &= message_filtered(qfp->qf_text);
3386  }
3387  if (filter_entry) {
3388    return;
3389  }
3390
3391  if (msg_col > 0) {
3392    msg_putchar('\n');
3393  }
3394  msg_outtrans(IObuff, cursel ? HLF_QFL : qfFile_hl_id, false);
3395
3396  if (qfp->qf_lnum != 0) {
3397    msg_puts_hl(":", qfSep_hl_id, false);
3398  }
3399  garray_T *gap = qfga_get();
3400  if (qfp->qf_lnum != 0) {
3401    qf_range_text(gap, qfp);
3402  }
3403  ga_concat(gap, qf_types(qfp->qf_type, qfp->qf_nr));
3404  ga_append(gap, NUL);
3405  if (*(char *)gap->ga_data != NUL) {
3406    msg_puts_hl(gap->ga_data, qfLine_hl_id, false);
3407  }
3408  msg_puts_hl(":", qfSep_hl_id, false);
3409  if (qfp->qf_pattern != NULL) {
3410    gap = qfga_get();
3411    qf_fmt_text(gap, qfp->qf_pattern);
3412    ga_append(gap, NUL);
3413    msg_puts(gap->ga_data);
3414    msg_puts_hl(":", qfSep_hl_id, false);
3415  }
3416  msg_puts(" ");
3417
3418  // Remove newlines and leading whitespace from the text.  For an
3419  // unrecognized line keep the indent, the compiler may mark a word
3420  // with ^^^^.
3421  gap = qfga_get();
3422  qf_fmt_text(gap, (fname != NULL || qfp->qf_lnum != 0) ? skipwhite(qfp->qf_text) : qfp->qf_text);
3423  ga_append(gap, NUL);
3424  msg_prt_line(gap->ga_data, false);
3425}
3426
3427// ":clist": list all errors
3428// ":llist": list all locations
3429void qf_list(exarg_T *eap)
3430{
3431  char *arg = eap->arg;
3432  int all = eap->forceit;     // if not :cl!, only show recognised errors
3433  qf_info_T *qi = qf_cmd_get_stack(eap, true);
3434
3435  if (qi == NULL) {
3436    return;
3437  }
3438
3439  if (qf_stack_empty(qi) || qf_list_empty(qf_get_curlist(qi))) {
3440    emsg(_(e_no_errors));
3441    return;
3442  }
3443
3444  bool plus = false;
3445  if (*arg == '+') {
3446    arg++;
3447    plus = true;
3448  }
3449  int idx1 = 1;
3450  int idx2 = -1;
3451  if (!get_list_range(&arg, &idx1, &idx2) || *arg != NUL) {
3452    semsg(_(e_trailing_arg), arg);
3453    return;
3454  }
3455  qf_list_T *qfl = qf_get_curlist(qi);
3456  int i;
3457  if (plus) {
3458    i = qfl->qf_index;
3459    idx2 = i + idx1;
3460    idx1 = i;
3461  } else {
3462    i = qfl->qf_count;
3463    if (idx1 < 0) {
3464      idx1 = (-idx1 > i) ? 0 : idx1 + i + 1;
3465    }
3466    if (idx2 < 0) {
3467      idx2 = (-idx2 > i) ? 0 : idx2 + i + 1;
3468    }
3469  }
3470
3471  // Shorten all the file names, so that it is easy to read.
3472  shorten_fnames(false);
3473
3474  // Get the attributes for the different quickfix highlight items.  Note
3475  // that this depends on syntax items defined in the qf.vim syntax file
3476  qfFile_hl_id = syn_name2id("qfFileName");
3477  if (qfFile_hl_id == 0) {
3478    qfFile_hl_id = HLF_D;
3479  }
3480  qfSep_hl_id = syn_name2id("qfSeparator");
3481  if (qfSep_hl_id == 0) {
3482    qfSep_hl_id = HLF_D;
3483  }
3484  qfLine_hl_id = syn_name2id("qfLineNr");
3485  if (qfLine_hl_id == 0) {
3486    qfLine_hl_id = HLF_N;
3487  }
3488
3489  if (qfl->qf_nonevalid) {
3490    all = true;
3491  }
3492  msg_ext_set_kind("list_cmd");
3493  qfline_T *qfp;
3494  FOR_ALL_QFL_ITEMS(qfl, qfp, i) {
3495    if ((qfp->qf_valid || all) && idx1 <= i && i <= idx2) {
3496      qf_list_entry(qfp, i, i == qfl->qf_index);
3497    }
3498    os_breakcheck();
3499  }
3500  qfga_clear();
3501}
3502
3503/// Remove newlines and leading whitespace from an error message.
3504/// Add the result to the grow array "gap".
3505static void qf_fmt_text(garray_T *gap, const char *restrict text)
3506  FUNC_ATTR_NONNULL_ALL
3507{
3508  const char *p = text;
3509  while (*p != NUL) {
3510    if (*p == '\n') {
3511      ga_append(gap, ' ');
3512      while (*++p != NUL) {
3513        if (!ascii_iswhite(*p) && *p != '\n') {
3514          break;
3515        }
3516      }
3517    } else {
3518      ga_append(gap, (uint8_t)(*p++));
3519    }
3520  }
3521}
3522
3523/// Add the range information from the lnum, col, end_lnum, and end_col values
3524/// of a quickfix entry to the grow array "gap".
3525static void qf_range_text(garray_T *gap, const qfline_T *qfp)
3526{
3527  String buf = cbuf_as_string(IObuff, 0);
3528
3529  buf.size = vim_snprintf_safelen(buf.data, IOSIZE, "%" PRIdLINENR, qfp->qf_lnum);
3530
3531  if (qfp->qf_end_lnum > 0 && qfp->qf_lnum != qfp->qf_end_lnum) {
3532    buf.size += vim_snprintf_safelen(buf.data + buf.size, IOSIZE - buf.size,
3533                                     "-%" PRIdLINENR, qfp->qf_end_lnum);
3534  }
3535  if (qfp->qf_col > 0) {
3536    buf.size += vim_snprintf_safelen(buf.data + buf.size, IOSIZE - buf.size,
3537                                     " col %d", qfp->qf_col);
3538    if (qfp->qf_end_col > 0 && qfp->qf_col != qfp->qf_end_col) {
3539      buf.size += vim_snprintf_safelen(buf.data + buf.size, IOSIZE - buf.size,
3540                                       "-%d", qfp->qf_end_col);
3541    }
3542  }
3543
3544  ga_concat_len(gap, buf.data, buf.size);
3545}
3546
3547/// Display information (list number, list size and the title) about a
3548/// quickfix/location list.
3549static void qf_msg(qf_info_T *qi, int which, char *lead)
3550{
3551  char *title = qi->qf_lists[which].qf_title;
3552  int count = qi->qf_lists[which].qf_count;
3553  char buf[IOSIZE];
3554
3555  vim_snprintf(buf, IOSIZE, _("%serror list %d of %d; %d errors "),
3556               lead,
3557               which + 1,
3558               qi->qf_listcount,
3559               count);
3560
3561  if (title != NULL) {
3562    size_t len = strlen(buf);
3563
3564    if (len < 34) {
3565      memset(buf + len, ' ', 34 - len);
3566      buf[34] = NUL;
3567    }
3568    xstrlcat(buf, title, IOSIZE);
3569  }
3570  trunc_string(buf, buf, Columns - 1, IOSIZE);
3571  msg(buf, 0);
3572}
3573
3574/// ":colder [count]": Up in the quickfix stack.
3575/// ":cnewer [count]": Down in the quickfix stack.
3576/// ":lolder [count]": Up in the location list stack.
3577/// ":lnewer [count]": Down in the location list stack.
3578void qf_age(exarg_T *eap)
3579{
3580  qf_info_T *qi;
3581
3582  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
3583    return;
3584  }
3585
3586  int count = (eap->addr_count != 0) ? (int)eap->line2 : 1;
3587  while (count--) {
3588    if (eap->cmdidx == CMD_colder || eap->cmdidx == CMD_lolder) {
3589      if (qi->qf_curlist == 0) {
3590        emsg(_("E380: At bottom of quickfix stack"));
3591        break;
3592      }
3593      qi->qf_curlist--;
3594    } else {
3595      if (qi->qf_curlist >= qi->qf_listcount - 1) {
3596        emsg(_("E381: At top of quickfix stack"));
3597        break;
3598      }
3599      qi->qf_curlist++;
3600    }
3601  }
3602  qf_msg(qi, qi->qf_curlist, "");
3603  qf_update_buffer(qi, NULL);
3604}
3605
3606/// Display the information about all the quickfix/location lists in the stack.
3607void qf_history(exarg_T *eap)
3608{
3609  qf_info_T *qi = qf_cmd_get_stack(eap, false);
3610
3611  if (eap->addr_count > 0) {
3612    if (qi == NULL) {
3613      emsg(_(e_loclist));
3614      return;
3615    }
3616
3617    // Jump to the specified quickfix list
3618    if (eap->line2 > 0 && eap->line2 <= qi->qf_listcount) {
3619      qi->qf_curlist = eap->line2 - 1;
3620      qf_msg(qi, qi->qf_curlist, "");
3621      qf_update_buffer(qi, NULL);
3622    } else {
3623      emsg(_(e_invrange));
3624    }
3625
3626    return;
3627  }
3628
3629  if (qf_stack_empty(qi)) {
3630    msg(_("No entries"), 0);
3631  } else {
3632    for (int i = 0; i < qi->qf_listcount; i++) {
3633      qf_msg(qi, i, i == qi->qf_curlist ? "> " : "  ");
3634    }
3635  }
3636}
3637
3638/// Free all the entries in the error list "idx". Note that other information
3639/// associated with the list like context and title are not freed.
3640static void qf_free_items(qf_list_T *qfl)
3641{
3642  bool stop = false;
3643
3644  while (qfl->qf_count && qfl->qf_start != NULL) {
3645    qfline_T *qfp = qfl->qf_start;
3646    qfline_T *qfpnext = qfp->qf_next;
3647    if (!stop) {
3648      xfree(qfp->qf_fname);
3649      xfree(qfp->qf_module);
3650      xfree(qfp->qf_text);
3651      xfree(qfp->qf_pattern);
3652      tv_clear(&qfp->qf_user_data);
3653      stop = (qfp == qfpnext);
3654      xfree(qfp);
3655      if (stop) {
3656        // Somehow qf_count may have an incorrect value, set it to 1
3657        // to avoid crashing when it's wrong.
3658        // TODO(vim): Avoid qf_count being incorrect.
3659        qfl->qf_count = 1;
3660      } else {
3661        qfl->qf_start = qfpnext;
3662      }
3663    }
3664    qfl->qf_count--;
3665  }
3666
3667  qfl->qf_index = 0;
3668  qfl->qf_start = NULL;
3669  qfl->qf_last = NULL;
3670  qfl->qf_ptr = NULL;
3671  qfl->qf_nonevalid = true;
3672
3673  qf_clean_dir_stack(&qfl->qf_dir_stack);
3674  qfl->qf_directory = NULL;
3675  qf_clean_dir_stack(&qfl->qf_file_stack);
3676  qfl->qf_currfile = NULL;
3677  qfl->qf_multiline = false;
3678  qfl->qf_multiignore = false;
3679  qfl->qf_multiscan = false;
3680}
3681
3682/// Free error list "idx". Frees all the entries in the quickfix list,
3683/// associated context information and the title.
3684static void qf_free(qf_list_T *qfl)
3685{
3686  qf_free_items(qfl);
3687
3688  XFREE_CLEAR(qfl->qf_title);
3689  tv_free(qfl->qf_ctx);
3690  qfl->qf_ctx = NULL;
3691  callback_free(&qfl->qf_qftf_cb);
3692  qfl->qf_id = 0;
3693  qfl->qf_changedtick = 0;
3694}
3695
3696/// Adjust error list entries for changed line numbers
3697///
3698/// Note: `buf` is the changed buffer, but `wp` is a potential location list
3699/// into that buffer, or NULL to check the quickfix list.
3700bool qf_mark_adjust(buf_T *buf, win_T *wp, linenr_T line1, linenr_T line2, linenr_T amount,
3701                    linenr_T amount_after)
3702{
3703  qf_info_T *qi = ql_info;
3704  assert(qi != NULL);
3705  int buf_has_flag = wp == NULL ? BUF_HAS_QF_ENTRY : BUF_HAS_LL_ENTRY;
3706
3707  if (!(buf->b_has_qf_entry & buf_has_flag)) {
3708    return false;
3709  }
3710  if (wp != NULL) {
3711    if (wp->w_llist == NULL) {
3712      return false;
3713    }
3714    qi = wp->w_llist;
3715  }
3716
3717  int i;
3718  qfline_T *qfp;
3719  bool found_one = false;
3720  for (int idx = 0; idx < qi->qf_listcount; idx++) {
3721    qf_list_T *qfl = qf_get_list(qi, idx);
3722    if (!qf_list_empty(qfl)) {
3723      FOR_ALL_QFL_ITEMS(qfl, qfp, i) {
3724        if (qfp->qf_fnum == buf->b_fnum) {
3725          found_one = true;
3726          if (qfp->qf_cleared) {
3727            continue;
3728          }
3729
3730          if (qfp->qf_lnum >= line1 && qfp->qf_lnum <= line2) {
3731            if (amount == MAXLNUM) {
3732              qfp->qf_cleared = true;
3733            } else {
3734              qfp->qf_lnum += amount;
3735            }
3736          } else if (amount_after && qfp->qf_lnum > line2) {
3737            qfp->qf_lnum += amount_after;
3738          }
3739        }
3740      }
3741    }
3742  }
3743
3744  return found_one;
3745}
3746
3747// Make a nice message out of the error character and the error number:
3748//  char    number  message
3749//  e or E    0     " error"
3750//  w or W    0     " warning"
3751//  i or I    0     " info"
3752//  n or N    0     " note"
3753//  0         0     ""
3754//  other     0     " c"
3755//  e or E    n     " error n"
3756//  w or W    n     " warning n"
3757//  i or I    n     " info n"
3758//  n or N    n     " note n"
3759//  0         n     " error n"
3760//  other     n     " c n"
3761//  1         x     ""          :helpgrep
3762static char *qf_types(int c, int nr)
3763{
3764  static char cc[3];
3765  char *p;
3766
3767  if (c == 'W' || c == 'w') {
3768    p = " warning";
3769  } else if (c == 'I' || c == 'i') {
3770    p = " info";
3771  } else if (c == 'N' || c == 'n') {
3772    p = " note";
3773  } else if (c == 'E' || c == 'e' || (c == 0 && nr > 0)) {
3774    p = " error";
3775  } else if (c == 0 || c == 1) {
3776    p = "";
3777  } else {
3778    cc[0] = ' ';
3779    cc[1] = (char)c;
3780    cc[2] = NUL;
3781    p = cc;
3782  }
3783
3784  if (nr <= 0) {
3785    return p;
3786  }
3787
3788  static char buf[20];
3789  snprintf(buf, sizeof(buf), "%s %3d", p, nr);
3790  return buf;
3791}
3792
3793// When "split" is false: Open the entry/result under the cursor.
3794// When "split" is true: Open the entry/result under the cursor in a new window.
3795void qf_view_result(bool split)
3796{
3797  qf_info_T *qi = ql_info;
3798  assert(qi != NULL);
3799
3800  if (IS_LL_WINDOW(curwin)) {
3801    qi = GET_LOC_LIST(curwin);
3802  }
3803
3804  if (qf_list_empty(qf_get_curlist(qi))) {
3805    emsg(_(e_no_errors));
3806    return;
3807  }
3808
3809  if (split) {
3810    // Open the selected entry in a new window
3811    qf_jump_newwin(qi, 0, (int)curwin->w_cursor.lnum, false, true);
3812    do_cmdline_cmd("clearjumps");
3813    return;
3814  }
3815
3816  do_cmdline_cmd((IS_LL_WINDOW(curwin) ? ".ll" : ".cc"));
3817}
3818
3819// ":cwindow": open the quickfix window if we have errors to display,
3820//             close it if not.
3821// ":lwindow": open the location list window if we have locations to display,
3822//             close it if not.
3823void ex_cwindow(exarg_T *eap)
3824{
3825  qf_info_T *qi;
3826
3827  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
3828    return;
3829  }
3830
3831  qf_list_T *qfl = qf_get_curlist(qi);
3832
3833  // Look for an existing quickfix window.
3834  win_T *win = qf_find_win(qi);
3835
3836  // If a quickfix window is open but we have no errors to display,
3837  // close the window.  If a quickfix window is not open, then open
3838  // it if we have errors; otherwise, leave it closed.
3839  if (qf_stack_empty(qi)
3840      || qfl->qf_nonevalid
3841      || qf_list_empty(qfl)) {
3842    if (win != NULL) {
3843      ex_cclose(eap);
3844    }
3845  } else if (win == NULL) {
3846    ex_copen(eap);
3847  }
3848}
3849
3850// ":cclose": close the window showing the list of errors.
3851// ":lclose": close the window showing the location list
3852void ex_cclose(exarg_T *eap)
3853{
3854  qf_info_T *qi;
3855
3856  if ((qi = qf_cmd_get_stack(eap, false)) == NULL) {
3857    return;
3858  }
3859
3860  // Find existing quickfix window and close it.
3861  win_T *win = qf_find_win(qi);
3862  if (win != NULL) {
3863    win_close(win, false, false);
3864  }
3865}
3866
3867// Goto a quickfix or location list window (if present).
3868// Returns OK if the window is found, FAIL otherwise.
3869static int qf_goto_cwindow(const qf_info_T *qi, bool resize, int sz, bool vertsplit)
3870{
3871  win_T *const win = qf_find_win(qi);
3872  if (win == NULL) {
3873    return FAIL;
3874  }
3875
3876  win_goto(win);
3877  if (resize) {
3878    if (vertsplit) {
3879      if (sz != win->w_width) {
3880        win_setwidth(sz);
3881      }
3882    } else if (sz != win->w_height
3883               && (win->w_height + win->w_hsep_height + win->w_status_height + tabline_height()
3884                   < cmdline_row)) {
3885      win_setheight(sz);
3886    }
3887  }
3888
3889  return OK;
3890}
3891
3892// Set options for the buffer in the quickfix or location list window.
3893static void qf_set_cwindow_options(void)
3894{
3895  // switch off 'swapfile'
3896  set_option_value_give_err(kOptSwapfile, BOOLEAN_OBJ(false), OPT_LOCAL);
3897  set_option_value_give_err(kOptBuftype, STATIC_CSTR_AS_OBJ("quickfix"), OPT_LOCAL);
3898  set_option_value_give_err(kOptBufhidden, STATIC_CSTR_AS_OBJ("hide"), OPT_LOCAL);
3899  RESET_BINDING(curwin);
3900  curwin->w_p_diff = false;
3901  set_option_value_give_err(kOptFoldmethod, STATIC_CSTR_AS_OBJ("manual"), OPT_LOCAL);
3902}
3903
3904// Open a new quickfix or location list window, load the quickfix buffer and
3905// set the appropriate options for the window.
3906// Returns FAIL if the window could not be opened.
3907static int qf_open_new_cwindow(qf_info_T *qi, int height)
3908  FUNC_ATTR_NONNULL_ALL
3909{
3910  win_T *oldwin = curwin;
3911  const tabpage_T *const prevtab = curtab;
3912  int flags = 0;
3913
3914  const buf_T *const qf_buf = qf_find_buf(qi);
3915
3916  // The current window becomes the previous window afterwards.
3917  win_T *const win = curwin;
3918
3919  // Default is to open the window below the current window or at the bottom,
3920  // except when :belowright or :aboveleft is used.
3921  if (cmdmod.cmod_split == 0) {
3922    flags = IS_QF_STACK(qi) ? WSP_BOT : WSP_BELOW;
3923  }
3924  flags |= WSP_NEWLOC;
3925
3926  // Create a snapshot for quickfix window (not for location list)
3927  // so that when closing it, we can restore to the previous window
3928  if (IS_QF_STACK(qi)) {
3929    flags |= WSP_QUICKFIX;
3930  }
3931
3932  if (win_split(height, flags) == FAIL) {
3933    return FAIL;  // not enough room for window
3934  }
3935  RESET_BINDING(curwin);
3936
3937  if (IS_LL_STACK(qi)) {
3938    // For the location list window, create a reference to the
3939    // location list stack from the window 'win'.
3940    curwin->w_llist_ref = qi;
3941    qi->qf_refcount++;
3942  }
3943
3944  if (oldwin != curwin) {
3945    oldwin = NULL;  // don't store info when in another window
3946  }
3947  if (qf_buf != NULL) {
3948    // Use the existing quickfix buffer
3949    if (do_ecmd(qf_buf->b_fnum, NULL, NULL, NULL, ECMD_ONE,
3950                ECMD_HIDE + ECMD_OLDBUF + ECMD_NOWINENTER, oldwin) == FAIL) {
3951      return FAIL;
3952    }
3953  } else {
3954    // Create a new quickfix buffer
3955    if (do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE + ECMD_NOWINENTER, oldwin) == FAIL) {
3956      return FAIL;
3957    }
3958    // save the number of the new buffer
3959    qi->qf_bufnr = curbuf->b_fnum;
3960  }
3961
3962  // Set the options for the quickfix buffer/window (if not already done)
3963  // Do this even if the quickfix buffer was already present, as an autocmd
3964  // might have previously deleted (:bdelete) the quickfix buffer.
3965  if (!bt_quickfix(curbuf)) {
3966    qf_set_cwindow_options();
3967  }
3968
3969  // Only set the height when still in the same tab page and there is no
3970  // window to the side.
3971  if (curtab == prevtab && curwin->w_width == Columns) {
3972    win_setheight(height);
3973  }
3974  curwin->w_p_wfh = true;  // set 'winfixheight'
3975  if (win_valid(win)) {
3976    prevwin = win;
3977  }
3978  return OK;
3979}
3980
3981/// Set "w:quickfix_title" if "qi" has a title.
3982static void qf_set_title_var(qf_list_T *qfl)
3983{
3984  if (qfl->qf_title != NULL) {
3985    set_internal_string_var("w:quickfix_title", qfl->qf_title);
3986  }
3987}
3988
3989/// ":copen": open a window that shows the list of errors.
3990/// ":lopen": open a window that shows the location list.
3991void ex_copen(exarg_T *eap)
3992{
3993  qf_info_T *qi;
3994
3995  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
3996    return;
3997  }
3998
3999  incr_quickfix_busy();
4000
4001  int height;
4002  if (eap->addr_count != 0) {
4003    height = (int)eap->line2;
4004  } else {
4005    height = QF_WINHEIGHT;
4006  }
4007  reset_VIsual_and_resel();  // stop Visual mode
4008
4009  // Find an existing quickfix window, or open a new one.
4010  int status = FAIL;
4011  if (cmdmod.cmod_tab == 0) {
4012    status = qf_goto_cwindow(qi, eap->addr_count != 0, height,
4013                             cmdmod.cmod_split & WSP_VERT);
4014  }
4015  if (status == FAIL) {
4016    if (qf_open_new_cwindow(qi, height) == FAIL) {
4017      decr_quickfix_busy();
4018      return;
4019    }
4020  }
4021
4022  qf_list_T *qfl = qf_get_curlist(qi);
4023  qf_set_title_var(qfl);
4024  // Save the current index here, as updating the quickfix buffer may free
4025  // the quickfix list
4026  int lnum = qfl->qf_index;
4027
4028  // Fill the buffer with the quickfix list.
4029  qf_fill_buffer(qfl, curbuf, NULL, curwin->handle);
4030
4031  decr_quickfix_busy();
4032
4033  curwin->w_cursor.lnum = lnum;
4034  curwin->w_cursor.col = 0;
4035  check_cursor(curwin);
4036  update_topline(curwin);             // scroll to show the line
4037}
4038
4039// Move the cursor in the quickfix window to "lnum".
4040static void qf_win_goto(win_T *win, linenr_T lnum)
4041{
4042  win_T *old_curwin = curwin;
4043
4044  curwin = win;
4045  curbuf = win->w_buffer;
4046  curwin->w_cursor.lnum = lnum;
4047  curwin->w_cursor.col = 0;
4048  curwin->w_cursor.coladd = 0;
4049  curwin->w_curswant = 0;
4050  update_topline(curwin);              // scroll to show the line
4051  redraw_later(curwin, UPD_VALID);
4052  curwin->w_redr_status = true;  // update ruler
4053  curwin = old_curwin;
4054  curbuf = curwin->w_buffer;
4055}
4056
4057/// :cbottom/:lbottom command.
4058void ex_cbottom(exarg_T *eap)
4059{
4060  qf_info_T *qi;
4061
4062  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
4063    return;
4064  }
4065
4066  win_T *win = qf_find_win(qi);
4067
4068  if (win != NULL && win->w_cursor.lnum != win->w_buffer->b_ml.ml_line_count) {
4069    qf_win_goto(win, win->w_buffer->b_ml.ml_line_count);
4070  }
4071}
4072
4073// Return the number of the current entry (line number in the quickfix
4074// window).
4075linenr_T qf_current_entry(win_T *wp)
4076{
4077  qf_info_T *qi = ql_info;
4078  assert(qi != NULL);
4079
4080  if (IS_LL_WINDOW(wp)) {
4081    // In the location list window, use the referenced location list
4082    qi = wp->w_llist_ref;
4083  }
4084
4085  return qf_get_curlist(qi)->qf_index;
4086}
4087
4088/// Update the cursor position in the quickfix window to the current error.
4089/// Return true if there is a quickfix window.
4090///
4091/// @param old_qf_index  previous qf_index or zero
4092static bool qf_win_pos_update(qf_info_T *qi, int old_qf_index)
4093{
4094  int qf_index = qf_get_curlist(qi)->qf_index;
4095
4096  // Put the cursor on the current error in the quickfix window, so that
4097  // it's viewable.
4098  win_T *win = qf_find_win(qi);
4099  if (win != NULL
4100      && qf_index <= win->w_buffer->b_ml.ml_line_count
4101      && old_qf_index != qf_index) {
4102    win->w_redraw_top = MIN(old_qf_index, qf_index);
4103    win->w_redraw_bot = MAX(old_qf_index, qf_index);
4104    qf_win_goto(win, qf_index);
4105  }
4106  return win != NULL;
4107}
4108
4109/// Checks whether the given window is displaying the specified
4110/// quickfix/location stack.
4111static int is_qf_win(const win_T *win, const qf_info_T *qi)
4112  FUNC_ATTR_NONNULL_ARG(2) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4113{
4114  // A window displaying the quickfix buffer will have the w_llist_ref field
4115  // set to NULL.
4116  // A window displaying a location list buffer will have the w_llist_ref
4117  // pointing to the location list.
4118  if (buf_valid(win->w_buffer) && bt_quickfix(win->w_buffer)) {
4119    if ((IS_QF_STACK(qi) && win->w_llist_ref == NULL)
4120        || (IS_LL_STACK(qi) && win->w_llist_ref == qi)) {
4121      return true;
4122    }
4123  }
4124
4125  return false;
4126}
4127
4128/// Find a window displaying the quickfix/location stack 'qi' in the current tab
4129/// page.
4130static win_T *qf_find_win(const qf_info_T *qi)
4131  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4132{
4133  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
4134    if (is_qf_win(win, qi)) {
4135      return win;
4136    }
4137  }
4138
4139  return NULL;
4140}
4141
4142/// Find a quickfix buffer.
4143/// Searches in windows opened in all the tab pages.
4144static buf_T *qf_find_buf(qf_info_T *qi)
4145  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4146{
4147  if (qi->qf_bufnr != INVALID_QFBUFNR) {
4148    buf_T *const qfbuf = buflist_findnr(qi->qf_bufnr);
4149    if (qfbuf != NULL) {
4150      return qfbuf;
4151    }
4152    // buffer is no longer present
4153    qi->qf_bufnr = INVALID_QFBUFNR;
4154  }
4155
4156  FOR_ALL_TAB_WINDOWS(tp, win) {
4157    if (is_qf_win(win, qi)) {
4158      return win->w_buffer;
4159    }
4160  }
4161
4162  return NULL;
4163}
4164
4165/// Process the 'quickfixtextfunc' option value.
4166/// Update the w:quickfix_title variable in the quickfix/location list window in
4167/// all the tab pages.
4168static void qf_update_win_titlevar(qf_info_T *qi)
4169  FUNC_ATTR_NONNULL_ALL
4170{
4171  qf_list_T *const qfl = qf_get_curlist(qi);
4172  win_T *const save_curwin = curwin;
4173
4174  FOR_ALL_TAB_WINDOWS(tp, win) {
4175    if (is_qf_win(win, qi)) {
4176      curwin = win;
4177      qf_set_title_var(qfl);
4178    }
4179  }
4180  curwin = save_curwin;
4181}
4182
4183// Find the quickfix buffer.  If it exists, update the contents.
4184static void qf_update_buffer(qf_info_T *qi, qfline_T *old_last)
4185{
4186  // Check if a buffer for the quickfix list exists.  Update it.
4187  buf_T *buf = qf_find_buf(qi);
4188  if (buf == NULL) {
4189    return;
4190  }
4191
4192  linenr_T old_line_count = buf->b_ml.ml_line_count;
4193  colnr_T old_endcol = ml_get_buf_len(buf, old_line_count);
4194  bcount_t old_bytecount = get_region_bytecount(buf, 1, old_line_count, 0, old_endcol);
4195  int qf_winid = 0;
4196
4197  win_T *win;
4198  if (IS_LL_STACK(qi)) {
4199    if (curwin->w_llist == qi) {
4200      win = curwin;
4201    } else {
4202      // Find the file window (non-quickfix) with this location list
4203      win = qf_find_win_with_loclist(qi);
4204      if (win == NULL) {
4205        // File window is not found. Find the location list window.
4206        win = qf_find_win(qi);
4207      }
4208      if (win == NULL) {
4209        return;
4210      }
4211    }
4212    qf_winid = (int)win->handle;
4213  }
4214
4215  // autocommands may cause trouble
4216  incr_quickfix_busy();
4217
4218  CtxSwitch aco = { 0 };
4219
4220  if (old_last == NULL) {
4221    // set curwin/curbuf to buf and save a few things
4222    ctx_switch(&aco, NULL, NULL, buf, 0);
4223  }
4224
4225  qf_update_win_titlevar(qi);
4226
4227  qf_fill_buffer(qf_get_curlist(qi), buf, old_last, qf_winid);
4228
4229  linenr_T new_line_count = buf->b_ml.ml_line_count;
4230  colnr_T new_endcol = ml_get_buf_len(buf, new_line_count);
4231  bcount_t new_byte_count = 0;
4232  linenr_T delta = new_line_count - old_line_count;
4233
4234  if (old_last == NULL) {
4235    new_byte_count = get_region_bytecount(buf, 1, new_line_count, 0, new_endcol);
4236    extmark_splice(buf, 0, 0, old_line_count - 1, 0, old_bytecount, new_line_count - 1, new_endcol,
4237                   new_byte_count, kExtmarkNoUndo);
4238    changed_lines(buf, 1, 0, old_line_count > 0 ? old_line_count + 1 : 1, delta, true);
4239  } else if (delta > 0) {
4240    linenr_T start_lnum = old_line_count + 1;
4241    new_byte_count = get_region_bytecount(buf, start_lnum, new_line_count, 0, new_endcol);
4242    extmark_splice(buf, old_line_count - 1, old_endcol, 0, 0, 0, delta, new_endcol, new_byte_count,
4243                   kExtmarkNoUndo);
4244    changed_lines(buf, start_lnum, 0, start_lnum, delta, true);
4245  }
4246  buf->b_changed = false;
4247
4248  if (old_last == NULL) {
4249    qf_win_pos_update(qi, 0);
4250
4251    // restore curwin/curbuf and a few other things
4252    ctx_restore(&aco);
4253  }
4254
4255  // Only redraw when added lines are visible.  This avoids flickering when
4256  // the added lines are not visible.
4257  if ((win = qf_find_win(qi)) != NULL && old_line_count < win->w_botline) {
4258    redraw_buf_later(buf, UPD_NOT_VALID);
4259  }
4260
4261  // always called after incr_quickfix_busy()
4262  decr_quickfix_busy();
4263}
4264
4265// Add an error line to the quickfix buffer.
4266static int qf_buf_add_line(qf_list_T *qfl, buf_T *buf, linenr_T lnum, const qfline_T *qfp,
4267                           char *dirname, char *qftf_str, bool first_bufline)
4268  FUNC_ATTR_NONNULL_ARG(1, 2, 4, 5)
4269{
4270  garray_T *gap = qfga_get();
4271
4272  // If the 'quickfixtextfunc' function returned a non-empty custom string
4273  // for this entry, then use it.
4274  if (qftf_str != NULL && *qftf_str != NUL) {
4275    ga_concat(gap, qftf_str);
4276  } else {
4277    buf_T *errbuf;
4278    if (qfp->qf_module != NULL) {
4279      ga_concat(gap, qfp->qf_module);
4280    } else if (qfp->qf_fnum != 0
4281               && (errbuf = buflist_findnr(qfp->qf_fnum)) != NULL
4282               && errbuf->b_fname != NULL) {
4283      if (qfp->qf_type == 1) {  // :helpgrep
4284        ga_concat(gap, path_tail(errbuf->b_fname));
4285      } else {
4286        // Shorten the file name if not done already.
4287        // For optimization, do this only for the first entry in a
4288        // buffer.
4289        if (first_bufline
4290            && (errbuf->b_sfname == NULL
4291                || path_is_absolute(errbuf->b_sfname))) {
4292          if (*dirname == NUL) {
4293            os_dirname(dirname, MAXPATHL);
4294          }
4295          shorten_buf_fname(errbuf, dirname, false);
4296        }
4297        ga_concat(gap, qfp->qf_fname == NULL ? errbuf->b_fname : qfp->qf_fname);
4298      }
4299    }
4300
4301    ga_append(gap, '|');
4302
4303    if (qfp->qf_lnum > 0) {
4304      qf_range_text(gap, qfp);
4305      ga_concat(gap, qf_types(qfp->qf_type, qfp->qf_nr));
4306    } else if (qfp->qf_pattern != NULL) {
4307      qf_fmt_text(gap, qfp->qf_pattern);
4308    }
4309    ga_append(gap, '|');
4310    ga_append(gap, ' ');
4311
4312    // Remove newlines and leading whitespace from the text.
4313    // For an unrecognized line keep the indent, the compiler may
4314    // mark a word with ^^^^.
4315    qf_fmt_text(gap, gap->ga_len > 3 ? skipwhite(qfp->qf_text) : qfp->qf_text);
4316  }
4317
4318  ga_append(gap, NUL);
4319  if (ml_append_buf(buf, lnum, gap->ga_data, gap->ga_len, false) == FAIL) {
4320    return FAIL;
4321  }
4322
4323  return OK;
4324}
4325
4326// Call the 'quickfixtextfunc' function to get the list of lines to display in
4327// the quickfix window for the entries 'start_idx' to 'end_idx'.
4328static list_T *call_qftf_func(qf_list_T *qfl, int qf_winid, int start_idx, int end_idx)
4329{
4330  Callback *cb = &p_qftf;
4331  list_T *qftf_list = NULL;
4332  static bool recursive = false;
4333
4334  if (recursive) {
4335    return NULL;  // this doesn't work properly recursively
4336  }
4337  recursive = true;
4338
4339  // If 'quickfixtextfunc' is set, then use the user-supplied function to get
4340  // the text to display. Use the local value of 'quickfixtextfunc' if it is
4341  // set.
4342  if (qfl->qf_qftf_cb.type != kCallbackNone) {
4343    cb = &qfl->qf_qftf_cb;
4344  }
4345  if (cb->type != kCallbackNone) {
4346    typval_T args[1];
4347    typval_T rettv;
4348
4349    // create the dict argument
4350    dict_T *const dict = tv_dict_alloc_lock(VAR_FIXED);
4351
4352    tv_dict_add_nr(dict, S_LEN("quickfix"), IS_QF_LIST(qfl));
4353    tv_dict_add_nr(dict, S_LEN("winid"), qf_winid);
4354    tv_dict_add_nr(dict, S_LEN("id"), qfl->qf_id);
4355    tv_dict_add_nr(dict, S_LEN("start_idx"), start_idx);
4356    tv_dict_add_nr(dict, S_LEN("end_idx"), end_idx);
4357    dict->dv_refcount++;
4358    args[0].v_type = VAR_DICT;
4359    args[0].vval.v_dict = dict;
4360
4361    textlock++;
4362    if (callback_call(cb, 1, args, &rettv)) {
4363      if (rettv.v_type == VAR_LIST) {
4364        qftf_list = rettv.vval.v_list;
4365        tv_list_ref(qftf_list);
4366      }
4367      tv_clear(&rettv);
4368    }
4369    textlock--;
4370    tv_dict_unref(dict);
4371  }
4372
4373  recursive = false;
4374  return qftf_list;
4375}
4376
4377/// Fill current buffer with quickfix errors, replacing any previous contents.
4378/// curbuf must be the quickfix buffer!
4379/// If "old_last" is not NULL append the items after this one.
4380/// When "old_last" is NULL then "buf" must equal "curbuf"!  Because ml_delete()
4381/// is used and autocommands will be triggered.
4382static void qf_fill_buffer(qf_list_T *qfl, buf_T *buf, qfline_T *old_last, int qf_winid)
4383  FUNC_ATTR_NONNULL_ARG(2)
4384{
4385  const bool old_KeyTyped = KeyTyped;
4386
4387  if (old_last == NULL) {
4388    if (buf != curbuf) {
4389      internal_error("qf_fill_buffer()");
4390      return;
4391    }
4392
4393    // delete all existing lines
4394    //
4395    // Note: we cannot store undo information, because
4396    // qf buffer is usually not allowed to be modified.
4397    //
4398    // So we need to clean up undo information
4399    // otherwise autocommands may invalidate the undo stack
4400    while ((curbuf->b_ml.ml_flags & ML_EMPTY) == 0) {
4401      // If deletion fails, this loop may run forever, so
4402      // signal error and return.
4403      if (ml_delete(1) == FAIL) {
4404        internal_error("qf_fill_buffer()");
4405        return;
4406      }
4407    }
4408
4409    FOR_ALL_TAB_WINDOWS(tp, wp) {
4410      if (wp->w_buffer == curbuf) {
4411        wp->w_skipcol = 0;
4412      }
4413    }
4414
4415    // Remove all undo information
4416    u_clearallandblockfree(curbuf);
4417  }
4418
4419  // Check if there is anything to display
4420  if (qfl != NULL && qfl->qf_start != NULL) {
4421    char dirname[MAXPATHL];
4422
4423    *dirname = NUL;
4424
4425    linenr_T lnum;
4426    qfline_T *qfp;
4427
4428    // Add one line for each error
4429    if (old_last == NULL) {
4430      qfp = qfl->qf_start;
4431      lnum = 0;
4432    } else {
4433      qfp = old_last->qf_next != NULL ? old_last->qf_next : old_last;
4434      lnum = buf->b_ml.ml_line_count;
4435    }
4436
4437    list_T *qftf_list = call_qftf_func(qfl, qf_winid, lnum + 1, qfl->qf_count);
4438    listitem_T *qftf_li = tv_list_first(qftf_list);
4439
4440    int prev_bufnr = -1;
4441    bool invalid_val = false;
4442
4443    while (lnum < qfl->qf_count) {
4444      char *qftf_str = NULL;
4445
4446      // Use the text supplied by the user defined function (if any).
4447      // If the returned value is not string, then ignore the rest
4448      // of the returned values and use the default.
4449      if (qftf_li != NULL && !invalid_val) {
4450        qftf_str = (char *)tv_get_string_chk(TV_LIST_ITEM_TV(qftf_li));
4451        if (qftf_str == NULL) {
4452          invalid_val = true;
4453        }
4454      }
4455
4456      if (qf_buf_add_line(qfl, buf, lnum, qfp, dirname, qftf_str,
4457                          prev_bufnr != qfp->qf_fnum) == FAIL) {
4458        break;
4459      }
4460      prev_bufnr = qfp->qf_fnum;
4461      lnum++;
4462      qfp = qfp->qf_next;
4463      if (qfp == NULL) {
4464        break;
4465      }
4466
4467      if (qftf_li != NULL) {
4468        qftf_li = TV_LIST_ITEM_NEXT(qftf_list, qftf_li);
4469      }
4470    }
4471    if (old_last == NULL) {
4472      // Delete the empty line which is now at the end
4473      ml_delete(lnum + 1);
4474    }
4475
4476    qfga_clear();
4477  }
4478
4479  // Correct cursor position.
4480  check_lnums(true);
4481
4482  if (old_last == NULL) {
4483    // Set the 'filetype' to "qf" each time after filling the buffer.  This
4484    // resembles reading a file into a buffer, it's more logical when using
4485    // autocommands.
4486    curbuf->b_ro_locked++;
4487    set_option_value_give_err(kOptFiletype, STATIC_CSTR_AS_OBJ("qf"), OPT_LOCAL);
4488    curbuf->b_p_ma = false;
4489
4490    curbuf->b_keep_filetype = true;  // don't detect 'filetype'
4491    apply_autocmds(EVENT_BUFREADPOST, "quickfix", NULL, false, curbuf);
4492    apply_autocmds(EVENT_BUFWINENTER, "quickfix", NULL, false, curbuf);
4493    curbuf->b_keep_filetype = false;
4494    curbuf->b_ro_locked--;
4495
4496    // make sure it will be redrawn
4497    redraw_curbuf_later(UPD_NOT_VALID);
4498  }
4499
4500  // Restore KeyTyped, setting 'filetype' may reset it.
4501  KeyTyped = old_KeyTyped;
4502}
4503
4504static void qf_list_changed(qf_list_T *qfl)
4505{
4506  qfl->qf_changedtick++;
4507}
4508
4509/// Return the quickfix/location list number with the given identifier.
4510///
4511/// @returns -1 if list is not found.
4512static int qf_id2nr(const qf_info_T *const qi, const unsigned qfid)
4513{
4514  for (int qf_idx = 0; qf_idx < qi->qf_listcount; qf_idx++) {
4515    if (qi->qf_lists[qf_idx].qf_id == qfid) {
4516      return qf_idx;
4517    }
4518  }
4519  return INVALID_QFIDX;
4520}
4521
4522/// If the current list is not "save_qfid" and we can find the list with that ID
4523/// then make it the current list.
4524/// This is used when autocommands may have changed the current list.
4525/// Returns OK if successfully restored the list. Returns FAIL if the list with
4526/// the specified identifier (save_qfid) is not found in the stack.
4527static int qf_restore_list(qf_info_T *qi, unsigned save_qfid)
4528  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
4529{
4530  if (qf_get_curlist(qi)->qf_id == save_qfid) {
4531    return OK;
4532  }
4533
4534  const int curlist = qf_id2nr(qi, save_qfid);
4535  if (curlist < 0) {
4536    // list is not present
4537    return FAIL;
4538  }
4539  qi->qf_curlist = curlist;
4540  return OK;
4541}
4542
4543// Jump to the first entry if there is one.
4544static void qf_jump_first(qf_info_T *qi, unsigned save_qfid, int forceit)
4545  FUNC_ATTR_NONNULL_ALL
4546{
4547  if (qf_restore_list(qi, save_qfid) == FAIL) {
4548    return;
4549  }
4550
4551  if (!check_can_set_curbuf_forceit(forceit)) {
4552    return;
4553  }
4554
4555  // Autocommands might have cleared the list, check for that
4556  if (!qf_list_empty(qf_get_curlist(qi))) {
4557    qf_jump(qi, 0, 0, forceit);
4558  }
4559}
4560
4561// Return true when using ":vimgrep" for ":grep".
4562int grep_internal(cmdidx_T cmdidx)
4563{
4564  return (cmdidx == CMD_grep
4565          || cmdidx == CMD_lgrep
4566          || cmdidx == CMD_grepadd
4567          || cmdidx == CMD_lgrepadd)
4568         && strcmp("internal", *curbuf->b_p_gp == NUL ? p_gp : curbuf->b_p_gp) == 0;
4569}
4570
4571// Return the make/grep autocmd name.
4572static char *make_get_auname(cmdidx_T cmdidx)
4573  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4574{
4575  switch (cmdidx) {
4576  case CMD_make:
4577    return "make";
4578  case CMD_lmake:
4579    return "lmake";
4580  case CMD_grep:
4581    return "grep";
4582  case CMD_lgrep:
4583    return "lgrep";
4584  case CMD_grepadd:
4585    return "grepadd";
4586  case CMD_lgrepadd:
4587    return "lgrepadd";
4588  default:
4589    return NULL;
4590  }
4591}
4592
4593// Form the complete command line to invoke 'make'/'grep'. Quote the command
4594// using 'shellquote' and append 'shellpipe'. Echo the fully formed command.
4595static char *make_get_fullcmd(const char *makecmd, const char *fname)
4596  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
4597{
4598  size_t len = strlen(p_shq) * 2 + strlen(makecmd) + 1;
4599  if (*p_sp != NUL) {
4600    len += strlen(p_sp) + strlen(fname) + 3;
4601  }
4602  char *const cmd = xmalloc(len);
4603  snprintf(cmd, len, "%s%s%s", p_shq, makecmd, p_shq);
4604
4605  // If 'shellpipe' empty: don't redirect to 'errorfile'.
4606  if (*p_sp != NUL) {
4607    append_redir(cmd, len, p_sp, fname);
4608  }
4609
4610  // Display the fully formed command.  Output a newline if there's something
4611  // else than the :make command that was typed (in which case the cursor is
4612  // in column 0).
4613  if (msg_col == 0) {
4614    msg_didout = false;
4615  }
4616  msg_start();
4617  msg_puts(":!");
4618  msg_outtrans(cmd, 0, false);  // show what we are doing
4619
4620  return cmd;
4621}
4622
4623// Used for ":make", ":lmake", ":grep", ":lgrep", ":grepadd", and ":lgrepadd"
4624void ex_make(exarg_T *eap)
4625{
4626  char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : p_menc;
4627
4628  // Redirect ":grep" to ":vimgrep" if 'grepprg' is "internal".
4629  if (grep_internal(eap->cmdidx)) {
4630    ex_vimgrep(eap);
4631    return;
4632  }
4633
4634  char *const au_name = make_get_auname(eap->cmdidx);
4635  if (au_name != NULL && apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
4636                                        curbuf->b_fname, true, curbuf)) {
4637    if (aborting()) {
4638      return;
4639    }
4640  }
4641
4642  win_T *wp = NULL;
4643  if (is_loclist_cmd(eap->cmdidx)) {
4644    wp = curwin;
4645  }
4646
4647  autowrite_all();
4648  char *fname = get_mef_name();
4649  if (fname == NULL) {
4650    return;
4651  }
4652  os_remove(fname);  // in case it's not unique
4653
4654  char *const cmd = make_get_fullcmd(eap->arg, fname);
4655
4656  do_shell(cmd, 0);
4657
4658  incr_quickfix_busy();
4659
4660  char *errorformat = (eap->cmdidx != CMD_make && eap->cmdidx != CMD_lmake)
4661                      ? *curbuf->b_p_gefm != NUL ? curbuf->b_p_gefm : p_gefm
4662                      : p_efm;
4663
4664  bool newlist = eap->cmdidx != CMD_grepadd && eap->cmdidx != CMD_lgrepadd;
4665
4666  int res = qf_init(wp, fname, errorformat, newlist, qf_cmdtitle(*eap->cmdlinep), enc);
4667
4668  qf_info_T *qi = ql_info;
4669  assert(qi != NULL);
4670  if (wp != NULL) {
4671    qi = GET_LOC_LIST(wp);
4672    if (qi == NULL) {
4673      goto cleanup;
4674    }
4675  }
4676  if (res >= 0) {
4677    qf_list_changed(qf_get_curlist(qi));
4678  }
4679  // Remember the current quickfix list identifier, so that we can
4680  // check for autocommands changing the current quickfix list.
4681  unsigned save_qfid = qf_get_curlist(qi)->qf_id;
4682  if (au_name != NULL) {
4683    apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, true,
4684                   curbuf);
4685  }
4686  if (res > 0 && !eap->forceit && qflist_valid(wp, save_qfid)) {
4687    // display the first error
4688    qf_jump_first(qi, save_qfid, false);
4689  }
4690
4691cleanup:
4692  decr_quickfix_busy();
4693  os_remove(fname);
4694  xfree(fname);
4695  xfree(cmd);
4696}
4697
4698// Return the name for the errorfile, in allocated memory.
4699// Find a new unique name when 'makeef' contains "##".
4700// Returns NULL for error.
4701static char *get_mef_name(void)
4702{
4703  char *name;
4704  static int start = -1;
4705  static int off = 0;
4706
4707  if (*p_mef == NUL) {
4708    name = vim_tempname();
4709    if (name == NULL) {
4710      emsg(_(e_notmp));
4711    }
4712    return name;
4713  }
4714
4715  char *p;
4716
4717  for (p = p_mef; *p; p++) {
4718    if (p[0] == '#' && p[1] == '#') {
4719      break;
4720    }
4721  }
4722
4723  if (*p == NUL) {
4724    return xstrdup(p_mef);
4725  }
4726
4727  // Keep trying until the name doesn't exist yet.
4728  while (true) {
4729    if (start == -1) {
4730      start = (int)os_get_pid();
4731    } else {
4732      off += 19;
4733    }
4734    name = xmalloc(strlen(p_mef) + 30);
4735    STRCPY(name, p_mef);
4736    snprintf(name + (p - p_mef), strlen(name), "%d%d", start, off);
4737    strcat(name, p + 2);
4738    // Don't accept a symbolic link, it's a security risk.
4739    FileInfo file_info;
4740    bool file_or_link_found = os_fileinfo_link(name, &file_info);
4741    if (!file_or_link_found) {
4742      break;
4743    }
4744    xfree(name);
4745  }
4746  return name;
4747}
4748
4749/// Returns the number of entries in the current quickfix/location list.
4750size_t qf_get_size(exarg_T *eap)
4751  FUNC_ATTR_NONNULL_ALL
4752{
4753  qf_info_T *qi;
4754
4755  if ((qi = qf_cmd_get_stack(eap, false)) == NULL) {
4756    return 0;
4757  }
4758  return (size_t)qf_get_curlist(qi)->qf_count;
4759}
4760
4761/// Returns the number of valid entries in the current quickfix/location list.
4762size_t qf_get_valid_size(exarg_T *eap)
4763{
4764  qf_info_T *qi;
4765
4766  if ((qi = qf_cmd_get_stack(eap, false)) == NULL) {
4767    return 0;
4768  }
4769
4770  int prev_fnum = 0;
4771  size_t sz = 0;
4772  qfline_T *qfp;
4773  int i;
4774  assert(qf_get_curlist(qi)->qf_count >= 0);
4775  qf_list_T *qfl = qf_get_curlist(qi);
4776  FOR_ALL_QFL_ITEMS(qfl, qfp, i) {
4777    if (!qfp->qf_valid) {
4778      continue;
4779    }
4780
4781    if (eap->cmdidx == CMD_cdo || eap->cmdidx == CMD_ldo) {
4782      // Count all valid entries.
4783      sz++;
4784    } else if (qfp->qf_fnum > 0 && qfp->qf_fnum != prev_fnum) {
4785      // Count the number of files.
4786      sz++;
4787      prev_fnum = qfp->qf_fnum;
4788    }
4789  }
4790
4791  return sz;
4792}
4793
4794/// Returns the current index of the quickfix/location list.
4795/// Returns 0 if there is an error.
4796size_t qf_get_cur_idx(exarg_T *eap)
4797  FUNC_ATTR_NONNULL_ALL
4798{
4799  qf_info_T *qi;
4800
4801  if ((qi = qf_cmd_get_stack(eap, false)) == NULL) {
4802    return 0;
4803  }
4804
4805  assert(qf_get_curlist(qi)->qf_index >= 0);
4806  return (size_t)qf_get_curlist(qi)->qf_index;
4807}
4808
4809/// Returns the current index in the quickfix/location list,
4810/// counting only valid entries.
4811/// Returns 1 if there are no valid entries.
4812int qf_get_cur_valid_idx(exarg_T *eap)
4813  FUNC_ATTR_NONNULL_ALL
4814{
4815  qf_info_T *qi;
4816
4817  if ((qi = qf_cmd_get_stack(eap, false)) == NULL) {
4818    return 1;
4819  }
4820
4821  qf_list_T *qfl = qf_get_curlist(qi);
4822
4823  // Check if the list has valid errors.
4824  if (!qf_list_has_valid_entries(qfl)) {
4825    return 1;
4826  }
4827
4828  int prev_fnum = 0;
4829  int eidx = 0;
4830  qfline_T *qfp;
4831  size_t i;
4832  assert(qfl->qf_index >= 0);
4833  for (i = 1, qfp = qfl->qf_start;
4834       i <= (size_t)qfl->qf_index && qfp != NULL;
4835       i++, qfp = qfp->qf_next) {
4836    if (!qfp->qf_valid) {
4837      continue;
4838    }
4839
4840    if (eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo) {
4841      if (qfp->qf_fnum > 0 && qfp->qf_fnum != prev_fnum) {
4842        // Count the number of files.
4843        eidx++;
4844        prev_fnum = qfp->qf_fnum;
4845      }
4846    } else {
4847      eidx++;
4848    }
4849  }
4850
4851  return eidx != 0 ? eidx : 1;
4852}
4853
4854/// Get the 'n'th valid error entry in the quickfix or location list.
4855///
4856/// Used by :cdo, :ldo, :cfdo and :lfdo commands.
4857/// For :cdo and :ldo, returns the 'n'th valid error entry.
4858/// For :cfdo and :lfdo, returns the 'n'th valid file entry.
4859static size_t qf_get_nth_valid_entry(qf_list_T *qfl, size_t n, bool fdo)
4860  FUNC_ATTR_NONNULL_ALL
4861{
4862  // Check if the list has valid errors.
4863  if (!qf_list_has_valid_entries(qfl)) {
4864    return 1;
4865  }
4866
4867  int prev_fnum = 0;
4868  size_t eidx = 0;
4869  int i;
4870  qfline_T *qfp;
4871  assert(qfl->qf_count >= 0);
4872  FOR_ALL_QFL_ITEMS(qfl, qfp, i) {
4873    if (qfp->qf_valid) {
4874      if (fdo) {
4875        if (qfp->qf_fnum > 0 && qfp->qf_fnum != prev_fnum) {
4876          // Count the number of files.
4877          eidx++;
4878          prev_fnum = qfp->qf_fnum;
4879        }
4880      } else {
4881        eidx++;
4882      }
4883    }
4884
4885    if (eidx == n) {
4886      break;
4887    }
4888  }
4889
4890  return i <= qfl->qf_count ? (size_t)i : 1;
4891}
4892
4893/// ":cc", ":crewind", ":cfirst" and ":clast".
4894/// ":ll", ":lrewind", ":lfirst" and ":llast".
4895/// ":cdo", ":ldo", ":cfdo" and ":lfdo".
4896void ex_cc(exarg_T *eap)
4897{
4898  qf_info_T *qi;
4899
4900  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
4901    return;
4902  }
4903
4904  int errornr;
4905  if (eap->addr_count > 0) {
4906    errornr = (int)eap->line2;
4907  } else {
4908    switch (eap->cmdidx) {
4909    case CMD_cc:
4910    case CMD_ll:
4911      errornr = 0;
4912      break;
4913    case CMD_crewind:
4914    case CMD_lrewind:
4915    case CMD_cfirst:
4916    case CMD_lfirst:
4917      errornr = 1;
4918      break;
4919    default:
4920      errornr = 32767;
4921      break;
4922    }
4923  }
4924
4925  // For cdo and ldo commands, jump to the nth valid error.
4926  // For cfdo and lfdo commands, jump to the nth valid file entry.
4927  if (eap->cmdidx == CMD_cdo || eap->cmdidx == CMD_ldo
4928      || eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo) {
4929    size_t n;
4930    if (eap->addr_count > 0) {
4931      assert(eap->line1 >= 0);
4932      n = (size_t)eap->line1;
4933    } else {
4934      n = 1;
4935    }
4936    size_t valid_entry = qf_get_nth_valid_entry(qf_get_curlist(qi), n,
4937                                                eap->cmdidx == CMD_cfdo || eap->cmdidx == CMD_lfdo);
4938    assert(valid_entry <= INT_MAX);
4939    errornr = (int)valid_entry;
4940  }
4941
4942  qf_jump(qi, 0, errornr, eap->forceit);
4943}
4944
4945/// ":cnext", ":cnfile", ":cNext" and ":cprevious".
4946/// ":lnext", ":lNext", ":lprevious", ":lnfile", ":lNfile" and ":lpfile".
4947/// ":cdo", ":ldo", ":cfdo" and ":lfdo".
4948void ex_cnext(exarg_T *eap)
4949{
4950  qf_info_T *qi;
4951
4952  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
4953    return;
4954  }
4955
4956  int errornr;
4957  if (eap->addr_count > 0
4958      && (eap->cmdidx != CMD_cdo && eap->cmdidx != CMD_ldo
4959          && eap->cmdidx != CMD_cfdo && eap->cmdidx != CMD_lfdo)) {
4960    errornr = (int)eap->line2;
4961  } else {
4962    errornr = 1;
4963  }
4964
4965  // Depending on the command jump to either next or previous entry/file.
4966  Direction dir;
4967  switch (eap->cmdidx) {
4968  case CMD_cprevious:
4969  case CMD_lprevious:
4970  case CMD_cNext:
4971  case CMD_lNext:
4972    dir = BACKWARD;
4973    break;
4974  case CMD_cnfile:
4975  case CMD_lnfile:
4976  case CMD_cfdo:
4977  case CMD_lfdo:
4978    dir = FORWARD_FILE;
4979    break;
4980  case CMD_cpfile:
4981  case CMD_lpfile:
4982  case CMD_cNfile:
4983  case CMD_lNfile:
4984    dir = BACKWARD_FILE;
4985    break;
4986  case CMD_cnext:
4987  case CMD_lnext:
4988  case CMD_cdo:
4989  case CMD_ldo:
4990  default:
4991    dir = FORWARD;
4992    break;
4993  }
4994
4995  qf_jump(qi, dir, errornr, eap->forceit);
4996}
4997
4998/// Find the first entry in the quickfix list 'qfl' from buffer 'bnr'.
4999/// The index of the entry is stored in 'errornr'.
5000/// Returns NULL if an entry is not found.
5001static qfline_T *qf_find_first_entry_in_buf(qf_list_T *qfl, int bnr, int *errornr)
5002{
5003  qfline_T *qfp = NULL;
5004  int idx = 0;
5005
5006  // Find the first entry in this file
5007  FOR_ALL_QFL_ITEMS(qfl, qfp, idx) {
5008    if (qfp->qf_fnum == bnr) {
5009      break;
5010    }
5011  }
5012
5013  *errornr = idx;
5014  return qfp;
5015}
5016
5017/// Find the first quickfix entry on the same line as 'entry'. Updates 'errornr'
5018/// with the error number for the first entry. Assumes the entries are sorted in
5019/// the quickfix list by line number.
5020static qfline_T *qf_find_first_entry_on_line(qfline_T *entry, int *errornr)
5021{
5022  while (!got_int
5023         && entry->qf_prev != NULL
5024         && entry->qf_fnum == entry->qf_prev->qf_fnum
5025         && entry->qf_lnum == entry->qf_prev->qf_lnum) {
5026    entry = entry->qf_prev;
5027    (*errornr)--;
5028  }
5029
5030  return entry;
5031}
5032
5033/// Find the last quickfix entry on the same line as 'entry'. Updates 'errornr'
5034/// with the error number for the last entry. Assumes the entries are sorted in
5035/// the quickfix list by line number.
5036static qfline_T *qf_find_last_entry_on_line(qfline_T *entry, int *errornr)
5037{
5038  while (!got_int
5039         && entry->qf_next != NULL
5040         && entry->qf_fnum == entry->qf_next->qf_fnum
5041         && entry->qf_lnum == entry->qf_next->qf_lnum) {
5042    entry = entry->qf_next;
5043    (*errornr)++;
5044  }
5045
5046  return entry;
5047}
5048
5049// Returns true if the specified quickfix entry is
5050// after the given line (linewise is true)
5051// or after the line and column.
5052static bool qf_entry_after_pos(const qfline_T *qfp, const pos_T *pos, bool linewise)
5053  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5054{
5055  if (linewise) {
5056    return qfp->qf_lnum > pos->lnum;
5057  }
5058  return qfp->qf_lnum > pos->lnum
5059         || (qfp->qf_lnum == pos->lnum && qfp->qf_col > pos->col);
5060}
5061
5062// Returns true if the specified quickfix entry is
5063// before the given line (linewise is true)
5064// or before the line and column.
5065static bool qf_entry_before_pos(const qfline_T *qfp, const pos_T *pos, bool linewise)
5066  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5067{
5068  if (linewise) {
5069    return qfp->qf_lnum < pos->lnum;
5070  }
5071  return qfp->qf_lnum < pos->lnum
5072         || (qfp->qf_lnum == pos->lnum && qfp->qf_col < pos->col);
5073}
5074
5075// Returns true if the specified quickfix entry is
5076// on or after the given line (linewise is true)
5077// or on or after the line and column.
5078static bool qf_entry_on_or_after_pos(const qfline_T *qfp, const pos_T *pos, bool linewise)
5079  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5080{
5081  if (linewise) {
5082    return qfp->qf_lnum >= pos->lnum;
5083  }
5084  return qfp->qf_lnum > pos->lnum
5085         || (qfp->qf_lnum == pos->lnum && qfp->qf_col >= pos->col);
5086}
5087
5088// Returns true if the specified quickfix entry is
5089// on or before the given line (linewise is true)
5090// or on or before the line and column.
5091static bool qf_entry_on_or_before_pos(const qfline_T *qfp, const pos_T *pos, bool linewise)
5092  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5093{
5094  if (linewise) {
5095    return qfp->qf_lnum <= pos->lnum;
5096  }
5097  return qfp->qf_lnum < pos->lnum
5098         || (qfp->qf_lnum == pos->lnum && qfp->qf_col <= pos->col);
5099}
5100
5101/// Find the first quickfix entry after position 'pos' in buffer 'bnr'.
5102/// If 'linewise' is true, returns the entry after the specified line and treats
5103/// multiple entries on a single line as one. Otherwise returns the entry after
5104/// the specified line and column.
5105/// 'qfp' points to the very first entry in the buffer and 'errornr' is the
5106/// index of the very first entry in the quickfix list.
5107/// Returns NULL if an entry is not found after 'pos'.
5108static qfline_T *qf_find_entry_after_pos(int bnr, const pos_T *pos, bool linewise, qfline_T *qfp,
5109                                         int *errornr)
5110  FUNC_ATTR_NONNULL_ALL
5111{
5112  if (qf_entry_after_pos(qfp, pos, linewise)) {
5113    // First entry is after position 'pos'
5114    return qfp;
5115  }
5116
5117  // Find the entry just before or at the position 'pos'
5118  while (qfp->qf_next != NULL
5119         && qfp->qf_next->qf_fnum == bnr
5120         && qf_entry_on_or_before_pos(qfp->qf_next, pos, linewise)) {
5121    qfp = qfp->qf_next;
5122    (*errornr)++;
5123  }
5124
5125  if (qfp->qf_next == NULL || qfp->qf_next->qf_fnum != bnr) {
5126    // No entries found after position 'pos'
5127    return NULL;
5128  }
5129
5130  // Use the entry just after position 'pos'
5131  qfp = qfp->qf_next;
5132  (*errornr)++;
5133
5134  return qfp;
5135}
5136
5137/// Find the first quickfix entry before position 'pos' in buffer 'bnr'.
5138/// If 'linewise' is true, returns the entry before the specified line and
5139/// treats multiple entries on a single line as one. Otherwise returns the entry
5140/// before the specified line and column.
5141/// 'qfp' points to the very first entry in the buffer and 'errornr' is the
5142/// index of the very first entry in the quickfix list.
5143/// Returns NULL if an entry is not found before 'pos'.
5144static qfline_T *qf_find_entry_before_pos(int bnr, const pos_T *pos, bool linewise, qfline_T *qfp,
5145                                          int *errornr)
5146  FUNC_ATTR_NONNULL_ALL
5147{
5148  // Find the entry just before the position 'pos'
5149  while (qfp->qf_next != NULL
5150         && qfp->qf_next->qf_fnum == bnr
5151         && qf_entry_before_pos(qfp->qf_next, pos, linewise)) {
5152    qfp = qfp->qf_next;
5153    (*errornr)++;
5154  }
5155
5156  if (qf_entry_on_or_after_pos(qfp, pos, linewise)) {
5157    return NULL;
5158  }
5159
5160  if (linewise) {
5161    // If multiple entries are on the same line, then use the first entry
5162    qfp = qf_find_first_entry_on_line(qfp, errornr);
5163  }
5164
5165  return qfp;
5166}
5167
5168/// Find a quickfix entry in 'qfl' closest to position 'pos' in buffer 'bnr' in
5169/// the direction 'dir'.
5170static qfline_T *qf_find_closest_entry(qf_list_T *qfl, int bnr, const pos_T *pos, Direction dir,
5171                                       bool linewise, int *errornr)
5172  FUNC_ATTR_NONNULL_ALL
5173{
5174  *errornr = 0;
5175
5176  // Find the first entry in this file
5177  qfline_T *qfp = qf_find_first_entry_in_buf(qfl, bnr, errornr);
5178  if (qfp == NULL) {
5179    return NULL;  // no entry in this file
5180  }
5181
5182  if (dir == FORWARD) {
5183    qfp = qf_find_entry_after_pos(bnr, pos, linewise, qfp, errornr);
5184  } else {
5185    qfp = qf_find_entry_before_pos(bnr, pos, linewise, qfp, errornr);
5186  }
5187
5188  return qfp;
5189}
5190
5191/// Get the nth quickfix entry below the specified entry.  Searches forward in
5192/// the list. If linewise is true, then treat multiple entries on a single line
5193/// as one.
5194static void qf_get_nth_below_entry(qfline_T *entry_arg, linenr_T n, bool linewise, int *errornr)
5195  FUNC_ATTR_NONNULL_ALL
5196{
5197  qfline_T *entry = entry_arg;
5198
5199  while (n-- > 0 && !got_int) {
5200    int first_errornr = *errornr;
5201
5202    if (linewise) {
5203      // Treat all the entries on the same line in this file as one
5204      entry = qf_find_last_entry_on_line(entry, errornr);
5205    }
5206
5207    if (entry->qf_next == NULL
5208        || entry->qf_next->qf_fnum != entry->qf_fnum) {
5209      if (linewise) {
5210        *errornr = first_errornr;
5211      }
5212      break;
5213    }
5214
5215    entry = entry->qf_next;
5216    (*errornr)++;
5217  }
5218}
5219
5220/// Get the nth quickfix entry above the specified entry.  Searches backwards in
5221/// the list. If linewise is true, then treat multiple entries on a single line
5222/// as one.
5223static void qf_get_nth_above_entry(qfline_T *entry, linenr_T n, bool linewise, int *errornr)
5224  FUNC_ATTR_NONNULL_ALL
5225{
5226  while (n-- > 0 && !got_int) {
5227    if (entry->qf_prev == NULL
5228        || entry->qf_prev->qf_fnum != entry->qf_fnum) {
5229      break;
5230    }
5231
5232    entry = entry->qf_prev;
5233    (*errornr)--;
5234
5235    if (linewise) {
5236      entry = qf_find_first_entry_on_line(entry, errornr);
5237    }
5238  }
5239}
5240
5241/// Find the n'th quickfix entry adjacent to position 'pos' in buffer 'bnr' in
5242/// the specified direction.  Returns the error number in the quickfix list or 0
5243/// if an entry is not found.
5244static int qf_find_nth_adj_entry(qf_list_T *qfl, int bnr, pos_T *pos, linenr_T n, Direction dir,
5245                                 bool linewise)
5246  FUNC_ATTR_NONNULL_ALL
5247{
5248  int errornr;
5249
5250  // Find an entry closest to the specified position
5251  qfline_T *const adj_entry = qf_find_closest_entry(qfl, bnr, pos, dir,
5252                                                    linewise, &errornr);
5253  if (adj_entry == NULL) {
5254    return 0;
5255  }
5256
5257  if (--n > 0) {
5258    // Go to the n'th entry in the current buffer
5259    if (dir == FORWARD) {
5260      qf_get_nth_below_entry(adj_entry, n, linewise, &errornr);
5261    } else {
5262      qf_get_nth_above_entry(adj_entry, n, linewise, &errornr);
5263    }
5264  }
5265
5266  return errornr;
5267}
5268
5269/// Jump to a quickfix entry in the current file nearest to the current line or
5270/// current line/col.
5271/// ":cabove", ":cbelow", ":labove", ":lbelow", ":cafter", ":cbefore",
5272/// ":lafter" and ":lbefore" commands
5273void ex_cbelow(exarg_T *eap)
5274{
5275  if (eap->addr_count > 0 && eap->line2 <= 0) {
5276    emsg(_(e_invrange));
5277    return;
5278  }
5279
5280  // Check whether the current buffer has any quickfix entries
5281  int buf_has_flag = (eap->cmdidx == CMD_cabove
5282                      || eap->cmdidx == CMD_cbelow
5283                      || eap->cmdidx == CMD_cbefore
5284                      || eap->cmdidx == CMD_cafter) ? BUF_HAS_QF_ENTRY : BUF_HAS_LL_ENTRY;
5285
5286  if (!(curbuf->b_has_qf_entry & buf_has_flag)) {
5287    emsg(_(e_no_errors));
5288    return;
5289  }
5290
5291  qf_info_T *qi;
5292  if ((qi = qf_cmd_get_stack(eap, true)) == NULL) {
5293    return;
5294  }
5295
5296  qf_list_T *qfl = qf_get_curlist(qi);
5297  // check if the list has valid errors
5298  if (!qf_list_has_valid_entries(qfl)) {
5299    emsg(_(e_no_errors));
5300    return;
5301  }
5302
5303  // Forward motion commands
5304  int dir = (eap->cmdidx == CMD_cbelow
5305             || eap->cmdidx == CMD_lbelow
5306             || eap->cmdidx == CMD_cafter
5307             || eap->cmdidx == CMD_lafter) ? FORWARD : BACKWARD;
5308
5309  pos_T pos = curwin->w_cursor;
5310  // A quickfix entry column number is 1 based whereas cursor column
5311  // number is 0 based. Adjust the column number.
5312  pos.col++;
5313  const int errornr = qf_find_nth_adj_entry(qfl,
5314                                            curbuf->b_fnum,
5315                                            &pos,
5316                                            eap->addr_count > 0 ? eap->line2 : 0,
5317                                            dir,
5318                                            eap->cmdidx == CMD_cbelow
5319                                            || eap->cmdidx == CMD_lbelow
5320                                            || eap->cmdidx == CMD_cabove
5321                                            || eap->cmdidx == CMD_labove);
5322
5323  if (errornr > 0) {
5324    qf_jump(qi, 0, errornr, false);
5325  } else {
5326    emsg(_(e_no_more_items));
5327  }
5328}
5329
5330/// Return the autocmd name for the :cfile Ex commands
5331static char *cfile_get_auname(cmdidx_T cmdidx)
5332{
5333  switch (cmdidx) {
5334  case CMD_cfile:
5335    return "cfile";
5336  case CMD_cgetfile:
5337    return "cgetfile";
5338  case CMD_caddfile:
5339    return "caddfile";
5340  case CMD_lfile:
5341    return "lfile";
5342  case CMD_lgetfile:
5343    return "lgetfile";
5344  case CMD_laddfile:
5345    return "laddfile";
5346  default:
5347    return NULL;
5348  }
5349}
5350
5351// ":cfile"/":cgetfile"/":caddfile" commands.
5352// ":lfile"/":lgetfile"/":laddfile" commands.
5353void ex_cfile(exarg_T *eap)
5354{
5355  win_T *wp = NULL;
5356  qf_info_T *qi = ql_info;
5357  assert(qi != NULL);
5358  char *au_name = NULL;
5359
5360  au_name = cfile_get_auname(eap->cmdidx);
5361  if (au_name != NULL
5362      && apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name, NULL, false, curbuf)) {
5363    if (aborting()) {
5364      return;
5365    }
5366  }
5367  if (*eap->arg != NUL) {
5368    set_option_direct(kOptErrorfile, CSTR_AS_OBJ(eap->arg), 0, 0);
5369  }
5370
5371  char *enc = (*curbuf->b_p_menc != NUL) ? curbuf->b_p_menc : p_menc;
5372
5373  if (is_loclist_cmd(eap->cmdidx)) {
5374    wp = curwin;
5375  }
5376
5377  incr_quickfix_busy();
5378
5379  // This function is used by the :cfile, :cgetfile and :caddfile
5380  // commands.
5381  // :cfile always creates a new quickfix list and may jump to the
5382  // first error.
5383  // :cgetfile creates a new quickfix list but doesn't jump to the
5384  // first error.
5385  // :caddfile adds to an existing quickfix list. If there is no
5386  // quickfix list then a new list is created.
5387  int res = qf_init(wp, p_ef, p_efm, (eap->cmdidx != CMD_caddfile
5388                                      && eap->cmdidx != CMD_laddfile),
5389                    qf_cmdtitle(*eap->cmdlinep), enc);
5390  if (wp != NULL) {
5391    qi = GET_LOC_LIST(wp);
5392    if (qi == NULL) {
5393      decr_quickfix_busy();
5394      return;
5395    }
5396  }
5397  if (res >= 0) {
5398    qf_list_changed(qf_get_curlist(qi));
5399  }
5400  unsigned save_qfid = qf_get_curlist(qi)->qf_id;
5401  if (au_name != NULL) {
5402    apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, NULL, false, curbuf);
5403  }
5404  // Jump to the first error for a new list and if autocmds didn't free the
5405  // list.
5406  if (res > 0 && (eap->cmdidx == CMD_cfile || eap->cmdidx == CMD_lfile)
5407      && qflist_valid(wp, save_qfid)) {
5408    // display the first error
5409    qf_jump_first(qi, save_qfid, eap->forceit);
5410  }
5411
5412  decr_quickfix_busy();
5413}
5414
5415/// Return the vimgrep autocmd name.
5416static char *vgr_get_auname(cmdidx_T cmdidx)
5417{
5418  switch (cmdidx) {
5419  case CMD_vimgrep:
5420    return "vimgrep";
5421  case CMD_lvimgrep:
5422    return "lvimgrep";
5423  case CMD_vimgrepadd:
5424    return "vimgrepadd";
5425  case CMD_lvimgrepadd:
5426    return "lvimgrepadd";
5427  case CMD_grep:
5428    return "grep";
5429  case CMD_lgrep:
5430    return "lgrep";
5431  case CMD_grepadd:
5432    return "grepadd";
5433  case CMD_lgrepadd:
5434    return "lgrepadd";
5435  default:
5436    return NULL;
5437  }
5438}
5439
5440/// Initialize the regmatch used by vimgrep for pattern "s".
5441static void vgr_init_regmatch(regmmatch_T *regmatch, char *s)
5442{
5443  // Get the search pattern: either white-separated or enclosed in //.
5444  regmatch->regprog = NULL;
5445
5446  if (s == NULL || *s == NUL) {
5447    // Pattern is empty, use last search pattern.
5448    if (last_search_pat() == NULL) {
5449      emsg(_(e_noprevre));
5450      return;
5451    }
5452    regmatch->regprog = vim_regcomp(last_search_pat(), RE_MAGIC);
5453  } else {
5454    regmatch->regprog = vim_regcomp(s, RE_MAGIC);
5455  }
5456
5457  regmatch->rmm_ic = p_ic;
5458  regmatch->rmm_maxcol = 0;
5459}
5460
5461/// Display a file name when vimgrep is running.
5462static void vgr_display_fname(char *fname)
5463{
5464  msg_start();
5465  char *p = msg_strtrunc(fname, true);
5466  if (p == NULL) {
5467    msg_outtrans(fname, 0, false);
5468  } else {
5469    msg_outtrans(p, 0, false);
5470    xfree(p);
5471  }
5472  msg_clr_eos();
5473  msg_didout = false;  // overwrite this message
5474  msg_nowait = true;   // don't wait for this message
5475  msg_col = 0;
5476  ui_flush();
5477}
5478
5479/// Load a dummy buffer to search for a pattern using vimgrep.
5480static buf_T *vgr_load_dummy_buf(char *fname, char *dirname_start, char *dirname_now)
5481{
5482  // Don't do Filetype autocommands to avoid loading syntax and
5483  // indent scripts, a great speed improvement.
5484  char *save_ei = au_event_disable(",Filetype");
5485
5486  OptInt save_mls = p_mls;
5487  p_mls = 0;
5488
5489  // Load file into a buffer, so that 'fileencoding' is detected,
5490  // autocommands applied, etc.
5491  buf_T *buf = load_dummy_buffer(fname, dirname_start, dirname_now);
5492
5493  p_mls = save_mls;
5494  au_event_restore(save_ei);
5495
5496  return buf;
5497}
5498
5499/// Check whether a quickfix/location list is valid. Autocmds may remove or
5500/// change a quickfix list when vimgrep is running. If the list is not found,
5501/// create a new list.
5502static bool vgr_qflist_valid(win_T *wp, qf_info_T *qi, unsigned qfid, char *title)
5503{
5504  // Verify that the quickfix/location list was not freed by an autocmd
5505  if (!qflist_valid(wp, qfid)) {
5506    if (wp != NULL) {
5507      // An autocmd has freed the location list
5508      emsg(_(e_current_location_list_was_changed));
5509      return false;
5510    }
5511    // Quickfix list is not found, create a new one.
5512    qf_new_list(qi, title);
5513    return true;
5514  }
5515  if (qf_restore_list(qi, qfid) == FAIL) {
5516    return false;
5517  }
5518
5519  return true;
5520}
5521
5522/// Search for a pattern in all the lines in a buffer and add the matching lines
5523/// to a quickfix list.
5524static bool vgr_match_buflines(qf_list_T *qfl, char *fname, buf_T *buf, char *spat,
5525                               regmmatch_T *regmatch, int *tomatch, int duplicate_name, int flags)
5526  FUNC_ATTR_NONNULL_ARG(1, 3, 4, 5, 6)
5527{
5528  bool found_match = false;
5529  size_t pat_len = strlen(spat);
5530  pat_len = MIN(pat_len, FUZZY_MATCH_MAX_LEN);
5531
5532  for (linenr_T lnum = 1; lnum <= buf->b_ml.ml_line_count && *tomatch > 0; lnum++) {
5533    colnr_T col = 0;
5534    if (!(flags & VGR_FUZZY)) {
5535      // Regular expression match
5536      while (vim_regexec_multi(regmatch, curwin, buf, lnum, col, NULL, NULL) > 0) {
5537        // Pass the buffer number so that it gets used even for a
5538        // dummy buffer, unless duplicate_name is set, then the
5539        // buffer will be wiped out below.
5540        if (qf_add_entry(qfl,
5541                         NULL,   // dir
5542                         fname,
5543                         NULL,
5544                         duplicate_name ? 0 : buf->b_fnum,
5545                         ml_get_buf(buf, regmatch->startpos[0].lnum + lnum),
5546                         regmatch->startpos[0].lnum + lnum,
5547                         regmatch->endpos[0].lnum + lnum,
5548                         regmatch->startpos[0].col + 1,
5549                         regmatch->endpos[0].col + 1,
5550                         false,  // vis_col
5551                         NULL,   // search pattern
5552                         0,      // nr
5553                         0,      // type
5554                         NULL,   // user_data
5555                         true)   // valid
5556            == QF_FAIL) {
5557          got_int = true;
5558          break;
5559        }
5560        found_match = true;
5561        if (--*tomatch == 0) {
5562          break;
5563        }
5564        if ((flags & VGR_GLOBAL) == 0 || regmatch->endpos[0].lnum > 0) {
5565          break;
5566        }
5567        col = regmatch->endpos[0].col + (col == regmatch->endpos[0].col);
5568        if (col > ml_get_buf_len(buf, lnum)) {
5569          break;
5570        }
5571      }
5572    } else {
5573      char *const str = ml_get_buf(buf, lnum);
5574      const colnr_T linelen = ml_get_buf_len(buf, lnum);
5575      int score;
5576      uint32_t matches[FUZZY_MATCH_MAX_LEN];
5577      const size_t sz = sizeof(matches) / sizeof(matches[0]);
5578
5579      // Fuzzy string match
5580      CLEAR_FIELD(matches);
5581      while (fuzzy_match(str + col, spat, false, &score, matches, (int)sz) > 0) {
5582        // Pass the buffer number so that it gets used even for a
5583        // dummy buffer, unless duplicate_name is set, then the
5584        // buffer will be wiped out below.
5585        if (qf_add_entry(qfl,
5586                         NULL,   // dir
5587                         fname,
5588                         NULL,
5589                         duplicate_name ? 0 : buf->b_fnum,
5590                         str,
5591                         lnum,
5592                         0,
5593                         (colnr_T)matches[0] + col + 1,
5594                         0,
5595                         false,  // vis_col
5596                         NULL,   // search pattern
5597                         0,      // nr
5598                         0,      // type
5599                         NULL,   // user_data
5600                         true)   // valid
5601            == QF_FAIL) {
5602          got_int = true;
5603          break;
5604        }
5605        found_match = true;
5606        if (--*tomatch == 0) {
5607          break;
5608        }
5609        if ((flags & VGR_GLOBAL) == 0) {
5610          break;
5611        }
5612        col = (colnr_T)matches[pat_len - 1] + col + 1;
5613        if (col > linelen) {
5614          break;
5615        }
5616      }
5617    }
5618    line_breakcheck();
5619    if (got_int) {
5620      break;
5621    }
5622  }
5623
5624  return found_match;
5625}
5626
5627/// Jump to the first match and update the directory.
5628static void vgr_jump_to_match(qf_info_T *qi, int forceit, bool *redraw_for_dummy,
5629                              buf_T *first_match_buf, char *target_dir)  // NOLINT(readability-non-const-parameter)
5630{
5631  buf_T *buf = curbuf;
5632  qf_jump(qi, 0, 0, forceit);
5633  if (buf != curbuf) {
5634    // If we jumped to another buffer redrawing will already be
5635    // taken care of.
5636    *redraw_for_dummy = false;
5637  }
5638
5639  // Jump to the directory used after loading the buffer.
5640  if (curbuf == first_match_buf && target_dir != NULL) {
5641    exarg_T ea = {
5642      .arg = target_dir,
5643      .cmdidx = CMD_lcd,
5644    };
5645    ex_cd(&ea);
5646  }
5647}
5648
5649// Return true if "buf" had an existing swap file, the current swap file does
5650// not end in ".swp".
5651static bool existing_swapfile(const buf_T *buf)
5652  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5653{
5654  if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL) {
5655    const char *const fname = buf->b_ml.ml_mfp->mf_fname;
5656    const size_t len = strlen(fname);
5657
5658    return fname[len - 1] != 'p' || fname[len - 2] != 'w';
5659  }
5660  return false;
5661}
5662
5663/// Process :vimgrep command arguments. The command syntax is:
5664///
5665/// :{count}vimgrep /{pattern}/[g][j] {file} ...
5666static int vgr_process_args(exarg_T *eap, vgr_args_T *args)
5667{
5668  CLEAR_POINTER(args);
5669
5670  args->regmatch.regprog = NULL;
5671  args->qf_title = xstrdup(qf_cmdtitle(*eap->cmdlinep));
5672  args->tomatch = eap->addr_count > 0 ? eap->line2 : MAXLNUM;
5673
5674  // Get the search pattern: either white-separated or enclosed in //
5675  char *p = skip_vimgrep_pat(eap->arg, &args->spat, &args->flags);
5676  if (p == NULL) {
5677    emsg(_(e_invalpat));
5678    return FAIL;
5679  }
5680
5681  vgr_init_regmatch(&args->regmatch, args->spat);
5682  if (args->regmatch.regprog == NULL) {
5683    return FAIL;
5684  }
5685
5686  p = skipwhite(p);
5687  if (*p == NUL) {
5688    emsg(_("E683: File name missing or invalid pattern"));
5689    return FAIL;
5690  }
5691
5692  // Parse the list of arguments, wildcards have already been expanded.
5693  if (get_arglist_exp(p, &args->fcount, &args->fnames, true) == FAIL
5694      || args->fcount == 0) {
5695    emsg(_(e_nomatch));
5696    return FAIL;
5697  }
5698
5699  return OK;
5700}
5701
5702/// Search for a pattern in a list of files and populate the quickfix list with
5703/// the matches.
5704static int vgr_process_files(win_T *wp, qf_info_T *qi, vgr_args_T *cmd_args, bool *redraw_for_dummy,
5705                             buf_T **first_match_buf, char **target_dir)
5706{
5707  int status = FAIL;
5708  unsigned save_qfid = qf_get_curlist(qi)->qf_id;
5709  bool duplicate_name = false;
5710
5711  char *dirname_start = xmalloc(MAXPATHL);
5712  char *dirname_now = xmalloc(MAXPATHL);
5713
5714  // Remember the current directory, because a BufRead autocommand that does
5715  // ":lcd %:p:h" changes the meaning of short path names.
5716  os_dirname(dirname_start, MAXPATHL);
5717
5718  time_t seconds = 0;
5719  for (int fi = 0; fi < cmd_args->fcount && !got_int && cmd_args->tomatch > 0; fi++) {
5720    char *fname = path_try_shorten_fname(cmd_args->fnames[fi]);
5721    if (time(NULL) > seconds) {
5722      // Display the file name every second or so, show the user we are
5723      // working on it.
5724      seconds = time(NULL);
5725      vgr_display_fname(fname);
5726    }
5727
5728    buf_T *buf = buflist_findname_exp(cmd_args->fnames[fi]);
5729    bool using_dummy;
5730    if (buf == NULL || buf->b_ml.ml_mfp == NULL) {
5731      // Remember that a buffer with this name already exists.
5732      duplicate_name = (buf != NULL);
5733      using_dummy = true;
5734      *redraw_for_dummy = true;
5735      buf = vgr_load_dummy_buf(fname, dirname_start, dirname_now);
5736    } else {
5737      // Use existing, loaded buffer.
5738      using_dummy = false;
5739    }
5740
5741    // Check whether the quickfix list is still valid. When loading a
5742    // buffer above, autocommands might have changed the quickfix list.
5743    if (!vgr_qflist_valid(wp, qi, save_qfid, cmd_args->qf_title)) {
5744      goto theend;
5745    }
5746
5747    save_qfid = qf_get_curlist(qi)->qf_id;
5748
5749    if (buf == NULL) {
5750      if (!got_int) {
5751        smsg(0, _("Cannot open file \"%s\""), fname);
5752      }
5753    } else {
5754      // Try for a match in all lines of the buffer.
5755      // For ":1vimgrep" look for first match only.
5756      bool found_match = vgr_match_buflines(qf_get_curlist(qi),
5757                                            fname,
5758                                            buf,
5759                                            cmd_args->spat,
5760                                            &cmd_args->regmatch,
5761                                            &cmd_args->tomatch,
5762                                            duplicate_name,
5763                                            cmd_args->flags);
5764
5765      if (using_dummy) {
5766        if (found_match && *first_match_buf == NULL) {
5767          *first_match_buf = buf;
5768        }
5769        if (duplicate_name) {
5770          // Never keep a dummy buffer if there is another buffer
5771          // with the same name.
5772          wipe_dummy_buffer(buf, dirname_start);
5773          buf = NULL;
5774        } else if ((cmdmod.cmod_flags & CMOD_HIDE) == 0
5775                   || buf->b_p_bh[0] == 'u'             // "unload"
5776                   || buf->b_p_bh[0] == 'w'             // "wipe"
5777                   || buf->b_p_bh[0] == 'd') {          // "delete"
5778          // When no match was found we don't need to remember the
5779          // buffer, wipe it out.  If there was a match and it
5780          // wasn't the first one or we won't jump there: only
5781          // unload the buffer.
5782          // Ignore 'hidden' here, because it may lead to having too
5783          // many swap files.
5784          if (!found_match) {
5785            wipe_dummy_buffer(buf, dirname_start);
5786            buf = NULL;
5787          } else if (buf != *first_match_buf
5788                     || (cmd_args->flags & VGR_NOJUMP)
5789                     || existing_swapfile(buf)) {
5790            unload_dummy_buffer(buf, dirname_start);
5791            // Keeping the buffer, remove the dummy flag.
5792            buf->b_flags &= ~BF_DUMMY;
5793            buf = NULL;
5794          }
5795        }
5796
5797        if (buf != NULL) {
5798          // Keeping the buffer, remove the dummy flag.
5799          buf->b_flags &= ~BF_DUMMY;
5800
5801          // If the buffer is still loaded we need to use the
5802          // directory we jumped to below.
5803          if (buf == *first_match_buf
5804              && *target_dir == NULL
5805              && strcmp(dirname_start, dirname_now) != 0) {
5806            *target_dir = xstrdup(dirname_now);
5807          }
5808
5809          // The buffer is still loaded, the Filetype autocommands
5810          // need to be done now, in that buffer.  And the modelines
5811          // need to be done (again).  But not the window-local
5812          // options!
5813          CtxSwitch aco = { 0 };
5814          ctx_switch(&aco, NULL, NULL, buf, 0);
5815          apply_autocmds(EVENT_FILETYPE, buf->b_p_ft, buf->b_fname, true, buf);
5816          do_modelines(OPT_NOWIN);
5817          ctx_restore(&aco);
5818        }
5819      }
5820    }
5821  }
5822
5823  status = OK;
5824
5825theend:
5826  xfree(dirname_now);
5827  xfree(dirname_start);
5828  return status;
5829}
5830
5831/// ":vimgrep {pattern} file(s)"
5832/// ":vimgrepadd {pattern} file(s)"
5833/// ":lvimgrep {pattern} file(s)"
5834/// ":lvimgrepadd {pattern} file(s)"
5835void ex_vimgrep(exarg_T *eap)
5836{
5837  if (!check_can_set_curbuf_forceit(eap->forceit)) {
5838    return;
5839  }
5840
5841  char *au_name = vgr_get_auname(eap->cmdidx);
5842  if (au_name != NULL && apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
5843                                        curbuf->b_fname, true, curbuf)) {
5844    if (aborting()) {
5845      return;
5846    }
5847  }
5848
5849  win_T *wp = NULL;
5850  qf_info_T *qi = qf_cmd_get_or_alloc_stack(eap, &wp);
5851  char *target_dir = NULL;
5852  vgr_args_T args;
5853  if (vgr_process_args(eap, &args) == FAIL) {
5854    goto theend;
5855  }
5856
5857  if ((eap->cmdidx != CMD_grepadd && eap->cmdidx != CMD_lgrepadd
5858       && eap->cmdidx != CMD_vimgrepadd && eap->cmdidx != CMD_lvimgrepadd)
5859      || qf_stack_empty(qi)) {
5860    // make place for a new list
5861    qf_new_list(qi, args.qf_title);
5862  }
5863
5864  incr_quickfix_busy();
5865
5866  bool redraw_for_dummy = false;
5867  buf_T *first_match_buf = NULL;
5868  int status = vgr_process_files(wp, qi, &args, &redraw_for_dummy, &first_match_buf, &target_dir);
5869
5870  if (status != OK) {
5871    FreeWild(args.fcount, args.fnames);
5872    decr_quickfix_busy();
5873    goto theend;
5874  }
5875
5876  FreeWild(args.fcount, args.fnames);
5877
5878  qf_list_T *qfl = qf_get_curlist(qi);
5879  qfl->qf_nonevalid = false;
5880  qfl->qf_ptr = qfl->qf_start;
5881  qfl->qf_index = 1;
5882  qf_list_changed(qfl);
5883
5884  qf_update_buffer(qi, NULL);
5885
5886  // Remember the current quickfix list identifier, so that we can check for
5887  // autocommands changing the current quickfix list.
5888  unsigned save_qfid = qf_get_curlist(qi)->qf_id;
5889
5890  if (au_name != NULL) {
5891    apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, true, curbuf);
5892  }
5893
5894  // The QuickFixCmdPost autocmd may free the quickfix list. Check the list
5895  // is still valid.
5896  if (!qflist_valid(wp, save_qfid) || qf_restore_list(qi, save_qfid) == FAIL) {
5897    decr_quickfix_busy();
5898    goto theend;
5899  }
5900
5901  // Jump to first match.
5902  if (!qf_list_empty(qf_get_curlist(qi))) {
5903    if ((args.flags & VGR_NOJUMP) == 0) {
5904      vgr_jump_to_match(qi, eap->forceit, &redraw_for_dummy, first_match_buf, target_dir);
5905    }
5906  } else {
5907    semsg(_(e_nomatch2), args.spat);
5908  }
5909
5910  decr_quickfix_busy();
5911
5912  // If we loaded a dummy buffer into the current window, the autocommands
5913  // may have messed up things, need to redraw and recompute folds.
5914  if (redraw_for_dummy) {
5915    foldUpdateAll(curwin);
5916  }
5917
5918theend:
5919  xfree(args.qf_title);
5920  xfree(target_dir);
5921  vim_regfree(args.regmatch.regprog);
5922}
5923
5924// Restore current working directory to "dirname_start" if they differ, taking
5925// into account whether it is set locally or globally.
5926static void restore_start_dir(char *dirname_start)
5927  FUNC_ATTR_NONNULL_ALL
5928{
5929  char *dirname_now = xmalloc(MAXPATHL);
5930
5931  os_dirname(dirname_now, MAXPATHL);
5932  if (strcmp(dirname_start, dirname_now) != 0) {
5933    // If the directory has changed, change it back by building up an
5934    // appropriate ex command and executing it.
5935    exarg_T ea = {
5936      .arg = dirname_start,
5937      .cmdidx = (curwin->w_localdir == NULL) ? CMD_cd : CMD_lcd,
5938    };
5939    ex_cd(&ea);
5940  }
5941  xfree(dirname_now);
5942}
5943
5944/// Load file "fname" into a dummy buffer and return the buffer pointer,
5945/// placing the directory resulting from the buffer load into the
5946/// "resulting_dir" pointer. "resulting_dir" must be allocated by the caller
5947/// prior to calling this function. Restores directory to "dirname_start" prior
5948/// to returning, if autocmds or the 'autochdir' option have changed it.
5949///
5950/// If creating the dummy buffer does not fail, must call unload_dummy_buffer()
5951/// or wipe_dummy_buffer() later!
5952///
5953/// @param dirname_start  in: old directory
5954/// @param resulting_dir  out: new directory
5955///
5956/// @return  NULL if it fails.
5957static buf_T *load_dummy_buffer(char *fname, char *dirname_start, char *resulting_dir)
5958{
5959  // Allocate a buffer without putting it in the buffer list.
5960  buf_T *newbuf = buflist_new(NULL, NULL, 1, BLN_DUMMY);
5961  if (newbuf == NULL) {
5962    return NULL;
5963  }
5964
5965  bool failed = true;
5966  bufref_T newbufref;
5967  set_bufref(&newbufref, newbuf);
5968
5969  // Init the options.
5970  buf_copy_options(newbuf, BCO_ENTER | BCO_NOHELP);
5971
5972  // need to open the memfile before putting the buffer in a window
5973  if (ml_open(newbuf) == OK) {
5974    // Make sure this buffer isn't wiped out by autocommands.
5975    newbuf->b_locked++;
5976    // set curwin/curbuf to buf and save a few things
5977    CtxSwitch aco = { 0 };
5978    ctx_switch(&aco, NULL, NULL, newbuf, 0);
5979
5980    // Need to set the filename for autocommands.
5981    setfname(curbuf, fname, NULL, false);
5982
5983    // Create swap file now to avoid the ATTENTION message.
5984    check_need_swap(true);
5985
5986    // Remove the "dummy" flag, otherwise autocommands may not
5987    // work.
5988    curbuf->b_flags &= ~BF_DUMMY;
5989
5990    bufref_T newbuf_to_wipe;
5991    newbuf_to_wipe.br_buf = NULL;
5992    int readfile_result = readfile(fname, NULL, 0, 0,
5993                                   (linenr_T)MAXLNUM, NULL,
5994                                   READ_NEW | READ_DUMMY, false);
5995    newbuf->b_locked--;
5996    if (readfile_result == OK
5997        && !got_int
5998        && !(curbuf->b_flags & BF_NEW)) {
5999      failed = false;
6000      if (curbuf != newbuf) {
6001        // Bloody autocommands changed the buffer!  Can happen when
6002        // using netrw and editing a remote file.  Use the current
6003        // buffer instead, delete the dummy one after restoring the
6004        // window stuff.
6005        set_bufref(&newbuf_to_wipe, newbuf);
6006        newbuf = curbuf;
6007      }
6008    }
6009
6010    // Restore curwin/curbuf and a few other things.
6011    ctx_restore(&aco);
6012
6013    if (newbuf_to_wipe.br_buf != NULL && bufref_valid(&newbuf_to_wipe)) {
6014      block_autocmds();
6015      wipe_dummy_buffer(newbuf_to_wipe.br_buf, NULL);
6016      unblock_autocmds();
6017    }
6018
6019    // Add back the "dummy" flag, otherwise buflist_findname_file_id()
6020    // won't skip it.
6021    newbuf->b_flags |= BF_DUMMY;
6022  }
6023
6024  // When autocommands/'autochdir' option changed directory: go back.
6025  // Let the caller know what the resulting dir was first, in case it is
6026  // important.
6027  os_dirname(resulting_dir, MAXPATHL);
6028  restore_start_dir(dirname_start);
6029
6030  if (!bufref_valid(&newbufref)) {
6031    return NULL;
6032  }
6033  if (failed) {
6034    wipe_dummy_buffer(newbuf, dirname_start);
6035    return NULL;
6036  }
6037  return newbuf;
6038}
6039
6040/// Wipe out the dummy buffer that load_dummy_buffer() created. Restores
6041/// directory to "dirname_start" if not NULL prior to returning, if autocmds or
6042/// the 'autochdir' option have changed it.
6043static void wipe_dummy_buffer(buf_T *buf, char *dirname_start)
6044  FUNC_ATTR_NONNULL_ARG(1)
6045{
6046  // If any autocommand opened a window on the dummy buffer, close that
6047  // window.  If we can't close them all then give up.
6048  while (buf->b_nwindows > 0) {
6049    bool did_one = false;
6050
6051    if (firstwin->w_next != NULL) {
6052      for (win_T *wp = firstwin; wp != NULL; wp = wp->w_next) {
6053        if (wp->w_buffer == buf) {
6054          if (win_close(wp, false, false) == OK) {
6055            did_one = true;
6056          }
6057          break;
6058        }
6059      }
6060    }
6061    if (!did_one) {
6062      goto fail;
6063    }
6064  }
6065
6066  if (curbuf != buf && buf->b_nwindows == 0) {  // safety check
6067    cleanup_T cs;
6068
6069    // Reset the error/interrupt/exception state here so that aborting()
6070    // returns false when wiping out the buffer.  Otherwise it doesn't
6071    // work when got_int is set.
6072    enter_cleanup(&cs);
6073
6074    wipe_buffer(buf, true);
6075
6076    // Restore the error/interrupt/exception state if not discarded by a
6077    // new aborting error, interrupt, or uncaught exception.
6078    leave_cleanup(&cs);
6079
6080    if (dirname_start != NULL) {
6081      // When autocommands/'autochdir' option changed directory: go back.
6082      restore_start_dir(dirname_start);
6083    }
6084
6085    return;
6086  }
6087
6088fail:
6089  // Keeping the buffer, remove the dummy flag.
6090  buf->b_flags &= ~BF_DUMMY;
6091}
6092
6093/// Unload the dummy buffer that load_dummy_buffer() created. Restores
6094/// directory to "dirname_start" prior to returning, if autocmds or the
6095/// 'autochdir' option have changed it.
6096static void unload_dummy_buffer(buf_T *buf, char *dirname_start)
6097{
6098  if (curbuf == buf) {          // safety check
6099    return;
6100  }
6101
6102  close_buffer(NULL, buf, DOBUF_UNLOAD, false, true, false);
6103
6104  // When autocommands/'autochdir' option changed directory: go back.
6105  restore_start_dir(dirname_start);
6106}
6107
6108/// Copy the specified quickfix entry items into a new dict and append the dict
6109/// to 'list'.  Returns OK on success.
6110static int get_qfline_items(qfline_T *qfp, list_T *list)
6111{
6112  // Handle entries with a non-existing buffer number.
6113  int bufnum = qfp->qf_fnum;
6114  if (bufnum != 0 && (buflist_findnr(bufnum) == NULL)) {
6115    bufnum = 0;
6116  }
6117
6118  dict_T *const dict = tv_dict_alloc();
6119  tv_list_append_dict(list, dict);
6120
6121  char buf[2];
6122  buf[0] = qfp->qf_type;
6123  buf[1] = NUL;
6124  size_t buflen = (buf[0] == NUL) ? 0 : 1;
6125  if (tv_dict_add_nr(dict, S_LEN("bufnr"), (varnumber_T)bufnum) == FAIL
6126      || (tv_dict_add_nr(dict, S_LEN("lnum"), (varnumber_T)qfp->qf_lnum) == FAIL)
6127      || (tv_dict_add_nr(dict, S_LEN("end_lnum"), (varnumber_T)qfp->qf_end_lnum) == FAIL)
6128      || (tv_dict_add_nr(dict, S_LEN("col"), (varnumber_T)qfp->qf_col) == FAIL)
6129      || (tv_dict_add_nr(dict, S_LEN("end_col"), (varnumber_T)qfp->qf_end_col) == FAIL)
6130      || (tv_dict_add_nr(dict, S_LEN("vcol"), (varnumber_T)qfp->qf_viscol) == FAIL)
6131      || (tv_dict_add_nr(dict, S_LEN("nr"), (varnumber_T)qfp->qf_nr) == FAIL)
6132      || (tv_dict_add_str(dict, S_LEN("module"), (qfp->qf_module == NULL ? "" : qfp->qf_module))
6133          == FAIL)
6134      || (tv_dict_add_str(dict, S_LEN("pattern"), (qfp->qf_pattern == NULL ? "" : qfp->qf_pattern))
6135          == FAIL)
6136      || (tv_dict_add_str(dict, S_LEN("text"), (qfp->qf_text == NULL ? "" : qfp->qf_text)) == FAIL)
6137      || (tv_dict_add_str_len(dict, S_LEN("type"), buf, (int)buflen) == FAIL)
6138      || (qfp->qf_user_data.v_type != VAR_UNKNOWN
6139          && tv_dict_add_tv(dict, S_LEN("user_data"), &qfp->qf_user_data) == FAIL)
6140      || (tv_dict_add_nr(dict, S_LEN("valid"), (varnumber_T)qfp->qf_valid) == FAIL)) {
6141    // tv_dict_add* fail only if key already exist, but this is a newly
6142    // allocated dictionary which is thus guaranteed to have no existing keys.
6143    abort();
6144  }
6145
6146  return OK;
6147}
6148
6149/// Add each quickfix error to list "list" as a dictionary.
6150/// If qf_idx is -1, use the current list. Otherwise, use the specified list.
6151/// If eidx is not 0, then return only the specified entry. Otherwise return
6152/// all the entries.
6153static int get_errorlist(qf_info_T *qi_arg, win_T *wp, int qf_idx, int eidx, list_T *list)
6154{
6155  qf_info_T *qi = qi_arg;
6156
6157  if (qi == NULL) {
6158    qi = ql_info;
6159    if (wp != NULL) {
6160      qi = GET_LOC_LIST(wp);
6161    }
6162    if (qi == NULL) {
6163      return FAIL;
6164    }
6165  }
6166
6167  if (eidx < 0) {
6168    return OK;
6169  }
6170
6171  if (qf_idx == INVALID_QFIDX) {
6172    qf_idx = qi->qf_curlist;
6173  }
6174
6175  if (qf_idx >= qi->qf_listcount) {
6176    return FAIL;
6177  }
6178
6179  qf_list_T *qfl = qf_get_list(qi, qf_idx);
6180  if (qf_list_empty(qfl)) {
6181    return FAIL;
6182  }
6183
6184  qfline_T *qfp;
6185  int i;
6186  FOR_ALL_QFL_ITEMS(qfl, qfp, i) {
6187    if (eidx > 0) {
6188      if (eidx == i) {
6189        return get_qfline_items(qfp, list);
6190      }
6191    } else if (get_qfline_items(qfp, list) == FAIL) {
6192      return FAIL;
6193    }
6194  }
6195
6196  return OK;
6197}
6198
6199/// Flags used by getqflist()/getloclist() to determine which fields to return.
6200enum {
6201  QF_GETLIST_NONE = 0x0,
6202  QF_GETLIST_TITLE = 0x1,
6203  QF_GETLIST_ITEMS = 0x2,
6204  QF_GETLIST_NR = 0x4,
6205  QF_GETLIST_WINID = 0x8,
6206  QF_GETLIST_CONTEXT = 0x10,
6207  QF_GETLIST_ID = 0x20,
6208  QF_GETLIST_IDX = 0x40,
6209  QF_GETLIST_SIZE = 0x80,
6210  QF_GETLIST_TICK = 0x100,
6211  QF_GETLIST_FILEWINID = 0x200,
6212  QF_GETLIST_QFBUFNR = 0x400,
6213  QF_GETLIST_QFTF = 0x800,
6214  QF_GETLIST_ALL = 0xFFF,
6215};
6216
6217/// Parse text from 'di' and return the quickfix list items.
6218/// Existing quickfix lists are not modified.
6219static int qf_get_list_from_lines(dict_T *what, dictitem_T *di, dict_T *retdict)
6220{
6221  int status = FAIL;
6222
6223  // Only a List value is supported
6224  if (di->di_tv.v_type != VAR_LIST || di->di_tv.vval.v_list == NULL) {
6225    return FAIL;
6226  }
6227
6228  char *errorformat = p_efm;
6229  dictitem_T *efm_di;
6230  // If errorformat is supplied then use it, otherwise use the 'efm'
6231  // option setting
6232  if ((efm_di = tv_dict_find(what, S_LEN("efm"))) != NULL) {
6233    if (efm_di->di_tv.v_type != VAR_STRING
6234        || efm_di->di_tv.vval.v_string == NULL) {
6235      return FAIL;
6236    }
6237    errorformat = efm_di->di_tv.vval.v_string;
6238  }
6239
6240  list_T *l = tv_list_alloc(kListLenMayKnow);
6241  qf_info_T *const qi = qf_alloc_stack(QFLT_INTERNAL, 1);
6242
6243  if (qf_init_ext(qi, 0, NULL, NULL, &di->di_tv, errorformat,
6244                  true, 0, 0, NULL, NULL) > 0) {
6245    get_errorlist(qi, NULL, 0, 0, l);
6246    qf_free(&qi->qf_lists[0]);
6247  }
6248
6249  qf_free_lists(qi);
6250
6251  tv_dict_add_list(retdict, S_LEN("items"), l);
6252  status = OK;
6253
6254  return status;
6255}
6256
6257/// Return the quickfix/location list window identifier in the current tabpage.
6258static int qf_winid(qf_info_T *qi)
6259{
6260  // The quickfix window can be opened even if the quickfix list is not set
6261  // using ":copen". This is not true for location lists.
6262  if (qi == NULL) {
6263    return 0;
6264  }
6265  win_T *win = qf_find_win(qi);
6266  if (win != NULL) {
6267    return win->handle;
6268  }
6269  return 0;
6270}
6271
6272/// Returns the number of the buffer displayed in the quickfix/location list
6273/// window. If there is no buffer associated with the list or the buffer is
6274/// wiped out, then returns 0.
6275static int qf_getprop_qfbufnr(const qf_info_T *qi, dict_T *retdict)
6276  FUNC_ATTR_NONNULL_ARG(2)
6277{
6278  int bufnum = 0;
6279
6280  if (qi != NULL && buflist_findnr(qi->qf_bufnr) != NULL) {
6281    bufnum = qi->qf_bufnr;
6282  }
6283
6284  return tv_dict_add_nr(retdict, S_LEN("qfbufnr"), bufnum);
6285}
6286
6287/// Convert the keys in 'what' to quickfix list property flags.
6288static int qf_getprop_keys2flags(const dict_T *what, bool loclist)
6289  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
6290{
6291  int flags = QF_GETLIST_NONE;
6292
6293  if (tv_dict_find(what, S_LEN("all")) != NULL) {
6294    flags |= QF_GETLIST_ALL;
6295    if (!loclist) {
6296      // File window ID is applicable only to location list windows
6297      flags &= ~QF_GETLIST_FILEWINID;
6298    }
6299  }
6300  if (tv_dict_find(what, S_LEN("title")) != NULL) {
6301    flags |= QF_GETLIST_TITLE;
6302  }
6303  if (tv_dict_find(what, S_LEN("nr")) != NULL) {
6304    flags |= QF_GETLIST_NR;
6305  }
6306  if (tv_dict_find(what, S_LEN("winid")) != NULL) {
6307    flags |= QF_GETLIST_WINID;
6308  }
6309  if (tv_dict_find(what, S_LEN("context")) != NULL) {
6310    flags |= QF_GETLIST_CONTEXT;
6311  }
6312  if (tv_dict_find(what, S_LEN("id")) != NULL) {
6313    flags |= QF_GETLIST_ID;
6314  }
6315  if (tv_dict_find(what, S_LEN("items")) != NULL) {
6316    flags |= QF_GETLIST_ITEMS;
6317  }
6318  if (tv_dict_find(what, S_LEN("idx")) != NULL) {
6319    flags |= QF_GETLIST_IDX;
6320  }
6321  if (tv_dict_find(what, S_LEN("size")) != NULL) {
6322    flags |= QF_GETLIST_SIZE;
6323  }
6324  if (tv_dict_find(what, S_LEN("changedtick")) != NULL) {
6325    flags |= QF_GETLIST_TICK;
6326  }
6327  if (loclist && tv_dict_find(what, S_LEN("filewinid")) != NULL) {
6328    flags |= QF_GETLIST_FILEWINID;
6329  }
6330  if (tv_dict_find(what, S_LEN("qfbufnr")) != NULL) {
6331    flags |= QF_GETLIST_QFBUFNR;
6332  }
6333  if (tv_dict_find(what, S_LEN("quickfixtextfunc")) != NULL) {
6334    flags |= QF_GETLIST_QFTF;
6335  }
6336
6337  return flags;
6338}
6339
6340/// Return the quickfix list index based on 'nr' or 'id' in 'what'.
6341///
6342/// If 'nr' and 'id' are not present in 'what' then return the current
6343/// quickfix list index.
6344/// If 'nr' is zero then return the current quickfix list index.
6345/// If 'nr' is '$' then return the last quickfix list index.
6346/// If 'id' is present then return the index of the quickfix list with that id.
6347/// If 'id' is zero then return the quickfix list index specified by 'nr'.
6348/// Return -1, if quickfix list is not present or if the stack is empty.
6349static int qf_getprop_qfidx(qf_info_T *qi, dict_T *what)
6350{
6351  dictitem_T *di = NULL;
6352
6353  int qf_idx = qi->qf_curlist;  // default is the current list
6354  if ((di = tv_dict_find(what, S_LEN("nr"))) != NULL) {
6355    // Use the specified quickfix/location list
6356    if (di->di_tv.v_type == VAR_NUMBER) {
6357      // for zero use the current list
6358      if (di->di_tv.vval.v_number != 0) {
6359        qf_idx = (int)di->di_tv.vval.v_number - 1;
6360        if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
6361          qf_idx = INVALID_QFIDX;
6362        }
6363      }
6364    } else if (di->di_tv.v_type == VAR_STRING && strequal(di->di_tv.vval.v_string, "$")) {
6365      // Get the last quickfix list number
6366      qf_idx = qi->qf_listcount - 1;
6367    } else {
6368      qf_idx = INVALID_QFIDX;
6369    }
6370  }
6371
6372  if ((di = tv_dict_find(what, S_LEN("id"))) != NULL) {
6373    // Look for a list with the specified id
6374    if (di->di_tv.v_type == VAR_NUMBER) {
6375      // For zero, use the current list or the list specified by 'nr'
6376      if (di->di_tv.vval.v_number != 0) {
6377        qf_idx = qf_id2nr(qi, (unsigned)di->di_tv.vval.v_number);
6378      }
6379    } else {
6380      qf_idx = INVALID_QFIDX;
6381    }
6382  }
6383
6384  return qf_idx;
6385}
6386
6387/// Return default values for quickfix list properties in retdict.
6388static int qf_getprop_defaults(qf_info_T *qi, int flags, int locstack, dict_T *retdict)
6389{
6390  int status = OK;
6391
6392  if (flags & QF_GETLIST_TITLE) {
6393    status = tv_dict_add_str_len(retdict, S_LEN("title"), "", 0);
6394  }
6395  if ((status == OK) && (flags & QF_GETLIST_ITEMS)) {
6396    list_T *l = tv_list_alloc(kListLenMayKnow);
6397    status = tv_dict_add_list(retdict, S_LEN("items"), l);
6398  }
6399  if ((status == OK) && (flags & QF_GETLIST_NR)) {
6400    status = tv_dict_add_nr(retdict, S_LEN("nr"), 0);
6401  }
6402  if ((status == OK) && (flags & QF_GETLIST_WINID)) {
6403    status = tv_dict_add_nr(retdict, S_LEN("winid"), qf_winid(qi));
6404  }
6405  if ((status == OK) && (flags & QF_GETLIST_CONTEXT)) {
6406    status = tv_dict_add_str_len(retdict, S_LEN("context"), "", 0);
6407  }
6408  if ((status == OK) && (flags & QF_GETLIST_ID)) {
6409    status = tv_dict_add_nr(retdict, S_LEN("id"), 0);
6410  }
6411  if ((status == OK) && (flags & QF_GETLIST_IDX)) {
6412    status = tv_dict_add_nr(retdict, S_LEN("idx"), 0);
6413  }
6414  if ((status == OK) && (flags & QF_GETLIST_SIZE)) {
6415    status = tv_dict_add_nr(retdict, S_LEN("size"), 0);
6416  }
6417  if ((status == OK) && (flags & QF_GETLIST_TICK)) {
6418    status = tv_dict_add_nr(retdict, S_LEN("changedtick"), 0);
6419  }
6420  if ((status == OK) && locstack && (flags & QF_GETLIST_FILEWINID)) {
6421    status = tv_dict_add_nr(retdict, S_LEN("filewinid"), 0);
6422  }
6423  if ((status == OK) && (flags & QF_GETLIST_QFBUFNR)) {
6424    status = qf_getprop_qfbufnr(qi, retdict);
6425  }
6426  if ((status == OK) && (flags & QF_GETLIST_QFTF)) {
6427    status = tv_dict_add_str_len(retdict, S_LEN("quickfixtextfunc"), "", 0);
6428  }
6429
6430  return status;
6431}
6432
6433/// Return the quickfix list title as 'title' in retdict
6434static int qf_getprop_title(qf_list_T *qfl, dict_T *retdict)
6435{
6436  return tv_dict_add_str(retdict, S_LEN("title"), qfl->qf_title);
6437}
6438
6439// Returns the identifier of the window used to display files from a location
6440// list.  If there is no associated window, then returns 0. Useful only when
6441// called from a location list window.
6442static int qf_getprop_filewinid(const win_T *wp, const qf_info_T *qi, dict_T *retdict)
6443  FUNC_ATTR_NONNULL_ARG(3)
6444{
6445  handle_T winid = 0;
6446
6447  if (wp != NULL && IS_LL_WINDOW(wp)) {
6448    win_T *ll_wp = qf_find_win_with_loclist(qi);
6449    if (ll_wp != NULL) {
6450      winid = ll_wp->handle;
6451    }
6452  }
6453
6454  return tv_dict_add_nr(retdict, S_LEN("filewinid"), winid);
6455}
6456
6457/// Return the quickfix list items/entries as 'items' in retdict.
6458/// If eidx is not 0, then return the item at the specified index.
6459static int qf_getprop_items(qf_info_T *qi, int qf_idx, int eidx, dict_T *retdict)
6460{
6461  list_T *l = tv_list_alloc(kListLenMayKnow);
6462  get_errorlist(qi, NULL, qf_idx, eidx, l);
6463  tv_dict_add_list(retdict, S_LEN("items"), l);
6464
6465  return OK;
6466}
6467
6468/// Return the quickfix list context (if any) as 'context' in retdict.
6469static int qf_getprop_ctx(qf_list_T *qfl, dict_T *retdict)
6470{
6471  int status;
6472
6473  if (qfl->qf_ctx != NULL) {
6474    dictitem_T *di = tv_dict_item_alloc_len(S_LEN("context"));
6475    tv_copy(qfl->qf_ctx, &di->di_tv);
6476    status = tv_dict_add(retdict, di);
6477    if (status == FAIL) {
6478      tv_dict_item_free(di);
6479    }
6480  } else {
6481    status = tv_dict_add_str_len(retdict, S_LEN("context"), "", 0);
6482  }
6483
6484  return status;
6485}
6486
6487/// Return the current quickfix list index as 'idx' in retdict.
6488/// If a specific entry index (eidx) is supplied, then use that.
6489static int qf_getprop_idx(qf_list_T *qfl, int eidx, dict_T *retdict)
6490{
6491  if (eidx == 0) {
6492    eidx = qfl->qf_index;
6493    if (qf_list_empty(qfl)) {
6494      // For empty lists, current index is set to 0
6495      eidx = 0;
6496    }
6497  }
6498  return tv_dict_add_nr(retdict, S_LEN("idx"), eidx);
6499}
6500
6501/// Return the 'quickfixtextfunc' function of a quickfix/location list
6502/// @return OK or FAIL
6503static int qf_getprop_qftf(qf_list_T *qfl, dict_T *retdict)
6504  FUNC_ATTR_NONNULL_ALL
6505{
6506  int status;
6507
6508  if (qfl->qf_qftf_cb.type != kCallbackNone) {
6509    typval_T tv;
6510
6511    callback_put(&qfl->qf_qftf_cb, &tv);
6512    status = tv_dict_add_tv(retdict, S_LEN("quickfixtextfunc"), &tv);
6513    tv_clear(&tv);
6514  } else {
6515    status = tv_dict_add_str_len(retdict, S_LEN("quickfixtextfunc"), "", 0);
6516  }
6517
6518  return status;
6519}
6520
6521/// Return quickfix/location list details (title) as a dictionary.
6522/// 'what' contains the details to return. If 'list_idx' is -1,
6523/// then current list is used. Otherwise the specified list is used.
6524static int qf_get_properties(win_T *wp, dict_T *what, dict_T *retdict)
6525{
6526  qf_info_T *qi = ql_info;
6527  assert(qi != NULL);
6528  dictitem_T *di = NULL;
6529  int status = OK;
6530  int qf_idx = INVALID_QFIDX;
6531
6532  if ((di = tv_dict_find(what, S_LEN("lines"))) != NULL) {
6533    return qf_get_list_from_lines(what, di, retdict);
6534  }
6535
6536  if (wp != NULL) {
6537    qi = GET_LOC_LIST(wp);
6538  }
6539
6540  const int flags = qf_getprop_keys2flags(what, wp != NULL);
6541
6542  if (!qf_stack_empty(qi)) {
6543    qf_idx = qf_getprop_qfidx(qi, what);
6544  }
6545
6546  // List is not present or is empty
6547  if (qf_stack_empty(qi) || qf_idx == INVALID_QFIDX) {
6548    return qf_getprop_defaults(qi, flags, wp != NULL, retdict);
6549  }
6550
6551  qf_list_T *qfl = qf_get_list(qi, qf_idx);
6552  int eidx = 0;
6553
6554  // If an entry index is specified, use that
6555  if ((di = tv_dict_find(what, S_LEN("idx"))) != NULL) {
6556    if (di->di_tv.v_type != VAR_NUMBER) {
6557      return FAIL;
6558    }
6559    eidx = (int)di->di_tv.vval.v_number;
6560  }
6561
6562  if (flags & QF_GETLIST_TITLE) {
6563    status = qf_getprop_title(qfl, retdict);
6564  }
6565  if ((status == OK) && (flags & QF_GETLIST_NR)) {
6566    status = tv_dict_add_nr(retdict, S_LEN("nr"), qf_idx + 1);
6567  }
6568  if ((status == OK) && (flags & QF_GETLIST_WINID)) {
6569    status = tv_dict_add_nr(retdict, S_LEN("winid"), qf_winid(qi));
6570  }
6571  if ((status == OK) && (flags & QF_GETLIST_ITEMS)) {
6572    status = qf_getprop_items(qi, qf_idx, eidx, retdict);
6573  }
6574  if ((status == OK) && (flags & QF_GETLIST_CONTEXT)) {
6575    status = qf_getprop_ctx(qfl, retdict);
6576  }
6577  if ((status == OK) && (flags & QF_GETLIST_ID)) {
6578    status = tv_dict_add_nr(retdict, S_LEN("id"), qfl->qf_id);
6579  }
6580  if ((status == OK) && (flags & QF_GETLIST_IDX)) {
6581    status = qf_getprop_idx(qfl, eidx, retdict);
6582  }
6583  if ((status == OK) && (flags & QF_GETLIST_SIZE)) {
6584    status = tv_dict_add_nr(retdict, S_LEN("size"),
6585                            qfl->qf_count);
6586  }
6587  if ((status == OK) && (flags & QF_GETLIST_TICK)) {
6588    status = tv_dict_add_nr(retdict, S_LEN("changedtick"),
6589                            qfl->qf_changedtick);
6590  }
6591  if ((status == OK) && (wp != NULL) && (flags & QF_GETLIST_FILEWINID)) {
6592    status = qf_getprop_filewinid(wp, qi, retdict);
6593  }
6594  if ((status == OK) && (flags & QF_GETLIST_QFBUFNR)) {
6595    status = qf_getprop_qfbufnr(qi, retdict);
6596  }
6597  if ((status == OK) && (flags & QF_GETLIST_QFTF)) {
6598    status = qf_getprop_qftf(qfl, retdict);
6599  }
6600
6601  return status;
6602}
6603
6604/// Set the 'quickfixtextfunc' in the specified quickfix/location list
6605/// @return OK or FAIL
6606static int qf_setprop_qftf(qf_list_T *qfl, dictitem_T *di)
6607  FUNC_ATTR_NONNULL_ALL
6608{
6609  Callback cb;
6610
6611  if (check_secure()) {
6612    return FAIL;
6613  }
6614
6615  callback_free(&qfl->qf_qftf_cb);
6616  if (callback_from_typval(&cb, &di->di_tv)) {
6617    qfl->qf_qftf_cb = cb;
6618  }
6619  return OK;
6620}
6621
6622/// Add a new quickfix entry to list at 'qf_idx' in the stack 'qi' from the
6623/// items in the dict 'd'. If it is a valid error entry, then set 'valid_entry'
6624/// to true.
6625static int qf_add_entry_from_dict(qf_list_T *qfl, dict_T *d, bool first_entry, bool *valid_entry)
6626  FUNC_ATTR_NONNULL_ALL
6627{
6628  static bool did_bufnr_emsg;
6629
6630  if (first_entry) {
6631    did_bufnr_emsg = false;
6632  }
6633
6634  char *const filename = tv_dict_get_string(d, "filename", true);
6635  char *const module = tv_dict_get_string(d, "module", true);
6636  int bufnum = (int)tv_dict_get_number(d, "bufnr");
6637  const linenr_T lnum = (linenr_T)tv_dict_get_number(d, "lnum");
6638  const linenr_T end_lnum = (linenr_T)tv_dict_get_number(d, "end_lnum");
6639  const int col = (int)tv_dict_get_number(d, "col");
6640  const int end_col = (int)tv_dict_get_number(d, "end_col");
6641  const char vcol = (char)tv_dict_get_number(d, "vcol");
6642  const int nr = (int)tv_dict_get_number(d, "nr");
6643  const char *const type = tv_dict_get_string(d, "type", false);
6644  char *const pattern = tv_dict_get_string(d, "pattern", true);
6645  char *text = tv_dict_get_string(d, "text", true);
6646  if (text == NULL) {
6647    text = xcalloc(1, 1);
6648  }
6649  typval_T user_data = { .v_type = VAR_UNKNOWN };
6650  tv_dict_get_tv(d, "user_data", &user_data);
6651
6652  bool valid = true;
6653  if ((filename == NULL && bufnum == 0)
6654      || (lnum == 0 && pattern == NULL)) {
6655    valid = false;
6656  }
6657
6658  // Mark entries with non-existing buffer number as not valid. Give the
6659  // error message only once.
6660  if (bufnum != 0 && (buflist_findnr(bufnum) == NULL)) {
6661    if (!did_bufnr_emsg) {
6662      did_bufnr_emsg = true;
6663      semsg(_("E92: Buffer %d not found"), bufnum);
6664    }
6665    valid = false;
6666    bufnum = 0;
6667  }
6668
6669  // If the 'valid' field is present it overrules the detected value.
6670  if (tv_dict_find(d, "valid", -1) != NULL) {
6671    valid = tv_dict_get_bool(d, "valid", false);
6672  }
6673
6674  const int status = qf_add_entry(qfl,
6675                                  NULL,      // dir
6676                                  filename,
6677                                  module,
6678                                  bufnum,
6679                                  text,
6680                                  lnum,
6681                                  end_lnum,
6682                                  col,
6683                                  end_col,
6684                                  vcol,      // vis_col
6685                                  pattern,   // search pattern
6686                                  nr,
6687                                  type == NULL ? NUL : *type,
6688                                  &user_data,
6689                                  valid);
6690
6691  xfree(filename);
6692  xfree(module);
6693  xfree(pattern);
6694  xfree(text);
6695  tv_clear(&user_data);
6696
6697  if (valid) {
6698    *valid_entry = true;
6699  }
6700
6701  return status;
6702}
6703
6704/// Check if `entry` is closer to the target than `other_entry`.
6705///
6706/// Only returns true if `entry` is definitively closer. If it's further
6707/// away, or there's not enough information to tell, return false.
6708static bool entry_is_closer_to_target(qfline_T *entry, qfline_T *other_entry, int target_fnum,
6709                                      int target_lnum, int target_col)
6710{
6711  // First, compare entries to target file.
6712  if (!target_fnum) {
6713    // Without a target file, we can't know which is closer.
6714    return false;
6715  }
6716
6717  bool is_target_file = entry->qf_fnum && entry->qf_fnum == target_fnum;
6718  bool other_is_target_file = other_entry->qf_fnum && other_entry->qf_fnum == target_fnum;
6719  if (!is_target_file && other_is_target_file) {
6720    return false;
6721  } else if (is_target_file && !other_is_target_file) {
6722    return true;
6723  }
6724
6725  // Both entries are pointing at the exact same file. Now compare line numbers.
6726  if (!target_lnum) {
6727    // Without a target line number, we can't know which is closer.
6728    return false;
6729  }
6730
6731  int line_distance = entry->qf_lnum
6732                      ? abs(entry->qf_lnum - target_lnum) : INT_MAX;
6733  int other_line_distance = other_entry->qf_lnum
6734                            ? abs(other_entry->qf_lnum - target_lnum) : INT_MAX;
6735  if (line_distance > other_line_distance) {
6736    return false;
6737  } else if (line_distance < other_line_distance) {
6738    return true;
6739  }
6740
6741  // Both entries are pointing at the exact same line number (or no line
6742  // number at all). Now compare columns.
6743  if (!target_col) {
6744    // Without a target column, we can't know which is closer.
6745    return false;
6746  }
6747
6748  int column_distance = entry->qf_col
6749                        ? abs(entry->qf_col - target_col) : INT_MAX;
6750  int other_column_distance = other_entry->qf_col
6751                              ? abs(other_entry->qf_col - target_col) : INT_MAX;
6752  if (column_distance > other_column_distance) {
6753    return false;
6754  } else if (column_distance < other_column_distance) {
6755    return true;
6756  }
6757
6758  // It's a complete tie! The exact same file, line, and column.
6759  return false;
6760}
6761
6762/// Add list of entries to quickfix/location list. Each list entry is
6763/// a dictionary with item information.
6764static int qf_add_entries(qf_info_T *qi, int qf_idx, list_T *list, char *title, int action)
6765{
6766  qf_list_T *qfl = qf_get_list(qi, qf_idx);
6767  qfline_T *old_last = NULL;
6768  int retval = OK;
6769  bool valid_entry = false;
6770
6771  // If there's an entry selected in the quickfix list, remember its location
6772  // (file, line, column), so we can select the nearest entry in the updated
6773  // quickfix list.
6774  int prev_fnum = 0;
6775  int prev_lnum = 0;
6776  int prev_col = 0;
6777  if (qfl->qf_ptr) {
6778    prev_fnum = qfl->qf_ptr->qf_fnum;
6779    prev_lnum = qfl->qf_ptr->qf_lnum;
6780    prev_col = qfl->qf_ptr->qf_col;
6781  }
6782
6783  bool select_first_entry = false;
6784  bool select_nearest_entry = false;
6785
6786  if (action == ' ' || qf_idx == qi->qf_listcount) {
6787    select_first_entry = true;
6788    // make place for a new list
6789    qf_new_list(qi, title);
6790    qf_idx = qi->qf_curlist;
6791    qfl = qf_get_list(qi, qf_idx);
6792  } else if (action == 'a') {
6793    if (qf_list_empty(qfl)) {
6794      // Appending to empty list, select first entry.
6795      select_first_entry = true;
6796    } else {
6797      // Adding to existing list, use last entry.
6798      old_last = qfl->qf_last;
6799    }
6800  } else if (action == 'r') {
6801    select_first_entry = true;
6802    qf_free_items(qfl);
6803    qf_store_title(qfl, title);
6804  } else if (action == 'u') {
6805    select_nearest_entry = true;
6806    qf_free_items(qfl);
6807    qf_store_title(qfl, title);
6808  }
6809
6810  qfline_T *entry_to_select = NULL;
6811  int entry_to_select_index = 0;
6812
6813  TV_LIST_ITER_CONST(list, li, {
6814    if (TV_LIST_ITEM_TV(li)->v_type != VAR_DICT) {
6815      continue;  // Skip non-dict items.
6816    }
6817
6818    dict_T *const d = TV_LIST_ITEM_TV(li)->vval.v_dict;
6819    if (d == NULL) {
6820      continue;
6821    }
6822
6823    retval = qf_add_entry_from_dict(qfl, d, li == tv_list_first(list), &valid_entry);
6824    if (retval == QF_FAIL) {
6825      break;
6826    }
6827
6828    qfline_T *entry = qfl->qf_last;
6829    if ((select_first_entry && entry_to_select == NULL)
6830        || (select_nearest_entry
6831            && (entry_to_select == NULL
6832                || entry_is_closer_to_target(entry, entry_to_select, prev_fnum,
6833                                             prev_lnum, prev_col)))) {
6834      entry_to_select = entry;
6835      entry_to_select_index = qfl->qf_count;
6836    }
6837  });
6838
6839  // Check if any valid error entries are added to the list.
6840  if (valid_entry) {
6841    qfl->qf_nonevalid = false;
6842  } else if (qfl->qf_index == 0) {
6843    qfl->qf_nonevalid = true;
6844  }
6845
6846  // Set the current error.
6847  if (entry_to_select) {
6848    qfl->qf_ptr = entry_to_select;
6849    qfl->qf_index = entry_to_select_index;
6850  }
6851
6852  // Don't update the cursor in quickfix window when appending entries
6853  qf_update_buffer(qi, old_last);
6854
6855  return retval;
6856}
6857
6858/// Get the quickfix list index from 'nr' or 'id'
6859static int qf_setprop_get_qfidx(const qf_info_T *qi, const dict_T *what, int action, bool *newlist)
6860  FUNC_ATTR_NONNULL_ALL
6861{
6862  dictitem_T *di;
6863  int qf_idx = qi->qf_curlist;  // default is the current list
6864
6865  if ((di = tv_dict_find(what, S_LEN("nr"))) != NULL) {
6866    // Use the specified quickfix/location list
6867    if (di->di_tv.v_type == VAR_NUMBER) {
6868      // for zero use the current list
6869      if (di->di_tv.vval.v_number != 0) {
6870        qf_idx = (int)di->di_tv.vval.v_number - 1;
6871      }
6872
6873      if ((action == ' ' || action == 'a') && qf_idx == qi->qf_listcount) {
6874        // When creating a new list, accept qf_idx pointing to the next
6875        // non-available list and add the new list at the end of the
6876        // stack.
6877        *newlist = true;
6878        qf_idx = qf_stack_empty(qi) ? 0 : qi->qf_listcount - 1;
6879      } else if (qf_idx < 0 || qf_idx >= qi->qf_listcount) {
6880        return INVALID_QFIDX;
6881      } else if (action != ' ') {
6882        *newlist = false;  // use the specified list
6883      }
6884    } else if (di->di_tv.v_type == VAR_STRING && strequal(di->di_tv.vval.v_string, "$")) {
6885      if (!qf_stack_empty(qi)) {
6886        qf_idx = qi->qf_listcount - 1;
6887      } else if (*newlist) {
6888        qf_idx = 0;
6889      } else {
6890        return INVALID_QFIDX;
6891      }
6892    } else {
6893      return INVALID_QFIDX;
6894    }
6895  }
6896
6897  if (!*newlist && (di = tv_dict_find(what, S_LEN("id"))) != NULL) {
6898    // Use the quickfix/location list with the specified id
6899    if (di->di_tv.v_type != VAR_NUMBER) {
6900      return INVALID_QFIDX;
6901    }
6902    return qf_id2nr(qi, (unsigned)di->di_tv.vval.v_number);
6903  }
6904
6905  return qf_idx;
6906}
6907
6908// Set the quickfix list title.
6909static int qf_setprop_title(qf_info_T *qi, int qf_idx, const dict_T *what, const dictitem_T *di)
6910  FUNC_ATTR_NONNULL_ALL
6911{
6912  qf_list_T *qfl = qf_get_list(qi, qf_idx);
6913  if (di->di_tv.v_type != VAR_STRING) {
6914    return FAIL;
6915  }
6916
6917  xfree(qfl->qf_title);
6918  qfl->qf_title = tv_dict_get_string(what, "title", true);
6919  if (qf_idx == qi->qf_curlist) {
6920    qf_update_win_titlevar(qi);
6921  }
6922
6923  return OK;
6924}
6925
6926// Set quickfix list items/entries.
6927static int qf_setprop_items(qf_info_T *qi, int qf_idx, dictitem_T *di, int action)
6928  FUNC_ATTR_NONNULL_ALL
6929{
6930  if (di->di_tv.v_type != VAR_LIST) {
6931    return FAIL;
6932  }
6933
6934  char *title_save = xstrdup(qi->qf_lists[qf_idx].qf_title);
6935  const int retval = qf_add_entries(qi, qf_idx, di->di_tv.vval.v_list, title_save,
6936                                    action == ' ' ? 'a' : action);
6937  xfree(title_save);
6938
6939  return retval;
6940}
6941
6942// Set quickfix list items/entries from a list of lines.
6943static int qf_setprop_items_from_lines(qf_info_T *qi, int qf_idx, const dict_T *what,
6944                                       dictitem_T *di, int action)
6945  FUNC_ATTR_NONNULL_ALL
6946{
6947  char *errorformat = p_efm;
6948  dictitem_T *efm_di;
6949  int retval = FAIL;
6950
6951  // Use the user supplied errorformat settings (if present)
6952  if ((efm_di = tv_dict_find(what, S_LEN("efm"))) != NULL) {
6953    if (efm_di->di_tv.v_type != VAR_STRING
6954        || efm_di->di_tv.vval.v_string == NULL) {
6955      return FAIL;
6956    }
6957    errorformat = efm_di->di_tv.vval.v_string;
6958  }
6959
6960  // Only a List value is supported
6961  if (di->di_tv.v_type != VAR_LIST || di->di_tv.vval.v_list == NULL) {
6962    return FAIL;
6963  }
6964
6965  if (action == 'r' || action == 'u') {
6966    qf_free_items(&qi->qf_lists[qf_idx]);
6967  }
6968  if (qf_init_ext(qi, qf_idx, NULL, NULL, &di->di_tv, errorformat,
6969                  false, 0, 0, NULL, NULL) >= 0) {
6970    retval = OK;
6971  }
6972
6973  return retval;
6974}
6975
6976// Set quickfix list context.
6977static int qf_setprop_context(qf_list_T *qfl, dictitem_T *di)
6978  FUNC_ATTR_NONNULL_ALL
6979{
6980  tv_free(qfl->qf_ctx);
6981  typval_T *ctx = xcalloc(1, sizeof(typval_T));
6982  tv_copy(&di->di_tv, ctx);
6983  qfl->qf_ctx = ctx;
6984
6985  return OK;
6986}
6987
6988// Set the current index in the specified quickfix list
6989static int qf_setprop_curidx(qf_info_T *qi, qf_list_T *qfl, const dictitem_T *di)
6990  FUNC_ATTR_NONNULL_ALL
6991{
6992  int newidx;
6993
6994  // If the specified index is '$', then use the last entry
6995  if (di->di_tv.v_type == VAR_STRING
6996      && di->di_tv.vval.v_string != NULL
6997      && strcmp(di->di_tv.vval.v_string, "$") == 0) {
6998    newidx = qfl->qf_count;
6999  } else {
7000    // Otherwise use the specified index
7001    bool denote = false;
7002    newidx = (int)tv_get_number_chk(&di->di_tv, &denote);
7003    if (denote) {
7004      return FAIL;
7005    }
7006  }
7007
7008  if (newidx < 1) {  // sanity check
7009    return FAIL;
7010  }
7011  newidx = MIN(newidx, qfl->qf_count);
7012  const int old_qfidx = qfl->qf_index;
7013  qfline_T *const qf_ptr = get_nth_entry(qfl, newidx, &newidx);
7014  if (qf_ptr == NULL) {
7015    return FAIL;
7016  }
7017  qfl->qf_ptr = qf_ptr;
7018  qfl->qf_index = newidx;
7019
7020  // If the current list is modified and it is displayed in the quickfix
7021  // window, then Update it.
7022  if (qi->qf_lists[qi->qf_curlist].qf_id == qfl->qf_id) {
7023    qf_win_pos_update(qi, old_qfidx);
7024  }
7025  return OK;
7026}
7027
7028/// Set quickfix/location list properties (title, items, context).
7029/// Also used to add items from parsing a list of lines.
7030/// Used by the setqflist() and setloclist() Vim script functions.
7031static int qf_set_properties(qf_info_T *qi, const dict_T *what, int action, char *title)
7032  FUNC_ATTR_NONNULL_ALL
7033{
7034  bool newlist = action == ' ' || qf_stack_empty(qi);
7035  int qf_idx = qf_setprop_get_qfidx(qi, what, action, &newlist);
7036  if (qf_idx == INVALID_QFIDX) {  // List not found
7037    return FAIL;
7038  }
7039
7040  if (newlist) {
7041    qi->qf_curlist = qf_idx;
7042    qf_new_list(qi, title);
7043    qf_idx = qi->qf_curlist;
7044  }
7045
7046  qf_list_T *qfl = qf_get_list(qi, qf_idx);
7047  dictitem_T *di;
7048  int retval = FAIL;
7049  if ((di = tv_dict_find(what, S_LEN("title"))) != NULL) {
7050    retval = qf_setprop_title(qi, qf_idx, what, di);
7051  }
7052  if ((di = tv_dict_find(what, S_LEN("items"))) != NULL) {
7053    retval = qf_setprop_items(qi, qf_idx, di, action);
7054  }
7055  if ((di = tv_dict_find(what, S_LEN("lines"))) != NULL) {
7056    retval = qf_setprop_items_from_lines(qi, qf_idx, what, di, action);
7057  }
7058  if ((di = tv_dict_find(what, S_LEN("context"))) != NULL) {
7059    retval = qf_setprop_context(qfl, di);
7060  }
7061  if ((di = tv_dict_find(what, S_LEN("idx"))) != NULL) {
7062    retval = qf_setprop_curidx(qi, qfl, di);
7063  }
7064  if ((di = tv_dict_find(what, S_LEN("quickfixtextfunc"))) != NULL) {
7065    retval = qf_setprop_qftf(qfl, di);
7066  }
7067
7068  if (newlist || retval == OK) {
7069    qf_list_changed(qfl);
7070  }
7071  if (newlist) {
7072    qf_update_buffer(qi, NULL);
7073  }
7074
7075  return retval;
7076}
7077
7078// Free the entire quickfix/location list stack.
7079// If the quickfix/location list window is open, then clear it.
7080static void qf_free_stack(win_T *wp, qf_info_T *qi)
7081{
7082  win_T *qfwin = qf_find_win(qi);
7083
7084  if (qfwin != NULL) {
7085    // If the quickfix/location list window is open, then clear it
7086    if (qi->qf_curlist < qi->qf_listcount) {
7087      qf_free(qf_get_curlist(qi));
7088    }
7089    qf_update_buffer(qi, NULL);
7090  }
7091
7092  if (wp != NULL && IS_LL_WINDOW(wp)) {
7093    // If in the location list window, then use the non-location list
7094    // window with this location list (if present)
7095    win_T *const llwin = qf_find_win_with_loclist(qi);
7096    if (llwin != NULL) {
7097      wp = llwin;
7098    }
7099  }
7100
7101  qf_free_all(wp);
7102  if (wp == NULL) {
7103    // quickfix list
7104    qi->qf_curlist = 0;
7105    qi->qf_listcount = 0;
7106  } else if (qfwin != NULL) {
7107    // If the location list window is open, then create a new empty location
7108    // list
7109    qf_info_T *new_ll = qf_alloc_stack(QFLT_LOCATION, (int)wp->w_p_lhi);
7110    new_ll->qf_bufnr = qfwin->w_buffer->b_fnum;
7111
7112    // first free the list reference in the location list window
7113    ll_free_all(&qfwin->w_llist_ref);
7114
7115    qfwin->w_llist_ref = new_ll;
7116    if (wp != qfwin) {
7117      win_set_loclist(wp, new_ll);
7118    }
7119  }
7120}
7121
7122/// Populate the quickfix list with the items supplied in the list
7123/// of dictionaries. "title" will be copied to w:quickfix_title
7124/// "action" is 'a' for add, 'r' for replace, 'u' for update.  Otherwise
7125/// create a new list.
7126/// When "what" is not NULL then only set some properties.
7127int set_errorlist(win_T *wp, list_T *list, int action, char *title, dict_T *what)
7128{
7129  qf_info_T *qi;
7130  if (wp != NULL) {
7131    qi = ll_get_or_alloc_list(wp);
7132  } else {
7133    qi = ql_info;
7134  }
7135  assert(qi != NULL);
7136
7137  if (action == 'f') {
7138    // Free the entire quickfix or location list stack
7139    qf_free_stack(wp, qi);
7140    return OK;
7141  }
7142
7143  // A dict argument cannot be specified with a non-empty list argument
7144  if (list != NULL && tv_list_len(list) != 0 && what != NULL) {
7145    semsg(_(e_invarg2), _("cannot have both a list and a \"what\" argument"));
7146    return FAIL;
7147  }
7148
7149  incr_quickfix_busy();
7150
7151  int retval = OK;
7152  if (what != NULL) {
7153    retval = qf_set_properties(qi, what, action, title);
7154  } else {
7155    retval = qf_add_entries(qi, qi->qf_curlist, list, title, action);
7156    if (retval == OK) {
7157      qf_list_changed(qf_get_curlist(qi));
7158    }
7159  }
7160
7161  decr_quickfix_busy();
7162
7163  return retval;
7164}
7165
7166static bool mark_quickfix_user_data(qf_info_T *qi, int copyID)
7167{
7168  bool abort = false;
7169  for (int i = 0; i < qi->qf_maxcount && !abort; i++) {
7170    qf_list_T *qfl = &qi->qf_lists[i];
7171    if (!qfl->qf_has_user_data) {
7172      continue;
7173    }
7174    qfline_T *qfp;
7175    int j;
7176    FOR_ALL_QFL_ITEMS(qfl, qfp, j) {
7177      typval_T *user_data = &qfp->qf_user_data;
7178      if (user_data != NULL && user_data->v_type != VAR_NUMBER
7179          && user_data->v_type != VAR_STRING && user_data->v_type != VAR_FLOAT) {
7180        abort = abort || set_ref_in_item(user_data, copyID, NULL, NULL);
7181      }
7182    }
7183  }
7184  return abort;
7185}
7186
7187/// Mark the quickfix context and callback function as in use for all the lists
7188/// in a quickfix stack.
7189static bool mark_quickfix_ctx(qf_info_T *qi, int copyID)
7190{
7191  bool abort = false;
7192
7193  for (int i = 0; i < qi->qf_maxcount && !abort; i++) {
7194    typval_T *ctx = qi->qf_lists[i].qf_ctx;
7195    if (ctx != NULL && ctx->v_type != VAR_NUMBER
7196        && ctx->v_type != VAR_STRING && ctx->v_type != VAR_FLOAT) {
7197      abort = set_ref_in_item(ctx, copyID, NULL, NULL);
7198    }
7199
7200    Callback *cb = &qi->qf_lists[i].qf_qftf_cb;
7201    abort = abort || set_ref_in_callback(cb, copyID, NULL, NULL);
7202  }
7203
7204  return abort;
7205}
7206
7207/// Mark the context of the quickfix list and the location lists (if present) as
7208/// "in use". So that garbage collection doesn't free the context.
7209bool set_ref_in_quickfix(int copyID)
7210{
7211  assert(ql_info != NULL);
7212  if (mark_quickfix_ctx(ql_info, copyID)
7213      || mark_quickfix_user_data(ql_info, copyID)
7214      || set_ref_in_callback(&p_qftf, copyID, NULL, NULL)) {
7215    return true;
7216  }
7217
7218  FOR_ALL_TAB_WINDOWS(tp, win) {
7219    if (win->w_llist != NULL) {
7220      if (mark_quickfix_ctx(win->w_llist, copyID)
7221          || mark_quickfix_user_data(win->w_llist, copyID)) {
7222        return true;
7223      }
7224    }
7225
7226    if (IS_LL_WINDOW(win) && (win->w_llist_ref->qf_refcount == 1)) {
7227      // In a location list window and none of the other windows is
7228      // referring to this location list. Mark the location list
7229      // context as still in use.
7230      if (mark_quickfix_ctx(win->w_llist_ref, copyID)
7231          || mark_quickfix_user_data(win->w_llist_ref, copyID)) {
7232        return true;
7233      }
7234    }
7235  }
7236
7237  return false;
7238}
7239
7240/// Return the autocmd name for the :cbuffer Ex commands
7241static char *cbuffer_get_auname(cmdidx_T cmdidx)
7242{
7243  switch (cmdidx) {
7244  case CMD_cbuffer:
7245    return "cbuffer";
7246  case CMD_cgetbuffer:
7247    return "cgetbuffer";
7248  case CMD_caddbuffer:
7249    return "caddbuffer";
7250  case CMD_lbuffer:
7251    return "lbuffer";
7252  case CMD_lgetbuffer:
7253    return "lgetbuffer";
7254  case CMD_laddbuffer:
7255    return "laddbuffer";
7256  default:
7257    return NULL;
7258  }
7259}
7260
7261/// Process and validate the arguments passed to the :cbuffer, :caddbuffer,
7262/// :cgetbuffer, :lbuffer, :laddbuffer, :lgetbuffer Ex commands.
7263static int cbuffer_process_args(exarg_T *eap, buf_T **bufp, linenr_T *line1, linenr_T *line2)
7264{
7265  buf_T *buf = NULL;
7266
7267  if (*eap->arg == NUL) {
7268    buf = curbuf;
7269  } else if (*skipwhite(skipdigits(eap->arg)) == NUL) {
7270    buf = buflist_findnr(atoi(eap->arg));
7271  }
7272
7273  if (buf == NULL) {
7274    emsg(_(e_invarg));
7275    return FAIL;
7276  }
7277
7278  if (buf->b_ml.ml_mfp == NULL) {
7279    emsg(_(e_buffer_is_not_loaded));
7280    return FAIL;
7281  }
7282
7283  if (eap->addr_count == 0) {
7284    eap->line1 = 1;
7285    eap->line2 = buf->b_ml.ml_line_count;
7286  }
7287
7288  if (eap->line1 < 1 || eap->line1 > buf->b_ml.ml_line_count
7289      || eap->line2 < 1 || eap->line2 > buf->b_ml.ml_line_count) {
7290    emsg(_(e_invrange));
7291    return FAIL;
7292  }
7293
7294  *line1 = eap->line1;
7295  *line2 = eap->line2;
7296  *bufp = buf;
7297
7298  return OK;
7299}
7300
7301// ":[range]cbuffer [bufnr]" command.
7302// ":[range]caddbuffer [bufnr]" command.
7303// ":[range]cgetbuffer [bufnr]" command.
7304// ":[range]lbuffer [bufnr]" command.
7305// ":[range]laddbuffer [bufnr]" command.
7306// ":[range]lgetbuffer [bufnr]" command.
7307void ex_cbuffer(exarg_T *eap)
7308{
7309  char *au_name = cbuffer_get_auname(eap->cmdidx);
7310  if (au_name != NULL && apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
7311                                        curbuf->b_fname, true, curbuf)) {
7312    if (aborting()) {
7313      return;
7314    }
7315  }
7316
7317  // Must come after autocommands.
7318  win_T *wp = NULL;
7319  qf_info_T *qi = qf_cmd_get_or_alloc_stack(eap, &wp);
7320
7321  buf_T *buf = NULL;
7322  linenr_T line1;
7323  linenr_T line2;
7324  if (cbuffer_process_args(eap, &buf, &line1, &line2) == FAIL) {
7325    return;
7326  }
7327
7328  char *qf_title = qf_cmdtitle(*eap->cmdlinep);
7329
7330  if (buf->b_sfname) {
7331    vim_snprintf(IObuff, IOSIZE, "%s (%s)", qf_title, buf->b_sfname);
7332    qf_title = IObuff;
7333  }
7334
7335  incr_quickfix_busy();
7336
7337  int res = qf_init_ext(qi, qi->qf_curlist, NULL, buf, NULL, p_efm,
7338                        (eap->cmdidx != CMD_caddbuffer
7339                         && eap->cmdidx != CMD_laddbuffer),
7340                        eap->line1, eap->line2, qf_title, NULL);
7341  if (qf_stack_empty(qi)) {
7342    decr_quickfix_busy();
7343    return;
7344  }
7345  if (res >= 0) {
7346    qf_list_changed(qf_get_curlist(qi));
7347  }
7348  // Remember the current quickfix list identifier, so that we can
7349  // check for autocommands changing the current quickfix list.
7350  unsigned save_qfid = qf_get_curlist(qi)->qf_id;
7351  if (au_name != NULL) {
7352    const buf_T *const curbuf_old = curbuf;
7353    apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, true, curbuf);
7354    if (curbuf != curbuf_old) {
7355      // Autocommands changed buffer, don't jump now, "qi" may
7356      // be invalid.
7357      res = 0;
7358    }
7359  }
7360  // Jump to the first error for new list and if autocmds didn't
7361  // free the list.
7362  if (res > 0 && (eap->cmdidx == CMD_cbuffer || eap->cmdidx == CMD_lbuffer)
7363      && qflist_valid(wp, save_qfid)) {
7364    // display the first error
7365    qf_jump_first(qi, save_qfid, eap->forceit);
7366  }
7367
7368  decr_quickfix_busy();
7369}
7370
7371/// Return the autocmd name for the :cexpr Ex commands.
7372static char *cexpr_get_auname(cmdidx_T cmdidx)
7373{
7374  switch (cmdidx) {
7375  case CMD_cexpr:
7376    return "cexpr";
7377  case CMD_cgetexpr:
7378    return "cgetexpr";
7379  case CMD_caddexpr:
7380    return "caddexpr";
7381  case CMD_lexpr:
7382    return "lexpr";
7383  case CMD_lgetexpr:
7384    return "lgetexpr";
7385  case CMD_laddexpr:
7386    return "laddexpr";
7387  default:
7388    return NULL;
7389  }
7390}
7391
7392static int trigger_cexpr_autocmd(int cmdidx)
7393{
7394  char *au_name = cexpr_get_auname(cmdidx);
7395  if (au_name != NULL && apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
7396                                        curbuf->b_fname, true, curbuf)) {
7397    if (aborting()) {
7398      return FAIL;
7399    }
7400  }
7401  return OK;
7402}
7403
7404int cexpr_core(const exarg_T *eap, typval_T *tv)
7405  FUNC_ATTR_NONNULL_ALL
7406{
7407  win_T *wp = NULL;
7408  qf_info_T *qi = qf_cmd_get_or_alloc_stack(eap, &wp);
7409
7410  if ((tv->v_type == VAR_STRING && tv->vval.v_string != NULL)
7411      || tv->v_type == VAR_LIST) {
7412    char *au_name = cexpr_get_auname(eap->cmdidx);
7413    incr_quickfix_busy();
7414    int res = qf_init_ext(qi, qi->qf_curlist, NULL, NULL, tv, p_efm,
7415                          (eap->cmdidx != CMD_caddexpr
7416                           && eap->cmdidx != CMD_laddexpr),
7417                          0, 0,
7418                          qf_cmdtitle(*eap->cmdlinep), NULL);
7419    if (qf_stack_empty(qi)) {
7420      decr_quickfix_busy();
7421      return FAIL;
7422    }
7423    if (res >= 0) {
7424      qf_list_changed(qf_get_curlist(qi));
7425    }
7426    // Remember the current quickfix list identifier, so that we can
7427    // check for autocommands changing the current quickfix list.
7428    unsigned save_qfid = qf_get_curlist(qi)->qf_id;
7429    if (au_name != NULL) {
7430      apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, true, curbuf);
7431    }
7432    // Jump to the first error for a new list and if autocmds didn't
7433    // free the list.
7434    if (res > 0
7435        && (eap->cmdidx == CMD_cexpr || eap->cmdidx == CMD_lexpr)
7436        && qflist_valid(wp, save_qfid)) {
7437      // display the first error
7438      qf_jump_first(qi, save_qfid, eap->forceit);
7439    }
7440    decr_quickfix_busy();
7441    return OK;
7442  } else {
7443    emsg(_("E777: String or List expected"));
7444  }
7445  return FAIL;
7446}
7447
7448/// ":cexpr {expr}", ":cgetexpr {expr}", ":caddexpr {expr}" command.
7449/// ":lexpr {expr}", ":lgetexpr {expr}", ":laddexpr {expr}" command.
7450/// Also: ":caddexpr", ":cgetexpr", "laddexpr" and "laddexpr".
7451void ex_cexpr(exarg_T *eap)
7452{
7453  if (trigger_cexpr_autocmd(eap->cmdidx) == FAIL) {
7454    return;
7455  }
7456
7457  // Evaluate the expression.  When the result is a string or a list we can
7458  // use it to fill the errorlist.
7459  typval_T *tv = eval_expr(eap->arg, eap);
7460  if (tv == NULL) {
7461    return;
7462  }
7463
7464  (void)cexpr_core(eap, tv);
7465  tv_free(tv);
7466}
7467
7468// Get the location list for ":lhelpgrep"
7469static qf_info_T *hgr_get_ll(bool *new_ll)
7470  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
7471{
7472  // If the current window is a help window, then use it, else find an existing help window
7473  win_T *wp = bt_help(curwin->w_buffer) ? curwin : qf_find_help_win();
7474
7475  qf_info_T *qi = wp == NULL ? NULL : wp->w_llist;
7476  if (qi == NULL) {
7477    // Allocate a new location list for help text matches
7478    qi = qf_alloc_stack(QFLT_LOCATION, 1);
7479    *new_ll = true;
7480  }
7481
7482  return qi;
7483}
7484
7485// Search for a pattern in a help file.
7486static void hgr_search_file(qf_list_T *qfl, char *fname, regmatch_T *p_regmatch)
7487  FUNC_ATTR_NONNULL_ARG(1, 3)
7488{
7489  FILE *const fd = os_fopen(fname, "r");
7490  if (fd == NULL) {
7491    return;
7492  }
7493
7494  linenr_T lnum = 1;
7495  while (!vim_fgets(IObuff, IOSIZE, fd) && !got_int) {
7496    char *line = IObuff;
7497
7498    if (vim_regexec(p_regmatch, line, 0)) {
7499      int l = (int)strlen(line);
7500
7501      // remove trailing CR, LF, spaces, etc.
7502      while (l > 0 && line[l - 1] <= ' ') {
7503        line[--l] = NUL;
7504      }
7505
7506      if (qf_add_entry(qfl,
7507                       NULL,   // dir
7508                       fname,
7509                       NULL,
7510                       0,
7511                       line,
7512                       lnum,
7513                       0,
7514                       (int)(p_regmatch->startp[0] - line) + 1,  // col
7515                       (int)(p_regmatch->endp[0] - line)
7516                       + 1,    // end_col
7517                       false,  // vis_col
7518                       NULL,   // search pattern
7519                       0,      // nr
7520                       1,      // type
7521                       NULL,   // user_data
7522                       true)   // valid
7523          == QF_FAIL) {
7524        got_int = true;
7525        if (line != IObuff) {
7526          xfree(line);
7527        }
7528        break;
7529      }
7530    }
7531    if (line != IObuff) {
7532      xfree(line);
7533    }
7534    lnum++;
7535    line_breakcheck();
7536  }
7537  fclose(fd);
7538}
7539
7540// Search for a pattern in all the help files in the doc directory under
7541// the given directory.
7542static void hgr_search_files_in_dir(qf_list_T *qfl, char *dirname, regmatch_T *p_regmatch,
7543                                    const char *lang)
7544  FUNC_ATTR_NONNULL_ARG(1, 2, 3)
7545{
7546  int fcount;
7547  char **fnames;
7548
7549  // Find all "*.txt" and "*.??x" files in the "doc" directory.
7550  add_pathsep(dirname);
7551  strcat(dirname, "doc/*.\\(txt\\|??x\\)");  // NOLINT
7552  if (gen_expand_wildcards(1, &dirname, &fcount, &fnames, EW_FILE|EW_SILENT) == OK
7553      && fcount > 0) {
7554    for (int fi = 0; fi < fcount && !got_int; fi++) {
7555      // Skip files for a different language.
7556      if (lang != NULL
7557          && STRNICMP(lang, fnames[fi] + strlen(fnames[fi]) - 3, 2) != 0
7558          && !(STRNICMP(lang, "en", 2) == 0
7559               && STRNICMP("txt", fnames[fi] + strlen(fnames[fi]) - 3, 3)
7560               == 0)) {
7561        continue;
7562      }
7563
7564      hgr_search_file(qfl, fnames[fi], p_regmatch);
7565    }
7566    FreeWild(fcount, fnames);
7567  }
7568}
7569
7570// Search for a pattern in all the help files in the 'runtimepath'
7571// and add the matches to a quickfix list.
7572// 'lang' is the language specifier.  If supplied, then only matches in the
7573// specified language are found.
7574static void hgr_search_in_rtp(qf_list_T *qfl, regmatch_T *p_regmatch, const char *lang)
7575  FUNC_ATTR_NONNULL_ARG(1, 2)
7576{
7577  // Go through all directories in 'runtimepath'
7578  char *p = p_rtp;
7579  while (*p != NUL && !got_int) {
7580    copy_option_part(&p, NameBuff, MAXPATHL, ",");
7581
7582    hgr_search_files_in_dir(qfl, NameBuff, p_regmatch, lang);
7583  }
7584}
7585
7586// ":helpgrep {pattern}"
7587void ex_helpgrep(exarg_T *eap)
7588{
7589  qf_info_T *qi = ql_info;
7590  assert(qi != NULL);
7591  char *au_name = NULL;
7592
7593  switch (eap->cmdidx) {
7594  case CMD_helpgrep:
7595    au_name = "helpgrep"; break;
7596  case CMD_lhelpgrep:
7597    au_name = "lhelpgrep"; break;
7598  default:
7599    break;
7600  }
7601  if (au_name != NULL && apply_autocmds(EVENT_QUICKFIXCMDPRE, au_name,
7602                                        curbuf->b_fname, true, curbuf)) {
7603    if (aborting()) {
7604      return;
7605    }
7606  }
7607
7608  bool updated = false;
7609  // Make 'cpoptions' empty, the 'l' flag should not be used here.
7610  char *const save_cpo = p_cpo;
7611  p_cpo = empty_string_option;
7612
7613  bool new_qi = false;
7614  if (is_loclist_cmd(eap->cmdidx)) {
7615    qi = hgr_get_ll(&new_qi);
7616  }
7617
7618  incr_quickfix_busy();
7619
7620  // Check for a specified language
7621  char *const lang = check_help_lang(eap->arg);
7622  regmatch_T regmatch = {
7623    .regprog = vim_regcomp(eap->arg, RE_MAGIC + RE_STRING),
7624    .rm_ic = false,
7625  };
7626  if (regmatch.regprog != NULL) {
7627    // Create a new quickfix list.
7628    qf_new_list(qi, qf_cmdtitle(*eap->cmdlinep));
7629    qf_list_T *const qfl = qf_get_curlist(qi);
7630
7631    hgr_search_in_rtp(qfl, &regmatch, lang);
7632
7633    vim_regfree(regmatch.regprog);
7634
7635    qfl->qf_nonevalid = false;
7636    qfl->qf_ptr = qfl->qf_start;
7637    qfl->qf_index = 1;
7638    qf_list_changed(qfl);
7639    updated = true;
7640  }
7641
7642  if (p_cpo == empty_string_option) {
7643    p_cpo = save_cpo;
7644  } else {
7645    // Darn, some plugin changed the value.  If it's still empty it was
7646    // changed and restored, need to restore in the complicated way.
7647    if (*p_cpo == NUL) {
7648      set_option_value_give_err(kOptCpoptions, CSTR_AS_OBJ(save_cpo), 0);
7649    }
7650    free_string_option(save_cpo);
7651  }
7652
7653  if (updated) {
7654    // This may open a window and source scripts, do this after 'cpo' was
7655    // restored.
7656    qf_update_buffer(qi, NULL);
7657  }
7658
7659  if (au_name != NULL) {
7660    apply_autocmds(EVENT_QUICKFIXCMDPOST, au_name, curbuf->b_fname, true, curbuf);
7661    // When adding a location list to an existing location list stack,
7662    // if the autocmd made the stack invalid, then just return.
7663    if (!new_qi && IS_LL_STACK(qi) && qf_find_win_with_loclist(qi) == NULL) {
7664      decr_quickfix_busy();
7665      return;
7666    }
7667  }
7668
7669  // Jump to first match.
7670  if (!qf_list_empty(qf_get_curlist(qi))) {
7671    qf_jump(qi, 0, 0, false);
7672  } else {
7673    semsg(_(e_nomatch2), eap->arg);
7674  }
7675
7676  decr_quickfix_busy();
7677
7678  if (eap->cmdidx == CMD_lhelpgrep) {
7679    // If the help window is not opened or if it already points to the
7680    // correct location list, then free the new location list.
7681    if (!bt_help(curwin->w_buffer) || curwin->w_llist == qi) {
7682      if (new_qi) {
7683        ll_free_all(&qi);
7684      }
7685    } else if (curwin->w_llist == NULL && new_qi) {
7686      // current window didn't have a location list associated with it
7687      // before. Associate the new location list now.
7688      curwin->w_llist = qi;
7689    }
7690  }
7691}
7692
7693#ifdef EXITFREE
7694void free_quickfix(void)
7695{
7696  qf_free_all(NULL);
7697  // Free all location lists
7698  FOR_ALL_TAB_WINDOWS(tab, win) {
7699    qf_free_all(win);
7700  }
7701
7702  callback_free(&p_qftf);
7703  ga_clear(&qfga);
7704}
7705#endif
7706
7707static void get_qf_loc_list(bool is_qf, win_T *wp, typval_T *what_arg, typval_T *rettv)
7708{
7709  if (what_arg->v_type == VAR_UNKNOWN) {
7710    tv_list_alloc_ret(rettv, kListLenMayKnow);
7711    if (is_qf || wp != NULL) {
7712      get_errorlist(NULL, wp, -1, 0, rettv->vval.v_list);
7713    }
7714  } else {
7715    tv_dict_alloc_ret(rettv);
7716    if (is_qf || wp != NULL) {
7717      if (what_arg->v_type == VAR_DICT) {
7718        dict_T *d = what_arg->vval.v_dict;
7719
7720        if (d != NULL) {
7721          qf_get_properties(wp, d, rettv->vval.v_dict);
7722        }
7723      } else {
7724        emsg(_(e_dictreq));
7725      }
7726    }
7727  }
7728}
7729
7730/// "getloclist()" function
7731void f_getloclist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7732{
7733  win_T *wp = find_win_by_nr_or_id(&argvars[0]);
7734  get_qf_loc_list(false, wp, &argvars[1], rettv);
7735}
7736
7737/// "getqflist()" functions
7738void f_getqflist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7739{
7740  get_qf_loc_list(true, NULL, &argvars[0], rettv);
7741}
7742
7743/// Create quickfix/location list from Vimscript values
7744///
7745/// Used by `setqflist()` and `setloclist()` functions. Accepts invalid
7746/// args argument in which case errors out, including VAR_UNKNOWN parameters.
7747///
7748/// @param[in,out]  wp  Window to create location list for. May be NULL in
7749///                     which case quickfix list will be created.
7750/// @param[in]  args  [list, action, what]
7751/// @param[in]  args[0]  Quickfix list contents.
7752/// @param[in]  args[1]  Optional. Action to perform:
7753///                      append to an existing list, replace its content,
7754///                      or create a new one.
7755/// @param[in]  args[2]  Optional. Quickfix list properties or title.
7756///                      Defaults to caller function name.
7757/// @param[out]  rettv  Return value: 0 in case of success, -1 otherwise.
7758static void set_qf_ll_list(win_T *wp, typval_T *args, typval_T *rettv)
7759  FUNC_ATTR_NONNULL_ARG(2, 3)
7760{
7761  static const char *e_invact = N_("E927: Invalid action: '%s'");
7762  const char *title = NULL;
7763  char action = ' ';
7764  static int recursive = 0;
7765  rettv->vval.v_number = -1;
7766  dict_T *what = NULL;
7767
7768  typval_T *list_arg = &args[0];
7769  if (list_arg->v_type != VAR_LIST) {
7770    emsg(_(e_listreq));
7771    return;
7772  } else if (recursive != 0) {
7773    emsg(_(e_au_recursive));
7774    return;
7775  }
7776
7777  typval_T *action_arg = &args[1];
7778  if (action_arg->v_type == VAR_UNKNOWN) {
7779    // Option argument was not given.
7780    goto skip_args;
7781  } else if (action_arg->v_type != VAR_STRING) {
7782    emsg(_(e_string_required));
7783    return;
7784  }
7785  const char *const act = tv_get_string_chk(action_arg);
7786  if ((*act == 'a' || *act == 'r' || *act == 'u' || *act == ' ' || *act == 'f')
7787      && act[1] == NUL) {
7788    action = *act;
7789  } else {
7790    semsg(_(e_invact), act);
7791    return;
7792  }
7793
7794  typval_T *const what_arg = &args[2];
7795  if (what_arg->v_type == VAR_UNKNOWN) {
7796    // Option argument was not given.
7797    goto skip_args;
7798  } else if (what_arg->v_type == VAR_STRING) {
7799    title = tv_get_string_chk(what_arg);
7800    if (!title) {
7801      // Type error. Error already printed by tv_get_string_chk().
7802      return;
7803    }
7804  } else if (what_arg->v_type == VAR_DICT && what_arg->vval.v_dict != NULL) {
7805    what = what_arg->vval.v_dict;
7806  } else {
7807    emsg(_(e_dictreq));
7808    return;
7809  }
7810
7811skip_args:
7812  if (!title) {
7813    title = (wp ? ":setloclist()" : ":setqflist()");
7814  }
7815
7816  recursive++;
7817  list_T *const l = list_arg->vval.v_list;
7818  if (set_errorlist(wp, l, action, (char *)title, what) == OK) {
7819    rettv->vval.v_number = 0;
7820  }
7821  recursive--;
7822}
7823
7824/// "setloclist()" function
7825void f_setloclist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7826{
7827  rettv->vval.v_number = -1;
7828
7829  win_T *win = find_win_by_nr_or_id(&argvars[0]);
7830  if (win != NULL) {
7831    set_qf_ll_list(win, &argvars[1], rettv);
7832  }
7833}
7834
7835/// "setqflist()" function
7836void f_setqflist(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
7837{
7838  set_qf_ll_list(NULL, argvars, rettv);
7839}