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