xref: /vim-8.2.3635/src/diff.c (revision df1bdc92)
1 /* vim:set ts=8 sts=4 sw=4:
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 or three buffers.
12  */
13 
14 #include "vim.h"
15 
16 #if defined(FEAT_DIFF) || defined(PROTO)
17 
18 static int	diff_busy = FALSE;	/* ex_diffgetput() is busy */
19 
20 /* flags obtained from the 'diffopt' option */
21 #define DIFF_FILLER	1	/* display filler lines */
22 #define DIFF_ICASE	2	/* ignore case */
23 #define DIFF_IWHITE	4	/* ignore change in white space */
24 static int	diff_flags = DIFF_FILLER;
25 
26 #define LBUFLEN 50		/* length of line in diff file */
27 
28 static int diff_a_works = MAYBE; /* TRUE when "diff -a" works, FALSE when it
29 				    doesn't work, MAYBE when not checked yet */
30 #if defined(MSWIN) || defined(MSDOS)
31 static int diff_bin_works = MAYBE; /* TRUE when "diff --binary" works, FALSE
32 				      when it doesn't work, MAYBE when not
33 				      checked yet */
34 #endif
35 
36 static int diff_buf_idx __ARGS((buf_T *buf));
37 static int diff_buf_idx_tp __ARGS((buf_T *buf, tabpage_T *tp));
38 static void diff_mark_adjust_tp __ARGS((tabpage_T *tp, int idx, linenr_T line1, linenr_T line2, long amount, long amount_after));
39 static void diff_check_unchanged __ARGS((tabpage_T *tp, diff_T *dp));
40 static int diff_check_sanity __ARGS((tabpage_T *tp, diff_T *dp));
41 static void diff_redraw __ARGS((int dofold));
42 static int diff_write __ARGS((buf_T *buf, char_u *fname));
43 static void diff_file __ARGS((char_u *tmp_orig, char_u *tmp_new, char_u *tmp_diff));
44 static int diff_equal_entry __ARGS((diff_T *dp, int idx1, int idx2));
45 static int diff_cmp __ARGS((char_u *s1, char_u *s2));
46 #ifdef FEAT_FOLDING
47 static void diff_fold_update __ARGS((diff_T *dp, int skip_idx));
48 #endif
49 static void diff_read __ARGS((int idx_orig, int idx_new, char_u *fname));
50 static void diff_copy_entry __ARGS((diff_T *dprev, diff_T *dp, int idx_orig, int idx_new));
51 static diff_T *diff_alloc_new __ARGS((tabpage_T *tp, diff_T *dprev, diff_T *dp));
52 
53 #ifndef USE_CR
54 # define tag_fgets vim_fgets
55 #endif
56 
57 /*
58  * Called when deleting or unloading a buffer: No longer make a diff with it.
59  */
60     void
61 diff_buf_delete(buf)
62     buf_T	*buf;
63 {
64     int		i;
65     tabpage_T	*tp;
66 
67     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
68     {
69 	i = diff_buf_idx_tp(buf, tp);
70 	if (i != DB_COUNT)
71 	{
72 	    tp->tp_diffbuf[i] = NULL;
73 	    tp->tp_diff_invalid = TRUE;
74 	}
75     }
76 }
77 
78 /*
79  * Check if the current buffer should be added to or removed from the list of
80  * diff buffers.
81  */
82     void
83 diff_buf_adjust(win)
84     win_T	*win;
85 {
86     win_T	*wp;
87     int		i;
88 
89     if (!win->w_p_diff)
90     {
91 	/* When there is no window showing a diff for this buffer, remove
92 	 * it from the diffs. */
93 	for (wp = firstwin; wp != NULL; wp = wp->w_next)
94 	    if (wp->w_buffer == win->w_buffer && wp->w_p_diff)
95 		break;
96 	if (wp == NULL)
97 	{
98 	    i = diff_buf_idx(win->w_buffer);
99 	    if (i != DB_COUNT)
100 	    {
101 		curtab->tp_diffbuf[i] = NULL;
102 		curtab->tp_diff_invalid = TRUE;
103 	    }
104 	}
105     }
106     else
107 	diff_buf_add(win->w_buffer);
108 }
109 
110 /*
111  * Add a buffer to make diffs for.
112  * Call this when a new buffer is being edited in the current window where
113  * 'diff' is set.
114  * Marks the current buffer as being part of the diff and requireing updating.
115  * This must be done before any autocmd, because a command may use info
116  * about the screen contents.
117  */
118     void
119 diff_buf_add(buf)
120     buf_T	*buf;
121 {
122     int		i;
123 
124     if (diff_buf_idx(buf) != DB_COUNT)
125 	return;		/* It's already there. */
126 
127     for (i = 0; i < DB_COUNT; ++i)
128 	if (curtab->tp_diffbuf[i] == NULL)
129 	{
130 	    curtab->tp_diffbuf[i] = buf;
131 	    curtab->tp_diff_invalid = TRUE;
132 	    return;
133 	}
134 
135     EMSGN(_("E96: Can not diff more than %ld buffers"), DB_COUNT);
136 }
137 
138 /*
139  * Find buffer "buf" in the list of diff buffers for the current tab page.
140  * Return its index or DB_COUNT if not found.
141  */
142     static int
143 diff_buf_idx(buf)
144     buf_T	*buf;
145 {
146     int		idx;
147 
148     for (idx = 0; idx < DB_COUNT; ++idx)
149 	if (curtab->tp_diffbuf[idx] == buf)
150 	    break;
151     return idx;
152 }
153 
154 /*
155  * Find buffer "buf" in the list of diff buffers for tab page "tp".
156  * Return its index or DB_COUNT if not found.
157  */
158     static int
159 diff_buf_idx_tp(buf, tp)
160     buf_T	*buf;
161     tabpage_T	*tp;
162 {
163     int		idx;
164 
165     for (idx = 0; idx < DB_COUNT; ++idx)
166 	if (tp->tp_diffbuf[idx] == buf)
167 	    break;
168     return idx;
169 }
170 
171 /*
172  * Mark the diff info involving buffer "buf" as invalid, it will be updated
173  * when info is requested.
174  */
175     void
176 diff_invalidate(buf)
177     buf_T	*buf;
178 {
179     tabpage_T	*tp;
180     int		i;
181 
182     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
183     {
184 	i = diff_buf_idx_tp(buf, tp);
185 	if (i != DB_COUNT)
186 	{
187 	    tp->tp_diff_invalid = TRUE;
188 	    if (tp == curtab)
189 		diff_redraw(TRUE);
190 	}
191     }
192 }
193 
194 /*
195  * Called by mark_adjust(): update line numbers in "curbuf".
196  */
197     void
198 diff_mark_adjust(line1, line2, amount, amount_after)
199     linenr_T	line1;
200     linenr_T	line2;
201     long	amount;
202     long	amount_after;
203 {
204     int		idx;
205     tabpage_T	*tp;
206 
207     /* Handle all tab pages that use the current buffer in a diff. */
208     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
209     {
210 	idx = diff_buf_idx_tp(curbuf, tp);
211 	if (idx != DB_COUNT)
212 	    diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after);
213     }
214 }
215 
216 /*
217  * Update line numbers in tab page "tp" for "curbuf" with index "idx".
218  * This attempts to update the changes as much as possible:
219  * When inserting/deleting lines outside of existing change blocks, create a
220  * new change block and update the line numbers in following blocks.
221  * When inserting/deleting lines in existing change blocks, update them.
222  */
223     static void
224 diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after)
225     tabpage_T	*tp;
226     int		idx;
227     linenr_T	line1;
228     linenr_T	line2;
229     long	amount;
230     long	amount_after;
231 {
232     diff_T	*dp;
233     diff_T	*dprev;
234     diff_T	*dnext;
235     int		i;
236     int		inserted, deleted;
237     int		n, off;
238     linenr_T	last;
239     linenr_T	lnum_deleted = line1;	/* lnum of remaining deletion */
240     int		check_unchanged;
241 
242     if (line2 == MAXLNUM)
243     {
244 	/* mark_adjust(99, MAXLNUM, 9, 0): insert lines */
245 	inserted = amount;
246 	deleted = 0;
247     }
248     else if (amount_after > 0)
249     {
250 	/* mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines*/
251 	inserted = amount_after;
252 	deleted = 0;
253     }
254     else
255     {
256 	/* mark_adjust(98, 99, MAXLNUM, -2): delete lines */
257 	inserted = 0;
258 	deleted = -amount_after;
259     }
260 
261     dprev = NULL;
262     dp = tp->tp_first_diff;
263     for (;;)
264     {
265 	/* If the change is after the previous diff block and before the next
266 	 * diff block, thus not touching an existing change, create a new diff
267 	 * block.  Don't do this when ex_diffgetput() is busy. */
268 	if ((dp == NULL || dp->df_lnum[idx] - 1 > line2
269 		    || (line2 == MAXLNUM && dp->df_lnum[idx] > line1))
270 		&& (dprev == NULL
271 		    || dprev->df_lnum[idx] + dprev->df_count[idx] < line1)
272 		&& !diff_busy)
273 	{
274 	    dnext = diff_alloc_new(tp, dprev, dp);
275 	    if (dnext == NULL)
276 		return;
277 
278 	    dnext->df_lnum[idx] = line1;
279 	    dnext->df_count[idx] = inserted;
280 	    for (i = 0; i < DB_COUNT; ++i)
281 		if (tp->tp_diffbuf[i] != NULL && i != idx)
282 		{
283 		    if (dprev == NULL)
284 			dnext->df_lnum[i] = line1;
285 		    else
286 			dnext->df_lnum[i] = line1
287 			    + (dprev->df_lnum[i] + dprev->df_count[i])
288 			    - (dprev->df_lnum[idx] + dprev->df_count[idx]);
289 		    dnext->df_count[i] = deleted;
290 		}
291 	}
292 
293 	/* if at end of the list, quit */
294 	if (dp == NULL)
295 	    break;
296 
297 	/*
298 	 * Check for these situations:
299 	 *	  1  2	3
300 	 *	  1  2	3
301 	 * line1     2	3  4  5
302 	 *	     2	3  4  5
303 	 *	     2	3  4  5
304 	 * line2     2	3  4  5
305 	 *		3     5  6
306 	 *		3     5  6
307 	 */
308 	/* compute last line of this change */
309 	last = dp->df_lnum[idx] + dp->df_count[idx] - 1;
310 
311 	/* 1. change completely above line1: nothing to do */
312 	if (last >= line1 - 1)
313 	{
314 	    /* 6. change below line2: only adjust for amount_after; also when
315 	     * "deleted" became zero when deleted all lines between two diffs */
316 	    if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2)
317 	    {
318 		if (amount_after == 0)
319 		    break;	/* nothing left to change */
320 		dp->df_lnum[idx] += amount_after;
321 	    }
322 	    else
323 	    {
324 		check_unchanged = FALSE;
325 
326 		/* 2. 3. 4. 5.: inserted/deleted lines touching this diff. */
327 		if (deleted > 0)
328 		{
329 		    if (dp->df_lnum[idx] >= line1)
330 		    {
331 			off = dp->df_lnum[idx] - lnum_deleted;
332 			if (last <= line2)
333 			{
334 			    /* 4. delete all lines of diff */
335 			    if (dp->df_next != NULL
336 				    && dp->df_next->df_lnum[idx] - 1 <= line2)
337 			    {
338 				/* delete continues in next diff, only do
339 				 * lines until that one */
340 				n = dp->df_next->df_lnum[idx] - lnum_deleted;
341 				deleted -= n;
342 				n -= dp->df_count[idx];
343 				lnum_deleted = dp->df_next->df_lnum[idx];
344 			    }
345 			    else
346 				n = deleted - dp->df_count[idx];
347 			    dp->df_count[idx] = 0;
348 			}
349 			else
350 			{
351 			    /* 5. delete lines at or just before top of diff */
352 			    n = off;
353 			    dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1;
354 			    check_unchanged = TRUE;
355 			}
356 			dp->df_lnum[idx] = line1;
357 		    }
358 		    else
359 		    {
360 			off = 0;
361 			if (last < line2)
362 			{
363 			    /* 2. delete at end of of diff */
364 			    dp->df_count[idx] -= last - lnum_deleted + 1;
365 			    if (dp->df_next != NULL
366 				    && dp->df_next->df_lnum[idx] - 1 <= line2)
367 			    {
368 				/* delete continues in next diff, only do
369 				 * lines until that one */
370 				n = dp->df_next->df_lnum[idx] - 1 - last;
371 				deleted -= dp->df_next->df_lnum[idx]
372 							       - lnum_deleted;
373 				lnum_deleted = dp->df_next->df_lnum[idx];
374 			    }
375 			    else
376 				n = line2 - last;
377 			    check_unchanged = TRUE;
378 			}
379 			else
380 			{
381 			    /* 3. delete lines inside the diff */
382 			    n = 0;
383 			    dp->df_count[idx] -= deleted;
384 			}
385 		    }
386 
387 		    for (i = 0; i < DB_COUNT; ++i)
388 			if (tp->tp_diffbuf[i] != NULL && i != idx)
389 			{
390 			    dp->df_lnum[i] -= off;
391 			    dp->df_count[i] += n;
392 			}
393 		}
394 		else
395 		{
396 		    if (dp->df_lnum[idx] <= line1)
397 		    {
398 			/* inserted lines somewhere in this diff */
399 			dp->df_count[idx] += inserted;
400 			check_unchanged = TRUE;
401 		    }
402 		    else
403 			/* inserted lines somewhere above this diff */
404 			dp->df_lnum[idx] += inserted;
405 		}
406 
407 		if (check_unchanged)
408 		    /* Check if inserted lines are equal, may reduce the
409 		     * size of the diff.  TODO: also check for equal lines
410 		     * in the middle and perhaps split the block. */
411 		    diff_check_unchanged(tp, dp);
412 	    }
413 	}
414 
415 	/* check if this block touches the previous one, may merge them. */
416 	if (dprev != NULL && dprev->df_lnum[idx] + dprev->df_count[idx]
417 							  == dp->df_lnum[idx])
418 	{
419 	    for (i = 0; i < DB_COUNT; ++i)
420 		if (tp->tp_diffbuf[i] != NULL)
421 		    dprev->df_count[i] += dp->df_count[i];
422 	    dprev->df_next = dp->df_next;
423 	    vim_free(dp);
424 	    dp = dprev->df_next;
425 	}
426 	else
427 	{
428 	    /* Advance to next entry. */
429 	    dprev = dp;
430 	    dp = dp->df_next;
431 	}
432     }
433 
434     dprev = NULL;
435     dp = tp->tp_first_diff;
436     while (dp != NULL)
437     {
438 	/* All counts are zero, remove this entry. */
439 	for (i = 0; i < DB_COUNT; ++i)
440 	    if (tp->tp_diffbuf[i] != NULL && dp->df_count[i] != 0)
441 		break;
442 	if (i == DB_COUNT)
443 	{
444 	    dnext = dp->df_next;
445 	    vim_free(dp);
446 	    dp = dnext;
447 	    if (dprev == NULL)
448 		tp->tp_first_diff = dnext;
449 	    else
450 		dprev->df_next = dnext;
451 	}
452 	else
453 	{
454 	    /* Advance to next entry. */
455 	    dprev = dp;
456 	    dp = dp->df_next;
457 	}
458 
459     }
460 
461     if (tp == curtab)
462     {
463 	diff_redraw(TRUE);
464 
465 	/* Need to recompute the scroll binding, may remove or add filler
466 	 * lines (e.g., when adding lines above w_topline). But it's slow when
467 	 * making many changes, postpone until redrawing. */
468 	diff_need_scrollbind = TRUE;
469     }
470 }
471 
472 /*
473  * Allocate a new diff block and link it between "dprev" and "dp".
474  */
475     static diff_T *
476 diff_alloc_new(tp, dprev, dp)
477     tabpage_T	*tp;
478     diff_T	*dprev;
479     diff_T	*dp;
480 {
481     diff_T	*dnew;
482 
483     dnew = (diff_T *)alloc((unsigned)sizeof(diff_T));
484     if (dnew != NULL)
485     {
486 	dnew->df_next = dp;
487 	if (dprev == NULL)
488 	    tp->tp_first_diff = dnew;
489 	else
490 	    dprev->df_next = dnew;
491     }
492     return dnew;
493 }
494 
495 /*
496  * Check if the diff block "dp" can be made smaller for lines at the start and
497  * end that are equal.  Called after inserting lines.
498  * This may result in a change where all buffers have zero lines, the caller
499  * must take care of removing it.
500  */
501     static void
502 diff_check_unchanged(tp, dp)
503     tabpage_T	*tp;
504     diff_T	*dp;
505 {
506     int		i_org;
507     int		i_new;
508     int		off_org, off_new;
509     char_u	*line_org;
510     int		dir = FORWARD;
511 
512     /* Find the first buffers, use it as the original, compare the other
513      * buffer lines against this one. */
514     for (i_org = 0; i_org < DB_COUNT; ++i_org)
515 	if (tp->tp_diffbuf[i_org] != NULL)
516 	    break;
517     if (i_org == DB_COUNT)	/* safety check */
518 	return;
519 
520     if (diff_check_sanity(tp, dp) == FAIL)
521 	return;
522 
523     /* First check lines at the top, then at the bottom. */
524     off_org = 0;
525     off_new = 0;
526     for (;;)
527     {
528 	/* Repeat until a line is found which is different or the number of
529 	 * lines has become zero. */
530 	while (dp->df_count[i_org] > 0)
531 	{
532 	    /* Copy the line, the next ml_get() will invalidate it.  */
533 	    if (dir == BACKWARD)
534 		off_org = dp->df_count[i_org] - 1;
535 	    line_org = vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org],
536 					dp->df_lnum[i_org] + off_org, FALSE));
537 	    if (line_org == NULL)
538 		return;
539 	    for (i_new = i_org + 1; i_new < DB_COUNT; ++i_new)
540 	    {
541 		if (tp->tp_diffbuf[i_new] == NULL)
542 		    continue;
543 		if (dir == BACKWARD)
544 		    off_new = dp->df_count[i_new] - 1;
545 		/* if other buffer doesn't have this line, it was inserted */
546 		if (off_new < 0 || off_new >= dp->df_count[i_new])
547 		    break;
548 		if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new],
549 				   dp->df_lnum[i_new] + off_new, FALSE)) != 0)
550 		    break;
551 	    }
552 	    vim_free(line_org);
553 
554 	    /* Stop when a line isn't equal in all diff buffers. */
555 	    if (i_new != DB_COUNT)
556 		break;
557 
558 	    /* Line matched in all buffers, remove it from the diff. */
559 	    for (i_new = i_org; i_new < DB_COUNT; ++i_new)
560 		if (tp->tp_diffbuf[i_new] != NULL)
561 		{
562 		    if (dir == FORWARD)
563 			++dp->df_lnum[i_new];
564 		    --dp->df_count[i_new];
565 		}
566 	}
567 	if (dir == BACKWARD)
568 	    break;
569 	dir = BACKWARD;
570     }
571 }
572 
573 /*
574  * Check if a diff block doesn't contain invalid line numbers.
575  * This can happen when the diff program returns invalid results.
576  */
577     static int
578 diff_check_sanity(tp, dp)
579     tabpage_T	*tp;
580     diff_T	*dp;
581 {
582     int		i;
583 
584     for (i = 0; i < DB_COUNT; ++i)
585 	if (tp->tp_diffbuf[i] != NULL)
586 	    if (dp->df_lnum[i] + dp->df_count[i] - 1
587 				      > tp->tp_diffbuf[i]->b_ml.ml_line_count)
588 		return FAIL;
589     return OK;
590 }
591 
592 /*
593  * Mark all diff buffers in the current tab page for redraw.
594  */
595     static void
596 diff_redraw(dofold)
597     int		dofold;	    /* also recompute the folds */
598 {
599     win_T	*wp;
600     int		n;
601 
602     for (wp = firstwin; wp != NULL; wp = wp->w_next)
603 	if (wp->w_p_diff)
604 	{
605 	    redraw_win_later(wp, NOT_VALID);
606 #ifdef FEAT_FOLDING
607 	    if (dofold && foldmethodIsDiff(wp))
608 		foldUpdateAll(wp);
609 #endif
610 	    /* A change may have made filler lines invalid, need to take care
611 	     * of that for other windows. */
612 	    if (wp != curwin && wp->w_topfill > 0)
613 	    {
614 		n = diff_check(wp, wp->w_topline);
615 		if (wp->w_topfill > n)
616 		    wp->w_topfill = (n < 0 ? 0 : n);
617 	    }
618 	}
619 }
620 
621 /*
622  * Write buffer "buf" to file "name".
623  * Always use 'fileformat' set to "unix".
624  * Return FAIL for failure
625  */
626     static int
627 diff_write(buf, fname)
628     buf_T	*buf;
629     char_u	*fname;
630 {
631     int		r;
632     char_u	*save_ff;
633 
634     save_ff = buf->b_p_ff;
635     buf->b_p_ff = vim_strsave((char_u *)FF_UNIX);
636     r = buf_write(buf, fname, NULL, (linenr_T)1, buf->b_ml.ml_line_count,
637 					     NULL, FALSE, FALSE, FALSE, TRUE);
638     free_string_option(buf->b_p_ff);
639     buf->b_p_ff = save_ff;
640     return r;
641 }
642 
643 /*
644  * Completely update the diffs for the buffers involved.
645  * This uses the ordinary "diff" command.
646  * The buffers are written to a file, also for unmodified buffers (the file
647  * could have been produced by autocommands, e.g. the netrw plugin).
648  */
649 /*ARGSUSED*/
650     void
651 ex_diffupdate(eap)
652     exarg_T	*eap;	    /* can be NULL, it's not used */
653 {
654     buf_T	*buf;
655     int		idx_orig;
656     int		idx_new;
657     char_u	*tmp_orig;
658     char_u	*tmp_new;
659     char_u	*tmp_diff;
660     FILE	*fd;
661     int		ok;
662 
663     /* Delete all diffblocks. */
664     diff_clear(curtab);
665     curtab->tp_diff_invalid = FALSE;
666 
667     /* Use the first buffer as the original text. */
668     for (idx_orig = 0; idx_orig < DB_COUNT; ++idx_orig)
669 	if (curtab->tp_diffbuf[idx_orig] != NULL)
670 	    break;
671     if (idx_orig == DB_COUNT)
672 	return;
673 
674     /* Only need to do something when there is another buffer. */
675     for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new)
676 	if (curtab->tp_diffbuf[idx_new] != NULL)
677 	    break;
678     if (idx_new == DB_COUNT)
679 	return;
680 
681     /* We need three temp file names. */
682     tmp_orig = vim_tempname('o');
683     tmp_new = vim_tempname('n');
684     tmp_diff = vim_tempname('d');
685     if (tmp_orig == NULL || tmp_new == NULL || tmp_diff == NULL)
686 	goto theend;
687 
688     /*
689      * Do a quick test if "diff" really works.  Otherwise it looks like there
690      * are no differences.  Can't use the return value, it's non-zero when
691      * there are differences.
692      * May try twice, first with "-a" and then without.
693      */
694     for (;;)
695     {
696 	ok = FALSE;
697 	fd = mch_fopen((char *)tmp_orig, "w");
698 	if (fd != NULL)
699 	{
700 	    fwrite("line1\n", (size_t)6, (size_t)1, fd);
701 	    fclose(fd);
702 	    fd = mch_fopen((char *)tmp_new, "w");
703 	    if (fd != NULL)
704 	    {
705 		fwrite("line2\n", (size_t)6, (size_t)1, fd);
706 		fclose(fd);
707 		diff_file(tmp_orig, tmp_new, tmp_diff);
708 		fd = mch_fopen((char *)tmp_diff, "r");
709 		if (fd != NULL)
710 		{
711 		    char_u	linebuf[LBUFLEN];
712 
713 		    for (;;)
714 		    {
715 			/* There must be a line that contains "1c1". */
716 			if (tag_fgets(linebuf, LBUFLEN, fd))
717 			    break;
718 			if (STRNCMP(linebuf, "1c1", 3) == 0)
719 			    ok = TRUE;
720 		    }
721 		    fclose(fd);
722 		}
723 		mch_remove(tmp_diff);
724 		mch_remove(tmp_new);
725 	    }
726 	    mch_remove(tmp_orig);
727 	}
728 
729 #ifdef FEAT_EVAL
730 	/* When using 'diffexpr' break here. */
731 	if (*p_dex != NUL)
732 	    break;
733 #endif
734 
735 #if defined(MSWIN) || defined(MSDOS)
736 	/* If the "-a" argument works, also check if "--binary" works. */
737 	if (ok && diff_a_works == MAYBE && diff_bin_works == MAYBE)
738 	{
739 	    diff_a_works = TRUE;
740 	    diff_bin_works = TRUE;
741 	    continue;
742 	}
743 	if (!ok && diff_a_works == TRUE && diff_bin_works == TRUE)
744 	{
745 	    /* Tried --binary, but it failed. "-a" works though. */
746 	    diff_bin_works = FALSE;
747 	    ok = TRUE;
748 	}
749 #endif
750 
751 	/* If we checked if "-a" works already, break here. */
752 	if (diff_a_works != MAYBE)
753 	    break;
754 	diff_a_works = ok;
755 
756 	/* If "-a" works break here, otherwise retry without "-a". */
757 	if (ok)
758 	    break;
759     }
760     if (!ok)
761     {
762 	EMSG(_("E97: Cannot create diffs"));
763 	diff_a_works = MAYBE;
764 #if defined(MSWIN) || defined(MSDOS)
765 	diff_bin_works = MAYBE;
766 #endif
767 	goto theend;
768     }
769 
770     /* Write the first buffer to a tempfile. */
771     buf = curtab->tp_diffbuf[idx_orig];
772     if (diff_write(buf, tmp_orig) == FAIL)
773 	goto theend;
774 
775     /* Make a difference between the first buffer and every other. */
776     for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new)
777     {
778 	buf = curtab->tp_diffbuf[idx_new];
779 	if (buf == NULL)
780 	    continue;
781 	if (diff_write(buf, tmp_new) == FAIL)
782 	    continue;
783 	diff_file(tmp_orig, tmp_new, tmp_diff);
784 
785 	/* Read the diff output and add each entry to the diff list. */
786 	diff_read(idx_orig, idx_new, tmp_diff);
787 	mch_remove(tmp_diff);
788 	mch_remove(tmp_new);
789     }
790     mch_remove(tmp_orig);
791 
792     diff_redraw(TRUE);
793 
794 theend:
795     vim_free(tmp_orig);
796     vim_free(tmp_new);
797     vim_free(tmp_diff);
798 }
799 
800 /*
801  * Make a diff between files "tmp_orig" and "tmp_new", results in "tmp_diff".
802  */
803     static void
804 diff_file(tmp_orig, tmp_new, tmp_diff)
805     char_u	*tmp_orig;
806     char_u	*tmp_new;
807     char_u	*tmp_diff;
808 {
809     char_u	*cmd;
810 
811 #ifdef FEAT_EVAL
812     if (*p_dex != NUL)
813 	/* Use 'diffexpr' to generate the diff file. */
814 	eval_diff(tmp_orig, tmp_new, tmp_diff);
815     else
816 #endif
817     {
818 	cmd = alloc((unsigned)(STRLEN(tmp_orig) + STRLEN(tmp_new)
819 				+ STRLEN(tmp_diff) + STRLEN(p_srr) + 27));
820 	if (cmd != NULL)
821 	{
822 	    /* We don't want $DIFF_OPTIONS to get in the way. */
823 	    if (getenv("DIFF_OPTIONS"))
824 		vim_setenv((char_u *)"DIFF_OPTIONS", (char_u *)"");
825 
826 	    /* Build the diff command and execute it.  Always use -a, binary
827 	     * differences are of no use.  Ignore errors, diff returns
828 	     * non-zero when differences have been found. */
829 	    sprintf((char *)cmd, "diff %s%s%s%s%s %s",
830 		    diff_a_works == FALSE ? "" : "-a ",
831 #if defined(MSWIN) || defined(MSDOS)
832 		    diff_bin_works == TRUE ? "--binary " : "",
833 #else
834 		    "",
835 #endif
836 		    (diff_flags & DIFF_IWHITE) ? "-b " : "",
837 		    (diff_flags & DIFF_ICASE) ? "-i " : "",
838 		    tmp_orig, tmp_new);
839 	    append_redir(cmd, p_srr, tmp_diff);
840 	    (void)call_shell(cmd, SHELL_FILTER|SHELL_SILENT|SHELL_DOOUT);
841 	    vim_free(cmd);
842 	}
843     }
844 }
845 
846 /*
847  * Create a new version of a file from the current buffer and a diff file.
848  * The buffer is written to a file, also for unmodified buffers (the file
849  * could have been produced by autocommands, e.g. the netrw plugin).
850  */
851     void
852 ex_diffpatch(eap)
853     exarg_T	*eap;
854 {
855     char_u	*tmp_orig;	/* name of original temp file */
856     char_u	*tmp_new;	/* name of patched temp file */
857     char_u	*buf = NULL;
858     win_T	*old_curwin = curwin;
859     char_u	*newname = NULL;	/* name of patched file buffer */
860 #ifdef UNIX
861     char_u	dirbuf[MAXPATHL];
862     char_u	*fullname = NULL;
863 #endif
864 #ifdef FEAT_BROWSE
865     char_u	*browseFile = NULL;
866     int		browse_flag = cmdmod.browse;
867 #endif
868 
869 #ifdef FEAT_BROWSE
870     if (cmdmod.browse)
871     {
872 	browseFile = do_browse(0, (char_u *)_("Patch file"),
873 			 eap->arg, NULL, NULL, BROWSE_FILTER_ALL_FILES, NULL);
874 	if (browseFile == NULL)
875 	    return;		/* operation cancelled */
876 	eap->arg = browseFile;
877 	cmdmod.browse = FALSE;	/* don't let do_ecmd() browse again */
878     }
879 #endif
880 
881     /* We need two temp file names. */
882     tmp_orig = vim_tempname('o');
883     tmp_new = vim_tempname('n');
884     if (tmp_orig == NULL || tmp_new == NULL)
885 	goto theend;
886 
887     /* Write the current buffer to "tmp_orig". */
888     if (buf_write(curbuf, tmp_orig, NULL,
889 		(linenr_T)1, curbuf->b_ml.ml_line_count,
890 				     NULL, FALSE, FALSE, FALSE, TRUE) == FAIL)
891 	goto theend;
892 
893 #ifdef UNIX
894     /* Get the absolute path of the patchfile, changing directory below. */
895     fullname = FullName_save(eap->arg, FALSE);
896 #endif
897     buf = alloc((unsigned)(STRLEN(tmp_orig) + (
898 # ifdef UNIX
899 		    fullname != NULL ? STRLEN(fullname) :
900 # endif
901 		    STRLEN(eap->arg)) + STRLEN(tmp_new) + 16));
902     if (buf == NULL)
903 	goto theend;
904 
905 #ifdef UNIX
906     /* Temporaraly chdir to /tmp, to avoid patching files in the current
907      * directory when the patch file contains more than one patch.  When we
908      * have our own temp dir use that instead, it will be cleaned up when we
909      * exit (any .rej files created).  Don't change directory if we can't
910      * return to the current. */
911     if (mch_dirname(dirbuf, MAXPATHL) != OK || mch_chdir((char *)dirbuf) != 0)
912 	dirbuf[0] = NUL;
913     else
914     {
915 # ifdef TEMPDIRNAMES
916 	if (vim_tempdir != NULL)
917 	    mch_chdir((char *)vim_tempdir);
918 	else
919 # endif
920 	    mch_chdir("/tmp");
921 	shorten_fnames(TRUE);
922     }
923 #endif
924 
925 #ifdef FEAT_EVAL
926     if (*p_pex != NUL)
927 	/* Use 'patchexpr' to generate the new file. */
928 	eval_patch(tmp_orig,
929 # ifdef UNIX
930 		fullname != NULL ? fullname :
931 # endif
932 		eap->arg, tmp_new);
933     else
934 #endif
935     {
936 	/* Build the patch command and execute it.  Ignore errors.  Switch to
937 	 * cooked mode to allow the user to respond to prompts. */
938 	sprintf((char *)buf, "patch -o %s %s < \"%s\"", tmp_new, tmp_orig,
939 # ifdef UNIX
940 		fullname != NULL ? fullname :
941 # endif
942 		eap->arg);
943 	(void)call_shell(buf, SHELL_FILTER | SHELL_COOKED);
944     }
945 
946 #ifdef UNIX
947     if (dirbuf[0] != NUL)
948     {
949 	if (mch_chdir((char *)dirbuf) != 0)
950 	    EMSG(_(e_prev_dir));
951 	shorten_fnames(TRUE);
952     }
953 #endif
954 
955     /* patch probably has written over the screen */
956     redraw_later(CLEAR);
957 
958     /* Delete any .orig or .rej file created. */
959     STRCPY(buf, tmp_new);
960     STRCAT(buf, ".orig");
961     mch_remove(buf);
962     STRCPY(buf, tmp_new);
963     STRCAT(buf, ".rej");
964     mch_remove(buf);
965 
966     if (curbuf->b_fname != NULL)
967     {
968 	newname = vim_strnsave(curbuf->b_fname,
969 					  (int)(STRLEN(curbuf->b_fname) + 4));
970 	if (newname != NULL)
971 	    STRCAT(newname, ".new");
972     }
973 
974 #ifdef FEAT_GUI
975     need_mouse_correct = TRUE;
976 #endif
977     /* don't use a new tab page, each tab page has its own diffs */
978     cmdmod.tab = 0;
979 
980     if (win_split(0, 0) != FAIL)
981     {
982 	/* Pretend it was a ":split fname" command */
983 	eap->cmdidx = CMD_split;
984 	eap->arg = tmp_new;
985 	do_exedit(eap, old_curwin);
986 
987 	if (curwin != old_curwin)		/* split must have worked */
988 	{
989 	    /* Set 'diff', 'scrollbind' on and 'wrap' off. */
990 	    diff_win_options(curwin, TRUE);
991 	    diff_win_options(old_curwin, TRUE);
992 
993 	    if (newname != NULL)
994 	    {
995 		/* do a ":file filename.new" on the patched buffer */
996 		eap->arg = newname;
997 		ex_file(eap);
998 
999 #ifdef FEAT_AUTOCMD
1000 		/* Do filetype detection with the new name. */
1001 		do_cmdline_cmd((char_u *)":doau filetypedetect BufRead");
1002 #endif
1003 	    }
1004 	}
1005     }
1006 
1007 theend:
1008     if (tmp_orig != NULL)
1009 	mch_remove(tmp_orig);
1010     vim_free(tmp_orig);
1011     if (tmp_new != NULL)
1012 	mch_remove(tmp_new);
1013     vim_free(tmp_new);
1014     vim_free(newname);
1015     vim_free(buf);
1016 #ifdef UNIX
1017     vim_free(fullname);
1018 #endif
1019 #ifdef FEAT_BROWSE
1020     vim_free(browseFile);
1021     cmdmod.browse = browse_flag;
1022 #endif
1023 }
1024 
1025 /*
1026  * Split the window and edit another file, setting options to show the diffs.
1027  */
1028     void
1029 ex_diffsplit(eap)
1030     exarg_T	*eap;
1031 {
1032     win_T	*old_curwin = curwin;
1033 
1034 #ifdef FEAT_GUI
1035     need_mouse_correct = TRUE;
1036 #endif
1037     /* don't use a new tab page, each tab page has its own diffs */
1038     cmdmod.tab = 0;
1039 
1040     if (win_split(0, 0) != FAIL)
1041     {
1042 	/* Pretend it was a ":split fname" command */
1043 	eap->cmdidx = CMD_split;
1044 	curwin->w_p_diff = TRUE;
1045 	do_exedit(eap, old_curwin);
1046 
1047 	if (curwin != old_curwin)		/* split must have worked */
1048 	{
1049 	    /* Set 'diff', 'scrollbind' on and 'wrap' off. */
1050 	    diff_win_options(curwin, TRUE);
1051 	    diff_win_options(old_curwin, TRUE);
1052 	}
1053     }
1054 }
1055 
1056 /*
1057  * Set options to show difs for the current window.
1058  */
1059 /*ARGSUSED*/
1060     void
1061 ex_diffthis(eap)
1062     exarg_T	*eap;
1063 {
1064     /* Set 'diff', 'scrollbind' on and 'wrap' off. */
1065     diff_win_options(curwin, TRUE);
1066 }
1067 
1068 /*
1069  * Set options in window "wp" for diff mode.
1070  */
1071     void
1072 diff_win_options(wp, addbuf)
1073     win_T	*wp;
1074     int		addbuf;		/* Add buffer to diff. */
1075 {
1076     wp->w_p_diff = TRUE;
1077     wp->w_p_scb = TRUE;
1078     wp->w_p_wrap = FALSE;
1079 # ifdef FEAT_FOLDING
1080     {
1081 	win_T	    *old_curwin = curwin;
1082 
1083 	curwin = wp;
1084 	curbuf = curwin->w_buffer;
1085 	set_string_option_direct((char_u *)"fdm", -1, (char_u *)"diff",
1086 							  OPT_LOCAL|OPT_FREE);
1087 # ifdef FEAT_EVAL
1088 	set_option_scriptID((char_u *)"fdm", current_SID);
1089 # endif
1090 	curwin = old_curwin;
1091 	curbuf = curwin->w_buffer;
1092 	wp->w_p_fdc = 2;
1093 	wp->w_p_fen = TRUE;
1094 	wp->w_p_fdl = 0;
1095 	foldUpdateAll(wp);
1096 	/* make sure topline is not halfway a fold */
1097 	changed_window_setting_win(wp);
1098     }
1099 # endif
1100 #ifdef FEAT_SCROLLBIND
1101     if (vim_strchr(p_sbo, 'h') == NULL)
1102 	do_cmdline_cmd((char_u *)"set sbo+=hor");
1103 #endif
1104 
1105     if (addbuf)
1106 	diff_buf_add(wp->w_buffer);
1107     redraw_win_later(wp, NOT_VALID);
1108 }
1109 
1110 /*
1111  * Set options not to show diffs.  For the current window or all windows.
1112  * Only in the current tab page.
1113  */
1114     void
1115 ex_diffoff(eap)
1116     exarg_T	*eap;
1117 {
1118     win_T	*wp;
1119     win_T	*old_curwin = curwin;
1120 #ifdef FEAT_SCROLLBIND
1121     int		diffwin = FALSE;
1122 #endif
1123 
1124     for (wp = firstwin; wp != NULL; wp = wp->w_next)
1125     {
1126 	if (wp == curwin || eap->forceit)
1127 	{
1128 	    /* Set 'diff', 'scrollbind' off and 'wrap' on. */
1129 	    wp->w_p_diff = FALSE;
1130 	    wp->w_p_scb = FALSE;
1131 	    wp->w_p_wrap = TRUE;
1132 #ifdef FEAT_FOLDING
1133 	    curwin = wp;
1134 	    curbuf = curwin->w_buffer;
1135 	    set_string_option_direct((char_u *)"fdm", -1,
1136 				      (char_u *)"manual", OPT_LOCAL|OPT_FREE);
1137 # ifdef FEAT_EVAL
1138 	    set_option_scriptID((char_u *)"fdm", current_SID);
1139 # endif
1140 	    curwin = old_curwin;
1141 	    curbuf = curwin->w_buffer;
1142 	    wp->w_p_fdc = 0;
1143 	    wp->w_p_fen = FALSE;
1144 	    wp->w_p_fdl = 0;
1145 	    foldUpdateAll(wp);
1146 	    /* make sure topline is not halfway a fold */
1147 	    changed_window_setting_win(wp);
1148 #endif
1149 	    diff_buf_adjust(wp);
1150 	}
1151 #ifdef FEAT_SCROLLBIND
1152 	diffwin |= wp->w_p_diff;
1153 #endif
1154     }
1155 
1156 #ifdef FEAT_SCROLLBIND
1157     /* Remove "hor" from from 'scrollopt' if there are no diff windows left. */
1158     if (!diffwin && vim_strchr(p_sbo, 'h') != NULL)
1159 	do_cmdline_cmd((char_u *)"set sbo-=hor");
1160 #endif
1161 }
1162 
1163 /*
1164  * Read the diff output and add each entry to the diff list.
1165  */
1166     static void
1167 diff_read(idx_orig, idx_new, fname)
1168     int		idx_orig;	/* idx of original file */
1169     int		idx_new;	/* idx of new file */
1170     char_u	*fname;		/* name of diff output file */
1171 {
1172     FILE	*fd;
1173     diff_T	*dprev = NULL;
1174     diff_T	*dp = curtab->tp_first_diff;
1175     diff_T	*dn, *dpl;
1176     long	f1, l1, f2, l2;
1177     char_u	linebuf[LBUFLEN];   /* only need to hold the diff line */
1178     int		difftype;
1179     char_u	*p;
1180     long	off;
1181     int		i;
1182     linenr_T	lnum_orig, lnum_new;
1183     long	count_orig, count_new;
1184     int		notset = TRUE;	    /* block "*dp" not set yet */
1185 
1186     fd = mch_fopen((char *)fname, "r");
1187     if (fd == NULL)
1188     {
1189 	EMSG(_("E98: Cannot read diff output"));
1190 	return;
1191     }
1192 
1193     for (;;)
1194     {
1195 	if (tag_fgets(linebuf, LBUFLEN, fd))
1196 	    break;		/* end of file */
1197 	if (!isdigit(*linebuf))
1198 	    continue;		/* not the start of a diff block */
1199 
1200 	/* This line must be one of three formats:
1201 	 * {first}[,{last}]c{first}[,{last}]
1202 	 * {first}a{first}[,{last}]
1203 	 * {first}[,{last}]d{first}
1204 	 */
1205 	p = linebuf;
1206 	f1 = getdigits(&p);
1207 	if (*p == ',')
1208 	{
1209 	    ++p;
1210 	    l1 = getdigits(&p);
1211 	}
1212 	else
1213 	    l1 = f1;
1214 	if (*p != 'a' && *p != 'c' && *p != 'd')
1215 	    continue;		/* invalid diff format */
1216 	difftype = *p++;
1217 	f2 = getdigits(&p);
1218 	if (*p == ',')
1219 	{
1220 	    ++p;
1221 	    l2 = getdigits(&p);
1222 	}
1223 	else
1224 	    l2 = f2;
1225 	if (l1 < f1 || l2 < f2)
1226 	    continue;		/* invalid line range */
1227 
1228 	if (difftype == 'a')
1229 	{
1230 	    lnum_orig = f1 + 1;
1231 	    count_orig = 0;
1232 	}
1233 	else
1234 	{
1235 	    lnum_orig = f1;
1236 	    count_orig = l1 - f1 + 1;
1237 	}
1238 	if (difftype == 'd')
1239 	{
1240 	    lnum_new = f2 + 1;
1241 	    count_new = 0;
1242 	}
1243 	else
1244 	{
1245 	    lnum_new = f2;
1246 	    count_new = l2 - f2 + 1;
1247 	}
1248 
1249 	/* Go over blocks before the change, for which orig and new are equal.
1250 	 * Copy blocks from orig to new. */
1251 	while (dp != NULL
1252 		&& lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig])
1253 	{
1254 	    if (notset)
1255 		diff_copy_entry(dprev, dp, idx_orig, idx_new);
1256 	    dprev = dp;
1257 	    dp = dp->df_next;
1258 	    notset = TRUE;
1259 	}
1260 
1261 	if (dp != NULL
1262 		&& lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig]
1263 		&& lnum_orig + count_orig >= dp->df_lnum[idx_orig])
1264 	{
1265 	    /* New block overlaps with existing block(s).
1266 	     * First find last block that overlaps. */
1267 	    for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next)
1268 		if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig])
1269 		    break;
1270 
1271 	    /* If the newly found block starts before the old one, set the
1272 	     * start back a number of lines. */
1273 	    off = dp->df_lnum[idx_orig] - lnum_orig;
1274 	    if (off > 0)
1275 	    {
1276 		for (i = idx_orig; i < idx_new; ++i)
1277 		    if (curtab->tp_diffbuf[i] != NULL)
1278 			dp->df_lnum[i] -= off;
1279 		dp->df_lnum[idx_new] = lnum_new;
1280 		dp->df_count[idx_new] = count_new;
1281 	    }
1282 	    else if (notset)
1283 	    {
1284 		/* new block inside existing one, adjust new block */
1285 		dp->df_lnum[idx_new] = lnum_new + off;
1286 		dp->df_count[idx_new] = count_new - off;
1287 	    }
1288 	    else
1289 		/* second overlap of new block with existing block */
1290 		dp->df_count[idx_new] += count_new - count_orig;
1291 
1292 	    /* Adjust the size of the block to include all the lines to the
1293 	     * end of the existing block or the new diff, whatever ends last. */
1294 	    off = (lnum_orig + count_orig)
1295 			 - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]);
1296 	    if (off < 0)
1297 	    {
1298 		/* new change ends in existing block, adjust the end if not
1299 		 * done already */
1300 		if (notset)
1301 		    dp->df_count[idx_new] += -off;
1302 		off = 0;
1303 	    }
1304 	    for (i = idx_orig; i < idx_new + !notset; ++i)
1305 		if (curtab->tp_diffbuf[i] != NULL)
1306 		    dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i]
1307 						       - dp->df_lnum[i] + off;
1308 
1309 	    /* Delete the diff blocks that have been merged into one. */
1310 	    dn = dp->df_next;
1311 	    dp->df_next = dpl->df_next;
1312 	    while (dn != dp->df_next)
1313 	    {
1314 		dpl = dn->df_next;
1315 		vim_free(dn);
1316 		dn = dpl;
1317 	    }
1318 	}
1319 	else
1320 	{
1321 	    /* Allocate a new diffblock. */
1322 	    dp = diff_alloc_new(curtab, dprev, dp);
1323 	    if (dp == NULL)
1324 		return;
1325 
1326 	    dp->df_lnum[idx_orig] = lnum_orig;
1327 	    dp->df_count[idx_orig] = count_orig;
1328 	    dp->df_lnum[idx_new] = lnum_new;
1329 	    dp->df_count[idx_new] = count_new;
1330 
1331 	    /* Set values for other buffers, these must be equal to the
1332 	     * original buffer, otherwise there would have been a change
1333 	     * already. */
1334 	    for (i = idx_orig + 1; i < idx_new; ++i)
1335 		if (curtab->tp_diffbuf[i] != NULL)
1336 		    diff_copy_entry(dprev, dp, idx_orig, i);
1337 	}
1338 	notset = FALSE;		/* "*dp" has been set */
1339     }
1340 
1341     /* for remaining diff blocks orig and new are equal */
1342     while (dp != NULL)
1343     {
1344 	if (notset)
1345 	    diff_copy_entry(dprev, dp, idx_orig, idx_new);
1346 	dprev = dp;
1347 	dp = dp->df_next;
1348 	notset = TRUE;
1349     }
1350 
1351     fclose(fd);
1352 }
1353 
1354 /*
1355  * Copy an entry at "dp" from "idx_orig" to "idx_new".
1356  */
1357     static void
1358 diff_copy_entry(dprev, dp, idx_orig, idx_new)
1359     diff_T	*dprev;
1360     diff_T	*dp;
1361     int		idx_orig;
1362     int		idx_new;
1363 {
1364     long	off;
1365 
1366     if (dprev == NULL)
1367 	off = 0;
1368     else
1369 	off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig])
1370 	    - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]);
1371     dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off;
1372     dp->df_count[idx_new] = dp->df_count[idx_orig];
1373 }
1374 
1375 /*
1376  * Clear the list of diffblocks for tab page "tp".
1377  */
1378     void
1379 diff_clear(tp)
1380     tabpage_T	*tp;
1381 {
1382     diff_T	*p, *next_p;
1383 
1384     for (p = tp->tp_first_diff; p != NULL; p = next_p)
1385     {
1386 	next_p = p->df_next;
1387 	vim_free(p);
1388     }
1389     tp->tp_first_diff = NULL;
1390 }
1391 
1392 /*
1393  * Check diff status for line "lnum" in buffer "buf":
1394  * Returns 0 for nothing special
1395  * Returns -1 for a line that should be highlighted as changed.
1396  * Returns -2 for a line that should be highlighted as added/deleted.
1397  * Returns > 0 for inserting that many filler lines above it (never happens
1398  * when 'diffopt' doesn't contain "filler").
1399  * This should only be used for windows where 'diff' is set.
1400  */
1401     int
1402 diff_check(wp, lnum)
1403     win_T	*wp;
1404     linenr_T	lnum;
1405 {
1406     int		idx;		/* index in tp_diffbuf[] for this buffer */
1407     diff_T	*dp;
1408     int		maxcount;
1409     int		i;
1410     buf_T	*buf = wp->w_buffer;
1411     int		cmp;
1412 
1413     if (curtab->tp_diff_invalid)
1414 	ex_diffupdate(NULL);		/* update after a big change */
1415 
1416     if (curtab->tp_first_diff == NULL || !wp->w_p_diff)	/* no diffs at all */
1417 	return 0;
1418 
1419     /* safety check: "lnum" must be a buffer line */
1420     if (lnum < 1 || lnum > buf->b_ml.ml_line_count + 1)
1421 	return 0;
1422 
1423     idx = diff_buf_idx(buf);
1424     if (idx == DB_COUNT)
1425 	return 0;		/* no diffs for buffer "buf" */
1426 
1427 #ifdef FEAT_FOLDING
1428     /* A closed fold never has filler lines. */
1429     if (hasFoldingWin(wp, lnum, NULL, NULL, TRUE, NULL))
1430 	return 0;
1431 #endif
1432 
1433     /* search for a change that includes "lnum" in the list of diffblocks. */
1434     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1435 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1436 	    break;
1437     if (dp == NULL || lnum < dp->df_lnum[idx])
1438 	return 0;
1439 
1440     if (lnum < dp->df_lnum[idx] + dp->df_count[idx])
1441     {
1442 	int	zero = FALSE;
1443 
1444 	/* Changed or inserted line.  If the other buffers have a count of
1445 	 * zero, the lines were inserted.  If the other buffers have the same
1446 	 * count, check if the lines are identical. */
1447 	cmp = FALSE;
1448 	for (i = 0; i < DB_COUNT; ++i)
1449 	    if (i != idx && curtab->tp_diffbuf[i] != NULL)
1450 	    {
1451 		if (dp->df_count[i] == 0)
1452 		    zero = TRUE;
1453 		else
1454 		{
1455 		    if (dp->df_count[i] != dp->df_count[idx])
1456 			return -1;	    /* nr of lines changed. */
1457 		    cmp = TRUE;
1458 		}
1459 	    }
1460 	if (cmp)
1461 	{
1462 	    /* Compare all lines.  If they are equal the lines were inserted
1463 	     * in some buffers, deleted in others, but not changed. */
1464 	    for (i = 0; i < DB_COUNT; ++i)
1465 		if (i != idx && curtab->tp_diffbuf[i] != NULL && dp->df_count[i] != 0)
1466 		    if (!diff_equal_entry(dp, idx, i))
1467 			return -1;
1468 	}
1469 	/* If there is no buffer with zero lines then there is no difference
1470 	 * any longer.  Happens when making a change (or undo) that removes
1471 	 * the difference.  Can't remove the entry here, we might be halfway
1472 	 * updating the window.  Just report the text as unchanged.  Other
1473 	 * windows might still show the change though. */
1474 	if (zero == FALSE)
1475 	    return 0;
1476 	return -2;
1477     }
1478 
1479     /* If 'diffopt' doesn't contain "filler", return 0. */
1480     if (!(diff_flags & DIFF_FILLER))
1481 	return 0;
1482 
1483     /* Insert filler lines above the line just below the change.  Will return
1484      * 0 when this buf had the max count. */
1485     maxcount = 0;
1486     for (i = 0; i < DB_COUNT; ++i)
1487 	if (curtab->tp_diffbuf[i] != NULL && dp->df_count[i] > maxcount)
1488 	    maxcount = dp->df_count[i];
1489     return maxcount - dp->df_count[idx];
1490 }
1491 
1492 /*
1493  * Compare two entries in diff "*dp" and return TRUE if they are equal.
1494  */
1495     static int
1496 diff_equal_entry(dp, idx1, idx2)
1497     diff_T	*dp;
1498     int		idx1;
1499     int		idx2;
1500 {
1501     int		i;
1502     char_u	*line;
1503     int		cmp;
1504 
1505     if (dp->df_count[idx1] != dp->df_count[idx2])
1506 	return FALSE;
1507     if (diff_check_sanity(curtab, dp) == FAIL)
1508 	return FALSE;
1509     for (i = 0; i < dp->df_count[idx1]; ++i)
1510     {
1511 	line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1],
1512 					       dp->df_lnum[idx1] + i, FALSE));
1513 	if (line == NULL)
1514 	    return FALSE;
1515 	cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2],
1516 					       dp->df_lnum[idx2] + i, FALSE));
1517 	vim_free(line);
1518 	if (cmp != 0)
1519 	    return FALSE;
1520     }
1521     return TRUE;
1522 }
1523 
1524 /*
1525  * Compare strings "s1" and "s2" according to 'diffopt'.
1526  * Return non-zero when they are different.
1527  */
1528     static int
1529 diff_cmp(s1, s2)
1530     char_u	*s1;
1531     char_u	*s2;
1532 {
1533     char_u	*p1, *p2;
1534 #ifdef FEAT_MBYTE
1535     int		l;
1536 #endif
1537 
1538     if ((diff_flags & (DIFF_ICASE | DIFF_IWHITE)) == 0)
1539 	return STRCMP(s1, s2);
1540     if ((diff_flags & DIFF_ICASE) && !(diff_flags & DIFF_IWHITE))
1541 	return MB_STRICMP(s1, s2);
1542 
1543     /* Ignore white space changes and possibly ignore case. */
1544     p1 = s1;
1545     p2 = s2;
1546     while (*p1 != NUL && *p2 != NUL)
1547     {
1548 	if (vim_iswhite(*p1) && vim_iswhite(*p2))
1549 	{
1550 	    p1 = skipwhite(p1);
1551 	    p2 = skipwhite(p2);
1552 	}
1553 	else
1554 	{
1555 #ifdef FEAT_MBYTE
1556 	    l  = (*mb_ptr2len)(p1);
1557 	    if (l != (*mb_ptr2len)(p2))
1558 		break;
1559 	    if (l > 1)
1560 	    {
1561 		if (STRNCMP(p1, p2, l) != 0
1562 			&& (!enc_utf8
1563 			    || !(diff_flags & DIFF_ICASE)
1564 			    || utf_fold(utf_ptr2char(p1))
1565 					       != utf_fold(utf_ptr2char(p2))))
1566 		    break;
1567 		p1 += l;
1568 		p2 += l;
1569 	    }
1570 	    else
1571 #endif
1572 	    {
1573 		if (*p1 != *p2 && (!(diff_flags & DIFF_ICASE)
1574 				     || TOLOWER_LOC(*p1) != TOLOWER_LOC(*p2)))
1575 		    break;
1576 		++p1;
1577 		++p2;
1578 	    }
1579 	}
1580     }
1581 
1582     /* Ignore trailing white space. */
1583     p1 = skipwhite(p1);
1584     p2 = skipwhite(p2);
1585     if (*p1 != NUL || *p2 != NUL)
1586 	return 1;
1587     return 0;
1588 }
1589 
1590 /*
1591  * Return the number of filler lines above "lnum".
1592  */
1593     int
1594 diff_check_fill(wp, lnum)
1595     win_T	*wp;
1596     linenr_T	lnum;
1597 {
1598     int		n;
1599 
1600     /* be quick when there are no filler lines */
1601     if (!(diff_flags & DIFF_FILLER))
1602 	return 0;
1603     n = diff_check(wp, lnum);
1604     if (n <= 0)
1605 	return 0;
1606     return n;
1607 }
1608 
1609 /*
1610  * Set the topline of "towin" to match the position in "fromwin", so that they
1611  * show the same diff'ed lines.
1612  */
1613     void
1614 diff_set_topline(fromwin, towin)
1615     win_T	*fromwin;
1616     win_T	*towin;
1617 {
1618     buf_T	*buf = fromwin->w_buffer;
1619     linenr_T	lnum = fromwin->w_topline;
1620     int		idx;
1621     diff_T	*dp;
1622     int		i;
1623 
1624     idx = diff_buf_idx(buf);
1625     if (idx == DB_COUNT)
1626 	return;		/* safety check */
1627 
1628     if (curtab->tp_diff_invalid)
1629 	ex_diffupdate(NULL);		/* update after a big change */
1630 
1631     towin->w_topfill = 0;
1632 
1633     /* search for a change that includes "lnum" in the list of diffblocks. */
1634     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1635 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1636 	    break;
1637     if (dp == NULL)
1638     {
1639 	/* After last change, compute topline relative to end of file; no
1640 	 * filler lines. */
1641 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count
1642 					   - (buf->b_ml.ml_line_count - lnum);
1643     }
1644     else
1645     {
1646 	/* Find index for "towin". */
1647 	i = diff_buf_idx(towin->w_buffer);
1648 	if (i == DB_COUNT)
1649 	    return;		/* safety check */
1650 
1651 	towin->w_topline = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
1652 	if (lnum >= dp->df_lnum[idx])
1653 	{
1654 	    /* Inside a change: compute filler lines. */
1655 	    if (dp->df_count[i] == dp->df_count[idx])
1656 		towin->w_topfill = fromwin->w_topfill;
1657 	    else if (dp->df_count[i] > dp->df_count[idx])
1658 	    {
1659 		if (lnum == dp->df_lnum[idx] + dp->df_count[idx])
1660 		    towin->w_topline = dp->df_lnum[i] + dp->df_count[i]
1661 							 - fromwin->w_topfill;
1662 	    }
1663 	    else
1664 	    {
1665 		if (towin->w_topline >= dp->df_lnum[i] + dp->df_count[i])
1666 		{
1667 		    if (diff_flags & DIFF_FILLER)
1668 			towin->w_topfill = dp->df_lnum[idx]
1669 						   + dp->df_count[idx] - lnum;
1670 		    towin->w_topline = dp->df_lnum[i] + dp->df_count[i];
1671 		}
1672 	    }
1673 	}
1674     }
1675 
1676     /* safety check (if diff info gets outdated strange things may happen) */
1677     towin->w_botfill = FALSE;
1678     if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count)
1679     {
1680 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count;
1681 	towin->w_botfill = TRUE;
1682     }
1683     if (towin->w_topline < 1)
1684     {
1685 	towin->w_topline = 1;
1686 	towin->w_topfill = 0;
1687     }
1688 
1689     /* When w_topline changes need to recompute w_botline and cursor position */
1690     invalidate_botline_win(towin);
1691     changed_line_abv_curs_win(towin);
1692 
1693     check_topfill(towin, FALSE);
1694 #ifdef FEAT_FOLDING
1695     (void)hasFoldingWin(towin, towin->w_topline, &towin->w_topline,
1696 							    NULL, TRUE, NULL);
1697 #endif
1698 }
1699 
1700 /*
1701  * This is called when 'diffopt' is changed.
1702  */
1703     int
1704 diffopt_changed()
1705 {
1706     char_u	*p;
1707     int		diff_context_new = 6;
1708     int		diff_flags_new = 0;
1709     tabpage_T	*tp;
1710 
1711     p = p_dip;
1712     while (*p != NUL)
1713     {
1714 	if (STRNCMP(p, "filler", 6) == 0)
1715 	{
1716 	    p += 6;
1717 	    diff_flags_new |= DIFF_FILLER;
1718 	}
1719 	else if (STRNCMP(p, "context:", 8) == 0 && VIM_ISDIGIT(p[8]))
1720 	{
1721 	    p += 8;
1722 	    diff_context_new = getdigits(&p);
1723 	}
1724 	else if (STRNCMP(p, "icase", 5) == 0)
1725 	{
1726 	    p += 5;
1727 	    diff_flags_new |= DIFF_ICASE;
1728 	}
1729 	else if (STRNCMP(p, "iwhite", 6) == 0)
1730 	{
1731 	    p += 6;
1732 	    diff_flags_new |= DIFF_IWHITE;
1733 	}
1734 	if (*p != ',' && *p != NUL)
1735 	    return FAIL;
1736 	if (*p == ',')
1737 	    ++p;
1738     }
1739 
1740     /* If "icase" or "iwhite" was added or removed, need to update the diff. */
1741     if (diff_flags != diff_flags_new)
1742 	for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
1743 	    tp->tp_diff_invalid = TRUE;
1744 
1745     diff_flags = diff_flags_new;
1746     diff_context = diff_context_new;
1747 
1748     diff_redraw(TRUE);
1749 
1750     /* recompute the scroll binding with the new option value, may
1751      * remove or add filler lines */
1752     check_scrollbind((linenr_T)0, 0L);
1753 
1754     return OK;
1755 }
1756 
1757 /*
1758  * Find the difference within a changed line.
1759  * Returns TRUE if the line was added, no other buffer has it.
1760  */
1761     int
1762 diff_find_change(wp, lnum, startp, endp)
1763     win_T	*wp;
1764     linenr_T	lnum;
1765     int		*startp;	/* first char of the change */
1766     int		*endp;		/* last char of the change */
1767 {
1768     char_u	*line_org;
1769     char_u	*line_new;
1770     int		i;
1771     int		si, ei_org, ei_new;
1772     diff_T	*dp;
1773     int		idx;
1774     int		off;
1775     int		added = TRUE;
1776 
1777     /* Make a copy of the line, the next ml_get() will invalidate it. */
1778     line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, FALSE));
1779     if (line_org == NULL)
1780 	return FALSE;
1781 
1782     idx = diff_buf_idx(wp->w_buffer);
1783     if (idx == DB_COUNT)	/* cannot happen */
1784 	return FALSE;
1785 
1786     /* search for a change that includes "lnum" in the list of diffblocks. */
1787     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1788 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1789 	    break;
1790     if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL)
1791 	return FALSE;
1792 
1793     off = lnum - dp->df_lnum[idx];
1794 
1795     for (i = 0; i < DB_COUNT; ++i)
1796 	if (curtab->tp_diffbuf[i] != NULL && i != idx)
1797 	{
1798 	    /* Skip lines that are not in the other change (filler lines). */
1799 	    if (off >= dp->df_count[i])
1800 		continue;
1801 	    added = FALSE;
1802 	    line_new = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off, FALSE);
1803 
1804 	    /* Search for start of difference */
1805 	    for (si = 0; line_org[si] != NUL && line_org[si] == line_new[si]; )
1806 		++si;
1807 #ifdef FEAT_MBYTE
1808 	    if (has_mbyte)
1809 	    {
1810 		/* Move back to first byte of character in both lines (may
1811 		 * have "nn^" in line_org and "n^ in line_new). */
1812 		si -= (*mb_head_off)(line_org, line_org + si);
1813 		si -= (*mb_head_off)(line_new, line_new + si);
1814 	    }
1815 #endif
1816 	    if (*startp > si)
1817 		*startp = si;
1818 
1819 	    /* Search for end of difference, if any. */
1820 	    if (line_org[si] != NUL || line_new[si] != NUL)
1821 	    {
1822 		ei_org = (int)STRLEN(line_org);
1823 		ei_new = (int)STRLEN(line_new);
1824 		while (ei_org >= *startp && ei_new >= *startp
1825 			&& ei_org >= 0 && ei_new >= 0
1826 			&& line_org[ei_org] == line_new[ei_new])
1827 		{
1828 		    --ei_org;
1829 		    --ei_new;
1830 		}
1831 		if (*endp < ei_org)
1832 		    *endp = ei_org;
1833 	    }
1834 	}
1835 
1836     vim_free(line_org);
1837     return added;
1838 }
1839 
1840 #if defined(FEAT_FOLDING) || defined(PROTO)
1841 /*
1842  * Return TRUE if line "lnum" is not close to a diff block, this line should
1843  * be in a fold.
1844  * Return FALSE if there are no diff blocks at all in this window.
1845  */
1846     int
1847 diff_infold(wp, lnum)
1848     win_T	*wp;
1849     linenr_T	lnum;
1850 {
1851     int		i;
1852     int		idx = -1;
1853     int		other = FALSE;
1854     diff_T	*dp;
1855 
1856     /* Return if 'diff' isn't set. */
1857     if (!wp->w_p_diff)
1858 	return FALSE;
1859 
1860     for (i = 0; i < DB_COUNT; ++i)
1861     {
1862 	if (curtab->tp_diffbuf[i] == wp->w_buffer)
1863 	    idx = i;
1864 	else if (curtab->tp_diffbuf[i] != NULL)
1865 	    other = TRUE;
1866     }
1867 
1868     /* return here if there are no diffs in the window */
1869     if (idx == -1 || !other)
1870 	return FALSE;
1871 
1872     if (curtab->tp_diff_invalid)
1873 	ex_diffupdate(NULL);		/* update after a big change */
1874 
1875     /* Return if there are no diff blocks.  All lines will be folded. */
1876     if (curtab->tp_first_diff == NULL)
1877 	return TRUE;
1878 
1879     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1880     {
1881 	/* If this change is below the line there can't be any further match. */
1882 	if (dp->df_lnum[idx] - diff_context > lnum)
1883 	    break;
1884 	/* If this change ends before the line we have a match. */
1885 	if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum)
1886 	    return FALSE;
1887     }
1888     return TRUE;
1889 }
1890 #endif
1891 
1892 /*
1893  * "dp" and "do" commands.
1894  */
1895     void
1896 nv_diffgetput(put)
1897     int		put;
1898 {
1899     exarg_T	ea;
1900 
1901     ea.arg = (char_u *)"";
1902     if (put)
1903 	ea.cmdidx = CMD_diffput;
1904     else
1905 	ea.cmdidx = CMD_diffget;
1906     ea.addr_count = 0;
1907     ea.line1 = curwin->w_cursor.lnum;
1908     ea.line2 = curwin->w_cursor.lnum;
1909     ex_diffgetput(&ea);
1910 }
1911 
1912 /*
1913  * ":diffget"
1914  * ":diffput"
1915  */
1916     void
1917 ex_diffgetput(eap)
1918     exarg_T	*eap;
1919 {
1920     linenr_T	lnum;
1921     int		count;
1922     linenr_T	off = 0;
1923     diff_T	*dp;
1924     diff_T	*dprev;
1925     diff_T	*dfree;
1926     int		idx_cur;
1927     int		idx_other;
1928     int		idx_from;
1929     int		idx_to;
1930     int		i;
1931     int		added;
1932     char_u	*p;
1933     aco_save_T	aco;
1934     buf_T	*buf;
1935     int		start_skip, end_skip;
1936     int		new_count;
1937     int		buf_empty;
1938 
1939     /* Find the current buffer in the list of diff buffers. */
1940     idx_cur = diff_buf_idx(curbuf);
1941     if (idx_cur == DB_COUNT)
1942     {
1943 	EMSG(_("E99: Current buffer is not in diff mode"));
1944 	return;
1945     }
1946 
1947     if (*eap->arg == NUL)
1948     {
1949 	/* No argument: Find the other buffer in the list of diff buffers. */
1950 	for (idx_other = 0; idx_other < DB_COUNT; ++idx_other)
1951 	    if (curtab->tp_diffbuf[idx_other] != curbuf
1952 		    && curtab->tp_diffbuf[idx_other] != NULL
1953 		    && (eap->cmdidx != CMD_diffput
1954 					       || curtab->tp_diffbuf[idx_other]->b_p_ma))
1955 		break;
1956 	if (idx_other == DB_COUNT)
1957 	{
1958 	    EMSG(_("E100: No other buffer in diff mode"));
1959 	    return;
1960 	}
1961 
1962 	/* Check that there isn't a third buffer in the list */
1963 	for (i = idx_other + 1; i < DB_COUNT; ++i)
1964 	    if (curtab->tp_diffbuf[i] != curbuf
1965 		    && curtab->tp_diffbuf[i] != NULL
1966 		    && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma))
1967 	    {
1968 		EMSG(_("E101: More than two buffers in diff mode, don't know which one to use"));
1969 		return;
1970 	    }
1971     }
1972     else
1973     {
1974 	/* Buffer number or pattern given.  Ignore trailing white space. */
1975 	p = eap->arg + STRLEN(eap->arg);
1976 	while (p > eap->arg && vim_iswhite(p[-1]))
1977 	    --p;
1978 	for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i)
1979 	    ;
1980 	if (eap->arg + i == p)	    /* digits only */
1981 	    i = atol((char *)eap->arg);
1982 	else
1983 	{
1984 	    i = buflist_findpat(eap->arg, p, FALSE, TRUE);
1985 	    if (i < 0)
1986 		return;		/* error message already given */
1987 	}
1988 	buf = buflist_findnr(i);
1989 	if (buf == NULL)
1990 	{
1991 	    EMSG2(_("E102: Can't find buffer \"%s\""), eap->arg);
1992 	    return;
1993 	}
1994 	idx_other = diff_buf_idx(buf);
1995 	if (idx_other == DB_COUNT)
1996 	{
1997 	    EMSG2(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg);
1998 	    return;
1999 	}
2000     }
2001 
2002     diff_busy = TRUE;
2003 
2004     /* When no range given include the line above or below the cursor. */
2005     if (eap->addr_count == 0)
2006     {
2007 	/* Make it possible that ":diffget" on the last line gets line below
2008 	 * the cursor line when there is no difference above the cursor. */
2009 	if (eap->cmdidx == CMD_diffget
2010 		&& eap->line1 == curbuf->b_ml.ml_line_count
2011 		&& diff_check(curwin, eap->line1) == 0
2012 		&& (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0))
2013 	    ++eap->line2;
2014 	else if (eap->line1 > 0)
2015 	    --eap->line1;
2016     }
2017 
2018     if (eap->cmdidx == CMD_diffget)
2019     {
2020 	idx_from = idx_other;
2021 	idx_to = idx_cur;
2022     }
2023     else
2024     {
2025 	idx_from = idx_cur;
2026 	idx_to = idx_other;
2027 	/* Need to make the other buffer the current buffer to be able to make
2028 	 * changes in it. */
2029 	/* set curwin/curbuf to buf and save a few things */
2030 	aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]);
2031     }
2032 
2033     dprev = NULL;
2034     for (dp = curtab->tp_first_diff; dp != NULL; )
2035     {
2036 	if (dp->df_lnum[idx_cur] > eap->line2 + off)
2037 	    break;	/* past the range that was specified */
2038 
2039 	dfree = NULL;
2040 	lnum = dp->df_lnum[idx_to];
2041 	count = dp->df_count[idx_to];
2042 	if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off
2043 		&& u_save(lnum - 1, lnum + count) != FAIL)
2044 	{
2045 	    /* Inside the specified range and saving for undo worked. */
2046 	    start_skip = 0;
2047 	    end_skip = 0;
2048 	    if (eap->addr_count > 0)
2049 	    {
2050 		/* A range was specified: check if lines need to be skipped. */
2051 		start_skip = eap->line1 + off - dp->df_lnum[idx_cur];
2052 		if (start_skip > 0)
2053 		{
2054 		    /* range starts below start of current diff block */
2055 		    if (start_skip > count)
2056 		    {
2057 			lnum += count;
2058 			count = 0;
2059 		    }
2060 		    else
2061 		    {
2062 			count -= start_skip;
2063 			lnum += start_skip;
2064 		    }
2065 		}
2066 		else
2067 		    start_skip = 0;
2068 
2069 		end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1
2070 							 - (eap->line2 + off);
2071 		if (end_skip > 0)
2072 		{
2073 		    /* range ends above end of current/from diff block */
2074 		    if (idx_cur == idx_from)	/* :diffput */
2075 		    {
2076 			i = dp->df_count[idx_cur] - start_skip - end_skip;
2077 			if (count > i)
2078 			    count = i;
2079 		    }
2080 		    else			/* :diffget */
2081 		    {
2082 			count -= end_skip;
2083 			end_skip = dp->df_count[idx_from] - start_skip - count;
2084 			if (end_skip < 0)
2085 			    end_skip = 0;
2086 		    }
2087 		}
2088 		else
2089 		    end_skip = 0;
2090 	    }
2091 
2092 	    buf_empty = FALSE;
2093 	    added = 0;
2094 	    for (i = 0; i < count; ++i)
2095 	    {
2096 		/* remember deleting the last line of the buffer */
2097 		buf_empty = curbuf->b_ml.ml_line_count == 1;
2098 		ml_delete(lnum, FALSE);
2099 		--added;
2100 	    }
2101 	    for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i)
2102 	    {
2103 		linenr_T nr;
2104 
2105 		nr = dp->df_lnum[idx_from] + start_skip + i;
2106 		if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count)
2107 		    break;
2108 		p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, FALSE));
2109 		if (p != NULL)
2110 		{
2111 		    ml_append(lnum + i - 1, p, 0, FALSE);
2112 		    vim_free(p);
2113 		    ++added;
2114 		    if (buf_empty && curbuf->b_ml.ml_line_count == 2)
2115 		    {
2116 			/* Added the first line into an empty buffer, need to
2117 			 * delete the dummy empty line. */
2118 			buf_empty = FALSE;
2119 			ml_delete((linenr_T)2, FALSE);
2120 		    }
2121 		}
2122 	    }
2123 	    new_count = dp->df_count[idx_to] + added;
2124 	    dp->df_count[idx_to] = new_count;
2125 
2126 	    if (start_skip == 0 && end_skip == 0)
2127 	    {
2128 		/* Check if there are any other buffers and if the diff is
2129 		 * equal in them. */
2130 		for (i = 0; i < DB_COUNT; ++i)
2131 		    if (curtab->tp_diffbuf[i] != NULL && i != idx_from && i != idx_to
2132 			    && !diff_equal_entry(dp, idx_from, i))
2133 			break;
2134 		if (i == DB_COUNT)
2135 		{
2136 		    /* delete the diff entry, the buffers are now equal here */
2137 		    dfree = dp;
2138 		    dp = dp->df_next;
2139 		    if (dprev == NULL)
2140 			curtab->tp_first_diff = dp;
2141 		    else
2142 			dprev->df_next = dp;
2143 		}
2144 	    }
2145 
2146 	    /* Adjust marks.  This will change the following entries! */
2147 	    if (added != 0)
2148 	    {
2149 		mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added);
2150 		if (curwin->w_cursor.lnum >= lnum)
2151 		{
2152 		    /* Adjust the cursor position if it's in/after the changed
2153 		     * lines. */
2154 		    if (curwin->w_cursor.lnum >= lnum + count)
2155 			curwin->w_cursor.lnum += added;
2156 		    else if (added < 0)
2157 			curwin->w_cursor.lnum = lnum;
2158 		}
2159 	    }
2160 	    changed_lines(lnum, 0, lnum + count, (long)added);
2161 
2162 	    if (dfree != NULL)
2163 	    {
2164 		/* Diff is deleted, update folds in other windows. */
2165 #ifdef FEAT_FOLDING
2166 		diff_fold_update(dfree, idx_to);
2167 #endif
2168 		vim_free(dfree);
2169 	    }
2170 	    else
2171 		/* mark_adjust() may have changed the count in a wrong way */
2172 		dp->df_count[idx_to] = new_count;
2173 
2174 	    /* When changing the current buffer, keep track of line numbers */
2175 	    if (idx_cur == idx_to)
2176 		off += added;
2177 	}
2178 
2179 	/* If before the range or not deleted, go to next diff. */
2180 	if (dfree == NULL)
2181 	{
2182 	    dprev = dp;
2183 	    dp = dp->df_next;
2184 	}
2185     }
2186 
2187     /* restore curwin/curbuf and a few other things */
2188     if (idx_other == idx_to)
2189     {
2190 	/* Syncing undo only works for the current buffer, but we change
2191 	 * another buffer.  Sync undo if the command was typed.  This isn't
2192 	 * 100% right when ":diffput" is used in a function or mapping. */
2193 	if (KeyTyped)
2194 	    u_sync();
2195 	aucmd_restbuf(&aco);
2196     }
2197 
2198     diff_busy = FALSE;
2199 
2200     /* Check that the cursor is on a valid character and update it's position.
2201      * When there were filler lines the topline has become invalid. */
2202     check_cursor();
2203     changed_line_abv_curs();
2204 
2205     /* Also need to redraw the other buffers. */
2206     diff_redraw(FALSE);
2207 }
2208 
2209 #ifdef FEAT_FOLDING
2210 /*
2211  * Update folds for all diff buffers for entry "dp".
2212  * Skip buffer with index "skip_idx".
2213  * When there are no diffs, all folds are removed.
2214  */
2215     static void
2216 diff_fold_update(dp, skip_idx)
2217     diff_T	*dp;
2218     int		skip_idx;
2219 {
2220     int		i;
2221     win_T	*wp;
2222 
2223     for (wp = firstwin; wp != NULL; wp = wp->w_next)
2224 	for (i = 0; i < DB_COUNT; ++i)
2225 	    if (curtab->tp_diffbuf[i] == wp->w_buffer && i != skip_idx)
2226 		foldUpdate(wp, dp->df_lnum[i],
2227 					    dp->df_lnum[i] + dp->df_count[i]);
2228 }
2229 #endif
2230 
2231 /*
2232  * Return TRUE if buffer "buf" is in diff-mode.
2233  */
2234     int
2235 diff_mode_buf(buf)
2236     buf_T	*buf;
2237 {
2238     tabpage_T	*tp;
2239 
2240     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
2241 	if (diff_buf_idx_tp(buf, tp) != DB_COUNT)
2242 	    return TRUE;
2243     return FALSE;
2244 }
2245 
2246 /*
2247  * Move "count" times in direction "dir" to the next diff block.
2248  * Return FAIL if there isn't such a diff block.
2249  */
2250     int
2251 diff_move_to(dir, count)
2252     int		dir;
2253     long	count;
2254 {
2255     int		idx;
2256     linenr_T	lnum = curwin->w_cursor.lnum;
2257     diff_T	*dp;
2258 
2259     idx = diff_buf_idx(curbuf);
2260     if (idx == DB_COUNT || curtab->tp_first_diff == NULL)
2261 	return FAIL;
2262 
2263     if (curtab->tp_diff_invalid)
2264 	ex_diffupdate(NULL);		/* update after a big change */
2265 
2266     if (curtab->tp_first_diff == NULL)		/* no diffs today */
2267 	return FAIL;
2268 
2269     while (--count >= 0)
2270     {
2271 	/* Check if already before first diff. */
2272 	if (dir == BACKWARD && lnum <= curtab->tp_first_diff->df_lnum[idx])
2273 	    break;
2274 
2275 	for (dp = curtab->tp_first_diff; ; dp = dp->df_next)
2276 	{
2277 	    if (dp == NULL)
2278 		break;
2279 	    if ((dir == FORWARD && lnum < dp->df_lnum[idx])
2280 		    || (dir == BACKWARD
2281 			&& (dp->df_next == NULL
2282 			    || lnum <= dp->df_next->df_lnum[idx])))
2283 	    {
2284 		lnum = dp->df_lnum[idx];
2285 		break;
2286 	    }
2287 	}
2288     }
2289 
2290     /* don't end up past the end of the file */
2291     if (lnum > curbuf->b_ml.ml_line_count)
2292 	lnum = curbuf->b_ml.ml_line_count;
2293 
2294     /* When the cursor didn't move at all we fail. */
2295     if (lnum == curwin->w_cursor.lnum)
2296 	return FAIL;
2297 
2298     setpcmark();
2299     curwin->w_cursor.lnum = lnum;
2300     curwin->w_cursor.col = 0;
2301 
2302     return OK;
2303 }
2304 
2305 #if defined(FEAT_FOLDING) || defined(PROTO)
2306 /*
2307  * For line "lnum" in the current window find the equivalent lnum in window
2308  * "wp", compensating for inserted/deleted lines.
2309  */
2310     linenr_T
2311 diff_lnum_win(lnum, wp)
2312     linenr_T	lnum;
2313     win_T	*wp;
2314 {
2315     diff_T	*dp;
2316     int		idx;
2317     int		i;
2318     linenr_T	n;
2319 
2320     idx = diff_buf_idx(curbuf);
2321     if (idx == DB_COUNT)		/* safety check */
2322 	return (linenr_T)0;
2323 
2324     if (curtab->tp_diff_invalid)
2325 	ex_diffupdate(NULL);		/* update after a big change */
2326 
2327     /* search for a change that includes "lnum" in the list of diffblocks. */
2328     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
2329 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
2330 	    break;
2331 
2332     /* When after the last change, compute relative to the last line number. */
2333     if (dp == NULL)
2334 	return wp->w_buffer->b_ml.ml_line_count
2335 					- (curbuf->b_ml.ml_line_count - lnum);
2336 
2337     /* Find index for "wp". */
2338     i = diff_buf_idx(wp->w_buffer);
2339     if (i == DB_COUNT)			/* safety check */
2340 	return (linenr_T)0;
2341 
2342     n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
2343     if (n > dp->df_lnum[i] + dp->df_count[i])
2344 	n = dp->df_lnum[i] + dp->df_count[i];
2345     return n;
2346 }
2347 #endif
2348 
2349 #endif	/* FEAT_DIFF */
2350