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