robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1/// @file diff.c 2/// 3/// Code for diff'ing two, three or four buffers. 4/// 5/// There are three ways to diff: 6/// - Shell out to an external diff program, using files. 7/// - Use the compiled-in xdiff library. 8/// - Let 'diffexpr' do the work, using files. 9 10#include <assert.h> 11#include <ctype.h> 12#include <inttypes.h> 13#include <stdbool.h> 14#include <stdio.h> 15#include <stdlib.h> 16#include <string.h> 17 18#include "auto/config.h" 19#include "nvim/api/private/helpers.h" 20#include "nvim/ascii_defs.h" 21#include "nvim/autocmd.h" 22#include "nvim/autocmd_defs.h" 23#include "nvim/buffer.h" 24#include "nvim/bufwrite.h" 25#include "nvim/change.h" 26#include "nvim/charset.h" 27#include "nvim/context.h" 28#include "nvim/cursor.h" 29#include "nvim/decoration.h" 30#include "nvim/diff.h" 31#include "nvim/drawscreen.h" 32#include "nvim/errors.h" 33#include "nvim/eval/typval.h" 34#include "nvim/eval/vars.h" 35#include "nvim/ex_cmds.h" 36#include "nvim/ex_cmds_defs.h" 37#include "nvim/ex_docmd.h" 38#include "nvim/extmark.h" 39#include "nvim/extmark_defs.h" 40#include "nvim/fileio.h" 41#include "nvim/fold.h" 42#include "nvim/garray.h" 43#include "nvim/garray_defs.h" 44#include "nvim/gettext_defs.h" 45#include "nvim/globals.h" 46#include "nvim/linematch.h" 47#include "nvim/mark.h" 48#include "nvim/mbyte.h" 49#include "nvim/mbyte_defs.h" 50#include "nvim/memline.h" 51#include "nvim/memline_defs.h" 52#include "nvim/memory.h" 53#include "nvim/message.h" 54#include "nvim/move.h" 55#include "nvim/normal.h" 56#include "nvim/option.h" 57#include "nvim/option_defs.h" 58#include "nvim/option_vars.h" 59#include "nvim/optionstr.h" 60#include "nvim/os/fs.h" 61#include "nvim/os/fs_defs.h" 62#include "nvim/os/os.h" 63#include "nvim/os/os_defs.h" 64#include "nvim/os/shell.h" 65#include "nvim/path.h" 66#include "nvim/pos_defs.h" 67#include "nvim/strings.h" 68#include "nvim/types_defs.h" 69#include "nvim/ui.h" 70#include "nvim/undo.h" 71#include "nvim/vim_defs.h" 72#include "nvim/window.h" 73#include "xdiff/xdiff.h" 74 75// KeyDict_dip + KeyDict_dip_get_field, generated from the 'diffopt' schema (reusing hashy.lua). 76#include "options_keysets.generated.h" 77 78static bool diff_busy = false;// using diff structs, don't change them 79static bool diff_need_update = false;// ex_diffupdate needs to be called 80 81// Flags obtained from the 'diffopt' option 82#define DIFF_FILLER 0x001 // display filler lines 83#define DIFF_IBLANK 0x002 // ignore empty lines 84#define DIFF_ICASE 0x004 // ignore case 85#define DIFF_IWHITE 0x008 // ignore change in white space 86#define DIFF_IWHITEALL 0x010 // ignore all white space changes 87#define DIFF_IWHITEEOL 0x020 // ignore change in white space at EOL 88#define DIFF_HORIZONTAL 0x040 // horizontal splits 89#define DIFF_VERTICAL 0x080 // vertical splits 90#define DIFF_HIDDEN_OFF 0x100 // diffoff when hidden 91#define DIFF_INTERNAL 0x200 // use internal xdiff algorithm 92#define DIFF_CLOSE_OFF 0x400 // diffoff when closing window 93#define DIFF_FOLLOWWRAP 0x800 // follow the wrap option 94#define DIFF_LINEMATCH 0x1000 // match most similar lines within diff 95#define DIFF_INLINE_NONE 0x2000 // no inline highlight 96#define DIFF_INLINE_SIMPLE 0x4000 // inline highlight with simple algorithm 97#define DIFF_INLINE_CHAR 0x8000 // inline highlight with character diff 98#define DIFF_INLINE_WORD 0x10000 // inline highlight with word diff 99#define DIFF_ANCHOR 0x20000 // use 'diffanchors' to anchor the diff 100#define ALL_WHITE_DIFF (DIFF_IWHITE | DIFF_IWHITEALL | DIFF_IWHITEEOL) 101#define ALL_INLINE (DIFF_INLINE_NONE | DIFF_INLINE_SIMPLE | DIFF_INLINE_CHAR | DIFF_INLINE_WORD) 102#define ALL_INLINE_DIFF (DIFF_INLINE_CHAR | DIFF_INLINE_WORD) 103static int diff_flags = DIFF_INTERNAL |DIFF_FILLER |DIFF_CLOSE_OFF 104 |DIFF_LINEMATCH |DIFF_INLINE_CHAR ; 105 106static int diff_algorithm = XDF_INDENT_HEURISTIC ; 107static int diff_word_gap = 5 ;// gap threshold for inline:word 108static int linematch_lines = 40 ; 109 110#define LBUFLEN 50 // length of line in diff file 111 112// Max file size xdiff is equipped to deal with. The value (1GB - 1MB) comes 113// from Git's implementation. 114#define MAX_XDIFF_SIZE (1024L * 1024 * 1023) 115 116// kTrue when "diff -a" works, kFalse when it doesn't work, 117// kNone when not checked yet 118static TriState diff_a_works = kNone ; 119 120enum {MAX_DIFF_ANCHORS = 20 , }; 121 122// used for diff input 123typedef struct { 124char * din_fname ;// used for external diff 125mmfile_t din_mmfile ;// used for internal diff 126}diffin_T ; 127 128// used for diff result 129typedef struct { 130char * dout_fname ;// used for external diff 131garray_T dout_ga ;// used for internal diff 132}diffout_T ; 133 134// used for recording hunks from xdiff 135typedef struct { 136linenr_T lnum_orig ; 137int count_orig ; 138linenr_T lnum_new ; 139int count_new ; 140}diffhunk_T ; 141 142// two diff inputs and one result 143typedef struct { 144diffin_T dio_orig ;// original file input 145diffin_T dio_new ;// new file input 146diffout_T dio_diff ;// diff result 147int dio_internal ;// using internal diff 148}diffio_T ; 149 150typedef enum { 151DIFF_ED , 152DIFF_UNIFIED , 153DIFF_NONE , 154}diffstyle_T ; 155 156#include "diff.c.generated.h" 157 158#define FOR_ALL_DIFFBLOCKS_IN_TAB (tp ,dp ) \ 159 for ((dp) = (tp)->tp_first_diff; (dp) != NULL; (dp) = (dp)->df_next) 160 161// Cursor into the diff block list for diff_infold() and 162// diff_check_with_linestatus(): both scan blocks in ascending df_lnum order, 163// usually with an increasing "lnum" during redraw. Remembering the last block 164// at or before "lnum" lets the next call resume there instead of from the head. 165// Cleared when a block is freed, allocated or line-shifted (see below). 166static diff_T * diff_finger_dp = NULL ; 167static tabpage_T * diff_finger_tp = NULL ; 168static int diff_finger_idx = -1 ; 169static linenr_T diff_finger_lnum = 0 ; 170 171static void clear_diffblock (diff_T * dp ) 172{ 173if (dp == diff_finger_dp ) { 174diff_finger_dp = NULL ;// don't leave a dangling finger 175 } 176ga_clear (& dp -> df_changes ); 177xfree (dp ); 178} 179 180/// Return the diff block to start a forward scan for line "lnum" in tab "tp", 181/// buffer index "idx". Resumes from the finger when it is still valid and 182/// "lnum" did not move backwards, else starts at the first block. 183static diff_T * diff_scan_start (tabpage_T * tp ,int idx ,linenr_T lnum ) 184{ 185if (diff_finger_dp != NULL 186&& diff_finger_tp == tp 187&& diff_finger_idx == idx 188&& lnum >=diff_finger_lnum ) { 189return diff_finger_dp ; 190 } 191return tp -> tp_first_diff ; 192} 193 194/// Remember "dp" as the finger for the next scan: the last block with 195/// df_lnum[idx] <= "lnum" seen by the scan, or NULL when there is none. 196static void diff_scan_remember (tabpage_T * tp ,int idx ,linenr_T lnum ,diff_T * dp ) 197{ 198diff_finger_tp = tp ; 199diff_finger_idx = idx ; 200diff_finger_lnum = lnum ; 201diff_finger_dp = dp != NULL ?dp :tp -> tp_first_diff ; 202} 203 204/// Called when deleting or unloading a buffer: No longer make a diff with it. 205/// 206/// @param buf 207void diff_buf_delete (buf_T * buf ) 208{ 209FOR_ALL_TABS (tp ) { 210int i = diff_buf_idx (buf ,tp ); 211 212if (i != DB_COUNT ) { 213tp -> tp_diffbuf [i ]= NULL ; 214tp -> tp_diff_invalid = true; 215 216if (tp == curtab ) { 217// don't redraw right away, more might change or buffer state 218// is invalid right now 219need_diff_redraw = true; 220redraw_later (curwin ,UPD_VALID ); 221 } 222 } 223 } 224} 225 226/// Check if the current buffer should be added to or removed from the list of 227/// diff buffers. 228/// 229/// @param win 230void diff_buf_adjust (win_T * win ) 231{ 232if (!win -> w_p_diff ) { 233// When there is no window showing a diff for this buffer, remove 234// it from the diffs. 235bool found_win = false; 236FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 237if ((wp -> w_buffer == win -> w_buffer )&& wp -> w_p_diff ) { 238found_win = true; 239 } 240 } 241 242if (!found_win ) { 243int i = diff_buf_idx (win -> w_buffer ,curtab ); 244if (i != DB_COUNT ) { 245curtab -> tp_diffbuf [i ]= NULL ; 246curtab -> tp_diff_invalid = true; 247diff_redraw (true); 248 } 249 } 250 }else { 251diff_buf_add (win -> w_buffer ); 252 } 253} 254 255/// Add a buffer to make diffs for. 256/// 257/// Call this when a new buffer is being edited in the current window where 258/// 'diff' is set. 259/// Marks the current buffer as being part of the diff and requiring updating. 260/// This must be done before any autocmd, because a command may use info 261/// about the screen contents. 262/// 263/// @param buf The buffer to add. 264void diff_buf_add (buf_T * buf ) 265{ 266if (diff_buf_idx (buf ,curtab )!= DB_COUNT ) { 267// It's already there. 268return ; 269 } 270 271for (int i = 0 ;i < DB_COUNT ;i ++ ) { 272if (curtab -> tp_diffbuf [i ]== NULL ) { 273curtab -> tp_diffbuf [i ]= buf ; 274curtab -> tp_diff_invalid = true; 275diff_redraw (true); 276return ; 277 } 278 } 279 280semsg (_ ("E96: Cannot diff more than %d buffers" ),DB_COUNT ); 281} 282 283/// Remove all buffers to make diffs for. 284static void diff_buf_clear (void ) 285{ 286for (int i = 0 ;i < DB_COUNT ;i ++ ) { 287if (curtab -> tp_diffbuf [i ]!= NULL ) { 288curtab -> tp_diffbuf [i ]= NULL ; 289curtab -> tp_diff_invalid = true; 290diff_redraw (true); 291 } 292 } 293} 294 295/// Find buffer "buf" in the list of diff buffers for tab page "tp". 296/// 297/// @param buf 298/// @param tp 299/// 300/// @return its index or DB_COUNT if not found. 301static int diff_buf_idx (buf_T * buf ,tabpage_T * tp ) 302{ 303int idx ; 304for (idx = 0 ;idx < DB_COUNT ;idx ++ ) { 305if (tp -> tp_diffbuf [idx ]== buf ) { 306break ; 307 } 308 } 309return idx ; 310} 311 312/// Mark the diff info involving buffer "buf" as invalid, it will be updated 313/// when info is requested. 314/// 315/// @param buf 316void diff_invalidate (buf_T * buf ) 317{ 318FOR_ALL_TABS (tp ) { 319int i = diff_buf_idx (buf ,tp ); 320if (i != DB_COUNT ) { 321tp -> tp_diff_invalid = true; 322if (tp == curtab ) { 323diff_redraw (true); 324 } 325 } 326 } 327} 328 329/// Called by mark_adjust(): update line numbers in "buf". 330/// 331/// @param line1 332/// @param line2 333/// @param amount 334/// @param amount_after 335void diff_mark_adjust (buf_T * buf ,linenr_T line1 ,linenr_T line2 ,linenr_T amount , 336linenr_T amount_after ) 337{ 338// Handle all tab pages that use "buf" in a diff. 339FOR_ALL_TABS (tp ) { 340int idx = diff_buf_idx (buf ,tp ); 341if (idx != DB_COUNT ) { 342diff_mark_adjust_tp (tp ,idx ,line1 ,line2 ,amount ,amount_after ); 343 } 344 } 345} 346 347/// Update line numbers in tab page "tp" for the buffer with index "idx". 348/// 349/// This attempts to update the changes as much as possible: 350/// When inserting/deleting lines outside of existing change blocks, create a 351/// new change block and update the line numbers in following blocks. 352/// When inserting/deleting lines in existing change blocks, update them. 353/// 354/// @param tp 355/// @param idx 356/// @param line1 357/// @param line2 358/// @param amount 359/// @amount_after 360static void diff_mark_adjust_tp (tabpage_T * tp ,int idx ,linenr_T line1 ,linenr_T line2 , 361linenr_T amount ,linenr_T amount_after ) 362{ 363diff_finger_dp = NULL ;// may shift df_lnum, invalidate the finger 364 365if (diff_internal ()) { 366// Will update diffs before redrawing. Set _invalid to update the 367// diffs themselves, set _update to also update folds properly just 368// before redrawing. 369// Do update marks here, it is needed for :%diffput. 370tp -> tp_diff_invalid = true; 371tp -> tp_diff_update = true; 372 } 373 374linenr_T inserted ; 375linenr_T deleted ; 376if (line2 == MAXLNUM ) { 377// mark_adjust(99, MAXLNUM, 9, 0): insert lines 378inserted = amount ; 379deleted = 0 ; 380 }else if (amount_after > 0 ) { 381// mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines 382inserted = amount_after ; 383deleted = 0 ; 384 }else { 385// mark_adjust(98, 99, MAXLNUM, -2): delete lines 386inserted = 0 ; 387deleted = - amount_after ; 388 } 389 390diff_T * dprev = NULL ; 391diff_T * dp = tp -> tp_first_diff ; 392 393linenr_T lnum_deleted = line1 ;// lnum of remaining deletion 394while (true) { 395// If the change is after the previous diff block and before the next 396// diff block, thus not touching an existing change, create a new diff 397// block. Don't do this when ex_diffgetput() is busy. 398if (((dp == NULL ) 399|| (dp -> df_lnum [idx ]- 1 > line2 ) 400|| ((line2 == MAXLNUM )&& (dp -> df_lnum [idx ]> line1 ))) 401&& ((dprev == NULL ) 402|| (dprev -> df_lnum [idx ]+ dprev -> df_count [idx ]< line1 )) 403&& !diff_busy ) { 404diff_T * dnext = diff_alloc_new (tp ,dprev ,dp ); 405 406dnext -> df_lnum [idx ]= line1 ; 407dnext -> df_count [idx ]= inserted ; 408for (int i = 0 ;i < DB_COUNT ;i ++ ) { 409if ((tp -> tp_diffbuf [i ]!= NULL )&& (i != idx )) { 410if (dprev == NULL ) { 411dnext -> df_lnum [i ]= line1 ; 412 }else { 413dnext -> df_lnum [i ]= line1 414+ (dprev -> df_lnum [i ]+ dprev -> df_count [i ]) 415- (dprev -> df_lnum [idx ]+ dprev -> df_count [idx ]); 416 } 417dnext -> df_count [i ]= deleted ; 418 } 419 } 420 } 421 422// if at end of the list, quit 423if (dp == NULL ) { 424break ; 425 } 426 427// Check for these situations: 428// 1 2 3 429// 1 2 3 430// line1 2 3 4 5 431// 2 3 4 5 432// 2 3 4 5 433// line2 2 3 4 5 434// 3 5 6 435// 3 5 6 436 437// compute last line of this change 438linenr_T last = dp -> df_lnum [idx ]+ dp -> df_count [idx ]- 1 ; 439 440// 1. change completely above line1: nothing to do 441if (last >=line1 - 1 ) { 442if (diff_busy ) { 443// Currently in the middle of updating diff blocks. All we want 444// is to adjust the line numbers and nothing else. 445if (dp -> df_lnum [idx ]> line2 ) { 446dp -> df_lnum [idx ]+= amount_after ; 447 } 448 449// Advance to next entry. 450dprev = dp ; 451dp = dp -> df_next ; 452continue ; 453 } 454 455// 6. change below line2: only adjust for amount_after; also when 456// "deleted" became zero when deleted all lines between two diffs. 457if (dp -> df_lnum [idx ]- (deleted + inserted != 0 )> line2 ) { 458if (amount_after == 0 ) { 459// nothing left to change 460break ; 461 } 462dp -> df_lnum [idx ]+= amount_after ; 463 }else { 464bool check_unchanged = false; 465 466// 2. 3. 4. 5.: inserted/deleted lines touching this diff. 467if (deleted > 0 ) { 468linenr_T n ; 469linenr_T off = 0 ; 470if (dp -> df_lnum [idx ] >=line1 ) { 471if (last <=line2 ) { 472// 4. delete all lines of diff 473if ((dp -> df_next != NULL ) 474&& (dp -> df_next -> df_lnum [idx ]- 1 <=line2 )) { 475// delete continues in next diff, only do 476// lines until that one 477n = dp -> df_next -> df_lnum [idx ]- lnum_deleted ; 478deleted -= n ; 479n -= dp -> df_count [idx ]; 480lnum_deleted = dp -> df_next -> df_lnum [idx ]; 481 }else { 482n = deleted - dp -> df_count [idx ]; 483 } 484dp -> df_count [idx ]= 0 ; 485 }else { 486// 5. delete lines at or just before top of diff 487off = dp -> df_lnum [idx ]- lnum_deleted ; 488n = off ; 489dp -> df_count [idx ]-= line2 - dp -> df_lnum [idx ]+ 1 ; 490check_unchanged = true; 491 } 492dp -> df_lnum [idx ]= line1 ; 493 }else { 494if (last < line2 ) { 495// 2. delete at end of diff 496dp -> df_count [idx ]-= last - lnum_deleted + 1 ; 497 498if ((dp -> df_next != NULL ) 499&& (dp -> df_next -> df_lnum [idx ]- 1 <=line2 )) { 500// delete continues in next diff, only do 501// lines until that one 502n = dp -> df_next -> df_lnum [idx ]- 1 - last ; 503deleted -= dp -> df_next -> df_lnum [idx ]- lnum_deleted ; 504lnum_deleted = dp -> df_next -> df_lnum [idx ]; 505 }else { 506n = line2 - last ; 507 } 508check_unchanged = true; 509 }else { 510// 3. delete lines inside the diff 511n = 0 ; 512dp -> df_count [idx ]-= deleted ; 513 } 514 } 515 516for (int i = 0 ;i < DB_COUNT ;i ++ ) { 517if ((tp -> tp_diffbuf [i ]!= NULL )&& (i != idx )) { 518if (dp -> df_lnum [i ]> off ) { 519dp -> df_lnum [i ]-= off ; 520 }else { 521dp -> df_lnum [i ]= 1 ; 522 } 523dp -> df_count [i ]+= n ; 524 } 525 } 526 }else { 527if (dp -> df_lnum [idx ] <=line1 ) { 528// inserted lines somewhere in this diff 529dp -> df_count [idx ]+= inserted ; 530check_unchanged = true; 531 }else { 532// inserted lines somewhere above this diff 533dp -> df_lnum [idx ]+= inserted ; 534 } 535 } 536 537if (check_unchanged ) { 538// Check if inserted lines are equal, may reduce the size of the 539// diff. 540// 541// TODO(unknown): also check for equal lines in the middle and perhaps split 542// the block. 543diff_check_unchanged (tp ,dp ); 544 } 545 } 546 } 547 548// check if this block touches the previous one, may merge them. 549if ((dprev != NULL )&& !dp -> is_linematched && !diff_busy 550&& (dprev -> df_lnum [idx ]+ dprev -> df_count [idx ]== dp -> df_lnum [idx ])) { 551for (int i = 0 ;i < DB_COUNT ;i ++ ) { 552if (tp -> tp_diffbuf [i ]!= NULL ) { 553dprev -> df_count [i ]+= dp -> df_count [i ]; 554 } 555 } 556dp = diff_free (tp ,dprev ,dp ); 557 }else { 558// Advance to next entry. 559dprev = dp ; 560dp = dp -> df_next ; 561 } 562 } 563 564dprev = NULL ; 565dp = tp -> tp_first_diff ; 566 567while (dp != NULL ) { 568// All counts are zero, remove this entry. 569int i ; 570for (i = 0 ;i < DB_COUNT ;i ++ ) { 571if ((tp -> tp_diffbuf [i ]!= NULL )&& (dp -> df_count [i ]!= 0 )) { 572break ; 573 } 574 } 575 576if (i == DB_COUNT ) { 577dp = diff_free (tp ,dprev ,dp ); 578 }else { 579// Advance to next entry. 580dprev = dp ; 581dp = dp -> df_next ; 582 } 583 } 584 585if (tp == curtab ) { 586// Don't redraw right away, this updates the diffs, which can be slow. 587need_diff_redraw = true; 588 589// Need to recompute the scroll binding, may remove or add filler 590// lines (e.g., when adding lines above w_topline). But it's slow when 591// making many changes, postpone until redrawing. 592diff_need_scrollbind = true; 593 } 594} 595 596/// Allocate a new diff block and link it between "dprev" and "dp". 597/// 598/// @param tp 599/// @param dprev 600/// @param dp 601/// 602/// @return The new diff block. 603static diff_T * diff_alloc_new (tabpage_T * tp ,diff_T * dprev ,diff_T * dp ) 604{ 605diff_T * dnew = xcalloc (1 ,sizeof (* dnew )); 606diff_finger_dp = NULL ;// list changed, invalidate the finger 607 608dnew -> is_linematched = false; 609dnew -> df_next = dp ; 610if (dprev == NULL ) { 611tp -> tp_first_diff = dnew ; 612 }else { 613dprev -> df_next = dnew ; 614 } 615 616dnew -> has_changes = false; 617ga_init (& dnew -> df_changes ,sizeof (diffline_change_T ),20 ); 618return dnew ; 619} 620 621static diff_T * diff_free (tabpage_T * tp ,diff_T * dprev ,diff_T * dp ) 622{ 623diff_T * ret = dp -> df_next ; 624clear_diffblock (dp ); 625 626if (dprev == NULL ) { 627tp -> tp_first_diff = ret ; 628 }else { 629dprev -> df_next = ret ; 630 } 631 632return ret ; 633} 634 635/// Check if the diff block "dp" can be made smaller for lines at the start and 636/// end that are equal. Called after inserting lines. 637/// 638/// This may result in a change where all buffers have zero lines, the caller 639/// must take care of removing it. 640/// 641/// @param tp 642/// @param dp 643static void diff_check_unchanged (tabpage_T * tp ,diff_T * dp ) 644{ 645// Find the first buffers, use it as the original, compare the other 646// buffer lines against this one. 647int i_org ; 648for (i_org = 0 ;i_org < DB_COUNT ;i_org ++ ) { 649if (tp -> tp_diffbuf [i_org ]!= NULL ) { 650break ; 651 } 652 } 653 654// safety check 655if (i_org == DB_COUNT ) { 656return ; 657 } 658 659if (diff_check_sanity (tp ,dp )== FAIL ) { 660return ; 661 } 662 663// First check lines at the top, then at the bottom. 664linenr_T off_org = 0 ; 665linenr_T off_new = 0 ; 666int dir = FORWARD ; 667while (true) { 668// Repeat until a line is found which is different or the number of 669// lines has become zero. 670while (dp -> df_count [i_org ]> 0 ) { 671// Copy the line, the next ml_get() will invalidate it. 672if (dir == BACKWARD ) { 673off_org = dp -> df_count [i_org ]- 1 ; 674 } 675char * line_org = xstrdup (ml_get_buf (tp -> tp_diffbuf [i_org ],dp -> df_lnum [i_org ]+ off_org )); 676 677int i_new ; 678for (i_new = i_org + 1 ;i_new < DB_COUNT ;i_new ++ ) { 679if (tp -> tp_diffbuf [i_new ]== NULL ) { 680continue ; 681 } 682 683if (dir == BACKWARD ) { 684off_new = dp -> df_count [i_new ]- 1 ; 685 } 686 687// if other buffer doesn't have this line, it was inserted 688if ((off_new < 0 )|| (off_new >=dp -> df_count [i_new ])) { 689break ; 690 } 691 692if (diff_cmp (line_org ,ml_get_buf (tp -> tp_diffbuf [i_new ], 693dp -> df_lnum [i_new ]+ off_new ))!= 0 ) { 694break ; 695 } 696 } 697xfree (line_org ); 698 699// Stop when a line isn't equal in all diff buffers. 700if (i_new != DB_COUNT ) { 701break ; 702 } 703 704// Line matched in all buffers, remove it from the diff. 705for (i_new = i_org ;i_new < DB_COUNT ;i_new ++ ) { 706if (tp -> tp_diffbuf [i_new ]!= NULL ) { 707if (dir == FORWARD ) { 708dp -> df_lnum [i_new ]++ ; 709 } 710dp -> df_count [i_new ]-- ; 711 } 712 } 713 } 714 715if (dir == BACKWARD ) { 716break ; 717 } 718dir = BACKWARD ; 719 } 720} 721 722/// Check if a diff block doesn't contain invalid line numbers. 723/// This can happen when the diff program returns invalid results. 724/// 725/// @param tp 726/// @param dp 727/// 728/// @return OK if the diff block doesn't contain invalid line numbers. 729static int diff_check_sanity (tabpage_T * tp ,diff_T * dp ) 730{ 731for (int i = 0 ;i < DB_COUNT ;i ++ ) { 732if (tp -> tp_diffbuf [i ]!= NULL ) { 733if (dp -> df_lnum [i ]+ dp -> df_count [i ]- 1 734> tp -> tp_diffbuf [i ]-> b_ml .ml_line_count ) { 735return FAIL ; 736 } 737 } 738 } 739return OK ; 740} 741 742/// Mark all diff buffers in the current tab page for redraw. 743/// 744/// @param dofold Also recompute the folds 745void diff_redraw (bool dofold ) 746{ 747win_T * wp_other = NULL ; 748bool used_max_fill_other = false; 749bool used_max_fill_curwin = false; 750 751need_diff_redraw = false; 752FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 753// when closing windows or wiping buffers skip invalid window 754if (!wp -> w_p_diff || !buf_valid (wp -> w_buffer )) { 755continue ; 756 } 757 758redraw_later (wp ,UPD_SOME_VALID ); 759if (wp != curwin ) { 760wp_other = wp ; 761 } 762if (dofold && foldmethodIsDiff (wp )) { 763foldUpdateAll (wp ); 764 } 765 766// A change may have made filler lines invalid, need to take care of 767// that for other windows. 768int n = diff_check_fill (wp ,wp -> w_topline ); 769 770if (((wp != curwin )&& (wp -> w_topfill > 0 ))|| (n > 0 )) { 771if (wp -> w_topfill > n ) { 772wp -> w_topfill = MAX (n ,0 ); 773 }else if ((n > 0 )&& (n > wp -> w_topfill )) { 774wp -> w_topfill = n ; 775if (wp == curwin ) { 776used_max_fill_curwin = true; 777 }else if (wp_other != NULL ) { 778used_max_fill_other = true; 779 } 780 } 781check_topfill (wp , false); 782 } 783 } 784 785if (wp_other != NULL && curwin -> w_p_scb ) { 786if (used_max_fill_curwin ) { 787// The current window was set to use the maximum number of filler 788// lines, may need to reduce them. 789diff_set_topline (wp_other ,curwin ); 790 }else if (used_max_fill_other ) { 791// The other window was set to use the maximum number of filler 792// lines, may need to reduce them. 793diff_set_topline (curwin ,wp_other ); 794 } 795 } 796} 797 798static void clear_diffin (diffin_T * din ) 799{ 800if (din -> din_fname == NULL ) { 801XFREE_CLEAR (din -> din_mmfile .ptr ); 802 }else { 803os_remove (din -> din_fname ); 804 } 805} 806 807static void clear_diffout (diffout_T * dout ) 808{ 809if (dout -> dout_fname == NULL ) { 810ga_clear (& dout -> dout_ga ); 811 }else { 812os_remove (dout -> dout_fname ); 813 } 814} 815 816/// Write buffer "buf" to a memory buffer. 817/// 818/// @param buf 819/// @param din 820/// 821/// @return FAIL for failure. 822static int diff_write_buffer (buf_T * buf ,mmfile_t * m ,linenr_T start ,linenr_T end ) 823{ 824if (end < 0 ) { 825end = buf -> b_ml .ml_line_count ; 826 } 827 828if (buf -> b_ml .ml_flags & ML_EMPTY || end < start ) { 829m -> ptr = NULL ; 830m -> size = 0 ; 831return OK ; 832 } 833 834size_t len = 0 ; 835 836// xdiff requires one big block of memory with all the text. 837for (linenr_T lnum = start ;lnum <=end ;lnum ++ ) { 838len += (size_t )ml_get_buf_len (buf ,lnum )+ 1 ; 839 } 840char * ptr = xmalloc (len ); 841m -> ptr = ptr ; 842m -> size = (int )len ; 843 844len = 0 ; 845for (linenr_T lnum = start ;lnum <=end ;lnum ++ ) { 846char * s = ml_get_buf (buf ,lnum ); 847if (diff_flags & DIFF_ICASE ) { 848while (* s != NUL ) { 849int c ; 850int c_len = 1 ; 851char cbuf [MB_MAXBYTES + 1 ]; 852 853if (* s == NL ) { 854c = NUL ; 855 }else { 856// xdiff doesn't support ignoring case, fold-case the text. 857c = utf_ptr2char (s ); 858c_len = utf_char2len (c ); 859c = utf_fold (c ); 860 } 861const int orig_len = utfc_ptr2len (s ); 862 863if (utf_char2bytes (c ,cbuf )!= c_len ) { 864// TODO(Bram): handle byte length difference 865// One example is Å (3 bytes) and å (2 bytes). 866memmove (ptr + len ,s , (size_t )orig_len ); 867 }else { 868memmove (ptr + len ,cbuf , (size_t )c_len ); 869if (orig_len > c_len ) { 870// Copy remaining composing characters 871memmove (ptr + len + c_len ,s + c_len , (size_t )(orig_len - c_len )); 872 } 873 } 874 875s += orig_len ; 876len += (size_t )orig_len ; 877 } 878 }else { 879size_t slen = strlen (s ); 880memmove (ptr + len ,s ,slen ); 881// NUL is represented as NL; convert 882memchrsub (ptr + len ,NL ,NUL ,slen ); 883len += slen ; 884 } 885ptr [len ++ ]= NL ; 886 } 887return OK ; 888} 889 890/// Write buffer "buf" to file or memory buffer. 891/// 892/// Always use 'fileformat' set to "unix". 893/// 894/// @param buf 895/// @param din 896/// 897/// @return FAIL for failure 898static int diff_write (buf_T * buf ,diffin_T * din ,linenr_T start ,linenr_T end ) 899{ 900if (din -> din_fname == NULL ) { 901return diff_write_buffer (buf ,& din -> din_mmfile ,start ,end ); 902 } 903 904// Writing the diff buffers may trigger changes in the window structure 905// via ctx_switch()/ctx_restore() commands. 906// This may cause recursively calling winframe_remove() which is not safe and causes 907// use after free, so let's stop it here. 908if (frames_locked ()) { 909return FAIL ; 910 } 911 912if (end < 0 ) { 913end = buf -> b_ml .ml_line_count ; 914 } 915 916// Always use 'fileformat' set to "unix". 917int save_ml_flags = buf -> b_ml .ml_flags ; 918char * save_ff = buf -> b_p_ff ; 919buf -> b_p_ff = xstrdup ("unix" ); 920const bool save_cmod_flags = cmdmod .cmod_flags ; 921// Writing the buffer is an implementation detail of performing the diff, 922// so it shouldn't update the '[ and '] marks. 923cmdmod .cmod_flags |=CMOD_LOCKMARKS ; 924if (end < start ) { 925// The line range specifies a completely empty file. 926end = start ; 927buf -> b_ml .ml_flags |=ML_EMPTY ; 928 } 929int r = buf_write (buf ,din -> din_fname ,NULL , 930start ,end , 931NULL , false, false, false, true); 932cmdmod .cmod_flags = save_cmod_flags ; 933free_string_option (buf -> b_p_ff ); 934buf -> b_p_ff = save_ff ; 935buf -> b_ml .ml_flags = (buf -> b_ml .ml_flags & ~ML_EMPTY ) | (save_ml_flags & ML_EMPTY ); 936return r ; 937} 938 939static int lnum_compare (const void * s1 ,const void * s2 ) 940{ 941linenr_T lnum1 = * (linenr_T * )s1 ; 942linenr_T lnum2 = * (linenr_T * )s2 ; 943if (lnum1 < lnum2 ) { 944return -1 ; 945 } 946if (lnum1 > lnum2 ) { 947return 1 ; 948 } 949return 0 ; 950} 951 952/// Update the diffs for all buffers involved. 953/// 954/// @param dio 955/// @param idx_orig 956/// @param eap can be NULL 957static void diff_try_update (diffio_T * dio ,int idx_orig ,exarg_T * eap ) 958{ 959if (dio -> dio_internal ) { 960ga_init (& dio -> dio_diff .dout_ga ,sizeof (diffhunk_T ),100 ); 961 }else { 962// We need three temp file names. 963dio -> dio_orig .din_fname = vim_tempname (); 964dio -> dio_new .din_fname = vim_tempname (); 965dio -> dio_diff .dout_fname = vim_tempname (); 966if (dio -> dio_orig .din_fname == NULL 967|| dio -> dio_new .din_fname == NULL 968|| dio -> dio_diff .dout_fname == NULL ) { 969 gototheend ; 970 } 971// Check external diff is actually working. 972if (check_external_diff (dio )== FAIL ) { 973 gototheend ; 974 } 975 } 976 977// :diffupdate! 978if (eap != NULL && eap -> forceit ) { 979for (int idx_new = idx_orig ;idx_new < DB_COUNT ;idx_new ++ ) { 980buf_T * buf = curtab -> tp_diffbuf [idx_new ]; 981if (buf_valid (buf )) { 982buf_check_timestamp (buf ); 983 } 984 } 985 } 986 987// Parse and sort diff anchors if enabled 988int num_anchors = INT_MAX ; 989linenr_T anchors [DB_COUNT ][MAX_DIFF_ANCHORS ]; 990CLEAR_FIELD (anchors ); 991if (diff_flags & DIFF_ANCHOR ) { 992for (int idx = 0 ;idx < DB_COUNT ;idx ++ ) { 993if (curtab -> tp_diffbuf [idx ]== NULL ) { 994continue ; 995 } 996int buf_num_anchors = 0 ; 997if (parse_diffanchors (false, 998curtab -> tp_diffbuf [idx ], 999anchors [idx ], 1000& buf_num_anchors )!= OK ) { 1001emsg (_ (e_failed_to_find_all_diff_anchors )); 1002num_anchors = 0 ; 1003CLEAR_FIELD (anchors ); 1004break ; 1005 } 1006if (buf_num_anchors < num_anchors ) { 1007num_anchors = buf_num_anchors ; 1008 } 1009 1010if (buf_num_anchors > 0 ) { 1011qsort ((void * )anchors [idx ], 1012 (size_t )buf_num_anchors , 1013sizeof (linenr_T ), 1014lnum_compare ); 1015 } 1016 } 1017 } 1018if (num_anchors == INT_MAX ) { 1019num_anchors = 0 ; 1020 } 1021 1022// Split the files into multiple sections by anchors. Each section starts 1023// from one anchor (inclusive) and ends at the next anchor (exclusive). 1024// Diff each section separately before combining the results. If we don't 1025// have any anchors, we will have one big section of the entire file. 1026for (int anchor_i = 0 ;anchor_i <=num_anchors ;anchor_i ++ ) { 1027diff_T * orig_diff = NULL ; 1028if (anchor_i != 0 ) { 1029orig_diff = curtab -> tp_first_diff ; 1030curtab -> tp_first_diff = NULL ; 1031 } 1032linenr_T lnum_start = (anchor_i == 0 ) ?1 :anchors [idx_orig ][anchor_i - 1 ]; 1033linenr_T lnum_end = (anchor_i == num_anchors ) ?-1 :anchors [idx_orig ][anchor_i ]- 1 ; 1034 1035// Write the first buffer to a tempfile or mmfile_t. 1036buf_T * buf = curtab -> tp_diffbuf [idx_orig ]; 1037if (diff_write (buf ,& dio -> dio_orig ,lnum_start ,lnum_end )== FAIL ) { 1038if (orig_diff != NULL ) { 1039// Clean up in-progress diff blocks 1040curtab -> tp_first_diff = orig_diff ; 1041diff_clear (curtab ); 1042 } 1043 gototheend ; 1044 } 1045 1046// Make a difference between the first buffer and every other. 1047for (int idx_new = idx_orig + 1 ;idx_new < DB_COUNT ;idx_new ++ ) { 1048buf = curtab -> tp_diffbuf [idx_new ]; 1049if (buf == NULL || buf -> b_ml .ml_mfp == NULL ) { 1050continue ;// skip buffer that isn't loaded 1051 } 1052lnum_start = anchor_i == 0 ?1 :anchors [idx_new ][anchor_i - 1 ]; 1053lnum_end = anchor_i == num_anchors ?-1 :anchors [idx_new ][anchor_i ]- 1 ; 1054 1055// Write the other buffer and diff with the first one. 1056if (diff_write (buf ,& dio -> dio_new ,lnum_start ,lnum_end )== FAIL ) { 1057continue ; 1058 } 1059if (diff_file (dio )== FAIL ) { 1060continue ; 1061 } 1062 1063// Read the diff output and add each entry to the diff list. 1064diff_read (idx_orig ,idx_new ,dio ); 1065 1066clear_diffin (& dio -> dio_new ); 1067clear_diffout (& dio -> dio_diff ); 1068 } 1069clear_diffin (& dio -> dio_orig ); 1070 1071if (anchor_i != 0 ) { 1072diff_finger_dp = NULL ;// df_lnum shifted, invalidate the finger 1073 1074// Combine the new diff blocks with the existing ones 1075for (diff_T * dp = curtab -> tp_first_diff ;dp != NULL ;dp = dp -> df_next ) { 1076for (int idx = 0 ;idx < DB_COUNT ;idx ++ ) { 1077if (anchors [idx ][anchor_i - 1 ]> 0 ) { 1078dp -> df_lnum [idx ]+= anchors [idx ][anchor_i - 1 ]- 1 ; 1079 } 1080 } 1081 } 1082if (orig_diff != NULL ) { 1083diff_T * last_diff = orig_diff ; 1084while (last_diff -> df_next != NULL ) { 1085last_diff = last_diff -> df_next ; 1086 } 1087last_diff -> df_next = curtab -> tp_first_diff ; 1088curtab -> tp_first_diff = orig_diff ; 1089 } 1090 } 1091 } 1092 1093theend : 1094xfree (dio -> dio_orig .din_fname ); 1095xfree (dio -> dio_new .din_fname ); 1096xfree (dio -> dio_diff .dout_fname ); 1097} 1098 1099/// Return true if the options are set to use the internal diff library. 1100/// Note that if the internal diff failed for one of the buffers, the external 1101/// diff will be used anyway. 1102int diff_internal (void ) 1103FUNC_ATTR_PURE 1104{ 1105return (diff_flags & DIFF_INTERNAL )!= 0 && p_dex .type == kCallbackNone ; 1106} 1107 1108/// Completely update the diffs for the buffers involved. 1109/// 1110/// When using the external "diff" command the buffers are written to a file, 1111/// also for unmodified buffers (the file could have been produced by 1112/// autocommands, e.g. the netrw plugin). 1113/// 1114/// @param eap can be NULL 1115void ex_diffupdate (exarg_T * eap ) 1116{ 1117if (diff_busy ) { 1118diff_need_update = true; 1119return ; 1120 } 1121 1122int had_diffs = curtab -> tp_first_diff != NULL ; 1123 1124// Delete all diffblocks. 1125diff_clear (curtab ); 1126curtab -> tp_diff_invalid = false; 1127 1128// Use the first buffer as the original text. 1129int idx_orig ; 1130for (idx_orig = 0 ;idx_orig < DB_COUNT ;idx_orig ++ ) { 1131if (curtab -> tp_diffbuf [idx_orig ]!= NULL ) { 1132break ; 1133 } 1134 } 1135 1136if (idx_orig == DB_COUNT ) { 1137 gototheend ; 1138 } 1139 1140// Only need to do something when there is another buffer. 1141int idx_new ; 1142for (idx_new = idx_orig + 1 ;idx_new < DB_COUNT ;idx_new ++ ) { 1143if (curtab -> tp_diffbuf [idx_new ]!= NULL ) { 1144break ; 1145 } 1146 } 1147 1148if (idx_new == DB_COUNT ) { 1149 gototheend ; 1150 } 1151 1152// Only use the internal method if it did not fail for one of the buffers. 1153diffio_T diffio = {0 }; 1154diffio .dio_internal = diff_internal (); 1155 1156diff_try_update (& diffio ,idx_orig ,eap ); 1157 1158// force updating cursor position on screen 1159curwin -> w_valid_cursor .lnum = 0 ; 1160 1161theend : 1162// A redraw is needed if there were diffs and they were cleared, or there 1163// are diffs now, which means they got updated. 1164if (had_diffs || curtab -> tp_first_diff != NULL ) { 1165diff_redraw (true); 1166apply_autocmds (EVENT_DIFFUPDATED ,NULL ,NULL , false,curbuf ); 1167 } 1168} 1169 1170/// Do a quick test if "diff" really works. Otherwise it looks like there 1171/// are no differences. Can't use the return value, it's non-zero when 1172/// there are differences. 1173static int check_external_diff (diffio_T * diffio ) 1174{ 1175// May try twice, first with "-a" and then without. 1176bool io_error = false; 1177TriState ok = kFalse ; 1178while (true) { 1179ok = kFalse ; 1180FILE * fd = os_fopen (diffio -> dio_orig .din_fname ,"w" ); 1181 1182if (fd == NULL ) { 1183io_error = true; 1184 }else { 1185if (fwrite ("line1\n" ,6 ,1 ,fd )!= 1 ) { 1186io_error = true; 1187 } 1188fclose (fd ); 1189fd = os_fopen (diffio -> dio_new .din_fname ,"w" ); 1190 1191if (fd == NULL ) { 1192io_error = true; 1193 }else { 1194if (fwrite ("line2\n" ,6 ,1 ,fd )!= 1 ) { 1195io_error = true; 1196 } 1197fclose (fd ); 1198fd = diff_file (diffio )== OK 1199 ?os_fopen (diffio -> dio_diff .dout_fname ,"r" ) 1200 :NULL ; 1201 1202if (fd == NULL ) { 1203io_error = true; 1204 }else { 1205char linebuf [LBUFLEN ]; 1206 1207while (true) { 1208// For normal diff there must be a line that contains 1209// "1c1". For unified diff "@@ -1 +1 @@". 1210if (vim_fgets (linebuf ,LBUFLEN ,fd )) { 1211break ; 1212 } 1213 1214if (strncmp (linebuf ,"1c1" ,3 )== 0 1215|| strncmp (linebuf ,"@@ -1 +1 @@" ,11 )== 0 ) { 1216ok = kTrue ; 1217 } 1218 } 1219fclose (fd ); 1220 } 1221os_remove (diffio -> dio_diff .dout_fname ); 1222os_remove (diffio -> dio_new .din_fname ); 1223 } 1224os_remove (diffio -> dio_orig .din_fname ); 1225 } 1226 1227// When using 'diffexpr' break here. 1228if (p_dex .type != kCallbackNone ) { 1229break ; 1230 } 1231 1232// If we checked if "-a" works already, break here. 1233if (diff_a_works != kNone ) { 1234break ; 1235 } 1236diff_a_works = ok ; 1237 1238// If "-a" works break here, otherwise retry without "-a". 1239if (ok ) { 1240break ; 1241 } 1242 } 1243 1244if (!ok ) { 1245if (io_error ) { 1246emsg (_ ("E810: Cannot read or write temp files" )); 1247 } 1248emsg (_ ("E97: Cannot create diffs" )); 1249diff_a_works = kNone ; 1250return FAIL ; 1251 } 1252return OK ; 1253} 1254 1255/// Invoke the xdiff function. 1256static int diff_file_internal (diffio_T * diffio ) 1257{ 1258xpparam_t param ; 1259xdemitconf_t emit_cfg ; 1260xdemitcb_t emit_cb ; 1261 1262CLEAR_FIELD (param ); 1263CLEAR_FIELD (emit_cfg ); 1264CLEAR_FIELD (emit_cb ); 1265 1266param .flags = (unsigned long )diff_algorithm ; 1267 1268if (diff_flags & DIFF_IWHITE ) { 1269param .flags |=XDF_IGNORE_WHITESPACE_CHANGE ; 1270 } 1271if (diff_flags & DIFF_IWHITEALL ) { 1272param .flags |=XDF_IGNORE_WHITESPACE ; 1273 } 1274if (diff_flags & DIFF_IWHITEEOL ) { 1275param .flags |=XDF_IGNORE_WHITESPACE_AT_EOL ; 1276 } 1277if (diff_flags & DIFF_IBLANK ) { 1278param .flags |=XDF_IGNORE_BLANK_LINES ; 1279 } 1280 1281emit_cfg .ctxlen = 0 ;// don't need any diff_context here 1282emit_cb .priv = & diffio -> dio_diff ; 1283emit_cfg .hunk_func = xdiff_out ; 1284if (diffio -> dio_orig .din_mmfile .size > MAX_XDIFF_SIZE 1285|| diffio -> dio_new .din_mmfile .size > MAX_XDIFF_SIZE ) { 1286emsg (_ (e_problem_creating_internal_diff )); 1287return FAIL ; 1288 } 1289if (xdl_diff (& diffio -> dio_orig .din_mmfile , 1290& diffio -> dio_new .din_mmfile , 1291& param ,& emit_cfg ,& emit_cb )< 0 ) { 1292emsg (_ (e_problem_creating_internal_diff )); 1293return FAIL ; 1294 } 1295return OK ; 1296} 1297 1298/// Make a diff between files "tmp_orig" and "tmp_new", results in "tmp_diff". 1299/// 1300/// @param dio 1301/// 1302/// @return OK or FAIL 1303static int diff_file (diffio_T * dio ) 1304{ 1305char * tmp_orig = dio -> dio_orig .din_fname ; 1306char * tmp_new = dio -> dio_new .din_fname ; 1307char * tmp_diff = dio -> dio_diff .dout_fname ; 1308if (p_dex .type != kCallbackNone ) { 1309// Use 'diffexpr' to generate the diff file. 1310eval_diff (tmp_orig ,tmp_new ,tmp_diff ); 1311return OK ; 1312 } 1313// Use xdiff for generating the diff. 1314if (dio -> dio_internal ) { 1315return diff_file_internal (dio ); 1316 } 1317 1318const size_t len = (strlen (tmp_orig )+ strlen (tmp_new )+ strlen (tmp_diff ) 1319+ strlen (p_srr )+ 27 ); 1320char * const cmd = xmalloc (len ); 1321 1322// We don't want $DIFF_OPTIONS to get in the way. 1323if (os_env_exists ("DIFF_OPTIONS" , true)) { 1324os_unsetenv ("DIFF_OPTIONS" ); 1325 } 1326 1327// Build the diff command and execute it. Always use -a, binary 1328// differences are of no use. Ignore errors, diff returns 1329// non-zero when differences have been found. 1330vim_snprintf (cmd ,len ,"diff %s%s%s%s%s%s%s%s %s" , 1331diff_a_works == kFalse ?"" :"-a " , 1332"" , 1333 (diff_flags & DIFF_IWHITE ) ?"-b " :"" , 1334 (diff_flags & DIFF_IWHITEALL ) ?"-w " :"" , 1335 (diff_flags & DIFF_IWHITEEOL ) ?"-Z " :"" , 1336 (diff_flags & DIFF_IBLANK ) ?"-B " :"" , 1337 (diff_flags & DIFF_ICASE ) ?"-i " :"" , 1338tmp_orig ,tmp_new ); 1339append_redir (cmd ,len ,p_srr ,tmp_diff ); 1340block_autocmds ();// Avoid ShellCmdPost stuff 1341call_shell (cmd , 1342kShellOptFilter |kShellOptSilent |kShellOptDoOut , 1343NULL ); 1344unblock_autocmds (); 1345xfree (cmd ); 1346return OK ; 1347} 1348 1349/// Create a new version of a file from the current buffer and a diff file. 1350/// 1351/// The buffer is written to a file, also for unmodified buffers (the file 1352/// could have been produced by autocommands, e.g. the netrw plugin). 1353/// 1354/// @param eap 1355void ex_diffpatch (exarg_T * eap ) 1356{ 1357char * buf = NULL ; 1358win_T * old_curwin = curwin ; 1359char * newname = NULL ;// name of patched file buffer 1360char * esc_name = NULL ; 1361 1362#ifdef UNIX 1363char * fullname = NULL ; 1364#endif 1365 1366// We need two temp file names. 1367// Name of original temp file. 1368char * tmp_orig = vim_tempname (); 1369// Name of patched temp file. 1370char * tmp_new = vim_tempname (); 1371 1372if ((tmp_orig == NULL )|| (tmp_new == NULL )) { 1373 gototheend ; 1374 } 1375 1376// Write the current buffer to "tmp_orig". 1377if (buf_write (curbuf ,tmp_orig ,NULL , 13781 ,curbuf -> b_ml .ml_line_count , 1379NULL , false, false, false, true)== FAIL ) { 1380 gototheend ; 1381 } 1382 1383#ifdef UNIX 1384// Get the absolute path of the patchfile, changing directory below. 1385fullname = FullName_save (eap -> arg , false); 1386esc_name = vim_strsave_shellescape (fullname != NULL ?fullname :eap -> arg , true, true); 1387#else 1388esc_name = vim_strsave_shellescape (eap -> arg , true, true); 1389#endif 1390size_t buflen = strlen (tmp_orig )+ strlen (esc_name )+ strlen (tmp_new )+ 16 ; 1391buf = xmalloc (buflen ); 1392 1393#ifdef UNIX 1394char dirbuf [MAXPATHL ]; 1395// Temporarily chdir to /tmp, to avoid patching files in the current 1396// directory when the patch file contains more than one patch. When we 1397// have our own temp dir use that instead, it will be cleaned up when we 1398// exit (any .rej files created). Don't change directory if we can't 1399// return to the current. 1400if ((os_dirname (dirbuf ,MAXPATHL )!= OK ) 1401|| (os_chdir (dirbuf )!= 0 )) { 1402dirbuf [0 ]= NUL ; 1403 }else { 1404char * tempdir = vim_gettempdir (); 1405if (tempdir == NULL ) { 1406tempdir = "/tmp" ; 1407 } 1408os_chdir (tempdir ); 1409shorten_fnames (true); 1410 } 1411#endif 1412 1413if (p_pex .type != kCallbackNone ) { 1414// Use 'patchexpr' to generate the new file. 1415#ifdef UNIX 1416eval_patch (tmp_orig , (fullname != NULL ?fullname :eap -> arg ),tmp_new ); 1417#else 1418eval_patch (tmp_orig ,eap -> arg ,tmp_new ); 1419#endif 1420 }else { 1421// Build the patch command and execute it. Ignore errors. 1422vim_snprintf (buf ,buflen ,"patch -o %s %s < %s" , 1423tmp_new ,tmp_orig ,esc_name ); 1424block_autocmds ();// Avoid ShellCmdPost stuff 1425call_shell (buf ,kShellOptFilter ,NULL ); 1426unblock_autocmds (); 1427 } 1428 1429#ifdef UNIX 1430if (dirbuf [0 ]!= NUL ) { 1431if (os_chdir (dirbuf )!= 0 ) { 1432emsg (_ (e_prev_dir )); 1433 } 1434shorten_fnames (true); 1435 } 1436#endif 1437 1438// Delete any .orig or .rej file created. 1439STRCPY (buf ,tmp_new ); 1440strcat (buf ,".orig" ); 1441os_remove (buf ); 1442STRCPY (buf ,tmp_new ); 1443strcat (buf ,".rej" ); 1444os_remove (buf ); 1445 1446// Only continue if the output file was created. 1447FileInfo file_info ; 1448bool info_ok = os_fileinfo (tmp_new ,& file_info ); 1449uint64_t filesize = os_fileinfo_size (& file_info ); 1450if (!info_ok || filesize == 0 ) { 1451emsg (_ ("E816: Cannot read patch output" )); 1452 }else { 1453if (curbuf -> b_fname != NULL ) { 1454newname = xstrnsave (curbuf -> b_fname ,strlen (curbuf -> b_fname )+ 4 ); 1455strcat (newname ,".new" ); 1456 } 1457 1458// don't use a new tab page, each tab page has its own diffs 1459cmdmod .cmod_tab = 0 ; 1460 1461if (win_split (0 , (diff_flags & DIFF_VERTICAL ) ?WSP_VERT :0 )!= FAIL ) { 1462// Pretend it was a ":split fname" command 1463eap -> cmdidx = CMD_split ; 1464eap -> arg = tmp_new ; 1465do_exedit (eap ,old_curwin ); 1466 1467// check that split worked and editing tmp_new 1468if ((curwin != old_curwin )&& win_valid (old_curwin )) { 1469// Set 'diff', 'scrollbind' on and 'wrap' off. 1470diff_win_options (curwin , true); 1471diff_win_options (old_curwin , true); 1472 1473if (newname != NULL ) { 1474// do a ":file filename.new" on the patched buffer 1475eap -> arg = newname ; 1476ex_file (eap ); 1477 1478// Do filetype detection with the new name. 1479if (augroup_exists ("filetypedetect" )) { 1480do_cmdline_cmd (":doau filetypedetect BufRead" ); 1481 } 1482 } 1483 } 1484 } 1485 } 1486 1487theend : 1488if (tmp_orig != NULL ) { 1489os_remove (tmp_orig ); 1490 } 1491xfree (tmp_orig ); 1492 1493if (tmp_new != NULL ) { 1494os_remove (tmp_new ); 1495 } 1496xfree (tmp_new ); 1497xfree (newname ); 1498xfree (buf ); 1499#ifdef UNIX 1500xfree (fullname ); 1501#endif 1502xfree (esc_name ); 1503} 1504 1505/// Split the window and edit another file, setting options to show the diffs. 1506/// 1507/// @param eap 1508void ex_diffsplit (exarg_T * eap ) 1509{ 1510win_T * old_curwin = curwin ; 1511bufref_T old_curbuf ; 1512set_bufref (& old_curbuf ,curbuf ); 1513 1514// Need to compute w_fraction when no redraw happened yet. 1515validate_cursor (curwin ); 1516set_fraction (curwin ); 1517 1518// don't use a new tab page, each tab page has its own diffs 1519cmdmod .cmod_tab = 0 ; 1520 1521if (win_split (0 , (diff_flags & DIFF_VERTICAL ) ?WSP_VERT :0 )== FAIL ) { 1522return ; 1523 } 1524 1525// Pretend it was a ":split fname" command 1526eap -> cmdidx = CMD_split ; 1527curwin -> w_p_diff = true; 1528do_exedit (eap ,old_curwin ); 1529 1530if (curwin == old_curwin ) {// split didn't work 1531return ; 1532 } 1533 1534// Set 'diff', 'scrollbind' on and 'wrap' off. 1535diff_win_options (curwin , true); 1536if (win_valid (old_curwin )) { 1537diff_win_options (old_curwin , true); 1538 1539if (bufref_valid (& old_curbuf )) { 1540// Move the cursor position to that of the old window. 1541curwin -> w_cursor .lnum = diff_get_corresponding_line (old_curbuf .br_buf , 1542old_curwin -> w_cursor .lnum ); 1543 } 1544 } 1545// Now that lines are folded scroll to show the cursor at the same 1546// relative position. 1547scroll_to_fraction (curwin ,curwin -> w_height ); 1548} 1549 1550// Set options to show diffs for the current window. 1551void ex_diffthis (exarg_T * eap ) 1552{ 1553// Set 'diff', 'scrollbind' on and 'wrap' off. 1554diff_win_options (curwin , true); 1555} 1556 1557static void set_diff_option (win_T * wp ,bool value ) 1558{ 1559win_T * old_curwin = curwin ; 1560 1561curwin = wp ; 1562curbuf = curwin -> w_buffer ; 1563curbuf -> b_ro_locked ++ ; 1564set_option_value_give_err (kOptDiff ,BOOLEAN_OBJ (value ),OPT_LOCAL ); 1565curbuf -> b_ro_locked -- ; 1566curwin = old_curwin ; 1567curbuf = curwin -> w_buffer ; 1568} 1569 1570/// Set options in window "wp" for diff mode. 1571/// 1572/// @param addbuf Add buffer to diff. 1573void diff_win_options (win_T * wp ,bool addbuf ) 1574{ 1575win_T * old_curwin = curwin ; 1576 1577// close the manually opened folds 1578curwin = wp ; 1579newFoldLevel (); 1580curwin = old_curwin ; 1581 1582// Use 'scrollbind' and 'cursorbind' when available 1583if (!wp -> w_p_diff ) { 1584wp -> w_p_scb_save = wp -> w_p_scb ; 1585 } 1586wp -> w_p_scb = true; 1587 1588if (!wp -> w_p_diff ) { 1589wp -> w_p_crb_save = wp -> w_p_crb ; 1590 } 1591wp -> w_p_crb = true; 1592if (!(diff_flags & DIFF_FOLLOWWRAP )) { 1593if (!wp -> w_p_diff ) { 1594wp -> w_p_wrap_save = wp -> w_p_wrap ; 1595 } 1596wp -> w_p_wrap = false; 1597wp -> w_skipcol = 0 ; 1598 } 1599 1600if (!wp -> w_p_diff ) { 1601if (wp -> w_p_diff_saved ) { 1602free_string_option (wp -> w_p_fdm_save ); 1603 } 1604wp -> w_p_fdm_save = xstrdup (wp -> w_p_fdm ); 1605 } 1606set_option_direct_for (kOptFoldmethod ,STATIC_CSTR_AS_OBJ ("diff" ),OPT_LOCAL ,0 , 1607kOptScopeWin ,wp ); 1608 1609if (!wp -> w_p_diff ) { 1610wp -> w_p_fen_save = wp -> w_p_fen ; 1611wp -> w_p_fdl_save = wp -> w_p_fdl ; 1612 1613if (wp -> w_p_diff_saved ) { 1614free_string_option (wp -> w_p_fdc_save ); 1615 } 1616wp -> w_p_fdc_save = xstrdup (wp -> w_p_fdc ); 1617 } 1618free_string_option (wp -> w_p_fdc ); 1619wp -> w_p_fdc = xstrdup ("2" ); 1620assert (diff_foldcolumn >=0 && diff_foldcolumn <=9 ); 1621snprintf (wp -> w_p_fdc ,strlen (wp -> w_p_fdc )+ 1 ,"%d" ,diff_foldcolumn ); 1622wp -> w_p_fen = true; 1623wp -> w_p_fdl = 0 ; 1624foldUpdateAll (wp ); 1625 1626// make sure topline is not halfway through a fold 1627changed_window_setting (wp ); 1628if (vim_strchr (p_sbo ,'h' )== NULL ) { 1629do_cmdline_cmd ("set sbo+=hor" ); 1630 } 1631 1632// Save the current values, to be restored in ex_diffoff(). 1633wp -> w_p_diff_saved = true; 1634 1635set_diff_option (wp , true); 1636 1637if (addbuf ) { 1638diff_buf_add (wp -> w_buffer ); 1639 } 1640redraw_later (wp ,UPD_NOT_VALID ); 1641} 1642 1643/// Set options not to show diffs. For the current window or all windows. 1644/// Only in the current tab page. 1645/// 1646/// @param eap 1647void ex_diffoff (exarg_T * eap ) 1648{ 1649bool diffwin = false; 1650 1651FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 1652if (eap -> forceit ?wp -> w_p_diff : (wp == curwin )) { 1653// Set 'diff' off. If option values were saved in 1654// diff_win_options(), restore the ones whose settings seem to have 1655// been left over from diff mode. 1656set_diff_option (wp , false); 1657 1658if (wp -> w_p_diff_saved ) { 1659if (wp -> w_p_scb ) { 1660wp -> w_p_scb = wp -> w_p_scb_save ; 1661 } 1662 1663if (wp -> w_p_crb ) { 1664wp -> w_p_crb = wp -> w_p_crb_save ; 1665 } 1666if (!(diff_flags & DIFF_FOLLOWWRAP )) { 1667if (!wp -> w_p_wrap && wp -> w_p_wrap_save ) { 1668wp -> w_p_wrap = true; 1669wp -> w_leftcol = 0 ; 1670 } 1671 } 1672free_string_option (wp -> w_p_fdm ); 1673wp -> w_p_fdm = xstrdup (* wp -> w_p_fdm_save ?wp -> w_p_fdm_save :"manual" ); 1674free_string_option (wp -> w_p_fdc ); 1675wp -> w_p_fdc = xstrdup (* wp -> w_p_fdc_save ?wp -> w_p_fdc_save :"0" ); 1676 1677if (wp -> w_p_fdl == 0 ) { 1678wp -> w_p_fdl = wp -> w_p_fdl_save ; 1679 } 1680// Only restore 'foldenable' when 'foldmethod' is not 1681// "manual", otherwise we continue to show the diff folds. 1682if (wp -> w_p_fen ) { 1683wp -> w_p_fen = foldmethodIsManual (wp ) ? false :wp -> w_p_fen_save ; 1684 } 1685 1686foldUpdateAll (wp ); 1687 } 1688// remove filler lines 1689wp -> w_topfill = 0 ; 1690 1691// make sure topline is not halfway a fold and cursor is 1692// invalidated 1693changed_window_setting (wp ); 1694 1695// Note: 'sbo' is not restored, it's a global option. 1696diff_buf_adjust (wp ); 1697 } 1698diffwin |=wp -> w_p_diff ; 1699 } 1700 1701// Also remove hidden buffers from the list. 1702if (eap -> forceit ) { 1703diff_buf_clear (); 1704 } 1705 1706if (!diffwin ) { 1707diff_need_update = false; 1708curtab -> tp_diff_invalid = false; 1709curtab -> tp_diff_update = false; 1710diff_clear (curtab ); 1711 } 1712 1713// Remove "hor" from 'scrollopt' if there are no diff windows left. 1714if (!diffwin && (vim_strchr (p_sbo ,'h' )!= NULL )) { 1715do_cmdline_cmd ("set sbo-=hor" ); 1716 } 1717} 1718 1719static bool extract_hunk_internal (diffout_T * dout ,diffhunk_T * hunk ,int * line_idx ) 1720{ 1721bool eof = * line_idx >=dout -> dout_ga .ga_len ; 1722if (!eof ) { 1723* hunk = ((diffhunk_T * )dout -> dout_ga .ga_data )[(* line_idx )++ ]; 1724 } 1725return eof ; 1726} 1727 1728// Extract hunk by parsing the diff output from file and calculate the diffstyle. 1729static bool extract_hunk (FILE * fd ,diffhunk_T * hunk ,diffstyle_T * diffstyle ) 1730{ 1731while (true) { 1732char line [LBUFLEN ];// only need to hold the diff line 1733if (vim_fgets (line ,LBUFLEN ,fd )) { 1734return true;// end of file 1735 } 1736 1737if (* diffstyle == DIFF_NONE ) { 1738// Determine diff style. 1739// ed like diff looks like this: 1740// {first}[,{last}]c{first}[,{last}] 1741// {first}a{first}[,{last}] 1742// {first}[,{last}]d{first} 1743// 1744// unified diff looks like this: 1745// --- file1 2018-03-20 13:23:35.783153140 +0100 1746// +++ file2 2018-03-20 13:23:41.183156066 +0100 1747// @@ -1,3 +1,5 @@ 1748if (isdigit ((uint8_t )(* line ))) { 1749* diffstyle = DIFF_ED ; 1750 }else if ((strncmp (line ,"@@ " ,3 )== 0 )) { 1751* diffstyle = DIFF_UNIFIED ; 1752 }else if ((strncmp (line ,"--- " ,4 )== 0 ) 1753&& (vim_fgets (line ,LBUFLEN ,fd )== 0 ) 1754&& (strncmp (line ,"+++ " ,4 )== 0 ) 1755&& (vim_fgets (line ,LBUFLEN ,fd )== 0 ) 1756&& (strncmp (line ,"@@ " ,3 )== 0 )) { 1757* diffstyle = DIFF_UNIFIED ; 1758 }else { 1759// Format not recognized yet, skip over this line. Cygwin diff 1760// may put a warning at the start of the file. 1761continue ; 1762 } 1763 } 1764 1765if (* diffstyle == DIFF_ED ) { 1766if (!isdigit ((uint8_t )(* line ))) { 1767continue ;// not the start of a diff block 1768 } 1769if (parse_diff_ed (line ,hunk )== FAIL ) { 1770continue ; 1771 } 1772 }else { 1773assert (* diffstyle == DIFF_UNIFIED ); 1774if (strncmp (line ,"@@ " ,3 )!= 0 ) { 1775continue ;// not the start of a diff block 1776 } 1777if (parse_diff_unified (line ,hunk )== FAIL ) { 1778continue ; 1779 } 1780 } 1781 1782// Successfully parsed diff output, can return 1783return false; 1784 } 1785} 1786 1787static void process_hunk (diff_T ** dpp ,diff_T ** dprevp ,int idx_orig ,int idx_new ,diffhunk_T * hunk , 1788bool * notsetp ) 1789{ 1790diff_T * dp = * dpp ; 1791diff_T * dprev = * dprevp ; 1792 1793// Go over blocks before the change, for which orig and new are equal. 1794// Copy blocks from orig to new. 1795while (dp != NULL 1796&& hunk -> lnum_orig > dp -> df_lnum [idx_orig ]+ dp -> df_count [idx_orig ]) { 1797if (* notsetp ) { 1798diff_copy_entry (dprev ,dp ,idx_orig ,idx_new ); 1799 } 1800dprev = dp ; 1801dp = dp -> df_next ; 1802* notsetp = true; 1803 } 1804 1805if ((dp != NULL ) 1806&& (hunk -> lnum_orig <=dp -> df_lnum [idx_orig ]+ dp -> df_count [idx_orig ]) 1807&& (hunk -> lnum_orig + hunk -> count_orig >=dp -> df_lnum [idx_orig ])) { 1808// New block overlaps with existing block(s). 1809// First find last block that overlaps. 1810diff_T * dpl ; 1811for (dpl = dp ;dpl -> df_next != NULL ;dpl = dpl -> df_next ) { 1812if (hunk -> lnum_orig + hunk -> count_orig < dpl -> df_next -> df_lnum [idx_orig ]) { 1813break ; 1814 } 1815 } 1816 1817// If the newly found block starts before the old one, set the 1818// start back a number of lines. 1819linenr_T off = dp -> df_lnum [idx_orig ]- hunk -> lnum_orig ; 1820 1821if (off > 0 ) { 1822for (int i = idx_orig ;i < idx_new ;i ++ ) { 1823if (curtab -> tp_diffbuf [i ]!= NULL ) { 1824dp -> df_lnum [i ]-= off ; 1825dp -> df_count [i ]+= off ; 1826 } 1827 } 1828dp -> df_lnum [idx_new ]= hunk -> lnum_new ; 1829dp -> df_count [idx_new ]= (linenr_T )hunk -> count_new ; 1830 }else if (* notsetp ) { 1831// new block inside existing one, adjust new block 1832dp -> df_lnum [idx_new ]= hunk -> lnum_new + off ; 1833dp -> df_count [idx_new ]= (linenr_T )hunk -> count_new - off ; 1834 }else { 1835// second overlap of new block with existing block 1836 1837// if this hunk has different orig/new counts, adjust 1838// the diff block size first. When we handled the first hunk we 1839// would have expanded it to fit, without knowing that this 1840// hunk exists 1841int orig_size_in_dp = MIN (hunk -> count_orig , 1842dp -> df_lnum [idx_orig ]+ 1843dp -> df_count [idx_orig ]- hunk -> lnum_orig ); 1844int size_diff = hunk -> count_new - orig_size_in_dp ; 1845dp -> df_count [idx_new ]+= size_diff ; 1846 1847// grow existing block to include the overlap completely 1848off = hunk -> lnum_new + hunk -> count_new 1849- (dp -> df_lnum [idx_new ]+ dp -> df_count [idx_new ]); 1850if (off > 0 ) { 1851dp -> df_count [idx_new ]+= off ; 1852 } 1853 } 1854 1855// Adjust the size of the block to include all the lines to the 1856// end of the existing block or the new diff, whatever ends last. 1857off = (hunk -> lnum_orig + (linenr_T )hunk -> count_orig ) 1858- (dpl -> df_lnum [idx_orig ]+ dpl -> df_count [idx_orig ]); 1859 1860if (off < 0 ) { 1861// new change ends in existing block, adjust the end. We only 1862// need to do this once per block or we will over-adjust. 1863if (* notsetp || dp != dpl ) { 1864// adjusting by 'off' here is only correct if 1865// there is not another hunk in this block. we 1866// adjust for this when we encounter a second 1867// overlap later. 1868dp -> df_count [idx_new ]+= - off ; 1869 } 1870off = 0 ; 1871 } 1872 1873for (int i = idx_orig ;i < idx_new ;i ++ ) { 1874if (curtab -> tp_diffbuf [i ]!= NULL ) { 1875dp -> df_count [i ]= dpl -> df_lnum [i ]+ dpl -> df_count [i ] 1876- dp -> df_lnum [i ]+ off ; 1877 } 1878 } 1879 1880// Delete the diff blocks that have been merged into one. 1881diff_T * dn = dp -> df_next ; 1882dp -> df_next = dpl -> df_next ; 1883 1884while (dn != dp -> df_next ) { 1885dpl = dn -> df_next ; 1886clear_diffblock (dn ); 1887dn = dpl ; 1888 } 1889 }else { 1890// Allocate a new diffblock. 1891dp = diff_alloc_new (curtab ,dprev ,dp ); 1892 1893dp -> df_lnum [idx_orig ]= hunk -> lnum_orig ; 1894dp -> df_count [idx_orig ]= (linenr_T )hunk -> count_orig ; 1895dp -> df_lnum [idx_new ]= hunk -> lnum_new ; 1896dp -> df_count [idx_new ]= (linenr_T )hunk -> count_new ; 1897 1898// Set values for other buffers, these must be equal to the 1899// original buffer, otherwise there would have been a change 1900// already. 1901for (int i = idx_orig + 1 ;i < idx_new ;i ++ ) { 1902if (curtab -> tp_diffbuf [i ]!= NULL ) { 1903diff_copy_entry (dprev ,dp ,idx_orig ,i ); 1904 } 1905 } 1906 } 1907* notsetp = false;// "*dp" has been set 1908* dpp = dp ; 1909* dprevp = dprev ; 1910} 1911 1912/// Read the diff output and add each entry to the diff list. 1913/// 1914/// @param idx_orig idx of original file 1915/// @param idx_new idx of new file 1916/// @dout diff output 1917static void diff_read (int idx_orig ,int idx_new ,diffio_T * dio ) 1918{ 1919FILE * fd = NULL ; 1920int line_hunk_idx = 0 ;// line or hunk index 1921diff_T * dprev = NULL ; 1922diff_T * dp = curtab -> tp_first_diff ; 1923diffout_T * dout = & dio -> dio_diff ; 1924bool notset = true;// block "*dp" not set yet 1925diffstyle_T diffstyle = DIFF_NONE ; 1926 1927if (!dio -> dio_internal ) { 1928fd = os_fopen (dout -> dout_fname ,"r" ); 1929if (fd == NULL ) { 1930emsg (_ ("E98: Cannot read diff output" )); 1931return ; 1932 } 1933 } 1934 1935while (true) { 1936diffhunk_T hunk = {0 }; 1937bool eof = dio -> dio_internal 1938 ?extract_hunk_internal (dout ,& hunk ,& line_hunk_idx ) 1939 :extract_hunk (fd ,& hunk ,& diffstyle ); 1940 1941if (eof ) { 1942break ; 1943 } 1944 1945process_hunk (& dp ,& dprev ,idx_orig ,idx_new ,& hunk ,& notset ); 1946 } 1947 1948// for remaining diff blocks orig and new are equal 1949while (dp != NULL ) { 1950if (notset ) { 1951diff_copy_entry (dprev ,dp ,idx_orig ,idx_new ); 1952 } 1953dprev = dp ; 1954dp = dp -> df_next ; 1955notset = true; 1956 } 1957 1958if (fd != NULL ) { 1959fclose (fd ); 1960 } 1961} 1962 1963/// Copy an entry at "dp" from "idx_orig" to "idx_new". 1964/// 1965/// @param dprev 1966/// @param dp 1967/// @param idx_orig 1968/// @param idx_new 1969static void diff_copy_entry (diff_T * dprev ,diff_T * dp ,int idx_orig ,int idx_new ) 1970{ 1971linenr_T off ; 1972 1973if (dprev == NULL ) { 1974off = 0 ; 1975 }else { 1976off = (dprev -> df_lnum [idx_orig ]+ dprev -> df_count [idx_orig ]) 1977- (dprev -> df_lnum [idx_new ]+ dprev -> df_count [idx_new ]); 1978 } 1979dp -> df_lnum [idx_new ]= dp -> df_lnum [idx_orig ]- off ; 1980dp -> df_count [idx_new ]= dp -> df_count [idx_orig ]; 1981} 1982 1983/// Clear the list of diffblocks for tab page "tp". 1984/// 1985/// @param tp 1986void diff_clear (tabpage_T * tp ) 1987FUNC_ATTR_NONNULL_ALL 1988{ 1989diff_T * next_p ; 1990for (diff_T * p = tp -> tp_first_diff ;p != NULL ;p = next_p ) { 1991next_p = p -> df_next ; 1992clear_diffblock (p ); 1993 } 1994tp -> tp_first_diff = NULL ; 1995} 1996 1997/// Return true if the options are set to use diff linematch. 1998bool diff_linematch (diff_T * dp ) 1999{ 2000if (!(diff_flags & DIFF_LINEMATCH )) { 2001return false; 2002 } 2003// are there more than three diff buffers? 2004int tsize = 0 ; 2005for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2006if (curtab -> tp_diffbuf [i ]!= NULL ) { 2007// for the rare case (bug?) that the count of a diff block is negative, do 2008// not run the algorithm because this will try to allocate a negative 2009// amount of space and crash 2010if (dp -> df_count [i ]< 0 ) { 2011return false; 2012 } 2013tsize += dp -> df_count [i ]; 2014 } 2015 } 2016// avoid allocating a huge array because it will lag 2017return tsize <=linematch_lines ; 2018} 2019 2020static int get_max_diff_length (const diff_T * dp ) 2021{ 2022int maxlength = 0 ; 2023for (int k = 0 ;k < DB_COUNT ;k ++ ) { 2024if (curtab -> tp_diffbuf [k ]!= NULL ) { 2025if (dp -> df_count [k ]> maxlength ) { 2026maxlength = dp -> df_count [k ]; 2027 } 2028 } 2029 } 2030return maxlength ; 2031} 2032 2033/// Find the first diff block that includes the specified line. Also find the 2034/// next diff block that's not in the current chain of adjacent blocks that are 2035/// all touching each other directly. 2036static void find_top_diff_block (diff_T ** thistopdiff ,diff_T ** next_adjacent_blocks ,int fromidx , 2037int topline ) 2038{ 2039diff_T * topdiff = NULL ; 2040diff_T * localtopdiff = NULL ; 2041int topdiffchange = 0 ; 2042 2043for (topdiff = curtab -> tp_first_diff ;topdiff != NULL ;topdiff = topdiff -> df_next ) { 2044// set the top of the current overlapping diff block set as we 2045// iterate through all of the sets of overlapping diff blocks 2046if (!localtopdiff || topdiffchange ) { 2047localtopdiff = topdiff ; 2048topdiffchange = 0 ; 2049 } 2050 2051// check if the fromwin topline is matched by the current diff. if so, 2052// set it to the top of the diff block 2053if (topline >=topdiff -> df_lnum [fromidx ]&& topline <= 2054 (topdiff -> df_lnum [fromidx ]+ topdiff -> df_count [fromidx ])) { 2055// this line is inside the current diff block, so we will save the 2056// top block of the set of blocks to refer to later 2057if ((* thistopdiff )== NULL ) { 2058 (* thistopdiff )= localtopdiff ; 2059 } 2060 } 2061 2062// check if the next set of overlapping diff blocks is next 2063if (!(topdiff -> df_next && (topdiff -> df_next -> df_lnum [fromidx ]== 2064 (topdiff -> df_lnum [fromidx ]+ topdiff -> df_count [fromidx ])))) { 2065// mark that the next diff block is belongs to a different set of 2066// overlapping diff blocks 2067topdiffchange = 1 ; 2068 2069// if we already have found that the line number is inside a diff block, 2070// set the marker of the next block and finish the iteration 2071if (* thistopdiff ) { 2072 (* next_adjacent_blocks )= topdiff -> df_next ; 2073break ; 2074 } 2075 } 2076 } 2077} 2078 2079/// Calculates topline/topfill of a target diff window to fit the source diff window. 2080static void calculate_topfill_and_topline (const int fromidx ,const int toidx ,const 2081int from_topline ,const int from_topfill ,int * topfill , 2082linenr_T * topline ) 2083{ 2084// find the position from the top of the diff block, and the next diff 2085// block that's no longer adjacent to the current block. "Adjacency" means 2086// a chain of diff blocks that are directly touching each other, allowed by 2087// linematch and diff anchors. 2088diff_T * thistopdiff = NULL ; 2089diff_T * next_adjacent_blocks = NULL ; 2090int virtual_lines_passed = 0 ; 2091 2092find_top_diff_block (& thistopdiff ,& next_adjacent_blocks ,fromidx ,from_topline ); 2093 2094// count the virtual lines (either filler or concrete line) that have been 2095// passed in the source buffer. There could be multiple diff blocks if 2096// there are adjacent empty blocks (count == 0 at fromidx). 2097 2098diff_T * curdif = thistopdiff ; 2099while (curdif && (curdif -> df_lnum [fromidx ]+ curdif -> df_count [fromidx ]) 2100 <=from_topline ) { 2101virtual_lines_passed += get_max_diff_length (curdif ); 2102 2103curdif = curdif -> df_next ; 2104 } 2105 2106if (curdif != next_adjacent_blocks ) { 2107virtual_lines_passed += from_topline - curdif -> df_lnum [fromidx ]; 2108 } 2109virtual_lines_passed -= from_topfill ; 2110 2111// clamp negative values in case from_topfill hasn't been updated yet and 2112// is larger than total virtual lines, which could happen when setting 2113// diffopt multiple times 2114if (virtual_lines_passed < 0 ) { 2115virtual_lines_passed = 0 ; 2116 } 2117 2118// move the same amount of virtual lines in the target buffer to find the 2119// cursor's line number 2120int curlinenum_to 2121= thistopdiff != NULL // this should not be null, but just for safety 2122 ?thistopdiff -> df_lnum [toidx ] :1 ; 2123 2124int virt_lines_left = virtual_lines_passed ; 2125curdif = thistopdiff ; 2126while (virt_lines_left > 0 && curdif != NULL && curdif != next_adjacent_blocks ) { 2127curlinenum_to += MIN (virt_lines_left ,curdif -> df_count [toidx ]); 2128virt_lines_left -= MIN (virt_lines_left ,get_max_diff_length (curdif )); 2129curdif = curdif -> df_next ; 2130 } 2131 2132// count the total number of virtual lines between the top diff block and 2133// the found line in the target buffer 2134int max_virt_lines = 0 ; 2135for (diff_T * dp = thistopdiff ;dp != NULL ;dp = dp -> df_next ) { 2136if (dp -> df_lnum [toidx ]+ dp -> df_count [toidx ] <=curlinenum_to ) { 2137max_virt_lines += get_max_diff_length (dp ); 2138 }else { 2139if (dp -> df_lnum [toidx ] <=curlinenum_to ) { 2140max_virt_lines += curlinenum_to - dp -> df_lnum [toidx ]; 2141 } 2142break ; 2143 } 2144 } 2145 2146if (diff_flags & DIFF_FILLER ) { 2147// should always be non-negative as max_virt_lines is larger 2148 (* topfill )= max_virt_lines - virtual_lines_passed ; 2149 } 2150 (* topline )= curlinenum_to ; 2151} 2152 2153// Apply results from the linematch algorithm and apply to 'dp' by splitting it into multiple 2154// adjacent diff blocks. 2155static void apply_linematch_results (diff_T * dp ,size_t decisions_length ,const int * decisions ) 2156{ 2157// get the start line number here in each diff buffer, and then increment 2158int line_numbers [DB_COUNT ]; 2159int outputmap [DB_COUNT ]; 2160size_t ndiffs = 0 ; 2161for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2162if (curtab -> tp_diffbuf [i ]!= NULL ) { 2163line_numbers [i ]= dp -> df_lnum [i ]; 2164dp -> df_count [i ]= 0 ; 2165 2166// Keep track of the index of the diff buffer we are using here. 2167// We will use this to write the output of the algorithm to 2168// diff_T structs at the correct indexes 2169outputmap [ndiffs ]= i ; 2170ndiffs ++ ; 2171 } 2172 } 2173 2174// write the diffs starting with the current diff block 2175diff_T * dp_s = dp ; 2176for (size_t i = 0 ;i < decisions_length ;i ++ ) { 2177// Don't allocate on first iter since we can reuse the initial diffblock 2178if (i != 0 && (decisions [i - 1 ]!= decisions [i ])) { 2179// create new sub diff blocks to segment the original diff block which we 2180// further divided by running the linematch algorithm 2181dp_s = diff_alloc_new (curtab ,dp_s ,dp_s -> df_next ); 2182dp_s -> is_linematched = true; 2183for (int j = 0 ;j < DB_COUNT ;j ++ ) { 2184if (curtab -> tp_diffbuf [j ]!= NULL ) { 2185dp_s -> df_lnum [j ]= line_numbers [j ]; 2186dp_s -> df_count [j ]= 0 ; 2187 } 2188 } 2189 } 2190for (size_t j = 0 ;j < ndiffs ;j ++ ) { 2191if (decisions [i ]& (1 <<j )) { 2192// will need to use the map here 2193dp_s -> df_count [outputmap [j ]]++ ; 2194line_numbers [outputmap [j ]]++ ; 2195 } 2196 } 2197 } 2198dp -> is_linematched = true; 2199} 2200 2201static void run_linematch_algorithm (diff_T * dp ) 2202{ 2203// define buffers for diff algorithm 2204mmfile_t diffbufs_mm [DB_COUNT ]; 2205const mmfile_t * diffbufs [DB_COUNT ]; 2206int diff_length [DB_COUNT ]; 2207size_t ndiffs = 0 ; 2208for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2209if (curtab -> tp_diffbuf [i ]!= NULL ) { 2210if (dp -> df_count [i ]> 0 ) { 2211// write the contents of the entire buffer to 2212// diffbufs_mm[diffbuffers_count] 2213diff_write_buffer (curtab -> tp_diffbuf [i ],& diffbufs_mm [ndiffs ], 2214dp -> df_lnum [i ],dp -> df_lnum [i ]+ dp -> df_count [i ]- 1 ); 2215 }else { 2216diffbufs_mm [ndiffs ].size = 0 ; 2217diffbufs_mm [ndiffs ].ptr = NULL ; 2218 } 2219 2220diffbufs [ndiffs ]= & diffbufs_mm [ndiffs ]; 2221 2222// keep track of the length of this diff block to pass it to the linematch 2223// algorithm 2224diff_length [ndiffs ]= dp -> df_count [i ]; 2225 2226// increment the amount of diff buffers we are passing to the algorithm 2227ndiffs ++ ; 2228 } 2229 } 2230 2231// we will get the output of the linematch algorithm in the format of an array 2232// of integers (*decisions) and the length of that array (decisions_length) 2233int * decisions = NULL ; 2234const bool iwhite = (diff_flags & (DIFF_IWHITEALL |DIFF_IWHITE ))> 0 ; 2235size_t decisions_length = linematch_nbuffers (diffbufs ,diff_length ,ndiffs ,& decisions ,iwhite ); 2236 2237for (size_t i = 0 ;i < ndiffs ;i ++ ) { 2238XFREE_CLEAR (diffbufs_mm [i ].ptr ); 2239 } 2240 2241apply_linematch_results (dp ,decisions_length ,decisions ); 2242 2243xfree (decisions ); 2244} 2245 2246/// Check diff status for line "lnum" in buffer "buf": 2247/// 2248/// Returns > 0 for inserting that many filler lines above it (never happens 2249/// when 'diffopt' doesn't contain "filler"). Otherwise returns 0. 2250/// 2251/// "linestatus" (can be NULL) will be set to: 2252/// 0 for nothing special. 2253/// -1 for a line that should be highlighted as changed. 2254/// -2 for a line that should be highlighted as added/deleted. 2255/// 2256/// This should only be used for windows where 'diff' is set. 2257/// 2258/// Note that it's possible for a changed/added/deleted line to also have filler 2259/// lines above it. This happens when using linematch or using diff anchors (at 2260/// the anchored lines). 2261/// 2262/// @param wp 2263/// @param lnum 2264/// @param[out] linestatus 2265/// 2266/// @return diff status. 2267int diff_check_with_linestatus (win_T * wp ,linenr_T lnum ,int * linestatus ) 2268{ 2269buf_T * buf = wp -> w_buffer ; 2270 2271if (linestatus != NULL ) { 2272* linestatus = 0 ; 2273 } 2274 2275if (curtab -> tp_diff_invalid ) { 2276// update after a big change 2277ex_diffupdate (NULL ); 2278 } 2279 2280// no diffs at all 2281if ((curtab -> tp_first_diff == NULL )|| !wp -> w_p_diff ) { 2282return 0 ; 2283 } 2284 2285// safety check: "lnum" must be a buffer line 2286if ((lnum < 1 )|| (lnum > buf -> b_ml .ml_line_count + 1 )) { 2287return 0 ; 2288 } 2289 2290int idx = diff_buf_idx (buf ,curtab );// index in tp_diffbuf[] for this buffer 2291 2292if (idx == DB_COUNT ) { 2293// no diffs for buffer "buf" 2294return 0 ; 2295 } 2296 2297// A closed fold never has filler lines. 2298if (hasFolding (wp ,lnum ,NULL ,NULL )|| decor_conceal_line (wp ,lnum - 1 , false)) { 2299return 0 ; 2300 } 2301 2302// Search for a change that includes "lnum" in the list of diffblocks. 2303// Resume from the scan finger to avoid restarting at the first block. 2304diff_T * le = NULL ;// last block with df_lnum[idx] <= lnum 2305diff_T * dp ; 2306for (dp = diff_scan_start (curtab ,idx ,lnum );dp != NULL ;dp = dp -> df_next ) { 2307if (dp -> df_lnum [idx ] <=lnum ) { 2308le = dp ; 2309 } 2310if (lnum <=dp -> df_lnum [idx ]+ dp -> df_count [idx ]) { 2311break ; 2312 } 2313 } 2314diff_scan_remember (curtab ,idx ,lnum ,le ); 2315if ((dp == NULL )|| (lnum < dp -> df_lnum [idx ])) { 2316return 0 ; 2317 } 2318 2319// Don't run linematch when lnum is offscreen. 2320// Useful for scrollbind calculations which need to count all the filler lines 2321// above the screen. 2322if (lnum >=wp -> w_topline && lnum < wp -> w_botline 2323&& !dp -> is_linematched && diff_linematch (dp ) 2324&& diff_check_sanity (curtab ,dp )) { 2325run_linematch_algorithm (dp ); 2326 } 2327 2328// Insert filler lines above the line just below the change. Will return 0 2329// when this buf had the max count. 2330int num_fill = 0 ; 2331while (lnum == dp -> df_lnum [idx ]+ dp -> df_count [idx ]) { 2332// Only calculate fill lines if 'diffopt' contains "filler". Otherwise 2333// returns 0 filler lines. 2334if (diff_flags & DIFF_FILLER ) { 2335int maxcount = get_max_diff_length (dp ); 2336num_fill += maxcount - dp -> df_count [idx ]; 2337 } 2338 2339// If there are adjacent blocks (e.g. linematch or anchor), loop 2340// through them. It's possible for multiple adjacent blocks to 2341// contribute to filler lines. 2342// This also helps us find the last diff block in the list of adjacent 2343// blocks which is necessary when it is a change/inserted line right 2344// after added lines. 2345if (dp -> df_next != NULL 2346&& lnum >=dp -> df_next -> df_lnum [idx ] 2347&& lnum <=dp -> df_next -> df_lnum [idx ]+ dp -> df_next -> df_count [idx ]) { 2348dp = dp -> df_next ; 2349 }else { 2350break ; 2351 } 2352 } 2353 2354if (lnum < dp -> df_lnum [idx ]+ dp -> df_count [idx ]) { 2355bool zero = false; 2356 2357// Changed or inserted line. If the other buffers have a count of 2358// zero, the lines were inserted. If the other buffers have the same 2359// count, check if the lines are identical. 2360bool cmp = false; 2361 2362for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2363if ((i != idx )&& (curtab -> tp_diffbuf [i ]!= NULL )) { 2364if (dp -> df_count [i ]== 0 ) { 2365zero = true; 2366 }else { 2367if (dp -> df_count [i ]!= dp -> df_count [idx ]) { 2368if (linestatus ) { 2369* linestatus = -1 ;// nr of lines changed. 2370 } 2371return num_fill ; 2372 } 2373cmp = true; 2374 } 2375 } 2376 } 2377 2378if (cmp ) { 2379// Compare all lines. If they are equal the lines were inserted 2380// in some buffers, deleted in others, but not changed. 2381for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2382if ((i != idx ) 2383&& (curtab -> tp_diffbuf [i ]!= NULL ) 2384&& (dp -> df_count [i ]!= 0 )) { 2385if (!diff_equal_entry (dp ,idx ,i )) { 2386if (linestatus ) { 2387* linestatus = -1 ; 2388 } 2389return num_fill ; 2390 } 2391 } 2392 } 2393 } 2394 2395// If there is no buffer with zero lines then there is no difference 2396// any longer. Happens when making a change (or undo) that removes 2397// the difference. Can't remove the entry here, we might be halfway 2398// through updating the window. Just report the text as unchanged. 2399// Other windows might still show the change though. 2400if (!zero ) { 2401return num_fill ; 2402 } 2403if (linestatus ) { 2404* linestatus = -2 ; 2405 } 2406return num_fill ; 2407 } 2408return num_fill ; 2409} 2410 2411/// See diff_check_with_linestatus 2412int diff_check_fill (win_T * wp ,linenr_T lnum ) 2413{ 2414// be quick when there are no filler lines 2415if (!(diff_flags & DIFF_FILLER )) { 2416return 0 ; 2417 } 2418int n = diff_check_with_linestatus (wp ,lnum ,NULL ); 2419return MAX (n ,0 ); 2420} 2421 2422/// Compare two entries in diff "dp" and return true if they are equal. 2423/// 2424/// @param dp diff 2425/// @param idx1 first entry in diff "dp" 2426/// @param idx2 second entry in diff "dp" 2427/// 2428/// @return true if two entries are equal. 2429static bool diff_equal_entry (diff_T * dp ,int idx1 ,int idx2 ) 2430FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ) 2431{ 2432if (dp -> df_count [idx1 ]!= dp -> df_count [idx2 ]) { 2433return false; 2434 } 2435 2436if (diff_check_sanity (curtab ,dp )== FAIL ) { 2437return false; 2438 } 2439 2440for (int i = 0 ;i < dp -> df_count [idx1 ];i ++ ) { 2441char * line = xstrdup (ml_get_buf (curtab -> tp_diffbuf [idx1 ],dp -> df_lnum [idx1 ]+ i )); 2442 2443int cmp = diff_cmp (line ,ml_get_buf (curtab -> tp_diffbuf [idx2 ],dp -> df_lnum [idx2 ]+ i )); 2444xfree (line ); 2445 2446if (cmp != 0 ) { 2447return false; 2448 } 2449 } 2450return true; 2451} 2452 2453// Compare the characters at "p1" and "p2". If they are equal (possibly 2454// ignoring case) return true and set "len" to the number of bytes. 2455static bool diff_equal_char (const char * const p1 ,const char * const p2 ,int * const len ) 2456{ 2457const int l = utfc_ptr2len (p1 ); 2458 2459if (l != utfc_ptr2len (p2 )) { 2460return false; 2461 } 2462if (l > 1 ) { 2463if (strncmp (p1 ,p2 , (size_t )l )!= 0 2464&& (!(diff_flags & DIFF_ICASE ) 2465|| utf_fold (utf_ptr2char (p1 ))!= utf_fold (utf_ptr2char (p2 )))) { 2466return false; 2467 } 2468* len = l ; 2469 }else { 2470if ((* p1 != * p2 ) 2471&& (!(diff_flags & DIFF_ICASE ) 2472|| TOLOWER_LOC ((uint8_t )(* p1 ))!= TOLOWER_LOC ((uint8_t )(* p2 )))) { 2473return false; 2474 } 2475* len = 1 ; 2476 } 2477return true; 2478} 2479 2480/// Compare strings "s1" and "s2" according to 'diffopt'. 2481/// Return non-zero when they are different. 2482/// 2483/// @param s1 The first string 2484/// @param s2 The second string 2485/// 2486/// @return on-zero if the two strings are different. 2487static int diff_cmp (char * s1 ,char * s2 ) 2488{ 2489if ((diff_flags & DIFF_IBLANK ) 2490&& (* skipwhite (s1 )== NUL || * skipwhite (s2 )== NUL )) { 2491return 0 ; 2492 } 2493 2494if ((diff_flags & (DIFF_ICASE |ALL_WHITE_DIFF ))== 0 ) { 2495return strcmp (s1 ,s2 ); 2496 } 2497 2498if ((diff_flags & DIFF_ICASE )&& !(diff_flags & ALL_WHITE_DIFF )) { 2499return mb_stricmp (s1 ,s2 ); 2500 } 2501 2502char * p1 = s1 ; 2503char * p2 = s2 ; 2504 2505// Ignore white space changes and possibly ignore case. 2506while (* p1 != NUL && * p2 != NUL ) { 2507if (((diff_flags & DIFF_IWHITE ) 2508&& ascii_iswhite (* p1 )&& ascii_iswhite (* p2 )) 2509|| ((diff_flags & DIFF_IWHITEALL ) 2510&& (ascii_iswhite (* p1 )|| ascii_iswhite (* p2 )))) { 2511p1 = skipwhite (p1 ); 2512p2 = skipwhite (p2 ); 2513 }else { 2514int l ; 2515if (!diff_equal_char (p1 ,p2 ,& l )) { 2516break ; 2517 } 2518p1 += l ; 2519p2 += l ; 2520 } 2521 } 2522 2523// Ignore trailing white space. 2524p1 = skipwhite (p1 ); 2525p2 = skipwhite (p2 ); 2526 2527if ((* p1 != NUL )|| (* p2 != NUL )) { 2528return 1 ; 2529 } 2530return 0 ; 2531} 2532 2533/// Set the topline of "towin" to match the position in "fromwin", so that they 2534/// show the same diff'ed lines. 2535/// 2536/// @param fromwin 2537/// @param towin 2538void diff_set_topline (win_T * fromwin ,win_T * towin ) 2539{ 2540buf_T * frombuf = fromwin -> w_buffer ; 2541 2542int fromidx = diff_buf_idx (frombuf ,curtab ); 2543if (fromidx == DB_COUNT ) { 2544// safety check 2545return ; 2546 } 2547 2548if (curtab -> tp_diff_invalid ) { 2549// update after a big change 2550ex_diffupdate (NULL ); 2551 } 2552linenr_T lnum = fromwin -> w_topline ; 2553towin -> w_topfill = 0 ; 2554 2555// search for a change that includes "lnum" in the list of diffblocks. 2556diff_T * dp ; 2557for (dp = curtab -> tp_first_diff ;dp != NULL ;dp = dp -> df_next ) { 2558if (lnum <=dp -> df_lnum [fromidx ]+ dp -> df_count [fromidx ]) { 2559break ; 2560 } 2561 } 2562 2563if (dp == NULL ) { 2564// After last change, compute topline relative to end of file; no 2565// filler lines. 2566towin -> w_topline = towin -> w_buffer -> b_ml .ml_line_count 2567- (frombuf -> b_ml .ml_line_count - lnum ); 2568 }else { 2569// Find index for "towin". 2570int toidx = diff_buf_idx (towin -> w_buffer ,curtab ); 2571 2572if (toidx == DB_COUNT ) { 2573// safety check 2574return ; 2575 } 2576towin -> w_topline = lnum + (dp -> df_lnum [toidx ]- dp -> df_lnum [fromidx ]); 2577 2578if (lnum >=dp -> df_lnum [fromidx ]) { 2579calculate_topfill_and_topline (fromidx ,toidx , 2580fromwin -> w_topline ,fromwin -> w_topfill , 2581& towin -> w_topfill ,& towin -> w_topline ); 2582 } 2583 } 2584 2585// safety check (if diff info gets outdated strange things may happen) 2586towin -> w_botfill = false; 2587 2588if (towin -> w_topline > towin -> w_buffer -> b_ml .ml_line_count ) { 2589towin -> w_topline = towin -> w_buffer -> b_ml .ml_line_count ; 2590towin -> w_botfill = true; 2591 } 2592 2593if (towin -> w_topline < 1 ) { 2594towin -> w_topline = 1 ; 2595towin -> w_topfill = 0 ; 2596 } 2597 2598// When w_topline changes need to recompute w_botline and cursor position 2599invalidate_botline_win (towin ); 2600changed_line_abv_curs_win (towin ); 2601 2602check_topfill (towin , false); 2603hasFolding (towin ,towin -> w_topline ,& towin -> w_topline ,NULL ); 2604} 2605 2606/// Parse the diff anchors. If "check_only" is set, will only make sure the 2607/// syntax is correct. 2608static int parse_diffanchors (bool check_only ,buf_T * buf ,linenr_T * anchors ,int * num_anchors ) 2609{ 2610int i ; 2611char * dia = (* buf -> b_p_dia == NUL ) ?p_dia :buf -> b_p_dia ; 2612 2613buf_T * orig_curbuf = curbuf ; 2614win_T * orig_curwin = curwin ; 2615 2616win_T * bufwin = NULL ; 2617if (check_only ) { 2618bufwin = curwin ; 2619 }else { 2620// Find the first window tied to this buffer and ignore the rest. Will 2621// only matter for window-specific addresses like `.` or `''`. 2622for (bufwin = firstwin ;bufwin != NULL ;bufwin = bufwin -> w_next ) { 2623if (bufwin -> w_buffer == buf && bufwin -> w_p_diff ) { 2624break ; 2625 } 2626 } 2627if (bufwin == NULL && * dia != NUL ) { 2628// The buffer is hidden. Currently this is not supported due to the 2629// edge cases of needing to decide if an address is window-specific 2630// or not. We could add more checks in the future so we can detect 2631// whether an address relies on curwin to make this more fleixble. 2632emsg (_ (e_diff_anchors_with_hidden_windows )); 2633return FAIL ; 2634 } 2635 } 2636 2637for (i = 0 ;i < MAX_DIFF_ANCHORS && * dia != NUL ;i ++ ) { 2638if (* dia == ',' ) {// don't allow empty values 2639return FAIL ; 2640 } 2641 2642curbuf = buf ; 2643curwin = bufwin ; 2644const char * errormsg = NULL ; 2645linenr_T lnum = get_address (NULL ,& dia ,ADDR_LINES ,check_only , true, false,1 ,& errormsg ); 2646curbuf = orig_curbuf ; 2647curwin = orig_curwin ; 2648 2649if (errormsg != NULL ) { 2650emsg (errormsg ); 2651 } 2652if (dia == NULL ) {// error detected 2653return FAIL ; 2654 } 2655if (* dia != ',' && * dia != NUL ) { 2656return FAIL ; 2657 } 2658 2659if (!check_only 2660&& (lnum == MAXLNUM || lnum <=0 || lnum > buf -> b_ml .ml_line_count + 1 )) { 2661emsg (_ (e_invrange )); 2662return FAIL ; 2663 } 2664 2665if (anchors != NULL ) { 2666anchors [i ]= lnum ; 2667 } 2668 2669if (* dia == ',' ) { 2670dia ++ ; 2671 } 2672 } 2673if (i == MAX_DIFF_ANCHORS && * dia != NUL ) { 2674semsg (_ (e_cannot_have_more_than_nr_diff_anchors ),MAX_DIFF_ANCHORS ); 2675return FAIL ; 2676 } 2677if (num_anchors != NULL ) { 2678* num_anchors = i ; 2679 } 2680return OK ; 2681} 2682 2683/// This is called when 'diffanchors' is changed. 2684int diffanchors_changed (bool buflocal ) 2685{ 2686int result = parse_diffanchors (true,curbuf ,NULL ,NULL ); 2687if (result == OK && (diff_flags & DIFF_ANCHOR )) { 2688FOR_ALL_TABS (tp ) { 2689if (!buflocal ) { 2690tp -> tp_diff_invalid = true; 2691 }else { 2692for (int idx = 0 ;idx < DB_COUNT ;idx ++ ) { 2693if (tp -> tp_diffbuf [idx ]== curbuf ) { 2694tp -> tp_diff_invalid = true; 2695break ; 2696 } 2697 } 2698 } 2699 } 2700 } 2701return result ; 2702} 2703 2704/// Map the 'diffopt' keyset onto diff.c's globals. `v` is `p_dip` reified into a keyset. 2705/// 2706/// @return FAIL only for the cross-part "horizontal" + "vertical" conflict. 2707int diffopt_changed (void ) 2708{ 2709OptKeyDict_dip * v = opt_keyset (p_dip ,kOptDiffopt ,NULL ); 2710 2711int flags = (v -> filler ?DIFF_FILLER :0 ) | (v -> anchor ?DIFF_ANCHOR :0 ) 2712 | (v -> iblank ?DIFF_IBLANK :0 ) | (v -> icase ?DIFF_ICASE :0 ) 2713 | (v -> iwhiteall ?DIFF_IWHITEALL :0 ) | (v -> iwhiteeol ?DIFF_IWHITEEOL :0 ) 2714 | (v -> iwhite ?DIFF_IWHITE :0 ) | (v -> horizontal ?DIFF_HORIZONTAL :0 ) 2715 | (v -> vertical ?DIFF_VERTICAL :0 ) | (v -> closeoff ?DIFF_CLOSE_OFF :0 ) 2716 | (v -> hiddenoff ?DIFF_HIDDEN_OFF :0 ) | (v -> followwrap ?DIFF_FOLLOWWRAP :0 ) 2717 | (v -> internal ?DIFF_INTERNAL :0 ); 2718if (HAS_KEY (v ,dip ,linematch )) { 2719flags |=DIFF_LINEMATCH |DIFF_FILLER ;// linematch needs filler 2720 } 2721if (HAS_KEY (v ,dip ,inline_ )) { 2722flags &= ~ALL_INLINE ; 2723if (strequal (v -> inline_ ,"simple" )) { 2724flags |=DIFF_INLINE_SIMPLE ; 2725 }else if (strequal (v -> inline_ ,"char" )) { 2726flags |=DIFF_INLINE_CHAR ; 2727 }else if (strequal (v -> inline_ ,"word" )) { 2728flags |=DIFF_INLINE_WORD ; 2729 }else { 2730flags |=DIFF_INLINE_NONE ; 2731 } 2732 } 2733int algorithm = v -> indent_heuristic ?XDF_INDENT_HEURISTIC :0 ; 2734if (HAS_KEY (v ,dip ,algorithm )) { 2735if (strequal (v -> algorithm ,"minimal" )) { 2736algorithm |=XDF_NEED_MINIMAL ; 2737 }else if (strequal (v -> algorithm ,"patience" )) { 2738algorithm |=XDF_PATIENCE_DIFF ; 2739 }else if (strequal (v -> algorithm ,"histogram" )) { 2740algorithm |=XDF_HISTOGRAM_DIFF ; 2741 }// else "myers" -> 0 2742 } 2743 2744int ret = OK ; 2745// Can't have both "horizontal" and "vertical". 2746if ((flags & DIFF_HORIZONTAL )&& (flags & DIFF_VERTICAL )) { 2747ret = FAIL ; 2748 }else { 2749// If flags were added or removed, or the algorithm was changed, update the diff. 2750if (diff_flags != flags || diff_algorithm != algorithm ) { 2751FOR_ALL_TABS (tp ) { 2752tp -> tp_diff_invalid = true; 2753 } 2754 } 2755 2756int context = HAS_KEY (v ,dip ,context ) ? (int )v -> context :6 ; 2757diff_flags = flags ; 2758diff_context = context == 0 ?1 :context ; 2759linematch_lines = HAS_KEY (v ,dip ,linematch ) ? (int )v -> linematch :0 ; 2760diff_foldcolumn = HAS_KEY (v ,dip ,foldcolumn ) ? (int )v -> foldcolumn :2 ; 2761diff_algorithm = algorithm ; 2762 2763diff_redraw (true); 2764 2765// recompute the scroll binding with the new option value, may 2766// remove or add filler lines 2767check_scrollbind (0 ,0 ); 2768 } 2769 2770return ret ; 2771} 2772 2773/// Check that "diffopt" contains "horizontal". 2774bool diffopt_horizontal (void ) 2775FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2776{ 2777return (diff_flags & DIFF_HORIZONTAL )!= 0 ; 2778} 2779 2780// Return true if 'diffopt' contains "hiddenoff". 2781bool diffopt_hiddenoff (void ) 2782FUNC_ATTR_PURE 2783{ 2784return (diff_flags & DIFF_HIDDEN_OFF )!= 0 ; 2785} 2786 2787// Return true if 'diffopt' contains "closeoff". 2788bool diffopt_closeoff (void ) 2789FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2790{ 2791return (diff_flags & DIFF_CLOSE_OFF )!= 0 ; 2792} 2793 2794// Return true if 'diffopt' contains "filler". 2795bool diffopt_filler (void ) 2796FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 2797{ 2798return (diff_flags & DIFF_FILLER )!= 0 ; 2799} 2800 2801/// Called when a line has been updated. Used for updating inline diff in Insert 2802/// mode without waiting for global diff update later. 2803void diff_update_line (linenr_T lnum ) 2804{ 2805if (!(diff_flags & ALL_INLINE_DIFF )) { 2806// We only care if we are doing inline-diff where we cache the diff results 2807return ; 2808 } 2809 2810int idx = diff_buf_idx (curbuf ,curtab ); 2811if (idx == DB_COUNT ) { 2812return ; 2813 } 2814diff_T * dp ; 2815FOR_ALL_DIFFBLOCKS_IN_TAB (curtab ,dp ) { 2816if (lnum <=dp -> df_lnum [idx ]+ dp -> df_count [idx ]) { 2817break ; 2818 } 2819 } 2820 2821// clear the inline change cache as it's invalid 2822if (dp != NULL ) { 2823dp -> has_changes = false; 2824dp -> df_changes .ga_len = 0 ; 2825 } 2826} 2827 2828/// used for simple inline diff algorithm 2829static diffline_change_T simple_diffline_change ; 2830 2831/// Parse a diffline struct and returns the [start,end] byte offsets 2832/// 2833/// Returns true if this change was added, no other buffer has it. 2834bool diff_change_parse (diffline_T * diffline ,diffline_change_T * change ,int * change_start , 2835int * change_end ) 2836{ 2837if (change -> dc_start_lnum_off [diffline -> bufidx ]< diffline -> lineoff ) { 2838* change_start = 0 ; 2839 }else { 2840* change_start = change -> dc_start [diffline -> bufidx ]; 2841 } 2842if (change -> dc_end_lnum_off [diffline -> bufidx ]> diffline -> lineoff ) { 2843* change_end = INT_MAX ; 2844 }else { 2845* change_end = change -> dc_end [diffline -> bufidx ]; 2846 } 2847 2848if (change == & simple_diffline_change ) { 2849// This is what we returned from simple inline diff. We always consider 2850// the range to be changed, rather than added for now. 2851return false; 2852 } 2853 2854// Find out whether this is an addition. Note that for multi buffer diff, 2855// to tell whether lines are additions we check whether all the other diff 2856// lines are identical (in diff_check_with_linestatus). If so, we mark them 2857// as add. We don't do that for inline diff here for simplicity. 2858for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2859if (i == diffline -> bufidx ) { 2860continue ; 2861 } 2862if (change -> dc_start [i ]!= change -> dc_end [i ] 2863|| change -> dc_end_lnum_off [i ]!= change -> dc_start_lnum_off [i ]) { 2864return false; 2865 } 2866 } 2867return true; 2868} 2869 2870/// Find the difference within a changed line and returns [startp,endp] byte 2871/// positions. Performs a simple algorithm by finding a single range in the 2872/// middle. 2873/// 2874/// If diffopt has DIFF_INLINE_NONE set, then this will only calculate the return 2875/// value (added or changed), but startp/endp will not be calculated. 2876/// 2877/// @param wp window whose current buffer to check 2878/// @param lnum line number to check within the buffer 2879/// @param startp first char of the change 2880/// @param endp last char of the change 2881/// 2882/// @return true if the line was added, no other buffer has it. 2883static bool diff_find_change_simple (win_T * wp ,linenr_T lnum ,const diff_T * dp ,int idx , 2884int * startp ,int * endp ) 2885FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 2886{ 2887char * line_org ; 2888if (diff_flags & DIFF_INLINE_NONE ) { 2889// We only care about the return value, not the actual string comparisons. 2890line_org = NULL ; 2891 }else { 2892// Make a copy of the line, the next ml_get() will invalidate it. 2893line_org = xstrdup (ml_get_buf (wp -> w_buffer ,lnum )); 2894 } 2895 2896int si_org ; 2897int si_new ; 2898int ei_org ; 2899int ei_new ; 2900bool added = true; 2901 2902linenr_T off = lnum - dp -> df_lnum [idx ]; 2903for (int i = 0 ;i < DB_COUNT ;i ++ ) { 2904if ((curtab -> tp_diffbuf [i ]!= NULL )&& (i != idx )) { 2905// Skip lines that are not in the other change (filler lines). 2906if (off >=dp -> df_count [i ]) { 2907continue ; 2908 } 2909added = false; 2910if (diff_flags & DIFF_INLINE_NONE ) { 2911break ;// early terminate as we only care about the return value 2912 } 2913 2914char * line_new = ml_get_buf (curtab -> tp_diffbuf [i ],dp -> df_lnum [i ]+ off ); 2915 2916// Search for start of difference 2917si_org = si_new = 0 ; 2918 2919while (line_org [si_org ]!= NUL ) { 2920if (((diff_flags & DIFF_IWHITE ) 2921&& ascii_iswhite (line_org [si_org ]) 2922&& ascii_iswhite (line_new [si_new ])) 2923|| ((diff_flags & DIFF_IWHITEALL ) 2924&& (ascii_iswhite (line_org [si_org ]) 2925|| ascii_iswhite (line_new [si_new ])))) { 2926si_org = (int )(skipwhite (line_org + si_org )- line_org ); 2927si_new = (int )(skipwhite (line_new + si_new )- line_new ); 2928 }else { 2929int l ; 2930if (!diff_equal_char (line_org + si_org ,line_new + si_new ,& l )) { 2931break ; 2932 } 2933si_org += l ; 2934si_new += l ; 2935 } 2936 } 2937 2938// Move back to first byte of character in both lines (may 2939// have "nn^" in line_org and "n^ in line_new). 2940si_org -= utf_head_off (line_org ,line_org + si_org ); 2941si_new -= utf_head_off (line_new ,line_new + si_new ); 2942 2943* startp = MIN (* startp ,si_org ); 2944 2945// Search for end of difference, if any. 2946if ((line_org [si_org ]!= NUL )|| (line_new [si_new ]!= NUL )) { 2947ei_org = (int )strlen (line_org ); 2948ei_new = (int )strlen (line_new ); 2949 2950while (ei_org >=* startp 2951&& ei_new >=si_new 2952&& ei_org >=0 2953&& ei_new >=0 ) { 2954if (((diff_flags & DIFF_IWHITE ) 2955&& ascii_iswhite (line_org [ei_org ]) 2956&& ascii_iswhite (line_new [ei_new ])) 2957|| ((diff_flags & DIFF_IWHITEALL ) 2958&& (ascii_iswhite (line_org [ei_org ]) 2959|| ascii_iswhite (line_new [ei_new ])))) { 2960while (ei_org >=* startp && ascii_iswhite (line_org [ei_org ])) { 2961ei_org -- ; 2962 } 2963 2964while (ei_new >=si_new && ascii_iswhite (line_new [ei_new ])) { 2965ei_new -- ; 2966 } 2967 }else { 2968const char * p1 = line_org + ei_org ; 2969const char * p2 = line_new + ei_new ; 2970 2971p1 -= utf_head_off (line_org ,p1 ); 2972p2 -= utf_head_off (line_new ,p2 ); 2973 2974int l ; 2975if (!diff_equal_char (p1 ,p2 ,& l )) { 2976break ; 2977 } 2978ei_org -= l ; 2979ei_new -= l ; 2980 } 2981 } 2982 2983* endp = MAX (* endp ,ei_org ); 2984 } 2985 } 2986 } 2987 2988xfree (line_org ); 2989return added ; 2990} 2991 2992/// Mapping used for mapping from temporary mmfile created for inline diff back 2993/// to original buffer's line/col. 2994typedef struct { 2995colnr_T byte_start ; 2996colnr_T num_bytes ; 2997int lineoff ; 2998}linemap_entry_T ; 2999 3000/// Refine inline character-wise diff blocks to create a more human readable 3001/// highlight. Otherwise a naive diff under existing algorithms tends to create 3002/// a messy output with lots of small gaps. 3003/// It does this by merging adjacent long diff blocks if they are only separated 3004/// by a couple characters. 3005/// These are done by heuristics and can be further tuned. 3006static void diff_refine_inline_char_highlight (diff_T * dp_orig ,garray_T * linemap ,int idx1 ) 3007{ 3008// Perform multiple passes so that newly merged blocks will now be long 3009// enough which may cause other previously unmerged gaps to be merged as 3010// well. 3011int pass = 1 ; 3012do { 3013bool has_unmerged_gaps = false; 3014bool has_merged_gaps = false; 3015diff_T * dp = dp_orig ; 3016while (dp != NULL && dp -> df_next != NULL ) { 3017// Only use first buffer to calculate the gap because the gap is 3018// unchanged text, which would be the same in all buffers. 3019if (dp -> df_lnum [idx1 ]+ dp -> df_count [idx1 ]- 1 >=linemap [idx1 ].ga_len 3020|| dp -> df_next -> df_lnum [idx1 ]- 1 >=linemap [idx1 ].ga_len ) { 3021dp = dp -> df_next ; 3022continue ; 3023 } 3024 3025// If the gap occurs over different lines, don't consider it 3026linemap_entry_T * entry1 = 3027& ((linemap_entry_T * )linemap [idx1 ].ga_data )[dp -> df_lnum [idx1 ] 3028+ dp -> df_count [idx1 ]- 1 ]; 3029linemap_entry_T * entry2 = 3030& ((linemap_entry_T * )linemap [idx1 ].ga_data )[dp -> df_next -> df_lnum [idx1 ]- 1 ]; 3031if (entry1 -> lineoff != entry2 -> lineoff ) { 3032dp = dp -> df_next ; 3033continue ; 3034 } 3035 3036linenr_T gap = dp -> df_next -> df_lnum [idx1 ]- (dp -> df_lnum [idx1 ]+ dp -> df_count [idx1 ]); 3037if (gap <=3 ) { 3038linenr_T max_df_count = 0 ; 3039for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3040max_df_count = MAX (max_df_count ,dp -> df_count [i ]+ dp -> df_next -> df_count [i ]); 3041 } 3042 3043if (max_df_count >=gap * 4 ) { 3044// Merge current block with the next one. Don't advance the 3045// pointer so we try the same merged block against the next 3046// one. 3047for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3048dp -> df_count [i ]= dp -> df_next -> df_lnum [i ] 3049+ dp -> df_next -> df_count [i ]- dp -> df_lnum [i ]; 3050 } 3051diff_T * dp_next = dp -> df_next ; 3052dp -> df_next = dp_next -> df_next ; 3053clear_diffblock (dp_next ); 3054has_merged_gaps = true; 3055continue ; 3056 }else { 3057has_unmerged_gaps = true; 3058 } 3059 } 3060dp = dp -> df_next ; 3061 } 3062if (!has_unmerged_gaps || !has_merged_gaps ) { 3063break ; 3064 } 3065 }while (pass ++ < 4 );// use limited number of passes to avoid excessive looping 3066} 3067 3068/// Refine inline word diff blocks by merging blocks that are only separated 3069/// by whitespace or punctuation. This creates more coherent highlighting. 3070static void diff_refine_inline_word_highlight (diff_T * dp_orig ,garray_T * linemap ,int idx1 , 3071linenr_T start_lnum ) 3072{ 3073int pass = 1 ; 3074do { 3075diff_T * dp = dp_orig ; 3076 3077while (dp != NULL && dp -> df_next != NULL ) { 3078// Index of the last line of this block and of the first line of the 3079// next one. When this block is empty, which happens for inserted 3080// lines, it has no last line and "idx_entry1" is negative. 3081linenr_T idx_entry1 = dp -> df_lnum [idx1 ]+ dp -> df_count [idx1 ]- 2 ; 3082linenr_T idx_entry2 = dp -> df_next -> df_lnum [idx1 ]- 1 ; 3083 3084// Only merge blocks on the same line 3085if (idx_entry1 < 0 || idx_entry1 >=linemap [idx1 ].ga_len 3086|| idx_entry2 < 0 || idx_entry2 >=linemap [idx1 ].ga_len ) { 3087dp = dp -> df_next ; 3088continue ; 3089 } 3090 3091linemap_entry_T * entry1 = 3092& ((linemap_entry_T * )linemap [idx1 ].ga_data )[idx_entry1 ]; 3093linemap_entry_T * entry2 = 3094& ((linemap_entry_T * )linemap [idx1 ].ga_data )[idx_entry2 ]; 3095 3096// Skip if blocks are on different lines 3097if (entry1 -> lineoff != entry2 -> lineoff ) { 3098dp = dp -> df_next ; 3099continue ; 3100 } 3101 3102// Calculate the gap between blocks 3103int gap_start = entry1 -> byte_start + entry1 -> num_bytes ; 3104int gap_end = entry2 -> byte_start ; 3105int gap_size = gap_end - gap_start ; 3106 3107// Merge adjacent diff blocks separated by small gaps to reduce visual 3108// fragmentation. Gap threshold is set to 5 bytes which handles most 3109// common separators (spaces, punctuation, short variable names) while 3110// still preserving visually distinct changes. 3111if (gap_size <=0 || gap_size > diff_word_gap ) { 3112dp = dp -> df_next ; 3113continue ; 3114 } 3115 3116// Get the text between the two blocks 3117char * line = ml_get_buf (curtab -> tp_diffbuf [idx1 ], 3118start_lnum + entry1 -> lineoff ); 3119char * gap_text = line + gap_start ; 3120 3121// Check if gap contains only whitespace and/or punctuation 3122bool only_non_word = true; 3123bool has_content = false; 3124for (int i = 0 ;i < gap_size && gap_text [i ]!= NUL ;i ++ ) { 3125has_content = true; 3126int char_class = mb_get_class_tab (gap_text + i , 3127curtab -> tp_diffbuf [idx1 ]-> b_chartab ); 3128// class 2 is word characters, if we find any, don't merge 3129if (char_class == 2 ) { 3130only_non_word = false; 3131break ; 3132 } 3133 } 3134 3135// Merge if the gap is small and contains only non-word characters 3136if (has_content && only_non_word ) { 3137long total_change_bytes = 0 ; 3138for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3139if (curtab -> tp_diffbuf [i ]!= NULL ) { 3140// count bytes in the first block 3141for (int k = 0 ;k < dp -> df_count [i ];k ++ ) { 3142int idx = dp -> df_lnum [i ]+ k - 1 ; 3143if (idx < linemap [i ].ga_len ) { 3144total_change_bytes += ((linemap_entry_T * )linemap [i ].ga_data )[idx ].num_bytes ; 3145 } 3146 } 3147// count bytes in the next block 3148for (int k = 0 ;k < dp -> df_next -> df_count [i ];k ++ ) { 3149int idx = dp -> df_next -> df_lnum [i ]+ k - 1 ; 3150if (idx < linemap [i ].ga_len ) { 3151total_change_bytes += ((linemap_entry_T * )linemap [i ].ga_data )[idx ].num_bytes ; 3152 } 3153 } 3154 } 3155 } 3156 3157if (total_change_bytes >=gap_size * 2 ) { 3158// Merge the blocks by extending the first block to include the next 3159for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3160if (curtab -> tp_diffbuf [i ]!= NULL ) { 3161dp -> df_count [i ]= dp -> df_next -> df_lnum [i ]+ dp -> df_next -> df_count [i ] 3162- dp -> df_lnum [i ]; 3163 } 3164 } 3165 3166diff_T * dp_next = dp -> df_next ; 3167dp -> df_next = dp_next -> df_next ; 3168clear_diffblock (dp_next ); 3169 3170// Don't advance dp, check if can merge with the next block too 3171continue ; 3172 } 3173 } 3174 3175dp = dp -> df_next ; 3176 } 3177 }while (pass ++ < 4 );// use limited number of passes to avoid excessive looping 3178} 3179 3180/// Find the inline difference within a diff block among different buffers. Do 3181/// this by splitting each block's content into characters or words, and then 3182/// use internal xdiff to calculate the per-character/word diff. The result is 3183/// stored in dp instead of returned by the function. 3184static void diff_find_change_inline_diff (diff_T * dp ) 3185{ 3186const int save_diff_algorithm = diff_algorithm ; 3187 3188diffio_T dio = {0 }; 3189ga_init (& dio .dio_diff .dout_ga ,sizeof (diffhunk_T ),1000 ); 3190 3191// inline diff only supports internal algo 3192dio .dio_internal = true; 3193 3194// always use indent-heuristics to slide diff splits along 3195// whitespace 3196diff_algorithm |=XDF_INDENT_HEURISTIC ; 3197 3198// diff_read() has an implicit dependency on curtab->tp_first_diff 3199diff_T * orig_diff = curtab -> tp_first_diff ; 3200curtab -> tp_first_diff = NULL ; 3201 3202// diff_read() also uses curtab->tp_diffbuf to determine what's an active 3203// buffer 3204buf_T * (orig_diffbuf [DB_COUNT ]); 3205memcpy (orig_diffbuf ,curtab -> tp_diffbuf ,sizeof (orig_diffbuf )); 3206 3207garray_T linemap [DB_COUNT ]; 3208garray_T file1_str ; 3209garray_T file2_str ; 3210 3211// Buffers to populate mmfile 1/2 that would be passed to xdiff as memory 3212// files. Use a grow array as it is not obvious how much exact space we 3213// need. 3214ga_init (& file1_str ,1 ,1024 ); 3215ga_init (& file2_str ,1 ,1024 ); 3216 3217// Line map to map from generated mmfiles' line numbers back to original 3218// diff blocks' locations. Need this even for char diff because not all 3219// characters are 1-byte long / ASCII. 3220for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3221ga_init (& linemap [i ],sizeof (linemap_entry_T ),128 ); 3222 } 3223 3224int file1_idx = -1 ; 3225for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3226dio .dio_diff .dout_ga .ga_len = 0 ; 3227 3228buf_T * buf = curtab -> tp_diffbuf [i ]; 3229if (buf == NULL || buf -> b_ml .ml_mfp == NULL ) { 3230continue ;// skip buffer that isn't loaded 3231 } 3232if (dp -> df_count [i ]== 0 ) { 3233// skip buffers that don't have any texts in this block so we don't 3234// end up marking the entire block as modified in multi-buffer diff 3235curtab -> tp_diffbuf [i ]= NULL ; 3236continue ; 3237 } 3238 3239if (file1_idx == -1 ) { 3240file1_idx = i ; 3241 } 3242 3243garray_T * curstr = (file1_idx != i ) ?& file2_str :& file1_str ; 3244 3245linenr_T numlines = 0 ; 3246curstr -> ga_len = 0 ; 3247 3248// Split each line into chars/words and populate fake file buffer as 3249// newline-delimited tokens as that's what xdiff requires. 3250for (int off = 0 ;off < dp -> df_count [i ];off ++ ) { 3251char * curline = ml_get_buf (curtab -> tp_diffbuf [i ],dp -> df_lnum [i ]+ off ); 3252 3253bool in_keyword = false; 3254 3255// iwhiteeol support vars 3256bool last_white = false; 3257int eol_ga_len = -1 ; 3258int eol_linemap_len = -1 ; 3259int eol_numlines = -1 ; 3260 3261char * s = curline ; 3262while (* s != NUL ) { 3263bool new_in_keyword = false; 3264if (diff_flags & DIFF_INLINE_WORD ) { 3265// Always use the first buffer's 'iskeyword' to have a 3266// consistent diff. 3267// For multibyte chars, only treat alphanumeric chars 3268// (class 2) as "word", as other classes such as emojis and 3269// CJK ideographs do not usually benefit from word diff as 3270// Vim doesn't have a good way to segment them. 3271new_in_keyword = (mb_get_class_tab (s ,curtab -> tp_diffbuf [file1_idx ]-> b_chartab )== 2 ); 3272 } 3273if (in_keyword && !new_in_keyword ) { 3274ga_append (curstr ,NL ); 3275numlines ++ ; 3276 } 3277 3278if (ascii_iswhite (* s )) { 3279if (diff_flags & DIFF_IWHITEALL ) { 3280in_keyword = false; 3281s = skipwhite (s ); 3282continue ; 3283 }else if ((diff_flags & DIFF_IWHITEEOL )|| (diff_flags & DIFF_IWHITE )) { 3284if (!last_white ) { 3285eol_ga_len = curstr -> ga_len ; 3286eol_linemap_len = linemap [i ].ga_len ; 3287eol_numlines = numlines ; 3288last_white = true; 3289 } 3290 } 3291 }else { 3292if ((diff_flags & DIFF_IWHITEEOL )|| (diff_flags & DIFF_IWHITE )) { 3293last_white = false; 3294eol_ga_len = -1 ; 3295eol_linemap_len = -1 ; 3296eol_numlines = -1 ; 3297 } 3298 } 3299 3300int char_len = 1 ; 3301if (* s == NL ) { 3302// NL is internal substitute for NUL 3303ga_append (curstr ,NUL ); 3304 }else { 3305char_len = utfc_ptr2len (s ); 3306 3307if (ascii_iswhite (* s )&& (diff_flags & DIFF_IWHITE )) { 3308// Treat the entire white space span as a single char. 3309char_len = (int )(skipwhite (s )- s ); 3310 } 3311 3312if (diff_flags & DIFF_ICASE ) { 3313// xdiff doesn't support ignoring case, fold-case the text manually. 3314int c = utf_ptr2char (s ); 3315int c_len = utf_char2len (c ); 3316c = utf_fold (c ); 3317char cbuf [MB_MAXBYTES + 1 ]; 3318int c_fold_len = utf_char2bytes (c ,cbuf ); 3319ga_concat_len (curstr ,cbuf , (size_t )c_fold_len ); 3320if (char_len > c_len ) { 3321// There may be remaining composing characters. Write those back in. 3322// Composing characters don't need case folding. 3323ga_concat_len (curstr ,s + c_len , (size_t )(char_len - c_len )); 3324 } 3325 }else { 3326ga_concat_len (curstr ,s , (size_t )char_len ); 3327 } 3328 } 3329 3330if (!new_in_keyword ) { 3331ga_append (curstr ,NL ); 3332numlines ++ ; 3333 } 3334 3335if (!new_in_keyword || (new_in_keyword && !in_keyword )) { 3336// create a new mapping entry from the xdiff mmfile back to 3337// original line/col. 3338linemap_entry_T linemap_entry = { 3339 .lineoff = off , 3340 .byte_start = (colnr_T )(s - curline ), 3341 .num_bytes = char_len , 3342 }; 3343GA_APPEND (linemap_entry_T ,& linemap [i ],linemap_entry ); 3344 }else { 3345// Still inside a keyword. Just increment byte count but 3346// don't make a new entry. 3347// linemap always has at least one entry here 3348 ((linemap_entry_T * )linemap [i ].ga_data )[linemap [i ].ga_len - 1 ].num_bytes += char_len ; 3349 } 3350 3351in_keyword = new_in_keyword ; 3352s += char_len ; 3353 } 3354if (in_keyword ) { 3355ga_append (curstr ,NL ); 3356numlines ++ ; 3357 } 3358 3359if ((diff_flags & DIFF_IWHITEEOL )|| (diff_flags & DIFF_IWHITE )) { 3360// Need to trim trailing whitespace. Do this simply by 3361// resetting arrays back to before we encountered them. 3362if (eol_ga_len != -1 ) { 3363curstr -> ga_len = eol_ga_len ; 3364linemap [i ].ga_len = eol_linemap_len ; 3365numlines = eol_numlines ; 3366 } 3367 } 3368 3369if (!(diff_flags & DIFF_IWHITEALL )) { 3370// Add an empty line token mapped to the end-of-line in the 3371// original file. This helps diff newline differences among 3372// files, which will be visualized when using 'list' as the eol 3373// listchar will be highlighted. 3374ga_append (curstr ,NL ); 3375numlines ++ ; 3376 3377linemap_entry_T linemap_entry = { 3378 .lineoff = off , 3379 .byte_start = (colnr_T )(s - curline ), 3380 .num_bytes = sizeof (NL ), 3381 }; 3382GA_APPEND (linemap_entry_T ,& linemap [i ],linemap_entry ); 3383 } 3384 } 3385 3386if (file1_idx != i ) { 3387dio .dio_new .din_mmfile .ptr = (char * )curstr -> ga_data ; 3388dio .dio_new .din_mmfile .size = curstr -> ga_len ; 3389 }else { 3390dio .dio_orig .din_mmfile .ptr = (char * )curstr -> ga_data ; 3391dio .dio_orig .din_mmfile .size = curstr -> ga_len ; 3392 } 3393if (file1_idx != i ) { 3394// Perform diff with first file and read the results 3395int diff_status = diff_file_internal (& dio ); 3396if (diff_status == FAIL ) { 3397 gotodone ; 3398 } 3399 3400diff_read (0 ,i ,& dio ); 3401clear_diffout (& dio .dio_diff ); 3402 } 3403 } 3404diff_T * new_diff = curtab -> tp_first_diff ; 3405 3406if (diff_flags & DIFF_INLINE_WORD && file1_idx != -1 ) { 3407diff_refine_inline_word_highlight (new_diff ,linemap ,file1_idx ,dp -> df_lnum [file1_idx ]); 3408 }else if (diff_flags & DIFF_INLINE_CHAR && file1_idx != -1 ) { 3409diff_refine_inline_char_highlight (new_diff ,linemap ,file1_idx ); 3410 } 3411 3412// After the diff, use the linemap to obtain the original line/col of the 3413// changes and cache them in dp. 3414dp -> df_changes .ga_len = 0 ;// this should already be zero 3415for (;new_diff != NULL ;new_diff = new_diff -> df_next ) { 3416diffline_change_T change = {0 }; 3417for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3418if (new_diff -> df_lnum [i ] <=0 ) {// should never be < 0. Checking just for safety 3419continue ; 3420 } 3421linenr_T diff_lnum = new_diff -> df_lnum [i ]- 1 ;// use zero-index 3422linenr_T diff_lnum_end = diff_lnum + new_diff -> df_count [i ]; 3423 3424if (diff_lnum >=linemap [i ].ga_len ) { 3425change .dc_start [i ]= MAXCOL ; 3426change .dc_start_lnum_off [i ]= INT_MAX ; 3427 }else { 3428change .dc_start [i ]= ((linemap_entry_T * )linemap [i ].ga_data )[diff_lnum ].byte_start ; 3429change .dc_start_lnum_off [i ]= ((linemap_entry_T * )linemap [i ].ga_data )[diff_lnum ].lineoff ; 3430 } 3431 3432if (diff_lnum == diff_lnum_end ) { 3433change .dc_end [i ]= change .dc_start [i ]; 3434change .dc_end_lnum_off [i ]= change .dc_start_lnum_off [i ]; 3435 }else if (diff_lnum_end - 1 >=linemap [i ].ga_len ) { 3436change .dc_end [i ]= MAXCOL ; 3437change .dc_end_lnum_off [i ]= INT_MAX ; 3438 }else { 3439change .dc_end [i ]= ((linemap_entry_T * )linemap [i ].ga_data )[diff_lnum_end - 1 ].byte_start + 3440 ((linemap_entry_T * )linemap [i ].ga_data )[diff_lnum_end - 1 ].num_bytes ; 3441change .dc_end_lnum_off [i ]= ((linemap_entry_T * )linemap [i ].ga_data )[diff_lnum_end - 34421 ].lineoff ; 3443 } 3444 } 3445GA_APPEND (diffline_change_T ,& dp -> df_changes ,change ); 3446 } 3447 3448done : 3449diff_algorithm = save_diff_algorithm ; 3450 3451dp -> has_changes = true; 3452 3453diff_clear (curtab ); 3454curtab -> tp_first_diff = orig_diff ; 3455memcpy (curtab -> tp_diffbuf ,orig_diffbuf ,sizeof (orig_diffbuf )); 3456 3457ga_clear (& file1_str ); 3458ga_clear (& file2_str ); 3459// No need to clear dio.dio_orig/dio_new because they were referencing 3460// strings that are now cleared. 3461clear_diffout (& dio .dio_diff ); 3462for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3463ga_clear (& linemap [i ]); 3464 } 3465} 3466 3467/// Find the difference within a changed line. 3468/// Returns true if the line was added, no other buffer has it. 3469bool diff_find_change (win_T * wp ,linenr_T lnum ,diffline_T * diffline ) 3470FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 3471{ 3472int idx = diff_buf_idx (wp -> w_buffer ,curtab ); 3473if (idx == DB_COUNT ) {// cannot happen 3474return false; 3475 } 3476 3477// search for a change that includes "lnum" in the list of diffblocks. 3478diff_T * dp ; 3479FOR_ALL_DIFFBLOCKS_IN_TAB (curtab ,dp ) { 3480if (lnum < dp -> df_lnum [idx ]+ dp -> df_count [idx ]) { 3481break ; 3482 } 3483 } 3484if (dp == NULL || diff_check_sanity (curtab ,dp )== FAIL ) { 3485return false; 3486 } 3487 3488int off = lnum - dp -> df_lnum [idx ]; 3489 3490if (!(diff_flags & ALL_INLINE_DIFF )) { 3491// Use simple algorithm 3492int change_start = MAXCOL ;// first col of changed area 3493int change_end = -1 ;// last col of changed area 3494 3495int ret = diff_find_change_simple (wp ,lnum ,dp ,idx ,& change_start ,& change_end ); 3496 3497// convert from inclusive end to exclusive end per diffline's contract 3498change_end += 1 ; 3499 3500// Create a mock diffline struct. We always only have one so no need to 3501// allocate memory. 3502CLEAR_FIELD (simple_diffline_change ); 3503diffline -> changes = & simple_diffline_change ; 3504diffline -> num_changes = 1 ; 3505diffline -> bufidx = idx ; 3506diffline -> lineoff = lnum - dp -> df_lnum [idx ]; 3507 3508simple_diffline_change .dc_start [idx ]= change_start ; 3509simple_diffline_change .dc_end [idx ]= change_end ; 3510simple_diffline_change .dc_start_lnum_off [idx ]= off ; 3511simple_diffline_change .dc_end_lnum_off [idx ]= off ; 3512return ret ; 3513 } 3514 3515// Use inline diff algorithm. 3516// The diff changes are usually cached so we check that first. 3517if (!dp -> has_changes ) { 3518diff_find_change_inline_diff (dp ); 3519 } 3520 3521garray_T * changes = & dp -> df_changes ; 3522 3523// Use linear search to find the first change for this line. We could 3524// optimize this to use binary search, but there should usually be a 3525// limited number of inline changes per diff block, and limited number of 3526// diff blocks shown on screen, so it is not necessary. 3527int num_changes = 0 ; 3528int change_idx = 0 ; 3529diffline -> changes = NULL ; 3530for (change_idx = 0 ;change_idx < changes -> ga_len ;change_idx ++ ) { 3531diffline_change_T * change = 3532& ((diffline_change_T * )dp -> df_changes .ga_data )[change_idx ]; 3533if (change -> dc_end_lnum_off [idx ]< off ) { 3534continue ; 3535 } 3536if (change -> dc_start_lnum_off [idx ]> off ) { 3537break ; 3538 } 3539if (diffline -> changes == NULL ) { 3540diffline -> changes = change ; 3541 } 3542num_changes ++ ; 3543 } 3544diffline -> num_changes = num_changes ; 3545diffline -> bufidx = idx ; 3546diffline -> lineoff = off ; 3547 3548// Detect simple cases of added lines in the end within a diff block. This 3549// has to be the last change of this diff block, and all other buffers are 3550// considering this to be an addition past their last line. Other scenarios 3551// will be considered a changed line instead. 3552bool added = false; 3553if (num_changes == 1 && change_idx == dp -> df_changes .ga_len ) { 3554added = true; 3555for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3556if (idx == i ) { 3557continue ; 3558 } 3559if (curtab -> tp_diffbuf [i ]== NULL ) { 3560continue ; 3561 } 3562diffline_change_T * change = 3563& ((diffline_change_T * )dp -> df_changes .ga_data )[dp -> df_changes .ga_len - 1 ]; 3564if (change -> dc_start_lnum_off [i ]!= INT_MAX ) { 3565added = false; 3566break ; 3567 } 3568 } 3569 } 3570return added ; 3571} 3572 3573/// Check that line "lnum" is not close to a diff block, this line should 3574/// be in a fold. 3575/// 3576/// @param wp window containing the buffer to check 3577/// @param lnum line number to check within the buffer 3578/// 3579/// @return false if there are no diff blocks at all in this window. 3580bool diff_infold (win_T * wp ,linenr_T lnum ) 3581FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ) 3582{ 3583// Return if 'diff' isn't set. 3584if (!wp -> w_p_diff ) { 3585return false; 3586 } 3587 3588int idx = -1 ; 3589bool other = false; 3590for (int i = 0 ;i < DB_COUNT ;i ++ ) { 3591if (curtab -> tp_diffbuf [i ]== wp -> w_buffer ) { 3592idx = i ; 3593 }else if (curtab -> tp_diffbuf [i ]!= NULL ) { 3594other = true; 3595 } 3596 } 3597 3598// return here if there are no diffs in the window 3599if ((idx == -1 )|| !other ) { 3600return false; 3601 } 3602 3603if (curtab -> tp_diff_invalid ) { 3604// update after a big change 3605ex_diffupdate (NULL ); 3606 } 3607 3608// Return if there are no diff blocks. All lines will be folded. 3609if (curtab -> tp_first_diff == NULL ) { 3610return true; 3611 } 3612 3613// Resume from the scan finger to avoid restarting at the first block. 3614diff_T * le = NULL ;// last block with df_lnum[idx] <= lnum 3615bool result = true; 3616for (diff_T * dp = diff_scan_start (curtab ,idx ,lnum );dp != NULL ;dp = dp -> df_next ) { 3617if (dp -> df_lnum [idx ] <=lnum ) { 3618le = dp ; 3619 } 3620if (dp -> df_lnum [idx ]- diff_context > lnum ) { 3621break ; 3622 } 3623 3624// If this change ends before the line we have a match. 3625if (dp -> df_lnum [idx ]+ dp -> df_count [idx ]+ diff_context > lnum ) { 3626result = false; 3627break ; 3628 } 3629 } 3630diff_scan_remember (curtab ,idx ,lnum ,le ); 3631return result ; 3632} 3633 3634/// "dp" and "do" commands. 3635void nv_diffgetput (bool put ,size_t count ) 3636{ 3637if (bt_prompt (curbuf )) { 3638vim_beep (kOptBoFlagOperator ); 3639return ; 3640 } 3641 3642exarg_T ea ; 3643char buf [30 ]; 3644if (count == 0 ) { 3645ea .arg = "" ; 3646 }else { 3647vim_snprintf (buf ,sizeof (buf ),"%zu" ,count ); 3648ea .arg = buf ; 3649 } 3650 3651if (put ) { 3652ea .cmdidx = CMD_diffput ; 3653 }else { 3654ea .cmdidx = CMD_diffget ; 3655 } 3656 3657ea .addr_count = 0 ; 3658ea .line1 = curwin -> w_cursor .lnum ; 3659ea .line2 = curwin -> w_cursor .lnum ; 3660ex_diffgetput (& ea ); 3661} 3662 3663/// Return true if "diff" appears in the list of diff blocks of the current tab. 3664static bool valid_diff (diff_T * diff ) 3665{ 3666for (diff_T * dp = curtab -> tp_first_diff ;dp != NULL ;dp = dp -> df_next ) { 3667if (dp == diff ) { 3668return true; 3669 } 3670 } 3671return false; 3672} 3673 3674/// ":diffget" and ":diffput" 3675/// 3676/// @param eap 3677void ex_diffgetput (exarg_T * eap ) 3678{ 3679int idx_other ; 3680 3681// Find the current buffer in the list of diff buffers. 3682int idx_cur = diff_buf_idx (curbuf ,curtab ); 3683if (idx_cur == DB_COUNT ) { 3684emsg (_ ("E99: Current buffer is not in diff mode" )); 3685return ; 3686 } 3687 3688if (* eap -> arg == NUL ) { 3689bool found_not_ma = false; 3690// No argument: Find the other buffer in the list of diff buffers. 3691for (idx_other = 0 ;idx_other < DB_COUNT ;idx_other ++ ) { 3692if ((curtab -> tp_diffbuf [idx_other ]!= curbuf ) 3693&& (curtab -> tp_diffbuf [idx_other ]!= NULL )) { 3694if ((eap -> cmdidx != CMD_diffput ) 3695|| MODIFIABLE (curtab -> tp_diffbuf [idx_other ])) { 3696break ; 3697 } 3698found_not_ma = true; 3699 } 3700 } 3701 3702if (idx_other == DB_COUNT ) { 3703if (found_not_ma ) { 3704emsg (_ ("E793: No other buffer in diff mode is modifiable" )); 3705 }else { 3706emsg (_ ("E100: No other buffer in diff mode" )); 3707 } 3708return ; 3709 } 3710 3711// Check that there isn't a third buffer in the list 3712for (int i = idx_other + 1 ;i < DB_COUNT ;i ++ ) { 3713if ((curtab -> tp_diffbuf [i ]!= curbuf ) 3714&& (curtab -> tp_diffbuf [i ]!= NULL ) 3715&& ((eap -> cmdidx != CMD_diffput ) 3716|| MODIFIABLE (curtab -> tp_diffbuf [i ]))) { 3717emsg (_ ("E101: More than two buffers in diff mode, don't know " 3718"which one to use" )); 3719return ; 3720 } 3721 } 3722 }else { 3723// Buffer number or pattern given. Ignore trailing white space. 3724char * p = eap -> arg + strlen (eap -> arg ); 3725while (p > eap -> arg && ascii_iswhite (p [-1 ])) { 3726p -- ; 3727 } 3728 3729int i ; 3730for (i = 0 ;ascii_isdigit (eap -> arg [i ])&& eap -> arg + i < p ;i ++ ) {} 3731 3732if (eap -> arg + i == p ) { 3733// digits only 3734i = (int )atol (eap -> arg ); 3735 }else { 3736i = buflist_findpat (eap -> arg ,p , false, true, false); 3737 3738if (i < 0 ) { 3739// error message already given 3740return ; 3741 } 3742 } 3743buf_T * buf = buflist_findnr (i ); 3744 3745if (buf == NULL ) { 3746semsg (_ ("E102: Can't find buffer \"%s\"" ),eap -> arg ); 3747return ; 3748 } 3749 3750if (buf == curbuf ) { 3751// nothing to do 3752return ; 3753 } 3754idx_other = diff_buf_idx (buf ,curtab ); 3755 3756if (idx_other == DB_COUNT ) { 3757semsg (_ ("E103: Buffer \"%s\" is not in diff mode" ),eap -> arg ); 3758return ; 3759 } 3760 } 3761 3762diff_busy = true; 3763 3764// When no range given include the line above or below the cursor. 3765if (eap -> addr_count == 0 ) { 3766// Make it possible that ":diffget" on the last line gets line below 3767// the cursor line when there is no difference above the cursor. 3768int linestatus = 0 ; 3769if (eap -> line1 == curbuf -> b_ml .ml_line_count 3770&& (diff_check_with_linestatus (curwin ,eap -> line1 ,& linestatus )== 0 3771&& linestatus == 0 ) 3772&& (eap -> line1 == 1 3773|| (diff_check_with_linestatus (curwin ,eap -> line1 - 1 ,& linestatus ) >=0 3774&& linestatus == 0 ))) { 3775eap -> line2 ++ ; 3776 }else if (eap -> line1 > 0 ) { 3777eap -> line1 -- ; 3778 } 3779 } 3780 3781CtxSwitch aco = {0 }; 3782 3783if (eap -> cmdidx != CMD_diffget ) { 3784// Need to make the other buffer the current buffer to be able to make 3785// changes in it. 3786 3787// Set curwin/curbuf to buf and save a few things. 3788ctx_switch (& aco ,NULL ,NULL ,curtab -> tp_diffbuf [idx_other ],0 ); 3789 } 3790 3791const int idx_from = eap -> cmdidx == CMD_diffget ?idx_other :idx_cur ; 3792const int idx_to = eap -> cmdidx == CMD_diffget ?idx_cur :idx_other ; 3793 3794// May give the warning for a changed buffer here, which can trigger the 3795// FileChangedRO autocommand, which may do nasty things and mess 3796// everything up. 3797if (!curbuf -> b_changed ) { 3798change_warning (curbuf ,0 ); 3799if (diff_buf_idx (curbuf ,curtab )!= idx_to ) { 3800emsg (_ ("E787: Buffer changed unexpectedly" )); 3801ctx_restore (& aco ); 3802 gototheend ; 3803 } 3804 } 3805 3806diffgetput (eap -> addr_count ,idx_cur ,idx_from ,idx_to ,eap -> line1 ,eap -> line2 ); 3807 3808// restore curwin/curbuf and a few other things 3809if (eap -> cmdidx != CMD_diffget ) { 3810// Syncing undo only works for the current buffer, but we change 3811// another buffer. Sync undo if the command was typed. This isn't 3812// 100% right when ":diffput" is used in a function or mapping. 3813if (KeyTyped ) { 3814u_sync (false); 3815 } 3816ctx_restore (& aco ); 3817 } 3818 3819theend : 3820diff_busy = false; 3821 3822if (diff_need_update ) { 3823ex_diffupdate (NULL ); 3824 } 3825 3826// Check that the cursor is on a valid character and update its 3827// position. When there were filler lines the topline has become 3828// invalid. 3829check_cursor (curwin ); 3830changed_line_abv_curs (); 3831 3832// If all diffs are gone, update folds in all diff windows. 3833if (curtab -> tp_first_diff == NULL ) { 3834FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 3835if (wp -> w_p_diff && wp -> w_p_fdm [0 ]== 'd' && wp -> w_p_fen ) { 3836foldUpdateAll (wp ); 3837 } 3838 } 3839 } 3840 3841if (diff_need_update ) { 3842// redraw already done by ex_diffupdate() 3843diff_need_update = false; 3844 }else { 3845// Also need to redraw the other buffers. 3846diff_redraw (false); 3847apply_autocmds (EVENT_DIFFUPDATED ,NULL ,NULL , false,curbuf ); 3848 } 3849} 3850 3851/// Apply diffget/diffput to buffers and diffblocks 3852/// 3853/// @param idx_cur index of "curbuf" before ctx_switch() in the list of diff buffers 3854/// @param idx_from index of the buffer to read from in the list of diff buffers 3855/// @param idx_to index of the buffer to modify in the list of diff buffers 3856static void diffgetput (const int addr_count ,const int idx_cur ,const int idx_from , 3857const int idx_to ,const linenr_T line1 ,const linenr_T line2 ) 3858{ 3859linenr_T off = 0 ; 3860diff_T * dprev = NULL ; 3861 3862for (diff_T * dp = curtab -> tp_first_diff ;dp != NULL ;) { 3863if (!addr_count ) { 3864// Handle the case with adjacent diff blocks (e.g. using linematch 3865// or anchors) at/above the cursor. Since a range wasn't specified, 3866// we just want to grab one diff block rather than all of them in 3867// the vicinity. 3868while (dp -> df_next 3869&& dp -> df_next -> df_lnum [idx_cur ]== dp -> df_lnum [idx_cur ]+ dp -> df_count [idx_cur ] 3870&& dp -> df_next -> df_lnum [idx_cur ]== line1 + off + 1 ) { 3871dprev = dp ; 3872dp = dp -> df_next ; 3873 } 3874 } 3875 3876if (dp -> df_lnum [idx_cur ]> line2 + off ) { 3877// past the range that was specified 3878break ; 3879 } 3880diff_T dfree = {0 }; 3881bool did_free = false; 3882linenr_T lnum = dp -> df_lnum [idx_to ]; 3883linenr_T count = dp -> df_count [idx_to ]; 3884// The empty line of an empty buffer is deleted below, include it in 3885// the undo information, otherwise undo leaves a line behind. 3886linenr_T undo_bot = lnum + count + (count == 0 && buf_is_empty (curbuf ) ?1 :0 ); 3887 3888if ((dp -> df_lnum [idx_cur ]+ dp -> df_count [idx_cur ]> line1 + off ) 3889&& (u_save (lnum - 1 ,undo_bot )!= FAIL )) { 3890// Inside the specified range and saving for undo worked. 3891linenr_T start_skip = 0 ; 3892linenr_T end_skip = 0 ; 3893 3894if (addr_count > 0 ) { 3895// A range was specified: check if lines need to be skipped. 3896start_skip = line1 + off - dp -> df_lnum [idx_cur ]; 3897if (start_skip > 0 ) { 3898// range starts below start of current diff block 3899if (start_skip > count ) { 3900lnum += count ; 3901count = 0 ; 3902 }else { 3903count -= start_skip ; 3904lnum += start_skip ; 3905 } 3906 }else { 3907start_skip = 0 ; 3908 } 3909 3910end_skip = dp -> df_lnum [idx_cur ]+ dp -> df_count [idx_cur ]- 1 3911- (line2 + off ); 3912 3913if (end_skip > 0 ) { 3914// range ends above end of current/from diff block 3915if (idx_cur == idx_from ) { 3916// :diffput 3917count = MIN (count ,dp -> df_count [idx_cur ]- start_skip - end_skip ); 3918 }else { 3919// :diffget 3920count -= end_skip ; 3921end_skip = MAX (dp -> df_count [idx_from ]- start_skip - count ,0 ); 3922 } 3923 }else { 3924end_skip = 0 ; 3925 } 3926 } 3927 3928bool buf_empty = buf_is_empty (curbuf ); 3929int added = 0 ; 3930 3931for (int i = 0 ;i < count ;i ++ ) { 3932// remember deleting the last line of the buffer 3933buf_empty = curbuf -> b_ml .ml_line_count == 1 ; 3934if (ml_delete (lnum )== OK ) { 3935added -- ; 3936 } 3937 } 3938 3939for (int i = 0 ;i < dp -> df_count [idx_from ]- start_skip - end_skip ;i ++ ) { 3940linenr_T nr = dp -> df_lnum [idx_from ]+ start_skip + i ; 3941if (nr > curtab -> tp_diffbuf [idx_from ]-> b_ml .ml_line_count ) { 3942break ; 3943 } 3944char * p = xstrdup (ml_get_buf (curtab -> tp_diffbuf [idx_from ],nr )); 3945ml_append (lnum + i - 1 ,p ,0 , false); 3946xfree (p ); 3947added ++ ; 3948if (buf_empty && (curbuf -> b_ml .ml_line_count == 2 )) { 3949// Added the first line into an empty buffer, need to 3950// delete the dummy empty line. 3951// This has a side effect of incrementing curbuf->deleted_bytes, 3952// which results in inaccurate reporting of the byte count of 3953// previous contents in buffer-update events. 3954buf_empty = false; 3955ml_delete (2 ); 3956 } 3957 } 3958linenr_T new_count = dp -> df_count [idx_to ]+ added ; 3959dp -> df_count [idx_to ]= new_count ; 3960 3961if ((start_skip == 0 )&& (end_skip == 0 )) { 3962// Check if there are any other buffers and if the diff is 3963// equal in them. 3964int i ; 3965for (i = 0 ;i < DB_COUNT ;i ++ ) { 3966if ((curtab -> tp_diffbuf [i ]!= NULL ) 3967&& (i != idx_from ) 3968&& (i != idx_to ) 3969&& !diff_equal_entry (dp ,idx_from ,i )) { 3970break ; 3971 } 3972 } 3973 3974if (i == DB_COUNT ) { 3975// delete the diff entry, the buffers are now equal here 3976dfree = * dp ; 3977did_free = true; 3978dp = diff_free (curtab ,dprev ,dp ); 3979 } 3980 } 3981 3982if (added != 0 ) { 3983// Adjust marks. This will change the following entries! 3984mark_adjust (lnum ,lnum + count - 1 ,MAXLNUM ,added ,kExtmarkNOOP ); 3985if (curwin -> w_cursor .lnum >=lnum ) { 3986// Adjust the cursor position if it's in/after the changed 3987// lines. 3988if (curwin -> w_cursor .lnum >=lnum + count ) { 3989curwin -> w_cursor .lnum += added ; 3990// When the buffer was previously empty, the cursor may 3991// now be beyond the last line, so clamp cursor lnum. 3992curwin -> w_cursor .lnum = MIN (curwin -> w_cursor .lnum , 3993curbuf -> b_ml .ml_line_count ); 3994 }else if (added < 0 ) { 3995curwin -> w_cursor .lnum = lnum ; 3996 } 3997 } 3998 } 3999extmark_adjust (curbuf ,lnum ,lnum + count - 1 ,MAXLNUM ,added ,kExtmarkUndo ); 4000changed_lines (curbuf ,lnum ,0 ,lnum + count ,added , true); 4001 4002if (did_free ) { 4003// Diff is deleted, update folds in other windows. 4004diff_fold_update (& dfree ,idx_to ); 4005 } 4006 4007// mark_adjust() may have made "dp" invalid. We don't know where 4008// to continue then, bail out. 4009if (added != 0 && !valid_diff (dp )) { 4010break ; 4011 } 4012 4013if (!did_free ) { 4014// mark_adjust() may have changed the count in a wrong way 4015dp -> df_count [idx_to ]= new_count ; 4016 } 4017 4018// When changing the current buffer, keep track of line numbers 4019if (idx_cur == idx_to ) { 4020off += added ; 4021 } 4022 } 4023 4024// If before the range or not deleted, go to next diff. 4025if (!did_free ) { 4026dprev = dp ; 4027dp = dp -> df_next ; 4028 } 4029 } 4030} 4031 4032/// Update folds for all diff buffers for entry "dp". 4033/// 4034/// Skip buffer with index "skip_idx". 4035/// When there are no diffs, all folds are removed. 4036/// 4037/// @param dp 4038/// @param skip_idx 4039static void diff_fold_update (diff_T * dp ,int skip_idx ) 4040{ 4041FOR_ALL_WINDOWS_IN_TAB (wp ,curtab ) { 4042for (int i = 0 ;i < DB_COUNT ;i ++ ) { 4043if ((curtab -> tp_diffbuf [i ]== wp -> w_buffer )&& (i != skip_idx )) { 4044foldUpdate (wp ,dp -> df_lnum [i ],dp -> df_lnum [i ]+ dp -> df_count [i ]); 4045 } 4046 } 4047 } 4048} 4049 4050/// Checks that the buffer is in diff-mode. 4051/// 4052/// @param buf buffer to check. 4053bool diff_mode_buf (buf_T * buf ) 4054FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ) 4055{ 4056FOR_ALL_TABS (tp ) { 4057if (diff_buf_idx (buf ,tp )!= DB_COUNT ) { 4058return true; 4059 } 4060 } 4061return false; 4062} 4063 4064/// Move "count" times in direction "dir" to the next diff block. 4065/// 4066/// @param dir 4067/// @param count 4068/// 4069/// @return FAIL if there isn't such a diff block. 4070int diff_move_to (int dir ,int count ) 4071{ 4072linenr_T lnum = curwin -> w_cursor .lnum ; 4073int idx = diff_buf_idx (curbuf ,curtab ); 4074if ((idx == DB_COUNT )|| (curtab -> tp_first_diff == NULL )) { 4075return FAIL ; 4076 } 4077 4078if (curtab -> tp_diff_invalid ) { 4079// update after a big change 4080ex_diffupdate (NULL ); 4081 } 4082 4083if (curtab -> tp_first_diff == NULL ) { 4084// no diffs today 4085return FAIL ; 4086 } 4087 4088while (-- count >=0 ) { 4089// Check if already before first diff. 4090if ((dir == BACKWARD )&& (lnum <=curtab -> tp_first_diff -> df_lnum [idx ])) { 4091break ; 4092 } 4093 4094diff_T * dp ; 4095for (dp = curtab -> tp_first_diff ;;dp = dp -> df_next ) { 4096if (dp == NULL ) { 4097break ; 4098 } 4099 4100if (((dir == FORWARD )&& (lnum < dp -> df_lnum [idx ])) 4101|| ((dir == BACKWARD ) 4102&& ((dp -> df_next == NULL ) 4103|| (lnum <=dp -> df_next -> df_lnum [idx ])))) { 4104lnum = dp -> df_lnum [idx ]; 4105break ; 4106 } 4107 } 4108 } 4109 4110// don't end up past the end of the file 4111lnum = MIN (lnum ,curbuf -> b_ml .ml_line_count ); 4112 4113// When the cursor didn't move at all we fail. 4114if (lnum == curwin -> w_cursor .lnum ) { 4115return FAIL ; 4116 } 4117 4118setpcmark (); 4119curwin -> w_cursor .lnum = lnum ; 4120curwin -> w_cursor .col = 0 ; 4121 4122return OK ; 4123} 4124 4125/// Return the line number in the current window that is closest to "lnum1" in 4126/// "buf1" in diff mode. 4127static linenr_T diff_get_corresponding_line_int (buf_T * buf1 ,linenr_T lnum1 ) 4128{ 4129linenr_T baseline = 0 ; 4130 4131int idx1 = diff_buf_idx (buf1 ,curtab ); 4132int idx2 = diff_buf_idx (curbuf ,curtab ); 4133 4134if ((idx1 == DB_COUNT ) 4135|| (idx2 == DB_COUNT ) 4136|| (curtab -> tp_first_diff == NULL )) { 4137return lnum1 ; 4138 } 4139 4140if (curtab -> tp_diff_invalid ) { 4141// update after a big change 4142ex_diffupdate (NULL ); 4143 } 4144 4145if (curtab -> tp_first_diff == NULL ) { 4146// no diffs today 4147return lnum1 ; 4148 } 4149 4150for (diff_T * dp = curtab -> tp_first_diff ;dp != NULL ;dp = dp -> df_next ) { 4151if (dp -> df_lnum [idx1 ]> lnum1 ) { 4152return lnum1 - baseline ; 4153 } 4154if ((dp -> df_lnum [idx1 ]+ dp -> df_count [idx1 ])> lnum1 ) { 4155// Inside the diffblock 4156baseline = lnum1 - dp -> df_lnum [idx1 ]; 4157baseline = MIN (baseline ,dp -> df_count [idx2 ]); 4158 4159return dp -> df_lnum [idx2 ]+ baseline ; 4160 } 4161if ((dp -> df_lnum [idx1 ]== lnum1 ) 4162&& (dp -> df_count [idx1 ]== 0 ) 4163&& (dp -> df_lnum [idx2 ] <=curwin -> w_cursor .lnum ) 4164&& ((dp -> df_lnum [idx2 ]+ dp -> df_count [idx2 ]) 4165> curwin -> w_cursor .lnum )) { 4166// Special case: if the cursor is just after a zero-count 4167// block (i.e. all filler) and the target cursor is already 4168// inside the corresponding block, leave the target cursor 4169// unmoved. This makes repeated CTRL-W W operations work 4170// as expected. 4171return curwin -> w_cursor .lnum ; 4172 } 4173baseline = (dp -> df_lnum [idx1 ]+ dp -> df_count [idx1 ]) 4174- (dp -> df_lnum [idx2 ]+ dp -> df_count [idx2 ]); 4175 } 4176 4177// If we get here then the cursor is after the last diff 4178return lnum1 - baseline ; 4179} 4180 4181/// Finds the corresponding line in a diff. 4182/// 4183/// @param buf1 4184/// @param lnum1 4185/// 4186/// @return The corresponding line. 4187linenr_T diff_get_corresponding_line (buf_T * buf1 ,linenr_T lnum1 ) 4188{ 4189linenr_T lnum = diff_get_corresponding_line_int (buf1 ,lnum1 ); 4190 4191// don't end up past the end of the file 4192return MIN (lnum ,curbuf -> b_ml .ml_line_count ); 4193} 4194 4195/// For line "lnum" in the current window find the equivalent lnum in window 4196/// "wp", compensating for inserted/deleted lines. 4197linenr_T diff_lnum_win (linenr_T lnum ,win_T * wp ) 4198{ 4199diff_T * dp ; 4200 4201int idx = diff_buf_idx (curbuf ,curtab ); 4202 4203if (idx == DB_COUNT ) { 4204// safety check 4205return 0 ; 4206 } 4207 4208if (curtab -> tp_diff_invalid ) { 4209// update after a big change 4210ex_diffupdate (NULL ); 4211 } 4212 4213// search for a change that includes "lnum" in the list of diffblocks. 4214for (dp = curtab -> tp_first_diff ;dp != NULL ;dp = dp -> df_next ) { 4215if (lnum <=dp -> df_lnum [idx ]+ dp -> df_count [idx ]) { 4216break ; 4217 } 4218 } 4219 4220// When after the last change, compute relative to the last line number. 4221if (dp == NULL ) { 4222return wp -> w_buffer -> b_ml .ml_line_count 4223- (curbuf -> b_ml .ml_line_count - lnum ); 4224 } 4225 4226// Find index for "wp". 4227int i = diff_buf_idx (wp -> w_buffer ,curtab ); 4228 4229if (i == DB_COUNT ) { 4230// safety check 4231return 0 ; 4232 } 4233 4234linenr_T n = lnum + (dp -> df_lnum [i ]- dp -> df_lnum [idx ]); 4235return MIN (n ,dp -> df_lnum [i ]+ dp -> df_count [i ]); 4236} 4237 4238/// Handle an ED style diff line. 4239/// 4240/// @return FAIL if the line does not contain diff info. 4241static int parse_diff_ed (char * line ,diffhunk_T * hunk ) 4242{ 4243int l1 ,l2 ; 4244 4245// The line must be one of three formats: 4246// change: {first}[,{last}]c{first}[,{last}] 4247// append: {first}a{first}[,{last}] 4248// delete: {first}[,{last}]d{first} 4249char * p = line ; 4250linenr_T f1 = getdigits_int32 (& p , true,0 ); 4251if (* p == ',' ) { 4252p ++ ; 4253l1 = getdigits_int (& p , true,0 ); 4254 }else { 4255l1 = f1 ; 4256 } 4257if (* p != 'a' && * p != 'c' && * p != 'd' ) { 4258return FAIL ;// invalid diff format 4259 } 4260int difftype = (uint8_t )(* p ++ ); 4261int f2 = getdigits_int (& p , true,0 ); 4262if (* p == ',' ) { 4263p ++ ; 4264l2 = getdigits_int (& p , true,0 ); 4265 }else { 4266l2 = f2 ; 4267 } 4268if (l1 < f1 || l2 < f2 ) { 4269return FAIL ; 4270 } 4271 4272if (difftype == 'a' ) { 4273hunk -> lnum_orig = f1 + 1 ; 4274hunk -> count_orig = 0 ; 4275 }else { 4276hunk -> lnum_orig = f1 ; 4277hunk -> count_orig = l1 - f1 + 1 ; 4278 } 4279if (difftype == 'd' ) { 4280hunk -> lnum_new = (linenr_T )f2 + 1 ; 4281hunk -> count_new = 0 ; 4282 }else { 4283hunk -> lnum_new = (linenr_T )f2 ; 4284hunk -> count_new = l2 - f2 + 1 ; 4285 } 4286return OK ; 4287} 4288 4289/// Parses unified diff with zero(!) context lines. 4290/// Return FAIL if there is no diff information in "line". 4291static int parse_diff_unified (char * line ,diffhunk_T * hunk ) 4292{ 4293// Parse unified diff hunk header: 4294// @@ -oldline,oldcount +newline,newcount @@ 4295char * p = line ; 4296if (* p ++ == '@' && * p ++ == '@' && * p ++ == ' ' && * p ++ == '-' ) { 4297int oldcount ; 4298linenr_T newline ; 4299int newcount ; 4300linenr_T oldline = getdigits_int32 (& p , true,0 ); 4301if (* p == ',' ) { 4302p ++ ; 4303oldcount = getdigits_int (& p , true,0 ); 4304 }else { 4305oldcount = 1 ; 4306 } 4307if (* p ++ == ' ' && * p ++ == '+' ) { 4308newline = getdigits_int (& p , true,0 ); 4309if (* p == ',' ) { 4310p ++ ; 4311newcount = getdigits_int (& p , true,0 ); 4312 }else { 4313newcount = 1 ; 4314 } 4315 }else { 4316return FAIL ;// invalid diff format 4317 } 4318 4319if (oldcount == 0 ) { 4320oldline += 1 ; 4321 } 4322if (newcount == 0 ) { 4323newline += 1 ; 4324 } 4325if (newline == 0 ) { 4326newline = 1 ; 4327 } 4328 4329hunk -> lnum_orig = oldline ; 4330hunk -> count_orig = oldcount ; 4331hunk -> lnum_new = newline ; 4332hunk -> count_new = newcount ; 4333 4334return OK ; 4335 } 4336 4337return FAIL ; 4338} 4339 4340/// Callback function for the xdl_diff() function. 4341/// Stores the diff output in a grow array. 4342static int xdiff_out (int start_a ,int count_a ,int start_b ,int count_b ,void * priv ) 4343{ 4344diffout_T * dout = (diffout_T * )priv ; 4345GA_APPEND (diffhunk_T ,& (dout -> dout_ga ), ((diffhunk_T ){ 4346 .lnum_orig = (linenr_T )start_a + 1 , 4347 .count_orig = count_a , 4348 .lnum_new = (linenr_T )start_b + 1 , 4349 .count_new = count_b , 4350 })); 4351return 0 ; 4352} 4353 4354/// "diff_filler()" function 4355void f_diff_filler (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4356{ 4357rettv -> vval .v_number = MAX (0 ,diff_check_fill (curwin ,tv_get_lnum (argvars ))); 4358} 4359 4360/// "diff_hlID()" function 4361void f_diff_hlID (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 4362{ 4363static linenr_T prev_lnum = 0 ; 4364static varnumber_T changedtick = 0 ; 4365static int fnum = 0 ; 4366static int prev_diff_flags = 0 ; 4367static int change_start = 0 ; 4368static int change_end = 0 ; 4369static hlf_T hlID = (hlf_T )0 ; 4370 4371diffline_T diffline = {0 }; 4372// Remember the results if using simple since it's recalculated per 4373// call. Otherwise just call diff_find_change() every time since 4374// internally the result is cached internally. 4375const bool cache_results = !(diff_flags & ALL_INLINE_DIFF ); 4376 4377linenr_T lnum = tv_get_lnum (argvars ); 4378if (lnum < 0 ) {// ignore type error in {lnum} arg 4379lnum = 0 ; 4380 } 4381if (!cache_results 4382|| lnum != prev_lnum 4383|| changedtick != buf_get_changedtick (curbuf ) 4384|| fnum != curbuf -> b_fnum 4385|| diff_flags != prev_diff_flags ) { 4386// New line, buffer, change: need to get the values. 4387int linestatus = 0 ; 4388diff_check_with_linestatus (curwin ,lnum ,& linestatus ); 4389if (linestatus < 0 ) { 4390if (linestatus == -1 ) { 4391change_start = MAXCOL ; 4392change_end = -1 ; 4393if (diff_find_change (curwin ,lnum ,& diffline )) { 4394hlID = HLF_ADD ;// added line 4395 }else { 4396hlID = HLF_CHD ;// changed line 4397if (diffline .num_changes > 0 && cache_results ) { 4398change_start = diffline .changes [0 ].dc_start [diffline .bufidx ]; 4399change_end = diffline .changes [0 ].dc_end [diffline .bufidx ]; 4400 } 4401 } 4402 }else { 4403hlID = HLF_ADD ;// added line 4404 } 4405 }else { 4406hlID = (hlf_T )0 ; 4407 } 4408 4409if (cache_results ) { 4410prev_lnum = lnum ; 4411changedtick = buf_get_changedtick (curbuf ); 4412fnum = curbuf -> b_fnum ; 4413prev_diff_flags = diff_flags ; 4414 } 4415 } 4416 4417if (hlID == HLF_CHD || hlID == HLF_TXD ) { 4418int col = (int )tv_get_number (& argvars [1 ])- 1 ;// Ignore type error in {col}. 4419if (cache_results ) { 4420if (col >=change_start && col < change_end ) { 4421hlID = HLF_TXD ;// Changed text. 4422 }else { 4423hlID = HLF_CHD ;// Changed line. 4424 } 4425 }else { 4426hlID = HLF_CHD ; 4427for (int i = 0 ;i < diffline .num_changes ;i ++ ) { 4428bool added = diff_change_parse (& diffline ,& diffline .changes [i ], 4429& change_start ,& change_end ); 4430if (col >=change_start && col < change_end ) { 4431hlID = added ?HLF_TXA :HLF_TXD ; 4432break ; 4433 } 4434if (col < change_start ) { 4435// the remaining changes are past this column and not relevant 4436break ; 4437 } 4438 } 4439 } 4440 } 4441rettv -> vval .v_number = hlID ; 4442}