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