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