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