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