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