robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// undo.c: multi level undo facility 2 3// The saved lines are stored in a list of lists (one for each buffer): 4// 5// b_u_oldhead------------------------------------------------+ 6// | 7// V 8// +--------------+ +--------------+ +--------------+ 9// b_u_newhead--->| u_header | | u_header | | u_header | 10// | uh_next------>| uh_next------>| uh_next---->NULL 11// NULL<--------uh_prev |<---------uh_prev |<---------uh_prev | 12// | uh_entry | | uh_entry | | uh_entry | 13// +--------|-----+ +--------|-----+ +--------|-----+ 14// | | | 15// V V V 16// +--------------+ +--------------+ +--------------+ 17// | u_entry | | u_entry | | u_entry | 18// | ue_next | | ue_next | | ue_next | 19// +--------|-----+ +--------|-----+ +--------|-----+ 20// | | | 21// V V V 22// +--------------+ NULL NULL 23// | u_entry | 24// | ue_next | 25// +--------|-----+ 26// | 27// V 28// etc. 29// 30// Each u_entry list contains the information for one undo or redo. 31// curbuf->b_u_curhead points to the header of the last undo (the next redo), 32// or is NULL if nothing has been undone ("leaf", end of the branch). 33// 34// For keeping alternate undo/redo branches the uh_alt field is used. Thus at 35// each point in the list a branch may appear for an alternate to redo. The 36// uh_seq field is numbered sequentially to be able to find a newer or older 37// branch. 38// 39// +---------------+ +---------------+ 40// b_u_oldhead --->| u_header | | u_header | 41// | uh_alt_next ---->| uh_alt_next ----> NULL 42// NULL <----- uh_alt_prev |<------ uh_alt_prev | 43// | uh_prev | | uh_prev | 44// +-----|---------+ +-----|---------+ 45// | | 46// V V 47// +---------------+ +---------------+ 48// | u_header | | u_header | 49// | uh_alt_next | | uh_alt_next | 50// b_u_newhead --->| uh_alt_prev | | uh_alt_prev | 51// | uh_prev | | uh_prev | 52// +-----|---------+ +-----|---------+ 53// | | 54// V V 55// NULL +---------------+ +---------------+ 56// | u_header | | u_header | 57// | uh_alt_next ---->| uh_alt_next | 58// | uh_alt_prev |<------ uh_alt_prev | 59// | uh_prev | | uh_prev | 60// +-----|---------+ +-----|---------+ 61// | | 62// etc. etc. 63// 64// 65// All data is allocated and will all be freed when the buffer is unloaded. 66 67// Uncomment the next line for including the u_check() function. This warns 68// for errors in the debug information. 69// #define U_DEBUG 1 70#define UH_MAGIC 0x18dade // value for uh_magic when in use 71#define UE_MAGIC 0xabc123 // value for ue_magic when in use 72 73#include <assert.h> 74#include <fcntl.h> 75#include <inttypes.h> 76#include <stdbool.h> 77#include <stdio.h> 78#include <stdlib.h> 79#include <string.h> 80#include <time.h> 81#include <uv.h> 82 83#include "auto/config.h" 84#include "klib/kvec.h" 85#include "nvim/ascii_defs.h" 86#include "nvim/autocmd.h" 87#include "nvim/buffer.h" 88#include "nvim/buffer_defs.h" 89#include "nvim/buffer_updates.h" 90#include "nvim/change.h" 91#include "nvim/context.h" 92#include "nvim/cursor.h" 93#include "nvim/drawscreen.h" 94#include "nvim/errors.h" 95#include "nvim/eval/funcs.h" 96#include "nvim/eval/typval.h" 97#include "nvim/ex_cmds_defs.h" 98#include "nvim/ex_docmd.h" 99#include "nvim/ex_getln.h" 100#include "nvim/extmark.h" 101#include "nvim/extmark_defs.h" 102#include "nvim/fileio.h" 103#include "nvim/fold.h" 104#include "nvim/garray.h" 105#include "nvim/garray_defs.h" 106#include "nvim/gettext_defs.h" 107#include "nvim/globals.h" 108#include "nvim/highlight_defs.h" 109#include "nvim/input.h" 110#include "nvim/input_cmdatom.h" 111#include "nvim/insert.h" 112#include "nvim/macros_defs.h" 113#include "nvim/mark.h" 114#include "nvim/mark_defs.h" 115#include "nvim/mbyte.h" 116#include "nvim/mcursor.h" 117#include "nvim/memline.h" 118#include "nvim/memline_defs.h" 119#include "nvim/memory.h" 120#include "nvim/message.h" 121#include "nvim/option.h" 122#include "nvim/option_vars.h" 123#include "nvim/os/fs.h" 124#include "nvim/os/fs_defs.h" 125#include "nvim/os/input.h" 126#include "nvim/os/os_defs.h" 127#include "nvim/os/time.h" 128#include "nvim/os/time_defs.h" 129#include "nvim/path.h" 130#include "nvim/pos_defs.h" 131#include "nvim/sha256.h" 132#include "nvim/spell.h" 133#include "nvim/state.h" 134#include "nvim/strings.h" 135#include "nvim/types_defs.h" 136#include "nvim/undo.h" 137#include "nvim/undo_defs.h" 138#include "nvim/vim_defs.h" 139 140/// Structure passed around between undofile functions. 141typedef struct { 142buf_T * bi_buf ; 143FILE * bi_fp ; 144off_T bi_fsize ;///< Size of `bi_fp` when reading, 0 if unknown. 145}bufinfo_T ; 146 147#include "undo.c.generated.h" 148 149static const char e_undo_list_corrupt [] 150= N_ ("E439: Undo list corrupt" ); 151static const char e_undo_line_missing [] 152= N_ ("E440: Undo line missing" ); 153static const char e_write_error_in_undo_file_str [] 154= N_ ("E829: Write error in undo file: %s" ); 155 156// used in undo_end() to report number of added and deleted lines 157static int u_newcount ,u_oldcount ; 158 159// When 'u' flag included in 'cpoptions', we behave like vi. Need to remember 160// the action that "u" should do. 161static bool undo_undoes = false; 162 163static int lastmark = 0 ; 164 165#ifdef U_DEBUG 166// Check the undo structures for being valid. Print a warning when something 167// looks wrong. 168static int seen_b_u_curhead ; 169static int seen_b_u_newhead ; 170static int header_count ; 171 172static void u_check_tree (u_header_T * uhp ,u_header_T * exp_uh_next ,u_header_T * exp_uh_alt_prev ) 173{ 174if (uhp == NULL ) { 175return ; 176 } 177header_count ++ ; 178if (uhp == curbuf -> b_u_curhead && ++ seen_b_u_curhead > 1 ) { 179emsg ("b_u_curhead found twice (looping?)" ); 180return ; 181 } 182if (uhp == curbuf -> b_u_newhead && ++ seen_b_u_newhead > 1 ) { 183emsg ("b_u_newhead found twice (looping?)" ); 184return ; 185 } 186 187if (uhp -> uh_magic != UH_MAGIC ) { 188emsg ("uh_magic wrong (may be using freed memory)" ); 189 }else { 190// Check pointers back are correct. 191if (uhp -> uh_next .ptr != exp_uh_next ) { 192emsg ("uh_next wrong" ); 193smsg (0 ,"expected: 0x%x, actual: 0x%x" , 194exp_uh_next ,uhp -> uh_next .ptr ); 195 } 196if (uhp -> uh_alt_prev .ptr != exp_uh_alt_prev ) { 197emsg ("uh_alt_prev wrong" ); 198smsg (0 ,"expected: 0x%x, actual: 0x%x" , 199exp_uh_alt_prev ,uhp -> uh_alt_prev .ptr ); 200 } 201 202// Check the undo tree at this header. 203for (u_entry_T * uep = uhp -> uh_entry ;uep != NULL ;uep = uep -> ue_next ) { 204if (uep -> ue_magic != UE_MAGIC ) { 205emsg ("ue_magic wrong (may be using freed memory)" ); 206break ; 207 } 208 } 209 210// Check the next alt tree. 211u_check_tree (uhp -> uh_alt_next .ptr ,uhp -> uh_next .ptr ,uhp ); 212 213// Check the next header in this branch. 214u_check_tree (uhp -> uh_prev .ptr ,uhp ,NULL ); 215 } 216} 217 218static void u_check (int newhead_may_be_NULL ) 219{ 220seen_b_u_newhead = 0 ; 221seen_b_u_curhead = 0 ; 222header_count = 0 ; 223 224u_check_tree (curbuf -> b_u_oldhead ,NULL ,NULL ); 225 226if (seen_b_u_newhead == 0 && curbuf -> b_u_oldhead != NULL 227&& !(newhead_may_be_NULL && curbuf -> b_u_newhead == NULL )) { 228semsg ("b_u_newhead invalid: 0x%x" ,curbuf -> b_u_newhead ); 229 } 230if (curbuf -> b_u_curhead != NULL && seen_b_u_curhead == 0 ) { 231semsg ("b_u_curhead invalid: 0x%x" ,curbuf -> b_u_curhead ); 232 } 233if (header_count != curbuf -> b_u_numhead ) { 234emsg ("b_u_numhead invalid" ); 235smsg (0 ,"expected: %" PRId64 ", actual: %" PRId64 , 236 (int64_t )header_count , (int64_t )curbuf -> b_u_numhead ); 237 } 238} 239 240#endif 241 242/// Save the current line for both the "u" and "U" command. 243/// Careful: may trigger autocommands that reload the buffer. 244/// Returns OK or FAIL. 245int u_save_cursor (void ) 246{ 247linenr_T cur = curwin -> w_cursor .lnum ; 248linenr_T top = cur > 0 ?cur - 1 :0 ; 249linenr_T bot = cur + 1 ; 250 251return u_save (top ,bot ); 252} 253 254/// Save the lines between "top" and "bot" for both the "u" and "U" command. 255/// "top" may be 0 and "bot" may be curbuf->b_ml.ml_line_count + 1. 256/// Careful: may trigger autocommands that reload the buffer. 257/// Returns FAIL when lines could not be saved, OK otherwise. 258int u_save (linenr_T top ,linenr_T bot ) 259{ 260return u_save_buf (curbuf ,top ,bot ); 261} 262 263int u_save_buf (buf_T * buf ,linenr_T top ,linenr_T bot ) 264{ 265if (top >=bot || bot > (buf -> b_ml .ml_line_count + 1 )) { 266return FAIL ;// rely on caller to do error messages 267 } 268 269if (top + 2 == bot ) { 270u_saveline (buf ,top + 1 ); 271 } 272 273return u_savecommon (buf ,top ,bot ,0 , false); 274} 275 276/// Save the line "lnum" (used by ":s" and "~" command). 277/// The line is replaced, so the new bottom line is lnum + 1. 278/// Careful: may trigger autocommands that reload the buffer. 279/// Returns FAIL when lines could not be saved, OK otherwise. 280int u_savesub (linenr_T lnum ) 281{ 282return u_savecommon (curbuf ,lnum - 1 ,lnum + 1 ,lnum + 1 , false); 283} 284 285/// A new line is inserted before line "lnum" (used by :s command). 286/// The line is inserted, so the new bottom line is lnum + 1. 287/// Careful: may trigger autocommands that reload the buffer. 288/// Returns FAIL when lines could not be saved, OK otherwise. 289int u_inssub (linenr_T lnum ) 290{ 291return u_savecommon (curbuf ,lnum - 1 ,lnum ,lnum + 1 , false); 292} 293 294/// Save the lines "lnum" - "lnum" + nlines (used by delete command). 295/// The lines are deleted, so the new bottom line is lnum, unless the buffer 296/// becomes empty. 297/// Careful: may trigger autocommands that reload the buffer. 298/// Returns FAIL when lines could not be saved, OK otherwise. 299int u_savedel (linenr_T lnum ,linenr_T nlines ) 300{ 301return u_savecommon (curbuf ,lnum - 1 ,lnum + nlines , 302nlines == curbuf -> b_ml .ml_line_count ?2 :lnum , false); 303} 304 305/// Return true when undo is allowed. Otherwise print an error message and 306/// return false. 307/// 308/// @return true if undo is allowed. 309bool undo_allowed (buf_T * buf ) 310{ 311// Don't allow changes when 'modifiable' is off. 312if (!MODIFIABLE (buf )) { 313emsg (_ (e_modifiable )); 314return false; 315 } 316 317// In the sandbox it's not allowed to change the text. 318if (sandbox != 0 ) { 319emsg (_ (e_sandbox )); 320return false; 321 } 322 323// Don't allow changes in the buffer while editing the cmdline. The 324// caller of getcmdline() may get confused. 325if (textlock != 0 || expr_map_locked ()) { 326emsg (_ (e_textlock )); 327return false; 328 } 329 330return true; 331} 332 333/// Get the 'undolevels' value for the current buffer. 334static OptInt get_undolevel (buf_T * buf ) 335{ 336if (buf -> b_p_ul == NO_LOCAL_UNDOLEVEL ) { 337return p_ul ; 338 } 339return buf -> b_p_ul ; 340} 341 342static inline void zero_fmark_additional_data (fmark_T * fmarks ) 343{ 344for (size_t i = 0 ;i < NMARKS ;i ++ ) { 345XFREE_CLEAR (fmarks [i ].additional_data ); 346 } 347} 348 349/// Common code for various ways to save text before a change. 350/// "top" is the line above the first changed line. 351/// "bot" is the line below the last changed line. 352/// "newbot" is the new bottom line. Use zero when not known. 353/// "reload" is true when saving for a buffer reload. 354/// Careful: may trigger autocommands that reload the buffer. 355/// Returns FAIL when lines could not be saved, OK otherwise. 356int u_savecommon (buf_T * buf ,linenr_T top ,linenr_T bot ,linenr_T newbot ,bool reload ) 357{ 358if (!reload ) { 359// When making changes is not allowed return FAIL. It's a crude way 360// to make all change commands fail. 361if (!undo_allowed (buf )) { 362return FAIL ; 363 } 364 365// Saving text for undo means we are going to make a change. Give a 366// warning for a read-only file before making the change, so that the 367// FileChangedRO event can replace the buffer with a read-write version 368// (e.g., obtained from a source control system). 369if (buf == curbuf ) { 370change_warning (buf ,0 ); 371 } 372 373if (bot > buf -> b_ml .ml_line_count + 1 ) { 374// This happens when the FileChangedRO autocommand changes the 375// file in a way it becomes shorter. 376emsg (_ ("E881: Line count changed unexpectedly" )); 377return FAIL ; 378 } 379 } 380 381#ifdef U_DEBUG 382u_check (false); 383#endif 384 385u_entry_T * uep ; 386u_entry_T * prev_uep ; 387linenr_T size = bot - top - 1 ; 388 389// If buf->b_u_synced is true make a new header. 390if (buf -> b_u_synced ) { 391// Need to create new entry in b_changelist. 392buf -> b_new_change = true; 393 394u_header_T * uhp ; 395if (get_undolevel (buf ) >=0 ) { 396// Make a new header entry. Do this first so that we don't mess 397// up the undo info when out of memory. 398uhp = xmalloc (sizeof (u_header_T )); 399kv_init (uhp -> uh_extmark ); 400#ifdef U_DEBUG 401uhp -> uh_magic = UH_MAGIC ; 402#endif 403 }else { 404uhp = NULL ; 405 } 406 407// If we undid more than we redid, move the entry lists before and 408// including buf->b_u_curhead to an alternate branch. 409u_header_T * old_curhead = buf -> b_u_curhead ; 410if (old_curhead != NULL ) { 411buf -> b_u_newhead = old_curhead -> uh_next .ptr ; 412buf -> b_u_curhead = NULL ; 413 } 414 415// free headers to keep the size right 416while (buf -> b_u_numhead > get_undolevel (buf ) 417&& buf -> b_u_oldhead != NULL ) { 418u_header_T * uhfree = buf -> b_u_oldhead ; 419 420if (uhfree == old_curhead ) { 421// Can't reconnect the branch, delete all of it. 422u_freebranch (buf ,uhfree ,& old_curhead ); 423 }else if (uhfree -> uh_alt_next .ptr == NULL ) { 424// There is no branch, only free one header. 425u_freeheader (buf ,uhfree ,& old_curhead ); 426 }else { 427// Free the oldest alternate branch as a whole. 428while (uhfree -> uh_alt_next .ptr != NULL ) { 429uhfree = uhfree -> uh_alt_next .ptr ; 430 } 431u_freebranch (buf ,uhfree ,& old_curhead ); 432 } 433#ifdef U_DEBUG 434u_check (true); 435#endif 436 } 437 438if (uhp == NULL ) {// no undo at all 439if (old_curhead != NULL ) { 440u_freebranch (buf ,old_curhead ,NULL ); 441 } 442buf -> b_u_synced = false; 443return OK ; 444 } 445 446uhp -> uh_prev .ptr = NULL ; 447uhp -> uh_next .ptr = buf -> b_u_newhead ; 448uhp -> uh_alt_next .ptr = old_curhead ; 449if (old_curhead != NULL ) { 450uhp -> uh_alt_prev .ptr = old_curhead -> uh_alt_prev .ptr ; 451 452if (uhp -> uh_alt_prev .ptr != NULL ) { 453uhp -> uh_alt_prev .ptr -> uh_alt_next .ptr = uhp ; 454 } 455 456old_curhead -> uh_alt_prev .ptr = uhp ; 457 458if (buf -> b_u_oldhead == old_curhead ) { 459buf -> b_u_oldhead = uhp ; 460 } 461 }else { 462uhp -> uh_alt_prev .ptr = NULL ; 463 } 464 465if (buf -> b_u_newhead != NULL ) { 466buf -> b_u_newhead -> uh_prev .ptr = uhp ; 467 } 468 469uhp -> uh_seq = ++ buf -> b_u_seq_last ; 470buf -> b_u_seq_cur = uhp -> uh_seq ; 471uhp -> uh_time = time (NULL ); 472uhp -> uh_save_nr = 0 ; 473buf -> b_u_time_cur = uhp -> uh_time + 1 ; 474 475uhp -> uh_walk = 0 ; 476uhp -> uh_entry = NULL ; 477uhp -> uh_getbot_entry = NULL ; 478uhp -> uh_cursor = atom_origin_pos (buf );// The pre-change position: undo restores it. 479if (virtual_active (curwin )&& curwin -> w_cursor .coladd > 0 480&& equalpos (uhp -> uh_cursor ,curwin -> w_cursor )) { 481uhp -> uh_cursor_vcol = getviscol (); 482 }else { 483uhp -> uh_cursor_vcol = -1 ; 484 } 485clearpos (& uhp -> uh_cursor_after ); 486 487// save changed and buffer empty flag for undo 488uhp -> uh_flags = (buf -> b_changed ?UH_CHANGED :0 )+ 489 ((buf -> b_ml .ml_flags & ML_EMPTY ) ?UH_EMPTYBUF :0 ); 490 491// save named marks and Visual marks for undo 492zero_fmark_additional_data (buf -> b_namedm ); 493memmove (uhp -> uh_namedm ,buf -> b_namedm , 494sizeof (buf -> b_namedm [0 ])* NMARKS ); 495uhp -> uh_visual = buf -> b_visual ; 496 497buf -> b_u_newhead = uhp ; 498 499if (buf -> b_u_oldhead == NULL ) { 500buf -> b_u_oldhead = uhp ; 501 } 502buf -> b_u_numhead ++ ; 503 }else { 504if (get_undolevel (buf )< 0 ) {// no undo at all 505return OK ; 506 } 507 508// When saving a single line, and it has been saved just before, it 509// doesn't make sense saving it again. Saves a lot of memory when 510// making lots of changes inside the same line. 511// This is only possible if the previous change didn't increase or 512// decrease the number of lines. 513// Check the ten last changes. More doesn't make sense and takes too 514// long. 515if (size == 1 ) { 516uep = u_get_headentry (buf ); 517prev_uep = NULL ; 518for (int i = 0 ;i < 10 ;i ++ ) { 519if (uep == NULL ) { 520break ; 521 } 522 523// If lines have been inserted/deleted we give up. 524// Also when the line was included in a multi-line save. 525if (u_entry_resized (buf ,uep ) 526|| (uep -> ue_size > 1 527&& top >=uep -> ue_top 528&& top + 2 <=uep -> ue_top + uep -> ue_size + 1 )) { 529break ; 530 } 531 532// If it's the same line we can skip saving it again. 533if (uep -> ue_size == 1 && uep -> ue_top == top ) { 534if (i > 0 ) { 535// It's not the last entry: get ue_bot for the last 536// entry now. Following deleted/inserted lines go to 537// the re-used entry. 538u_getbot (buf ); 539buf -> b_u_synced = false; 540 541// Move the found entry to become the last entry. The 542// order of undo/redo doesn't matter for the entries 543// we move it over, since they don't change the line 544// count and don't include this line. It does matter 545// for the found entry if the line count is changed by 546// the executed command. 547prev_uep -> ue_next = uep -> ue_next ; 548uep -> ue_next = buf -> b_u_newhead -> uh_entry ; 549buf -> b_u_newhead -> uh_entry = uep ; 550 } 551 552// The executed command may change the line count. 553if (newbot != 0 ) { 554uep -> ue_bot = newbot ; 555 }else if (bot > buf -> b_ml .ml_line_count ) { 556uep -> ue_bot = 0 ; 557 }else { 558uep -> ue_lcount = buf -> b_ml .ml_line_count ; 559buf -> b_u_newhead -> uh_getbot_entry = uep ; 560 } 561return OK ; 562 } 563prev_uep = uep ; 564uep = uep -> ue_next ; 565 } 566 } 567 568// find line number for ue_bot for previous u_save() 569u_getbot (buf ); 570 } 571 572// add lines in front of entry list 573uep = xmalloc (sizeof (u_entry_T )); 574CLEAR_POINTER (uep ); 575#ifdef U_DEBUG 576uep -> ue_magic = UE_MAGIC ; 577#endif 578 579uep -> ue_size = size ; 580uep -> ue_top = top ; 581if (newbot != 0 ) { 582uep -> ue_bot = newbot ; 583// Use 0 for ue_bot if bot is below last line. 584// Otherwise we have to compute ue_bot later. 585 }else if (bot > buf -> b_ml .ml_line_count ) { 586uep -> ue_bot = 0 ; 587 }else { 588uep -> ue_lcount = buf -> b_ml .ml_line_count ; 589buf -> b_u_newhead -> uh_getbot_entry = uep ; 590 } 591 592if (size > 0 ) { 593uep -> ue_array = xmalloc (sizeof (char * )* (size_t )size ); 594linenr_T lnum ; 595int i ; 596for (i = 0 ,lnum = top + 1 ;i < size ;i ++ ) { 597fast_breakcheck (); 598if (got_int ) { 599u_freeentry (uep ,i ); 600return FAIL ; 601 } 602uep -> ue_array [i ]= u_save_line_buf (buf ,lnum ++ ); 603 } 604 }else { 605uep -> ue_array = NULL ; 606 } 607 608uep -> ue_next = buf -> b_u_newhead -> uh_entry ; 609buf -> b_u_newhead -> uh_entry = uep ; 610if (reload ) { 611// buffer was reloaded, notify text change subscribers 612buf -> b_u_newhead -> uh_flags |=UH_RELOAD ; 613 } 614buf -> b_u_synced = false; 615undo_undoes = false; 616 617#ifdef U_DEBUG 618u_check (false); 619#endif 620return OK ; 621} 622 623/// Whether lines were added or deleted since `uep` (an entry of the newest undo state) was saved. 624static bool u_entry_resized (buf_T * buf ,u_entry_T * uep ) 625{ 626return buf -> b_u_newhead -> uh_getbot_entry != uep 627 ?uep -> ue_top + uep -> ue_size + 1 628!= (uep -> ue_bot == 0 ?buf -> b_ml .ml_line_count + 1 :uep -> ue_bot ) 629 :uep -> ue_lcount != buf -> b_ml .ml_line_count ; 630} 631 632// magic at start of undofile 633#define UF_START_MAGIC "Vim\237UnDo\345" 634#define UF_START_MAGIC_LEN 9 635// magic at start of header 636#define UF_HEADER_MAGIC 0x5fd0 637// magic after last header 638#define UF_HEADER_END_MAGIC 0xe7aa 639// magic at start of entry 640#define UF_ENTRY_MAGIC 0xf518 641// magic after last entry 642#define UF_ENTRY_END_MAGIC 0x3581 643 644// 2-byte undofile version number 645#define UF_VERSION 3 646 647// extra fields for header 648#define UF_LAST_SAVE_NR 1 649 650// extra fields for uhp 651#define UHP_SAVE_NR 1 652 653static const char e_not_open []= N_ ("E828: Cannot open undo file for writing: %s" ); 654 655/// Compute the hash for a buffer text into hash[UNDO_HASH_SIZE]. 656/// 657/// @param[in] buf The buffer used to compute the hash 658/// @param[in] hash Array of size UNDO_HASH_SIZE in which to store the value of 659/// the hash 660void u_compute_hash (buf_T * buf ,uint8_t * hash ) 661{ 662context_sha256_T ctx ; 663sha256_start (& ctx ); 664for (linenr_T lnum = 1 ;lnum <=buf -> b_ml .ml_line_count ;lnum ++ ) { 665char * p = ml_get_buf (buf ,lnum ); 666sha256_update (& ctx , (uint8_t * )p ,strlen (p )+ 1 ); 667 } 668sha256_finish (& ctx ,hash ); 669} 670 671/// Return an allocated string of the full path of the target undofile. 672/// 673/// @param[in] buf_ffname Full file name for which undo file location should 674/// be found. 675/// @param[in] reading If true, find the file to read by traversing all of the 676/// directories in &undodir. If false use the first 677/// existing directory. If none of the directories in 678/// &undodir option exist then last directory in the list 679/// will be automatically created. 680/// 681/// @return [allocated] File name to read from/write to or NULL. 682char * u_get_undo_file_name (const char * const buf_ffname ,const bool reading ) 683FUNC_ATTR_WARN_UNUSED_RESULT 684{ 685const char * ffname = buf_ffname ; 686 687if (ffname == NULL ) { 688return NULL ; 689 } 690 691#ifdef HAVE_READLINK 692char fname_buf [MAXPATHL ]; 693// Expand symlink in the file name, so that we put the undo file with the 694// actual file instead of with the symlink. 695if (resolve_symlink (ffname ,fname_buf )== OK ) { 696ffname = fname_buf ; 697 } 698#endif 699 700char dir_name [MAXPATHL + 1 ]; 701String munged_name = STRING_INIT ; 702char * undo_file_name = NULL ; 703 704const size_t ffname_len = strlen (ffname ); 705// Loop over 'undodir'. When reading find the first file that exists. 706// When not reading use the first directory that exists or ".". 707char * dirp = p_udir ; 708while (* dirp != NUL ) { 709size_t dir_len = copy_option_part (& dirp ,dir_name ,MAXPATHL ,"," ); 710if (dir_len == 1 && dir_name [0 ]== '.' ) { 711// Use same directory as the ffname, 712// "dir/name" -> "dir/.name.un~" 713undo_file_name = xmalloc (ffname_len + 6 ); 714memmove (undo_file_name ,ffname ,ffname_len + 1 ); 715char * const tail = path_tail (undo_file_name ); 716const size_t tail_len = ffname_len - (size_t )(tail - undo_file_name ); 717memmove (tail + 1 ,tail ,tail_len + 1 ); 718* tail = '.' ; 719memmove (tail + tail_len + 1 ,".un~" ,sizeof (".un~" )); 720 }else { 721dir_name [dir_len ]= NUL ; 722 723// Remove trailing pathseps from directory name 724while (dir_len > 1 && vim_ispathsep_nocolon (dir_name [dir_len - 1 ])) { 725dir_name [-- dir_len ]= NUL ; 726 } 727 728bool has_directory = os_isdir (dir_name ); 729if (!has_directory && * dirp == NUL && !reading ) { 730// Last directory in the list does not exist, create it. 731int ret ; 732char * failed_dir ; 733if ((ret = os_mkdir_recurse (dir_name ,0755 ,& failed_dir ,NULL ))!= 0 ) { 734semsg (_ ("E5003: Unable to create directory \"%s\" for undo file: %s" ), 735failed_dir ,os_strerror (ret )); 736xfree (failed_dir ); 737 }else { 738has_directory = true; 739 } 740 } 741if (has_directory ) { 742if (munged_name .data == NULL ) { 743munged_name = cbuf_to_string (ffname ,ffname_len ); 744for (char * p = munged_name .data ;* p != NUL ;MB_PTR_ADV (p )) { 745if (vim_ispathsep (* p )) { 746* p = '%' ; 747 } 748 } 749 } 750undo_file_name = concat_fnames (cbuf_as_string (dir_name ,dir_len ), 751munged_name , true).data ; 752 } 753 } 754 755// When reading check if the file exists. 756if (undo_file_name != NULL 757&& (!reading || os_path_exists (undo_file_name ))) { 758break ; 759 } 760XFREE_CLEAR (undo_file_name ); 761 } 762 763xfree (munged_name .data ); 764return undo_file_name ; 765} 766 767/// Display an error for corrupted undo file 768/// 769/// @param[in] mesg Identifier of the corruption kind. 770/// @param[in] file_name File in which error occurred. 771static void corruption_error (const char * const mesg ,const char * const file_name ) 772FUNC_ATTR_NONNULL_ALL 773{ 774semsg (_ ("E825: Corrupted undo file (%s): %s" ),mesg ,file_name ); 775} 776 777static void u_free_uhp (u_header_T * uhp ) 778{ 779u_entry_T * uep = uhp -> uh_entry ; 780while (uep != NULL ) { 781u_entry_T * nuep = uep -> ue_next ; 782u_freeentry (uep ,uep -> ue_size ); 783uep = nuep ; 784 } 785kv_destroy (uhp -> uh_extmark ); 786xfree (uhp ); 787} 788 789/// Writes the undofile header. 790/// 791/// @param bi The buffer information 792/// @param hash The hash of the buffer contents 793// 794/// @returns false in case of an error. 795static bool serialize_header (bufinfo_T * bi ,uint8_t * hash ) 796FUNC_ATTR_NONNULL_ALL 797{ 798buf_T * buf = bi -> bi_buf ; 799FILE * fp = bi -> bi_fp ; 800 801// Start writing, first the magic marker and undo info version. 802if (fwrite (UF_START_MAGIC ,UF_START_MAGIC_LEN ,1 ,fp )!= 1 ) { 803return false; 804 } 805 806undo_write_bytes (bi ,UF_VERSION ,2 ); 807 808// Write a hash of the buffer text, so that we can verify it is 809// still the same when reading the buffer text. 810if (!undo_write (bi ,hash ,UNDO_HASH_SIZE )) { 811return false; 812 } 813 814// Write buffer-specific data. 815undo_write_bytes (bi , (uintmax_t )buf -> b_ml .ml_line_count ,4 ); 816size_t len = buf -> b_u_line_ptr ?strlen (buf -> b_u_line_ptr ) :0 ; 817undo_write_bytes (bi ,len ,4 ); 818if (len > 0 && !undo_write (bi , (uint8_t * )buf -> b_u_line_ptr ,len )) { 819return false; 820 } 821undo_write_bytes (bi , (uintmax_t )buf -> b_u_line_lnum ,4 ); 822undo_write_bytes (bi , (uintmax_t )buf -> b_u_line_colnr ,4 ); 823 824// Write undo structures header data. 825put_header_ptr (bi ,buf -> b_u_oldhead ); 826put_header_ptr (bi ,buf -> b_u_newhead ); 827put_header_ptr (bi ,buf -> b_u_curhead ); 828 829undo_write_bytes (bi , (uintmax_t )buf -> b_u_numhead ,4 ); 830undo_write_bytes (bi , (uintmax_t )buf -> b_u_seq_last ,4 ); 831undo_write_bytes (bi , (uintmax_t )buf -> b_u_seq_cur ,4 ); 832uint8_t time_buf [8 ]; 833time_to_bytes (buf -> b_u_time_cur ,time_buf ); 834undo_write (bi ,time_buf ,sizeof (time_buf )); 835 836// Write optional fields. 837undo_write_bytes (bi ,4 ,1 ); 838undo_write_bytes (bi ,UF_LAST_SAVE_NR ,1 ); 839undo_write_bytes (bi , (uintmax_t )buf -> b_u_save_nr_last ,4 ); 840 841// Write end marker. 842undo_write_bytes (bi ,0 ,1 ); 843 844return true; 845} 846 847/// Writes an undo header. 848/// 849/// @param bi The buffer information 850/// @param uhp The undo header to write 851// 852/// @returns false in case of an error. 853static bool serialize_uhp (bufinfo_T * bi ,u_header_T * uhp ) 854{ 855if (!undo_write_bytes (bi , (uintmax_t )UF_HEADER_MAGIC ,2 )) { 856return false; 857 } 858 859put_header_ptr (bi ,uhp -> uh_next .ptr ); 860put_header_ptr (bi ,uhp -> uh_prev .ptr ); 861put_header_ptr (bi ,uhp -> uh_alt_next .ptr ); 862put_header_ptr (bi ,uhp -> uh_alt_prev .ptr ); 863undo_write_bytes (bi , (uintmax_t )uhp -> uh_seq ,4 ); 864serialize_pos (bi ,uhp -> uh_cursor ); 865undo_write_bytes (bi , (uintmax_t )uhp -> uh_cursor_vcol ,4 ); 866undo_write_bytes (bi , (uintmax_t )uhp -> uh_flags ,2 ); 867// Assume NMARKS will stay the same. 868for (size_t i = 0 ;i < (size_t )NMARKS ;i ++ ) { 869serialize_pos (bi ,uhp -> uh_namedm [i ].mark ); 870 } 871serialize_visualinfo (bi ,& uhp -> uh_visual ); 872uint8_t time_buf [8 ]; 873time_to_bytes (uhp -> uh_time ,time_buf ); 874undo_write (bi ,time_buf ,sizeof (time_buf )); 875 876// Write optional fields. 877undo_write_bytes (bi ,4 ,1 ); 878undo_write_bytes (bi ,UHP_SAVE_NR ,1 ); 879undo_write_bytes (bi , (uintmax_t )uhp -> uh_save_nr ,4 ); 880 881// Write end marker. 882undo_write_bytes (bi ,0 ,1 ); 883 884// Write all the entries. 885for (u_entry_T * uep = uhp -> uh_entry ;uep ;uep = uep -> ue_next ) { 886undo_write_bytes (bi , (uintmax_t )UF_ENTRY_MAGIC ,2 ); 887if (!serialize_uep (bi ,uep )) { 888return false; 889 } 890 } 891undo_write_bytes (bi , (uintmax_t )UF_ENTRY_END_MAGIC ,2 ); 892 893// Write all extmark undo objects 894for (size_t i = 0 ;i < kv_size (uhp -> uh_extmark );i ++ ) { 895if (!serialize_extmark (bi ,kv_A (uhp -> uh_extmark ,i ))) { 896return false; 897 } 898 } 899undo_write_bytes (bi , (uintmax_t )UF_ENTRY_END_MAGIC ,2 ); 900 901return true; 902} 903 904static u_header_T * unserialize_uhp (bufinfo_T * bi ,const char * file_name ) 905{ 906u_header_T * uhp = xmalloc (sizeof (u_header_T )); 907CLEAR_POINTER (uhp ); 908#ifdef U_DEBUG 909uhp -> uh_magic = UH_MAGIC ; 910#endif 911uhp -> uh_next .seq = undo_read_4c (bi ); 912uhp -> uh_prev .seq = undo_read_4c (bi ); 913uhp -> uh_alt_next .seq = undo_read_4c (bi ); 914uhp -> uh_alt_prev .seq = undo_read_4c (bi ); 915uhp -> uh_seq = undo_read_4c (bi ); 916if (uhp -> uh_seq <=0 ) { 917corruption_error ("uh_seq" ,file_name ); 918xfree (uhp ); 919return NULL ; 920 } 921unserialize_pos (bi ,& uhp -> uh_cursor ); 922uhp -> uh_cursor_vcol = undo_read_4c (bi ); 923uhp -> uh_flags = undo_read_2c (bi ); 924const Timestamp cur_timestamp = os_time (); 925for (size_t i = 0 ;i < (size_t )NMARKS ;i ++ ) { 926unserialize_pos (bi ,& uhp -> uh_namedm [i ].mark ); 927uhp -> uh_namedm [i ].timestamp = cur_timestamp ; 928uhp -> uh_namedm [i ].fnum = 0 ; 929 } 930unserialize_visualinfo (bi ,& uhp -> uh_visual ); 931uhp -> uh_time = undo_read_time (bi ); 932 933// Unserialize optional fields. 934while (true) { 935int len = undo_read_byte (bi ); 936 937if (len == EOF ) { 938corruption_error ("truncated" ,file_name ); 939u_free_uhp (uhp ); 940return NULL ; 941 } 942if (len == 0 ) { 943break ; 944 } 945int what = undo_read_byte (bi ); 946switch (what ) { 947case UHP_SAVE_NR : 948uhp -> uh_save_nr = undo_read_4c (bi ); 949break ; 950default : 951// Field not supported, skip it. 952while (-- len >=0 ) { 953undo_read_byte (bi ); 954 } 955 } 956 } 957 958// Unserialize the uep list. 959u_entry_T * last_uep = NULL ; 960int c ; 961while ((c = undo_read_2c (bi ))== UF_ENTRY_MAGIC ) { 962bool error = false; 963u_entry_T * uep = unserialize_uep (bi ,& error ,file_name ); 964if (last_uep == NULL ) { 965uhp -> uh_entry = uep ; 966 }else { 967last_uep -> ue_next = uep ; 968 } 969last_uep = uep ; 970if (error ) { 971u_free_uhp (uhp ); 972return NULL ; 973 } 974 } 975if (c != UF_ENTRY_END_MAGIC ) { 976corruption_error ("entry end" ,file_name ); 977u_free_uhp (uhp ); 978return NULL ; 979 } 980 981// Unserialize all extmark undo information 982kv_init (uhp -> uh_extmark ); 983 984while ((c = undo_read_2c (bi ))== UF_ENTRY_MAGIC ) { 985bool error = false; 986ExtmarkUndoObject * extup = unserialize_extmark (bi ,& error ,file_name ); 987if (error ) { 988xfree (extup ); 989u_free_uhp (uhp ); 990return NULL ; 991 } 992kv_push (uhp -> uh_extmark ,* extup ); 993xfree (extup ); 994 } 995if (c != UF_ENTRY_END_MAGIC ) { 996corruption_error ("entry end" ,file_name ); 997u_free_uhp (uhp ); 998return NULL ; 999 } 1000 1001return uhp ; 1002} 1003 1004static bool serialize_extmark (bufinfo_T * bi ,ExtmarkUndoObject extup ) 1005{ 1006if (extup .type == kExtmarkSplice ) { 1007undo_write_bytes (bi , (uintmax_t )UF_ENTRY_MAGIC ,2 ); 1008undo_write_bytes (bi , (uintmax_t )extup .type ,4 ); 1009if (!undo_write (bi , (uint8_t * )& (extup .data .splice ), 1010sizeof (ExtmarkSplice ))) { 1011return false; 1012 } 1013 }else if (extup .type == kExtmarkMove ) { 1014undo_write_bytes (bi , (uintmax_t )UF_ENTRY_MAGIC ,2 ); 1015undo_write_bytes (bi , (uintmax_t )extup .type ,4 ); 1016if (!undo_write (bi , (uint8_t * )& (extup .data .move ),sizeof (ExtmarkMove ))) { 1017return false; 1018 } 1019 } 1020// Note: We do not serialize ExtmarkSavePos information, since 1021// buffer marktrees are not retained when closing/reopening a file 1022return true; 1023} 1024 1025static ExtmarkUndoObject * unserialize_extmark (bufinfo_T * bi ,bool * error ,const char * filename ) 1026{ 1027uint8_t * buf = NULL ; 1028 1029ExtmarkUndoObject * extup = xmalloc (sizeof (ExtmarkUndoObject )); 1030 1031UndoObjectType type = (UndoObjectType )undo_read_4c (bi ); 1032extup -> type = type ; 1033if (type == kExtmarkSplice ) { 1034size_t n_elems = (size_t )sizeof (ExtmarkSplice ) /sizeof (uint8_t ); 1035buf = xcalloc (n_elems ,sizeof (uint8_t )); 1036if (!undo_read (bi ,buf ,n_elems )) { 1037 gotoerror ; 1038 } 1039extup -> data .splice = * (ExtmarkSplice * )buf ; 1040 }else if (type == kExtmarkMove ) { 1041size_t n_elems = (size_t )sizeof (ExtmarkMove ) /sizeof (uint8_t ); 1042buf = xcalloc (n_elems ,sizeof (uint8_t )); 1043if (!undo_read (bi ,buf ,n_elems )) { 1044 gotoerror ; 1045 } 1046extup -> data .move = * (ExtmarkMove * )buf ; 1047 }else { 1048 gotoerror ; 1049 } 1050 1051xfree (buf ); 1052 1053return extup ; 1054 1055error : 1056xfree (extup ); 1057if (buf ) { 1058xfree (buf ); 1059 } 1060* error = true; 1061return NULL ; 1062} 1063 1064/// Serializes "uep". 1065/// 1066/// @param bi The buffer information 1067/// @param uep The undo entry to write 1068// 1069/// @returns false in case of an error. 1070static bool serialize_uep (bufinfo_T * bi ,u_entry_T * uep ) 1071{ 1072undo_write_bytes (bi , (uintmax_t )uep -> ue_top ,4 ); 1073undo_write_bytes (bi , (uintmax_t )uep -> ue_bot ,4 ); 1074undo_write_bytes (bi , (uintmax_t )uep -> ue_lcount ,4 ); 1075undo_write_bytes (bi , (uintmax_t )uep -> ue_size ,4 ); 1076 1077for (size_t i = 0 ;i < (size_t )uep -> ue_size ;i ++ ) { 1078size_t len = strlen (uep -> ue_array [i ]); 1079if (!undo_write_bytes (bi ,len ,4 )) { 1080return false; 1081 } 1082if (len > 0 && !undo_write (bi , (uint8_t * )uep -> ue_array [i ],len )) { 1083return false; 1084 } 1085 } 1086return true; 1087} 1088 1089static u_entry_T * unserialize_uep (bufinfo_T * bi ,bool * error ,const char * file_name ) 1090FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 1091{ 1092u_entry_T * uep = xmalloc (sizeof (u_entry_T )); 1093CLEAR_POINTER (uep ); 1094#ifdef U_DEBUG 1095uep -> ue_magic = UE_MAGIC ; 1096#endif 1097uep -> ue_top = undo_read_4c (bi ); 1098uep -> ue_bot = undo_read_4c (bi ); 1099uep -> ue_lcount = undo_read_4c (bi ); 1100if (uep -> ue_top < 0 || uep -> ue_bot < 0 || uep -> ue_lcount < 0 ) { 1101// Fail early; u_undoredo() takes these as line numbers. 1102corruption_error ("entry lnum" ,file_name ); 1103* error = true; 1104return uep ; 1105 } 1106 1107uep -> ue_size = undo_read_len (bi ,"entry size" ,file_name ); 1108if (uep -> ue_size < 0 ) { 1109uep -> ue_size = 0 ;// u_freeentry() must not walk ue_array. 1110* error = true; 1111return uep ; 1112 } 1113 1114char ** array = uep -> ue_size > 0 ?xcalloc ((size_t )uep -> ue_size ,sizeof (char * )) :NULL ; 1115uep -> ue_array = array ; 1116 1117for (size_t i = 0 ;i < (size_t )uep -> ue_size ;i ++ ) { 1118int line_len = undo_read_len (bi ,"line length" ,file_name ); 1119char * line = line_len < 0 ?NULL :undo_read_string (bi , (size_t )line_len ); 1120if (line == NULL ) { 1121* error = true; 1122return uep ; 1123 } 1124array [i ]= line ; 1125 } 1126return uep ; 1127} 1128 1129/// Serializes "pos". 1130static void serialize_pos (bufinfo_T * bi ,pos_T pos ) 1131{ 1132undo_write_bytes (bi , (uintmax_t )pos .lnum ,4 ); 1133undo_write_bytes (bi , (uintmax_t )pos .col ,4 ); 1134undo_write_bytes (bi , (uintmax_t )pos .coladd ,4 ); 1135} 1136 1137/// Unserializes the pos_T at the current position. 1138static void unserialize_pos (bufinfo_T * bi ,pos_T * pos ) 1139{ 1140pos -> lnum = undo_read_4c (bi ); 1141pos -> lnum = MAX (pos -> lnum ,0 ); 1142pos -> col = undo_read_4c (bi ); 1143pos -> col = MAX (pos -> col ,0 ); 1144pos -> coladd = undo_read_4c (bi ); 1145pos -> coladd = MAX (pos -> coladd ,0 ); 1146} 1147 1148/// Serializes "info". 1149static void serialize_visualinfo (bufinfo_T * bi ,visualinfo_T * info ) 1150{ 1151serialize_pos (bi ,info -> vi_start ); 1152serialize_pos (bi ,info -> vi_end ); 1153undo_write_bytes (bi , (uintmax_t )info -> vi_mode ,4 ); 1154undo_write_bytes (bi , (uintmax_t )info -> vi_curswant ,4 ); 1155} 1156 1157/// Unserializes the visualinfo_T at the current position. 1158static void unserialize_visualinfo (bufinfo_T * bi ,visualinfo_T * info ) 1159{ 1160unserialize_pos (bi ,& info -> vi_start ); 1161unserialize_pos (bi ,& info -> vi_end ); 1162info -> vi_mode = undo_read_4c (bi ); 1163info -> vi_curswant = undo_read_4c (bi ); 1164} 1165 1166/// Write the undo tree in an undo file. 1167/// 1168/// @param[in] name Name of the undo file or NULL if this function needs to 1169/// generate the undo file name based on buf->b_ffname. 1170/// @param[in] forceit True for `:wundo!`, false otherwise. 1171/// @param[in] buf Buffer for which undo file is written. 1172/// @param[in] hash Hash value of the buffer text. Must have #UNDO_HASH_SIZE 1173/// size. 1174void u_write_undo (const char * const name ,const bool forceit ,buf_T * const buf ,uint8_t * const hash ) 1175FUNC_ATTR_NONNULL_ARG (3 ,4 ) 1176{ 1177char * file_name ; 1178#ifdef U_DEBUG 1179int headers_written = 0 ; 1180#endif 1181FILE * fp = NULL ; 1182bool write_ok = false; 1183 1184if (name == NULL ) { 1185file_name = u_get_undo_file_name (buf -> b_ffname , false); 1186if (file_name == NULL ) { 1187if (p_verbose > 0 ) { 1188verbose_enter (); 1189smsg (0 ,"%s" ,_ ("Cannot write undo file in any directory in 'undodir'" )); 1190verbose_leave (); 1191 } 1192return ; 1193 } 1194 }else { 1195file_name = (char * )name ; 1196 } 1197 1198// Decide about the permission to use for the undo file. If the buffer 1199// has a name use the permission of the original file. Otherwise only 1200// allow the user to access the undo file. 1201int perm = 0600 ; 1202if (buf -> b_ffname != NULL ) { 1203perm = os_getperm (buf -> b_ffname ); 1204if (perm < 0 ) { 1205perm = 0600 ; 1206 } 1207 } 1208 1209// Strip any sticky and executable bits. 1210perm = perm & 0666 ; 1211 1212// If the undo file already exists, verify that it actually is an undo 1213// file, and delete it. 1214if (os_path_exists (file_name )) { 1215if (name == NULL || !forceit ) { 1216// Check we can read it and it's an undo file. 1217int fd = os_open (file_name ,O_RDONLY ,0 ); 1218if (fd < 0 ) { 1219if (name != NULL || p_verbose > 0 ) { 1220if (name == NULL ) { 1221verbose_enter (); 1222 } 1223smsg (0 ,_ ("Will not overwrite with undo file, cannot read: %s" ), 1224file_name ); 1225if (name == NULL ) { 1226verbose_leave (); 1227 } 1228 } 1229 gototheend ; 1230 }else { 1231char mbuf [UF_START_MAGIC_LEN ]; 1232ssize_t len = read_eintr (fd ,mbuf ,UF_START_MAGIC_LEN ); 1233close (fd ); 1234if (len < UF_START_MAGIC_LEN 1235|| memcmp (mbuf ,UF_START_MAGIC ,UF_START_MAGIC_LEN )!= 0 ) { 1236if (name != NULL || p_verbose > 0 ) { 1237if (name == NULL ) { 1238verbose_enter (); 1239 } 1240smsg (0 ,_ ("Will not overwrite, this is not an undo file: %s" ), 1241file_name ); 1242if (name == NULL ) { 1243verbose_leave (); 1244 } 1245 } 1246 gototheend ; 1247 } 1248 } 1249 } 1250os_remove (file_name ); 1251 } 1252 1253// If there is no undo information at all, quit here after deleting any 1254// existing undo file. 1255if (buf -> b_u_numhead == 0 && buf -> b_u_line_ptr == NULL ) { 1256if (p_verbose > 0 ) { 1257verb_msg (_ ("Skipping undo file write, nothing to undo" )); 1258 } 1259 gototheend ; 1260 } 1261 1262int fd = os_open (file_name ,O_CREAT |O_WRONLY |O_EXCL |O_NOFOLLOW ,perm ); 1263if (fd < 0 ) { 1264semsg (_ (e_not_open ),file_name ); 1265 gototheend ; 1266 } 1267os_setperm (file_name ,perm ); 1268if (p_verbose > 0 ) { 1269verbose_enter (); 1270smsg (0 ,_ ("Writing undo file: %s" ),file_name ); 1271verbose_leave (); 1272 } 1273 1274#ifdef U_DEBUG 1275// Check there is no problem in undo info before writing. 1276u_check (false); 1277#endif 1278 1279#ifdef UNIX 1280// Try to set the group of the undo file same as the original file. If 1281// this fails, set the protection bits for the group same as the 1282// protection bits for others. 1283FileInfo file_info_old ; 1284FileInfo file_info_new ; 1285if (buf -> b_ffname != NULL 1286&& os_fileinfo (buf -> b_ffname ,& file_info_old ) 1287&& os_fileinfo (file_name ,& file_info_new ) 1288&& file_info_old .stat .st_gid != file_info_new .stat .st_gid 1289&& os_fchown (fd , (uv_uid_t )- 1 , (uv_gid_t )file_info_old .stat .st_gid )) { 1290os_setperm (file_name , (perm & 0707 ) | ((perm & 07 ) <<3 )); 1291 } 1292#endif 1293 1294fp = fdopen (fd ,"w" ); 1295if (fp == NULL ) { 1296semsg (_ (e_not_open ),file_name ); 1297close (fd ); 1298os_remove (file_name ); 1299 gototheend ; 1300 } 1301 1302// Undo must be synced. 1303u_sync (true); 1304 1305// Write the header. 1306bufinfo_T bi = { 1307 .bi_buf = buf , 1308 .bi_fp = fp , 1309 }; 1310if (!serialize_header (& bi ,hash )) { 1311 gotowrite_error ; 1312 } 1313 1314// Iteratively serialize UHPs and their UEPs from the top down. 1315int mark = ++ lastmark ; 1316u_header_T * uhp = buf -> b_u_oldhead ; 1317while (uhp != NULL ) { 1318// Serialize current UHP if we haven't seen it 1319if (uhp -> uh_walk != mark ) { 1320uhp -> uh_walk = mark ; 1321#ifdef U_DEBUG 1322headers_written ++ ; 1323#endif 1324if (!serialize_uhp (& bi ,uhp )) { 1325 gotowrite_error ; 1326 } 1327 } 1328 1329// Now walk through the tree - algorithm from undo_time(). 1330if (uhp -> uh_prev .ptr != NULL && uhp -> uh_prev .ptr -> uh_walk != mark ) { 1331uhp = uhp -> uh_prev .ptr ; 1332 }else if (uhp -> uh_alt_next .ptr != NULL 1333&& uhp -> uh_alt_next .ptr -> uh_walk != mark ) { 1334uhp = uhp -> uh_alt_next .ptr ; 1335 }else if (uhp -> uh_next .ptr != NULL && uhp -> uh_alt_prev .ptr == NULL 1336&& uhp -> uh_next .ptr -> uh_walk != mark ) { 1337uhp = uhp -> uh_next .ptr ; 1338 }else if (uhp -> uh_alt_prev .ptr != NULL ) { 1339uhp = uhp -> uh_alt_prev .ptr ; 1340 }else { 1341uhp = uhp -> uh_next .ptr ; 1342 } 1343 } 1344 1345if (undo_write_bytes (& bi , (uintmax_t )UF_HEADER_END_MAGIC ,2 )) { 1346write_ok = true; 1347 } 1348#ifdef U_DEBUG 1349if (headers_written != buf -> b_u_numhead ) { 1350semsg ("Written %" PRId64 " headers, ..." , (int64_t )headers_written ); 1351semsg ("... but numhead is %" PRId64 , (int64_t )buf -> b_u_numhead ); 1352 } 1353#endif 1354 1355if ((buf -> b_p_fs >=0 ?buf -> b_p_fs :p_fs )&& fflush (fp )== 0 1356&& os_fsync (fd )!= 0 ) { 1357write_ok = false; 1358 } 1359 1360write_error : 1361fclose (fp ); 1362if (!write_ok ) { 1363semsg (_ (e_write_error_in_undo_file_str ),file_name ); 1364 } 1365 1366if (buf -> b_ffname != NULL ) { 1367// For systems that support ACL: get the ACL from the original file. 1368vim_acl_T acl = os_get_acl (buf -> b_ffname ); 1369os_set_acl (file_name ,acl ); 1370os_free_acl (acl ); 1371 } 1372 1373theend : 1374if (file_name != name ) { 1375xfree (file_name ); 1376 } 1377} 1378 1379/// Compare undo headers on the sequence number, for sorting uhp_table. 1380static int uhp_seq_cmp (const void * v1 ,const void * v2 ) 1381{ 1382const u_header_T * u1 = * (u_header_T ** )v1 ; 1383const u_header_T * u2 = * (u_header_T ** )v2 ; 1384 1385return u1 -> uh_seq == u2 -> uh_seq ?0 :u1 -> uh_seq > u2 -> uh_seq ?1 :-1 ; 1386} 1387 1388/// Find the header with sequence number "seq" in "uhp_table", which has 1389/// "num_head" entries and is sorted on uh_seq. 1390/// Return the table index of the header or -1 when not found. 1391static int uhp_table_find (u_header_T ** uhp_table ,int num_head ,int seq ) 1392{ 1393int lo = 0 ; 1394int hi = num_head - 1 ; 1395 1396while (lo <=hi ) { 1397int mid = lo + (hi - lo ) /2 ; 1398 1399if (uhp_table [mid ]-> uh_seq < seq ) { 1400lo = mid + 1 ; 1401 }else if (uhp_table [mid ]-> uh_seq > seq ) { 1402hi = mid - 1 ; 1403 }else { 1404return mid ; 1405 } 1406 } 1407return -1 ; 1408} 1409 1410/// Loads the undo tree from an undo file. 1411/// If "name" is not NULL use it as the undo file name. This also means being 1412/// a bit more verbose. 1413/// Otherwise use curbuf->b_ffname to generate the undo file name. 1414/// "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. 1415void u_read_undo (char * name ,const uint8_t * hash ,const char * orig_name FUNC_ATTR_UNUSED ) 1416FUNC_ATTR_NONNULL_ARG (2 ) 1417{ 1418u_header_T ** uhp_table = NULL ; 1419char * line_ptr = NULL ; 1420 1421char * file_name ; 1422if (name == NULL ) { 1423file_name = u_get_undo_file_name (curbuf -> b_ffname , true); 1424if (file_name == NULL ) { 1425return ; 1426 } 1427 1428#ifdef UNIX 1429// For safety we only read an undo file if the owner is equal to the 1430// owner of the text file or equal to the current user. 1431FileInfo file_info_orig ; 1432FileInfo file_info_undo ; 1433if (os_fileinfo (orig_name ,& file_info_orig ) 1434&& os_fileinfo (file_name ,& file_info_undo ) 1435&& file_info_orig .stat .st_uid != file_info_undo .stat .st_uid 1436&& file_info_undo .stat .st_uid != getuid ()) { 1437if (p_verbose > 0 ) { 1438verbose_enter (); 1439smsg (0 ,_ ("Not reading undo file, owner differs: %s" ), 1440file_name ); 1441verbose_leave (); 1442 } 1443xfree (file_name ); 1444return ; 1445 } 1446#endif 1447 }else { 1448file_name = name ; 1449 } 1450 1451if (p_verbose > 0 ) { 1452verbose_enter (); 1453smsg (0 ,_ ("Reading undo file: %s" ),file_name ); 1454verbose_leave (); 1455 } 1456 1457FILE * fp = os_fopen (file_name ,"r" ); 1458if (fp == NULL ) { 1459if (name != NULL || p_verbose > 0 ) { 1460semsg (_ ("E822: Cannot open undo file for reading: %s" ),file_name ); 1461 } 1462 gotoerror ; 1463 } 1464 1465FileInfo file_info ; 1466bufinfo_T bi = { 1467 .bi_buf = curbuf , 1468 .bi_fp = fp , 1469 .bi_fsize = os_fileinfo_fd (fileno (fp ),& file_info ) ? (off_T )os_fileinfo_size (& file_info ) :0 , 1470 }; 1471 1472// Read the undo file header. 1473char magic_buf [UF_START_MAGIC_LEN ]; 1474if (fread (magic_buf ,UF_START_MAGIC_LEN ,1 ,fp )!= 1 1475|| memcmp (magic_buf ,UF_START_MAGIC ,UF_START_MAGIC_LEN )!= 0 ) { 1476semsg (_ ("E823: Not an undo file: %s" ),file_name ); 1477 gotoerror ; 1478 } 1479int version = get2c (fp ); 1480if (version != UF_VERSION ) { 1481semsg (_ ("E824: Incompatible undo file: %s" ),file_name ); 1482 gotoerror ; 1483 } 1484 1485uint8_t read_hash [UNDO_HASH_SIZE ]; 1486if (!undo_read (& bi ,read_hash ,UNDO_HASH_SIZE )) { 1487corruption_error ("hash" ,file_name ); 1488 gotoerror ; 1489 } 1490linenr_T line_count = (linenr_T )undo_read_4c (& bi ); 1491if (memcmp (hash ,read_hash ,UNDO_HASH_SIZE )!= 0 1492|| line_count != curbuf -> b_ml .ml_line_count ) { 1493if (p_verbose > 0 || name != NULL ) { 1494if (name == NULL ) { 1495verbose_enter (); 1496 } 1497give_warning (_ ("File contents changed, cannot use undo info" ), true, true); 1498if (name == NULL ) { 1499verbose_leave (); 1500 } 1501 } 1502 gotoerror ; 1503 } 1504 1505// Read undo data for "U" command. 1506int str_len = undo_read_len (& bi ,"line length" ,file_name ); 1507if (str_len < 0 ) { 1508 gotoerror ; 1509 } 1510 1511if (str_len > 0 ) { 1512line_ptr = undo_read_string (& bi , (size_t )str_len ); 1513if (line_ptr == NULL ) { 1514corruption_error ("truncated" ,file_name ); 1515 gotoerror ; 1516 } 1517 } 1518linenr_T line_lnum = (linenr_T )undo_read_4c (& bi ); 1519colnr_T line_colnr = (colnr_T )undo_read_4c (& bi ); 1520if (line_lnum < 0 || line_colnr < 0 ) { 1521corruption_error ("line lnum/col" ,file_name ); 1522 gotoerror ; 1523 } 1524 1525// Begin general undo data 1526int old_header_seq = undo_read_4c (& bi ); 1527int new_header_seq = undo_read_4c (& bi ); 1528int cur_header_seq = undo_read_4c (& bi ); 1529int num_head = undo_read_len (& bi ,"num_head" ,file_name ); 1530if (num_head < 0 ) { 1531 gotoerror ; 1532 } 1533int seq_last = undo_read_4c (& bi ); 1534int seq_cur = undo_read_4c (& bi ); 1535time_t seq_time = undo_read_time (& bi ); 1536 1537// Optional header fields. 1538int last_save_nr = 0 ; 1539while (true) { 1540int len = undo_read_byte (& bi ); 1541 1542if (len == 0 || len == EOF ) { 1543break ; 1544 } 1545int what = undo_read_byte (& bi ); 1546switch (what ) { 1547case UF_LAST_SAVE_NR : 1548last_save_nr = undo_read_4c (& bi ); 1549break ; 1550 1551default : 1552// field not supported, skip 1553while (-- len >=0 ) { 1554undo_read_byte (& bi ); 1555 } 1556 } 1557 } 1558 1559// uhp_table will store the freshly created undo headers we allocate 1560// until we insert them into curbuf. The table remains sorted by the 1561// sequence numbers of the headers. 1562// When there are no headers uhp_table is NULL. 1563if (num_head > 0 ) { 1564uhp_table = xcalloc ((size_t )num_head ,sizeof (* uhp_table )); 1565 } 1566 1567int num_read_uhps = 0 ; 1568 1569int c ; 1570while ((c = undo_read_2c (& bi ))== UF_HEADER_MAGIC ) { 1571if (num_read_uhps >=num_head ) { 1572corruption_error ("num_head too small" ,file_name ); 1573 gotoerror ; 1574 } 1575 1576u_header_T * uhp = unserialize_uhp (& bi ,file_name ); 1577if (uhp == NULL ) { 1578 gotoerror ; 1579 } 1580uhp_table [num_read_uhps ++ ]= uhp ; 1581 } 1582 1583if (num_read_uhps != num_head ) { 1584corruption_error ("num_head" ,file_name ); 1585 gotoerror ; 1586 } 1587if (c != UF_HEADER_END_MAGIC ) { 1588corruption_error ("end marker" ,file_name ); 1589 gotoerror ; 1590 } 1591 1592#ifdef U_DEBUG 1593size_t amount = num_head * sizeof (int )+ 1 ; 1594int * uhp_table_used = xmalloc (amount ); 1595memset (uhp_table_used ,0 ,amount ); 1596# define SET_FLAG (j ) ++uhp_table_used[j] 1597#else 1598# define SET_FLAG (j ) 1599#endif 1600 1601// We have put all of the headers into a table. Each header stores the 1602// sequence numbers of the headers it links to; resolve those into 1603// pointers. Every entry is non-NULL: a header that failed to 1604// unserialize or a count mismatch was an error above. 1605if (num_head > 0 ) { 1606qsort (uhp_table , (size_t )num_head ,sizeof (u_header_T * ),uhp_seq_cmp ); 1607 } 1608 1609// In the sorted table two headers with the same uh_seq are neighbours. 1610for (int i = 0 ;i < num_head - 1 ;i ++ ) { 1611if (uhp_table [i ]-> uh_seq == uhp_table [i + 1 ]-> uh_seq ) { 1612corruption_error ("duplicate uh_seq" ,file_name ); 1613 gotoerror ; 1614 } 1615 } 1616 1617// Resolve the sequence number "link".seq into a pointer to the header 1618// with that number. A number that does not match any header, including 1619// zero (written for a NULL pointer) and the own sequence number of the 1620// header "hidx", resolves to NULL. 1621#define SWIZZLE_SEQ (link ,hidx ) \ 1622 do { \ 1623 int fidx = uhp_table_find(uhp_table, num_head, (link).seq); \ 1624 if (fidx >= 0 && fidx != (hidx)) { \ 1625 (link).ptr = uhp_table[fidx]; \ 1626 SET_FLAG(fidx); \ 1627 } else { \ 1628 (link).ptr = NULL; \ 1629 } \ 1630 } while (0) 1631 1632int old_idx = -1 ; 1633int new_idx = -1 ; 1634int cur_idx = -1 ; 1635for (int i = 0 ;i < num_head ;i ++ ) { 1636u_header_T * uhp = uhp_table [i ]; 1637SWIZZLE_SEQ (uhp -> uh_next ,i ); 1638SWIZZLE_SEQ (uhp -> uh_prev ,i ); 1639SWIZZLE_SEQ (uhp -> uh_alt_next ,i ); 1640SWIZZLE_SEQ (uhp -> uh_alt_prev ,i ); 1641if (old_header_seq > 0 && old_idx < 0 && uhp -> uh_seq == old_header_seq ) { 1642old_idx = i ; 1643SET_FLAG (i ); 1644 } 1645if (new_header_seq > 0 && new_idx < 0 && uhp -> uh_seq == new_header_seq ) { 1646new_idx = i ; 1647SET_FLAG (i ); 1648 } 1649if (cur_header_seq > 0 && cur_idx < 0 && uhp -> uh_seq == cur_header_seq ) { 1650cur_idx = i ; 1651SET_FLAG (i ); 1652 } 1653 } 1654#undef SWIZZLE_SEQ 1655 1656// Now that we have read the undo info successfully, free the current undo 1657// info and use the info from the file. 1658u_blockfree (curbuf ); 1659curbuf -> b_u_oldhead = old_idx < 0 ?NULL :uhp_table [old_idx ]; 1660curbuf -> b_u_newhead = new_idx < 0 ?NULL :uhp_table [new_idx ]; 1661curbuf -> b_u_curhead = cur_idx < 0 ?NULL :uhp_table [cur_idx ]; 1662curbuf -> b_u_line_ptr = line_ptr ; 1663curbuf -> b_u_line_lnum = line_lnum ; 1664curbuf -> b_u_line_colnr = line_colnr ; 1665curbuf -> b_u_numhead = num_head ; 1666curbuf -> b_u_seq_last = seq_last ; 1667curbuf -> b_u_seq_cur = seq_cur ; 1668curbuf -> b_u_time_cur = seq_time ; 1669curbuf -> b_u_save_nr_last = last_save_nr ; 1670curbuf -> b_u_save_nr_cur = last_save_nr ; 1671 1672curbuf -> b_u_synced = true; 1673xfree (uhp_table ); 1674 1675#ifdef U_DEBUG 1676for (int i = 0 ;i < num_head ;i ++ ) { 1677if (uhp_table_used [i ]== 0 ) { 1678semsg ("uhp_table entry %" PRId64 " not used, leaking memory" , (int64_t )i ); 1679 } 1680 } 1681xfree (uhp_table_used ); 1682u_check (true); 1683#endif 1684 1685if (name != NULL ) { 1686smsg (0 ,_ ("Finished reading undo file %s" ),file_name ); 1687 } 1688 gototheend ; 1689 1690error : 1691xfree (line_ptr ); 1692if (uhp_table != NULL ) { 1693for (int i = 0 ;i < num_read_uhps ;i ++ ) { 1694if (uhp_table [i ]!= NULL ) { 1695u_free_uhp (uhp_table [i ]); 1696 } 1697 } 1698xfree (uhp_table ); 1699 } 1700 1701theend : 1702if (fp != NULL ) { 1703fclose (fp ); 1704 } 1705if (file_name != name ) { 1706xfree (file_name ); 1707 } 1708} 1709 1710/// Writes a sequence of bytes to the undo file. 1711/// 1712/// @param bi The buffer info 1713/// @param ptr The byte buffer to write 1714/// @param len The number of bytes to write 1715/// 1716/// @returns false in case of an error. 1717static bool undo_write (bufinfo_T * bi ,uint8_t * ptr ,size_t len ) 1718FUNC_ATTR_NONNULL_ARG (1 ) 1719{ 1720return fwrite (ptr ,len ,1 ,bi -> bi_fp )== 1 ; 1721} 1722 1723/// Writes a number, most significant bit first, in "len" bytes. 1724/// 1725/// Must match with undo_read_?c() functions. 1726/// 1727/// @param bi The buffer info 1728/// @param nr The number to write 1729/// @param len The number of bytes to use when writing the number. 1730/// 1731/// @returns false in case of an error. 1732static bool undo_write_bytes (bufinfo_T * bi ,uintmax_t nr ,size_t len ) 1733{ 1734assert (len > 0 ); 1735uint8_t buf [8 ]; 1736for (size_t i = len - 1 ,bufi = 0 ;bufi < len ;i -- ,bufi ++ ) { 1737buf [bufi ]= (uint8_t )(nr >> (i * 8 )); 1738 } 1739return undo_write (bi ,buf ,len ); 1740} 1741 1742/// Writes the pointer to an undo header. 1743/// 1744/// Instead of writing the pointer itself, we use the sequence 1745/// number of the header. This is converted back to pointers 1746/// when reading. 1747static void put_header_ptr (bufinfo_T * bi ,u_header_T * uhp ) 1748{ 1749assert (uhp == NULL || uhp -> uh_seq >=0 ); 1750undo_write_bytes (bi , (uint64_t )(uhp != NULL ?uhp -> uh_seq :0 ),4 ); 1751} 1752 1753static int undo_read_4c (bufinfo_T * bi ) 1754{ 1755return get4c (bi -> bi_fp ); 1756} 1757 1758/// Reads a 4-byte count/length field. A corrupted file can hold any value here, so reject negative 1759/// or if it exceeds the bytes left in the file. 1760/// 1761/// @param what Name of the field, for the error message. 1762/// @return The value, or -1 if invalid (reported). 1763static int undo_read_len (bufinfo_T * bi ,const char * what ,const char * file_name ) 1764FUNC_ATTR_NONNULL_ALL 1765{ 1766int len = undo_read_4c (bi ); 1767off_T pos = vim_ftell (bi -> bi_fp ); 1768if (len < 0 || (bi -> bi_fsize > 0 && (pos < 0 || len > bi -> bi_fsize - pos ))) { 1769// get4c() also returns -1 for a file that ends here. 1770corruption_error (feof (bi -> bi_fp ) ?"truncated" :what ,file_name ); 1771return -1 ; 1772 } 1773return len ; 1774} 1775 1776static int undo_read_2c (bufinfo_T * bi ) 1777{ 1778return get2c (bi -> bi_fp ); 1779} 1780 1781static int undo_read_byte (bufinfo_T * bi ) 1782{ 1783return getc (bi -> bi_fp ); 1784} 1785 1786static time_t undo_read_time (bufinfo_T * bi ) 1787{ 1788return get8ctime (bi -> bi_fp ); 1789} 1790 1791/// Reads "buffer[size]" from the undo file. 1792/// 1793/// @param bi The buffer info 1794/// @param buffer Character buffer to read data into 1795/// @param size The size of the character buffer 1796/// 1797/// @returns false in case of an error. 1798static bool undo_read (bufinfo_T * bi ,uint8_t * buffer ,size_t size ) 1799FUNC_ATTR_NONNULL_ARG (1 ) 1800{ 1801const bool retval = fread (buffer ,size ,1 ,bi -> bi_fp )== 1 ; 1802if (!retval ) { 1803// Error may be checked for only later. Fill with zeros, 1804// so that the reader won't use garbage. 1805memset (buffer ,0 ,size ); 1806 } 1807return retval ; 1808} 1809 1810/// Reads a string of length "len" from "bi->bi_fd" and appends a zero to it. 1811/// 1812/// @param len can be zero to allocate an empty line. 1813/// 1814/// @returns a pointer to allocated memory or NULL in case of an error. 1815static char * undo_read_string (bufinfo_T * bi ,size_t len ) 1816{ 1817char * ptr = xmallocz (len ); 1818if (len > 0 && !undo_read (bi , (uint8_t * )ptr ,len )) { 1819xfree (ptr ); 1820return NULL ; 1821 } 1822return ptr ; 1823} 1824 1825/// If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible). 1826/// If 'cpoptions' does not contain 'u': Always undo. 1827void u_undo (int count ) 1828{ 1829// If we get an undo command while executing a macro, we behave like the 1830// original vi. If this happens twice in one macro the result will not 1831// be compatible. 1832if (!curbuf -> b_u_synced ) { 1833u_sync (true); 1834count = 1 ; 1835 } 1836 1837if (vim_strchr (p_cpo ,kCpoUndo )== NULL ) { 1838undo_undoes = true; 1839 }else { 1840undo_undoes = !undo_undoes ; 1841 } 1842u_doit (count , false, true); 1843} 1844 1845/// If 'cpoptions' contains 'u': Repeat the previous undo or redo. 1846/// If 'cpoptions' does not contain 'u': Always redo. 1847void u_redo (int count ) 1848{ 1849if (vim_strchr (p_cpo ,kCpoUndo )== NULL ) { 1850undo_undoes = false; 1851 } 1852 1853u_doit (count , false, true); 1854} 1855 1856/// Undo and remove the branch from the undo tree. 1857/// Also moves the cursor (as a "normal" undo would). 1858/// 1859/// @param do_buf_event If `true`, send the changedtick with the buffer updates 1860bool u_undo_and_forget (int count ,bool do_buf_event ) 1861{ 1862if (curbuf -> b_u_synced == false) { 1863u_sync (true); 1864count = 1 ; 1865 } 1866undo_undoes = true; 1867u_doit (count , true,do_buf_event ); 1868 1869if (curbuf -> b_u_curhead == NULL ) { 1870// nothing was undone. 1871return false; 1872 } 1873 1874u_forget_header (curbuf ,curbuf -> b_u_curhead );// The undone branch. 1875return true; 1876} 1877 1878/// Undo or redo, depending on `undo_undoes`, `count` times. 1879/// 1880/// @param startcount How often to undo or redo 1881/// @param quiet If `true`, don't show messages 1882/// @param do_buf_event If `true`, send the changedtick with the buffer updates 1883static void u_doit (int startcount ,bool quiet ,bool do_buf_event ) 1884{ 1885if (!undo_allowed (curbuf )) { 1886return ; 1887 } 1888atom_did_global_op ();// multicursor: undo/redo must not cascade (global, not per-cursor). 1889 1890u_newcount = 0 ; 1891u_oldcount = 0 ; 1892if (curbuf -> b_ml .ml_flags & ML_EMPTY ) { 1893u_oldcount = -1 ; 1894 } 1895 1896msg_ext_set_kind ("undo" ); 1897int count = startcount ; 1898while (count -- ) { 1899// Do the change warning now, so that it triggers FileChangedRO when 1900// needed. This may cause the file to be reloaded, that must happen 1901// before we do anything, because it may change curbuf->b_u_curhead 1902// and more. 1903change_warning (curbuf ,0 ); 1904 1905if (undo_undoes ) { 1906if (curbuf -> b_u_curhead == NULL ) {// first undo 1907curbuf -> b_u_curhead = curbuf -> b_u_newhead ; 1908 }else if (get_undolevel (curbuf )> 0 ) {// multi level undo 1909// get next undo 1910curbuf -> b_u_curhead = curbuf -> b_u_curhead -> uh_next .ptr ; 1911 } 1912// nothing to undo 1913if (curbuf -> b_u_numhead == 0 || curbuf -> b_u_curhead == NULL ) { 1914// stick curbuf->b_u_curhead at end 1915curbuf -> b_u_curhead = curbuf -> b_u_oldhead ; 1916beep_flush (); 1917if (count == startcount - 1 ) { 1918if (!shortmess (kShmUndo )) { 1919msg (_ ("Already at oldest change" ),0 ); 1920 } 1921return ; 1922 } 1923break ; 1924 } 1925 1926u_undoredo (true,do_buf_event ); 1927 }else { 1928if (curbuf -> b_u_curhead == NULL || get_undolevel (curbuf ) <=0 ) { 1929beep_flush ();// nothing to redo 1930if (count == startcount - 1 ) { 1931if (!shortmess (kShmUndo )) { 1932msg (_ ("Already at newest change" ),0 ); 1933 } 1934return ; 1935 } 1936break ; 1937 } 1938 1939u_undoredo (false,do_buf_event ); 1940 1941// Advance for next redo. Set "newhead" when at the end of the 1942// redoable changes. 1943if (curbuf -> b_u_curhead -> uh_prev .ptr == NULL ) { 1944curbuf -> b_u_newhead = curbuf -> b_u_curhead ; 1945 } 1946curbuf -> b_u_curhead = curbuf -> b_u_curhead -> uh_prev .ptr ; 1947 } 1948 } 1949u_undo_end (undo_undoes , false,quiet ); 1950} 1951 1952// Undo or redo over the timeline. 1953// When "step" is negative go back in time, otherwise goes forward in time. 1954// When "sec" is false make "step" steps, when "sec" is true use "step" as 1955// seconds. 1956// When "file" is true use "step" as a number of file writes. 1957// When "absolute" is true use "step" as the sequence number to jump to. 1958// "sec" must be false then. 1959void undo_time (int step ,bool sec ,bool file ,bool absolute ) 1960{ 1961if (text_locked ()) { 1962text_locked_msg (); 1963return ; 1964 } 1965mc_undo_time ();// Time-travel crosses cascade boundaries, exit mc-session. 1966 1967// First make sure the current undoable change is synced. 1968if (!curbuf -> b_u_synced ) { 1969u_sync (true); 1970 } 1971 1972u_newcount = 0 ; 1973u_oldcount = 0 ; 1974if (curbuf -> b_ml .ml_flags & ML_EMPTY ) { 1975u_oldcount = -1 ; 1976 } 1977 1978int target ; 1979int closest ; 1980u_header_T * uhp = NULL ; 1981bool dosec = sec ; 1982bool dofile = file ; 1983bool above = false; 1984bool did_undo = true; 1985 1986// "target" is the node below which we want to be. 1987// Init "closest" to a value we can't reach. 1988if (absolute ) { 1989target = step ; 1990closest = -1 ; 1991 }else { 1992if (dosec ) { 1993target = (int )curbuf -> b_u_time_cur + step ; 1994 }else if (dofile ) { 1995if (step < 0 ) { 1996// Going back to a previous write. If there were changes after 1997// the last write, count that as moving one file-write, so 1998// that ":earlier 1f" undoes all changes since the last save. 1999uhp = curbuf -> b_u_curhead ; 2000if (uhp != NULL ) { 2001uhp = uhp -> uh_next .ptr ; 2002 }else { 2003uhp = curbuf -> b_u_newhead ; 2004 } 2005if (uhp != NULL && uhp -> uh_save_nr != 0 ) { 2006// "uh_save_nr" was set in the last block, that means 2007// there were no changes since the last write 2008target = curbuf -> b_u_save_nr_cur + step ; 2009 }else { 2010// count the changes since the last write as one step 2011target = curbuf -> b_u_save_nr_cur + step + 1 ; 2012 } 2013if (target <=0 ) { 2014// Go to before first write: before the oldest change. Use 2015// the sequence number for that. 2016dofile = false; 2017 } 2018 }else { 2019// Moving forward to a newer write. 2020target = curbuf -> b_u_save_nr_cur + step ; 2021if (target > curbuf -> b_u_save_nr_last ) { 2022// Go to after last write: after the latest change. Use 2023// the sequence number for that. 2024target = curbuf -> b_u_seq_last + 1 ; 2025dofile = false; 2026 } 2027 } 2028 }else { 2029target = curbuf -> b_u_seq_cur + step ; 2030 } 2031if (step < 0 ) { 2032target = MAX (target ,0 ); 2033closest = -1 ; 2034 }else { 2035if (dosec ) { 2036closest = (int )(os_time ()+ 1 ); 2037 }else if (dofile ) { 2038closest = curbuf -> b_u_save_nr_last + 2 ; 2039 }else { 2040closest = curbuf -> b_u_seq_last + 2 ; 2041 } 2042if (target >=closest ) { 2043target = closest - 1 ; 2044 } 2045 } 2046 } 2047int closest_start = closest ; 2048int closest_seq = curbuf -> b_u_seq_cur ; 2049int mark ; 2050int nomark = 0 ;// shut up compiler 2051 2052// When "target" is 0; Back to origin. 2053if (target == 0 ) { 2054mark = lastmark ;// avoid that GCC complains 2055 gototarget_zero ; 2056 } 2057 2058// May do this twice: 2059// 1. Search for "target", update "closest" to the best match found. 2060// 2. If "target" not found search for "closest". 2061// 2062// When using the closest time we use the sequence number in the second 2063// round, because there may be several entries with the same time. 2064for (int round = 1 ;round <=2 ;round ++ ) { 2065// Find the path from the current state to where we want to go. The 2066// desired state can be anywhere in the undo tree, need to go all over 2067// it. We put "nomark" in uh_walk where we have been without success, 2068// "mark" where it could possibly be. 2069mark = ++ lastmark ; 2070nomark = ++ lastmark ; 2071 2072if (curbuf -> b_u_curhead == NULL ) {// at leaf of the tree 2073uhp = curbuf -> b_u_newhead ; 2074 }else { 2075uhp = curbuf -> b_u_curhead ; 2076 } 2077 2078while (uhp != NULL ) { 2079uhp -> uh_walk = mark ; 2080int val = dosec ? (int )(uhp -> uh_time ) 2081 :dofile ?uhp -> uh_save_nr 2082 :uhp -> uh_seq ; 2083 2084if (round == 1 && !(dofile && val == 0 )) { 2085// Remember the header that is closest to the target. 2086// It must be at least in the right direction (checked with 2087// "b_u_seq_cur"). When the timestamp is equal find the 2088// highest/lowest sequence number. 2089if ((step < 0 ?uhp -> uh_seq <=curbuf -> b_u_seq_cur 2090 :uhp -> uh_seq > curbuf -> b_u_seq_cur ) 2091&& ((dosec && val == closest ) 2092 ? (step < 0 2093 ?uhp -> uh_seq < closest_seq 2094 :uhp -> uh_seq > closest_seq ) 2095 :closest == closest_start 2096|| (val > target 2097 ? (closest > target 2098 ?val - target <=closest - target 2099 :val - target <=target - closest ) 2100 : (closest > target 2101 ?target - val <=closest - target 2102 :target - val <=target - closest )))) { 2103closest = val ; 2104closest_seq = uhp -> uh_seq ; 2105 } 2106 } 2107 2108// Quit searching when we found a match. But when searching for a 2109// time we need to continue looking for the best uh_seq. 2110if (target == val && !dosec ) { 2111target = uhp -> uh_seq ; 2112break ; 2113 } 2114 2115// go down in the tree if we haven't been there 2116if (uhp -> uh_prev .ptr != NULL && uhp -> uh_prev .ptr -> uh_walk != nomark 2117&& uhp -> uh_prev .ptr -> uh_walk != mark ) { 2118uhp = uhp -> uh_prev .ptr ; 2119 }else if (uhp -> uh_alt_next .ptr != NULL 2120&& uhp -> uh_alt_next .ptr -> uh_walk != nomark 2121&& uhp -> uh_alt_next .ptr -> uh_walk != mark ) { 2122// go to alternate branch if we haven't been there 2123uhp = uhp -> uh_alt_next .ptr ; 2124 }else if (uhp -> uh_next .ptr != NULL && uhp -> uh_alt_prev .ptr == NULL 2125// go up in the tree if we haven't been there and we are at the 2126// start of alternate branches 2127&& uhp -> uh_next .ptr -> uh_walk != nomark 2128&& uhp -> uh_next .ptr -> uh_walk != mark ) { 2129// If still at the start we don't go through this change. 2130if (uhp == curbuf -> b_u_curhead ) { 2131uhp -> uh_walk = nomark ; 2132 } 2133uhp = uhp -> uh_next .ptr ; 2134 }else { 2135// need to backtrack; mark this node as useless 2136uhp -> uh_walk = nomark ; 2137if (uhp -> uh_alt_prev .ptr != NULL ) { 2138uhp = uhp -> uh_alt_prev .ptr ; 2139 }else { 2140uhp = uhp -> uh_next .ptr ; 2141 } 2142 } 2143 } 2144 2145if (uhp != NULL ) {// found it 2146break ; 2147 } 2148 2149if (absolute ) { 2150semsg (_ ("E830: Undo number %" PRId64 " not found" ), (int64_t )step ); 2151return ; 2152 } 2153 2154if (closest == closest_start ) { 2155if (!shortmess (kShmUndo )) { 2156if (step < 0 ) { 2157msg (_ ("Already at oldest change" ),0 ); 2158 }else { 2159msg (_ ("Already at newest change" ),0 ); 2160 } 2161 } 2162return ; 2163 } 2164 2165target = closest_seq ; 2166dosec = false; 2167dofile = false; 2168if (step < 0 ) { 2169above = true;// stop above the header 2170 } 2171 } 2172 2173target_zero : 2174// If we found it: Follow the path to go to where we want to be. 2175if (uhp != NULL || target == 0 ) { 2176// First go up the tree as much as needed. 2177while (!got_int ) { 2178// Do the change warning now, for the same reason as above. 2179change_warning (curbuf ,0 ); 2180 2181uhp = curbuf -> b_u_curhead ; 2182if (uhp == NULL ) { 2183uhp = curbuf -> b_u_newhead ; 2184 }else { 2185uhp = uhp -> uh_next .ptr ; 2186 } 2187if (uhp == NULL 2188|| (target > 0 && uhp -> uh_walk != mark ) 2189|| (uhp -> uh_seq == target && !above )) { 2190break ; 2191 } 2192curbuf -> b_u_curhead = uhp ; 2193u_undoredo (true, true); 2194if (target > 0 ) { 2195uhp -> uh_walk = nomark ;// don't go back down here 2196 } 2197 } 2198 2199// When back to origin, redo is not needed. 2200if (target > 0 ) { 2201// And now go down the tree (redo), branching off where needed. 2202while (!got_int ) { 2203// Do the change warning now, for the same reason as above. 2204change_warning (curbuf ,0 ); 2205 2206uhp = curbuf -> b_u_curhead ; 2207if (uhp == NULL ) { 2208break ; 2209 } 2210 2211// Go back to the first branch with a mark. 2212while (uhp -> uh_alt_prev .ptr != NULL 2213&& uhp -> uh_alt_prev .ptr -> uh_walk == mark ) { 2214uhp = uhp -> uh_alt_prev .ptr ; 2215 } 2216 2217// Find the last branch with a mark, that's the one. 2218u_header_T * last = uhp ; 2219while (last -> uh_alt_next .ptr != NULL 2220&& last -> uh_alt_next .ptr -> uh_walk == mark ) { 2221last = last -> uh_alt_next .ptr ; 2222 } 2223if (last != uhp ) { 2224// Make the used branch the first entry in the list of 2225// alternatives to make "u" and CTRL-R take this branch. 2226while (uhp -> uh_alt_prev .ptr != NULL ) { 2227uhp = uhp -> uh_alt_prev .ptr ; 2228 } 2229if (last -> uh_alt_next .ptr != NULL ) { 2230last -> uh_alt_next .ptr -> uh_alt_prev .ptr = last -> uh_alt_prev .ptr ; 2231 } 2232last -> uh_alt_prev .ptr -> uh_alt_next .ptr = last -> uh_alt_next .ptr ; 2233last -> uh_alt_prev .ptr = NULL ; 2234last -> uh_alt_next .ptr = uhp ; 2235uhp -> uh_alt_prev .ptr = last ; 2236 2237if (curbuf -> b_u_oldhead == uhp ) { 2238curbuf -> b_u_oldhead = last ; 2239 } 2240uhp = last ; 2241if (uhp -> uh_next .ptr != NULL ) { 2242uhp -> uh_next .ptr -> uh_prev .ptr = uhp ; 2243 } 2244 } 2245curbuf -> b_u_curhead = uhp ; 2246 2247if (uhp -> uh_walk != mark ) { 2248break ;// must have reached the target 2249 } 2250 2251// Stop when going backwards in time and didn't find the exact 2252// header we were looking for. 2253if (uhp -> uh_seq == target && above ) { 2254curbuf -> b_u_seq_cur = target - 1 ; 2255break ; 2256 } 2257 2258u_undoredo (false, true); 2259 2260// Advance "curhead" to below the header we last used. If it 2261// becomes NULL then we need to set "newhead" to this leaf. 2262if (uhp -> uh_prev .ptr == NULL ) { 2263curbuf -> b_u_newhead = uhp ; 2264 } 2265curbuf -> b_u_curhead = uhp -> uh_prev .ptr ; 2266did_undo = false; 2267 2268if (uhp -> uh_seq == target ) {// found it! 2269break ; 2270 } 2271 2272uhp = uhp -> uh_prev .ptr ; 2273if (uhp == NULL || uhp -> uh_walk != mark ) { 2274// Need to redo more but can't find it... 2275internal_error ("undo_time()" ); 2276break ; 2277 } 2278 } 2279 } 2280 } 2281u_undo_end (did_undo ,absolute , false); 2282} 2283 2284/// u_undoredo: common code for undo and redo 2285/// 2286/// The lines in the file are replaced by the lines in the entry list at 2287/// curbuf->b_u_curhead. The replaced lines in the file are saved in the entry 2288/// list for the next undo/redo. 2289/// 2290/// @param undo If `true`, go up the tree. Down if `false`. 2291/// @param do_buf_event If `true`, send buffer updates. 2292static void u_undoredo (bool undo ,bool do_buf_event ) 2293{ 2294char ** newarray = NULL ; 2295linenr_T newlnum = MAXLNUM ; 2296pos_T new_curpos = curwin -> w_cursor ; 2297u_entry_T * nuep ; 2298u_entry_T * newlist = NULL ; 2299fmark_T namedm [NMARKS ]; 2300u_header_T * curhead = curbuf -> b_u_curhead ; 2301 2302// Don't want autocommands using the undo structures here, they are 2303// invalid till the end. 2304block_autocmds (); 2305 2306#ifdef U_DEBUG 2307u_check (false); 2308#endif 2309int old_flags = curhead -> uh_flags ; 2310int new_flags = (curbuf -> b_changed ?UH_CHANGED :0 ) 2311 | ((curbuf -> b_ml .ml_flags & ML_EMPTY ) ?UH_EMPTYBUF :0 ) 2312 | (old_flags & UH_RELOAD ); 2313setpcmark (); 2314 2315// save marks before undo/redo 2316zero_fmark_additional_data (curbuf -> b_namedm ); 2317memmove (namedm ,curbuf -> b_namedm ,sizeof (curbuf -> b_namedm [0 ])* NMARKS ); 2318visualinfo_T visualinfo = curbuf -> b_visual ; 2319curbuf -> b_op_start .lnum = curbuf -> b_ml .ml_line_count ; 2320curbuf -> b_op_start .col = 0 ; 2321curbuf -> b_op_end .lnum = 0 ; 2322curbuf -> b_op_end .col = 0 ; 2323 2324for (u_entry_T * uep = curhead -> uh_entry ;uep != NULL ;uep = nuep ) { 2325linenr_T top = uep -> ue_top ; 2326linenr_T bot = uep -> ue_bot ; 2327if (bot == 0 ) { 2328bot = curbuf -> b_ml .ml_line_count + 1 ; 2329 } 2330if (top > curbuf -> b_ml .ml_line_count || top >=bot 2331|| bot > curbuf -> b_ml .ml_line_count + 1 ) { 2332unblock_autocmds (); 2333iemsg (_ ("E438: u_undo: line numbers wrong" )); 2334changed (curbuf );// don't want UNCHANGED now 2335return ; 2336 } 2337 2338linenr_T oldsize = bot - top - 1 ;// number of lines before undo 2339linenr_T newsize = uep -> ue_size ;// number of lines after undo 2340 2341// Decide about the cursor position, depending on what text changed. 2342// Don't set it yet, it may be invalid if lines are going to be added. 2343 { 2344// If the saved cursor is somewhere in this undo block, move it to 2345// the remembered position. Makes "gwap" put the cursor back 2346// where it was. 2347linenr_T lnum = curhead -> uh_cursor .lnum ; 2348if (lnum >=top && lnum <=top + newsize + 1 ) { 2349new_curpos = curhead -> uh_cursor ; 2350// We don't want other entries to override saved cursor 2351// position. 2352newlnum = -1 ; 2353 }else if (top < newlnum ) { 2354// Use the first line that actually changed. Avoids that 2355// undoing auto-formatting puts the cursor in the previous 2356// line. 2357int i ; 2358for (i = 0 ;i < newsize && i < oldsize ;i ++ ) { 2359if (strcmp (uep -> ue_array [i ],ml_get (top + 1 + (linenr_T )i ))!= 0 ) { 2360break ; 2361 } 2362 } 2363if (i == newsize && newlnum == MAXLNUM && uep -> ue_next == NULL ) { 2364newlnum = top ; 2365new_curpos .lnum = newlnum + 1 ; 2366 }else if (i < newsize ) { 2367newlnum = top + (linenr_T )i ; 2368new_curpos .lnum = newlnum + 1 ; 2369 } 2370 } 2371 } 2372 2373bool empty_buffer = false; 2374 2375// Delete the lines between top and bot and save them in newarray. 2376if (oldsize > 0 ) { 2377newarray = xmalloc (sizeof (char * )* (size_t )oldsize ); 2378// delete backwards, it goes faster in most cases 2379int i ; 2380linenr_T lnum ; 2381for (lnum = bot - 1 ,i = oldsize ;-- i >=0 ;lnum -- ) { 2382// what can we do when we run out of memory? 2383newarray [i ]= u_save_line (lnum ); 2384// remember we deleted the last line in the buffer, and a 2385// dummy empty line will be inserted 2386if (curbuf -> b_ml .ml_line_count == 1 ) { 2387empty_buffer = true; 2388 } 2389ml_delete (lnum );// ML_DEL_UNDO 2390 } 2391 }else { 2392newarray = NULL ; 2393 } 2394 2395// make sure the cursor is on a valid line after the deletions 2396check_cursor_lnum (curwin ); 2397 2398// Insert the lines in u_array between top and bot. 2399if (newsize ) { 2400int i ; 2401linenr_T lnum ; 2402for (lnum = top ,i = 0 ;i < newsize ;i ++ ,lnum ++ ) { 2403// If the file is empty, there is an empty line 1 that we 2404// should get rid of, by replacing it with the new line 2405if (empty_buffer && lnum == 0 ) { 2406ml_replace (1 ,uep -> ue_array [i ], true); 2407 }else { 2408ml_append_flags (lnum ,uep -> ue_array [i ],0 ,0 );// ML_APPEND_UNDO 2409 } 2410xfree (uep -> ue_array [i ]); 2411 } 2412xfree (uep -> ue_array ); 2413 } 2414 2415// Adjust marks 2416if (oldsize != newsize ) { 2417mark_adjust (top + 1 ,top + oldsize ,MAXLNUM ,newsize - oldsize ,kExtmarkNOOP ); 2418if (curbuf -> b_op_start .lnum > top + oldsize ) { 2419curbuf -> b_op_start .lnum += newsize - oldsize ; 2420 } 2421if (curbuf -> b_op_end .lnum > top + oldsize ) { 2422curbuf -> b_op_end .lnum += newsize - oldsize ; 2423 } 2424 } 2425 2426if (oldsize > 0 || newsize > 0 ) { 2427changed_lines (curbuf ,top + 1 ,0 ,bot ,newsize - oldsize ,do_buf_event ); 2428// When text has been changed, possibly the start of the next line 2429// may have SpellCap that should be removed or it needs to be 2430// displayed. Schedule the next line for redrawing just in case. 2431if (spell_check_window (curwin )&& bot <=curbuf -> b_ml .ml_line_count ) { 2432redrawWinline (curwin ,bot ); 2433 } 2434 } 2435 2436// Set the '[ mark. 2437curbuf -> b_op_start .lnum = MIN (curbuf -> b_op_start .lnum ,top + 1 ); 2438// Set the '] mark. 2439if (newsize == 0 && top + 1 > curbuf -> b_op_end .lnum ) { 2440curbuf -> b_op_end .lnum = top + 1 ; 2441 }else if (top + newsize > curbuf -> b_op_end .lnum ) { 2442curbuf -> b_op_end .lnum = top + newsize ; 2443 } 2444 2445u_newcount += newsize ; 2446u_oldcount += oldsize ; 2447uep -> ue_size = oldsize ; 2448uep -> ue_array = newarray ; 2449uep -> ue_bot = top + newsize + 1 ; 2450 2451// insert this entry in front of the new entry list 2452nuep = uep -> ue_next ; 2453uep -> ue_next = newlist ; 2454newlist = uep ; 2455 } 2456 2457// Ensure the '[ and '] marks are within bounds. 2458curbuf -> b_op_start .lnum = MIN (curbuf -> b_op_start .lnum ,curbuf -> b_ml .ml_line_count ); 2459curbuf -> b_op_end .lnum = MIN (curbuf -> b_op_end .lnum ,curbuf -> b_ml .ml_line_count ); 2460 2461// Adjust Extmarks 2462if (undo ) { 2463for (int i = (int )kv_size (curhead -> uh_extmark )- 1 ;i > -1 ;i -- ) { 2464extmark_apply_undo (kv_A (curhead -> uh_extmark ,i ),undo ); 2465 } 2466// redo 2467 }else { 2468for (int i = 0 ;i < (int )kv_size (curhead -> uh_extmark );i ++ ) { 2469extmark_apply_undo (kv_A (curhead -> uh_extmark ,i ),undo ); 2470 } 2471 } 2472if (curhead -> uh_flags & UH_RELOAD ) { 2473// TODO(bfredl): this is a bit crude. When 'undoreload' is used we 2474// should have all info to send a buffer-reloaing on_lines/on_bytes event 2475buf_updates_unload (curbuf , true); 2476 } 2477// Finish adjusting extmarks 2478 2479// Set the cursor to the desired position. Check that the line is valid. 2480curwin -> w_cursor = new_curpos ; 2481check_cursor_lnum (curwin ); 2482 2483curhead -> uh_entry = newlist ; 2484curhead -> uh_flags = new_flags ; 2485if ((old_flags & UH_EMPTYBUF )&& buf_is_empty (curbuf )) { 2486curbuf -> b_ml .ml_flags |=ML_EMPTY ; 2487 } 2488if (old_flags & UH_CHANGED ) { 2489changed (curbuf ); 2490 }else { 2491unchanged (curbuf , false, true); 2492 } 2493 2494// because the calls to changed()/unchanged() above will bump changedtick 2495// again, we need to send a nvim_buf_lines_event with just the new value of 2496// b:changedtick 2497if (do_buf_event ) { 2498buf_updates_changedtick (curbuf ); 2499 } 2500 2501// restore marks from before undo/redo 2502for (int i = 0 ;i < NMARKS ;i ++ ) { 2503if (curhead -> uh_namedm [i ].mark .lnum != 0 ) { 2504free_fmark (curbuf -> b_namedm [i ]); 2505curbuf -> b_namedm [i ]= curhead -> uh_namedm [i ]; 2506 } 2507if (namedm [i ].mark .lnum != 0 ) { 2508curhead -> uh_namedm [i ]= namedm [i ]; 2509 }else { 2510curhead -> uh_namedm [i ].mark .lnum = 0 ; 2511 } 2512 } 2513if (curhead -> uh_visual .vi_start .lnum != 0 ) { 2514curbuf -> b_visual = curhead -> uh_visual ; 2515curhead -> uh_visual = visualinfo ; 2516 } 2517 2518if (undo && curhead -> uh_cursor .lnum >=1 2519&& curhead -> uh_cursor .lnum <=curbuf -> b_ml .ml_line_count ) { 2520// Undo restores the pre-change text; restore the pre-change cursor too. #5989 2521curwin -> w_cursor = curhead -> uh_cursor ; 2522if (virtual_active (curwin )&& curhead -> uh_cursor_vcol >=0 ) { 2523coladvance (curwin ,curhead -> uh_cursor_vcol ); 2524 } 2525 }else { 2526// If the cursor is only off by one line, put it at the same position as 2527// before starting the change (for the "o" command). 2528// Otherwise the cursor should go to the first changed line. 2529if (curhead -> uh_cursor .lnum + 1 == curwin -> w_cursor .lnum 2530&& curwin -> w_cursor .lnum > 1 ) { 2531curwin -> w_cursor .lnum -- ; 2532 } 2533if (curwin -> w_cursor .lnum <=curbuf -> b_ml .ml_line_count ) { 2534if (curhead -> uh_cursor .lnum == curwin -> w_cursor .lnum ) { 2535curwin -> w_cursor .col = curhead -> uh_cursor .col ; 2536if (virtual_active (curwin )&& curhead -> uh_cursor_vcol >=0 ) { 2537coladvance (curwin ,curhead -> uh_cursor_vcol ); 2538 }else { 2539curwin -> w_cursor .coladd = 0 ; 2540 } 2541 }else { 2542beginline (BL_SOL |BL_FIX ); 2543 } 2544 }else { 2545// We get here with the current cursor line being past the end (eg 2546// after adding lines at the end of the file, and then undoing it). 2547// check_cursor() will move the cursor to the last line. Move it to 2548// the first column here. 2549curwin -> w_cursor .col = 0 ; 2550curwin -> w_cursor .coladd = 0 ; 2551 } 2552 } 2553 2554// Make sure the cursor is on an existing line and column. 2555check_cursor (curwin ); 2556 2557if (!undo && curhead -> uh_cursor_after .lnum > 0 ) { 2558// Restore the post-change cursor pos, if available. 2559curwin -> w_cursor = curhead -> uh_cursor_after ; 2560check_cursor (curwin ); 2561 } 2562 2563// Remember where we are for "g-" and ":earlier 10s". 2564curbuf -> b_u_seq_cur = curhead -> uh_seq ; 2565if (undo ) { 2566// We are below the previous undo. However, to make ":earlier 1s" 2567// work we compute this as being just above the just undone change. 2568curbuf -> b_u_seq_cur = curhead -> uh_next .ptr 2569 ?curhead -> uh_next .ptr -> uh_seq :0 ; 2570 } 2571 2572// Remember where we are for ":earlier 1f" and ":later 1f". 2573if (curhead -> uh_save_nr != 0 ) { 2574if (undo ) { 2575curbuf -> b_u_save_nr_cur = curhead -> uh_save_nr - 1 ; 2576 }else { 2577curbuf -> b_u_save_nr_cur = curhead -> uh_save_nr ; 2578 } 2579 } 2580 2581// The timestamp can be the same for multiple changes, just use the one of 2582// the undone/redone change. 2583curbuf -> b_u_time_cur = curhead -> uh_time ; 2584 2585unblock_autocmds (); 2586#ifdef U_DEBUG 2587u_check (false); 2588#endif 2589} 2590 2591/// If we deleted or added lines, report the number of less/more lines. 2592/// Otherwise, report the number of changes (this may be incorrect 2593/// in some cases, but it's better than nothing). 2594/// 2595/// @param did_undo just did an undo 2596/// @param absolute used ":undo N" 2597static void u_undo_end (bool did_undo ,bool absolute ,bool quiet ) 2598{ 2599if ((fdo_flags & kOptFdoFlagUndo )&& KeyTyped ) { 2600foldOpenCursor (); 2601 } 2602 2603if (quiet 2604|| global_busy // no messages until global is finished 2605|| !messaging ()// 'lazyredraw' set, don't do messages now 2606|| shortmess (kShmUndo )) { 2607return ; 2608 } 2609 2610if (curbuf -> b_ml .ml_flags & ML_EMPTY ) { 2611u_newcount -- ; 2612 } 2613 2614u_oldcount -= u_newcount ; 2615char * msgstr ; 2616if (u_oldcount == -1 ) { 2617msgstr = N_ ("more line" ); 2618 }else if (u_oldcount < 0 ) { 2619msgstr = N_ ("more lines" ); 2620 }else if (u_oldcount == 1 ) { 2621msgstr = N_ ("line less" ); 2622 }else if (u_oldcount > 1 ) { 2623msgstr = N_ ("fewer lines" ); 2624 }else { 2625u_oldcount = u_newcount ; 2626if (u_newcount == 1 ) { 2627msgstr = N_ ("change" ); 2628 }else { 2629msgstr = N_ ("changes" ); 2630 } 2631 } 2632 2633u_header_T * uhp ; 2634if (curbuf -> b_u_curhead != NULL ) { 2635// For ":undo N" we prefer a "after #N" message. 2636if (absolute && curbuf -> b_u_curhead -> uh_next .ptr != NULL ) { 2637uhp = curbuf -> b_u_curhead -> uh_next .ptr ; 2638did_undo = false; 2639 }else if (did_undo ) { 2640uhp = curbuf -> b_u_curhead ; 2641 }else { 2642uhp = curbuf -> b_u_curhead -> uh_next .ptr ; 2643 } 2644 }else { 2645uhp = curbuf -> b_u_newhead ; 2646 } 2647 2648char msgbuf [80 ]; 2649if (uhp == NULL ) { 2650* msgbuf = NUL ; 2651 }else { 2652undo_fmt_time (msgbuf ,sizeof (msgbuf ),uhp -> uh_time ); 2653 } 2654 2655 { 2656FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 2657if (wp -> w_buffer == curbuf && wp -> w_p_cole > 0 ) { 2658redraw_later (wp ,UPD_NOT_VALID ); 2659 } 2660 } 2661 } 2662 2663if (Visual .active ) { 2664check_pos (curbuf ,& Visual .start ); 2665 } 2666 2667smsg_keep (0 ,_ ("%" PRId64 " %s; %s #%" PRId64 " %s" ), 2668u_oldcount < 0 ? (int64_t )- u_oldcount : (int64_t )u_oldcount , 2669_ (msgstr ), 2670did_undo ?_ ("before" ) :_ ("after" ), 2671uhp == NULL ?0 : (int64_t )uhp -> uh_seq , 2672msgbuf ); 2673} 2674 2675/// Put the timestamp of an undo header in "buf[buflen]" in a nice format. 2676void undo_fmt_time (char * buf ,size_t buflen ,time_t tt ) 2677{ 2678if (time (NULL )- tt >=100 ) { 2679struct tm curtime ; 2680os_localtime_r (& tt ,& curtime ); 2681size_t n ; 2682if (time (NULL )- tt < (60 * 60 * 12 )) { 2683// within 12 hours 2684n = strftime (buf ,buflen ,"%H:%M:%S" ,& curtime ); 2685 }else { 2686// longer ago 2687n = strftime (buf ,buflen ,"%Y/%m/%d %H:%M:%S" ,& curtime ); 2688 } 2689if (n == 0 ) { 2690buf [0 ]= NUL ; 2691 } 2692 }else { 2693int64_t seconds = time (NULL )- tt ; 2694vim_snprintf (buf ,buflen , 2695NGETTEXT ("%" PRId64 " second ago" , 2696"%" PRId64 " seconds ago" , (uint32_t )seconds ), 2697seconds ); 2698 } 2699} 2700 2701/// u_sync: stop adding to the current entry list 2702/// 2703/// @param force if true, also sync when no_u_sync is set. 2704void u_sync (bool force ) 2705{ 2706// Skip it when already synced or syncing is disabled. 2707if (curbuf -> b_u_synced || (!force && no_u_sync > 0 )) { 2708return ; 2709 } 2710 2711if (get_undolevel (curbuf )< 0 ) { 2712curbuf -> b_u_synced = true;// no entries, nothing to do 2713 }else { 2714u_getbot (curbuf );// compute ue_bot of previous u_save 2715curbuf -> b_u_curhead = NULL ; 2716 } 2717} 2718 2719/// ":undolist": List the leafs of the undo tree 2720void ex_undolist (exarg_T * eap ) 2721{ 2722int changes = 1 ; 2723 2724// 1: walk the tree to find all leafs, put the info in "ga". 2725// 2: sort the lines 2726// 3: display the list 2727int mark = ++ lastmark ; 2728int nomark = ++ lastmark ; 2729garray_T ga ; 2730ga_init (& ga , (int )sizeof (char * ),20 ); 2731 2732u_header_T * uhp = curbuf -> b_u_oldhead ; 2733while (uhp != NULL ) { 2734if (uhp -> uh_prev .ptr == NULL && uhp -> uh_walk != nomark 2735&& uhp -> uh_walk != mark ) { 2736vim_snprintf (IObuff ,IOSIZE ,"%6d %7d " ,uhp -> uh_seq ,changes ); 2737undo_fmt_time (IObuff + strlen (IObuff ),IOSIZE - strlen (IObuff ),uhp -> uh_time ); 2738if (uhp -> uh_save_nr > 0 ) { 2739while (strlen (IObuff )< 33 ) { 2740xstrlcat (IObuff ," " ,IOSIZE ); 2741 } 2742vim_snprintf_add (IObuff ,IOSIZE ," %3d" ,uhp -> uh_save_nr ); 2743 } 2744GA_APPEND (char * ,& ga ,xstrdup (IObuff )); 2745 } 2746 2747uhp -> uh_walk = mark ; 2748 2749// go down in the tree if we haven't been there 2750if (uhp -> uh_prev .ptr != NULL && uhp -> uh_prev .ptr -> uh_walk != nomark 2751&& uhp -> uh_prev .ptr -> uh_walk != mark ) { 2752uhp = uhp -> uh_prev .ptr ; 2753changes ++ ; 2754 }else if (uhp -> uh_alt_next .ptr != NULL 2755&& uhp -> uh_alt_next .ptr -> uh_walk != nomark 2756&& uhp -> uh_alt_next .ptr -> uh_walk != mark ) { 2757// go to alternate branch if we haven't been there 2758uhp = uhp -> uh_alt_next .ptr ; 2759 }else if (uhp -> uh_next .ptr != NULL && uhp -> uh_alt_prev .ptr == NULL 2760// go up in the tree if we haven't been there and we are at the 2761// start of alternate branches 2762&& uhp -> uh_next .ptr -> uh_walk != nomark 2763&& uhp -> uh_next .ptr -> uh_walk != mark ) { 2764uhp = uhp -> uh_next .ptr ; 2765changes -- ; 2766 }else { 2767// need to backtrack; mark this node as done 2768uhp -> uh_walk = nomark ; 2769if (uhp -> uh_alt_prev .ptr != NULL ) { 2770uhp = uhp -> uh_alt_prev .ptr ; 2771 }else { 2772uhp = uhp -> uh_next .ptr ; 2773changes -- ; 2774 } 2775 } 2776 } 2777 2778msg_ext_set_kind ("list_cmd" ); 2779if (GA_EMPTY (& ga )) { 2780msg (_ ("Nothing to undo" ),0 ); 2781 }else { 2782sort_strings (ga .ga_data ,ga .ga_len ); 2783 2784msg_start (); 2785msg_puts_hl (_ ("number changes when saved" ),HLF_T , false); 2786for (int i = 0 ;i < ga .ga_len && !got_int ;i ++ ) { 2787msg_putchar ('\n' ); 2788if (got_int ) { 2789break ; 2790 } 2791msg_puts (((const char ** )ga .ga_data )[i ]); 2792 } 2793msg_end (); 2794 2795ga_clear_strings (& ga ); 2796 } 2797} 2798 2799/// ":undojoin": continue adding to the last entry list 2800void ex_undojoin (exarg_T * eap ) 2801{ 2802if (curbuf -> b_u_newhead == NULL ) { 2803return ;// nothing changed before 2804 } 2805if (curbuf -> b_u_curhead != NULL ) { 2806emsg (_ ("E790: undojoin is not allowed after undo" )); 2807return ; 2808 } 2809if (!curbuf -> b_u_synced ) { 2810return ;// already unsynced 2811 } 2812if (get_undolevel (curbuf )< 0 ) { 2813return ;// no entries, nothing to do 2814 } 2815curbuf -> b_u_synced = false;// Append next change to last entry 2816} 2817 2818/// Called after writing or reloading the file and setting b_changed to false. 2819/// Now an undo means that the buffer is modified. 2820void u_unchanged (buf_T * buf ) 2821{ 2822u_unch_branch (buf -> b_u_oldhead ); 2823buf -> b_did_warn = false; 2824} 2825 2826/// After reloading a buffer which was saved for 'undoreload': Find the first 2827/// line that was changed and set the cursor there. 2828void u_find_first_changed (void ) 2829{ 2830u_header_T * uhp = curbuf -> b_u_newhead ; 2831 2832if (curbuf -> b_u_curhead != NULL || uhp == NULL ) { 2833return ;// undid something in an autocmd? 2834 } 2835// Check that the last undo block was for the whole file. 2836u_entry_T * uep = uhp -> uh_entry ; 2837if (uep -> ue_top != 0 || uep -> ue_bot != 0 ) { 2838return ; 2839 } 2840 2841linenr_T lnum ; 2842for (lnum = 1 ;lnum < curbuf -> b_ml .ml_line_count 2843&& lnum <=uep -> ue_size ;lnum ++ ) { 2844if (strcmp (ml_get_buf (curbuf ,lnum ),uep -> ue_array [lnum - 1 ])!= 0 ) { 2845clearpos (& (uhp -> uh_cursor )); 2846uhp -> uh_cursor .lnum = lnum ; 2847return ; 2848 } 2849 } 2850if (curbuf -> b_ml .ml_line_count != uep -> ue_size ) { 2851// lines added or deleted at the end, put the cursor there 2852clearpos (& (uhp -> uh_cursor )); 2853uhp -> uh_cursor .lnum = lnum ; 2854 } 2855} 2856 2857/// Increase the write count, store it in the last undo header, what would be 2858/// used for "u". 2859void u_update_save_nr (buf_T * buf ) 2860{ 2861buf -> b_u_save_nr_last ++ ; 2862buf -> b_u_save_nr_cur = buf -> b_u_save_nr_last ; 2863u_header_T * uhp = buf -> b_u_curhead ; 2864if (uhp != NULL ) { 2865uhp = uhp -> uh_next .ptr ; 2866 }else { 2867uhp = buf -> b_u_newhead ; 2868 } 2869if (uhp != NULL ) { 2870uhp -> uh_save_nr = buf -> b_u_save_nr_last ; 2871 } 2872} 2873 2874static void u_unch_branch (u_header_T * uhp ) 2875{ 2876for (u_header_T * uh = uhp ;uh != NULL ;uh = uh -> uh_prev .ptr ) { 2877uh -> uh_flags |=UH_CHANGED ; 2878if (uh -> uh_alt_next .ptr != NULL ) { 2879u_unch_branch (uh -> uh_alt_next .ptr );// recursive 2880 } 2881 } 2882} 2883 2884/// Get pointer to last added entry. 2885/// If it's not valid, give an error message and return NULL. 2886static u_entry_T * u_get_headentry (buf_T * buf ) 2887{ 2888if (buf -> b_u_newhead == NULL || buf -> b_u_newhead -> uh_entry == NULL ) { 2889iemsg (_ (e_undo_list_corrupt )); 2890return NULL ; 2891 } 2892return buf -> b_u_newhead -> uh_entry ; 2893} 2894 2895/// u_getbot(): compute the line number of the previous u_save 2896/// It is called only when b_u_synced is false. 2897static void u_getbot (buf_T * buf ) 2898{ 2899u_entry_T * uep = u_get_headentry (buf );// check for corrupt undo list 2900if (uep == NULL ) { 2901return ; 2902 } 2903 2904uep = buf -> b_u_newhead -> uh_getbot_entry ; 2905if (uep != NULL ) { 2906// the new ue_bot is computed from the number of lines that has been 2907// inserted (0 - deleted) since calling u_save. This is equal to the 2908// old line count subtracted from the current line count. 2909linenr_T extra = buf -> b_ml .ml_line_count - uep -> ue_lcount ; 2910uep -> ue_bot = uep -> ue_top + uep -> ue_size + 1 + extra ; 2911if (uep -> ue_bot < 1 || uep -> ue_bot > buf -> b_ml .ml_line_count ) { 2912iemsg (_ (e_undo_line_missing )); 2913uep -> ue_bot = uep -> ue_top + 1 ;// assume all lines deleted, will 2914// get all the old lines back 2915// without deleting the current 2916// ones 2917 } 2918 2919buf -> b_u_newhead -> uh_getbot_entry = NULL ; 2920 } 2921 2922buf -> b_u_synced = true; 2923} 2924 2925/// Free one header "uhp" and its entry list and adjust the pointers. 2926/// 2927/// @param uhpp if not NULL reset when freeing this header 2928static void u_freeheader (buf_T * buf ,u_header_T * uhp ,u_header_T ** uhpp ) 2929{ 2930// When there is an alternate redo list free that branch completely, 2931// because we can never go there. 2932if (uhp -> uh_alt_next .ptr != NULL ) { 2933u_freebranch (buf ,uhp -> uh_alt_next .ptr ,uhpp ); 2934 } 2935 2936if (uhp -> uh_alt_prev .ptr != NULL ) { 2937uhp -> uh_alt_prev .ptr -> uh_alt_next .ptr = NULL ; 2938 } 2939 2940// Update the links in the list to remove the header. 2941if (uhp -> uh_next .ptr == NULL ) { 2942buf -> b_u_oldhead = uhp -> uh_prev .ptr ; 2943 }else { 2944uhp -> uh_next .ptr -> uh_prev .ptr = uhp -> uh_prev .ptr ; 2945 } 2946 2947if (uhp -> uh_prev .ptr == NULL ) { 2948buf -> b_u_newhead = uhp -> uh_next .ptr ; 2949 }else { 2950for (u_header_T * uhap = uhp -> uh_prev .ptr ;uhap != NULL ; 2951uhap = uhap -> uh_alt_next .ptr ) { 2952uhap -> uh_next .ptr = uhp -> uh_next .ptr ; 2953 } 2954 } 2955 2956u_freeentries (buf ,uhp ,uhpp ); 2957} 2958 2959/// Free an alternate branch and any following alternate branches. 2960/// 2961/// @param uhpp if not NULL reset when freeing this header 2962static void u_freebranch (buf_T * buf ,u_header_T * uhp ,u_header_T ** uhpp ) 2963{ 2964// If this is the top branch we may need to use u_freeheader() to update 2965// all the pointers. 2966if (uhp == buf -> b_u_oldhead ) { 2967while (buf -> b_u_oldhead != NULL ) { 2968u_freeheader (buf ,buf -> b_u_oldhead ,uhpp ); 2969 } 2970return ; 2971 } 2972 2973if (uhp -> uh_alt_prev .ptr != NULL ) { 2974uhp -> uh_alt_prev .ptr -> uh_alt_next .ptr = NULL ; 2975 } 2976 2977u_header_T * next = uhp ; 2978while (next != NULL ) { 2979u_header_T * tofree = next ; 2980if (tofree -> uh_alt_next .ptr != NULL ) { 2981u_freebranch (buf ,tofree -> uh_alt_next .ptr ,uhpp );// recursive 2982 } 2983next = tofree -> uh_prev .ptr ; 2984u_freeentries (buf ,tofree ,uhpp ); 2985 } 2986} 2987 2988/// Forgets `uhp` and its branch (the changes above it). The alt branch displaced by `uhp` (see 2989/// u_savecommon()) takes its place as the redo branch; if there is none, the tree is at the leaf 2990/// state (end of the branch, nothing to redo). 2991static void u_forget_header (buf_T * buf ,u_header_T * uhp ) 2992{ 2993u_header_T * parent = uhp -> uh_next .ptr ; 2994u_header_T * alt = uhp -> uh_alt_next .ptr ; 2995if (alt != NULL ) { 2996alt -> uh_alt_prev .ptr = uhp -> uh_alt_prev .ptr ; 2997 } 2998if (uhp -> uh_alt_prev .ptr != NULL ) { 2999uhp -> uh_alt_prev .ptr -> uh_alt_next .ptr = alt ; 3000 } 3001if (parent != NULL ) { 3002parent -> uh_prev .ptr = alt ; 3003 } 3004if (buf -> b_u_oldhead == uhp ) { 3005buf -> b_u_oldhead = alt ; 3006 } 3007// Detached: u_freebranch() must not touch the alternate branch. 3008uhp -> uh_alt_next .ptr = NULL ; 3009uhp -> uh_alt_prev .ptr = NULL ; 3010// Positioned at the parent, with the alternate branch as redo. 3011buf -> b_u_newhead = parent ; 3012buf -> b_u_curhead = alt ; 3013buf -> b_u_seq_cur = parent != NULL ?parent -> uh_seq :0 ; 3014if (buf -> b_u_seq_last == uhp -> uh_seq ) { 3015buf -> b_u_seq_last -- ; 3016 } 3017buf -> b_u_synced = true; 3018u_freebranch (buf ,uhp ,NULL ); 3019} 3020 3021/// Free all the undo entries for one header and the header itself. 3022/// This means that "uhp" is invalid when returning. 3023/// 3024/// @param uhpp if not NULL reset when freeing this header 3025static void u_freeentries (buf_T * buf ,u_header_T * uhp ,u_header_T ** uhpp ) 3026{ 3027// Check for pointers to the header that become invalid now. 3028if (buf -> b_u_curhead == uhp ) { 3029buf -> b_u_curhead = NULL ; 3030 } 3031if (buf -> b_u_newhead == uhp ) { 3032buf -> b_u_newhead = NULL ;// freeing the newest entry 3033 } 3034if (uhpp != NULL && uhp == * uhpp ) { 3035* uhpp = NULL ; 3036 } 3037 3038u_entry_T * nuep ; 3039for (u_entry_T * uep = uhp -> uh_entry ;uep != NULL ;uep = nuep ) { 3040nuep = uep -> ue_next ; 3041u_freeentry (uep ,uep -> ue_size ); 3042 } 3043 3044kv_destroy (uhp -> uh_extmark ); 3045 3046#ifdef U_DEBUG 3047uhp -> uh_magic = 0 ; 3048#endif 3049xfree (uhp ); 3050buf -> b_u_numhead -- ; 3051} 3052 3053/// free entry 'uep' and 'n' lines in uep->ue_array[] 3054static void u_freeentry (u_entry_T * uep ,int n ) 3055{ 3056while (n > 0 ) { 3057xfree (uep -> ue_array [-- n ]); 3058 } 3059xfree (uep -> ue_array ); 3060#ifdef U_DEBUG 3061uep -> ue_magic = 0 ; 3062#endif 3063xfree (uep ); 3064} 3065 3066/// Prunes the newest undo entry if it has no changes (u_save() not followed by an actual edit). 3067/// Frees the undo state (and extmark undo) if no entries remain, restoring the redo branch it 3068/// displaced. 3069/// 3070/// Dropping the entry loses nothing: undoing it would "restore" identical lines. 3071void u_forget_unchanged (buf_T * buf ) 3072FUNC_ATTR_NONNULL_ALL 3073{ 3074u_header_T * uhp = buf -> b_u_newhead ; 3075u_entry_T * uep = uhp != NULL ?uhp -> uh_entry :NULL ; 3076if (uep == NULL || buf -> b_u_curhead != NULL || u_entry_resized (buf ,uep )) { 3077return ;// Keep the entry: not at leaf, or lines were added/deleted. 3078 } 3079for (linenr_T i = 0 ;i < uep -> ue_size ;i ++ ) { 3080if (strcmp (uep -> ue_array [i ],ml_get_buf (buf ,uep -> ue_top + 1 + i ))!= 0 ) { 3081return ;// Keep the entry: it has changes (lines differ vs the buffer). 3082 } 3083 } 3084 3085uhp -> uh_entry = uep -> ue_next ; 3086if (uhp -> uh_getbot_entry == uep ) { 3087uhp -> uh_getbot_entry = NULL ; 3088 } 3089u_freeentry (uep ,uep -> ue_size ); 3090if (uhp -> uh_entry == NULL ) { 3091u_forget_header (buf ,uhp );// Empty state (no changes). 3092 } 3093} 3094 3095/// invalidate the undo buffer; called when storage has already been released 3096void u_clearall (buf_T * buf ) 3097{ 3098buf -> b_u_newhead = buf -> b_u_oldhead = buf -> b_u_curhead = NULL ; 3099buf -> b_u_synced = true; 3100buf -> b_u_numhead = 0 ; 3101buf -> b_u_line_ptr = NULL ; 3102buf -> b_u_line_lnum = 0 ; 3103} 3104 3105/// Free all allocated memory blocks for the buffer 'buf'. 3106void u_blockfree (buf_T * buf ) 3107{ 3108while (buf -> b_u_oldhead != NULL ) { 3109#ifndef NDEBUG 3110u_header_T * previous_oldhead = buf -> b_u_oldhead ; 3111#endif 3112 3113u_freeheader (buf ,buf -> b_u_oldhead ,NULL ); 3114assert (buf -> b_u_oldhead != previous_oldhead ); 3115 } 3116xfree (buf -> b_u_line_ptr ); 3117} 3118 3119/// Free all allocated memory blocks for the buffer 'buf'. 3120/// and invalidate the undo buffer 3121void u_clearallandblockfree (buf_T * buf ) 3122{ 3123u_blockfree (buf ); 3124u_clearall (buf ); 3125} 3126 3127/// Save the line "lnum" for the "U" command. 3128static void u_saveline (buf_T * buf ,linenr_T lnum ) 3129{ 3130if (lnum == buf -> b_u_line_lnum ) {// line is already saved 3131return ; 3132 } 3133if (lnum < 1 || lnum > buf -> b_ml .ml_line_count ) {// should never happen 3134return ; 3135 } 3136u_clearline (buf ); 3137buf -> b_u_line_lnum = lnum ; 3138if (curwin -> w_buffer == buf && curwin -> w_cursor .lnum == lnum ) { 3139buf -> b_u_line_colnr = curwin -> w_cursor .col ; 3140 }else { 3141buf -> b_u_line_colnr = 0 ; 3142 } 3143buf -> b_u_line_ptr = u_save_line_buf (buf ,lnum ); 3144} 3145 3146/// clear the line saved for the "U" command 3147/// (this is used externally for crossing a line while in insert mode) 3148void u_clearline (buf_T * buf ) 3149{ 3150if (buf -> b_u_line_ptr == NULL ) { 3151return ; 3152 } 3153 3154XFREE_CLEAR (buf -> b_u_line_ptr ); 3155buf -> b_u_line_lnum = 0 ; 3156} 3157 3158/// Implementation of the "U" command. 3159/// Differentiation from vi: "U" can be undone with the next "U". 3160/// We also allow the cursor to be in another line. 3161/// Careful: may trigger autocommands that reload the buffer. 3162void u_undoline (void ) 3163{ 3164if (curbuf -> b_u_line_ptr == NULL 3165|| curbuf -> b_u_line_lnum > curbuf -> b_ml .ml_line_count ) { 3166beep_flush (); 3167return ; 3168 } 3169atom_did_global_op ();// multicursor: treat "U" as a global op. 3170 3171// first save the line for the 'u' command 3172if (u_savecommon (curbuf ,curbuf -> b_u_line_lnum - 1 , 3173curbuf -> b_u_line_lnum + 1 ,0 , false)== FAIL ) { 3174return ; 3175 } 3176 3177char * oldp = u_save_line (curbuf -> b_u_line_lnum ); 3178ml_replace (curbuf -> b_u_line_lnum ,curbuf -> b_u_line_ptr , true); 3179extmark_splice_cols (curbuf , (int )curbuf -> b_u_line_lnum - 1 ,0 , (colnr_T )strlen (oldp ), 3180 (colnr_T )strlen (curbuf -> b_u_line_ptr ),kExtmarkUndo ); 3181changed_bytes (curbuf -> b_u_line_lnum ,0 ); 3182xfree (curbuf -> b_u_line_ptr ); 3183curbuf -> b_u_line_ptr = oldp ; 3184 3185colnr_T t = curbuf -> b_u_line_colnr ; 3186if (curwin -> w_cursor .lnum == curbuf -> b_u_line_lnum ) { 3187curbuf -> b_u_line_colnr = curwin -> w_cursor .col ; 3188 } 3189curwin -> w_cursor .col = t ; 3190curwin -> w_cursor .lnum = curbuf -> b_u_line_lnum ; 3191check_cursor_col (curwin ); 3192} 3193 3194/// Allocate memory and copy curbuf line into it. 3195/// 3196/// @param lnum the line to copy 3197static char * u_save_line (linenr_T lnum ) 3198{ 3199return u_save_line_buf (curbuf ,lnum ); 3200} 3201 3202/// Allocate memory and copy line into it 3203/// 3204/// @param lnum line to copy 3205/// @param buf buffer to copy from 3206static char * u_save_line_buf (buf_T * buf ,linenr_T lnum ) 3207{ 3208return xstrdup (ml_get_buf (buf ,lnum )); 3209} 3210 3211/// Check if the 'modified' flag is set, or 'ff' has changed (only need to 3212/// check the first character, because it can only be "dos", "unix" or "mac"). 3213/// "nofile" and "scratch" type buffers are considered to always be unchanged. 3214/// Prompt buffers ignore implicit modifications by default, but an explicit 3215/// ":set modified" still makes them count as changed. 3216/// 3217/// @param buf The buffer to check 3218/// 3219/// @return true if the buffer has changed 3220bool bufIsChanged (buf_T * buf ) 3221FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 3222{ 3223// In a "prompt" buffer we respect 'modified' if the user or a plugin explicitly set it. 3224return bt_prompt (buf ) 3225 ?buf -> b_modified_was_set 3226 : (!bt_dontwrite (buf )&& (buf -> b_changed || file_ff_differs (buf , true))); 3227} 3228 3229// Return true if any buffer has changes. Also buffers that are not written. 3230bool anyBufIsChanged (void ) 3231FUNC_ATTR_WARN_UNUSED_RESULT 3232{ 3233FOR_ALL_BUFFERS (buf ) { 3234if (bufIsChanged (buf )) { 3235return true; 3236 } 3237 } 3238return false; 3239} 3240 3241/// @see bufIsChanged 3242/// @return true if the current buffer has changed 3243bool curbufIsChanged (void ) 3244FUNC_ATTR_WARN_UNUSED_RESULT 3245{ 3246return bufIsChanged (curbuf ); 3247} 3248 3249/// Append the list of undo blocks to a newly allocated list 3250/// 3251/// For use in undotree(). Recursive. 3252/// 3253/// @param[in] first_uhp Undo blocks list to start with. 3254/// 3255/// @return [allocated] List with a representation of undo blocks. 3256static list_T * u_eval_tree (buf_T * const buf ,const u_header_T * const first_uhp ) 3257FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_RET 3258{ 3259list_T * const list = tv_list_alloc (kListLenMayKnow ); 3260 3261for (const u_header_T * uhp = first_uhp ;uhp != NULL ;uhp = uhp -> uh_prev .ptr ) { 3262dict_T * const dict = tv_dict_alloc (); 3263tv_dict_add_nr (dict ,S_LEN ("seq" ), (varnumber_T )uhp -> uh_seq ); 3264tv_dict_add_nr (dict ,S_LEN ("time" ), (varnumber_T )uhp -> uh_time ); 3265if (uhp == buf -> b_u_newhead ) { 3266tv_dict_add_nr (dict ,S_LEN ("newhead" ),1 ); 3267 } 3268if (uhp == buf -> b_u_curhead ) { 3269tv_dict_add_nr (dict ,S_LEN ("curhead" ),1 ); 3270 } 3271if (uhp -> uh_save_nr > 0 ) { 3272tv_dict_add_nr (dict ,S_LEN ("save" ), (varnumber_T )uhp -> uh_save_nr ); 3273 } 3274 3275if (uhp -> uh_alt_next .ptr != NULL ) { 3276// Recursive call to add alternate undo tree. 3277tv_dict_add_list (dict ,S_LEN ("alt" ),u_eval_tree (buf ,uhp -> uh_alt_next .ptr )); 3278 } 3279 3280tv_list_append_dict (list ,dict ); 3281 } 3282 3283return list ; 3284} 3285 3286/// "undofile(name)" function 3287void f_undofile (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3288{ 3289rettv -> v_type = VAR_STRING ; 3290const char * const fname = tv_get_string (& argvars [0 ]); 3291 3292if (* fname == NUL ) { 3293// If there is no file name there will be no undo file. 3294rettv -> vval .v_string = NULL ; 3295 }else { 3296char * ffname = FullName_save (fname , true); 3297 3298if (ffname != NULL ) { 3299rettv -> vval .v_string = u_get_undo_file_name (ffname , false); 3300 } 3301xfree (ffname ); 3302 } 3303} 3304 3305/// "undotree(expr)" function 3306void f_undotree (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3307{ 3308tv_dict_alloc_ret (rettv ); 3309 3310typval_T * const tv = & argvars [0 ]; 3311buf_T * const buf = tv -> v_type == VAR_UNKNOWN ?curbuf :get_buf_arg (tv ); 3312if (buf == NULL ) { 3313return ; 3314 } 3315 3316dict_T * dict = rettv -> vval .v_dict ; 3317 3318tv_dict_add_nr (dict ,S_LEN ("synced" ), (varnumber_T )buf -> b_u_synced ); 3319tv_dict_add_nr (dict ,S_LEN ("seq_last" ), (varnumber_T )buf -> b_u_seq_last ); 3320tv_dict_add_nr (dict ,S_LEN ("save_last" ), (varnumber_T )buf -> b_u_save_nr_last ); 3321tv_dict_add_nr (dict ,S_LEN ("seq_cur" ), (varnumber_T )buf -> b_u_seq_cur ); 3322tv_dict_add_nr (dict ,S_LEN ("time_cur" ), (varnumber_T )buf -> b_u_time_cur ); 3323tv_dict_add_nr (dict ,S_LEN ("save_cur" ), (varnumber_T )buf -> b_u_save_nr_cur ); 3324 3325tv_dict_add_list (dict ,S_LEN ("entries" ),u_eval_tree (buf ,buf -> b_u_oldhead )); 3326} 3327 3328/// Drops named mark `idx` from the pending undo snapshot (if the user moved that mark after the 3329/// change was recorded, undo must not put it back). 3330/// 3331/// The mark is then left to mark_adjust(), so undo shifts it with its text, like other marks not 3332/// touched by the change. 3333/// 3334/// TODO(justinmk): could drop this and use a more "architectural" approach: compare 3335/// `fmark_T.timestamp` vs `uh_time` and skip the restore if the mark is newer. But that requires 3336/// changing the timestamps to nanosecond precision. 3337void u_update_named_mark (buf_T * buf ,int idx ) 3338{ 3339u_header_T * uhp = buf -> b_u_curhead != NULL ?buf -> b_u_curhead :buf -> b_u_newhead ; 3340if (uhp != NULL ) { 3341uhp -> uh_namedm [idx ].mark .lnum = 0 ; 3342 } 3343} 3344 3345// Given the buffer, Return the undo header. If none is set, set one first. 3346// NULL will be returned if e.g undolevels = -1 (undo disabled) 3347u_header_T * u_force_get_undo_header (buf_T * buf ) 3348{ 3349u_header_T * uhp = NULL ; 3350if (buf -> b_u_curhead != NULL ) { 3351uhp = buf -> b_u_curhead ; 3352 }else if (buf -> b_u_newhead ) { 3353uhp = buf -> b_u_newhead ; 3354 } 3355// Create the first undo header for the buffer 3356if (!uhp ) { 3357// Args are tricky: this means replace empty range by empty range.. 3358u_savecommon (buf ,0 ,1 ,1 , true); 3359 3360uhp = buf -> b_u_curhead ; 3361if (!uhp ) { 3362uhp = buf -> b_u_newhead ; 3363if (get_undolevel (buf )> 0 && !uhp ) { 3364abort (); 3365 } 3366 } 3367 } 3368return uhp ; 3369} 3370 3371/// Checkpoints the undo state of `buf` and detaches its undotree: subsequent edits build 3372/// a disposable tree. Then u_rollback() can revert them without a trace ("undo-invisible" 3373/// speculative edits, e.g. 'inccommand' preview). Sets 'undolevels' so every edit stays undoable. 3374void u_checkpoint (UndoCheckpoint * uc ,buf_T * buf ) 3375FUNC_ATTR_NONNULL_ALL 3376{ 3377uc -> uc_synced = buf -> b_u_synced ; 3378uc -> uc_oldhead = buf -> b_u_oldhead ; 3379uc -> uc_newhead = buf -> b_u_newhead ; 3380uc -> uc_curhead = buf -> b_u_curhead ; 3381uc -> uc_numhead = buf -> b_u_numhead ; 3382uc -> uc_seq_last = buf -> b_u_seq_last ; 3383uc -> uc_save_nr_last = buf -> b_u_save_nr_last ; 3384uc -> uc_seq_cur = buf -> b_u_seq_cur ; 3385uc -> uc_time_cur = buf -> b_u_time_cur ; 3386uc -> uc_save_nr_cur = buf -> b_u_save_nr_cur ; 3387uc -> uc_line_ptr = buf -> b_u_line_ptr ; 3388uc -> uc_line_lnum = buf -> b_u_line_lnum ; 3389uc -> uc_line_colnr = buf -> b_u_line_colnr ; 3390uc -> uc_undolevels = buf -> b_p_ul ; 3391uc -> uc_changedtick = buf_get_changedtick (buf ); 3392 3393u_clearall (buf ); 3394buf -> b_p_ul = INT_MAX ;// Make sure we can undo all changes 3395} 3396 3397/// Reverts `buf` from a checkpoint: drops all edits made since u_checkpoint(), and reattaches the 3398/// checkpointed undotree. Also restores b:changedtick and 'undolevels'. 3399void u_rollback (UndoCheckpoint * uc ,buf_T * buf ) 3400FUNC_ATTR_NONNULL_ALL 3401{ 3402if (buf -> b_u_seq_cur != uc -> uc_seq_cur ) { 3403int count = 0 ; 3404 3405// Calculate how many undo steps are necessary to restore earlier state. 3406for (u_header_T * uhp = buf -> b_u_curhead ?buf -> b_u_curhead :buf -> b_u_newhead ; 3407uhp != NULL ; 3408uhp = uhp -> uh_next .ptr ,++ count ) {} 3409 3410CtxSwitch cs = {0 }; 3411ctx_switch (& cs ,NULL ,NULL ,buf ,0 ); 3412// Ensure all the entries will be undone 3413if (curbuf -> b_u_synced == false) { 3414u_sync (true); 3415 } 3416// Undo invisibly. This also moves the cursor! 3417if (!u_undo_and_forget (count , false)) { 3418abort (); 3419 } 3420ctx_restore (& cs ); 3421 } 3422 3423u_blockfree (buf ); 3424buf -> b_u_oldhead = uc -> uc_oldhead ; 3425buf -> b_u_newhead = uc -> uc_newhead ; 3426buf -> b_u_curhead = uc -> uc_curhead ; 3427buf -> b_u_numhead = uc -> uc_numhead ; 3428buf -> b_u_seq_last = uc -> uc_seq_last ; 3429buf -> b_u_save_nr_last = uc -> uc_save_nr_last ; 3430buf -> b_u_seq_cur = uc -> uc_seq_cur ; 3431buf -> b_u_time_cur = uc -> uc_time_cur ; 3432buf -> b_u_save_nr_cur = uc -> uc_save_nr_cur ; 3433buf -> b_u_line_ptr = uc -> uc_line_ptr ; 3434buf -> b_u_line_lnum = uc -> uc_line_lnum ; 3435buf -> b_u_line_colnr = uc -> uc_line_colnr ; 3436if (buf -> b_u_curhead == NULL ) { 3437buf -> b_u_synced = uc -> uc_synced ; 3438 } 3439 3440if (uc -> uc_changedtick != buf_get_changedtick (buf )) { 3441buf_set_changedtick (buf ,uc -> uc_changedtick ); 3442 } 3443buf -> b_p_ul = uc -> uc_undolevels ;// Restore 'undolevels' 3444}