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