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