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