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