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