robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
134.7 KiB4358 linesraw
1//
2// buffer.c: functions for dealing with the buffer structure
3//
4
5//
6// The buffer list is a double linked list of all buffers.
7// Each buffer can be in one of these states:
8// never loaded: BF_NEVERLOADED is set, only the file name is valid
9//   not loaded: b_ml.ml_mfp == NULL, no memfile allocated
10//       hidden: b_nwindows == 0, loaded but not displayed in a window
11//       normal: loaded and displayed in a window
12//
13// Instead of storing file names all over the place, each file name is
14// stored in the buffer list. It can be referenced by a number.
15//
16// The current implementation remembers all file names ever used.
17//
18
19#include <assert.h>
20#include <ctype.h>
21#include <inttypes.h>
22#include <stdbool.h>
23#include <stdlib.h>
24#include <string.h>
25#include <sys/stat.h>
26#include <time.h>
27
28#include "auto/config.h"
29#include "klib/kvec.h"
30#include "nvim/api/private/helpers.h"
31#include "nvim/arglist.h"
32#include "nvim/ascii_defs.h"
33#include "nvim/assert_defs.h"
34#include "nvim/autocmd.h"
35#include "nvim/autocmd_defs.h"
36#include "nvim/buffer.h"
37#include "nvim/buffer_updates.h"
38#include "nvim/change.h"
39#include "nvim/channel.h"
40#include "nvim/charset.h"
41#include "nvim/cmdexpand.h"
42#include "nvim/context.h"
43#include "nvim/cursor.h"
44#include "nvim/diff.h"
45#include "nvim/digraph.h"
46#include "nvim/drawscreen.h"
47#include "nvim/errors.h"
48#include "nvim/eval/typval.h"
49#include "nvim/eval/vars.h"
50#include "nvim/eval/window.h"
51#include "nvim/ex_cmds.h"
52#include "nvim/ex_cmds2.h"
53#include "nvim/ex_cmds_defs.h"
54#include "nvim/ex_docmd.h"
55#include "nvim/ex_eval.h"
56#include "nvim/ex_eval_defs.h"
57#include "nvim/ex_getln.h"
58#include "nvim/extmark.h"
59#include "nvim/file_search.h"
60#include "nvim/fileio.h"
61#include "nvim/fold.h"
62#include "nvim/fuzzy.h"
63#include "nvim/garray.h"
64#include "nvim/garray_defs.h"
65#include "nvim/gettext_defs.h"
66#include "nvim/globals.h"
67#include "nvim/hashtab.h"
68#include "nvim/hashtab_defs.h"
69#include "nvim/help.h"
70#include "nvim/indent.h"
71#include "nvim/indent_c.h"
72#include "nvim/input.h"
73#include "nvim/insexpand.h"
74#include "nvim/main.h"
75#include "nvim/map_defs.h"
76#include "nvim/mapping.h"
77#include "nvim/mark.h"
78#include "nvim/mark_defs.h"
79#include "nvim/mbyte.h"
80#include "nvim/mcursor.h"
81#include "nvim/memfile_defs.h"
82#include "nvim/memline.h"
83#include "nvim/memline_defs.h"
84#include "nvim/memory.h"
85#include "nvim/message.h"
86#include "nvim/move.h"
87#include "nvim/normal.h"
88#include "nvim/option.h"
89#include "nvim/option_defs.h"
90#include "nvim/option_vars.h"
91#include "nvim/optionstr.h"
92#include "nvim/os/fs.h"
93#include "nvim/os/fs_defs.h"
94#include "nvim/os/input.h"
95#include "nvim/os/os.h"
96#include "nvim/os/os_defs.h"
97#include "nvim/os/time.h"
98#include "nvim/path.h"
99#include "nvim/plines.h"
100#include "nvim/pos_defs.h"
101#include "nvim/quickfix.h"
102#include "nvim/regexp.h"
103#include "nvim/regexp_defs.h"
104#include "nvim/runtime.h"
105#include "nvim/runtime_defs.h"
106#include "nvim/spell.h"
107#include "nvim/state_defs.h"
108#include "nvim/statusline.h"
109#include "nvim/strings.h"
110#include "nvim/syntax.h"
111#include "nvim/terminal.h"
112#include "nvim/ui.h"
113#include "nvim/undo.h"
114#include "nvim/usercmd.h"
115#include "nvim/version.h"
116#include "nvim/vim_defs.h"
117#include "nvim/window.h"
118#include "nvim/winfloat.h"
119
120#include "buffer.c.generated.h"
121
122#ifdef ABORT_ON_INTERNAL_ERROR
123# define CHECK_CURBUF \
124  do { \
125    if (curwin != NULL && curwin->w_buffer != curbuf) { \
126      iemsg("curbuf != curwin->w_buffer"); \
127    } \
128  } while (0)
129#else
130# define CHECK_CURBUF do {} while (0)
131#endif
132
133static const char e_attempt_to_delete_buffer_that_is_in_use_str[]
134  = N_("E937: Attempt to delete a buffer that is in use: %s");
135
136// Number of times free_buffer() was called.
137static int buf_free_count = 0;
138
139static int top_file_num = 1;            ///< highest file number
140
141typedef enum {
142  kBffClearWinInfo = 1,
143  kBffInitChangedtick = 2,
144} BufFreeFlags;
145
146static void trigger_undo_ftplugin(buf_T *buf, win_T *win)
147{
148  window_layout_lock();
149  buf->b_locked++;
150  win->w_locked++;
151  // b:undo_ftplugin may be set, undo it
152  do_cmdline_cmd("if exists('b:undo_ftplugin') | exe b:undo_ftplugin | endif");
153  buf->b_locked--;
154  win->w_locked--;
155  window_layout_unlock();
156}
157
158/// Calculate the percentage that `part` is of the `whole`.
159int calc_percentage(int64_t part, int64_t whole)
160{
161  // With 32 bit longs and more than 21,474,836 lines multiplying by 100
162  // causes an overflow, thus for large numbers divide instead.
163  return (part > 1000000) ? (int)(part / (whole / 100))
164                          : (int)((part * 100) / whole);
165}
166
167/// @return  the highest possible buffer number
168int get_highest_fnum(void)
169{
170  return top_file_num - 1;
171}
172
173/// Read data from buffer for retrying.
174///
175/// @param read_stdin  read file from stdin, otherwise fifo
176/// @param eap  for forced 'ff' and 'fenc' or NULL
177/// @param flags  extra flags for readfile()
178static int read_buffer(bool read_stdin, exarg_T *eap, int flags)
179{
180  int retval = OK;
181  bool silent = shortmess(kShmFileinfo);
182
183  // Read from the buffer which the text is already filled in and append at
184  // the end.  This makes it possible to retry when 'fileformat' or
185  // 'fileencoding' was guessed wrong.
186  linenr_T line_count = curbuf->b_ml.ml_line_count;
187  retval = readfile(read_stdin ? NULL : curbuf->b_ffname,
188                    read_stdin ? NULL : curbuf->b_fname,
189                    line_count, 0, (linenr_T)MAXLNUM, eap,
190                    flags | READ_BUFFER, silent);
191  if (retval == OK) {
192    // Delete the binary lines.
193    while (--line_count >= 0) {
194      ml_delete(1);
195    }
196  } else {
197    // Delete the converted lines.
198    while (curbuf->b_ml.ml_line_count > line_count) {
199      ml_delete(line_count);
200    }
201  }
202  // Put the cursor on the first line.
203  curwin->w_cursor.lnum = 1;
204  curwin->w_cursor.col = 0;
205
206  if (read_stdin) {
207    // Set or reset 'modified' before executing autocommands, so that
208    // it can be changed there.
209    if (!readonlymode && !buf_is_empty(curbuf)) {
210      changed(curbuf);
211    } else if (retval != FAIL) {
212      unchanged(curbuf, false, true);
213    }
214
215    apply_autocmds_retval(EVENT_STDINREADPOST, NULL, NULL, false,
216                          curbuf, &retval);
217  }
218  return retval;
219}
220
221/// Ensure buffer "buf" is loaded.
222bool buf_ensure_loaded(buf_T *buf)
223{
224  if (buf->b_ml.ml_mfp != NULL) {
225    // already open (common case)
226    return true;
227  }
228
229  CtxSwitch aco = { 0 };
230
231  // Make sure the buffer is in a window.
232  ctx_switch(&aco, NULL, NULL, buf, 0);
233  // status can be OK or NOTDONE (which also means ok/done)
234  int status = open_buffer(false, NULL, 0);
235  ctx_restore(&aco);
236  return (status != FAIL);
237}
238
239/// Open current buffer, that is: open the memfile and read the file into
240/// memory.
241///
242/// @param read_stdin  read file from stdin
243/// @param eap  for forced 'ff' and 'fenc' or NULL
244/// @param flags_arg  extra flags for readfile()
245///
246/// @return  FAIL for failure, OK otherwise.
247int open_buffer(bool read_stdin, exarg_T *eap, int flags_arg)
248{
249  int flags = flags_arg;
250  int retval = OK;
251  bufref_T old_curbuf;
252  OptInt old_tw = curbuf->b_p_tw;
253  bool read_fifo = false;
254  bool silent = shortmess(kShmFileinfo);
255
256  // The 'readonly' flag is only set when BF_NEVERLOADED is being reset.
257  // When re-entering the same buffer, it should not change, because the
258  // user may have reset the flag by hand.
259  if (readonlymode && curbuf->b_ffname != NULL
260      && (curbuf->b_flags & BF_NEVERLOADED)) {
261    curbuf->b_p_ro = true;
262  }
263
264  if (ml_open(curbuf) == FAIL) {
265    // There MUST be a memfile, otherwise we can't do anything
266    // If we can't create one for the current buffer, take another buffer
267    close_buffer(curwin, curbuf, 0, false, false, false);
268
269    curbuf = NULL;
270    FOR_ALL_BUFFERS(buf) {
271      if (buf->b_ml.ml_mfp != NULL) {
272        curbuf = buf;
273        break;
274      }
275    }
276
277    // If there is no memfile at all, exit.
278    // This is OK, since there are no changes to lose.
279    if (curbuf == NULL) {
280      emsg(_("E82: Cannot allocate any buffer, exiting..."));
281
282      // Don't try to do any saving, with "curbuf" NULL almost nothing
283      // will work.
284      v_dying = 2;
285      getout(2);
286    }
287
288    emsg(_("E83: Cannot allocate buffer, using other one..."));
289    enter_buffer(curbuf);
290    if (old_tw != curbuf->b_p_tw) {
291      check_colorcolumn(NULL, curwin);
292    }
293    return FAIL;
294  }
295
296  // Do not sync this buffer yet, may first want to read the file.
297  if (curbuf->b_ml.ml_mfp != NULL) {
298    curbuf->b_ml.ml_mfp->mf_dirty = MF_DIRTY_YES_NOSYNC;
299  }
300
301  // The autocommands in readfile() may change the buffer, but only AFTER
302  // reading the file.
303  set_bufref(&old_curbuf, curbuf);
304  curbuf->b_modified_was_set = false;
305
306  // mark cursor position as being invalid
307  curwin->w_valid = 0;
308
309  // A buffer without an actual file should not use the buffer name to read a
310  // file.
311  if (bt_nofileread(curbuf)) {
312    flags |= READ_NOFILE;
313  }
314
315  // Read the file if there is one.
316  if (curbuf->b_ffname != NULL) {
317#ifdef UNIX
318    int save_bin = curbuf->b_p_bin;
319    int perm = os_getperm(curbuf->b_ffname);
320    if (perm >= 0 && (0 || S_ISFIFO(perm)
321                      || S_ISSOCK(perm)
322# ifdef OPEN_CHR_FILES
323                      || (S_ISCHR(perm)
324                          && is_dev_fd_file(curbuf->b_ffname))
325# endif
326                      )) {
327      read_fifo = true;
328    }
329    if (read_fifo) {
330      curbuf->b_p_bin = true;
331    }
332#endif
333
334    retval = readfile(curbuf->b_ffname, curbuf->b_fname,
335                      0, 0, (linenr_T)MAXLNUM, eap,
336                      flags | READ_NEW | (read_fifo ? READ_FIFO : 0), silent);
337#ifdef UNIX
338    if (read_fifo) {
339      curbuf->b_p_bin = save_bin;
340      if (retval == OK) {
341        // don't add READ_FIFO here, otherwise we won't be able to
342        // detect the encoding
343        retval = read_buffer(false, eap, flags);
344      }
345    }
346#endif
347
348    // Help buffer: populate *local-additions* in help.txt
349    if (bt_help(curbuf)) {
350      get_local_additions();
351    }
352  } else if (read_stdin) {
353    int save_bin = curbuf->b_p_bin;
354
355    // First read the text in binary mode into the buffer.
356    // Then read from that same buffer and append at the end.  This makes
357    // it possible to retry when 'fileformat' or 'fileencoding' was
358    // guessed wrong.
359    curbuf->b_p_bin = true;
360    retval = readfile(NULL, NULL, 0,
361                      0, (linenr_T)MAXLNUM, NULL,
362                      flags | (READ_NEW + READ_STDIN), silent);
363    curbuf->b_p_bin = save_bin;
364    if (retval == OK) {
365      retval = read_buffer(true, eap, flags);
366    }
367  }
368
369  // Can now sync this buffer in ml_sync_all().
370  if (curbuf->b_ml.ml_mfp != NULL
371      && curbuf->b_ml.ml_mfp->mf_dirty == MF_DIRTY_YES_NOSYNC) {
372    curbuf->b_ml.ml_mfp->mf_dirty = MF_DIRTY_YES;
373  }
374
375  // if first time loading this buffer, init b_chartab[]
376  if (curbuf->b_flags & BF_NEVERLOADED) {
377    buf_init_isk_chartab(curbuf);
378    parse_cino(curbuf);
379  }
380
381  // Set/reset the Changed flag first, autocmds may change the buffer.
382  // Apply the automatic commands, before processing the modelines.
383  // So the modelines have priority over autocommands.
384
385  // When reading stdin, the buffer contents always needs writing, so set
386  // the changed flag.  Unless in readonly mode: "ls | nvim -R -".
387  // When interrupted and 'cpoptions' contains 'i' set changed flag.
388  if ((got_int && vim_strchr(p_cpo, kCpoIntmod) != NULL)
389      || curbuf->b_modified_was_set  // autocmd did ":set modified"
390      || (aborting() && vim_strchr(p_cpo, kCpoIntmod) != NULL)) {
391    changed(curbuf);
392  } else if (retval != FAIL && !read_stdin && !read_fifo) {
393    unchanged(curbuf, false, true);
394  }
395  save_file_ff(curbuf);                 // keep this fileformat
396
397  // Set last_changedtick to avoid triggering a TextChanged autocommand right
398  // after it was added.
399  curbuf->b_last_changedtick = buf_get_changedtick(curbuf);
400  curbuf->b_last_changedtick_i = buf_get_changedtick(curbuf);
401  curbuf->b_last_changedtick_pum = buf_get_changedtick(curbuf);
402
403  // require "!" to overwrite the file, because it wasn't read completely
404  if (aborting()) {
405    curbuf->b_flags |= BF_READERR;
406  }
407
408  // Directory buf:
409  // readfile() returns NOTDONE without firing BufReadPost when it did not read a
410  // file (e.g. a directory). Since BufReadPost is what normally runs filetype
411  // detection, do it here so FileType fires before the BufEnter below.
412  if (retval == NOTDONE && *curbuf->b_p_ft == NUL
413      && curbuf->b_ffname != NULL
414      && after_pathsep(curbuf->b_ffname,
415                       curbuf->b_ffname + strlen(curbuf->b_ffname))) {
416    if (augroup_exists("filetypedetect")) {
417      bufref_T bufref;
418      set_bufref(&bufref, curbuf);
419      do_doautocmd("filetypedetect BufRead", false, NULL);
420      if (!bufref_valid(&bufref) || curbuf != old_curbuf.br_buf || aborting()) {
421        return FAIL;
422      }
423    }
424  }
425
426  // Need to update automatic folding.  Do this before the autocommands,
427  // they may use the fold info.
428  foldUpdateAll(curwin);
429
430  // need to set w_topline, unless some autocommand already did that.
431  if (!(curwin->w_valid & VALID_TOPLINE)) {
432    curwin->w_topline = 1;
433    curwin->w_topfill = 0;
434  }
435  apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, false, curbuf, &retval);
436
437  // if (retval != OK) {
438  if (retval == FAIL) {
439    return retval;
440  }
441
442  // The autocommands may have changed the current buffer.  Apply the
443  // modelines to the correct buffer, if it still exists and is loaded.
444  if (bufref_valid(&old_curbuf) && old_curbuf.br_buf->b_ml.ml_mfp != NULL) {
445    CtxSwitch aco = { 0 };
446
447    // Go to the buffer that was opened, make sure it is in a window.
448    ctx_switch(&aco, NULL, NULL, old_curbuf.br_buf, 0);
449    do_modelines(0);
450    curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED);
451
452    if ((flags & READ_NOWINENTER) == 0) {
453      apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, false, curbuf,
454                            &retval);
455    }
456
457    // restore curwin/curbuf and a few other things
458    ctx_restore(&aco);
459  }
460
461  return retval;
462}
463
464/// Store "buf" in "bufref" and set the free count.
465///
466/// @param bufref Reference to be used for the buffer.
467/// @param buf    The buffer to reference.
468void set_bufref(bufref_T *bufref, buf_T *buf)
469{
470  bufref->br_buf = buf;
471  bufref->br_fnum = buf == NULL ? 0 : buf->b_fnum;
472  bufref->br_buf_free_count = buf_free_count;
473}
474
475/// Return true if "bufref->br_buf" points to the same buffer as when
476/// set_bufref() was called and it is a valid buffer.
477/// Only goes through the buffer list if buf_free_count changed.
478/// Also checks if b_fnum is still the same, a :bwipe followed by :new might get
479/// the same allocated memory, but it's a different buffer.
480///
481/// @param bufref Buffer reference to check for.
482bool bufref_valid(bufref_T *bufref)
483  FUNC_ATTR_PURE
484{
485  return bufref->br_buf_free_count == buf_free_count
486         ? true
487         : buf_valid(bufref->br_buf) && bufref->br_fnum == bufref->br_buf->b_fnum;
488}
489
490/// Check that "buf" points to a valid buffer in the buffer list.
491///
492/// Can be slow if there are many buffers, prefer using bufref_valid().
493///
494/// @param buf The buffer to check for.
495bool buf_valid(buf_T *buf)
496  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
497{
498  if (buf == NULL) {
499    return false;
500  }
501  // Assume that we more often have a recent buffer,
502  // start with the last one.
503  for (buf_T *bp = lastbuf; bp != NULL; bp = bp->b_prev) {
504    if (bp == buf) {
505      return true;
506    }
507  }
508  return false;
509}
510
511/// Return true when buffer "buf" can be unloaded.
512/// Give an error message and return false when the buffer is locked or the
513/// screen is being redrawn and the buffer is in a window.
514static bool can_unload_buffer(buf_T *buf)
515{
516  bool can_unload = !buf->b_locked;
517
518  if (can_unload && updating_screen) {
519    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
520      if (wp->w_buffer == buf) {
521        can_unload = false;
522        break;
523      }
524    }
525  }
526  // Don't unload the buffer while it's still being saved
527  if (can_unload && buf->b_saving) {
528    can_unload = false;
529  }
530
531  if (!can_unload) {
532    char *fname = buf->b_fname != NULL ? buf->b_fname : buf->b_ffname;
533    semsg(_(e_attempt_to_delete_buffer_that_is_in_use_str),
534          fname != NULL ? fname : "[No Name]");
535  }
536  return can_unload;
537}
538
539void buf_close_terminal(buf_T *buf)
540{
541  assert(buf->terminal);
542  buf->b_locked++;
543  terminal_close(&buf->terminal, -1);
544  buf->b_locked--;
545}
546
547/// Close the link to a buffer.
548///
549/// @param win    If not NULL and we reached the end and unloaded "buf", b_nwindows is decremented
550///               if w_buffer was "buf" after autocmds.  w_buffer is set to NULL in that case.
551///               Otherwise, w_buffer->b_nwindows is not decremented; callers should decrement it if
552///               they still intend to switch "win"'s buffer or close "win"!  If "win" was initially
553///               curwin displaying "buf", it is re-entered if autocmds switched windows, if still
554///               open.
555/// @param buf
556/// @param action Used when there is no longer a window for the buffer.
557///               Possible values:
558///                 0            buffer becomes hidden
559///                 DOBUF_UNLOAD buffer is unloaded
560///                 DOBUF_DEL    buffer is unloaded and removed from buffer list
561///                 DOBUF_WIPE   buffer is unloaded and really deleted
562///               When doing all but the first, the caller should get a new buffer very soon!
563///               The 'bufhidden' option can force freeing and deleting.
564/// @param abort_if_last
565///               If true, do not close the buffer if autocommands cause
566///               there to be only one window with this buffer. e.g. when
567///               ":quit" is supposed to close the window but autocommands
568///               close all other windows.
569/// @param ignore_abort
570///               If true, don't abort even when aborting() returns true.
571/// @param set_context
572///               If true, also call buflist_setfpos for "win" if it's showing "buf", and set
573///               b_last_cursor if "win" is the buffer's only window.
574/// @return  true when we got to the end and unloaded "buf".
575bool close_buffer(win_T *win, buf_T *buf, int action, bool abort_if_last, bool ignore_abort,
576                  bool set_context)
577  FUNC_ATTR_NONNULL_ARG(2)
578{
579  bool unload_buf = (action != 0);
580  bool del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE);
581  bool wipe_buf = (action == DOBUF_WIPE);
582
583  bool is_curwin = (curwin != NULL && curwin == win && curwin->w_buffer == buf);
584  tabpage_T *the_curtab = curtab;
585
586  CHECK_CURBUF;
587
588  // Force unloading or deleting when 'bufhidden' says so, but not for terminal
589  // buffers.
590  // The caller must take care of NOT deleting/freeing when 'bufhidden' is
591  // "hide" (otherwise we could never free or delete a buffer).
592  if (!buf->terminal) {
593    if (buf->b_p_bh[0] == 'd') {         // 'bufhidden' == "delete"
594      del_buf = true;
595      unload_buf = true;
596    } else if (buf->b_p_bh[0] == 'w') {  // 'bufhidden' == "wipe"
597      del_buf = true;
598      unload_buf = true;
599      wipe_buf = true;
600    } else if (buf->b_p_bh[0] == 'u') {  // 'bufhidden' == "unload"
601      unload_buf = true;
602    }
603  }
604
605  if (buf->terminal && (unload_buf || del_buf || wipe_buf)) {
606    // terminal buffers can only be wiped
607    unload_buf = true;
608    del_buf = true;
609    wipe_buf = true;
610  }
611
612  // Disallow deleting the buffer when it is locked (already being closed or
613  // halfway a command that relies on it). Unloading is allowed.
614  if ((del_buf || wipe_buf) && !can_unload_buffer(buf)) {
615    return false;
616  }
617
618  bool win_valid = win_valid_any_tab(win);
619  if (set_context && win_valid && win->w_buffer == buf) {
620    // Set b_last_cursor when closing the last window for the buffer.
621    // Remember the last cursor position and window options of the buffer.
622    // This used to be only for the current window, but then options like
623    // 'foldmethod' may be lost with a ":only" command.
624    if (buf->b_nwindows == 1) {
625      set_last_cursor(win);
626    }
627    buflist_setfpos(buf, win,
628                    win->w_cursor.lnum == 1 ? 0 : win->w_cursor.lnum,
629                    win->w_cursor.col, true);
630  }
631
632  bufref_T bufref;
633  set_bufref(&bufref, buf);
634
635  // When the buffer is no longer in a window, trigger BufWinLeave
636  if (win_valid && win->w_buffer == buf && buf->b_nwindows == 1) {
637    buf->b_locked++;
638    buf->b_locked_split++;
639    if (apply_autocmds_win(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, false,
640                           buf, win) && !bufref_valid(&bufref)) {
641      // Autocommands deleted the buffer.
642      emsg(_(e_auabort));
643      return false;
644    }
645    buf->b_locked--;
646    buf->b_locked_split--;
647    if (abort_if_last && one_window(win, NULL)) {
648      // Autocommands made this the only window.
649      emsg(_(e_auabort));
650      return false;
651    }
652
653    // When the buffer becomes hidden, but is not unloaded, trigger
654    // BufHidden
655    if (!unload_buf) {
656      buf->b_locked++;
657      buf->b_locked_split++;
658      if (apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname, false,
659                         buf) && !bufref_valid(&bufref)) {
660        // Autocommands deleted the buffer.
661        emsg(_(e_auabort));
662        return false;
663      }
664      buf->b_locked--;
665      buf->b_locked_split--;
666      if (abort_if_last && one_window(win, NULL)) {
667        // Autocommands made this the only window.
668        emsg(_(e_auabort));
669        return false;
670      }
671    }
672    // autocmds may abort script processing
673    if (!ignore_abort && aborting()) {
674      return false;
675    }
676    win_valid = win_valid && win_valid_any_tab(win);
677  }
678
679  // If the buffer was in curwin and the window has changed, go back to that
680  // window, if it still exists.  This avoids that ":edit x" triggering a
681  // "tabnext" BufUnload autocmd leaves a window behind without a buffer.
682  if (is_curwin && curwin != win && win_valid) {
683    block_autocmds();
684    goto_tabpage_win(the_curtab, win);
685    unblock_autocmds();
686  }
687
688  // When a quickfix buffer is deleted from a window, clear the
689  // 'winfixheight' option.
690  if (bt_quickfix(buf) && win_valid && win->w_buffer == buf) {
691    win->w_p_wfh = false;
692  }
693
694  // Remember if the buffer may be hidden soon, or is already hidden.
695  bool hiding_buf = buf->b_nwindows <= 0
696                    || (win_valid && win->w_buffer == buf && buf->b_nwindows == 1);
697
698  if (diffopt_hiddenoff() && !unload_buf && hiding_buf) {
699    diff_buf_delete(buf);   // Clear 'diff' for hidden buffer.
700  }
701
702  // Return when another window is displaying the buffer or when not unloaded.
703  if (!hiding_buf || !unload_buf) {
704    return false;
705  }
706
707  // Always remove the buffer when there is no file name.
708  if (buf->b_ffname == NULL) {
709    del_buf = true;
710  }
711
712  // Free all things allocated for this buffer.
713  // Also calls the "BufDelete" autocommands when del_buf is true.
714  // Abort if nothing was freed, or if autocommands delete the buffer.
715  if (!buf_freeall(buf, ((del_buf ? BFA_DEL : 0)
716                         + (wipe_buf ? BFA_WIPE : 0)
717                         + (ignore_abort ? BFA_IGNORE_ABORT : 0)))) {
718    return false;
719  }
720
721  bool clear_w_buf = false;
722  win_valid = win_valid && win_valid_any_tab(win);
723  if (win_valid && win->w_buffer == buf) {
724    // Autocommands may have opened (despite b_locked_split) or closed
725    // windows for this buffer.  Decrement for the close we do here.
726    buf->b_nwindows--;
727    // Defer clearing w_buffer until after operations that may invoke dict
728    // watchers (e.g., buf_clear_file()), so callers like tabpagebuflist()
729    // never see a window in the window list with a NULL buffer.
730    clear_w_buf = true;
731  }
732
733  // Remove the buffer from the list.
734  // Do not wipe out the buffer if it is used in a window, or if autocommands
735  // wiped out all other buffers (unless when inside free_all_mem() where all
736  // buffers need to be freed and autocommands are blocked).
737  if (wipe_buf && buf->b_nwindows <= 0 && (buf->b_prev != NULL || buf->b_next != NULL
738#if defined(EXITFREE)
739                                           || entered_free_all_mem
740#endif
741                                           )) {
742    if (clear_w_buf) {
743      win->w_buffer = NULL;
744    }
745    FOR_ALL_TAB_WINDOWS(tp, wp) {
746      mark_forget_file(wp, buf->b_fnum);
747    }
748    if (buf->b_sfname != buf->b_ffname) {
749      XFREE_CLEAR(buf->b_sfname);
750    } else {
751      buf->b_sfname = NULL;
752    }
753    XFREE_CLEAR(buf->b_ffname);
754    if (buf->b_prev == NULL) {
755      firstbuf = buf->b_next;
756    } else {
757      buf->b_prev->b_next = buf->b_next;
758    }
759    if (buf->b_next == NULL) {
760      lastbuf = buf->b_prev;
761    } else {
762      buf->b_next->b_prev = buf->b_prev;
763    }
764    free_buffer(buf);
765  } else {
766    if (del_buf) {
767      // Free all internal variables and reset option values, to make
768      // ":bdel" compatible with Vim 5.7.
769      free_buffer_stuff(buf, kBffClearWinInfo | kBffInitChangedtick);
770
771      // Make it look like a new buffer.
772      buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
773
774      // Init the options when loaded again.
775      buf->b_p_initialized = false;
776    }
777    // Dict watchers set b_locked, but also don't want them messing with windows...
778    textlock++;
779    buf_clear_file(buf);
780    textlock--;
781    if (clear_w_buf) {
782      win->w_buffer = NULL;
783    }
784    if (del_buf) {
785      buf->b_p_bl = false;
786    }
787  }
788  // NOTE: at this point "curbuf" may be invalid!
789
790  // When closing curbuf for curwin, is_curwin checks should've ensured
791  // autocmds don't switch windows, unless they closed curwin.  Otherwise
792  // callers may leave the window open to a NULL buffer!
793  assert(!win_valid || !is_curwin || win == curwin);
794  return true;
795}
796
797/// Make buffer not contain a file.
798void buf_clear_file(buf_T *buf)
799{
800  buf->b_ml.ml_line_count = 1;
801  unchanged(buf, true, true);
802  buf->b_p_eof = false;
803  buf->b_start_eof = false;
804  buf->b_p_eol = true;
805  buf->b_start_eol = true;
806  buf->b_p_bomb = false;
807  buf->b_start_bomb = false;
808  buf->b_ml.ml_mfp = NULL;
809  buf->b_ml.ml_flags = ML_EMPTY;                // empty buffer
810}
811
812/// Clears the current buffer contents.
813void buf_clear(void)
814{
815  linenr_T line_count = curbuf->b_ml.ml_line_count;
816  extmark_free_all(curbuf);   // delete any extmarks
817  mc_buf_free(curbuf);        // Multicursors died with their extmarks.
818  while (!(curbuf->b_ml.ml_flags & ML_EMPTY)) {
819    ml_delete(1);
820  }
821  deleted_lines_mark(1, line_count);  // prepare for display
822}
823
824/// buf_freeall() - free all things allocated for a buffer that are related to
825/// the file.  Careful: get here with "curwin" NULL when exiting.
826///
827/// @param flags BFA_DEL           buffer is going to be deleted
828///              BFA_WIPE          buffer is going to be wiped out
829///              BFA_KEEP_UNDO     do not free undo information
830///              BFA_IGNORE_ABORT  don't abort even when aborting() returns true
831/// @return  true when we got to the end.
832bool buf_freeall(buf_T *buf, int flags)
833  FUNC_ATTR_NONNULL_ALL
834{
835  bool is_curbuf = (buf == curbuf);
836  int is_curwin = (curwin != NULL && curwin->w_buffer == buf);
837  win_T *the_curwin = curwin;
838  tabpage_T *the_curtab = curtab;
839
840  // Make sure the buffer isn't closed by autocommands.
841  buf->b_locked++;
842  buf->b_locked_split++;
843
844  bufref_T bufref;
845  set_bufref(&bufref, buf);
846
847  if (buf->terminal) {
848    buf_close_terminal(buf);
849  }
850
851  buf_updates_unload(buf, false);
852
853  if ((buf->b_ml.ml_mfp != NULL)
854      && apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, false, buf)
855      && !bufref_valid(&bufref)) {
856    // Autocommands deleted the buffer.
857    return false;
858  }
859  if ((flags & BFA_DEL)
860      && buf->b_p_bl
861      && apply_autocmds(EVENT_BUFDELETE, buf->b_fname, buf->b_fname, false, buf)
862      && !bufref_valid(&bufref)) {
863    // Autocommands may delete the buffer.
864    return false;
865  }
866  if ((flags & BFA_WIPE)
867      && apply_autocmds(EVENT_BUFWIPEOUT, buf->b_fname, buf->b_fname, false,
868                        buf)
869      && !bufref_valid(&bufref)) {
870    // Autocommands may delete the buffer.
871    return false;
872  }
873  buf->b_locked--;
874  buf->b_locked_split--;
875
876  // If the buffer was in curwin and the window has changed, go back to that
877  // window, if it still exists.  This avoids that ":edit x" triggering a
878  // "tabnext" BufUnload autocmd leaves a window behind without a buffer.
879  if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) {
880    block_autocmds();
881    goto_tabpage_win(the_curtab, the_curwin);
882    unblock_autocmds();
883  }
884  // autocmds may abort script processing
885  if ((flags & BFA_IGNORE_ABORT) == 0 && aborting()) {
886    return false;
887  }
888
889  // It's possible that autocommands change curbuf to the one being deleted.
890  // This might cause curbuf to be deleted unexpectedly.  But in some cases
891  // it's OK to delete the curbuf, because a new one is obtained anyway.
892  // Therefore only return if curbuf changed to the deleted buffer.
893  if (buf == curbuf && !is_curbuf) {
894    return false;
895  }
896
897  // If curbuf, stop Visual mode just before freeing, but after autocmds that may restart it.
898  if (buf == curbuf && Visual.active
899#if defined(EXITFREE)
900      && !entered_free_all_mem
901#endif
902      ) {
903    end_visual_mode();
904  }
905
906  diff_buf_delete(buf);             // Can't use 'diff' for unloaded buffer.
907  // Remove any ownsyntax, unless exiting.
908  if (curwin != NULL && curwin->w_buffer == buf) {
909    reset_synblock(curwin);
910  }
911
912  // No folds in an empty buffer.
913  FOR_ALL_TAB_WINDOWS(tp, win) {
914    if (win->w_buffer == buf) {
915      clearFolding(win);
916    }
917  }
918
919  // Autocommands may have opened another terminal. Block them this time.
920  if (buf->terminal) {
921    block_autocmds();
922    buf_close_terminal(buf);
923    unblock_autocmds();
924  }
925
926  linenr_T count = buf->b_ml.ml_line_count;
927  ml_close(buf, true);              // close and delete the memline/memfile
928  buf->b_ml.ml_line_count = 0;      // no lines in buffer
929  mc_buf_clear(buf);                // Tracked mc positions died with the text.
930
931  // Ensure marks are adjusted for cleared buffer in case buffer not on disk:
932  // if it is reloaded the buffer will be empty.
933  if (bt_nofilename(buf) && !exiting) {
934    mark_adjust_buf(buf, 1, count, MAXLNUM, -count, false, kMarkAdjustNormal, kExtmarkNoUndo);
935  }
936
937  if ((flags & BFA_KEEP_UNDO) == 0) {
938    // free the memory allocated for undo
939    // and reset all undo information
940    u_clearallandblockfree(buf);
941  }
942  syntax_clear(&buf->b_s);          // reset syntax info
943  buf->b_flags &= ~BF_READERR;      // a read error is no longer relevant
944  return true;
945}
946
947/// Free a buffer structure and the things it contains related to the buffer
948/// itself (not the file, that must have been done already).
949static void free_buffer(buf_T *buf)
950{
951  pmap_del(int)(&buffer_handles, buf->b_fnum, NULL);
952  buf_free_count++;
953  // b:changedtick uses an item in buf_T.
954  free_buffer_stuff(buf, kBffClearWinInfo);
955  if (buf->b_vars->dv_refcount > DO_NOT_FREE_CNT) {
956    tv_dict_add(buf->b_vars,
957                tv_dict_item_copy((dictitem_T *)(&buf->changedtick_di)));
958  }
959  unref_var_dict(buf->b_vars);
960  aubuflocal_remove(buf);
961  xfree(buf->additional_data);
962  xfree(buf->b_prompt_text);
963  kv_destroy(buf->b_wininfo);
964  callback_free(&buf->b_prompt_callback);
965  callback_free(&buf->b_prompt_interrupt);
966  clear_fmark(&buf->b_last_cursor, 0);
967  clear_fmark(&buf->b_last_insert, 0);
968  clear_fmark(&buf->b_last_change, 0);
969  clear_fmark(&buf->b_prompt_start, 0);
970  for (size_t i = 0; i < NMARKS; i++) {
971    free_fmark(buf->b_namedm[i]);
972  }
973  for (int i = 0; i < buf->b_changelistlen; i++) {
974    free_fmark(buf->b_changelist[i]);
975  }
976  if (autocmd_busy) {
977    // Do not free the buffer structure while autocommands are executing,
978    // it's still needed. Free it when autocmd_busy is reset.
979    CLEAR_FIELD(buf->b_namedm);
980    CLEAR_FIELD(buf->b_changelist);
981    buf->b_next = au_pending_free_buf;
982    au_pending_free_buf = buf;
983  } else {
984    xfree(buf);
985    if (curbuf == buf) {
986      curbuf = NULL;  // make clear it's not to be used
987    }
988  }
989}
990
991/// Free the b_wininfo list for buffer "buf".
992static void clear_wininfo(buf_T *buf)
993{
994  for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
995    free_wininfo(kv_A(buf->b_wininfo, i), buf);
996  }
997  kv_size(buf->b_wininfo) = 0;
998}
999
1000/// Free stuff in the buffer for ":bdel" and when wiping out the buffer.
1001///
1002/// @param buf  Buffer pointer
1003/// @param free_flags  BufFreeFlags
1004static void free_buffer_stuff(buf_T *buf, int free_flags)
1005{
1006  if (free_flags & kBffClearWinInfo) {
1007    clear_wininfo(buf);                 // including window-local options
1008    free_buf_options(buf, true);
1009    ga_clear(&buf->b_s.b_langp);
1010  }
1011  {
1012    // Avoid losing b:changedtick when deleting buffer: clearing variables
1013    // implies using clear_tv() on b:changedtick and that sets changedtick to
1014    // zero.
1015    hashitem_T *const changedtick_hi = hash_find(&buf->b_vars->dv_hashtab, "changedtick");
1016    assert(changedtick_hi != NULL);
1017    hash_remove(&buf->b_vars->dv_hashtab, changedtick_hi);
1018  }
1019  vars_clear(&buf->b_vars->dv_hashtab);   // free all internal variables
1020  hash_init(&buf->b_vars->dv_hashtab);
1021  if (free_flags & kBffInitChangedtick) {
1022    buf_init_changedtick(buf);
1023  }
1024  uc_clear(&buf->b_ucmds);               // clear local user commands
1025  extmark_free_all(buf);                 // delete any extmarks
1026  mc_buf_free(buf);                      // Multicursors died with their extmarks.
1027  map_clear_mode(buf, MAP_ALL_MODES, true, false);  // clear local mappings
1028  map_clear_mode(buf, MAP_ALL_MODES, true, true);   // clear local abbrevs
1029  XFREE_CLEAR(buf->b_start_fenc);
1030  XFREE_CLEAR(buf->b_localdir);
1031  XFREE_CLEAR(buf->b_prevdir);
1032
1033  buf_free_callbacks(buf);
1034}
1035
1036/// Go to another buffer.  Handles the result of the ATTENTION dialog.
1037void goto_buffer(exarg_T *eap, int start, int dir, int count)
1038{
1039  const int save_sea = swap_exists_action;
1040  bool skip_help_buf;
1041
1042  switch (eap->cmdidx) {
1043  case CMD_bnext:
1044  case CMD_sbnext:
1045  case CMD_bNext:
1046  case CMD_bprevious:
1047  case CMD_sbNext:
1048  case CMD_sbprevious:
1049    skip_help_buf = true;
1050    break;
1051  default:
1052    skip_help_buf = false;
1053    break;
1054  }
1055
1056  bufref_T old_curbuf;
1057  set_bufref(&old_curbuf, curbuf);
1058
1059  if (swap_exists_action == SEA_NONE) {
1060    swap_exists_action = SEA_DIALOG;
1061  }
1062  (void)do_buffer_ext(*eap->cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO, start, dir, count,
1063                      (eap->forceit ? DOBUF_FORCEIT : 0) |
1064                      (skip_help_buf ? DOBUF_SKIPHELP : 0));
1065
1066  if (swap_exists_action == SEA_QUIT && *eap->cmd == 's') {
1067    cleanup_T cs;
1068
1069    // Reset the error/interrupt/exception state here so that
1070    // aborting() returns false when closing a window.
1071    enter_cleanup(&cs);
1072
1073    // Quitting means closing the split window, nothing else.
1074    win_close(curwin, true, false);
1075    swap_exists_action = save_sea;
1076    swap_exists_did_quit = true;
1077
1078    // Restore the error/interrupt/exception state if not discarded by a
1079    // new aborting error, interrupt, or uncaught exception.
1080    leave_cleanup(&cs);
1081  } else {
1082    handle_swap_exists(&old_curbuf);
1083  }
1084}
1085
1086/// Handle the situation of swap_exists_action being set.
1087///
1088/// It is allowed for "old_curbuf" to be NULL or invalid.
1089///
1090/// @param old_curbuf The buffer to check for.
1091void handle_swap_exists(bufref_T *old_curbuf)
1092{
1093  cleanup_T cs;
1094  OptInt old_tw = curbuf->b_p_tw;
1095  buf_T *buf;
1096
1097  if (swap_exists_action == SEA_QUIT) {
1098    // Reset the error/interrupt/exception state here so that
1099    // aborting() returns false when closing a buffer.
1100    enter_cleanup(&cs);
1101
1102    // User selected Quit at ATTENTION prompt.  Go back to previous
1103    // buffer.  If that buffer is gone or the same as the current one,
1104    // open a new, empty buffer.
1105    swap_exists_action = SEA_NONE;      // don't want it again
1106    swap_exists_did_quit = true;
1107    close_buffer(curwin, curbuf, DOBUF_UNLOAD, false, false, true);
1108    if (old_curbuf == NULL
1109        || !bufref_valid(old_curbuf)
1110        || old_curbuf->br_buf == curbuf) {
1111      // Block autocommands here because curwin->w_buffer may be NULL.
1112      block_autocmds();
1113      buf = buflist_new(NULL, NULL, 1, BLN_CURBUF | BLN_LISTED);
1114      unblock_autocmds();
1115    } else {
1116      buf = old_curbuf->br_buf;
1117    }
1118    if (buf != NULL) {
1119      enter_buffer(buf);
1120
1121      if (old_tw != curbuf->b_p_tw) {
1122        check_colorcolumn(NULL, curwin);
1123      }
1124    }
1125    // If "old_curbuf" is NULL we are in big trouble here...
1126
1127    // Restore the error/interrupt/exception state if not discarded by a
1128    // new aborting error, interrupt, or uncaught exception.
1129    leave_cleanup(&cs);
1130  } else if (swap_exists_action == SEA_RECOVER) {
1131    // Reset the error/interrupt/exception state here so that
1132    // aborting() returns false when closing a buffer.
1133    enter_cleanup(&cs);
1134
1135    // User selected Recover at ATTENTION prompt.
1136    msg_scroll = true;
1137    ml_recover(false);
1138    msg_puts("\n");     // don't overwrite the last message
1139    cmdline_row = msg_row;
1140    do_modelines(0);
1141
1142    // Restore the error/interrupt/exception state if not discarded by a
1143    // new aborting error, interrupt, or uncaught exception.
1144    leave_cleanup(&cs);
1145  }
1146  swap_exists_action = SEA_NONE;
1147}
1148
1149/// do_bufdel() - delete or unload buffer(s)
1150///
1151/// addr_count == 0: ":bdel" - delete current buffer
1152/// addr_count == 1: ":N bdel" or ":bdel N [N ..]" - first delete
1153///                  buffer "end_bnr", then any other arguments.
1154/// addr_count == 2: ":N,N bdel" - delete buffers in range
1155///
1156/// command can be DOBUF_UNLOAD (":bunload"), DOBUF_WIPE (":bwipeout") or
1157/// DOBUF_DEL (":bdel")
1158///
1159/// @param arg  pointer to extra arguments
1160/// @param start_bnr  first buffer number in a range
1161/// @param end_bnr  buffer nr or last buffer nr in a range
1162///
1163/// @return  error message or NULL
1164char *do_bufdel(int command, char *arg, int addr_count, int start_bnr, int end_bnr, int forceit)
1165{
1166  int do_current = 0;             // delete current buffer?
1167  int deleted = 0;                // number of buffers deleted
1168  char *errormsg = NULL;          // return value
1169  int bnr;                        // buffer number
1170
1171  if (addr_count == 0) {
1172    do_buffer(command, DOBUF_CURRENT, FORWARD, 0, forceit);
1173  } else {
1174    if (addr_count == 2) {
1175      if (*arg) {               // both range and argument is not allowed
1176        return ex_errmsg(e_trailing_arg, arg);
1177      }
1178      bnr = start_bnr;
1179    } else {    // addr_count == 1
1180      bnr = end_bnr;
1181    }
1182
1183    for (; !got_int; os_breakcheck()) {
1184      // delete the current buffer last, otherwise when the
1185      // current buffer is deleted, the next buffer becomes
1186      // the current one and will be loaded, which may then
1187      // also be deleted, etc.
1188      if (bnr == curbuf->b_fnum) {
1189        do_current = bnr;
1190      } else if (do_buffer(command, DOBUF_FIRST, FORWARD, bnr,
1191                           forceit) == OK) {
1192        deleted++;
1193      }
1194
1195      // find next buffer number to delete/unload
1196      if (addr_count == 2) {
1197        if (++bnr > end_bnr) {
1198          break;
1199        }
1200      } else {    // addr_count == 1
1201        arg = skipwhite(arg);
1202        if (*arg == NUL) {
1203          break;
1204        }
1205        if (!ascii_isdigit(*arg)) {
1206          char *p = skiptowhite_esc(arg);
1207          bnr = buflist_findpat(arg, p, command == DOBUF_WIPE, false, false);
1208          if (bnr < 0) {                    // failed
1209            break;
1210          }
1211          arg = p;
1212        } else {
1213          bnr = getdigits_int(&arg, false, 0);
1214        }
1215      }
1216    }
1217    if (!got_int && do_current
1218        && do_buffer(command, DOBUF_FIRST,
1219                     FORWARD, do_current, forceit) == OK) {
1220      deleted++;
1221    }
1222
1223    if (deleted == 0) {
1224      if (command == DOBUF_UNLOAD) {
1225        xstrlcpy(IObuff, _("E515: No buffers were unloaded"), IOSIZE);
1226      } else if (command == DOBUF_DEL) {
1227        xstrlcpy(IObuff, _("E516: No buffers were deleted"), IOSIZE);
1228      } else {
1229        xstrlcpy(IObuff, _("E517: No buffers were wiped out"), IOSIZE);
1230      }
1231      errormsg = IObuff;
1232    } else if (deleted >= p_report) {
1233      if (command == DOBUF_UNLOAD) {
1234        smsg(0, NGETTEXT("%d buffer unloaded", "%d buffers unloaded", deleted),
1235             deleted);
1236      } else if (command == DOBUF_DEL) {
1237        smsg(0, NGETTEXT("%d buffer deleted", "%d buffers deleted", deleted),
1238             deleted);
1239      } else {
1240        smsg(0, NGETTEXT("%d buffer wiped out", "%d buffers wiped out", deleted),
1241             deleted);
1242      }
1243    }
1244  }
1245
1246  return errormsg;
1247}
1248
1249/// Make the current buffer empty.
1250/// Used when it is wiped out and it's the last buffer.
1251static int empty_curbuf(bool close_others, int forceit, int action)
1252{
1253  buf_T *buf = curbuf;
1254
1255  if (action == DOBUF_UNLOAD) {
1256    emsg(_("E90: Cannot unload last buffer"));
1257    return FAIL;
1258  }
1259
1260  bufref_T bufref;
1261  set_bufref(&bufref, buf);
1262
1263  if (close_others) {
1264    bool can_close_all_others = true;
1265    if (curwin->w_floating) {
1266      // Closing all other windows with this buffer may leave only floating windows.
1267      can_close_all_others = false;
1268      for (win_T *wp = firstwin; !wp->w_floating; wp = wp->w_next) {
1269        if (wp->w_buffer != curbuf) {
1270          // Found another non-floating window with a different (probably unlisted) buffer.
1271          // Closing all other windows with this buffer is fine in this case.
1272          can_close_all_others = true;
1273          break;
1274        }
1275      }
1276    }
1277    // If it is fine to close all other windows with this buffer, keep the current window and
1278    // close any other windows with this buffer, then make it empty.
1279    // Otherwise close_windows() will refuse to close the last non-floating window, so allow it
1280    // to close the current window instead.
1281    close_windows(buf, can_close_all_others);
1282  }
1283
1284  setpcmark();
1285  int retval = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, forceit ? ECMD_FORCEIT : 0, curwin);
1286
1287  // do_ecmd() may create a new buffer, then we have to delete
1288  // the old one.  But do_ecmd() may have done that already, check
1289  // if the buffer still exists.
1290  if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows == 0) {
1291    close_buffer(NULL, buf, action, false, false, false);
1292  }
1293
1294  if (!close_others) {
1295    need_fileinfo = false;
1296  } else if (retval == OK && !shortmess(kShmFileinfo)) {
1297    // do_ecmd() does not display file info for a new empty buffer.
1298    need_fileinfo = true;
1299  }
1300
1301  return retval;
1302}
1303
1304/// Implementation of the commands for the buffer list.
1305///
1306/// action == DOBUF_GOTO     go to specified buffer
1307/// action == DOBUF_SPLIT    split window and go to specified buffer
1308/// action == DOBUF_UNLOAD   unload specified buffer(s)
1309/// action == DOBUF_DEL      delete specified buffer(s) from buffer list
1310/// action == DOBUF_WIPE     delete specified buffer(s) really
1311///
1312/// start == DOBUF_CURRENT   go to "count" buffer from current buffer
1313/// start == DOBUF_FIRST     go to "count" buffer from first buffer
1314/// start == DOBUF_LAST      go to "count" buffer from last buffer
1315/// start == DOBUF_MOD       go to "count" modified buffer from current buffer
1316///
1317/// @param dir  FORWARD or BACKWARD
1318/// @param count  buffer number or number of buffers
1319/// @param flags  see @ref dobuf_flags_value
1320///
1321/// @return  FAIL or OK.
1322static int do_buffer_ext(int action, int start, int dir, int count, int flags)
1323{
1324  buf_T *buf;
1325  buf_T *bp;
1326  bool update_jumplist = true;
1327  bool unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1328                 || action == DOBUF_WIPE);
1329
1330  switch (start) {
1331  case DOBUF_FIRST:
1332    buf = firstbuf; break;
1333  case DOBUF_LAST:
1334    buf = lastbuf;  break;
1335  default:
1336    buf = curbuf;   break;
1337  }
1338  if (start == DOBUF_MOD) {         // find next modified buffer
1339    while (count-- > 0) {
1340      do {
1341        buf = buf->b_next;
1342        if (buf == NULL) {
1343          buf = firstbuf;
1344        }
1345      } while (buf != curbuf && !bufIsChanged(buf));
1346    }
1347    if (!bufIsChanged(buf)) {
1348      emsg(_("E84: No modified buffer found"));
1349      return FAIL;
1350    }
1351  } else if (start == DOBUF_FIRST && count) {  // find specified buffer number
1352    while (buf != NULL && buf->b_fnum != count) {
1353      buf = buf->b_next;
1354    }
1355  } else {
1356    const bool help_only = (flags & DOBUF_SKIPHELP) != 0 && buf->b_help;
1357
1358    bp = NULL;
1359    while (count > 0 || (bp != buf && !unload
1360                         && !(help_only ? buf->b_help : buf->b_p_bl))) {
1361      // remember the buffer where we start, we come back there when all
1362      // buffers are unlisted.
1363      if (bp == NULL) {
1364        bp = buf;
1365      }
1366      buf = dir == FORWARD ? (buf->b_next != NULL ? buf->b_next : firstbuf)
1367                           : (buf->b_prev != NULL ? buf->b_prev : lastbuf);
1368      // Avoid non-help buffers if the starting point was a help buffer
1369      // and vice-versa.
1370      // Don't count unlisted buffers.
1371      if (unload
1372          || (help_only
1373              ? buf->b_help
1374              : (buf->b_p_bl && ((flags & DOBUF_SKIPHELP) == 0 || !buf->b_help)))) {
1375        count--;
1376        bp = NULL;              // use this buffer as new starting point
1377      }
1378      if (bp == buf) {
1379        // back where we started, didn't find anything.
1380        emsg(_("E85: There is no listed buffer"));
1381        return FAIL;
1382      }
1383    }
1384  }
1385
1386  if (buf == NULL) {        // could not find it
1387    if (start == DOBUF_FIRST) {
1388      // don't warn when deleting
1389      if (!unload) {
1390        semsg(_(e_nobufnr), (int64_t)count);
1391      }
1392    } else if (dir == FORWARD) {
1393      emsg(_("E87: Cannot go beyond last buffer"));
1394    } else {
1395      emsg(_("E88: Cannot go before first buffer"));
1396    }
1397    return FAIL;
1398  }
1399
1400  if (action == DOBUF_GOTO && buf != curbuf
1401      && !check_can_set_curbuf_forceit((flags & DOBUF_FORCEIT) != 0)) {
1402    // disallow navigating to another buffer when 'winfixbuf' is applied
1403    return FAIL;
1404  }
1405
1406  if ((action == DOBUF_GOTO || action == DOBUF_SPLIT) && (buf->b_flags & BF_DUMMY)) {
1407    // disallow navigating to the dummy buffer
1408    semsg(_(e_nobufnr), count);
1409    return FAIL;
1410  }
1411
1412  // delete buffer "buf" from memory and/or the list
1413  if (unload) {
1414    int forward;
1415    bufref_T bufref;
1416    if (!can_unload_buffer(buf)) {
1417      return FAIL;
1418    }
1419    set_bufref(&bufref, buf);
1420
1421    // When unloading or deleting a buffer that's already unloaded and
1422    // unlisted: fail silently.
1423    if (action != DOBUF_WIPE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl) {
1424      return FAIL;
1425    }
1426
1427    if ((flags & DOBUF_FORCEIT) == 0 && bufIsChanged(buf)) {
1428      if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) {
1429        dialog_changed(buf, false);
1430        if (!bufref_valid(&bufref)) {
1431          // Autocommand deleted buffer, oops! It's not changed now.
1432          return FAIL;
1433        }
1434        // If it's still changed fail silently, the dialog already
1435        // mentioned why it fails.
1436        if (bufIsChanged(buf)) {
1437          return FAIL;
1438        }
1439      } else {
1440        semsg(_(e_no_write_since_last_change_for_buffer_nr_add_bang_to_override),
1441              buf->b_fnum);
1442        return FAIL;
1443      }
1444    }
1445
1446    if (!(flags & DOBUF_FORCEIT) && buf->terminal && terminal_running(buf->terminal)) {
1447      if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) {
1448        if (!dialog_close_terminal(buf)) {
1449          return FAIL;
1450        }
1451      } else {
1452        semsg(_("E89: %s will be killed (add ! to override)"), buf->b_fname);
1453        return FAIL;
1454      }
1455    }
1456
1457    int buf_fnum = buf->b_fnum;
1458
1459    // When closing the current buffer stop Visual mode.
1460    if (buf == curbuf && Visual.active) {
1461      end_visual_mode();
1462    }
1463
1464    // If deleting the last (listed) buffer, make it empty.
1465    // The last (listed) buffer cannot be unloaded.
1466    bp = NULL;
1467    FOR_ALL_BUFFERS(bp2) {
1468      if (bp2->b_p_bl && bp2 != buf) {
1469        bp = bp2;
1470        break;
1471      }
1472    }
1473    if (bp == NULL && buf == curbuf) {
1474      return empty_curbuf(true, (flags & DOBUF_FORCEIT), action);
1475    }
1476
1477    // If the deleted buffer is the current one, close the current window
1478    // (unless it's the only non-floating window).
1479    // When the autocommand window is involved win_close() may need to print an error message.
1480    // Repeat this so long as we end up in a window with this buffer.
1481    while (buf == curbuf
1482           && !(win_locked(curwin) || curwin->w_buffer->b_locked > 0)
1483           && (is_ctx_win(lastwin) || !last_window(curwin))) {
1484      if (win_close(curwin, false, false) == FAIL) {
1485        break;
1486      }
1487    }
1488
1489    // If the buffer to be deleted is not the current one, delete it here.
1490    if (buf != curbuf) {
1491      if (jop_flags & kOptJopFlagClean) {
1492        // Remove the buffer to be deleted from the jump list.
1493        mark_jumplist_forget_file(curwin, buf_fnum);
1494      }
1495
1496      close_windows(buf, false);
1497      // close_windows() refuses to close curtab's last non-float window.
1498      // If it still shows buf, retry the delete from there.
1499      if (buf != curbuf && bufref_valid(&bufref) && firstwin->w_buffer == buf
1500          && one_window(firstwin, NULL)) {
1501        // Switch to buf's holder window without entering it: caller keeps focus,
1502        // BufEnter doesn't fire for the deleted buffer.
1503        // curwin must be floating: buf != curbuf, yet firstwin (the last non-float) shows buf.
1504        // Also firstwin is valid in curtab, so ctx_switch should not fail.
1505        assert(curwin->w_floating);
1506        CtxSwitch switchwin;
1507        const bool rv = ctx_switch(&switchwin, firstwin, curtab, NULL, kCtxNoDisplay);
1508        assert(rv);
1509        (void)rv;
1510        // retry (recurse)
1511        do_buffer_ext(action, start, dir, count, flags);
1512        ctx_restore(&switchwin);
1513      }
1514
1515      if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows <= 0) {
1516        close_buffer(NULL, buf, action, false, false, false);
1517      }
1518      return OK;
1519    }
1520
1521    // Deleting the current buffer: Need to find another buffer to go to.
1522    // There should be another, otherwise it would have been handled
1523    // above.  However, autocommands may have deleted all buffers.
1524    // First use au_new_curbuf.br_buf, if it is valid.
1525    // Then prefer the buffer we most recently visited.
1526    // Else try to find one that is loaded, after the current buffer,
1527    // then before the current buffer.
1528    // Finally use any buffer.  Skip buffers that are closing throughout.
1529    buf = NULL;  // Selected buffer.
1530    bp = NULL;   // Used when no loaded buffer found.
1531    if (au_new_curbuf.br_buf != NULL && bufref_valid(&au_new_curbuf)
1532        && !au_new_curbuf.br_buf->b_locked_split) {
1533      buf = au_new_curbuf.br_buf;
1534    } else if (curwin->w_jumplistlen > 0) {
1535      if (jop_flags & kOptJopFlagClean) {
1536        // Remove the buffer from the jump list.
1537        mark_jumplist_forget_file(curwin, buf_fnum);
1538      }
1539
1540      // It's possible that we removed all jump list entries, in that case we need to try another
1541      // approach
1542      if (curwin->w_jumplistlen > 0) {
1543        int jumpidx = curwin->w_jumplistidx;
1544
1545        if (jop_flags & kOptJopFlagClean) {
1546          // If the index is the same as the length, the current position was not yet added to the
1547          // jump list. So we can safely go back to the last entry and search from there.
1548          if (jumpidx == curwin->w_jumplistlen) {
1549            jumpidx = curwin->w_jumplistidx = curwin->w_jumplistlen - 1;
1550          }
1551        } else {
1552          jumpidx--;
1553          if (jumpidx < 0) {
1554            jumpidx = curwin->w_jumplistlen - 1;
1555          }
1556        }
1557
1558        forward = jumpidx;
1559        while ((jop_flags & kOptJopFlagClean) || jumpidx != curwin->w_jumplistidx) {
1560          buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum);
1561
1562          if (buf != NULL) {
1563            // Skip current and unlisted bufs.  Also skip a quickfix
1564            // or closing buffer, it might be deleted soon.
1565            if (buf == curbuf || !buf->b_p_bl || bt_quickfix(buf)
1566                || buf->b_locked_split) {
1567              buf = NULL;
1568            } else if (buf->b_ml.ml_mfp == NULL) {
1569              // skip unloaded buf, but may keep it for later
1570              if (bp == NULL) {
1571                bp = buf;
1572              }
1573              buf = NULL;
1574            }
1575          }
1576          if (buf != NULL) {         // found a valid buffer: stop searching
1577            if (jop_flags & kOptJopFlagClean) {
1578              curwin->w_jumplistidx = jumpidx;
1579              update_jumplist = false;
1580            }
1581            break;
1582          }
1583          // advance to older entry in jump list
1584          if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen) {
1585            break;
1586          }
1587          if (--jumpidx < 0) {
1588            jumpidx = curwin->w_jumplistlen - 1;
1589          }
1590          if (jumpidx == forward) {               // List exhausted for sure
1591            break;
1592          }
1593        }
1594      }
1595    }
1596
1597    if (buf == NULL) {          // No previous buffer, Try 2'nd approach
1598      forward = true;
1599      buf = curbuf->b_next;
1600      while (true) {
1601        if (buf == NULL) {
1602          if (!forward) {               // tried both directions
1603            break;
1604          }
1605          buf = curbuf->b_prev;
1606          forward = false;
1607          continue;
1608        }
1609        // in non-help buffer, try to skip help buffers, and vv
1610        if (buf->b_help == curbuf->b_help && buf->b_p_bl
1611            && !bt_quickfix(buf) && !buf->b_locked_split) {
1612          if (buf->b_ml.ml_mfp != NULL) {           // found loaded buffer
1613            break;
1614          }
1615          if (bp == NULL) {             // remember unloaded buf for later
1616            bp = buf;
1617          }
1618        }
1619        buf = forward ? buf->b_next : buf->b_prev;
1620      }
1621    }
1622    if (buf == NULL) {          // No loaded buffer, use unloaded one
1623      buf = bp;
1624    }
1625    if (buf == NULL) {          // No loaded buffer, find listed one
1626      FOR_ALL_BUFFERS(buf2) {
1627        if (buf2->b_p_bl && buf2 != curbuf && !bt_quickfix(buf2) && !buf2->b_locked_split) {
1628          buf = buf2;
1629          break;
1630        }
1631      }
1632    }
1633    if (buf == NULL) {          // Still no buffer, just take one
1634      buf = curbuf->b_next != NULL ? curbuf->b_next : curbuf->b_prev;
1635      if (bt_quickfix(buf) || (buf != NULL && buf != curbuf && buf->b_locked_split)) {
1636        buf = NULL;
1637      }
1638    }
1639  }
1640
1641  if (buf == NULL) {
1642    // Autocommands must have wiped out all other buffers.  Only option
1643    // now is to make the current buffer empty.
1644    return empty_curbuf(false, (flags & DOBUF_FORCEIT), action);
1645  }
1646
1647  // make "buf" the current buffer
1648  // If 'switchbuf' is set jump to the window containing "buf".
1649  if (action == DOBUF_SPLIT && swbuf_goto_win_with_buf(buf) != NULL) {
1650    return OK;
1651  }
1652  // Whether splitting or not, don't open a closing buffer in more windows.
1653  if (buf != curbuf && buf->b_locked_split) {
1654    emsg(_(e_cannot_switch_to_a_closing_buffer));
1655    return FAIL;
1656  }
1657  if (action == DOBUF_SPLIT && win_split(0, 0) == FAIL) {  // split window first
1658    return FAIL;
1659  }
1660
1661  // go to current buffer - nothing to do
1662  if (buf == curbuf) {
1663    return OK;
1664  }
1665
1666  // Check if the current buffer may be abandoned.
1667  if (action == DOBUF_GOTO && !can_abandon(curbuf, (flags & DOBUF_FORCEIT))) {
1668    if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM)) && p_write) {
1669      bufref_T bufref;
1670      set_bufref(&bufref, buf);
1671      dialog_changed(curbuf, false);
1672      if (!bufref_valid(&bufref)) {
1673        // Autocommand deleted buffer, oops!
1674        return FAIL;
1675      }
1676    }
1677    if (bufIsChanged(curbuf)) {
1678      no_write_message();
1679      return FAIL;
1680    }
1681  }
1682
1683  // Go to the other buffer.
1684  set_curbuf(buf, action, update_jumplist);
1685
1686  if (action == DOBUF_SPLIT) {
1687    RESET_BINDING(curwin);      // reset 'scrollbind' and 'cursorbind'
1688  }
1689
1690  if (aborting()) {         // autocmds may abort script processing
1691    return FAIL;
1692  }
1693
1694  return OK;
1695}
1696
1697int do_buffer(int action, int start, int dir, int count, int forceit)
1698{
1699  return do_buffer_ext(action, start, dir, count, forceit ? DOBUF_FORCEIT : 0);
1700}
1701
1702/// Set current buffer to "buf".  Executes autocommands and closes current
1703/// buffer.
1704///
1705/// @param action  tells how to close the current buffer:
1706///                DOBUF_GOTO       free or hide it
1707///                DOBUF_SPLIT      nothing
1708///                DOBUF_UNLOAD     unload it
1709///                DOBUF_DEL        delete it
1710///                DOBUF_WIPE       wipe it out
1711void set_curbuf(buf_T *buf, int action, bool update_jumplist)
1712{
1713  buf_T *prevbuf;
1714  int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1715                || action == DOBUF_WIPE);
1716  OptInt old_tw = curbuf->b_p_tw;
1717
1718  if (update_jumplist) {
1719    setpcmark();
1720  }
1721
1722  if ((cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
1723    curwin->w_alt_fnum = curbuf->b_fnum;     // remember alternate file
1724  }
1725  buflist_altfpos(curwin);                       // remember curpos
1726
1727  // Don't restart Select mode after switching to another buffer.
1728  Visual.reselect = false;
1729
1730  // close_windows() or apply_autocmds() may change curbuf and wipe out "buf"
1731  prevbuf = curbuf;
1732  bufref_T newbufref;
1733  bufref_T prevbufref;
1734  set_bufref(&prevbufref, prevbuf);
1735  set_bufref(&newbufref, buf);
1736
1737  // Autocommands may delete the current buffer and/or the buffer we want to
1738  // go to.  In those cases don't close the buffer.
1739  if (!apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf)
1740      || (bufref_valid(&prevbufref) && bufref_valid(&newbufref)
1741          && !aborting())) {
1742    if (prevbuf == curwin->w_buffer) {
1743      reset_synblock(curwin);
1744    }
1745    if (unload) {
1746      close_windows(prevbuf, false);
1747    }
1748    if (bufref_valid(&prevbufref) && !aborting()) {
1749      // Do not sync when in Insert mode and the buffer is open in
1750      // another window, might be a timer doing something in another
1751      // window.
1752      if (prevbuf == curbuf && ((State & MODE_INSERT) == 0 || curbuf->b_nwindows <= 1)) {
1753        u_sync(false);
1754      }
1755      close_buffer(curwin,
1756                   prevbuf,
1757                   unload
1758                   ? action
1759                   : (action == DOBUF_GOTO && !buf_hide(prevbuf)
1760                      && !bufIsChanged(prevbuf)) ? DOBUF_UNLOAD : 0,
1761                   false, false, true);
1762    }
1763  }
1764  // An autocommand may have deleted "buf", already entered it (e.g., when
1765  // it did ":bunload") or aborted the script processing!
1766  // If curwin->w_buffer is null, enter_buffer() will make it valid again
1767  bool valid = buf_valid(buf);
1768  if ((valid && buf != curbuf && !aborting()) || curwin->w_buffer == NULL) {
1769    // If the buffer is not valid but curwin->w_buffer is NULL we must
1770    // enter some buffer.  Using the last one is hopefully OK.
1771    enter_buffer(valid ? buf : lastbuf);
1772    if (old_tw != curbuf->b_p_tw) {
1773      check_colorcolumn(NULL, curwin);
1774    }
1775  }
1776
1777  if (bufref_valid(&prevbufref) && prevbuf->terminal != NULL) {
1778    terminal_check_size(prevbuf->terminal);
1779  }
1780
1781  // Maybe cd to buffer-local directory
1782  update_cwd(kCdCauseBuffer);
1783}
1784
1785/// Enter a new current buffer.
1786/// Old curbuf must have been abandoned already!  This also means "curbuf" may
1787/// be pointing to freed memory.
1788static void enter_buffer(buf_T *buf)
1789{
1790  // Stop Visual mode before changing curbuf.  Assumes curbuf and curwin->w_buffer is valid; if not,
1791  // buf_freeall() should've done this already!
1792  if (Visual.active
1793#ifdef EXITFREE
1794      && !entered_free_all_mem
1795#endif
1796      ) {
1797    end_visual_mode();
1798  }
1799
1800  if (curwin->w_buffer != NULL) {
1801    curwin->w_buffer->b_nwindows--;
1802  }
1803
1804  // Get the buffer in the current window.
1805  curwin->w_buffer = buf;
1806  curbuf = buf;
1807  curbuf->b_nwindows++;
1808
1809  // Copy buffer and window local option values.  Not for a help buffer.
1810  buf_copy_options(buf, BCO_ENTER | BCO_NOHELP);
1811  if (!buf->b_help) {
1812    get_winopts(buf);
1813  } else {
1814    // Remove all folds in the window.
1815    clearFolding(curwin);
1816  }
1817  foldUpdateAll(curwin);        // update folds (later).
1818
1819  if (curwin->w_p_diff) {
1820    diff_buf_add(curbuf);
1821  }
1822
1823  curwin->w_s = &(curbuf->b_s);
1824
1825  // Cursor on first line by default.
1826  curwin->w_cursor.lnum = 1;
1827  curwin->w_cursor.col = 0;
1828  curwin->w_cursor.coladd = 0;
1829  curwin->w_set_curswant = true;
1830  curwin->w_topline_was_set = false;
1831
1832  // mark cursor position as being invalid
1833  curwin->w_valid = 0;
1834
1835  // Make sure the buffer is loaded.
1836  if (curbuf->b_ml.ml_mfp == NULL) {    // need to load the file
1837    // If there is no filetype, allow for detecting one.  Esp. useful for
1838    // ":ball" used in an autocommand.  If there already is a filetype we
1839    // might prefer to keep it.
1840    if (*curbuf->b_p_ft == NUL) {
1841      curbuf->b_did_filetype = false;
1842    }
1843
1844    open_buffer(false, NULL, 0);
1845  } else {
1846    if (!msg_silent && !shortmess(kShmFileinfo)) {
1847      need_fileinfo = true;             // display file info after redraw
1848    }
1849    // check if file changed
1850    buf_check_timestamp(curbuf);
1851
1852    curwin->w_topline = 1;
1853    curwin->w_topfill = 0;
1854    apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
1855    apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, false, curbuf);
1856  }
1857
1858  // If autocommands did not change the cursor position, restore cursor lnum
1859  // and possibly cursor col.
1860  if (curwin->w_cursor.lnum == 1 && inindent(0)) {
1861    buflist_getfpos();
1862  }
1863
1864  check_arg_idx(curwin);                // check for valid arg_idx
1865  maketitle();
1866  win_float_update_preview(curwin);
1867  // when autocmds didn't change it
1868  if (curwin->w_topline == 1 && !curwin->w_topline_was_set) {
1869    scroll_cursor_halfway(curwin, false, false);  // redisplay at correct position
1870  }
1871
1872  // Change directories when the 'acd' option is set.
1873  do_autochdir();
1874
1875  if (curbuf->b_kmap_state & KEYMAP_INIT) {
1876    keymap_init();
1877  }
1878  // May need to set the spell language.  Can only do this after the buffer
1879  // has been properly setup.
1880  if (!curbuf->b_help && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) {
1881    parse_spelllang(curwin);
1882  }
1883  curbuf->b_last_used = time(NULL);
1884
1885  if (curbuf->terminal != NULL) {
1886    terminal_check_size(curbuf->terminal);
1887  }
1888
1889  redraw_later(curwin, UPD_NOT_VALID);
1890}
1891
1892/// Change to the directory of the current buffer.
1893/// Don't do this while still starting up.
1894void do_autochdir(void)
1895{
1896  if (p_acd) {
1897    if (starting == 0
1898        && curbuf->b_ffname != NULL
1899        && vim_chdirfile(curbuf->b_ffname, kCdCauseAuto) == OK) {
1900      last_chdir_reason = "autochdir";
1901      shorten_fnames(true);
1902    }
1903  }
1904}
1905
1906void no_write_message_buf(buf_T *buf)
1907{
1908  if (buf->terminal
1909      && channel_job_running((uint64_t)buf->b_p_channel)) {
1910    emsg(_(e_job_still_running_add_bang_to_end_the_job));
1911  } else {
1912    semsg(_(e_no_write_since_last_change_for_buffer_nr_add_bang_to_override),
1913          buf->b_fnum);
1914  }
1915}
1916
1917void no_write_message(void)
1918{
1919  if (curbuf->terminal
1920      && channel_job_running((uint64_t)curbuf->b_p_channel)) {
1921    emsg(_(e_job_still_running_add_bang_to_end_the_job));
1922  } else {
1923    emsg(_(e_no_write_since_last_change_add_bang_to_override));
1924  }
1925}
1926
1927void no_write_message_nobang(const buf_T *const buf)
1928  FUNC_ATTR_NONNULL_ALL
1929{
1930  if (buf->terminal
1931      && channel_job_running((uint64_t)buf->b_p_channel)) {
1932    emsg(_(e_job_still_running));
1933  } else {
1934    emsg(_(e_no_write_since_last_change));
1935  }
1936}
1937
1938//
1939// functions for dealing with the buffer list
1940//
1941
1942/// Initialize b:changedtick and changedtick_val attribute
1943///
1944/// @param[out]  buf  Buffer to initialize for.
1945static inline void buf_init_changedtick(buf_T *const buf)
1946  FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL
1947{
1948  STATIC_ASSERT(sizeof("changedtick") <= sizeof(buf->changedtick_di.di_key),
1949                "buf->changedtick_di cannot hold large enough keys");
1950  buf->changedtick_di = (ChangedtickDictItem) {
1951    .di_flags = DI_FLAGS_RO|DI_FLAGS_FIX,  // Must not include DI_FLAGS_ALLOC.
1952    .di_tv = (typval_T) {
1953      .v_type = VAR_NUMBER,
1954      .v_lock = VAR_FIXED,
1955      .vval.v_number = buf_get_changedtick(buf),
1956    },
1957    .di_key = "changedtick",
1958  };
1959  tv_dict_add(buf->b_vars, (dictitem_T *)&buf->changedtick_di);
1960}
1961
1962/// Add a file name to the buffer list.
1963/// If the same file name already exists return a pointer to that buffer.
1964/// If it does not exist, or if fname == NULL, a new entry is created.
1965/// If (flags & BLN_CURBUF) is true, may use current buffer.
1966/// If (flags & BLN_LISTED) is true, add new buffer to buffer list.
1967/// If (flags & BLN_DUMMY) is true, don't count it as a real buffer.
1968/// If (flags & BLN_NEW) is true, don't use an existing buffer.
1969/// If (flags & BLN_NOOPT) is true, don't copy options from the current buffer
1970///                                 if the buffer already exists.
1971/// This is the ONLY way to create a new buffer.
1972///
1973/// @param ffname_arg  full path of fname or relative
1974/// @param sfname_arg  short fname or NULL
1975/// @param lnum   preferred cursor line
1976/// @param flags  BLN_ defines
1977/// @param bufnr
1978///
1979/// @return  pointer to the buffer
1980buf_T *buflist_new(char *ffname_arg, char *sfname_arg, linenr_T lnum, int flags)
1981{
1982  char *ffname = ffname_arg;
1983  char *sfname = sfname_arg;
1984  buf_T *buf;
1985
1986  fname_expand(curbuf, &ffname, &sfname);       // will allocate ffname
1987
1988  // If the file name already exists in the list, update the entry.
1989
1990  // We can use inode numbers when the file exists.  Works better
1991  // for hard links.
1992  FileID file_id;
1993  bool file_id_valid = (sfname != NULL && os_fileid(sfname, &file_id));
1994  if (ffname != NULL && !(flags & (BLN_DUMMY | BLN_NEW))
1995      && (buf = buflist_findname_file_id(ffname, &file_id, file_id_valid)) != NULL) {
1996    xfree(ffname);
1997    if (lnum != 0) {
1998      buflist_setfpos(buf, (flags & BLN_NOCURWIN) ? NULL : curwin,
1999                      lnum, 0, false);
2000    }
2001    if ((flags & BLN_NOOPT) == 0) {
2002      // Copy the options now, if 'cpo' doesn't have 's' and not done already.
2003      buf_copy_options(buf, 0);
2004    }
2005    if ((flags & BLN_LISTED) && !buf->b_p_bl) {
2006      buf->b_p_bl = true;
2007      bufref_T bufref;
2008      set_bufref(&bufref, buf);
2009      if (!(flags & BLN_DUMMY)) {
2010        if (apply_autocmds(EVENT_BUFADD, NULL, NULL, false, buf)
2011            && !bufref_valid(&bufref)) {
2012          return NULL;
2013        }
2014      }
2015    }
2016    return buf;
2017  }
2018
2019  // If the current buffer has no name and no contents, use the current
2020  // buffer.    Otherwise: Need to allocate a new buffer structure.
2021  //
2022  // This is the ONLY place where a new buffer structure is allocated!
2023  // (A spell file buffer is allocated in spell.c, but that's not a normal
2024  // buffer.)
2025  buf = NULL;
2026  if ((flags & BLN_CURBUF) && curbuf_reusable()) {
2027    bufref_T bufref;
2028
2029    assert(curbuf != NULL);
2030    buf = curbuf;
2031    set_bufref(&bufref, buf);
2032    trigger_undo_ftplugin(buf, curwin);
2033    // It's like this buffer is deleted.  Watch out for autocommands that
2034    // change curbuf!  If that happens, allocate a new buffer anyway.
2035    buf_freeall(buf, BFA_WIPE | BFA_DEL);
2036    if (aborting()) {           // autocmds may abort script processing
2037      xfree(ffname);
2038      return NULL;
2039    }
2040    if (!bufref_valid(&bufref)) {
2041      buf = NULL;  // buf was deleted; allocate a new buffer
2042    }
2043  }
2044  if (buf != curbuf || curbuf == NULL) {
2045    buf = xcalloc(1, sizeof(buf_T));
2046    // init b: variables
2047    buf->b_vars = tv_dict_alloc();
2048    init_var_dict(buf->b_vars, &buf->b_bufvar, VAR_SCOPE);
2049    buf_init_changedtick(buf);
2050  }
2051
2052  if (ffname != NULL) {
2053    assert(sfname != NULL);
2054    buf->b_ffname = ffname;
2055    buf->b_sfname = xstrdup(sfname);
2056    TO_SLASH(buf->b_sfname);
2057  }
2058
2059  clear_wininfo(buf);
2060  WinInfo *curwin_info = xcalloc(1, sizeof(WinInfo));
2061  kv_push(buf->b_wininfo, curwin_info);
2062
2063  if (buf == curbuf) {
2064    free_buffer_stuff(buf, kBffInitChangedtick);  // delete local vars et al.
2065
2066    // Init the options.
2067    buf->b_p_initialized = false;
2068    buf_copy_options(buf, BCO_ENTER);
2069
2070    // need to reload lmaps and set b:keymap_name
2071    curbuf->b_kmap_state |= KEYMAP_INIT;
2072  } else {
2073    // put new buffer at the end of the buffer list
2074    buf->b_next = NULL;
2075    if (firstbuf == NULL) {             // buffer list is empty
2076      buf->b_prev = NULL;
2077      firstbuf = buf;
2078    } else {                            // append new buffer at end of list
2079      lastbuf->b_next = buf;
2080      buf->b_prev = lastbuf;
2081    }
2082    lastbuf = buf;
2083
2084    buf->b_fnum = top_file_num++;
2085    pmap_put(int)(&buffer_handles, buf->b_fnum, buf);
2086    if (top_file_num < 0) {  // wrap around (may cause duplicates)
2087      emsg(_("W14: Warning: List of file names overflow"));
2088      if (emsg_silent == 0 && !in_assert_fails) {
2089        msg_delay(3001, true);  // make sure it is noticed
2090      }
2091      top_file_num = 1;
2092    }
2093
2094    // Always copy the options from the current buffer.
2095    buf_copy_options(buf, BCO_ALWAYS);
2096  }
2097
2098  curwin_info->wi_mark = (fmark_T)INIT_FMARK;
2099  curwin_info->wi_mark.mark.lnum = lnum;
2100  curwin_info->wi_win = curwin;
2101
2102  hash_init(&buf->b_s.b_keywtab);
2103  hash_init(&buf->b_s.b_keywtab_ic);
2104
2105  buf->b_fname = buf->b_sfname;
2106  if (!file_id_valid) {
2107    buf->file_id_valid = false;
2108  } else {
2109    buf->file_id_valid = true;
2110    buf->file_id = file_id;
2111  }
2112  buf->b_u_synced = true;
2113  buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
2114  if (flags & BLN_DUMMY) {
2115    buf->b_flags |= BF_DUMMY;
2116  }
2117  buf_clear_file(buf);
2118  clrallmarks(buf, 0);                  // clear marks
2119  fmarks_check_names(buf);              // check file marks for this file
2120  buf->b_p_bl = (flags & BLN_LISTED) ? true : false;    // init 'buflisted'
2121  kv_destroy(buf->update_channels);
2122  kv_init(buf->update_channels);
2123  kv_destroy(buf->update_callbacks);
2124  kv_init(buf->update_callbacks);
2125  if (!(flags & BLN_DUMMY)) {
2126    // Tricky: these autocommands may change the buffer list.  They could also
2127    // split the window with re-using the one empty buffer. This may result in
2128    // unexpectedly losing the empty buffer.
2129    bufref_T bufref;
2130    set_bufref(&bufref, buf);
2131    if (apply_autocmds(EVENT_BUFNEW, NULL, NULL, false, buf)
2132        && !bufref_valid(&bufref)) {
2133      return NULL;
2134    }
2135    if ((flags & BLN_LISTED)
2136        && apply_autocmds(EVENT_BUFADD, NULL, NULL, false, buf)
2137        && !bufref_valid(&bufref)) {
2138      return NULL;
2139    }
2140    if (aborting()) {
2141      // Autocmds may abort script processing.
2142      return NULL;
2143    }
2144  }
2145
2146  buf->b_prompt_callback.type = kCallbackNone;
2147  buf->b_prompt_interrupt.type = kCallbackNone;
2148  buf->b_prompt_text = NULL;
2149  buf->b_prompt_start = (fmark_T)INIT_FMARK;
2150  buf->b_prompt_start.mark.col = 2;  // default prompt is "% "
2151  buf->b_prompt_append_new_line = true;
2152
2153  return buf;
2154}
2155
2156/// Return true if the current buffer is empty, unnamed, unmodified and used in
2157/// only one window. That means it can be reused.
2158bool curbuf_reusable(void)
2159{
2160  return (curbuf != NULL
2161          && curbuf->b_ffname == NULL
2162          && curbuf->b_nwindows <= 1
2163          && !curbuf->terminal
2164          && (curbuf->b_ml.ml_mfp == NULL || buf_is_empty(curbuf))
2165          && !bt_quickfix(curbuf)
2166          && !curbufIsChanged());
2167}
2168
2169/// Free the memory for the options of a buffer.
2170/// If "free_p_ff" is true also free 'fileformat', 'buftype' and
2171/// 'fileencoding'.
2172void free_buf_options(buf_T *buf, bool free_p_ff)
2173{
2174  if (free_p_ff) {
2175    clear_string_option(&buf->b_p_fenc);
2176    clear_string_option(&buf->b_p_ff);
2177    clear_string_option(&buf->b_p_bh);
2178    clear_string_option(&buf->b_p_bt);
2179  }
2180  clear_string_option(&buf->b_p_def);
2181  clear_string_option(&buf->b_p_inc);
2182  callback_free(&buf->b_p_inex);
2183  callback_free(&buf->b_p_inde);
2184  clear_string_option(&buf->b_p_indk);
2185  clear_string_option(&buf->b_p_fp);
2186  callback_free(&buf->b_p_fex);
2187  clear_string_option(&buf->b_p_kp);
2188  clear_string_option(&buf->b_p_mps);
2189  clear_string_option(&buf->b_p_fo);
2190  clear_string_option(&buf->b_p_flp);
2191  clear_string_option(&buf->b_p_isk);
2192  clear_string_option(&buf->b_p_vsts);
2193  XFREE_CLEAR(buf->b_p_vsts_nopaste);
2194  XFREE_CLEAR(buf->b_p_vsts_array);
2195  clear_string_option(&buf->b_p_vts);
2196  XFREE_CLEAR(buf->b_p_vts_array);
2197  clear_string_option(&buf->b_p_keymap);
2198  keymap_ga_clear(&buf->b_kmap_ga);
2199  ga_clear(&buf->b_kmap_ga);
2200  clear_string_option(&buf->b_p_com);
2201  clear_string_option(&buf->b_p_cms);
2202  clear_string_option(&buf->b_p_nf);
2203  clear_string_option(&buf->b_p_syn);
2204  clear_string_option(&buf->b_s.b_syn_isk);
2205  clear_string_option(&buf->b_s.b_p_spc);
2206  clear_string_option(&buf->b_s.b_p_spf);
2207  vim_regfree(buf->b_s.b_cap_prog);
2208  buf->b_s.b_cap_prog = NULL;
2209  clear_string_option(&buf->b_s.b_p_spl);
2210  clear_string_option(&buf->b_s.b_p_spo);
2211  clear_string_option(&buf->b_p_sua);
2212  clear_string_option(&buf->b_p_ft);
2213  clear_string_option(&buf->b_p_cink);
2214  clear_string_option(&buf->b_p_cino);
2215  clear_string_option(&buf->b_p_lop);
2216  clear_string_option(&buf->b_p_cinsd);
2217  clear_string_option(&buf->b_p_cinw);
2218  clear_string_option(&buf->b_p_cot);
2219  clear_string_option(&buf->b_p_cpt);
2220#ifdef BACKSLASH_IN_FILENAME
2221  clear_string_option(&buf->b_p_csl);
2222#endif
2223  callback_free(&buf->b_p_cfu);
2224  callback_free(&buf->b_p_ofu);
2225  callback_free(&buf->b_p_tsrfu);
2226  clear_cpt_callbacks(&buf->b_p_cpt_cb, buf->b_p_cpt_count);
2227  buf->b_p_cpt_count = 0;
2228  clear_string_option(&buf->b_p_gefm);
2229  clear_string_option(&buf->b_p_gp);
2230  clear_string_option(&buf->b_p_mp);
2231  clear_string_option(&buf->b_p_efm);
2232  clear_string_option(&buf->b_p_ep);
2233  clear_string_option(&buf->b_p_path);
2234  clear_string_option(&buf->b_p_tags);
2235  clear_string_option(&buf->b_p_tc);
2236  callback_free(&buf->b_p_tfu);
2237  callback_free(&buf->b_p_ffu);
2238  clear_string_option(&buf->b_p_dict);
2239  clear_string_option(&buf->b_p_dia);
2240  clear_string_option(&buf->b_p_tsr);
2241  clear_string_option(&buf->b_p_qe);
2242  buf->b_p_ac = -1;
2243  buf->b_p_ar = -1;
2244  buf->b_p_fs = -1;
2245  buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
2246  clear_string_option(&buf->b_p_lw);
2247  clear_string_option(&buf->b_p_bkc);
2248  clear_string_option(&buf->b_p_menc);
2249}
2250
2251/// Get alternate file "n".
2252/// Set linenr to "lnum" or altfpos.lnum if "lnum" == 0.
2253/// Also set cursor column to altfpos.col if 'startofline' is not set.
2254/// if (options & GETF_SETMARK) call setpcmark()
2255/// if (options & GETF_ALT) we are jumping to an alternate file.
2256/// if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping
2257///
2258/// Return FAIL for failure, OK for success.
2259int buflist_getfile(int n, linenr_T lnum, int options, int forceit)
2260{
2261  win_T *wp = NULL;
2262  fmark_T *fm = NULL;
2263
2264  buf_T *buf = buflist_findnr(n);
2265  if (buf == NULL) {
2266    if ((options & GETF_ALT) && n == 0) {
2267      emsg(_(e_noalt));
2268    } else {
2269      semsg(_(e_buffer_nr_not_found), n);
2270    }
2271    return FAIL;
2272  }
2273
2274  // if alternate file is the current buffer, nothing to do
2275  if (buf == curbuf) {
2276    return OK;
2277  }
2278
2279  if (text_or_buf_locked()) {
2280    return FAIL;
2281  }
2282
2283  colnr_T col;
2284  bool restore_view = false;
2285  // altfpos may be changed by getfile(), get it now
2286  if (lnum == 0) {
2287    fm = buflist_findfmark(buf);
2288    lnum = fm->mark.lnum;
2289    col = fm->mark.col;
2290    restore_view = true;
2291  } else {
2292    col = 0;
2293  }
2294
2295  if (options & GETF_SWITCH) {
2296    // If 'switchbuf' is set jump to the window containing "buf".
2297    wp = swbuf_goto_win_with_buf(buf);
2298
2299    // If 'switchbuf' contains "split", "vsplit" or "newtab" and the
2300    // current buffer isn't empty: open new tab or window
2301    if (wp == NULL && (swb_flags & (kOptSwbFlagVsplit | kOptSwbFlagSplit | kOptSwbFlagNewtab))
2302        && !buf_is_empty(curbuf)) {
2303      if (swb_flags & kOptSwbFlagNewtab) {
2304        tabpage_new();
2305      } else if (win_split(0, (swb_flags & kOptSwbFlagVsplit) ? WSP_VERT : 0)
2306                 == FAIL) {
2307        return FAIL;
2308      }
2309      RESET_BINDING(curwin);
2310    }
2311  }
2312
2313  RedrawingDisabled++;
2314  if (GETFILE_SUCCESS(getfile(buf->b_fnum, NULL, NULL,
2315                              (options & GETF_SETMARK), lnum, forceit))) {
2316    RedrawingDisabled--;
2317
2318    // cursor is at to BOL and w_cursor.lnum is checked due to getfile()
2319    if (!p_sol && col != 0) {
2320      curwin->w_cursor.col = col;
2321      check_cursor_col(curwin);
2322      curwin->w_cursor.coladd = 0;
2323      curwin->w_set_curswant = true;
2324    }
2325    if (jop_flags & kOptJopFlagView && restore_view) {
2326      mark_view_restore(fm);
2327    }
2328    return OK;
2329  }
2330  RedrawingDisabled--;
2331  return FAIL;
2332}
2333
2334/// Go to the last known line number for the current buffer.
2335static void buflist_getfpos(void)
2336{
2337  fmark_T *fm = buflist_findfmark(curbuf);
2338  const pos_T *fpos = &fm->mark;
2339
2340  curwin->w_cursor.lnum = fpos->lnum;
2341  check_cursor_lnum(curwin);
2342
2343  if (p_sol) {
2344    curwin->w_cursor.col = 0;
2345  } else {
2346    curwin->w_cursor.col = fpos->col;
2347    check_cursor_col(curwin);
2348    curwin->w_cursor.coladd = 0;
2349    curwin->w_set_curswant = true;
2350  }
2351
2352  if (jop_flags & kOptJopFlagView) {
2353    mark_view_restore(fm);
2354  }
2355}
2356
2357/// Find file in buffer list by name (it has to be for the current window).
2358///
2359/// @return  buffer or NULL if not found
2360buf_T *buflist_findname_exp(char *fname)
2361{
2362  buf_T *buf = NULL;
2363
2364  // First make the name into a full path name
2365  char *ffname = FullName_save(fname,
2366#ifdef UNIX
2367                               // force expansion, get rid of symbolic links
2368                               true
2369#else
2370                               false
2371#endif
2372                               );
2373  if (ffname != NULL) {
2374    buf = buflist_findname(ffname);
2375    xfree(ffname);
2376  }
2377  return buf;
2378}
2379
2380/// Find file in buffer list by name (it has to be for the current window).
2381/// "ffname" must have a full path.
2382/// Skips dummy buffers.
2383///
2384/// @return  buffer or NULL if not found
2385buf_T *buflist_findname(char *ffname)
2386{
2387  FileID file_id;
2388  bool file_id_valid = os_fileid(ffname, &file_id);
2389  return buflist_findname_file_id(ffname, &file_id, file_id_valid);
2390}
2391
2392/// Same as buflist_findname(), but pass the FileID structure to avoid
2393/// getting it twice for the same file.
2394///
2395/// @return  buffer or NULL if not found
2396static buf_T *buflist_findname_file_id(char *ffname, FileID *file_id, bool file_id_valid)
2397  FUNC_ATTR_PURE
2398{
2399  // Start at the last buffer, expect to find a match sooner.
2400  FOR_ALL_BUFFERS_BACKWARDS(buf) {
2401    if ((buf->b_flags & BF_DUMMY) == 0
2402        && !otherfile_buf(buf, ffname, file_id, file_id_valid)) {
2403      return buf;
2404    }
2405  }
2406  return NULL;
2407}
2408
2409/// Find file in buffer list by a regexp pattern.
2410///
2411/// @param pattern_end  pointer to first char after pattern
2412/// @param unlisted  find unlisted buffers
2413/// @param diffmode  find diff-mode buffers only
2414/// @param curtab_only  find buffers in current tab only
2415///
2416/// @return  fnum of the found buffer or < 0 for error.
2417int buflist_findpat(const char *pattern, const char *pattern_end, bool unlisted, bool diffmode,
2418                    bool curtab_only)
2419  FUNC_ATTR_NONNULL_ARG(1)
2420{
2421  int match = -1;
2422
2423  if (pattern_end == pattern + 1 && (*pattern == '%' || *pattern == '#')) {
2424    match = *pattern == '%' ? curbuf->b_fnum : curwin->w_alt_fnum;
2425    buf_T *found_buf = buflist_findnr(match);
2426    if (diffmode && !(found_buf && diff_mode_buf(found_buf))) {
2427      match = -1;
2428    }
2429  } else {
2430    // Try four ways of matching a listed buffer:
2431    // attempt == 0: without '^' or '$' (at any position)
2432    // attempt == 1: with '^' at start (only at position 0)
2433    // attempt == 2: with '$' at end (only match at end)
2434    // attempt == 3: with '^' at start and '$' at end (only full match)
2435    // Repeat this for finding an unlisted buffer if there was no matching
2436    // listed buffer.
2437
2438    char *pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, false);
2439    if (pat == NULL) {
2440      return -1;
2441    }
2442    char *patend = pat + strlen(pat) - 1;
2443    bool toggledollar = (patend > pat && *patend == '$');
2444
2445    // First try finding a listed buffer.  If not found and "unlisted"
2446    // is true, try finding an unlisted buffer.
2447
2448    int find_listed = true;
2449    while (true) {
2450      for (int attempt = 0; attempt <= 3; attempt++) {
2451        // may add '^' and '$'
2452        if (toggledollar) {
2453          *patend = (attempt < 2) ? NUL : '$';           // add/remove '$'
2454        }
2455        char *p = pat;
2456        if (*p == '^' && !(attempt & 1)) {               // add/remove '^'
2457          p++;
2458        }
2459
2460        regmatch_T regmatch;
2461        regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
2462
2463        FOR_ALL_BUFFERS_BACKWARDS(buf) {
2464          if (regmatch.regprog == NULL) {
2465            // invalid pattern, possibly after switching engine
2466            xfree(pat);
2467            return -1;
2468          }
2469          if (buf->b_p_bl == find_listed
2470              && (!diffmode || diff_mode_buf(buf))
2471              && buflist_match(&regmatch, buf, false) != NULL) {
2472            if (curtab_only) {
2473              // Ignore the match if the buffer is not open in
2474              // the current tab.
2475              bool found_window = false;
2476              FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2477                if (wp->w_buffer == buf) {
2478                  found_window = true;
2479                  break;
2480                }
2481              }
2482              if (!found_window) {
2483                continue;
2484              }
2485            }
2486            if (match >= 0) {                   // already found a match
2487              match = -2;
2488              break;
2489            }
2490            match = buf->b_fnum;                // remember first match
2491          }
2492        }
2493
2494        vim_regfree(regmatch.regprog);
2495        if (match >= 0) {                       // found one match
2496          break;
2497        }
2498      }
2499
2500      // Only search for unlisted buffers if there was no match with
2501      // a listed buffer.
2502      if (!unlisted || !find_listed || match != -1) {
2503        break;
2504      }
2505      find_listed = false;
2506    }
2507
2508    xfree(pat);
2509  }
2510
2511  if (match == -2) {
2512    semsg(_("E93: More than one match for %s"), pattern);
2513  } else if (match < 0) {
2514    semsg(_("E94: No matching buffer for %s"), pattern);
2515  }
2516  return match;
2517}
2518
2519typedef struct {
2520  buf_T *buf;
2521  char *match;
2522} bufmatch_T;
2523
2524/// Compare functions for qsort() below, that compares b_last_used.
2525static int buf_time_compare(const void *s1, const void *s2)
2526{
2527  buf_T *buf1 = *(buf_T **)s1;
2528  buf_T *buf2 = *(buf_T **)s2;
2529
2530  if (buf1->b_last_used == buf2->b_last_used) {
2531    return 0;
2532  }
2533  return buf1->b_last_used > buf2->b_last_used ? -1 : 1;
2534}
2535
2536/// Find all buffer names that match.
2537/// For command line expansion of ":buf" and ":sbuf".
2538///
2539/// @return  OK if matches found, FAIL otherwise.
2540int ExpandBufnames(char *pat, int *num_file, char ***file, int options)
2541{
2542  bufmatch_T *matches = NULL;
2543  bool to_free = false;
2544
2545  *num_file = 0;                    // return values in case of FAIL
2546  *file = NULL;
2547
2548  if ((options & BUF_DIFF_FILTER) && !curwin->w_p_diff) {
2549    return FAIL;
2550  }
2551
2552  const bool fuzzy = cmdline_fuzzy_complete(pat);
2553
2554  char *patc = NULL;
2555  fuzmatch_str_T *fuzmatch = NULL;
2556  regmatch_T regmatch;
2557
2558  // Make a copy of "pat" and change "^" to "\(^\|[\/]\)" (if doing regular
2559  // expression matching)
2560  if (!fuzzy) {
2561    if (*pat == '^' && pat[1] != NUL) {
2562      patc = xstrdup(pat + 1);
2563      to_free = true;
2564    } else if (*pat == '^') {
2565      patc = "";
2566    } else {
2567      patc = pat;
2568    }
2569    regmatch.regprog = vim_regcomp(patc, RE_MAGIC);
2570  }
2571
2572  int count = 0;
2573  int score = 0;
2574  // round == 1: Count the matches.
2575  // round == 2: Build the array to keep the matches.
2576  for (int round = 1; round <= 2; round++) {
2577    count = 0;
2578    FOR_ALL_BUFFERS(buf) {
2579      if (!buf->b_p_bl) {             // skip unlisted buffers
2580        continue;
2581      }
2582      if (options & BUF_DIFF_FILTER) {
2583        // Skip buffers not suitable for
2584        // :diffget or :diffput completion.
2585        if (buf == curbuf || !diff_mode_buf(buf)) {
2586          continue;
2587        }
2588      }
2589
2590      char *p = NULL;
2591      if (!fuzzy) {
2592        if (regmatch.regprog == NULL) {
2593          // invalid pattern, possibly after recompiling
2594          if (to_free) {
2595            xfree(patc);
2596          }
2597          return FAIL;
2598        }
2599        p = buflist_match(&regmatch, buf, p_wic);
2600      } else {
2601        p = NULL;
2602        // first try matching with the short file name
2603        if ((score = fuzzy_match_str(buf->b_sfname, pat)) != FUZZY_SCORE_NONE) {
2604          p = buf->b_sfname;
2605        }
2606        if (p == NULL) {
2607          // next try matching with the full path file name
2608          if ((score = fuzzy_match_str(buf->b_ffname, pat)) != FUZZY_SCORE_NONE) {
2609            p = buf->b_ffname;
2610          }
2611        }
2612      }
2613
2614      if (p == NULL) {
2615        continue;
2616      }
2617
2618      if (round == 1) {
2619        count++;
2620        continue;
2621      }
2622
2623      if (options & WILD_HOME_REPLACE) {
2624        p = home_replace_save(buf, p);
2625      } else {
2626        p = xstrdup(p);
2627      }
2628
2629      if (!fuzzy) {
2630        if (matches != NULL) {
2631          matches[count].buf = buf;
2632          matches[count].match = p;
2633          count++;
2634        } else {
2635          (*file)[count++] = p;
2636        }
2637      } else {
2638        fuzmatch[count].idx = count;
2639        fuzmatch[count].str = p;
2640        fuzmatch[count].score = score;
2641        count++;
2642      }
2643    }
2644    if (count == 0) {         // no match found, break here
2645      break;
2646    }
2647    if (round == 1) {
2648      if (!fuzzy) {
2649        *file = xmalloc((size_t)count * sizeof(**file));
2650        if (options & WILD_BUFLASTUSED) {
2651          matches = xmalloc((size_t)count * sizeof(*matches));
2652        }
2653      } else {
2654        fuzmatch = xmalloc((size_t)count * sizeof(fuzmatch_str_T));
2655      }
2656    }
2657  }
2658
2659  if (!fuzzy) {
2660    vim_regfree(regmatch.regprog);
2661    if (to_free) {
2662      xfree(patc);
2663    }
2664  }
2665
2666  if (!fuzzy) {
2667    if (matches != NULL) {
2668      if (count > 1) {
2669        qsort(matches, (size_t)count, sizeof(bufmatch_T), buf_time_compare);
2670      }
2671
2672      // if the current buffer is first in the list, place it at the end
2673      if (matches[0].buf == curbuf) {
2674        for (int i = 1; i < count; i++) {
2675          (*file)[i - 1] = matches[i].match;
2676        }
2677        (*file)[count - 1] = matches[0].match;
2678      } else {
2679        for (int i = 0; i < count; i++) {
2680          (*file)[i] = matches[i].match;
2681        }
2682      }
2683      xfree(matches);
2684    }
2685  } else {
2686    fuzzymatches_to_strmatches(fuzmatch, file, count, false);
2687  }
2688
2689  *num_file = count;
2690  return count == 0 ? FAIL : OK;
2691}
2692
2693/// Check for a match on the file name for buffer "buf" with regprog "prog".
2694/// Note that rmp->regprog may become NULL when switching regexp engine.
2695///
2696/// @param ignore_case  When true, ignore case. Use 'fic' otherwise.
2697static char *buflist_match(regmatch_T *rmp, buf_T *buf, bool ignore_case)
2698{
2699  // First try the short file name, then the long file name.
2700  char *match = fname_match(rmp, buf->b_sfname, ignore_case);
2701  if (match == NULL && rmp->regprog != NULL) {
2702    match = fname_match(rmp, buf->b_ffname, ignore_case);
2703  }
2704  return match;
2705}
2706
2707/// Try matching the regexp in "rmp->regprog" with file name "name".
2708/// Note that rmp->regprog may become NULL when switching regexp engine.
2709///
2710/// @param ignore_case  When true, ignore case. Use 'fileignorecase' otherwise.
2711///
2712/// @return  "name" when there is a match, NULL when not.
2713static char *fname_match(regmatch_T *rmp, char *name, bool ignore_case)
2714{
2715  char *match = NULL;
2716
2717  // extra check for valid arguments
2718  if (name == NULL || rmp->regprog == NULL) {
2719    return NULL;
2720  }
2721
2722  // Ignore case when 'fileignorecase' or the argument is set.
2723  rmp->rm_ic = p_fic || ignore_case;
2724  if (vim_regexec(rmp, name, 0)) {
2725    match = name;
2726  } else if (rmp->regprog != NULL) {
2727    // Replace $(HOME) with '~' and try matching again.
2728    char *p = home_replace_save(NULL, name);
2729    if (vim_regexec(rmp, p, 0)) {
2730      match = name;
2731    }
2732    xfree(p);
2733  }
2734
2735  return match;
2736}
2737
2738/// Find a file in the buffer list by buffer number.
2739buf_T *buflist_findnr(int nr)
2740{
2741  if (nr == 0) {
2742    nr = curwin->w_alt_fnum;
2743  }
2744
2745  return handle_get_buffer((handle_T)nr);
2746}
2747
2748/// Get name of file 'n' in the buffer list.
2749/// When the file has no name an empty string is returned.
2750/// home_replace() is used to shorten the file name (used for marks).
2751///
2752/// @param helptail  for help buffers return tail only
2753///
2754/// @return  a pointer to allocated memory, of NULL when failed.
2755char *buflist_nr2name(int n, int fullname, int helptail)
2756{
2757  buf_T *buf = buflist_findnr(n);
2758  if (buf == NULL) {
2759    return NULL;
2760  }
2761  return home_replace_save(helptail ? buf : NULL,
2762                           fullname ? buf->b_ffname : buf->b_fname);
2763}
2764
2765/// Set the line and column numbers for the given buffer and window
2766///
2767/// @param[in,out]  buf           Buffer for which line and column are set.
2768/// @param[in,out]  win           Window for which line and column are set.
2769///                               May be NULL when using :badd.
2770/// @param[in]      lnum          Line number to be set. If it is zero then only
2771///                               options are touched.
2772/// @param[in]      col           Column number to be set.
2773/// @param[in]      copy_options  If true save the local window option values.
2774void buflist_setfpos(buf_T *const buf, win_T *const win, linenr_T lnum, colnr_T col,
2775                     bool copy_options)
2776  FUNC_ATTR_NONNULL_ARG(1)
2777{
2778  WinInfo *wip;
2779
2780  size_t i;
2781  for (i = 0; i < kv_size(buf->b_wininfo); i++) {
2782    wip = kv_A(buf->b_wininfo, i);
2783    if (wip->wi_win == win) {
2784      break;
2785    }
2786  }
2787
2788  if (i == kv_size(buf->b_wininfo)) {
2789    // allocate a new entry
2790    wip = xcalloc(1, sizeof(WinInfo));
2791    wip->wi_win = win;
2792    if (lnum == 0) {            // set lnum even when it's 0
2793      lnum = 1;
2794    }
2795  } else {
2796    // remove the entry from the list
2797    kv_shift(buf->b_wininfo, i, 1);
2798    if (copy_options && wip->wi_optset) {
2799      clear_winopt(&wip->wi_opt);
2800      deleteFoldRecurse(buf, &wip->wi_folds);
2801    }
2802  }
2803  if (lnum != 0) {
2804    wip->wi_mark.mark.lnum = lnum;
2805    wip->wi_mark.mark.col = col;
2806    if (win != NULL) {
2807      wip->wi_mark.view = mark_view_make(win, wip->wi_mark.mark);
2808    }
2809  }
2810  if (win != NULL) {
2811    wip->wi_changelistidx = win->w_changelistidx;
2812  }
2813  if (copy_options && win != NULL) {
2814    // Save the window-specific option values.
2815    copy_winopt(&win->w_onebuf_opt, &wip->wi_opt);
2816    wip->wi_fold_manual = win->w_fold_manual;
2817    cloneFoldGrowArray(&win->w_folds, &wip->wi_folds);
2818    wip->wi_optset = true;
2819  }
2820
2821  // insert the entry in front of the list
2822  kv_pushp(buf->b_wininfo);
2823  memmove(&kv_A(buf->b_wininfo, 1), &kv_A(buf->b_wininfo, 0),
2824          (kv_size(buf->b_wininfo) - 1) * sizeof(kv_A(buf->b_wininfo, 0)));
2825  kv_A(buf->b_wininfo, 0) = wip;
2826}
2827
2828/// Check that "wip" has 'diff' set and the diff is only for another tab page.
2829/// That's because a diff is local to a tab page.
2830static bool wininfo_other_tab_diff(WinInfo *wip)
2831  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2832{
2833  if (!wip->wi_opt.wo_diff) {
2834    return false;
2835  }
2836
2837  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2838    // return false when it's a window in the current tab page, thus
2839    // the buffer was in diff mode here
2840    if (wip->wi_win == wp) {
2841      return false;
2842    }
2843  }
2844  return true;
2845}
2846
2847/// Find info for the current window in buffer "buf".
2848/// If not found, return the info for the most recently used window.
2849///
2850/// @param need_options      when true, skip entries where wi_optset is false.
2851/// @param skip_diff_buffer  when true, avoid windows with 'diff' set that is in another tab page.
2852///
2853/// @return  NULL when there isn't any info.
2854static WinInfo *find_wininfo(buf_T *buf, bool need_options, bool skip_diff_buffer)
2855  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE
2856{
2857  for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
2858    WinInfo *wip = kv_A(buf->b_wininfo, i);
2859    if (wip->wi_win == curwin
2860        && (!skip_diff_buffer || !wininfo_other_tab_diff(wip))
2861        && (!need_options || wip->wi_optset)) {
2862      return wip;
2863    }
2864  }
2865
2866  // If no wininfo for curwin, use the first in the list (that doesn't have
2867  // 'diff' set and is in another tab page).
2868  // If "need_options" is true skip entries that don't have options set,
2869  // unless the window is editing "buf", so we can copy from the window
2870  // itself.
2871  if (skip_diff_buffer) {
2872    for (size_t i = 0; i < kv_size(buf->b_wininfo); i++) {
2873      WinInfo *wip = kv_A(buf->b_wininfo, i);
2874      if (!wininfo_other_tab_diff(wip)
2875          && (!need_options
2876              || wip->wi_optset
2877              || (wip->wi_win != NULL
2878                  && wip->wi_win->w_buffer == buf))) {
2879        return wip;
2880      }
2881    }
2882  } else if (kv_size(buf->b_wininfo)) {
2883    return kv_A(buf->b_wininfo, 0);
2884  }
2885  return NULL;
2886}
2887
2888/// Reset the local window options to the values last used in this window.
2889/// If the buffer wasn't used in this window before, use the values from
2890/// the most recently used window.  If the values were never set, use the
2891/// global values for the window.
2892void get_winopts(buf_T *buf)
2893{
2894  clear_winopt(&curwin->w_onebuf_opt);
2895  clearFolding(curwin);
2896
2897  WinInfo *const wip = find_wininfo(buf, true, true);
2898  if (wip != NULL && wip->wi_win != curwin && wip->wi_win != NULL
2899      && wip->wi_win->w_buffer == buf
2900      && wip->wi_win->w_config.style != kWinStyleMinimal) {
2901    win_T *wp = wip->wi_win;
2902    copy_winopt(&wp->w_onebuf_opt, &curwin->w_onebuf_opt);
2903    curwin->w_fold_manual = wp->w_fold_manual;
2904    curwin->w_foldinvalid = true;
2905    cloneFoldGrowArray(&wp->w_folds, &curwin->w_folds);
2906  } else if (wip != NULL && wip->wi_optset
2907             && (wip->wi_win == NULL || wip->wi_win == curwin
2908                 || wip->wi_win->w_config.style != kWinStyleMinimal)) {
2909    copy_winopt(&wip->wi_opt, &curwin->w_onebuf_opt);
2910    curwin->w_fold_manual = wip->wi_fold_manual;
2911    curwin->w_foldinvalid = true;
2912    cloneFoldGrowArray(&wip->wi_folds, &curwin->w_folds);
2913  } else {
2914    copy_winopt(&curwin->w_allbuf_opt, &curwin->w_onebuf_opt);
2915  }
2916  if (wip != NULL) {
2917    curwin->w_changelistidx = wip->wi_changelistidx;
2918  }
2919
2920  if (curwin->w_config.style == kWinStyleMinimal) {
2921    didset_window_options(curwin, false);
2922    win_set_minimal_style(curwin);
2923  }
2924
2925  // Set 'foldlevel' to 'foldlevelstart' if it's not negative.
2926  if (p_fdls >= 0) {
2927    curwin->w_p_fdl = p_fdls;
2928  }
2929  didset_window_options(curwin, false);
2930}
2931
2932/// Find the mark for the buffer 'buf' for the current window.
2933///
2934/// @return  a pointer to no_position if no position is found.
2935fmark_T *buflist_findfmark(buf_T *buf)
2936  FUNC_ATTR_PURE
2937{
2938  static fmark_T no_position = { { 1, 0, 0 }, 0, 0, INIT_FMARKV, NULL };
2939
2940  WinInfo *const wip = find_wininfo(buf, false, false);
2941  return (wip == NULL) ? &no_position : &(wip->wi_mark);
2942}
2943
2944/// Find the lnum for the buffer 'buf' for the current window.
2945linenr_T buflist_findlnum(buf_T *buf)
2946  FUNC_ATTR_PURE
2947{
2948  return buflist_findfmark(buf)->mark.lnum;
2949}
2950
2951/// List all known file names (for :files and :buffers command).
2952void buflist_list(exarg_T *eap)
2953{
2954  buf_T *buf = firstbuf;
2955
2956  garray_T buflist;
2957  buf_T **buflist_data = NULL;
2958
2959  msg_ext_set_kind("list_cmd");
2960  if (vim_strchr(eap->arg, 't')) {
2961    ga_init(&buflist, sizeof(buf_T *), 50);
2962    for (buf = firstbuf; buf != NULL; buf = buf->b_next) {
2963      ga_grow(&buflist, 1);
2964      ((buf_T **)buflist.ga_data)[buflist.ga_len++] = buf;
2965    }
2966
2967    qsort(buflist.ga_data, (size_t)buflist.ga_len,
2968          sizeof(buf_T *), buf_time_compare);
2969
2970    buflist_data = (buf_T **)buflist.ga_data;
2971    buf = *buflist_data;
2972  }
2973  buf_T **p = buflist_data;
2974
2975  for (;
2976       buf != NULL && !got_int;
2977       buf = buflist_data != NULL
2978             ? (++p < buflist_data + buflist.ga_len ? *p : NULL) : buf->b_next) {
2979    const bool is_terminal = buf->terminal;
2980    const bool job_running = buf->terminal && terminal_running(buf->terminal);
2981
2982    // skip unspecified buffers
2983    if ((!buf->b_p_bl && !eap->forceit && !vim_strchr(eap->arg, 'u'))
2984        || (vim_strchr(eap->arg, 'u') && buf->b_p_bl)
2985        || (vim_strchr(eap->arg, '+')
2986            && ((buf->b_flags & BF_READERR) || !bufIsChanged(buf)))
2987        || (vim_strchr(eap->arg, 'a')
2988            && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows == 0))
2989        || (vim_strchr(eap->arg, 'h')
2990            && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows != 0))
2991        || (vim_strchr(eap->arg, 'R') && (!is_terminal || !job_running))
2992        || (vim_strchr(eap->arg, 'F') && (!is_terminal || job_running))
2993        || (vim_strchr(eap->arg, '-') && buf->b_p_ma)
2994        || (vim_strchr(eap->arg, '=') && !buf->b_p_ro)
2995        || (vim_strchr(eap->arg, 'x') && !(buf->b_flags & BF_READERR))
2996        || (vim_strchr(eap->arg, '%') && buf != curbuf)
2997        || (vim_strchr(eap->arg, '#')
2998            && (buf == curbuf || curwin->w_alt_fnum != buf->b_fnum))) {
2999      continue;
3000    }
3001    char *name = buf_spname(buf);
3002    if (name != NULL) {
3003      xstrlcpy(NameBuff, name, MAXPATHL);
3004    } else {
3005      home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, true);
3006    }
3007
3008    if (message_filtered(NameBuff)) {
3009      continue;
3010    }
3011
3012    const int changed_char = (buf->b_flags & BF_READERR)
3013                             ? 'x'
3014                             : (bufIsChanged(buf) ? '+' : ' ');
3015    int ro_char = !MODIFIABLE(buf) ? '-' : (buf->b_p_ro ? '=' : ' ');
3016    if (buf->terminal) {
3017      ro_char = terminal_running(buf->terminal) ? 'R' : 'F';
3018    }
3019
3020    if (!ui_has(kUIMessages) || msg_col > 0) {
3021      msg_putchar('\n');
3022    }
3023    int len = (int)vim_snprintf_safelen(IObuff, IOSIZE - 20, "%3d%c%c%c%c%c \"%s\"",
3024                                        buf->b_fnum,
3025                                        buf->b_p_bl ? ' ' : 'u',
3026                                        buf == curbuf ? '%'
3027                                                      : (curwin->w_alt_fnum
3028                                                         == buf->b_fnum ? '#' : ' '),
3029                                        buf->b_ml.ml_mfp == NULL ? ' '
3030                                                                 : (buf->b_nwindows
3031                                                                    == 0 ? 'h' : 'a'),
3032                                        ro_char,
3033                                        changed_char,
3034                                        NameBuff);
3035
3036    len = MIN(len, IOSIZE - 20);
3037
3038    // put "line 999" in column 40 or after the file name
3039    int i = 40 - vim_strsize(IObuff);
3040    do {
3041      IObuff[len++] = ' ';
3042    } while (--i > 0 && len < IOSIZE - 18);
3043    if (vim_strchr(eap->arg, 't') && buf->b_last_used) {
3044      undo_fmt_time(IObuff + len, (size_t)(IOSIZE - len), buf->b_last_used);
3045    } else {
3046      vim_snprintf(IObuff + len, (size_t)(IOSIZE - len), _("line %" PRId64),
3047                   buf == curbuf ? (int64_t)curwin->w_cursor.lnum : (int64_t)buflist_findlnum(buf));
3048    }
3049
3050    msg_outtrans(IObuff, 0, false);
3051    line_breakcheck();
3052  }
3053
3054  if (buflist_data) {
3055    ga_clear(&buflist);
3056  }
3057}
3058
3059/// Get file name and line number for file 'fnum'.
3060/// Used by DoOneCmd() for translating '%' and '#'.
3061/// Used by insert_reg() and cmdline_paste() for '#' register.
3062///
3063/// @return  FAIL if not found, OK for success.
3064int buflist_name_nr(int fnum, char **fname, linenr_T *lnum)
3065{
3066  buf_T *buf = buflist_findnr(fnum);
3067  if (buf == NULL || buf->b_fname == NULL) {
3068    return FAIL;
3069  }
3070
3071  *fname = buf->b_fname;
3072  *lnum = buflist_findlnum(buf);
3073
3074  return OK;
3075}
3076
3077/// Set the file name for "buf" to "ffname_arg", short file name to
3078/// "sfname_arg".
3079/// The file name with the full path is also remembered, for when :cd is used.
3080///
3081/// @param message  give message when buffer already exists
3082///
3083/// @return  FAIL for failure (file name already in use by other buffer) OK otherwise.
3084int setfname(buf_T *buf, char *ffname_arg, char *sfname_arg, bool message)
3085{
3086  char *ffname = ffname_arg;
3087  char *sfname = sfname_arg;
3088  buf_T *obuf = NULL;
3089  FileID file_id;
3090  bool file_id_valid = false;
3091
3092  if (ffname == NULL || *ffname == NUL) {
3093    // Removing the name.
3094    if (buf->b_sfname != buf->b_ffname) {
3095      XFREE_CLEAR(buf->b_sfname);
3096    } else {
3097      buf->b_sfname = NULL;
3098    }
3099    XFREE_CLEAR(buf->b_ffname);
3100  } else {
3101    fname_expand(buf, &ffname, &sfname);    // will allocate ffname
3102    if (ffname == NULL) {                   // out of memory
3103      return FAIL;
3104    }
3105
3106    // If the file name is already used in another buffer:
3107    // - if the buffer is loaded, fail
3108    // - if the buffer is not loaded, delete it from the list
3109    file_id_valid = os_fileid(ffname, &file_id);
3110    if (!(buf->b_flags & BF_DUMMY)) {
3111      obuf = buflist_findname_file_id(ffname, &file_id, file_id_valid);
3112    }
3113    if (obuf != NULL && obuf != buf) {
3114      bool in_use = false;
3115
3116      // during startup a window may use a buffer that is not loaded yet
3117      FOR_ALL_TAB_WINDOWS(tab, win) {
3118        if (win->w_buffer == obuf) {
3119          in_use = true;
3120        }
3121      }
3122
3123      // it's loaded or used in a window, fail
3124      if (obuf->b_ml.ml_mfp != NULL || in_use) {
3125        if (message) {
3126          emsg(_("E95: Buffer with this name already exists"));
3127        }
3128        xfree(ffname);
3129        return FAIL;
3130      }
3131      // delete from the list
3132      close_buffer(NULL, obuf, DOBUF_WIPE, false, false, false);
3133    }
3134    sfname = xstrdup(sfname);
3135#ifdef CASE_INSENSITIVE_FILENAME
3136    TO_SLASH(sfname);
3137    path_fix_case(sfname);            // set correct case for short file name
3138#endif
3139    if (buf->b_sfname != buf->b_ffname) {
3140      xfree(buf->b_sfname);
3141    }
3142    xfree(buf->b_ffname);
3143    buf->b_ffname = ffname;
3144    buf->b_sfname = sfname;
3145  }
3146  buf->b_fname = buf->b_sfname;
3147  if (!file_id_valid) {
3148    buf->file_id_valid = false;
3149  } else {
3150    buf->file_id_valid = true;
3151    buf->file_id = file_id;
3152  }
3153
3154  buf_name_changed(buf);
3155  return OK;
3156}
3157
3158/// Crude way of changing the name of a buffer.  Use with care!
3159/// The name should be relative to the current directory.
3160void buf_set_name(int fnum, char *name)
3161{
3162  buf_T *buf = buflist_findnr(fnum);
3163  if (buf == NULL) {
3164    return;
3165  }
3166
3167  if (buf->b_sfname != buf->b_ffname) {
3168    xfree(buf->b_sfname);
3169  }
3170  xfree(buf->b_ffname);
3171  buf->b_ffname = xstrdup(name);
3172  buf->b_sfname = NULL;
3173  // Allocate ffname and expand into full path.  Also resolves .lnk
3174  // files on Win32.
3175  fname_expand(buf, &buf->b_ffname, &buf->b_sfname);
3176  buf->b_fname = buf->b_sfname;
3177}
3178
3179/// Take care of what needs to be done when the name of buffer "buf" has changed.
3180void buf_name_changed(buf_T *buf)
3181{
3182  // If the file name changed, also change the name of the swapfile
3183  if (buf->b_ml.ml_mfp != NULL) {
3184    ml_setname(buf);
3185  }
3186
3187  if (curwin->w_buffer == buf) {
3188    check_arg_idx(curwin);      // check file name for arg list
3189  }
3190  maketitle();                  // set window title
3191  status_redraw_all();          // status lines need to be redrawn
3192  fmarks_check_names(buf);      // check named file marks
3193  ml_timestamp(buf);            // reset timestamp
3194}
3195
3196/// Set alternate file name for current window
3197///
3198/// Used by do_one_cmd(), do_write() and do_ecmd().
3199///
3200/// @return  the buffer.
3201buf_T *setaltfname(char *ffname, char *sfname, linenr_T lnum)
3202{
3203  // Create a buffer.  'buflisted' is not set if it's a new buffer
3204  buf_T *buf = buflist_new(ffname, sfname, lnum, 0);
3205  if (buf != NULL && (cmdmod.cmod_flags & CMOD_KEEPALT) == 0) {
3206    curwin->w_alt_fnum = buf->b_fnum;
3207  }
3208  return buf;
3209}
3210
3211/// Get alternate file name for current window.
3212/// Return NULL if there isn't any, and give error message if requested.
3213///
3214/// @param errmsg  give error message
3215char *getaltfname(bool errmsg)
3216{
3217  char *fname;
3218  linenr_T dummy;
3219
3220  if (buflist_name_nr(0, &fname, &dummy) == FAIL) {
3221    if (errmsg) {
3222      emsg(_(e_noalt));
3223    }
3224    return NULL;
3225  }
3226  return fname;
3227}
3228
3229/// Add a file name to the buflist and return its number.
3230/// Uses same flags as buflist_new(), except BLN_DUMMY.
3231///
3232/// Used by qf_init(), main() and doarglist()
3233int buflist_add(char *fname, int flags)
3234{
3235  buf_T *buf = buflist_new(fname, NULL, 0, flags);
3236  if (buf != NULL) {
3237    return buf->b_fnum;
3238  }
3239  return 0;
3240}
3241
3242/// Set alternate cursor position for the current buffer and window "win".
3243/// Also save the local window option values.
3244void buflist_altfpos(win_T *win)
3245{
3246  buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, true);
3247}
3248
3249/// Check that "ffname" is not the same file as current file.
3250/// Fname must have a full path (expanded by path_to_absolute()).
3251///
3252/// @param  ffname  full path name to check
3253bool otherfile(char *ffname)
3254  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3255{
3256  return otherfile_buf(curbuf, ffname, NULL, false);
3257}
3258
3259/// Check that "ffname" is not the same file as the file loaded in "buf".
3260/// Fname must have a full path (expanded by path_to_absolute()).
3261///
3262/// @param  buf            buffer to check
3263/// @param  ffname         full path name to check
3264/// @param  file_id_p      information about the file at "ffname".
3265/// @param  file_id_valid  whether a valid "file_id_p" was passed in.
3266static bool otherfile_buf(buf_T *buf, char *ffname, FileID *file_id_p, bool file_id_valid)
3267  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
3268{
3269  // no name is different
3270  if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL) {
3271    return true;
3272  }
3273  if (path_equal(ffname, buf->b_ffname, kPathCmpLiteral)) {
3274    return false;
3275  }
3276  {
3277    FileID file_id;
3278    // If no struct stat given, get it now
3279    if (file_id_p == NULL) {
3280      file_id_p = &file_id;
3281      file_id_valid = os_fileid(ffname, file_id_p);
3282    }
3283    if (!file_id_valid) {
3284      // file_id not valid, assume files are different.
3285      return true;
3286    }
3287    // Use dev/ino to check if the files are the same, even when the names
3288    // are different (possible with links).  Still need to compare the
3289    // name above, for when the file doesn't exist yet.
3290    // Problem: The dev/ino changes when a file is deleted (and created
3291    // again) and remains the same when renamed/moved.  We don't want to
3292    // stat() each buffer each time, that would be too slow.  Get the
3293    // dev/ino again when they appear to match, but not when they appear
3294    // to be different: Could skip a buffer when it's actually the same
3295    // file.
3296    if (buf_same_file_id(buf, file_id_p)) {
3297      buf_set_file_id(buf);
3298      if (buf_same_file_id(buf, file_id_p)) {
3299        return false;
3300      }
3301    }
3302  }
3303  return true;
3304}
3305
3306/// Set file_id for a buffer.
3307/// Must always be called when b_fname is changed!
3308void buf_set_file_id(buf_T *buf)
3309{
3310  FileID file_id;
3311  if (buf->b_fname != NULL
3312      && os_fileid(buf->b_fname, &file_id)) {
3313    buf->file_id_valid = true;
3314    buf->file_id = file_id;
3315  } else {
3316    buf->file_id_valid = false;
3317  }
3318}
3319
3320/// Check that file_id in buffer "buf" matches with "file_id".
3321///
3322/// @param  buf      buffer
3323/// @param  file_id  file id
3324static bool buf_same_file_id(buf_T *buf, FileID *file_id)
3325  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3326{
3327  return buf->file_id_valid && os_fileid_equal(&(buf->file_id), file_id);
3328}
3329
3330/// Print info about the current buffer.
3331///
3332/// @param fullname  when non-zero print full path
3333void fileinfo(int fullname, int shorthelp, bool dont_truncate)
3334{
3335  char *buffer = xmalloc(IOSIZE);
3336  size_t bufferlen = 0;
3337
3338  if (fullname > 1) {       // 2 CTRL-G: include buffer number
3339    bufferlen = vim_snprintf_safelen(buffer, IOSIZE, "buf %d: ", curbuf->b_fnum);
3340  }
3341
3342  buffer[bufferlen++] = '"';
3343
3344  char *name = buf_spname(curbuf);
3345  if (name != NULL) {
3346    bufferlen += vim_snprintf_safelen(buffer + bufferlen,
3347                                      IOSIZE - bufferlen, "%s", name);
3348  } else {
3349    name = (!fullname && curbuf->b_fname != NULL) ? curbuf->b_fname : curbuf->b_ffname;
3350    bufferlen += home_replace(shorthelp ? curbuf : NULL, name,
3351                              buffer + bufferlen, IOSIZE - bufferlen, true);
3352  }
3353
3354  bool dontwrite = bt_dontwrite(curbuf);
3355  bufferlen += vim_snprintf_safelen(buffer + bufferlen,
3356                                    IOSIZE - bufferlen,
3357                                    "\"%s%s%s%s%s%s",
3358                                    curbufIsChanged()
3359                                    ? (shortmess(kShmMod) ? " [+]" : _(" [Modified]"))
3360                                    : " ",
3361                                    (curbuf->b_flags & BF_NOTEDITED) && !dontwrite
3362                                    ? _("[Not edited]") : "",
3363                                    (curbuf->b_flags & BF_NEW) && !dontwrite
3364                                    ? _("[New]") : "",
3365                                    (curbuf->b_flags & BF_READERR)
3366                                    ? _("[Read errors]") : "",
3367                                    curbuf->b_p_ro
3368                                    ? (shortmess(kShmRo) ? _("[RO]") : _("[readonly]"))
3369                                    : "",
3370                                    (curbufIsChanged()
3371                                     || (curbuf->b_flags & BF_WRITE_MASK)
3372                                     || curbuf->b_p_ro)
3373                                    ? " " : "");
3374
3375  if (curbuf->b_ml.ml_flags & ML_EMPTY) {
3376    bufferlen += vim_snprintf_safelen(buffer + bufferlen,
3377                                      IOSIZE - bufferlen, "%s", _(no_lines_msg));
3378  } else if (p_ru) {
3379    // Current line and column are already on the screen -- webb
3380    bufferlen += vim_snprintf_safelen(buffer + bufferlen,
3381                                      IOSIZE - bufferlen,
3382                                      NGETTEXT("%" PRId64 " line --%d%%--",
3383                                               "%" PRId64 " lines --%d%%--",
3384                                               curbuf->b_ml.ml_line_count),
3385                                      (int64_t)curbuf->b_ml.ml_line_count,
3386                                      calc_percentage(curwin->w_cursor.lnum,
3387                                                      curbuf->b_ml.ml_line_count));
3388  } else {
3389    bufferlen += vim_snprintf_safelen(buffer + bufferlen,
3390                                      IOSIZE - bufferlen,
3391                                      _("line %" PRId64 " of %" PRId64 " --%d%%-- col "),
3392                                      (int64_t)curwin->w_cursor.lnum,
3393                                      (int64_t)curbuf->b_ml.ml_line_count,
3394                                      calc_percentage(curwin->w_cursor.lnum,
3395                                                      curbuf->b_ml.ml_line_count));
3396    validate_virtcol(curwin);
3397    bufferlen += (size_t)col_print(buffer + bufferlen, IOSIZE - bufferlen,
3398                                   curwin->w_cursor.col + 1, curwin->w_virtcol + 1);
3399  }
3400
3401  append_arg_number(curwin, buffer + bufferlen, IOSIZE - bufferlen);
3402
3403  if (dont_truncate) {
3404    // Temporarily set msg_scroll to avoid the message being truncated.
3405    // First call msg_start() to get the message in the right place.
3406    msg_start();
3407    int n = msg_scroll;
3408    msg_scroll = true;
3409    msg(buffer, 0);
3410    msg_scroll = n;
3411  } else {
3412    char *p = msg_trunc(buffer, false, 0);
3413    if (restart_edit != 0 || (msg_scrolled && !need_wait_return)) {
3414      // Need to repeat the message after redrawing when:
3415      // - When restart_edit is set (otherwise there will be a delay
3416      //   before redrawing).
3417      // - When the screen was scrolled but there is no wait-return
3418      //   prompt.
3419      set_keep_msg(p, 0);
3420    }
3421  }
3422
3423  xfree(buffer);
3424}
3425
3426int col_print(char *buf, size_t buflen, int col, int vcol)
3427{
3428  if (col == vcol) {
3429    return (int)vim_snprintf_safelen(buf, buflen, "%d", col);
3430  }
3431
3432  return (int)vim_snprintf_safelen(buf, buflen, "%d-%d", col, vcol);
3433}
3434
3435static char *lasttitle = NULL;
3436static char *lasticon = NULL;
3437
3438/// Put the title name in the title bar and icon of the window.
3439void maketitle(void)
3440{
3441  char *title_str = NULL;
3442  char *icon_str = NULL;
3443  char buf[IOSIZE];
3444  const CharBuf outbuf = { buf, sizeof(buf) };
3445
3446  if (!redrawing()) {
3447    // Postpone updating the title when 'lazyredraw' is set.
3448    need_maketitle = true;
3449    return;
3450  }
3451
3452  need_maketitle = false;
3453  if (!p_title && !p_icon && lasttitle == NULL && lasticon == NULL) {
3454    return;  // nothing to do
3455  }
3456
3457  if (p_title) {
3458    int maxlen = 0;
3459
3460    if (p_titlelen > 0) {
3461      maxlen = MAX((int)(p_titlelen * Columns / 100), 10);
3462    }
3463
3464    if (*p_titlestring != NUL) {
3465      if (stl_syntax & STL_IN_TITLE) {
3466        build_stl_str_hl(curwin, outbuf, p_titlestring,
3467                         kOptTitlestring, 0, 0, maxlen, NULL, NULL, NULL, NULL);
3468        title_str = buf;
3469      } else {
3470        title_str = p_titlestring;
3471      }
3472    } else {
3473      // Format: "fname + (path) (1 of 2) - Nvim".
3474#ifdef MSWIN
3475      int p_ssl_save = p_ssl;
3476      p_ssl = true;
3477#endif
3478      char *default_titlestring = "%t%( %M%)%( (%{expand('%:p:~:h')})%)%a - Nvim";
3479      build_stl_str_hl(curwin, outbuf, default_titlestring,
3480                       kOptTitlestring, 0, 0, maxlen, NULL, NULL, NULL, NULL);
3481      title_str = buf;
3482#ifdef MSWIN
3483      p_ssl = p_ssl_save;
3484#endif
3485    }
3486  }
3487  bool mustset = value_change(title_str, &lasttitle);
3488
3489  if (p_icon) {
3490    icon_str = buf;
3491    if (*p_iconstring != NUL) {
3492      if (stl_syntax & STL_IN_ICON) {
3493        build_stl_str_hl(curwin, outbuf, p_iconstring,
3494                         kOptIconstring, 0, 0, 0, NULL, NULL, NULL, NULL);
3495      } else {
3496        icon_str = p_iconstring;
3497      }
3498    } else {
3499      char *name = buf_spname(curbuf);
3500      if (name == NULL) {
3501        name = path_tail(curbuf->b_ffname);
3502      }
3503      // Truncate name at 100 bytes.
3504      int namelen = (int)strlen(name);
3505      if (namelen > 100) {
3506        namelen -= 100;
3507        namelen += utf_cp_bounds(name, name + namelen).end_off;
3508        name += namelen;
3509      }
3510      STRCPY(buf, name);
3511      trans_characters(buf, sizeof(buf));
3512    }
3513  }
3514
3515  mustset |= value_change(icon_str, &lasticon);
3516
3517  if (mustset) {
3518    resettitle();
3519  }
3520}
3521
3522/// Used for title and icon: Check if "str" differs from "*last".  Set "*last"
3523/// from "str" if it does by freeing the old value of "*last" and duplicating
3524/// "str".
3525///
3526/// @param          str   desired title string
3527/// @param[in,out]  last  current title string
3528///
3529/// @return  true if resettitle() is to be called.
3530static bool value_change(char *str, char **last)
3531  FUNC_ATTR_WARN_UNUSED_RESULT
3532{
3533  if ((str == NULL) != (*last == NULL)
3534      || (str != NULL && *last != NULL && strcmp(str, *last) != 0)) {
3535    xfree(*last);
3536    if (str == NULL) {
3537      *last = NULL;
3538      resettitle();
3539    } else {
3540      *last = xstrdup(str);
3541      return true;
3542    }
3543  }
3544  return false;
3545}
3546
3547/// Set current window title
3548void resettitle(void)
3549{
3550  ui_call_set_icon(cstr_as_string(lasticon));
3551  ui_call_set_title(cstr_as_string(lasttitle));
3552}
3553
3554#ifdef EXITFREE
3555void free_titles(void)
3556{
3557  xfree(lasttitle);
3558  xfree(lasticon);
3559}
3560
3561#endif
3562
3563/// Get relative cursor position in window into "buf[]", in the localized
3564/// percentage form like %99, 99%; using "Top", "Bot" or "All" when appropriate.
3565int get_rel_pos(win_T *wp, char *buf, int buflen)
3566{
3567  // Need at least 3 chars for writing.
3568  if (buflen < 3) {
3569    return 0;
3570  }
3571
3572  linenr_T above;          // number of lines above window
3573  linenr_T below;          // number of lines below window
3574
3575  above = wp->w_topline - 1;
3576  above += win_get_fill(wp, wp->w_topline) - wp->w_topfill;
3577  if (wp->w_topline == 1 && wp->w_topfill >= 1) {
3578    // All buffer lines are displayed and there is an indication
3579    // of filler lines, that can be considered seeing all lines.
3580    above = 0;
3581  }
3582  below = wp->w_buffer->b_ml.ml_line_count - wp->w_botline + 1;
3583  if (below <= 0) {
3584    return (int)vim_snprintf_safelen(buf, (size_t)buflen,
3585                                     "%s", (above == 0) ? _("All") : _("Bot"));
3586  }
3587
3588  if (above <= 0) {
3589    return (int)vim_snprintf_safelen(buf, (size_t)buflen,
3590                                     "%s", _("Top"));
3591  }
3592
3593  int perc = calc_percentage(above, above + below);
3594  char tmp[8];
3595  // localized percentage value
3596  vim_snprintf(tmp, sizeof(tmp), _("%d%%"), perc);
3597  return (int)vim_snprintf_safelen(buf, (size_t)buflen, _("%3s"), tmp);
3598}
3599
3600/// Append (2 of 8) to "buf[]", if editing more than one file.
3601///
3602/// @param          wp        window whose buffers to check
3603/// @param[in,out]  buf       string buffer to add the text to
3604/// @param          buflen    length of the string buffer
3605///
3606/// @return  the number of characters appended.
3607int append_arg_number(win_T *wp, char *buf, size_t buflen)
3608  FUNC_ATTR_NONNULL_ALL
3609{
3610  // Nothing to do
3611  if (ARGCOUNT <= 1) {
3612    return 0;
3613  }
3614
3615  const char *msg = wp->w_arg_idx_invalid ? _(" ((%d) of %d)") : _(" (%d of %d)");
3616
3617  return (int)vim_snprintf_safelen(buf, buflen, msg, wp->w_arg_idx + 1, ARGCOUNT);
3618}
3619
3620/// Make "*ffname" a full file name, set "*sfname" to "*ffname" if not NULL.
3621/// For a directory the resulting "*ffname" gets a trailing path separator. When
3622/// "*sfname" already ends with a separator the final component is not resolved,
3623/// so the symbolic link path is preserved.
3624/// "*ffname" becomes a pointer to allocated memory (or NULL).
3625/// When resolving a link both "*sfname" and "*ffname" will point to the same
3626/// allocated memory.
3627/// The "*ffname" and "*sfname" pointer values on call will not be freed.
3628/// Note that the resulting "*ffname" pointer should be considered not allocated.
3629void fname_expand(buf_T *buf, char **ffname, char **sfname)
3630{
3631  if (*ffname == NULL) {  // no file name given, nothing to do
3632    return;
3633  }
3634  if (*sfname == NULL) {  // no short file name given, use ffname
3635    *sfname = *ffname;
3636  }
3637  *ffname = fix_fname(*ffname);     // expand to full path
3638  if (*ffname == NULL) {
3639    *sfname = NULL;
3640    return;
3641  }
3642  // Preserve a symbolic link path for directory buffers. fix_fname("link/")
3643  // resolves to the target, so re-expand without the trailing separator: if
3644  // "link" is a symbolic link to directory "target", ":edit link/" produces
3645  // ".../link/", not ".../target/".
3646  if (os_isdir(*ffname)) {
3647    char *name = xstrdup(*sfname);
3648    size_t name_len = strlen(name);
3649    if (name_len > 0 && after_pathsep(name, name + name_len)
3650        && name + name_len > get_past_head(name)) {
3651      *path_tail_with_sep(name) = NUL;
3652    }
3653    char *full = fix_fname(name);
3654    xfree(name);
3655    if (full != NULL) {
3656      xfree(*ffname);
3657      *ffname = full;
3658    }
3659    *ffname = concat_fnames_realloc(*ffname, "", true);
3660  }
3661
3662#ifdef MSWIN
3663  if (!buf->b_p_bin) {
3664    // If the file name is a shortcut file, use the file it links to.
3665    char *rfname = os_resolve_shortcut(*ffname);
3666    if (rfname != NULL) {
3667      xfree(*ffname);
3668      *ffname = rfname;
3669      *sfname = rfname;
3670    }
3671  }
3672#endif
3673}
3674
3675/// @return  true if "buf" is a prompt buffer.
3676bool bt_prompt(buf_T *buf)
3677  FUNC_ATTR_PURE
3678{
3679  return buf != NULL && buf->b_p_bt[0] == 'p';
3680}
3681
3682/// @return  true if "buf" is the |cmdwin| scratch buffer.
3683bool bt_cmdwin(const buf_T *buf)
3684  FUNC_ATTR_PURE
3685{
3686  return buf != NULL && buf == cmdwin_buf;
3687}
3688
3689/// Open a window for a number of buffers.
3690void ex_buffer_all(exarg_T *eap)
3691{
3692  win_T *wpnext;
3693  int split_ret = OK;
3694  int open_wins = 0;
3695  int had_tab = cmdmod.cmod_tab;
3696
3697  // Maximum number of windows to open.
3698  linenr_T count = eap->addr_count == 0
3699                   ? 9999         // make as many windows as possible
3700                   : eap->line2;  // make as many windows as specified
3701
3702  // When true also load inactive buffers.
3703  int all = eap->cmdidx != CMD_unhide && eap->cmdidx != CMD_sunhide;
3704
3705  // Stop Visual mode, the cursor and `Visual.start` may very well be invalid after
3706  // switching to another buffer.
3707  reset_VIsual_and_resel();
3708
3709  setpcmark();
3710
3711  // Close superfluous windows (two windows for the same buffer).
3712  // Also close windows that are not full-width.
3713  if (had_tab > 0) {
3714    goto_tabpage_tp(first_tabpage, true, true);
3715  }
3716  while (true) {
3717    tabpage_T *tpnext = curtab->tp_next;
3718    // Try to close floating windows first
3719    for (win_T *wp = lastwin->w_floating ? lastwin : firstwin; wp != NULL; wp = wpnext) {
3720      wpnext = wp->w_floating
3721               ? wp->w_prev->w_floating ? wp->w_prev : firstwin
3722               : (wp->w_next == NULL || wp->w_next->w_floating) ? NULL : wp->w_next;
3723      if ((wp->w_buffer->b_nwindows > 1
3724           || wp->w_floating
3725           || ((cmdmod.cmod_split & WSP_VERT)
3726               ? wp->w_height + wp->w_hsep_height + wp->w_status_height < Rows - p_ch
3727               - tabline_height() - global_stl_height()
3728               : wp->w_width != Columns)
3729           || (had_tab > 0 && wp != firstwin))
3730          && !ONE_WINDOW
3731          && !(win_locked(wp) || wp->w_buffer->b_locked > 0)
3732          && !is_ctx_win(wp)) {
3733        if (win_close(wp, false, false) == FAIL) {
3734          break;
3735        }
3736        // Just in case an autocommand does something strange with
3737        // windows: start all over...
3738        wpnext = lastwin->w_floating ? lastwin : firstwin;
3739        tpnext = first_tabpage;
3740        open_wins = 0;
3741      } else {
3742        open_wins++;
3743      }
3744    }
3745
3746    // Without the ":tab" modifier only do the current tab page.
3747    if (had_tab == 0 || tpnext == NULL) {
3748      break;
3749    }
3750    goto_tabpage_tp(tpnext, true, true);
3751  }
3752
3753  // Go through the buffer list.  When a buffer doesn't have a window yet,
3754  // open one.  Otherwise move the window to the right position.
3755  // Watch out for autocommands that delete buffers or windows!
3756  //
3757  // Don't execute Win/Buf Enter/Leave autocommands here.
3758  autocmd_no_enter++;
3759  // lastwin may be ctx_win
3760  win_enter(lastwin_nofloating(NULL), false);
3761  autocmd_no_leave++;
3762  for (buf_T *buf = firstbuf; buf != NULL && open_wins < count; buf = buf->b_next) {
3763    // Check if this buffer needs a window
3764    if ((!all && buf->b_ml.ml_mfp == NULL) || !buf->b_p_bl) {
3765      continue;
3766    }
3767
3768    win_T *wp;
3769    if (had_tab != 0) {
3770      // With the ":tab" modifier don't move the window.
3771      wp = buf->b_nwindows > 0
3772           ? lastwin  // buffer has a window, skip it
3773           : NULL;
3774    } else {
3775      // Check if this buffer already has a window
3776      for (wp = firstwin; wp != NULL; wp = wp->w_next) {
3777        if (!wp->w_floating && wp->w_buffer == buf) {
3778          break;
3779        }
3780      }
3781      // If the buffer already has a window, move it
3782      if (wp != NULL) {
3783        win_move_after(wp, curwin);
3784      }
3785    }
3786
3787    if (wp == NULL && split_ret == OK) {
3788      bufref_T bufref;
3789      set_bufref(&bufref, buf);
3790      // Split the window and put the buffer in it.
3791      bool p_ea_save = p_ea;
3792      p_ea = true;                      // use space from all windows
3793      split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
3794      open_wins++;
3795      p_ea = p_ea_save;
3796      if (split_ret == FAIL) {
3797        continue;
3798      }
3799
3800      // Open the buffer in this window.
3801      swap_exists_action = SEA_DIALOG;
3802      set_curbuf(buf, DOBUF_GOTO, !(jop_flags & kOptJopFlagClean));
3803      if (!bufref_valid(&bufref)) {
3804        // Autocommands deleted the buffer.
3805        swap_exists_action = SEA_NONE;
3806        break;
3807      }
3808      if (swap_exists_action == SEA_QUIT) {
3809        cleanup_T cs;
3810
3811        // Reset the error/interrupt/exception state here so that
3812        // aborting() returns false when closing a window.
3813        enter_cleanup(&cs);
3814
3815        // User selected Quit at ATTENTION prompt; close this window.
3816        win_close(curwin, true, false);
3817        open_wins--;
3818        swap_exists_action = SEA_NONE;
3819        swap_exists_did_quit = true;
3820
3821        // Restore the error/interrupt/exception state if not
3822        // discarded by a new aborting error, interrupt, or uncaught
3823        // exception.
3824        leave_cleanup(&cs);
3825      } else {
3826        handle_swap_exists(NULL);
3827      }
3828    }
3829
3830    os_breakcheck();
3831    if (got_int) {
3832      vgetc();            // only break the file loading, not the rest
3833      break;
3834    }
3835    // Autocommands deleted the buffer or aborted script processing!!!
3836    if (aborting()) {
3837      break;
3838    }
3839    // When ":tab" was used open a new tab for a new window repeatedly.
3840    if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) {
3841      cmdmod.cmod_tab = 9999;
3842    }
3843  }
3844  autocmd_no_enter--;
3845  win_enter(firstwin, false);           // back to first window
3846  autocmd_no_leave--;
3847
3848  // Close superfluous windows.
3849  for (win_T *wp = lastwin; open_wins > count;) {
3850    bool r = (buf_hide(wp->w_buffer) || !bufIsChanged(wp->w_buffer)
3851              || autowrite(wp->w_buffer, false) == OK) && !is_ctx_win(wp);
3852    if (!win_valid(wp)) {
3853      // BufWrite Autocommands made the window invalid, start over
3854      wp = lastwin;
3855    } else if (r) {
3856      win_close(wp, !buf_hide(wp->w_buffer), false);
3857      open_wins--;
3858      wp = lastwin;
3859    } else {
3860      wp = wp->w_prev;
3861      if (wp == NULL) {
3862        break;
3863      }
3864    }
3865  }
3866}
3867
3868/// do_modelines() - process mode lines for the current file
3869///
3870/// @param flags
3871///        OPT_WINONLY      only set options local to window
3872///        OPT_NOWIN        don't set options local to window
3873///
3874/// Returns immediately if the "ml" option isn't set.
3875void do_modelines(int flags)
3876{
3877  linenr_T lnum;
3878  int nmlines;
3879  static int entered = 0;
3880
3881  if (!curbuf->b_p_ml || (nmlines = (int)p_mls) == 0) {
3882    return;
3883  }
3884
3885  // Disallow recursive entry here.  Can happen when executing a modeline
3886  // triggers an autocommand, which reloads modelines with a ":do".
3887  if (entered) {
3888    return;
3889  }
3890
3891  entered++;
3892  for (lnum = 1; curbuf->b_p_ml && lnum <= curbuf->b_ml.ml_line_count
3893       && lnum <= nmlines; lnum++) {
3894    if (chk_modeline(lnum, flags) == FAIL) {
3895      nmlines = 0;
3896    }
3897  }
3898
3899  for (lnum = curbuf->b_ml.ml_line_count; curbuf->b_p_ml && lnum > 0
3900       && lnum > nmlines && lnum > curbuf->b_ml.ml_line_count - nmlines;
3901       lnum--) {
3902    if (chk_modeline(lnum, flags) == FAIL) {
3903      nmlines = 0;
3904    }
3905  }
3906  entered--;
3907}
3908
3909/// chk_modeline() - check a single line for a mode string
3910/// Return FAIL if an error encountered.
3911///
3912/// @param flags  Same as for do_modelines().
3913static int chk_modeline(linenr_T lnum, int flags)
3914{
3915  char *e;
3916  int retval = OK;
3917  ESTACK_CHECK_DECLARATION;
3918
3919  int prev = -1;
3920  char *s = ml_get(lnum);
3921  char *line_end = s + ml_get_len(lnum);
3922  for (; *s != NUL; s++) {
3923    if (prev == -1 || ascii_isspace(prev)) {
3924      if ((prev != -1 && strncmp(s, "ex:", 3) == 0)
3925          || strncmp(s, "vi:", 3) == 0) {
3926        break;
3927      }
3928      // Accept both "vim" and "Vim".
3929      if ((s[0] == 'v' || s[0] == 'V') && s[1] == 'i' && s[2] == 'm') {
3930        if (s[3] == '<' || s[3] == '=' || s[3] == '>') {
3931          e = s + 4;
3932        } else {
3933          e = s + 3;
3934        }
3935        intmax_t vers;
3936        if (!try_getdigits(&e, &vers)) {
3937          continue;
3938        }
3939
3940        const int vim_version = min_vim_version();
3941        if (*e == ':'
3942            && (s[0] != 'V'
3943                || strncmp(skipwhite(e + 1), "set", 3) == 0)
3944            && (s[3] == ':'
3945                || (vim_version >= vers && isdigit((uint8_t)s[3]))
3946                || (vim_version < vers && s[3] == '<')
3947                || (vim_version > vers && s[3] == '>')
3948                || (vim_version == vers && s[3] == '='))) {
3949          break;
3950        }
3951      }
3952    }
3953    prev = (uint8_t)(*s);
3954  }
3955
3956  if (!*s) {
3957    return retval;
3958  }
3959
3960  do {                                // skip over "ex:", "vi:" or "vim:"
3961    s++;
3962  } while (s[-1] != ':');
3963
3964  size_t len = (size_t)(line_end - s);  // remember the line length so we can restore
3965                                        // 'line_end' after the copy
3966  char *linecopy;  // local copy of any modeline found
3967  s = linecopy = xstrnsave(s, len);     // copy the line, it will change
3968
3969  line_end = s + len;                   // restore 'line_end'
3970
3971  // prepare for emsg()
3972  estack_push(ETYPE_MODELINE, "modelines", lnum);
3973  ESTACK_CHECK_SETUP;
3974
3975  bool end = false;
3976  while (end == false) {
3977    s = skipwhite(s);
3978    if (*s == NUL) {
3979      break;
3980    }
3981
3982    // Find end of set command: ':' or end of line.
3983    // Skip over "\:", replacing it with ":".
3984    for (e = s; *e != ':' && *e != NUL; e++) {
3985      if (e[0] == '\\' && e[1] == ':') {
3986        memmove(e, e + 1, (size_t)(line_end - (e + 1)) + 1);    // +1 for NUL
3987        line_end--;
3988      }
3989    }
3990    if (*e == NUL) {
3991      end = true;
3992    }
3993
3994    // If there is a "set" command, require a terminating ':' and
3995    // ignore the stuff after the ':'.
3996    // "vi:set opt opt opt: foo" -- foo not interpreted
3997    // "vi:opt opt opt: foo" -- foo interpreted
3998    // Accept "se" for compatibility with Elvis.
3999    if (strncmp(s, "set ", 4) == 0
4000        || strncmp(s, "se ", 3) == 0) {
4001      if (*e != ':') {                // no terminating ':'?
4002        break;
4003      }
4004      end = true;
4005      s += (*(s + 2) == ' ') ? 3 : 4;
4006    }
4007    *e = NUL;                         // truncate the set command
4008
4009    if (*s != NUL) {                  // skip over an empty "::"
4010      const int secure_save = secure;
4011      const sctx_T save_current_sctx = current_sctx;
4012      current_sctx.sc_sid = SID_MODELINE;
4013      current_sctx.sc_seq = 0;
4014      current_sctx.sc_lnum = lnum;
4015      // Make sure no risky things are executed as a side effect.
4016      secure = 1;
4017
4018      retval = do_set(s, OPT_MODELINE | OPT_LOCAL | flags);
4019
4020      secure = secure_save;
4021      current_sctx = save_current_sctx;
4022      if (retval == FAIL) {                   // stop if error found
4023        break;
4024      }
4025    }
4026    s = (e == line_end) ? e : e + 1;  // advance to next part
4027                                      // careful not to go off the end
4028  }
4029
4030  ESTACK_CHECK_NOW;
4031  estack_pop();
4032  xfree(linecopy);
4033
4034  return retval;
4035}
4036
4037/// @return  true if "buf" is a help buffer.
4038bool bt_help(const buf_T *const buf)
4039  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4040{
4041  return buf != NULL && buf->b_help;
4042}
4043
4044/// @return  true if "buf" is a normal buffer, 'buftype' is empty.
4045bool bt_normal(const buf_T *const buf)
4046  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4047{
4048  return buf != NULL && buf->b_p_bt[0] == NUL;
4049}
4050
4051/// @return  true if "buf" is the quickfix buffer.
4052bool bt_quickfix(const buf_T *const buf)
4053  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4054{
4055  return buf != NULL && buf->b_p_bt[0] == 'q';
4056}
4057
4058/// @return  true if "buf" is a terminal buffer.
4059bool bt_terminal(const buf_T *const buf)
4060  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4061{
4062  return buf != NULL && buf->b_p_bt[0] == 't';
4063}
4064
4065/// @return  true if "buf" is a "nofile", "acwrite", "terminal" or "prompt"
4066///          buffer.  This means the buffer name may not be a file name,
4067///          at least not for writing the buffer.
4068bool bt_nofilename(const buf_T *const buf)
4069  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4070{
4071  return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f')
4072                         || buf->b_p_bt[0] == 'a'
4073                         || buf->terminal
4074                         || buf->b_p_bt[0] == 'p');
4075}
4076
4077/// @return  true if "buf" is a "nofile", "quickfix", "terminal" or "prompt"
4078///          buffer.  This means the buffer is not to be read from a file.
4079static bool bt_nofileread(const buf_T *const buf)
4080  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4081{
4082  return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f')
4083                         || buf->b_p_bt[0] == 't'
4084                         || buf->b_p_bt[0] == 'q'
4085                         || buf->b_p_bt[0] == 'p');
4086}
4087
4088/// @return  true if "buf" has 'buftype' set to "nofile".
4089bool bt_nofile(const buf_T *const buf)
4090  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4091{
4092  return buf != NULL && buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f';
4093}
4094
4095/// @return  true if "buf" is a "nowrite", "nofile", "terminal" or "prompt"
4096///          buffer.
4097bool bt_dontwrite(const buf_T *const buf)
4098  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4099{
4100  return buf != NULL && (buf->b_p_bt[0] == 'n'
4101                         || buf->terminal
4102                         || buf->b_p_bt[0] == 'p');
4103}
4104
4105bool bt_dontwrite_msg(const buf_T *const buf)
4106  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
4107{
4108  if (bt_dontwrite(buf)) {
4109    emsg(_("E382: Cannot write, 'buftype' option is set"));
4110    return true;
4111  }
4112  return false;
4113}
4114
4115/// @return  true if the buffer should be hidden, according to 'hidden', ":hide"
4116///          and 'bufhidden'.
4117bool buf_hide(const buf_T *const buf)
4118  FUNC_ATTR_PURE
4119{
4120  // 'bufhidden' overrules 'hidden' and ":hide", check it first
4121  switch (buf->b_p_bh[0]) {
4122  case 'u':                         // "unload"
4123  case 'w':                         // "wipe"
4124  case 'd':
4125    return false;           // "delete"
4126  case 'h':
4127    return true;            // "hide"
4128  }
4129  return p_hid || (cmdmod.cmod_flags & CMOD_HIDE);
4130}
4131
4132/// @return  special buffer name or
4133///          NULL when the buffer has a normal file name.
4134char *buf_spname(buf_T *buf)
4135{
4136  if (bt_quickfix(buf)) {
4137    // Differentiate between the quickfix and location list buffers using
4138    // the buffer number stored in the global quickfix stack.
4139    if (buf->b_fnum == qf_stack_get_bufnr()) {
4140      return _(msg_qflist);
4141    }
4142    return _(msg_loclist);
4143  }
4144  // There is no _file_ when 'buftype' is "nofile", b_sfname
4145  // contains the name as specified by the user.
4146  if (bt_nofilename(buf)) {
4147    if (buf->b_fname != NULL) {
4148      return buf->b_fname;
4149    }
4150    if (bt_cmdwin(buf)) {
4151      return _("[Command Line]");
4152    }
4153    if (bt_prompt(buf)) {
4154      return _("[Prompt]");
4155    }
4156    return _("[Scratch]");
4157  }
4158  if (buf->b_fname == NULL) {
4159    return buf_get_fname(buf);
4160  }
4161  return NULL;
4162}
4163
4164/// Get "buf->b_fname", use "[No Name]" if it is NULL.
4165char *buf_get_fname(const buf_T *buf)
4166  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
4167{
4168  if (buf->b_fname == NULL) {
4169    return _("[No Name]");
4170  }
4171  return buf->b_fname;
4172}
4173
4174/// Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed.
4175void set_buflisted(int on)
4176{
4177  if (on == curbuf->b_p_bl) {
4178    return;
4179  }
4180
4181  curbuf->b_p_bl = on;
4182  if (on) {
4183    apply_autocmds(EVENT_BUFADD, NULL, NULL, false, curbuf);
4184  } else {
4185    apply_autocmds(EVENT_BUFDELETE, NULL, NULL, false, curbuf);
4186  }
4187}
4188
4189/// Read the file for "buf" again and check if the contents changed.
4190/// Return true if it changed or this could not be checked.
4191///
4192/// @param  buf  buffer to check
4193///
4194/// @return  true if the buffer's contents have changed
4195bool buf_contents_changed(buf_T *buf)
4196  FUNC_ATTR_NONNULL_ALL
4197{
4198  bool differ = true;
4199
4200  // Allocate a buffer without putting it in the buffer list.
4201  buf_T *newbuf = buflist_new(NULL, NULL, 1, BLN_DUMMY);
4202  if (newbuf == NULL) {
4203    return true;
4204  }
4205
4206  // Force the 'fileencoding' and 'fileformat' to be equal.
4207  exarg_T ea;
4208  prep_exarg(&ea, buf);
4209
4210  // Set curwin/curbuf to buf and save a few things.
4211  CtxSwitch aco = { 0 };
4212  ctx_switch(&aco, NULL, NULL, newbuf, 0);
4213
4214  // We don't want to trigger autocommands now, they may have nasty
4215  // side-effects like wiping buffers
4216  block_autocmds();
4217
4218  if (ml_open(curbuf) == OK
4219      && readfile(buf->b_ffname, buf->b_fname,
4220                  0, 0, (linenr_T)MAXLNUM,
4221                  &ea, READ_NEW | READ_DUMMY, false) == OK) {
4222    // compare the two files line by line
4223    if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count) {
4224      differ = false;
4225      for (linenr_T lnum = 1; lnum <= curbuf->b_ml.ml_line_count; lnum++) {
4226        if (strcmp(ml_get_buf(buf, lnum), ml_get(lnum)) != 0) {
4227          differ = true;
4228          break;
4229        }
4230      }
4231    }
4232  }
4233  xfree(ea.cmd);
4234
4235  // restore curwin/curbuf and a few other things
4236  ctx_restore(&aco);
4237
4238  if (curbuf != newbuf) {  // safety check
4239    wipe_buffer(newbuf, false);
4240  }
4241
4242  unblock_autocmds();
4243
4244  return differ;
4245}
4246
4247/// Wipe out a (typically temporary) buffer.
4248/// @param aucmd  When true trigger autocommands.
4249void wipe_buffer(buf_T *buf, bool aucmd)
4250{
4251  if (!aucmd) {
4252    // Don't trigger BufDelete autocommands here.
4253    block_autocmds();
4254  }
4255  close_buffer(NULL, buf, DOBUF_WIPE, false, true, false);
4256  if (!aucmd) {
4257    unblock_autocmds();
4258  }
4259}
4260
4261bool buf_is_empty(buf_T *buf)
4262{
4263  return buf->b_ml.ml_line_count == 1 && *ml_get_buf(buf, 1) == NUL;
4264}
4265
4266/// Increment b:changedtick value
4267///
4268/// Also checks b: for consistency in case of debug build.
4269///
4270/// @param[in,out]  buf  Buffer to increment value in.
4271void buf_inc_changedtick(buf_T *const buf)
4272  FUNC_ATTR_NONNULL_ALL
4273{
4274  buf_set_changedtick(buf, buf_get_changedtick(buf) + 1);
4275}
4276
4277/// Set b:changedtick, also checking b: for consistency in debug build
4278///
4279/// @param[out]  buf  Buffer to set changedtick in.
4280/// @param[in]  changedtick  New value.
4281void buf_set_changedtick(buf_T *const buf, const varnumber_T changedtick)
4282  FUNC_ATTR_NONNULL_ALL
4283{
4284  typval_T old_val = buf->changedtick_di.di_tv;
4285
4286#ifndef NDEBUG
4287  dictitem_T *const changedtick_di = tv_dict_find(buf->b_vars, S_LEN("changedtick"));
4288  assert(changedtick_di != NULL);
4289  assert(changedtick_di->di_tv.v_type == VAR_NUMBER);
4290  assert(changedtick_di->di_tv.v_lock == VAR_FIXED);
4291  // For some reason formatc does not like the below.
4292# ifndef UNIT_TESTING_LUA_PREPROCESSING
4293  assert(changedtick_di->di_flags == (DI_FLAGS_RO|DI_FLAGS_FIX));
4294# endif
4295  assert(changedtick_di == (dictitem_T *)&buf->changedtick_di);
4296#endif
4297  buf->changedtick_di.di_tv.vval.v_number = changedtick;
4298
4299  if (tv_dict_is_watched(buf->b_vars)) {
4300    buf->b_locked++;
4301    tv_dict_watcher_notify(buf->b_vars,
4302                           (char *)buf->changedtick_di.di_key,
4303                           &buf->changedtick_di.di_tv,
4304                           &old_val);
4305    buf->b_locked--;
4306  }
4307}
4308
4309/// Read the given buffer contents into a string.
4310void read_buffer_into(buf_T *buf, linenr_T start, linenr_T end, StringBuilder *sb)
4311  FUNC_ATTR_NONNULL_ALL
4312{
4313  assert(buf);
4314  assert(sb);
4315
4316  if (buf->b_ml.ml_flags & ML_EMPTY) {
4317    return;
4318  }
4319
4320  size_t written = 0;
4321  size_t len = 0;
4322  linenr_T lnum = start;
4323  char *lp = ml_get_buf(buf, lnum);
4324  size_t lplen = (size_t)ml_get_buf_len(buf, lnum);
4325
4326  while (true) {
4327    if (lplen == 0) {
4328      len = 0;
4329    } else if (lp[written] == NL) {
4330      // NL -> NUL translation
4331      len = 1;
4332      kv_push(*sb, NUL);
4333    } else {
4334      char *s = vim_strchr(lp + written, NL);
4335      len = s == NULL ? lplen - written : (size_t)(s - (lp + written));
4336      kv_concat_len(*sb, lp + written, len);
4337    }
4338
4339    if (len == lplen - written) {
4340      // Finished a line, add a NL, unless this line should not have one.
4341      if (lnum != end
4342          || (!buf->b_p_bin && buf->b_p_fixeol)
4343          || (lnum != buf->b_no_eol_lnum
4344              && (lnum != buf->b_ml.ml_line_count || buf->b_p_eol))) {
4345        kv_push(*sb, NL);
4346      }
4347      lnum++;
4348      if (lnum > end) {
4349        break;
4350      }
4351      lp = ml_get_buf(buf, lnum);
4352      lplen = (size_t)ml_get_buf_len(buf, lnum);
4353      written = 0;
4354    } else if (len > 0) {
4355      written += len;
4356    }
4357  }
4358}