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