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