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