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