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