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