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