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