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