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