robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// for debugging 2// #define CHECK(c, s) do { if (c) emsg(s); } while (0) 3#define CHECK (c ,s ) do {} while (0) 4 5// memline.c: Contains the functions for appending, deleting and changing the 6// text lines. The memfile functions are used to store the information in 7// blocks of memory, backed up by a file. The structure of the information is 8// a tree. The root of the tree is a pointer block. The leaves of the tree 9// are data blocks. In between may be several layers of pointer blocks, 10// forming branches. 11// 12// Three types of blocks are used: 13// - Block nr 0 contains information for recovery 14// - Pointer blocks contain list of pointers to other blocks. 15// - Data blocks contain the actual text. 16// 17// Block nr 0 contains the block0 structure (see below). 18// 19// Block nr 1 is the first pointer block. It is the root of the tree. 20// Other pointer blocks are branches. 21// 22// If a line is too big to fit in a single page, the block containing that 23// line is made big enough to hold the line. It may span several pages. 24// Otherwise all blocks are one page. 25// 26// A data block that was filled when starting to edit a file and was not 27// changed since then, can have a negative block number. This means that it 28// has not yet been assigned a place in the file. When recovering, the lines 29// in this data block can be read from the original file. When the block is 30// changed (lines appended/deleted/changed) or when it is flushed it gets a 31// positive number. Use mf_trans_del() to get the new number, before calling 32// mf_get(). 33// 34// "Mom, can we get ropes?" 35// "We have ropes at home." 36// Ropes at home: 37 38#include <assert.h> 39#include <errno.h> 40#include <fcntl.h> 41#include <inttypes.h> 42#include <stdbool.h> 43#include <stddef.h> 44#include <stdio.h> 45#include <string.h> 46#include <time.h> 47#include <uv.h> 48 49#include "auto/config.h" 50#include "klib/kvec.h" 51#include "nvim/ascii_defs.h" 52#include "nvim/autocmd.h" 53#include "nvim/autocmd_defs.h" 54#include "nvim/buffer.h" 55#include "nvim/buffer_defs.h" 56#include "nvim/change.h" 57#include "nvim/cursor.h" 58#include "nvim/dialog.h" 59#include "nvim/drawscreen.h" 60#include "nvim/eval/typval.h" 61#include "nvim/eval/vars.h" 62#include "nvim/ex_cmds_defs.h" 63#include "nvim/fileio.h" 64#include "nvim/gettext_defs.h" 65#include "nvim/globals.h" 66#include "nvim/highlight_defs.h" 67#include "nvim/input.h" 68#include "nvim/lua/executor.h" 69#include "nvim/macros_defs.h" 70#include "nvim/main.h" 71#include "nvim/map_defs.h" 72#include "nvim/mark.h" 73#include "nvim/mbyte.h" 74#include "nvim/memfile.h" 75#include "nvim/memfile_defs.h" 76#include "nvim/memline.h" 77#include "nvim/memory.h" 78#include "nvim/message.h" 79#include "nvim/option.h" 80#include "nvim/option_defs.h" 81#include "nvim/option_vars.h" 82#include "nvim/os/fs.h" 83#include "nvim/os/fs_defs.h" 84#include "nvim/os/input.h" 85#include "nvim/os/os.h" 86#include "nvim/os/os_defs.h" 87#include "nvim/os/proc.h" 88#include "nvim/os/time.h" 89#include "nvim/os/time_defs.h" 90#include "nvim/path.h" 91#include "nvim/pos_defs.h" 92#include "nvim/spell.h" 93#include "nvim/statusline.h" 94#include "nvim/strings.h" 95#include "nvim/ui.h" 96#include "nvim/undo.h" 97#include "nvim/version.h" 98#include "nvim/vim_defs.h" 99 100#ifndef UNIX // it's in os/unix_defs.h for Unix 101# include <time.h> 102#endif 103 104enum { 105DATA_ID = (('d' <<8 )+ 'a' ),// data block id 106PTR_ID = (('p' <<8 )+ 't' ),// pointer block id 107BLOCK0_ID0 = 'b' ,// block 0 id 0 108BLOCK0_ID1 = '0' ,// block 0 id 1 109}; 110 111// pointer to a block, used in a pointer block 112typedef struct { 113blocknr_T pe_bnum ;// block number 114linenr_T pe_line_count ;// number of lines in this branch 115linenr_T pe_old_lnum ;// lnum for this block (for recovery) 116int pe_page_count ;// number of pages in block pe_bnum 117}PointerEntry ; 118 119// A pointer block contains a list of branches in the tree. 120typedef struct { 121uint16_t pb_id ;// ID for pointer block: PTR_ID 122uint16_t pb_count ;// number of pointers in this block 123uint16_t pb_count_max ;// maximum value for pb_count 124PointerEntry pb_pointer [];// list of pointers to blocks 125// followed by empty space until end of page 126}PointerBlock ; 127 128// Value for pb_count_max. 129#define PB_COUNT_MAX (mfp ) \ 130 (uint16_t)((mfp->mf_page_size - offsetof(PointerBlock, pb_pointer)) / sizeof(PointerEntry)) 131 132// A data block is a leaf in the tree. 133// 134// The text of the lines is at the end of the block. The text of the first line 135// in the block is put at the end, the text of the second line in front of it, 136// etc. Thus the order of the lines is the opposite of the line number. 137typedef struct { 138uint16_t db_id ;// ID for data block: DATA_ID 139unsigned db_free ;// free space available 140unsigned db_txt_start ;// byte where text starts 141unsigned db_txt_end ;// byte just after data block 142// linenr_T db_line_count; 143long db_line_count ;// number of lines in this block 144unsigned db_index [];// index for start of line 145// followed by empty space up to db_txt_start 146// followed by the text in the lines until 147// end of page 148}DataBlock ; 149 150// The low bits of db_index hold the actual index. The topmost bit is 151// used for the global command to be able to mark a line. 152// This method is not clean, but otherwise there would be at least one extra 153// byte used for each line. 154// The mark has to be in this place to keep it with the correct line when other 155// lines are inserted or deleted. 156#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1)) 157#define DB_INDEX_MASK (~DB_MARKED) 158 159#define INDEX_SIZE (sizeof(unsigned)) // size of one db_index entry 160#define HEADER_SIZE (offsetof(DataBlock, db_index)) // size of data block header 161 162enum { 163B0_FNAME_SIZE_ORG = 900 ,// what it was in older versions 164B0_FNAME_SIZE_NOCRYPT = 898 ,// 2 bytes used for other things 165B0_FNAME_SIZE_CRYPT = 890 ,// 10 bytes used for other things 166B0_UNAME_SIZE = 40 , 167B0_HNAME_SIZE = 40 , 168}; 169// Restrict the numbers to 32 bits, otherwise most compilers will complain. 170// This won't detect a 64 bit machine that only swaps a byte in the top 32 171// bits, but that is crazy anyway. 172enum { 173B0_MAGIC_LONG = 0x30313233 , 174B0_MAGIC_INT = 0x20212223 , 175B0_MAGIC_SHORT = 0x10111213 , 176B0_MAGIC_CHAR = 0x55 , 177}; 178 179/// Block zero holds all info about the swapfile. This is the first block in the file. 180/// 181/// NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing swapfiles unusable! 182/// 183/// If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in memfile.h!! 184/// 185/// This block is built up of single bytes, to make it portable across 186/// different machines. b0_magic_* is used to check the byte order and size of 187/// variables, because the rest of the swapfile is not portable. 188typedef struct { 189char b0_id [2 ];///< ID for block 0: BLOCK0_ID0 and BLOCK0_ID1. 190char b0_version [10 ];///< Vim version string 191char b0_page_size [4 ];///< number of bytes per page 192char b0_mtime [4 ];///< last modification time of file 193char b0_ino [4 ];///< inode of b0_fname 194char b0_pid [4 ];///< process id of creator (or 0) 195char b0_uname [B0_UNAME_SIZE ];///< name of user (uid if no name) 196char b0_hname [B0_HNAME_SIZE ];///< host name (if it has a name) 197char b0_fname [B0_FNAME_SIZE_ORG ];///< name of file being edited 198long b0_magic_long ;///< check for byte order of long 199int b0_magic_int ;///< check for byte order of int 200int16_t b0_magic_short ;///< check for byte order of short 201char b0_magic_char ;///< check for last char 202}ZeroBlock ; 203 204// Note: b0_dirty and b0_flags are put at the end of the file name. For very 205// long file names in older versions of Vim they are invalid. 206// The 'fileencoding' comes before b0_flags, with a NUL in front. But only 207// when there is room, for very long file names it's omitted. 208#define B0_DIRTY 0x55 209#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1] 210 211// The b0_flags field is new in Vim 7.0. 212#define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2] 213 214// The lowest two bits contain the fileformat. Zero means it's not set 215// (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or 216// EOL_MAC + 1. 217#define B0_FF_MASK 3 218 219// Swapfile is in directory of edited file. Used to find the file from different mount points. 220#define B0_SAME_DIR 4 221 222// The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it. 223// When empty there is only the NUL. 224#define B0_HAS_FENC 8 225 226#define STACK_INCR 5 // nr of entries added to ml_stack at a time 227 228// The line number where the first mark may be is remembered. 229// If it is 0 there are no marks at all. 230// (always used for the current buffer only, no buffer change possible while 231// executing a global command). 232static linenr_T lowest_marked = 0 ; 233 234// arguments for ml_find_line() 235enum { 236ML_DELETE = 0x11 ,// delete line 237ML_INSERT = 0x12 ,// insert line 238ML_FIND = 0x13 ,// just find the line 239ML_FLUSH = 0x02 ,// flush locked block 240}; 241#define ML_SIMPLE (x ) ((x) & 0x10) // DEL, INS or FIND 242 243// argument for ml_upd_block0() 244typedef enum { 245UB_FNAME = 0 ,// update timestamp and filename 246UB_SAME_DIR ,// update the B0_SAME_DIR flag 247}upd_block0_T ; 248 249typedef enum { 250SEA_CHOICE_NONE = 0 , 251SEA_CHOICE_READONLY = 1 , 252SEA_CHOICE_EDIT = 2 , 253SEA_CHOICE_RECOVER = 3 , 254SEA_CHOICE_DELETE = 4 , 255SEA_CHOICE_QUIT = 5 , 256SEA_CHOICE_ABORT = 6 , 257}sea_choice_T ; 258 259#include "memline.c.generated.h" 260 261static const char e_ml_get_invalid_lnum_nr [] 262= N_ ("E315: ml_get: Invalid lnum: %" PRId64 ); 263static const char e_ml_get_cannot_find_line_nr_in_buffer_nr_str [] 264= N_ ("E316: ml_get: Cannot find line %" PRId64 "in buffer %d %s" ); 265static const char e_pointer_block_id_wrong [] 266= N_ ("E317: Pointer block id wrong" ); 267static const char e_pointer_block_id_wrong_two [] 268= N_ ("E317: Pointer block id wrong 2" ); 269static const char e_pointer_block_id_wrong_three [] 270= N_ ("E317: Pointer block id wrong 3" ); 271static const char e_pointer_block_id_wrong_four [] 272= N_ ("E317: Pointer block id wrong 4" ); 273static const char e_line_number_out_of_range_nr_past_the_end [] 274= N_ ("E322: Line number out of range: %" PRId64 " past the end" ); 275static const char e_line_count_wrong_in_block_nr [] 276= N_ ("E323: Line count wrong in block %" PRId64 ); 277static const char e_warning_pointer_block_corrupted [] 278= N_ ("E1364: Warning: Pointer block corrupted" ); 279 280#if __has_feature (address_sanitizer ) 281# define ML_GET_ALLOC_LINES 282#endif 283 284/// Open a new memline for "buf". 285/// 286/// @return FAIL for failure, OK otherwise. 287int ml_open (buf_T * buf ) 288{ 289// init fields in memline struct 290buf -> b_ml .ml_stack_size = 0 ;// no stack yet 291buf -> b_ml .ml_stack = NULL ;// no stack yet 292buf -> b_ml .ml_stack_top = 0 ;// nothing in the stack 293buf -> b_ml .ml_locked = NULL ;// no cached block 294buf -> b_ml .ml_line_lnum = 0 ;// no cached line 295buf -> b_ml .ml_line_offset = 0 ; 296buf -> b_ml .ml_chunksize = NULL ; 297buf -> b_ml .ml_usedchunks = 0 ; 298 299if (cmdmod .cmod_flags & CMOD_NOSWAPFILE ) { 300buf -> b_p_swf = false; 301 } 302 303// When 'updatecount' is non-zero swapfile may be opened later. 304if (!buf -> terminal && p_uc && buf -> b_p_swf ) { 305buf -> b_may_swap = true; 306 }else { 307buf -> b_may_swap = false; 308 } 309 310// Open the memfile. No swapfile is created yet. 311memfile_T * mfp = mf_open (NULL ,0 ); 312if (mfp == NULL ) { 313 gotoerror ; 314 } 315 316buf -> b_ml .ml_mfp = mfp ; 317buf -> b_ml .ml_flags = ML_EMPTY ; 318buf -> b_ml .ml_line_count = 1 ; 319 320// fill block0 struct and write page 0 321bhdr_T * hp = mf_new (mfp , false,1 ); 322if (hp -> bh_bnum != 0 ) { 323iemsg (_ ("E298: Didn't get block nr 0?" )); 324 gotoerror ; 325 } 326ZeroBlock * b0p = hp -> bh_data ; 327 328b0p -> b0_id [0 ]= BLOCK0_ID0 ; 329b0p -> b0_id [1 ]= BLOCK0_ID1 ; 330b0p -> b0_magic_long = B0_MAGIC_LONG ; 331b0p -> b0_magic_int = B0_MAGIC_INT ; 332b0p -> b0_magic_short = (int16_t )B0_MAGIC_SHORT ; 333b0p -> b0_magic_char = B0_MAGIC_CHAR ; 334xstrlcpy (xstpcpy (b0p -> b0_version ,"VIM " ),Versions [0 ],6 ); 335long_to_char ((long )mfp -> mf_page_size ,b0p -> b0_page_size ); 336 337if (!buf -> b_spell ) { 338b0p -> b0_dirty = buf -> b_changed ?B0_DIRTY :0 ; 339b0p -> b0_flags = (char )(get_fileformat (buf )+ 1 ); 340set_b0_fname (b0p ,buf ); 341os_get_username (b0p -> b0_uname ,B0_UNAME_SIZE ); 342b0p -> b0_uname [B0_UNAME_SIZE - 1 ]= NUL ; 343os_get_hostname (b0p -> b0_hname ,B0_HNAME_SIZE ); 344b0p -> b0_hname [B0_HNAME_SIZE - 1 ]= NUL ; 345long_to_char ((long )os_get_pid (),b0p -> b0_pid ); 346 } 347 348// Always sync block number 0 to disk, so we can check the file name in 349// the swapfile in findswapname(). Don't do this for a help files or 350// a spell buffer though. 351// Only works when there's a swapfile, otherwise it's done when the file 352// is created. 353mf_put (mfp ,hp , true, false); 354if (!buf -> b_help && !buf -> b_spell ) { 355mf_sync (mfp ,0 ); 356 } 357 358// Fill in root pointer block and write page 1. 359hp = ml_new_ptr (mfp ); 360assert (hp != NULL ); 361if (hp -> bh_bnum != 1 ) { 362iemsg (_ ("E298: Didn't get block nr 1?" )); 363 gotoerror ; 364 } 365PointerBlock * pp = hp -> bh_data ; 366pp -> pb_count = 1 ; 367pp -> pb_pointer [0 ].pe_bnum = 2 ; 368pp -> pb_pointer [0 ].pe_page_count = 1 ; 369pp -> pb_pointer [0 ].pe_old_lnum = 1 ; 370pp -> pb_pointer [0 ].pe_line_count = 1 ;// line count after insertion 371mf_put (mfp ,hp , true, false); 372 373// Allocate first data block and create an empty line 1. 374hp = ml_new_data (mfp , false,1 ); 375if (hp -> bh_bnum != 2 ) { 376iemsg (_ ("E298: Didn't get block nr 2?" )); 377 gotoerror ; 378 } 379 380DataBlock * dp = hp -> bh_data ; 381dp -> db_index [0 ]= -- dp -> db_txt_start ;// at end of block 382dp -> db_free -= 1 + (unsigned )INDEX_SIZE ; 383dp -> db_line_count = 1 ; 384* ((char * )dp + dp -> db_txt_start )= NUL ;// empty line 385 386return OK ; 387 388error : 389if (mfp != NULL ) { 390if (hp ) { 391mf_put (mfp ,hp , false, false); 392 } 393mf_close (mfp , true);// will also xfree(mfp->mf_fname) 394 } 395buf -> b_ml .ml_mfp = NULL ; 396return FAIL ; 397} 398 399/// ml_setname() is called when the file name of "buf" has been changed. 400/// It may rename the swapfile. 401void ml_setname (buf_T * buf ) 402{ 403bool success = false; 404 405memfile_T * mfp = buf -> b_ml .ml_mfp ; 406if (mfp -> mf_fd < 0 ) {// there is no swapfile yet 407// When 'updatecount' is 0 and 'noswapfile' there is no swapfile. 408// For help files we will make a swapfile now. 409if (p_uc != 0 && (cmdmod .cmod_flags & CMOD_NOSWAPFILE )== 0 ) { 410ml_open_file (buf );// create a swapfile 411 } 412return ; 413 } 414 415// Try all directories in the 'directory' option. 416char * dirp = p_dir ; 417bool found_existing_dir = false; 418while (true) { 419if (* dirp == NUL ) {// tried all directories, fail 420break ; 421 } 422char * fname = findswapname (buf ,& dirp ,mfp -> mf_fname ,& found_existing_dir ); 423// autocmd may have freed mfp if findswapname creates different swapfile name 424if (buf -> b_ml .ml_mfp != mfp ) { 425xfree (fname ); 426return ; 427 } 428// alloc's fname 429if (dirp == NULL ) {// out of memory 430break ; 431 } 432if (fname == NULL ) {// no file name found for this dir 433continue ; 434 } 435 436// if the file name is the same we don't have to do anything 437if (path_equal (fname ,mfp -> mf_fname ,kPathCmpLiteral )) { 438xfree (fname ); 439success = true; 440break ; 441 } 442// need to close the swapfile before renaming 443if (mfp -> mf_fd >=0 ) { 444close (mfp -> mf_fd ); 445mfp -> mf_fd = -1 ; 446 } 447 448// try to rename the swapfile 449if (vim_rename (mfp -> mf_fname ,fname )== 0 ) { 450success = true; 451mf_free_fnames (mfp ); 452mf_set_fnames (mfp ,fname ); 453ml_upd_block0 (buf ,UB_SAME_DIR ); 454break ; 455 } 456xfree (fname );// this fname didn't work, try another 457 } 458 459if (mfp -> mf_fd == -1 ) {// need to (re)open the swapfile 460mfp -> mf_fd = os_open (mfp -> mf_fname ,O_RDWR ,0 ); 461if (mfp -> mf_fd < 0 ) { 462// could not (re)open the swapfile, what can we do???? 463emsg (_ ("E301: Oops, lost the swap file!!!" )); 464return ; 465 } 466os_set_cloexec (mfp -> mf_fd ); 467 } 468if (!success ) { 469emsg (_ ("E302: Could not rename swap file" )); 470 } 471} 472 473/// Open a file for the memfile for all buffers that are not readonly or have 474/// been modified. 475/// Used when 'updatecount' changes from zero to non-zero. 476void ml_open_files (void ) 477{ 478FOR_ALL_BUFFERS (buf ) { 479if (!buf -> b_p_ro || buf -> b_changed ) { 480ml_open_file (buf ); 481 } 482 } 483} 484 485/// Open a swapfile for an existing memfile, if there is no swapfile yet. 486/// If we are unable to find a file name, mf_fname will be NULL 487/// and the memfile will be in memory only (no recovery possible). 488void ml_open_file (buf_T * buf ) 489{ 490memfile_T * mfp = buf -> b_ml .ml_mfp ; 491if (mfp == NULL || mfp -> mf_fd >=0 || !buf -> b_p_swf 492|| (cmdmod .cmod_flags & CMOD_NOSWAPFILE ) 493|| buf -> terminal ) { 494return ;// nothing to do 495 } 496 497// For a spell buffer use a temp file name. 498if (buf -> b_spell ) { 499char * fname = vim_tempname (); 500if (fname != NULL ) { 501mf_open_file (mfp ,fname );// consumes fname! 502 } 503buf -> b_may_swap = false; 504return ; 505 } 506 507// Try all directories in 'directory' option. 508char * dirp = p_dir ; 509bool found_existing_dir = false; 510while (true) { 511if (* dirp == NUL ) { 512break ; 513 } 514// There is a small chance that between choosing the swapfile name 515// and creating it, another Vim creates the file. In that case the 516// creation will fail and we will use another directory. 517char * fname = findswapname (buf ,& dirp ,NULL ,& found_existing_dir ); 518// autocmd may have freed mfp, grr! 519if (buf -> b_ml .ml_mfp != mfp ) { 520xfree (fname ); 521return ; 522 } 523if (dirp == NULL ) { 524break ;// out of memory 525 } 526if (fname == NULL ) { 527continue ; 528 } 529if (mf_open_file (mfp ,fname )== OK ) {// consumes fname! 530// don't sync yet in ml_sync_all() 531mfp -> mf_dirty = MF_DIRTY_YES_NOSYNC ; 532ml_upd_block0 (buf ,UB_SAME_DIR ); 533 534// Flush block zero, so others can read it 535if (mf_sync (mfp ,MFS_ZERO )== OK ) { 536// Mark all blocks that should be in the swapfile as dirty. 537// Needed for when the 'swapfile' option was reset, so that 538// the swapfile was deleted, and then on again. 539mf_set_dirty (mfp ); 540break ; 541 } 542// Writing block 0 failed: close the file and try another dir 543mf_close_file (buf , false); 544 } 545 } 546 547if (* p_dir != NUL && mfp -> mf_fname == NULL ) { 548need_wait_return = true;// call wait_return() later 549no_wait_return ++ ; 550semsg (_ ("E303: Unable to open swap file for \"%s\", recovery impossible" ), 551buf_spname (buf )!= NULL ?buf_spname (buf ) :buf -> b_fname ); 552no_wait_return -- ; 553 } 554 555// don't try to open a swapfile again 556buf -> b_may_swap = false; 557} 558 559/// If still need to create a swapfile, and starting to edit a not-readonly 560/// file, or reading into an existing buffer, create a swapfile now. 561/// 562/// @param newfile reading file into new buffer 563void check_need_swap (bool newfile ) 564{ 565int old_msg_silent = msg_silent ;// might be reset by an E325 message 566msg_silent = 0 ;// If swap dialog prompts for input, user needs to see it! 567 568if (curbuf -> b_may_swap && (!curbuf -> b_p_ro || !newfile )) { 569ml_open_file (curbuf ); 570 } 571 572msg_silent = old_msg_silent ; 573} 574 575/// Close memline for buffer 'buf'. 576/// 577/// @param del_file if true, delete the swapfile 578void ml_close (buf_T * buf ,int del_file ) 579{ 580if (buf -> b_ml .ml_mfp == NULL ) {// not open 581return ; 582 } 583mf_close (buf -> b_ml .ml_mfp ,del_file );// close the .swp file 584if (buf -> b_ml .ml_line_lnum != 0 585&& (buf -> b_ml .ml_flags & (ML_LINE_DIRTY |ML_ALLOCATED ))) { 586xfree (buf -> b_ml .ml_line_ptr ); 587 } 588xfree (buf -> b_ml .ml_stack ); 589XFREE_CLEAR (buf -> b_ml .ml_chunksize ); 590buf -> b_ml .ml_mfp = NULL ; 591 592// Reset the "recovered" flag, give the ATTENTION prompt the next time 593// this buffer is loaded. 594buf -> b_flags &= ~BF_RECOVERED ; 595} 596 597/// Close all existing memlines and memfiles. 598/// Only used when exiting. 599/// 600/// @param del_file if true, delete the memfiles. 601void ml_close_all (bool del_file ) 602{ 603FOR_ALL_BUFFERS (buf ) { 604ml_close (buf ,del_file ); 605 } 606spell_delete_wordlist ();// delete the internal wordlist 607vim_deltempdir ();// delete created temp directory 608} 609 610/// Close all memfiles for not modified buffers. 611/// Only use just before exiting! 612void ml_close_notmod (void ) 613{ 614FOR_ALL_BUFFERS (buf ) { 615if (!bufIsChanged (buf )) { 616ml_close (buf , true);// close all not-modified buffers 617 } 618 } 619} 620 621/// Update the timestamp in the .swp file. 622/// Used when the file has been written. 623void ml_timestamp (buf_T * buf ) 624{ 625ml_upd_block0 (buf ,UB_FNAME ); 626} 627 628/// Checks whether the IDs in b0 are valid. 629static bool ml_check_b0_id (ZeroBlock * b0p ) 630FUNC_ATTR_NONNULL_ALL 631{ 632return b0p -> b0_id [0 ]== BLOCK0_ID0 && b0p -> b0_id [1 ]== BLOCK0_ID1 ; 633} 634 635/// Checks whether all strings in b0 are valid (i.e. nul-terminated). 636static bool ml_check_b0_strings (ZeroBlock * b0p ) 637FUNC_ATTR_NONNULL_ALL 638{ 639return (memchr (b0p -> b0_version ,NUL ,10 ) 640&& memchr (b0p -> b0_uname ,NUL ,B0_UNAME_SIZE ) 641&& memchr (b0p -> b0_hname ,NUL ,B0_HNAME_SIZE ) 642&& memchr (b0p -> b0_fname ,NUL ,B0_FNAME_SIZE_CRYPT )); 643} 644 645/// Update the timestamp or the B0_SAME_DIR flag of the .swp file. 646static void ml_upd_block0 (buf_T * buf ,upd_block0_T what ) 647{ 648bhdr_T * hp ; 649 650memfile_T * mfp = buf -> b_ml .ml_mfp ; 651if (mfp == NULL || (hp = mf_get (mfp ,0 ,1 ))== NULL ) { 652return ; 653 } 654ZeroBlock * b0p = hp -> bh_data ; 655if (ml_check_b0_id (b0p )== FAIL ) { 656iemsg (_ ("E304: ml_upd_block0(): Didn't get block 0??" )); 657 }else { 658if (what == UB_FNAME ) { 659set_b0_fname (b0p ,buf ); 660 }else {// what == UB_SAME_DIR 661set_b0_dir_flag (b0p ,buf ); 662 } 663 } 664mf_put (mfp ,hp , true, false); 665} 666 667/// Write file name and timestamp into block 0 of a swapfile. 668/// Also set buf->b_mtime. 669/// Don't use NameBuff[]!!! 670static void set_b0_fname (ZeroBlock * b0p ,buf_T * buf ) 671{ 672if (buf -> b_ffname == NULL ) { 673b0p -> b0_fname [0 ]= NUL ; 674 }else { 675char uname [B0_UNAME_SIZE ]; 676 677// For a file under the home directory of the current user, we try to 678// replace the home directory path with "~user". This helps when 679// editing the same file on different machines over a network. 680// First replace home dir path with "~/" with home_replace(). 681// Then insert the user name to get "~user/". 682size_t flen = home_replace (NULL ,buf -> b_ffname ,b0p -> b0_fname , 683B0_FNAME_SIZE_CRYPT , true); 684if (b0p -> b0_fname [0 ]== '~' ) { 685// If there is no user name or it is too long, don't use "~/" 686int retval = os_get_username (uname ,B0_UNAME_SIZE ); 687size_t ulen = strlen (uname ); 688if (retval == FAIL || ulen + flen > B0_FNAME_SIZE_CRYPT - 1 ) { 689xstrlcpy (b0p -> b0_fname ,buf -> b_ffname ,B0_FNAME_SIZE_CRYPT ); 690 }else { 691memmove (b0p -> b0_fname + ulen + 1 ,b0p -> b0_fname + 1 ,flen ); 692memmove (b0p -> b0_fname + 1 ,uname ,ulen ); 693 } 694 } 695FileInfo file_info ; 696if (os_fileinfo (buf -> b_ffname ,& file_info )) { 697long_to_char (file_info .stat .st_mtim .tv_sec ,b0p -> b0_mtime ); 698long_to_char ((long )os_fileinfo_inode (& file_info ),b0p -> b0_ino ); 699buf_store_file_info (buf ,& file_info ); 700buf -> b_mtime_read = buf -> b_mtime ; 701buf -> b_mtime_read_ns = buf -> b_mtime_ns ; 702 }else { 703long_to_char (0 ,b0p -> b0_mtime ); 704long_to_char (0 ,b0p -> b0_ino ); 705buf -> b_mtime = 0 ; 706buf -> b_mtime_ns = 0 ; 707buf -> b_mtime_read = 0 ; 708buf -> b_mtime_read_ns = 0 ; 709buf -> b_orig_size = 0 ; 710buf -> b_orig_mode = 0 ; 711 } 712 } 713 714// Also add the 'fileencoding' if there is room. 715add_b0_fenc (b0p ,curbuf ); 716} 717 718/// Update the B0_SAME_DIR flag of the swapfile. It's set if the file and the 719/// swapfile for "buf" are in the same directory. 720/// This is fail safe: if we are not sure the directories are equal the flag is 721/// not set. 722static void set_b0_dir_flag (ZeroBlock * b0p ,buf_T * buf ) 723{ 724if (same_directory (buf -> b_ml .ml_mfp -> mf_fname ,buf -> b_ffname )) { 725b0p -> b0_flags |=B0_SAME_DIR ; 726 }else { 727b0p -> b0_flags = (char )(b0p -> b0_flags & ~B0_SAME_DIR ); 728 } 729} 730 731/// When there is room, add the 'fileencoding' to block zero. 732static void add_b0_fenc (ZeroBlock * b0p ,buf_T * buf ) 733{ 734const int size = B0_FNAME_SIZE_NOCRYPT ; 735 736int n = (int )strlen (buf -> b_p_fenc ); 737if ((int )strlen (b0p -> b0_fname )+ n + 1 > size ) { 738b0p -> b0_flags = (char )(b0p -> b0_flags & ~B0_HAS_FENC ); 739 }else { 740memmove (b0p -> b0_fname + size - n , 741buf -> b_p_fenc , (size_t )n ); 742* (b0p -> b0_fname + size - n - 1 )= NUL ; 743b0p -> b0_flags |=B0_HAS_FENC ; 744 } 745} 746 747/// Returns the PID of the process that owns the swapfile, if it is running. 748/// 749/// @param b0p swapfile data 750/// @param swap_fname Name of the swapfile. If it's from before a reboot, the result is 0. 751/// 752/// @return PID, or 0 if process is not running or the swapfile is from before a reboot. 753static int swapfile_proc_running (const ZeroBlock * b0p ,const char * swap_fname ) 754{ 755FileInfo st ; 756double uptime ; 757// If the system rebooted after when the swapfile was written then the 758// process can't be running now. 759if (os_fileinfo (swap_fname ,& st ) 760&& uv_uptime (& uptime )== 0 761&& (Timestamp )st .stat .st_mtim .tv_sec < os_time ()- (Timestamp )uptime ) { 762return 0 ; 763 } 764int pid = (int )char_to_long (b0p -> b0_pid ); 765return os_proc_running (pid ) ?pid :0 ; 766} 767 768/// Try to recover curbuf from the .swp file. 769/// 770/// @param checkext if true, check the extension and detect whether it is a swapfile. 771void ml_recover (bool checkext ) 772{ 773buf_T * buf = NULL ; 774memfile_T * mfp = NULL ; 775char * fname_used = NULL ; 776bhdr_T * hp = NULL ; 777char * b0_fenc = NULL ; 778infoptr_T * ip ; 779bool directly ; 780bool serious_error = true; 781int orig_file_status = NOTDONE ; 782 783recoverymode = true; 784int called_from_main = (curbuf -> b_ml .ml_mfp == NULL ); 785 786// If the file name ends in ".s[a-w][a-z]" we assume this is the swapfile. 787// Otherwise a search is done to find the swapfile(s). 788char * fname = curbuf -> b_fname ; 789if (fname == NULL ) {// When there is no file name 790fname = "" ; 791 } 792int len = (int )strlen (fname ); 793if (checkext && len >=4 794&& STRNICMP (fname + len - 4 ,".s" ,2 )== 0 795&& vim_strchr ("abcdefghijklmnopqrstuvw" ,TOLOWER_ASC ((uint8_t )fname [len - 2 ]))!= NULL 796&& ASCII_ISALPHA (fname [len - 1 ])) { 797directly = true; 798fname_used = xstrdup (fname );// make a copy for mf_open() 799 }else { 800directly = false; 801 802// Enumerate matching swapfiles into items_tv. 803typval_T items_tv ; 804tv_list_alloc_ret (& items_tv ,0 ); 805recover_names (fname , true,items_tv .vval .v_list ); 806int n_swaps = tv_list_len (items_tv .vval .v_list ); 807 808if (n_swaps == 0 ) { 809tv_clear (& items_tv ); 810semsg (_ ("E305: No swap file found for %s" ),fname ); 811 gototheend ; 812 } 813if (n_swaps > 1 ) { 814// Several swapfiles found: prompt (async) via vim.ui.select(). 815typval_T lua_args []= {items_tv , { .v_type = VAR_UNKNOWN } }; 816nlua_call_typval ("vim._core.swapfile" ,"select_swap" ,lua_args ,NULL ); 817tv_clear (& items_tv ); 818 gototheend ; 819 } 820// One swapfile: use it directly. 821fname_used = xstrdup (tv_list_first (items_tv .vval .v_list )-> li_tv .vval .v_string ); 822tv_clear (& items_tv ); 823 } 824if (fname_used == NULL ) { 825 gototheend ;// user chose invalid number. 826 } 827// When called from main() still need to initialize storage structure 828if (called_from_main && ml_open (curbuf )== FAIL ) { 829getout (1 ); 830 } 831 832// Allocate a buffer structure for the swapfile that is used for recovery. 833// Only the memline in it is really used. 834buf = xmalloc (sizeof (buf_T )); 835 836// init fields in memline struct 837buf -> b_ml .ml_stack_size = 0 ;// no stack yet 838buf -> b_ml .ml_stack = NULL ;// no stack yet 839buf -> b_ml .ml_stack_top = 0 ;// nothing in the stack 840buf -> b_ml .ml_line_lnum = 0 ;// no cached line 841buf -> b_ml .ml_line_offset = 0 ; 842buf -> b_ml .ml_locked = NULL ;// no locked block 843buf -> b_ml .ml_flags = 0 ; 844 845// open the memfile from the old swapfile 846char * p = xstrdup (fname_used );// save "fname_used" for the message: 847// mf_open() will consume "fname_used"! 848mfp = mf_open (fname_used ,O_RDONLY ); 849fname_used = p ; 850if (mfp == NULL || mfp -> mf_fd < 0 ) { 851semsg (_ ("E306: Cannot open %s" ),fname_used ); 852 gototheend ; 853 } 854buf -> b_ml .ml_mfp = mfp ; 855 856// The page size set in mf_open() might be different from the page size 857// used in the swapfile, we must get it from block 0. But to read block 858// 0 we need a page size. Use the minimal size for block 0 here, it will 859// be set to the real value below. 860mfp -> mf_page_size = MIN_SWAP_PAGE_SIZE ; 861 862int hl_id = HLF_E ; 863msg_ext_set_kind ("emsg" ); 864// try to read block 0 865if ((hp = mf_get (mfp ,0 ,1 ))== NULL ) { 866msg_start (); 867msg_puts_hl (_ ("Unable to read block 0 from " ),hl_id , true); 868msg_outtrans (mfp -> mf_fname ,hl_id , true); 869msg_puts_hl (_ ("\nMaybe no changes were made or Nvim did not update the swap file." ),hl_id , 870 true); 871msg_end (); 872 gototheend ; 873 } 874ZeroBlock * b0p = hp -> bh_data ; 875if (strncmp (b0p -> b0_version ,"VIM 3.0" ,7 )== 0 ) { 876msg_start (); 877msg_outtrans (mfp -> mf_fname ,0 , true); 878msg_puts_hl (_ (" cannot be used with this version of Nvim.\n" ),0 , true); 879msg_puts_hl (_ ("Use Vim version 3.0.\n" ),0 , true); 880msg_end (); 881 gototheend ; 882 } 883if (ml_check_b0_id (b0p )== FAIL ) { 884semsg (_ ("E307: %s does not look like a Nvim swap file" ),mfp -> mf_fname ); 885 gototheend ; 886 } 887if (b0_magic_wrong (b0p )) { 888msg_start (); 889msg_outtrans (mfp -> mf_fname ,hl_id , true); 890msg_puts_hl (_ (" cannot be used on this computer.\n" ),hl_id , true); 891msg_puts_hl (_ ("The file was created on " ),hl_id , true); 892// avoid going past the end of a corrupted hostname 893b0p -> b0_fname [0 ]= NUL ; 894msg_puts_hl (b0p -> b0_hname ,hl_id , true); 895msg_puts_hl (_ (",\nor the file has been damaged." ),hl_id , true); 896msg_end (); 897 gototheend ; 898 } 899 900// If we guessed the wrong page size, we have to recalculate the 901// highest block number in the file. 902if (mfp -> mf_page_size != (unsigned )char_to_long (b0p -> b0_page_size )) { 903unsigned previous_page_size = mfp -> mf_page_size ; 904 905mf_new_page_size (mfp , (unsigned )char_to_long (b0p -> b0_page_size )); 906if (mfp -> mf_page_size < previous_page_size ) { 907msg_start (); 908msg_outtrans (mfp -> mf_fname ,hl_id , true); 909msg_puts_hl (_ (" has been damaged (page size is smaller than minimum value).\n" ),hl_id , true); 910msg_end (); 911 gototheend ; 912 } 913off_T size = vim_lseek (mfp -> mf_fd ,0 ,SEEK_END ); 914// 0 means no file or empty file 915mfp -> mf_blocknr_max = size <=0 ?0 :size /mfp -> mf_page_size ; 916mfp -> mf_infile_count = mfp -> mf_blocknr_max ; 917 918// need to reallocate the memory used to store the data 919p = xmalloc (mfp -> mf_page_size ); 920memmove (p ,hp -> bh_data ,previous_page_size ); 921xfree (hp -> bh_data ); 922hp -> bh_data = p ; 923b0p = hp -> bh_data ; 924 } 925 926// If .swp file name given directly, use name from swapfile for buffer. 927if (directly ) { 928TO_SLASH (b0p -> b0_fname ); 929expand_env (b0p -> b0_fname ,NameBuff ,MAXPATHL ); 930if (setfname (curbuf ,NameBuff ,NULL , true)== FAIL ) { 931 gototheend ; 932 } 933 } 934 935msg_ext_set_kind ("wmsg" ); 936msg_ext_skip_flush = true; 937home_replace (NULL ,mfp -> mf_fname ,NameBuff ,MAXPATHL , true); 938smsg (0 ,_ ("Using swap file \"%s\"" ),NameBuff ); 939 940if (buf_spname (curbuf )!= NULL ) { 941xstrlcpy (NameBuff ,buf_spname (curbuf ),MAXPATHL ); 942 }else { 943home_replace (NULL ,curbuf -> b_ffname ,NameBuff ,MAXPATHL , true); 944 } 945msg_putchar ('\n' ); 946smsg (0 ,_ ("Original file \"%s\"" ),NameBuff ); 947msg_putchar ('\n' ); 948msg_ext_skip_flush = false; 949 950// check date of swapfile and original file 951FileInfo org_file_info ; 952FileInfo swp_file_info ; 953int mtime = (int )char_to_long (b0p -> b0_mtime ); 954if (curbuf -> b_ffname != NULL 955&& os_fileinfo (curbuf -> b_ffname ,& org_file_info ) 956&& ((os_fileinfo (mfp -> mf_fname ,& swp_file_info ) 957&& org_file_info .stat .st_mtim .tv_sec 958> swp_file_info .stat .st_mtim .tv_sec ) 959|| org_file_info .stat .st_mtim .tv_sec != mtime )) { 960emsg (_ ("E308: Warning: Original file may have been changed" )); 961 } 962ui_flush (); 963 964// Get the 'fileformat' and 'fileencoding' from block zero. 965int b0_ff = (b0p -> b0_flags & B0_FF_MASK ); 966if (b0p -> b0_flags & B0_HAS_FENC ) { 967int fnsize = B0_FNAME_SIZE_NOCRYPT ; 968 969for (p = b0p -> b0_fname + fnsize ;p > b0p -> b0_fname && p [-1 ]!= NUL ;p -- ) {} 970b0_fenc = xstrnsave (p , (size_t )(b0p -> b0_fname + fnsize - p )); 971 } 972 973mf_put (mfp ,hp , false, false);// release block 0 974hp = NULL ; 975 976// Now that we are sure that the file is going to be recovered, clear the 977// contents of the current buffer. 978while (!(curbuf -> b_ml .ml_flags & ML_EMPTY )) { 979ml_delete (1 ); 980 } 981 982// Try reading the original file to obtain the values of 'fileformat', 983// 'fileencoding', etc. Ignore errors. The text itself is not used. 984if (curbuf -> b_ffname != NULL ) { 985orig_file_status = readfile (curbuf -> b_ffname ,NULL ,0 , 9860 ,MAXLNUM ,NULL ,READ_NEW , false); 987 } 988 989// Use the 'fileformat' and 'fileencoding' as stored in the swapfile. 990if (b0_ff != 0 ) { 991set_fileformat (b0_ff - 1 ,OPT_LOCAL ); 992 } 993if (b0_fenc != NULL ) { 994set_option_value_give_err (kOptFileencoding ,CSTR_AS_OBJ (b0_fenc ),OPT_LOCAL ); 995xfree (b0_fenc ); 996 } 997unchanged (curbuf , true, true); 998 999blocknr_T bnum = 1 ;// start with block 1 1000unsigned page_count = 1 ;// which is 1 page 1001linenr_T lnum = 0 ;// append after line 0 in curbuf 1002linenr_T line_count = 0 ; 1003int idx = 0 ;// start with first index in block 1 1004int error = 0 ; 1005buf -> b_ml .ml_stack_top = 0 ; 1006buf -> b_ml .ml_stack = NULL ; 1007buf -> b_ml .ml_stack_size = 0 ; 1008 1009bool cannot_open = (curbuf -> b_ffname == NULL ); 1010 1011serious_error = false; 1012for (; !got_int ;line_breakcheck ()) { 1013if (hp != NULL ) { 1014mf_put (mfp ,hp , false, false);// release previous block 1015 } 1016// get block 1017if ((hp = mf_get (mfp ,bnum ,page_count ))== NULL ) { 1018if (bnum == 1 ) { 1019semsg (_ ("E309: Unable to read block 1 from %s" ),mfp -> mf_fname ); 1020 gototheend ; 1021 } 1022error ++ ; 1023ml_append (lnum ++ ,_ ("???MANY LINES MISSING" ),0 , true); 1024 }else {// there is a block 1025PointerBlock * pp = hp -> bh_data ; 1026if (pp -> pb_id == PTR_ID ) {// it is a pointer block 1027bool ptr_block_error = false; 1028if (pp -> pb_count_max != PB_COUNT_MAX (mfp )) { 1029ptr_block_error = true; 1030pp -> pb_count_max = PB_COUNT_MAX (mfp ); 1031 } 1032if (pp -> pb_count > pp -> pb_count_max ) { 1033ptr_block_error = true; 1034pp -> pb_count = pp -> pb_count_max ; 1035 } 1036if (ptr_block_error ) { 1037emsg (_ (e_warning_pointer_block_corrupted )); 1038 } 1039 1040// check line count when using pointer block first time 1041if (idx == 0 && line_count != 0 ) { 1042for (int i = 0 ;i < (int )pp -> pb_count ;i ++ ) { 1043line_count -= pp -> pb_pointer [i ].pe_line_count ; 1044 } 1045if (line_count != 0 ) { 1046error ++ ; 1047ml_append (lnum ++ ,_ ("???LINE COUNT WRONG" ),0 , true); 1048 } 1049 } 1050 1051if (pp -> pb_count == 0 ) { 1052ml_append (lnum ++ ,_ ("???EMPTY BLOCK" ),0 , true); 1053error ++ ; 1054 }else if (idx < (int )pp -> pb_count ) {// go a block deeper 1055if (pp -> pb_pointer [idx ].pe_bnum < 0 ) { 1056// Data block with negative block number. 1057// Try to read lines from the original file. 1058// This is slow, but it works. 1059if (!cannot_open ) { 1060line_count = pp -> pb_pointer [idx ].pe_line_count ; 1061linenr_T pe_old_lnum = pp -> pb_pointer [idx ].pe_old_lnum ; 1062// Validate pe_line_count and pe_old_lnum from the 1063// untrusted swap file before passing to readfile(). 1064if (line_count <=0 || pe_old_lnum < 1 1065|| readfile (curbuf -> b_ffname ,NULL ,lnum ,pe_old_lnum - 1 , 1066line_count ,NULL ,0 , false)!= OK ) { 1067cannot_open = true; 1068 }else { 1069lnum += line_count ; 1070 } 1071 } 1072if (cannot_open ) { 1073error ++ ; 1074ml_append (lnum ++ ,_ ("???LINES MISSING" ),0 , true); 1075 } 1076idx ++ ;// get same block again for next index 1077continue ; 1078 } 1079 1080// going one block deeper in the tree 1081int top = ml_add_stack (buf );// new entry in stack 1082ip = & (buf -> b_ml .ml_stack [top ]); 1083ip -> ip_bnum = bnum ; 1084ip -> ip_index = idx ; 1085 1086bnum = pp -> pb_pointer [idx ].pe_bnum ; 1087line_count = pp -> pb_pointer [idx ].pe_line_count ; 1088page_count = (unsigned )pp -> pb_pointer [idx ].pe_page_count ; 1089// Validate pe_bnum and pe_page_count from the untrusted 1090// swap file before passing to mf_get(), which uses 1091// page_count to calculate allocation size. A bogus value 1092// (e.g. 0x40000000) would cause a multi-GB allocation. 1093// pe_page_count must be >= 1 and bnum + page_count must 1094// not exceed the number of pages in the swap file. 1095if (page_count < 1 || bnum + page_count > mfp -> mf_blocknr_max + 1 ) { 1096error ++ ; 1097ml_append (lnum ++ ,_ ("???ILLEGAL BLOCK NUMBER" ), (colnr_T )0 , true); 1098// Skip this entry and pop back up the stack to keep 1099// recovering whatever else we can. 1100idx = ip -> ip_index + 1 ; 1101bnum = ip -> ip_bnum ; 1102page_count = 1 ; 1103buf -> b_ml .ml_stack_top -- ; 1104continue ; 1105 } 1106idx = 0 ; 1107continue ; 1108 } 1109 }else {// not a pointer block 1110DataBlock * dp = hp -> bh_data ; 1111if (dp -> db_id != DATA_ID ) {// block id wrong 1112if (bnum == 1 ) { 1113semsg (_ ("E310: Block 1 ID wrong (%s not a .swp file?)" ), 1114mfp -> mf_fname ); 1115 gototheend ; 1116 } 1117error ++ ; 1118ml_append (lnum ++ ,_ ("???BLOCK MISSING" ),0 , true); 1119 }else { 1120// It is a data block. 1121// Append all the lines in this block. 1122bool has_error = false; 1123 1124// Verify the cached block's actual size matches the 1125// pointer entry's pe_page_count. mf_get() cache hits 1126// return the original block without resizing, so a 1127// crafted swap file referencing the same block twice 1128// with different pe_page_count values would cause an 1129// OOB write below. 1130if (hp -> bh_page_count != page_count ) { 1131error ++ ; 1132ml_append (lnum ++ ,_ ("??? BLOCK PAGE COUNT MISMATCH" ),0 , true); 1133page_count = hp -> bh_page_count ; 1134 } 1135 1136// Check the length of the block. 1137// If wrong, use the length given in the pointer block. 1138if (page_count * mfp -> mf_page_size != dp -> db_txt_end ) { 1139ml_append (lnum ++ , 1140_ ("??? from here until ???END lines" " may be messed up" ), 11410 , true); 1142error ++ ; 1143has_error = true; 1144dp -> db_txt_end = page_count * mfp -> mf_page_size ; 1145 } 1146 1147if (dp -> db_txt_start < HEADER_SIZE || dp -> db_txt_start > dp -> db_txt_end ) { 1148ml_append (lnum ++ ,_ ("??? block header corrupted" ),0 , true); 1149error ++ ; 1150has_error = true; 1151dp -> db_txt_start = dp -> db_txt_end ; 1152 } 1153// Make sure there is a NUL at the end of the block so we 1154// don't go over the end when copying text. 1155* ((char * )dp + dp -> db_txt_end - 1 )= NUL ; 1156 1157// Check the number of lines in the block. 1158// If wrong, use the count in the data block. 1159if (line_count != dp -> db_line_count ) { 1160ml_append (lnum ++ , 1161_ ("??? from here until ???END lines" 1162" may have been inserted/deleted" ), 11630 , true); 1164error ++ ; 1165has_error = true; 1166 } 1167 1168bool did_questions = false; 1169for (int i = 0 ;i < dp -> db_line_count ;i ++ ) { 1170if ((char * )& (dp -> db_index [i ]) >= (char * )dp + dp -> db_txt_start ) { 1171// line count must be wrong 1172error ++ ; 1173ml_append (lnum ++ ,_ ("??? lines may be missing" ),0 , true); 1174break ; 1175 } 1176 1177int txt_start = (dp -> db_index [i ]& DB_INDEX_MASK ); 1178if (txt_start <= (int )HEADER_SIZE 1179|| txt_start >= (int )dp -> db_txt_end ) { 1180error ++ ; 1181// avoid lots of lines with "???" 1182if (did_questions ) { 1183continue ; 1184 } 1185did_questions = true; 1186p = "???" ; 1187 }else { 1188did_questions = false; 1189p = (char * )dp + txt_start ; 1190 } 1191ml_append (lnum ++ ,p ,0 , true); 1192 } 1193if (has_error ) { 1194ml_append (lnum ++ ,_ ("???END" ),0 , true); 1195 } 1196 } 1197 } 1198 } 1199 1200if (buf -> b_ml .ml_stack_top == 0 ) {// finished 1201break ; 1202 } 1203 1204// go one block up in the tree 1205ip = & (buf -> b_ml .ml_stack [-- (buf -> b_ml .ml_stack_top )]); 1206bnum = ip -> ip_bnum ; 1207idx = ip -> ip_index + 1 ;// go to next index 1208page_count = 1 ; 1209 } 1210 1211// Compare the buffer contents with the original file. When they differ 1212// set the 'modified' flag. 1213// Lines 1 - lnum are the new contents. 1214// Lines lnum + 1 to ml_line_count are the original contents. 1215// Line ml_line_count + 1 in the dummy empty line. 1216if (orig_file_status != OK || curbuf -> b_ml .ml_line_count != lnum * 2 + 1 ) { 1217// Recovering an empty file results in two lines and the first line is 1218// empty. Don't set the modified flag then. 1219if (!(curbuf -> b_ml .ml_line_count == 2 && * ml_get (1 )== NUL )) { 1220changed_internal (curbuf ); 1221buf_inc_changedtick (curbuf ); 1222 } 1223 }else { 1224for (idx = 1 ;idx <=lnum ;idx ++ ) { 1225// Need to copy one line, fetching the other one may flush it. 1226p = xstrnsave (ml_get (idx ), (size_t )ml_get_len (idx )); 1227int i = strcmp (p ,ml_get (idx + lnum )); 1228xfree (p ); 1229if (i != 0 ) { 1230changed_internal (curbuf ); 1231buf_inc_changedtick (curbuf ); 1232break ; 1233 } 1234 } 1235 } 1236 1237// Delete the lines from the original file and the dummy line from the 1238// empty buffer. These will now be after the last line in the buffer. 1239while (curbuf -> b_ml .ml_line_count > lnum 1240&& !(curbuf -> b_ml .ml_flags & ML_EMPTY )) { 1241ml_delete (curbuf -> b_ml .ml_line_count ); 1242 } 1243curbuf -> b_flags |=BF_RECOVERED ; 1244check_cursor (curwin ); 1245 1246msg_ext_skip_flush = !got_int ; 1247recoverymode = false; 1248if (got_int ) { 1249emsg (_ ("E311: Recovery Interrupted" )); 1250 }else if (error ) { 1251no_wait_return ++ ; 1252msg_ext_set_kind ("emsg" ); 1253msg (">>>>>>>>>>>>>\n" ,0 ); 1254emsg (_ ("E312: Errors detected while recovering; look for lines starting with ???" )); 1255no_wait_return -- ; 1256msg_putchar ('\n' ); 1257msg (_ ("See \":help E312\" for more information." ),0 ); 1258msg ("\n>>>>>>>>>>>>>" ,0 ); 1259 }else { 1260msg_ext_set_kind ("wmsg" ); 1261if (curbuf -> b_changed ) { 1262msg (_ ("Recovery completed. You should check if everything is OK." ),0 ); 1263msg_puts (_ ("\n(You might want to write out this file under another name\n" )); 1264msg_puts (_ ("and run diff with the original file to check for changes)" )); 1265 }else { 1266msg (_ ("Recovery completed. Buffer contents equals file contents." ),0 ); 1267 } 1268msg_puts (_ ("\nYou may want to delete the .swp file now." )); 1269if (swapfile_proc_running (b0p ,fname_used )) { 1270// Warn there could be an active Vim on the same file, the user may 1271// want to kill it. 1272msg_puts (_ ("\nNote: process STILL RUNNING: " )); 1273msg_outnum ((int )char_to_long (b0p -> b0_pid )); 1274 } 1275if (!ui_has (kUIMessages )) { 1276msg_puts ("\n\n" ); 1277 } 1278cmdline_row = msg_row ; 1279 } 1280redraw_curbuf_later (UPD_NOT_VALID ); 1281 1282theend : 1283msg_ext_skip_flush = false; 1284xfree (fname_used ); 1285recoverymode = false; 1286if (mfp != NULL ) { 1287if (hp != NULL ) { 1288mf_put (mfp ,hp , false, false); 1289 } 1290mf_close (mfp , false);// will also xfree(mfp->mf_fname) 1291 } 1292if (buf != NULL ) {// may be NULL if swapfile not found. 1293xfree (buf -> b_ml .ml_stack ); 1294xfree (buf ); 1295 } 1296if (serious_error && called_from_main ) { 1297ml_close (curbuf , true); 1298 }else { 1299apply_autocmds (EVENT_BUFREADPOST ,NULL ,curbuf -> b_fname , false,curbuf ); 1300apply_autocmds (EVENT_BUFWINENTER ,NULL ,curbuf -> b_fname , false,curbuf ); 1301 } 1302} 1303 1304/// Enumerate swapfiles for `fname` (or for the global swap dir if `fname` is NULL), 1305/// appending each found path to `ret_list`. 1306/// 1307/// Used by `:recover` (`ml_recover()`), `nvim -r`, and `swapfilelist()`. 1308/// 1309/// @param fname base for swapfile name, or NULL to list every swapfile in 'directory'. 1310/// @param skip_curbuf exclude the current buffer's own active swapfile (used by `:recover`, 1311/// not by `swapfilelist()`). 1312/// @param ret_list receives the paths. 1313void recover_names (char * fname ,bool skip_curbuf ,list_T * ret_list ) 1314FUNC_ATTR_NONNULL_ARG (3 ) 1315{ 1316int num_names ; 1317char * (names [6 ]); 1318char * tail ; 1319char * p ; 1320char ** files ; 1321char * fname_res = NULL ; 1322#ifdef HAVE_READLINK 1323char fname_buf [MAXPATHL ]; 1324#endif 1325 1326if (fname != NULL ) { 1327#ifdef HAVE_READLINK 1328// Expand symlink in the file name, because the swapfile is created 1329// with the actual file instead of with the symlink. 1330fname_res = (resolve_symlink (fname ,fname_buf )== OK ) ?fname_buf :fname ; 1331#else 1332fname_res = fname ; 1333#endif 1334 } 1335 1336// Do the loop for every directory in 'directory'. 1337// First allocate some memory to put the directory name in. 1338String dir_name ; 1339dir_name .data = xmalloc (strlen (p_dir )+ 1 ); 1340char * dirp = p_dir ; 1341while (* dirp ) { 1342// Isolate a directory name from *dirp and put it in dir_name (we know 1343// it is large enough, so use 31000 for length). 1344// Advance dirp to next directory name. 1345dir_name .size = copy_option_part (& dirp ,dir_name .data ,31000 ,"," ); 1346 1347if (dir_name .data [0 ]== '.' && dir_name .data [1 ]== NUL ) {// check current dir 1348if (fname == NULL ) { 1349names [0 ]= xmemdupz (S_LEN ("*.sw?" )); 1350// For Unix names starting with a dot are special. MS-Windows 1351// supports this too, on some file systems. 1352names [1 ]= xmemdupz (S_LEN (".*.sw?" )); 1353names [2 ]= xmemdupz (S_LEN (".sw?" )); 1354num_names = 3 ; 1355 }else { 1356num_names = recov_file_names (names ,fname_res , true); 1357 } 1358 }else {// check directory dir_name 1359if (fname == NULL ) { 1360names [0 ]= concat_fnames (dir_name ,STATIC_CSTR_AS_STRING ("*.sw?" ), true).data ; 1361// For Unix names starting with a dot are special. MS-Windows 1362// supports this too, on some file systems. 1363names [1 ]= concat_fnames (dir_name ,STATIC_CSTR_AS_STRING (".*.sw?" ), true).data ; 1364names [2 ]= concat_fnames (dir_name ,STATIC_CSTR_AS_STRING (".sw?" ), true).data ; 1365num_names = 3 ; 1366 }else { 1367p = dir_name .data + dir_name .size ; 1368if (after_pathsep (dir_name .data ,p )&& dir_name .size > 1 && p [-1 ]== p [-2 ]) { 1369// Ends with '//', Use Full path for swap name 1370tail = make_percent_swname (dir_name .data ,p ,fname_res ); 1371 }else { 1372tail = path_tail (fname_res ); 1373tail = concat_fnames (dir_name ,cstr_as_string (tail ), true).data ; 1374 } 1375num_names = recov_file_names (names ,tail , false); 1376xfree (tail ); 1377 } 1378 } 1379 1380int num_files ; 1381if (num_names == 0 ) { 1382num_files = 0 ; 1383 }else if (expand_wildcards (num_names ,names ,& num_files ,& files , 1384EW_KEEPALL |EW_FILE |EW_SILENT )== FAIL ) { 1385num_files = 0 ; 1386 } 1387 1388// When no swapfile found, wildcard expansion might have failed (e.g. 1389// not able to execute the shell). 1390// Try finding a swapfile by simply adding ".swp" to the file name. 1391if (* dirp == NUL && tv_list_len (ret_list )+ num_files == 0 && fname != NULL ) { 1392char * swapname = modname (fname_res ,".swp" , true); 1393if (swapname != NULL ) { 1394if (os_path_exists (swapname )) { 1395files = xmalloc (sizeof (char * )); 1396files [0 ]= swapname ; 1397swapname = NULL ; 1398num_files = 1 ; 1399 } 1400xfree (swapname ); 1401 } 1402 } 1403 1404// Remove swapfile name of the current buffer, it must be ignored. 1405if (skip_curbuf 1406&& curbuf -> b_ml .ml_mfp != NULL 1407&& (p = curbuf -> b_ml .ml_mfp -> mf_fname )!= NULL ) { 1408for (int i = 0 ;i < num_files ;i ++ ) { 1409// Do not expand wildcards, on Windows would try to expand 1410// "%tmp%" in "%tmp%file" 1411if (path_equal (p ,files [i ],kPathCmpFull )) { 1412// Remove the name from files[i]. Move further entries 1413// down. When the array becomes empty free it here, since 1414// FreeWild() won't be called below. 1415xfree (files [i ]); 1416if (-- num_files == 0 ) { 1417xfree (files ); 1418 }else { 1419for (;i < num_files ;i ++ ) { 1420files [i ]= files [i + 1 ]; 1421 } 1422 } 1423 } 1424 } 1425 } 1426for (int i = 0 ;i < num_files ;i ++ ) { 1427// `files[i]` is already a full path (from `expand_wildcards`). 1428tv_list_append_allocated_string (ret_list ,xstrdup (files [i ])); 1429 } 1430 1431for (int i = 0 ;i < num_names ;i ++ ) { 1432xfree (names [i ]); 1433 } 1434if (num_files > 0 ) { 1435FreeWild (num_files ,files ); 1436 } 1437 } 1438xfree (dir_name .data ); 1439} 1440 1441/// Append the full path to name with path separators made into percent 1442/// signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"") 1443/// signs, to "dir". An unnamed buffer is handled as "" (<currentdir>/"") 1444/// The last character in "dir" must be an extra slash or backslash, it is 1445/// removed. 1446char * make_percent_swname (char * dir ,char * dir_end ,const char * name ) 1447FUNC_ATTR_NONNULL_ARG (1 ,2 ) 1448{ 1449String fixed_fname ; 1450char * fname = fix_fname (name != NULL ?name :"" ); 1451if (fname == NULL ) { 1452return NULL ; 1453 } 1454 1455FileInfo file_info ; 1456if (!os_fileinfo2 (fname ,& file_info )) { 1457xfree (fname ); 1458return NULL ; 1459 } 1460fixed_fname .data = fname + file_info .root_off ; 1461if (file_info .type == kPathDeviceUNC ) { 1462assert (file_info .root_off >=2 ); 1463fixed_fname .data -= 2 ; 1464fixed_fname .data [0 ]= '/' ;// Fixup //?/UNC/server/ path: "C/server/..." -> "//server/..." 1465 } 1466char * p ; 1467for (p = fixed_fname .data ;* p != NUL ;MB_PTR_ADV (p )) { 1468if (vim_ispathsep (* p )) { 1469* p = '%' ; 1470 } 1471 } 1472fixed_fname .size = (size_t )(p - fixed_fname .data ); 1473 1474// remove one trailing slash 1475p = & dir_end [-1 ]; 1476* p = NUL ; 1477String d = concat_fnames (cbuf_as_string (dir , (size_t )(p - dir )),fixed_fname , true); 1478xfree (fname ); 1479 1480return d .data ; 1481} 1482 1483// PID of swapfile owner, or zero if not running. 1484static int proc_running ; 1485 1486/// For Vimscript "swapinfo()". 1487/// 1488/// @return information found in swapfile "fname" in dictionary "d". 1489void swapfile_dict (const char * fname ,dict_T * d ) 1490{ 1491int fd ; 1492ZeroBlock b0 ; 1493 1494if ((fd = os_open (fname ,O_RDONLY ,0 )) >=0 ) { 1495if (read_eintr (fd ,& b0 ,sizeof (b0 ))== sizeof (b0 )) { 1496if (ml_check_b0_id (& b0 )== FAIL ) { 1497tv_dict_add_str_len (d ,S_LEN ("error" ),S_LEN ("Not a swap file" )); 1498 }else if (b0_magic_wrong (& b0 )) { 1499tv_dict_add_str_len (d ,S_LEN ("error" ),S_LEN ("Magic number mismatch" )); 1500 }else { 1501// We have swap information. 1502tv_dict_add_str_len (d ,S_LEN ("version" ),b0 .b0_version ,10 ); 1503tv_dict_add_str_len (d ,S_LEN ("user" ),b0 .b0_uname , 1504B0_UNAME_SIZE ); 1505tv_dict_add_str_len (d ,S_LEN ("host" ),b0 .b0_hname , 1506B0_HNAME_SIZE ); 1507tv_dict_add_str_len (d ,S_LEN ("fname" ),b0 .b0_fname , 1508B0_FNAME_SIZE_ORG ); 1509 1510tv_dict_add_nr (d ,S_LEN ("pid" ),swapfile_proc_running (& b0 ,fname )); 1511tv_dict_add_nr (d ,S_LEN ("mtime" ),char_to_long (b0 .b0_mtime )); 1512tv_dict_add_nr (d ,S_LEN ("dirty" ),b0 .b0_dirty ?1 :0 ); 1513tv_dict_add_nr (d ,S_LEN ("inode" ),char_to_long (b0 .b0_ino )); 1514 } 1515 }else { 1516tv_dict_add_str_len (d ,S_LEN ("error" ),S_LEN ("Cannot read file" )); 1517 } 1518close (fd ); 1519 }else { 1520tv_dict_add_str_len (d ,S_LEN ("error" ),S_LEN ("Cannot open file" )); 1521 } 1522} 1523 1524/// Loads info from swapfile `fname`, and displays it to the user. 1525/// 1526/// @return timestamp (0 when unknown). 1527static time_t swapfile_info (char * fname ,StringBuilder * msg ) 1528{ 1529assert (fname != NULL ); 1530ZeroBlock b0 ; 1531time_t x = (time_t )0 ; 1532#ifdef UNIX 1533char uname [B0_UNAME_SIZE ]; 1534#endif 1535 1536// print the swapfile date 1537FileInfo file_info ; 1538if (os_fileinfo (fname ,& file_info )) { 1539#ifdef UNIX 1540// print name of owner of the file 1541if (os_get_uname ((uv_uid_t )file_info .stat .st_uid ,uname ,B0_UNAME_SIZE )== OK ) { 1542kv_printf (* msg ,"%s%s" ,_ (" owned by: " ),uname ); 1543kv_printf (* msg ,_ (" dated: " )); 1544 }else { 1545kv_printf (* msg ,_ (" dated: " )); 1546 } 1547#else 1548kv_printf (* msg ,_ (" dated: " )); 1549#endif 1550x = file_info .stat .st_mtim .tv_sec ; 1551char ctime_buf [100 ];// hopefully enough for every language 1552kv_printf (* msg ,"%s" ,os_ctime_r (& x ,ctime_buf ,sizeof (ctime_buf ), true)); 1553 } 1554 1555// print the original file name 1556int fd = os_open (fname ,O_RDONLY ,0 ); 1557if (fd >=0 ) { 1558if (read_eintr (fd ,& b0 ,sizeof (b0 ))== sizeof (b0 )) { 1559if (strncmp (b0 .b0_version ,"VIM 3.0" ,7 )== 0 ) { 1560kv_printf (* msg ,_ (" [from Vim version 3.0]" )); 1561 }else if (ml_check_b0_id (& b0 )== FAIL ) { 1562kv_printf (* msg ,_ (" [does not look like a Nvim swap file]" )); 1563 }else if (!ml_check_b0_strings (& b0 )) { 1564kv_printf (* msg ,_ (" [garbled strings (not nul terminated)]" )); 1565 }else { 1566kv_printf (* msg ,_ (" file name: " )); 1567if (b0 .b0_fname [0 ]== NUL ) { 1568kv_printf (* msg ,_ ("[No Name]" )); 1569 }else { 1570kv_printf (* msg ,"%s" ,b0 .b0_fname ); 1571 } 1572 1573kv_printf (* msg ,_ ("\n modified: " )); 1574kv_printf (* msg ,b0 .b0_dirty ?_ ("YES" ) :_ ("no" )); 1575 1576if (* (b0 .b0_uname )!= NUL ) { 1577kv_printf (* msg ,_ ("\n user name: " )); 1578kv_printf (* msg ,"%s" ,b0 .b0_uname ); 1579 } 1580 1581if (* (b0 .b0_hname )!= NUL ) { 1582if (* (b0 .b0_uname )!= NUL ) { 1583kv_printf (* msg ,_ (" host name: " )); 1584 }else { 1585kv_printf (* msg ,_ ("\n host name: " )); 1586 } 1587kv_printf (* msg ,"%s" ,b0 .b0_hname ); 1588 } 1589 1590if (char_to_long (b0 .b0_pid )!= 0 ) { 1591kv_printf (* msg ,_ ("\n process ID: " )); 1592kv_printf (* msg ,"%d" , (int )char_to_long (b0 .b0_pid )); 1593if ((proc_running = swapfile_proc_running (& b0 ,fname ))) { 1594kv_printf (* msg ,_ (" (STILL RUNNING)" )); 1595 } 1596 } 1597 1598if (b0_magic_wrong (& b0 )) { 1599kv_printf (* msg ,_ ("\n [not usable on this computer]" )); 1600 } 1601 } 1602 }else { 1603kv_printf (* msg ,_ (" [cannot be read]" )); 1604 } 1605close (fd ); 1606 }else { 1607kv_printf (* msg ,_ (" [cannot be opened]" )); 1608 } 1609kv_printf (* msg ,"\n" ); 1610 1611return x ; 1612} 1613 1614/// @return true if the swapfile looks OK and there are no changes, thus it can be safely deleted. 1615static bool swapfile_unchanged (char * fname ) 1616{ 1617ZeroBlock b0 ; 1618 1619// Swapfile must exist. 1620if (!os_path_exists (fname )) { 1621return false; 1622 } 1623 1624// must be able to read the first block 1625int fd = os_open (fname ,O_RDONLY ,0 ); 1626if (fd < 0 ) { 1627return false; 1628 } 1629if (read_eintr (fd ,& b0 ,sizeof (b0 ))!= sizeof (b0 )) { 1630close (fd ); 1631return false; 1632 } 1633 1634bool ret = true; 1635 1636// the ID and magic number must be correct 1637if (ml_check_b0_id (& b0 )== FAIL || b0_magic_wrong (& b0 )) { 1638ret = false; 1639 } 1640 1641// must be unchanged 1642if (b0 .b0_dirty ) { 1643ret = false; 1644 } 1645 1646// Host name must be known and must equal the current host name, otherwise 1647// comparing pid is meaningless. 1648if (* (b0 .b0_hname )== NUL ) { 1649ret = false; 1650 }else { 1651char hostname [B0_HNAME_SIZE ]; 1652os_get_hostname (hostname ,B0_HNAME_SIZE ); 1653hostname [B0_HNAME_SIZE - 1 ]= NUL ; 1654b0 .b0_hname [B0_HNAME_SIZE - 1 ]= NUL ;// in case of corruption 1655if (STRICMP (b0 .b0_hname ,hostname )!= 0 ) { 1656ret = false; 1657 } 1658 } 1659 1660// process must be known and not running. 1661if (char_to_long (b0 .b0_pid )== 0 || swapfile_proc_running (& b0 ,fname )) { 1662ret = false; 1663 } 1664 1665// We do not check the user, it should be irrelevant for whether the swap 1666// file is still useful. 1667 1668close (fd ); 1669return ret ; 1670} 1671 1672static int recov_file_names (char ** names ,char * path ,bool prepend_dot ) 1673FUNC_ATTR_NONNULL_ALL 1674{ 1675int num_names = 0 ; 1676 1677// May also add the file name with a dot prepended, for swapfile in same 1678// dir as original file. 1679if (prepend_dot ) { 1680names [num_names ]= modname (path ,".sw?" , true); 1681if (names [num_names ]== NULL ) { 1682return num_names ; 1683 } 1684num_names ++ ; 1685 } 1686 1687// Form the normal swapfile name pattern by appending ".sw?". 1688names [num_names ]= concat_fnames (cstr_as_string (path ), 1689STATIC_CSTR_AS_STRING (".sw?" ), false).data ; 1690if (num_names >=1 ) {// check if we have the same name twice 1691char * p = names [num_names - 1 ]; 1692int i = (int )strlen (names [num_names - 1 ])- (int )strlen (names [num_names ]); 1693if (i > 0 ) { 1694p += i ;// file name has been expanded to full path 1695 } 1696if (strcmp (p ,names [num_names ])!= 0 ) { 1697num_names ++ ; 1698 }else { 1699xfree (names [num_names ]); 1700 } 1701 }else { 1702num_names ++ ; 1703 } 1704 1705return num_names ; 1706} 1707 1708/// sync all memlines 1709/// 1710/// @param check_file if true, check if original file exists and was not changed. 1711/// @param check_char if true, stop syncing when character becomes available, but 1712/// 1713/// always sync at least one block. 1714void ml_sync_all (int check_file ,int check_char ,bool do_fsync ) 1715{ 1716FOR_ALL_BUFFERS (buf ) { 1717if (buf -> b_ml .ml_mfp == NULL || buf -> b_ml .ml_mfp -> mf_fname == NULL ) { 1718continue ;// no file 1719 } 1720ml_flush_line (buf , false);// flush buffered line 1721// flush locked block 1722ml_find_line (buf ,0 ,ML_FLUSH ); 1723if (bufIsChanged (buf )&& check_file && mf_need_trans (buf -> b_ml .ml_mfp ) 1724&& buf -> b_ffname != NULL ) { 1725// If the original file does not exist anymore or has been changed 1726// call ml_preserve() to get rid of all negative numbered blocks. 1727FileInfo file_info ; 1728if (!os_fileinfo (buf -> b_ffname ,& file_info ) 1729|| file_info .stat .st_mtim .tv_sec != buf -> b_mtime_read 1730|| file_info .stat .st_mtim .tv_nsec != buf -> b_mtime_read_ns 1731|| os_fileinfo_size (& file_info )!= buf -> b_orig_size ) { 1732ml_preserve (buf , false,do_fsync ); 1733did_check_timestamps = false; 1734need_check_timestamps = true;// give message later 1735 } 1736 } 1737if (buf -> b_ml .ml_mfp -> mf_dirty == MF_DIRTY_YES ) { 1738mf_sync (buf -> b_ml .ml_mfp , (check_char ?MFS_STOP :0 ) 1739 | (do_fsync && bufIsChanged (buf ) ?MFS_FLUSH :0 )); 1740if (check_char && os_char_avail ()) {// character available now 1741break ; 1742 } 1743 } 1744 } 1745} 1746 1747/// sync one buffer, including negative blocks 1748/// 1749/// after this all the blocks are in the swapfile 1750/// 1751/// Used for the :preserve command and when the original file has been 1752/// changed or deleted. 1753/// 1754/// @param message if true, the success of preserving is reported. 1755void ml_preserve (buf_T * buf ,bool message ,bool do_fsync ) 1756{ 1757memfile_T * mfp = buf -> b_ml .ml_mfp ; 1758int got_int_save = got_int ; 1759 1760if (mfp == NULL || mfp -> mf_fname == NULL ) { 1761if (message ) { 1762emsg (_ ("E313: Cannot preserve, there is no swap file" )); 1763 } 1764return ; 1765 } 1766 1767// We only want to stop when interrupted here, not when interrupted 1768// before. 1769got_int = false; 1770 1771ml_flush_line (buf , false);// flush buffered line 1772ml_find_line (buf ,0 ,ML_FLUSH );// flush locked block 1773int status = mf_sync (mfp ,MFS_ALL | (do_fsync ?MFS_FLUSH :0 )); 1774 1775// stack is invalid after mf_sync(.., MFS_ALL) 1776buf -> b_ml .ml_stack_top = 0 ; 1777 1778// Some of the data blocks may have been changed from negative to 1779// positive block number. In that case the pointer blocks need to be 1780// updated. 1781// 1782// We don't know in which pointer block the references are, so we visit 1783// all data blocks until there are no more translations to be done (or 1784// we hit the end of the file, which can only happen in case a write fails, 1785// e.g. when file system if full). 1786// ml_find_line() does the work by translating the negative block numbers 1787// when getting the first line of each data block. 1788if (mf_need_trans (mfp )&& !got_int ) { 1789linenr_T lnum = 1 ; 1790while (mf_need_trans (mfp )&& lnum <=buf -> b_ml .ml_line_count ) { 1791bhdr_T * hp = ml_find_line (buf ,lnum ,ML_FIND ); 1792if (hp == NULL ) { 1793status = FAIL ; 1794 gototheend ; 1795 } 1796CHECK (buf -> b_ml .ml_locked_low != lnum ,"low != lnum" ); 1797lnum = buf -> b_ml .ml_locked_high + 1 ; 1798 } 1799ml_find_line (buf ,0 ,ML_FLUSH );// flush locked block 1800// sync the updated pointer blocks 1801if (mf_sync (mfp ,MFS_ALL | (do_fsync ?MFS_FLUSH :0 ))== FAIL ) { 1802status = FAIL ; 1803 } 1804buf -> b_ml .ml_stack_top = 0 ;// stack is invalid now 1805 } 1806theend : 1807got_int |=got_int_save ; 1808 1809if (message ) { 1810if (status == OK ) { 1811msg (_ ("File preserved" ),0 ); 1812 }else { 1813emsg (_ ("E314: Preserve failed" )); 1814 } 1815 } 1816} 1817 1818// NOTE: The pointer returned by the ml_get_*() functions only remains valid 1819// until the next call! 1820// line1 = ml_get(1); 1821// line2 = ml_get(2); // line1 is now invalid! 1822// Make a copy of the line if necessary. 1823 1824/// @return a pointer to a (read-only copy of a) line in curbuf. 1825/// 1826/// On failure an error message is given and IObuff is returned (to avoid 1827/// having to check for error everywhere). 1828char * ml_get (linenr_T lnum ) 1829FUNC_ATTR_NONNULL_RET 1830{ 1831return ml_get_buf_impl (curbuf ,lnum , false); 1832} 1833 1834/// @return a pointer to a (read-only copy of a) line. 1835/// 1836/// This is the same as ml_get(), but taking in the buffer 1837/// as an argument. 1838char * ml_get_buf (buf_T * buf ,linenr_T lnum ) 1839FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 1840{ 1841return ml_get_buf_impl (buf ,lnum , false); 1842} 1843 1844/// Like `ml_get_buf`, but allow the line to be mutated in place. 1845/// 1846/// This is very limited. Generally ml_replace_buf() 1847/// should be used to modify a line. 1848/// 1849/// @return a pointer to a line in the buffer 1850char * ml_get_buf_mut (buf_T * buf ,linenr_T lnum ) 1851FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 1852{ 1853return ml_get_buf_impl (buf ,lnum , true); 1854} 1855 1856/// @return pointer to position "pos". 1857char * ml_get_pos (const pos_T * pos ) 1858FUNC_ATTR_NONNULL_ALL 1859{ 1860return ml_get_buf (curbuf ,pos -> lnum )+ pos -> col ; 1861} 1862 1863/// @return length (excluding the NUL) of the given line. 1864colnr_T ml_get_len (linenr_T lnum ) 1865{ 1866return ml_get_buf_len (curbuf ,lnum ); 1867} 1868 1869/// @return length (excluding the NUL) of the text after position "pos". 1870colnr_T ml_get_pos_len (pos_T * pos ) 1871{ 1872return ml_get_buf_len (curbuf ,pos -> lnum )- pos -> col ; 1873} 1874 1875/// @return length (excluding the NUL) of the given line in the given buffer. 1876colnr_T ml_get_buf_len (buf_T * buf ,linenr_T lnum ) 1877{ 1878const char * line = ml_get_buf (buf ,lnum ); 1879 1880if (* line == NUL ) { 1881return 0 ; 1882 } 1883 1884assert (buf -> b_ml .ml_line_textlen > 0 ); 1885return buf -> b_ml .ml_line_textlen - 1 ; 1886} 1887 1888/// Gets the charwise NL-joined text of range [start, end), 1-based lnum, 0-based col, end col 1889/// exclusive, as an allocated String ("" if empty). Line range must be valid (start <= end); cols 1890/// clamp to line-length. 1891String ml_region_text (buf_T * buf ,pos_T start ,pos_T end ) 1892FUNC_ATTR_NONNULL_ALL 1893{ 1894StringBuilder sb = KV_INITIAL_VALUE ; 1895for (linenr_T lnum = start .lnum ;lnum <=end .lnum ;lnum ++ ) { 1896char * line = ml_get_buf (buf ,lnum ); 1897colnr_T len = ml_get_buf_len (buf ,lnum ); 1898colnr_T from = lnum == start .lnum ?MIN (start .col ,len ) :0 ; 1899colnr_T to = lnum == end .lnum ?MIN (end .col ,len ) :len ; 1900kv_concat_len (sb ,line + from , (size_t )(to - from )); 1901if (lnum < end .lnum ) { 1902kv_push (sb ,NL ); 1903 } 1904 } 1905kv_push (sb ,NUL ); 1906return cbuf_as_string (sb .items ,kv_size (sb )- 1 ); 1907} 1908 1909/// @return codepoint at pos. pos must be either valid or have col set to MAXCOL! 1910int gchar_pos (pos_T * pos ) 1911FUNC_ATTR_NONNULL_ARG (1 ) 1912{ 1913// When searching columns is sometimes put at the end of a line. 1914if (pos -> col == MAXCOL || pos -> col > ml_get_len (pos -> lnum )) { 1915return NUL ; 1916 } 1917return utf_ptr2char (ml_get_pos (pos )); 1918} 1919 1920/// @param will_change true mark the buffer dirty (chars in the line will be changed) 1921/// 1922/// @return a pointer to a line in a specific buffer 1923static char * ml_get_buf_impl (buf_T * buf ,linenr_T lnum ,bool will_change ) 1924FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 1925{ 1926static int recursive = 0 ; 1927static char questions [4 ]; 1928 1929if (buf -> b_ml .ml_mfp == NULL ) {// there are no lines 1930buf -> b_ml .ml_line_textlen = 1 ; 1931return "" ; 1932 } 1933 1934if (lnum > buf -> b_ml .ml_line_count ) {// invalid line number 1935if (recursive == 0 ) { 1936// Avoid giving this message for a recursive call, may happen when 1937// the GUI redraws part of the text. 1938recursive ++ ; 1939siemsg (_ (e_ml_get_invalid_lnum_nr ), (int64_t )lnum ); 1940recursive -- ; 1941 } 1942ml_flush_line (buf , false); 1943errorret : 1944STRCPY (questions ,"???" ); 1945buf -> b_ml .ml_line_textlen = 4 ; 1946buf -> b_ml .ml_line_lnum = lnum ; 1947return questions ; 1948 } 1949lnum = MAX (lnum ,1 );// pretend line 0 is line 1 1950 1951// See if it is the same line as requested last time. 1952// Otherwise may need to flush last used line. 1953// Don't use the last used line when 'swapfile' is reset, need to load all 1954// blocks. 1955if (buf -> b_ml .ml_line_lnum != lnum ) { 1956ml_flush_line (buf , false); 1957 1958// Find the data block containing the line. 1959// This also fills the stack with the blocks from the root to the data 1960// block and releases any locked block. 1961bhdr_T * hp ; 1962if ((hp = ml_find_line (buf ,lnum ,ML_FIND ))== NULL ) { 1963if (recursive == 0 ) { 1964// Avoid giving this message for a recursive call, may happen 1965// when the GUI redraws part of the text. 1966recursive ++ ; 1967get_trans_bufname (buf ); 1968shorten_dir (NameBuff ); 1969siemsg (_ (e_ml_get_cannot_find_line_nr_in_buffer_nr_str ), 1970 (int64_t )lnum ,buf -> b_fnum ,NameBuff ); 1971recursive -- ; 1972 } 1973 gotoerrorret ; 1974 } 1975 1976DataBlock * dp = hp -> bh_data ; 1977 1978int idx = lnum - buf -> b_ml .ml_locked_low ; 1979unsigned start = (dp -> db_index [idx ]& DB_INDEX_MASK ); 1980// The text ends where the previous line starts. The first line ends 1981// at the end of the block. 1982unsigned end = idx == 0 ?dp -> db_txt_end : (dp -> db_index [idx - 1 ]& DB_INDEX_MASK ); 1983 1984buf -> b_ml .ml_line_ptr = (char * )dp + start ; 1985buf -> b_ml .ml_line_textlen = (colnr_T )(end - start ); 1986buf -> b_ml .ml_line_lnum = lnum ; 1987buf -> b_ml .ml_flags &= ~(ML_LINE_DIRTY |ML_ALLOCATED ); 1988 } 1989if (will_change ) { 1990buf -> b_ml .ml_flags |= (ML_LOCKED_DIRTY |ML_LOCKED_POS ); 1991#ifdef ML_GET_ALLOC_LINES 1992if (buf -> b_ml .ml_flags & ML_ALLOCATED ) { 1993// can't make the change in the data block 1994buf -> b_ml .ml_flags |=ML_LINE_DIRTY ; 1995 } 1996#endif 1997ml_add_deleted_len_buf (buf ,buf -> b_ml .ml_line_ptr ,-1 ); 1998 } 1999 2000#ifdef ML_GET_ALLOC_LINES 2001if ((buf -> b_ml .ml_flags & (ML_LINE_DIRTY |ML_ALLOCATED ))== 0 ) { 2002// make sure the text is in allocated memory 2003buf -> b_ml .ml_line_ptr = xmemdup (buf -> b_ml .ml_line_ptr , 2004 (size_t )buf -> b_ml .ml_line_textlen ); 2005buf -> b_ml .ml_flags |=ML_ALLOCATED ; 2006if (will_change ) { 2007// can't make the change in the data block 2008buf -> b_ml .ml_flags |=ML_LINE_DIRTY ; 2009 } 2010 } 2011#endif 2012return buf -> b_ml .ml_line_ptr ; 2013} 2014 2015/// Check if a line that was just obtained by a call to ml_get 2016/// is in allocated memory. 2017/// This ignores ML_ALLOCATED to get the same behavior as without ML_GET_ALLOC_LINES. 2018int ml_line_alloced (void ) 2019{ 2020return curbuf -> b_ml .ml_flags & ML_LINE_DIRTY ; 2021} 2022 2023/// @param lnum append after this line (can be 0) 2024/// @param line_arg text of the new line 2025/// @param len_arg length of line, including NUL, or 0 2026/// @param flags ML_APPEND_ flags 2027/// 2028/// @return FAIL for failure, OK otherwise 2029static int ml_append_int (buf_T * buf ,linenr_T lnum ,char * line_arg ,colnr_T len_arg ,int flags ) 2030FUNC_ATTR_NONNULL_ARG (1 ) 2031{ 2032char * line = line_arg ; 2033colnr_T len = len_arg ; 2034 2035if (lnum > buf -> b_ml .ml_line_count || buf -> b_ml .ml_mfp == NULL ) { 2036return FAIL ;// lnum out of range 2037 } 2038 2039if (lowest_marked && lowest_marked > lnum ) { 2040lowest_marked = lnum + 1 ; 2041 } 2042 2043if (len == 0 ) { 2044len = (colnr_T )strlen (line )+ 1 ;// space needed for the text 2045 } 2046int64_t space_needed = len + (int64_t )INDEX_SIZE ;// space needed for text + index 2047 2048memfile_T * mfp = buf -> b_ml .ml_mfp ; 2049int64_t page_size = mfp -> mf_page_size ; 2050 2051// find the data block containing the previous line 2052// This also fills the stack with the blocks from the root to the data block 2053// This also releases any locked block. 2054int ret = FAIL ; 2055bhdr_T * hp ; 2056if ((hp = ml_find_line (buf ,lnum == 0 ?1 :lnum , 2057ML_INSERT ))== NULL ) { 2058 gototheend ; 2059 } 2060 2061buf -> b_ml .ml_flags &= ~ML_EMPTY ; 2062 2063int db_idx ;// index for lnum in data block 2064if (lnum == 0 ) {// got line one instead, correct db_idx 2065db_idx = -1 ;// careful, it is negative! 2066 }else { 2067db_idx = lnum - buf -> b_ml .ml_locked_low ; 2068 } 2069// get line count (number of indexes in current block) before the insertion 2070int line_count = buf -> b_ml .ml_locked_high - buf -> b_ml .ml_locked_low ; 2071 2072DataBlock * dp = hp -> bh_data ; 2073 2074// If 2075// - there is not enough room in the current block 2076// - appending to the last line in the block 2077// - not appending to the last line in the file 2078// insert in front of the next block. 2079if ((int64_t )dp -> db_free < space_needed && db_idx == line_count - 1 2080&& lnum < buf -> b_ml .ml_line_count ) { 2081// Now that the line is not going to be inserted in the block that we 2082// expected, the line count has to be adjusted in the pointer blocks 2083// by using ml_locked_lineadd. 2084 (buf -> b_ml .ml_locked_lineadd )-- ; 2085 (buf -> b_ml .ml_locked_high )-- ; 2086if ((hp = ml_find_line (buf ,lnum + 1 ,ML_INSERT ))== NULL ) { 2087 gototheend ; 2088 } 2089 2090db_idx = -1 ;// careful, it is negative! 2091// get line count before the insertion 2092line_count = buf -> b_ml .ml_locked_high - buf -> b_ml .ml_locked_low ; 2093CHECK (buf -> b_ml .ml_locked_low != lnum + 1 ,"locked_low != lnum + 1" ); 2094 2095dp = hp -> bh_data ; 2096 } 2097 2098if (buf -> b_prev_line_count == 0 ) { 2099buf -> b_prev_line_count = buf -> b_ml .ml_line_count ; 2100 } 2101buf -> b_ml .ml_line_count ++ ; 2102 2103if ((int64_t )dp -> db_free >=space_needed ) {// enough room in data block 2104// Insert the new line in an existing data block, or in the data block 2105// allocated above. 2106dp -> db_txt_start -= (unsigned )len ; 2107dp -> db_free -= (unsigned )space_needed ; 2108dp -> db_line_count ++ ; 2109 2110// move the text of the lines that follow to the front 2111// adjust the indexes of the lines that follow 2112if (line_count > db_idx + 1 ) {// if there are following lines 2113// Offset is the start of the previous line. 2114// This will become the character just after the new line. 2115int offset = db_idx < 0 ? (int )dp -> db_txt_end 2116 : (int )((dp -> db_index [db_idx ])& DB_INDEX_MASK ); 2117memmove ((char * )dp + dp -> db_txt_start , 2118 (char * )dp + dp -> db_txt_start + len , 2119 (size_t )offset - (dp -> db_txt_start + (size_t )len )); 2120for (int i = line_count - 1 ;i > db_idx ;i -- ) { 2121dp -> db_index [i + 1 ]= dp -> db_index [i ]- (unsigned )len ; 2122 } 2123dp -> db_index [db_idx + 1 ]= (unsigned )(offset - len ); 2124 }else { 2125// add line at the end (which is the start of the text) 2126dp -> db_index [db_idx + 1 ]= dp -> db_txt_start ; 2127 } 2128 2129// copy the text into the block 2130memmove ((char * )dp + dp -> db_index [db_idx + 1 ],line , (size_t )len ); 2131if (flags & ML_APPEND_MARK ) { 2132dp -> db_index [db_idx + 1 ] |=DB_MARKED ; 2133 } 2134 2135// Mark the block dirty. 2136buf -> b_ml .ml_flags |=ML_LOCKED_DIRTY ; 2137if (!(flags & ML_APPEND_NEW )) { 2138buf -> b_ml .ml_flags |=ML_LOCKED_POS ; 2139 } 2140 }else {// not enough space in data block 2141int line_count_left ,line_count_right ; 2142int page_count_left ,page_count_right ; 2143bhdr_T * hp_left ; 2144bhdr_T * hp_right ; 2145bhdr_T * hp_new ; 2146int lines_moved ; 2147int data_moved = 0 ;// init to shut up gcc 2148int total_moved = 0 ;// init to shut up gcc 2149int stack_idx ; 2150bool in_left ; 2151linenr_T lnum_left ,lnum_right ; 2152PointerBlock * pp_new ; 2153 2154// There is not enough room, we have to create a new data block and 2155// copy some lines into it. 2156// Then we have to insert an entry in the pointer block. 2157// If this pointer block also is full, we go up another block, and so 2158// on, up to the root if necessary. 2159// The line counts in the pointer blocks have already been adjusted by 2160// ml_find_line(). 2161// 2162// We are going to allocate a new data block. Depending on the 2163// situation it will be put to the left or right of the existing 2164// block. If possible we put the new line in the left block and move 2165// the lines after it to the right block. Otherwise the new line is 2166// also put in the right block. This method is more efficient when 2167// inserting a lot of lines at one place. 2168if (db_idx < 0 ) {// left block is new, right block is existing 2169lines_moved = 0 ; 2170in_left = true; 2171// space_needed does not change 2172 }else {// left block is existing, right block is new 2173lines_moved = line_count - db_idx - 1 ; 2174if (lines_moved == 0 ) { 2175in_left = false;// put new line in right block 2176// space_needed does not change 2177 }else { 2178data_moved = (int )(((dp -> db_index [db_idx ])& DB_INDEX_MASK )- 2179dp -> db_txt_start ); 2180total_moved = data_moved + lines_moved * (int )INDEX_SIZE ; 2181if ((int64_t )dp -> db_free + total_moved >=space_needed ) { 2182in_left = true;// put new line in left block 2183space_needed = total_moved ; 2184 }else { 2185in_left = false;// put new line in right block 2186space_needed += total_moved ; 2187 } 2188 } 2189 } 2190 2191int64_t page_count = ((space_needed + (int64_t )HEADER_SIZE )+ page_size - 1 ) /page_size ; 2192hp_new = ml_new_data (mfp ,flags & ML_APPEND_NEW ,page_count ); 2193if (db_idx < 0 ) {// left block is new 2194hp_left = hp_new ; 2195hp_right = hp ; 2196line_count_left = 0 ; 2197line_count_right = line_count ; 2198 }else {// right block is new 2199hp_left = hp ; 2200hp_right = hp_new ; 2201line_count_left = line_count ; 2202line_count_right = 0 ; 2203 } 2204DataBlock * dp_right = hp_right -> bh_data ; 2205DataBlock * dp_left = hp_left -> bh_data ; 2206blocknr_T bnum_left = hp_left -> bh_bnum ; 2207blocknr_T bnum_right = hp_right -> bh_bnum ; 2208page_count_left = (int )hp_left -> bh_page_count ; 2209page_count_right = (int )hp_right -> bh_page_count ; 2210 2211// May move the new line into the right/new block. 2212if (!in_left ) { 2213dp_right -> db_txt_start -= (unsigned )len ; 2214dp_right -> db_free -= (unsigned )len + (unsigned )INDEX_SIZE ; 2215dp_right -> db_index [0 ]= dp_right -> db_txt_start ; 2216if (flags & ML_APPEND_MARK ) { 2217dp_right -> db_index [0 ] |=DB_MARKED ; 2218 } 2219 2220memmove ((char * )dp_right + dp_right -> db_txt_start , 2221line , (size_t )len ); 2222line_count_right ++ ; 2223 } 2224// may move lines from the left/old block to the right/new one. 2225if (lines_moved ) { 2226dp_right -> db_txt_start -= (unsigned )data_moved ; 2227dp_right -> db_free -= (unsigned )total_moved ; 2228memmove ((char * )dp_right + dp_right -> db_txt_start , 2229 (char * )dp_left + dp_left -> db_txt_start , 2230 (size_t )data_moved ); 2231int offset = (int )(dp_right -> db_txt_start - dp_left -> db_txt_start ); 2232dp_left -> db_txt_start += (unsigned )data_moved ; 2233dp_left -> db_free += (unsigned )total_moved ; 2234 2235// update indexes in the new block 2236for (int to = line_count_right ,from = db_idx + 1 ; 2237from < line_count_left ;from ++ ,to ++ ) { 2238dp_right -> db_index [to ]= dp -> db_index [from ]+ (unsigned )offset ; 2239 } 2240line_count_right += lines_moved ; 2241line_count_left -= lines_moved ; 2242 } 2243 2244// May move the new line into the left (old or new) block. 2245if (in_left ) { 2246dp_left -> db_txt_start -= (unsigned )len ; 2247dp_left -> db_free -= (unsigned )len + (unsigned )INDEX_SIZE ; 2248dp_left -> db_index [line_count_left ]= dp_left -> db_txt_start ; 2249if (flags & ML_APPEND_MARK ) { 2250dp_left -> db_index [line_count_left ] |=DB_MARKED ; 2251 } 2252memmove ((char * )dp_left + dp_left -> db_txt_start , 2253line , (size_t )len ); 2254line_count_left ++ ; 2255 } 2256 2257if (db_idx < 0 ) {// left block is new 2258lnum_left = lnum + 1 ; 2259lnum_right = 0 ; 2260 }else {// right block is new 2261lnum_left = 0 ; 2262if (in_left ) { 2263lnum_right = lnum + 2 ; 2264 }else { 2265lnum_right = lnum + 1 ; 2266 } 2267 } 2268dp_left -> db_line_count = line_count_left ; 2269dp_right -> db_line_count = line_count_right ; 2270 2271// release the two data blocks 2272// The new one (hp_new) already has a correct blocknumber. 2273// The old one (hp, in ml_locked) gets a positive blocknumber if 2274// we changed it and we are not editing a new file. 2275if (lines_moved || in_left ) { 2276buf -> b_ml .ml_flags |=ML_LOCKED_DIRTY ; 2277 } 2278if (!(flags & ML_APPEND_NEW )&& db_idx >=0 && in_left ) { 2279buf -> b_ml .ml_flags |=ML_LOCKED_POS ; 2280 } 2281mf_put (mfp ,hp_new , true, false); 2282 2283// flush the old data block 2284// set ml_locked_lineadd to 0, because the updating of the 2285// pointer blocks is done below 2286int lineadd = buf -> b_ml .ml_locked_lineadd ; 2287buf -> b_ml .ml_locked_lineadd = 0 ; 2288ml_find_line (buf ,0 ,ML_FLUSH );// flush data block 2289 2290// update pointer blocks for the new data block 2291for (stack_idx = buf -> b_ml .ml_stack_top - 1 ;stack_idx >=0 ;stack_idx -- ) { 2292infoptr_T * ip = & (buf -> b_ml .ml_stack [stack_idx ]); 2293int pb_idx = ip -> ip_index ; 2294if ((hp = mf_get (mfp ,ip -> ip_bnum ,1 ))== NULL ) { 2295 gototheend ; 2296 } 2297PointerBlock * pp = hp -> bh_data ;// must be pointer block 2298if (pp -> pb_id != PTR_ID ) { 2299iemsg (_ (e_pointer_block_id_wrong_three )); 2300mf_put (mfp ,hp , false, false); 2301 gototheend ; 2302 } 2303// TODO(vim): If the pointer block is full and we are adding at the end 2304// try to insert in front of the next block 2305// block not full, add one entry 2306if (pp -> pb_count < pp -> pb_count_max ) { 2307if (pb_idx + 1 < (int )pp -> pb_count ) { 2308memmove (& pp -> pb_pointer [pb_idx + 2 ], 2309& pp -> pb_pointer [pb_idx + 1 ], 2310 (size_t )(pp -> pb_count - pb_idx - 1 )* sizeof (PointerEntry )); 2311 } 2312pp -> pb_count ++ ; 2313pp -> pb_pointer [pb_idx ].pe_line_count = line_count_left ; 2314pp -> pb_pointer [pb_idx ].pe_bnum = bnum_left ; 2315pp -> pb_pointer [pb_idx ].pe_page_count = page_count_left ; 2316pp -> pb_pointer [pb_idx + 1 ].pe_line_count = line_count_right ; 2317pp -> pb_pointer [pb_idx + 1 ].pe_bnum = bnum_right ; 2318pp -> pb_pointer [pb_idx + 1 ].pe_page_count = page_count_right ; 2319 2320if (lnum_left != 0 ) { 2321pp -> pb_pointer [pb_idx ].pe_old_lnum = lnum_left ; 2322 } 2323if (lnum_right != 0 ) { 2324pp -> pb_pointer [pb_idx + 1 ].pe_old_lnum = lnum_right ; 2325 } 2326 2327mf_put (mfp ,hp , true, false); 2328buf -> b_ml .ml_stack_top = stack_idx + 1 ;// truncate stack 2329 2330if (lineadd ) { 2331 (buf -> b_ml .ml_stack_top )-- ; 2332// fix line count for rest of blocks in the stack 2333ml_lineadd (buf ,lineadd ); 2334// fix stack itself 2335buf -> b_ml .ml_stack [buf -> b_ml .ml_stack_top ].ip_high += lineadd ; 2336 (buf -> b_ml .ml_stack_top )++ ; 2337 } 2338 2339// We are finished, break the loop here. 2340break ; 2341 } 2342// pointer block full 2343// 2344// split the pointer block 2345// allocate a new pointer block 2346// move some of the pointer into the new block 2347// prepare for updating the parent block 2348while (true) {// do this twice when splitting block 1 2349hp_new = ml_new_ptr (mfp ); 2350if (hp_new == NULL ) {// TODO(vim): try to fix tree 2351 gototheend ; 2352 } 2353pp_new = hp_new -> bh_data ; 2354 2355if (hp -> bh_bnum != 1 ) { 2356break ; 2357 } 2358 2359// if block 1 becomes full the tree is given an extra level 2360// The pointers from block 1 are moved into the new block. 2361// block 1 is updated to point to the new block 2362// then continue to split the new block 2363memmove (pp_new ,pp , (size_t )page_size ); 2364pp -> pb_count = 1 ; 2365pp -> pb_pointer [0 ].pe_bnum = hp_new -> bh_bnum ; 2366pp -> pb_pointer [0 ].pe_line_count = buf -> b_ml .ml_line_count ; 2367pp -> pb_pointer [0 ].pe_old_lnum = 1 ; 2368pp -> pb_pointer [0 ].pe_page_count = 1 ; 2369mf_put (mfp ,hp , true, false);// release block 1 2370hp = hp_new ;// new block is to be split 2371pp = pp_new ; 2372CHECK (stack_idx != 0 ,_ ("stack_idx should be 0" )); 2373ip -> ip_index = 0 ; 2374stack_idx ++ ;// do block 1 again later 2375 } 2376// move the pointers after the current one to the new block 2377// If there are none, the new entry will be in the new block. 2378total_moved = pp -> pb_count - pb_idx - 1 ; 2379if (total_moved ) { 2380memmove (& pp_new -> pb_pointer [0 ], 2381& pp -> pb_pointer [pb_idx + 1 ], 2382 (size_t )total_moved * sizeof (PointerEntry )); 2383pp_new -> pb_count = (uint16_t )total_moved ; 2384pp -> pb_count = (uint16_t )(pp -> pb_count - (total_moved - 1 )); 2385pp -> pb_pointer [pb_idx + 1 ].pe_bnum = bnum_right ; 2386pp -> pb_pointer [pb_idx + 1 ].pe_line_count = line_count_right ; 2387pp -> pb_pointer [pb_idx + 1 ].pe_page_count = page_count_right ; 2388if (lnum_right ) { 2389pp -> pb_pointer [pb_idx + 1 ].pe_old_lnum = lnum_right ; 2390 } 2391 }else { 2392pp_new -> pb_count = 1 ; 2393pp_new -> pb_pointer [0 ].pe_bnum = bnum_right ; 2394pp_new -> pb_pointer [0 ].pe_line_count = line_count_right ; 2395pp_new -> pb_pointer [0 ].pe_page_count = page_count_right ; 2396pp_new -> pb_pointer [0 ].pe_old_lnum = lnum_right ; 2397 } 2398pp -> pb_pointer [pb_idx ].pe_bnum = bnum_left ; 2399pp -> pb_pointer [pb_idx ].pe_line_count = line_count_left ; 2400pp -> pb_pointer [pb_idx ].pe_page_count = page_count_left ; 2401if (lnum_left ) { 2402pp -> pb_pointer [pb_idx ].pe_old_lnum = lnum_left ; 2403 } 2404lnum_left = 0 ; 2405lnum_right = 0 ; 2406 2407// recompute line counts 2408line_count_right = 0 ; 2409for (int i = 0 ;i < (int )pp_new -> pb_count ;i ++ ) { 2410line_count_right += pp_new -> pb_pointer [i ].pe_line_count ; 2411 } 2412line_count_left = 0 ; 2413for (int i = 0 ;i < (int )pp -> pb_count ;i ++ ) { 2414line_count_left += pp -> pb_pointer [i ].pe_line_count ; 2415 } 2416 2417bnum_left = hp -> bh_bnum ; 2418bnum_right = hp_new -> bh_bnum ; 2419page_count_left = 1 ; 2420page_count_right = 1 ; 2421mf_put (mfp ,hp , true, false); 2422mf_put (mfp ,hp_new , true, false); 2423 } 2424 2425// Safety check: fallen out of for loop? 2426if (stack_idx < 0 ) { 2427iemsg (_ ("E318: Updated too many blocks?" )); 2428buf -> b_ml .ml_stack_top = 0 ;// invalidate stack 2429 } 2430 } 2431 2432// The line was inserted below 'lnum' 2433ml_updatechunk (buf ,lnum + 1 ,len ,ML_CHNK_ADDLINE ); 2434ret = OK ; 2435 2436theend : 2437return ret ; 2438} 2439 2440/// Flush any pending change and call ml_append_int() 2441/// 2442/// @param buf 2443/// @param lnum append after this line (can be 0) 2444/// @param line text of the new line 2445/// @param len length of line, including NUL, or 0 2446/// @param flags ML_APPEND_ flags 2447/// 2448/// @return FAIL for failure, OK otherwise 2449static int ml_append_flush (buf_T * buf ,linenr_T lnum ,char * line ,colnr_T len ,int flags ) 2450FUNC_ATTR_NONNULL_ARG (1 ) 2451{ 2452if (lnum > buf -> b_ml .ml_line_count ) { 2453return FAIL ;// lnum out of range 2454 } 2455if (buf -> b_ml .ml_line_lnum != 0 ) { 2456// This may also invoke ml_append_int(). 2457ml_flush_line (buf , false); 2458 } 2459 2460return ml_append_int (buf ,lnum ,line ,len ,flags ); 2461} 2462 2463/// Append a line after lnum (may be 0 to insert a line in front of the file). 2464/// "line" does not need to be allocated, but can't be another line in a 2465/// buffer, unlocking may make it invalid. 2466/// 2467/// "newfile": true when starting to edit a new file, meaning that pe_old_lnum 2468/// will be set for recovery 2469/// Check: The caller of this function should probably also call 2470/// appended_lines(). 2471/// 2472/// @param lnum append after this line (can be 0) 2473/// @param line text of the new line 2474/// @param len length of new line, including NUL, or 0 2475/// @param newfile flag, see above 2476/// 2477/// @return FAIL for failure, OK otherwise 2478int ml_append (linenr_T lnum ,char * line ,colnr_T len ,bool newfile ) 2479{ 2480return ml_append_flags (lnum ,line ,len ,newfile ?ML_APPEND_NEW :0 ); 2481} 2482 2483/// @param lnum append after this line (can be 0) 2484/// @param line text of the new line 2485/// @param len length of new line, including nul, or 0 2486/// @param flags ML_APPEND_ values 2487/// 2488/// @return FAIL for failure, OK otherwise 2489int ml_append_flags (linenr_T lnum ,char * line ,colnr_T len ,int flags ) 2490{ 2491// When starting up, we might still need to create the memfile 2492if (curbuf -> b_ml .ml_mfp == NULL && open_buffer (false,NULL ,0 )== FAIL ) { 2493return FAIL ; 2494 } 2495 2496return ml_append_flush (curbuf ,lnum ,line ,len ,flags ); 2497} 2498 2499/// Like ml_append() but for an arbitrary buffer. The buffer must already have 2500/// a memline. 2501/// 2502/// @param lnum append after this line (can be 0) 2503/// @param line text of the new line 2504/// @param len length of new line, including NUL, or 0 2505/// @param newfile flag, see above 2506int ml_append_buf (buf_T * buf ,linenr_T lnum ,char * line ,colnr_T len ,bool newfile ) 2507FUNC_ATTR_NONNULL_ARG (1 ) 2508{ 2509if (buf -> b_ml .ml_mfp == NULL ) { 2510return FAIL ; 2511 } 2512 2513return ml_append_flush (buf ,lnum ,line ,len ,newfile ?ML_APPEND_NEW :0 ); 2514} 2515 2516void ml_add_deleted_len (char * ptr ,ssize_t len ) 2517{ 2518ml_add_deleted_len_buf (curbuf ,ptr ,len ); 2519} 2520 2521void ml_add_deleted_len_buf (buf_T * buf ,char * ptr ,ssize_t len ) 2522{ 2523if (inhibit_delete_count ) { 2524return ; 2525 } 2526ssize_t maxlen = (ssize_t )strlen (ptr ); 2527if (len == -1 || len > maxlen ) { 2528len = maxlen ; 2529 } 2530buf -> deleted_bytes += (size_t )len + 1 ; 2531buf -> deleted_bytes2 += (size_t )len + 1 ; 2532if (buf -> update_need_codepoints ) { 2533mb_utflen (ptr , (size_t )len ,& buf -> deleted_codepoints , 2534& buf -> deleted_codeunits ); 2535buf -> deleted_codepoints ++ ;// NL char 2536buf -> deleted_codeunits ++ ; 2537 } 2538} 2539 2540/// Replace line "lnum", with buffering, in current buffer. 2541int ml_replace (linenr_T lnum ,char * line ,bool copy ) 2542{ 2543return ml_replace_buf (curbuf ,lnum ,line ,copy , false); 2544} 2545 2546/// Replace a line for the current buffer. Like ml_replace() with: 2547/// "len" is the length of the text, excluding NUL. 2548int ml_replace_len (linenr_T lnum ,char * line ,size_t len ,bool copy ) 2549{ 2550return ml_replace_buf_len (curbuf ,lnum ,line ,len ,copy , false); 2551} 2552 2553int ml_replace_buf (buf_T * buf ,linenr_T lnum ,char * line ,bool copy ,bool noalloc ) 2554FUNC_ATTR_NONNULL_ARG (1 ) 2555{ 2556size_t len = line != NULL ?strlen (line ) : (size_t )-1 ; 2557return ml_replace_buf_len (buf ,lnum ,line ,len ,copy ,noalloc ); 2558} 2559 2560/// Replace line "lnum", with buffering. 2561/// 2562/// @param copy if true, make a copy of the line, otherwise the line has been 2563/// copied to allocated memory already. 2564/// if false, the "line" may be freed to add text properties! 2565/// @param len_arg length of the text, excluding NUL 2566/// 2567/// Do not use it after calling ml_replace(). 2568/// 2569/// Check: The caller of this function should probably also call 2570/// changed_lines(), unless update_screen(UPD_NOT_VALID) is used. 2571/// 2572/// @return FAIL for failure, OK otherwise 2573int ml_replace_buf_len (buf_T * buf ,linenr_T lnum ,char * line_arg ,size_t len_arg ,bool copy , 2574bool noalloc ) 2575FUNC_ATTR_NONNULL_ARG (1 ) 2576{ 2577char * line = line_arg ; 2578 2579if (line == NULL ) {// just checking... 2580return FAIL ; 2581 } 2582 2583// When starting up, we might still need to create the memfile 2584if (buf -> b_ml .ml_mfp == NULL && open_buffer (false,NULL ,0 )== FAIL ) { 2585return FAIL ; 2586 } 2587 2588if (copy ) { 2589assert (!noalloc ); 2590line = xmemdupz (line ,len_arg ); 2591 } 2592 2593if (buf -> b_ml .ml_line_lnum != lnum ) { 2594// another line is buffered, flush it 2595ml_flush_line (buf , false); 2596 } 2597 2598if (kv_size (buf -> update_callbacks )) { 2599ml_add_deleted_len_buf (buf ,ml_get_buf (buf ,lnum ),-1 ); 2600 } 2601 2602if (buf -> b_ml .ml_flags & (ML_LINE_DIRTY |ML_ALLOCATED )) { 2603xfree (buf -> b_ml .ml_line_ptr );// free allocated line 2604 } 2605 2606buf -> b_ml .ml_line_ptr = line ; 2607buf -> b_ml .ml_line_textlen = (colnr_T )len_arg + 1 ; 2608buf -> b_ml .ml_line_lnum = lnum ; 2609buf -> b_ml .ml_flags = (buf -> b_ml .ml_flags |ML_LINE_DIRTY )& ~ML_EMPTY ; 2610if (noalloc ) { 2611// TODO(bfredl): this is a bit of a hack. but replacing lines in a loop is really common, 2612// and allocating a separate scratch buffer for each line which is immediately freed adds 2613// a lot of noise. A more general refactor could be to use a _fixed_ scratch buffer for 2614// all lines up to $REASONABLE_SIZE . 2615ml_flush_line (buf , true); 2616 } 2617 2618return OK ; 2619} 2620 2621/// Delete line `lnum` in buffer 2622/// 2623/// @note The caller of this function should probably also call changed_lines() after this. 2624/// 2625/// @param message Show "--No lines in buffer--" message. 2626/// 2627/// @return FAIL for failure, OK otherwise 2628int ml_delete_buf (buf_T * buf ,linenr_T lnum ,bool message ) 2629FUNC_ATTR_NONNULL_ALL 2630{ 2631ml_flush_line (buf , false); 2632return ml_delete_int (buf ,lnum ,message ?ML_DEL_MESSAGE :0 ); 2633} 2634 2635/// Delete line `lnum` in the current buffer. 2636/// 2637/// @param flags ML_DEL_MESSAGE may give a "No lines in buffer" message. 2638/// ML_DEL_UNDO this is called from undo. 2639/// 2640/// @return FAIL for failure, OK otherwise 2641static int ml_delete_int (buf_T * buf ,linenr_T lnum ,int flags ) 2642FUNC_ATTR_NONNULL_ALL 2643{ 2644if (lowest_marked && lowest_marked > lnum ) { 2645lowest_marked -- ; 2646 } 2647 2648// If the file becomes empty the last line is replaced by an empty line. 2649if (buf -> b_ml .ml_line_count == 1 ) {// file becomes empty 2650if (flags & ML_DEL_MESSAGE ) { 2651set_keep_msg (_ (no_lines_msg ),0 ); 2652 } 2653 2654int i = ml_replace_buf (buf ,1 ,"" , true, false); 2655buf -> b_ml .ml_flags |=ML_EMPTY ; 2656 2657return i ; 2658 } 2659 2660// Find the data block containing the line. 2661// This also fills the stack with the blocks from the root to the data block. 2662// This also releases any locked block. 2663memfile_T * mfp = buf -> b_ml .ml_mfp ; 2664if (mfp == NULL ) { 2665return FAIL ; 2666 } 2667 2668bhdr_T * hp ; 2669if ((hp = ml_find_line (buf ,lnum ,ML_DELETE ))== NULL ) { 2670return FAIL ; 2671 } 2672 2673DataBlock * dp = hp -> bh_data ; 2674// compute line count (number of entries in block) before the delete 2675int count = buf -> b_ml .ml_locked_high - buf -> b_ml .ml_locked_low + 2 ; 2676int idx = lnum - buf -> b_ml .ml_locked_low ; 2677 2678if (buf -> b_prev_line_count == 0 ) { 2679buf -> b_prev_line_count = buf -> b_ml .ml_line_count ; 2680 } 2681buf -> b_ml .ml_line_count -- ; 2682 2683int line_start = ((dp -> db_index [idx ])& DB_INDEX_MASK ); 2684int line_size ; 2685if (idx == 0 ) {// first line in block, text at the end 2686line_size = (int )(dp -> db_txt_end - (unsigned )line_start ); 2687 }else { 2688line_size = (int )(((dp -> db_index [idx - 1 ])& DB_INDEX_MASK )- (unsigned )line_start ); 2689 } 2690 2691// Line should always have an NL char internally (represented as NUL), 2692// even if 'noeol' is set. 2693assert (line_size >=1 ); 2694ml_add_deleted_len_buf (buf , (char * )dp + line_start ,line_size - 1 ); 2695 2696// special case: If there is only one line in the data block it becomes empty. 2697// Then we have to remove the entry, pointing to this data block, from the 2698// pointer block. If this pointer block also becomes empty, we go up another 2699// block, and so on, up to the root if necessary. 2700// The line counts in the pointer blocks have already been adjusted by 2701// ml_find_line(). 2702int ret = FAIL ; 2703if (count == 1 ) { 2704mf_free (mfp ,hp );// free the data block 2705buf -> b_ml .ml_locked = NULL ; 2706 2707for (int stack_idx = buf -> b_ml .ml_stack_top - 1 ;stack_idx >=0 ;stack_idx -- ) { 2708buf -> b_ml .ml_stack_top = 0 ;// stack is invalid when failing 2709infoptr_T * ip = & (buf -> b_ml .ml_stack [stack_idx ]); 2710idx = ip -> ip_index ; 2711if ((hp = mf_get (mfp ,ip -> ip_bnum ,1 ))== NULL ) { 2712 gototheend ; 2713 } 2714PointerBlock * pp = hp -> bh_data ;// must be pointer block 2715if (pp -> pb_id != PTR_ID ) { 2716iemsg (_ (e_pointer_block_id_wrong_four )); 2717mf_put (mfp ,hp , false, false); 2718 gototheend ; 2719 } 2720count = -- (pp -> pb_count ); 2721if (count == 0 ) {// the pointer block becomes empty! 2722mf_free (mfp ,hp ); 2723 }else { 2724if (count != idx ) {// move entries after the deleted one 2725memmove (& pp -> pb_pointer [idx ],& pp -> pb_pointer [idx + 1 ], 2726 (size_t )(count - idx )* sizeof (PointerEntry )); 2727 } 2728mf_put (mfp ,hp , true, false); 2729 2730buf -> b_ml .ml_stack_top = stack_idx ;// truncate stack 2731// fix line count for rest of blocks in the stack 2732if (buf -> b_ml .ml_locked_lineadd != 0 ) { 2733ml_lineadd (buf ,buf -> b_ml .ml_locked_lineadd ); 2734buf -> b_ml .ml_stack [buf -> b_ml .ml_stack_top ].ip_high += 2735buf -> b_ml .ml_locked_lineadd ; 2736 } 2737 (buf -> b_ml .ml_stack_top )++ ; 2738 2739break ; 2740 } 2741 } 2742CHECK (stack_idx < 0 ,_ ("deleted block 1?" )); 2743 }else { 2744// delete the text by moving the next lines forwards 2745int text_start = (int )dp -> db_txt_start ; 2746memmove ((char * )dp + text_start + line_size , 2747 (char * )dp + text_start , (size_t )(line_start - text_start )); 2748 2749// delete the index by moving the next indexes backwards 2750// Adjust the indexes for the text movement. 2751for (int i = idx ;i < count - 1 ;i ++ ) { 2752dp -> db_index [i ]= dp -> db_index [i + 1 ]+ (unsigned )line_size ; 2753 } 2754 2755dp -> db_free += (unsigned )line_size + (unsigned )INDEX_SIZE ; 2756dp -> db_txt_start += (unsigned )line_size ; 2757dp -> db_line_count -- ; 2758 2759// mark the block dirty and make sure it is in the file (for recovery) 2760buf -> b_ml .ml_flags |= (ML_LOCKED_DIRTY |ML_LOCKED_POS ); 2761 } 2762 2763ml_updatechunk (buf ,lnum ,line_size ,ML_CHNK_DELLINE ); 2764ret = OK ; 2765 2766theend : 2767return ret ; 2768} 2769 2770/// Delete line "lnum" in the current buffer. 2771/// 2772/// @note The caller of this function should probably also call 2773/// deleted_lines() after this. 2774/// 2775/// @return FAIL for failure, OK otherwise 2776int ml_delete (linenr_T lnum ) 2777{ 2778return ml_delete_flags (lnum ,0 ); 2779} 2780 2781/// Like ml_delete() but using flags (see ml_delete_int()). 2782/// 2783/// @return FAIL for failure, OK otherwise 2784int ml_delete_flags (linenr_T lnum ,int flags ) 2785{ 2786ml_flush_line (curbuf , false); 2787if (lnum < 1 || lnum > curbuf -> b_ml .ml_line_count ) { 2788return FAIL ; 2789 } 2790 2791return ml_delete_int (curbuf ,lnum ,flags ); 2792} 2793 2794/// set the DB_MARKED flag for line 'lnum' 2795void ml_setmarked (linenr_T lnum ) 2796{ 2797// invalid line number 2798if (lnum < 1 || lnum > curbuf -> b_ml .ml_line_count 2799|| curbuf -> b_ml .ml_mfp == NULL ) { 2800return ;// give error message? 2801 } 2802if (lowest_marked == 0 || lowest_marked > lnum ) { 2803lowest_marked = lnum ; 2804 } 2805 2806// find the data block containing the line 2807// This also fills the stack with the blocks from the root to the data block 2808// This also releases any locked block. 2809bhdr_T * hp ; 2810if ((hp = ml_find_line (curbuf ,lnum ,ML_FIND ))== NULL ) { 2811return ;// give error message? 2812 } 2813DataBlock * dp = hp -> bh_data ; 2814dp -> db_index [lnum - curbuf -> b_ml .ml_locked_low ] |=DB_MARKED ; 2815curbuf -> b_ml .ml_flags |=ML_LOCKED_DIRTY ; 2816} 2817 2818/// find the first line with its DB_MARKED flag set 2819linenr_T ml_firstmarked (void ) 2820{ 2821if (curbuf -> b_ml .ml_mfp == NULL ) { 2822return 0 ; 2823 } 2824 2825// The search starts with lowest_marked line. This is the last line where 2826// a mark was found, adjusted by inserting/deleting lines. 2827for (linenr_T lnum = lowest_marked ;lnum <=curbuf -> b_ml .ml_line_count ;) { 2828// Find the data block containing the line. 2829// This also fills the stack with the blocks from the root to the data 2830// block This also releases any locked block. 2831bhdr_T * hp ; 2832if ((hp = ml_find_line (curbuf ,lnum ,ML_FIND ))== NULL ) { 2833return 0 ;// give error message? 2834 } 2835DataBlock * dp = hp -> bh_data ; 2836 2837for (int i = lnum - curbuf -> b_ml .ml_locked_low ; 2838lnum <=curbuf -> b_ml .ml_locked_high ;i ++ ,lnum ++ ) { 2839if ((dp -> db_index [i ])& DB_MARKED ) { 2840 (dp -> db_index [i ]) &=DB_INDEX_MASK ; 2841curbuf -> b_ml .ml_flags |=ML_LOCKED_DIRTY ; 2842lowest_marked = lnum + 1 ; 2843return lnum ; 2844 } 2845 } 2846 } 2847 2848return 0 ; 2849} 2850 2851/// clear all DB_MARKED flags 2852void ml_clearmarked (void ) 2853{ 2854if (curbuf -> b_ml .ml_mfp == NULL ) {// nothing to do 2855return ; 2856 } 2857 2858// The search starts with line lowest_marked. 2859for (linenr_T lnum = lowest_marked ;lnum <=curbuf -> b_ml .ml_line_count ;) { 2860// Find the data block containing the line. 2861// This also fills the stack with the blocks from the root to the data 2862// block and releases any locked block. 2863bhdr_T * hp ; 2864if ((hp = ml_find_line (curbuf ,lnum ,ML_FIND ))== NULL ) { 2865return ;// give error message? 2866 } 2867DataBlock * dp = hp -> bh_data ; 2868 2869for (int i = lnum - curbuf -> b_ml .ml_locked_low ; 2870lnum <=curbuf -> b_ml .ml_locked_high ;i ++ ,lnum ++ ) { 2871if ((dp -> db_index [i ])& DB_MARKED ) { 2872 (dp -> db_index [i ]) &=DB_INDEX_MASK ; 2873curbuf -> b_ml .ml_flags |=ML_LOCKED_DIRTY ; 2874 } 2875 } 2876 } 2877 2878lowest_marked = 0 ; 2879} 2880 2881size_t ml_flush_deleted_bytes (buf_T * buf ,size_t * codepoints ,size_t * codeunits ) 2882{ 2883size_t ret = buf -> deleted_bytes ; 2884* codepoints = buf -> deleted_codepoints ; 2885* codeunits = buf -> deleted_codeunits ; 2886buf -> deleted_bytes = 0 ; 2887buf -> deleted_codepoints = 0 ; 2888buf -> deleted_codeunits = 0 ; 2889return ret ; 2890} 2891 2892/// flush ml_line if necessary 2893static void ml_flush_line (buf_T * buf ,bool noalloc ) 2894{ 2895static bool entered = false; 2896 2897if (buf -> b_ml .ml_line_lnum == 0 || buf -> b_ml .ml_mfp == NULL ) { 2898return ;// nothing to do 2899 } 2900if (buf -> b_ml .ml_flags & ML_LINE_DIRTY ) { 2901// This code doesn't work recursively. 2902if (entered ) { 2903return ; 2904 } 2905entered = true; 2906 2907buf -> flush_count ++ ; 2908 2909linenr_T lnum = buf -> b_ml .ml_line_lnum ; 2910char * new_line = buf -> b_ml .ml_line_ptr ; 2911 2912bhdr_T * hp = ml_find_line (buf ,lnum ,ML_FIND ); 2913if (hp == NULL ) { 2914siemsg (_ ("E320: Cannot find line %" PRId64 ), (int64_t )lnum ); 2915 }else { 2916DataBlock * dp = hp -> bh_data ; 2917int idx = lnum - buf -> b_ml .ml_locked_low ; 2918int start = ((dp -> db_index [idx ])& DB_INDEX_MASK ); 2919char * old_line = (char * )dp + start ; 2920int old_len ; 2921if (idx == 0 ) {// line is last in block 2922old_len = (int )dp -> db_txt_end - start ; 2923 }else {// text of previous line follows 2924old_len = (int )(dp -> db_index [idx - 1 ]& DB_INDEX_MASK )- start ; 2925 } 2926colnr_T new_len = buf -> b_ml .ml_line_textlen ; 2927int extra = new_len - old_len ;// negative if lines gets smaller 2928 2929// if new line fits in data block, replace directly 2930if ((int )dp -> db_free >=extra ) { 2931// if the length changes and there are following lines 2932int count = buf -> b_ml .ml_locked_high - buf -> b_ml .ml_locked_low + 1 ; 2933if (extra != 0 && idx < count - 1 ) { 2934// move text of following lines 2935memmove ((char * )dp + dp -> db_txt_start - extra , 2936 (char * )dp + dp -> db_txt_start , 2937 (size_t )(start - (int )dp -> db_txt_start )); 2938 2939// adjust pointers of this and following lines 2940for (int i = idx + 1 ;i < count ;i ++ ) { 2941dp -> db_index [i ]-= (unsigned )extra ; 2942 } 2943 } 2944dp -> db_index [idx ]-= (unsigned )extra ; 2945 2946// adjust free space 2947dp -> db_free -= (unsigned )extra ; 2948dp -> db_txt_start -= (unsigned )extra ; 2949 2950// copy new line into the data block 2951memmove (old_line - extra ,new_line , (size_t )new_len ); 2952buf -> b_ml .ml_flags |= (ML_LOCKED_DIRTY |ML_LOCKED_POS ); 2953// The else case is already covered by the insert and delete 2954if (extra != 0 ) { 2955ml_updatechunk (buf ,lnum ,extra ,ML_CHNK_UPDLINE ); 2956 } 2957 }else { 2958// Cannot do it in one data block: Delete and append. 2959// Append first, because ml_delete_int() cannot delete the 2960// last line in a buffer, which causes trouble for a buffer 2961// that has only one line. 2962// Don't forget to copy the mark! 2963// How about handling errors??? 2964 (void )ml_append_int (buf ,lnum ,new_line ,new_len , 2965 (dp -> db_index [idx ]& DB_MARKED ) ?ML_APPEND_MARK :0 ); 2966 (void )ml_delete_int (buf ,lnum ,0 ); 2967 } 2968 } 2969if (!noalloc ) { 2970xfree (new_line ); 2971 } 2972 2973entered = false; 2974 }else if (buf -> b_ml .ml_flags & ML_ALLOCATED ) { 2975assert (!noalloc );// caller must set ML_LINE_DIRTY with noalloc, handled above 2976xfree (buf -> b_ml .ml_line_ptr ); 2977 } 2978 2979buf -> b_ml .ml_flags &= ~(ML_LINE_DIRTY |ML_ALLOCATED ); 2980buf -> b_ml .ml_line_lnum = 0 ; 2981buf -> b_ml .ml_line_offset = 0 ; 2982} 2983 2984/// create a new, empty, data block 2985static bhdr_T * ml_new_data (memfile_T * mfp ,bool negative ,int64_t page_count ) 2986{ 2987assert (page_count >=0 ); 2988bhdr_T * hp = mf_new (mfp ,negative , (unsigned )page_count ); 2989DataBlock * dp = hp -> bh_data ; 2990dp -> db_id = DATA_ID ; 2991dp -> db_txt_start = dp -> db_txt_end = (unsigned )page_count * mfp -> mf_page_size ; 2992dp -> db_free = dp -> db_txt_start - (unsigned )HEADER_SIZE ; 2993dp -> db_line_count = 0 ; 2994 2995return hp ; 2996} 2997 2998/// create a new, empty, pointer block 2999static bhdr_T * ml_new_ptr (memfile_T * mfp ) 3000{ 3001bhdr_T * hp = mf_new (mfp , false,1 ); 3002PointerBlock * pp = hp -> bh_data ; 3003pp -> pb_id = PTR_ID ; 3004pp -> pb_count = 0 ; 3005pp -> pb_count_max = PB_COUNT_MAX (mfp ); 3006 3007return hp ; 3008} 3009 3010/// Lookup line 'lnum' in a memline. 3011/// 3012/// @param action: if ML_DELETE or ML_INSERT the line count is updated while searching 3013/// if ML_FLUSH only flush a locked block 3014/// if ML_FIND just find the line 3015/// 3016/// If the block was found it is locked and put in ml_locked. 3017/// The stack is updated to lead to the locked block. The ip_high field in 3018/// the stack is updated to reflect the last line in the block AFTER the 3019/// insert or delete, also if the pointer block has not been updated yet. But 3020/// if ml_locked != NULL ml_locked_lineadd must be added to ip_high. 3021/// 3022/// @return NULL for failure, pointer to block header otherwise 3023static bhdr_T * ml_find_line (buf_T * buf ,linenr_T lnum ,int action ) 3024{ 3025bhdr_T * hp ; 3026int top ; 3027 3028memfile_T * mfp = buf -> b_ml .ml_mfp ; 3029 3030// If there is a locked block check if the wanted line is in it. 3031// If not, flush and release the locked block. 3032// Don't do this for ML_INSERT_SAME, because the stack need to be updated. 3033// Don't do this for ML_FLUSH, because we want to flush the locked block. 3034// Don't do this when 'swapfile' is reset, we want to load all the blocks. 3035if (buf -> b_ml .ml_locked ) { 3036if (ML_SIMPLE (action ) 3037&& buf -> b_ml .ml_locked_low <=lnum 3038&& buf -> b_ml .ml_locked_high >=lnum ) { 3039// remember to update pointer blocks and stack later 3040if (action == ML_INSERT ) { 3041 (buf -> b_ml .ml_locked_lineadd )++ ; 3042 (buf -> b_ml .ml_locked_high )++ ; 3043 }else if (action == ML_DELETE ) { 3044 (buf -> b_ml .ml_locked_lineadd )-- ; 3045 (buf -> b_ml .ml_locked_high )-- ; 3046 } 3047return buf -> b_ml .ml_locked ; 3048 } 3049 3050mf_put (mfp ,buf -> b_ml .ml_locked ,buf -> b_ml .ml_flags & ML_LOCKED_DIRTY , 3051buf -> b_ml .ml_flags & ML_LOCKED_POS ); 3052buf -> b_ml .ml_locked = NULL ; 3053 3054// If lines have been added or deleted in the locked block, need to 3055// update the line count in pointer blocks. 3056if (buf -> b_ml .ml_locked_lineadd != 0 ) { 3057ml_lineadd (buf ,buf -> b_ml .ml_locked_lineadd ); 3058 } 3059 } 3060 3061if (action == ML_FLUSH ) {// nothing else to do 3062return NULL ; 3063 } 3064 3065blocknr_T bnum = 1 ;// start at the root of the tree 3066blocknr_T bnum2 ; 3067int page_count = 1 ; 3068linenr_T low = 1 ; 3069linenr_T high = buf -> b_ml .ml_line_count ; 3070 3071if (action == ML_FIND ) {// first try stack entries 3072for (top = buf -> b_ml .ml_stack_top - 1 ;top >=0 ;top -- ) { 3073infoptr_T * ip = & (buf -> b_ml .ml_stack [top ]); 3074if (ip -> ip_low <=lnum && ip -> ip_high >=lnum ) { 3075bnum = ip -> ip_bnum ; 3076low = ip -> ip_low ; 3077high = ip -> ip_high ; 3078buf -> b_ml .ml_stack_top = top ;// truncate stack at prev entry 3079break ; 3080 } 3081 } 3082if (top < 0 ) { 3083buf -> b_ml .ml_stack_top = 0 ;// not found, start at the root 3084 } 3085 }else {// ML_DELETE or ML_INSERT 3086buf -> b_ml .ml_stack_top = 0 ;// start at the root 3087 } 3088// search downwards in the tree until a data block is found 3089while (true) { 3090if ((hp = mf_get (mfp ,bnum , (unsigned )page_count ))== NULL ) { 3091 gotoerror_noblock ; 3092 } 3093 3094// update high for insert/delete 3095if (action == ML_INSERT ) { 3096high ++ ; 3097 }else if (action == ML_DELETE ) { 3098high -- ; 3099 } 3100 3101DataBlock * dp = hp -> bh_data ; 3102if (dp -> db_id == DATA_ID ) {// data block 3103buf -> b_ml .ml_locked = hp ; 3104buf -> b_ml .ml_locked_low = low ; 3105buf -> b_ml .ml_locked_high = high ; 3106buf -> b_ml .ml_locked_lineadd = 0 ; 3107buf -> b_ml .ml_flags &= ~(ML_LOCKED_DIRTY |ML_LOCKED_POS ); 3108return hp ; 3109 } 3110 3111PointerBlock * pp = (PointerBlock * )dp ;// must be pointer block 3112if (pp -> pb_id != PTR_ID ) { 3113iemsg (_ (e_pointer_block_id_wrong )); 3114 gotoerror_block ; 3115 } 3116 3117top = ml_add_stack (buf );// add new entry to stack 3118infoptr_T * ip = & (buf -> b_ml .ml_stack [top ]); 3119ip -> ip_bnum = bnum ; 3120ip -> ip_low = low ; 3121ip -> ip_high = high ; 3122ip -> ip_index = -1 ;// index not known yet 3123 3124bool dirty = false; 3125int idx ; 3126for (idx = 0 ;idx < (int )pp -> pb_count ;idx ++ ) { 3127linenr_T t = pp -> pb_pointer [idx ].pe_line_count ; 3128CHECK (t == 0 ,_ ("pe_line_count is zero" )); 3129if ((low += t )> lnum ) { 3130ip -> ip_index = idx ; 3131bnum = pp -> pb_pointer [idx ].pe_bnum ; 3132page_count = pp -> pb_pointer [idx ].pe_page_count ; 3133high = low - 1 ; 3134low -= t ; 3135 3136// a negative block number may have been changed 3137if (bnum < 0 ) { 3138bnum2 = mf_trans_del (mfp ,bnum ); 3139if (bnum != bnum2 ) { 3140bnum = bnum2 ; 3141pp -> pb_pointer [idx ].pe_bnum = bnum ; 3142dirty = true; 3143 } 3144 } 3145 3146break ; 3147 } 3148 } 3149if (idx >= (int )pp -> pb_count ) {// past the end: something wrong! 3150if (lnum > buf -> b_ml .ml_line_count ) { 3151siemsg (_ (e_line_number_out_of_range_nr_past_the_end ), 3152 (int64_t )lnum - buf -> b_ml .ml_line_count ); 3153 }else { 3154siemsg (_ (e_line_count_wrong_in_block_nr ),bnum ); 3155 } 3156 gotoerror_block ; 3157 } 3158if (action == ML_DELETE ) { 3159pp -> pb_pointer [idx ].pe_line_count -- ; 3160dirty = true; 3161 }else if (action == ML_INSERT ) { 3162pp -> pb_pointer [idx ].pe_line_count ++ ; 3163dirty = true; 3164 } 3165mf_put (mfp ,hp ,dirty , false); 3166 } 3167 3168error_block : 3169mf_put (mfp ,hp , false, false); 3170error_noblock : 3171// If action is ML_DELETE or ML_INSERT we have to correct the tree for 3172// the incremented/decremented line counts, because there won't be a line 3173// inserted/deleted after all. 3174if (action == ML_DELETE ) { 3175ml_lineadd (buf ,1 ); 3176 }else if (action == ML_INSERT ) { 3177ml_lineadd (buf ,-1 ); 3178 } 3179buf -> b_ml .ml_stack_top = 0 ; 3180return NULL ; 3181} 3182 3183/// add an entry to the info pointer stack 3184/// 3185/// @return number of the new entry 3186static int ml_add_stack (buf_T * buf ) 3187{ 3188int top = buf -> b_ml .ml_stack_top ; 3189 3190// may have to increase the stack size 3191if (top == buf -> b_ml .ml_stack_size ) { 3192CHECK (top > 0 ,_ ("Stack size increases" ));// more than 5 levels??? 3193 3194buf -> b_ml .ml_stack_size += STACK_INCR ; 3195size_t new_size = sizeof (infoptr_T )* (size_t )buf -> b_ml .ml_stack_size ; 3196buf -> b_ml .ml_stack = xrealloc (buf -> b_ml .ml_stack ,new_size ); 3197 } 3198 3199buf -> b_ml .ml_stack_top ++ ; 3200return top ; 3201} 3202 3203/// Update the pointer blocks on the stack for inserted/deleted lines. 3204/// The stack itself is also updated. 3205/// 3206/// When an insert/delete line action fails, the line is not inserted/deleted, 3207/// but the pointer blocks have already been updated. That is fixed here by 3208/// walking through the stack. 3209/// 3210/// Count is the number of lines added, negative if lines have been deleted. 3211static void ml_lineadd (buf_T * buf ,int count ) 3212{ 3213memfile_T * mfp = buf -> b_ml .ml_mfp ; 3214 3215for (int idx = buf -> b_ml .ml_stack_top - 1 ;idx >=0 ;idx -- ) { 3216infoptr_T * ip = & (buf -> b_ml .ml_stack [idx ]); 3217bhdr_T * hp ; 3218if ((hp = mf_get (mfp ,ip -> ip_bnum ,1 ))== NULL ) { 3219break ; 3220 } 3221PointerBlock * pp = hp -> bh_data ;// must be pointer block 3222if (pp -> pb_id != PTR_ID ) { 3223mf_put (mfp ,hp , false, false); 3224iemsg (_ (e_pointer_block_id_wrong_two )); 3225break ; 3226 } 3227pp -> pb_pointer [ip -> ip_index ].pe_line_count += count ; 3228ip -> ip_high += count ; 3229mf_put (mfp ,hp , true, false); 3230 } 3231} 3232 3233#ifdef HAVE_READLINK 3234 3235/// Resolve a symlink in the last component of a file name. 3236/// Note that f_resolve() does it for every part of the path, we don't do that 3237/// here. 3238/// 3239/// @return OK if it worked and the resolved link in "buf[MAXPATHL]", 3240/// FAIL otherwise 3241int resolve_symlink (const char * fname ,char * buf ) 3242{ 3243char tmp [MAXPATHL ]; 3244int depth = 0 ; 3245 3246if (fname == NULL ) { 3247return FAIL ; 3248 } 3249 3250// Put the result so far in tmp[], starting with the original name. 3251xstrlcpy (tmp ,fname ,MAXPATHL ); 3252 3253while (true) { 3254// Limit symlink depth to 100, catch recursive loops. 3255if (++ depth == 100 ) { 3256semsg (_ ("E773: Symlink loop for \"%s\"" ),fname ); 3257return FAIL ; 3258 } 3259 3260int ret = (int )readlink (tmp ,buf ,MAXPATHL - 1 ); 3261if (ret <=0 ) { 3262if (errno == EINVAL || errno == ENOENT ) { 3263// Found non-symlink or not existing file, stop here. 3264// When at the first level use the unmodified name, skip the 3265// call to vim_FullName(). 3266if (depth == 1 ) { 3267return FAIL ; 3268 } 3269 3270// Use the resolved name in tmp[]. 3271break ; 3272 } 3273 3274// There must be some error reading links, use original name. 3275return FAIL ; 3276 } 3277buf [ret ]= NUL ; 3278 3279// Check whether the symlink is relative or absolute. 3280// If it's relative, build a new path based on the directory 3281// portion of the filename (if any) and the path the symlink 3282// points to. 3283if (path_is_absolute (buf )) { 3284STRCPY (tmp ,buf ); 3285 }else { 3286char * tail = path_tail (tmp ); 3287if (strlen (tail )+ strlen (buf ) >=MAXPATHL ) { 3288return FAIL ; 3289 } 3290STRCPY (tail ,buf ); 3291 } 3292 } 3293 3294// Try to resolve the full name of the file so that the swapfile name will 3295// be consistent even when opening a relative symlink from different 3296// working directories. 3297return vim_FullName (tmp ,buf ,MAXPATHL , true); 3298} 3299#endif 3300 3301/// Make swapfile name out of the file name and a directory name. 3302/// 3303/// @return pointer to allocated memory or NULL. 3304char * makeswapname (char * fname ,char * ffname ,buf_T * buf ,char * dir_name ) 3305{ 3306char * fname_res = fname ; 3307#ifdef HAVE_READLINK 3308char fname_buf [MAXPATHL ]; 3309 3310// Expand symlink in the file name, so that we put the swapfile with the 3311// actual file instead of with the symlink. 3312if (resolve_symlink (fname ,fname_buf )== OK ) { 3313fname_res = fname_buf ; 3314 } 3315#endif 3316int len = (int )strlen (dir_name ); 3317 3318char * s = dir_name + len ; 3319if (after_pathsep (dir_name ,s )&& len > 1 && s [-1 ]== s [-2 ]) { 3320// Ends with '//', Use Full path 3321char * r = NULL ; 3322s = make_percent_swname (dir_name ,s ,fname_res ); 3323if (s != NULL ) { 3324r = modname (s ,".swp" , false); 3325xfree (s ); 3326 } 3327return r ; 3328 } 3329 3330// Prepend a '.' to the swapfile name for the current directory. 3331char * r = modname (fname_res ,".swp" , 3332dir_name [0 ]== '.' && dir_name [1 ]== NUL ); 3333if (r == NULL ) {// out of memory 3334return NULL ; 3335 } 3336 3337s = get_file_in_dir (r ,dir_name ); 3338xfree (r ); 3339return s ; 3340} 3341 3342/// Get file name to use for swapfile or backup file. 3343/// Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir' option "dname". 3344/// - If "dname" is ".", return "fname" (swapfile in dir of file). 3345/// - If "dname" starts with "./", insert "dname" in "fname" (swapfile relative to dir of file). 3346/// - Otherwise, prepend "dname" to the tail of "fname" (swapfile in specific dir). 3347/// 3348/// The return value is an allocated string and can be NULL. 3349/// 3350/// @param dname don't use "dirname", it is a global for Alpha 3351char * get_file_in_dir (char * fname ,char * dname ) 3352{ 3353String retval ; 3354String tail = cstr_as_string (path_tail (fname )); 3355 3356if (dname [0 ]== '.' && dname [1 ]== NUL ) { 3357retval = cbuf_to_string (fname , (size_t )(tail .data - fname )+ tail .size ); 3358 }else { 3359size_t dname_len = strlen (dname ); 3360if (dname [0 ]== '.' && vim_ispathsep (dname [1 ])) { 3361if (tail .data == fname ) {// no path before file name 3362retval = concat_fnames (cbuf_as_string (dname + 2 ,dname_len - 2 ),tail , true); 3363 }else { 3364const char save_char = * tail .data ; 3365* tail .data = NUL ; 3366String tmp = concat_fnames (cbuf_as_string (fname , (size_t )(tail .data - fname )), 3367cbuf_as_string (dname + 2 ,dname_len - 2 ), true); 3368* tail .data = save_char ; 3369retval = concat_fnames (tmp ,tail , true); 3370xfree (tmp .data ); 3371 } 3372 }else { 3373retval = concat_fnames (cbuf_as_string (dname ,dname_len ),tail , true); 3374 } 3375 } 3376 3377return retval .data ; 3378} 3379 3380/// Build the ATTENTION message: info about an existing swapfile. 3381/// 3382/// @param buf buffer being edited 3383/// @param fname swapfile name 3384/// @param fhname swapfile name, home replaced 3385/// @param msg string buffer, emitted as either a regular or confirm message 3386static void attention_message (buf_T * buf ,char * fname ,char * fhname ,StringBuilder * msg ) 3387{ 3388assert (buf -> b_fname != NULL ); 3389 3390emsg (_ ("E325: ATTENTION" )); 3391kv_printf (* msg ,_ ("Found a swap file by the name \"" )); 3392kv_printf (* msg ,"%s\"\n" ,fhname ); 3393const time_t swap_mtime = swapfile_info (fname ,msg ); 3394kv_printf (* msg , (_ ("While opening file \"" ))); 3395kv_printf (* msg ,"%s\"\n" ,buf -> b_fname ); 3396FileInfo file_info ; 3397if (!os_fileinfo (buf -> b_fname ,& file_info )) { 3398kv_printf (* msg ,_ (" CANNOT BE FOUND" )); 3399 }else { 3400kv_printf (* msg ,_ (" dated: " )); 3401time_t x = file_info .stat .st_mtim .tv_sec ; 3402char ctime_buf [50 ]; 3403kv_printf (* msg ,"%s" ,os_ctime_r (& x ,ctime_buf ,sizeof (ctime_buf ), true)); 3404if (swap_mtime != 0 && x > swap_mtime ) { 3405kv_printf (* msg ,_ (" NEWER than swap file!\n" )); 3406 } 3407 } 3408// Some of these messages are long to allow translation to 3409// other languages. 3410kv_printf (* msg ,_ ("\n(1) Another program may be editing the same file. If this is" 3411" the case,\n be careful not to end up with two different" 3412" instances of the same\n file when making changes." 3413" Quit, or continue with caution.\n" )); 3414kv_printf (* msg ,_ ("(2) An edit session for this file crashed.\n" )); 3415kv_printf (* msg ,_ (" If this is the case, use \":recover\" or \"nvim -r " )); 3416kv_printf (* msg ,"%s" ,buf -> b_fname ); 3417kv_printf (* msg , (_ ("\"\n to recover the changes (see \":help recovery\").\n" ))); 3418kv_printf (* msg ,_ (" If you did this already, delete the swap file \"" )); 3419kv_printf (* msg ,"%s" ,fname ); 3420kv_printf (* msg ,_ ("\"\n to avoid this message.\n" )); 3421} 3422 3423/// Trigger the SwapExists autocommands. 3424/// 3425/// @return a value for equivalent to do_dialog(). 3426static sea_choice_T do_swapexists (buf_T * buf ,char * fname ) 3427{ 3428set_vim_var_string (VV_SWAPNAME ,fname ,-1 ); 3429set_vim_var_string (VV_SWAPCHOICE ,NULL ,-1 ); 3430 3431// Trigger SwapExists autocommands with <afile> set to the file being 3432// edited. Disallow changing directory here. 3433allbuf_lock ++ ; 3434apply_autocmds (EVENT_SWAPEXISTS ,buf -> b_fname ,NULL , false,NULL ); 3435allbuf_lock -- ; 3436 3437set_vim_var_string (VV_SWAPNAME ,NULL ,-1 ); 3438 3439switch (* get_vim_var_str (VV_SWAPCHOICE )) { 3440case 'o' : 3441return SEA_CHOICE_READONLY ; 3442case 'e' : 3443return SEA_CHOICE_EDIT ; 3444case 'r' : 3445return SEA_CHOICE_RECOVER ; 3446case 'd' : 3447return SEA_CHOICE_DELETE ; 3448case 'q' : 3449return SEA_CHOICE_QUIT ; 3450case 'a' : 3451return SEA_CHOICE_ABORT ; 3452 } 3453 3454return SEA_CHOICE_NONE ; 3455} 3456 3457/// Find out what name to use for the swapfile for buffer 'buf'. 3458/// 3459/// Several names are tried to find one that does not exist. Last directory in 3460/// option is automatically created. 3461/// 3462/// @note If BASENAMELEN is not correct, you will get error messages for 3463/// not being able to open the swap or undo file. 3464/// @note May trigger SwapExists autocmd, pointers may change! 3465/// 3466/// @param[in] buf Buffer for which swapfile names needs to be found. 3467/// @param[in,out] dirp Pointer to a list of directories. When out of memory, 3468/// is set to NULL. Is advanced to the next directory in 3469/// the list otherwise. 3470/// @param[in] old_fname Allowed existing swapfile name. Except for this 3471/// case, name of the non-existing file is used. 3472/// @param[in,out] found_existing_dir If points to true, then new directory 3473/// for swapfile is not created. At first 3474/// findswapname() call this argument must 3475/// point to false. This parameter may only 3476/// be set to true by this function, it is 3477/// never set to false. 3478/// 3479/// @return [allocated] Name of the swapfile. 3480static char * findswapname (buf_T * buf ,char ** dirp ,char * old_fname ,bool * found_existing_dir ) 3481FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ,2 ,4 ) 3482{ 3483char * buf_fname = buf -> b_fname ; 3484 3485// Isolate a directory name from *dirp and put it in dir_name. 3486// First allocate some memory to put the directory name in. 3487const size_t dir_len = strlen (* dirp )+ 1 ; 3488char * dir_name = xmalloc (dir_len ); 3489copy_option_part (dirp ,dir_name ,dir_len ,"," ); 3490 3491// We try different swapfile names until we find one that does not exist yet. 3492char * fname = makeswapname (buf_fname ,buf -> b_ffname ,buf ,dir_name ); 3493 3494while (true) { 3495size_t n ; 3496if (fname == NULL ) {// must be out of memory 3497break ; 3498 } 3499if ((n = strlen (fname ))== 0 ) {// safety check 3500XFREE_CLEAR (fname ); 3501break ; 3502 } 3503// check if the swapfile already exists 3504// Extra security check: When a swapfile is a symbolic link, this 3505// is most likely a symlink attack. 3506FileInfo file_info ; 3507bool file_or_link_found = os_fileinfo_link (fname ,& file_info ); 3508if (!file_or_link_found ) { 3509break ; 3510 } 3511 3512// A file name equal to old_fname is OK to use. 3513if (old_fname != NULL && path_equal (fname ,old_fname ,kPathCmpLiteral )) { 3514break ; 3515 } 3516 3517// get here when file already exists 3518if (fname [n - 2 ]== 'w' && fname [n - 1 ]== 'p' ) {// first try 3519// If we get here the ".swp" file really exists. 3520// Give an error message, unless recovering, no file name, we are 3521// viewing a help file or when the path of the file is different 3522// (happens when all .swp files are in one directory). 3523if (!recoverymode && buf_fname != NULL && !buf -> b_help && !(buf -> b_flags & BF_DUMMY )) { 3524int fd ; 3525ZeroBlock b0 ; 3526bool differ = false; 3527 3528// Try to read block 0 from the swapfile to get the original file name (and inode number). 3529fd = os_open (fname ,O_RDONLY ,0 ); 3530if (fd >=0 ) { 3531if (read_eintr (fd ,& b0 ,sizeof (b0 ))== sizeof (b0 )) { 3532TO_SLASH (b0 .b0_fname ); 3533proc_running = swapfile_proc_running (& b0 ,fname ); 3534 3535// If the swapfile has the same directory as the 3536// buffer don't compare the directory names, they can 3537// have a different mountpoint. 3538if (b0 .b0_flags & B0_SAME_DIR ) { 3539if (!path_equal (path_tail (buf -> b_ffname ),path_tail (b0 .b0_fname ),kPathCmpLiteral ) 3540|| !same_directory (fname ,buf -> b_ffname )) { 3541// Symlinks may point to the same file even 3542// when the name differs, need to check the 3543// inode too. 3544expand_env (b0 .b0_fname ,NameBuff ,MAXPATHL ); 3545if (fnamecmp_ino (buf -> b_ffname ,NameBuff , 3546char_to_long (b0 .b0_ino ))) { 3547differ = true; 3548 } 3549 } 3550 }else { 3551// The name in the swapfile may be "~user/path/file". Expand it first. 3552expand_env (b0 .b0_fname ,NameBuff ,MAXPATHL ); 3553if (fnamecmp_ino (buf -> b_ffname ,NameBuff , 3554char_to_long (b0 .b0_ino ))) { 3555differ = true; 3556 } 3557 } 3558 } 3559close (fd ); 3560 } 3561 3562// Show the ATTENTION message when: 3563// - there is an old swapfile for the current file 3564// - the buffer was not recovered 3565if (!differ && !(curbuf -> b_flags & BF_RECOVERED ) 3566&& vim_strchr (p_shm ,kShmAttention )== NULL ) { 3567sea_choice_T choice = SEA_CHOICE_NONE ; 3568 3569// It's safe to delete the swapfile if all these are true: 3570// - the edited file exists 3571// - the swapfile has no changes and looks OK 3572if (os_path_exists (buf -> b_fname )&& swapfile_unchanged (fname )) { 3573choice = SEA_CHOICE_DELETE ; 3574if (p_verbose > 0 ) { 3575verb_msg (_ ("Found a swap file that is not useful, deleting it" )); 3576 } 3577 } 3578 3579// If there is a SwapExists autocommand and we can handle the 3580// response, trigger it. It may return 0 to ask the user anyway. 3581if (choice == SEA_CHOICE_NONE 3582&& swap_exists_action != SEA_NONE 3583&& has_autocmd (EVENT_SWAPEXISTS ,buf_fname ,buf )) { 3584choice = do_swapexists (buf ,fname ); 3585 } 3586 3587if (choice == SEA_CHOICE_NONE && swap_exists_action == SEA_READONLY ) { 3588// always open readonly. 3589choice = SEA_CHOICE_READONLY ; 3590 } 3591 3592proc_running = 0 ;// Set by attention_message..swapfile_info. 3593if (choice == SEA_CHOICE_NONE ) { 3594no_wait_return ++ ; 3595// Show info about the existing swapfile. 3596StringBuilder msg = KV_INITIAL_VALUE ; 3597kv_resize (msg ,IOSIZE ); 3598char * fhname = home_replace_save (NULL ,fname ); 3599attention_message (buf ,fname ,fhname ,& msg ); 3600 3601// We don't want a 'q' typed at the more-prompt 3602// interrupt loading a file. 3603got_int = false; 3604 3605// If vimrc has "simalt ~x" we don't want it to 3606// interfere with the prompt here. 3607flush_buffers (FLUSH_TYPEAHEAD ); 3608 3609if (swap_exists_action != SEA_NONE ) { 3610kv_printf (msg ,_ ("Swap file \"" )); 3611kv_printf (msg ,"%s" ,fhname ); 3612kv_printf (msg ,_ ("\" already exists!" )); 3613char * run_but = _ ("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort" ); 3614char * but = _ ("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort" ); 3615choice = (sea_choice_T )do_dialog (VIM_WARNING ,_ ("VIM - ATTENTION" ),msg .items , 3616proc_running ?run_but :but ,1 ,NULL , false); 3617 3618// compensate for missing "Delete it" button 3619choice += proc_running && choice >=4 ; 3620// pretend screen didn't scroll, need redraw anyway 3621msg_reset_scroll (); 3622 }else { 3623bool need_clear = false; 3624msg_ext_set_kind ("wmsg" ); 3625msg_multiline (cbuf_as_string (msg .items ,msg .size ),0 , false, false,& need_clear ); 3626 } 3627no_wait_return -- ; 3628kv_destroy (msg ); 3629xfree (fhname ); 3630 } 3631 3632switch (choice ) { 3633case SEA_CHOICE_READONLY :// "Open Read-Only" 3634buf -> b_p_ro = true; 3635break ; 3636case SEA_CHOICE_EDIT :// "Edit anyway" 3637break ; 3638case SEA_CHOICE_RECOVER :// "Recover" 3639swap_exists_action = SEA_RECOVER ; 3640break ; 3641case SEA_CHOICE_DELETE :// "Delete it" 3642os_remove (fname ); 3643break ; 3644case SEA_CHOICE_QUIT :// "Quit" 3645swap_exists_action = SEA_QUIT ; 3646break ; 3647case SEA_CHOICE_ABORT :// "Abort" 3648swap_exists_action = SEA_QUIT ; 3649got_int = true; 3650break ; 3651case SEA_CHOICE_NONE : 3652msg_puts ("\n" ); 3653if (msg_silent == 0 ) { 3654// call wait_return() later 3655need_wait_return = true; 3656 } 3657break ; 3658 } 3659 3660// If the swapfile was deleted this `fname` can be used. 3661if (choice != SEA_CHOICE_NONE && !os_path_exists (fname )) { 3662break ; 3663 } 3664 } 3665 } 3666 } 3667 3668// Permute the ".swp" extension to find a unique swapfile name. 3669// First decrement the last char: ".swo", ".swn", etc. 3670// If that still isn't enough decrement the last but one char: ".svz" 3671// Can happen when many Nvim instances are editing the same file (including "No Name" buffers). 3672if (fname [n - 1 ]== 'a' ) {// ".s?a" 3673if (fname [n - 2 ]== 'a' ) {// ".saa": tried enough, give up 3674emsg (_ ("E326: Too many swap files found" )); 3675XFREE_CLEAR (fname ); 3676break ; 3677 } 3678fname [n - 2 ]-- ;// ".svz", ".suz", etc. 3679fname [n - 1 ]= 'z' + 1 ; 3680 } 3681fname [n - 1 ]-- ;// ".swo", ".swn", etc. 3682 } 3683 3684if (os_isdir (dir_name )) { 3685* found_existing_dir = true; 3686 }else if (!* found_existing_dir && ** dirp == NUL ) { 3687int ret ; 3688char * failed_dir ; 3689if ((ret = os_mkdir_recurse (dir_name ,0755 ,& failed_dir ,NULL ))!= 0 ) { 3690semsg (_ ("E303: Unable to create directory \"%s\" for swap file, " 3691"recovery impossible: %s" ), 3692failed_dir ,os_strerror (ret )); 3693xfree (failed_dir ); 3694 } 3695 } 3696 3697xfree (dir_name ); 3698return fname ; 3699} 3700 3701static int b0_magic_wrong (ZeroBlock * b0p ) 3702{ 3703return b0p -> b0_magic_long != B0_MAGIC_LONG 3704|| b0p -> b0_magic_int != B0_MAGIC_INT 3705|| b0p -> b0_magic_short != (int16_t )B0_MAGIC_SHORT 3706|| b0p -> b0_magic_char != B0_MAGIC_CHAR ; 3707} 3708 3709/// Compare current file name with file name from swapfile. 3710/// Try to use inode numbers when possible. 3711/// Return non-zero when files are different. 3712/// 3713/// When comparing file names a few things have to be taken into consideration: 3714/// - When working over a network the full path of a file depends on the host. 3715/// We check the inode number if possible. It is not 100% reliable though, 3716/// because the device number cannot be used over a network. 3717/// - When a file does not exist yet (editing a new file) there is no inode 3718/// number. 3719/// - The file name in a swapfile may not be valid on the current host. The 3720/// "~user" form is used whenever possible to avoid this. 3721/// 3722/// This is getting complicated, let's make a table: 3723/// 3724/// ino_c ino_s fname_c fname_s differ = 3725/// 3726/// both files exist -> compare inode numbers: 3727/// != 0 != 0 X X ino_c != ino_s 3728/// 3729/// inode number(s) unknown, file names available -> compare file names 3730/// == 0 X OK OK fname_c != fname_s 3731/// X == 0 OK OK fname_c != fname_s 3732/// 3733/// current file doesn't exist, file for swapfile exist, file name(s) not 3734/// available -> probably different 3735/// == 0 != 0 FAIL X true 3736/// == 0 != 0 X FAIL true 3737/// 3738/// current file exists, inode for swap unknown, file name(s) not 3739/// available -> probably different 3740/// != 0 == 0 FAIL X true 3741/// != 0 == 0 X FAIL true 3742/// 3743/// current file doesn't exist, inode for swap unknown, one file name not 3744/// available -> probably different 3745/// == 0 == 0 FAIL OK true 3746/// == 0 == 0 OK FAIL true 3747/// 3748/// current file doesn't exist, inode for swap unknown, both file names not 3749/// available -> compare file names 3750/// == 0 == 0 FAIL FAIL fname_c != fname_s 3751/// 3752/// Only the last 32 bits of the inode will be used. This can't be changed 3753/// without making the block 0 incompatible with 32 bit versions. 3754/// 3755/// @param fname_c current file name 3756/// @param fname_s file name from swapfile 3757static bool fnamecmp_ino (char * fname_c ,char * fname_s ,long ino_block0 ) 3758{ 3759uint64_t ino_c = 0 ;// ino of current file 3760uint64_t ino_s ;// ino of file from swapfile 3761char buf_c [MAXPATHL ];// full path of fname_c 3762char buf_s [MAXPATHL ];// full path of fname_s 3763int retval_c ;// flag: buf_c valid 3764int retval_s ;// flag: buf_s valid 3765 3766FileInfo file_info ; 3767if (os_fileinfo (fname_c ,& file_info )) { 3768ino_c = os_fileinfo_inode (& file_info ); 3769 } 3770 3771// First we try to get the inode from the file name, because the inode in 3772// the swapfile may be outdated. If that fails (e.g. this path is not 3773// valid on this machine), use the inode from block 0. 3774if (os_fileinfo (fname_s ,& file_info )) { 3775ino_s = os_fileinfo_inode (& file_info ); 3776 }else { 3777ino_s = (uint64_t )ino_block0 ; 3778 } 3779 3780if (ino_c && ino_s ) { 3781return ino_c != ino_s ; 3782 } 3783 3784// One of the inode numbers is unknown, try a forced vim_FullName() and 3785// compare the file names. 3786retval_c = vim_FullName (fname_c ,buf_c ,MAXPATHL , true); 3787retval_s = vim_FullName (fname_s ,buf_s ,MAXPATHL , true); 3788if (retval_c == OK && retval_s == OK ) { 3789return strcmp (buf_c ,buf_s )!= 0 ; 3790 } 3791 3792// Can't compare inodes or file names, guess that the files are different, 3793// unless both appear not to exist at all, then compare with the file name 3794// in the swapfile. 3795if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL ) { 3796return strcmp (fname_c ,fname_s )!= 0 ; 3797 } 3798return true; 3799} 3800 3801/// Move a long integer into a four byte character array. 3802/// Used for machine independency in block zero. 3803static void long_to_char (long n ,char * s_in ) 3804{ 3805uint8_t * s = (uint8_t * )s_in ; 3806s [0 ]= (uint8_t )(n & 0xff ); 3807n = (unsigned )n >>8 ; 3808s [1 ]= (uint8_t )(n & 0xff ); 3809n = (unsigned )n >>8 ; 3810s [2 ]= (uint8_t )(n & 0xff ); 3811n = (unsigned )n >>8 ; 3812s [3 ]= (uint8_t )(n & 0xff ); 3813} 3814 3815static long char_to_long (const char * s_in ) 3816{ 3817const uint8_t * s = (uint8_t * )s_in ; 3818 3819long retval = s [3 ]; 3820retval <<=8 ; 3821retval |=s [2 ]; 3822retval <<=8 ; 3823retval |=s [1 ]; 3824retval <<=8 ; 3825retval |=s [0 ]; 3826 3827return retval ; 3828} 3829 3830/// Set the flags in the first block of the swapfile: 3831/// - file is modified or not: buf->b_changed 3832/// - 'fileformat' 3833/// - 'fileencoding' 3834void ml_setflags (buf_T * buf ) 3835{ 3836if (!buf -> b_ml .ml_mfp ) { 3837return ; 3838 } 3839bhdr_T * hp = pmap_get (int64_t )(& buf -> b_ml .ml_mfp -> mf_hash ,0 ); 3840if (hp ) { 3841ZeroBlock * b0p = hp -> bh_data ; 3842b0p -> b0_dirty = buf -> b_changed ?B0_DIRTY :0 ; 3843b0p -> b0_flags = (char )((b0p -> b0_flags & ~B0_FF_MASK ) | (uint8_t )(get_fileformat (buf )+ 1 )); 3844add_b0_fenc (b0p ,buf ); 3845hp -> bh_flags |=BH_DIRTY ; 3846mf_sync (buf -> b_ml .ml_mfp ,MFS_ZERO ); 3847 } 3848} 3849 3850enum { 3851MLCS_MAXL = 800 ,// max no of lines in chunk 3852MLCS_MINL = 400 ,// should be half of MLCS_MAXL 3853}; 3854 3855/// Keep information for finding byte offset of a line 3856/// 3857/// @param updtype may be one of: 3858/// ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it 3859/// Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called. 3860/// ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it 3861/// ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity. 3862static void ml_updatechunk (buf_T * buf ,linenr_T line ,int len ,int updtype ) 3863{ 3864static buf_T * ml_upd_lastbuf = NULL ; 3865static linenr_T ml_upd_lastcurline ; 3866static int ml_upd_lastcurix ; 3867 3868linenr_T curline = ml_upd_lastcurline ; 3869int curix = ml_upd_lastcurix ; 3870bhdr_T * hp ; 3871 3872if (buf -> b_ml .ml_usedchunks == -1 || len == 0 ) { 3873return ; 3874 } 3875if (buf -> b_ml .ml_chunksize == NULL ) { 3876buf -> b_ml .ml_chunksize = xmalloc (sizeof (chunksize_T )* 100 ); 3877buf -> b_ml .ml_numchunks = 100 ; 3878buf -> b_ml .ml_usedchunks = 1 ; 3879buf -> b_ml .ml_chunksize [0 ].mlcs_numlines = 1 ; 3880buf -> b_ml .ml_chunksize [0 ].mlcs_totalsize = 1 ; 3881ml_upd_lastbuf = NULL ;// invalidate resume cache 3882 } 3883 3884if (updtype == ML_CHNK_UPDLINE && buf -> b_ml .ml_line_count == 1 ) { 3885// First line in empty buffer from ml_flush_line() -- reset 3886buf -> b_ml .ml_usedchunks = 1 ; 3887buf -> b_ml .ml_chunksize [0 ].mlcs_numlines = 1 ; 3888buf -> b_ml .ml_chunksize [0 ].mlcs_totalsize = buf -> b_ml .ml_line_textlen ; 3889ml_upd_lastbuf = NULL ;// invalidate resume cache 3890return ; 3891 } 3892 3893// Find chunk that our line belongs to, curline will be at start of the 3894// chunk. 3895// The scan resumes at the cached chunk while ml_upd_lastbuf is set: the 3896// chunks have not moved since the last call. 3897if (buf != ml_upd_lastbuf || line < curline ) { 3898curline = 1 ; 3899curix = 0 ; 3900 } 3901for (;curix < buf -> b_ml .ml_usedchunks - 1 3902&& line >=curline + buf -> b_ml .ml_chunksize [curix ].mlcs_numlines ; 3903curix ++ ) { 3904curline += buf -> b_ml .ml_chunksize [curix ].mlcs_numlines ; 3905 } 3906chunksize_T * curchnk = buf -> b_ml .ml_chunksize + curix ; 3907 3908if (updtype == ML_CHNK_DELLINE ) { 3909len = - len ; 3910 } 3911curchnk -> mlcs_totalsize += len ; 3912if (updtype == ML_CHNK_ADDLINE ) { 3913int rest ; 3914DataBlock * dp ; 3915curchnk -> mlcs_numlines ++ ; 3916 3917// May resize here so we don't have to do it in both cases below 3918if (buf -> b_ml .ml_usedchunks + 1 >=buf -> b_ml .ml_numchunks ) { 3919buf -> b_ml .ml_numchunks = buf -> b_ml .ml_numchunks * 3 /2 ; 3920buf -> b_ml .ml_chunksize = xrealloc (buf -> b_ml .ml_chunksize , 3921sizeof (chunksize_T )* (size_t )buf -> b_ml .ml_numchunks ); 3922 } 3923 3924if (buf -> b_ml .ml_chunksize [curix ].mlcs_numlines >=MLCS_MAXL ) { 3925int end_idx ; 3926int text_end ; 3927 3928memmove (buf -> b_ml .ml_chunksize + curix + 1 , 3929buf -> b_ml .ml_chunksize + curix , 3930 (size_t )(buf -> b_ml .ml_usedchunks - curix )* sizeof (chunksize_T )); 3931// Compute length of first half of lines in the split chunk 3932int size = 0 ; 3933int linecnt = 0 ; 3934while (curline < buf -> b_ml .ml_line_count 3935&& linecnt < MLCS_MINL ) { 3936if ((hp = ml_find_line (buf ,curline ,ML_FIND ))== NULL ) { 3937buf -> b_ml .ml_usedchunks = -1 ; 3938return ; 3939 } 3940dp = hp -> bh_data ; 3941int count 3942= buf -> b_ml .ml_locked_high - buf -> b_ml .ml_locked_low + 1 ;// number of entries in block 3943int idx = curline - buf -> b_ml .ml_locked_low ; 3944curline = buf -> b_ml .ml_locked_high + 1 ; 3945// compute index of last line to use in this MEMLINE 3946rest = count - idx ; 3947if (linecnt + rest > MLCS_MINL ) { 3948end_idx = idx + MLCS_MINL - linecnt - 1 ; 3949linecnt = MLCS_MINL ; 3950 }else { 3951end_idx = count - 1 ; 3952linecnt += rest ; 3953 } 3954if (idx == 0 ) {// first line in block, text at the end 3955text_end = (int )dp -> db_txt_end ; 3956 }else { 3957text_end = ((dp -> db_index [idx - 1 ])& DB_INDEX_MASK ); 3958 } 3959size += text_end - (int )((dp -> db_index [end_idx ])& DB_INDEX_MASK ); 3960 } 3961buf -> b_ml .ml_chunksize [curix ].mlcs_numlines = linecnt ; 3962buf -> b_ml .ml_chunksize [curix + 1 ].mlcs_numlines -= linecnt ; 3963buf -> b_ml .ml_chunksize [curix ].mlcs_totalsize = size ; 3964buf -> b_ml .ml_chunksize [curix + 1 ].mlcs_totalsize -= size ; 3965buf -> b_ml .ml_usedchunks ++ ; 3966ml_upd_lastbuf = NULL ;// Force recalc of curix & curline 3967return ; 3968 }else if (buf -> b_ml .ml_chunksize [curix ].mlcs_numlines >=MLCS_MINL 3969&& curix == buf -> b_ml .ml_usedchunks - 1 3970&& buf -> b_ml .ml_line_count - line <=1 ) { 3971// We are in the last chunk and it is cheap to create a new one 3972// after this. Do it now to avoid the loop above later on 3973curchnk = buf -> b_ml .ml_chunksize + curix + 1 ; 3974buf -> b_ml .ml_usedchunks ++ ; 3975if (line == buf -> b_ml .ml_line_count ) { 3976curchnk -> mlcs_numlines = 0 ; 3977curchnk -> mlcs_totalsize = 0 ; 3978 }else { 3979// Line is just prior to last, move count for last 3980// This is the common case when loading a new file 3981hp = ml_find_line (buf ,buf -> b_ml .ml_line_count ,ML_FIND ); 3982if (hp == NULL ) { 3983buf -> b_ml .ml_usedchunks = -1 ; 3984return ; 3985 } 3986dp = hp -> bh_data ; 3987if (dp -> db_line_count == 1 ) { 3988rest = (int )(dp -> db_txt_end - dp -> db_txt_start ); 3989 }else { 3990rest = (int )((dp -> db_index [dp -> db_line_count - 2 ])& DB_INDEX_MASK ) 3991- (int )dp -> db_txt_start ; 3992 } 3993curchnk -> mlcs_totalsize = rest ; 3994curchnk -> mlcs_numlines = 1 ; 3995curchnk [-1 ].mlcs_totalsize -= rest ; 3996curchnk [-1 ].mlcs_numlines -= 1 ; 3997 } 3998 } 3999 }else if (updtype == ML_CHNK_DELLINE ) { 4000curchnk -> mlcs_numlines -- ; 4001if (curix < (buf -> b_ml .ml_usedchunks - 1 ) 4002&& (curchnk -> mlcs_numlines + curchnk [1 ].mlcs_numlines ) 4003 <=MLCS_MINL ) { 4004curix ++ ; 4005curchnk = buf -> b_ml .ml_chunksize + curix ; 4006 }else if (curix == 0 && curchnk -> mlcs_numlines <=0 ) { 4007ml_upd_lastbuf = NULL ;// Force recalc of curix & curline 4008buf -> b_ml .ml_usedchunks -- ; 4009memmove (buf -> b_ml .ml_chunksize ,buf -> b_ml .ml_chunksize + 1 , 4010 (size_t )buf -> b_ml .ml_usedchunks * sizeof (chunksize_T )); 4011return ; 4012 }else if (curix == 0 || (curchnk -> mlcs_numlines > 10 4013&& (curchnk -> mlcs_numlines + 4014curchnk [-1 ].mlcs_numlines ) 4015> MLCS_MINL )) { 4016// The chunks are left as they are, the cached position stays valid. 4017ml_upd_lastbuf = buf ; 4018ml_upd_lastcurline = curline ; 4019ml_upd_lastcurix = curix ; 4020return ; 4021 } 4022 4023// Collapse chunks 4024ml_upd_lastbuf = NULL ;// Force recalc of curix & curline 4025curchnk [-1 ].mlcs_numlines += curchnk -> mlcs_numlines ; 4026curchnk [-1 ].mlcs_totalsize += curchnk -> mlcs_totalsize ; 4027buf -> b_ml .ml_usedchunks -- ; 4028if (curix < buf -> b_ml .ml_usedchunks ) { 4029memmove (buf -> b_ml .ml_chunksize + curix , 4030buf -> b_ml .ml_chunksize + curix + 1 , 4031 (size_t )(buf -> b_ml .ml_usedchunks - curix )* sizeof (chunksize_T )); 4032 } 4033return ; 4034 } 4035ml_upd_lastbuf = buf ; 4036ml_upd_lastcurline = curline ; 4037ml_upd_lastcurix = curix ; 4038} 4039 4040/// Find offset for line or line with offset. 4041/// 4042/// @param buf buffer to use 4043/// @param lnum if > 0, find offset of lnum, return offset 4044/// if == 0, return line with offset *offp 4045/// @param offp offset to use to find line, store remaining column offset 4046/// Should be NULL when getting offset of line 4047/// @param no_ff ignore 'fileformat' option, always use one byte for NL. 4048/// 4049/// @return -1 if information is not available 4050int ml_find_line_or_offset (buf_T * buf ,linenr_T lnum ,int * offp ,bool no_ff ) 4051{ 4052bhdr_T * hp ; 4053int text_end ; 4054int offset ; 4055int ffdos = !no_ff && (get_fileformat (buf )== EOL_DOS ); 4056int extra = 0 ; 4057 4058// take care of cached line first. Only needed if the cached line is before 4059// the requested line. Additionally cache the value for the cached line. 4060// This is used by the extmark code which needs the byte offset of the edited 4061// line. So when doing multiple small edits on the same line the value is 4062// only calculated once. 4063// 4064// NB: caching doesn't work with 'fileformat'. This is not a problem for 4065// bytetracking, as bytetracking ignores 'fileformat' option. But calling 4066// line2byte() will invalidate the cache for the time being (this function 4067// was never cached to start with anyway). 4068bool can_cache = (lnum != 0 && !ffdos && buf -> b_ml .ml_line_lnum == lnum ); 4069if (lnum == 0 || buf -> b_ml .ml_line_lnum < lnum || !no_ff ) { 4070ml_flush_line (curbuf , false); 4071 }else if (can_cache && buf -> b_ml .ml_line_offset > 0 ) { 4072return (int )buf -> b_ml .ml_line_offset ; 4073 } 4074 4075if (buf -> b_ml .ml_usedchunks == -1 4076|| buf -> b_ml .ml_chunksize == NULL 4077|| lnum < 0 ) { 4078// memline is currently empty. Although if it is loaded, 4079// it behaves like there is one empty line. 4080if (no_ff && buf -> b_ml .ml_mfp && (lnum == 1 || lnum == 2 )) { 4081return lnum - 1 ; 4082 } 4083return -1 ; 4084 } 4085 4086if (offp == NULL ) { 4087offset = 0 ; 4088 }else { 4089offset = * offp ; 4090 } 4091if (lnum == 0 && offset <=0 ) { 4092return 1 ;// Not a "find offset" and offset 0 _must_ be in line 1 4093 } 4094// Find the last chunk before the one containing our line. Last chunk is 4095// special because it will never qualify. 4096linenr_T curline = 1 ; 4097int curix = 0 ; 4098int size = 0 ; 4099while (curix < buf -> b_ml .ml_usedchunks - 1 4100&& ((lnum != 0 4101&& lnum >=curline + buf -> b_ml .ml_chunksize [curix ].mlcs_numlines ) 4102|| (offset != 0 4103&& offset > size + 4104buf -> b_ml .ml_chunksize [curix ].mlcs_totalsize 4105+ ffdos * buf -> b_ml .ml_chunksize [curix ].mlcs_numlines ))) { 4106curline += buf -> b_ml .ml_chunksize [curix ].mlcs_numlines ; 4107size += buf -> b_ml .ml_chunksize [curix ].mlcs_totalsize ; 4108if (offset && ffdos ) { 4109size += buf -> b_ml .ml_chunksize [curix ].mlcs_numlines ; 4110 } 4111curix ++ ; 4112 } 4113 4114while ((lnum != 0 && curline < lnum )|| (offset != 0 && size < offset )) { 4115if (curline > buf -> b_ml .ml_line_count 4116|| (hp = ml_find_line (buf ,curline ,ML_FIND ))== NULL ) { 4117return -1 ; 4118 } 4119DataBlock * dp = hp -> bh_data ; 4120int count 4121= buf -> b_ml .ml_locked_high - buf -> b_ml .ml_locked_low + 1 ;// number of entries in block 4122int idx ; 4123int start_idx = idx = curline - buf -> b_ml .ml_locked_low ; 4124if (idx == 0 ) {// first line in block, text at the end 4125text_end = (int )dp -> db_txt_end ; 4126 }else { 4127text_end = ((dp -> db_index [idx - 1 ])& DB_INDEX_MASK ); 4128 } 4129// Compute index of last line to use in this MEMLINE 4130if (lnum != 0 ) { 4131if (curline + (count - idx ) >=lnum ) { 4132idx += lnum - curline - 1 ; 4133 }else { 4134idx = count - 1 ; 4135 } 4136 }else { 4137extra = 0 ; 4138while (true) { 4139if (!(offset >=size 4140+ text_end - (int )((dp -> db_index [idx ])& DB_INDEX_MASK ) 4141+ ffdos )) { 4142break ; 4143 } 4144if (ffdos ) { 4145size ++ ; 4146 } 4147if (idx == count - 1 ) { 4148extra = 1 ; 4149break ; 4150 } 4151idx ++ ; 4152 } 4153 } 4154int len = text_end - (int )((dp -> db_index [idx ])& DB_INDEX_MASK ); 4155size += len ; 4156if (offset != 0 && size >=offset ) { 4157if (size + ffdos == offset ) { 4158* offp = 0 ; 4159 }else if (idx == start_idx ) { 4160* offp = offset - size + len ; 4161 }else { 4162* offp = offset - size + len 4163- (text_end - (int )((dp -> db_index [idx - 1 ])& DB_INDEX_MASK )); 4164 } 4165curline += idx - start_idx + extra ; 4166if (curline > buf -> b_ml .ml_line_count ) { 4167return -1 ;// exactly one byte beyond the end 4168 } 4169return curline ; 4170 } 4171curline = buf -> b_ml .ml_locked_high + 1 ; 4172 } 4173 4174if (lnum != 0 ) { 4175// Count extra CR characters. 4176if (ffdos ) { 4177size += lnum - 1 ; 4178 } 4179 4180// Don't count the last line break if 'noeol' and ('bin' or 4181// 'nofixeol'). 4182if ((!buf -> b_p_fixeol || buf -> b_p_bin )&& !buf -> b_p_eol 4183&& lnum > buf -> b_ml .ml_line_count ) { 4184size -= ffdos + 1 ; 4185 } 4186 } 4187 4188if (can_cache && size > 0 ) { 4189buf -> b_ml .ml_line_offset = (size_t )size ; 4190 } 4191 4192return size ; 4193} 4194 4195/// Goto byte in buffer with offset 'cnt'. 4196void goto_byte (int cnt ) 4197{ 4198int boff = cnt ; 4199 4200ml_flush_line (curbuf , false);// cached line may be dirty 4201setpcmark (); 4202if (boff ) { 4203boff -- ; 4204 } 4205linenr_T lnum = (linenr_T )ml_find_line_or_offset (curbuf ,0 ,& boff , false); 4206if (lnum < 1 ) {// past the end 4207curwin -> w_cursor .lnum = curbuf -> b_ml .ml_line_count ; 4208curwin -> w_curswant = MAXCOL ; 4209coladvance (curwin ,MAXCOL ); 4210 }else { 4211curwin -> w_cursor .lnum = lnum ; 4212curwin -> w_cursor .col = (colnr_T )boff ; 4213curwin -> w_cursor .coladd = 0 ; 4214curwin -> w_set_curswant = true; 4215 } 4216check_cursor (curwin ); 4217 4218// Make sure the cursor is on the first byte of a multi-byte char. 4219mb_adjust_cursor (); 4220} 4221 4222/// Increment the line pointer "lp" crossing line boundaries as necessary. 4223/// 4224/// @return 1 when going to the next line. 4225/// 2 when moving forward onto a NUL at the end of the line). 4226/// -1 when at the end of file. 4227/// 0 otherwise. 4228int inc (pos_T * lp ) 4229{ 4230// when searching position may be set to end of a line 4231if (lp -> col != MAXCOL ) { 4232const char * const p = ml_get_pos (lp ); 4233if (* p != NUL ) {// still within line, move to next char (may be NUL) 4234const int l = utfc_ptr2len (p ); 4235 4236lp -> col += l ; 4237return ((p [l ]!= NUL ) ?0 :2 ); 4238 } 4239 } 4240if (lp -> lnum != curbuf -> b_ml .ml_line_count ) {// there is a next line 4241lp -> col = 0 ; 4242lp -> lnum ++ ; 4243lp -> coladd = 0 ; 4244return 1 ; 4245 } 4246return -1 ; 4247} 4248 4249/// Same as inc(), but skip NUL at the end of non-empty lines. 4250int incl (pos_T * lp ) 4251{ 4252int r ; 4253 4254if ((r = inc (lp )) >=1 && lp -> col ) { 4255r = inc (lp ); 4256 } 4257return r ; 4258} 4259 4260/// Decrements position `lp` by one character (multibyte-aware), crossing line boundaries as 4261/// necessary. Resets `lp.coladd`. Uses curbuf. 4262/// 4263/// @return 1 when crossing to the previous line. 4264/// -1 when at the start of the file. 4265/// 0 otherwise. 4266int dec (pos_T * lp ) 4267{ 4268lp -> coladd = 0 ; 4269if (lp -> col == MAXCOL ) { 4270// past end of line 4271char * p = ml_get (lp -> lnum ); 4272lp -> col = ml_get_len (lp -> lnum ); 4273lp -> col -= utf_head_off (p ,p + lp -> col ); 4274return 0 ; 4275 } 4276 4277if (lp -> col > 0 ) { 4278// still within line 4279lp -> col -- ; 4280char * p = ml_get (lp -> lnum ); 4281lp -> col -= utf_head_off (p ,p + lp -> col ); 4282return 0 ; 4283 } 4284if (lp -> lnum > 1 ) { 4285// there is a prior line 4286lp -> lnum -- ; 4287char * p = ml_get (lp -> lnum ); 4288lp -> col = ml_get_len (lp -> lnum ); 4289lp -> col -= utf_head_off (p ,p + lp -> col ); 4290return 1 ; 4291 } 4292 4293// at start of file 4294return -1 ; 4295} 4296 4297/// Same as dec(), but skip NUL at the end of non-empty lines. 4298int decl (pos_T * lp ) 4299{ 4300int r ; 4301 4302if ((r = dec (lp ))== 1 && lp -> col ) { 4303r = dec (lp ); 4304 } 4305return r ; 4306}