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