robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
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 { 142kBffClearWinInfo = 1 , 143kBffInitChangedtick = 2 , 144}BufFreeFlags ; 145 146static void trigger_undo_ftplugin (buf_T * buf ,win_T * win ) 147{ 148window_layout_lock (); 149buf -> b_locked ++ ; 150win -> w_locked ++ ; 151// b:undo_ftplugin may be set, undo it 152do_cmdline_cmd ("if exists('b:undo_ftplugin') | exe b:undo_ftplugin | endif" ); 153buf -> b_locked -- ; 154win -> w_locked -- ; 155window_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. 163return (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{ 170return 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{ 180int retval = OK ; 181bool 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. 186linenr_T line_count = curbuf -> b_ml .ml_line_count ; 187retval = readfile (read_stdin ?NULL :curbuf -> b_ffname , 188read_stdin ?NULL :curbuf -> b_fname , 189line_count ,0 , (linenr_T )MAXLNUM ,eap , 190flags |READ_BUFFER ,silent ); 191if (retval == OK ) { 192// Delete the binary lines. 193while (-- line_count >=0 ) { 194ml_delete (1 ); 195 } 196 }else { 197// Delete the converted lines. 198while (curbuf -> b_ml .ml_line_count > line_count ) { 199ml_delete (line_count ); 200 } 201 } 202// Put the cursor on the first line. 203curwin -> w_cursor .lnum = 1 ; 204curwin -> w_cursor .col = 0 ; 205 206if (read_stdin ) { 207// Set or reset 'modified' before executing autocommands, so that 208// it can be changed there. 209if (!readonlymode && !buf_is_empty (curbuf )) { 210changed (curbuf ); 211 }else if (retval != FAIL ) { 212unchanged (curbuf , false, true); 213 } 214 215apply_autocmds_retval (EVENT_STDINREADPOST ,NULL ,NULL , false, 216curbuf ,& retval ); 217 } 218return retval ; 219} 220 221/// Ensure buffer "buf" is loaded. 222bool buf_ensure_loaded (buf_T * buf ) 223{ 224if (buf -> b_ml .ml_mfp != NULL ) { 225// already open (common case) 226return true; 227 } 228 229CtxSwitch aco = {0 }; 230 231// Make sure the buffer is in a window. 232ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 233// status can be OK or NOTDONE (which also means ok/done) 234int status = open_buffer (false,NULL ,0 ); 235ctx_restore (& aco ); 236return (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{ 249int flags = flags_arg ; 250int retval = OK ; 251bufref_T old_curbuf ; 252OptInt old_tw = curbuf -> b_p_tw ; 253bool read_fifo = false; 254bool 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. 259if (readonlymode && curbuf -> b_ffname != NULL 260&& (curbuf -> b_flags & BF_NEVERLOADED )) { 261curbuf -> b_p_ro = true; 262 } 263 264if (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 267close_buffer (curwin ,curbuf ,0 , false, false, false); 268 269curbuf = NULL ; 270FOR_ALL_BUFFERS (buf ) { 271if (buf -> b_ml .ml_mfp != NULL ) { 272curbuf = buf ; 273break ; 274 } 275 } 276 277// If there is no memfile at all, exit. 278// This is OK, since there are no changes to lose. 279if (curbuf == NULL ) { 280emsg (_ ("E82: Cannot allocate any buffer, exiting..." )); 281 282// Don't try to do any saving, with "curbuf" NULL almost nothing 283// will work. 284v_dying = 2 ; 285getout (2 ); 286 } 287 288emsg (_ ("E83: Cannot allocate buffer, using other one..." )); 289enter_buffer (curbuf ); 290if (old_tw != curbuf -> b_p_tw ) { 291check_colorcolumn (NULL ,curwin ); 292 } 293return FAIL ; 294 } 295 296// Do not sync this buffer yet, may first want to read the file. 297if (curbuf -> b_ml .ml_mfp != NULL ) { 298curbuf -> 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. 303set_bufref (& old_curbuf ,curbuf ); 304curbuf -> b_modified_was_set = false; 305 306// mark cursor position as being invalid 307curwin -> w_valid = 0 ; 308 309// A buffer without an actual file should not use the buffer name to read a 310// file. 311if (bt_nofileread (curbuf )) { 312flags |=READ_NOFILE ; 313 } 314 315// Read the file if there is one. 316if (curbuf -> b_ffname != NULL ) { 317#ifdef UNIX 318int save_bin = curbuf -> b_p_bin ; 319int perm = os_getperm (curbuf -> b_ffname ); 320if (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 )) { 327read_fifo = true; 328 } 329if (read_fifo ) { 330curbuf -> b_p_bin = true; 331 } 332#endif 333 334retval = readfile (curbuf -> b_ffname ,curbuf -> b_fname , 3350 ,0 , (linenr_T )MAXLNUM ,eap , 336flags |READ_NEW | (read_fifo ?READ_FIFO :0 ),silent ); 337#ifdef UNIX 338if (read_fifo ) { 339curbuf -> b_p_bin = save_bin ; 340if (retval == OK ) { 341// don't add READ_FIFO here, otherwise we won't be able to 342// detect the encoding 343retval = read_buffer (false,eap ,flags ); 344 } 345 } 346#endif 347 348// Help buffer: populate *local-additions* in help.txt 349if (bt_help (curbuf )) { 350get_local_additions (); 351 } 352 }else if (read_stdin ) { 353int 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. 359curbuf -> b_p_bin = true; 360retval = readfile (NULL ,NULL ,0 , 3610 , (linenr_T )MAXLNUM ,NULL , 362flags | (READ_NEW + READ_STDIN ),silent ); 363curbuf -> b_p_bin = save_bin ; 364if (retval == OK ) { 365retval = read_buffer (true,eap ,flags ); 366 } 367 } 368 369// Can now sync this buffer in ml_sync_all(). 370if (curbuf -> b_ml .ml_mfp != NULL 371&& curbuf -> b_ml .ml_mfp -> mf_dirty == MF_DIRTY_YES_NOSYNC ) { 372curbuf -> b_ml .ml_mfp -> mf_dirty = MF_DIRTY_YES ; 373 } 374 375// if first time loading this buffer, init b_chartab[] 376if (curbuf -> b_flags & BF_NEVERLOADED ) { 377buf_init_isk_chartab (curbuf ); 378parse_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. 388if ((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 )) { 391changed (curbuf ); 392 }else if (retval != FAIL && !read_stdin && !read_fifo ) { 393unchanged (curbuf , false, true); 394 } 395save_file_ff (curbuf );// keep this fileformat 396 397// Set last_changedtick to avoid triggering a TextChanged autocommand right 398// after it was added. 399curbuf -> b_last_changedtick = buf_get_changedtick (curbuf ); 400curbuf -> b_last_changedtick_i = buf_get_changedtick (curbuf ); 401curbuf -> b_last_changedtick_pum = buf_get_changedtick (curbuf ); 402 403// require "!" to overwrite the file, because it wasn't read completely 404if (aborting ()) { 405curbuf -> 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. 412if (retval == NOTDONE && * curbuf -> b_p_ft == NUL 413&& curbuf -> b_ffname != NULL 414&& after_pathsep (curbuf -> b_ffname , 415curbuf -> b_ffname + strlen (curbuf -> b_ffname ))) { 416if (augroup_exists ("filetypedetect" )) { 417bufref_T bufref ; 418set_bufref (& bufref ,curbuf ); 419do_doautocmd ("filetypedetect BufRead" , false,NULL ); 420if (!bufref_valid (& bufref )|| curbuf != old_curbuf .br_buf || aborting ()) { 421return FAIL ; 422 } 423 } 424 } 425 426// Need to update automatic folding. Do this before the autocommands, 427// they may use the fold info. 428foldUpdateAll (curwin ); 429 430// need to set w_topline, unless some autocommand already did that. 431if (!(curwin -> w_valid & VALID_TOPLINE )) { 432curwin -> w_topline = 1 ; 433curwin -> w_topfill = 0 ; 434 } 435apply_autocmds_retval (EVENT_BUFENTER ,NULL ,NULL , false,curbuf ,& retval ); 436 437// if (retval != OK) { 438if (retval == FAIL ) { 439return 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. 444if (bufref_valid (& old_curbuf )&& old_curbuf .br_buf -> b_ml .ml_mfp != NULL ) { 445CtxSwitch aco = {0 }; 446 447// Go to the buffer that was opened, make sure it is in a window. 448ctx_switch (& aco ,NULL ,NULL ,old_curbuf .br_buf ,0 ); 449do_modelines (0 ); 450curbuf -> b_flags &= ~(BF_CHECK_RO |BF_NEVERLOADED ); 451 452if ((flags & READ_NOWINENTER )== 0 ) { 453apply_autocmds_retval (EVENT_BUFWINENTER ,NULL ,NULL , false,curbuf , 454& retval ); 455 } 456 457// restore curwin/curbuf and a few other things 458ctx_restore (& aco ); 459 } 460 461return 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{ 470bufref -> br_buf = buf ; 471bufref -> br_fnum = buf == NULL ?0 :buf -> b_fnum ; 472bufref -> 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 ) 483FUNC_ATTR_PURE 484{ 485return 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 ) 496FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 497{ 498if (buf == NULL ) { 499return false; 500 } 501// Assume that we more often have a recent buffer, 502// start with the last one. 503for (buf_T * bp = lastbuf ;bp != NULL ;bp = bp -> b_prev ) { 504if (bp == buf ) { 505return true; 506 } 507 } 508return 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{ 516bool can_unload = !buf -> b_locked ; 517 518if (can_unload && updating_screen ) { 519FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 520if (wp -> w_buffer == buf ) { 521can_unload = false; 522break ; 523 } 524 } 525 } 526// Don't unload the buffer while it's still being saved 527if (can_unload && buf -> b_saving ) { 528can_unload = false; 529 } 530 531if (!can_unload ) { 532char * fname = buf -> b_fname != NULL ?buf -> b_fname :buf -> b_ffname ; 533semsg (_ (e_attempt_to_delete_buffer_that_is_in_use_str ), 534fname != NULL ?fname :"[No Name]" ); 535 } 536return can_unload ; 537} 538 539void buf_close_terminal (buf_T * buf ) 540{ 541assert (buf -> terminal ); 542buf -> b_locked ++ ; 543terminal_close (& buf -> terminal ,-1 ); 544buf -> 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 , 576bool set_context ) 577FUNC_ATTR_NONNULL_ARG (2 ) 578{ 579bool unload_buf = (action != 0 ); 580bool del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE ); 581bool wipe_buf = (action == DOBUF_WIPE ); 582 583bool is_curwin = (curwin != NULL && curwin == win && curwin -> w_buffer == buf ); 584tabpage_T * the_curtab = curtab ; 585 586CHECK_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). 592if (!buf -> terminal ) { 593if (buf -> b_p_bh [0 ]== 'd' ) {// 'bufhidden' == "delete" 594del_buf = true; 595unload_buf = true; 596 }else if (buf -> b_p_bh [0 ]== 'w' ) {// 'bufhidden' == "wipe" 597del_buf = true; 598unload_buf = true; 599wipe_buf = true; 600 }else if (buf -> b_p_bh [0 ]== 'u' ) {// 'bufhidden' == "unload" 601unload_buf = true; 602 } 603 } 604 605if (buf -> terminal && (unload_buf || del_buf || wipe_buf )) { 606// terminal buffers can only be wiped 607unload_buf = true; 608del_buf = true; 609wipe_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. 614if ((del_buf || wipe_buf )&& !can_unload_buffer (buf )) { 615return false; 616 } 617 618bool win_valid = win_valid_any_tab (win ); 619if (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. 624if (buf -> b_nwindows == 1 ) { 625set_last_cursor (win ); 626 } 627buflist_setfpos (buf ,win , 628win -> w_cursor .lnum == 1 ?0 :win -> w_cursor .lnum , 629win -> w_cursor .col , true); 630 } 631 632bufref_T bufref ; 633set_bufref (& bufref ,buf ); 634 635// When the buffer is no longer in a window, trigger BufWinLeave 636if (win_valid && win -> w_buffer == buf && buf -> b_nwindows == 1 ) { 637buf -> b_locked ++ ; 638buf -> b_locked_split ++ ; 639if (apply_autocmds_win (EVENT_BUFWINLEAVE ,buf -> b_fname ,buf -> b_fname , false, 640buf ,win )&& !bufref_valid (& bufref )) { 641// Autocommands deleted the buffer. 642emsg (_ (e_auabort )); 643return false; 644 } 645buf -> b_locked -- ; 646buf -> b_locked_split -- ; 647if (abort_if_last && one_window (win ,NULL )) { 648// Autocommands made this the only window. 649emsg (_ (e_auabort )); 650return false; 651 } 652 653// When the buffer becomes hidden, but is not unloaded, trigger 654// BufHidden 655if (!unload_buf ) { 656buf -> b_locked ++ ; 657buf -> b_locked_split ++ ; 658if (apply_autocmds (EVENT_BUFHIDDEN ,buf -> b_fname ,buf -> b_fname , false, 659buf )&& !bufref_valid (& bufref )) { 660// Autocommands deleted the buffer. 661emsg (_ (e_auabort )); 662return false; 663 } 664buf -> b_locked -- ; 665buf -> b_locked_split -- ; 666if (abort_if_last && one_window (win ,NULL )) { 667// Autocommands made this the only window. 668emsg (_ (e_auabort )); 669return false; 670 } 671 } 672// autocmds may abort script processing 673if (!ignore_abort && aborting ()) { 674return false; 675 } 676win_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. 682if (is_curwin && curwin != win && win_valid ) { 683block_autocmds (); 684goto_tabpage_win (the_curtab ,win ); 685unblock_autocmds (); 686 } 687 688// When a quickfix buffer is deleted from a window, clear the 689// 'winfixheight' option. 690if (bt_quickfix (buf )&& win_valid && win -> w_buffer == buf ) { 691win -> w_p_wfh = false; 692 } 693 694// Remember if the buffer may be hidden soon, or is already hidden. 695bool hiding_buf = buf -> b_nwindows <=0 696|| (win_valid && win -> w_buffer == buf && buf -> b_nwindows == 1 ); 697 698if (diffopt_hiddenoff ()&& !unload_buf && hiding_buf ) { 699diff_buf_delete (buf );// Clear 'diff' for hidden buffer. 700 } 701 702// Return when another window is displaying the buffer or when not unloaded. 703if (!hiding_buf || !unload_buf ) { 704return false; 705 } 706 707// Always remove the buffer when there is no file name. 708if (buf -> b_ffname == NULL ) { 709del_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. 715if (!buf_freeall (buf , ((del_buf ?BFA_DEL :0 ) 716+ (wipe_buf ?BFA_WIPE :0 ) 717+ (ignore_abort ?BFA_IGNORE_ABORT :0 )))) { 718return false; 719 } 720 721bool clear_w_buf = false; 722win_valid = win_valid && win_valid_any_tab (win ); 723if (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. 726buf -> 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. 730clear_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). 737if (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 )) { 742if (clear_w_buf ) { 743win -> w_buffer = NULL ; 744 } 745FOR_ALL_TAB_WINDOWS (tp ,wp ) { 746mark_forget_file (wp ,buf -> b_fnum ); 747 } 748if (buf -> b_sfname != buf -> b_ffname ) { 749XFREE_CLEAR (buf -> b_sfname ); 750 }else { 751buf -> b_sfname = NULL ; 752 } 753XFREE_CLEAR (buf -> b_ffname ); 754if (buf -> b_prev == NULL ) { 755firstbuf = buf -> b_next ; 756 }else { 757buf -> b_prev -> b_next = buf -> b_next ; 758 } 759if (buf -> b_next == NULL ) { 760lastbuf = buf -> b_prev ; 761 }else { 762buf -> b_next -> b_prev = buf -> b_prev ; 763 } 764free_buffer (buf ); 765 }else { 766if (del_buf ) { 767// Free all internal variables and reset option values, to make 768// ":bdel" compatible with Vim 5.7. 769free_buffer_stuff (buf ,kBffClearWinInfo |kBffInitChangedtick ); 770 771// Make it look like a new buffer. 772buf -> b_flags = BF_CHECK_RO |BF_NEVERLOADED ; 773 774// Init the options when loaded again. 775buf -> b_p_initialized = false; 776 } 777// Dict watchers set b_locked, but also don't want them messing with windows... 778textlock ++ ; 779buf_clear_file (buf ); 780textlock -- ; 781if (clear_w_buf ) { 782win -> w_buffer = NULL ; 783 } 784if (del_buf ) { 785buf -> 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! 793assert (!win_valid || !is_curwin || win == curwin ); 794return true; 795} 796 797/// Make buffer not contain a file. 798void buf_clear_file (buf_T * buf ) 799{ 800buf -> b_ml .ml_line_count = 1 ; 801unchanged (buf , true, true); 802buf -> b_p_eof = false; 803buf -> b_start_eof = false; 804buf -> b_p_eol = true; 805buf -> b_start_eol = true; 806buf -> b_p_bomb = false; 807buf -> b_start_bomb = false; 808buf -> b_ml .ml_mfp = NULL ; 809buf -> b_ml .ml_flags = ML_EMPTY ;// empty buffer 810} 811 812/// Clears the current buffer contents. 813void buf_clear (void ) 814{ 815linenr_T line_count = curbuf -> b_ml .ml_line_count ; 816extmark_free_all (curbuf );// delete any extmarks 817mc_buf_free (curbuf );// Multicursors died with their extmarks. 818while (!(curbuf -> b_ml .ml_flags & ML_EMPTY )) { 819ml_delete (1 ); 820 } 821deleted_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 ) 833FUNC_ATTR_NONNULL_ALL 834{ 835bool is_curbuf = (buf == curbuf ); 836int is_curwin = (curwin != NULL && curwin -> w_buffer == buf ); 837win_T * the_curwin = curwin ; 838tabpage_T * the_curtab = curtab ; 839 840// Make sure the buffer isn't closed by autocommands. 841buf -> b_locked ++ ; 842buf -> b_locked_split ++ ; 843 844bufref_T bufref ; 845set_bufref (& bufref ,buf ); 846 847if (buf -> terminal ) { 848buf_close_terminal (buf ); 849 } 850 851buf_updates_unload (buf , false); 852 853if ((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. 857return false; 858 } 859if ((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. 864return false; 865 } 866if ((flags & BFA_WIPE ) 867&& apply_autocmds (EVENT_BUFWIPEOUT ,buf -> b_fname ,buf -> b_fname , false, 868buf ) 869&& !bufref_valid (& bufref )) { 870// Autocommands may delete the buffer. 871return false; 872 } 873buf -> b_locked -- ; 874buf -> 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. 879if (is_curwin && curwin != the_curwin && win_valid_any_tab (the_curwin )) { 880block_autocmds (); 881goto_tabpage_win (the_curtab ,the_curwin ); 882unblock_autocmds (); 883 } 884// autocmds may abort script processing 885if ((flags & BFA_IGNORE_ABORT )== 0 && aborting ()) { 886return 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. 893if (buf == curbuf && !is_curbuf ) { 894return false; 895 } 896 897// If curbuf, stop Visual mode just before freeing, but after autocmds that may restart it. 898if (buf == curbuf && Visual .active 899#if defined(EXITFREE ) 900&& !entered_free_all_mem 901#endif 902 ) { 903end_visual_mode (); 904 } 905 906diff_buf_delete (buf );// Can't use 'diff' for unloaded buffer. 907// Remove any ownsyntax, unless exiting. 908if (curwin != NULL && curwin -> w_buffer == buf ) { 909reset_synblock (curwin ); 910 } 911 912// No folds in an empty buffer. 913FOR_ALL_TAB_WINDOWS (tp ,win ) { 914if (win -> w_buffer == buf ) { 915clearFolding (win ); 916 } 917 } 918 919// Autocommands may have opened another terminal. Block them this time. 920if (buf -> terminal ) { 921block_autocmds (); 922buf_close_terminal (buf ); 923unblock_autocmds (); 924 } 925 926linenr_T count = buf -> b_ml .ml_line_count ; 927ml_close (buf , true);// close and delete the memline/memfile 928buf -> b_ml .ml_line_count = 0 ;// no lines in buffer 929mc_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. 933if (bt_nofilename (buf )&& !exiting ) { 934mark_adjust_buf (buf ,1 ,count ,MAXLNUM ,- count , false,kMarkAdjustNormal ,kExtmarkNoUndo ); 935 } 936 937if ((flags & BFA_KEEP_UNDO )== 0 ) { 938// free the memory allocated for undo 939// and reset all undo information 940u_clearallandblockfree (buf ); 941 } 942syntax_clear (& buf -> b_s );// reset syntax info 943buf -> b_flags &= ~BF_READERR ;// a read error is no longer relevant 944return 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{ 951pmap_del ( int )( & buffer_handles , buf -> b_fnum , NULL ); 952buf_free_count ++ ; 953// b:changedtick uses an item in buf_T. 954free_buffer_stuff ( buf , kBffClearWinInfo ); 955if ( buf -> b_vars -> dv_refcount > DO_NOT_FREE_CNT ) { 956tv_dict_add ( buf -> b_vars , 957tv_dict_item_copy (( dictitem_T * )( & buf -> changedtick_di ))); 958} 959unref_var_dict ( buf -> b_vars ); 960aubuflocal_remove ( buf ); 961xfree ( buf -> additional_data ); 962xfree ( buf -> b_prompt_text ); 963kv_destroy ( buf -> b_wininfo ); 964callback_free ( & buf -> b_prompt_callback ); 965callback_free ( & buf -> b_prompt_interrupt ); 966clear_fmark ( & buf -> b_last_cursor , 0 ); 967clear_fmark ( & buf -> b_last_insert , 0 ); 968clear_fmark ( & buf -> b_last_change , 0 ); 969clear_fmark ( & buf -> b_prompt_start , 0 ); 970for ( size_t i = 0 ; i < NMARKS ; i ++ ) { 971free_fmark ( buf -> b_namedm [ i ]); 972} 973for ( int i = 0 ; i < buf -> b_changelistlen ; i ++ ) { 974free_fmark ( buf -> b_changelist [ i ]); 975} 976if ( 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. 979CLEAR_FIELD ( buf -> b_namedm ); 980CLEAR_FIELD ( buf -> b_changelist ); 981buf -> b_next = au_pending_free_buf ; 982au_pending_free_buf = buf ; 983} else { 984xfree ( buf ); 985if ( curbuf == buf ) { 986curbuf = 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{ 994for ( size_t i = 0 ; i < kv_size ( buf -> b_wininfo ); i ++ ) { 995free_wininfo ( kv_A ( buf -> b_wininfo , i ), buf ); 996} 997kv_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{ 1006if ( free_flags & kBffClearWinInfo ) { 1007clear_wininfo ( buf ); // including window-local options 1008free_buf_options ( buf , true); 1009ga_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. 1015hashitem_T * const changedtick_hi = hash_find ( & buf -> b_vars -> dv_hashtab , "changedtick" ); 1016assert ( changedtick_hi != NULL ); 1017hash_remove ( & buf -> b_vars -> dv_hashtab , changedtick_hi ); 1018} 1019vars_clear ( & buf -> b_vars -> dv_hashtab ); // free all internal variables 1020hash_init ( & buf -> b_vars -> dv_hashtab ); 1021if ( free_flags & kBffInitChangedtick ) { 1022buf_init_changedtick ( buf ); 1023} 1024uc_clear ( & buf -> b_ucmds ); // clear local user commands 1025extmark_free_all ( buf ); // delete any extmarks 1026mc_buf_free ( buf ); // Multicursors died with their extmarks. 1027map_clear_mode ( buf , MAP_ALL_MODES , true, false); // clear local mappings 1028map_clear_mode ( buf , MAP_ALL_MODES , true, true); // clear local abbrevs 1029XFREE_CLEAR ( buf -> b_start_fenc ); 1030XFREE_CLEAR ( buf -> b_localdir ); 1031XFREE_CLEAR ( buf -> b_prevdir ); 1032 1033buf_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{ 1039const int save_sea = swap_exists_action ; 1040bool skip_help_buf ; 1041 1042switch ( eap -> cmdidx ) { 1043case CMD_bnext : 1044case CMD_sbnext : 1045case CMD_bNext : 1046case CMD_bprevious : 1047case CMD_sbNext : 1048case CMD_sbprevious : 1049skip_help_buf = true; 1050break; 1051default: 1052skip_help_buf = false; 1053break; 1054} 1055 1056bufref_T old_curbuf ; 1057set_bufref ( & old_curbuf , curbuf ); 1058 1059if ( swap_exists_action == SEA_NONE ) { 1060swap_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 1066if ( swap_exists_action == SEA_QUIT && * eap -> cmd == 's' ) { 1067cleanup_T cs ; 1068 1069// Reset the error/interrupt/exception state here so that 1070// aborting() returns false when closing a window. 1071enter_cleanup ( & cs ); 1072 1073// Quitting means closing the split window, nothing else. 1074win_close ( curwin , true, false); 1075swap_exists_action = save_sea ; 1076swap_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. 1080leave_cleanup ( & cs ); 1081} else { 1082handle_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{ 1093cleanup_T cs ; 1094OptInt old_tw = curbuf -> b_p_tw ; 1095buf_T * buf ; 1096 1097if ( swap_exists_action == SEA_QUIT ) { 1098// Reset the error/interrupt/exception state here so that 1099// aborting() returns false when closing a buffer. 1100enter_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. 1105swap_exists_action = SEA_NONE ; // don't want it again 1106swap_exists_did_quit = true; 1107close_buffer ( curwin , curbuf , DOBUF_UNLOAD , false, false, true); 1108if ( 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. 1112block_autocmds (); 1113buf = buflist_new ( NULL , NULL , 1 , BLN_CURBUF | BLN_LISTED ); 1114unblock_autocmds (); 1115} else { 1116buf = old_curbuf -> br_buf ; 1117} 1118if ( buf != NULL ) { 1119enter_buffer ( buf ); 1120 1121if ( old_tw != curbuf -> b_p_tw ) { 1122check_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. 1129leave_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. 1133enter_cleanup ( & cs ); 1134 1135// User selected Recover at ATTENTION prompt. 1136msg_scroll = true; 1137ml_recover (false); 1138msg_puts ( "\n" ); // don't overwrite the last message 1139cmdline_row = msg_row ; 1140do_modelines ( 0 ); 1141 1142// Restore the error/interrupt/exception state if not discarded by a 1143// new aborting error, interrupt, or uncaught exception. 1144leave_cleanup ( & cs ); 1145} 1146swap_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{ 1166int do_current = 0 ; // delete current buffer? 1167int deleted = 0 ; // number of buffers deleted 1168char * errormsg = NULL ; // return value 1169int bnr ; // buffer number 1170 1171if ( addr_count == 0 ) { 1172do_buffer ( command , DOBUF_CURRENT , FORWARD , 0 , forceit ); 1173} else { 1174if ( addr_count == 2 ) { 1175if ( * arg ) { // both range and argument is not allowed 1176return ex_errmsg ( e_trailing_arg , arg ); 1177} 1178bnr = start_bnr ; 1179} else { // addr_count == 1 1180bnr = end_bnr ; 1181} 1182 1183for (; ! 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. 1188if ( bnr == curbuf -> b_fnum ) { 1189do_current = bnr ; 1190} else if ( do_buffer ( command , DOBUF_FIRST , FORWARD , bnr , 1191forceit ) == OK ) { 1192deleted ++ ; 1193} 1194 1195// find next buffer number to delete/unload 1196if ( addr_count == 2 ) { 1197if ( ++ bnr > end_bnr ) { 1198break; 1199} 1200} else { // addr_count == 1 1201arg = skipwhite ( arg ); 1202if ( * arg == NUL ) { 1203break; 1204} 1205if (! ascii_isdigit ( * arg )) { 1206char * p = skiptowhite_esc ( arg ); 1207bnr = buflist_findpat ( arg , p , command == DOBUF_WIPE , false, false); 1208if ( bnr < 0 ) { // failed 1209break; 1210} 1211arg = p ; 1212} else { 1213bnr = getdigits_int ( & arg , false, 0 ); 1214} 1215} 1216} 1217if (! got_int && do_current 1218&& do_buffer ( command , DOBUF_FIRST , 1219FORWARD , do_current , forceit ) == OK ) { 1220deleted ++ ; 1221} 1222 1223if ( deleted == 0 ) { 1224if ( command == DOBUF_UNLOAD ) { 1225xstrlcpy ( IObuff , _ ( "E515: No buffers were unloaded" ), IOSIZE ); 1226} else if ( command == DOBUF_DEL ) { 1227xstrlcpy ( IObuff , _ ( "E516: No buffers were deleted" ), IOSIZE ); 1228} else { 1229xstrlcpy ( IObuff , _ ( "E517: No buffers were wiped out" ), IOSIZE ); 1230} 1231errormsg = IObuff ; 1232} else if ( deleted >= p_report ) { 1233if ( command == DOBUF_UNLOAD ) { 1234smsg ( 0 , NGETTEXT ( "%d buffer unloaded" , "%d buffers unloaded" , deleted ), 1235deleted ); 1236} else if ( command == DOBUF_DEL ) { 1237smsg ( 0 , NGETTEXT ( "%d buffer deleted" , "%d buffers deleted" , deleted ), 1238deleted ); 1239} else { 1240smsg ( 0 , NGETTEXT ( "%d buffer wiped out" , "%d buffers wiped out" , deleted ), 1241deleted ); 1242} 1243} 1244} 1245 1246return 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{ 1253buf_T * buf = curbuf ; 1254 1255if ( action == DOBUF_UNLOAD ) { 1256emsg ( _ ( "E90: Cannot unload last buffer" )); 1257return FAIL ; 1258} 1259 1260bufref_T bufref ; 1261set_bufref ( & bufref , buf ); 1262 1263if ( close_others ) { 1264bool can_close_all_others = true; 1265if ( curwin -> w_floating ) { 1266// Closing all other windows with this buffer may leave only floating windows. 1267can_close_all_others = false; 1268for ( win_T * wp = firstwin ; ! wp -> w_floating ; wp = wp -> w_next ) { 1269if ( 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. 1272can_close_all_others = true; 1273break; 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. 1281close_windows ( buf , can_close_all_others ); 1282} 1283 1284setpcmark (); 1285int 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. 1290if ( buf != curbuf && bufref_valid ( & bufref ) && buf -> b_nwindows == 0 ) { 1291close_buffer ( NULL , buf , action , false, false, false); 1292} 1293 1294if (! close_others ) { 1295need_fileinfo = false; 1296} else if ( retval == OK && ! shortmess ( kShmFileinfo )) { 1297// do_ecmd() does not display file info for a new empty buffer. 1298need_fileinfo = true; 1299} 1300 1301return 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{ 1324buf_T * buf ; 1325buf_T * bp ; 1326bool update_jumplist = true; 1327bool unload = ( action == DOBUF_UNLOAD || action == DOBUF_DEL 1328|| action == DOBUF_WIPE ); 1329 1330switch ( start ) { 1331case DOBUF_FIRST : 1332buf = firstbuf ; break; 1333case DOBUF_LAST : 1334buf = lastbuf ; break; 1335default: 1336buf = curbuf ; break; 1337} 1338if ( start == DOBUF_MOD ) { // find next modified buffer 1339while ( count -- > 0 ) { 1340do { 1341buf = buf -> b_next ; 1342if ( buf == NULL ) { 1343buf = firstbuf ; 1344} 1345} while ( buf != curbuf && ! bufIsChanged ( buf )); 1346} 1347if (! bufIsChanged ( buf )) { 1348emsg ( _ ( "E84: No modified buffer found" )); 1349return FAIL ; 1350} 1351} else if ( start == DOBUF_FIRST && count ) { // find specified buffer number 1352while ( buf != NULL && buf -> b_fnum != count ) { 1353buf = buf -> b_next ; 1354} 1355} else { 1356const bool help_only = ( flags & DOBUF_SKIPHELP ) != 0 && buf -> b_help ; 1357 1358bp = NULL ; 1359while ( 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. 1363if ( bp == NULL ) { 1364bp = buf ; 1365} 1366buf = 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. 1371if ( unload 1372|| ( help_only 1373? buf -> b_help 1374: ( buf -> b_p_bl && (( flags & DOBUF_SKIPHELP ) == 0 || ! buf -> b_help )))) { 1375count -- ; 1376bp = NULL ; // use this buffer as new starting point 1377} 1378if ( bp == buf ) { 1379// back where we started, didn't find anything. 1380emsg ( _ ( "E85: There is no listed buffer" )); 1381return FAIL ; 1382} 1383} 1384} 1385 1386if ( buf == NULL ) { // could not find it 1387if ( start == DOBUF_FIRST ) { 1388// don't warn when deleting 1389if (! unload ) { 1390semsg ( _ ( e_nobufnr ), ( int64_t ) count ); 1391} 1392} else if ( dir == FORWARD ) { 1393emsg ( _ ( "E87: Cannot go beyond last buffer" )); 1394} else { 1395emsg ( _ ( "E88: Cannot go before first buffer" )); 1396} 1397return FAIL ; 1398} 1399 1400if ( 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 1403return FAIL ; 1404} 1405 1406if (( action == DOBUF_GOTO || action == DOBUF_SPLIT ) && ( buf -> b_flags & BF_DUMMY )) { 1407// disallow navigating to the dummy buffer 1408semsg ( _ ( e_nobufnr ), count ); 1409return FAIL ; 1410} 1411 1412// delete buffer "buf" from memory and/or the list 1413if ( unload ) { 1414int forward ; 1415bufref_T bufref ; 1416if (! can_unload_buffer ( buf )) { 1417return FAIL ; 1418} 1419set_bufref ( & bufref , buf ); 1420 1421// When unloading or deleting a buffer that's already unloaded and 1422// unlisted: fail silently. 1423if ( action != DOBUF_WIPE && buf -> b_ml . ml_mfp == NULL && ! buf -> b_p_bl ) { 1424return FAIL ; 1425} 1426 1427if (( flags & DOBUF_FORCEIT ) == 0 && bufIsChanged ( buf )) { 1428if (( p_confirm || ( cmdmod . cmod_flags & CMOD_CONFIRM )) && p_write ) { 1429dialog_changed ( buf , false); 1430if (! bufref_valid ( & bufref )) { 1431// Autocommand deleted buffer, oops! It's not changed now. 1432return FAIL ; 1433} 1434// If it's still changed fail silently, the dialog already 1435// mentioned why it fails. 1436if ( bufIsChanged ( buf )) { 1437return FAIL ; 1438} 1439} else { 1440semsg ( _ ( e_no_write_since_last_change_for_buffer_nr_add_bang_to_override ), 1441buf -> b_fnum ); 1442return FAIL ; 1443} 1444} 1445 1446if (!( flags & DOBUF_FORCEIT ) && buf -> terminal && terminal_running ( buf -> terminal )) { 1447if ( p_confirm || ( cmdmod . cmod_flags & CMOD_CONFIRM )) { 1448if (! dialog_close_terminal ( buf )) { 1449return FAIL ; 1450} 1451} else { 1452semsg ( _ ( "E89: %s will be killed (add ! to override)" ), buf -> b_fname ); 1453return FAIL ; 1454} 1455} 1456 1457int buf_fnum = buf -> b_fnum ; 1458 1459// When closing the current buffer stop Visual mode. 1460if ( buf == curbuf && Visual . active ) { 1461end_visual_mode (); 1462} 1463 1464// If deleting the last (listed) buffer, make it empty. 1465// The last (listed) buffer cannot be unloaded. 1466bp = NULL ; 1467FOR_ALL_BUFFERS ( bp2 ) { 1468if ( bp2 -> b_p_bl && bp2 != buf ) { 1469bp = bp2 ; 1470break; 1471} 1472} 1473if ( bp == NULL && buf == curbuf ) { 1474return 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. 1481while ( buf == curbuf 1482&& !( win_locked ( curwin ) || curwin -> w_buffer -> b_locked > 0 ) 1483&& ( is_ctx_win ( lastwin ) || ! last_window ( curwin ))) { 1484if ( win_close ( curwin , false, false) == FAIL ) { 1485break; 1486} 1487} 1488 1489// If the buffer to be deleted is not the current one, delete it here. 1490if ( buf != curbuf ) { 1491if ( jop_flags & kOptJopFlagClean ) { 1492// Remove the buffer to be deleted from the jump list. 1493mark_jumplist_forget_file ( curwin , buf_fnum ); 1494} 1495 1496close_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. 1499if ( 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. 1505assert ( curwin -> w_floating ); 1506CtxSwitch switchwin ; 1507const bool rv = ctx_switch ( & switchwin , firstwin , curtab , NULL , kCtxNoDisplay ); 1508assert ( rv ); 1509( void ) rv ; 1510// retry (recurse) 1511do_buffer_ext ( action , start , dir , count , flags ); 1512ctx_restore ( & switchwin ); 1513} 1514 1515if ( buf != curbuf && bufref_valid ( & bufref ) && buf -> b_nwindows <= 0 ) { 1516close_buffer ( NULL , buf , action , false, false, false); 1517} 1518return 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. 1529buf = NULL ; // Selected buffer. 1530bp = NULL ; // Used when no loaded buffer found. 1531if ( au_new_curbuf . br_buf != NULL && bufref_valid ( & au_new_curbuf ) 1532&& ! au_new_curbuf . br_buf -> b_locked_split ) { 1533buf = au_new_curbuf . br_buf ; 1534} else if ( curwin -> w_jumplistlen > 0 ) { 1535if ( jop_flags & kOptJopFlagClean ) { 1536// Remove the buffer from the jump list. 1537mark_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 1542if ( curwin -> w_jumplistlen > 0 ) { 1543int jumpidx = curwin -> w_jumplistidx ; 1544 1545if ( 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. 1548if ( jumpidx == curwin -> w_jumplistlen ) { 1549jumpidx = curwin -> w_jumplistidx = curwin -> w_jumplistlen - 1 ; 1550} 1551} else { 1552jumpidx -- ; 1553if ( jumpidx < 0 ) { 1554jumpidx = curwin -> w_jumplistlen - 1 ; 1555} 1556} 1557 1558forward = jumpidx ; 1559while (( jop_flags & kOptJopFlagClean ) || jumpidx != curwin -> w_jumplistidx ) { 1560buf = buflist_findnr ( curwin -> w_jumplist [ jumpidx ]. fmark . fnum ); 1561 1562if ( buf != NULL ) { 1563// Skip current and unlisted bufs. Also skip a quickfix 1564// or closing buffer, it might be deleted soon. 1565if ( buf == curbuf || ! buf -> b_p_bl || bt_quickfix ( buf ) 1566|| buf -> b_locked_split ) { 1567buf = NULL ; 1568} else if ( buf -> b_ml . ml_mfp == NULL ) { 1569// skip unloaded buf, but may keep it for later 1570if ( bp == NULL ) { 1571bp = buf ; 1572} 1573buf = NULL ; 1574} 1575} 1576if ( buf != NULL ) { // found a valid buffer: stop searching 1577if ( jop_flags & kOptJopFlagClean ) { 1578curwin -> w_jumplistidx = jumpidx ; 1579update_jumplist = false; 1580} 1581break; 1582} 1583// advance to older entry in jump list 1584if (! jumpidx && curwin -> w_jumplistidx == curwin -> w_jumplistlen ) { 1585break; 1586} 1587if ( -- jumpidx < 0 ) { 1588jumpidx = curwin -> w_jumplistlen - 1 ; 1589} 1590if ( jumpidx == forward ) { // List exhausted for sure 1591break; 1592} 1593} 1594} 1595} 1596 1597if ( buf == NULL ) { // No previous buffer, Try 2'nd approach 1598forward = true; 1599buf = curbuf -> b_next ; 1600while (true) { 1601if ( buf == NULL ) { 1602if (! forward ) { // tried both directions 1603break; 1604} 1605buf = curbuf -> b_prev ; 1606forward = false; 1607continue; 1608} 1609// in non-help buffer, try to skip help buffers, and vv 1610if ( buf -> b_help == curbuf -> b_help && buf -> b_p_bl 1611&& ! bt_quickfix ( buf ) && ! buf -> b_locked_split ) { 1612if ( buf -> b_ml . ml_mfp != NULL ) { // found loaded buffer 1613break; 1614} 1615if ( bp == NULL ) { // remember unloaded buf for later 1616bp = buf ; 1617} 1618} 1619buf = forward ? buf -> b_next : buf -> b_prev ; 1620} 1621} 1622if ( buf == NULL ) { // No loaded buffer, use unloaded one 1623buf = bp ; 1624} 1625if ( buf == NULL ) { // No loaded buffer, find listed one 1626FOR_ALL_BUFFERS ( buf2 ) { 1627if ( buf2 -> b_p_bl && buf2 != curbuf && ! bt_quickfix ( buf2 ) && ! buf2 -> b_locked_split ) { 1628buf = buf2 ; 1629break; 1630} 1631} 1632} 1633if ( buf == NULL ) { // Still no buffer, just take one 1634buf = curbuf -> b_next != NULL ? curbuf -> b_next : curbuf -> b_prev ; 1635if ( bt_quickfix ( buf ) || ( buf != NULL && buf != curbuf && buf -> b_locked_split )) { 1636buf = NULL ; 1637} 1638} 1639} 1640 1641if ( buf == NULL ) { 1642// Autocommands must have wiped out all other buffers. Only option 1643// now is to make the current buffer empty. 1644return 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". 1649if ( action == DOBUF_SPLIT && swbuf_goto_win_with_buf ( buf ) != NULL ) { 1650return OK ; 1651} 1652// Whether splitting or not, don't open a closing buffer in more windows. 1653if ( buf != curbuf && buf -> b_locked_split ) { 1654emsg ( _ ( e_cannot_switch_to_a_closing_buffer )); 1655return FAIL ; 1656} 1657if ( action == DOBUF_SPLIT && win_split ( 0 , 0 ) == FAIL ) { // split window first 1658return FAIL ; 1659} 1660 1661// go to current buffer - nothing to do 1662if ( buf == curbuf ) { 1663return OK ; 1664} 1665 1666// Check if the current buffer may be abandoned. 1667if ( action == DOBUF_GOTO && ! can_abandon ( curbuf , ( flags & DOBUF_FORCEIT ))) { 1668if (( p_confirm || ( cmdmod . cmod_flags & CMOD_CONFIRM )) && p_write ) { 1669bufref_T bufref ; 1670set_bufref ( & bufref , buf ); 1671dialog_changed ( curbuf , false); 1672if (! bufref_valid ( & bufref )) { 1673// Autocommand deleted buffer, oops! 1674return FAIL ; 1675} 1676} 1677if ( bufIsChanged ( curbuf )) { 1678no_write_message (); 1679return FAIL ; 1680} 1681} 1682 1683// Go to the other buffer. 1684set_curbuf ( buf , action , update_jumplist ); 1685 1686if ( action == DOBUF_SPLIT ) { 1687RESET_BINDING ( curwin ); // reset 'scrollbind' and 'cursorbind' 1688} 1689 1690if ( aborting ()) { // autocmds may abort script processing 1691return FAIL ; 1692} 1693 1694return OK ; 1695} 1696 1697int do_buffer ( int action , int start , int dir , int count , int forceit ) 1698{ 1699return 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{ 1713buf_T * prevbuf ; 1714int unload = ( action == DOBUF_UNLOAD || action == DOBUF_DEL 1715|| action == DOBUF_WIPE ); 1716OptInt old_tw = curbuf -> b_p_tw ; 1717 1718if ( update_jumplist ) { 1719setpcmark (); 1720} 1721 1722if (( cmdmod . cmod_flags & CMOD_KEEPALT ) == 0 ) { 1723curwin -> w_alt_fnum = curbuf -> b_fnum ; // remember alternate file 1724} 1725buflist_altfpos ( curwin ); // remember curpos 1726 1727// Don't restart Select mode after switching to another buffer. 1728Visual . reselect = false; 1729 1730// close_windows() or apply_autocmds() may change curbuf and wipe out "buf" 1731prevbuf = curbuf ; 1732bufref_T newbufref ; 1733bufref_T prevbufref ; 1734set_bufref ( & prevbufref , prevbuf ); 1735set_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. 1739if (! apply_autocmds ( EVENT_BUFLEAVE , NULL , NULL , false, curbuf ) 1740|| ( bufref_valid ( & prevbufref ) && bufref_valid ( & newbufref ) 1741&& ! aborting ())) { 1742if ( prevbuf == curwin -> w_buffer ) { 1743reset_synblock ( curwin ); 1744} 1745if ( unload ) { 1746close_windows ( prevbuf , false); 1747} 1748if ( 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. 1752if ( prevbuf == curbuf && (( State & MODE_INSERT ) == 0 || curbuf -> b_nwindows <= 1 )) { 1753u_sync (false); 1754} 1755close_buffer ( curwin , 1756prevbuf , 1757unload 1758? action 1759: ( action == DOBUF_GOTO && ! buf_hide ( prevbuf ) 1760&& ! bufIsChanged ( prevbuf )) ? DOBUF_UNLOAD : 0 , 1761false, 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 1767bool valid = buf_valid ( buf ); 1768if (( 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. 1771enter_buffer ( valid ? buf : lastbuf ); 1772if ( old_tw != curbuf -> b_p_tw ) { 1773check_colorcolumn ( NULL , curwin ); 1774} 1775} 1776 1777if ( bufref_valid ( & prevbufref ) && prevbuf -> terminal != NULL ) { 1778terminal_check_size ( prevbuf -> terminal ); 1779} 1780 1781// Maybe cd to buffer-local directory 1782update_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! 1792if ( Visual . active 1793#ifdef EXITFREE 1794&& ! entered_free_all_mem 1795#endif 1796) { 1797end_visual_mode (); 1798} 1799 1800if ( curwin -> w_buffer != NULL ) { 1801curwin -> w_buffer -> b_nwindows -- ; 1802} 1803 1804// Get the buffer in the current window. 1805curwin -> w_buffer = buf ; 1806curbuf = buf ; 1807curbuf -> b_nwindows ++ ; 1808 1809// Copy buffer and window local option values. Not for a help buffer. 1810buf_copy_options ( buf , BCO_ENTER | BCO_NOHELP ); 1811if (! buf -> b_help ) { 1812get_winopts ( buf ); 1813} else { 1814// Remove all folds in the window. 1815clearFolding ( curwin ); 1816} 1817foldUpdateAll ( curwin ); // update folds (later). 1818 1819if ( curwin -> w_p_diff ) { 1820diff_buf_add ( curbuf ); 1821} 1822 1823curwin -> w_s = & ( curbuf -> b_s ); 1824 1825// Cursor on first line by default. 1826curwin -> w_cursor . lnum = 1 ; 1827curwin -> w_cursor . col = 0 ; 1828curwin -> w_cursor . coladd = 0 ; 1829curwin -> w_set_curswant = true; 1830curwin -> w_topline_was_set = false; 1831 1832// mark cursor position as being invalid 1833curwin -> w_valid = 0 ; 1834 1835// Make sure the buffer is loaded. 1836if ( 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. 1840if ( * curbuf -> b_p_ft == NUL ) { 1841curbuf -> b_did_filetype = false; 1842} 1843 1844open_buffer (false, NULL , 0 ); 1845} else { 1846if (! msg_silent && ! shortmess ( kShmFileinfo )) { 1847need_fileinfo = true; // display file info after redraw 1848} 1849// check if file changed 1850buf_check_timestamp ( curbuf ); 1851 1852curwin -> w_topline = 1 ; 1853curwin -> w_topfill = 0 ; 1854apply_autocmds ( EVENT_BUFENTER , NULL , NULL , false, curbuf ); 1855apply_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. 1860if ( curwin -> w_cursor . lnum == 1 && inindent ( 0 )) { 1861buflist_getfpos (); 1862} 1863 1864check_arg_idx ( curwin ); // check for valid arg_idx 1865maketitle (); 1866win_float_update_preview ( curwin ); 1867// when autocmds didn't change it 1868if ( curwin -> w_topline == 1 && ! curwin -> w_topline_was_set ) { 1869scroll_cursor_halfway ( curwin , false, false); // redisplay at correct position 1870} 1871 1872// Change directories when the 'acd' option is set. 1873do_autochdir (); 1874 1875if ( curbuf -> b_kmap_state & KEYMAP_INIT ) { 1876keymap_init (); 1877} 1878// May need to set the spell language. Can only do this after the buffer 1879// has been properly setup. 1880if (! curbuf -> b_help && curwin -> w_p_spell && * curwin -> w_s -> b_p_spl != NUL ) { 1881parse_spelllang ( curwin ); 1882} 1883curbuf -> b_last_used = time ( NULL ); 1884 1885if ( curbuf -> terminal != NULL ) { 1886terminal_check_size ( curbuf -> terminal ); 1887} 1888 1889redraw_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{ 1896if ( p_acd ) { 1897if ( starting == 0 1898&& curbuf -> b_ffname != NULL 1899&& vim_chdirfile ( curbuf -> b_ffname , kCdCauseAuto ) == OK ) { 1900last_chdir_reason = "autochdir" ; 1901shorten_fnames (true); 1902} 1903} 1904} 1905 1906void no_write_message_buf ( buf_T * buf ) 1907{ 1908if ( buf -> terminal 1909&& channel_job_running (( uint64_t ) buf -> b_p_channel )) { 1910emsg ( _ ( e_job_still_running_add_bang_to_end_the_job )); 1911} else { 1912semsg ( _ ( e_no_write_since_last_change_for_buffer_nr_add_bang_to_override ), 1913buf -> b_fnum ); 1914} 1915} 1916 1917void no_write_message ( void ) 1918{ 1919if ( curbuf -> terminal 1920&& channel_job_running (( uint64_t ) curbuf -> b_p_channel )) { 1921emsg ( _ ( e_job_still_running_add_bang_to_end_the_job )); 1922} else { 1923emsg ( _ ( e_no_write_since_last_change_add_bang_to_override )); 1924} 1925} 1926 1927void no_write_message_nobang (const buf_T * const buf ) 1928FUNC_ATTR_NONNULL_ALL 1929{ 1930if ( buf -> terminal 1931&& channel_job_running (( uint64_t ) buf -> b_p_channel )) { 1932emsg ( _ ( e_job_still_running )); 1933} else { 1934emsg ( _ ( 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 ) 1946FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL 1947{ 1948STATIC_ASSERT (sizeof( "changedtick" ) <= sizeof( buf -> changedtick_di . di_key ), 1949"buf->changedtick_di cannot hold large enough keys" ); 1950buf -> 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}; 1959tv_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{ 1982char * ffname = ffname_arg ; 1983char * sfname = sfname_arg ; 1984buf_T * buf ; 1985 1986fname_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. 1992FileID file_id ; 1993bool file_id_valid = ( sfname != NULL && os_fileid ( sfname , & file_id )); 1994if ( ffname != NULL && !( flags & ( BLN_DUMMY | BLN_NEW )) 1995&& ( buf = buflist_findname_file_id ( ffname , & file_id , file_id_valid )) != NULL ) { 1996xfree ( ffname ); 1997if ( lnum != 0 ) { 1998buflist_setfpos ( buf , ( flags & BLN_NOCURWIN ) ? NULL : curwin , 1999lnum , 0 , false); 2000} 2001if (( flags & BLN_NOOPT ) == 0 ) { 2002// Copy the options now, if 'cpo' doesn't have 's' and not done already. 2003buf_copy_options ( buf , 0 ); 2004} 2005if (( flags & BLN_LISTED ) && ! buf -> b_p_bl ) { 2006buf -> b_p_bl = true; 2007bufref_T bufref ; 2008set_bufref ( & bufref , buf ); 2009if (!( flags & BLN_DUMMY )) { 2010if ( apply_autocmds ( EVENT_BUFADD , NULL , NULL , false, buf ) 2011&& ! bufref_valid ( & bufref )) { 2012return NULL ; 2013} 2014} 2015} 2016return 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.) 2025buf = NULL ; 2026if (( flags & BLN_CURBUF ) && curbuf_reusable ()) { 2027bufref_T bufref ; 2028 2029assert ( curbuf != NULL ); 2030buf = curbuf ; 2031set_bufref ( & bufref , buf ); 2032trigger_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. 2035buf_freeall ( buf , BFA_WIPE | BFA_DEL ); 2036if ( aborting ()) { // autocmds may abort script processing 2037xfree ( ffname ); 2038return NULL ; 2039} 2040if (! bufref_valid ( & bufref )) { 2041buf = NULL ; // buf was deleted; allocate a new buffer 2042} 2043} 2044if ( buf != curbuf || curbuf == NULL ) { 2045buf = xcalloc ( 1 , sizeof( buf_T )); 2046// init b: variables 2047buf -> b_vars = tv_dict_alloc (); 2048init_var_dict ( buf -> b_vars , & buf -> b_bufvar , VAR_SCOPE ); 2049buf_init_changedtick ( buf ); 2050} 2051 2052if ( ffname != NULL ) { 2053assert ( sfname != NULL ); 2054buf -> b_ffname = ffname ; 2055buf -> b_sfname = xstrdup ( sfname ); 2056TO_SLASH ( buf -> b_sfname ); 2057} 2058 2059clear_wininfo ( buf ); 2060WinInfo * curwin_info = xcalloc ( 1 , sizeof( WinInfo )); 2061kv_push ( buf -> b_wininfo , curwin_info ); 2062 2063if ( buf == curbuf ) { 2064free_buffer_stuff ( buf , kBffInitChangedtick ); // delete local vars et al. 2065 2066// Init the options. 2067buf -> b_p_initialized = false; 2068buf_copy_options ( buf , BCO_ENTER ); 2069 2070// need to reload lmaps and set b:keymap_name 2071curbuf -> b_kmap_state |= KEYMAP_INIT ; 2072} else { 2073// put new buffer at the end of the buffer list 2074buf -> b_next = NULL ; 2075if ( firstbuf == NULL ) { // buffer list is empty 2076buf -> b_prev = NULL ; 2077firstbuf = buf ; 2078} else { // append new buffer at end of list 2079lastbuf -> b_next = buf ; 2080buf -> b_prev = lastbuf ; 2081} 2082lastbuf = buf ; 2083 2084buf -> b_fnum = top_file_num ++ ; 2085pmap_put ( int )( & buffer_handles , buf -> b_fnum , buf ); 2086if ( top_file_num < 0 ) { // wrap around (may cause duplicates) 2087emsg ( _ ( "W14: Warning: List of file names overflow" )); 2088if ( emsg_silent == 0 && ! in_assert_fails ) { 2089msg_delay ( 3001 , true); // make sure it is noticed 2090} 2091top_file_num = 1 ; 2092} 2093 2094// Always copy the options from the current buffer. 2095buf_copy_options ( buf , BCO_ALWAYS ); 2096} 2097 2098curwin_info -> wi_mark = ( fmark_T ) INIT_FMARK ; 2099curwin_info -> wi_mark . mark . lnum = lnum ; 2100curwin_info -> wi_win = curwin ; 2101 2102hash_init ( & buf -> b_s . b_keywtab ); 2103hash_init ( & buf -> b_s . b_keywtab_ic ); 2104 2105buf -> b_fname = buf -> b_sfname ; 2106if (! file_id_valid ) { 2107buf -> file_id_valid = false; 2108} else { 2109buf -> file_id_valid = true; 2110buf -> file_id = file_id ; 2111} 2112buf -> b_u_synced = true; 2113buf -> b_flags = BF_CHECK_RO | BF_NEVERLOADED ; 2114if ( flags & BLN_DUMMY ) { 2115buf -> b_flags |= BF_DUMMY ; 2116} 2117buf_clear_file ( buf ); 2118clrallmarks ( buf , 0 ); // clear marks 2119fmarks_check_names ( buf ); // check file marks for this file 2120buf -> b_p_bl = ( flags & BLN_LISTED ) ? true : false; // init 'buflisted' 2121kv_destroy ( buf -> update_channels ); 2122kv_init ( buf -> update_channels ); 2123kv_destroy ( buf -> update_callbacks ); 2124kv_init ( buf -> update_callbacks ); 2125if (!( 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. 2129bufref_T bufref ; 2130set_bufref ( & bufref , buf ); 2131if ( apply_autocmds ( EVENT_BUFNEW , NULL , NULL , false, buf ) 2132&& ! bufref_valid ( & bufref )) { 2133return NULL ; 2134} 2135if (( flags & BLN_LISTED ) 2136&& apply_autocmds ( EVENT_BUFADD , NULL , NULL , false, buf ) 2137&& ! bufref_valid ( & bufref )) { 2138return NULL ; 2139} 2140if ( aborting ()) { 2141// Autocmds may abort script processing. 2142return NULL ; 2143} 2144} 2145 2146buf -> b_prompt_callback . type = kCallbackNone ; 2147buf -> b_prompt_interrupt . type = kCallbackNone ; 2148buf -> b_prompt_text = NULL ; 2149buf -> b_prompt_start = ( fmark_T ) INIT_FMARK ; 2150buf -> b_prompt_start . mark . col = 2 ; // default prompt is "% " 2151buf -> b_prompt_append_new_line = true; 2152 2153return 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{ 2160return ( 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{ 2174if ( free_p_ff ) { 2175clear_string_option ( & buf -> b_p_fenc ); 2176clear_string_option ( & buf -> b_p_ff ); 2177clear_string_option ( & buf -> b_p_bh ); 2178clear_string_option ( & buf -> b_p_bt ); 2179} 2180clear_string_option ( & buf -> b_p_def ); 2181clear_string_option ( & buf -> b_p_inc ); 2182callback_free ( & buf -> b_p_inex ); 2183callback_free ( & buf -> b_p_inde ); 2184clear_string_option ( & buf -> b_p_indk ); 2185clear_string_option ( & buf -> b_p_fp ); 2186callback_free ( & buf -> b_p_fex ); 2187clear_string_option ( & buf -> b_p_kp ); 2188clear_string_option ( & buf -> b_p_mps ); 2189clear_string_option ( & buf -> b_p_fo ); 2190clear_string_option ( & buf -> b_p_flp ); 2191clear_string_option ( & buf -> b_p_isk ); 2192clear_string_option ( & buf -> b_p_vsts ); 2193XFREE_CLEAR ( buf -> b_p_vsts_nopaste ); 2194XFREE_CLEAR ( buf -> b_p_vsts_array ); 2195clear_string_option ( & buf -> b_p_vts ); 2196XFREE_CLEAR ( buf -> b_p_vts_array ); 2197clear_string_option ( & buf -> b_p_keymap ); 2198keymap_ga_clear ( & buf -> b_kmap_ga ); 2199ga_clear ( & buf -> b_kmap_ga ); 2200clear_string_option ( & buf -> b_p_com ); 2201clear_string_option ( & buf -> b_p_cms ); 2202clear_string_option ( & buf -> b_p_nf ); 2203clear_string_option ( & buf -> b_p_syn ); 2204clear_string_option ( & buf -> b_s . b_syn_isk ); 2205clear_string_option ( & buf -> b_s . b_p_spc ); 2206clear_string_option ( & buf -> b_s . b_p_spf ); 2207vim_regfree ( buf -> b_s . b_cap_prog ); 2208buf -> b_s . b_cap_prog = NULL ; 2209clear_string_option ( & buf -> b_s . b_p_spl ); 2210clear_string_option ( & buf -> b_s . b_p_spo ); 2211clear_string_option ( & buf -> b_p_sua ); 2212clear_string_option ( & buf -> b_p_ft ); 2213clear_string_option ( & buf -> b_p_cink ); 2214clear_string_option ( & buf -> b_p_cino ); 2215clear_string_option ( & buf -> b_p_lop ); 2216clear_string_option ( & buf -> b_p_cinsd ); 2217clear_string_option ( & buf -> b_p_cinw ); 2218clear_string_option ( & buf -> b_p_cot ); 2219clear_string_option ( & buf -> b_p_cpt ); 2220#ifdef BACKSLASH_IN_FILENAME 2221clear_string_option ( & buf -> b_p_csl ); 2222#endif 2223callback_free ( & buf -> b_p_cfu ); 2224callback_free ( & buf -> b_p_ofu ); 2225callback_free ( & buf -> b_p_tsrfu ); 2226clear_cpt_callbacks ( & buf -> b_p_cpt_cb , buf -> b_p_cpt_count ); 2227buf -> b_p_cpt_count = 0 ; 2228clear_string_option ( & buf -> b_p_gefm ); 2229clear_string_option ( & buf -> b_p_gp ); 2230clear_string_option ( & buf -> b_p_mp ); 2231clear_string_option ( & buf -> b_p_efm ); 2232clear_string_option ( & buf -> b_p_ep ); 2233clear_string_option ( & buf -> b_p_path ); 2234clear_string_option ( & buf -> b_p_tags ); 2235clear_string_option ( & buf -> b_p_tc ); 2236callback_free ( & buf -> b_p_tfu ); 2237callback_free ( & buf -> b_p_ffu ); 2238clear_string_option ( & buf -> b_p_dict ); 2239clear_string_option ( & buf -> b_p_dia ); 2240clear_string_option ( & buf -> b_p_tsr ); 2241clear_string_option ( & buf -> b_p_qe ); 2242buf -> b_p_ac = -1 ; 2243buf -> b_p_ar = -1 ; 2244buf -> b_p_fs = -1 ; 2245buf -> b_p_ul = NO_LOCAL_UNDOLEVEL ; 2246clear_string_option ( & buf -> b_p_lw ); 2247clear_string_option ( & buf -> b_p_bkc ); 2248clear_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{ 2261win_T * wp = NULL ; 2262fmark_T * fm = NULL ; 2263 2264buf_T * buf = buflist_findnr ( n ); 2265if ( buf == NULL ) { 2266if (( options & GETF_ALT ) && n == 0 ) { 2267emsg ( _ ( e_noalt )); 2268} else { 2269semsg ( _ ( e_buffer_nr_not_found ), n ); 2270} 2271return FAIL ; 2272} 2273 2274// if alternate file is the current buffer, nothing to do 2275if ( buf == curbuf ) { 2276return OK ; 2277} 2278 2279if ( text_or_buf_locked ()) { 2280return FAIL ; 2281} 2282 2283colnr_T col ; 2284bool restore_view = false; 2285// altfpos may be changed by getfile(), get it now 2286if ( lnum == 0 ) { 2287fm = buflist_findfmark ( buf ); 2288lnum = fm -> mark . lnum ; 2289col = fm -> mark . col ; 2290restore_view = true; 2291} else { 2292col = 0 ; 2293} 2294 2295if ( options & GETF_SWITCH ) { 2296// If 'switchbuf' is set jump to the window containing "buf". 2297wp = 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 2301if ( wp == NULL && ( swb_flags & ( kOptSwbFlagVsplit | kOptSwbFlagSplit | kOptSwbFlagNewtab )) 2302&& ! buf_is_empty ( curbuf )) { 2303if ( swb_flags & kOptSwbFlagNewtab ) { 2304tabpage_new (); 2305} else if ( win_split ( 0 , ( swb_flags & kOptSwbFlagVsplit ) ? WSP_VERT : 0 ) 2306== FAIL ) { 2307return FAIL ; 2308} 2309RESET_BINDING ( curwin ); 2310} 2311} 2312 2313RedrawingDisabled ++ ; 2314if ( GETFILE_SUCCESS ( getfile ( buf -> b_fnum , NULL , NULL , 2315( options & GETF_SETMARK ), lnum , forceit ))) { 2316RedrawingDisabled -- ; 2317 2318// cursor is at to BOL and w_cursor.lnum is checked due to getfile() 2319if (! p_sol && col != 0 ) { 2320curwin -> w_cursor . col = col ; 2321check_cursor_col ( curwin ); 2322curwin -> w_cursor . coladd = 0 ; 2323curwin -> w_set_curswant = true; 2324} 2325if ( jop_flags & kOptJopFlagView && restore_view ) { 2326mark_view_restore ( fm ); 2327} 2328return OK ; 2329} 2330RedrawingDisabled -- ; 2331return FAIL ; 2332} 2333 2334/// Go to the last known line number for the current buffer. 2335static void buflist_getfpos ( void ) 2336{ 2337fmark_T * fm = buflist_findfmark ( curbuf ); 2338const pos_T * fpos = & fm -> mark ; 2339 2340curwin -> w_cursor . lnum = fpos -> lnum ; 2341check_cursor_lnum ( curwin ); 2342 2343if ( p_sol ) { 2344curwin -> w_cursor . col = 0 ; 2345} else { 2346curwin -> w_cursor . col = fpos -> col ; 2347check_cursor_col ( curwin ); 2348curwin -> w_cursor . coladd = 0 ; 2349curwin -> w_set_curswant = true; 2350} 2351 2352if ( jop_flags & kOptJopFlagView ) { 2353mark_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{ 2362buf_T * buf = NULL ; 2363 2364// First make the name into a full path name 2365char * ffname = FullName_save ( fname , 2366#ifdef UNIX 2367// force expansion, get rid of symbolic links 2368true 2369#else 2370false 2371#endif 2372); 2373if ( ffname != NULL ) { 2374buf = buflist_findname ( ffname ); 2375xfree ( ffname ); 2376} 2377return 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{ 2387FileID file_id ; 2388bool file_id_valid = os_fileid ( ffname , & file_id ); 2389return 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 ) 2397FUNC_ATTR_PURE 2398{ 2399// Start at the last buffer, expect to find a match sooner. 2400FOR_ALL_BUFFERS_BACKWARDS ( buf ) { 2401if (( buf -> b_flags & BF_DUMMY ) == 0 2402&& ! otherfile_buf ( buf , ffname , file_id , file_id_valid )) { 2403return buf ; 2404} 2405} 2406return 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 , 2418bool curtab_only ) 2419FUNC_ATTR_NONNULL_ARG ( 1 ) 2420{ 2421int match = -1 ; 2422 2423if ( pattern_end == pattern + 1 && ( * pattern == '%' || * pattern == '#' )) { 2424match = * pattern == '%' ? curbuf -> b_fnum : curwin -> w_alt_fnum ; 2425buf_T * found_buf = buflist_findnr ( match ); 2426if ( diffmode && !( found_buf && diff_mode_buf ( found_buf ))) { 2427match = -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 2438char * pat = file_pat_to_reg_pat ( pattern , pattern_end , NULL , false); 2439if ( pat == NULL ) { 2440return -1 ; 2441} 2442char * patend = pat + strlen ( pat ) - 1 ; 2443bool 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 2448int find_listed = true; 2449while (true) { 2450for ( int attempt = 0 ; attempt <= 3 ; attempt ++ ) { 2451// may add '^' and '$' 2452if ( toggledollar ) { 2453* patend = ( attempt < 2 ) ? NUL : '$' ; // add/remove '$' 2454} 2455char * p = pat ; 2456if ( * p == '^' && !( attempt & 1 )) { // add/remove '^' 2457p ++ ; 2458} 2459 2460regmatch_T regmatch ; 2461regmatch . regprog = vim_regcomp ( p , p_magic ? RE_MAGIC : 0 ); 2462 2463FOR_ALL_BUFFERS_BACKWARDS ( buf ) { 2464if ( regmatch . regprog == NULL ) { 2465// invalid pattern, possibly after switching engine 2466xfree ( pat ); 2467return -1 ; 2468} 2469if ( buf -> b_p_bl == find_listed 2470&& (! diffmode || diff_mode_buf ( buf )) 2471&& buflist_match ( & regmatch , buf , false) != NULL ) { 2472if ( curtab_only ) { 2473// Ignore the match if the buffer is not open in 2474// the current tab. 2475bool found_window = false; 2476FOR_ALL_WINDOWS_IN_TAB ( wp , curtab ) { 2477if ( wp -> w_buffer == buf ) { 2478found_window = true; 2479break; 2480} 2481} 2482if (! found_window ) { 2483continue; 2484} 2485} 2486if ( match >= 0 ) { // already found a match 2487match = -2 ; 2488break; 2489} 2490match = buf -> b_fnum ; // remember first match 2491} 2492} 2493 2494vim_regfree ( regmatch . regprog ); 2495if ( match >= 0 ) { // found one match 2496break; 2497} 2498} 2499 2500// Only search for unlisted buffers if there was no match with 2501// a listed buffer. 2502if (! unlisted || ! find_listed || match != -1 ) { 2503break; 2504} 2505find_listed = false; 2506} 2507 2508xfree ( pat ); 2509} 2510 2511if ( match == -2 ) { 2512semsg ( _ ( "E93: More than one match for %s" ), pattern ); 2513} else if ( match < 0 ) { 2514semsg ( _ ( "E94: No matching buffer for %s" ), pattern ); 2515} 2516return match ; 2517} 2518 2519typedef struct { 2520buf_T * buf ; 2521char * 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{ 2527buf_T * buf1 = * ( buf_T ** ) s1 ; 2528buf_T * buf2 = * ( buf_T ** ) s2 ; 2529 2530if ( buf1 -> b_last_used == buf2 -> b_last_used ) { 2531return 0 ; 2532} 2533return 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{ 2542bufmatch_T * matches = NULL ; 2543bool to_free = false; 2544 2545* num_file = 0 ; // return values in case of FAIL 2546* file = NULL ; 2547 2548if (( options & BUF_DIFF_FILTER ) && ! curwin -> w_p_diff ) { 2549return FAIL ; 2550} 2551 2552const bool fuzzy = cmdline_fuzzy_complete ( pat ); 2553 2554char * patc = NULL ; 2555fuzmatch_str_T * fuzmatch = NULL ; 2556regmatch_T regmatch ; 2557 2558// Make a copy of "pat" and change "^" to "\(^\|[\/]\)" (if doing regular 2559// expression matching) 2560if (! fuzzy ) { 2561if ( * pat == '^' && pat [ 1 ] != NUL ) { 2562patc = xstrdup ( pat + 1 ); 2563to_free = true; 2564} else if ( * pat == '^' ) { 2565patc = "" ; 2566} else { 2567patc = pat ; 2568} 2569regmatch . regprog = vim_regcomp ( patc , RE_MAGIC ); 2570} 2571 2572int count = 0 ; 2573int score = 0 ; 2574// round == 1: Count the matches. 2575// round == 2: Build the array to keep the matches. 2576for ( int round = 1 ; round <= 2 ; round ++ ) { 2577count = 0 ; 2578FOR_ALL_BUFFERS ( buf ) { 2579if (! buf -> b_p_bl ) { // skip unlisted buffers 2580continue; 2581} 2582if ( options & BUF_DIFF_FILTER ) { 2583// Skip buffers not suitable for 2584// :diffget or :diffput completion. 2585if ( buf == curbuf || ! diff_mode_buf ( buf )) { 2586continue; 2587} 2588} 2589 2590char * p = NULL ; 2591if (! fuzzy ) { 2592if ( regmatch . regprog == NULL ) { 2593// invalid pattern, possibly after recompiling 2594if ( to_free ) { 2595xfree ( patc ); 2596} 2597return FAIL ; 2598} 2599p = buflist_match ( & regmatch , buf , p_wic ); 2600} else { 2601p = NULL ; 2602// first try matching with the short file name 2603if (( score = fuzzy_match_str ( buf -> b_sfname , pat )) != FUZZY_SCORE_NONE ) { 2604p = buf -> b_sfname ; 2605} 2606if ( p == NULL ) { 2607// next try matching with the full path file name 2608if (( score = fuzzy_match_str ( buf -> b_ffname , pat )) != FUZZY_SCORE_NONE ) { 2609p = buf -> b_ffname ; 2610} 2611} 2612} 2613 2614if ( p == NULL ) { 2615continue; 2616} 2617 2618if ( round == 1 ) { 2619count ++ ; 2620continue; 2621} 2622 2623if ( options & WILD_HOME_REPLACE ) { 2624p = home_replace_save ( buf , p ); 2625} else { 2626p = xstrdup ( p ); 2627} 2628 2629if (! fuzzy ) { 2630if ( matches != NULL ) { 2631matches [ count ]. buf = buf ; 2632matches [ count ]. match = p ; 2633count ++ ; 2634} else { 2635( * file )[ count ++ ] = p ; 2636} 2637} else { 2638fuzmatch [ count ]. idx = count ; 2639fuzmatch [ count ]. str = p ; 2640fuzmatch [ count ]. score = score ; 2641count ++ ; 2642} 2643} 2644if ( count == 0 ) { // no match found, break here 2645break; 2646} 2647if ( round == 1 ) { 2648if (! fuzzy ) { 2649* file = xmalloc (( size_t ) count * sizeof( ** file )); 2650if ( options & WILD_BUFLASTUSED ) { 2651matches = xmalloc (( size_t ) count * sizeof( * matches )); 2652} 2653} else { 2654fuzmatch = xmalloc (( size_t ) count * sizeof( fuzmatch_str_T )); 2655} 2656} 2657} 2658 2659if (! fuzzy ) { 2660vim_regfree ( regmatch . regprog ); 2661if ( to_free ) { 2662xfree ( patc ); 2663} 2664} 2665 2666if (! fuzzy ) { 2667if ( matches != NULL ) { 2668if ( count > 1 ) { 2669qsort ( 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 2673if ( matches [ 0 ]. buf == curbuf ) { 2674for ( int i = 1 ; i < count ; i ++ ) { 2675( * file )[ i - 1 ] = matches [ i ]. match ; 2676} 2677( * file )[ count - 1 ] = matches [ 0 ]. match ; 2678} else { 2679for ( int i = 0 ; i < count ; i ++ ) { 2680( * file )[ i ] = matches [ i ]. match ; 2681} 2682} 2683xfree ( matches ); 2684} 2685} else { 2686fuzzymatches_to_strmatches ( fuzmatch , file , count , false); 2687} 2688 2689* num_file = count ; 2690return 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. 2700char * match = fname_match ( rmp , buf -> b_sfname , ignore_case ); 2701if ( match == NULL && rmp -> regprog != NULL ) { 2702match = fname_match ( rmp , buf -> b_ffname , ignore_case ); 2703} 2704return 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{ 2715char * match = NULL ; 2716 2717// extra check for valid arguments 2718if ( name == NULL || rmp -> regprog == NULL ) { 2719return NULL ; 2720} 2721 2722// Ignore case when 'fileignorecase' or the argument is set. 2723rmp -> rm_ic = p_fic || ignore_case ; 2724if ( vim_regexec ( rmp , name , 0 )) { 2725match = name ; 2726} else if ( rmp -> regprog != NULL ) { 2727// Replace $(HOME) with '~' and try matching again. 2728char * p = home_replace_save ( NULL , name ); 2729if ( vim_regexec ( rmp , p , 0 )) { 2730match = name ; 2731} 2732xfree ( p ); 2733} 2734 2735return match ; 2736} 2737 2738/// Find a file in the buffer list by buffer number. 2739buf_T * buflist_findnr ( int nr ) 2740{ 2741if ( nr == 0 ) { 2742nr = curwin -> w_alt_fnum ; 2743} 2744 2745return 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{ 2757buf_T * buf = buflist_findnr ( n ); 2758if ( buf == NULL ) { 2759return NULL ; 2760} 2761return home_replace_save ( helptail ? buf : NULL , 2762fullname ? 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 , 2775bool copy_options ) 2776FUNC_ATTR_NONNULL_ARG ( 1 ) 2777{ 2778WinInfo * wip ; 2779 2780size_t i ; 2781for ( i = 0 ; i < kv_size ( buf -> b_wininfo ); i ++ ) { 2782wip = kv_A ( buf -> b_wininfo , i ); 2783if ( wip -> wi_win == win ) { 2784break; 2785} 2786} 2787 2788if ( i == kv_size ( buf -> b_wininfo )) { 2789// allocate a new entry 2790wip = xcalloc ( 1 , sizeof( WinInfo )); 2791wip -> wi_win = win ; 2792if ( lnum == 0 ) { // set lnum even when it's 0 2793lnum = 1 ; 2794} 2795} else { 2796// remove the entry from the list 2797kv_shift ( buf -> b_wininfo , i , 1 ); 2798if ( copy_options && wip -> wi_optset ) { 2799clear_winopt ( & wip -> wi_opt ); 2800deleteFoldRecurse ( buf , & wip -> wi_folds ); 2801} 2802} 2803if ( lnum != 0 ) { 2804wip -> wi_mark . mark . lnum = lnum ; 2805wip -> wi_mark . mark . col = col ; 2806if ( win != NULL ) { 2807wip -> wi_mark . view = mark_view_make ( win , wip -> wi_mark . mark ); 2808} 2809} 2810if ( win != NULL ) { 2811wip -> wi_changelistidx = win -> w_changelistidx ; 2812} 2813if ( copy_options && win != NULL ) { 2814// Save the window-specific option values. 2815copy_winopt ( & win -> w_onebuf_opt , & wip -> wi_opt ); 2816wip -> wi_fold_manual = win -> w_fold_manual ; 2817cloneFoldGrowArray ( & win -> w_folds , & wip -> wi_folds ); 2818wip -> wi_optset = true; 2819} 2820 2821// insert the entry in front of the list 2822kv_pushp ( buf -> b_wininfo ); 2823memmove ( & 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 ))); 2825kv_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 ) 2831FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 2832{ 2833if (! wip -> wi_opt . wo_diff ) { 2834return false; 2835} 2836 2837FOR_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 2840if ( wip -> wi_win == wp ) { 2841return false; 2842} 2843} 2844return 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 ) 2855FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 2856{ 2857for ( size_t i = 0 ; i < kv_size ( buf -> b_wininfo ); i ++ ) { 2858WinInfo * wip = kv_A ( buf -> b_wininfo , i ); 2859if ( wip -> wi_win == curwin 2860&& (! skip_diff_buffer || ! wininfo_other_tab_diff ( wip )) 2861&& (! need_options || wip -> wi_optset )) { 2862return 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. 2871if ( skip_diff_buffer ) { 2872for ( size_t i = 0 ; i < kv_size ( buf -> b_wininfo ); i ++ ) { 2873WinInfo * wip = kv_A ( buf -> b_wininfo , i ); 2874if (! wininfo_other_tab_diff ( wip ) 2875&& (! need_options 2876|| wip -> wi_optset 2877|| ( wip -> wi_win != NULL 2878&& wip -> wi_win -> w_buffer == buf ))) { 2879return wip ; 2880} 2881} 2882} else if ( kv_size ( buf -> b_wininfo )) { 2883return kv_A ( buf -> b_wininfo , 0 ); 2884} 2885return 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{ 2894clear_winopt ( & curwin -> w_onebuf_opt ); 2895clearFolding ( curwin ); 2896 2897WinInfo * const wip = find_wininfo ( buf , true, true); 2898if ( 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 ) { 2901win_T * wp = wip -> wi_win ; 2902copy_winopt ( & wp -> w_onebuf_opt , & curwin -> w_onebuf_opt ); 2903curwin -> w_fold_manual = wp -> w_fold_manual ; 2904curwin -> w_foldinvalid = true; 2905cloneFoldGrowArray ( & 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 )) { 2909copy_winopt ( & wip -> wi_opt , & curwin -> w_onebuf_opt ); 2910curwin -> w_fold_manual = wip -> wi_fold_manual ; 2911curwin -> w_foldinvalid = true; 2912cloneFoldGrowArray ( & wip -> wi_folds , & curwin -> w_folds ); 2913} else { 2914copy_winopt ( & curwin -> w_allbuf_opt , & curwin -> w_onebuf_opt ); 2915} 2916if ( wip != NULL ) { 2917curwin -> w_changelistidx = wip -> wi_changelistidx ; 2918} 2919 2920if ( curwin -> w_config . style == kWinStyleMinimal ) { 2921didset_window_options ( curwin , false); 2922win_set_minimal_style ( curwin ); 2923} 2924 2925// Set 'foldlevel' to 'foldlevelstart' if it's not negative. 2926if ( p_fdls >= 0 ) { 2927curwin -> w_p_fdl = p_fdls ; 2928} 2929didset_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 ) 2936FUNC_ATTR_PURE 2937{ 2938static fmark_T no_position = { { 1 , 0 , 0 }, 0 , 0 , INIT_FMARKV , NULL }; 2939 2940WinInfo * const wip = find_wininfo ( buf , false, false); 2941return ( 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 ) 2946FUNC_ATTR_PURE 2947{ 2948return 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{ 2954buf_T * buf = firstbuf ; 2955 2956garray_T buflist ; 2957buf_T ** buflist_data = NULL ; 2958 2959msg_ext_set_kind ( "list_cmd" ); 2960if ( vim_strchr ( eap -> arg , 't' )) { 2961ga_init ( & buflist , sizeof( buf_T * ), 50 ); 2962for ( buf = firstbuf ; buf != NULL ; buf = buf -> b_next ) { 2963ga_grow ( & buflist , 1 ); 2964(( buf_T ** ) buflist . ga_data )[ buflist . ga_len ++ ] = buf ; 2965} 2966 2967qsort ( buflist . ga_data , ( size_t ) buflist . ga_len , 2968sizeof( buf_T * ), buf_time_compare ); 2969 2970buflist_data = ( buf_T ** ) buflist . ga_data ; 2971buf = * buflist_data ; 2972} 2973buf_T ** p = buflist_data ; 2974 2975for (; 2976buf != NULL && ! got_int ; 2977buf = buflist_data != NULL 2978? ( ++ p < buflist_data + buflist . ga_len ? * p : NULL ) : buf -> b_next ) { 2979const bool is_terminal = buf -> terminal ; 2980const bool job_running = buf -> terminal && terminal_running ( buf -> terminal ); 2981 2982// skip unspecified buffers 2983if ((! 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 ))) { 2999continue; 3000} 3001char * name = buf_spname ( buf ); 3002if ( name != NULL ) { 3003xstrlcpy ( NameBuff , name , MAXPATHL ); 3004} else { 3005home_replace ( buf , buf -> b_fname , NameBuff , MAXPATHL , true); 3006} 3007 3008if ( message_filtered ( NameBuff )) { 3009continue; 3010} 3011 3012const int changed_char = ( buf -> b_flags & BF_READERR ) 3013? 'x' 3014: ( bufIsChanged ( buf ) ? '+' : ' ' ); 3015int ro_char = ! MODIFIABLE ( buf ) ? '-' : ( buf -> b_p_ro ? '=' : ' ' ); 3016if ( buf -> terminal ) { 3017ro_char = terminal_running ( buf -> terminal ) ? 'R' : 'F' ; 3018} 3019 3020if (! ui_has ( kUIMessages ) || msg_col > 0 ) { 3021msg_putchar ( '\n' ); 3022} 3023int len = ( int ) vim_snprintf_safelen ( IObuff , IOSIZE - 20 , "%3d%c%c%c%c%c \"%s\"" , 3024buf -> b_fnum , 3025buf -> b_p_bl ? ' ' : 'u' , 3026buf == curbuf ? '%' 3027: ( curwin -> w_alt_fnum 3028== buf -> b_fnum ? '#' : ' ' ), 3029buf -> b_ml . ml_mfp == NULL ? ' ' 3030: ( buf -> b_nwindows 3031== 0 ? 'h' : 'a' ), 3032ro_char , 3033changed_char , 3034NameBuff ); 3035 3036len = MIN ( len , IOSIZE - 20 ); 3037 3038// put "line 999" in column 40 or after the file name 3039int i = 40 - vim_strsize ( IObuff ); 3040do { 3041IObuff [ len ++ ] = ' ' ; 3042} while ( -- i > 0 && len < IOSIZE - 18 ); 3043if ( vim_strchr ( eap -> arg , 't' ) && buf -> b_last_used ) { 3044undo_fmt_time ( IObuff + len , ( size_t )( IOSIZE - len ), buf -> b_last_used ); 3045} else { 3046vim_snprintf ( IObuff + len , ( size_t )( IOSIZE - len ), _ ( "line %" PRId64 ), 3047buf == curbuf ? ( int64_t ) curwin -> w_cursor . lnum : ( int64_t ) buflist_findlnum ( buf )); 3048} 3049 3050msg_outtrans ( IObuff , 0 , false); 3051line_breakcheck (); 3052} 3053 3054if ( buflist_data ) { 3055ga_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{ 3066buf_T * buf = buflist_findnr ( fnum ); 3067if ( buf == NULL || buf -> b_fname == NULL ) { 3068return FAIL ; 3069} 3070 3071* fname = buf -> b_fname ; 3072* lnum = buflist_findlnum ( buf ); 3073 3074return 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{ 3086char * ffname = ffname_arg ; 3087char * sfname = sfname_arg ; 3088buf_T * obuf = NULL ; 3089FileID file_id ; 3090bool file_id_valid = false; 3091 3092if ( ffname == NULL || * ffname == NUL ) { 3093// Removing the name. 3094if ( buf -> b_sfname != buf -> b_ffname ) { 3095XFREE_CLEAR ( buf -> b_sfname ); 3096} else { 3097buf -> b_sfname = NULL ; 3098} 3099XFREE_CLEAR ( buf -> b_ffname ); 3100} else { 3101fname_expand ( buf , & ffname , & sfname ); // will allocate ffname 3102if ( ffname == NULL ) { // out of memory 3103return 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 3109file_id_valid = os_fileid ( ffname , & file_id ); 3110if (!( buf -> b_flags & BF_DUMMY )) { 3111obuf = buflist_findname_file_id ( ffname , & file_id , file_id_valid ); 3112} 3113if ( obuf != NULL && obuf != buf ) { 3114bool in_use = false; 3115 3116// during startup a window may use a buffer that is not loaded yet 3117FOR_ALL_TAB_WINDOWS ( tab , win ) { 3118if ( win -> w_buffer == obuf ) { 3119in_use = true; 3120} 3121} 3122 3123// it's loaded or used in a window, fail 3124if ( obuf -> b_ml . ml_mfp != NULL || in_use ) { 3125if ( message ) { 3126emsg ( _ ( "E95: Buffer with this name already exists" )); 3127} 3128xfree ( ffname ); 3129return FAIL ; 3130} 3131// delete from the list 3132close_buffer ( NULL , obuf , DOBUF_WIPE , false, false, false); 3133} 3134sfname = xstrdup ( sfname ); 3135#ifdef CASE_INSENSITIVE_FILENAME 3136TO_SLASH ( sfname ); 3137path_fix_case ( sfname ); // set correct case for short file name 3138#endif 3139if ( buf -> b_sfname != buf -> b_ffname ) { 3140xfree ( buf -> b_sfname ); 3141} 3142xfree ( buf -> b_ffname ); 3143buf -> b_ffname = ffname ; 3144buf -> b_sfname = sfname ; 3145} 3146buf -> b_fname = buf -> b_sfname ; 3147if (! file_id_valid ) { 3148buf -> file_id_valid = false; 3149} else { 3150buf -> file_id_valid = true; 3151buf -> file_id = file_id ; 3152} 3153 3154buf_name_changed ( buf ); 3155return 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{ 3162buf_T * buf = buflist_findnr ( fnum ); 3163if ( buf == NULL ) { 3164return; 3165} 3166 3167if ( buf -> b_sfname != buf -> b_ffname ) { 3168xfree ( buf -> b_sfname ); 3169} 3170xfree ( buf -> b_ffname ); 3171buf -> b_ffname = xstrdup ( name ); 3172buf -> b_sfname = NULL ; 3173// Allocate ffname and expand into full path. Also resolves .lnk 3174// files on Win32. 3175fname_expand ( buf , & buf -> b_ffname , & buf -> b_sfname ); 3176buf -> 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 3183if ( buf -> b_ml . ml_mfp != NULL ) { 3184ml_setname ( buf ); 3185} 3186 3187if ( curwin -> w_buffer == buf ) { 3188check_arg_idx ( curwin ); // check file name for arg list 3189} 3190maketitle (); // set window title 3191status_redraw_all (); // status lines need to be redrawn 3192fmarks_check_names ( buf ); // check named file marks 3193ml_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 3204buf_T * buf = buflist_new ( ffname , sfname , lnum , 0 ); 3205if ( buf != NULL && ( cmdmod . cmod_flags & CMOD_KEEPALT ) == 0 ) { 3206curwin -> w_alt_fnum = buf -> b_fnum ; 3207} 3208return 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{ 3217char * fname ; 3218linenr_T dummy ; 3219 3220if ( buflist_name_nr ( 0 , & fname , & dummy ) == FAIL ) { 3221if ( errmsg ) { 3222emsg ( _ ( e_noalt )); 3223} 3224return NULL ; 3225} 3226return 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{ 3235buf_T * buf = buflist_new ( fname , NULL , 0 , flags ); 3236if ( buf != NULL ) { 3237return buf -> b_fnum ; 3238} 3239return 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{ 3246buflist_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 ) 3254FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 3255{ 3256return 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 ) 3267FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 3268{ 3269// no name is different 3270if ( ffname == NULL || * ffname == NUL || buf -> b_ffname == NULL ) { 3271return true; 3272} 3273if ( path_equal ( ffname , buf -> b_ffname , kPathCmpLiteral )) { 3274return false; 3275} 3276{ 3277FileID file_id ; 3278// If no struct stat given, get it now 3279if ( file_id_p == NULL ) { 3280file_id_p = & file_id ; 3281file_id_valid = os_fileid ( ffname , file_id_p ); 3282} 3283if (! file_id_valid ) { 3284// file_id not valid, assume files are different. 3285return 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. 3296if ( buf_same_file_id ( buf , file_id_p )) { 3297buf_set_file_id ( buf ); 3298if ( buf_same_file_id ( buf , file_id_p )) { 3299return false; 3300} 3301} 3302} 3303return 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{ 3310FileID file_id ; 3311if ( buf -> b_fname != NULL 3312&& os_fileid ( buf -> b_fname , & file_id )) { 3313buf -> file_id_valid = true; 3314buf -> file_id = file_id ; 3315} else { 3316buf -> 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 ) 3325FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 3326{ 3327return 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{ 3335char * buffer = xmalloc ( IOSIZE ); 3336size_t bufferlen = 0 ; 3337 3338if ( fullname > 1 ) { // 2 CTRL-G: include buffer number 3339bufferlen = vim_snprintf_safelen ( buffer , IOSIZE , "buf %d: " , curbuf -> b_fnum ); 3340} 3341 3342buffer [ bufferlen ++ ] = '"' ; 3343 3344char * name = buf_spname ( curbuf ); 3345if ( name != NULL ) { 3346bufferlen += vim_snprintf_safelen ( buffer + bufferlen , 3347IOSIZE - bufferlen , "%s" , name ); 3348} else { 3349name = (! fullname && curbuf -> b_fname != NULL ) ? curbuf -> b_fname : curbuf -> b_ffname ; 3350bufferlen += home_replace ( shorthelp ? curbuf : NULL , name , 3351buffer + bufferlen , IOSIZE - bufferlen , true); 3352} 3353 3354bool dontwrite = bt_dontwrite ( curbuf ); 3355bufferlen += vim_snprintf_safelen ( buffer + bufferlen , 3356IOSIZE - bufferlen , 3357"\"%s%s%s%s%s%s" , 3358curbufIsChanged () 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]" ) : "" , 3367curbuf -> 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 3375if ( curbuf -> b_ml . ml_flags & ML_EMPTY ) { 3376bufferlen += vim_snprintf_safelen ( buffer + bufferlen , 3377IOSIZE - bufferlen , "%s" , _ ( no_lines_msg )); 3378} else if ( p_ru ) { 3379// Current line and column are already on the screen -- webb 3380bufferlen += vim_snprintf_safelen ( buffer + bufferlen , 3381IOSIZE - bufferlen , 3382NGETTEXT ( "%" PRId64 " line --%d%%--" , 3383"%" PRId64 " lines --%d%%--" , 3384curbuf -> b_ml . ml_line_count ), 3385( int64_t ) curbuf -> b_ml . ml_line_count , 3386calc_percentage ( curwin -> w_cursor . lnum , 3387curbuf -> b_ml . ml_line_count )); 3388} else { 3389bufferlen += vim_snprintf_safelen ( buffer + bufferlen , 3390IOSIZE - bufferlen , 3391_ ( "line %" PRId64 " of %" PRId64 " --%d%%-- col " ), 3392( int64_t ) curwin -> w_cursor . lnum , 3393( int64_t ) curbuf -> b_ml . ml_line_count , 3394calc_percentage ( curwin -> w_cursor . lnum , 3395curbuf -> b_ml . ml_line_count )); 3396validate_virtcol ( curwin ); 3397bufferlen += ( size_t ) col_print ( buffer + bufferlen , IOSIZE - bufferlen , 3398curwin -> w_cursor . col + 1 , curwin -> w_virtcol + 1 ); 3399} 3400 3401append_arg_number ( curwin , buffer + bufferlen , IOSIZE - bufferlen ); 3402 3403if ( 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. 3406msg_start (); 3407int n = msg_scroll ; 3408msg_scroll = true; 3409msg ( buffer , 0 ); 3410msg_scroll = n ; 3411} else { 3412char * p = msg_trunc ( buffer , false, 0 ); 3413if ( 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. 3419set_keep_msg ( p , 0 ); 3420} 3421} 3422 3423xfree ( buffer ); 3424} 3425 3426int col_print ( char * buf , size_t buflen , int col , int vcol ) 3427{ 3428if ( col == vcol ) { 3429return ( int ) vim_snprintf_safelen ( buf , buflen , "%d" , col ); 3430} 3431 3432return ( 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{ 3441char * title_str = NULL ; 3442char * icon_str = NULL ; 3443char buf [ IOSIZE ]; 3444const CharBuf outbuf = { buf , sizeof( buf ) }; 3445 3446if (! redrawing ()) { 3447// Postpone updating the title when 'lazyredraw' is set. 3448need_maketitle = true; 3449return; 3450} 3451 3452need_maketitle = false; 3453if (! p_title && ! p_icon && lasttitle == NULL && lasticon == NULL ) { 3454return; // nothing to do 3455} 3456 3457if ( p_title ) { 3458int maxlen = 0 ; 3459 3460if ( p_titlelen > 0 ) { 3461maxlen = MAX (( int )( p_titlelen * Columns / 100 ), 10 ); 3462} 3463 3464if ( * p_titlestring != NUL ) { 3465if ( stl_syntax & STL_IN_TITLE ) { 3466build_stl_str_hl ( curwin , outbuf , p_titlestring , 3467kOptTitlestring , 0 , 0 , maxlen , NULL , NULL , NULL , NULL ); 3468title_str = buf ; 3469} else { 3470title_str = p_titlestring ; 3471} 3472} else { 3473// Format: "fname + (path) (1 of 2) - Nvim". 3474#ifdef MSWIN 3475int p_ssl_save = p_ssl ; 3476p_ssl = true; 3477#endif 3478char * default_titlestring = "%t%( %M%)%( (%{expand('%:p:~:h')})%)%a - Nvim" ; 3479build_stl_str_hl ( curwin , outbuf , default_titlestring , 3480kOptTitlestring , 0 , 0 , maxlen , NULL , NULL , NULL , NULL ); 3481title_str = buf ; 3482#ifdef MSWIN 3483p_ssl = p_ssl_save ; 3484#endif 3485} 3486} 3487bool mustset = value_change ( title_str , & lasttitle ); 3488 3489if ( p_icon ) { 3490icon_str = buf ; 3491if ( * p_iconstring != NUL ) { 3492if ( stl_syntax & STL_IN_ICON ) { 3493build_stl_str_hl ( curwin , outbuf , p_iconstring , 3494kOptIconstring , 0 , 0 , 0 , NULL , NULL , NULL , NULL ); 3495} else { 3496icon_str = p_iconstring ; 3497} 3498} else { 3499char * name = buf_spname ( curbuf ); 3500if ( name == NULL ) { 3501name = path_tail ( curbuf -> b_ffname ); 3502} 3503// Truncate name at 100 bytes. 3504int namelen = ( int ) strlen ( name ); 3505if ( namelen > 100 ) { 3506namelen -= 100 ; 3507namelen += utf_cp_bounds ( name , name + namelen ). end_off ; 3508name += namelen ; 3509} 3510STRCPY ( buf , name ); 3511trans_characters ( buf , sizeof( buf )); 3512} 3513} 3514 3515mustset |= value_change ( icon_str , & lasticon ); 3516 3517if ( mustset ) { 3518resettitle (); 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 ) 3531FUNC_ATTR_WARN_UNUSED_RESULT 3532{ 3533if (( str == NULL ) != ( * last == NULL ) 3534|| ( str != NULL && * last != NULL && strcmp ( str , * last ) != 0 )) { 3535xfree ( * last ); 3536if ( str == NULL ) { 3537* last = NULL ; 3538resettitle (); 3539} else { 3540* last = xstrdup ( str ); 3541return true; 3542} 3543} 3544return false; 3545} 3546 3547/// Set current window title 3548void resettitle ( void ) 3549{ 3550ui_call_set_icon ( cstr_as_string ( lasticon )); 3551ui_call_set_title ( cstr_as_string ( lasttitle )); 3552} 3553 3554#ifdef EXITFREE 3555void free_titles ( void ) 3556{ 3557xfree ( lasttitle ); 3558xfree ( 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. 3568if ( buflen < 3 ) { 3569return 0 ; 3570} 3571 3572linenr_T above ; // number of lines above window 3573linenr_T below ; // number of lines below window 3574 3575above = wp -> w_topline - 1 ; 3576above += win_get_fill ( wp , wp -> w_topline ) - wp -> w_topfill ; 3577if ( 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. 3580above = 0 ; 3581} 3582below = wp -> w_buffer -> b_ml . ml_line_count - wp -> w_botline + 1 ; 3583if ( below <= 0 ) { 3584return ( int ) vim_snprintf_safelen ( buf , ( size_t ) buflen , 3585"%s" , ( above == 0 ) ? _ ( "All" ) : _ ( "Bot" )); 3586} 3587 3588if ( above <= 0 ) { 3589return ( int ) vim_snprintf_safelen ( buf , ( size_t ) buflen , 3590"%s" , _ ( "Top" )); 3591} 3592 3593int perc = calc_percentage ( above , above + below ); 3594char tmp [ 8 ]; 3595// localized percentage value 3596vim_snprintf ( tmp , sizeof( tmp ), _ ( "%d%%" ), perc ); 3597return ( 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 ) 3608FUNC_ATTR_NONNULL_ALL 3609{ 3610// Nothing to do 3611if ( ARGCOUNT <= 1 ) { 3612return 0 ; 3613} 3614 3615const char * msg = wp -> w_arg_idx_invalid ? _ ( " ((%d) of %d)" ) : _ ( " (%d of %d)" ); 3616 3617return ( 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{ 3631if ( * ffname == NULL ) { // no file name given, nothing to do 3632return; 3633} 3634if ( * sfname == NULL ) { // no short file name given, use ffname 3635* sfname = * ffname ; 3636} 3637* ffname = fix_fname ( * ffname ); // expand to full path 3638if ( * ffname == NULL ) { 3639* sfname = NULL ; 3640return; 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/". 3646if ( os_isdir ( * ffname )) { 3647char * name = xstrdup ( * sfname ); 3648size_t name_len = strlen ( name ); 3649if ( 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} 3653char * full = fix_fname ( name ); 3654xfree ( name ); 3655if ( full != NULL ) { 3656xfree ( * ffname ); 3657* ffname = full ; 3658} 3659* ffname = concat_fnames_realloc ( * ffname , "" , true); 3660} 3661 3662#ifdef MSWIN 3663if (! buf -> b_p_bin ) { 3664// If the file name is a shortcut file, use the file it links to. 3665char * rfname = os_resolve_shortcut ( * ffname ); 3666if ( rfname != NULL ) { 3667xfree ( * 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 ) 3677FUNC_ATTR_PURE 3678{ 3679return 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 ) 3684FUNC_ATTR_PURE 3685{ 3686return buf != NULL && buf == cmdwin_buf ; 3687} 3688 3689/// Open a window for a number of buffers. 3690void ex_buffer_all ( exarg_T * eap ) 3691{ 3692win_T * wpnext ; 3693int split_ret = OK ; 3694int open_wins = 0 ; 3695int had_tab = cmdmod . cmod_tab ; 3696 3697// Maximum number of windows to open. 3698linenr_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. 3703int 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. 3707reset_VIsual_and_resel (); 3708 3709setpcmark (); 3710 3711// Close superfluous windows (two windows for the same buffer). 3712// Also close windows that are not full-width. 3713if ( had_tab > 0 ) { 3714goto_tabpage_tp ( first_tabpage , true, true); 3715} 3716while (true) { 3717tabpage_T * tpnext = curtab -> tp_next ; 3718// Try to close floating windows first 3719for ( win_T * wp = lastwin -> w_floating ? lastwin : firstwin ; wp != NULL ; wp = wpnext ) { 3720wpnext = 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 ; 3723if (( 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 )) { 3733if ( win_close ( wp , false, false) == FAIL ) { 3734break; 3735} 3736// Just in case an autocommand does something strange with 3737// windows: start all over... 3738wpnext = lastwin -> w_floating ? lastwin : firstwin ; 3739tpnext = first_tabpage ; 3740open_wins = 0 ; 3741} else { 3742open_wins ++ ; 3743} 3744} 3745 3746// Without the ":tab" modifier only do the current tab page. 3747if ( had_tab == 0 || tpnext == NULL ) { 3748break; 3749} 3750goto_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. 3758autocmd_no_enter ++ ; 3759// lastwin may be ctx_win 3760win_enter ( lastwin_nofloating ( NULL ), false); 3761autocmd_no_leave ++ ; 3762for ( buf_T * buf = firstbuf ; buf != NULL && open_wins < count ; buf = buf -> b_next ) { 3763// Check if this buffer needs a window 3764if ((! all && buf -> b_ml . ml_mfp == NULL ) || ! buf -> b_p_bl ) { 3765continue; 3766} 3767 3768win_T * wp ; 3769if ( had_tab != 0 ) { 3770// With the ":tab" modifier don't move the window. 3771wp = 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 3776for ( wp = firstwin ; wp != NULL ; wp = wp -> w_next ) { 3777if (! wp -> w_floating && wp -> w_buffer == buf ) { 3778break; 3779} 3780} 3781// If the buffer already has a window, move it 3782if ( wp != NULL ) { 3783win_move_after ( wp , curwin ); 3784} 3785} 3786 3787if ( wp == NULL && split_ret == OK ) { 3788bufref_T bufref ; 3789set_bufref ( & bufref , buf ); 3790// Split the window and put the buffer in it. 3791bool p_ea_save = p_ea ; 3792p_ea = true; // use space from all windows 3793split_ret = win_split ( 0 , WSP_ROOM | WSP_BELOW ); 3794open_wins ++ ; 3795p_ea = p_ea_save ; 3796if ( split_ret == FAIL ) { 3797continue; 3798} 3799 3800// Open the buffer in this window. 3801swap_exists_action = SEA_DIALOG ; 3802set_curbuf ( buf , DOBUF_GOTO , !( jop_flags & kOptJopFlagClean )); 3803if (! bufref_valid ( & bufref )) { 3804// Autocommands deleted the buffer. 3805swap_exists_action = SEA_NONE ; 3806break; 3807} 3808if ( swap_exists_action == SEA_QUIT ) { 3809cleanup_T cs ; 3810 3811// Reset the error/interrupt/exception state here so that 3812// aborting() returns false when closing a window. 3813enter_cleanup ( & cs ); 3814 3815// User selected Quit at ATTENTION prompt; close this window. 3816win_close ( curwin , true, false); 3817open_wins -- ; 3818swap_exists_action = SEA_NONE ; 3819swap_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. 3824leave_cleanup ( & cs ); 3825} else { 3826handle_swap_exists ( NULL ); 3827} 3828} 3829 3830os_breakcheck (); 3831if ( got_int ) { 3832vgetc (); // only break the file loading, not the rest 3833break; 3834} 3835// Autocommands deleted the buffer or aborted script processing!!! 3836if ( aborting ()) { 3837break; 3838} 3839// When ":tab" was used open a new tab for a new window repeatedly. 3840if ( had_tab > 0 && tabpage_index ( NULL ) <= p_tpm ) { 3841cmdmod . cmod_tab = 9999 ; 3842} 3843} 3844autocmd_no_enter -- ; 3845win_enter ( firstwin , false); // back to first window 3846autocmd_no_leave -- ; 3847 3848// Close superfluous windows. 3849for ( win_T * wp = lastwin ; open_wins > count ;) { 3850bool r = ( buf_hide ( wp -> w_buffer ) || ! bufIsChanged ( wp -> w_buffer ) 3851|| autowrite ( wp -> w_buffer , false) == OK ) && ! is_ctx_win ( wp ); 3852if (! win_valid ( wp )) { 3853// BufWrite Autocommands made the window invalid, start over 3854wp = lastwin ; 3855} else if ( r ) { 3856win_close ( wp , ! buf_hide ( wp -> w_buffer ), false); 3857open_wins -- ; 3858wp = lastwin ; 3859} else { 3860wp = wp -> w_prev ; 3861if ( wp == NULL ) { 3862break; 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{ 3877linenr_T lnum ; 3878int nmlines ; 3879static int entered = 0 ; 3880 3881if (! curbuf -> b_p_ml || ( nmlines = ( int ) p_mls ) == 0 ) { 3882return; 3883} 3884 3885// Disallow recursive entry here. Can happen when executing a modeline 3886// triggers an autocommand, which reloads modelines with a ":do". 3887if ( entered ) { 3888return; 3889} 3890 3891entered ++ ; 3892for ( lnum = 1 ; curbuf -> b_p_ml && lnum <= curbuf -> b_ml . ml_line_count 3893&& lnum <= nmlines ; lnum ++ ) { 3894if ( chk_modeline ( lnum , flags ) == FAIL ) { 3895nmlines = 0 ; 3896} 3897} 3898 3899for ( lnum = curbuf -> b_ml . ml_line_count ; curbuf -> b_p_ml && lnum > 0 3900&& lnum > nmlines && lnum > curbuf -> b_ml . ml_line_count - nmlines ; 3901lnum -- ) { 3902if ( chk_modeline ( lnum , flags ) == FAIL ) { 3903nmlines = 0 ; 3904} 3905} 3906entered -- ; 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{ 3915char * e ; 3916int retval = OK ; 3917ESTACK_CHECK_DECLARATION ; 3918 3919int prev = -1 ; 3920char * s = ml_get ( lnum ); 3921char * line_end = s + ml_get_len ( lnum ); 3922for (; * s != NUL ; s ++ ) { 3923if ( prev == -1 || ascii_isspace ( prev )) { 3924if (( prev != -1 && strncmp ( s , "ex:" , 3 ) == 0 ) 3925|| strncmp ( s , "vi:" , 3 ) == 0 ) { 3926break; 3927} 3928// Accept both "vim" and "Vim". 3929if (( s [ 0 ] == 'v' || s [ 0 ] == 'V' ) && s [ 1 ] == 'i' && s [ 2 ] == 'm' ) { 3930if ( s [ 3 ] == '<' || s [ 3 ] == '=' || s [ 3 ] == '>' ) { 3931e = s + 4 ; 3932} else { 3933e = s + 3 ; 3934} 3935intmax_t vers ; 3936if (! try_getdigits ( & e , & vers )) { 3937continue; 3938} 3939 3940const int vim_version = min_vim_version (); 3941if ( * 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 ] == '=' ))) { 3949break; 3950} 3951} 3952} 3953prev = ( uint8_t )( * s ); 3954} 3955 3956if (! * s ) { 3957return retval ; 3958} 3959 3960do { // skip over "ex:", "vi:" or "vim:" 3961s ++ ; 3962} while ( s [ -1 ] != ':' ); 3963 3964size_t len = ( size_t )( line_end - s ); // remember the line length so we can restore 3965// 'line_end' after the copy 3966char * linecopy ; // local copy of any modeline found 3967s = linecopy = xstrnsave ( s , len ); // copy the line, it will change 3968 3969line_end = s + len ; // restore 'line_end' 3970 3971// prepare for emsg() 3972estack_push ( ETYPE_MODELINE , "modelines" , lnum ); 3973ESTACK_CHECK_SETUP ; 3974 3975bool end = false; 3976while ( end == false) { 3977s = skipwhite ( s ); 3978if ( * s == NUL ) { 3979break; 3980} 3981 3982// Find end of set command: ':' or end of line. 3983// Skip over "\:", replacing it with ":". 3984for ( e = s ; * e != ':' && * e != NUL ; e ++ ) { 3985if ( e [ 0 ] == '\\' && e [ 1 ] == ':' ) { 3986memmove ( e , e + 1 , ( size_t )( line_end - ( e + 1 )) + 1 ); // +1 for NUL 3987line_end -- ; 3988} 3989} 3990if ( * e == NUL ) { 3991end = 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. 3999if ( strncmp ( s , "set " , 4 ) == 0 4000|| strncmp ( s , "se " , 3 ) == 0 ) { 4001if ( * e != ':' ) { // no terminating ':'? 4002break; 4003} 4004end = true; 4005s += ( * ( s + 2 ) == ' ' ) ? 3 : 4 ; 4006} 4007* e = NUL ; // truncate the set command 4008 4009if ( * s != NUL ) { // skip over an empty "::" 4010const int secure_save = secure ; 4011const sctx_T save_current_sctx = current_sctx ; 4012current_sctx . sc_sid = SID_MODELINE ; 4013current_sctx . sc_seq = 0 ; 4014current_sctx . sc_lnum = lnum ; 4015// Make sure no risky things are executed as a side effect. 4016secure = 1 ; 4017 4018retval = do_set ( s , OPT_MODELINE | OPT_LOCAL | flags ); 4019 4020secure = secure_save ; 4021current_sctx = save_current_sctx ; 4022if ( retval == FAIL ) { // stop if error found 4023break; 4024} 4025} 4026s = ( e == line_end ) ? e : e + 1 ; // advance to next part 4027// careful not to go off the end 4028} 4029 4030ESTACK_CHECK_NOW ; 4031estack_pop (); 4032xfree ( linecopy ); 4033 4034return retval ; 4035} 4036 4037/// @return true if "buf" is a help buffer. 4038bool bt_help (const buf_T * const buf ) 4039FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4040{ 4041return 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 ) 4046FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4047{ 4048return 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 ) 4053FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4054{ 4055return 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 ) 4060FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4061{ 4062return 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 ) 4069FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4070{ 4071return 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 ) 4080FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4081{ 4082return 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 ) 4090FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4091{ 4092return 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 ) 4098FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4099{ 4100return 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 ) 4106FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 4107{ 4108if ( bt_dontwrite ( buf )) { 4109emsg ( _ ( "E382: Cannot write, 'buftype' option is set" )); 4110return true; 4111} 4112return 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 ) 4118FUNC_ATTR_PURE 4119{ 4120// 'bufhidden' overrules 'hidden' and ":hide", check it first 4121switch ( buf -> b_p_bh [ 0 ]) { 4122case 'u' : // "unload" 4123case 'w' : // "wipe" 4124case 'd' : 4125return false; // "delete" 4126case 'h' : 4127return true; // "hide" 4128} 4129return 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{ 4136if ( bt_quickfix ( buf )) { 4137// Differentiate between the quickfix and location list buffers using 4138// the buffer number stored in the global quickfix stack. 4139if ( buf -> b_fnum == qf_stack_get_bufnr ()) { 4140return _ ( msg_qflist ); 4141} 4142return _ ( msg_loclist ); 4143} 4144// There is no _file_ when 'buftype' is "nofile", b_sfname 4145// contains the name as specified by the user. 4146if ( bt_nofilename ( buf )) { 4147if ( buf -> b_fname != NULL ) { 4148return buf -> b_fname ; 4149} 4150if ( bt_cmdwin ( buf )) { 4151return _ ( "[Command Line]" ); 4152} 4153if ( bt_prompt ( buf )) { 4154return _ ( "[Prompt]" ); 4155} 4156return _ ( "[Scratch]" ); 4157} 4158if ( buf -> b_fname == NULL ) { 4159return buf_get_fname ( buf ); 4160} 4161return NULL ; 4162} 4163 4164/// Get "buf->b_fname", use "[No Name]" if it is NULL. 4165char * buf_get_fname (const buf_T * buf ) 4166FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 4167{ 4168if ( buf -> b_fname == NULL ) { 4169return _ ( "[No Name]" ); 4170} 4171return buf -> b_fname ; 4172} 4173 4174/// Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed. 4175void set_buflisted ( int on ) 4176{ 4177if ( on == curbuf -> b_p_bl ) { 4178return; 4179} 4180 4181curbuf -> b_p_bl = on ; 4182if ( on ) { 4183apply_autocmds ( EVENT_BUFADD , NULL , NULL , false, curbuf ); 4184} else { 4185apply_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 ) 4196FUNC_ATTR_NONNULL_ALL 4197{ 4198bool differ = true; 4199 4200// Allocate a buffer without putting it in the buffer list. 4201buf_T * newbuf = buflist_new ( NULL , NULL , 1 , BLN_DUMMY ); 4202if ( newbuf == NULL ) { 4203return true; 4204} 4205 4206// Force the 'fileencoding' and 'fileformat' to be equal. 4207exarg_T ea ; 4208prep_exarg ( & ea , buf ); 4209 4210// Set curwin/curbuf to buf and save a few things. 4211CtxSwitch aco = { 0 }; 4212ctx_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 4216block_autocmds (); 4217 4218if ( ml_open ( curbuf ) == OK 4219&& readfile ( buf -> b_ffname , buf -> b_fname , 42200 , 0 , ( linenr_T ) MAXLNUM , 4221& ea , READ_NEW | READ_DUMMY , false) == OK ) { 4222// compare the two files line by line 4223if ( buf -> b_ml . ml_line_count == curbuf -> b_ml . ml_line_count ) { 4224differ = false; 4225for ( linenr_T lnum = 1 ; lnum <= curbuf -> b_ml . ml_line_count ; lnum ++ ) { 4226if ( strcmp ( ml_get_buf ( buf , lnum ), ml_get ( lnum )) != 0 ) { 4227differ = true; 4228break; 4229} 4230} 4231} 4232} 4233xfree ( ea . cmd ); 4234 4235// restore curwin/curbuf and a few other things 4236ctx_restore ( & aco ); 4237 4238if ( curbuf != newbuf ) { // safety check 4239wipe_buffer ( newbuf , false); 4240} 4241 4242unblock_autocmds (); 4243 4244return 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{ 4251if (! aucmd ) { 4252// Don't trigger BufDelete autocommands here. 4253block_autocmds (); 4254} 4255close_buffer ( NULL , buf , DOBUF_WIPE , false, true, false); 4256if (! aucmd ) { 4257unblock_autocmds (); 4258} 4259} 4260 4261bool buf_is_empty ( buf_T * buf ) 4262{ 4263return 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 ) 4272FUNC_ATTR_NONNULL_ALL 4273{ 4274buf_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 ) 4282FUNC_ATTR_NONNULL_ALL 4283{ 4284typval_T old_val = buf -> changedtick_di . di_tv ; 4285 4286#ifndef NDEBUG 4287dictitem_T * const changedtick_di = tv_dict_find ( buf -> b_vars , S_LEN ( "changedtick" )); 4288assert ( changedtick_di != NULL ); 4289assert ( changedtick_di -> di_tv . v_type == VAR_NUMBER ); 4290assert ( changedtick_di -> di_tv . v_lock == VAR_FIXED ); 4291// For some reason formatc does not like the below. 4292# ifndef UNIT_TESTING_LUA_PREPROCESSING 4293assert ( changedtick_di -> di_flags == ( DI_FLAGS_RO | DI_FLAGS_FIX )); 4294# endif 4295assert ( changedtick_di == ( dictitem_T * ) & buf -> changedtick_di ); 4296#endif 4297buf -> changedtick_di . di_tv . vval . v_number = changedtick ; 4298 4299if ( tv_dict_is_watched ( buf -> b_vars )) { 4300buf -> b_locked ++ ; 4301tv_dict_watcher_notify ( buf -> b_vars , 4302( char * ) buf -> changedtick_di . di_key , 4303& buf -> changedtick_di . di_tv , 4304& old_val ); 4305buf -> 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 ) 4311FUNC_ATTR_NONNULL_ALL 4312{ 4313assert ( buf ); 4314assert ( sb ); 4315 4316if ( buf -> b_ml . ml_flags & ML_EMPTY ) { 4317return; 4318} 4319 4320size_t written = 0 ; 4321size_t len = 0 ; 4322linenr_T lnum = start ; 4323char * lp = ml_get_buf ( buf , lnum ); 4324size_t lplen = ( size_t ) ml_get_buf_len ( buf , lnum ); 4325 4326while (true) { 4327if ( lplen == 0 ) { 4328len = 0 ; 4329} else if ( lp [ written ] == NL ) { 4330// NL -> NUL translation 4331len = 1 ; 4332kv_push ( * sb , NUL ); 4333} else { 4334char * s = vim_strchr ( lp + written , NL ); 4335len = s == NULL ? lplen - written : ( size_t )( s - ( lp + written )); 4336kv_concat_len ( * sb , lp + written , len ); 4337} 4338 4339if ( len == lplen - written ) { 4340// Finished a line, add a NL, unless this line should not have one. 4341if ( 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 ))) { 4345kv_push ( * sb , NL ); 4346} 4347lnum ++ ; 4348if ( lnum > end ) { 4349break; 4350} 4351lp = ml_get_buf ( buf , lnum ); 4352lplen = ( size_t ) ml_get_buf_len ( buf , lnum ); 4353written = 0 ; 4354} else if ( len > 0 ) { 4355written += len ; 4356 } 4357 } 4358}