xref: /vim-8.2.3635/src/buffer.c (revision 200d0e36)
1 /* vi:set ts=8 sts=4 sw=4 noet:
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  * buffer.c: functions for dealing with the buffer structure
12  */
13 
14 /*
15  * The buffer list is a double linked list of all buffers.
16  * Each buffer can be in one of these states:
17  * never loaded: BF_NEVERLOADED is set, only the file name is valid
18  *   not loaded: b_ml.ml_mfp == NULL, no memfile allocated
19  *	 hidden: b_nwindows == 0, loaded but not displayed in a window
20  *	 normal: loaded and displayed in a window
21  *
22  * Instead of storing file names all over the place, each file name is
23  * stored in the buffer list. It can be referenced by a number.
24  *
25  * The current implementation remembers all file names ever used.
26  */
27 
28 #include "vim.h"
29 
30 #if defined(FEAT_CMDL_COMPL) || defined(FEAT_LISTCMDS) || defined(FEAT_EVAL) || defined(FEAT_PERL)
31 static char_u	*buflist_match(regmatch_T *rmp, buf_T *buf, int ignore_case);
32 # define HAVE_BUFLIST_MATCH
33 static char_u	*fname_match(regmatch_T *rmp, char_u *name, int ignore_case);
34 #endif
35 static void	buflist_setfpos(buf_T *buf, win_T *win, linenr_T lnum, colnr_T col, int copy_options);
36 static wininfo_T *find_wininfo(buf_T *buf, int skip_diff_buffer);
37 #ifdef UNIX
38 static buf_T	*buflist_findname_stat(char_u *ffname, stat_T *st);
39 static int	otherfile_buf(buf_T *buf, char_u *ffname, stat_T *stp);
40 static int	buf_same_ino(buf_T *buf, stat_T *stp);
41 #else
42 static int	otherfile_buf(buf_T *buf, char_u *ffname);
43 #endif
44 #ifdef FEAT_TITLE
45 static int	ti_change(char_u *str, char_u **last);
46 #endif
47 static int	append_arg_number(win_T *wp, char_u *buf, int buflen, int add_file);
48 static void	free_buffer(buf_T *);
49 static void	free_buffer_stuff(buf_T *buf, int free_options);
50 static void	clear_wininfo(buf_T *buf);
51 
52 #ifdef UNIX
53 # define dev_T dev_t
54 #else
55 # define dev_T unsigned
56 #endif
57 
58 #if defined(FEAT_SIGNS)
59 static void insert_sign(buf_T *buf, signlist_T *prev, signlist_T *next, int id, linenr_T lnum, int typenr);
60 #endif
61 
62 #if defined(FEAT_QUICKFIX)
63 static char *msg_loclist = N_("[Location List]");
64 static char *msg_qflist = N_("[Quickfix List]");
65 #endif
66 #ifdef FEAT_AUTOCMD
67 static char *e_auabort = N_("E855: Autocommands caused command to abort");
68 #endif
69 
70 /* Number of times free_buffer() was called. */
71 static int	buf_free_count = 0;
72 
73 /* Read data from buffer for retrying. */
74     static int
75 read_buffer(
76     int		read_stdin,	    /* read file from stdin, otherwise fifo */
77     exarg_T	*eap,		    /* for forced 'ff' and 'fenc' or NULL */
78     int		flags)		    /* extra flags for readfile() */
79 {
80     int		retval = OK;
81     linenr_T	line_count;
82 
83     /*
84      * Read from the buffer which the text is already filled in and append at
85      * the end.  This makes it possible to retry when 'fileformat' or
86      * 'fileencoding' was guessed wrong.
87      */
88     line_count = curbuf->b_ml.ml_line_count;
89     retval = readfile(
90 	    read_stdin ? NULL : curbuf->b_ffname,
91 	    read_stdin ? NULL : curbuf->b_fname,
92 	    (linenr_T)line_count, (linenr_T)0, (linenr_T)MAXLNUM, eap,
93 	    flags | READ_BUFFER);
94     if (retval == OK)
95     {
96 	/* Delete the binary lines. */
97 	while (--line_count >= 0)
98 	    ml_delete((linenr_T)1, FALSE);
99     }
100     else
101     {
102 	/* Delete the converted lines. */
103 	while (curbuf->b_ml.ml_line_count > line_count)
104 	    ml_delete(line_count, FALSE);
105     }
106     /* Put the cursor on the first line. */
107     curwin->w_cursor.lnum = 1;
108     curwin->w_cursor.col = 0;
109 
110     if (read_stdin)
111     {
112 	/* Set or reset 'modified' before executing autocommands, so that
113 	 * it can be changed there. */
114 	if (!readonlymode && !BUFEMPTY())
115 	    changed();
116 	else if (retval == OK)
117 	    unchanged(curbuf, FALSE);
118 
119 #ifdef FEAT_AUTOCMD
120 	if (retval == OK)
121 	{
122 # ifdef FEAT_EVAL
123 	    apply_autocmds_retval(EVENT_STDINREADPOST, NULL, NULL, FALSE,
124 							curbuf, &retval);
125 # else
126 	    apply_autocmds(EVENT_STDINREADPOST, NULL, NULL, FALSE, curbuf);
127 # endif
128 	}
129 #endif
130     }
131     return retval;
132 }
133 
134 /*
135  * Open current buffer, that is: open the memfile and read the file into
136  * memory.
137  * Return FAIL for failure, OK otherwise.
138  */
139     int
140 open_buffer(
141     int		read_stdin,	    /* read file from stdin */
142     exarg_T	*eap,		    /* for forced 'ff' and 'fenc' or NULL */
143     int		flags)		    /* extra flags for readfile() */
144 {
145     int		retval = OK;
146 #ifdef FEAT_AUTOCMD
147     bufref_T	old_curbuf;
148 #endif
149 #ifdef FEAT_SYN_HL
150     long	old_tw = curbuf->b_p_tw;
151 #endif
152     int		read_fifo = FALSE;
153 
154     /*
155      * The 'readonly' flag is only set when BF_NEVERLOADED is being reset.
156      * When re-entering the same buffer, it should not change, because the
157      * user may have reset the flag by hand.
158      */
159     if (readonlymode && curbuf->b_ffname != NULL
160 					&& (curbuf->b_flags & BF_NEVERLOADED))
161 	curbuf->b_p_ro = TRUE;
162 
163     if (ml_open(curbuf) == FAIL)
164     {
165 	/*
166 	 * There MUST be a memfile, otherwise we can't do anything
167 	 * If we can't create one for the current buffer, take another buffer
168 	 */
169 	close_buffer(NULL, curbuf, 0, FALSE);
170 	FOR_ALL_BUFFERS(curbuf)
171 	    if (curbuf->b_ml.ml_mfp != NULL)
172 		break;
173 	/*
174 	 * if there is no memfile at all, exit
175 	 * This is OK, since there are no changes to lose.
176 	 */
177 	if (curbuf == NULL)
178 	{
179 	    EMSG(_("E82: Cannot allocate any buffer, exiting..."));
180 	    getout(2);
181 	}
182 	EMSG(_("E83: Cannot allocate buffer, using other one..."));
183 	enter_buffer(curbuf);
184 #ifdef FEAT_SYN_HL
185 	if (old_tw != curbuf->b_p_tw)
186 	    check_colorcolumn(curwin);
187 #endif
188 	return FAIL;
189     }
190 
191 #ifdef FEAT_AUTOCMD
192     /* The autocommands in readfile() may change the buffer, but only AFTER
193      * reading the file. */
194     set_bufref(&old_curbuf, curbuf);
195     modified_was_set = FALSE;
196 #endif
197 
198     /* mark cursor position as being invalid */
199     curwin->w_valid = 0;
200 
201     if (curbuf->b_ffname != NULL
202 #ifdef FEAT_NETBEANS_INTG
203 	    && netbeansReadFile
204 #endif
205        )
206     {
207 	int old_msg_silent = msg_silent;
208 #ifdef UNIX
209 	int save_bin = curbuf->b_p_bin;
210 	int perm;
211 #endif
212 #ifdef FEAT_NETBEANS_INTG
213 	int oldFire = netbeansFireChanges;
214 
215 	netbeansFireChanges = 0;
216 #endif
217 #ifdef UNIX
218 	perm = mch_getperm(curbuf->b_ffname);
219 	if (perm >= 0 && (0
220 # ifdef S_ISFIFO
221 		      || S_ISFIFO(perm)
222 # endif
223 # ifdef S_ISSOCK
224 		      || S_ISSOCK(perm)
225 # endif
226 # ifdef OPEN_CHR_FILES
227 		      || (S_ISCHR(perm) && is_dev_fd_file(curbuf->b_ffname))
228 # endif
229 		    ))
230 		read_fifo = TRUE;
231 	if (read_fifo)
232 	    curbuf->b_p_bin = TRUE;
233 #endif
234 	if (shortmess(SHM_FILEINFO))
235 	    msg_silent = 1;
236 	retval = readfile(curbuf->b_ffname, curbuf->b_fname,
237 		  (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, eap,
238 		  flags | READ_NEW | (read_fifo ? READ_FIFO : 0));
239 #ifdef UNIX
240 	if (read_fifo)
241 	{
242 	    curbuf->b_p_bin = save_bin;
243 	    if (retval == OK)
244 		retval = read_buffer(FALSE, eap, flags);
245 	}
246 #endif
247 	msg_silent = old_msg_silent;
248 #ifdef FEAT_NETBEANS_INTG
249 	netbeansFireChanges = oldFire;
250 #endif
251 	/* Help buffer is filtered. */
252 	if (bt_help(curbuf))
253 	    fix_help_buffer();
254     }
255     else if (read_stdin)
256     {
257 	int	save_bin = curbuf->b_p_bin;
258 
259 	/*
260 	 * First read the text in binary mode into the buffer.
261 	 * Then read from that same buffer and append at the end.  This makes
262 	 * it possible to retry when 'fileformat' or 'fileencoding' was
263 	 * guessed wrong.
264 	 */
265 	curbuf->b_p_bin = TRUE;
266 	retval = readfile(NULL, NULL, (linenr_T)0,
267 		  (linenr_T)0, (linenr_T)MAXLNUM, NULL,
268 		  flags | (READ_NEW + READ_STDIN));
269 	curbuf->b_p_bin = save_bin;
270 	if (retval == OK)
271 	    retval = read_buffer(TRUE, eap, flags);
272     }
273 
274     /* if first time loading this buffer, init b_chartab[] */
275     if (curbuf->b_flags & BF_NEVERLOADED)
276     {
277 	(void)buf_init_chartab(curbuf, FALSE);
278 #ifdef FEAT_CINDENT
279 	parse_cino(curbuf);
280 #endif
281     }
282 
283     /*
284      * Set/reset the Changed flag first, autocmds may change the buffer.
285      * Apply the automatic commands, before processing the modelines.
286      * So the modelines have priority over auto commands.
287      */
288     /* When reading stdin, the buffer contents always needs writing, so set
289      * the changed flag.  Unless in readonly mode: "ls | gview -".
290      * When interrupted and 'cpoptions' contains 'i' set changed flag. */
291     if ((got_int && vim_strchr(p_cpo, CPO_INTMOD) != NULL)
292 #ifdef FEAT_AUTOCMD
293 		|| modified_was_set	/* ":set modified" used in autocmd */
294 # ifdef FEAT_EVAL
295 		|| (aborting() && vim_strchr(p_cpo, CPO_INTMOD) != NULL)
296 # endif
297 #endif
298        )
299 	changed();
300     else if (retval == OK && !read_stdin && !read_fifo)
301 	unchanged(curbuf, FALSE);
302     save_file_ff(curbuf);		/* keep this fileformat */
303 
304     /* require "!" to overwrite the file, because it wasn't read completely */
305 #ifdef FEAT_EVAL
306     if (aborting())
307 #else
308     if (got_int)
309 #endif
310 	curbuf->b_flags |= BF_READERR;
311 
312 #ifdef FEAT_FOLDING
313     /* Need to update automatic folding.  Do this before the autocommands,
314      * they may use the fold info. */
315     foldUpdateAll(curwin);
316 #endif
317 
318 #ifdef FEAT_AUTOCMD
319     /* need to set w_topline, unless some autocommand already did that. */
320     if (!(curwin->w_valid & VALID_TOPLINE))
321     {
322 	curwin->w_topline = 1;
323 # ifdef FEAT_DIFF
324 	curwin->w_topfill = 0;
325 # endif
326     }
327 # ifdef FEAT_EVAL
328     apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf, &retval);
329 # else
330     apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
331 # endif
332 #endif
333 
334     if (retval == OK)
335     {
336 #ifdef FEAT_AUTOCMD
337 	/*
338 	 * The autocommands may have changed the current buffer.  Apply the
339 	 * modelines to the correct buffer, if it still exists and is loaded.
340 	 */
341 	if (bufref_valid(&old_curbuf) && old_curbuf.br_buf->b_ml.ml_mfp != NULL)
342 	{
343 	    aco_save_T	aco;
344 
345 	    /* Go to the buffer that was opened. */
346 	    aucmd_prepbuf(&aco, old_curbuf.br_buf);
347 #endif
348 	    do_modelines(0);
349 	    curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED);
350 
351 #ifdef FEAT_AUTOCMD
352 # ifdef FEAT_EVAL
353 	    apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf,
354 								    &retval);
355 # else
356 	    apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
357 # endif
358 
359 	    /* restore curwin/curbuf and a few other things */
360 	    aucmd_restbuf(&aco);
361 	}
362 #endif
363     }
364 
365     return retval;
366 }
367 
368 /*
369  * Store "buf" in "bufref" and set the free count.
370  */
371     void
372 set_bufref(bufref_T *bufref, buf_T *buf)
373 {
374     bufref->br_buf = buf;
375     bufref->br_fnum = buf == NULL ? 0 : buf->b_fnum;
376     bufref->br_buf_free_count = buf_free_count;
377 }
378 
379 /*
380  * Return TRUE if "bufref->br_buf" points to the same buffer as when
381  * set_bufref() was called and it is a valid buffer.
382  * Only goes through the buffer list if buf_free_count changed.
383  * Also checks if b_fnum is still the same, a :bwipe followed by :new might get
384  * the same allocated memory, but it's a different buffer.
385  */
386     int
387 bufref_valid(bufref_T *bufref)
388 {
389     return bufref->br_buf_free_count == buf_free_count
390 	? TRUE : buf_valid(bufref->br_buf)
391 				  && bufref->br_fnum == bufref->br_buf->b_fnum;
392 }
393 
394 /*
395  * Return TRUE if "buf" points to a valid buffer (in the buffer list).
396  * This can be slow if there are many buffers, prefer using bufref_valid().
397  */
398     int
399 buf_valid(buf_T *buf)
400 {
401     buf_T	*bp;
402 
403     /* Assume that we more often have a recent buffer, start with the last
404      * one. */
405     for (bp = lastbuf; bp != NULL; bp = bp->b_prev)
406 	if (bp == buf)
407 	    return TRUE;
408     return FALSE;
409 }
410 
411 /*
412  * A hash table used to quickly lookup a buffer by its number.
413  */
414 static hashtab_T buf_hashtab;
415 
416     static void
417 buf_hashtab_add(buf_T *buf)
418 {
419     sprintf((char *)buf->b_key, "%x", buf->b_fnum);
420     if (hash_add(&buf_hashtab, buf->b_key) == FAIL)
421 	EMSG(_("E931: Buffer cannot be registered"));
422 }
423 
424     static void
425 buf_hashtab_remove(buf_T *buf)
426 {
427     hashitem_T *hi = hash_find(&buf_hashtab, buf->b_key);
428 
429     if (!HASHITEM_EMPTY(hi))
430 	hash_remove(&buf_hashtab, hi);
431 }
432 
433 /*
434  * Close the link to a buffer.
435  * "action" is used when there is no longer a window for the buffer.
436  * It can be:
437  * 0			buffer becomes hidden
438  * DOBUF_UNLOAD		buffer is unloaded
439  * DOBUF_DELETE		buffer is unloaded and removed from buffer list
440  * DOBUF_WIPE		buffer is unloaded and really deleted
441  * When doing all but the first one on the current buffer, the caller should
442  * get a new buffer very soon!
443  *
444  * The 'bufhidden' option can force freeing and deleting.
445  *
446  * When "abort_if_last" is TRUE then do not close the buffer if autocommands
447  * cause there to be only one window with this buffer.  e.g. when ":quit" is
448  * supposed to close the window but autocommands close all other windows.
449  */
450     void
451 close_buffer(
452     win_T	*win,		/* if not NULL, set b_last_cursor */
453     buf_T	*buf,
454     int		action,
455     int		abort_if_last UNUSED)
456 {
457 #ifdef FEAT_AUTOCMD
458     int		is_curbuf;
459     int		nwindows;
460     bufref_T	bufref;
461     int		is_curwin = (curwin != NULL && curwin->w_buffer == buf);
462     win_T	*the_curwin = curwin;
463     tabpage_T	*the_curtab = curtab;
464 #endif
465     int		unload_buf = (action != 0);
466     int		del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE);
467     int		wipe_buf = (action == DOBUF_WIPE);
468 
469     /*
470      * Force unloading or deleting when 'bufhidden' says so.
471      * The caller must take care of NOT deleting/freeing when 'bufhidden' is
472      * "hide" (otherwise we could never free or delete a buffer).
473      */
474     if (buf->b_p_bh[0] == 'd')		/* 'bufhidden' == "delete" */
475     {
476 	del_buf = TRUE;
477 	unload_buf = TRUE;
478     }
479     else if (buf->b_p_bh[0] == 'w')	/* 'bufhidden' == "wipe" */
480     {
481 	del_buf = TRUE;
482 	unload_buf = TRUE;
483 	wipe_buf = TRUE;
484     }
485     else if (buf->b_p_bh[0] == 'u')	/* 'bufhidden' == "unload" */
486 	unload_buf = TRUE;
487 
488 #ifdef FEAT_TERMINAL
489     if (bt_terminal(buf) && (buf->b_nwindows == 1 || del_buf))
490     {
491 	if (term_job_running(buf->b_term))
492 	{
493 	    if (wipe_buf || unload_buf)
494 		/* Wiping out or unloading a terminal buffer kills the job. */
495 		free_terminal(buf);
496 	    else
497 	    {
498 		/* The job keeps running, hide the buffer. */
499 		del_buf = FALSE;
500 		unload_buf = FALSE;
501 	    }
502 	}
503 	else
504 	{
505 	    /* A terminal buffer is wiped out if the job has finished. */
506 	    del_buf = TRUE;
507 	    unload_buf = TRUE;
508 	    wipe_buf = TRUE;
509 	}
510     }
511 #endif
512 
513 #ifdef FEAT_AUTOCMD
514     /* Disallow deleting the buffer when it is locked (already being closed or
515      * halfway a command that relies on it). Unloading is allowed. */
516     if (buf->b_locked > 0 && (del_buf || wipe_buf))
517     {
518 	EMSG(_("E937: Attempt to delete a buffer that is in use"));
519 	return;
520     }
521 #endif
522 
523     /* check no autocommands closed the window */
524     if (win != NULL && win_valid_any_tab(win))
525     {
526 	/* Set b_last_cursor when closing the last window for the buffer.
527 	 * Remember the last cursor position and window options of the buffer.
528 	 * This used to be only for the current window, but then options like
529 	 * 'foldmethod' may be lost with a ":only" command. */
530 	if (buf->b_nwindows == 1)
531 	    set_last_cursor(win);
532 	buflist_setfpos(buf, win,
533 		    win->w_cursor.lnum == 1 ? 0 : win->w_cursor.lnum,
534 		    win->w_cursor.col, TRUE);
535     }
536 
537 #ifdef FEAT_AUTOCMD
538     set_bufref(&bufref, buf);
539 
540     /* When the buffer is no longer in a window, trigger BufWinLeave */
541     if (buf->b_nwindows == 1)
542     {
543 	++buf->b_locked;
544 	if (apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
545 								  FALSE, buf)
546 		&& !bufref_valid(&bufref))
547 	{
548 	    /* Autocommands deleted the buffer. */
549 aucmd_abort:
550 	    EMSG(_(e_auabort));
551 	    return;
552 	}
553 	--buf->b_locked;
554 	if (abort_if_last && one_window())
555 	    /* Autocommands made this the only window. */
556 	    goto aucmd_abort;
557 
558 	/* When the buffer becomes hidden, but is not unloaded, trigger
559 	 * BufHidden */
560 	if (!unload_buf)
561 	{
562 	    ++buf->b_locked;
563 	    if (apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname,
564 								  FALSE, buf)
565 		    && !bufref_valid(&bufref))
566 		/* Autocommands deleted the buffer. */
567 		goto aucmd_abort;
568 	    --buf->b_locked;
569 	    if (abort_if_last && one_window())
570 		/* Autocommands made this the only window. */
571 		goto aucmd_abort;
572 	}
573 # ifdef FEAT_EVAL
574 	if (aborting())	    /* autocmds may abort script processing */
575 	    return;
576 # endif
577     }
578 
579     /* If the buffer was in curwin and the window has changed, go back to that
580      * window, if it still exists.  This avoids that ":edit x" triggering a
581      * "tabnext" BufUnload autocmd leaves a window behind without a buffer. */
582     if (is_curwin && curwin != the_curwin &&  win_valid_any_tab(the_curwin))
583     {
584 	block_autocmds();
585 	goto_tabpage_win(the_curtab, the_curwin);
586 	unblock_autocmds();
587     }
588 
589     nwindows = buf->b_nwindows;
590 #endif
591 
592     /* decrease the link count from windows (unless not in any window) */
593     if (buf->b_nwindows > 0)
594 	--buf->b_nwindows;
595 
596 #ifdef FEAT_DIFF
597     if (diffopt_hiddenoff() && !unload_buf && buf->b_nwindows == 0)
598     	diff_buf_delete(buf);	/* Clear 'diff' for hidden buffer. */
599 #endif
600 
601     /* Return when a window is displaying the buffer or when it's not
602      * unloaded. */
603     if (buf->b_nwindows > 0 || !unload_buf)
604 	return;
605 
606     /* Always remove the buffer when there is no file name. */
607     if (buf->b_ffname == NULL)
608 	del_buf = TRUE;
609 
610     /* When closing the current buffer stop Visual mode before freeing
611      * anything. */
612     if (buf == curbuf && VIsual_active
613 #if defined(EXITFREE)
614 	    && !entered_free_all_mem
615 #endif
616 	    )
617 	end_visual_mode();
618 
619     /*
620      * Free all things allocated for this buffer.
621      * Also calls the "BufDelete" autocommands when del_buf is TRUE.
622      */
623 #ifdef FEAT_AUTOCMD
624     /* Remember if we are closing the current buffer.  Restore the number of
625      * windows, so that autocommands in buf_freeall() don't get confused. */
626     is_curbuf = (buf == curbuf);
627     buf->b_nwindows = nwindows;
628 #endif
629 
630     buf_freeall(buf, (del_buf ? BFA_DEL : 0) + (wipe_buf ? BFA_WIPE : 0));
631 
632 #ifdef FEAT_AUTOCMD
633     /* Autocommands may have deleted the buffer. */
634     if (!bufref_valid(&bufref))
635 	return;
636 # ifdef FEAT_EVAL
637     if (aborting())	    /* autocmds may abort script processing */
638 	return;
639 # endif
640 
641     /*
642      * It's possible that autocommands change curbuf to the one being deleted.
643      * This might cause the previous curbuf to be deleted unexpectedly.  But
644      * in some cases it's OK to delete the curbuf, because a new one is
645      * obtained anyway.  Therefore only return if curbuf changed to the
646      * deleted buffer.
647      */
648     if (buf == curbuf && !is_curbuf)
649 	return;
650 
651     if (win_valid_any_tab(win) && win->w_buffer == buf)
652 	win->w_buffer = NULL;  /* make sure we don't use the buffer now */
653 
654     /* Autocommands may have opened or closed windows for this buffer.
655      * Decrement the count for the close we do here. */
656     if (buf->b_nwindows > 0)
657 	--buf->b_nwindows;
658 #endif
659 
660     /* Change directories when the 'acd' option is set. */
661     DO_AUTOCHDIR
662 
663     /*
664      * Remove the buffer from the list.
665      */
666     if (wipe_buf)
667     {
668 #ifdef FEAT_SUN_WORKSHOP
669 	if (usingSunWorkShop)
670 	    workshop_file_closed_lineno((char *)buf->b_ffname,
671 			(int)buf->b_last_cursor.lnum);
672 #endif
673 	vim_free(buf->b_ffname);
674 	vim_free(buf->b_sfname);
675 	if (buf->b_prev == NULL)
676 	    firstbuf = buf->b_next;
677 	else
678 	    buf->b_prev->b_next = buf->b_next;
679 	if (buf->b_next == NULL)
680 	    lastbuf = buf->b_prev;
681 	else
682 	    buf->b_next->b_prev = buf->b_prev;
683 	free_buffer(buf);
684     }
685     else
686     {
687 	if (del_buf)
688 	{
689 	    /* Free all internal variables and reset option values, to make
690 	     * ":bdel" compatible with Vim 5.7. */
691 	    free_buffer_stuff(buf, TRUE);
692 
693 	    /* Make it look like a new buffer. */
694 	    buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
695 
696 	    /* Init the options when loaded again. */
697 	    buf->b_p_initialized = FALSE;
698 	}
699 	buf_clear_file(buf);
700 	if (del_buf)
701 	    buf->b_p_bl = FALSE;
702     }
703 }
704 
705 /*
706  * Make buffer not contain a file.
707  */
708     void
709 buf_clear_file(buf_T *buf)
710 {
711     buf->b_ml.ml_line_count = 1;
712     unchanged(buf, TRUE);
713     buf->b_shortname = FALSE;
714     buf->b_p_eol = TRUE;
715     buf->b_start_eol = TRUE;
716 #ifdef FEAT_MBYTE
717     buf->b_p_bomb = FALSE;
718     buf->b_start_bomb = FALSE;
719 #endif
720     buf->b_ml.ml_mfp = NULL;
721     buf->b_ml.ml_flags = ML_EMPTY;		/* empty buffer */
722 #ifdef FEAT_NETBEANS_INTG
723     netbeans_deleted_all_lines(buf);
724 #endif
725 }
726 
727 /*
728  * buf_freeall() - free all things allocated for a buffer that are related to
729  * the file.  Careful: get here with "curwin" NULL when exiting.
730  * flags:
731  * BFA_DEL	  buffer is going to be deleted
732  * BFA_WIPE	  buffer is going to be wiped out
733  * BFA_KEEP_UNDO  do not free undo information
734  */
735     void
736 buf_freeall(buf_T *buf, int flags)
737 {
738 #ifdef FEAT_AUTOCMD
739     int		is_curbuf = (buf == curbuf);
740     bufref_T	bufref;
741     int		is_curwin = (curwin != NULL && curwin->w_buffer == buf);
742     win_T	*the_curwin = curwin;
743     tabpage_T	*the_curtab = curtab;
744 
745     /* Make sure the buffer isn't closed by autocommands. */
746     ++buf->b_locked;
747     set_bufref(&bufref, buf);
748     if (buf->b_ml.ml_mfp != NULL)
749     {
750 	if (apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname,
751 								  FALSE, buf)
752 		&& !bufref_valid(&bufref))
753 	    /* autocommands deleted the buffer */
754 	    return;
755     }
756     if ((flags & BFA_DEL) && buf->b_p_bl)
757     {
758 	if (apply_autocmds(EVENT_BUFDELETE, buf->b_fname, buf->b_fname,
759 								   FALSE, buf)
760 		&& !bufref_valid(&bufref))
761 	    /* autocommands deleted the buffer */
762 	    return;
763     }
764     if (flags & BFA_WIPE)
765     {
766 	if (apply_autocmds(EVENT_BUFWIPEOUT, buf->b_fname, buf->b_fname,
767 								  FALSE, buf)
768 		&& !bufref_valid(&bufref))
769 	    /* autocommands deleted the buffer */
770 	    return;
771     }
772     --buf->b_locked;
773 
774     /* If the buffer was in curwin and the window has changed, go back to that
775      * window, if it still exists.  This avoids that ":edit x" triggering a
776      * "tabnext" BufUnload autocmd leaves a window behind without a buffer. */
777     if (is_curwin && curwin != the_curwin &&  win_valid_any_tab(the_curwin))
778     {
779 	block_autocmds();
780 	goto_tabpage_win(the_curtab, the_curwin);
781 	unblock_autocmds();
782     }
783 
784 # ifdef FEAT_EVAL
785     if (aborting())	    /* autocmds may abort script processing */
786 	return;
787 # endif
788 
789     /*
790      * It's possible that autocommands change curbuf to the one being deleted.
791      * This might cause curbuf to be deleted unexpectedly.  But in some cases
792      * it's OK to delete the curbuf, because a new one is obtained anyway.
793      * Therefore only return if curbuf changed to the deleted buffer.
794      */
795     if (buf == curbuf && !is_curbuf)
796 	return;
797 #endif
798 #ifdef FEAT_DIFF
799     diff_buf_delete(buf);	    /* Can't use 'diff' for unloaded buffer. */
800 #endif
801 #ifdef FEAT_SYN_HL
802     /* Remove any ownsyntax, unless exiting. */
803     if (curwin != NULL && curwin->w_buffer == buf)
804 	reset_synblock(curwin);
805 #endif
806 
807 #ifdef FEAT_FOLDING
808     /* No folds in an empty buffer. */
809     {
810 	win_T		*win;
811 	tabpage_T	*tp;
812 
813 	FOR_ALL_TAB_WINDOWS(tp, win)
814 	    if (win->w_buffer == buf)
815 		clearFolding(win);
816     }
817 #endif
818 
819 #ifdef FEAT_TCL
820     tcl_buffer_free(buf);
821 #endif
822     ml_close(buf, TRUE);	    /* close and delete the memline/memfile */
823     buf->b_ml.ml_line_count = 0;    /* no lines in buffer */
824     if ((flags & BFA_KEEP_UNDO) == 0)
825     {
826 	u_blockfree(buf);	    /* free the memory allocated for undo */
827 	u_clearall(buf);	    /* reset all undo information */
828     }
829 #ifdef FEAT_SYN_HL
830     syntax_clear(&buf->b_s);	    /* reset syntax info */
831 #endif
832     buf->b_flags &= ~BF_READERR;    /* a read error is no longer relevant */
833 }
834 
835 /*
836  * Free a buffer structure and the things it contains related to the buffer
837  * itself (not the file, that must have been done already).
838  */
839     static void
840 free_buffer(buf_T *buf)
841 {
842     ++buf_free_count;
843     free_buffer_stuff(buf, TRUE);
844 #ifdef FEAT_EVAL
845     /* b:changedtick uses an item in buf_T, remove it now */
846     dictitem_remove(buf->b_vars, (dictitem_T *)&buf->b_ct_di);
847     unref_var_dict(buf->b_vars);
848 #endif
849 #ifdef FEAT_LUA
850     lua_buffer_free(buf);
851 #endif
852 #ifdef FEAT_MZSCHEME
853     mzscheme_buffer_free(buf);
854 #endif
855 #ifdef FEAT_PERL
856     perl_buf_free(buf);
857 #endif
858 #ifdef FEAT_PYTHON
859     python_buffer_free(buf);
860 #endif
861 #ifdef FEAT_PYTHON3
862     python3_buffer_free(buf);
863 #endif
864 #ifdef FEAT_RUBY
865     ruby_buffer_free(buf);
866 #endif
867 #ifdef FEAT_JOB_CHANNEL
868     channel_buffer_free(buf);
869 #endif
870 #ifdef FEAT_TERMINAL
871     free_terminal(buf);
872 #endif
873 
874     buf_hashtab_remove(buf);
875 
876 #ifdef FEAT_AUTOCMD
877     aubuflocal_remove(buf);
878 
879     if (autocmd_busy)
880     {
881 	/* Do not free the buffer structure while autocommands are executing,
882 	 * it's still needed. Free it when autocmd_busy is reset. */
883 	buf->b_next = au_pending_free_buf;
884 	au_pending_free_buf = buf;
885     }
886     else
887 #endif
888 	vim_free(buf);
889 }
890 
891 /*
892  * Initializes b:changedtick.
893  */
894     static void
895 init_changedtick(buf_T *buf)
896 {
897     dictitem_T *di = (dictitem_T *)&buf->b_ct_di;
898 
899     di->di_flags = DI_FLAGS_FIX | DI_FLAGS_RO;
900     di->di_tv.v_type = VAR_NUMBER;
901     di->di_tv.v_lock = VAR_FIXED;
902     di->di_tv.vval.v_number = 0;
903 
904 #ifdef FEAT_EVAL
905     STRCPY(buf->b_ct_di.di_key, "changedtick");
906     (void)dict_add(buf->b_vars, di);
907 #endif
908 }
909 
910 /*
911  * Free stuff in the buffer for ":bdel" and when wiping out the buffer.
912  */
913     static void
914 free_buffer_stuff(
915     buf_T	*buf,
916     int		free_options)		/* free options as well */
917 {
918     if (free_options)
919     {
920 	clear_wininfo(buf);		/* including window-local options */
921 	free_buf_options(buf, TRUE);
922 #ifdef FEAT_SPELL
923 	ga_clear(&buf->b_s.b_langp);
924 #endif
925     }
926 #ifdef FEAT_EVAL
927     {
928 	varnumber_T tick = CHANGEDTICK(buf);
929 
930 	vars_clear(&buf->b_vars->dv_hashtab); /* free all buffer variables */
931 	hash_init(&buf->b_vars->dv_hashtab);
932 	init_changedtick(buf);
933 	CHANGEDTICK(buf) = tick;
934     }
935 #endif
936 #ifdef FEAT_USR_CMDS
937     uc_clear(&buf->b_ucmds);		/* clear local user commands */
938 #endif
939 #ifdef FEAT_SIGNS
940     buf_delete_signs(buf);		/* delete any signs */
941 #endif
942 #ifdef FEAT_NETBEANS_INTG
943     netbeans_file_killed(buf);
944 #endif
945 #ifdef FEAT_LOCALMAP
946     map_clear_int(buf, MAP_ALL_MODES, TRUE, FALSE);  /* clear local mappings */
947     map_clear_int(buf, MAP_ALL_MODES, TRUE, TRUE);   /* clear local abbrevs */
948 #endif
949 #ifdef FEAT_MBYTE
950     vim_free(buf->b_start_fenc);
951     buf->b_start_fenc = NULL;
952 #endif
953 }
954 
955 /*
956  * Free the b_wininfo list for buffer "buf".
957  */
958     static void
959 clear_wininfo(buf_T *buf)
960 {
961     wininfo_T	*wip;
962 
963     while (buf->b_wininfo != NULL)
964     {
965 	wip = buf->b_wininfo;
966 	buf->b_wininfo = wip->wi_next;
967 	if (wip->wi_optset)
968 	{
969 	    clear_winopt(&wip->wi_opt);
970 #ifdef FEAT_FOLDING
971 	    deleteFoldRecurse(&wip->wi_folds);
972 #endif
973 	}
974 	vim_free(wip);
975     }
976 }
977 
978 #if defined(FEAT_LISTCMDS) || defined(PROTO)
979 /*
980  * Go to another buffer.  Handles the result of the ATTENTION dialog.
981  */
982     void
983 goto_buffer(
984     exarg_T	*eap,
985     int		start,
986     int		dir,
987     int		count)
988 {
989 # if defined(HAS_SWAP_EXISTS_ACTION)
990     bufref_T	old_curbuf;
991 
992     set_bufref(&old_curbuf, curbuf);
993 
994     swap_exists_action = SEA_DIALOG;
995 # endif
996     (void)do_buffer(*eap->cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
997 					     start, dir, count, eap->forceit);
998 # if defined(HAS_SWAP_EXISTS_ACTION)
999     if (swap_exists_action == SEA_QUIT && *eap->cmd == 's')
1000     {
1001 #  if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1002 	cleanup_T   cs;
1003 
1004 	/* Reset the error/interrupt/exception state here so that
1005 	 * aborting() returns FALSE when closing a window. */
1006 	enter_cleanup(&cs);
1007 #  endif
1008 
1009 	/* Quitting means closing the split window, nothing else. */
1010 	win_close(curwin, TRUE);
1011 	swap_exists_action = SEA_NONE;
1012 	swap_exists_did_quit = TRUE;
1013 
1014 #  if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1015 	/* Restore the error/interrupt/exception state if not discarded by a
1016 	 * new aborting error, interrupt, or uncaught exception. */
1017 	leave_cleanup(&cs);
1018 #  endif
1019     }
1020     else
1021 	handle_swap_exists(&old_curbuf);
1022 # endif
1023 }
1024 #endif
1025 
1026 #if defined(HAS_SWAP_EXISTS_ACTION) || defined(PROTO)
1027 /*
1028  * Handle the situation of swap_exists_action being set.
1029  * It is allowed for "old_curbuf" to be NULL or invalid.
1030  */
1031     void
1032 handle_swap_exists(bufref_T *old_curbuf)
1033 {
1034 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1035     cleanup_T	cs;
1036 # endif
1037 #ifdef FEAT_SYN_HL
1038     long	old_tw = curbuf->b_p_tw;
1039 #endif
1040     buf_T	*buf;
1041 
1042     if (swap_exists_action == SEA_QUIT)
1043     {
1044 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1045 	/* Reset the error/interrupt/exception state here so that
1046 	 * aborting() returns FALSE when closing a buffer. */
1047 	enter_cleanup(&cs);
1048 # endif
1049 
1050 	/* User selected Quit at ATTENTION prompt.  Go back to previous
1051 	 * buffer.  If that buffer is gone or the same as the current one,
1052 	 * open a new, empty buffer. */
1053 	swap_exists_action = SEA_NONE;	/* don't want it again */
1054 	swap_exists_did_quit = TRUE;
1055 	close_buffer(curwin, curbuf, DOBUF_UNLOAD, FALSE);
1056 	if (old_curbuf == NULL || !bufref_valid(old_curbuf)
1057 					      || old_curbuf->br_buf == curbuf)
1058 	    buf = buflist_new(NULL, NULL, 1L, BLN_CURBUF | BLN_LISTED);
1059 	else
1060 	    buf = old_curbuf->br_buf;
1061 	if (buf != NULL)
1062 	{
1063 	    enter_buffer(buf);
1064 #ifdef FEAT_SYN_HL
1065 	    if (old_tw != curbuf->b_p_tw)
1066 		check_colorcolumn(curwin);
1067 #endif
1068 	}
1069 	/* If "old_curbuf" is NULL we are in big trouble here... */
1070 
1071 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1072 	/* Restore the error/interrupt/exception state if not discarded by a
1073 	 * new aborting error, interrupt, or uncaught exception. */
1074 	leave_cleanup(&cs);
1075 # endif
1076     }
1077     else if (swap_exists_action == SEA_RECOVER)
1078     {
1079 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1080 	/* Reset the error/interrupt/exception state here so that
1081 	 * aborting() returns FALSE when closing a buffer. */
1082 	enter_cleanup(&cs);
1083 # endif
1084 
1085 	/* User selected Recover at ATTENTION prompt. */
1086 	msg_scroll = TRUE;
1087 	ml_recover();
1088 	MSG_PUTS("\n");	/* don't overwrite the last message */
1089 	cmdline_row = msg_row;
1090 	do_modelines(0);
1091 
1092 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1093 	/* Restore the error/interrupt/exception state if not discarded by a
1094 	 * new aborting error, interrupt, or uncaught exception. */
1095 	leave_cleanup(&cs);
1096 # endif
1097     }
1098     swap_exists_action = SEA_NONE;
1099 }
1100 #endif
1101 
1102 #if defined(FEAT_LISTCMDS) || defined(PROTO)
1103 /*
1104  * do_bufdel() - delete or unload buffer(s)
1105  *
1106  * addr_count == 0: ":bdel" - delete current buffer
1107  * addr_count == 1: ":N bdel" or ":bdel N [N ..]" - first delete
1108  *		    buffer "end_bnr", then any other arguments.
1109  * addr_count == 2: ":N,N bdel" - delete buffers in range
1110  *
1111  * command can be DOBUF_UNLOAD (":bunload"), DOBUF_WIPE (":bwipeout") or
1112  * DOBUF_DEL (":bdel")
1113  *
1114  * Returns error message or NULL
1115  */
1116     char_u *
1117 do_bufdel(
1118     int		command,
1119     char_u	*arg,		/* pointer to extra arguments */
1120     int		addr_count,
1121     int		start_bnr,	/* first buffer number in a range */
1122     int		end_bnr,	/* buffer nr or last buffer nr in a range */
1123     int		forceit)
1124 {
1125     int		do_current = 0;	/* delete current buffer? */
1126     int		deleted = 0;	/* number of buffers deleted */
1127     char_u	*errormsg = NULL; /* return value */
1128     int		bnr;		/* buffer number */
1129     char_u	*p;
1130 
1131     if (addr_count == 0)
1132     {
1133 	(void)do_buffer(command, DOBUF_CURRENT, FORWARD, 0, forceit);
1134     }
1135     else
1136     {
1137 	if (addr_count == 2)
1138 	{
1139 	    if (*arg)		/* both range and argument is not allowed */
1140 		return (char_u *)_(e_trailing);
1141 	    bnr = start_bnr;
1142 	}
1143 	else	/* addr_count == 1 */
1144 	    bnr = end_bnr;
1145 
1146 	for ( ;!got_int; ui_breakcheck())
1147 	{
1148 	    /*
1149 	     * delete the current buffer last, otherwise when the
1150 	     * current buffer is deleted, the next buffer becomes
1151 	     * the current one and will be loaded, which may then
1152 	     * also be deleted, etc.
1153 	     */
1154 	    if (bnr == curbuf->b_fnum)
1155 		do_current = bnr;
1156 	    else if (do_buffer(command, DOBUF_FIRST, FORWARD, (int)bnr,
1157 							       forceit) == OK)
1158 		++deleted;
1159 
1160 	    /*
1161 	     * find next buffer number to delete/unload
1162 	     */
1163 	    if (addr_count == 2)
1164 	    {
1165 		if (++bnr > end_bnr)
1166 		    break;
1167 	    }
1168 	    else    /* addr_count == 1 */
1169 	    {
1170 		arg = skipwhite(arg);
1171 		if (*arg == NUL)
1172 		    break;
1173 		if (!VIM_ISDIGIT(*arg))
1174 		{
1175 		    p = skiptowhite_esc(arg);
1176 		    bnr = buflist_findpat(arg, p, command == DOBUF_WIPE,
1177 								FALSE, FALSE);
1178 		    if (bnr < 0)	    /* failed */
1179 			break;
1180 		    arg = p;
1181 		}
1182 		else
1183 		    bnr = getdigits(&arg);
1184 	    }
1185 	}
1186 	if (!got_int && do_current && do_buffer(command, DOBUF_FIRST,
1187 					  FORWARD, do_current, forceit) == OK)
1188 	    ++deleted;
1189 
1190 	if (deleted == 0)
1191 	{
1192 	    if (command == DOBUF_UNLOAD)
1193 		STRCPY(IObuff, _("E515: No buffers were unloaded"));
1194 	    else if (command == DOBUF_DEL)
1195 		STRCPY(IObuff, _("E516: No buffers were deleted"));
1196 	    else
1197 		STRCPY(IObuff, _("E517: No buffers were wiped out"));
1198 	    errormsg = IObuff;
1199 	}
1200 	else if (deleted >= p_report)
1201 	{
1202 	    if (command == DOBUF_UNLOAD)
1203 	    {
1204 		if (deleted == 1)
1205 		    MSG(_("1 buffer unloaded"));
1206 		else
1207 		    smsg((char_u *)_("%d buffers unloaded"), deleted);
1208 	    }
1209 	    else if (command == DOBUF_DEL)
1210 	    {
1211 		if (deleted == 1)
1212 		    MSG(_("1 buffer deleted"));
1213 		else
1214 		    smsg((char_u *)_("%d buffers deleted"), deleted);
1215 	    }
1216 	    else
1217 	    {
1218 		if (deleted == 1)
1219 		    MSG(_("1 buffer wiped out"));
1220 		else
1221 		    smsg((char_u *)_("%d buffers wiped out"), deleted);
1222 	    }
1223 	}
1224     }
1225 
1226 
1227     return errormsg;
1228 }
1229 #endif /* FEAT_LISTCMDS */
1230 
1231 #if defined(FEAT_LISTCMDS) || defined(FEAT_PYTHON) \
1232 	|| defined(FEAT_PYTHON3) || defined(PROTO)
1233 
1234 static int	empty_curbuf(int close_others, int forceit, int action);
1235 
1236 /*
1237  * Make the current buffer empty.
1238  * Used when it is wiped out and it's the last buffer.
1239  */
1240     static int
1241 empty_curbuf(
1242     int close_others,
1243     int forceit,
1244     int action)
1245 {
1246     int	    retval;
1247     buf_T   *buf = curbuf;
1248     bufref_T bufref;
1249 
1250     if (action == DOBUF_UNLOAD)
1251     {
1252 	EMSG(_("E90: Cannot unload last buffer"));
1253 	return FAIL;
1254     }
1255 
1256     set_bufref(&bufref, buf);
1257     if (close_others)
1258 	/* Close any other windows on this buffer, then make it empty. */
1259 	close_windows(buf, TRUE);
1260 
1261     setpcmark();
1262     retval = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE,
1263 					  forceit ? ECMD_FORCEIT : 0, curwin);
1264 
1265     /*
1266      * do_ecmd() may create a new buffer, then we have to delete
1267      * the old one.  But do_ecmd() may have done that already, check
1268      * if the buffer still exists.
1269      */
1270     if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows == 0)
1271 	close_buffer(NULL, buf, action, FALSE);
1272     if (!close_others)
1273 	need_fileinfo = FALSE;
1274     return retval;
1275 }
1276 /*
1277  * Implementation of the commands for the buffer list.
1278  *
1279  * action == DOBUF_GOTO	    go to specified buffer
1280  * action == DOBUF_SPLIT    split window and go to specified buffer
1281  * action == DOBUF_UNLOAD   unload specified buffer(s)
1282  * action == DOBUF_DEL	    delete specified buffer(s) from buffer list
1283  * action == DOBUF_WIPE	    delete specified buffer(s) really
1284  *
1285  * start == DOBUF_CURRENT   go to "count" buffer from current buffer
1286  * start == DOBUF_FIRST	    go to "count" buffer from first buffer
1287  * start == DOBUF_LAST	    go to "count" buffer from last buffer
1288  * start == DOBUF_MOD	    go to "count" modified buffer from current buffer
1289  *
1290  * Return FAIL or OK.
1291  */
1292     int
1293 do_buffer(
1294     int		action,
1295     int		start,
1296     int		dir,		/* FORWARD or BACKWARD */
1297     int		count,		/* buffer number or number of buffers */
1298     int		forceit)	/* TRUE for :...! */
1299 {
1300     buf_T	*buf;
1301     buf_T	*bp;
1302     int		unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1303 						     || action == DOBUF_WIPE);
1304 
1305     switch (start)
1306     {
1307 	case DOBUF_FIRST:   buf = firstbuf; break;
1308 	case DOBUF_LAST:    buf = lastbuf;  break;
1309 	default:	    buf = curbuf;   break;
1310     }
1311     if (start == DOBUF_MOD)	    /* find next modified buffer */
1312     {
1313 	while (count-- > 0)
1314 	{
1315 	    do
1316 	    {
1317 		buf = buf->b_next;
1318 		if (buf == NULL)
1319 		    buf = firstbuf;
1320 	    }
1321 	    while (buf != curbuf && !bufIsChanged(buf));
1322 	}
1323 	if (!bufIsChanged(buf))
1324 	{
1325 	    EMSG(_("E84: No modified buffer found"));
1326 	    return FAIL;
1327 	}
1328     }
1329     else if (start == DOBUF_FIRST && count) /* find specified buffer number */
1330     {
1331 	while (buf != NULL && buf->b_fnum != count)
1332 	    buf = buf->b_next;
1333     }
1334     else
1335     {
1336 	bp = NULL;
1337 	while (count > 0 || (!unload && !buf->b_p_bl && bp != buf))
1338 	{
1339 	    /* remember the buffer where we start, we come back there when all
1340 	     * buffers are unlisted. */
1341 	    if (bp == NULL)
1342 		bp = buf;
1343 	    if (dir == FORWARD)
1344 	    {
1345 		buf = buf->b_next;
1346 		if (buf == NULL)
1347 		    buf = firstbuf;
1348 	    }
1349 	    else
1350 	    {
1351 		buf = buf->b_prev;
1352 		if (buf == NULL)
1353 		    buf = lastbuf;
1354 	    }
1355 	    /* don't count unlisted buffers */
1356 	    if (unload || buf->b_p_bl)
1357 	    {
1358 		 --count;
1359 		 bp = NULL;	/* use this buffer as new starting point */
1360 	    }
1361 	    if (bp == buf)
1362 	    {
1363 		/* back where we started, didn't find anything. */
1364 		EMSG(_("E85: There is no listed buffer"));
1365 		return FAIL;
1366 	    }
1367 	}
1368     }
1369 
1370     if (buf == NULL)	    /* could not find it */
1371     {
1372 	if (start == DOBUF_FIRST)
1373 	{
1374 	    /* don't warn when deleting */
1375 	    if (!unload)
1376 		EMSGN(_(e_nobufnr), count);
1377 	}
1378 	else if (dir == FORWARD)
1379 	    EMSG(_("E87: Cannot go beyond last buffer"));
1380 	else
1381 	    EMSG(_("E88: Cannot go before first buffer"));
1382 	return FAIL;
1383     }
1384 
1385 #ifdef FEAT_GUI
1386     need_mouse_correct = TRUE;
1387 #endif
1388 
1389 #ifdef FEAT_LISTCMDS
1390     /*
1391      * delete buffer buf from memory and/or the list
1392      */
1393     if (unload)
1394     {
1395 	int	forward;
1396 	bufref_T bufref;
1397 
1398 	set_bufref(&bufref, buf);
1399 
1400 	/* When unloading or deleting a buffer that's already unloaded and
1401 	 * unlisted: fail silently. */
1402 	if (action != DOBUF_WIPE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl)
1403 	    return FAIL;
1404 
1405 	if (!forceit && bufIsChanged(buf))
1406 	{
1407 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1408 	    if ((p_confirm || cmdmod.confirm) && p_write)
1409 	    {
1410 		dialog_changed(buf, FALSE);
1411 # ifdef FEAT_AUTOCMD
1412 		if (!bufref_valid(&bufref))
1413 		    /* Autocommand deleted buffer, oops!  It's not changed
1414 		     * now. */
1415 		    return FAIL;
1416 # endif
1417 		/* If it's still changed fail silently, the dialog already
1418 		 * mentioned why it fails. */
1419 		if (bufIsChanged(buf))
1420 		    return FAIL;
1421 	    }
1422 	    else
1423 #endif
1424 	    {
1425 		EMSGN(_("E89: No write since last change for buffer %ld (add ! to override)"),
1426 								 buf->b_fnum);
1427 		return FAIL;
1428 	    }
1429 	}
1430 
1431 	/* When closing the current buffer stop Visual mode. */
1432 	if (buf == curbuf && VIsual_active)
1433 	    end_visual_mode();
1434 
1435 	/*
1436 	 * If deleting the last (listed) buffer, make it empty.
1437 	 * The last (listed) buffer cannot be unloaded.
1438 	 */
1439 	FOR_ALL_BUFFERS(bp)
1440 	    if (bp->b_p_bl && bp != buf)
1441 		break;
1442 	if (bp == NULL && buf == curbuf)
1443 	    return empty_curbuf(TRUE, forceit, action);
1444 
1445 	/*
1446 	 * If the deleted buffer is the current one, close the current window
1447 	 * (unless it's the only window).  Repeat this so long as we end up in
1448 	 * a window with this buffer.
1449 	 */
1450 	while (buf == curbuf
1451 #ifdef FEAT_AUTOCMD
1452 		   && !(curwin->w_closing || curwin->w_buffer->b_locked > 0)
1453 #endif
1454 		   && (!ONE_WINDOW || first_tabpage->tp_next != NULL))
1455 	{
1456 	    if (win_close(curwin, FALSE) == FAIL)
1457 		break;
1458 	}
1459 
1460 	/*
1461 	 * If the buffer to be deleted is not the current one, delete it here.
1462 	 */
1463 	if (buf != curbuf)
1464 	{
1465 	    close_windows(buf, FALSE);
1466 	    if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows <= 0)
1467 		    close_buffer(NULL, buf, action, FALSE);
1468 	    return OK;
1469 	}
1470 
1471 	/*
1472 	 * Deleting the current buffer: Need to find another buffer to go to.
1473 	 * There should be another, otherwise it would have been handled
1474 	 * above.  However, autocommands may have deleted all buffers.
1475 	 * First use au_new_curbuf.br_buf, if it is valid.
1476 	 * Then prefer the buffer we most recently visited.
1477 	 * Else try to find one that is loaded, after the current buffer,
1478 	 * then before the current buffer.
1479 	 * Finally use any buffer.
1480 	 */
1481 	buf = NULL;	/* selected buffer */
1482 	bp = NULL;	/* used when no loaded buffer found */
1483 #ifdef FEAT_AUTOCMD
1484 	if (au_new_curbuf.br_buf != NULL && bufref_valid(&au_new_curbuf))
1485 	    buf = au_new_curbuf.br_buf;
1486 # ifdef FEAT_JUMPLIST
1487 	else
1488 # endif
1489 #endif
1490 #ifdef FEAT_JUMPLIST
1491 	    if (curwin->w_jumplistlen > 0)
1492 	{
1493 	    int     jumpidx;
1494 
1495 	    jumpidx = curwin->w_jumplistidx - 1;
1496 	    if (jumpidx < 0)
1497 		jumpidx = curwin->w_jumplistlen - 1;
1498 
1499 	    forward = jumpidx;
1500 	    while (jumpidx != curwin->w_jumplistidx)
1501 	    {
1502 		buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum);
1503 		if (buf != NULL)
1504 		{
1505 		    if (buf == curbuf || !buf->b_p_bl)
1506 			buf = NULL;	/* skip current and unlisted bufs */
1507 		    else if (buf->b_ml.ml_mfp == NULL)
1508 		    {
1509 			/* skip unloaded buf, but may keep it for later */
1510 			if (bp == NULL)
1511 			    bp = buf;
1512 			buf = NULL;
1513 		    }
1514 		}
1515 		if (buf != NULL)   /* found a valid buffer: stop searching */
1516 		    break;
1517 		/* advance to older entry in jump list */
1518 		if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen)
1519 		    break;
1520 		if (--jumpidx < 0)
1521 		    jumpidx = curwin->w_jumplistlen - 1;
1522 		if (jumpidx == forward)		/* List exhausted for sure */
1523 		    break;
1524 	    }
1525 	}
1526 #endif
1527 
1528 	if (buf == NULL)	/* No previous buffer, Try 2'nd approach */
1529 	{
1530 	    forward = TRUE;
1531 	    buf = curbuf->b_next;
1532 	    for (;;)
1533 	    {
1534 		if (buf == NULL)
1535 		{
1536 		    if (!forward)	/* tried both directions */
1537 			break;
1538 		    buf = curbuf->b_prev;
1539 		    forward = FALSE;
1540 		    continue;
1541 		}
1542 		/* in non-help buffer, try to skip help buffers, and vv */
1543 		if (buf->b_help == curbuf->b_help && buf->b_p_bl)
1544 		{
1545 		    if (buf->b_ml.ml_mfp != NULL)   /* found loaded buffer */
1546 			break;
1547 		    if (bp == NULL)	/* remember unloaded buf for later */
1548 			bp = buf;
1549 		}
1550 		if (forward)
1551 		    buf = buf->b_next;
1552 		else
1553 		    buf = buf->b_prev;
1554 	    }
1555 	}
1556 	if (buf == NULL)	/* No loaded buffer, use unloaded one */
1557 	    buf = bp;
1558 	if (buf == NULL)	/* No loaded buffer, find listed one */
1559 	{
1560 	    FOR_ALL_BUFFERS(buf)
1561 		if (buf->b_p_bl && buf != curbuf)
1562 		    break;
1563 	}
1564 	if (buf == NULL)	/* Still no buffer, just take one */
1565 	{
1566 	    if (curbuf->b_next != NULL)
1567 		buf = curbuf->b_next;
1568 	    else
1569 		buf = curbuf->b_prev;
1570 	}
1571     }
1572 
1573     if (buf == NULL)
1574     {
1575 	/* Autocommands must have wiped out all other buffers.  Only option
1576 	 * now is to make the current buffer empty. */
1577 	return empty_curbuf(FALSE, forceit, action);
1578     }
1579 
1580     /*
1581      * make buf current buffer
1582      */
1583     if (action == DOBUF_SPLIT)	    /* split window first */
1584     {
1585 	/* If 'switchbuf' contains "useopen": jump to first window containing
1586 	 * "buf" if one exists */
1587 	if ((swb_flags & SWB_USEOPEN) && buf_jump_open_win(buf))
1588 	    return OK;
1589 	/* If 'switchbuf' contains "usetab": jump to first window in any tab
1590 	 * page containing "buf" if one exists */
1591 	if ((swb_flags & SWB_USETAB) && buf_jump_open_tab(buf))
1592 	    return OK;
1593 	if (win_split(0, 0) == FAIL)
1594 	    return FAIL;
1595     }
1596 #endif
1597 
1598     /* go to current buffer - nothing to do */
1599     if (buf == curbuf)
1600 	return OK;
1601 
1602     /*
1603      * Check if the current buffer may be abandoned.
1604      */
1605     if (action == DOBUF_GOTO && !can_abandon(curbuf, forceit))
1606     {
1607 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1608 	if ((p_confirm || cmdmod.confirm) && p_write)
1609 	{
1610 # ifdef FEAT_AUTOCMD
1611 	    bufref_T bufref;
1612 
1613 	    set_bufref(&bufref, buf);
1614 # endif
1615 	    dialog_changed(curbuf, FALSE);
1616 # ifdef FEAT_AUTOCMD
1617 	    if (!bufref_valid(&bufref))
1618 		/* Autocommand deleted buffer, oops! */
1619 		return FAIL;
1620 # endif
1621 	}
1622 	if (bufIsChanged(curbuf))
1623 #endif
1624 	{
1625 	    no_write_message();
1626 	    return FAIL;
1627 	}
1628     }
1629 
1630     /* Go to the other buffer. */
1631     set_curbuf(buf, action);
1632 
1633 #if defined(FEAT_LISTCMDS) \
1634 	&& (defined(FEAT_SCROLLBIND) || defined(FEAT_CURSORBIND))
1635     if (action == DOBUF_SPLIT)
1636     {
1637 	RESET_BINDING(curwin);	/* reset 'scrollbind' and 'cursorbind' */
1638     }
1639 #endif
1640 
1641 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1642     if (aborting())	    /* autocmds may abort script processing */
1643 	return FAIL;
1644 #endif
1645 
1646     return OK;
1647 }
1648 #endif
1649 
1650 /*
1651  * Set current buffer to "buf".  Executes autocommands and closes current
1652  * buffer.  "action" tells how to close the current buffer:
1653  * DOBUF_GOTO	    free or hide it
1654  * DOBUF_SPLIT	    nothing
1655  * DOBUF_UNLOAD	    unload it
1656  * DOBUF_DEL	    delete it
1657  * DOBUF_WIPE	    wipe it out
1658  */
1659     void
1660 set_curbuf(buf_T *buf, int action)
1661 {
1662     buf_T	*prevbuf;
1663     int		unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1664 						     || action == DOBUF_WIPE);
1665 #ifdef FEAT_SYN_HL
1666     long	old_tw = curbuf->b_p_tw;
1667 #endif
1668     bufref_T	bufref;
1669 
1670     setpcmark();
1671     if (!cmdmod.keepalt)
1672 	curwin->w_alt_fnum = curbuf->b_fnum; /* remember alternate file */
1673     buflist_altfpos(curwin);			 /* remember curpos */
1674 
1675     /* Don't restart Select mode after switching to another buffer. */
1676     VIsual_reselect = FALSE;
1677 
1678     /* close_windows() or apply_autocmds() may change curbuf */
1679     prevbuf = curbuf;
1680     set_bufref(&bufref, prevbuf);
1681 
1682 #ifdef FEAT_AUTOCMD
1683     if (!apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf)
1684 # ifdef FEAT_EVAL
1685 	    || (bufref_valid(&bufref) && !aborting())
1686 # else
1687 	    || bufref_valid(&bufref)
1688 # endif
1689        )
1690 #endif
1691     {
1692 #ifdef FEAT_SYN_HL
1693 	if (prevbuf == curwin->w_buffer)
1694 	    reset_synblock(curwin);
1695 #endif
1696 	if (unload)
1697 	    close_windows(prevbuf, FALSE);
1698 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1699 	if (bufref_valid(&bufref) && !aborting())
1700 #else
1701 	if (bufref_valid(&bufref))
1702 #endif
1703 	{
1704 	    win_T  *previouswin = curwin;
1705 	    if (prevbuf == curbuf)
1706 		u_sync(FALSE);
1707 	    close_buffer(prevbuf == curwin->w_buffer ? curwin : NULL, prevbuf,
1708 		    unload ? action : (action == DOBUF_GOTO
1709 			&& !buf_hide(prevbuf)
1710 			&& !bufIsChanged(prevbuf)) ? DOBUF_UNLOAD : 0, FALSE);
1711 	    if (curwin != previouswin && win_valid(previouswin))
1712 	      /* autocommands changed curwin, Grr! */
1713 	      curwin = previouswin;
1714 	}
1715     }
1716 #ifdef FEAT_AUTOCMD
1717     /* An autocommand may have deleted "buf", already entered it (e.g., when
1718      * it did ":bunload") or aborted the script processing.
1719      * If curwin->w_buffer is null, enter_buffer() will make it valid again */
1720     if ((buf_valid(buf) && buf != curbuf
1721 # ifdef FEAT_EVAL
1722 		&& !aborting()
1723 # endif
1724 	) || curwin->w_buffer == NULL)
1725 #endif
1726     {
1727 	enter_buffer(buf);
1728 #ifdef FEAT_SYN_HL
1729 	if (old_tw != curbuf->b_p_tw)
1730 	    check_colorcolumn(curwin);
1731 #endif
1732     }
1733 }
1734 
1735 /*
1736  * Enter a new current buffer.
1737  * Old curbuf must have been abandoned already!  This also means "curbuf" may
1738  * be pointing to freed memory.
1739  */
1740     void
1741 enter_buffer(buf_T *buf)
1742 {
1743     /* Copy buffer and window local option values.  Not for a help buffer. */
1744     buf_copy_options(buf, BCO_ENTER | BCO_NOHELP);
1745     if (!buf->b_help)
1746 	get_winopts(buf);
1747 #ifdef FEAT_FOLDING
1748     else
1749 	/* Remove all folds in the window. */
1750 	clearFolding(curwin);
1751     foldUpdateAll(curwin);	/* update folds (later). */
1752 #endif
1753 
1754     /* Get the buffer in the current window. */
1755     curwin->w_buffer = buf;
1756     curbuf = buf;
1757     ++curbuf->b_nwindows;
1758 
1759 #ifdef FEAT_DIFF
1760     if (curwin->w_p_diff)
1761 	diff_buf_add(curbuf);
1762 #endif
1763 
1764 #ifdef FEAT_SYN_HL
1765     curwin->w_s = &(curbuf->b_s);
1766 #endif
1767 
1768     /* Cursor on first line by default. */
1769     curwin->w_cursor.lnum = 1;
1770     curwin->w_cursor.col = 0;
1771 #ifdef FEAT_VIRTUALEDIT
1772     curwin->w_cursor.coladd = 0;
1773 #endif
1774     curwin->w_set_curswant = TRUE;
1775 #ifdef FEAT_AUTOCMD
1776     curwin->w_topline_was_set = FALSE;
1777 #endif
1778 
1779     /* mark cursor position as being invalid */
1780     curwin->w_valid = 0;
1781 
1782     /* Make sure the buffer is loaded. */
1783     if (curbuf->b_ml.ml_mfp == NULL)	/* need to load the file */
1784     {
1785 #ifdef FEAT_AUTOCMD
1786 	/* If there is no filetype, allow for detecting one.  Esp. useful for
1787 	 * ":ball" used in a autocommand.  If there already is a filetype we
1788 	 * might prefer to keep it. */
1789 	if (*curbuf->b_p_ft == NUL)
1790 	    did_filetype = FALSE;
1791 #endif
1792 
1793 	open_buffer(FALSE, NULL, 0);
1794     }
1795     else
1796     {
1797 	if (!msg_silent)
1798 	    need_fileinfo = TRUE;	/* display file info after redraw */
1799 	(void)buf_check_timestamp(curbuf, FALSE); /* check if file changed */
1800 #ifdef FEAT_AUTOCMD
1801 	curwin->w_topline = 1;
1802 # ifdef FEAT_DIFF
1803 	curwin->w_topfill = 0;
1804 # endif
1805 	apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
1806 	apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
1807 #endif
1808     }
1809 
1810     /* If autocommands did not change the cursor position, restore cursor lnum
1811      * and possibly cursor col. */
1812     if (curwin->w_cursor.lnum == 1 && inindent(0))
1813 	buflist_getfpos();
1814 
1815     check_arg_idx(curwin);		/* check for valid arg_idx */
1816 #ifdef FEAT_TITLE
1817     maketitle();
1818 #endif
1819 #ifdef FEAT_AUTOCMD
1820 	/* when autocmds didn't change it */
1821     if (curwin->w_topline == 1 && !curwin->w_topline_was_set)
1822 #endif
1823 	scroll_cursor_halfway(FALSE);	/* redisplay at correct position */
1824 
1825 #ifdef FEAT_NETBEANS_INTG
1826     /* Send fileOpened event because we've changed buffers. */
1827     netbeans_file_activated(curbuf);
1828 #endif
1829 
1830     /* Change directories when the 'acd' option is set. */
1831     DO_AUTOCHDIR
1832 
1833 #ifdef FEAT_KEYMAP
1834     if (curbuf->b_kmap_state & KEYMAP_INIT)
1835 	(void)keymap_init();
1836 #endif
1837 #ifdef FEAT_SPELL
1838     /* May need to set the spell language.  Can only do this after the buffer
1839      * has been properly setup. */
1840     if (!curbuf->b_help && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
1841 	(void)did_set_spelllang(curwin);
1842 #endif
1843 #ifdef FEAT_VIMINFO
1844     curbuf->b_last_used = vim_time();
1845 #endif
1846 
1847     redraw_later(NOT_VALID);
1848 }
1849 
1850 #if defined(FEAT_AUTOCHDIR) || defined(PROTO)
1851 /*
1852  * Change to the directory of the current buffer.
1853  * Don't do this while still starting up.
1854  */
1855     void
1856 do_autochdir(void)
1857 {
1858     if ((starting == 0 || test_autochdir)
1859 	    && curbuf->b_ffname != NULL
1860 	    && vim_chdirfile(curbuf->b_ffname) == OK)
1861 	shorten_fnames(TRUE);
1862 }
1863 #endif
1864 
1865     void
1866 no_write_message(void)
1867 {
1868 #ifdef FEAT_TERMINAL
1869     if (term_job_running(curbuf->b_term))
1870 	EMSG(_("E948: Job still running (add ! to end the job)"));
1871     else
1872 #endif
1873 	EMSG(_("E37: No write since last change (add ! to override)"));
1874 }
1875 
1876     void
1877 no_write_message_nobang(void)
1878 {
1879 #ifdef FEAT_TERMINAL
1880     if (term_job_running(curbuf->b_term))
1881 	EMSG(_("E948: Job still running"));
1882     else
1883 #endif
1884 	EMSG(_("E37: No write since last change"));
1885 }
1886 
1887 /*
1888  * functions for dealing with the buffer list
1889  */
1890 
1891 static int  top_file_num = 1;		/* highest file number */
1892 
1893 /*
1894  * Add a file name to the buffer list.  Return a pointer to the buffer.
1895  * If the same file name already exists return a pointer to that buffer.
1896  * If it does not exist, or if fname == NULL, a new entry is created.
1897  * If (flags & BLN_CURBUF) is TRUE, may use current buffer.
1898  * If (flags & BLN_LISTED) is TRUE, add new buffer to buffer list.
1899  * If (flags & BLN_DUMMY) is TRUE, don't count it as a real buffer.
1900  * If (flags & BLN_NEW) is TRUE, don't use an existing buffer.
1901  * If (flags & BLN_NOOPT) is TRUE, don't copy options from the current buffer
1902  *				    if the buffer already exists.
1903  * This is the ONLY way to create a new buffer.
1904  */
1905     buf_T *
1906 buflist_new(
1907     char_u	*ffname,	/* full path of fname or relative */
1908     char_u	*sfname,	/* short fname or NULL */
1909     linenr_T	lnum,		/* preferred cursor line */
1910     int		flags)		/* BLN_ defines */
1911 {
1912     buf_T	*buf;
1913 #ifdef UNIX
1914     stat_T	st;
1915 #endif
1916 
1917     if (top_file_num == 1)
1918 	hash_init(&buf_hashtab);
1919 
1920     fname_expand(curbuf, &ffname, &sfname);	/* will allocate ffname */
1921 
1922     /*
1923      * If file name already exists in the list, update the entry.
1924      */
1925 #ifdef UNIX
1926     /* On Unix we can use inode numbers when the file exists.  Works better
1927      * for hard links. */
1928     if (sfname == NULL || mch_stat((char *)sfname, &st) < 0)
1929 	st.st_dev = (dev_T)-1;
1930 #endif
1931     if (ffname != NULL && !(flags & (BLN_DUMMY | BLN_NEW)) && (buf =
1932 #ifdef UNIX
1933 		buflist_findname_stat(ffname, &st)
1934 #else
1935 		buflist_findname(ffname)
1936 #endif
1937 		) != NULL)
1938     {
1939 	vim_free(ffname);
1940 	if (lnum != 0)
1941 	    buflist_setfpos(buf, curwin, lnum, (colnr_T)0, FALSE);
1942 
1943 	if ((flags & BLN_NOOPT) == 0)
1944 	    /* copy the options now, if 'cpo' doesn't have 's' and not done
1945 	     * already */
1946 	    buf_copy_options(buf, 0);
1947 
1948 	if ((flags & BLN_LISTED) && !buf->b_p_bl)
1949 	{
1950 #ifdef FEAT_AUTOCMD
1951 	    bufref_T bufref;
1952 #endif
1953 	    buf->b_p_bl = TRUE;
1954 #ifdef FEAT_AUTOCMD
1955 	    set_bufref(&bufref, buf);
1956 	    if (!(flags & BLN_DUMMY))
1957 	    {
1958 		if (apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf)
1959 			&& !bufref_valid(&bufref))
1960 		    return NULL;
1961 	    }
1962 #endif
1963 	}
1964 	return buf;
1965     }
1966 
1967     /*
1968      * If the current buffer has no name and no contents, use the current
1969      * buffer.	Otherwise: Need to allocate a new buffer structure.
1970      *
1971      * This is the ONLY place where a new buffer structure is allocated!
1972      * (A spell file buffer is allocated in spell.c, but that's not a normal
1973      * buffer.)
1974      */
1975     buf = NULL;
1976     if ((flags & BLN_CURBUF)
1977 	    && curbuf != NULL
1978 	    && curbuf->b_ffname == NULL
1979 	    && curbuf->b_nwindows <= 1
1980 	    && (curbuf->b_ml.ml_mfp == NULL || BUFEMPTY()))
1981     {
1982 	buf = curbuf;
1983 #ifdef FEAT_AUTOCMD
1984 	/* It's like this buffer is deleted.  Watch out for autocommands that
1985 	 * change curbuf!  If that happens, allocate a new buffer anyway. */
1986 	if (curbuf->b_p_bl)
1987 	    apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
1988 	if (buf == curbuf)
1989 	    apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
1990 # ifdef FEAT_EVAL
1991 	if (aborting())		/* autocmds may abort script processing */
1992 	    return NULL;
1993 # endif
1994 #endif
1995 #ifdef FEAT_AUTOCMD
1996 	if (buf == curbuf)
1997 #endif
1998 	{
1999 	    /* Make sure 'bufhidden' and 'buftype' are empty */
2000 	    clear_string_option(&buf->b_p_bh);
2001 	    clear_string_option(&buf->b_p_bt);
2002 	}
2003     }
2004     if (buf != curbuf || curbuf == NULL)
2005     {
2006 	buf = (buf_T *)alloc_clear((unsigned)sizeof(buf_T));
2007 	if (buf == NULL)
2008 	{
2009 	    vim_free(ffname);
2010 	    return NULL;
2011 	}
2012 #ifdef FEAT_EVAL
2013 	/* init b: variables */
2014 	buf->b_vars = dict_alloc();
2015 	if (buf->b_vars == NULL)
2016 	{
2017 	    vim_free(ffname);
2018 	    vim_free(buf);
2019 	    return NULL;
2020 	}
2021 	init_var_dict(buf->b_vars, &buf->b_bufvar, VAR_SCOPE);
2022 #endif
2023 	init_changedtick(buf);
2024     }
2025 
2026     if (ffname != NULL)
2027     {
2028 	buf->b_ffname = ffname;
2029 	buf->b_sfname = vim_strsave(sfname);
2030     }
2031 
2032     clear_wininfo(buf);
2033     buf->b_wininfo = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T));
2034 
2035     if ((ffname != NULL && (buf->b_ffname == NULL || buf->b_sfname == NULL))
2036 	    || buf->b_wininfo == NULL)
2037     {
2038 	vim_free(buf->b_ffname);
2039 	buf->b_ffname = NULL;
2040 	vim_free(buf->b_sfname);
2041 	buf->b_sfname = NULL;
2042 	if (buf != curbuf)
2043 	    free_buffer(buf);
2044 	return NULL;
2045     }
2046 
2047     if (buf == curbuf)
2048     {
2049 	/* free all things allocated for this buffer */
2050 	buf_freeall(buf, 0);
2051 	if (buf != curbuf)	 /* autocommands deleted the buffer! */
2052 	    return NULL;
2053 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
2054 	if (aborting())		/* autocmds may abort script processing */
2055 	    return NULL;
2056 #endif
2057 	free_buffer_stuff(buf, FALSE);	/* delete local variables et al. */
2058 
2059 	/* Init the options. */
2060 	buf->b_p_initialized = FALSE;
2061 	buf_copy_options(buf, BCO_ENTER);
2062 
2063 #ifdef FEAT_KEYMAP
2064 	/* need to reload lmaps and set b:keymap_name */
2065 	curbuf->b_kmap_state |= KEYMAP_INIT;
2066 #endif
2067     }
2068     else
2069     {
2070 	/*
2071 	 * put new buffer at the end of the buffer list
2072 	 */
2073 	buf->b_next = NULL;
2074 	if (firstbuf == NULL)		/* buffer list is empty */
2075 	{
2076 	    buf->b_prev = NULL;
2077 	    firstbuf = buf;
2078 	}
2079 	else				/* append new buffer at end of list */
2080 	{
2081 	    lastbuf->b_next = buf;
2082 	    buf->b_prev = lastbuf;
2083 	}
2084 	lastbuf = buf;
2085 
2086 	buf->b_fnum = top_file_num++;
2087 	if (top_file_num < 0)		/* wrap around (may cause duplicates) */
2088 	{
2089 	    EMSG(_("W14: Warning: List of file names overflow"));
2090 	    if (emsg_silent == 0)
2091 	    {
2092 		out_flush();
2093 		ui_delay(3000L, TRUE);	/* make sure it is noticed */
2094 	    }
2095 	    top_file_num = 1;
2096 	}
2097 	buf_hashtab_add(buf);
2098 
2099 	/*
2100 	 * Always copy the options from the current buffer.
2101 	 */
2102 	buf_copy_options(buf, BCO_ALWAYS);
2103     }
2104 
2105     buf->b_wininfo->wi_fpos.lnum = lnum;
2106     buf->b_wininfo->wi_win = curwin;
2107 
2108 #ifdef FEAT_SYN_HL
2109     hash_init(&buf->b_s.b_keywtab);
2110     hash_init(&buf->b_s.b_keywtab_ic);
2111 #endif
2112 
2113     buf->b_fname = buf->b_sfname;
2114 #ifdef UNIX
2115     if (st.st_dev == (dev_T)-1)
2116 	buf->b_dev_valid = FALSE;
2117     else
2118     {
2119 	buf->b_dev_valid = TRUE;
2120 	buf->b_dev = st.st_dev;
2121 	buf->b_ino = st.st_ino;
2122     }
2123 #endif
2124     buf->b_u_synced = TRUE;
2125     buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
2126     if (flags & BLN_DUMMY)
2127 	buf->b_flags |= BF_DUMMY;
2128     buf_clear_file(buf);
2129     clrallmarks(buf);			/* clear marks */
2130     fmarks_check_names(buf);		/* check file marks for this file */
2131     buf->b_p_bl = (flags & BLN_LISTED) ? TRUE : FALSE;	/* init 'buflisted' */
2132 #ifdef FEAT_AUTOCMD
2133     if (!(flags & BLN_DUMMY))
2134     {
2135 	bufref_T bufref;
2136 
2137 	/* Tricky: these autocommands may change the buffer list.  They could
2138 	 * also split the window with re-using the one empty buffer. This may
2139 	 * result in unexpectedly losing the empty buffer. */
2140 	set_bufref(&bufref, buf);
2141 	if (apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, buf)
2142 		&& !bufref_valid(&bufref))
2143 	    return NULL;
2144 	if (flags & BLN_LISTED)
2145 	{
2146 	    if (apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf)
2147 		    && !bufref_valid(&bufref))
2148 		return NULL;
2149 	}
2150 # ifdef FEAT_EVAL
2151 	if (aborting())		/* autocmds may abort script processing */
2152 	    return NULL;
2153 # endif
2154     }
2155 #endif
2156 
2157     return buf;
2158 }
2159 
2160 /*
2161  * Free the memory for the options of a buffer.
2162  * If "free_p_ff" is TRUE also free 'fileformat', 'buftype' and
2163  * 'fileencoding'.
2164  */
2165     void
2166 free_buf_options(
2167     buf_T	*buf,
2168     int		free_p_ff)
2169 {
2170     if (free_p_ff)
2171     {
2172 #ifdef FEAT_MBYTE
2173 	clear_string_option(&buf->b_p_fenc);
2174 #endif
2175 	clear_string_option(&buf->b_p_ff);
2176 	clear_string_option(&buf->b_p_bh);
2177 	clear_string_option(&buf->b_p_bt);
2178     }
2179 #ifdef FEAT_FIND_ID
2180     clear_string_option(&buf->b_p_def);
2181     clear_string_option(&buf->b_p_inc);
2182 # ifdef FEAT_EVAL
2183     clear_string_option(&buf->b_p_inex);
2184 # endif
2185 #endif
2186 #if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
2187     clear_string_option(&buf->b_p_inde);
2188     clear_string_option(&buf->b_p_indk);
2189 #endif
2190 #if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
2191     clear_string_option(&buf->b_p_bexpr);
2192 #endif
2193 #if defined(FEAT_CRYPT)
2194     clear_string_option(&buf->b_p_cm);
2195 #endif
2196     clear_string_option(&buf->b_p_fp);
2197 #if defined(FEAT_EVAL)
2198     clear_string_option(&buf->b_p_fex);
2199 #endif
2200 #ifdef FEAT_CRYPT
2201     clear_string_option(&buf->b_p_key);
2202 #endif
2203     clear_string_option(&buf->b_p_kp);
2204     clear_string_option(&buf->b_p_mps);
2205     clear_string_option(&buf->b_p_fo);
2206     clear_string_option(&buf->b_p_flp);
2207     clear_string_option(&buf->b_p_isk);
2208 #ifdef FEAT_KEYMAP
2209     clear_string_option(&buf->b_p_keymap);
2210     ga_clear(&buf->b_kmap_ga);
2211 #endif
2212 #ifdef FEAT_COMMENTS
2213     clear_string_option(&buf->b_p_com);
2214 #endif
2215 #ifdef FEAT_FOLDING
2216     clear_string_option(&buf->b_p_cms);
2217 #endif
2218     clear_string_option(&buf->b_p_nf);
2219 #ifdef FEAT_SYN_HL
2220     clear_string_option(&buf->b_p_syn);
2221     clear_string_option(&buf->b_s.b_syn_isk);
2222 #endif
2223 #ifdef FEAT_SPELL
2224     clear_string_option(&buf->b_s.b_p_spc);
2225     clear_string_option(&buf->b_s.b_p_spf);
2226     vim_regfree(buf->b_s.b_cap_prog);
2227     buf->b_s.b_cap_prog = NULL;
2228     clear_string_option(&buf->b_s.b_p_spl);
2229 #endif
2230 #ifdef FEAT_SEARCHPATH
2231     clear_string_option(&buf->b_p_sua);
2232 #endif
2233 #ifdef FEAT_AUTOCMD
2234     clear_string_option(&buf->b_p_ft);
2235 #endif
2236 #ifdef FEAT_CINDENT
2237     clear_string_option(&buf->b_p_cink);
2238     clear_string_option(&buf->b_p_cino);
2239 #endif
2240 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
2241     clear_string_option(&buf->b_p_cinw);
2242 #endif
2243 #ifdef FEAT_INS_EXPAND
2244     clear_string_option(&buf->b_p_cpt);
2245 #endif
2246 #ifdef FEAT_COMPL_FUNC
2247     clear_string_option(&buf->b_p_cfu);
2248     clear_string_option(&buf->b_p_ofu);
2249 #endif
2250 #ifdef FEAT_QUICKFIX
2251     clear_string_option(&buf->b_p_gp);
2252     clear_string_option(&buf->b_p_mp);
2253     clear_string_option(&buf->b_p_efm);
2254 #endif
2255     clear_string_option(&buf->b_p_ep);
2256     clear_string_option(&buf->b_p_path);
2257     clear_string_option(&buf->b_p_tags);
2258     clear_string_option(&buf->b_p_tc);
2259 #ifdef FEAT_INS_EXPAND
2260     clear_string_option(&buf->b_p_dict);
2261     clear_string_option(&buf->b_p_tsr);
2262 #endif
2263 #ifdef FEAT_TEXTOBJ
2264     clear_string_option(&buf->b_p_qe);
2265 #endif
2266     buf->b_p_ar = -1;
2267     buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
2268 #ifdef FEAT_LISP
2269     clear_string_option(&buf->b_p_lw);
2270 #endif
2271     clear_string_option(&buf->b_p_bkc);
2272 #ifdef FEAT_MBYTE
2273     clear_string_option(&buf->b_p_menc);
2274 #endif
2275 }
2276 
2277 /*
2278  * Get alternate file "n".
2279  * Set linenr to "lnum" or altfpos.lnum if "lnum" == 0.
2280  *	Also set cursor column to altfpos.col if 'startofline' is not set.
2281  * if (options & GETF_SETMARK) call setpcmark()
2282  * if (options & GETF_ALT) we are jumping to an alternate file.
2283  * if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping
2284  *
2285  * Return FAIL for failure, OK for success.
2286  */
2287     int
2288 buflist_getfile(
2289     int		n,
2290     linenr_T	lnum,
2291     int		options,
2292     int		forceit)
2293 {
2294     buf_T	*buf;
2295     win_T	*wp = NULL;
2296     pos_T	*fpos;
2297     colnr_T	col;
2298 
2299     buf = buflist_findnr(n);
2300     if (buf == NULL)
2301     {
2302 	if ((options & GETF_ALT) && n == 0)
2303 	    EMSG(_(e_noalt));
2304 	else
2305 	    EMSGN(_("E92: Buffer %ld not found"), n);
2306 	return FAIL;
2307     }
2308 
2309     /* if alternate file is the current buffer, nothing to do */
2310     if (buf == curbuf)
2311 	return OK;
2312 
2313     if (text_locked())
2314     {
2315 	text_locked_msg();
2316 	return FAIL;
2317     }
2318 #ifdef FEAT_AUTOCMD
2319     if (curbuf_locked())
2320 	return FAIL;
2321 #endif
2322 
2323     /* altfpos may be changed by getfile(), get it now */
2324     if (lnum == 0)
2325     {
2326 	fpos = buflist_findfpos(buf);
2327 	lnum = fpos->lnum;
2328 	col = fpos->col;
2329     }
2330     else
2331 	col = 0;
2332 
2333     if (options & GETF_SWITCH)
2334     {
2335 	/* If 'switchbuf' contains "useopen": jump to first window containing
2336 	 * "buf" if one exists */
2337 	if (swb_flags & SWB_USEOPEN)
2338 	    wp = buf_jump_open_win(buf);
2339 
2340 	/* If 'switchbuf' contains "usetab": jump to first window in any tab
2341 	 * page containing "buf" if one exists */
2342 	if (wp == NULL && (swb_flags & SWB_USETAB))
2343 	    wp = buf_jump_open_tab(buf);
2344 
2345 	/* If 'switchbuf' contains "split", "vsplit" or "newtab" and the
2346 	 * current buffer isn't empty: open new tab or window */
2347 	if (wp == NULL && (swb_flags & (SWB_VSPLIT | SWB_SPLIT | SWB_NEWTAB))
2348 							       && !BUFEMPTY())
2349 	{
2350 	    if (swb_flags & SWB_NEWTAB)
2351 		tabpage_new();
2352 	    else if (win_split(0, (swb_flags & SWB_VSPLIT) ? WSP_VERT : 0)
2353 								      == FAIL)
2354 		return FAIL;
2355 	    RESET_BINDING(curwin);
2356 	}
2357     }
2358 
2359     ++RedrawingDisabled;
2360     if (GETFILE_SUCCESS(getfile(buf->b_fnum, NULL, NULL,
2361 				     (options & GETF_SETMARK), lnum, forceit)))
2362     {
2363 	--RedrawingDisabled;
2364 
2365 	/* cursor is at to BOL and w_cursor.lnum is checked due to getfile() */
2366 	if (!p_sol && col != 0)
2367 	{
2368 	    curwin->w_cursor.col = col;
2369 	    check_cursor_col();
2370 #ifdef FEAT_VIRTUALEDIT
2371 	    curwin->w_cursor.coladd = 0;
2372 #endif
2373 	    curwin->w_set_curswant = TRUE;
2374 	}
2375 	return OK;
2376     }
2377     --RedrawingDisabled;
2378     return FAIL;
2379 }
2380 
2381 /*
2382  * go to the last know line number for the current buffer
2383  */
2384     void
2385 buflist_getfpos(void)
2386 {
2387     pos_T	*fpos;
2388 
2389     fpos = buflist_findfpos(curbuf);
2390 
2391     curwin->w_cursor.lnum = fpos->lnum;
2392     check_cursor_lnum();
2393 
2394     if (p_sol)
2395 	curwin->w_cursor.col = 0;
2396     else
2397     {
2398 	curwin->w_cursor.col = fpos->col;
2399 	check_cursor_col();
2400 #ifdef FEAT_VIRTUALEDIT
2401 	curwin->w_cursor.coladd = 0;
2402 #endif
2403 	curwin->w_set_curswant = TRUE;
2404     }
2405 }
2406 
2407 #if defined(FEAT_QUICKFIX) || defined(FEAT_EVAL) || defined(PROTO)
2408 /*
2409  * Find file in buffer list by name (it has to be for the current window).
2410  * Returns NULL if not found.
2411  */
2412     buf_T *
2413 buflist_findname_exp(char_u *fname)
2414 {
2415     char_u	*ffname;
2416     buf_T	*buf = NULL;
2417 
2418     /* First make the name into a full path name */
2419     ffname = FullName_save(fname,
2420 #ifdef UNIX
2421 	    TRUE	    /* force expansion, get rid of symbolic links */
2422 #else
2423 	    FALSE
2424 #endif
2425 	    );
2426     if (ffname != NULL)
2427     {
2428 	buf = buflist_findname(ffname);
2429 	vim_free(ffname);
2430     }
2431     return buf;
2432 }
2433 #endif
2434 
2435 /*
2436  * Find file in buffer list by name (it has to be for the current window).
2437  * "ffname" must have a full path.
2438  * Skips dummy buffers.
2439  * Returns NULL if not found.
2440  */
2441     buf_T *
2442 buflist_findname(char_u *ffname)
2443 {
2444 #ifdef UNIX
2445     stat_T	st;
2446 
2447     if (mch_stat((char *)ffname, &st) < 0)
2448 	st.st_dev = (dev_T)-1;
2449     return buflist_findname_stat(ffname, &st);
2450 }
2451 
2452 /*
2453  * Same as buflist_findname(), but pass the stat structure to avoid getting it
2454  * twice for the same file.
2455  * Returns NULL if not found.
2456  */
2457     static buf_T *
2458 buflist_findname_stat(
2459     char_u	*ffname,
2460     stat_T	*stp)
2461 {
2462 #endif
2463     buf_T	*buf;
2464 
2465     /* Start at the last buffer, expect to find a match sooner. */
2466     for (buf = lastbuf; buf != NULL; buf = buf->b_prev)
2467 	if ((buf->b_flags & BF_DUMMY) == 0 && !otherfile_buf(buf, ffname
2468 #ifdef UNIX
2469 		    , stp
2470 #endif
2471 		    ))
2472 	    return buf;
2473     return NULL;
2474 }
2475 
2476 #if defined(FEAT_LISTCMDS) || defined(FEAT_EVAL) || defined(FEAT_PERL) \
2477 	|| defined(PROTO)
2478 /*
2479  * Find file in buffer list by a regexp pattern.
2480  * Return fnum of the found buffer.
2481  * Return < 0 for error.
2482  */
2483     int
2484 buflist_findpat(
2485     char_u	*pattern,
2486     char_u	*pattern_end,	/* pointer to first char after pattern */
2487     int		unlisted,	/* find unlisted buffers */
2488     int		diffmode UNUSED, /* find diff-mode buffers only */
2489     int		curtab_only)	/* find buffers in current tab only */
2490 {
2491     buf_T	*buf;
2492     int		match = -1;
2493     int		find_listed;
2494     char_u	*pat;
2495     char_u	*patend;
2496     int		attempt;
2497     char_u	*p;
2498     int		toggledollar;
2499 
2500     if (pattern_end == pattern + 1 && (*pattern == '%' || *pattern == '#'))
2501     {
2502 	if (*pattern == '%')
2503 	    match = curbuf->b_fnum;
2504 	else
2505 	    match = curwin->w_alt_fnum;
2506 #ifdef FEAT_DIFF
2507 	if (diffmode && !diff_mode_buf(buflist_findnr(match)))
2508 	    match = -1;
2509 #endif
2510     }
2511 
2512     /*
2513      * Try four ways of matching a listed buffer:
2514      * attempt == 0: without '^' or '$' (at any position)
2515      * attempt == 1: with '^' at start (only at position 0)
2516      * attempt == 2: with '$' at end (only match at end)
2517      * attempt == 3: with '^' at start and '$' at end (only full match)
2518      * Repeat this for finding an unlisted buffer if there was no matching
2519      * listed buffer.
2520      */
2521     else
2522     {
2523 	pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, FALSE);
2524 	if (pat == NULL)
2525 	    return -1;
2526 	patend = pat + STRLEN(pat) - 1;
2527 	toggledollar = (patend > pat && *patend == '$');
2528 
2529 	/* First try finding a listed buffer.  If not found and "unlisted"
2530 	 * is TRUE, try finding an unlisted buffer. */
2531 	find_listed = TRUE;
2532 	for (;;)
2533 	{
2534 	    for (attempt = 0; attempt <= 3; ++attempt)
2535 	    {
2536 		regmatch_T	regmatch;
2537 
2538 		/* may add '^' and '$' */
2539 		if (toggledollar)
2540 		    *patend = (attempt < 2) ? NUL : '$'; /* add/remove '$' */
2541 		p = pat;
2542 		if (*p == '^' && !(attempt & 1))	 /* add/remove '^' */
2543 		    ++p;
2544 		regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
2545 		if (regmatch.regprog == NULL)
2546 		{
2547 		    vim_free(pat);
2548 		    return -1;
2549 		}
2550 
2551 		for (buf = lastbuf; buf != NULL; buf = buf->b_prev)
2552 		    if (buf->b_p_bl == find_listed
2553 #ifdef FEAT_DIFF
2554 			    && (!diffmode || diff_mode_buf(buf))
2555 #endif
2556 			    && buflist_match(&regmatch, buf, FALSE) != NULL)
2557 		    {
2558 			if (curtab_only)
2559 			{
2560 			    /* Ignore the match if the buffer is not open in
2561 			     * the current tab. */
2562 			    win_T	*wp;
2563 
2564 			    FOR_ALL_WINDOWS(wp)
2565 				if (wp->w_buffer == buf)
2566 				    break;
2567 			    if (wp == NULL)
2568 				continue;
2569 			}
2570 			if (match >= 0)		/* already found a match */
2571 			{
2572 			    match = -2;
2573 			    break;
2574 			}
2575 			match = buf->b_fnum;	/* remember first match */
2576 		    }
2577 
2578 		vim_regfree(regmatch.regprog);
2579 		if (match >= 0)			/* found one match */
2580 		    break;
2581 	    }
2582 
2583 	    /* Only search for unlisted buffers if there was no match with
2584 	     * a listed buffer. */
2585 	    if (!unlisted || !find_listed || match != -1)
2586 		break;
2587 	    find_listed = FALSE;
2588 	}
2589 
2590 	vim_free(pat);
2591     }
2592 
2593     if (match == -2)
2594 	EMSG2(_("E93: More than one match for %s"), pattern);
2595     else if (match < 0)
2596 	EMSG2(_("E94: No matching buffer for %s"), pattern);
2597     return match;
2598 }
2599 #endif
2600 
2601 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2602 
2603 /*
2604  * Find all buffer names that match.
2605  * For command line expansion of ":buf" and ":sbuf".
2606  * Return OK if matches found, FAIL otherwise.
2607  */
2608     int
2609 ExpandBufnames(
2610     char_u	*pat,
2611     int		*num_file,
2612     char_u	***file,
2613     int		options)
2614 {
2615     int		count = 0;
2616     buf_T	*buf;
2617     int		round;
2618     char_u	*p;
2619     int		attempt;
2620     char_u	*patc;
2621 
2622     *num_file = 0;		    /* return values in case of FAIL */
2623     *file = NULL;
2624 
2625     /* Make a copy of "pat" and change "^" to "\(^\|[\/]\)". */
2626     if (*pat == '^')
2627     {
2628 	patc = alloc((unsigned)STRLEN(pat) + 11);
2629 	if (patc == NULL)
2630 	    return FAIL;
2631 	STRCPY(patc, "\\(^\\|[\\/]\\)");
2632 	STRCPY(patc + 11, pat + 1);
2633     }
2634     else
2635 	patc = pat;
2636 
2637     /*
2638      * attempt == 0: try match with    '\<', match at start of word
2639      * attempt == 1: try match without '\<', match anywhere
2640      */
2641     for (attempt = 0; attempt <= 1; ++attempt)
2642     {
2643 	regmatch_T	regmatch;
2644 
2645 	if (attempt > 0 && patc == pat)
2646 	    break;	/* there was no anchor, no need to try again */
2647 	regmatch.regprog = vim_regcomp(patc + attempt * 11, RE_MAGIC);
2648 	if (regmatch.regprog == NULL)
2649 	{
2650 	    if (patc != pat)
2651 		vim_free(patc);
2652 	    return FAIL;
2653 	}
2654 
2655 	/*
2656 	 * round == 1: Count the matches.
2657 	 * round == 2: Build the array to keep the matches.
2658 	 */
2659 	for (round = 1; round <= 2; ++round)
2660 	{
2661 	    count = 0;
2662 	    FOR_ALL_BUFFERS(buf)
2663 	    {
2664 		if (!buf->b_p_bl)	/* skip unlisted buffers */
2665 		    continue;
2666 		p = buflist_match(&regmatch, buf, p_wic);
2667 		if (p != NULL)
2668 		{
2669 		    if (round == 1)
2670 			++count;
2671 		    else
2672 		    {
2673 			if (options & WILD_HOME_REPLACE)
2674 			    p = home_replace_save(buf, p);
2675 			else
2676 			    p = vim_strsave(p);
2677 			(*file)[count++] = p;
2678 		    }
2679 		}
2680 	    }
2681 	    if (count == 0)	/* no match found, break here */
2682 		break;
2683 	    if (round == 1)
2684 	    {
2685 		*file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
2686 		if (*file == NULL)
2687 		{
2688 		    vim_regfree(regmatch.regprog);
2689 		    if (patc != pat)
2690 			vim_free(patc);
2691 		    return FAIL;
2692 		}
2693 	    }
2694 	}
2695 	vim_regfree(regmatch.regprog);
2696 	if (count)		/* match(es) found, break here */
2697 	    break;
2698     }
2699 
2700     if (patc != pat)
2701 	vim_free(patc);
2702 
2703     *num_file = count;
2704     return (count == 0 ? FAIL : OK);
2705 }
2706 
2707 #endif /* FEAT_CMDL_COMPL */
2708 
2709 #ifdef HAVE_BUFLIST_MATCH
2710 /*
2711  * Check for a match on the file name for buffer "buf" with regprog "prog".
2712  */
2713     static char_u *
2714 buflist_match(
2715     regmatch_T	*rmp,
2716     buf_T	*buf,
2717     int		ignore_case)  /* when TRUE ignore case, when FALSE use 'fic' */
2718 {
2719     char_u	*match;
2720 
2721     /* First try the short file name, then the long file name. */
2722     match = fname_match(rmp, buf->b_sfname, ignore_case);
2723     if (match == NULL)
2724 	match = fname_match(rmp, buf->b_ffname, ignore_case);
2725 
2726     return match;
2727 }
2728 
2729 /*
2730  * Try matching the regexp in "prog" with file name "name".
2731  * Return "name" when there is a match, NULL when not.
2732  */
2733     static char_u *
2734 fname_match(
2735     regmatch_T	*rmp,
2736     char_u	*name,
2737     int		ignore_case)  /* when TRUE ignore case, when FALSE use 'fic' */
2738 {
2739     char_u	*match = NULL;
2740     char_u	*p;
2741 
2742     if (name != NULL)
2743     {
2744 	/* Ignore case when 'fileignorecase' or the argument is set. */
2745 	rmp->rm_ic = p_fic || ignore_case;
2746 	if (vim_regexec(rmp, name, (colnr_T)0))
2747 	    match = name;
2748 	else
2749 	{
2750 	    /* Replace $(HOME) with '~' and try matching again. */
2751 	    p = home_replace_save(NULL, name);
2752 	    if (p != NULL && vim_regexec(rmp, p, (colnr_T)0))
2753 		match = name;
2754 	    vim_free(p);
2755 	}
2756     }
2757 
2758     return match;
2759 }
2760 #endif
2761 
2762 /*
2763  * Find a file in the buffer list by buffer number.
2764  */
2765     buf_T *
2766 buflist_findnr(int nr)
2767 {
2768     char_u	key[VIM_SIZEOF_INT * 2 + 1];
2769     hashitem_T	*hi;
2770 
2771     if (nr == 0)
2772 	nr = curwin->w_alt_fnum;
2773     sprintf((char *)key, "%x", nr);
2774     hi = hash_find(&buf_hashtab, key);
2775 
2776     if (!HASHITEM_EMPTY(hi))
2777 	return (buf_T *)(hi->hi_key
2778 			     - ((unsigned)(curbuf->b_key - (char_u *)curbuf)));
2779     return NULL;
2780 }
2781 
2782 /*
2783  * Get name of file 'n' in the buffer list.
2784  * When the file has no name an empty string is returned.
2785  * home_replace() is used to shorten the file name (used for marks).
2786  * Returns a pointer to allocated memory, of NULL when failed.
2787  */
2788     char_u *
2789 buflist_nr2name(
2790     int		n,
2791     int		fullname,
2792     int		helptail)	/* for help buffers return tail only */
2793 {
2794     buf_T	*buf;
2795 
2796     buf = buflist_findnr(n);
2797     if (buf == NULL)
2798 	return NULL;
2799     return home_replace_save(helptail ? buf : NULL,
2800 				     fullname ? buf->b_ffname : buf->b_fname);
2801 }
2802 
2803 /*
2804  * Set the "lnum" and "col" for the buffer "buf" and the current window.
2805  * When "copy_options" is TRUE save the local window option values.
2806  * When "lnum" is 0 only do the options.
2807  */
2808     static void
2809 buflist_setfpos(
2810     buf_T	*buf,
2811     win_T	*win,
2812     linenr_T	lnum,
2813     colnr_T	col,
2814     int		copy_options)
2815 {
2816     wininfo_T	*wip;
2817 
2818     for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
2819 	if (wip->wi_win == win)
2820 	    break;
2821     if (wip == NULL)
2822     {
2823 	/* allocate a new entry */
2824 	wip = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T));
2825 	if (wip == NULL)
2826 	    return;
2827 	wip->wi_win = win;
2828 	if (lnum == 0)		/* set lnum even when it's 0 */
2829 	    lnum = 1;
2830     }
2831     else
2832     {
2833 	/* remove the entry from the list */
2834 	if (wip->wi_prev)
2835 	    wip->wi_prev->wi_next = wip->wi_next;
2836 	else
2837 	    buf->b_wininfo = wip->wi_next;
2838 	if (wip->wi_next)
2839 	    wip->wi_next->wi_prev = wip->wi_prev;
2840 	if (copy_options && wip->wi_optset)
2841 	{
2842 	    clear_winopt(&wip->wi_opt);
2843 #ifdef FEAT_FOLDING
2844 	    deleteFoldRecurse(&wip->wi_folds);
2845 #endif
2846 	}
2847     }
2848     if (lnum != 0)
2849     {
2850 	wip->wi_fpos.lnum = lnum;
2851 	wip->wi_fpos.col = col;
2852     }
2853     if (copy_options)
2854     {
2855 	/* Save the window-specific option values. */
2856 	copy_winopt(&win->w_onebuf_opt, &wip->wi_opt);
2857 #ifdef FEAT_FOLDING
2858 	wip->wi_fold_manual = win->w_fold_manual;
2859 	cloneFoldGrowArray(&win->w_folds, &wip->wi_folds);
2860 #endif
2861 	wip->wi_optset = TRUE;
2862     }
2863 
2864     /* insert the entry in front of the list */
2865     wip->wi_next = buf->b_wininfo;
2866     buf->b_wininfo = wip;
2867     wip->wi_prev = NULL;
2868     if (wip->wi_next)
2869 	wip->wi_next->wi_prev = wip;
2870 
2871     return;
2872 }
2873 
2874 #ifdef FEAT_DIFF
2875 static int wininfo_other_tab_diff(wininfo_T *wip);
2876 
2877 /*
2878  * Return TRUE when "wip" has 'diff' set and the diff is only for another tab
2879  * page.  That's because a diff is local to a tab page.
2880  */
2881     static int
2882 wininfo_other_tab_diff(wininfo_T *wip)
2883 {
2884     win_T	*wp;
2885 
2886     if (wip->wi_opt.wo_diff)
2887     {
2888 	FOR_ALL_WINDOWS(wp)
2889 	    /* return FALSE when it's a window in the current tab page, thus
2890 	     * the buffer was in diff mode here */
2891 	    if (wip->wi_win == wp)
2892 		return FALSE;
2893 	return TRUE;
2894     }
2895     return FALSE;
2896 }
2897 #endif
2898 
2899 /*
2900  * Find info for the current window in buffer "buf".
2901  * If not found, return the info for the most recently used window.
2902  * When "skip_diff_buffer" is TRUE avoid windows with 'diff' set that is in
2903  * another tab page.
2904  * Returns NULL when there isn't any info.
2905  */
2906     static wininfo_T *
2907 find_wininfo(
2908     buf_T	*buf,
2909     int		skip_diff_buffer UNUSED)
2910 {
2911     wininfo_T	*wip;
2912 
2913     for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
2914 	if (wip->wi_win == curwin
2915 #ifdef FEAT_DIFF
2916 		&& (!skip_diff_buffer || !wininfo_other_tab_diff(wip))
2917 #endif
2918 	   )
2919 	    break;
2920 
2921     /* If no wininfo for curwin, use the first in the list (that doesn't have
2922      * 'diff' set and is in another tab page). */
2923     if (wip == NULL)
2924     {
2925 #ifdef FEAT_DIFF
2926 	if (skip_diff_buffer)
2927 	{
2928 	    for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
2929 		if (!wininfo_other_tab_diff(wip))
2930 		    break;
2931 	}
2932 	else
2933 #endif
2934 	    wip = buf->b_wininfo;
2935     }
2936     return wip;
2937 }
2938 
2939 /*
2940  * Reset the local window options to the values last used in this window.
2941  * If the buffer wasn't used in this window before, use the values from
2942  * the most recently used window.  If the values were never set, use the
2943  * global values for the window.
2944  */
2945     void
2946 get_winopts(buf_T *buf)
2947 {
2948     wininfo_T	*wip;
2949 
2950     clear_winopt(&curwin->w_onebuf_opt);
2951 #ifdef FEAT_FOLDING
2952     clearFolding(curwin);
2953 #endif
2954 
2955     wip = find_wininfo(buf, TRUE);
2956     if (wip != NULL && wip->wi_optset)
2957     {
2958 	copy_winopt(&wip->wi_opt, &curwin->w_onebuf_opt);
2959 #ifdef FEAT_FOLDING
2960 	curwin->w_fold_manual = wip->wi_fold_manual;
2961 	curwin->w_foldinvalid = TRUE;
2962 	cloneFoldGrowArray(&wip->wi_folds, &curwin->w_folds);
2963 #endif
2964     }
2965     else
2966 	copy_winopt(&curwin->w_allbuf_opt, &curwin->w_onebuf_opt);
2967 
2968 #ifdef FEAT_FOLDING
2969     /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2970     if (p_fdls >= 0)
2971 	curwin->w_p_fdl = p_fdls;
2972 #endif
2973 #ifdef FEAT_SYN_HL
2974     check_colorcolumn(curwin);
2975 #endif
2976 }
2977 
2978 /*
2979  * Find the position (lnum and col) for the buffer 'buf' for the current
2980  * window.
2981  * Returns a pointer to no_position if no position is found.
2982  */
2983     pos_T *
2984 buflist_findfpos(buf_T *buf)
2985 {
2986     wininfo_T	*wip;
2987     static pos_T no_position = INIT_POS_T(1, 0, 0);
2988 
2989     wip = find_wininfo(buf, FALSE);
2990     if (wip != NULL)
2991 	return &(wip->wi_fpos);
2992     else
2993 	return &no_position;
2994 }
2995 
2996 /*
2997  * Find the lnum for the buffer 'buf' for the current window.
2998  */
2999     linenr_T
3000 buflist_findlnum(buf_T *buf)
3001 {
3002     return buflist_findfpos(buf)->lnum;
3003 }
3004 
3005 #if defined(FEAT_LISTCMDS) || defined(PROTO)
3006 /*
3007  * List all known file names (for :files and :buffers command).
3008  */
3009     void
3010 buflist_list(exarg_T *eap)
3011 {
3012     buf_T	*buf;
3013     int		len;
3014     int		i;
3015     int		ro_char;
3016     int		changed_char;
3017 
3018     for (buf = firstbuf; buf != NULL && !got_int; buf = buf->b_next)
3019     {
3020 	/* skip unlisted buffers, unless ! was used */
3021 	if ((!buf->b_p_bl && !eap->forceit && !vim_strchr(eap->arg, 'u'))
3022 		|| (vim_strchr(eap->arg, 'u') && buf->b_p_bl)
3023 		|| (vim_strchr(eap->arg, '+')
3024 			&& ((buf->b_flags & BF_READERR) || !bufIsChanged(buf)))
3025 		|| (vim_strchr(eap->arg, 'a')
3026 			 && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows == 0))
3027 		|| (vim_strchr(eap->arg, 'h')
3028 			 && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows != 0))
3029 		|| (vim_strchr(eap->arg, '-') && buf->b_p_ma)
3030 		|| (vim_strchr(eap->arg, '=') && !buf->b_p_ro)
3031 		|| (vim_strchr(eap->arg, 'x') && !(buf->b_flags & BF_READERR))
3032 		|| (vim_strchr(eap->arg, '%') && buf != curbuf)
3033 		|| (vim_strchr(eap->arg, '#')
3034 		      && (buf == curbuf || curwin->w_alt_fnum != buf->b_fnum)))
3035 	    continue;
3036 	if (buf_spname(buf) != NULL)
3037 	    vim_strncpy(NameBuff, buf_spname(buf), MAXPATHL - 1);
3038 	else
3039 	    home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE);
3040 	if (message_filtered(NameBuff))
3041 	    continue;
3042 
3043 	changed_char = (buf->b_flags & BF_READERR) ? 'x'
3044 					     : (bufIsChanged(buf) ? '+' : ' ');
3045 #ifdef FEAT_TERMINAL
3046 	if (term_job_running(buf->b_term))
3047 	{
3048 	    if (term_none_open(buf->b_term))
3049 		ro_char = '?';
3050 	    else
3051 		ro_char = 'R';
3052 	    changed_char = ' ';  /* bufIsChanged() returns TRUE to avoid
3053 				  * closing, but it's not actually changed. */
3054 	}
3055 	else if (buf->b_term != NULL)
3056 	    ro_char = 'F';
3057 	else
3058 #endif
3059 	    ro_char = !buf->b_p_ma ? '-' : (buf->b_p_ro ? '=' : ' ');
3060 
3061 	msg_putchar('\n');
3062 	len = vim_snprintf((char *)IObuff, IOSIZE - 20, "%3d%c%c%c%c%c \"%s\"",
3063 		buf->b_fnum,
3064 		buf->b_p_bl ? ' ' : 'u',
3065 		buf == curbuf ? '%' :
3066 			(curwin->w_alt_fnum == buf->b_fnum ? '#' : ' '),
3067 		buf->b_ml.ml_mfp == NULL ? ' ' :
3068 			(buf->b_nwindows == 0 ? 'h' : 'a'),
3069 		ro_char,
3070 		changed_char,
3071 		NameBuff);
3072 	if (len > IOSIZE - 20)
3073 	    len = IOSIZE - 20;
3074 
3075 	/* put "line 999" in column 40 or after the file name */
3076 	i = 40 - vim_strsize(IObuff);
3077 	do
3078 	{
3079 	    IObuff[len++] = ' ';
3080 	} while (--i > 0 && len < IOSIZE - 18);
3081 	vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len),
3082 		_("line %ld"), buf == curbuf ? curwin->w_cursor.lnum
3083 					       : (long)buflist_findlnum(buf));
3084 	msg_outtrans(IObuff);
3085 	out_flush();	    /* output one line at a time */
3086 	ui_breakcheck();
3087     }
3088 }
3089 #endif
3090 
3091 /*
3092  * Get file name and line number for file 'fnum'.
3093  * Used by DoOneCmd() for translating '%' and '#'.
3094  * Used by insert_reg() and cmdline_paste() for '#' register.
3095  * Return FAIL if not found, OK for success.
3096  */
3097     int
3098 buflist_name_nr(
3099     int		fnum,
3100     char_u	**fname,
3101     linenr_T	*lnum)
3102 {
3103     buf_T	*buf;
3104 
3105     buf = buflist_findnr(fnum);
3106     if (buf == NULL || buf->b_fname == NULL)
3107 	return FAIL;
3108 
3109     *fname = buf->b_fname;
3110     *lnum = buflist_findlnum(buf);
3111 
3112     return OK;
3113 }
3114 
3115 /*
3116  * Set the file name for "buf"' to 'ffname', short file name to 'sfname'.
3117  * The file name with the full path is also remembered, for when :cd is used.
3118  * Returns FAIL for failure (file name already in use by other buffer)
3119  *	OK otherwise.
3120  */
3121     int
3122 setfname(
3123     buf_T	*buf,
3124     char_u	*ffname,
3125     char_u	*sfname,
3126     int		message)	/* give message when buffer already exists */
3127 {
3128     buf_T	*obuf = NULL;
3129 #ifdef UNIX
3130     stat_T	st;
3131 #endif
3132 
3133     if (ffname == NULL || *ffname == NUL)
3134     {
3135 	/* Removing the name. */
3136 	vim_free(buf->b_ffname);
3137 	vim_free(buf->b_sfname);
3138 	buf->b_ffname = NULL;
3139 	buf->b_sfname = NULL;
3140 #ifdef UNIX
3141 	st.st_dev = (dev_T)-1;
3142 #endif
3143     }
3144     else
3145     {
3146 	fname_expand(buf, &ffname, &sfname); /* will allocate ffname */
3147 	if (ffname == NULL)		    /* out of memory */
3148 	    return FAIL;
3149 
3150 	/*
3151 	 * if the file name is already used in another buffer:
3152 	 * - if the buffer is loaded, fail
3153 	 * - if the buffer is not loaded, delete it from the list
3154 	 */
3155 #ifdef UNIX
3156 	if (mch_stat((char *)ffname, &st) < 0)
3157 	    st.st_dev = (dev_T)-1;
3158 #endif
3159 	if (!(buf->b_flags & BF_DUMMY))
3160 #ifdef UNIX
3161 	    obuf = buflist_findname_stat(ffname, &st);
3162 #else
3163 	    obuf = buflist_findname(ffname);
3164 #endif
3165 	if (obuf != NULL && obuf != buf)
3166 	{
3167 	    if (obuf->b_ml.ml_mfp != NULL)	/* it's loaded, fail */
3168 	    {
3169 		if (message)
3170 		    EMSG(_("E95: Buffer with this name already exists"));
3171 		vim_free(ffname);
3172 		return FAIL;
3173 	    }
3174 	    /* delete from the list */
3175 	    close_buffer(NULL, obuf, DOBUF_WIPE, FALSE);
3176 	}
3177 	sfname = vim_strsave(sfname);
3178 	if (ffname == NULL || sfname == NULL)
3179 	{
3180 	    vim_free(sfname);
3181 	    vim_free(ffname);
3182 	    return FAIL;
3183 	}
3184 #ifdef USE_FNAME_CASE
3185 # ifdef USE_LONG_FNAME
3186 	if (USE_LONG_FNAME)
3187 # endif
3188 	    fname_case(sfname, 0);    /* set correct case for short file name */
3189 #endif
3190 	vim_free(buf->b_ffname);
3191 	vim_free(buf->b_sfname);
3192 	buf->b_ffname = ffname;
3193 	buf->b_sfname = sfname;
3194     }
3195     buf->b_fname = buf->b_sfname;
3196 #ifdef UNIX
3197     if (st.st_dev == (dev_T)-1)
3198 	buf->b_dev_valid = FALSE;
3199     else
3200     {
3201 	buf->b_dev_valid = TRUE;
3202 	buf->b_dev = st.st_dev;
3203 	buf->b_ino = st.st_ino;
3204     }
3205 #endif
3206 
3207     buf->b_shortname = FALSE;
3208 
3209     buf_name_changed(buf);
3210     return OK;
3211 }
3212 
3213 /*
3214  * Crude way of changing the name of a buffer.  Use with care!
3215  * The name should be relative to the current directory.
3216  */
3217     void
3218 buf_set_name(int fnum, char_u *name)
3219 {
3220     buf_T	*buf;
3221 
3222     buf = buflist_findnr(fnum);
3223     if (buf != NULL)
3224     {
3225 	vim_free(buf->b_sfname);
3226 	vim_free(buf->b_ffname);
3227 	buf->b_ffname = vim_strsave(name);
3228 	buf->b_sfname = NULL;
3229 	/* Allocate ffname and expand into full path.  Also resolves .lnk
3230 	 * files on Win32. */
3231 	fname_expand(buf, &buf->b_ffname, &buf->b_sfname);
3232 	buf->b_fname = buf->b_sfname;
3233     }
3234 }
3235 
3236 /*
3237  * Take care of what needs to be done when the name of buffer "buf" has
3238  * changed.
3239  */
3240     void
3241 buf_name_changed(buf_T *buf)
3242 {
3243     /*
3244      * If the file name changed, also change the name of the swapfile
3245      */
3246     if (buf->b_ml.ml_mfp != NULL)
3247 	ml_setname(buf);
3248 
3249     if (curwin->w_buffer == buf)
3250 	check_arg_idx(curwin);	/* check file name for arg list */
3251 #ifdef FEAT_TITLE
3252     maketitle();		/* set window title */
3253 #endif
3254     status_redraw_all();	/* status lines need to be redrawn */
3255     fmarks_check_names(buf);	/* check named file marks */
3256     ml_timestamp(buf);		/* reset timestamp */
3257 }
3258 
3259 /*
3260  * set alternate file name for current window
3261  *
3262  * Used by do_one_cmd(), do_write() and do_ecmd().
3263  * Return the buffer.
3264  */
3265     buf_T *
3266 setaltfname(
3267     char_u	*ffname,
3268     char_u	*sfname,
3269     linenr_T	lnum)
3270 {
3271     buf_T	*buf;
3272 
3273     /* Create a buffer.  'buflisted' is not set if it's a new buffer */
3274     buf = buflist_new(ffname, sfname, lnum, 0);
3275     if (buf != NULL && !cmdmod.keepalt)
3276 	curwin->w_alt_fnum = buf->b_fnum;
3277     return buf;
3278 }
3279 
3280 /*
3281  * Get alternate file name for current window.
3282  * Return NULL if there isn't any, and give error message if requested.
3283  */
3284     char_u  *
3285 getaltfname(
3286     int		errmsg)		/* give error message */
3287 {
3288     char_u	*fname;
3289     linenr_T	dummy;
3290 
3291     if (buflist_name_nr(0, &fname, &dummy) == FAIL)
3292     {
3293 	if (errmsg)
3294 	    EMSG(_(e_noalt));
3295 	return NULL;
3296     }
3297     return fname;
3298 }
3299 
3300 /*
3301  * Add a file name to the buflist and return its number.
3302  * Uses same flags as buflist_new(), except BLN_DUMMY.
3303  *
3304  * used by qf_init(), main() and doarglist()
3305  */
3306     int
3307 buflist_add(char_u *fname, int flags)
3308 {
3309     buf_T	*buf;
3310 
3311     buf = buflist_new(fname, NULL, (linenr_T)0, flags);
3312     if (buf != NULL)
3313 	return buf->b_fnum;
3314     return 0;
3315 }
3316 
3317 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
3318 /*
3319  * Adjust slashes in file names.  Called after 'shellslash' was set.
3320  */
3321     void
3322 buflist_slash_adjust(void)
3323 {
3324     buf_T	*bp;
3325 
3326     FOR_ALL_BUFFERS(bp)
3327     {
3328 	if (bp->b_ffname != NULL)
3329 	    slash_adjust(bp->b_ffname);
3330 	if (bp->b_sfname != NULL)
3331 	    slash_adjust(bp->b_sfname);
3332     }
3333 }
3334 #endif
3335 
3336 /*
3337  * Set alternate cursor position for the current buffer and window "win".
3338  * Also save the local window option values.
3339  */
3340     void
3341 buflist_altfpos(win_T *win)
3342 {
3343     buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, TRUE);
3344 }
3345 
3346 /*
3347  * Return TRUE if 'ffname' is not the same file as current file.
3348  * Fname must have a full path (expanded by mch_FullName()).
3349  */
3350     int
3351 otherfile(char_u *ffname)
3352 {
3353     return otherfile_buf(curbuf, ffname
3354 #ifdef UNIX
3355 	    , NULL
3356 #endif
3357 	    );
3358 }
3359 
3360     static int
3361 otherfile_buf(
3362     buf_T		*buf,
3363     char_u		*ffname
3364 #ifdef UNIX
3365     , stat_T		*stp
3366 #endif
3367     )
3368 {
3369     /* no name is different */
3370     if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL)
3371 	return TRUE;
3372     if (fnamecmp(ffname, buf->b_ffname) == 0)
3373 	return FALSE;
3374 #ifdef UNIX
3375     {
3376 	stat_T	    st;
3377 
3378 	/* If no stat_T given, get it now */
3379 	if (stp == NULL)
3380 	{
3381 	    if (!buf->b_dev_valid || mch_stat((char *)ffname, &st) < 0)
3382 		st.st_dev = (dev_T)-1;
3383 	    stp = &st;
3384 	}
3385 	/* Use dev/ino to check if the files are the same, even when the names
3386 	 * are different (possible with links).  Still need to compare the
3387 	 * name above, for when the file doesn't exist yet.
3388 	 * Problem: The dev/ino changes when a file is deleted (and created
3389 	 * again) and remains the same when renamed/moved.  We don't want to
3390 	 * mch_stat() each buffer each time, that would be too slow.  Get the
3391 	 * dev/ino again when they appear to match, but not when they appear
3392 	 * to be different: Could skip a buffer when it's actually the same
3393 	 * file. */
3394 	if (buf_same_ino(buf, stp))
3395 	{
3396 	    buf_setino(buf);
3397 	    if (buf_same_ino(buf, stp))
3398 		return FALSE;
3399 	}
3400     }
3401 #endif
3402     return TRUE;
3403 }
3404 
3405 #if defined(UNIX) || defined(PROTO)
3406 /*
3407  * Set inode and device number for a buffer.
3408  * Must always be called when b_fname is changed!.
3409  */
3410     void
3411 buf_setino(buf_T *buf)
3412 {
3413     stat_T	st;
3414 
3415     if (buf->b_fname != NULL && mch_stat((char *)buf->b_fname, &st) >= 0)
3416     {
3417 	buf->b_dev_valid = TRUE;
3418 	buf->b_dev = st.st_dev;
3419 	buf->b_ino = st.st_ino;
3420     }
3421     else
3422 	buf->b_dev_valid = FALSE;
3423 }
3424 
3425 /*
3426  * Return TRUE if dev/ino in buffer "buf" matches with "stp".
3427  */
3428     static int
3429 buf_same_ino(
3430     buf_T	*buf,
3431     stat_T	*stp)
3432 {
3433     return (buf->b_dev_valid
3434 	    && stp->st_dev == buf->b_dev
3435 	    && stp->st_ino == buf->b_ino);
3436 }
3437 #endif
3438 
3439 /*
3440  * Print info about the current buffer.
3441  */
3442     void
3443 fileinfo(
3444     int fullname,	    /* when non-zero print full path */
3445     int shorthelp,
3446     int	dont_truncate)
3447 {
3448     char_u	*name;
3449     int		n;
3450     char_u	*p;
3451     char_u	*buffer;
3452     size_t	len;
3453 
3454     buffer = alloc(IOSIZE);
3455     if (buffer == NULL)
3456 	return;
3457 
3458     if (fullname > 1)	    /* 2 CTRL-G: include buffer number */
3459     {
3460 	vim_snprintf((char *)buffer, IOSIZE, "buf %d: ", curbuf->b_fnum);
3461 	p = buffer + STRLEN(buffer);
3462     }
3463     else
3464 	p = buffer;
3465 
3466     *p++ = '"';
3467     if (buf_spname(curbuf) != NULL)
3468 	vim_strncpy(p, buf_spname(curbuf), IOSIZE - (p - buffer) - 1);
3469     else
3470     {
3471 	if (!fullname && curbuf->b_fname != NULL)
3472 	    name = curbuf->b_fname;
3473 	else
3474 	    name = curbuf->b_ffname;
3475 	home_replace(shorthelp ? curbuf : NULL, name, p,
3476 					  (int)(IOSIZE - (p - buffer)), TRUE);
3477     }
3478 
3479     vim_snprintf_add((char *)buffer, IOSIZE, "\"%s%s%s%s%s%s",
3480 	    curbufIsChanged() ? (shortmess(SHM_MOD)
3481 					  ?  " [+]" : _(" [Modified]")) : " ",
3482 	    (curbuf->b_flags & BF_NOTEDITED)
3483 #ifdef FEAT_QUICKFIX
3484 		    && !bt_dontwrite(curbuf)
3485 #endif
3486 					? _("[Not edited]") : "",
3487 	    (curbuf->b_flags & BF_NEW)
3488 #ifdef FEAT_QUICKFIX
3489 		    && !bt_dontwrite(curbuf)
3490 #endif
3491 					? _("[New file]") : "",
3492 	    (curbuf->b_flags & BF_READERR) ? _("[Read errors]") : "",
3493 	    curbuf->b_p_ro ? (shortmess(SHM_RO) ? _("[RO]")
3494 						      : _("[readonly]")) : "",
3495 	    (curbufIsChanged() || (curbuf->b_flags & BF_WRITE_MASK)
3496 							  || curbuf->b_p_ro) ?
3497 								    " " : "");
3498     /* With 32 bit longs and more than 21,474,836 lines multiplying by 100
3499      * causes an overflow, thus for large numbers divide instead. */
3500     if (curwin->w_cursor.lnum > 1000000L)
3501 	n = (int)(((long)curwin->w_cursor.lnum) /
3502 				   ((long)curbuf->b_ml.ml_line_count / 100L));
3503     else
3504 	n = (int)(((long)curwin->w_cursor.lnum * 100L) /
3505 					    (long)curbuf->b_ml.ml_line_count);
3506     if (curbuf->b_ml.ml_flags & ML_EMPTY)
3507     {
3508 	vim_snprintf_add((char *)buffer, IOSIZE, "%s", _(no_lines_msg));
3509     }
3510 #ifdef FEAT_CMDL_INFO
3511     else if (p_ru)
3512     {
3513 	/* Current line and column are already on the screen -- webb */
3514 	if (curbuf->b_ml.ml_line_count == 1)
3515 	    vim_snprintf_add((char *)buffer, IOSIZE, _("1 line --%d%%--"), n);
3516 	else
3517 	    vim_snprintf_add((char *)buffer, IOSIZE, _("%ld lines --%d%%--"),
3518 					 (long)curbuf->b_ml.ml_line_count, n);
3519     }
3520 #endif
3521     else
3522     {
3523 	vim_snprintf_add((char *)buffer, IOSIZE,
3524 		_("line %ld of %ld --%d%%-- col "),
3525 		(long)curwin->w_cursor.lnum,
3526 		(long)curbuf->b_ml.ml_line_count,
3527 		n);
3528 	validate_virtcol();
3529 	len = STRLEN(buffer);
3530 	col_print(buffer + len, IOSIZE - len,
3531 		   (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1);
3532     }
3533 
3534     (void)append_arg_number(curwin, buffer, IOSIZE, !shortmess(SHM_FILE));
3535 
3536     if (dont_truncate)
3537     {
3538 	/* Temporarily set msg_scroll to avoid the message being truncated.
3539 	 * First call msg_start() to get the message in the right place. */
3540 	msg_start();
3541 	n = msg_scroll;
3542 	msg_scroll = TRUE;
3543 	msg(buffer);
3544 	msg_scroll = n;
3545     }
3546     else
3547     {
3548 	p = msg_trunc_attr(buffer, FALSE, 0);
3549 	if (restart_edit != 0 || (msg_scrolled && !need_wait_return))
3550 	    /* Need to repeat the message after redrawing when:
3551 	     * - When restart_edit is set (otherwise there will be a delay
3552 	     *   before redrawing).
3553 	     * - When the screen was scrolled but there is no wait-return
3554 	     *   prompt. */
3555 	    set_keep_msg(p, 0);
3556     }
3557 
3558     vim_free(buffer);
3559 }
3560 
3561     void
3562 col_print(
3563     char_u  *buf,
3564     size_t  buflen,
3565     int	    col,
3566     int	    vcol)
3567 {
3568     if (col == vcol)
3569 	vim_snprintf((char *)buf, buflen, "%d", col);
3570     else
3571 	vim_snprintf((char *)buf, buflen, "%d-%d", col, vcol);
3572 }
3573 
3574 #if defined(FEAT_TITLE) || defined(PROTO)
3575 /*
3576  * put file name in title bar of window and in icon title
3577  */
3578 
3579 static char_u *lasttitle = NULL;
3580 static char_u *lasticon = NULL;
3581 
3582     void
3583 maketitle(void)
3584 {
3585     char_u	*p;
3586     char_u	*t_str = NULL;
3587     char_u	*i_name;
3588     char_u	*i_str = NULL;
3589     int		maxlen = 0;
3590     int		len;
3591     int		mustset;
3592     char_u	buf[IOSIZE];
3593     int		off;
3594 
3595     if (!redrawing())
3596     {
3597 	/* Postpone updating the title when 'lazyredraw' is set. */
3598 	need_maketitle = TRUE;
3599 	return;
3600     }
3601 
3602     need_maketitle = FALSE;
3603     if (!p_title && !p_icon && lasttitle == NULL && lasticon == NULL)
3604 	return;
3605 
3606     if (p_title)
3607     {
3608 	if (p_titlelen > 0)
3609 	{
3610 	    maxlen = p_titlelen * Columns / 100;
3611 	    if (maxlen < 10)
3612 		maxlen = 10;
3613 	}
3614 
3615 	t_str = buf;
3616 	if (*p_titlestring != NUL)
3617 	{
3618 #ifdef FEAT_STL_OPT
3619 	    if (stl_syntax & STL_IN_TITLE)
3620 	    {
3621 		int	use_sandbox = FALSE;
3622 		int	save_called_emsg = called_emsg;
3623 
3624 # ifdef FEAT_EVAL
3625 		use_sandbox = was_set_insecurely((char_u *)"titlestring", 0);
3626 # endif
3627 		called_emsg = FALSE;
3628 		build_stl_str_hl(curwin, t_str, sizeof(buf),
3629 					      p_titlestring, use_sandbox,
3630 					      0, maxlen, NULL, NULL);
3631 		if (called_emsg)
3632 		    set_string_option_direct((char_u *)"titlestring", -1,
3633 					   (char_u *)"", OPT_FREE, SID_ERROR);
3634 		called_emsg |= save_called_emsg;
3635 	    }
3636 	    else
3637 #endif
3638 		t_str = p_titlestring;
3639 	}
3640 	else
3641 	{
3642 	    /* format: "fname + (path) (1 of 2) - VIM" */
3643 
3644 #define SPACE_FOR_FNAME (IOSIZE - 100)
3645 #define SPACE_FOR_DIR   (IOSIZE - 20)
3646 #define SPACE_FOR_ARGNR (IOSIZE - 10)  /* at least room for " - VIM" */
3647 	    if (curbuf->b_fname == NULL)
3648 		vim_strncpy(buf, (char_u *)_("[No Name]"), SPACE_FOR_FNAME);
3649 #ifdef FEAT_TERMINAL
3650 	    else if (curbuf->b_term != NULL)
3651 	    {
3652 		vim_strncpy(buf, term_get_status_text(curbuf->b_term),
3653 							      SPACE_FOR_FNAME);
3654 	    }
3655 #endif
3656 	    else
3657 	    {
3658 		p = transstr(gettail(curbuf->b_fname));
3659 		vim_strncpy(buf, p, SPACE_FOR_FNAME);
3660 		vim_free(p);
3661 	    }
3662 
3663 #ifdef FEAT_TERMINAL
3664 	    if (curbuf->b_term == NULL)
3665 #endif
3666 		switch (bufIsChanged(curbuf)
3667 			+ (curbuf->b_p_ro * 2)
3668 			+ (!curbuf->b_p_ma * 4))
3669 		{
3670 		    case 1: STRCAT(buf, " +"); break;
3671 		    case 2: STRCAT(buf, " ="); break;
3672 		    case 3: STRCAT(buf, " =+"); break;
3673 		    case 4:
3674 		    case 6: STRCAT(buf, " -"); break;
3675 		    case 5:
3676 		    case 7: STRCAT(buf, " -+"); break;
3677 		}
3678 
3679 	    if (curbuf->b_fname != NULL
3680 #ifdef FEAT_TERMINAL
3681 		    && curbuf->b_term == NULL
3682 #endif
3683 		    )
3684 	    {
3685 		/* Get path of file, replace home dir with ~ */
3686 		off = (int)STRLEN(buf);
3687 		buf[off++] = ' ';
3688 		buf[off++] = '(';
3689 		home_replace(curbuf, curbuf->b_ffname,
3690 					buf + off, SPACE_FOR_DIR - off, TRUE);
3691 #ifdef BACKSLASH_IN_FILENAME
3692 		/* avoid "c:/name" to be reduced to "c" */
3693 		if (isalpha(buf[off]) && buf[off + 1] == ':')
3694 		    off += 2;
3695 #endif
3696 		/* remove the file name */
3697 		p = gettail_sep(buf + off);
3698 		if (p == buf + off)
3699 		{
3700 		    /* must be a help buffer */
3701 		    vim_strncpy(buf + off, (char_u *)_("help"),
3702 					   (size_t)(SPACE_FOR_DIR - off - 1));
3703 		}
3704 		else
3705 		    *p = NUL;
3706 
3707 		/* Translate unprintable chars and concatenate.  Keep some
3708 		 * room for the server name.  When there is no room (very long
3709 		 * file name) use (...). */
3710 		if (off < SPACE_FOR_DIR)
3711 		{
3712 		    p = transstr(buf + off);
3713 		    vim_strncpy(buf + off, p, (size_t)(SPACE_FOR_DIR - off));
3714 		    vim_free(p);
3715 		}
3716 		else
3717 		{
3718 		    vim_strncpy(buf + off, (char_u *)"...",
3719 					     (size_t)(SPACE_FOR_ARGNR - off));
3720 		}
3721 		STRCAT(buf, ")");
3722 	    }
3723 
3724 	    append_arg_number(curwin, buf, SPACE_FOR_ARGNR, FALSE);
3725 
3726 #if defined(FEAT_CLIENTSERVER)
3727 	    if (serverName != NULL)
3728 	    {
3729 		STRCAT(buf, " - ");
3730 		vim_strcat(buf, serverName, IOSIZE);
3731 	    }
3732 	    else
3733 #endif
3734 		STRCAT(buf, " - VIM");
3735 
3736 	    if (maxlen > 0)
3737 	    {
3738 		/* make it shorter by removing a bit in the middle */
3739 		if (vim_strsize(buf) > maxlen)
3740 		    trunc_string(buf, buf, maxlen, IOSIZE);
3741 	    }
3742 	}
3743     }
3744     mustset = ti_change(t_str, &lasttitle);
3745 
3746     if (p_icon)
3747     {
3748 	i_str = buf;
3749 	if (*p_iconstring != NUL)
3750 	{
3751 #ifdef FEAT_STL_OPT
3752 	    if (stl_syntax & STL_IN_ICON)
3753 	    {
3754 		int	use_sandbox = FALSE;
3755 		int	save_called_emsg = called_emsg;
3756 
3757 # ifdef FEAT_EVAL
3758 		use_sandbox = was_set_insecurely((char_u *)"iconstring", 0);
3759 # endif
3760 		called_emsg = FALSE;
3761 		build_stl_str_hl(curwin, i_str, sizeof(buf),
3762 						    p_iconstring, use_sandbox,
3763 						    0, 0, NULL, NULL);
3764 		if (called_emsg)
3765 		    set_string_option_direct((char_u *)"iconstring", -1,
3766 					   (char_u *)"", OPT_FREE, SID_ERROR);
3767 		called_emsg |= save_called_emsg;
3768 	    }
3769 	    else
3770 #endif
3771 		i_str = p_iconstring;
3772 	}
3773 	else
3774 	{
3775 	    if (buf_spname(curbuf) != NULL)
3776 		i_name = buf_spname(curbuf);
3777 	    else		    /* use file name only in icon */
3778 		i_name = gettail(curbuf->b_ffname);
3779 	    *i_str = NUL;
3780 	    /* Truncate name at 100 bytes. */
3781 	    len = (int)STRLEN(i_name);
3782 	    if (len > 100)
3783 	    {
3784 		len -= 100;
3785 #ifdef FEAT_MBYTE
3786 		if (has_mbyte)
3787 		    len += (*mb_tail_off)(i_name, i_name + len) + 1;
3788 #endif
3789 		i_name += len;
3790 	    }
3791 	    STRCPY(i_str, i_name);
3792 	    trans_characters(i_str, IOSIZE);
3793 	}
3794     }
3795 
3796     mustset |= ti_change(i_str, &lasticon);
3797 
3798     if (mustset)
3799 	resettitle();
3800 }
3801 
3802 /*
3803  * Used for title and icon: Check if "str" differs from "*last".  Set "*last"
3804  * from "str" if it does.
3805  * Return TRUE when "*last" changed.
3806  */
3807     static int
3808 ti_change(char_u *str, char_u **last)
3809 {
3810     if ((str == NULL) != (*last == NULL)
3811 	    || (str != NULL && *last != NULL && STRCMP(str, *last) != 0))
3812     {
3813 	vim_free(*last);
3814 	if (str == NULL)
3815 	    *last = NULL;
3816 	else
3817 	    *last = vim_strsave(str);
3818 	return TRUE;
3819     }
3820     return FALSE;
3821 }
3822 
3823 /*
3824  * Put current window title back (used after calling a shell)
3825  */
3826     void
3827 resettitle(void)
3828 {
3829     mch_settitle(lasttitle, lasticon);
3830 }
3831 
3832 # if defined(EXITFREE) || defined(PROTO)
3833     void
3834 free_titles(void)
3835 {
3836     vim_free(lasttitle);
3837     vim_free(lasticon);
3838 }
3839 # endif
3840 
3841 #endif /* FEAT_TITLE */
3842 
3843 #if defined(FEAT_STL_OPT) || defined(FEAT_GUI_TABLINE) || defined(PROTO)
3844 /*
3845  * Build a string from the status line items in "fmt".
3846  * Return length of string in screen cells.
3847  *
3848  * Normally works for window "wp", except when working for 'tabline' then it
3849  * is "curwin".
3850  *
3851  * Items are drawn interspersed with the text that surrounds it
3852  * Specials: %-<wid>(xxx%) => group, %= => middle marker, %< => truncation
3853  * Item: %-<minwid>.<maxwid><itemch> All but <itemch> are optional
3854  *
3855  * If maxwidth is not zero, the string will be filled at any middle marker
3856  * or truncated if too long, fillchar is used for all whitespace.
3857  */
3858     int
3859 build_stl_str_hl(
3860     win_T	*wp,
3861     char_u	*out,		/* buffer to write into != NameBuff */
3862     size_t	outlen,		/* length of out[] */
3863     char_u	*fmt,
3864     int		use_sandbox UNUSED, /* "fmt" was set insecurely, use sandbox */
3865     int		fillchar,
3866     int		maxwidth,
3867     struct stl_hlrec *hltab,	/* return: HL attributes (can be NULL) */
3868     struct stl_hlrec *tabtab)	/* return: tab page nrs (can be NULL) */
3869 {
3870     char_u	*p;
3871     char_u	*s;
3872     char_u	*t;
3873     int		byteval;
3874 #ifdef FEAT_EVAL
3875     win_T	*save_curwin;
3876     buf_T	*save_curbuf;
3877 #endif
3878     int		empty_line;
3879     colnr_T	virtcol;
3880     long	l;
3881     long	n;
3882     int		prevchar_isflag;
3883     int		prevchar_isitem;
3884     int		itemisflag;
3885     int		fillable;
3886     char_u	*str;
3887     long	num;
3888     int		width;
3889     int		itemcnt;
3890     int		curitem;
3891     int		group_end_userhl;
3892     int		group_start_userhl;
3893     int		groupitem[STL_MAX_ITEM];
3894     int		groupdepth;
3895     struct stl_item
3896     {
3897 	char_u		*start;
3898 	int		minwid;
3899 	int		maxwid;
3900 	enum
3901 	{
3902 	    Normal,
3903 	    Empty,
3904 	    Group,
3905 	    Middle,
3906 	    Highlight,
3907 	    TabPage,
3908 	    Trunc
3909 	}		type;
3910     }		item[STL_MAX_ITEM];
3911     int		minwid;
3912     int		maxwid;
3913     int		zeropad;
3914     char_u	base;
3915     char_u	opt;
3916 #define TMPLEN 70
3917     char_u	tmp[TMPLEN];
3918     char_u	*usefmt = fmt;
3919     struct stl_hlrec *sp;
3920     int		save_must_redraw = must_redraw;
3921     int		save_redr_type = curwin->w_redr_type;
3922 
3923 #ifdef FEAT_EVAL
3924     /*
3925      * When the format starts with "%!" then evaluate it as an expression and
3926      * use the result as the actual format string.
3927      */
3928     if (fmt[0] == '%' && fmt[1] == '!')
3929     {
3930 	usefmt = eval_to_string_safe(fmt + 2, NULL, use_sandbox);
3931 	if (usefmt == NULL)
3932 	    usefmt = fmt;
3933     }
3934 #endif
3935 
3936     if (fillchar == 0)
3937 	fillchar = ' ';
3938 #ifdef FEAT_MBYTE
3939     /* Can't handle a multi-byte fill character yet. */
3940     else if (mb_char2len(fillchar) > 1)
3941 	fillchar = '-';
3942 #endif
3943 
3944     /* Get line & check if empty (cursorpos will show "0-1").  Note that
3945      * p will become invalid when getting another buffer line. */
3946     p = ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE);
3947     empty_line = (*p == NUL);
3948 
3949     /* Get the byte value now, in case we need it below. This is more
3950      * efficient than making a copy of the line. */
3951     if (wp->w_cursor.col > (colnr_T)STRLEN(p))
3952 	byteval = 0;
3953     else
3954 #ifdef FEAT_MBYTE
3955 	byteval = (*mb_ptr2char)(p + wp->w_cursor.col);
3956 #else
3957 	byteval = p[wp->w_cursor.col];
3958 #endif
3959 
3960     groupdepth = 0;
3961     p = out;
3962     curitem = 0;
3963     prevchar_isflag = TRUE;
3964     prevchar_isitem = FALSE;
3965     for (s = usefmt; *s; )
3966     {
3967 	if (curitem == STL_MAX_ITEM)
3968 	{
3969 	    /* There are too many items.  Add the error code to the statusline
3970 	     * to give the user a hint about what went wrong. */
3971 	    if (p + 6 < out + outlen)
3972 	    {
3973 		mch_memmove(p, " E541", (size_t)5);
3974 		p += 5;
3975 	    }
3976 	    break;
3977 	}
3978 
3979 	if (*s != NUL && *s != '%')
3980 	    prevchar_isflag = prevchar_isitem = FALSE;
3981 
3982 	/*
3983 	 * Handle up to the next '%' or the end.
3984 	 */
3985 	while (*s != NUL && *s != '%' && p + 1 < out + outlen)
3986 	    *p++ = *s++;
3987 	if (*s == NUL || p + 1 >= out + outlen)
3988 	    break;
3989 
3990 	/*
3991 	 * Handle one '%' item.
3992 	 */
3993 	s++;
3994 	if (*s == NUL)  /* ignore trailing % */
3995 	    break;
3996 	if (*s == '%')
3997 	{
3998 	    if (p + 1 >= out + outlen)
3999 		break;
4000 	    *p++ = *s++;
4001 	    prevchar_isflag = prevchar_isitem = FALSE;
4002 	    continue;
4003 	}
4004 	if (*s == STL_MIDDLEMARK)
4005 	{
4006 	    s++;
4007 	    if (groupdepth > 0)
4008 		continue;
4009 	    item[curitem].type = Middle;
4010 	    item[curitem++].start = p;
4011 	    continue;
4012 	}
4013 	if (*s == STL_TRUNCMARK)
4014 	{
4015 	    s++;
4016 	    item[curitem].type = Trunc;
4017 	    item[curitem++].start = p;
4018 	    continue;
4019 	}
4020 	if (*s == ')')
4021 	{
4022 	    s++;
4023 	    if (groupdepth < 1)
4024 		continue;
4025 	    groupdepth--;
4026 
4027 	    t = item[groupitem[groupdepth]].start;
4028 	    *p = NUL;
4029 	    l = vim_strsize(t);
4030 	    if (curitem > groupitem[groupdepth] + 1
4031 		    && item[groupitem[groupdepth]].minwid == 0)
4032 	    {
4033 		/* remove group if all items are empty and highlight group
4034 		 * doesn't change */
4035 		group_start_userhl = group_end_userhl = 0;
4036 		for (n = groupitem[groupdepth] - 1; n >= 0; n--)
4037 		{
4038 		    if (item[n].type == Highlight)
4039 		    {
4040 			group_start_userhl = group_end_userhl = item[n].minwid;
4041 			break;
4042 		    }
4043 		}
4044 		for (n = groupitem[groupdepth] + 1; n < curitem; n++)
4045 		{
4046 		    if (item[n].type == Normal)
4047 			break;
4048 		    if (item[n].type == Highlight)
4049 			group_end_userhl = item[n].minwid;
4050 		}
4051 		if (n == curitem && group_start_userhl == group_end_userhl)
4052 		{
4053 		    p = t;
4054 		    l = 0;
4055 		}
4056 	    }
4057 	    if (l > item[groupitem[groupdepth]].maxwid)
4058 	    {
4059 		/* truncate, remove n bytes of text at the start */
4060 #ifdef FEAT_MBYTE
4061 		if (has_mbyte)
4062 		{
4063 		    /* Find the first character that should be included. */
4064 		    n = 0;
4065 		    while (l >= item[groupitem[groupdepth]].maxwid)
4066 		    {
4067 			l -= ptr2cells(t + n);
4068 			n += (*mb_ptr2len)(t + n);
4069 		    }
4070 		}
4071 		else
4072 #endif
4073 		    n = (long)(p - t) - item[groupitem[groupdepth]].maxwid + 1;
4074 
4075 		*t = '<';
4076 		mch_memmove(t + 1, t + n, (size_t)(p - (t + n)));
4077 		p = p - n + 1;
4078 #ifdef FEAT_MBYTE
4079 		/* Fill up space left over by half a double-wide char. */
4080 		while (++l < item[groupitem[groupdepth]].minwid)
4081 		    *p++ = fillchar;
4082 #endif
4083 
4084 		/* correct the start of the items for the truncation */
4085 		for (l = groupitem[groupdepth] + 1; l < curitem; l++)
4086 		{
4087 		    item[l].start -= n;
4088 		    if (item[l].start < t)
4089 			item[l].start = t;
4090 		}
4091 	    }
4092 	    else if (abs(item[groupitem[groupdepth]].minwid) > l)
4093 	    {
4094 		/* fill */
4095 		n = item[groupitem[groupdepth]].minwid;
4096 		if (n < 0)
4097 		{
4098 		    /* fill by appending characters */
4099 		    n = 0 - n;
4100 		    while (l++ < n && p + 1 < out + outlen)
4101 			*p++ = fillchar;
4102 		}
4103 		else
4104 		{
4105 		    /* fill by inserting characters */
4106 		    mch_memmove(t + n - l, t, (size_t)(p - t));
4107 		    l = n - l;
4108 		    if (p + l >= out + outlen)
4109 			l = (long)((out + outlen) - p - 1);
4110 		    p += l;
4111 		    for (n = groupitem[groupdepth] + 1; n < curitem; n++)
4112 			item[n].start += l;
4113 		    for ( ; l > 0; l--)
4114 			*t++ = fillchar;
4115 		}
4116 	    }
4117 	    continue;
4118 	}
4119 	minwid = 0;
4120 	maxwid = 9999;
4121 	zeropad = FALSE;
4122 	l = 1;
4123 	if (*s == '0')
4124 	{
4125 	    s++;
4126 	    zeropad = TRUE;
4127 	}
4128 	if (*s == '-')
4129 	{
4130 	    s++;
4131 	    l = -1;
4132 	}
4133 	if (VIM_ISDIGIT(*s))
4134 	{
4135 	    minwid = (int)getdigits(&s);
4136 	    if (minwid < 0)	/* overflow */
4137 		minwid = 0;
4138 	}
4139 	if (*s == STL_USER_HL)
4140 	{
4141 	    item[curitem].type = Highlight;
4142 	    item[curitem].start = p;
4143 	    item[curitem].minwid = minwid > 9 ? 1 : minwid;
4144 	    s++;
4145 	    curitem++;
4146 	    continue;
4147 	}
4148 	if (*s == STL_TABPAGENR || *s == STL_TABCLOSENR)
4149 	{
4150 	    if (*s == STL_TABCLOSENR)
4151 	    {
4152 		if (minwid == 0)
4153 		{
4154 		    /* %X ends the close label, go back to the previously
4155 		     * define tab label nr. */
4156 		    for (n = curitem - 1; n >= 0; --n)
4157 			if (item[n].type == TabPage && item[n].minwid >= 0)
4158 			{
4159 			    minwid = item[n].minwid;
4160 			    break;
4161 			}
4162 		}
4163 		else
4164 		    /* close nrs are stored as negative values */
4165 		    minwid = - minwid;
4166 	    }
4167 	    item[curitem].type = TabPage;
4168 	    item[curitem].start = p;
4169 	    item[curitem].minwid = minwid;
4170 	    s++;
4171 	    curitem++;
4172 	    continue;
4173 	}
4174 	if (*s == '.')
4175 	{
4176 	    s++;
4177 	    if (VIM_ISDIGIT(*s))
4178 	    {
4179 		maxwid = (int)getdigits(&s);
4180 		if (maxwid <= 0)	/* overflow */
4181 		    maxwid = 50;
4182 	    }
4183 	}
4184 	minwid = (minwid > 50 ? 50 : minwid) * l;
4185 	if (*s == '(')
4186 	{
4187 	    groupitem[groupdepth++] = curitem;
4188 	    item[curitem].type = Group;
4189 	    item[curitem].start = p;
4190 	    item[curitem].minwid = minwid;
4191 	    item[curitem].maxwid = maxwid;
4192 	    s++;
4193 	    curitem++;
4194 	    continue;
4195 	}
4196 	if (vim_strchr(STL_ALL, *s) == NULL)
4197 	{
4198 	    s++;
4199 	    continue;
4200 	}
4201 	opt = *s++;
4202 
4203 	/* OK - now for the real work */
4204 	base = 'D';
4205 	itemisflag = FALSE;
4206 	fillable = TRUE;
4207 	num = -1;
4208 	str = NULL;
4209 	switch (opt)
4210 	{
4211 	case STL_FILEPATH:
4212 	case STL_FULLPATH:
4213 	case STL_FILENAME:
4214 	    fillable = FALSE;	/* don't change ' ' to fillchar */
4215 	    if (buf_spname(wp->w_buffer) != NULL)
4216 		vim_strncpy(NameBuff, buf_spname(wp->w_buffer), MAXPATHL - 1);
4217 	    else
4218 	    {
4219 		t = (opt == STL_FULLPATH) ? wp->w_buffer->b_ffname
4220 					  : wp->w_buffer->b_fname;
4221 		home_replace(wp->w_buffer, t, NameBuff, MAXPATHL, TRUE);
4222 	    }
4223 	    trans_characters(NameBuff, MAXPATHL);
4224 	    if (opt != STL_FILENAME)
4225 		str = NameBuff;
4226 	    else
4227 		str = gettail(NameBuff);
4228 	    break;
4229 
4230 	case STL_VIM_EXPR: /* '{' */
4231 	    itemisflag = TRUE;
4232 	    t = p;
4233 	    while (*s != '}' && *s != NUL && p + 1 < out + outlen)
4234 		*p++ = *s++;
4235 	    if (*s != '}')	/* missing '}' or out of space */
4236 		break;
4237 	    s++;
4238 	    *p = 0;
4239 	    p = t;
4240 
4241 #ifdef FEAT_EVAL
4242 	    vim_snprintf((char *)tmp, sizeof(tmp), "%d", curbuf->b_fnum);
4243 	    set_internal_string_var((char_u *)"actual_curbuf", tmp);
4244 
4245 	    save_curbuf = curbuf;
4246 	    save_curwin = curwin;
4247 	    curwin = wp;
4248 	    curbuf = wp->w_buffer;
4249 
4250 	    str = eval_to_string_safe(p, &t, use_sandbox);
4251 
4252 	    curwin = save_curwin;
4253 	    curbuf = save_curbuf;
4254 	    do_unlet((char_u *)"g:actual_curbuf", TRUE);
4255 
4256 	    if (str != NULL && *str != 0)
4257 	    {
4258 		if (*skipdigits(str) == NUL)
4259 		{
4260 		    num = atoi((char *)str);
4261 		    vim_free(str);
4262 		    str = NULL;
4263 		    itemisflag = FALSE;
4264 		}
4265 	    }
4266 #endif
4267 	    break;
4268 
4269 	case STL_LINE:
4270 	    num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY)
4271 		  ? 0L : (long)(wp->w_cursor.lnum);
4272 	    break;
4273 
4274 	case STL_NUMLINES:
4275 	    num = wp->w_buffer->b_ml.ml_line_count;
4276 	    break;
4277 
4278 	case STL_COLUMN:
4279 	    num = !(State & INSERT) && empty_line
4280 		  ? 0 : (int)wp->w_cursor.col + 1;
4281 	    break;
4282 
4283 	case STL_VIRTCOL:
4284 	case STL_VIRTCOL_ALT:
4285 	    /* In list mode virtcol needs to be recomputed */
4286 	    virtcol = wp->w_virtcol;
4287 	    if (wp->w_p_list && lcs_tab1 == NUL)
4288 	    {
4289 		wp->w_p_list = FALSE;
4290 		getvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL);
4291 		wp->w_p_list = TRUE;
4292 	    }
4293 	    ++virtcol;
4294 	    /* Don't display %V if it's the same as %c. */
4295 	    if (opt == STL_VIRTCOL_ALT
4296 		    && (virtcol == (colnr_T)(!(State & INSERT) && empty_line
4297 			    ? 0 : (int)wp->w_cursor.col + 1)))
4298 		break;
4299 	    num = (long)virtcol;
4300 	    break;
4301 
4302 	case STL_PERCENTAGE:
4303 	    num = (int)(((long)wp->w_cursor.lnum * 100L) /
4304 			(long)wp->w_buffer->b_ml.ml_line_count);
4305 	    break;
4306 
4307 	case STL_ALTPERCENT:
4308 	    str = tmp;
4309 	    get_rel_pos(wp, str, TMPLEN);
4310 	    break;
4311 
4312 	case STL_ARGLISTSTAT:
4313 	    fillable = FALSE;
4314 	    tmp[0] = 0;
4315 	    if (append_arg_number(wp, tmp, (int)sizeof(tmp), FALSE))
4316 		str = tmp;
4317 	    break;
4318 
4319 	case STL_KEYMAP:
4320 	    fillable = FALSE;
4321 	    if (get_keymap_str(wp, (char_u *)"<%s>", tmp, TMPLEN))
4322 		str = tmp;
4323 	    break;
4324 	case STL_PAGENUM:
4325 #if defined(FEAT_PRINTER) || defined(FEAT_GUI_TABLINE)
4326 	    num = printer_page_num;
4327 #else
4328 	    num = 0;
4329 #endif
4330 	    break;
4331 
4332 	case STL_BUFNO:
4333 	    num = wp->w_buffer->b_fnum;
4334 	    break;
4335 
4336 	case STL_OFFSET_X:
4337 	    base = 'X';
4338 	    /* FALLTHROUGH */
4339 	case STL_OFFSET:
4340 #ifdef FEAT_BYTEOFF
4341 	    l = ml_find_line_or_offset(wp->w_buffer, wp->w_cursor.lnum, NULL);
4342 	    num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) || l < 0 ?
4343 		  0L : l + 1 + (!(State & INSERT) && empty_line ?
4344 				0 : (int)wp->w_cursor.col);
4345 #endif
4346 	    break;
4347 
4348 	case STL_BYTEVAL_X:
4349 	    base = 'X';
4350 	    /* FALLTHROUGH */
4351 	case STL_BYTEVAL:
4352 	    num = byteval;
4353 	    if (num == NL)
4354 		num = 0;
4355 	    else if (num == CAR && get_fileformat(wp->w_buffer) == EOL_MAC)
4356 		num = NL;
4357 	    break;
4358 
4359 	case STL_ROFLAG:
4360 	case STL_ROFLAG_ALT:
4361 	    itemisflag = TRUE;
4362 	    if (wp->w_buffer->b_p_ro)
4363 		str = (char_u *)((opt == STL_ROFLAG_ALT) ? ",RO" : _("[RO]"));
4364 	    break;
4365 
4366 	case STL_HELPFLAG:
4367 	case STL_HELPFLAG_ALT:
4368 	    itemisflag = TRUE;
4369 	    if (wp->w_buffer->b_help)
4370 		str = (char_u *)((opt == STL_HELPFLAG_ALT) ? ",HLP"
4371 							       : _("[Help]"));
4372 	    break;
4373 
4374 #ifdef FEAT_AUTOCMD
4375 	case STL_FILETYPE:
4376 	    if (*wp->w_buffer->b_p_ft != NUL
4377 		    && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 3)
4378 	    {
4379 		vim_snprintf((char *)tmp, sizeof(tmp), "[%s]",
4380 							wp->w_buffer->b_p_ft);
4381 		str = tmp;
4382 	    }
4383 	    break;
4384 
4385 	case STL_FILETYPE_ALT:
4386 	    itemisflag = TRUE;
4387 	    if (*wp->w_buffer->b_p_ft != NUL
4388 		    && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 2)
4389 	    {
4390 		vim_snprintf((char *)tmp, sizeof(tmp), ",%s",
4391 							wp->w_buffer->b_p_ft);
4392 		for (t = tmp; *t != 0; t++)
4393 		    *t = TOUPPER_LOC(*t);
4394 		str = tmp;
4395 	    }
4396 	    break;
4397 #endif
4398 
4399 #if defined(FEAT_QUICKFIX)
4400 	case STL_PREVIEWFLAG:
4401 	case STL_PREVIEWFLAG_ALT:
4402 	    itemisflag = TRUE;
4403 	    if (wp->w_p_pvw)
4404 		str = (char_u *)((opt == STL_PREVIEWFLAG_ALT) ? ",PRV"
4405 							    : _("[Preview]"));
4406 	    break;
4407 
4408 	case STL_QUICKFIX:
4409 	    if (bt_quickfix(wp->w_buffer))
4410 		str = (char_u *)(wp->w_llist_ref
4411 			    ? _(msg_loclist)
4412 			    : _(msg_qflist));
4413 	    break;
4414 #endif
4415 
4416 	case STL_MODIFIED:
4417 	case STL_MODIFIED_ALT:
4418 	    itemisflag = TRUE;
4419 	    switch ((opt == STL_MODIFIED_ALT)
4420 		    + bufIsChanged(wp->w_buffer) * 2
4421 		    + (!wp->w_buffer->b_p_ma) * 4)
4422 	    {
4423 		case 2: str = (char_u *)"[+]"; break;
4424 		case 3: str = (char_u *)",+"; break;
4425 		case 4: str = (char_u *)"[-]"; break;
4426 		case 5: str = (char_u *)",-"; break;
4427 		case 6: str = (char_u *)"[+-]"; break;
4428 		case 7: str = (char_u *)",+-"; break;
4429 	    }
4430 	    break;
4431 
4432 	case STL_HIGHLIGHT:
4433 	    t = s;
4434 	    while (*s != '#' && *s != NUL)
4435 		++s;
4436 	    if (*s == '#')
4437 	    {
4438 		item[curitem].type = Highlight;
4439 		item[curitem].start = p;
4440 		item[curitem].minwid = -syn_namen2id(t, (int)(s - t));
4441 		curitem++;
4442 	    }
4443 	    if (*s != NUL)
4444 		++s;
4445 	    continue;
4446 	}
4447 
4448 	item[curitem].start = p;
4449 	item[curitem].type = Normal;
4450 	if (str != NULL && *str)
4451 	{
4452 	    t = str;
4453 	    if (itemisflag)
4454 	    {
4455 		if ((t[0] && t[1])
4456 			&& ((!prevchar_isitem && *t == ',')
4457 			      || (prevchar_isflag && *t == ' ')))
4458 		    t++;
4459 		prevchar_isflag = TRUE;
4460 	    }
4461 	    l = vim_strsize(t);
4462 	    if (l > 0)
4463 		prevchar_isitem = TRUE;
4464 	    if (l > maxwid)
4465 	    {
4466 		while (l >= maxwid)
4467 #ifdef FEAT_MBYTE
4468 		    if (has_mbyte)
4469 		    {
4470 			l -= ptr2cells(t);
4471 			t += (*mb_ptr2len)(t);
4472 		    }
4473 		    else
4474 #endif
4475 			l -= byte2cells(*t++);
4476 		if (p + 1 >= out + outlen)
4477 		    break;
4478 		*p++ = '<';
4479 	    }
4480 	    if (minwid > 0)
4481 	    {
4482 		for (; l < minwid && p + 1 < out + outlen; l++)
4483 		{
4484 		    /* Don't put a "-" in front of a digit. */
4485 		    if (l + 1 == minwid && fillchar == '-' && VIM_ISDIGIT(*t))
4486 			*p++ = ' ';
4487 		    else
4488 			*p++ = fillchar;
4489 		}
4490 		minwid = 0;
4491 	    }
4492 	    else
4493 		minwid *= -1;
4494 	    while (*t && p + 1 < out + outlen)
4495 	    {
4496 		*p++ = *t++;
4497 		/* Change a space by fillchar, unless fillchar is '-' and a
4498 		 * digit follows. */
4499 		if (fillable && p[-1] == ' '
4500 				     && (!VIM_ISDIGIT(*t) || fillchar != '-'))
4501 		    p[-1] = fillchar;
4502 	    }
4503 	    for (; l < minwid && p + 1 < out + outlen; l++)
4504 		*p++ = fillchar;
4505 	}
4506 	else if (num >= 0)
4507 	{
4508 	    int nbase = (base == 'D' ? 10 : (base == 'O' ? 8 : 16));
4509 	    char_u nstr[20];
4510 
4511 	    if (p + 20 >= out + outlen)
4512 		break;		/* not sufficient space */
4513 	    prevchar_isitem = TRUE;
4514 	    t = nstr;
4515 	    if (opt == STL_VIRTCOL_ALT)
4516 	    {
4517 		*t++ = '-';
4518 		minwid--;
4519 	    }
4520 	    *t++ = '%';
4521 	    if (zeropad)
4522 		*t++ = '0';
4523 	    *t++ = '*';
4524 	    *t++ = nbase == 16 ? base : (char_u)(nbase == 8 ? 'o' : 'd');
4525 	    *t = 0;
4526 
4527 	    for (n = num, l = 1; n >= nbase; n /= nbase)
4528 		l++;
4529 	    if (opt == STL_VIRTCOL_ALT)
4530 		l++;
4531 	    if (l > maxwid)
4532 	    {
4533 		l += 2;
4534 		n = l - maxwid;
4535 		while (l-- > maxwid)
4536 		    num /= nbase;
4537 		*t++ = '>';
4538 		*t++ = '%';
4539 		*t = t[-3];
4540 		*++t = 0;
4541 		vim_snprintf((char *)p, outlen - (p - out), (char *)nstr,
4542 								   0, num, n);
4543 	    }
4544 	    else
4545 		vim_snprintf((char *)p, outlen - (p - out), (char *)nstr,
4546 								 minwid, num);
4547 	    p += STRLEN(p);
4548 	}
4549 	else
4550 	    item[curitem].type = Empty;
4551 
4552 	if (opt == STL_VIM_EXPR)
4553 	    vim_free(str);
4554 
4555 	if (num >= 0 || (!itemisflag && str && *str))
4556 	    prevchar_isflag = FALSE;	    /* Item not NULL, but not a flag */
4557 	curitem++;
4558     }
4559     *p = NUL;
4560     itemcnt = curitem;
4561 
4562 #ifdef FEAT_EVAL
4563     if (usefmt != fmt)
4564 	vim_free(usefmt);
4565 #endif
4566 
4567     width = vim_strsize(out);
4568     if (maxwidth > 0 && width > maxwidth)
4569     {
4570 	/* Result is too long, must truncate somewhere. */
4571 	l = 0;
4572 	if (itemcnt == 0)
4573 	    s = out;
4574 	else
4575 	{
4576 	    for ( ; l < itemcnt; l++)
4577 		if (item[l].type == Trunc)
4578 		{
4579 		    /* Truncate at %< item. */
4580 		    s = item[l].start;
4581 		    break;
4582 		}
4583 	    if (l == itemcnt)
4584 	    {
4585 		/* No %< item, truncate first item. */
4586 		s = item[0].start;
4587 		l = 0;
4588 	    }
4589 	}
4590 
4591 	if (width - vim_strsize(s) >= maxwidth)
4592 	{
4593 	    /* Truncation mark is beyond max length */
4594 #ifdef FEAT_MBYTE
4595 	    if (has_mbyte)
4596 	    {
4597 		s = out;
4598 		width = 0;
4599 		for (;;)
4600 		{
4601 		    width += ptr2cells(s);
4602 		    if (width >= maxwidth)
4603 			break;
4604 		    s += (*mb_ptr2len)(s);
4605 		}
4606 		/* Fill up for half a double-wide character. */
4607 		while (++width < maxwidth)
4608 		    *s++ = fillchar;
4609 	    }
4610 	    else
4611 #endif
4612 		s = out + maxwidth - 1;
4613 	    for (l = 0; l < itemcnt; l++)
4614 		if (item[l].start > s)
4615 		    break;
4616 	    itemcnt = l;
4617 	    *s++ = '>';
4618 	    *s = 0;
4619 	}
4620 	else
4621 	{
4622 #ifdef FEAT_MBYTE
4623 	    if (has_mbyte)
4624 	    {
4625 		n = 0;
4626 		while (width >= maxwidth)
4627 		{
4628 		    width -= ptr2cells(s + n);
4629 		    n += (*mb_ptr2len)(s + n);
4630 		}
4631 	    }
4632 	    else
4633 #endif
4634 		n = width - maxwidth + 1;
4635 	    p = s + n;
4636 	    STRMOVE(s + 1, p);
4637 	    *s = '<';
4638 
4639 	    /* Fill up for half a double-wide character. */
4640 	    while (++width < maxwidth)
4641 	    {
4642 		s = s + STRLEN(s);
4643 		*s++ = fillchar;
4644 		*s = NUL;
4645 	    }
4646 
4647 	    --n;	/* count the '<' */
4648 	    for (; l < itemcnt; l++)
4649 	    {
4650 		if (item[l].start - n >= s)
4651 		    item[l].start -= n;
4652 		else
4653 		    item[l].start = s;
4654 	    }
4655 	}
4656 	width = maxwidth;
4657     }
4658     else if (width < maxwidth && STRLEN(out) + maxwidth - width + 1 < outlen)
4659     {
4660 	/* Apply STL_MIDDLE if any */
4661 	for (l = 0; l < itemcnt; l++)
4662 	    if (item[l].type == Middle)
4663 		break;
4664 	if (l < itemcnt)
4665 	{
4666 	    p = item[l].start + maxwidth - width;
4667 	    STRMOVE(p, item[l].start);
4668 	    for (s = item[l].start; s < p; s++)
4669 		*s = fillchar;
4670 	    for (l++; l < itemcnt; l++)
4671 		item[l].start += maxwidth - width;
4672 	    width = maxwidth;
4673 	}
4674     }
4675 
4676     /* Store the info about highlighting. */
4677     if (hltab != NULL)
4678     {
4679 	sp = hltab;
4680 	for (l = 0; l < itemcnt; l++)
4681 	{
4682 	    if (item[l].type == Highlight)
4683 	    {
4684 		sp->start = item[l].start;
4685 		sp->userhl = item[l].minwid;
4686 		sp++;
4687 	    }
4688 	}
4689 	sp->start = NULL;
4690 	sp->userhl = 0;
4691     }
4692 
4693     /* Store the info about tab pages labels. */
4694     if (tabtab != NULL)
4695     {
4696 	sp = tabtab;
4697 	for (l = 0; l < itemcnt; l++)
4698 	{
4699 	    if (item[l].type == TabPage)
4700 	    {
4701 		sp->start = item[l].start;
4702 		sp->userhl = item[l].minwid;
4703 		sp++;
4704 	    }
4705 	}
4706 	sp->start = NULL;
4707 	sp->userhl = 0;
4708     }
4709 
4710     /* When inside update_screen we do not want redrawing a stausline, ruler,
4711      * title, etc. to trigger another redraw, it may cause an endless loop. */
4712     if (updating_screen)
4713     {
4714 	must_redraw = save_must_redraw;
4715 	curwin->w_redr_type = save_redr_type;
4716     }
4717 
4718     return width;
4719 }
4720 #endif /* FEAT_STL_OPT */
4721 
4722 #if defined(FEAT_STL_OPT) || defined(FEAT_CMDL_INFO) \
4723 	    || defined(FEAT_GUI_TABLINE) || defined(PROTO)
4724 /*
4725  * Get relative cursor position in window into "buf[buflen]", in the form 99%,
4726  * using "Top", "Bot" or "All" when appropriate.
4727  */
4728     void
4729 get_rel_pos(
4730     win_T	*wp,
4731     char_u	*buf,
4732     int		buflen)
4733 {
4734     long	above; /* number of lines above window */
4735     long	below; /* number of lines below window */
4736 
4737     if (buflen < 3) /* need at least 3 chars for writing */
4738 	return;
4739     above = wp->w_topline - 1;
4740 #ifdef FEAT_DIFF
4741     above += diff_check_fill(wp, wp->w_topline) - wp->w_topfill;
4742     if (wp->w_topline == 1 && wp->w_topfill >= 1)
4743 	above = 0;  /* All buffer lines are displayed and there is an
4744 		     * indication of filler lines, that can be considered
4745 		     * seeing all lines. */
4746 #endif
4747     below = wp->w_buffer->b_ml.ml_line_count - wp->w_botline + 1;
4748     if (below <= 0)
4749 	vim_strncpy(buf, (char_u *)(above == 0 ? _("All") : _("Bot")),
4750 							(size_t)(buflen - 1));
4751     else if (above <= 0)
4752 	vim_strncpy(buf, (char_u *)_("Top"), (size_t)(buflen - 1));
4753     else
4754 	vim_snprintf((char *)buf, (size_t)buflen, "%2d%%", above > 1000000L
4755 				    ? (int)(above / ((above + below) / 100L))
4756 				    : (int)(above * 100L / (above + below)));
4757 }
4758 #endif
4759 
4760 /*
4761  * Append (file 2 of 8) to "buf[buflen]", if editing more than one file.
4762  * Return TRUE if it was appended.
4763  */
4764     static int
4765 append_arg_number(
4766     win_T	*wp,
4767     char_u	*buf,
4768     int		buflen,
4769     int		add_file)	/* Add "file" before the arg number */
4770 {
4771     char_u	*p;
4772 
4773     if (ARGCOUNT <= 1)		/* nothing to do */
4774 	return FALSE;
4775 
4776     p = buf + STRLEN(buf);	/* go to the end of the buffer */
4777     if (p - buf + 35 >= buflen)	/* getting too long */
4778 	return FALSE;
4779     *p++ = ' ';
4780     *p++ = '(';
4781     if (add_file)
4782     {
4783 	STRCPY(p, "file ");
4784 	p += 5;
4785     }
4786     vim_snprintf((char *)p, (size_t)(buflen - (p - buf)),
4787 		wp->w_arg_idx_invalid ? "(%d) of %d)"
4788 				  : "%d of %d)", wp->w_arg_idx + 1, ARGCOUNT);
4789     return TRUE;
4790 }
4791 
4792 /*
4793  * If fname is not a full path, make it a full path.
4794  * Returns pointer to allocated memory (NULL for failure).
4795  */
4796     char_u  *
4797 fix_fname(char_u  *fname)
4798 {
4799     /*
4800      * Force expanding the path always for Unix, because symbolic links may
4801      * mess up the full path name, even though it starts with a '/'.
4802      * Also expand when there is ".." in the file name, try to remove it,
4803      * because "c:/src/../README" is equal to "c:/README".
4804      * Similarly "c:/src//file" is equal to "c:/src/file".
4805      * For MS-Windows also expand names like "longna~1" to "longname".
4806      */
4807 #ifdef UNIX
4808     return FullName_save(fname, TRUE);
4809 #else
4810     if (!vim_isAbsName(fname)
4811 	    || strstr((char *)fname, "..") != NULL
4812 	    || strstr((char *)fname, "//") != NULL
4813 # ifdef BACKSLASH_IN_FILENAME
4814 	    || strstr((char *)fname, "\\\\") != NULL
4815 # endif
4816 # if defined(MSWIN)
4817 	    || vim_strchr(fname, '~') != NULL
4818 # endif
4819 	    )
4820 	return FullName_save(fname, FALSE);
4821 
4822     fname = vim_strsave(fname);
4823 
4824 # ifdef USE_FNAME_CASE
4825 #  ifdef USE_LONG_FNAME
4826     if (USE_LONG_FNAME)
4827 #  endif
4828     {
4829 	if (fname != NULL)
4830 	    fname_case(fname, 0);	/* set correct case for file name */
4831     }
4832 # endif
4833 
4834     return fname;
4835 #endif
4836 }
4837 
4838 /*
4839  * Make "ffname" a full file name, set "sfname" to "ffname" if not NULL.
4840  * "ffname" becomes a pointer to allocated memory (or NULL).
4841  */
4842     void
4843 fname_expand(
4844     buf_T	*buf UNUSED,
4845     char_u	**ffname,
4846     char_u	**sfname)
4847 {
4848     if (*ffname == NULL)	/* if no file name given, nothing to do */
4849 	return;
4850     if (*sfname == NULL)	/* if no short file name given, use ffname */
4851 	*sfname = *ffname;
4852     *ffname = fix_fname(*ffname);   /* expand to full path */
4853 
4854 #ifdef FEAT_SHORTCUT
4855     if (!buf->b_p_bin)
4856     {
4857 	char_u  *rfname;
4858 
4859 	/* If the file name is a shortcut file, use the file it links to. */
4860 	rfname = mch_resolve_shortcut(*ffname);
4861 	if (rfname != NULL)
4862 	{
4863 	    vim_free(*ffname);
4864 	    *ffname = rfname;
4865 	    *sfname = rfname;
4866 	}
4867     }
4868 #endif
4869 }
4870 
4871 /*
4872  * Get the file name for an argument list entry.
4873  */
4874     char_u *
4875 alist_name(aentry_T *aep)
4876 {
4877     buf_T	*bp;
4878 
4879     /* Use the name from the associated buffer if it exists. */
4880     bp = buflist_findnr(aep->ae_fnum);
4881     if (bp == NULL || bp->b_fname == NULL)
4882 	return aep->ae_fname;
4883     return bp->b_fname;
4884 }
4885 
4886 /*
4887  * do_arg_all(): Open up to 'count' windows, one for each argument.
4888  */
4889     void
4890 do_arg_all(
4891     int	count,
4892     int	forceit,		/* hide buffers in current windows */
4893     int keep_tabs)		/* keep current tabs, for ":tab drop file" */
4894 {
4895     int		i;
4896     win_T	*wp, *wpnext;
4897     char_u	*opened;	/* Array of weight for which args are open:
4898 				 *  0: not opened
4899 				 *  1: opened in other tab
4900 				 *  2: opened in curtab
4901 				 *  3: opened in curtab and curwin
4902 				 */
4903     int		opened_len;	/* length of opened[] */
4904     int		use_firstwin = FALSE;	/* use first window for arglist */
4905     int		split_ret = OK;
4906     int		p_ea_save;
4907     alist_T	*alist;		/* argument list to be used */
4908     buf_T	*buf;
4909     tabpage_T	*tpnext;
4910     int		had_tab = cmdmod.tab;
4911     win_T	*old_curwin, *last_curwin;
4912     tabpage_T	*old_curtab, *last_curtab;
4913     win_T	*new_curwin = NULL;
4914     tabpage_T	*new_curtab = NULL;
4915 
4916     if (ARGCOUNT <= 0)
4917     {
4918 	/* Don't give an error message.  We don't want it when the ":all"
4919 	 * command is in the .vimrc. */
4920 	return;
4921     }
4922     setpcmark();
4923 
4924     opened_len = ARGCOUNT;
4925     opened = alloc_clear((unsigned)opened_len);
4926     if (opened == NULL)
4927 	return;
4928 
4929     /* Autocommands may do anything to the argument list.  Make sure it's not
4930      * freed while we are working here by "locking" it.  We still have to
4931      * watch out for its size to be changed. */
4932     alist = curwin->w_alist;
4933     ++alist->al_refcount;
4934 
4935     old_curwin = curwin;
4936     old_curtab = curtab;
4937 
4938 # ifdef FEAT_GUI
4939     need_mouse_correct = TRUE;
4940 # endif
4941 
4942     /*
4943      * Try closing all windows that are not in the argument list.
4944      * Also close windows that are not full width;
4945      * When 'hidden' or "forceit" set the buffer becomes hidden.
4946      * Windows that have a changed buffer and can't be hidden won't be closed.
4947      * When the ":tab" modifier was used do this for all tab pages.
4948      */
4949     if (had_tab > 0)
4950 	goto_tabpage_tp(first_tabpage, TRUE, TRUE);
4951     for (;;)
4952     {
4953 	tpnext = curtab->tp_next;
4954 	for (wp = firstwin; wp != NULL; wp = wpnext)
4955 	{
4956 	    wpnext = wp->w_next;
4957 	    buf = wp->w_buffer;
4958 	    if (buf->b_ffname == NULL
4959 		    || (!keep_tabs && (buf->b_nwindows > 1
4960 			    || wp->w_width != Columns)))
4961 		i = opened_len;
4962 	    else
4963 	    {
4964 		/* check if the buffer in this window is in the arglist */
4965 		for (i = 0; i < opened_len; ++i)
4966 		{
4967 		    if (i < alist->al_ga.ga_len
4968 			    && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum
4969 				|| fullpathcmp(alist_name(&AARGLIST(alist)[i]),
4970 					      buf->b_ffname, TRUE) & FPC_SAME))
4971 		    {
4972 			int weight = 1;
4973 
4974 			if (old_curtab == curtab)
4975 			{
4976 			    ++weight;
4977 			    if (old_curwin == wp)
4978 				++weight;
4979 			}
4980 
4981 			if (weight > (int)opened[i])
4982 			{
4983 			    opened[i] = (char_u)weight;
4984 			    if (i == 0)
4985 			    {
4986 				if (new_curwin != NULL)
4987 				    new_curwin->w_arg_idx = opened_len;
4988 				new_curwin = wp;
4989 				new_curtab = curtab;
4990 			    }
4991 			}
4992 			else if (keep_tabs)
4993 			    i = opened_len;
4994 
4995 			if (wp->w_alist != alist)
4996 			{
4997 			    /* Use the current argument list for all windows
4998 			     * containing a file from it. */
4999 			    alist_unlink(wp->w_alist);
5000 			    wp->w_alist = alist;
5001 			    ++wp->w_alist->al_refcount;
5002 			}
5003 			break;
5004 		    }
5005 		}
5006 	    }
5007 	    wp->w_arg_idx = i;
5008 
5009 	    if (i == opened_len && !keep_tabs)/* close this window */
5010 	    {
5011 		if (buf_hide(buf) || forceit || buf->b_nwindows > 1
5012 							|| !bufIsChanged(buf))
5013 		{
5014 		    /* If the buffer was changed, and we would like to hide it,
5015 		     * try autowriting. */
5016 		    if (!buf_hide(buf) && buf->b_nwindows <= 1
5017 							 && bufIsChanged(buf))
5018 		    {
5019 #ifdef FEAT_AUTOCMD
5020 			bufref_T    bufref;
5021 
5022 			set_bufref(&bufref, buf);
5023 #endif
5024 			(void)autowrite(buf, FALSE);
5025 #ifdef FEAT_AUTOCMD
5026 			/* check if autocommands removed the window */
5027 			if (!win_valid(wp) || !bufref_valid(&bufref))
5028 			{
5029 			    wpnext = firstwin;	/* start all over... */
5030 			    continue;
5031 			}
5032 #endif
5033 		    }
5034 		    /* don't close last window */
5035 		    if (ONE_WINDOW
5036 			    && (first_tabpage->tp_next == NULL || !had_tab))
5037 			use_firstwin = TRUE;
5038 		    else
5039 		    {
5040 			win_close(wp, !buf_hide(buf) && !bufIsChanged(buf));
5041 #ifdef FEAT_AUTOCMD
5042 			/* check if autocommands removed the next window */
5043 			if (!win_valid(wpnext))
5044 			    wpnext = firstwin;	/* start all over... */
5045 #endif
5046 		    }
5047 		}
5048 	    }
5049 	}
5050 
5051 	/* Without the ":tab" modifier only do the current tab page. */
5052 	if (had_tab == 0 || tpnext == NULL)
5053 	    break;
5054 
5055 # ifdef FEAT_AUTOCMD
5056 	/* check if autocommands removed the next tab page */
5057 	if (!valid_tabpage(tpnext))
5058 	    tpnext = first_tabpage;	/* start all over...*/
5059 # endif
5060 	goto_tabpage_tp(tpnext, TRUE, TRUE);
5061     }
5062 
5063     /*
5064      * Open a window for files in the argument list that don't have one.
5065      * ARGCOUNT may change while doing this, because of autocommands.
5066      */
5067     if (count > opened_len || count <= 0)
5068 	count = opened_len;
5069 
5070 #ifdef FEAT_AUTOCMD
5071     /* Don't execute Win/Buf Enter/Leave autocommands here. */
5072     ++autocmd_no_enter;
5073     ++autocmd_no_leave;
5074 #endif
5075     last_curwin = curwin;
5076     last_curtab = curtab;
5077     win_enter(lastwin, FALSE);
5078     /* ":drop all" should re-use an empty window to avoid "--remote-tab"
5079      * leaving an empty tab page when executed locally. */
5080     if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1
5081 			    && curbuf->b_ffname == NULL && !curbuf->b_changed)
5082 	use_firstwin = TRUE;
5083 
5084     for (i = 0; i < count && i < opened_len && !got_int; ++i)
5085     {
5086 	if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)
5087 	    arg_had_last = TRUE;
5088 	if (opened[i] > 0)
5089 	{
5090 	    /* Move the already present window to below the current window */
5091 	    if (curwin->w_arg_idx != i)
5092 	    {
5093 		for (wpnext = firstwin; wpnext != NULL; wpnext = wpnext->w_next)
5094 		{
5095 		    if (wpnext->w_arg_idx == i)
5096 		    {
5097 			if (keep_tabs)
5098 			{
5099 			    new_curwin = wpnext;
5100 			    new_curtab = curtab;
5101 			}
5102 			else
5103 			    win_move_after(wpnext, curwin);
5104 			break;
5105 		    }
5106 		}
5107 	    }
5108 	}
5109 	else if (split_ret == OK)
5110 	{
5111 	    if (!use_firstwin)		/* split current window */
5112 	    {
5113 		p_ea_save = p_ea;
5114 		p_ea = TRUE;		/* use space from all windows */
5115 		split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
5116 		p_ea = p_ea_save;
5117 		if (split_ret == FAIL)
5118 		    continue;
5119 	    }
5120 #ifdef FEAT_AUTOCMD
5121 	    else    /* first window: do autocmd for leaving this buffer */
5122 		--autocmd_no_leave;
5123 #endif
5124 
5125 	    /*
5126 	     * edit file "i"
5127 	     */
5128 	    curwin->w_arg_idx = i;
5129 	    if (i == 0)
5130 	    {
5131 		new_curwin = curwin;
5132 		new_curtab = curtab;
5133 	    }
5134 	    (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,
5135 		      ECMD_ONE,
5136 		      ((buf_hide(curwin->w_buffer)
5137 			   || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)
5138 						       + ECMD_OLDBUF, curwin);
5139 #ifdef FEAT_AUTOCMD
5140 	    if (use_firstwin)
5141 		++autocmd_no_leave;
5142 #endif
5143 	    use_firstwin = FALSE;
5144 	}
5145 	ui_breakcheck();
5146 
5147 	/* When ":tab" was used open a new tab for a new window repeatedly. */
5148 	if (had_tab > 0 && tabpage_index(NULL) <= p_tpm)
5149 	    cmdmod.tab = 9999;
5150     }
5151 
5152     /* Remove the "lock" on the argument list. */
5153     alist_unlink(alist);
5154 
5155 #ifdef FEAT_AUTOCMD
5156     --autocmd_no_enter;
5157 #endif
5158     /* restore last referenced tabpage's curwin */
5159     if (last_curtab != new_curtab)
5160     {
5161 	if (valid_tabpage(last_curtab))
5162 	    goto_tabpage_tp(last_curtab, TRUE, TRUE);
5163 	if (win_valid(last_curwin))
5164 	    win_enter(last_curwin, FALSE);
5165     }
5166     /* to window with first arg */
5167     if (valid_tabpage(new_curtab))
5168 	goto_tabpage_tp(new_curtab, TRUE, TRUE);
5169     if (win_valid(new_curwin))
5170 	win_enter(new_curwin, FALSE);
5171 
5172 #ifdef FEAT_AUTOCMD
5173     --autocmd_no_leave;
5174 #endif
5175     vim_free(opened);
5176 }
5177 
5178 # if defined(FEAT_LISTCMDS) || defined(PROTO)
5179 /*
5180  * Open a window for a number of buffers.
5181  */
5182     void
5183 ex_buffer_all(exarg_T *eap)
5184 {
5185     buf_T	*buf;
5186     win_T	*wp, *wpnext;
5187     int		split_ret = OK;
5188     int		p_ea_save;
5189     int		open_wins = 0;
5190     int		r;
5191     int		count;		/* Maximum number of windows to open. */
5192     int		all;		/* When TRUE also load inactive buffers. */
5193     int		had_tab = cmdmod.tab;
5194     tabpage_T	*tpnext;
5195 
5196     if (eap->addr_count == 0)	/* make as many windows as possible */
5197 	count = 9999;
5198     else
5199 	count = eap->line2;	/* make as many windows as specified */
5200     if (eap->cmdidx == CMD_unhide || eap->cmdidx == CMD_sunhide)
5201 	all = FALSE;
5202     else
5203 	all = TRUE;
5204 
5205     setpcmark();
5206 
5207 #ifdef FEAT_GUI
5208     need_mouse_correct = TRUE;
5209 #endif
5210 
5211     /*
5212      * Close superfluous windows (two windows for the same buffer).
5213      * Also close windows that are not full-width.
5214      */
5215     if (had_tab > 0)
5216 	goto_tabpage_tp(first_tabpage, TRUE, TRUE);
5217     for (;;)
5218     {
5219 	tpnext = curtab->tp_next;
5220 	for (wp = firstwin; wp != NULL; wp = wpnext)
5221 	{
5222 	    wpnext = wp->w_next;
5223 	    if ((wp->w_buffer->b_nwindows > 1
5224 		    || ((cmdmod.split & WSP_VERT)
5225 			? wp->w_height + wp->w_status_height < Rows - p_ch
5226 							    - tabline_height()
5227 			: wp->w_width != Columns)
5228 		    || (had_tab > 0 && wp != firstwin)) && !ONE_WINDOW
5229 #ifdef FEAT_AUTOCMD
5230 		    && !(wp->w_closing || wp->w_buffer->b_locked > 0)
5231 #endif
5232 		    )
5233 	    {
5234 		win_close(wp, FALSE);
5235 #ifdef FEAT_AUTOCMD
5236 		wpnext = firstwin;	/* just in case an autocommand does
5237 					   something strange with windows */
5238 		tpnext = first_tabpage;	/* start all over...*/
5239 		open_wins = 0;
5240 #endif
5241 	    }
5242 	    else
5243 		++open_wins;
5244 	}
5245 
5246 	/* Without the ":tab" modifier only do the current tab page. */
5247 	if (had_tab == 0 || tpnext == NULL)
5248 	    break;
5249 	goto_tabpage_tp(tpnext, TRUE, TRUE);
5250     }
5251 
5252     /*
5253      * Go through the buffer list.  When a buffer doesn't have a window yet,
5254      * open one.  Otherwise move the window to the right position.
5255      * Watch out for autocommands that delete buffers or windows!
5256      */
5257 #ifdef FEAT_AUTOCMD
5258     /* Don't execute Win/Buf Enter/Leave autocommands here. */
5259     ++autocmd_no_enter;
5260 #endif
5261     win_enter(lastwin, FALSE);
5262 #ifdef FEAT_AUTOCMD
5263     ++autocmd_no_leave;
5264 #endif
5265     for (buf = firstbuf; buf != NULL && open_wins < count; buf = buf->b_next)
5266     {
5267 	/* Check if this buffer needs a window */
5268 	if ((!all && buf->b_ml.ml_mfp == NULL) || !buf->b_p_bl)
5269 	    continue;
5270 
5271 	if (had_tab != 0)
5272 	{
5273 	    /* With the ":tab" modifier don't move the window. */
5274 	    if (buf->b_nwindows > 0)
5275 		wp = lastwin;	    /* buffer has a window, skip it */
5276 	    else
5277 		wp = NULL;
5278 	}
5279 	else
5280 	{
5281 	    /* Check if this buffer already has a window */
5282 	    FOR_ALL_WINDOWS(wp)
5283 		if (wp->w_buffer == buf)
5284 		    break;
5285 	    /* If the buffer already has a window, move it */
5286 	    if (wp != NULL)
5287 		win_move_after(wp, curwin);
5288 	}
5289 
5290 	if (wp == NULL && split_ret == OK)
5291 	{
5292 #ifdef FEAT_AUTOCMD
5293 	    bufref_T	bufref;
5294 
5295 	    set_bufref(&bufref, buf);
5296 #endif
5297 	    /* Split the window and put the buffer in it */
5298 	    p_ea_save = p_ea;
5299 	    p_ea = TRUE;		/* use space from all windows */
5300 	    split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
5301 	    ++open_wins;
5302 	    p_ea = p_ea_save;
5303 	    if (split_ret == FAIL)
5304 		continue;
5305 
5306 	    /* Open the buffer in this window. */
5307 #if defined(HAS_SWAP_EXISTS_ACTION)
5308 	    swap_exists_action = SEA_DIALOG;
5309 #endif
5310 	    set_curbuf(buf, DOBUF_GOTO);
5311 #ifdef FEAT_AUTOCMD
5312 	    if (!bufref_valid(&bufref))
5313 	    {
5314 		/* autocommands deleted the buffer!!! */
5315 #if defined(HAS_SWAP_EXISTS_ACTION)
5316 		swap_exists_action = SEA_NONE;
5317 # endif
5318 		break;
5319 	    }
5320 #endif
5321 #if defined(HAS_SWAP_EXISTS_ACTION)
5322 	    if (swap_exists_action == SEA_QUIT)
5323 	    {
5324 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
5325 		cleanup_T   cs;
5326 
5327 		/* Reset the error/interrupt/exception state here so that
5328 		 * aborting() returns FALSE when closing a window. */
5329 		enter_cleanup(&cs);
5330 # endif
5331 
5332 		/* User selected Quit at ATTENTION prompt; close this window. */
5333 		win_close(curwin, TRUE);
5334 		--open_wins;
5335 		swap_exists_action = SEA_NONE;
5336 		swap_exists_did_quit = TRUE;
5337 
5338 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
5339 		/* Restore the error/interrupt/exception state if not
5340 		 * discarded by a new aborting error, interrupt, or uncaught
5341 		 * exception. */
5342 		leave_cleanup(&cs);
5343 # endif
5344 	    }
5345 	    else
5346 		handle_swap_exists(NULL);
5347 #endif
5348 	}
5349 
5350 	ui_breakcheck();
5351 	if (got_int)
5352 	{
5353 	    (void)vgetc();	/* only break the file loading, not the rest */
5354 	    break;
5355 	}
5356 #ifdef FEAT_EVAL
5357 	/* Autocommands deleted the buffer or aborted script processing!!! */
5358 	if (aborting())
5359 	    break;
5360 #endif
5361 	/* When ":tab" was used open a new tab for a new window repeatedly. */
5362 	if (had_tab > 0 && tabpage_index(NULL) <= p_tpm)
5363 	    cmdmod.tab = 9999;
5364     }
5365 #ifdef FEAT_AUTOCMD
5366     --autocmd_no_enter;
5367 #endif
5368     win_enter(firstwin, FALSE);		/* back to first window */
5369 #ifdef FEAT_AUTOCMD
5370     --autocmd_no_leave;
5371 #endif
5372 
5373     /*
5374      * Close superfluous windows.
5375      */
5376     for (wp = lastwin; open_wins > count; )
5377     {
5378 	r = (buf_hide(wp->w_buffer) || !bufIsChanged(wp->w_buffer)
5379 				     || autowrite(wp->w_buffer, FALSE) == OK);
5380 #ifdef FEAT_AUTOCMD
5381 	if (!win_valid(wp))
5382 	{
5383 	    /* BufWrite Autocommands made the window invalid, start over */
5384 	    wp = lastwin;
5385 	}
5386 	else
5387 #endif
5388 	    if (r)
5389 	{
5390 	    win_close(wp, !buf_hide(wp->w_buffer));
5391 	    --open_wins;
5392 	    wp = lastwin;
5393 	}
5394 	else
5395 	{
5396 	    wp = wp->w_prev;
5397 	    if (wp == NULL)
5398 		break;
5399 	}
5400     }
5401 }
5402 # endif /* FEAT_LISTCMDS */
5403 
5404 
5405 static int  chk_modeline(linenr_T, int);
5406 
5407 /*
5408  * do_modelines() - process mode lines for the current file
5409  *
5410  * "flags" can be:
5411  * OPT_WINONLY	    only set options local to window
5412  * OPT_NOWIN	    don't set options local to window
5413  *
5414  * Returns immediately if the "ml" option isn't set.
5415  */
5416     void
5417 do_modelines(int flags)
5418 {
5419     linenr_T	lnum;
5420     int		nmlines;
5421     static int	entered = 0;
5422 
5423     if (!curbuf->b_p_ml || (nmlines = (int)p_mls) == 0)
5424 	return;
5425 
5426     /* Disallow recursive entry here.  Can happen when executing a modeline
5427      * triggers an autocommand, which reloads modelines with a ":do". */
5428     if (entered)
5429 	return;
5430 
5431     ++entered;
5432     for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count && lnum <= nmlines;
5433 								       ++lnum)
5434 	if (chk_modeline(lnum, flags) == FAIL)
5435 	    nmlines = 0;
5436 
5437     for (lnum = curbuf->b_ml.ml_line_count; lnum > 0 && lnum > nmlines
5438 		       && lnum > curbuf->b_ml.ml_line_count - nmlines; --lnum)
5439 	if (chk_modeline(lnum, flags) == FAIL)
5440 	    nmlines = 0;
5441     --entered;
5442 }
5443 
5444 #include "version.h"		/* for version number */
5445 
5446 /*
5447  * chk_modeline() - check a single line for a mode string
5448  * Return FAIL if an error encountered.
5449  */
5450     static int
5451 chk_modeline(
5452     linenr_T	lnum,
5453     int		flags)		/* Same as for do_modelines(). */
5454 {
5455     char_u	*s;
5456     char_u	*e;
5457     char_u	*linecopy;		/* local copy of any modeline found */
5458     int		prev;
5459     int		vers;
5460     int		end;
5461     int		retval = OK;
5462     char_u	*save_sourcing_name;
5463     linenr_T	save_sourcing_lnum;
5464 #ifdef FEAT_EVAL
5465     scid_T	save_SID;
5466 #endif
5467 
5468     prev = -1;
5469     for (s = ml_get(lnum); *s != NUL; ++s)
5470     {
5471 	if (prev == -1 || vim_isspace(prev))
5472 	{
5473 	    if ((prev != -1 && STRNCMP(s, "ex:", (size_t)3) == 0)
5474 		    || STRNCMP(s, "vi:", (size_t)3) == 0)
5475 		break;
5476 	    /* Accept both "vim" and "Vim". */
5477 	    if ((s[0] == 'v' || s[0] == 'V') && s[1] == 'i' && s[2] == 'm')
5478 	    {
5479 		if (s[3] == '<' || s[3] == '=' || s[3] == '>')
5480 		    e = s + 4;
5481 		else
5482 		    e = s + 3;
5483 		vers = getdigits(&e);
5484 		if (*e == ':'
5485 			&& (s[0] != 'V'
5486 				  || STRNCMP(skipwhite(e + 1), "set", 3) == 0)
5487 			&& (s[3] == ':'
5488 			    || (VIM_VERSION_100 >= vers && isdigit(s[3]))
5489 			    || (VIM_VERSION_100 < vers && s[3] == '<')
5490 			    || (VIM_VERSION_100 > vers && s[3] == '>')
5491 			    || (VIM_VERSION_100 == vers && s[3] == '=')))
5492 		    break;
5493 	    }
5494 	}
5495 	prev = *s;
5496     }
5497 
5498     if (*s)
5499     {
5500 	do				/* skip over "ex:", "vi:" or "vim:" */
5501 	    ++s;
5502 	while (s[-1] != ':');
5503 
5504 	s = linecopy = vim_strsave(s);	/* copy the line, it will change */
5505 	if (linecopy == NULL)
5506 	    return FAIL;
5507 
5508 	save_sourcing_lnum = sourcing_lnum;
5509 	save_sourcing_name = sourcing_name;
5510 	sourcing_lnum = lnum;		/* prepare for emsg() */
5511 	sourcing_name = (char_u *)"modelines";
5512 
5513 	end = FALSE;
5514 	while (end == FALSE)
5515 	{
5516 	    s = skipwhite(s);
5517 	    if (*s == NUL)
5518 		break;
5519 
5520 	    /*
5521 	     * Find end of set command: ':' or end of line.
5522 	     * Skip over "\:", replacing it with ":".
5523 	     */
5524 	    for (e = s; *e != ':' && *e != NUL; ++e)
5525 		if (e[0] == '\\' && e[1] == ':')
5526 		    STRMOVE(e, e + 1);
5527 	    if (*e == NUL)
5528 		end = TRUE;
5529 
5530 	    /*
5531 	     * If there is a "set" command, require a terminating ':' and
5532 	     * ignore the stuff after the ':'.
5533 	     * "vi:set opt opt opt: foo" -- foo not interpreted
5534 	     * "vi:opt opt opt: foo" -- foo interpreted
5535 	     * Accept "se" for compatibility with Elvis.
5536 	     */
5537 	    if (STRNCMP(s, "set ", (size_t)4) == 0
5538 		    || STRNCMP(s, "se ", (size_t)3) == 0)
5539 	    {
5540 		if (*e != ':')		/* no terminating ':'? */
5541 		    break;
5542 		end = TRUE;
5543 		s = vim_strchr(s, ' ') + 1;
5544 	    }
5545 	    *e = NUL;			/* truncate the set command */
5546 
5547 	    if (*s != NUL)		/* skip over an empty "::" */
5548 	    {
5549 #ifdef FEAT_EVAL
5550 		save_SID = current_SID;
5551 		current_SID = SID_MODELINE;
5552 #endif
5553 		retval = do_set(s, OPT_MODELINE | OPT_LOCAL | flags);
5554 #ifdef FEAT_EVAL
5555 		current_SID = save_SID;
5556 #endif
5557 		if (retval == FAIL)		/* stop if error found */
5558 		    break;
5559 	    }
5560 	    s = e + 1;			/* advance to next part */
5561 	}
5562 
5563 	sourcing_lnum = save_sourcing_lnum;
5564 	sourcing_name = save_sourcing_name;
5565 
5566 	vim_free(linecopy);
5567     }
5568     return retval;
5569 }
5570 
5571 #if defined(FEAT_VIMINFO) || defined(PROTO)
5572     int
5573 read_viminfo_bufferlist(
5574     vir_T	*virp,
5575     int		writing)
5576 {
5577     char_u	*tab;
5578     linenr_T	lnum;
5579     colnr_T	col;
5580     buf_T	*buf;
5581     char_u	*sfname;
5582     char_u	*xline;
5583 
5584     /* Handle long line and escaped characters. */
5585     xline = viminfo_readstring(virp, 1, FALSE);
5586 
5587     /* don't read in if there are files on the command-line or if writing: */
5588     if (xline != NULL && !writing && ARGCOUNT == 0
5589 				       && find_viminfo_parameter('%') != NULL)
5590     {
5591 	/* Format is: <fname> Tab <lnum> Tab <col>.
5592 	 * Watch out for a Tab in the file name, work from the end. */
5593 	lnum = 0;
5594 	col = 0;
5595 	tab = vim_strrchr(xline, '\t');
5596 	if (tab != NULL)
5597 	{
5598 	    *tab++ = '\0';
5599 	    col = (colnr_T)atoi((char *)tab);
5600 	    tab = vim_strrchr(xline, '\t');
5601 	    if (tab != NULL)
5602 	    {
5603 		*tab++ = '\0';
5604 		lnum = atol((char *)tab);
5605 	    }
5606 	}
5607 
5608 	/* Expand "~/" in the file name at "line + 1" to a full path.
5609 	 * Then try shortening it by comparing with the current directory */
5610 	expand_env(xline, NameBuff, MAXPATHL);
5611 	sfname = shorten_fname1(NameBuff);
5612 
5613 	buf = buflist_new(NameBuff, sfname, (linenr_T)0, BLN_LISTED);
5614 	if (buf != NULL)	/* just in case... */
5615 	{
5616 	    buf->b_last_cursor.lnum = lnum;
5617 	    buf->b_last_cursor.col = col;
5618 	    buflist_setfpos(buf, curwin, lnum, col, FALSE);
5619 	}
5620     }
5621     vim_free(xline);
5622 
5623     return viminfo_readline(virp);
5624 }
5625 
5626     void
5627 write_viminfo_bufferlist(FILE *fp)
5628 {
5629     buf_T	*buf;
5630     win_T	*win;
5631     tabpage_T	*tp;
5632     char_u	*line;
5633     int		max_buffers;
5634 
5635     if (find_viminfo_parameter('%') == NULL)
5636 	return;
5637 
5638     /* Without a number -1 is returned: do all buffers. */
5639     max_buffers = get_viminfo_parameter('%');
5640 
5641     /* Allocate room for the file name, lnum and col. */
5642 #define LINE_BUF_LEN (MAXPATHL + 40)
5643     line = alloc(LINE_BUF_LEN);
5644     if (line == NULL)
5645 	return;
5646 
5647     FOR_ALL_TAB_WINDOWS(tp, win)
5648 	set_last_cursor(win);
5649 
5650     fputs(_("\n# Buffer list:\n"), fp);
5651     FOR_ALL_BUFFERS(buf)
5652     {
5653 	if (buf->b_fname == NULL
5654 		|| !buf->b_p_bl
5655 #ifdef FEAT_QUICKFIX
5656 		|| bt_quickfix(buf)
5657 #endif
5658 #ifdef FEAT_TERMINAL
5659 		|| bt_terminal(buf)
5660 #endif
5661 		|| removable(buf->b_ffname))
5662 	    continue;
5663 
5664 	if (max_buffers-- == 0)
5665 	    break;
5666 	putc('%', fp);
5667 	home_replace(NULL, buf->b_ffname, line, MAXPATHL, TRUE);
5668 	vim_snprintf_add((char *)line, LINE_BUF_LEN, "\t%ld\t%d",
5669 			(long)buf->b_last_cursor.lnum,
5670 			buf->b_last_cursor.col);
5671 	viminfo_writestring(fp, line);
5672     }
5673     vim_free(line);
5674 }
5675 #endif
5676 
5677 /*
5678  * Return TRUE if "buf" is the quickfix buffer.
5679  */
5680     int
5681 bt_quickfix(buf_T *buf)
5682 {
5683     return buf != NULL && buf->b_p_bt[0] == 'q';
5684 }
5685 
5686 /*
5687  * Return TRUE if "buf" is a terminal buffer.
5688  */
5689     int
5690 bt_terminal(buf_T *buf)
5691 {
5692     return buf != NULL && buf->b_p_bt[0] == 't';
5693 }
5694 
5695 /*
5696  * Return TRUE if "buf" is a help buffer.
5697  */
5698     int
5699 bt_help(buf_T *buf)
5700 {
5701     return buf != NULL && buf->b_help;
5702 }
5703 
5704 /*
5705  * Return TRUE if "buf" is a "nofile", "acwrite" or "terminal" buffer.
5706  * This means the buffer name is not a file name.
5707  */
5708     int
5709 bt_nofile(buf_T *buf)
5710 {
5711     return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f')
5712 	    || buf->b_p_bt[0] == 'a'
5713 	    || buf->b_p_bt[0] == 't');
5714 }
5715 
5716 /*
5717  * Return TRUE if "buf" is a "nowrite", "nofile" or "terminal" buffer.
5718  */
5719     int
5720 bt_dontwrite(buf_T *buf)
5721 {
5722     return buf != NULL && (buf->b_p_bt[0] == 'n' || buf->b_p_bt[0] == 't');
5723 }
5724 
5725     int
5726 bt_dontwrite_msg(buf_T *buf)
5727 {
5728     if (bt_dontwrite(buf))
5729     {
5730 	EMSG(_("E382: Cannot write, 'buftype' option is set"));
5731 	return TRUE;
5732     }
5733     return FALSE;
5734 }
5735 
5736 /*
5737  * Return TRUE if the buffer should be hidden, according to 'hidden', ":hide"
5738  * and 'bufhidden'.
5739  */
5740     int
5741 buf_hide(buf_T *buf)
5742 {
5743     /* 'bufhidden' overrules 'hidden' and ":hide", check it first */
5744     switch (buf->b_p_bh[0])
5745     {
5746 	case 'u':		    /* "unload" */
5747 	case 'w':		    /* "wipe" */
5748 	case 'd': return FALSE;	    /* "delete" */
5749 	case 'h': return TRUE;	    /* "hide" */
5750     }
5751     return (p_hid || cmdmod.hide);
5752 }
5753 
5754 /*
5755  * Return special buffer name.
5756  * Returns NULL when the buffer has a normal file name.
5757  */
5758     char_u *
5759 buf_spname(buf_T *buf)
5760 {
5761 #if defined(FEAT_QUICKFIX)
5762     if (bt_quickfix(buf))
5763     {
5764 	win_T	    *win;
5765 	tabpage_T   *tp;
5766 
5767 	/*
5768 	 * For location list window, w_llist_ref points to the location list.
5769 	 * For quickfix window, w_llist_ref is NULL.
5770 	 */
5771 	if (find_win_for_buf(buf, &win, &tp) == OK && win->w_llist_ref != NULL)
5772 	    return (char_u *)_(msg_loclist);
5773 	else
5774 	    return (char_u *)_(msg_qflist);
5775     }
5776 #endif
5777 
5778     /* There is no _file_ when 'buftype' is "nofile", b_sfname
5779      * contains the name as specified by the user. */
5780     if (bt_nofile(buf))
5781     {
5782 #ifdef FEAT_TERMINAL
5783 	if (buf->b_term != NULL)
5784 	    return term_get_status_text(buf->b_term);
5785 #endif
5786 	if (buf->b_fname != NULL)
5787 	    return buf->b_fname;
5788 	return (char_u *)_("[Scratch]");
5789     }
5790 
5791     if (buf->b_fname == NULL)
5792 	return (char_u *)_("[No Name]");
5793     return NULL;
5794 }
5795 
5796 #if defined(FEAT_JOB_CHANNEL) \
5797 	|| defined(FEAT_PYTHON) || defined(FEAT_PYTHON3) \
5798 	|| defined(PROTO)
5799 # define SWITCH_TO_WIN
5800 
5801 /*
5802  * Find a window that contains "buf" and switch to it.
5803  * If there is no such window, use the current window and change "curbuf".
5804  * Caller must initialize save_curbuf to NULL.
5805  * restore_win_for_buf() MUST be called later!
5806  */
5807     void
5808 switch_to_win_for_buf(
5809     buf_T	*buf,
5810     win_T	**save_curwinp,
5811     tabpage_T	**save_curtabp,
5812     bufref_T	*save_curbuf)
5813 {
5814     win_T	*wp;
5815     tabpage_T	*tp;
5816 
5817     if (find_win_for_buf(buf, &wp, &tp) == FAIL)
5818 	switch_buffer(save_curbuf, buf);
5819     else if (switch_win(save_curwinp, save_curtabp, wp, tp, TRUE) == FAIL)
5820     {
5821 	restore_win(*save_curwinp, *save_curtabp, TRUE);
5822 	switch_buffer(save_curbuf, buf);
5823     }
5824 }
5825 
5826     void
5827 restore_win_for_buf(
5828     win_T	*save_curwin,
5829     tabpage_T	*save_curtab,
5830     bufref_T	*save_curbuf)
5831 {
5832     if (save_curbuf->br_buf == NULL)
5833 	restore_win(save_curwin, save_curtab, TRUE);
5834     else
5835 	restore_buffer(save_curbuf);
5836 }
5837 #endif
5838 
5839 #if defined(FEAT_QUICKFIX) || defined(SWITCH_TO_WIN) || defined(PROTO)
5840 /*
5841  * Find a window for buffer "buf".
5842  * If found OK is returned and "wp" and "tp" are set to the window and tabpage.
5843  * If not found FAIL is returned.
5844  */
5845     int
5846 find_win_for_buf(
5847     buf_T     *buf,
5848     win_T     **wp,
5849     tabpage_T **tp)
5850 {
5851     FOR_ALL_TAB_WINDOWS(*tp, *wp)
5852 	if ((*wp)->w_buffer == buf)
5853 	    goto win_found;
5854     return FAIL;
5855 win_found:
5856     return OK;
5857 }
5858 #endif
5859 
5860 #if defined(FEAT_SIGNS) || defined(PROTO)
5861 /*
5862  * Insert the sign into the signlist.
5863  */
5864     static void
5865 insert_sign(
5866     buf_T	*buf,		/* buffer to store sign in */
5867     signlist_T	*prev,		/* previous sign entry */
5868     signlist_T	*next,		/* next sign entry */
5869     int		id,		/* sign ID */
5870     linenr_T	lnum,		/* line number which gets the mark */
5871     int		typenr)		/* typenr of sign we are adding */
5872 {
5873     signlist_T	*newsign;
5874 
5875     newsign = (signlist_T *)lalloc((long_u)sizeof(signlist_T), FALSE);
5876     if (newsign != NULL)
5877     {
5878 	newsign->id = id;
5879 	newsign->lnum = lnum;
5880 	newsign->typenr = typenr;
5881 	newsign->next = next;
5882 #ifdef FEAT_NETBEANS_INTG
5883 	newsign->prev = prev;
5884 	if (next != NULL)
5885 	    next->prev = newsign;
5886 #endif
5887 
5888 	if (prev == NULL)
5889 	{
5890 	    /* When adding first sign need to redraw the windows to create the
5891 	     * column for signs. */
5892 	    if (buf->b_signlist == NULL)
5893 	    {
5894 		redraw_buf_later(buf, NOT_VALID);
5895 		changed_cline_bef_curs();
5896 	    }
5897 
5898 	    /* first sign in signlist */
5899 	    buf->b_signlist = newsign;
5900 #ifdef FEAT_NETBEANS_INTG
5901 	    if (netbeans_active())
5902 		buf->b_has_sign_column = TRUE;
5903 #endif
5904 	}
5905 	else
5906 	    prev->next = newsign;
5907     }
5908 }
5909 
5910 /*
5911  * Add the sign into the signlist. Find the right spot to do it though.
5912  */
5913     void
5914 buf_addsign(
5915     buf_T	*buf,		/* buffer to store sign in */
5916     int		id,		/* sign ID */
5917     linenr_T	lnum,		/* line number which gets the mark */
5918     int		typenr)		/* typenr of sign we are adding */
5919 {
5920     signlist_T	*sign;		/* a sign in the signlist */
5921     signlist_T	*prev;		/* the previous sign */
5922 
5923     prev = NULL;
5924     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5925     {
5926 	if (lnum == sign->lnum && id == sign->id)
5927 	{
5928 	    sign->typenr = typenr;
5929 	    return;
5930 	}
5931 	else if (
5932 #ifndef FEAT_NETBEANS_INTG  /* keep signs sorted by lnum */
5933 		   id < 0 &&
5934 #endif
5935 			     lnum < sign->lnum)
5936 	{
5937 #ifdef FEAT_NETBEANS_INTG /* insert new sign at head of list for this lnum */
5938 	    /* XXX - GRP: Is this because of sign slide problem? Or is it
5939 	     * really needed? Or is it because we allow multiple signs per
5940 	     * line? If so, should I add that feature to FEAT_SIGNS?
5941 	     */
5942 	    while (prev != NULL && prev->lnum == lnum)
5943 		prev = prev->prev;
5944 	    if (prev == NULL)
5945 		sign = buf->b_signlist;
5946 	    else
5947 		sign = prev->next;
5948 #endif
5949 	    insert_sign(buf, prev, sign, id, lnum, typenr);
5950 	    return;
5951 	}
5952 	prev = sign;
5953     }
5954 #ifdef FEAT_NETBEANS_INTG /* insert new sign at head of list for this lnum */
5955     /* XXX - GRP: See previous comment */
5956     while (prev != NULL && prev->lnum == lnum)
5957 	prev = prev->prev;
5958     if (prev == NULL)
5959 	sign = buf->b_signlist;
5960     else
5961 	sign = prev->next;
5962 #endif
5963     insert_sign(buf, prev, sign, id, lnum, typenr);
5964 
5965     return;
5966 }
5967 
5968 /*
5969  * For an existing, placed sign "markId" change the type to "typenr".
5970  * Returns the line number of the sign, or zero if the sign is not found.
5971  */
5972     linenr_T
5973 buf_change_sign_type(
5974     buf_T	*buf,		/* buffer to store sign in */
5975     int		markId,		/* sign ID */
5976     int		typenr)		/* typenr of sign we are adding */
5977 {
5978     signlist_T	*sign;		/* a sign in the signlist */
5979 
5980     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5981     {
5982 	if (sign->id == markId)
5983 	{
5984 	    sign->typenr = typenr;
5985 	    return sign->lnum;
5986 	}
5987     }
5988 
5989     return (linenr_T)0;
5990 }
5991 
5992     int
5993 buf_getsigntype(
5994     buf_T	*buf,
5995     linenr_T	lnum,
5996     int		type)	/* SIGN_ICON, SIGN_TEXT, SIGN_ANY, SIGN_LINEHL */
5997 {
5998     signlist_T	*sign;		/* a sign in a b_signlist */
5999 
6000     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
6001 	if (sign->lnum == lnum
6002 		&& (type == SIGN_ANY
6003 # ifdef FEAT_SIGN_ICONS
6004 		    || (type == SIGN_ICON
6005 			&& sign_get_image(sign->typenr) != NULL)
6006 # endif
6007 		    || (type == SIGN_TEXT
6008 			&& sign_get_text(sign->typenr) != NULL)
6009 		    || (type == SIGN_LINEHL
6010 			&& sign_get_attr(sign->typenr, TRUE) != 0)))
6011 	    return sign->typenr;
6012     return 0;
6013 }
6014 
6015 
6016     linenr_T
6017 buf_delsign(
6018     buf_T	*buf,		/* buffer sign is stored in */
6019     int		id)		/* sign id */
6020 {
6021     signlist_T	**lastp;	/* pointer to pointer to current sign */
6022     signlist_T	*sign;		/* a sign in a b_signlist */
6023     signlist_T	*next;		/* the next sign in a b_signlist */
6024     linenr_T	lnum;		/* line number whose sign was deleted */
6025 
6026     lastp = &buf->b_signlist;
6027     lnum = 0;
6028     for (sign = buf->b_signlist; sign != NULL; sign = next)
6029     {
6030 	next = sign->next;
6031 	if (sign->id == id)
6032 	{
6033 	    *lastp = next;
6034 #ifdef FEAT_NETBEANS_INTG
6035 	    if (next != NULL)
6036 		next->prev = sign->prev;
6037 #endif
6038 	    lnum = sign->lnum;
6039 	    vim_free(sign);
6040 	    break;
6041 	}
6042 	else
6043 	    lastp = &sign->next;
6044     }
6045 
6046     /* When deleted the last sign need to redraw the windows to remove the
6047      * sign column. */
6048     if (buf->b_signlist == NULL)
6049     {
6050 	redraw_buf_later(buf, NOT_VALID);
6051 	changed_cline_bef_curs();
6052     }
6053 
6054     return lnum;
6055 }
6056 
6057 
6058 /*
6059  * Find the line number of the sign with the requested id. If the sign does
6060  * not exist, return 0 as the line number. This will still let the correct file
6061  * get loaded.
6062  */
6063     int
6064 buf_findsign(
6065     buf_T	*buf,		/* buffer to store sign in */
6066     int		id)		/* sign ID */
6067 {
6068     signlist_T	*sign;		/* a sign in the signlist */
6069 
6070     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
6071 	if (sign->id == id)
6072 	    return sign->lnum;
6073 
6074     return 0;
6075 }
6076 
6077     int
6078 buf_findsign_id(
6079     buf_T	*buf,		/* buffer whose sign we are searching for */
6080     linenr_T	lnum)		/* line number of sign */
6081 {
6082     signlist_T	*sign;		/* a sign in the signlist */
6083 
6084     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
6085 	if (sign->lnum == lnum)
6086 	    return sign->id;
6087 
6088     return 0;
6089 }
6090 
6091 
6092 # if defined(FEAT_NETBEANS_INTG) || defined(PROTO)
6093 /* see if a given type of sign exists on a specific line */
6094     int
6095 buf_findsigntype_id(
6096     buf_T	*buf,		/* buffer whose sign we are searching for */
6097     linenr_T	lnum,		/* line number of sign */
6098     int		typenr)		/* sign type number */
6099 {
6100     signlist_T	*sign;		/* a sign in the signlist */
6101 
6102     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
6103 	if (sign->lnum == lnum && sign->typenr == typenr)
6104 	    return sign->id;
6105 
6106     return 0;
6107 }
6108 
6109 
6110 #  if defined(FEAT_SIGN_ICONS) || defined(PROTO)
6111 /* return the number of icons on the given line */
6112     int
6113 buf_signcount(buf_T *buf, linenr_T lnum)
6114 {
6115     signlist_T	*sign;		/* a sign in the signlist */
6116     int		count = 0;
6117 
6118     for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
6119 	if (sign->lnum == lnum)
6120 	    if (sign_get_image(sign->typenr) != NULL)
6121 		count++;
6122 
6123     return count;
6124 }
6125 #  endif /* FEAT_SIGN_ICONS */
6126 # endif /* FEAT_NETBEANS_INTG */
6127 
6128 
6129 /*
6130  * Delete signs in buffer "buf".
6131  */
6132     void
6133 buf_delete_signs(buf_T *buf)
6134 {
6135     signlist_T	*next;
6136 
6137     /* When deleting the last sign need to redraw the windows to remove the
6138      * sign column. Not when curwin is NULL (this means we're exiting). */
6139     if (buf->b_signlist != NULL && curwin != NULL)
6140     {
6141 	redraw_buf_later(buf, NOT_VALID);
6142 	changed_cline_bef_curs();
6143     }
6144 
6145     while (buf->b_signlist != NULL)
6146     {
6147 	next = buf->b_signlist->next;
6148 	vim_free(buf->b_signlist);
6149 	buf->b_signlist = next;
6150     }
6151 }
6152 
6153 /*
6154  * Delete all signs in all buffers.
6155  */
6156     void
6157 buf_delete_all_signs(void)
6158 {
6159     buf_T	*buf;		/* buffer we are checking for signs */
6160 
6161     FOR_ALL_BUFFERS(buf)
6162 	if (buf->b_signlist != NULL)
6163 	    buf_delete_signs(buf);
6164 }
6165 
6166 /*
6167  * List placed signs for "rbuf".  If "rbuf" is NULL do it for all buffers.
6168  */
6169     void
6170 sign_list_placed(buf_T *rbuf)
6171 {
6172     buf_T	*buf;
6173     signlist_T	*p;
6174     char	lbuf[BUFSIZ];
6175 
6176     MSG_PUTS_TITLE(_("\n--- Signs ---"));
6177     msg_putchar('\n');
6178     if (rbuf == NULL)
6179 	buf = firstbuf;
6180     else
6181 	buf = rbuf;
6182     while (buf != NULL && !got_int)
6183     {
6184 	if (buf->b_signlist != NULL)
6185 	{
6186 	    vim_snprintf(lbuf, BUFSIZ, _("Signs for %s:"), buf->b_fname);
6187 	    MSG_PUTS_ATTR(lbuf, HL_ATTR(HLF_D));
6188 	    msg_putchar('\n');
6189 	}
6190 	for (p = buf->b_signlist; p != NULL && !got_int; p = p->next)
6191 	{
6192 	    vim_snprintf(lbuf, BUFSIZ, _("    line=%ld  id=%d  name=%s"),
6193 			   (long)p->lnum, p->id, sign_typenr2name(p->typenr));
6194 	    MSG_PUTS(lbuf);
6195 	    msg_putchar('\n');
6196 	}
6197 	if (rbuf != NULL)
6198 	    break;
6199 	buf = buf->b_next;
6200     }
6201 }
6202 
6203 /*
6204  * Adjust a placed sign for inserted/deleted lines.
6205  */
6206     void
6207 sign_mark_adjust(
6208     linenr_T	line1,
6209     linenr_T	line2,
6210     long	amount,
6211     long	amount_after)
6212 {
6213     signlist_T	*sign;		/* a sign in a b_signlist */
6214 
6215     for (sign = curbuf->b_signlist; sign != NULL; sign = sign->next)
6216     {
6217 	if (sign->lnum >= line1 && sign->lnum <= line2)
6218 	{
6219 	    if (amount == MAXLNUM)
6220 		sign->lnum = line1;
6221 	    else
6222 		sign->lnum += amount;
6223 	}
6224 	else if (sign->lnum > line2)
6225 	    sign->lnum += amount_after;
6226     }
6227 }
6228 #endif /* FEAT_SIGNS */
6229 
6230 /*
6231  * Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed.
6232  */
6233     void
6234 set_buflisted(int on)
6235 {
6236     if (on != curbuf->b_p_bl)
6237     {
6238 	curbuf->b_p_bl = on;
6239 #ifdef FEAT_AUTOCMD
6240 	if (on)
6241 	    apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
6242 	else
6243 	    apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
6244 #endif
6245     }
6246 }
6247 
6248 /*
6249  * Read the file for "buf" again and check if the contents changed.
6250  * Return TRUE if it changed or this could not be checked.
6251  */
6252     int
6253 buf_contents_changed(buf_T *buf)
6254 {
6255     buf_T	*newbuf;
6256     int		differ = TRUE;
6257     linenr_T	lnum;
6258     aco_save_T	aco;
6259     exarg_T	ea;
6260 
6261     /* Allocate a buffer without putting it in the buffer list. */
6262     newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
6263     if (newbuf == NULL)
6264 	return TRUE;
6265 
6266     /* Force the 'fileencoding' and 'fileformat' to be equal. */
6267     if (prep_exarg(&ea, buf) == FAIL)
6268     {
6269 	wipe_buffer(newbuf, FALSE);
6270 	return TRUE;
6271     }
6272 
6273     /* set curwin/curbuf to buf and save a few things */
6274     aucmd_prepbuf(&aco, newbuf);
6275 
6276     if (ml_open(curbuf) == OK
6277 	    && readfile(buf->b_ffname, buf->b_fname,
6278 				  (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM,
6279 					    &ea, READ_NEW | READ_DUMMY) == OK)
6280     {
6281 	/* compare the two files line by line */
6282 	if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count)
6283 	{
6284 	    differ = FALSE;
6285 	    for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
6286 		if (STRCMP(ml_get_buf(buf, lnum, FALSE), ml_get(lnum)) != 0)
6287 		{
6288 		    differ = TRUE;
6289 		    break;
6290 		}
6291 	}
6292     }
6293     vim_free(ea.cmd);
6294 
6295     /* restore curwin/curbuf and a few other things */
6296     aucmd_restbuf(&aco);
6297 
6298     if (curbuf != newbuf)	/* safety check */
6299 	wipe_buffer(newbuf, FALSE);
6300 
6301     return differ;
6302 }
6303 
6304 /*
6305  * Wipe out a buffer and decrement the last buffer number if it was used for
6306  * this buffer.  Call this to wipe out a temp buffer that does not contain any
6307  * marks.
6308  */
6309     void
6310 wipe_buffer(
6311     buf_T	*buf,
6312     int		aucmd UNUSED)	    /* When TRUE trigger autocommands. */
6313 {
6314     if (buf->b_fnum == top_file_num - 1)
6315 	--top_file_num;
6316 
6317 #ifdef FEAT_AUTOCMD
6318     if (!aucmd)		    /* Don't trigger BufDelete autocommands here. */
6319 	block_autocmds();
6320 #endif
6321     close_buffer(NULL, buf, DOBUF_WIPE, FALSE);
6322 #ifdef FEAT_AUTOCMD
6323     if (!aucmd)
6324 	unblock_autocmds();
6325 #endif
6326 }
6327