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