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