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