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