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