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