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