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