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