robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
131.1 KiB4442 linesraw
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 {
124  char *din_fname;   // used for external diff
125  mmfile_t din_mmfile;  // used for internal diff
126} diffin_T;
127
128// used for diff result
129typedef struct {
130  char *dout_fname;  // used for external diff
131  garray_T dout_ga;     // used for internal diff
132} diffout_T;
133
134// used for recording hunks from xdiff
135typedef struct {
136  linenr_T lnum_orig;
137  int count_orig;
138  linenr_T lnum_new;
139  int count_new;
140} diffhunk_T;
141
142// two diff inputs and one result
143typedef struct {
144  diffin_T dio_orig;      // original file input
145  diffin_T dio_new;       // new file input
146  diffout_T dio_diff;      // diff result
147  int dio_internal;  // using internal diff
148} diffio_T;
149
150typedef enum {
151  DIFF_ED,
152  DIFF_UNIFIED,
153  DIFF_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{
173  if (dp == diff_finger_dp) {
174    diff_finger_dp = NULL;          // don't leave a dangling finger
175  }
176  ga_clear(&dp->df_changes);
177  xfree(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{
185  if (diff_finger_dp != NULL
186      && diff_finger_tp == tp
187      && diff_finger_idx == idx
188      && lnum >= diff_finger_lnum) {
189    return diff_finger_dp;
190  }
191  return 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{
198  diff_finger_tp = tp;
199  diff_finger_idx = idx;
200  diff_finger_lnum = lnum;
201  diff_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{
209  FOR_ALL_TABS(tp) {
210    int i = diff_buf_idx(buf, tp);
211
212    if (i != DB_COUNT) {
213      tp->tp_diffbuf[i] = NULL;
214      tp->tp_diff_invalid = true;
215
216      if (tp == curtab) {
217        // don't redraw right away, more might change or buffer state
218        // is invalid right now
219        need_diff_redraw = true;
220        redraw_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{
232  if (!win->w_p_diff) {
233    // When there is no window showing a diff for this buffer, remove
234    // it from the diffs.
235    bool found_win = false;
236    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
237      if ((wp->w_buffer == win->w_buffer) && wp->w_p_diff) {
238        found_win = true;
239      }
240    }
241
242    if (!found_win) {
243      int i = diff_buf_idx(win->w_buffer, curtab);
244      if (i != DB_COUNT) {
245        curtab->tp_diffbuf[i] = NULL;
246        curtab->tp_diff_invalid = true;
247        diff_redraw(true);
248      }
249    }
250  } else {
251    diff_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{
266  if (diff_buf_idx(buf, curtab) != DB_COUNT) {
267    // It's already there.
268    return;
269  }
270
271  for (int i = 0; i < DB_COUNT; i++) {
272    if (curtab->tp_diffbuf[i] == NULL) {
273      curtab->tp_diffbuf[i] = buf;
274      curtab->tp_diff_invalid = true;
275      diff_redraw(true);
276      return;
277    }
278  }
279
280  semsg(_("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{
286  for (int i = 0; i < DB_COUNT; i++) {
287    if (curtab->tp_diffbuf[i] != NULL) {
288      curtab->tp_diffbuf[i] = NULL;
289      curtab->tp_diff_invalid = true;
290      diff_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{
303  int idx;
304  for (idx = 0; idx < DB_COUNT; idx++) {
305    if (tp->tp_diffbuf[idx] == buf) {
306      break;
307    }
308  }
309  return 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{
318  FOR_ALL_TABS(tp) {
319    int i = diff_buf_idx(buf, tp);
320    if (i != DB_COUNT) {
321      tp->tp_diff_invalid = true;
322      if (tp == curtab) {
323        diff_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,
336                      linenr_T amount_after)
337{
338  // Handle all tab pages that use "buf" in a diff.
339  FOR_ALL_TABS(tp) {
340    int idx = diff_buf_idx(buf, tp);
341    if (idx != DB_COUNT) {
342      diff_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,
361                                linenr_T amount, linenr_T amount_after)
362{
363  diff_finger_dp = NULL;              // may shift df_lnum, invalidate the finger
364
365  if (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.
370    tp->tp_diff_invalid = true;
371    tp->tp_diff_update = true;
372  }
373
374  linenr_T inserted;
375  linenr_T deleted;
376  if (line2 == MAXLNUM) {
377    // mark_adjust(99, MAXLNUM, 9, 0): insert lines
378    inserted = amount;
379    deleted = 0;
380  } else if (amount_after > 0) {
381    // mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines
382    inserted = amount_after;
383    deleted = 0;
384  } else {
385    // mark_adjust(98, 99, MAXLNUM, -2): delete lines
386    inserted = 0;
387    deleted = -amount_after;
388  }
389
390  diff_T *dprev = NULL;
391  diff_T *dp = tp->tp_first_diff;
392
393  linenr_T lnum_deleted = line1;  // lnum of remaining deletion
394  while (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.
398    if (((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) {
404      diff_T *dnext = diff_alloc_new(tp, dprev, dp);
405
406      dnext->df_lnum[idx] = line1;
407      dnext->df_count[idx] = inserted;
408      for (int i = 0; i < DB_COUNT; i++) {
409        if ((tp->tp_diffbuf[i] != NULL) && (i != idx)) {
410          if (dprev == NULL) {
411            dnext->df_lnum[i] = line1;
412          } else {
413            dnext->df_lnum[i] = line1
414                                + (dprev->df_lnum[i] + dprev->df_count[i])
415                                - (dprev->df_lnum[idx] + dprev->df_count[idx]);
416          }
417          dnext->df_count[i] = deleted;
418        }
419      }
420    }
421
422    // if at end of the list, quit
423    if (dp == NULL) {
424      break;
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
438    linenr_T last = dp->df_lnum[idx] + dp->df_count[idx] - 1;
439
440    // 1. change completely above line1: nothing to do
441    if (last >= line1 - 1) {
442      if (diff_busy) {
443        // Currently in the middle of updating diff blocks. All we want
444        // is to adjust the line numbers and nothing else.
445        if (dp->df_lnum[idx] > line2) {
446          dp->df_lnum[idx] += amount_after;
447        }
448
449        // Advance to next entry.
450        dprev = dp;
451        dp = dp->df_next;
452        continue;
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.
457      if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2) {
458        if (amount_after == 0) {
459          // nothing left to change
460          break;
461        }
462        dp->df_lnum[idx] += amount_after;
463      } else {
464        bool check_unchanged = false;
465
466        // 2. 3. 4. 5.: inserted/deleted lines touching this diff.
467        if (deleted > 0) {
468          linenr_T n;
469          linenr_T off = 0;
470          if (dp->df_lnum[idx] >= line1) {
471            if (last <= line2) {
472              // 4. delete all lines of diff
473              if ((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
477                n = dp->df_next->df_lnum[idx] - lnum_deleted;
478                deleted -= n;
479                n -= dp->df_count[idx];
480                lnum_deleted = dp->df_next->df_lnum[idx];
481              } else {
482                n = deleted - dp->df_count[idx];
483              }
484              dp->df_count[idx] = 0;
485            } else {
486              // 5. delete lines at or just before top of diff
487              off = dp->df_lnum[idx] - lnum_deleted;
488              n = off;
489              dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1;
490              check_unchanged = true;
491            }
492            dp->df_lnum[idx] = line1;
493          } else {
494            if (last < line2) {
495              // 2. delete at end of diff
496              dp->df_count[idx] -= last - lnum_deleted + 1;
497
498              if ((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
502                n = dp->df_next->df_lnum[idx] - 1 - last;
503                deleted -= dp->df_next->df_lnum[idx] - lnum_deleted;
504                lnum_deleted = dp->df_next->df_lnum[idx];
505              } else {
506                n = line2 - last;
507              }
508              check_unchanged = true;
509            } else {
510              // 3. delete lines inside the diff
511              n = 0;
512              dp->df_count[idx] -= deleted;
513            }
514          }
515
516          for (int i = 0; i < DB_COUNT; i++) {
517            if ((tp->tp_diffbuf[i] != NULL) && (i != idx)) {
518              if (dp->df_lnum[i] > off) {
519                dp->df_lnum[i] -= off;
520              } else {
521                dp->df_lnum[i] = 1;
522              }
523              dp->df_count[i] += n;
524            }
525          }
526        } else {
527          if (dp->df_lnum[idx] <= line1) {
528            // inserted lines somewhere in this diff
529            dp->df_count[idx] += inserted;
530            check_unchanged = true;
531          } else {
532            // inserted lines somewhere above this diff
533            dp->df_lnum[idx] += inserted;
534          }
535        }
536
537        if (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.
543          diff_check_unchanged(tp, dp);
544        }
545      }
546    }
547
548    // check if this block touches the previous one, may merge them.
549    if ((dprev != NULL) && !dp->is_linematched && !diff_busy
550        && (dprev->df_lnum[idx] + dprev->df_count[idx] == dp->df_lnum[idx])) {
551      for (int i = 0; i < DB_COUNT; i++) {
552        if (tp->tp_diffbuf[i] != NULL) {
553          dprev->df_count[i] += dp->df_count[i];
554        }
555      }
556      dp = diff_free(tp, dprev, dp);
557    } else {
558      // Advance to next entry.
559      dprev = dp;
560      dp = dp->df_next;
561    }
562  }
563
564  dprev = NULL;
565  dp = tp->tp_first_diff;
566
567  while (dp != NULL) {
568    // All counts are zero, remove this entry.
569    int i;
570    for (i = 0; i < DB_COUNT; i++) {
571      if ((tp->tp_diffbuf[i] != NULL) && (dp->df_count[i] != 0)) {
572        break;
573      }
574    }
575
576    if (i == DB_COUNT) {
577      dp = diff_free(tp, dprev, dp);
578    } else {
579      // Advance to next entry.
580      dprev = dp;
581      dp = dp->df_next;
582    }
583  }
584
585  if (tp == curtab) {
586    // Don't redraw right away, this updates the diffs, which can be slow.
587    need_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.
592    diff_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{
605  diff_T *dnew = xcalloc(1, sizeof(*dnew));
606  diff_finger_dp = NULL;              // list changed, invalidate the finger
607
608  dnew->is_linematched = false;
609  dnew->df_next = dp;
610  if (dprev == NULL) {
611    tp->tp_first_diff = dnew;
612  } else {
613    dprev->df_next = dnew;
614  }
615
616  dnew->has_changes = false;
617  ga_init(&dnew->df_changes, sizeof(diffline_change_T), 20);
618  return dnew;
619}
620
621static diff_T *diff_free(tabpage_T *tp, diff_T *dprev, diff_T *dp)
622{
623  diff_T *ret = dp->df_next;
624  clear_diffblock(dp);
625
626  if (dprev == NULL) {
627    tp->tp_first_diff = ret;
628  } else {
629    dprev->df_next = ret;
630  }
631
632  return 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.
647  int i_org;
648  for (i_org = 0; i_org < DB_COUNT; i_org++) {
649    if (tp->tp_diffbuf[i_org] != NULL) {
650      break;
651    }
652  }
653
654  // safety check
655  if (i_org == DB_COUNT) {
656    return;
657  }
658
659  if (diff_check_sanity(tp, dp) == FAIL) {
660    return;
661  }
662
663  // First check lines at the top, then at the bottom.
664  linenr_T off_org = 0;
665  linenr_T off_new = 0;
666  int dir = FORWARD;
667  while (true) {
668    // Repeat until a line is found which is different or the number of
669    // lines has become zero.
670    while (dp->df_count[i_org] > 0) {
671      // Copy the line, the next ml_get() will invalidate it.
672      if (dir == BACKWARD) {
673        off_org = dp->df_count[i_org] - 1;
674      }
675      char *line_org = xstrdup(ml_get_buf(tp->tp_diffbuf[i_org], dp->df_lnum[i_org] + off_org));
676
677      int i_new;
678      for (i_new = i_org + 1; i_new < DB_COUNT; i_new++) {
679        if (tp->tp_diffbuf[i_new] == NULL) {
680          continue;
681        }
682
683        if (dir == BACKWARD) {
684          off_new = dp->df_count[i_new] - 1;
685        }
686
687        // if other buffer doesn't have this line, it was inserted
688        if ((off_new < 0) || (off_new >= dp->df_count[i_new])) {
689          break;
690        }
691
692        if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new],
693                                          dp->df_lnum[i_new] + off_new)) != 0) {
694          break;
695        }
696      }
697      xfree(line_org);
698
699      // Stop when a line isn't equal in all diff buffers.
700      if (i_new != DB_COUNT) {
701        break;
702      }
703
704      // Line matched in all buffers, remove it from the diff.
705      for (i_new = i_org; i_new < DB_COUNT; i_new++) {
706        if (tp->tp_diffbuf[i_new] != NULL) {
707          if (dir == FORWARD) {
708            dp->df_lnum[i_new]++;
709          }
710          dp->df_count[i_new]--;
711        }
712      }
713    }
714
715    if (dir == BACKWARD) {
716      break;
717    }
718    dir = 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{
731  for (int i = 0; i < DB_COUNT; i++) {
732    if (tp->tp_diffbuf[i] != NULL) {
733      if (dp->df_lnum[i] + dp->df_count[i] - 1
734          > tp->tp_diffbuf[i]->b_ml.ml_line_count) {
735        return FAIL;
736      }
737    }
738  }
739  return 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{
747  win_T *wp_other = NULL;
748  bool used_max_fill_other = false;
749  bool used_max_fill_curwin = false;
750
751  need_diff_redraw = false;
752  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
753    // when closing windows or wiping buffers skip invalid window
754    if (!wp->w_p_diff || !buf_valid(wp->w_buffer)) {
755      continue;
756    }
757
758    redraw_later(wp, UPD_SOME_VALID);
759    if (wp != curwin) {
760      wp_other = wp;
761    }
762    if (dofold && foldmethodIsDiff(wp)) {
763      foldUpdateAll(wp);
764    }
765
766    // A change may have made filler lines invalid, need to take care of
767    // that for other windows.
768    int n = diff_check_fill(wp, wp->w_topline);
769
770    if (((wp != curwin) && (wp->w_topfill > 0)) || (n > 0)) {
771      if (wp->w_topfill > n) {
772        wp->w_topfill = MAX(n, 0);
773      } else if ((n > 0) && (n > wp->w_topfill)) {
774        wp->w_topfill = n;
775        if (wp == curwin) {
776          used_max_fill_curwin = true;
777        } else if (wp_other != NULL) {
778          used_max_fill_other = true;
779        }
780      }
781      check_topfill(wp, false);
782    }
783  }
784
785  if (wp_other != NULL && curwin->w_p_scb) {
786    if (used_max_fill_curwin) {
787      // The current window was set to use the maximum number of filler
788      // lines, may need to reduce them.
789      diff_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.
793      diff_set_topline(curwin, wp_other);
794    }
795  }
796}
797
798static void clear_diffin(diffin_T *din)
799{
800  if (din->din_fname == NULL) {
801    XFREE_CLEAR(din->din_mmfile.ptr);
802  } else {
803    os_remove(din->din_fname);
804  }
805}
806
807static void clear_diffout(diffout_T *dout)
808{
809  if (dout->dout_fname == NULL) {
810    ga_clear(&dout->dout_ga);
811  } else {
812    os_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{
824  if (end < 0) {
825    end = buf->b_ml.ml_line_count;
826  }
827
828  if (buf->b_ml.ml_flags & ML_EMPTY || end < start) {
829    m->ptr = NULL;
830    m->size = 0;
831    return OK;
832  }
833
834  size_t len = 0;
835
836  // xdiff requires one big block of memory with all the text.
837  for (linenr_T lnum = start; lnum <= end; lnum++) {
838    len += (size_t)ml_get_buf_len(buf, lnum) + 1;
839  }
840  char *ptr = xmalloc(len);
841  m->ptr = ptr;
842  m->size = (int)len;
843
844  len = 0;
845  for (linenr_T lnum = start; lnum <= end; lnum++) {
846    char *s = ml_get_buf(buf, lnum);
847    if (diff_flags & DIFF_ICASE) {
848      while (*s != NUL) {
849        int c;
850        int c_len = 1;
851        char cbuf[MB_MAXBYTES + 1];
852
853        if (*s == NL) {
854          c = NUL;
855        } else {
856          // xdiff doesn't support ignoring case, fold-case the text.
857          c = utf_ptr2char(s);
858          c_len = utf_char2len(c);
859          c = utf_fold(c);
860        }
861        const int orig_len = utfc_ptr2len(s);
862
863        if (utf_char2bytes(c, cbuf) != c_len) {
864          // TODO(Bram): handle byte length difference
865          // One example is Å (3 bytes) and å (2 bytes).
866          memmove(ptr + len, s, (size_t)orig_len);
867        } else {
868          memmove(ptr + len, cbuf, (size_t)c_len);
869          if (orig_len > c_len) {
870            // Copy remaining composing characters
871            memmove(ptr + len + c_len, s + c_len, (size_t)(orig_len - c_len));
872          }
873        }
874
875        s += orig_len;
876        len += (size_t)orig_len;
877      }
878    } else {
879      size_t slen = strlen(s);
880      memmove(ptr + len, s, slen);
881      // NUL is represented as NL; convert
882      memchrsub(ptr + len, NL, NUL, slen);
883      len += slen;
884    }
885    ptr[len++] = NL;
886  }
887  return 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{
900  if (din->din_fname == NULL) {
901    return 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.
908  if (frames_locked()) {
909    return FAIL;
910  }
911
912  if (end < 0) {
913    end = buf->b_ml.ml_line_count;
914  }
915
916  // Always use 'fileformat' set to "unix".
917  int save_ml_flags = buf->b_ml.ml_flags;
918  char *save_ff = buf->b_p_ff;
919  buf->b_p_ff = xstrdup("unix");
920  const 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.
923  cmdmod.cmod_flags |= CMOD_LOCKMARKS;
924  if (end < start) {
925    // The line range specifies a completely empty file.
926    end = start;
927    buf->b_ml.ml_flags |= ML_EMPTY;
928  }
929  int r = buf_write(buf, din->din_fname, NULL,
930                    start, end,
931                    NULL, false, false, false, true);
932  cmdmod.cmod_flags = save_cmod_flags;
933  free_string_option(buf->b_p_ff);
934  buf->b_p_ff = save_ff;
935  buf->b_ml.ml_flags = (buf->b_ml.ml_flags & ~ML_EMPTY) | (save_ml_flags & ML_EMPTY);
936  return r;
937}
938
939static int lnum_compare(const void *s1, const void *s2)
940{
941  linenr_T lnum1 = *(linenr_T *)s1;
942  linenr_T lnum2 = *(linenr_T *)s2;
943  if (lnum1 < lnum2) {
944    return -1;
945  }
946  if (lnum1 > lnum2) {
947    return 1;
948  }
949  return 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{
959  if (dio->dio_internal) {
960    ga_init(&dio->dio_diff.dout_ga, sizeof(diffhunk_T), 100);
961  } else {
962    // We need three temp file names.
963    dio->dio_orig.din_fname = vim_tempname();
964    dio->dio_new.din_fname = vim_tempname();
965    dio->dio_diff.dout_fname = vim_tempname();
966    if (dio->dio_orig.din_fname == NULL
967        || dio->dio_new.din_fname == NULL
968        || dio->dio_diff.dout_fname == NULL) {
969      goto theend;
970    }
971    // Check external diff is actually working.
972    if (check_external_diff(dio) == FAIL) {
973      goto theend;
974    }
975  }
976
977  // :diffupdate!
978  if (eap != NULL && eap->forceit) {
979    for (int idx_new = idx_orig; idx_new < DB_COUNT; idx_new++) {
980      buf_T *buf = curtab->tp_diffbuf[idx_new];
981      if (buf_valid(buf)) {
982        buf_check_timestamp(buf);
983      }
984    }
985  }
986
987  // Parse and sort diff anchors if enabled
988  int num_anchors = INT_MAX;
989  linenr_T anchors[DB_COUNT][MAX_DIFF_ANCHORS];
990  CLEAR_FIELD(anchors);
991  if (diff_flags & DIFF_ANCHOR) {
992    for (int idx = 0; idx < DB_COUNT; idx++) {
993      if (curtab->tp_diffbuf[idx] == NULL) {
994        continue;
995      }
996      int buf_num_anchors = 0;
997      if (parse_diffanchors(false,
998                            curtab->tp_diffbuf[idx],
999                            anchors[idx],
1000                            &buf_num_anchors) != OK) {
1001        emsg(_(e_failed_to_find_all_diff_anchors));
1002        num_anchors = 0;
1003        CLEAR_FIELD(anchors);
1004        break;
1005      }
1006      if (buf_num_anchors < num_anchors) {
1007        num_anchors = buf_num_anchors;
1008      }
1009
1010      if (buf_num_anchors > 0) {
1011        qsort((void *)anchors[idx],
1012              (size_t)buf_num_anchors,
1013              sizeof(linenr_T),
1014              lnum_compare);
1015      }
1016    }
1017  }
1018  if (num_anchors == INT_MAX) {
1019    num_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.
1026  for (int anchor_i = 0; anchor_i <= num_anchors; anchor_i++) {
1027    diff_T *orig_diff = NULL;
1028    if (anchor_i != 0) {
1029      orig_diff = curtab->tp_first_diff;
1030      curtab->tp_first_diff = NULL;
1031    }
1032    linenr_T lnum_start = (anchor_i == 0) ? 1 : anchors[idx_orig][anchor_i - 1];
1033    linenr_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.
1036    buf_T *buf = curtab->tp_diffbuf[idx_orig];
1037    if (diff_write(buf, &dio->dio_orig, lnum_start, lnum_end) == FAIL) {
1038      if (orig_diff != NULL) {
1039        // Clean up in-progress diff blocks
1040        curtab->tp_first_diff = orig_diff;
1041        diff_clear(curtab);
1042      }
1043      goto theend;
1044    }
1045
1046    // Make a difference between the first buffer and every other.
1047    for (int idx_new = idx_orig + 1; idx_new < DB_COUNT; idx_new++) {
1048      buf = curtab->tp_diffbuf[idx_new];
1049      if (buf == NULL || buf->b_ml.ml_mfp == NULL) {
1050        continue;  // skip buffer that isn't loaded
1051      }
1052      lnum_start = anchor_i == 0 ? 1 : anchors[idx_new][anchor_i - 1];
1053      lnum_end = anchor_i == num_anchors ? -1 : anchors[idx_new][anchor_i] - 1;
1054
1055      // Write the other buffer and diff with the first one.
1056      if (diff_write(buf, &dio->dio_new, lnum_start, lnum_end) == FAIL) {
1057        continue;
1058      }
1059      if (diff_file(dio) == FAIL) {
1060        continue;
1061      }
1062
1063      // Read the diff output and add each entry to the diff list.
1064      diff_read(idx_orig, idx_new, dio);
1065
1066      clear_diffin(&dio->dio_new);
1067      clear_diffout(&dio->dio_diff);
1068    }
1069    clear_diffin(&dio->dio_orig);
1070
1071    if (anchor_i != 0) {
1072      diff_finger_dp = NULL;      // df_lnum shifted, invalidate the finger
1073
1074      // Combine the new diff blocks with the existing ones
1075      for (diff_T *dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
1076        for (int idx = 0; idx < DB_COUNT; idx++) {
1077          if (anchors[idx][anchor_i - 1] > 0) {
1078            dp->df_lnum[idx] += anchors[idx][anchor_i - 1] - 1;
1079          }
1080        }
1081      }
1082      if (orig_diff != NULL) {
1083        diff_T *last_diff = orig_diff;
1084        while (last_diff->df_next != NULL) {
1085          last_diff = last_diff->df_next;
1086        }
1087        last_diff->df_next = curtab->tp_first_diff;
1088        curtab->tp_first_diff = orig_diff;
1089      }
1090    }
1091  }
1092
1093theend:
1094  xfree(dio->dio_orig.din_fname);
1095  xfree(dio->dio_new.din_fname);
1096  xfree(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)
1103  FUNC_ATTR_PURE
1104{
1105  return (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{
1117  if (diff_busy) {
1118    diff_need_update = true;
1119    return;
1120  }
1121
1122  int had_diffs = curtab->tp_first_diff != NULL;
1123
1124  // Delete all diffblocks.
1125  diff_clear(curtab);
1126  curtab->tp_diff_invalid = false;
1127
1128  // Use the first buffer as the original text.
1129  int idx_orig;
1130  for (idx_orig = 0; idx_orig < DB_COUNT; idx_orig++) {
1131    if (curtab->tp_diffbuf[idx_orig] != NULL) {
1132      break;
1133    }
1134  }
1135
1136  if (idx_orig == DB_COUNT) {
1137    goto theend;
1138  }
1139
1140  // Only need to do something when there is another buffer.
1141  int idx_new;
1142  for (idx_new = idx_orig + 1; idx_new < DB_COUNT; idx_new++) {
1143    if (curtab->tp_diffbuf[idx_new] != NULL) {
1144      break;
1145    }
1146  }
1147
1148  if (idx_new == DB_COUNT) {
1149    goto theend;
1150  }
1151
1152  // Only use the internal method if it did not fail for one of the buffers.
1153  diffio_T diffio = { 0 };
1154  diffio.dio_internal = diff_internal();
1155
1156  diff_try_update(&diffio, idx_orig, eap);
1157
1158  // force updating cursor position on screen
1159  curwin->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.
1164  if (had_diffs || curtab->tp_first_diff != NULL) {
1165    diff_redraw(true);
1166    apply_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.
1176  bool io_error = false;
1177  TriState ok = kFalse;
1178  while (true) {
1179    ok = kFalse;
1180    FILE *fd = os_fopen(diffio->dio_orig.din_fname, "w");
1181
1182    if (fd == NULL) {
1183      io_error = true;
1184    } else {
1185      if (fwrite("line1\n", 6, 1, fd) != 1) {
1186        io_error = true;
1187      }
1188      fclose(fd);
1189      fd = os_fopen(diffio->dio_new.din_fname, "w");
1190
1191      if (fd == NULL) {
1192        io_error = true;
1193      } else {
1194        if (fwrite("line2\n", 6, 1, fd) != 1) {
1195          io_error = true;
1196        }
1197        fclose(fd);
1198        fd = diff_file(diffio) == OK
1199             ? os_fopen(diffio->dio_diff.dout_fname, "r")
1200             : NULL;
1201
1202        if (fd == NULL) {
1203          io_error = true;
1204        } else {
1205          char linebuf[LBUFLEN];
1206
1207          while (true) {
1208            // For normal diff there must be a line that contains
1209            // "1c1".  For unified diff "@@ -1 +1 @@".
1210            if (vim_fgets(linebuf, LBUFLEN, fd)) {
1211              break;
1212            }
1213
1214            if (strncmp(linebuf, "1c1", 3) == 0
1215                || strncmp(linebuf, "@@ -1 +1 @@", 11) == 0) {
1216              ok = kTrue;
1217            }
1218          }
1219          fclose(fd);
1220        }
1221        os_remove(diffio->dio_diff.dout_fname);
1222        os_remove(diffio->dio_new.din_fname);
1223      }
1224      os_remove(diffio->dio_orig.din_fname);
1225    }
1226
1227    // When using 'diffexpr' break here.
1228    if (p_dex.type != kCallbackNone) {
1229      break;
1230    }
1231
1232    // If we checked if "-a" works already, break here.
1233    if (diff_a_works != kNone) {
1234      break;
1235    }
1236    diff_a_works = ok;
1237
1238    // If "-a" works break here, otherwise retry without "-a".
1239    if (ok) {
1240      break;
1241    }
1242  }
1243
1244  if (!ok) {
1245    if (io_error) {
1246      emsg(_("E810: Cannot read or write temp files"));
1247    }
1248    emsg(_("E97: Cannot create diffs"));
1249    diff_a_works = kNone;
1250    return FAIL;
1251  }
1252  return OK;
1253}
1254
1255/// Invoke the xdiff function.
1256static int diff_file_internal(diffio_T *diffio)
1257{
1258  xpparam_t param;
1259  xdemitconf_t emit_cfg;
1260  xdemitcb_t emit_cb;
1261
1262  CLEAR_FIELD(param);
1263  CLEAR_FIELD(emit_cfg);
1264  CLEAR_FIELD(emit_cb);
1265
1266  param.flags = (unsigned long)diff_algorithm;
1267
1268  if (diff_flags & DIFF_IWHITE) {
1269    param.flags |= XDF_IGNORE_WHITESPACE_CHANGE;
1270  }
1271  if (diff_flags & DIFF_IWHITEALL) {
1272    param.flags |= XDF_IGNORE_WHITESPACE;
1273  }
1274  if (diff_flags & DIFF_IWHITEEOL) {
1275    param.flags |= XDF_IGNORE_WHITESPACE_AT_EOL;
1276  }
1277  if (diff_flags & DIFF_IBLANK) {
1278    param.flags |= XDF_IGNORE_BLANK_LINES;
1279  }
1280
1281  emit_cfg.ctxlen = 0;  // don't need any diff_context here
1282  emit_cb.priv = &diffio->dio_diff;
1283  emit_cfg.hunk_func = xdiff_out;
1284  if (diffio->dio_orig.din_mmfile.size > MAX_XDIFF_SIZE
1285      || diffio->dio_new.din_mmfile.size > MAX_XDIFF_SIZE) {
1286    emsg(_(e_problem_creating_internal_diff));
1287    return FAIL;
1288  }
1289  if (xdl_diff(&diffio->dio_orig.din_mmfile,
1290               &diffio->dio_new.din_mmfile,
1291               &param, &emit_cfg, &emit_cb) < 0) {
1292    emsg(_(e_problem_creating_internal_diff));
1293    return FAIL;
1294  }
1295  return 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{
1305  char *tmp_orig = dio->dio_orig.din_fname;
1306  char *tmp_new = dio->dio_new.din_fname;
1307  char *tmp_diff = dio->dio_diff.dout_fname;
1308  if (p_dex.type != kCallbackNone) {
1309    // Use 'diffexpr' to generate the diff file.
1310    eval_diff(tmp_orig, tmp_new, tmp_diff);
1311    return OK;
1312  }
1313  // Use xdiff for generating the diff.
1314  if (dio->dio_internal) {
1315    return diff_file_internal(dio);
1316  }
1317
1318  const size_t len = (strlen(tmp_orig) + strlen(tmp_new) + strlen(tmp_diff)
1319                      + strlen(p_srr) + 27);
1320  char *const cmd = xmalloc(len);
1321
1322  // We don't want $DIFF_OPTIONS to get in the way.
1323  if (os_env_exists("DIFF_OPTIONS", true)) {
1324    os_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.
1330  vim_snprintf(cmd, len, "diff %s%s%s%s%s%s%s%s %s",
1331               diff_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 " : "",
1338               tmp_orig, tmp_new);
1339  append_redir(cmd, len, p_srr, tmp_diff);
1340  block_autocmds();  // Avoid ShellCmdPost stuff
1341  call_shell(cmd,
1342             kShellOptFilter | kShellOptSilent | kShellOptDoOut,
1343             NULL);
1344  unblock_autocmds();
1345  xfree(cmd);
1346  return 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{
1357  char *buf = NULL;
1358  win_T *old_curwin = curwin;
1359  char *newname = NULL;  // name of patched file buffer
1360  char *esc_name = NULL;
1361
1362#ifdef UNIX
1363  char *fullname = NULL;
1364#endif
1365
1366  // We need two temp file names.
1367  // Name of original temp file.
1368  char *tmp_orig = vim_tempname();
1369  // Name of patched temp file.
1370  char *tmp_new = vim_tempname();
1371
1372  if ((tmp_orig == NULL) || (tmp_new == NULL)) {
1373    goto theend;
1374  }
1375
1376  // Write the current buffer to "tmp_orig".
1377  if (buf_write(curbuf, tmp_orig, NULL,
1378                1, curbuf->b_ml.ml_line_count,
1379                NULL, false, false, false, true) == FAIL) {
1380    goto theend;
1381  }
1382
1383#ifdef UNIX
1384  // Get the absolute path of the patchfile, changing directory below.
1385  fullname = FullName_save(eap->arg, false);
1386  esc_name = vim_strsave_shellescape(fullname != NULL ? fullname : eap->arg, true, true);
1387#else
1388  esc_name = vim_strsave_shellescape(eap->arg, true, true);
1389#endif
1390  size_t buflen = strlen(tmp_orig) + strlen(esc_name) + strlen(tmp_new) + 16;
1391  buf = xmalloc(buflen);
1392
1393#ifdef UNIX
1394  char 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.
1400  if ((os_dirname(dirbuf, MAXPATHL) != OK)
1401      || (os_chdir(dirbuf) != 0)) {
1402    dirbuf[0] = NUL;
1403  } else {
1404    char *tempdir = vim_gettempdir();
1405    if (tempdir == NULL) {
1406      tempdir = "/tmp";
1407    }
1408    os_chdir(tempdir);
1409    shorten_fnames(true);
1410  }
1411#endif
1412
1413  if (p_pex.type != kCallbackNone) {
1414    // Use 'patchexpr' to generate the new file.
1415#ifdef UNIX
1416    eval_patch(tmp_orig, (fullname != NULL ? fullname : eap->arg), tmp_new);
1417#else
1418    eval_patch(tmp_orig, eap->arg, tmp_new);
1419#endif
1420  } else {
1421    // Build the patch command and execute it. Ignore errors.
1422    vim_snprintf(buf, buflen, "patch -o %s %s < %s",
1423                 tmp_new, tmp_orig, esc_name);
1424    block_autocmds();  // Avoid ShellCmdPost stuff
1425    call_shell(buf, kShellOptFilter, NULL);
1426    unblock_autocmds();
1427  }
1428
1429#ifdef UNIX
1430  if (dirbuf[0] != NUL) {
1431    if (os_chdir(dirbuf) != 0) {
1432      emsg(_(e_prev_dir));
1433    }
1434    shorten_fnames(true);
1435  }
1436#endif
1437
1438  // Delete any .orig or .rej file created.
1439  STRCPY(buf, tmp_new);
1440  strcat(buf, ".orig");
1441  os_remove(buf);
1442  STRCPY(buf, tmp_new);
1443  strcat(buf, ".rej");
1444  os_remove(buf);
1445
1446  // Only continue if the output file was created.
1447  FileInfo file_info;
1448  bool info_ok = os_fileinfo(tmp_new, &file_info);
1449  uint64_t filesize = os_fileinfo_size(&file_info);
1450  if (!info_ok || filesize == 0) {
1451    emsg(_("E816: Cannot read patch output"));
1452  } else {
1453    if (curbuf->b_fname != NULL) {
1454      newname = xstrnsave(curbuf->b_fname, strlen(curbuf->b_fname) + 4);
1455      strcat(newname, ".new");
1456    }
1457
1458    // don't use a new tab page, each tab page has its own diffs
1459    cmdmod.cmod_tab = 0;
1460
1461    if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL) {
1462      // Pretend it was a ":split fname" command
1463      eap->cmdidx = CMD_split;
1464      eap->arg = tmp_new;
1465      do_exedit(eap, old_curwin);
1466
1467      // check that split worked and editing tmp_new
1468      if ((curwin != old_curwin) && win_valid(old_curwin)) {
1469        // Set 'diff', 'scrollbind' on and 'wrap' off.
1470        diff_win_options(curwin, true);
1471        diff_win_options(old_curwin, true);
1472
1473        if (newname != NULL) {
1474          // do a ":file filename.new" on the patched buffer
1475          eap->arg = newname;
1476          ex_file(eap);
1477
1478          // Do filetype detection with the new name.
1479          if (augroup_exists("filetypedetect")) {
1480            do_cmdline_cmd(":doau filetypedetect BufRead");
1481          }
1482        }
1483      }
1484    }
1485  }
1486
1487theend:
1488  if (tmp_orig != NULL) {
1489    os_remove(tmp_orig);
1490  }
1491  xfree(tmp_orig);
1492
1493  if (tmp_new != NULL) {
1494    os_remove(tmp_new);
1495  }
1496  xfree(tmp_new);
1497  xfree(newname);
1498  xfree(buf);
1499#ifdef UNIX
1500  xfree(fullname);
1501#endif
1502  xfree(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{
1510  win_T *old_curwin = curwin;
1511  bufref_T old_curbuf;
1512  set_bufref(&old_curbuf, curbuf);
1513
1514  // Need to compute w_fraction when no redraw happened yet.
1515  validate_cursor(curwin);
1516  set_fraction(curwin);
1517
1518  // don't use a new tab page, each tab page has its own diffs
1519  cmdmod.cmod_tab = 0;
1520
1521  if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) == FAIL) {
1522    return;
1523  }
1524
1525  // Pretend it was a ":split fname" command
1526  eap->cmdidx = CMD_split;
1527  curwin->w_p_diff = true;
1528  do_exedit(eap, old_curwin);
1529
1530  if (curwin == old_curwin) {  // split didn't work
1531    return;
1532  }
1533
1534  // Set 'diff', 'scrollbind' on and 'wrap' off.
1535  diff_win_options(curwin, true);
1536  if (win_valid(old_curwin)) {
1537    diff_win_options(old_curwin, true);
1538
1539    if (bufref_valid(&old_curbuf)) {
1540      // Move the cursor position to that of the old window.
1541      curwin->w_cursor.lnum = diff_get_corresponding_line(old_curbuf.br_buf,
1542                                                          old_curwin->w_cursor.lnum);
1543    }
1544  }
1545  // Now that lines are folded scroll to show the cursor at the same
1546  // relative position.
1547  scroll_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.
1554  diff_win_options(curwin, true);
1555}
1556
1557static void set_diff_option(win_T *wp, bool value)
1558{
1559  win_T *old_curwin = curwin;
1560
1561  curwin = wp;
1562  curbuf = curwin->w_buffer;
1563  curbuf->b_ro_locked++;
1564  set_option_value_give_err(kOptDiff, BOOLEAN_OBJ(value), OPT_LOCAL);
1565  curbuf->b_ro_locked--;
1566  curwin = old_curwin;
1567  curbuf = 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{
1575  win_T *old_curwin = curwin;
1576
1577  // close the manually opened folds
1578  curwin = wp;
1579  newFoldLevel();
1580  curwin = old_curwin;
1581
1582  // Use 'scrollbind' and 'cursorbind' when available
1583  if (!wp->w_p_diff) {
1584    wp->w_p_scb_save = wp->w_p_scb;
1585  }
1586  wp->w_p_scb = true;
1587
1588  if (!wp->w_p_diff) {
1589    wp->w_p_crb_save = wp->w_p_crb;
1590  }
1591  wp->w_p_crb = true;
1592  if (!(diff_flags & DIFF_FOLLOWWRAP)) {
1593    if (!wp->w_p_diff) {
1594      wp->w_p_wrap_save = wp->w_p_wrap;
1595    }
1596    wp->w_p_wrap = false;
1597    wp->w_skipcol = 0;
1598  }
1599
1600  if (!wp->w_p_diff) {
1601    if (wp->w_p_diff_saved) {
1602      free_string_option(wp->w_p_fdm_save);
1603    }
1604    wp->w_p_fdm_save = xstrdup(wp->w_p_fdm);
1605  }
1606  set_option_direct_for(kOptFoldmethod, STATIC_CSTR_AS_OBJ("diff"), OPT_LOCAL, 0,
1607                        kOptScopeWin, wp);
1608
1609  if (!wp->w_p_diff) {
1610    wp->w_p_fen_save = wp->w_p_fen;
1611    wp->w_p_fdl_save = wp->w_p_fdl;
1612
1613    if (wp->w_p_diff_saved) {
1614      free_string_option(wp->w_p_fdc_save);
1615    }
1616    wp->w_p_fdc_save = xstrdup(wp->w_p_fdc);
1617  }
1618  free_string_option(wp->w_p_fdc);
1619  wp->w_p_fdc = xstrdup("2");
1620  assert(diff_foldcolumn >= 0 && diff_foldcolumn <= 9);
1621  snprintf(wp->w_p_fdc, strlen(wp->w_p_fdc) + 1, "%d", diff_foldcolumn);
1622  wp->w_p_fen = true;
1623  wp->w_p_fdl = 0;
1624  foldUpdateAll(wp);
1625
1626  // make sure topline is not halfway through a fold
1627  changed_window_setting(wp);
1628  if (vim_strchr(p_sbo, 'h') == NULL) {
1629    do_cmdline_cmd("set sbo+=hor");
1630  }
1631
1632  // Save the current values, to be restored in ex_diffoff().
1633  wp->w_p_diff_saved = true;
1634
1635  set_diff_option(wp, true);
1636
1637  if (addbuf) {
1638    diff_buf_add(wp->w_buffer);
1639  }
1640  redraw_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{
1649  bool diffwin = false;
1650
1651  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
1652    if (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.
1656      set_diff_option(wp, false);
1657
1658      if (wp->w_p_diff_saved) {
1659        if (wp->w_p_scb) {
1660          wp->w_p_scb = wp->w_p_scb_save;
1661        }
1662
1663        if (wp->w_p_crb) {
1664          wp->w_p_crb = wp->w_p_crb_save;
1665        }
1666        if (!(diff_flags & DIFF_FOLLOWWRAP)) {
1667          if (!wp->w_p_wrap && wp->w_p_wrap_save) {
1668            wp->w_p_wrap = true;
1669            wp->w_leftcol = 0;
1670          }
1671        }
1672        free_string_option(wp->w_p_fdm);
1673        wp->w_p_fdm = xstrdup(*wp->w_p_fdm_save ? wp->w_p_fdm_save : "manual");
1674        free_string_option(wp->w_p_fdc);
1675        wp->w_p_fdc = xstrdup(*wp->w_p_fdc_save ? wp->w_p_fdc_save : "0");
1676
1677        if (wp->w_p_fdl == 0) {
1678          wp->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.
1682        if (wp->w_p_fen) {
1683          wp->w_p_fen = foldmethodIsManual(wp) ? false : wp->w_p_fen_save;
1684        }
1685
1686        foldUpdateAll(wp);
1687      }
1688      // remove filler lines
1689      wp->w_topfill = 0;
1690
1691      // make sure topline is not halfway a fold and cursor is
1692      // invalidated
1693      changed_window_setting(wp);
1694
1695      // Note: 'sbo' is not restored, it's a global option.
1696      diff_buf_adjust(wp);
1697    }
1698    diffwin |= wp->w_p_diff;
1699  }
1700
1701  // Also remove hidden buffers from the list.
1702  if (eap->forceit) {
1703    diff_buf_clear();
1704  }
1705
1706  if (!diffwin) {
1707    diff_need_update = false;
1708    curtab->tp_diff_invalid = false;
1709    curtab->tp_diff_update = false;
1710    diff_clear(curtab);
1711  }
1712
1713  // Remove "hor" from 'scrollopt' if there are no diff windows left.
1714  if (!diffwin && (vim_strchr(p_sbo, 'h') != NULL)) {
1715    do_cmdline_cmd("set sbo-=hor");
1716  }
1717}
1718
1719static bool extract_hunk_internal(diffout_T *dout, diffhunk_T *hunk, int *line_idx)
1720{
1721  bool eof = *line_idx >= dout->dout_ga.ga_len;
1722  if (!eof) {
1723    *hunk = ((diffhunk_T *)dout->dout_ga.ga_data)[(*line_idx)++];
1724  }
1725  return 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{
1731  while (true) {
1732    char line[LBUFLEN];  // only need to hold the diff line
1733    if (vim_fgets(line, LBUFLEN, fd)) {
1734      return true;  // end of file
1735    }
1736
1737    if (*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 @@
1748      if (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.
1761        continue;
1762      }
1763    }
1764
1765    if (*diffstyle == DIFF_ED) {
1766      if (!isdigit((uint8_t)(*line))) {
1767        continue;   // not the start of a diff block
1768      }
1769      if (parse_diff_ed(line, hunk) == FAIL) {
1770        continue;
1771      }
1772    } else {
1773      assert(*diffstyle == DIFF_UNIFIED);
1774      if (strncmp(line, "@@ ", 3) != 0) {
1775        continue;   // not the start of a diff block
1776      }
1777      if (parse_diff_unified(line, hunk) == FAIL) {
1778        continue;
1779      }
1780    }
1781
1782    // Successfully parsed diff output, can return
1783    return false;
1784  }
1785}
1786
1787static void process_hunk(diff_T **dpp, diff_T **dprevp, int idx_orig, int idx_new, diffhunk_T *hunk,
1788                         bool *notsetp)
1789{
1790  diff_T *dp = *dpp;
1791  diff_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.
1795  while (dp != NULL
1796         && hunk->lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig]) {
1797    if (*notsetp) {
1798      diff_copy_entry(dprev, dp, idx_orig, idx_new);
1799    }
1800    dprev = dp;
1801    dp = dp->df_next;
1802    *notsetp = true;
1803  }
1804
1805  if ((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.
1810    diff_T *dpl;
1811    for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next) {
1812      if (hunk->lnum_orig + hunk->count_orig < dpl->df_next->df_lnum[idx_orig]) {
1813        break;
1814      }
1815    }
1816
1817    // If the newly found block starts before the old one, set the
1818    // start back a number of lines.
1819    linenr_T off = dp->df_lnum[idx_orig] - hunk->lnum_orig;
1820
1821    if (off > 0) {
1822      for (int i = idx_orig; i < idx_new; i++) {
1823        if (curtab->tp_diffbuf[i] != NULL) {
1824          dp->df_lnum[i] -= off;
1825          dp->df_count[i] += off;
1826        }
1827      }
1828      dp->df_lnum[idx_new] = hunk->lnum_new;
1829      dp->df_count[idx_new] = (linenr_T)hunk->count_new;
1830    } else if (*notsetp) {
1831      // new block inside existing one, adjust new block
1832      dp->df_lnum[idx_new] = hunk->lnum_new + off;
1833      dp->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
1841      int orig_size_in_dp = MIN(hunk->count_orig,
1842                                dp->df_lnum[idx_orig] +
1843                                dp->df_count[idx_orig] - hunk->lnum_orig);
1844      int size_diff = hunk->count_new - orig_size_in_dp;
1845      dp->df_count[idx_new] += size_diff;
1846
1847      // grow existing block to include the overlap completely
1848      off = hunk->lnum_new + hunk->count_new
1849            - (dp->df_lnum[idx_new] + dp->df_count[idx_new]);
1850      if (off > 0) {
1851        dp->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.
1857    off = (hunk->lnum_orig + (linenr_T)hunk->count_orig)
1858          - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]);
1859
1860    if (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.
1863      if (*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.
1868        dp->df_count[idx_new] += -off;
1869      }
1870      off = 0;
1871    }
1872
1873    for (int i = idx_orig; i < idx_new; i++) {
1874      if (curtab->tp_diffbuf[i] != NULL) {
1875        dp->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.
1881    diff_T *dn = dp->df_next;
1882    dp->df_next = dpl->df_next;
1883
1884    while (dn != dp->df_next) {
1885      dpl = dn->df_next;
1886      clear_diffblock(dn);
1887      dn = dpl;
1888    }
1889  } else {
1890    // Allocate a new diffblock.
1891    dp = diff_alloc_new(curtab, dprev, dp);
1892
1893    dp->df_lnum[idx_orig] = hunk->lnum_orig;
1894    dp->df_count[idx_orig] = (linenr_T)hunk->count_orig;
1895    dp->df_lnum[idx_new] = hunk->lnum_new;
1896    dp->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.
1901    for (int i = idx_orig + 1; i < idx_new; i++) {
1902      if (curtab->tp_diffbuf[i] != NULL) {
1903        diff_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{
1919  FILE *fd = NULL;
1920  int line_hunk_idx = 0;  // line or hunk index
1921  diff_T *dprev = NULL;
1922  diff_T *dp = curtab->tp_first_diff;
1923  diffout_T *dout = &dio->dio_diff;
1924  bool notset = true;  // block "*dp" not set yet
1925  diffstyle_T diffstyle = DIFF_NONE;
1926
1927  if (!dio->dio_internal) {
1928    fd = os_fopen(dout->dout_fname, "r");
1929    if (fd == NULL) {
1930      emsg(_("E98: Cannot read diff output"));
1931      return;
1932    }
1933  }
1934
1935  while (true) {
1936    diffhunk_T hunk = { 0 };
1937    bool eof = dio->dio_internal
1938               ? extract_hunk_internal(dout, &hunk, &line_hunk_idx)
1939               : extract_hunk(fd, &hunk, &diffstyle);
1940
1941    if (eof) {
1942      break;
1943    }
1944
1945    process_hunk(&dp, &dprev, idx_orig, idx_new, &hunk, &notset);
1946  }
1947
1948  // for remaining diff blocks orig and new are equal
1949  while (dp != NULL) {
1950    if (notset) {
1951      diff_copy_entry(dprev, dp, idx_orig, idx_new);
1952    }
1953    dprev = dp;
1954    dp = dp->df_next;
1955    notset = true;
1956  }
1957
1958  if (fd != NULL) {
1959    fclose(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{
1971  linenr_T off;
1972
1973  if (dprev == NULL) {
1974    off = 0;
1975  } else {
1976    off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig])
1977          - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]);
1978  }
1979  dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off;
1980  dp->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)
1987  FUNC_ATTR_NONNULL_ALL
1988{
1989  diff_T *next_p;
1990  for (diff_T *p = tp->tp_first_diff; p != NULL; p = next_p) {
1991    next_p = p->df_next;
1992    clear_diffblock(p);
1993  }
1994  tp->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{
2000  if (!(diff_flags & DIFF_LINEMATCH)) {
2001    return false;
2002  }
2003  // are there more than three diff buffers?
2004  int tsize = 0;
2005  for (int i = 0; i < DB_COUNT; i++) {
2006    if (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
2010      if (dp->df_count[i] < 0) {
2011        return false;
2012      }
2013      tsize += dp->df_count[i];
2014    }
2015  }
2016  // avoid allocating a huge array because it will lag
2017  return tsize <= linematch_lines;
2018}
2019
2020static int get_max_diff_length(const diff_T *dp)
2021{
2022  int maxlength = 0;
2023  for (int k = 0; k < DB_COUNT; k++) {
2024    if (curtab->tp_diffbuf[k] != NULL) {
2025      if (dp->df_count[k] > maxlength) {
2026        maxlength = dp->df_count[k];
2027      }
2028    }
2029  }
2030  return 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,
2037                                int topline)
2038{
2039  diff_T *topdiff = NULL;
2040  diff_T *localtopdiff = NULL;
2041  int topdiffchange = 0;
2042
2043  for (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
2046    if (!localtopdiff || topdiffchange) {
2047      localtopdiff = topdiff;
2048      topdiffchange = 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
2053    if (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
2057      if ((*thistopdiff) == NULL) {
2058        (*thistopdiff) = localtopdiff;
2059      }
2060    }
2061
2062    // check if the next set of overlapping diff blocks is next
2063    if (!(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
2067      topdiffchange = 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
2071      if (*thistopdiff) {
2072        (*next_adjacent_blocks) = topdiff->df_next;
2073        break;
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
2081                                          int from_topline, const int from_topfill, int *topfill,
2082                                          linenr_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.
2088  diff_T *thistopdiff = NULL;
2089  diff_T *next_adjacent_blocks = NULL;
2090  int virtual_lines_passed = 0;
2091
2092  find_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
2098  diff_T *curdif = thistopdiff;
2099  while (curdif && (curdif->df_lnum[fromidx] + curdif->df_count[fromidx])
2100         <= from_topline) {
2101    virtual_lines_passed += get_max_diff_length(curdif);
2102
2103    curdif = curdif->df_next;
2104  }
2105
2106  if (curdif != next_adjacent_blocks) {
2107    virtual_lines_passed += from_topline - curdif->df_lnum[fromidx];
2108  }
2109  virtual_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
2114  if (virtual_lines_passed < 0) {
2115    virtual_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
2120  int curlinenum_to
2121    = thistopdiff != NULL  // this should not be null, but just for safety
2122      ? thistopdiff->df_lnum[toidx] : 1;
2123
2124  int virt_lines_left = virtual_lines_passed;
2125  curdif = thistopdiff;
2126  while (virt_lines_left > 0 && curdif != NULL && curdif != next_adjacent_blocks) {
2127    curlinenum_to += MIN(virt_lines_left, curdif->df_count[toidx]);
2128    virt_lines_left -= MIN(virt_lines_left, get_max_diff_length(curdif));
2129    curdif = 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
2134  int max_virt_lines = 0;
2135  for (diff_T *dp = thistopdiff; dp != NULL; dp = dp->df_next) {
2136    if (dp->df_lnum[toidx] + dp->df_count[toidx] <= curlinenum_to) {
2137      max_virt_lines += get_max_diff_length(dp);
2138    } else {
2139      if (dp->df_lnum[toidx] <= curlinenum_to) {
2140        max_virt_lines += curlinenum_to - dp->df_lnum[toidx];
2141      }
2142      break;
2143    }
2144  }
2145
2146  if (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
2158  int line_numbers[DB_COUNT];
2159  int outputmap[DB_COUNT];
2160  size_t ndiffs = 0;
2161  for (int i = 0; i < DB_COUNT; i++) {
2162    if (curtab->tp_diffbuf[i] != NULL) {
2163      line_numbers[i] = dp->df_lnum[i];
2164      dp->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
2169      outputmap[ndiffs] = i;
2170      ndiffs++;
2171    }
2172  }
2173
2174  // write the diffs starting with the current diff block
2175  diff_T *dp_s = dp;
2176  for (size_t i = 0; i < decisions_length; i++) {
2177    // Don't allocate on first iter since we can reuse the initial diffblock
2178    if (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
2181      dp_s = diff_alloc_new(curtab, dp_s, dp_s->df_next);
2182      dp_s->is_linematched = true;
2183      for (int j = 0; j < DB_COUNT; j++) {
2184        if (curtab->tp_diffbuf[j] != NULL) {
2185          dp_s->df_lnum[j] = line_numbers[j];
2186          dp_s->df_count[j] = 0;
2187        }
2188      }
2189    }
2190    for (size_t j = 0; j < ndiffs; j++) {
2191      if (decisions[i] & (1 << j)) {
2192        // will need to use the map here
2193        dp_s->df_count[outputmap[j]]++;
2194        line_numbers[outputmap[j]]++;
2195      }
2196    }
2197  }
2198  dp->is_linematched = true;
2199}
2200
2201static void run_linematch_algorithm(diff_T *dp)
2202{
2203  // define buffers for diff algorithm
2204  mmfile_t diffbufs_mm[DB_COUNT];
2205  const mmfile_t *diffbufs[DB_COUNT];
2206  int diff_length[DB_COUNT];
2207  size_t ndiffs = 0;
2208  for (int i = 0; i < DB_COUNT; i++) {
2209    if (curtab->tp_diffbuf[i] != NULL) {
2210      if (dp->df_count[i] > 0) {
2211        // write the contents of the entire buffer to
2212        // diffbufs_mm[diffbuffers_count]
2213        diff_write_buffer(curtab->tp_diffbuf[i], &diffbufs_mm[ndiffs],
2214                          dp->df_lnum[i], dp->df_lnum[i] + dp->df_count[i] - 1);
2215      } else {
2216        diffbufs_mm[ndiffs].size = 0;
2217        diffbufs_mm[ndiffs].ptr = NULL;
2218      }
2219
2220      diffbufs[ndiffs] = &diffbufs_mm[ndiffs];
2221
2222      // keep track of the length of this diff block to pass it to the linematch
2223      // algorithm
2224      diff_length[ndiffs] = dp->df_count[i];
2225
2226      // increment the amount of diff buffers we are passing to the algorithm
2227      ndiffs++;
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)
2233  int *decisions = NULL;
2234  const bool iwhite = (diff_flags & (DIFF_IWHITEALL | DIFF_IWHITE)) > 0;
2235  size_t decisions_length = linematch_nbuffers(diffbufs, diff_length, ndiffs, &decisions, iwhite);
2236
2237  for (size_t i = 0; i < ndiffs; i++) {
2238    XFREE_CLEAR(diffbufs_mm[i].ptr);
2239  }
2240
2241  apply_linematch_results(dp, decisions_length, decisions);
2242
2243  xfree(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{
2269  buf_T *buf = wp->w_buffer;
2270
2271  if (linestatus != NULL) {
2272    *linestatus = 0;
2273  }
2274
2275  if (curtab->tp_diff_invalid) {
2276    // update after a big change
2277    ex_diffupdate(NULL);
2278  }
2279
2280  // no diffs at all
2281  if ((curtab->tp_first_diff == NULL) || !wp->w_p_diff) {
2282    return 0;
2283  }
2284
2285  // safety check: "lnum" must be a buffer line
2286  if ((lnum < 1) || (lnum > buf->b_ml.ml_line_count + 1)) {
2287    return 0;
2288  }
2289
2290  int idx = diff_buf_idx(buf, curtab);  // index in tp_diffbuf[] for this buffer
2291
2292  if (idx == DB_COUNT) {
2293    // no diffs for buffer "buf"
2294    return 0;
2295  }
2296
2297  // A closed fold never has filler lines.
2298  if (hasFolding(wp, lnum, NULL, NULL) || decor_conceal_line(wp, lnum - 1, false)) {
2299    return 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.
2304  diff_T *le = NULL;             // last block with df_lnum[idx] <= lnum
2305  diff_T *dp;
2306  for (dp = diff_scan_start(curtab, idx, lnum); dp != NULL; dp = dp->df_next) {
2307    if (dp->df_lnum[idx] <= lnum) {
2308      le = dp;
2309    }
2310    if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) {
2311      break;
2312    }
2313  }
2314  diff_scan_remember(curtab, idx, lnum, le);
2315  if ((dp == NULL) || (lnum < dp->df_lnum[idx])) {
2316    return 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.
2322  if (lnum >= wp->w_topline && lnum < wp->w_botline
2323      && !dp->is_linematched && diff_linematch(dp)
2324      && diff_check_sanity(curtab, dp)) {
2325    run_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.
2330  int num_fill = 0;
2331  while (lnum == dp->df_lnum[idx] + dp->df_count[idx]) {
2332    // Only calculate fill lines if 'diffopt' contains "filler". Otherwise
2333    // returns 0 filler lines.
2334    if (diff_flags & DIFF_FILLER) {
2335      int maxcount = get_max_diff_length(dp);
2336      num_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.
2345    if (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]) {
2348      dp = dp->df_next;
2349    } else {
2350      break;
2351    }
2352  }
2353
2354  if (lnum < dp->df_lnum[idx] + dp->df_count[idx]) {
2355    bool 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.
2360    bool cmp = false;
2361
2362    for (int i = 0; i < DB_COUNT; i++) {
2363      if ((i != idx) && (curtab->tp_diffbuf[i] != NULL)) {
2364        if (dp->df_count[i] == 0) {
2365          zero = true;
2366        } else {
2367          if (dp->df_count[i] != dp->df_count[idx]) {
2368            if (linestatus) {
2369              *linestatus = -1;  // nr of lines changed.
2370            }
2371            return num_fill;
2372          }
2373          cmp = true;
2374        }
2375      }
2376    }
2377
2378    if (cmp) {
2379      // Compare all lines.  If they are equal the lines were inserted
2380      // in some buffers, deleted in others, but not changed.
2381      for (int i = 0; i < DB_COUNT; i++) {
2382        if ((i != idx)
2383            && (curtab->tp_diffbuf[i] != NULL)
2384            && (dp->df_count[i] != 0)) {
2385          if (!diff_equal_entry(dp, idx, i)) {
2386            if (linestatus) {
2387              *linestatus = -1;
2388            }
2389            return 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.
2400    if (!zero) {
2401      return num_fill;
2402    }
2403    if (linestatus) {
2404      *linestatus = -2;
2405    }
2406    return num_fill;
2407  }
2408  return 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
2415  if (!(diff_flags & DIFF_FILLER)) {
2416    return 0;
2417  }
2418  int n = diff_check_with_linestatus(wp, lnum, NULL);
2419  return 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)
2430  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
2431{
2432  if (dp->df_count[idx1] != dp->df_count[idx2]) {
2433    return false;
2434  }
2435
2436  if (diff_check_sanity(curtab, dp) == FAIL) {
2437    return false;
2438  }
2439
2440  for (int i = 0; i < dp->df_count[idx1]; i++) {
2441    char *line = xstrdup(ml_get_buf(curtab->tp_diffbuf[idx1], dp->df_lnum[idx1] + i));
2442
2443    int cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2], dp->df_lnum[idx2] + i));
2444    xfree(line);
2445
2446    if (cmp != 0) {
2447      return false;
2448    }
2449  }
2450  return 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{
2457  const int l = utfc_ptr2len(p1);
2458
2459  if (l != utfc_ptr2len(p2)) {
2460    return false;
2461  }
2462  if (l > 1) {
2463    if (strncmp(p1, p2, (size_t)l) != 0
2464        && (!(diff_flags & DIFF_ICASE)
2465            || utf_fold(utf_ptr2char(p1)) != utf_fold(utf_ptr2char(p2)))) {
2466      return false;
2467    }
2468    *len = l;
2469  } else {
2470    if ((*p1 != *p2)
2471        && (!(diff_flags & DIFF_ICASE)
2472            || TOLOWER_LOC((uint8_t)(*p1)) != TOLOWER_LOC((uint8_t)(*p2)))) {
2473      return false;
2474    }
2475    *len = 1;
2476  }
2477  return 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{
2489  if ((diff_flags & DIFF_IBLANK)
2490      && (*skipwhite(s1) == NUL || *skipwhite(s2) == NUL)) {
2491    return 0;
2492  }
2493
2494  if ((diff_flags & (DIFF_ICASE | ALL_WHITE_DIFF)) == 0) {
2495    return strcmp(s1, s2);
2496  }
2497
2498  if ((diff_flags & DIFF_ICASE) && !(diff_flags & ALL_WHITE_DIFF)) {
2499    return mb_stricmp(s1, s2);
2500  }
2501
2502  char *p1 = s1;
2503  char *p2 = s2;
2504
2505  // Ignore white space changes and possibly ignore case.
2506  while (*p1 != NUL && *p2 != NUL) {
2507    if (((diff_flags & DIFF_IWHITE)
2508         && ascii_iswhite(*p1) && ascii_iswhite(*p2))
2509        || ((diff_flags & DIFF_IWHITEALL)
2510            && (ascii_iswhite(*p1) || ascii_iswhite(*p2)))) {
2511      p1 = skipwhite(p1);
2512      p2 = skipwhite(p2);
2513    } else {
2514      int l;
2515      if (!diff_equal_char(p1, p2, &l)) {
2516        break;
2517      }
2518      p1 += l;
2519      p2 += l;
2520    }
2521  }
2522
2523  // Ignore trailing white space.
2524  p1 = skipwhite(p1);
2525  p2 = skipwhite(p2);
2526
2527  if ((*p1 != NUL) || (*p2 != NUL)) {
2528    return 1;
2529  }
2530  return 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{
2540  buf_T *frombuf = fromwin->w_buffer;
2541
2542  int fromidx = diff_buf_idx(frombuf, curtab);
2543  if (fromidx == DB_COUNT) {
2544    // safety check
2545    return;
2546  }
2547
2548  if (curtab->tp_diff_invalid) {
2549    // update after a big change
2550    ex_diffupdate(NULL);
2551  }
2552  linenr_T lnum = fromwin->w_topline;
2553  towin->w_topfill = 0;
2554
2555  // search for a change that includes "lnum" in the list of diffblocks.
2556  diff_T *dp;
2557  for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
2558    if (lnum <= dp->df_lnum[fromidx] + dp->df_count[fromidx]) {
2559      break;
2560    }
2561  }
2562
2563  if (dp == NULL) {
2564    // After last change, compute topline relative to end of file; no
2565    // filler lines.
2566    towin->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".
2570    int toidx = diff_buf_idx(towin->w_buffer, curtab);
2571
2572    if (toidx == DB_COUNT) {
2573      // safety check
2574      return;
2575    }
2576    towin->w_topline = lnum + (dp->df_lnum[toidx] - dp->df_lnum[fromidx]);
2577
2578    if (lnum >= dp->df_lnum[fromidx]) {
2579      calculate_topfill_and_topline(fromidx, toidx,
2580                                    fromwin->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)
2586  towin->w_botfill = false;
2587
2588  if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count) {
2589    towin->w_topline = towin->w_buffer->b_ml.ml_line_count;
2590    towin->w_botfill = true;
2591  }
2592
2593  if (towin->w_topline < 1) {
2594    towin->w_topline = 1;
2595    towin->w_topfill = 0;
2596  }
2597
2598  // When w_topline changes need to recompute w_botline and cursor position
2599  invalidate_botline_win(towin);
2600  changed_line_abv_curs_win(towin);
2601
2602  check_topfill(towin, false);
2603  hasFolding(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{
2610  int i;
2611  char *dia = (*buf->b_p_dia == NUL) ? p_dia : buf->b_p_dia;
2612
2613  buf_T *orig_curbuf = curbuf;
2614  win_T *orig_curwin = curwin;
2615
2616  win_T *bufwin = NULL;
2617  if (check_only) {
2618    bufwin = 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 `''`.
2622    for (bufwin = firstwin; bufwin != NULL; bufwin = bufwin->w_next) {
2623      if (bufwin->w_buffer == buf && bufwin->w_p_diff) {
2624        break;
2625      }
2626    }
2627    if (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.
2632      emsg(_(e_diff_anchors_with_hidden_windows));
2633      return FAIL;
2634    }
2635  }
2636
2637  for (i = 0; i < MAX_DIFF_ANCHORS && *dia != NUL; i++) {
2638    if (*dia == ',') {  // don't allow empty values
2639      return FAIL;
2640    }
2641
2642    curbuf = buf;
2643    curwin = bufwin;
2644    const char *errormsg = NULL;
2645    linenr_T lnum = get_address(NULL, &dia, ADDR_LINES, check_only, true, false, 1, &errormsg);
2646    curbuf = orig_curbuf;
2647    curwin = orig_curwin;
2648
2649    if (errormsg != NULL) {
2650      emsg(errormsg);
2651    }
2652    if (dia == NULL) {  // error detected
2653      return FAIL;
2654    }
2655    if (*dia != ',' && *dia != NUL) {
2656      return FAIL;
2657    }
2658
2659    if (!check_only
2660        && (lnum == MAXLNUM || lnum <= 0 || lnum > buf->b_ml.ml_line_count + 1)) {
2661      emsg(_(e_invrange));
2662      return FAIL;
2663    }
2664
2665    if (anchors != NULL) {
2666      anchors[i] = lnum;
2667    }
2668
2669    if (*dia == ',') {
2670      dia++;
2671    }
2672  }
2673  if (i == MAX_DIFF_ANCHORS && *dia != NUL) {
2674    semsg(_(e_cannot_have_more_than_nr_diff_anchors), MAX_DIFF_ANCHORS);
2675    return FAIL;
2676  }
2677  if (num_anchors != NULL) {
2678    *num_anchors = i;
2679  }
2680  return OK;
2681}
2682
2683/// This is called when 'diffanchors' is changed.
2684int diffanchors_changed(bool buflocal)
2685{
2686  int result = parse_diffanchors(true, curbuf, NULL, NULL);
2687  if (result == OK && (diff_flags & DIFF_ANCHOR)) {
2688    FOR_ALL_TABS(tp) {
2689      if (!buflocal) {
2690        tp->tp_diff_invalid = true;
2691      } else {
2692        for (int idx = 0; idx < DB_COUNT; idx++) {
2693          if (tp->tp_diffbuf[idx] == curbuf) {
2694            tp->tp_diff_invalid = true;
2695            break;
2696          }
2697        }
2698      }
2699    }
2700  }
2701  return 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{
2709  OptKeyDict_dip *v = opt_keyset(p_dip, kOptDiffopt, NULL);
2710
2711  int 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);
2718  if (HAS_KEY(v, dip, linematch)) {
2719    flags |= DIFF_LINEMATCH | DIFF_FILLER;  // linematch needs filler
2720  }
2721  if (HAS_KEY(v, dip, inline_)) {
2722    flags &= ~ALL_INLINE;
2723    if (strequal(v->inline_, "simple")) {
2724      flags |= DIFF_INLINE_SIMPLE;
2725    } else if (strequal(v->inline_, "char")) {
2726      flags |= DIFF_INLINE_CHAR;
2727    } else if (strequal(v->inline_, "word")) {
2728      flags |= DIFF_INLINE_WORD;
2729    } else {
2730      flags |= DIFF_INLINE_NONE;
2731    }
2732  }
2733  int algorithm = v->indent_heuristic ? XDF_INDENT_HEURISTIC : 0;
2734  if (HAS_KEY(v, dip, algorithm)) {
2735    if (strequal(v->algorithm, "minimal")) {
2736      algorithm |= XDF_NEED_MINIMAL;
2737    } else if (strequal(v->algorithm, "patience")) {
2738      algorithm |= XDF_PATIENCE_DIFF;
2739    } else if (strequal(v->algorithm, "histogram")) {
2740      algorithm |= XDF_HISTOGRAM_DIFF;
2741    }  // else "myers" -> 0
2742  }
2743
2744  int ret = OK;
2745  // Can't have both "horizontal" and "vertical".
2746  if ((flags & DIFF_HORIZONTAL) && (flags & DIFF_VERTICAL)) {
2747    ret = FAIL;
2748  } else {
2749    // If flags were added or removed, or the algorithm was changed, update the diff.
2750    if (diff_flags != flags || diff_algorithm != algorithm) {
2751      FOR_ALL_TABS(tp) {
2752        tp->tp_diff_invalid = true;
2753      }
2754    }
2755
2756    int context = HAS_KEY(v, dip, context) ? (int)v->context : 6;
2757    diff_flags = flags;
2758    diff_context = context == 0 ? 1 : context;
2759    linematch_lines = HAS_KEY(v, dip, linematch) ? (int)v->linematch : 0;
2760    diff_foldcolumn = HAS_KEY(v, dip, foldcolumn) ? (int)v->foldcolumn : 2;
2761    diff_algorithm = algorithm;
2762
2763    diff_redraw(true);
2764
2765    // recompute the scroll binding with the new option value, may
2766    // remove or add filler lines
2767    check_scrollbind(0, 0);
2768  }
2769
2770  return ret;
2771}
2772
2773/// Check that "diffopt" contains "horizontal".
2774bool diffopt_horizontal(void)
2775  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2776{
2777  return (diff_flags & DIFF_HORIZONTAL) != 0;
2778}
2779
2780// Return true if 'diffopt' contains "hiddenoff".
2781bool diffopt_hiddenoff(void)
2782  FUNC_ATTR_PURE
2783{
2784  return (diff_flags & DIFF_HIDDEN_OFF) != 0;
2785}
2786
2787// Return true if 'diffopt' contains "closeoff".
2788bool diffopt_closeoff(void)
2789  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2790{
2791  return (diff_flags & DIFF_CLOSE_OFF) != 0;
2792}
2793
2794// Return true if 'diffopt' contains "filler".
2795bool diffopt_filler(void)
2796  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2797{
2798  return (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{
2805  if (!(diff_flags & ALL_INLINE_DIFF)) {
2806    // We only care if we are doing inline-diff where we cache the diff results
2807    return;
2808  }
2809
2810  int idx = diff_buf_idx(curbuf, curtab);
2811  if (idx == DB_COUNT) {
2812    return;
2813  }
2814  diff_T *dp;
2815  FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp) {
2816    if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) {
2817      break;
2818    }
2819  }
2820
2821  // clear the inline change cache as it's invalid
2822  if (dp != NULL) {
2823    dp->has_changes = false;
2824    dp->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,
2835                       int *change_end)
2836{
2837  if (change->dc_start_lnum_off[diffline->bufidx] < diffline->lineoff) {
2838    *change_start = 0;
2839  } else {
2840    *change_start = change->dc_start[diffline->bufidx];
2841  }
2842  if (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
2848  if (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.
2851    return 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.
2858  for (int i = 0; i < DB_COUNT; i++) {
2859    if (i == diffline->bufidx) {
2860      continue;
2861    }
2862    if (change->dc_start[i] != change->dc_end[i]
2863        || change->dc_end_lnum_off[i] != change->dc_start_lnum_off[i]) {
2864      return false;
2865    }
2866  }
2867  return 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,
2884                                    int *startp, int *endp)
2885  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2886{
2887  char *line_org;
2888  if (diff_flags & DIFF_INLINE_NONE) {
2889    // We only care about the return value, not the actual string comparisons.
2890    line_org = NULL;
2891  } else {
2892    // Make a copy of the line, the next ml_get() will invalidate it.
2893    line_org = xstrdup(ml_get_buf(wp->w_buffer, lnum));
2894  }
2895
2896  int si_org;
2897  int si_new;
2898  int ei_org;
2899  int ei_new;
2900  bool added = true;
2901
2902  linenr_T off = lnum - dp->df_lnum[idx];
2903  for (int i = 0; i < DB_COUNT; i++) {
2904    if ((curtab->tp_diffbuf[i] != NULL) && (i != idx)) {
2905      // Skip lines that are not in the other change (filler lines).
2906      if (off >= dp->df_count[i]) {
2907        continue;
2908      }
2909      added = false;
2910      if (diff_flags & DIFF_INLINE_NONE) {
2911        break;  // early terminate as we only care about the return value
2912      }
2913
2914      char *line_new = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off);
2915
2916      // Search for start of difference
2917      si_org = si_new = 0;
2918
2919      while (line_org[si_org] != NUL) {
2920        if (((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])))) {
2926          si_org = (int)(skipwhite(line_org + si_org) - line_org);
2927          si_new = (int)(skipwhite(line_new + si_new) - line_new);
2928        } else {
2929          int l;
2930          if (!diff_equal_char(line_org + si_org, line_new + si_new, &l)) {
2931            break;
2932          }
2933          si_org += l;
2934          si_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).
2940      si_org -= utf_head_off(line_org, line_org + si_org);
2941      si_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.
2946      if ((line_org[si_org] != NUL) || (line_new[si_new] != NUL)) {
2947        ei_org = (int)strlen(line_org);
2948        ei_new = (int)strlen(line_new);
2949
2950        while (ei_org >= *startp
2951               && ei_new >= si_new
2952               && ei_org >= 0
2953               && ei_new >= 0) {
2954          if (((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])))) {
2960            while (ei_org >= *startp && ascii_iswhite(line_org[ei_org])) {
2961              ei_org--;
2962            }
2963
2964            while (ei_new >= si_new && ascii_iswhite(line_new[ei_new])) {
2965              ei_new--;
2966            }
2967          } else {
2968            const char *p1 = line_org + ei_org;
2969            const char *p2 = line_new + ei_new;
2970
2971            p1 -= utf_head_off(line_org, p1);
2972            p2 -= utf_head_off(line_new, p2);
2973
2974            int l;
2975            if (!diff_equal_char(p1, p2, &l)) {
2976              break;
2977            }
2978            ei_org -= l;
2979            ei_new -= l;
2980          }
2981        }
2982
2983        *endp = MAX(*endp, ei_org);
2984      }
2985    }
2986  }
2987
2988  xfree(line_org);
2989  return 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 {
2995  colnr_T byte_start;
2996  colnr_T num_bytes;
2997  int 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.
3011  int pass = 1;
3012  do {
3013    bool has_unmerged_gaps = false;
3014    bool has_merged_gaps = false;
3015    diff_T *dp = dp_orig;
3016    while (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.
3019      if (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) {
3021        dp = dp->df_next;
3022        continue;
3023      }
3024
3025      // If the gap occurs over different lines, don't consider it
3026      linemap_entry_T *entry1 =
3027        &((linemap_entry_T *)linemap[idx1].ga_data)[dp->df_lnum[idx1]
3028                                                    + dp->df_count[idx1] - 1];
3029      linemap_entry_T *entry2 =
3030        &((linemap_entry_T *)linemap[idx1].ga_data)[dp->df_next->df_lnum[idx1] - 1];
3031      if (entry1->lineoff != entry2->lineoff) {
3032        dp = dp->df_next;
3033        continue;
3034      }
3035
3036      linenr_T gap = dp->df_next->df_lnum[idx1] - (dp->df_lnum[idx1] + dp->df_count[idx1]);
3037      if (gap <= 3) {
3038        linenr_T max_df_count = 0;
3039        for (int i = 0; i < DB_COUNT; i++) {
3040          max_df_count = MAX(max_df_count, dp->df_count[i] + dp->df_next->df_count[i]);
3041        }
3042
3043        if (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.
3047          for (int i = 0; i < DB_COUNT; i++) {
3048            dp->df_count[i] = dp->df_next->df_lnum[i]
3049                              + dp->df_next->df_count[i] - dp->df_lnum[i];
3050          }
3051          diff_T *dp_next = dp->df_next;
3052          dp->df_next = dp_next->df_next;
3053          clear_diffblock(dp_next);
3054          has_merged_gaps = true;
3055          continue;
3056        } else {
3057          has_unmerged_gaps = true;
3058        }
3059      }
3060      dp = dp->df_next;
3061    }
3062    if (!has_unmerged_gaps || !has_merged_gaps) {
3063      break;
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,
3071                                              linenr_T start_lnum)
3072{
3073  int pass = 1;
3074  do {
3075    diff_T *dp = dp_orig;
3076
3077    while (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.
3081      linenr_T idx_entry1 = dp->df_lnum[idx1] + dp->df_count[idx1] - 2;
3082      linenr_T idx_entry2 = dp->df_next->df_lnum[idx1] - 1;
3083
3084      // Only merge blocks on the same line
3085      if (idx_entry1 < 0 || idx_entry1 >= linemap[idx1].ga_len
3086          || idx_entry2 < 0 || idx_entry2 >= linemap[idx1].ga_len) {
3087        dp = dp->df_next;
3088        continue;
3089      }
3090
3091      linemap_entry_T *entry1 =
3092        &((linemap_entry_T *)linemap[idx1].ga_data)[idx_entry1];
3093      linemap_entry_T *entry2 =
3094        &((linemap_entry_T *)linemap[idx1].ga_data)[idx_entry2];
3095
3096      // Skip if blocks are on different lines
3097      if (entry1->lineoff != entry2->lineoff) {
3098        dp = dp->df_next;
3099        continue;
3100      }
3101
3102      // Calculate the gap between blocks
3103      int gap_start = entry1->byte_start + entry1->num_bytes;
3104      int gap_end = entry2->byte_start;
3105      int 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.
3111      if (gap_size <= 0 || gap_size > diff_word_gap) {
3112        dp = dp->df_next;
3113        continue;
3114      }
3115
3116      // Get the text between the two blocks
3117      char *line = ml_get_buf(curtab->tp_diffbuf[idx1],
3118                              start_lnum + entry1->lineoff);
3119      char *gap_text = line + gap_start;
3120
3121      // Check if gap contains only whitespace and/or punctuation
3122      bool only_non_word = true;
3123      bool has_content = false;
3124      for (int i = 0; i < gap_size && gap_text[i] != NUL; i++) {
3125        has_content = true;
3126        int char_class = mb_get_class_tab(gap_text + i,
3127                                          curtab->tp_diffbuf[idx1]->b_chartab);
3128        // class 2 is word characters, if we find any, don't merge
3129        if (char_class == 2) {
3130          only_non_word = false;
3131          break;
3132        }
3133      }
3134
3135      // Merge if the gap is small and contains only non-word characters
3136      if (has_content && only_non_word) {
3137        long total_change_bytes = 0;
3138        for (int i = 0; i < DB_COUNT; i++) {
3139          if (curtab->tp_diffbuf[i] != NULL) {
3140            // count bytes in the first block
3141            for (int k = 0; k < dp->df_count[i]; k++) {
3142              int idx = dp->df_lnum[i] + k - 1;
3143              if (idx < linemap[i].ga_len) {
3144                total_change_bytes += ((linemap_entry_T *)linemap[i].ga_data)[idx].num_bytes;
3145              }
3146            }
3147            // count bytes in the next block
3148            for (int k = 0; k < dp->df_next->df_count[i]; k++) {
3149              int idx = dp->df_next->df_lnum[i] + k - 1;
3150              if (idx < linemap[i].ga_len) {
3151                total_change_bytes += ((linemap_entry_T *)linemap[i].ga_data)[idx].num_bytes;
3152              }
3153            }
3154          }
3155        }
3156
3157        if (total_change_bytes >= gap_size * 2) {
3158          // Merge the blocks by extending the first block to include the next
3159          for (int i = 0; i < DB_COUNT; i++) {
3160            if (curtab->tp_diffbuf[i] != NULL) {
3161              dp->df_count[i] = dp->df_next->df_lnum[i] + dp->df_next->df_count[i]
3162                                - dp->df_lnum[i];
3163            }
3164          }
3165
3166          diff_T *dp_next = dp->df_next;
3167          dp->df_next = dp_next->df_next;
3168          clear_diffblock(dp_next);
3169
3170          // Don't advance dp, check if can merge with the next block too
3171          continue;
3172        }
3173      }
3174
3175      dp = 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{
3186  const int save_diff_algorithm = diff_algorithm;
3187
3188  diffio_T dio = { 0 };
3189  ga_init(&dio.dio_diff.dout_ga, sizeof(diffhunk_T), 1000);
3190
3191  // inline diff only supports internal algo
3192  dio.dio_internal = true;
3193
3194  // always use indent-heuristics to slide diff splits along
3195  // whitespace
3196  diff_algorithm |= XDF_INDENT_HEURISTIC;
3197
3198  // diff_read() has an implicit dependency on curtab->tp_first_diff
3199  diff_T *orig_diff = curtab->tp_first_diff;
3200  curtab->tp_first_diff = NULL;
3201
3202  // diff_read() also uses curtab->tp_diffbuf to determine what's an active
3203  // buffer
3204  buf_T *(orig_diffbuf[DB_COUNT]);
3205  memcpy(orig_diffbuf, curtab->tp_diffbuf, sizeof(orig_diffbuf));
3206
3207  garray_T linemap[DB_COUNT];
3208  garray_T file1_str;
3209  garray_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.
3214  ga_init(&file1_str, 1, 1024);
3215  ga_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.
3220  for (int i = 0; i < DB_COUNT; i++) {
3221    ga_init(&linemap[i], sizeof(linemap_entry_T), 128);
3222  }
3223
3224  int file1_idx = -1;
3225  for (int i = 0; i < DB_COUNT; i++) {
3226    dio.dio_diff.dout_ga.ga_len = 0;
3227
3228    buf_T *buf = curtab->tp_diffbuf[i];
3229    if (buf == NULL || buf->b_ml.ml_mfp == NULL) {
3230      continue;  // skip buffer that isn't loaded
3231    }
3232    if (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
3235      curtab->tp_diffbuf[i] = NULL;
3236      continue;
3237    }
3238
3239    if (file1_idx == -1) {
3240      file1_idx = i;
3241    }
3242
3243    garray_T *curstr = (file1_idx != i) ? &file2_str : &file1_str;
3244
3245    linenr_T numlines = 0;
3246    curstr->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.
3250    for (int off = 0; off < dp->df_count[i]; off++) {
3251      char *curline = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off);
3252
3253      bool in_keyword = false;
3254
3255      // iwhiteeol support vars
3256      bool last_white = false;
3257      int eol_ga_len = -1;
3258      int eol_linemap_len = -1;
3259      int eol_numlines = -1;
3260
3261      char *s = curline;
3262      while (*s != NUL) {
3263        bool new_in_keyword = false;
3264        if (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.
3271          new_in_keyword = (mb_get_class_tab(s, curtab->tp_diffbuf[file1_idx]->b_chartab) == 2);
3272        }
3273        if (in_keyword && !new_in_keyword) {
3274          ga_append(curstr, NL);
3275          numlines++;
3276        }
3277
3278        if (ascii_iswhite(*s)) {
3279          if (diff_flags & DIFF_IWHITEALL) {
3280            in_keyword = false;
3281            s = skipwhite(s);
3282            continue;
3283          } else if ((diff_flags & DIFF_IWHITEEOL) || (diff_flags & DIFF_IWHITE)) {
3284            if (!last_white) {
3285              eol_ga_len = curstr->ga_len;
3286              eol_linemap_len = linemap[i].ga_len;
3287              eol_numlines = numlines;
3288              last_white = true;
3289            }
3290          }
3291        } else {
3292          if ((diff_flags & DIFF_IWHITEEOL) || (diff_flags & DIFF_IWHITE)) {
3293            last_white = false;
3294            eol_ga_len = -1;
3295            eol_linemap_len = -1;
3296            eol_numlines = -1;
3297          }
3298        }
3299
3300        int char_len = 1;
3301        if (*s == NL) {
3302          // NL is internal substitute for NUL
3303          ga_append(curstr, NUL);
3304        } else {
3305          char_len = utfc_ptr2len(s);
3306
3307          if (ascii_iswhite(*s) && (diff_flags & DIFF_IWHITE)) {
3308            // Treat the entire white space span as a single char.
3309            char_len = (int)(skipwhite(s) - s);
3310          }
3311
3312          if (diff_flags & DIFF_ICASE) {
3313            // xdiff doesn't support ignoring case, fold-case the text manually.
3314            int c = utf_ptr2char(s);
3315            int c_len = utf_char2len(c);
3316            c = utf_fold(c);
3317            char cbuf[MB_MAXBYTES + 1];
3318            int c_fold_len = utf_char2bytes(c, cbuf);
3319            ga_concat_len(curstr, cbuf, (size_t)c_fold_len);
3320            if (char_len > c_len) {
3321              // There may be remaining composing characters. Write those back in.
3322              // Composing characters don't need case folding.
3323              ga_concat_len(curstr, s + c_len, (size_t)(char_len - c_len));
3324            }
3325          } else {
3326            ga_concat_len(curstr, s, (size_t)char_len);
3327          }
3328        }
3329
3330        if (!new_in_keyword) {
3331          ga_append(curstr, NL);
3332          numlines++;
3333        }
3334
3335        if (!new_in_keyword || (new_in_keyword && !in_keyword)) {
3336          // create a new mapping entry from the xdiff mmfile back to
3337          // original line/col.
3338          linemap_entry_T linemap_entry = {
3339            .lineoff = off,
3340            .byte_start = (colnr_T)(s - curline),
3341            .num_bytes = char_len,
3342          };
3343          GA_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
3351        in_keyword = new_in_keyword;
3352        s += char_len;
3353      }
3354      if (in_keyword) {
3355        ga_append(curstr, NL);
3356        numlines++;
3357      }
3358
3359      if ((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.
3362        if (eol_ga_len != -1) {
3363          curstr->ga_len = eol_ga_len;
3364          linemap[i].ga_len = eol_linemap_len;
3365          numlines = eol_numlines;
3366        }
3367      }
3368
3369      if (!(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.
3374        ga_append(curstr, NL);
3375        numlines++;
3376
3377        linemap_entry_T linemap_entry = {
3378          .lineoff = off,
3379          .byte_start = (colnr_T)(s - curline),
3380          .num_bytes = sizeof(NL),
3381        };
3382        GA_APPEND(linemap_entry_T, &linemap[i], linemap_entry);
3383      }
3384    }
3385
3386    if (file1_idx != i) {
3387      dio.dio_new.din_mmfile.ptr = (char *)curstr->ga_data;
3388      dio.dio_new.din_mmfile.size = curstr->ga_len;
3389    } else {
3390      dio.dio_orig.din_mmfile.ptr = (char *)curstr->ga_data;
3391      dio.dio_orig.din_mmfile.size = curstr->ga_len;
3392    }
3393    if (file1_idx != i) {
3394      // Perform diff with first file and read the results
3395      int diff_status = diff_file_internal(&dio);
3396      if (diff_status == FAIL) {
3397        goto done;
3398      }
3399
3400      diff_read(0, i, &dio);
3401      clear_diffout(&dio.dio_diff);
3402    }
3403  }
3404  diff_T *new_diff = curtab->tp_first_diff;
3405
3406  if (diff_flags & DIFF_INLINE_WORD && file1_idx != -1) {
3407    diff_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) {
3409    diff_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.
3414  dp->df_changes.ga_len = 0;  // this should already be zero
3415  for (; new_diff != NULL; new_diff = new_diff->df_next) {
3416    diffline_change_T change = { 0 };
3417    for (int i = 0; i < DB_COUNT; i++) {
3418      if (new_diff->df_lnum[i] <= 0) {  // should never be < 0. Checking just for safety
3419        continue;
3420      }
3421      linenr_T diff_lnum = new_diff->df_lnum[i] - 1;  // use zero-index
3422      linenr_T diff_lnum_end = diff_lnum + new_diff->df_count[i];
3423
3424      if (diff_lnum >= linemap[i].ga_len) {
3425        change.dc_start[i] = MAXCOL;
3426        change.dc_start_lnum_off[i] = INT_MAX;
3427      } else {
3428        change.dc_start[i] = ((linemap_entry_T *)linemap[i].ga_data)[diff_lnum].byte_start;
3429        change.dc_start_lnum_off[i] = ((linemap_entry_T *)linemap[i].ga_data)[diff_lnum].lineoff;
3430      }
3431
3432      if (diff_lnum == diff_lnum_end) {
3433        change.dc_end[i] = change.dc_start[i];
3434        change.dc_end_lnum_off[i] = change.dc_start_lnum_off[i];
3435      } else if (diff_lnum_end - 1 >= linemap[i].ga_len) {
3436        change.dc_end[i] = MAXCOL;
3437        change.dc_end_lnum_off[i] = INT_MAX;
3438      } else {
3439        change.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;
3441        change.dc_end_lnum_off[i] = ((linemap_entry_T *)linemap[i].ga_data)[diff_lnum_end -
3442                                                                            1].lineoff;
3443      }
3444    }
3445    GA_APPEND(diffline_change_T, &dp->df_changes, change);
3446  }
3447
3448done:
3449  diff_algorithm = save_diff_algorithm;
3450
3451  dp->has_changes = true;
3452
3453  diff_clear(curtab);
3454  curtab->tp_first_diff = orig_diff;
3455  memcpy(curtab->tp_diffbuf, orig_diffbuf, sizeof(orig_diffbuf));
3456
3457  ga_clear(&file1_str);
3458  ga_clear(&file2_str);
3459  // No need to clear dio.dio_orig/dio_new because they were referencing
3460  // strings that are now cleared.
3461  clear_diffout(&dio.dio_diff);
3462  for (int i = 0; i < DB_COUNT; i++) {
3463    ga_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)
3470  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
3471{
3472  int idx = diff_buf_idx(wp->w_buffer, curtab);
3473  if (idx == DB_COUNT) {  // cannot happen
3474    return false;
3475  }
3476
3477  // search for a change that includes "lnum" in the list of diffblocks.
3478  diff_T *dp;
3479  FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp) {
3480    if (lnum < dp->df_lnum[idx] + dp->df_count[idx]) {
3481      break;
3482    }
3483  }
3484  if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL) {
3485    return false;
3486  }
3487
3488  int off = lnum - dp->df_lnum[idx];
3489
3490  if (!(diff_flags & ALL_INLINE_DIFF)) {
3491    // Use simple algorithm
3492    int change_start = MAXCOL;  // first col of changed area
3493    int change_end = -1;        // last col of changed area
3494
3495    int 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
3498    change_end += 1;
3499
3500    // Create a mock diffline struct. We always only have one so no need to
3501    // allocate memory.
3502    CLEAR_FIELD(simple_diffline_change);
3503    diffline->changes = &simple_diffline_change;
3504    diffline->num_changes = 1;
3505    diffline->bufidx = idx;
3506    diffline->lineoff = lnum - dp->df_lnum[idx];
3507
3508    simple_diffline_change.dc_start[idx] = change_start;
3509    simple_diffline_change.dc_end[idx] = change_end;
3510    simple_diffline_change.dc_start_lnum_off[idx] = off;
3511    simple_diffline_change.dc_end_lnum_off[idx] = off;
3512    return ret;
3513  }
3514
3515  // Use inline diff algorithm.
3516  // The diff changes are usually cached so we check that first.
3517  if (!dp->has_changes) {
3518    diff_find_change_inline_diff(dp);
3519  }
3520
3521  garray_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.
3527  int num_changes = 0;
3528  int change_idx = 0;
3529  diffline->changes = NULL;
3530  for (change_idx = 0; change_idx < changes->ga_len; change_idx++) {
3531    diffline_change_T *change =
3532      &((diffline_change_T *)dp->df_changes.ga_data)[change_idx];
3533    if (change->dc_end_lnum_off[idx] < off) {
3534      continue;
3535    }
3536    if (change->dc_start_lnum_off[idx] > off) {
3537      break;
3538    }
3539    if (diffline->changes == NULL) {
3540      diffline->changes = change;
3541    }
3542    num_changes++;
3543  }
3544  diffline->num_changes = num_changes;
3545  diffline->bufidx = idx;
3546  diffline->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.
3552  bool added = false;
3553  if (num_changes == 1 && change_idx == dp->df_changes.ga_len) {
3554    added = true;
3555    for (int i = 0; i < DB_COUNT; i++) {
3556      if (idx == i) {
3557        continue;
3558      }
3559      if (curtab->tp_diffbuf[i] == NULL) {
3560        continue;
3561      }
3562      diffline_change_T *change =
3563        &((diffline_change_T *)dp->df_changes.ga_data)[dp->df_changes.ga_len - 1];
3564      if (change->dc_start_lnum_off[i] != INT_MAX) {
3565        added = false;
3566        break;
3567      }
3568    }
3569  }
3570  return 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)
3581  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
3582{
3583  // Return if 'diff' isn't set.
3584  if (!wp->w_p_diff) {
3585    return false;
3586  }
3587
3588  int idx = -1;
3589  bool other = false;
3590  for (int i = 0; i < DB_COUNT; i++) {
3591    if (curtab->tp_diffbuf[i] == wp->w_buffer) {
3592      idx = i;
3593    } else if (curtab->tp_diffbuf[i] != NULL) {
3594      other = true;
3595    }
3596  }
3597
3598  // return here if there are no diffs in the window
3599  if ((idx == -1) || !other) {
3600    return false;
3601  }
3602
3603  if (curtab->tp_diff_invalid) {
3604    // update after a big change
3605    ex_diffupdate(NULL);
3606  }
3607
3608  // Return if there are no diff blocks.  All lines will be folded.
3609  if (curtab->tp_first_diff == NULL) {
3610    return true;
3611  }
3612
3613  // Resume from the scan finger to avoid restarting at the first block.
3614  diff_T *le = NULL;             // last block with df_lnum[idx] <= lnum
3615  bool result = true;
3616  for (diff_T *dp = diff_scan_start(curtab, idx, lnum); dp != NULL; dp = dp->df_next) {
3617    if (dp->df_lnum[idx] <= lnum) {
3618      le = dp;
3619    }
3620    if (dp->df_lnum[idx] - diff_context > lnum) {
3621      break;
3622    }
3623
3624    // If this change ends before the line we have a match.
3625    if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum) {
3626      result = false;
3627      break;
3628    }
3629  }
3630  diff_scan_remember(curtab, idx, lnum, le);
3631  return result;
3632}
3633
3634/// "dp" and "do" commands.
3635void nv_diffgetput(bool put, size_t count)
3636{
3637  if (bt_prompt(curbuf)) {
3638    vim_beep(kOptBoFlagOperator);
3639    return;
3640  }
3641
3642  exarg_T ea;
3643  char buf[30];
3644  if (count == 0) {
3645    ea.arg = "";
3646  } else {
3647    vim_snprintf(buf, sizeof(buf), "%zu", count);
3648    ea.arg = buf;
3649  }
3650
3651  if (put) {
3652    ea.cmdidx = CMD_diffput;
3653  } else {
3654    ea.cmdidx = CMD_diffget;
3655  }
3656
3657  ea.addr_count = 0;
3658  ea.line1 = curwin->w_cursor.lnum;
3659  ea.line2 = curwin->w_cursor.lnum;
3660  ex_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{
3666  for (diff_T *dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
3667    if (dp == diff) {
3668      return true;
3669    }
3670  }
3671  return false;
3672}
3673
3674/// ":diffget" and ":diffput"
3675///
3676/// @param eap
3677void ex_diffgetput(exarg_T *eap)
3678{
3679  int idx_other;
3680
3681  // Find the current buffer in the list of diff buffers.
3682  int idx_cur = diff_buf_idx(curbuf, curtab);
3683  if (idx_cur == DB_COUNT) {
3684    emsg(_("E99: Current buffer is not in diff mode"));
3685    return;
3686  }
3687
3688  if (*eap->arg == NUL) {
3689    bool found_not_ma = false;
3690    // No argument: Find the other buffer in the list of diff buffers.
3691    for (idx_other = 0; idx_other < DB_COUNT; idx_other++) {
3692      if ((curtab->tp_diffbuf[idx_other] != curbuf)
3693          && (curtab->tp_diffbuf[idx_other] != NULL)) {
3694        if ((eap->cmdidx != CMD_diffput)
3695            || MODIFIABLE(curtab->tp_diffbuf[idx_other])) {
3696          break;
3697        }
3698        found_not_ma = true;
3699      }
3700    }
3701
3702    if (idx_other == DB_COUNT) {
3703      if (found_not_ma) {
3704        emsg(_("E793: No other buffer in diff mode is modifiable"));
3705      } else {
3706        emsg(_("E100: No other buffer in diff mode"));
3707      }
3708      return;
3709    }
3710
3711    // Check that there isn't a third buffer in the list
3712    for (int i = idx_other + 1; i < DB_COUNT; i++) {
3713      if ((curtab->tp_diffbuf[i] != curbuf)
3714          && (curtab->tp_diffbuf[i] != NULL)
3715          && ((eap->cmdidx != CMD_diffput)
3716              || MODIFIABLE(curtab->tp_diffbuf[i]))) {
3717        emsg(_("E101: More than two buffers in diff mode, don't know "
3718               "which one to use"));
3719        return;
3720      }
3721    }
3722  } else {
3723    // Buffer number or pattern given. Ignore trailing white space.
3724    char *p = eap->arg + strlen(eap->arg);
3725    while (p > eap->arg && ascii_iswhite(p[-1])) {
3726      p--;
3727    }
3728
3729    int i;
3730    for (i = 0; ascii_isdigit(eap->arg[i]) && eap->arg + i < p; i++) {}
3731
3732    if (eap->arg + i == p) {
3733      // digits only
3734      i = (int)atol(eap->arg);
3735    } else {
3736      i = buflist_findpat(eap->arg, p, false, true, false);
3737
3738      if (i < 0) {
3739        // error message already given
3740        return;
3741      }
3742    }
3743    buf_T *buf = buflist_findnr(i);
3744
3745    if (buf == NULL) {
3746      semsg(_("E102: Can't find buffer \"%s\""), eap->arg);
3747      return;
3748    }
3749
3750    if (buf == curbuf) {
3751      // nothing to do
3752      return;
3753    }
3754    idx_other = diff_buf_idx(buf, curtab);
3755
3756    if (idx_other == DB_COUNT) {
3757      semsg(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg);
3758      return;
3759    }
3760  }
3761
3762  diff_busy = true;
3763
3764  // When no range given include the line above or below the cursor.
3765  if (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.
3768    int linestatus = 0;
3769    if (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))) {
3775      eap->line2++;
3776    } else if (eap->line1 > 0) {
3777      eap->line1--;
3778    }
3779  }
3780
3781  CtxSwitch aco = { 0 };
3782
3783  if (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.
3788    ctx_switch(&aco, NULL, NULL, curtab->tp_diffbuf[idx_other], 0);
3789  }
3790
3791  const int idx_from = eap->cmdidx == CMD_diffget ? idx_other : idx_cur;
3792  const 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.
3797  if (!curbuf->b_changed) {
3798    change_warning(curbuf, 0);
3799    if (diff_buf_idx(curbuf, curtab) != idx_to) {
3800      emsg(_("E787: Buffer changed unexpectedly"));
3801      ctx_restore(&aco);
3802      goto theend;
3803    }
3804  }
3805
3806  diffgetput(eap->addr_count, idx_cur, idx_from, idx_to, eap->line1, eap->line2);
3807
3808  // restore curwin/curbuf and a few other things
3809  if (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.
3813    if (KeyTyped) {
3814      u_sync(false);
3815    }
3816    ctx_restore(&aco);
3817  }
3818
3819theend:
3820  diff_busy = false;
3821
3822  if (diff_need_update) {
3823    ex_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.
3829  check_cursor(curwin);
3830  changed_line_abv_curs();
3831
3832  // If all diffs are gone, update folds in all diff windows.
3833  if (curtab->tp_first_diff == NULL) {
3834    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
3835      if (wp->w_p_diff && wp->w_p_fdm[0] == 'd' && wp->w_p_fen) {
3836        foldUpdateAll(wp);
3837      }
3838    }
3839  }
3840
3841  if (diff_need_update) {
3842    // redraw already done by ex_diffupdate()
3843    diff_need_update = false;
3844  } else {
3845    // Also need to redraw the other buffers.
3846    diff_redraw(false);
3847    apply_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,
3857                       const int idx_to, const linenr_T line1, const linenr_T line2)
3858{
3859  linenr_T off = 0;
3860  diff_T *dprev = NULL;
3861
3862  for (diff_T *dp = curtab->tp_first_diff; dp != NULL;) {
3863    if (!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.
3868      while (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) {
3871        dprev = dp;
3872        dp = dp->df_next;
3873      }
3874    }
3875
3876    if (dp->df_lnum[idx_cur] > line2 + off) {
3877      // past the range that was specified
3878      break;
3879    }
3880    diff_T dfree = { 0 };
3881    bool did_free = false;
3882    linenr_T lnum = dp->df_lnum[idx_to];
3883    linenr_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.
3886    linenr_T undo_bot = lnum + count + (count == 0 && buf_is_empty(curbuf) ? 1 : 0);
3887
3888    if ((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.
3891      linenr_T start_skip = 0;
3892      linenr_T end_skip = 0;
3893
3894      if (addr_count > 0) {
3895        // A range was specified: check if lines need to be skipped.
3896        start_skip = line1 + off - dp->df_lnum[idx_cur];
3897        if (start_skip > 0) {
3898          // range starts below start of current diff block
3899          if (start_skip > count) {
3900            lnum += count;
3901            count = 0;
3902          } else {
3903            count -= start_skip;
3904            lnum += start_skip;
3905          }
3906        } else {
3907          start_skip = 0;
3908        }
3909
3910        end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1
3911                   - (line2 + off);
3912
3913        if (end_skip > 0) {
3914          // range ends above end of current/from diff block
3915          if (idx_cur == idx_from) {
3916            // :diffput
3917            count = MIN(count, dp->df_count[idx_cur] - start_skip - end_skip);
3918          } else {
3919            // :diffget
3920            count -= end_skip;
3921            end_skip = MAX(dp->df_count[idx_from] - start_skip - count, 0);
3922          }
3923        } else {
3924          end_skip = 0;
3925        }
3926      }
3927
3928      bool buf_empty = buf_is_empty(curbuf);
3929      int added = 0;
3930
3931      for (int i = 0; i < count; i++) {
3932        // remember deleting the last line of the buffer
3933        buf_empty = curbuf->b_ml.ml_line_count == 1;
3934        if (ml_delete(lnum) == OK) {
3935          added--;
3936        }
3937      }
3938
3939      for (int i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; i++) {
3940        linenr_T nr = dp->df_lnum[idx_from] + start_skip + i;
3941        if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count) {
3942          break;
3943        }
3944        char *p = xstrdup(ml_get_buf(curtab->tp_diffbuf[idx_from], nr));
3945        ml_append(lnum + i - 1, p, 0, false);
3946        xfree(p);
3947        added++;
3948        if (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.
3954          buf_empty = false;
3955          ml_delete(2);
3956        }
3957      }
3958      linenr_T new_count = dp->df_count[idx_to] + added;
3959      dp->df_count[idx_to] = new_count;
3960
3961      if ((start_skip == 0) && (end_skip == 0)) {
3962        // Check if there are any other buffers and if the diff is
3963        // equal in them.
3964        int i;
3965        for (i = 0; i < DB_COUNT; i++) {
3966          if ((curtab->tp_diffbuf[i] != NULL)
3967              && (i != idx_from)
3968              && (i != idx_to)
3969              && !diff_equal_entry(dp, idx_from, i)) {
3970            break;
3971          }
3972        }
3973
3974        if (i == DB_COUNT) {
3975          // delete the diff entry, the buffers are now equal here
3976          dfree = *dp;
3977          did_free = true;
3978          dp = diff_free(curtab, dprev, dp);
3979        }
3980      }
3981
3982      if (added != 0) {
3983        // Adjust marks.  This will change the following entries!
3984        mark_adjust(lnum, lnum + count - 1, MAXLNUM, added, kExtmarkNOOP);
3985        if (curwin->w_cursor.lnum >= lnum) {
3986          // Adjust the cursor position if it's in/after the changed
3987          // lines.
3988          if (curwin->w_cursor.lnum >= lnum + count) {
3989            curwin->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.
3992            curwin->w_cursor.lnum = MIN(curwin->w_cursor.lnum,
3993                                        curbuf->b_ml.ml_line_count);
3994          } else if (added < 0) {
3995            curwin->w_cursor.lnum = lnum;
3996          }
3997        }
3998      }
3999      extmark_adjust(curbuf, lnum, lnum + count - 1, MAXLNUM, added, kExtmarkUndo);
4000      changed_lines(curbuf, lnum, 0, lnum + count, added, true);
4001
4002      if (did_free) {
4003        // Diff is deleted, update folds in other windows.
4004        diff_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.
4009      if (added != 0 && !valid_diff(dp)) {
4010        break;
4011      }
4012
4013      if (!did_free) {
4014        // mark_adjust() may have changed the count in a wrong way
4015        dp->df_count[idx_to] = new_count;
4016      }
4017
4018      // When changing the current buffer, keep track of line numbers
4019      if (idx_cur == idx_to) {
4020        off += added;
4021      }
4022    }
4023
4024    // If before the range or not deleted, go to next diff.
4025    if (!did_free) {
4026      dprev = dp;
4027      dp = 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{
4041  FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
4042    for (int i = 0; i < DB_COUNT; i++) {
4043      if ((curtab->tp_diffbuf[i] == wp->w_buffer) && (i != skip_idx)) {
4044        foldUpdate(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)
4054  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1)
4055{
4056  FOR_ALL_TABS(tp) {
4057    if (diff_buf_idx(buf, tp) != DB_COUNT) {
4058      return true;
4059    }
4060  }
4061  return 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{
4072  linenr_T lnum = curwin->w_cursor.lnum;
4073  int idx = diff_buf_idx(curbuf, curtab);
4074  if ((idx == DB_COUNT) || (curtab->tp_first_diff == NULL)) {
4075    return FAIL;
4076  }
4077
4078  if (curtab->tp_diff_invalid) {
4079    // update after a big change
4080    ex_diffupdate(NULL);
4081  }
4082
4083  if (curtab->tp_first_diff == NULL) {
4084    // no diffs today
4085    return FAIL;
4086  }
4087
4088  while (--count >= 0) {
4089    // Check if already before first diff.
4090    if ((dir == BACKWARD) && (lnum <= curtab->tp_first_diff->df_lnum[idx])) {
4091      break;
4092    }
4093
4094    diff_T *dp;
4095    for (dp = curtab->tp_first_diff;; dp = dp->df_next) {
4096      if (dp == NULL) {
4097        break;
4098      }
4099
4100      if (((dir == FORWARD) && (lnum < dp->df_lnum[idx]))
4101          || ((dir == BACKWARD)
4102              && ((dp->df_next == NULL)
4103                  || (lnum <= dp->df_next->df_lnum[idx])))) {
4104        lnum = dp->df_lnum[idx];
4105        break;
4106      }
4107    }
4108  }
4109
4110  // don't end up past the end of the file
4111  lnum = MIN(lnum, curbuf->b_ml.ml_line_count);
4112
4113  // When the cursor didn't move at all we fail.
4114  if (lnum == curwin->w_cursor.lnum) {
4115    return FAIL;
4116  }
4117
4118  setpcmark();
4119  curwin->w_cursor.lnum = lnum;
4120  curwin->w_cursor.col = 0;
4121
4122  return 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{
4129  linenr_T baseline = 0;
4130
4131  int idx1 = diff_buf_idx(buf1, curtab);
4132  int idx2 = diff_buf_idx(curbuf, curtab);
4133
4134  if ((idx1 == DB_COUNT)
4135      || (idx2 == DB_COUNT)
4136      || (curtab->tp_first_diff == NULL)) {
4137    return lnum1;
4138  }
4139
4140  if (curtab->tp_diff_invalid) {
4141    // update after a big change
4142    ex_diffupdate(NULL);
4143  }
4144
4145  if (curtab->tp_first_diff == NULL) {
4146    // no diffs today
4147    return lnum1;
4148  }
4149
4150  for (diff_T *dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
4151    if (dp->df_lnum[idx1] > lnum1) {
4152      return lnum1 - baseline;
4153    }
4154    if ((dp->df_lnum[idx1] + dp->df_count[idx1]) > lnum1) {
4155      // Inside the diffblock
4156      baseline = lnum1 - dp->df_lnum[idx1];
4157      baseline = MIN(baseline, dp->df_count[idx2]);
4158
4159      return dp->df_lnum[idx2] + baseline;
4160    }
4161    if ((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.
4171      return curwin->w_cursor.lnum;
4172    }
4173    baseline = (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
4178  return 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{
4189  linenr_T lnum = diff_get_corresponding_line_int(buf1, lnum1);
4190
4191  // don't end up past the end of the file
4192  return 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{
4199  diff_T *dp;
4200
4201  int idx = diff_buf_idx(curbuf, curtab);
4202
4203  if (idx == DB_COUNT) {
4204    // safety check
4205    return 0;
4206  }
4207
4208  if (curtab->tp_diff_invalid) {
4209    // update after a big change
4210    ex_diffupdate(NULL);
4211  }
4212
4213  // search for a change that includes "lnum" in the list of diffblocks.
4214  for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next) {
4215    if (lnum <= dp->df_lnum[idx] + dp->df_count[idx]) {
4216      break;
4217    }
4218  }
4219
4220  // When after the last change, compute relative to the last line number.
4221  if (dp == NULL) {
4222    return wp->w_buffer->b_ml.ml_line_count
4223           - (curbuf->b_ml.ml_line_count - lnum);
4224  }
4225
4226  // Find index for "wp".
4227  int i = diff_buf_idx(wp->w_buffer, curtab);
4228
4229  if (i == DB_COUNT) {
4230    // safety check
4231    return 0;
4232  }
4233
4234  linenr_T n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
4235  return 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{
4243  int 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}
4249  char *p = line;
4250  linenr_T f1 = getdigits_int32(&p, true, 0);
4251  if (*p == ',') {
4252    p++;
4253    l1 = getdigits_int(&p, true, 0);
4254  } else {
4255    l1 = f1;
4256  }
4257  if (*p != 'a' && *p != 'c' && *p != 'd') {
4258    return FAIL;        // invalid diff format
4259  }
4260  int difftype = (uint8_t)(*p++);
4261  int f2 = getdigits_int(&p, true, 0);
4262  if (*p == ',') {
4263    p++;
4264    l2 = getdigits_int(&p, true, 0);
4265  } else {
4266    l2 = f2;
4267  }
4268  if (l1 < f1 || l2 < f2) {
4269    return FAIL;
4270  }
4271
4272  if (difftype == 'a') {
4273    hunk->lnum_orig = f1 + 1;
4274    hunk->count_orig = 0;
4275  } else {
4276    hunk->lnum_orig = f1;
4277    hunk->count_orig = l1 - f1 + 1;
4278  }
4279  if (difftype == 'd') {
4280    hunk->lnum_new = (linenr_T)f2 + 1;
4281    hunk->count_new = 0;
4282  } else {
4283    hunk->lnum_new = (linenr_T)f2;
4284    hunk->count_new = l2 - f2 + 1;
4285  }
4286  return 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 @@
4295  char *p = line;
4296  if (*p++ == '@' && *p++ == '@' && *p++ == ' ' && *p++ == '-') {
4297    int oldcount;
4298    linenr_T newline;
4299    int newcount;
4300    linenr_T oldline = getdigits_int32(&p, true, 0);
4301    if (*p == ',') {
4302      p++;
4303      oldcount = getdigits_int(&p, true, 0);
4304    } else {
4305      oldcount = 1;
4306    }
4307    if (*p++ == ' ' && *p++ == '+') {
4308      newline = getdigits_int(&p, true, 0);
4309      if (*p == ',') {
4310        p++;
4311        newcount = getdigits_int(&p, true, 0);
4312      } else {
4313        newcount = 1;
4314      }
4315    } else {
4316      return FAIL;  // invalid diff format
4317    }
4318
4319    if (oldcount == 0) {
4320      oldline += 1;
4321    }
4322    if (newcount == 0) {
4323      newline += 1;
4324    }
4325    if (newline == 0) {
4326      newline = 1;
4327    }
4328
4329    hunk->lnum_orig = oldline;
4330    hunk->count_orig = oldcount;
4331    hunk->lnum_new = newline;
4332    hunk->count_new = newcount;
4333
4334    return OK;
4335  }
4336
4337  return 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{
4344  diffout_T *dout = (diffout_T *)priv;
4345  GA_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  }));
4351  return 0;
4352}
4353
4354/// "diff_filler()" function
4355void f_diff_filler(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4356{
4357  rettv->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{
4363  static linenr_T prev_lnum = 0;
4364  static varnumber_T changedtick = 0;
4365  static int fnum = 0;
4366  static int prev_diff_flags = 0;
4367  static int change_start = 0;
4368  static int change_end = 0;
4369  static hlf_T hlID = (hlf_T)0;
4370
4371  diffline_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.
4375  const bool cache_results = !(diff_flags & ALL_INLINE_DIFF);
4376
4377  linenr_T lnum = tv_get_lnum(argvars);
4378  if (lnum < 0) {       // ignore type error in {lnum} arg
4379    lnum = 0;
4380  }
4381  if (!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.
4387    int linestatus = 0;
4388    diff_check_with_linestatus(curwin, lnum, &linestatus);
4389    if (linestatus < 0) {
4390      if (linestatus == -1) {
4391        change_start = MAXCOL;
4392        change_end = -1;
4393        if (diff_find_change(curwin, lnum, &diffline)) {
4394          hlID = HLF_ADD;               // added line
4395        } else {
4396          hlID = HLF_CHD;               // changed line
4397          if (diffline.num_changes > 0 && cache_results) {
4398            change_start = diffline.changes[0].dc_start[diffline.bufidx];
4399            change_end = diffline.changes[0].dc_end[diffline.bufidx];
4400          }
4401        }
4402      } else {
4403        hlID = HLF_ADD;         // added line
4404      }
4405    } else {
4406      hlID = (hlf_T)0;
4407    }
4408
4409    if (cache_results) {
4410      prev_lnum = lnum;
4411      changedtick = buf_get_changedtick(curbuf);
4412      fnum = curbuf->b_fnum;
4413      prev_diff_flags = diff_flags;
4414    }
4415  }
4416
4417  if (hlID == HLF_CHD || hlID == HLF_TXD) {
4418    int col = (int)tv_get_number(&argvars[1]) - 1;  // Ignore type error in {col}.
4419    if (cache_results) {
4420      if (col >= change_start && col < change_end) {
4421        hlID = HLF_TXD;  // Changed text.
4422      } else {
4423        hlID = HLF_CHD;  // Changed line.
4424      }
4425    } else {
4426      hlID = HLF_CHD;
4427      for (int i = 0; i < diffline.num_changes; i++) {
4428        bool added = diff_change_parse(&diffline, &diffline.changes[i],
4429                                       &change_start, &change_end);
4430        if (col >= change_start && col < change_end) {
4431          hlID = added ? HLF_TXA : HLF_TXD;
4432          break;
4433        }
4434        if (col < change_start) {
4435          // the remaining changes are past this column and not relevant
4436          break;
4437        }
4438      }
4439    }
4440  }
4441  rettv->vval.v_number = hlID;
4442}