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