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