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