xref: /vim-8.2.3635/src/diff.c (revision 125ed274)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * diff.c: code for diff'ing two, three or four buffers.
12  *
13  * There are three ways to diff:
14  * - Shell out to an external diff program, using files.
15  * - Use the compiled-in xdiff library.
16  * - Let 'diffexpr' do the work, using files.
17  */
18 
19 #include "vim.h"
20 #include "xdiff/xdiff.h"
21 
22 #if defined(FEAT_DIFF) || defined(PROTO)
23 
24 static int diff_busy = FALSE;	    // using diff structs, don't change them
25 static int diff_need_update = FALSE; // ex_diffupdate needs to be called
26 
27 // flags obtained from the 'diffopt' option
28 #define DIFF_FILLER	0x001	// display filler lines
29 #define DIFF_IBLANK	0x002	// ignore empty lines
30 #define DIFF_ICASE	0x004	// ignore case
31 #define DIFF_IWHITE	0x008	// ignore change in white space
32 #define DIFF_IWHITEALL	0x010	// ignore all white space changes
33 #define DIFF_IWHITEEOL	0x020	// ignore change in white space at EOL
34 #define DIFF_HORIZONTAL	0x040	// horizontal splits
35 #define DIFF_VERTICAL	0x080	// vertical splits
36 #define DIFF_HIDDEN_OFF	0x100	// diffoff when hidden
37 #define DIFF_INTERNAL	0x200	// use internal xdiff algorithm
38 #define DIFF_CLOSE_OFF	0x400	// diffoff when closing window
39 #define DIFF_FOLLOWWRAP	0x800	// follow the wrap option
40 #define ALL_WHITE_DIFF (DIFF_IWHITE | DIFF_IWHITEALL | DIFF_IWHITEEOL)
41 static int	diff_flags = DIFF_INTERNAL | DIFF_FILLER | DIFF_CLOSE_OFF;
42 
43 static long diff_algorithm = 0;
44 
45 #define LBUFLEN 50		// length of line in diff file
46 
47 static int diff_a_works = MAYBE; // TRUE when "diff -a" works, FALSE when it
48 				 // doesn't work, MAYBE when not checked yet
49 #if defined(MSWIN)
50 static int diff_bin_works = MAYBE; // TRUE when "diff --binary" works, FALSE
51 				   // when it doesn't work, MAYBE when not
52 				   // checked yet
53 #endif
54 
55 // used for diff input
56 typedef struct {
57     char_u	*din_fname;  // used for external diff
58     mmfile_t	din_mmfile;  // used for internal diff
59 } diffin_T;
60 
61 // used for diff result
62 typedef struct {
63     char_u	*dout_fname;  // used for external diff
64     garray_T	dout_ga;      // used for internal diff
65 } diffout_T;
66 
67 // two diff inputs and one result
68 typedef struct {
69     diffin_T	dio_orig;     // original file input
70     diffin_T	dio_new;      // new file input
71     diffout_T	dio_diff;     // diff result
72     int		dio_internal; // using internal diff
73 } diffio_T;
74 
75 static int diff_buf_idx(buf_T *buf);
76 static int diff_buf_idx_tp(buf_T *buf, tabpage_T *tp);
77 static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T line2, long amount, long amount_after);
78 static void diff_check_unchanged(tabpage_T *tp, diff_T *dp);
79 static int diff_check_sanity(tabpage_T *tp, diff_T *dp);
80 static int check_external_diff(diffio_T *diffio);
81 static int diff_file(diffio_T *diffio);
82 static int diff_equal_entry(diff_T *dp, int idx1, int idx2);
83 static int diff_cmp(char_u *s1, char_u *s2);
84 #ifdef FEAT_FOLDING
85 static void diff_fold_update(diff_T *dp, int skip_idx);
86 #endif
87 static void diff_read(int idx_orig, int idx_new, diffout_T *fname);
88 static void diff_copy_entry(diff_T *dprev, diff_T *dp, int idx_orig, int idx_new);
89 static diff_T *diff_alloc_new(tabpage_T *tp, diff_T *dprev, diff_T *dp);
90 static int parse_diff_ed(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new);
91 static int parse_diff_unified(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new);
92 static int xdiff_out(void *priv, mmbuffer_t *mb, int nbuf);
93 
94 #define FOR_ALL_DIFFBLOCKS_IN_TAB(tp, dp) \
95     for ((dp) = (tp)->tp_first_diff; (dp) != NULL; (dp) = (dp)->df_next)
96 
97 /*
98  * Called when deleting or unloading a buffer: No longer make a diff with it.
99  */
100     void
101 diff_buf_delete(buf_T *buf)
102 {
103     int		i;
104     tabpage_T	*tp;
105 
106     FOR_ALL_TABPAGES(tp)
107     {
108 	i = diff_buf_idx_tp(buf, tp);
109 	if (i != DB_COUNT)
110 	{
111 	    tp->tp_diffbuf[i] = NULL;
112 	    tp->tp_diff_invalid = TRUE;
113 	    if (tp == curtab)
114 		diff_redraw(TRUE);
115 	}
116     }
117 }
118 
119 /*
120  * Check if the current buffer should be added to or removed from the list of
121  * diff buffers.
122  */
123     void
124 diff_buf_adjust(win_T *win)
125 {
126     win_T	*wp;
127     int		i;
128 
129     if (!win->w_p_diff)
130     {
131 	// When there is no window showing a diff for this buffer, remove
132 	// it from the diffs.
133 	FOR_ALL_WINDOWS(wp)
134 	    if (wp->w_buffer == win->w_buffer && wp->w_p_diff)
135 		break;
136 	if (wp == NULL)
137 	{
138 	    i = diff_buf_idx(win->w_buffer);
139 	    if (i != DB_COUNT)
140 	    {
141 		curtab->tp_diffbuf[i] = NULL;
142 		curtab->tp_diff_invalid = TRUE;
143 		diff_redraw(TRUE);
144 	    }
145 	}
146     }
147     else
148 	diff_buf_add(win->w_buffer);
149 }
150 
151 /*
152  * Add a buffer to make diffs for.
153  * Call this when a new buffer is being edited in the current window where
154  * 'diff' is set.
155  * Marks the current buffer as being part of the diff and requiring updating.
156  * This must be done before any autocmd, because a command may use info
157  * about the screen contents.
158  */
159     void
160 diff_buf_add(buf_T *buf)
161 {
162     int		i;
163 
164     if (diff_buf_idx(buf) != DB_COUNT)
165 	return;		// It's already there.
166 
167     for (i = 0; i < DB_COUNT; ++i)
168 	if (curtab->tp_diffbuf[i] == NULL)
169 	{
170 	    curtab->tp_diffbuf[i] = buf;
171 	    curtab->tp_diff_invalid = TRUE;
172 	    diff_redraw(TRUE);
173 	    return;
174 	}
175 
176     semsg(_("E96: Cannot diff more than %d buffers"), DB_COUNT);
177 }
178 
179 /*
180  * Remove all buffers to make diffs for.
181  */
182     static void
183 diff_buf_clear(void)
184 {
185     int		i;
186 
187     for (i = 0; i < DB_COUNT; ++i)
188 	if (curtab->tp_diffbuf[i] != NULL)
189 	{
190 	    curtab->tp_diffbuf[i] = NULL;
191 	    curtab->tp_diff_invalid = TRUE;
192 	    diff_redraw(TRUE);
193 	}
194 }
195 
196 /*
197  * Find buffer "buf" in the list of diff buffers for the current tab page.
198  * Return its index or DB_COUNT if not found.
199  */
200     static int
201 diff_buf_idx(buf_T *buf)
202 {
203     int		idx;
204 
205     for (idx = 0; idx < DB_COUNT; ++idx)
206 	if (curtab->tp_diffbuf[idx] == buf)
207 	    break;
208     return idx;
209 }
210 
211 /*
212  * Find buffer "buf" in the list of diff buffers for tab page "tp".
213  * Return its index or DB_COUNT if not found.
214  */
215     static int
216 diff_buf_idx_tp(buf_T *buf, tabpage_T *tp)
217 {
218     int		idx;
219 
220     for (idx = 0; idx < DB_COUNT; ++idx)
221 	if (tp->tp_diffbuf[idx] == buf)
222 	    break;
223     return idx;
224 }
225 
226 /*
227  * Mark the diff info involving buffer "buf" as invalid, it will be updated
228  * when info is requested.
229  */
230     void
231 diff_invalidate(buf_T *buf)
232 {
233     tabpage_T	*tp;
234     int		i;
235 
236     FOR_ALL_TABPAGES(tp)
237     {
238 	i = diff_buf_idx_tp(buf, tp);
239 	if (i != DB_COUNT)
240 	{
241 	    tp->tp_diff_invalid = TRUE;
242 	    if (tp == curtab)
243 		diff_redraw(TRUE);
244 	}
245     }
246 }
247 
248 /*
249  * Called by mark_adjust(): update line numbers in "curbuf".
250  */
251     void
252 diff_mark_adjust(
253     linenr_T	line1,
254     linenr_T	line2,
255     long	amount,
256     long	amount_after)
257 {
258     int		idx;
259     tabpage_T	*tp;
260 
261     // Handle all tab pages that use the current buffer in a diff.
262     FOR_ALL_TABPAGES(tp)
263     {
264 	idx = diff_buf_idx_tp(curbuf, tp);
265 	if (idx != DB_COUNT)
266 	    diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after);
267     }
268 }
269 
270 /*
271  * Update line numbers in tab page "tp" for "curbuf" with index "idx".
272  * This attempts to update the changes as much as possible:
273  * When inserting/deleting lines outside of existing change blocks, create a
274  * new change block and update the line numbers in following blocks.
275  * When inserting/deleting lines in existing change blocks, update them.
276  */
277     static void
278 diff_mark_adjust_tp(
279     tabpage_T	*tp,
280     int		idx,
281     linenr_T	line1,
282     linenr_T	line2,
283     long	amount,
284     long	amount_after)
285 {
286     diff_T	*dp;
287     diff_T	*dprev;
288     diff_T	*dnext;
289     int		i;
290     int		inserted, deleted;
291     int		n, off;
292     linenr_T	last;
293     linenr_T	lnum_deleted = line1;	// lnum of remaining deletion
294     int		check_unchanged;
295 
296     if (diff_internal())
297     {
298 	// Will update diffs before redrawing.  Set _invalid to update the
299 	// diffs themselves, set _update to also update folds properly just
300 	// before redrawing.
301 	// Do update marks here, it is needed for :%diffput.
302 	tp->tp_diff_invalid = TRUE;
303 	tp->tp_diff_update = TRUE;
304     }
305 
306     if (line2 == MAXLNUM)
307     {
308 	// mark_adjust(99, MAXLNUM, 9, 0): insert lines
309 	inserted = amount;
310 	deleted = 0;
311     }
312     else if (amount_after > 0)
313     {
314 	// mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines
315 	inserted = amount_after;
316 	deleted = 0;
317     }
318     else
319     {
320 	// mark_adjust(98, 99, MAXLNUM, -2): delete lines
321 	inserted = 0;
322 	deleted = -amount_after;
323     }
324 
325     dprev = NULL;
326     dp = tp->tp_first_diff;
327     for (;;)
328     {
329 	// If the change is after the previous diff block and before the next
330 	// diff block, thus not touching an existing change, create a new diff
331 	// block.  Don't do this when ex_diffgetput() is busy.
332 	if ((dp == NULL || dp->df_lnum[idx] - 1 > line2
333 		    || (line2 == MAXLNUM && dp->df_lnum[idx] > line1))
334 		&& (dprev == NULL
335 		    || dprev->df_lnum[idx] + dprev->df_count[idx] < line1)
336 		&& !diff_busy)
337 	{
338 	    dnext = diff_alloc_new(tp, dprev, dp);
339 	    if (dnext == NULL)
340 		return;
341 
342 	    dnext->df_lnum[idx] = line1;
343 	    dnext->df_count[idx] = inserted;
344 	    for (i = 0; i < DB_COUNT; ++i)
345 		if (tp->tp_diffbuf[i] != NULL && i != idx)
346 		{
347 		    if (dprev == NULL)
348 			dnext->df_lnum[i] = line1;
349 		    else
350 			dnext->df_lnum[i] = line1
351 			    + (dprev->df_lnum[i] + dprev->df_count[i])
352 			    - (dprev->df_lnum[idx] + dprev->df_count[idx]);
353 		    dnext->df_count[i] = deleted;
354 		}
355 	}
356 
357 	// if at end of the list, quit
358 	if (dp == NULL)
359 	    break;
360 
361 	/*
362 	 * Check for these situations:
363 	 *	  1  2	3
364 	 *	  1  2	3
365 	 * line1     2	3  4  5
366 	 *	     2	3  4  5
367 	 *	     2	3  4  5
368 	 * line2     2	3  4  5
369 	 *		3     5  6
370 	 *		3     5  6
371 	 */
372 	// compute last line of this change
373 	last = dp->df_lnum[idx] + dp->df_count[idx] - 1;
374 
375 	// 1. change completely above line1: nothing to do
376 	if (last >= line1 - 1)
377 	{
378 	    // 6. change below line2: only adjust for amount_after; also when
379 	    // "deleted" became zero when deleted all lines between two diffs
380 	    if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2)
381 	    {
382 		if (amount_after == 0)
383 		    break;	// nothing left to change
384 		dp->df_lnum[idx] += amount_after;
385 	    }
386 	    else
387 	    {
388 		check_unchanged = FALSE;
389 
390 		// 2. 3. 4. 5.: inserted/deleted lines touching this diff.
391 		if (deleted > 0)
392 		{
393 		    if (dp->df_lnum[idx] >= line1)
394 		    {
395 			off = dp->df_lnum[idx] - lnum_deleted;
396 			if (last <= line2)
397 			{
398 			    // 4. delete all lines of diff
399 			    if (dp->df_next != NULL
400 				    && dp->df_next->df_lnum[idx] - 1 <= line2)
401 			    {
402 				// delete continues in next diff, only do
403 				// lines until that one
404 				n = dp->df_next->df_lnum[idx] - lnum_deleted;
405 				deleted -= n;
406 				n -= dp->df_count[idx];
407 				lnum_deleted = dp->df_next->df_lnum[idx];
408 			    }
409 			    else
410 				n = deleted - dp->df_count[idx];
411 			    dp->df_count[idx] = 0;
412 			}
413 			else
414 			{
415 			    // 5. delete lines at or just before top of diff
416 			    n = off;
417 			    dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1;
418 			    check_unchanged = TRUE;
419 			}
420 			dp->df_lnum[idx] = line1;
421 		    }
422 		    else
423 		    {
424 			off = 0;
425 			if (last < line2)
426 			{
427 			    // 2. delete at end of diff
428 			    dp->df_count[idx] -= last - lnum_deleted + 1;
429 			    if (dp->df_next != NULL
430 				    && dp->df_next->df_lnum[idx] - 1 <= line2)
431 			    {
432 				// delete continues in next diff, only do
433 				// lines until that one
434 				n = dp->df_next->df_lnum[idx] - 1 - last;
435 				deleted -= dp->df_next->df_lnum[idx]
436 							       - lnum_deleted;
437 				lnum_deleted = dp->df_next->df_lnum[idx];
438 			    }
439 			    else
440 				n = line2 - last;
441 			    check_unchanged = TRUE;
442 			}
443 			else
444 			{
445 			    // 3. delete lines inside the diff
446 			    n = 0;
447 			    dp->df_count[idx] -= deleted;
448 			}
449 		    }
450 
451 		    for (i = 0; i < DB_COUNT; ++i)
452 			if (tp->tp_diffbuf[i] != NULL && i != idx)
453 			{
454 			    dp->df_lnum[i] -= off;
455 			    dp->df_count[i] += n;
456 			}
457 		}
458 		else
459 		{
460 		    if (dp->df_lnum[idx] <= line1)
461 		    {
462 			// inserted lines somewhere in this diff
463 			dp->df_count[idx] += inserted;
464 			check_unchanged = TRUE;
465 		    }
466 		    else
467 			// inserted lines somewhere above this diff
468 			dp->df_lnum[idx] += inserted;
469 		}
470 
471 		if (check_unchanged)
472 		    // Check if inserted lines are equal, may reduce the
473 		    // size of the diff.  TODO: also check for equal lines
474 		    // in the middle and perhaps split the block.
475 		    diff_check_unchanged(tp, dp);
476 	    }
477 	}
478 
479 	// check if this block touches the previous one, may merge them.
480 	if (dprev != NULL && dprev->df_lnum[idx] + dprev->df_count[idx]
481 							  == dp->df_lnum[idx])
482 	{
483 	    for (i = 0; i < DB_COUNT; ++i)
484 		if (tp->tp_diffbuf[i] != NULL)
485 		    dprev->df_count[i] += dp->df_count[i];
486 	    dprev->df_next = dp->df_next;
487 	    vim_free(dp);
488 	    dp = dprev->df_next;
489 	}
490 	else
491 	{
492 	    // Advance to next entry.
493 	    dprev = dp;
494 	    dp = dp->df_next;
495 	}
496     }
497 
498     dprev = NULL;
499     dp = tp->tp_first_diff;
500     while (dp != NULL)
501     {
502 	// All counts are zero, remove this entry.
503 	for (i = 0; i < DB_COUNT; ++i)
504 	    if (tp->tp_diffbuf[i] != NULL && dp->df_count[i] != 0)
505 		break;
506 	if (i == DB_COUNT)
507 	{
508 	    dnext = dp->df_next;
509 	    vim_free(dp);
510 	    dp = dnext;
511 	    if (dprev == NULL)
512 		tp->tp_first_diff = dnext;
513 	    else
514 		dprev->df_next = dnext;
515 	}
516 	else
517 	{
518 	    // Advance to next entry.
519 	    dprev = dp;
520 	    dp = dp->df_next;
521 	}
522 
523     }
524 
525     if (tp == curtab)
526     {
527 	// Don't redraw right away, this updates the diffs, which can be slow.
528 	need_diff_redraw = TRUE;
529 
530 	// Need to recompute the scroll binding, may remove or add filler
531 	// lines (e.g., when adding lines above w_topline). But it's slow when
532 	// making many changes, postpone until redrawing.
533 	diff_need_scrollbind = TRUE;
534     }
535 }
536 
537 /*
538  * Allocate a new diff block and link it between "dprev" and "dp".
539  */
540     static diff_T *
541 diff_alloc_new(tabpage_T *tp, diff_T *dprev, diff_T *dp)
542 {
543     diff_T	*dnew;
544 
545     dnew = ALLOC_ONE(diff_T);
546     if (dnew != NULL)
547     {
548 	dnew->df_next = dp;
549 	if (dprev == NULL)
550 	    tp->tp_first_diff = dnew;
551 	else
552 	    dprev->df_next = dnew;
553     }
554     return dnew;
555 }
556 
557 /*
558  * Check if the diff block "dp" can be made smaller for lines at the start and
559  * end that are equal.  Called after inserting lines.
560  * This may result in a change where all buffers have zero lines, the caller
561  * must take care of removing it.
562  */
563     static void
564 diff_check_unchanged(tabpage_T *tp, diff_T *dp)
565 {
566     int		i_org;
567     int		i_new;
568     int		off_org, off_new;
569     char_u	*line_org;
570     int		dir = FORWARD;
571 
572     // Find the first buffers, use it as the original, compare the other
573     // buffer lines against this one.
574     for (i_org = 0; i_org < DB_COUNT; ++i_org)
575 	if (tp->tp_diffbuf[i_org] != NULL)
576 	    break;
577     if (i_org == DB_COUNT)	// safety check
578 	return;
579 
580     if (diff_check_sanity(tp, dp) == FAIL)
581 	return;
582 
583     // First check lines at the top, then at the bottom.
584     off_org = 0;
585     off_new = 0;
586     for (;;)
587     {
588 	// Repeat until a line is found which is different or the number of
589 	// lines has become zero.
590 	while (dp->df_count[i_org] > 0)
591 	{
592 	    // Copy the line, the next ml_get() will invalidate it.
593 	    if (dir == BACKWARD)
594 		off_org = dp->df_count[i_org] - 1;
595 	    line_org = vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org],
596 					dp->df_lnum[i_org] + off_org, FALSE));
597 	    if (line_org == NULL)
598 		return;
599 	    for (i_new = i_org + 1; i_new < DB_COUNT; ++i_new)
600 	    {
601 		if (tp->tp_diffbuf[i_new] == NULL)
602 		    continue;
603 		if (dir == BACKWARD)
604 		    off_new = dp->df_count[i_new] - 1;
605 		// if other buffer doesn't have this line, it was inserted
606 		if (off_new < 0 || off_new >= dp->df_count[i_new])
607 		    break;
608 		if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new],
609 				   dp->df_lnum[i_new] + off_new, FALSE)) != 0)
610 		    break;
611 	    }
612 	    vim_free(line_org);
613 
614 	    // Stop when a line isn't equal in all diff buffers.
615 	    if (i_new != DB_COUNT)
616 		break;
617 
618 	    // Line matched in all buffers, remove it from the diff.
619 	    for (i_new = i_org; i_new < DB_COUNT; ++i_new)
620 		if (tp->tp_diffbuf[i_new] != NULL)
621 		{
622 		    if (dir == FORWARD)
623 			++dp->df_lnum[i_new];
624 		    --dp->df_count[i_new];
625 		}
626 	}
627 	if (dir == BACKWARD)
628 	    break;
629 	dir = BACKWARD;
630     }
631 }
632 
633 /*
634  * Check if a diff block doesn't contain invalid line numbers.
635  * This can happen when the diff program returns invalid results.
636  */
637     static int
638 diff_check_sanity(tabpage_T *tp, diff_T *dp)
639 {
640     int		i;
641 
642     for (i = 0; i < DB_COUNT; ++i)
643 	if (tp->tp_diffbuf[i] != NULL)
644 	    if (dp->df_lnum[i] + dp->df_count[i] - 1
645 				      > tp->tp_diffbuf[i]->b_ml.ml_line_count)
646 		return FAIL;
647     return OK;
648 }
649 
650 /*
651  * Mark all diff buffers in the current tab page for redraw.
652  */
653     void
654 diff_redraw(
655     int		dofold)	    // also recompute the folds
656 {
657     win_T	*wp;
658     int		n;
659 
660     need_diff_redraw = FALSE;
661     FOR_ALL_WINDOWS(wp)
662 	if (wp->w_p_diff)
663 	{
664 	    redraw_win_later(wp, SOME_VALID);
665 #ifdef FEAT_FOLDING
666 	    if (dofold && foldmethodIsDiff(wp))
667 		foldUpdateAll(wp);
668 #endif
669 	    // A change may have made filler lines invalid, need to take care
670 	    // of that for other windows.
671 	    n = diff_check(wp, wp->w_topline);
672 	    if ((wp != curwin && wp->w_topfill > 0) || n > 0)
673 	    {
674 		if (wp->w_topfill > n)
675 		    wp->w_topfill = (n < 0 ? 0 : n);
676 		else if (n > 0 && n > wp->w_topfill)
677 		    wp->w_topfill = n;
678 		check_topfill(wp, FALSE);
679 	    }
680 	}
681 }
682 
683     static void
684 clear_diffin(diffin_T *din)
685 {
686     if (din->din_fname == NULL)
687     {
688 	vim_free(din->din_mmfile.ptr);
689 	din->din_mmfile.ptr = NULL;
690     }
691     else
692 	mch_remove(din->din_fname);
693 }
694 
695     static void
696 clear_diffout(diffout_T *dout)
697 {
698     if (dout->dout_fname == NULL)
699 	ga_clear_strings(&dout->dout_ga);
700     else
701 	mch_remove(dout->dout_fname);
702 }
703 
704 /*
705  * Write buffer "buf" to a memory buffer.
706  * Return FAIL for failure.
707  */
708     static int
709 diff_write_buffer(buf_T *buf, diffin_T *din)
710 {
711     linenr_T	lnum;
712     char_u	*s;
713     long	len = 0;
714     char_u	*ptr;
715 
716     // xdiff requires one big block of memory with all the text.
717     for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum)
718 	len += (long)STRLEN(ml_get_buf(buf, lnum, FALSE)) + 1;
719     ptr = alloc(len);
720     if (ptr == NULL)
721     {
722 	// Allocating memory failed.  This can happen, because we try to read
723 	// the whole buffer text into memory.  Set the failed flag, the diff
724 	// will be retried with external diff.  The flag is never reset.
725 	buf->b_diff_failed = TRUE;
726 	if (p_verbose > 0)
727 	{
728 	    verbose_enter();
729 	    smsg(_("Not enough memory to use internal diff for buffer \"%s\""),
730 								 buf->b_fname);
731 	    verbose_leave();
732 	}
733 	return FAIL;
734     }
735     din->din_mmfile.ptr = (char *)ptr;
736     din->din_mmfile.size = len;
737 
738     len = 0;
739     for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum)
740     {
741 	for (s = ml_get_buf(buf, lnum, FALSE); *s != NUL; )
742 	{
743 	    if (diff_flags & DIFF_ICASE)
744 	    {
745 		int c;
746 		int	orig_len;
747 		char_u	cbuf[MB_MAXBYTES + 1];
748 
749 		// xdiff doesn't support ignoring case, fold-case the text.
750 		c = PTR2CHAR(s);
751 		c = MB_CASEFOLD(c);
752 		orig_len = mb_ptr2len(s);
753 		if (mb_char2bytes(c, cbuf) != orig_len)
754 		    // TODO: handle byte length difference
755 		    mch_memmove(ptr + len, s, orig_len);
756 		else
757 		    mch_memmove(ptr + len, cbuf, orig_len);
758 
759 		s += orig_len;
760 		len += orig_len;
761 	    }
762 	    else
763 		ptr[len++] = *s++;
764 	}
765 	ptr[len++] = NL;
766     }
767     return OK;
768 }
769 
770 /*
771  * Write buffer "buf" to file or memory buffer.
772  * Return FAIL for failure.
773  */
774     static int
775 diff_write(buf_T *buf, diffin_T *din)
776 {
777     int		r;
778     char_u	*save_ff;
779     int		save_cmod_flags;
780 
781     if (din->din_fname == NULL)
782 	return diff_write_buffer(buf, din);
783 
784     // Always use 'fileformat' set to "unix".
785     save_ff = buf->b_p_ff;
786     buf->b_p_ff = vim_strsave((char_u *)FF_UNIX);
787     save_cmod_flags = cmdmod.cmod_flags;
788     // Writing the buffer is an implementation detail of performing the diff,
789     // so it shouldn't update the '[ and '] marks.
790     cmdmod.cmod_flags |= CMOD_LOCKMARKS;
791     r = buf_write(buf, din->din_fname, NULL,
792 			(linenr_T)1, buf->b_ml.ml_line_count,
793 			NULL, FALSE, FALSE, FALSE, TRUE);
794     cmdmod.cmod_flags = save_cmod_flags;
795     free_string_option(buf->b_p_ff);
796     buf->b_p_ff = save_ff;
797     return r;
798 }
799 
800 /*
801  * Update the diffs for all buffers involved.
802  */
803     static void
804 diff_try_update(
805 	diffio_T    *dio,
806 	int	    idx_orig,
807 	exarg_T	    *eap)	// "eap" can be NULL
808 {
809     buf_T	*buf;
810     int		idx_new;
811 
812     if (dio->dio_internal)
813     {
814 	ga_init2(&dio->dio_diff.dout_ga, sizeof(char *), 1000);
815     }
816     else
817     {
818 	// We need three temp file names.
819 	dio->dio_orig.din_fname = vim_tempname('o', TRUE);
820 	dio->dio_new.din_fname = vim_tempname('n', TRUE);
821 	dio->dio_diff.dout_fname = vim_tempname('d', TRUE);
822 	if (dio->dio_orig.din_fname == NULL
823 		|| dio->dio_new.din_fname == NULL
824 		|| dio->dio_diff.dout_fname == NULL)
825 	    goto theend;
826     }
827 
828     // Check external diff is actually working.
829     if (!dio->dio_internal && check_external_diff(dio) == FAIL)
830 	goto theend;
831 
832     // :diffupdate!
833     if (eap != NULL && eap->forceit)
834 	for (idx_new = idx_orig; idx_new < DB_COUNT; ++idx_new)
835 	{
836 	    buf = curtab->tp_diffbuf[idx_new];
837 	    if (buf_valid(buf))
838 		buf_check_timestamp(buf, FALSE);
839 	}
840 
841     // Write the first buffer to a tempfile or mmfile_t.
842     buf = curtab->tp_diffbuf[idx_orig];
843     if (diff_write(buf, &dio->dio_orig) == FAIL)
844 	goto theend;
845 
846     // Make a difference between the first buffer and every other.
847     for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new)
848     {
849 	buf = curtab->tp_diffbuf[idx_new];
850 	if (buf == NULL || buf->b_ml.ml_mfp == NULL)
851 	    continue; // skip buffer that isn't loaded
852 
853 	// Write the other buffer and diff with the first one.
854 	if (diff_write(buf, &dio->dio_new) == FAIL)
855 	    continue;
856 	if (diff_file(dio) == FAIL)
857 	    continue;
858 
859 	// Read the diff output and add each entry to the diff list.
860 	diff_read(idx_orig, idx_new, &dio->dio_diff);
861 
862 	clear_diffin(&dio->dio_new);
863 	clear_diffout(&dio->dio_diff);
864     }
865     clear_diffin(&dio->dio_orig);
866 
867 theend:
868     vim_free(dio->dio_orig.din_fname);
869     vim_free(dio->dio_new.din_fname);
870     vim_free(dio->dio_diff.dout_fname);
871 }
872 
873 /*
874  * Return TRUE if the options are set to use the internal diff library.
875  * Note that if the internal diff failed for one of the buffers, the external
876  * diff will be used anyway.
877  */
878     int
879 diff_internal(void)
880 {
881     return (diff_flags & DIFF_INTERNAL) != 0
882 #ifdef FEAT_EVAL
883 	&& *p_dex == NUL
884 #endif
885 	;
886 }
887 
888 /*
889  * Return TRUE if the internal diff failed for one of the diff buffers.
890  */
891     static int
892 diff_internal_failed(void)
893 {
894     int idx;
895 
896     // Only need to do something when there is another buffer.
897     for (idx = 0; idx < DB_COUNT; ++idx)
898 	if (curtab->tp_diffbuf[idx] != NULL
899 		&& curtab->tp_diffbuf[idx]->b_diff_failed)
900 	    return TRUE;
901     return FALSE;
902 }
903 
904 /*
905  * Completely update the diffs for the buffers involved.
906  * When using the external "diff" command the buffers are written to a file,
907  * also for unmodified buffers (the file could have been produced by
908  * autocommands, e.g. the netrw plugin).
909  */
910     void
911 ex_diffupdate(exarg_T *eap)	// "eap" can be NULL
912 {
913     int		idx_orig;
914     int		idx_new;
915     diffio_T	diffio;
916     int		had_diffs = curtab->tp_first_diff != NULL;
917 
918     if (diff_busy)
919     {
920 	diff_need_update = TRUE;
921 	return;
922     }
923 
924     // Delete all diffblocks.
925     diff_clear(curtab);
926     curtab->tp_diff_invalid = FALSE;
927 
928     // Use the first buffer as the original text.
929     for (idx_orig = 0; idx_orig < DB_COUNT; ++idx_orig)
930 	if (curtab->tp_diffbuf[idx_orig] != NULL)
931 	    break;
932     if (idx_orig == DB_COUNT)
933 	goto theend;
934 
935     // Only need to do something when there is another buffer.
936     for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new)
937 	if (curtab->tp_diffbuf[idx_new] != NULL)
938 	    break;
939     if (idx_new == DB_COUNT)
940 	goto theend;
941 
942     // Only use the internal method if it did not fail for one of the buffers.
943     CLEAR_FIELD(diffio);
944     diffio.dio_internal = diff_internal() && !diff_internal_failed();
945 
946     diff_try_update(&diffio, idx_orig, eap);
947     if (diffio.dio_internal && diff_internal_failed())
948     {
949 	// Internal diff failed, use external diff instead.
950 	CLEAR_FIELD(diffio);
951 	diff_try_update(&diffio, idx_orig, eap);
952     }
953 
954     // force updating cursor position on screen
955     curwin->w_valid_cursor.lnum = 0;
956 
957 theend:
958     // A redraw is needed if there were diffs and they were cleared, or there
959     // are diffs now, which means they got updated.
960     if (had_diffs || curtab->tp_first_diff != NULL)
961     {
962 	diff_redraw(TRUE);
963 	apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf);
964     }
965 }
966 
967 /*
968  * Do a quick test if "diff" really works.  Otherwise it looks like there
969  * are no differences.  Can't use the return value, it's non-zero when
970  * there are differences.
971  */
972     static int
973 check_external_diff(diffio_T *diffio)
974 {
975     FILE	*fd;
976     int		ok;
977     int		io_error = FALSE;
978 
979     // May try twice, first with "-a" and then without.
980     for (;;)
981     {
982 	ok = FALSE;
983 	fd = mch_fopen((char *)diffio->dio_orig.din_fname, "w");
984 	if (fd == NULL)
985 	    io_error = TRUE;
986 	else
987 	{
988 	    if (fwrite("line1\n", (size_t)6, (size_t)1, fd) != 1)
989 		io_error = TRUE;
990 	    fclose(fd);
991 	    fd = mch_fopen((char *)diffio->dio_new.din_fname, "w");
992 	    if (fd == NULL)
993 		io_error = TRUE;
994 	    else
995 	    {
996 		if (fwrite("line2\n", (size_t)6, (size_t)1, fd) != 1)
997 		    io_error = TRUE;
998 		fclose(fd);
999 		fd = NULL;
1000 		if (diff_file(diffio) == OK)
1001 		    fd = mch_fopen((char *)diffio->dio_diff.dout_fname, "r");
1002 		if (fd == NULL)
1003 		    io_error = TRUE;
1004 		else
1005 		{
1006 		    char_u	linebuf[LBUFLEN];
1007 
1008 		    for (;;)
1009 		    {
1010 			// There must be a line that contains "1c1".
1011 			if (vim_fgets(linebuf, LBUFLEN, fd))
1012 			    break;
1013 			if (STRNCMP(linebuf, "1c1", 3) == 0)
1014 			    ok = TRUE;
1015 		    }
1016 		    fclose(fd);
1017 		}
1018 		mch_remove(diffio->dio_diff.dout_fname);
1019 		mch_remove(diffio->dio_new.din_fname);
1020 	    }
1021 	    mch_remove(diffio->dio_orig.din_fname);
1022 	}
1023 
1024 #ifdef FEAT_EVAL
1025 	// When using 'diffexpr' break here.
1026 	if (*p_dex != NUL)
1027 	    break;
1028 #endif
1029 
1030 #if defined(MSWIN)
1031 	// If the "-a" argument works, also check if "--binary" works.
1032 	if (ok && diff_a_works == MAYBE && diff_bin_works == MAYBE)
1033 	{
1034 	    diff_a_works = TRUE;
1035 	    diff_bin_works = TRUE;
1036 	    continue;
1037 	}
1038 	if (!ok && diff_a_works == TRUE && diff_bin_works == TRUE)
1039 	{
1040 	    // Tried --binary, but it failed. "-a" works though.
1041 	    diff_bin_works = FALSE;
1042 	    ok = TRUE;
1043 	}
1044 #endif
1045 
1046 	// If we checked if "-a" works already, break here.
1047 	if (diff_a_works != MAYBE)
1048 	    break;
1049 	diff_a_works = ok;
1050 
1051 	// If "-a" works break here, otherwise retry without "-a".
1052 	if (ok)
1053 	    break;
1054     }
1055     if (!ok)
1056     {
1057 	if (io_error)
1058 	    emsg(_("E810: Cannot read or write temp files"));
1059 	emsg(_("E97: Cannot create diffs"));
1060 	diff_a_works = MAYBE;
1061 #if defined(MSWIN)
1062 	diff_bin_works = MAYBE;
1063 #endif
1064 	return FAIL;
1065     }
1066     return OK;
1067 }
1068 
1069 /*
1070  * Invoke the xdiff function.
1071  */
1072     static int
1073 diff_file_internal(diffio_T *diffio)
1074 {
1075     xpparam_t	    param;
1076     xdemitconf_t    emit_cfg;
1077     xdemitcb_t	    emit_cb;
1078 
1079     CLEAR_FIELD(param);
1080     CLEAR_FIELD(emit_cfg);
1081     CLEAR_FIELD(emit_cb);
1082 
1083     param.flags = diff_algorithm;
1084 
1085     if (diff_flags & DIFF_IWHITE)
1086 	param.flags |= XDF_IGNORE_WHITESPACE_CHANGE;
1087     if (diff_flags & DIFF_IWHITEALL)
1088 	param.flags |= XDF_IGNORE_WHITESPACE;
1089     if (diff_flags & DIFF_IWHITEEOL)
1090 	param.flags |= XDF_IGNORE_WHITESPACE_AT_EOL;
1091     if (diff_flags & DIFF_IBLANK)
1092 	param.flags |= XDF_IGNORE_BLANK_LINES;
1093 
1094     emit_cfg.ctxlen = 0; // don't need any diff_context here
1095     emit_cb.priv = &diffio->dio_diff;
1096     emit_cb.outf = xdiff_out;
1097     if (xdl_diff(&diffio->dio_orig.din_mmfile,
1098 		&diffio->dio_new.din_mmfile,
1099 		&param, &emit_cfg, &emit_cb) < 0)
1100     {
1101 	emsg(_("E960: Problem creating the internal diff"));
1102 	return FAIL;
1103     }
1104     return OK;
1105 }
1106 
1107 /*
1108  * Make a diff between files "tmp_orig" and "tmp_new", results in "tmp_diff".
1109  * return OK or FAIL;
1110  */
1111     static int
1112 diff_file(diffio_T *dio)
1113 {
1114     char_u	*cmd;
1115     size_t	len;
1116     char_u	*tmp_orig = dio->dio_orig.din_fname;
1117     char_u	*tmp_new = dio->dio_new.din_fname;
1118     char_u	*tmp_diff = dio->dio_diff.dout_fname;
1119 
1120 #ifdef FEAT_EVAL
1121     if (*p_dex != NUL)
1122     {
1123 	// Use 'diffexpr' to generate the diff file.
1124 	eval_diff(tmp_orig, tmp_new, tmp_diff);
1125 	return OK;
1126     }
1127     else
1128 #endif
1129     // Use xdiff for generating the diff.
1130     if (dio->dio_internal)
1131     {
1132 	return diff_file_internal(dio);
1133     }
1134     else
1135     {
1136 	len = STRLEN(tmp_orig) + STRLEN(tmp_new)
1137 				      + STRLEN(tmp_diff) + STRLEN(p_srr) + 27;
1138 	cmd = alloc(len);
1139 	if (cmd == NULL)
1140 	    return FAIL;
1141 
1142 	// We don't want $DIFF_OPTIONS to get in the way.
1143 	if (getenv("DIFF_OPTIONS"))
1144 	    vim_setenv((char_u *)"DIFF_OPTIONS", (char_u *)"");
1145 
1146 	// Build the diff command and execute it.  Always use -a, binary
1147 	// differences are of no use.  Ignore errors, diff returns
1148 	// non-zero when differences have been found.
1149 	vim_snprintf((char *)cmd, len, "diff %s%s%s%s%s%s%s%s %s",
1150 		diff_a_works == FALSE ? "" : "-a ",
1151 #if defined(MSWIN)
1152 		diff_bin_works == TRUE ? "--binary " : "",
1153 #else
1154 		"",
1155 #endif
1156 		(diff_flags & DIFF_IWHITE) ? "-b " : "",
1157 		(diff_flags & DIFF_IWHITEALL) ? "-w " : "",
1158 		(diff_flags & DIFF_IWHITEEOL) ? "-Z " : "",
1159 		(diff_flags & DIFF_IBLANK) ? "-B " : "",
1160 		(diff_flags & DIFF_ICASE) ? "-i " : "",
1161 		tmp_orig, tmp_new);
1162 	append_redir(cmd, (int)len, p_srr, tmp_diff);
1163 	block_autocmds();	// avoid ShellCmdPost stuff
1164 	(void)call_shell(cmd, SHELL_FILTER|SHELL_SILENT|SHELL_DOOUT);
1165 	unblock_autocmds();
1166 	vim_free(cmd);
1167 	return OK;
1168     }
1169 }
1170 
1171 /*
1172  * Create a new version of a file from the current buffer and a diff file.
1173  * The buffer is written to a file, also for unmodified buffers (the file
1174  * could have been produced by autocommands, e.g. the netrw plugin).
1175  */
1176     void
1177 ex_diffpatch(exarg_T *eap)
1178 {
1179     char_u	*tmp_orig;	// name of original temp file
1180     char_u	*tmp_new;	// name of patched temp file
1181     char_u	*buf = NULL;
1182     size_t	buflen;
1183     win_T	*old_curwin = curwin;
1184     char_u	*newname = NULL;	// name of patched file buffer
1185 #ifdef UNIX
1186     char_u	dirbuf[MAXPATHL];
1187     char_u	*fullname = NULL;
1188 #endif
1189 #ifdef FEAT_BROWSE
1190     char_u	*browseFile = NULL;
1191     int		save_cmod_flags = cmdmod.cmod_flags;
1192 #endif
1193     stat_T	st;
1194     char_u	*esc_name = NULL;
1195 
1196 #ifdef FEAT_BROWSE
1197     if (cmdmod.cmod_flags & CMOD_BROWSE)
1198     {
1199 	browseFile = do_browse(0, (char_u *)_("Patch file"),
1200 			 eap->arg, NULL, NULL,
1201 			 (char_u *)_(BROWSE_FILTER_ALL_FILES), NULL);
1202 	if (browseFile == NULL)
1203 	    return;		// operation cancelled
1204 	eap->arg = browseFile;
1205 	cmdmod.cmod_flags &= ~CMOD_BROWSE; // don't let do_ecmd() browse again
1206     }
1207 #endif
1208 
1209     // We need two temp file names.
1210     tmp_orig = vim_tempname('o', FALSE);
1211     tmp_new = vim_tempname('n', FALSE);
1212     if (tmp_orig == NULL || tmp_new == NULL)
1213 	goto theend;
1214 
1215     // Write the current buffer to "tmp_orig".
1216     if (buf_write(curbuf, tmp_orig, NULL,
1217 		(linenr_T)1, curbuf->b_ml.ml_line_count,
1218 				     NULL, FALSE, FALSE, FALSE, TRUE) == FAIL)
1219 	goto theend;
1220 
1221 #ifdef UNIX
1222     // Get the absolute path of the patchfile, changing directory below.
1223     fullname = FullName_save(eap->arg, FALSE);
1224 #endif
1225     esc_name = vim_strsave_shellescape(
1226 # ifdef UNIX
1227 		    fullname != NULL ? fullname :
1228 # endif
1229 		    eap->arg, TRUE, TRUE);
1230     if (esc_name == NULL)
1231 	goto theend;
1232     buflen = STRLEN(tmp_orig) + STRLEN(esc_name) + STRLEN(tmp_new) + 16;
1233     buf = alloc(buflen);
1234     if (buf == NULL)
1235 	goto theend;
1236 
1237 #ifdef UNIX
1238     // Temporarily chdir to /tmp, to avoid patching files in the current
1239     // directory when the patch file contains more than one patch.  When we
1240     // have our own temp dir use that instead, it will be cleaned up when we
1241     // exit (any .rej files created).  Don't change directory if we can't
1242     // return to the current.
1243     if (mch_dirname(dirbuf, MAXPATHL) != OK || mch_chdir((char *)dirbuf) != 0)
1244 	dirbuf[0] = NUL;
1245     else
1246     {
1247 # ifdef TEMPDIRNAMES
1248 	if (vim_tempdir != NULL)
1249 	    vim_ignored = mch_chdir((char *)vim_tempdir);
1250 	else
1251 # endif
1252 	    vim_ignored = mch_chdir("/tmp");
1253 	shorten_fnames(TRUE);
1254     }
1255 #endif
1256 
1257 #ifdef FEAT_EVAL
1258     if (*p_pex != NUL)
1259 	// Use 'patchexpr' to generate the new file.
1260 	eval_patch(tmp_orig,
1261 # ifdef UNIX
1262 		fullname != NULL ? fullname :
1263 # endif
1264 		eap->arg, tmp_new);
1265     else
1266 #endif
1267     {
1268 	// Build the patch command and execute it.  Ignore errors.  Switch to
1269 	// cooked mode to allow the user to respond to prompts.
1270 	vim_snprintf((char *)buf, buflen, "patch -o %s %s < %s",
1271 						  tmp_new, tmp_orig, esc_name);
1272 	block_autocmds();	// Avoid ShellCmdPost stuff
1273 	(void)call_shell(buf, SHELL_FILTER | SHELL_COOKED);
1274 	unblock_autocmds();
1275     }
1276 
1277 #ifdef UNIX
1278     if (dirbuf[0] != NUL)
1279     {
1280 	if (mch_chdir((char *)dirbuf) != 0)
1281 	    emsg(_(e_prev_dir));
1282 	shorten_fnames(TRUE);
1283     }
1284 #endif
1285 
1286     // patch probably has written over the screen
1287     redraw_later(CLEAR);
1288 
1289     // Delete any .orig or .rej file created.
1290     STRCPY(buf, tmp_new);
1291     STRCAT(buf, ".orig");
1292     mch_remove(buf);
1293     STRCPY(buf, tmp_new);
1294     STRCAT(buf, ".rej");
1295     mch_remove(buf);
1296 
1297     // Only continue if the output file was created.
1298     if (mch_stat((char *)tmp_new, &st) < 0 || st.st_size == 0)
1299 	emsg(_("E816: Cannot read patch output"));
1300     else
1301     {
1302 	if (curbuf->b_fname != NULL)
1303 	{
1304 	    newname = vim_strnsave(curbuf->b_fname,
1305 						  STRLEN(curbuf->b_fname) + 4);
1306 	    if (newname != NULL)
1307 		STRCAT(newname, ".new");
1308 	}
1309 
1310 #ifdef FEAT_GUI
1311 	need_mouse_correct = TRUE;
1312 #endif
1313 	// don't use a new tab page, each tab page has its own diffs
1314 	cmdmod.cmod_tab = 0;
1315 
1316 	if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL)
1317 	{
1318 	    // Pretend it was a ":split fname" command
1319 	    eap->cmdidx = CMD_split;
1320 	    eap->arg = tmp_new;
1321 	    do_exedit(eap, old_curwin);
1322 
1323 	    // check that split worked and editing tmp_new
1324 	    if (curwin != old_curwin && win_valid(old_curwin))
1325 	    {
1326 		// Set 'diff', 'scrollbind' on and 'wrap' off.
1327 		diff_win_options(curwin, TRUE);
1328 		diff_win_options(old_curwin, TRUE);
1329 
1330 		if (newname != NULL)
1331 		{
1332 		    // do a ":file filename.new" on the patched buffer
1333 		    eap->arg = newname;
1334 		    ex_file(eap);
1335 
1336 		    // Do filetype detection with the new name.
1337 		    if (au_has_group((char_u *)"filetypedetect"))
1338 			do_cmdline_cmd((char_u *)":doau filetypedetect BufRead");
1339 		}
1340 	    }
1341 	}
1342     }
1343 
1344 theend:
1345     if (tmp_orig != NULL)
1346 	mch_remove(tmp_orig);
1347     vim_free(tmp_orig);
1348     if (tmp_new != NULL)
1349 	mch_remove(tmp_new);
1350     vim_free(tmp_new);
1351     vim_free(newname);
1352     vim_free(buf);
1353 #ifdef UNIX
1354     vim_free(fullname);
1355 #endif
1356     vim_free(esc_name);
1357 #ifdef FEAT_BROWSE
1358     vim_free(browseFile);
1359     cmdmod.cmod_flags = save_cmod_flags;
1360 #endif
1361 }
1362 
1363 /*
1364  * Split the window and edit another file, setting options to show the diffs.
1365  */
1366     void
1367 ex_diffsplit(exarg_T *eap)
1368 {
1369     win_T	*old_curwin = curwin;
1370     bufref_T	old_curbuf;
1371 
1372     set_bufref(&old_curbuf, curbuf);
1373 #ifdef FEAT_GUI
1374     need_mouse_correct = TRUE;
1375 #endif
1376     // Need to compute w_fraction when no redraw happened yet.
1377     validate_cursor();
1378     set_fraction(curwin);
1379 
1380     // don't use a new tab page, each tab page has its own diffs
1381     cmdmod.cmod_tab = 0;
1382 
1383     if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL)
1384     {
1385 	// Pretend it was a ":split fname" command
1386 	eap->cmdidx = CMD_split;
1387 	curwin->w_p_diff = TRUE;
1388 	do_exedit(eap, old_curwin);
1389 
1390 	if (curwin != old_curwin)		// split must have worked
1391 	{
1392 	    // Set 'diff', 'scrollbind' on and 'wrap' off.
1393 	    diff_win_options(curwin, TRUE);
1394 	    if (win_valid(old_curwin))
1395 	    {
1396 		diff_win_options(old_curwin, TRUE);
1397 
1398 		if (bufref_valid(&old_curbuf))
1399 		    // Move the cursor position to that of the old window.
1400 		    curwin->w_cursor.lnum = diff_get_corresponding_line(
1401 			    old_curbuf.br_buf, old_curwin->w_cursor.lnum);
1402 	    }
1403 	    // Now that lines are folded scroll to show the cursor at the same
1404 	    // relative position.
1405 	    scroll_to_fraction(curwin, curwin->w_height);
1406 	}
1407     }
1408 }
1409 
1410 /*
1411  * Set options to show diffs for the current window.
1412  */
1413     void
1414 ex_diffthis(exarg_T *eap UNUSED)
1415 {
1416     // Set 'diff', 'scrollbind' on and 'wrap' off.
1417     diff_win_options(curwin, TRUE);
1418 }
1419 
1420     static void
1421 set_diff_option(win_T *wp, int value)
1422 {
1423     win_T *old_curwin = curwin;
1424 
1425     curwin = wp;
1426     curbuf = curwin->w_buffer;
1427     ++curbuf_lock;
1428     set_option_value((char_u *)"diff", (long)value, NULL, OPT_LOCAL);
1429     --curbuf_lock;
1430     curwin = old_curwin;
1431     curbuf = curwin->w_buffer;
1432 }
1433 
1434 /*
1435  * Set options in window "wp" for diff mode.
1436  */
1437     void
1438 diff_win_options(
1439     win_T	*wp,
1440     int		addbuf)		// Add buffer to diff.
1441 {
1442 # ifdef FEAT_FOLDING
1443     win_T *old_curwin = curwin;
1444 
1445     // close the manually opened folds
1446     curwin = wp;
1447     newFoldLevel();
1448     curwin = old_curwin;
1449 # endif
1450 
1451     // Use 'scrollbind' and 'cursorbind' when available
1452     if (!wp->w_p_diff)
1453 	wp->w_p_scb_save = wp->w_p_scb;
1454     wp->w_p_scb = TRUE;
1455     if (!wp->w_p_diff)
1456 	wp->w_p_crb_save = wp->w_p_crb;
1457     wp->w_p_crb = TRUE;
1458     if (!(diff_flags & DIFF_FOLLOWWRAP))
1459     {
1460         if (!wp->w_p_diff)
1461 	    wp->w_p_wrap_save = wp->w_p_wrap;
1462         wp->w_p_wrap = FALSE;
1463     }
1464 # ifdef FEAT_FOLDING
1465     if (!wp->w_p_diff)
1466     {
1467 	if (wp->w_p_diff_saved)
1468 	    free_string_option(wp->w_p_fdm_save);
1469 	wp->w_p_fdm_save = vim_strsave(wp->w_p_fdm);
1470     }
1471     set_string_option_direct_in_win(wp, (char_u *)"fdm", -1, (char_u *)"diff",
1472 						       OPT_LOCAL|OPT_FREE, 0);
1473     if (!wp->w_p_diff)
1474     {
1475 	wp->w_p_fdc_save = wp->w_p_fdc;
1476 	wp->w_p_fen_save = wp->w_p_fen;
1477 	wp->w_p_fdl_save = wp->w_p_fdl;
1478     }
1479     wp->w_p_fdc = diff_foldcolumn;
1480     wp->w_p_fen = TRUE;
1481     wp->w_p_fdl = 0;
1482     foldUpdateAll(wp);
1483     // make sure topline is not halfway a fold
1484     changed_window_setting_win(wp);
1485 # endif
1486     if (vim_strchr(p_sbo, 'h') == NULL)
1487 	do_cmdline_cmd((char_u *)"set sbo+=hor");
1488     // Save the current values, to be restored in ex_diffoff().
1489     wp->w_p_diff_saved = TRUE;
1490 
1491     set_diff_option(wp, TRUE);
1492 
1493     if (addbuf)
1494 	diff_buf_add(wp->w_buffer);
1495     redraw_win_later(wp, NOT_VALID);
1496 }
1497 
1498 /*
1499  * Set options not to show diffs.  For the current window or all windows.
1500  * Only in the current tab page.
1501  */
1502     void
1503 ex_diffoff(exarg_T *eap)
1504 {
1505     win_T	*wp;
1506     int		diffwin = FALSE;
1507 
1508     FOR_ALL_WINDOWS(wp)
1509     {
1510 	if (eap->forceit ? wp->w_p_diff : wp == curwin)
1511 	{
1512 	    // Set 'diff' off. If option values were saved in
1513 	    // diff_win_options(), restore the ones whose settings seem to have
1514 	    // been left over from diff mode.
1515 	    set_diff_option(wp, FALSE);
1516 
1517 	    if (wp->w_p_diff_saved)
1518 	    {
1519 
1520 		if (wp->w_p_scb)
1521 		    wp->w_p_scb = wp->w_p_scb_save;
1522 		if (wp->w_p_crb)
1523 		    wp->w_p_crb = wp->w_p_crb_save;
1524 		if (!(diff_flags & DIFF_FOLLOWWRAP))
1525 		{
1526 		    if (!wp->w_p_wrap)
1527 		        wp->w_p_wrap = wp->w_p_wrap_save;
1528 		}
1529 #ifdef FEAT_FOLDING
1530 		free_string_option(wp->w_p_fdm);
1531 		wp->w_p_fdm = vim_strsave(
1532 		    *wp->w_p_fdm_save ? wp->w_p_fdm_save : (char_u*)"manual");
1533 
1534 		if (wp->w_p_fdc == diff_foldcolumn)
1535 		    wp->w_p_fdc = wp->w_p_fdc_save;
1536 		if (wp->w_p_fdl == 0)
1537 		    wp->w_p_fdl = wp->w_p_fdl_save;
1538 
1539 		// Only restore 'foldenable' when 'foldmethod' is not
1540 		// "manual", otherwise we continue to show the diff folds.
1541 		if (wp->w_p_fen)
1542 		    wp->w_p_fen = foldmethodIsManual(wp) ? FALSE
1543 							 : wp->w_p_fen_save;
1544 
1545 		foldUpdateAll(wp);
1546 #endif
1547 	    }
1548 	    // remove filler lines
1549 	    wp->w_topfill = 0;
1550 
1551 	    // make sure topline is not halfway a fold and cursor is
1552 	    // invalidated
1553 	    changed_window_setting_win(wp);
1554 
1555 	    // Note: 'sbo' is not restored, it's a global option.
1556 	    diff_buf_adjust(wp);
1557 	}
1558 	diffwin |= wp->w_p_diff;
1559     }
1560 
1561     // Also remove hidden buffers from the list.
1562     if (eap->forceit)
1563 	diff_buf_clear();
1564 
1565     if (!diffwin)
1566     {
1567 	diff_need_update = FALSE;
1568 	curtab->tp_diff_invalid = FALSE;
1569 	curtab->tp_diff_update = FALSE;
1570 	diff_clear(curtab);
1571     }
1572 
1573     // Remove "hor" from from 'scrollopt' if there are no diff windows left.
1574     if (!diffwin && vim_strchr(p_sbo, 'h') != NULL)
1575 	do_cmdline_cmd((char_u *)"set sbo-=hor");
1576 }
1577 
1578 /*
1579  * Read the diff output and add each entry to the diff list.
1580  */
1581     static void
1582 diff_read(
1583     int		idx_orig,	// idx of original file
1584     int		idx_new,	// idx of new file
1585     diffout_T	*dout)		// diff output
1586 {
1587     FILE	*fd = NULL;
1588     int		line_idx = 0;
1589     diff_T	*dprev = NULL;
1590     diff_T	*dp = curtab->tp_first_diff;
1591     diff_T	*dn, *dpl;
1592     char_u	linebuf[LBUFLEN];   // only need to hold the diff line
1593     char_u	*line;
1594     long	off;
1595     int		i;
1596     linenr_T	lnum_orig, lnum_new;
1597     long	count_orig, count_new;
1598     int		notset = TRUE;	    // block "*dp" not set yet
1599     enum {
1600 	DIFF_ED,
1601 	DIFF_UNIFIED,
1602 	DIFF_NONE
1603     } diffstyle = DIFF_NONE;
1604 
1605     if (dout->dout_fname == NULL)
1606     {
1607 	diffstyle = DIFF_UNIFIED;
1608     }
1609     else
1610     {
1611 	fd = mch_fopen((char *)dout->dout_fname, "r");
1612 	if (fd == NULL)
1613 	{
1614 	    emsg(_("E98: Cannot read diff output"));
1615 	    return;
1616 	}
1617     }
1618 
1619     for (;;)
1620     {
1621 	if (fd == NULL)
1622 	{
1623 	    if (line_idx >= dout->dout_ga.ga_len)
1624 		break;	    // did last line
1625 	    line = ((char_u **)dout->dout_ga.ga_data)[line_idx++];
1626 	}
1627 	else
1628 	{
1629 	    if (vim_fgets(linebuf, LBUFLEN, fd))
1630 		break;		// end of file
1631 	    line = linebuf;
1632 	}
1633 
1634 	if (diffstyle == DIFF_NONE)
1635 	{
1636 	    // Determine diff style.
1637 	    // ed like diff looks like this:
1638 	    // {first}[,{last}]c{first}[,{last}]
1639 	    // {first}a{first}[,{last}]
1640 	    // {first}[,{last}]d{first}
1641 	    //
1642 	    // unified diff looks like this:
1643 	    // --- file1       2018-03-20 13:23:35.783153140 +0100
1644 	    // +++ file2       2018-03-20 13:23:41.183156066 +0100
1645 	    // @@ -1,3 +1,5 @@
1646 	    if (isdigit(*line))
1647 		diffstyle = DIFF_ED;
1648 	    else if ((STRNCMP(line, "@@ ", 3) == 0))
1649 	       diffstyle = DIFF_UNIFIED;
1650 	    else if ((STRNCMP(line, "--- ", 4) == 0)
1651 		    && (vim_fgets(linebuf, LBUFLEN, fd) == 0)
1652 		    && (STRNCMP(line, "+++ ", 4) == 0)
1653 		    && (vim_fgets(linebuf, LBUFLEN, fd) == 0)
1654 		    && (STRNCMP(line, "@@ ", 3) == 0))
1655 		diffstyle = DIFF_UNIFIED;
1656 	    else
1657 		// Format not recognized yet, skip over this line.  Cygwin diff
1658 		// may put a warning at the start of the file.
1659 		continue;
1660 	}
1661 
1662 	if (diffstyle == DIFF_ED)
1663 	{
1664 	    if (!isdigit(*line))
1665 		continue;	// not the start of a diff block
1666 	    if (parse_diff_ed(line, &lnum_orig, &count_orig,
1667 						&lnum_new, &count_new) == FAIL)
1668 		continue;
1669 	}
1670 	else if (diffstyle == DIFF_UNIFIED)
1671 	{
1672 	    if (STRNCMP(line, "@@ ", 3)  != 0)
1673 		continue;	// not the start of a diff block
1674 	    if (parse_diff_unified(line, &lnum_orig, &count_orig,
1675 						&lnum_new, &count_new) == FAIL)
1676 		continue;
1677 	}
1678 	else
1679 	{
1680 	    emsg(_("E959: Invalid diff format."));
1681 	    break;
1682 	}
1683 
1684 	// Go over blocks before the change, for which orig and new are equal.
1685 	// Copy blocks from orig to new.
1686 	while (dp != NULL
1687 		&& lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig])
1688 	{
1689 	    if (notset)
1690 		diff_copy_entry(dprev, dp, idx_orig, idx_new);
1691 	    dprev = dp;
1692 	    dp = dp->df_next;
1693 	    notset = TRUE;
1694 	}
1695 
1696 	if (dp != NULL
1697 		&& lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig]
1698 		&& lnum_orig + count_orig >= dp->df_lnum[idx_orig])
1699 	{
1700 	    // New block overlaps with existing block(s).
1701 	    // First find last block that overlaps.
1702 	    for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next)
1703 		if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig])
1704 		    break;
1705 
1706 	    // If the newly found block starts before the old one, set the
1707 	    // start back a number of lines.
1708 	    off = dp->df_lnum[idx_orig] - lnum_orig;
1709 	    if (off > 0)
1710 	    {
1711 		for (i = idx_orig; i < idx_new; ++i)
1712 		    if (curtab->tp_diffbuf[i] != NULL)
1713 			dp->df_lnum[i] -= off;
1714 		dp->df_lnum[idx_new] = lnum_new;
1715 		dp->df_count[idx_new] = count_new;
1716 	    }
1717 	    else if (notset)
1718 	    {
1719 		// new block inside existing one, adjust new block
1720 		dp->df_lnum[idx_new] = lnum_new + off;
1721 		dp->df_count[idx_new] = count_new - off;
1722 	    }
1723 	    else
1724 		// second overlap of new block with existing block
1725 		dp->df_count[idx_new] += count_new - count_orig
1726 		    + dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]
1727 		    - (dp->df_lnum[idx_orig] + dp->df_count[idx_orig]);
1728 
1729 	    // Adjust the size of the block to include all the lines to the
1730 	    // end of the existing block or the new diff, whatever ends last.
1731 	    off = (lnum_orig + count_orig)
1732 			 - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]);
1733 	    if (off < 0)
1734 	    {
1735 		// new change ends in existing block, adjust the end if not
1736 		// done already
1737 		if (notset)
1738 		    dp->df_count[idx_new] += -off;
1739 		off = 0;
1740 	    }
1741 	    for (i = idx_orig; i < idx_new; ++i)
1742 		if (curtab->tp_diffbuf[i] != NULL)
1743 		    dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i]
1744 						       - dp->df_lnum[i] + off;
1745 
1746 	    // Delete the diff blocks that have been merged into one.
1747 	    dn = dp->df_next;
1748 	    dp->df_next = dpl->df_next;
1749 	    while (dn != dp->df_next)
1750 	    {
1751 		dpl = dn->df_next;
1752 		vim_free(dn);
1753 		dn = dpl;
1754 	    }
1755 	}
1756 	else
1757 	{
1758 	    // Allocate a new diffblock.
1759 	    dp = diff_alloc_new(curtab, dprev, dp);
1760 	    if (dp == NULL)
1761 		goto done;
1762 
1763 	    dp->df_lnum[idx_orig] = lnum_orig;
1764 	    dp->df_count[idx_orig] = count_orig;
1765 	    dp->df_lnum[idx_new] = lnum_new;
1766 	    dp->df_count[idx_new] = count_new;
1767 
1768 	    // Set values for other buffers, these must be equal to the
1769 	    // original buffer, otherwise there would have been a change
1770 	    // already.
1771 	    for (i = idx_orig + 1; i < idx_new; ++i)
1772 		if (curtab->tp_diffbuf[i] != NULL)
1773 		    diff_copy_entry(dprev, dp, idx_orig, i);
1774 	}
1775 	notset = FALSE;		// "*dp" has been set
1776     }
1777 
1778     // for remaining diff blocks orig and new are equal
1779     while (dp != NULL)
1780     {
1781 	if (notset)
1782 	    diff_copy_entry(dprev, dp, idx_orig, idx_new);
1783 	dprev = dp;
1784 	dp = dp->df_next;
1785 	notset = TRUE;
1786     }
1787 
1788 done:
1789     if (fd != NULL)
1790 	fclose(fd);
1791 }
1792 
1793 /*
1794  * Copy an entry at "dp" from "idx_orig" to "idx_new".
1795  */
1796     static void
1797 diff_copy_entry(
1798     diff_T	*dprev,
1799     diff_T	*dp,
1800     int		idx_orig,
1801     int		idx_new)
1802 {
1803     long	off;
1804 
1805     if (dprev == NULL)
1806 	off = 0;
1807     else
1808 	off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig])
1809 	    - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]);
1810     dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off;
1811     dp->df_count[idx_new] = dp->df_count[idx_orig];
1812 }
1813 
1814 /*
1815  * Clear the list of diffblocks for tab page "tp".
1816  */
1817     void
1818 diff_clear(tabpage_T *tp)
1819 {
1820     diff_T	*p, *next_p;
1821 
1822     for (p = tp->tp_first_diff; p != NULL; p = next_p)
1823     {
1824 	next_p = p->df_next;
1825 	vim_free(p);
1826     }
1827     tp->tp_first_diff = NULL;
1828 }
1829 
1830 /*
1831  * Check diff status for line "lnum" in buffer "buf":
1832  * Returns 0 for nothing special
1833  * Returns -1 for a line that should be highlighted as changed.
1834  * Returns -2 for a line that should be highlighted as added/deleted.
1835  * Returns > 0 for inserting that many filler lines above it (never happens
1836  * when 'diffopt' doesn't contain "filler").
1837  * This should only be used for windows where 'diff' is set.
1838  */
1839     int
1840 diff_check(win_T *wp, linenr_T lnum)
1841 {
1842     int		idx;		// index in tp_diffbuf[] for this buffer
1843     diff_T	*dp;
1844     int		maxcount;
1845     int		i;
1846     buf_T	*buf = wp->w_buffer;
1847     int		cmp;
1848 
1849     if (curtab->tp_diff_invalid)
1850 	ex_diffupdate(NULL);		// update after a big change
1851 
1852     if (curtab->tp_first_diff == NULL || !wp->w_p_diff)	// no diffs at all
1853 	return 0;
1854 
1855     // safety check: "lnum" must be a buffer line
1856     if (lnum < 1 || lnum > buf->b_ml.ml_line_count + 1)
1857 	return 0;
1858 
1859     idx = diff_buf_idx(buf);
1860     if (idx == DB_COUNT)
1861 	return 0;		// no diffs for buffer "buf"
1862 
1863 #ifdef FEAT_FOLDING
1864     // A closed fold never has filler lines.
1865     if (hasFoldingWin(wp, lnum, NULL, NULL, TRUE, NULL))
1866 	return 0;
1867 #endif
1868 
1869     // search for a change that includes "lnum" in the list of diffblocks.
1870     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
1871 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1872 	    break;
1873     if (dp == NULL || lnum < dp->df_lnum[idx])
1874 	return 0;
1875 
1876     if (lnum < dp->df_lnum[idx] + dp->df_count[idx])
1877     {
1878 	int	zero = FALSE;
1879 
1880 	// Changed or inserted line.  If the other buffers have a count of
1881 	// zero, the lines were inserted.  If the other buffers have the same
1882 	// count, check if the lines are identical.
1883 	cmp = FALSE;
1884 	for (i = 0; i < DB_COUNT; ++i)
1885 	    if (i != idx && curtab->tp_diffbuf[i] != NULL)
1886 	    {
1887 		if (dp->df_count[i] == 0)
1888 		    zero = TRUE;
1889 		else
1890 		{
1891 		    if (dp->df_count[i] != dp->df_count[idx])
1892 			return -1;	    // nr of lines changed.
1893 		    cmp = TRUE;
1894 		}
1895 	    }
1896 	if (cmp)
1897 	{
1898 	    // Compare all lines.  If they are equal the lines were inserted
1899 	    // in some buffers, deleted in others, but not changed.
1900 	    for (i = 0; i < DB_COUNT; ++i)
1901 		if (i != idx && curtab->tp_diffbuf[i] != NULL
1902 						      && dp->df_count[i] != 0)
1903 		    if (!diff_equal_entry(dp, idx, i))
1904 			return -1;
1905 	}
1906 	// If there is no buffer with zero lines then there is no difference
1907 	// any longer.  Happens when making a change (or undo) that removes
1908 	// the difference.  Can't remove the entry here, we might be halfway
1909 	// updating the window.  Just report the text as unchanged.  Other
1910 	// windows might still show the change though.
1911 	if (zero == FALSE)
1912 	    return 0;
1913 	return -2;
1914     }
1915 
1916     // If 'diffopt' doesn't contain "filler", return 0.
1917     if (!(diff_flags & DIFF_FILLER))
1918 	return 0;
1919 
1920     // Insert filler lines above the line just below the change.  Will return
1921     // 0 when this buf had the max count.
1922     maxcount = 0;
1923     for (i = 0; i < DB_COUNT; ++i)
1924 	if (curtab->tp_diffbuf[i] != NULL && dp->df_count[i] > maxcount)
1925 	    maxcount = dp->df_count[i];
1926     return maxcount - dp->df_count[idx];
1927 }
1928 
1929 /*
1930  * Compare two entries in diff "*dp" and return TRUE if they are equal.
1931  */
1932     static int
1933 diff_equal_entry(diff_T *dp, int idx1, int idx2)
1934 {
1935     int		i;
1936     char_u	*line;
1937     int		cmp;
1938 
1939     if (dp->df_count[idx1] != dp->df_count[idx2])
1940 	return FALSE;
1941     if (diff_check_sanity(curtab, dp) == FAIL)
1942 	return FALSE;
1943     for (i = 0; i < dp->df_count[idx1]; ++i)
1944     {
1945 	line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1],
1946 					       dp->df_lnum[idx1] + i, FALSE));
1947 	if (line == NULL)
1948 	    return FALSE;
1949 	cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2],
1950 					       dp->df_lnum[idx2] + i, FALSE));
1951 	vim_free(line);
1952 	if (cmp != 0)
1953 	    return FALSE;
1954     }
1955     return TRUE;
1956 }
1957 
1958 /*
1959  * Compare the characters at "p1" and "p2".  If they are equal (possibly
1960  * ignoring case) return TRUE and set "len" to the number of bytes.
1961  */
1962     static int
1963 diff_equal_char(char_u *p1, char_u *p2, int *len)
1964 {
1965     int l  = (*mb_ptr2len)(p1);
1966 
1967     if (l != (*mb_ptr2len)(p2))
1968 	return FALSE;
1969     if (l > 1)
1970     {
1971 	if (STRNCMP(p1, p2, l) != 0
1972 		&& (!enc_utf8
1973 		    || !(diff_flags & DIFF_ICASE)
1974 		    || utf_fold(utf_ptr2char(p1))
1975 						!= utf_fold(utf_ptr2char(p2))))
1976 	    return FALSE;
1977 	*len = l;
1978     }
1979     else
1980     {
1981 	if ((*p1 != *p2)
1982 		&& (!(diff_flags & DIFF_ICASE)
1983 		    || TOLOWER_LOC(*p1) != TOLOWER_LOC(*p2)))
1984 	    return FALSE;
1985 	*len = 1;
1986     }
1987     return TRUE;
1988 }
1989 
1990 /*
1991  * Compare strings "s1" and "s2" according to 'diffopt'.
1992  * Return non-zero when they are different.
1993  */
1994     static int
1995 diff_cmp(char_u *s1, char_u *s2)
1996 {
1997     char_u	*p1, *p2;
1998     int		l;
1999 
2000     if ((diff_flags & DIFF_IBLANK)
2001 	    && (*skipwhite(s1) == NUL || *skipwhite(s2) == NUL))
2002 	return 0;
2003 
2004     if ((diff_flags & (DIFF_ICASE | ALL_WHITE_DIFF)) == 0)
2005 	return STRCMP(s1, s2);
2006     if ((diff_flags & DIFF_ICASE) && !(diff_flags & ALL_WHITE_DIFF))
2007 	return MB_STRICMP(s1, s2);
2008 
2009     p1 = s1;
2010     p2 = s2;
2011 
2012     // Ignore white space changes and possibly ignore case.
2013     while (*p1 != NUL && *p2 != NUL)
2014     {
2015 	if (((diff_flags & DIFF_IWHITE)
2016 		    && VIM_ISWHITE(*p1) && VIM_ISWHITE(*p2))
2017 		|| ((diff_flags & DIFF_IWHITEALL)
2018 		    && (VIM_ISWHITE(*p1) || VIM_ISWHITE(*p2))))
2019 	{
2020 	    p1 = skipwhite(p1);
2021 	    p2 = skipwhite(p2);
2022 	}
2023 	else
2024 	{
2025 	    if (!diff_equal_char(p1, p2, &l))
2026 		break;
2027 	    p1 += l;
2028 	    p2 += l;
2029 	}
2030     }
2031 
2032     // Ignore trailing white space.
2033     p1 = skipwhite(p1);
2034     p2 = skipwhite(p2);
2035     if (*p1 != NUL || *p2 != NUL)
2036 	return 1;
2037     return 0;
2038 }
2039 
2040 /*
2041  * Return the number of filler lines above "lnum".
2042  */
2043     int
2044 diff_check_fill(win_T *wp, linenr_T lnum)
2045 {
2046     int		n;
2047 
2048     // be quick when there are no filler lines
2049     if (!(diff_flags & DIFF_FILLER))
2050 	return 0;
2051     n = diff_check(wp, lnum);
2052     if (n <= 0)
2053 	return 0;
2054     return n;
2055 }
2056 
2057 /*
2058  * Set the topline of "towin" to match the position in "fromwin", so that they
2059  * show the same diff'ed lines.
2060  */
2061     void
2062 diff_set_topline(win_T *fromwin, win_T *towin)
2063 {
2064     buf_T	*frombuf = fromwin->w_buffer;
2065     linenr_T	lnum = fromwin->w_topline;
2066     int		fromidx;
2067     int		toidx;
2068     diff_T	*dp;
2069     int		max_count;
2070     int		i;
2071 
2072     fromidx = diff_buf_idx(frombuf);
2073     if (fromidx == DB_COUNT)
2074 	return;		// safety check
2075 
2076     if (curtab->tp_diff_invalid)
2077 	ex_diffupdate(NULL);		// update after a big change
2078 
2079     towin->w_topfill = 0;
2080 
2081     // search for a change that includes "lnum" in the list of diffblocks.
2082     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
2083 	if (lnum <= dp->df_lnum[fromidx] + dp->df_count[fromidx])
2084 	    break;
2085     if (dp == NULL)
2086     {
2087 	// After last change, compute topline relative to end of file; no
2088 	// filler lines.
2089 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count
2090 				       - (frombuf->b_ml.ml_line_count - lnum);
2091     }
2092     else
2093     {
2094 	// Find index for "towin".
2095 	toidx = diff_buf_idx(towin->w_buffer);
2096 	if (toidx == DB_COUNT)
2097 	    return;		// safety check
2098 
2099 	towin->w_topline = lnum + (dp->df_lnum[toidx] - dp->df_lnum[fromidx]);
2100 	if (lnum >= dp->df_lnum[fromidx])
2101 	{
2102 	    // Inside a change: compute filler lines. With three or more
2103 	    // buffers we need to know the largest count.
2104 	    max_count = 0;
2105 	    for (i = 0; i < DB_COUNT; ++i)
2106 		if (curtab->tp_diffbuf[i] != NULL
2107 					       && max_count < dp->df_count[i])
2108 		    max_count = dp->df_count[i];
2109 
2110 	    if (dp->df_count[toidx] == dp->df_count[fromidx])
2111 	    {
2112 		// same number of lines: use same filler count
2113 		towin->w_topfill = fromwin->w_topfill;
2114 	    }
2115 	    else if (dp->df_count[toidx] > dp->df_count[fromidx])
2116 	    {
2117 		if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx])
2118 		{
2119 		    // more lines in towin and fromwin doesn't show diff
2120 		    // lines, only filler lines
2121 		    if (max_count - fromwin->w_topfill >= dp->df_count[toidx])
2122 		    {
2123 			// towin also only shows filler lines
2124 			towin->w_topline = dp->df_lnum[toidx]
2125 						       + dp->df_count[toidx];
2126 			towin->w_topfill = fromwin->w_topfill;
2127 		    }
2128 		    else
2129 			// towin still has some diff lines to show
2130 			towin->w_topline = dp->df_lnum[toidx]
2131 					     + max_count - fromwin->w_topfill;
2132 		}
2133 	    }
2134 	    else if (towin->w_topline >= dp->df_lnum[toidx]
2135 							+ dp->df_count[toidx])
2136 	    {
2137 		// less lines in towin and no diff lines to show: compute
2138 		// filler lines
2139 		towin->w_topline = dp->df_lnum[toidx] + dp->df_count[toidx];
2140 		if (diff_flags & DIFF_FILLER)
2141 		{
2142 		    if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx])
2143 			// fromwin is also out of diff lines
2144 			towin->w_topfill = fromwin->w_topfill;
2145 		    else
2146 			// fromwin has some diff lines
2147 			towin->w_topfill = dp->df_lnum[fromidx]
2148 							   + max_count - lnum;
2149 		}
2150 	    }
2151 	}
2152     }
2153 
2154     // safety check (if diff info gets outdated strange things may happen)
2155     towin->w_botfill = FALSE;
2156     if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count)
2157     {
2158 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count;
2159 	towin->w_botfill = TRUE;
2160     }
2161     if (towin->w_topline < 1)
2162     {
2163 	towin->w_topline = 1;
2164 	towin->w_topfill = 0;
2165     }
2166 
2167     // When w_topline changes need to recompute w_botline and cursor position
2168     invalidate_botline_win(towin);
2169     changed_line_abv_curs_win(towin);
2170 
2171     check_topfill(towin, FALSE);
2172 #ifdef FEAT_FOLDING
2173     (void)hasFoldingWin(towin, towin->w_topline, &towin->w_topline,
2174 							    NULL, TRUE, NULL);
2175 #endif
2176 }
2177 
2178 /*
2179  * This is called when 'diffopt' is changed.
2180  */
2181     int
2182 diffopt_changed(void)
2183 {
2184     char_u	*p;
2185     int		diff_context_new = 6;
2186     int		diff_flags_new = 0;
2187     int		diff_foldcolumn_new = 2;
2188     long	diff_algorithm_new = 0;
2189     long	diff_indent_heuristic = 0;
2190     tabpage_T	*tp;
2191 
2192     p = p_dip;
2193     while (*p != NUL)
2194     {
2195 	if (STRNCMP(p, "filler", 6) == 0)
2196 	{
2197 	    p += 6;
2198 	    diff_flags_new |= DIFF_FILLER;
2199 	}
2200 	else if (STRNCMP(p, "context:", 8) == 0 && VIM_ISDIGIT(p[8]))
2201 	{
2202 	    p += 8;
2203 	    diff_context_new = getdigits(&p);
2204 	}
2205 	else if (STRNCMP(p, "iblank", 6) == 0)
2206 	{
2207 	    p += 6;
2208 	    diff_flags_new |= DIFF_IBLANK;
2209 	}
2210 	else if (STRNCMP(p, "icase", 5) == 0)
2211 	{
2212 	    p += 5;
2213 	    diff_flags_new |= DIFF_ICASE;
2214 	}
2215 	else if (STRNCMP(p, "iwhiteall", 9) == 0)
2216 	{
2217 	    p += 9;
2218 	    diff_flags_new |= DIFF_IWHITEALL;
2219 	}
2220 	else if (STRNCMP(p, "iwhiteeol", 9) == 0)
2221 	{
2222 	    p += 9;
2223 	    diff_flags_new |= DIFF_IWHITEEOL;
2224 	}
2225 	else if (STRNCMP(p, "iwhite", 6) == 0)
2226 	{
2227 	    p += 6;
2228 	    diff_flags_new |= DIFF_IWHITE;
2229 	}
2230 	else if (STRNCMP(p, "horizontal", 10) == 0)
2231 	{
2232 	    p += 10;
2233 	    diff_flags_new |= DIFF_HORIZONTAL;
2234 	}
2235 	else if (STRNCMP(p, "vertical", 8) == 0)
2236 	{
2237 	    p += 8;
2238 	    diff_flags_new |= DIFF_VERTICAL;
2239 	}
2240 	else if (STRNCMP(p, "foldcolumn:", 11) == 0 && VIM_ISDIGIT(p[11]))
2241 	{
2242 	    p += 11;
2243 	    diff_foldcolumn_new = getdigits(&p);
2244 	}
2245 	else if (STRNCMP(p, "hiddenoff", 9) == 0)
2246 	{
2247 	    p += 9;
2248 	    diff_flags_new |= DIFF_HIDDEN_OFF;
2249 	}
2250 	else if (STRNCMP(p, "closeoff", 8) == 0)
2251 	{
2252 	    p += 8;
2253 	    diff_flags_new |= DIFF_CLOSE_OFF;
2254 	}
2255 	else if (STRNCMP(p, "followwrap", 10) == 0)
2256 	{
2257 	    p += 10;
2258 	    diff_flags_new |= DIFF_FOLLOWWRAP;
2259 	}
2260 	else if (STRNCMP(p, "indent-heuristic", 16) == 0)
2261 	{
2262 	    p += 16;
2263 	    diff_indent_heuristic = XDF_INDENT_HEURISTIC;
2264 	}
2265 	else if (STRNCMP(p, "internal", 8) == 0)
2266 	{
2267 	    p += 8;
2268 	    diff_flags_new |= DIFF_INTERNAL;
2269 	}
2270 	else if (STRNCMP(p, "algorithm:", 10) == 0)
2271 	{
2272 	    p += 10;
2273 	    if (STRNCMP(p, "myers", 5) == 0)
2274 	    {
2275 		p += 5;
2276 		diff_algorithm_new = 0;
2277 	    }
2278 	    else if (STRNCMP(p, "minimal", 7) == 0)
2279 	    {
2280 		p += 7;
2281 		diff_algorithm_new = XDF_NEED_MINIMAL;
2282 	    }
2283 	    else if (STRNCMP(p, "patience", 8) == 0)
2284 	    {
2285 		p += 8;
2286 		diff_algorithm_new = XDF_PATIENCE_DIFF;
2287 	    }
2288 	    else if (STRNCMP(p, "histogram", 9) == 0)
2289 	    {
2290 		p += 9;
2291 		diff_algorithm_new = XDF_HISTOGRAM_DIFF;
2292 	    }
2293 	    else
2294 		return FAIL;
2295 	}
2296 
2297 	if (*p != ',' && *p != NUL)
2298 	    return FAIL;
2299 	if (*p == ',')
2300 	    ++p;
2301     }
2302 
2303     diff_algorithm_new |= diff_indent_heuristic;
2304 
2305     // Can't have both "horizontal" and "vertical".
2306     if ((diff_flags_new & DIFF_HORIZONTAL) && (diff_flags_new & DIFF_VERTICAL))
2307 	return FAIL;
2308 
2309     // If flags were added or removed, or the algorithm was changed, need to
2310     // update the diff.
2311     if (diff_flags != diff_flags_new || diff_algorithm != diff_algorithm_new)
2312 	FOR_ALL_TABPAGES(tp)
2313 	    tp->tp_diff_invalid = TRUE;
2314 
2315     diff_flags = diff_flags_new;
2316     diff_context = diff_context_new == 0 ? 1 : diff_context_new;
2317     diff_foldcolumn = diff_foldcolumn_new;
2318     diff_algorithm = diff_algorithm_new;
2319 
2320     diff_redraw(TRUE);
2321 
2322     // recompute the scroll binding with the new option value, may
2323     // remove or add filler lines
2324     check_scrollbind((linenr_T)0, 0L);
2325 
2326     return OK;
2327 }
2328 
2329 /*
2330  * Return TRUE if 'diffopt' contains "horizontal".
2331  */
2332     int
2333 diffopt_horizontal(void)
2334 {
2335     return (diff_flags & DIFF_HORIZONTAL) != 0;
2336 }
2337 
2338 /*
2339  * Return TRUE if 'diffopt' contains "hiddenoff".
2340  */
2341     int
2342 diffopt_hiddenoff(void)
2343 {
2344     return (diff_flags & DIFF_HIDDEN_OFF) != 0;
2345 }
2346 
2347 /*
2348  * Return TRUE if 'diffopt' contains "closeoff".
2349  */
2350     int
2351 diffopt_closeoff(void)
2352 {
2353     return (diff_flags & DIFF_CLOSE_OFF) != 0;
2354 }
2355 
2356 /*
2357  * Find the difference within a changed line.
2358  * Returns TRUE if the line was added, no other buffer has it.
2359  */
2360     int
2361 diff_find_change(
2362     win_T	*wp,
2363     linenr_T	lnum,
2364     int		*startp,	// first char of the change
2365     int		*endp)		// last char of the change
2366 {
2367     char_u	*line_org;
2368     char_u	*line_new;
2369     int		i;
2370     int		si_org, si_new;
2371     int		ei_org, ei_new;
2372     diff_T	*dp;
2373     int		idx;
2374     int		off;
2375     int		added = TRUE;
2376     char_u	*p1, *p2;
2377     int		l;
2378 
2379     // Make a copy of the line, the next ml_get() will invalidate it.
2380     line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, FALSE));
2381     if (line_org == NULL)
2382 	return FALSE;
2383 
2384     idx = diff_buf_idx(wp->w_buffer);
2385     if (idx == DB_COUNT)	// cannot happen
2386     {
2387 	vim_free(line_org);
2388 	return FALSE;
2389     }
2390 
2391     // search for a change that includes "lnum" in the list of diffblocks.
2392     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
2393 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
2394 	    break;
2395     if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL)
2396     {
2397 	vim_free(line_org);
2398 	return FALSE;
2399     }
2400 
2401     off = lnum - dp->df_lnum[idx];
2402 
2403     for (i = 0; i < DB_COUNT; ++i)
2404 	if (curtab->tp_diffbuf[i] != NULL && i != idx)
2405 	{
2406 	    // Skip lines that are not in the other change (filler lines).
2407 	    if (off >= dp->df_count[i])
2408 		continue;
2409 	    added = FALSE;
2410 	    line_new = ml_get_buf(curtab->tp_diffbuf[i],
2411 						 dp->df_lnum[i] + off, FALSE);
2412 
2413 	    // Search for start of difference
2414 	    si_org = si_new = 0;
2415 	    while (line_org[si_org] != NUL)
2416 	    {
2417 		if (((diff_flags & DIFF_IWHITE)
2418 			    && VIM_ISWHITE(line_org[si_org])
2419 					      && VIM_ISWHITE(line_new[si_new]))
2420 			|| ((diff_flags & DIFF_IWHITEALL)
2421 			    && (VIM_ISWHITE(line_org[si_org])
2422 					    || VIM_ISWHITE(line_new[si_new]))))
2423 		{
2424 		    si_org = (int)(skipwhite(line_org + si_org) - line_org);
2425 		    si_new = (int)(skipwhite(line_new + si_new) - line_new);
2426 		}
2427 		else
2428 		{
2429 		    if (!diff_equal_char(line_org + si_org, line_new + si_new,
2430 									   &l))
2431 			break;
2432 		    si_org += l;
2433 		    si_new += l;
2434 		}
2435 	    }
2436 	    if (has_mbyte)
2437 	    {
2438 		// Move back to first byte of character in both lines (may
2439 		// have "nn^" in line_org and "n^ in line_new).
2440 		si_org -= (*mb_head_off)(line_org, line_org + si_org);
2441 		si_new -= (*mb_head_off)(line_new, line_new + si_new);
2442 	    }
2443 	    if (*startp > si_org)
2444 		*startp = si_org;
2445 
2446 	    // Search for end of difference, if any.
2447 	    if (line_org[si_org] != NUL || line_new[si_new] != NUL)
2448 	    {
2449 		ei_org = (int)STRLEN(line_org);
2450 		ei_new = (int)STRLEN(line_new);
2451 		while (ei_org >= *startp && ei_new >= si_new
2452 						&& ei_org >= 0 && ei_new >= 0)
2453 		{
2454 		    if (((diff_flags & DIFF_IWHITE)
2455 				&& VIM_ISWHITE(line_org[ei_org])
2456 					      && VIM_ISWHITE(line_new[ei_new]))
2457 			    || ((diff_flags & DIFF_IWHITEALL)
2458 				&& (VIM_ISWHITE(line_org[ei_org])
2459 					    || VIM_ISWHITE(line_new[ei_new]))))
2460 		    {
2461 			while (ei_org >= *startp
2462 					     && VIM_ISWHITE(line_org[ei_org]))
2463 			    --ei_org;
2464 			while (ei_new >= si_new
2465 					     && VIM_ISWHITE(line_new[ei_new]))
2466 			    --ei_new;
2467 		    }
2468 		    else
2469 		    {
2470 			p1 = line_org + ei_org;
2471 			p2 = line_new + ei_new;
2472 			p1 -= (*mb_head_off)(line_org, p1);
2473 			p2 -= (*mb_head_off)(line_new, p2);
2474 			if (!diff_equal_char(p1, p2, &l))
2475 			    break;
2476 			ei_org -= l;
2477 			ei_new -= l;
2478 		    }
2479 		}
2480 		if (*endp < ei_org)
2481 		    *endp = ei_org;
2482 	    }
2483 	}
2484 
2485     vim_free(line_org);
2486     return added;
2487 }
2488 
2489 #if defined(FEAT_FOLDING) || defined(PROTO)
2490 /*
2491  * Return TRUE if line "lnum" is not close to a diff block, this line should
2492  * be in a fold.
2493  * Return FALSE if there are no diff blocks at all in this window.
2494  */
2495     int
2496 diff_infold(win_T *wp, linenr_T lnum)
2497 {
2498     int		i;
2499     int		idx = -1;
2500     int		other = FALSE;
2501     diff_T	*dp;
2502 
2503     // Return if 'diff' isn't set.
2504     if (!wp->w_p_diff)
2505 	return FALSE;
2506 
2507     for (i = 0; i < DB_COUNT; ++i)
2508     {
2509 	if (curtab->tp_diffbuf[i] == wp->w_buffer)
2510 	    idx = i;
2511 	else if (curtab->tp_diffbuf[i] != NULL)
2512 	    other = TRUE;
2513     }
2514 
2515     // return here if there are no diffs in the window
2516     if (idx == -1 || !other)
2517 	return FALSE;
2518 
2519     if (curtab->tp_diff_invalid)
2520 	ex_diffupdate(NULL);		// update after a big change
2521 
2522     // Return if there are no diff blocks.  All lines will be folded.
2523     if (curtab->tp_first_diff == NULL)
2524 	return TRUE;
2525 
2526     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
2527     {
2528 	// If this change is below the line there can't be any further match.
2529 	if (dp->df_lnum[idx] - diff_context > lnum)
2530 	    break;
2531 	// If this change ends before the line we have a match.
2532 	if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum)
2533 	    return FALSE;
2534     }
2535     return TRUE;
2536 }
2537 #endif
2538 
2539 /*
2540  * "dp" and "do" commands.
2541  */
2542     void
2543 nv_diffgetput(int put, long count)
2544 {
2545     exarg_T	ea;
2546     char_u	buf[30];
2547 
2548 #ifdef FEAT_JOB_CHANNEL
2549     if (bt_prompt(curbuf))
2550     {
2551 	vim_beep(BO_OPER);
2552 	return;
2553     }
2554 #endif
2555     if (count == 0)
2556 	ea.arg = (char_u *)"";
2557     else
2558     {
2559 	vim_snprintf((char *)buf, 30, "%ld", count);
2560 	ea.arg = buf;
2561     }
2562     if (put)
2563 	ea.cmdidx = CMD_diffput;
2564     else
2565 	ea.cmdidx = CMD_diffget;
2566     ea.addr_count = 0;
2567     ea.line1 = curwin->w_cursor.lnum;
2568     ea.line2 = curwin->w_cursor.lnum;
2569     ex_diffgetput(&ea);
2570 }
2571 
2572 /*
2573  * ":diffget"
2574  * ":diffput"
2575  */
2576     void
2577 ex_diffgetput(exarg_T *eap)
2578 {
2579     linenr_T	lnum;
2580     int		count;
2581     linenr_T	off = 0;
2582     diff_T	*dp;
2583     diff_T	*dprev;
2584     diff_T	*dfree;
2585     int		idx_cur;
2586     int		idx_other;
2587     int		idx_from;
2588     int		idx_to;
2589     int		i;
2590     int		added;
2591     char_u	*p;
2592     aco_save_T	aco;
2593     buf_T	*buf;
2594     int		start_skip, end_skip;
2595     int		new_count;
2596     int		buf_empty;
2597     int		found_not_ma = FALSE;
2598 
2599     // Find the current buffer in the list of diff buffers.
2600     idx_cur = diff_buf_idx(curbuf);
2601     if (idx_cur == DB_COUNT)
2602     {
2603 	emsg(_("E99: Current buffer is not in diff mode"));
2604 	return;
2605     }
2606 
2607     if (*eap->arg == NUL)
2608     {
2609 	// No argument: Find the other buffer in the list of diff buffers.
2610 	for (idx_other = 0; idx_other < DB_COUNT; ++idx_other)
2611 	    if (curtab->tp_diffbuf[idx_other] != curbuf
2612 		    && curtab->tp_diffbuf[idx_other] != NULL)
2613 	    {
2614 		if (eap->cmdidx != CMD_diffput
2615 				     || curtab->tp_diffbuf[idx_other]->b_p_ma)
2616 		    break;
2617 		found_not_ma = TRUE;
2618 	    }
2619 	if (idx_other == DB_COUNT)
2620 	{
2621 	    if (found_not_ma)
2622 		emsg(_("E793: No other buffer in diff mode is modifiable"));
2623 	    else
2624 		emsg(_("E100: No other buffer in diff mode"));
2625 	    return;
2626 	}
2627 
2628 	// Check that there isn't a third buffer in the list
2629 	for (i = idx_other + 1; i < DB_COUNT; ++i)
2630 	    if (curtab->tp_diffbuf[i] != curbuf
2631 		    && curtab->tp_diffbuf[i] != NULL
2632 		    && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma))
2633 	    {
2634 		emsg(_("E101: More than two buffers in diff mode, don't know which one to use"));
2635 		return;
2636 	    }
2637     }
2638     else
2639     {
2640 	// Buffer number or pattern given.  Ignore trailing white space.
2641 	p = eap->arg + STRLEN(eap->arg);
2642 	while (p > eap->arg && VIM_ISWHITE(p[-1]))
2643 	    --p;
2644 	for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i)
2645 	    ;
2646 	if (eap->arg + i == p)	    // digits only
2647 	    i = atol((char *)eap->arg);
2648 	else
2649 	{
2650 	    i = buflist_findpat(eap->arg, p, FALSE, TRUE, FALSE);
2651 	    if (i < 0)
2652 		return;		// error message already given
2653 	}
2654 	buf = buflist_findnr(i);
2655 	if (buf == NULL)
2656 	{
2657 	    semsg(_("E102: Can't find buffer \"%s\""), eap->arg);
2658 	    return;
2659 	}
2660 	if (buf == curbuf)
2661 	    return;		// nothing to do
2662 	idx_other = diff_buf_idx(buf);
2663 	if (idx_other == DB_COUNT)
2664 	{
2665 	    semsg(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg);
2666 	    return;
2667 	}
2668     }
2669 
2670     diff_busy = TRUE;
2671 
2672     // When no range given include the line above or below the cursor.
2673     if (eap->addr_count == 0)
2674     {
2675 	// Make it possible that ":diffget" on the last line gets line below
2676 	// the cursor line when there is no difference above the cursor.
2677 	if (eap->cmdidx == CMD_diffget
2678 		&& eap->line1 == curbuf->b_ml.ml_line_count
2679 		&& diff_check(curwin, eap->line1) == 0
2680 		&& (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0))
2681 	    ++eap->line2;
2682 	else if (eap->line1 > 0)
2683 	    --eap->line1;
2684     }
2685 
2686     if (eap->cmdidx == CMD_diffget)
2687     {
2688 	idx_from = idx_other;
2689 	idx_to = idx_cur;
2690     }
2691     else
2692     {
2693 	idx_from = idx_cur;
2694 	idx_to = idx_other;
2695 	// Need to make the other buffer the current buffer to be able to make
2696 	// changes in it.
2697 	// set curwin/curbuf to buf and save a few things
2698 	aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]);
2699     }
2700 
2701     // May give the warning for a changed buffer here, which can trigger the
2702     // FileChangedRO autocommand, which may do nasty things and mess
2703     // everything up.
2704     if (!curbuf->b_changed)
2705     {
2706 	change_warning(0);
2707 	if (diff_buf_idx(curbuf) != idx_to)
2708 	{
2709 	    emsg(_("E787: Buffer changed unexpectedly"));
2710 	    goto theend;
2711 	}
2712     }
2713 
2714     dprev = NULL;
2715     for (dp = curtab->tp_first_diff; dp != NULL; )
2716     {
2717 	if (dp->df_lnum[idx_cur] > eap->line2 + off)
2718 	    break;	// past the range that was specified
2719 
2720 	dfree = NULL;
2721 	lnum = dp->df_lnum[idx_to];
2722 	count = dp->df_count[idx_to];
2723 	if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off
2724 		&& u_save(lnum - 1, lnum + count) != FAIL)
2725 	{
2726 	    // Inside the specified range and saving for undo worked.
2727 	    start_skip = 0;
2728 	    end_skip = 0;
2729 	    if (eap->addr_count > 0)
2730 	    {
2731 		// A range was specified: check if lines need to be skipped.
2732 		start_skip = eap->line1 + off - dp->df_lnum[idx_cur];
2733 		if (start_skip > 0)
2734 		{
2735 		    // range starts below start of current diff block
2736 		    if (start_skip > count)
2737 		    {
2738 			lnum += count;
2739 			count = 0;
2740 		    }
2741 		    else
2742 		    {
2743 			count -= start_skip;
2744 			lnum += start_skip;
2745 		    }
2746 		}
2747 		else
2748 		    start_skip = 0;
2749 
2750 		end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1
2751 							 - (eap->line2 + off);
2752 		if (end_skip > 0)
2753 		{
2754 		    // range ends above end of current/from diff block
2755 		    if (idx_cur == idx_from)	// :diffput
2756 		    {
2757 			i = dp->df_count[idx_cur] - start_skip - end_skip;
2758 			if (count > i)
2759 			    count = i;
2760 		    }
2761 		    else			// :diffget
2762 		    {
2763 			count -= end_skip;
2764 			end_skip = dp->df_count[idx_from] - start_skip - count;
2765 			if (end_skip < 0)
2766 			    end_skip = 0;
2767 		    }
2768 		}
2769 		else
2770 		    end_skip = 0;
2771 	    }
2772 
2773 	    buf_empty = BUFEMPTY();
2774 	    added = 0;
2775 	    for (i = 0; i < count; ++i)
2776 	    {
2777 		// remember deleting the last line of the buffer
2778 		buf_empty = curbuf->b_ml.ml_line_count == 1;
2779 		ml_delete(lnum);
2780 		--added;
2781 	    }
2782 	    for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i)
2783 	    {
2784 		linenr_T nr;
2785 
2786 		nr = dp->df_lnum[idx_from] + start_skip + i;
2787 		if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count)
2788 		    break;
2789 		p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from],
2790 								  nr, FALSE));
2791 		if (p != NULL)
2792 		{
2793 		    ml_append(lnum + i - 1, p, 0, FALSE);
2794 		    vim_free(p);
2795 		    ++added;
2796 		    if (buf_empty && curbuf->b_ml.ml_line_count == 2)
2797 		    {
2798 			// Added the first line into an empty buffer, need to
2799 			// delete the dummy empty line.
2800 			buf_empty = FALSE;
2801 			ml_delete((linenr_T)2);
2802 		    }
2803 		}
2804 	    }
2805 	    new_count = dp->df_count[idx_to] + added;
2806 	    dp->df_count[idx_to] = new_count;
2807 
2808 	    if (start_skip == 0 && end_skip == 0)
2809 	    {
2810 		// Check if there are any other buffers and if the diff is
2811 		// equal in them.
2812 		for (i = 0; i < DB_COUNT; ++i)
2813 		    if (curtab->tp_diffbuf[i] != NULL && i != idx_from
2814 								&& i != idx_to
2815 			    && !diff_equal_entry(dp, idx_from, i))
2816 			break;
2817 		if (i == DB_COUNT)
2818 		{
2819 		    // delete the diff entry, the buffers are now equal here
2820 		    dfree = dp;
2821 		    dp = dp->df_next;
2822 		    if (dprev == NULL)
2823 			curtab->tp_first_diff = dp;
2824 		    else
2825 			dprev->df_next = dp;
2826 		}
2827 	    }
2828 
2829 	    // Adjust marks.  This will change the following entries!
2830 	    if (added != 0)
2831 	    {
2832 		mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added);
2833 		if (curwin->w_cursor.lnum >= lnum)
2834 		{
2835 		    // Adjust the cursor position if it's in/after the changed
2836 		    // lines.
2837 		    if (curwin->w_cursor.lnum >= lnum + count)
2838 			curwin->w_cursor.lnum += added;
2839 		    else if (added < 0)
2840 			curwin->w_cursor.lnum = lnum;
2841 		}
2842 	    }
2843 	    changed_lines(lnum, 0, lnum + count, (long)added);
2844 
2845 	    if (dfree != NULL)
2846 	    {
2847 		// Diff is deleted, update folds in other windows.
2848 #ifdef FEAT_FOLDING
2849 		diff_fold_update(dfree, idx_to);
2850 #endif
2851 		vim_free(dfree);
2852 	    }
2853 	    else
2854 		// mark_adjust() may have changed the count in a wrong way
2855 		dp->df_count[idx_to] = new_count;
2856 
2857 	    // When changing the current buffer, keep track of line numbers
2858 	    if (idx_cur == idx_to)
2859 		off += added;
2860 	}
2861 
2862 	// If before the range or not deleted, go to next diff.
2863 	if (dfree == NULL)
2864 	{
2865 	    dprev = dp;
2866 	    dp = dp->df_next;
2867 	}
2868     }
2869 
2870     // restore curwin/curbuf and a few other things
2871     if (eap->cmdidx != CMD_diffget)
2872     {
2873 	// Syncing undo only works for the current buffer, but we change
2874 	// another buffer.  Sync undo if the command was typed.  This isn't
2875 	// 100% right when ":diffput" is used in a function or mapping.
2876 	if (KeyTyped)
2877 	    u_sync(FALSE);
2878 	aucmd_restbuf(&aco);
2879     }
2880 
2881 theend:
2882     diff_busy = FALSE;
2883     if (diff_need_update)
2884 	ex_diffupdate(NULL);
2885 
2886     // Check that the cursor is on a valid character and update its
2887     // position.  When there were filler lines the topline has become
2888     // invalid.
2889     check_cursor();
2890     changed_line_abv_curs();
2891 
2892     if (diff_need_update)
2893 	// redraw already done by ex_diffupdate()
2894 	diff_need_update = FALSE;
2895     else
2896     {
2897 	// Also need to redraw the other buffers.
2898 	diff_redraw(FALSE);
2899 	apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf);
2900     }
2901 }
2902 
2903 #ifdef FEAT_FOLDING
2904 /*
2905  * Update folds for all diff buffers for entry "dp".
2906  * Skip buffer with index "skip_idx".
2907  * When there are no diffs, all folds are removed.
2908  */
2909     static void
2910 diff_fold_update(diff_T *dp, int skip_idx)
2911 {
2912     int		i;
2913     win_T	*wp;
2914 
2915     FOR_ALL_WINDOWS(wp)
2916 	for (i = 0; i < DB_COUNT; ++i)
2917 	    if (curtab->tp_diffbuf[i] == wp->w_buffer && i != skip_idx)
2918 		foldUpdate(wp, dp->df_lnum[i],
2919 					    dp->df_lnum[i] + dp->df_count[i]);
2920 }
2921 #endif
2922 
2923 /*
2924  * Return TRUE if buffer "buf" is in diff-mode.
2925  */
2926     int
2927 diff_mode_buf(buf_T *buf)
2928 {
2929     tabpage_T	*tp;
2930 
2931     FOR_ALL_TABPAGES(tp)
2932 	if (diff_buf_idx_tp(buf, tp) != DB_COUNT)
2933 	    return TRUE;
2934     return FALSE;
2935 }
2936 
2937 /*
2938  * Move "count" times in direction "dir" to the next diff block.
2939  * Return FAIL if there isn't such a diff block.
2940  */
2941     int
2942 diff_move_to(int dir, long count)
2943 {
2944     int		idx;
2945     linenr_T	lnum = curwin->w_cursor.lnum;
2946     diff_T	*dp;
2947 
2948     idx = diff_buf_idx(curbuf);
2949     if (idx == DB_COUNT || curtab->tp_first_diff == NULL)
2950 	return FAIL;
2951 
2952     if (curtab->tp_diff_invalid)
2953 	ex_diffupdate(NULL);		// update after a big change
2954 
2955     if (curtab->tp_first_diff == NULL)		// no diffs today
2956 	return FAIL;
2957 
2958     while (--count >= 0)
2959     {
2960 	// Check if already before first diff.
2961 	if (dir == BACKWARD && lnum <= curtab->tp_first_diff->df_lnum[idx])
2962 	    break;
2963 
2964 	for (dp = curtab->tp_first_diff; ; dp = dp->df_next)
2965 	{
2966 	    if (dp == NULL)
2967 		break;
2968 	    if ((dir == FORWARD && lnum < dp->df_lnum[idx])
2969 		    || (dir == BACKWARD
2970 			&& (dp->df_next == NULL
2971 			    || lnum <= dp->df_next->df_lnum[idx])))
2972 	    {
2973 		lnum = dp->df_lnum[idx];
2974 		break;
2975 	    }
2976 	}
2977     }
2978 
2979     // don't end up past the end of the file
2980     if (lnum > curbuf->b_ml.ml_line_count)
2981 	lnum = curbuf->b_ml.ml_line_count;
2982 
2983     // When the cursor didn't move at all we fail.
2984     if (lnum == curwin->w_cursor.lnum)
2985 	return FAIL;
2986 
2987     setpcmark();
2988     curwin->w_cursor.lnum = lnum;
2989     curwin->w_cursor.col = 0;
2990 
2991     return OK;
2992 }
2993 
2994 /*
2995  * Return the line number in the current window that is closest to "lnum1" in
2996  * "buf1" in diff mode.
2997  */
2998     static linenr_T
2999 diff_get_corresponding_line_int(
3000     buf_T	*buf1,
3001     linenr_T	lnum1)
3002 {
3003     int		idx1;
3004     int		idx2;
3005     diff_T	*dp;
3006     int		baseline = 0;
3007 
3008     idx1 = diff_buf_idx(buf1);
3009     idx2 = diff_buf_idx(curbuf);
3010     if (idx1 == DB_COUNT || idx2 == DB_COUNT || curtab->tp_first_diff == NULL)
3011 	return lnum1;
3012 
3013     if (curtab->tp_diff_invalid)
3014 	ex_diffupdate(NULL);		// update after a big change
3015 
3016     if (curtab->tp_first_diff == NULL)		// no diffs today
3017 	return lnum1;
3018 
3019     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
3020     {
3021 	if (dp->df_lnum[idx1] > lnum1)
3022 	    return lnum1 - baseline;
3023 	if ((dp->df_lnum[idx1] + dp->df_count[idx1]) > lnum1)
3024 	{
3025 	    // Inside the diffblock
3026 	    baseline = lnum1 - dp->df_lnum[idx1];
3027 	    if (baseline > dp->df_count[idx2])
3028 		baseline = dp->df_count[idx2];
3029 
3030 	    return dp->df_lnum[idx2] + baseline;
3031 	}
3032 	if (    (dp->df_lnum[idx1] == lnum1)
3033 	     && (dp->df_count[idx1] == 0)
3034 	     && (dp->df_lnum[idx2] <= curwin->w_cursor.lnum)
3035 	     && ((dp->df_lnum[idx2] + dp->df_count[idx2])
3036 						      > curwin->w_cursor.lnum))
3037 	    /*
3038 	     * Special case: if the cursor is just after a zero-count
3039 	     * block (i.e. all filler) and the target cursor is already
3040 	     * inside the corresponding block, leave the target cursor
3041 	     * unmoved. This makes repeated CTRL-W W operations work
3042 	     * as expected.
3043 	     */
3044 	    return curwin->w_cursor.lnum;
3045 	baseline = (dp->df_lnum[idx1] + dp->df_count[idx1])
3046 				   - (dp->df_lnum[idx2] + dp->df_count[idx2]);
3047     }
3048 
3049     // If we get here then the cursor is after the last diff
3050     return lnum1 - baseline;
3051 }
3052 
3053 /*
3054  * Return the line number in the current window that is closest to "lnum1" in
3055  * "buf1" in diff mode.  Checks the line number to be valid.
3056  */
3057     linenr_T
3058 diff_get_corresponding_line(buf_T *buf1, linenr_T lnum1)
3059 {
3060     linenr_T lnum = diff_get_corresponding_line_int(buf1, lnum1);
3061 
3062     // don't end up past the end of the file
3063     if (lnum > curbuf->b_ml.ml_line_count)
3064 	return curbuf->b_ml.ml_line_count;
3065     return lnum;
3066 }
3067 
3068 /*
3069  * For line "lnum" in the current window find the equivalent lnum in window
3070  * "wp", compensating for inserted/deleted lines.
3071  */
3072     linenr_T
3073 diff_lnum_win(linenr_T lnum, win_T *wp)
3074 {
3075     diff_T	*dp;
3076     int		idx;
3077     int		i;
3078     linenr_T	n;
3079 
3080     idx = diff_buf_idx(curbuf);
3081     if (idx == DB_COUNT)		// safety check
3082 	return (linenr_T)0;
3083 
3084     if (curtab->tp_diff_invalid)
3085 	ex_diffupdate(NULL);		// update after a big change
3086 
3087     // search for a change that includes "lnum" in the list of diffblocks.
3088     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
3089 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
3090 	    break;
3091 
3092     // When after the last change, compute relative to the last line number.
3093     if (dp == NULL)
3094 	return wp->w_buffer->b_ml.ml_line_count
3095 					- (curbuf->b_ml.ml_line_count - lnum);
3096 
3097     // Find index for "wp".
3098     i = diff_buf_idx(wp->w_buffer);
3099     if (i == DB_COUNT)			// safety check
3100 	return (linenr_T)0;
3101 
3102     n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
3103     if (n > dp->df_lnum[i] + dp->df_count[i])
3104 	n = dp->df_lnum[i] + dp->df_count[i];
3105     return n;
3106 }
3107 
3108 /*
3109  * Handle an ED style diff line.
3110  * Return FAIL if the line does not contain diff info.
3111  */
3112     static int
3113 parse_diff_ed(
3114 	char_u	    *line,
3115 	linenr_T    *lnum_orig,
3116 	long	    *count_orig,
3117 	linenr_T    *lnum_new,
3118 	long	    *count_new)
3119 {
3120     char_u *p;
3121     long    f1, l1, f2, l2;
3122     int	    difftype;
3123 
3124     // The line must be one of three formats:
3125     // change: {first}[,{last}]c{first}[,{last}]
3126     // append: {first}a{first}[,{last}]
3127     // delete: {first}[,{last}]d{first}
3128     p = line;
3129     f1 = getdigits(&p);
3130     if (*p == ',')
3131     {
3132 	++p;
3133 	l1 = getdigits(&p);
3134     }
3135     else
3136 	l1 = f1;
3137     if (*p != 'a' && *p != 'c' && *p != 'd')
3138 	return FAIL;		// invalid diff format
3139     difftype = *p++;
3140     f2 = getdigits(&p);
3141     if (*p == ',')
3142     {
3143 	++p;
3144 	l2 = getdigits(&p);
3145     }
3146     else
3147 	l2 = f2;
3148     if (l1 < f1 || l2 < f2)
3149 	return FAIL;
3150 
3151     if (difftype == 'a')
3152     {
3153 	*lnum_orig = f1 + 1;
3154 	*count_orig = 0;
3155     }
3156     else
3157     {
3158 	*lnum_orig = f1;
3159 	*count_orig = l1 - f1 + 1;
3160     }
3161     if (difftype == 'd')
3162     {
3163 	*lnum_new = f2 + 1;
3164 	*count_new = 0;
3165     }
3166     else
3167     {
3168 	*lnum_new = f2;
3169 	*count_new = l2 - f2 + 1;
3170     }
3171     return OK;
3172 }
3173 
3174 /*
3175  * Parses unified diff with zero(!) context lines.
3176  * Return FAIL if there is no diff information in "line".
3177  */
3178     static int
3179 parse_diff_unified(
3180 	char_u	    *line,
3181 	linenr_T    *lnum_orig,
3182 	long	    *count_orig,
3183 	linenr_T    *lnum_new,
3184 	long	    *count_new)
3185 {
3186     char_u *p;
3187     long    oldline, oldcount, newline, newcount;
3188 
3189     // Parse unified diff hunk header:
3190     // @@ -oldline,oldcount +newline,newcount @@
3191     p = line;
3192     if (*p++ == '@' && *p++ == '@' && *p++ == ' ' && *p++ == '-')
3193     {
3194 	oldline = getdigits(&p);
3195 	if (*p == ',')
3196 	{
3197 	    ++p;
3198 	    oldcount = getdigits(&p);
3199 	}
3200 	else
3201 	    oldcount = 1;
3202 	if (*p++ == ' ' && *p++ == '+')
3203 	{
3204 	    newline = getdigits(&p);
3205 	    if (*p == ',')
3206 	    {
3207 		++p;
3208 		newcount = getdigits(&p);
3209 	    }
3210 	    else
3211 		newcount = 1;
3212 	}
3213 	else
3214 	    return FAIL;	// invalid diff format
3215 
3216 	if (oldcount == 0)
3217 	    oldline += 1;
3218 	if (newcount == 0)
3219 	    newline += 1;
3220 	if (newline == 0)
3221 	    newline = 1;
3222 
3223 	*lnum_orig = oldline;
3224 	*count_orig = oldcount;
3225 	*lnum_new = newline;
3226 	*count_new = newcount;
3227 
3228 	return OK;
3229     }
3230 
3231     return FAIL;
3232 }
3233 
3234 /*
3235  * Callback function for the xdl_diff() function.
3236  * Stores the diff output in a grow array.
3237  */
3238     static int
3239 xdiff_out(void *priv, mmbuffer_t *mb, int nbuf)
3240 {
3241     diffout_T	*dout = (diffout_T *)priv;
3242     char_u	*p;
3243 
3244     // The header line always comes by itself, text lines in at least two
3245     // parts.  We drop the text part.
3246     if (nbuf > 1)
3247 	return 0;
3248 
3249     // sanity check
3250     if (STRNCMP(mb[0].ptr, "@@ ", 3)  != 0)
3251 	return 0;
3252 
3253     if (ga_grow(&dout->dout_ga, 1) == FAIL)
3254 	return -1;
3255     p = vim_strnsave((char_u *)mb[0].ptr, mb[0].size);
3256     if (p == NULL)
3257 	return -1;
3258     ((char_u **)dout->dout_ga.ga_data)[dout->dout_ga.ga_len++] = p;
3259     return 0;
3260 }
3261 
3262 #endif	// FEAT_DIFF
3263 
3264 #if defined(FEAT_EVAL) || defined(PROTO)
3265 
3266 /*
3267  * "diff_filler()" function
3268  */
3269     void
3270 f_diff_filler(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
3271 {
3272 #ifdef FEAT_DIFF
3273     rettv->vval.v_number = diff_check_fill(curwin, tv_get_lnum(argvars));
3274 #endif
3275 }
3276 
3277 /*
3278  * "diff_hlID()" function
3279  */
3280     void
3281 f_diff_hlID(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
3282 {
3283 #ifdef FEAT_DIFF
3284     linenr_T		lnum = tv_get_lnum(argvars);
3285     static linenr_T	prev_lnum = 0;
3286     static varnumber_T	changedtick = 0;
3287     static int		fnum = 0;
3288     static int		change_start = 0;
3289     static int		change_end = 0;
3290     static hlf_T	hlID = (hlf_T)0;
3291     int			filler_lines;
3292     int			col;
3293 
3294     if (lnum < 0)	// ignore type error in {lnum} arg
3295 	lnum = 0;
3296     if (lnum != prev_lnum
3297 	    || changedtick != CHANGEDTICK(curbuf)
3298 	    || fnum != curbuf->b_fnum)
3299     {
3300 	// New line, buffer, change: need to get the values.
3301 	filler_lines = diff_check(curwin, lnum);
3302 	if (filler_lines < 0)
3303 	{
3304 	    if (filler_lines == -1)
3305 	    {
3306 		change_start = MAXCOL;
3307 		change_end = -1;
3308 		if (diff_find_change(curwin, lnum, &change_start, &change_end))
3309 		    hlID = HLF_ADD;	// added line
3310 		else
3311 		    hlID = HLF_CHD;	// changed line
3312 	    }
3313 	    else
3314 		hlID = HLF_ADD;	// added line
3315 	}
3316 	else
3317 	    hlID = (hlf_T)0;
3318 	prev_lnum = lnum;
3319 	changedtick = CHANGEDTICK(curbuf);
3320 	fnum = curbuf->b_fnum;
3321     }
3322 
3323     if (hlID == HLF_CHD || hlID == HLF_TXD)
3324     {
3325 	col = tv_get_number(&argvars[1]) - 1; // ignore type error in {col}
3326 	if (col >= change_start && col <= change_end)
3327 	    hlID = HLF_TXD;			// changed text
3328 	else
3329 	    hlID = HLF_CHD;			// changed line
3330     }
3331     rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
3332 #endif
3333 }
3334 
3335 #endif
3336