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