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