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