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