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