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