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