xref: /vim-8.2.3635/src/diff.c (revision a3227e2b)
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, 0);
1087 	curwin = old_curwin;
1088 	curbuf = curwin->w_buffer;
1089 	wp->w_p_fdc = 2;
1090 	wp->w_p_fen = TRUE;
1091 	wp->w_p_fdl = 0;
1092 	foldUpdateAll(wp);
1093 	/* make sure topline is not halfway a fold */
1094 	changed_window_setting_win(wp);
1095     }
1096 # endif
1097 #ifdef FEAT_SCROLLBIND
1098     if (vim_strchr(p_sbo, 'h') == NULL)
1099 	do_cmdline_cmd((char_u *)"set sbo+=hor");
1100 #endif
1101 
1102     if (addbuf)
1103 	diff_buf_add(wp->w_buffer);
1104     redraw_win_later(wp, NOT_VALID);
1105 }
1106 
1107 /*
1108  * Set options not to show diffs.  For the current window or all windows.
1109  * Only in the current tab page.
1110  */
1111     void
1112 ex_diffoff(eap)
1113     exarg_T	*eap;
1114 {
1115     win_T	*wp;
1116     win_T	*old_curwin = curwin;
1117 #ifdef FEAT_SCROLLBIND
1118     int		diffwin = FALSE;
1119 #endif
1120 
1121     for (wp = firstwin; wp != NULL; wp = wp->w_next)
1122     {
1123 	if (wp == curwin || eap->forceit)
1124 	{
1125 	    /* Set 'diff', 'scrollbind' off and 'wrap' on. */
1126 	    wp->w_p_diff = FALSE;
1127 	    wp->w_p_scb = FALSE;
1128 	    wp->w_p_wrap = TRUE;
1129 #ifdef FEAT_FOLDING
1130 	    curwin = wp;
1131 	    curbuf = curwin->w_buffer;
1132 	    set_string_option_direct((char_u *)"fdm", -1,
1133 				   (char_u *)"manual", OPT_LOCAL|OPT_FREE, 0);
1134 	    curwin = old_curwin;
1135 	    curbuf = curwin->w_buffer;
1136 	    wp->w_p_fdc = 0;
1137 	    wp->w_p_fen = FALSE;
1138 	    wp->w_p_fdl = 0;
1139 	    foldUpdateAll(wp);
1140 	    /* make sure topline is not halfway a fold */
1141 	    changed_window_setting_win(wp);
1142 #endif
1143 	    diff_buf_adjust(wp);
1144 	}
1145 #ifdef FEAT_SCROLLBIND
1146 	diffwin |= wp->w_p_diff;
1147 #endif
1148     }
1149 
1150 #ifdef FEAT_SCROLLBIND
1151     /* Remove "hor" from from 'scrollopt' if there are no diff windows left. */
1152     if (!diffwin && vim_strchr(p_sbo, 'h') != NULL)
1153 	do_cmdline_cmd((char_u *)"set sbo-=hor");
1154 #endif
1155 }
1156 
1157 /*
1158  * Read the diff output and add each entry to the diff list.
1159  */
1160     static void
1161 diff_read(idx_orig, idx_new, fname)
1162     int		idx_orig;	/* idx of original file */
1163     int		idx_new;	/* idx of new file */
1164     char_u	*fname;		/* name of diff output file */
1165 {
1166     FILE	*fd;
1167     diff_T	*dprev = NULL;
1168     diff_T	*dp = curtab->tp_first_diff;
1169     diff_T	*dn, *dpl;
1170     long	f1, l1, f2, l2;
1171     char_u	linebuf[LBUFLEN];   /* only need to hold the diff line */
1172     int		difftype;
1173     char_u	*p;
1174     long	off;
1175     int		i;
1176     linenr_T	lnum_orig, lnum_new;
1177     long	count_orig, count_new;
1178     int		notset = TRUE;	    /* block "*dp" not set yet */
1179 
1180     fd = mch_fopen((char *)fname, "r");
1181     if (fd == NULL)
1182     {
1183 	EMSG(_("E98: Cannot read diff output"));
1184 	return;
1185     }
1186 
1187     for (;;)
1188     {
1189 	if (tag_fgets(linebuf, LBUFLEN, fd))
1190 	    break;		/* end of file */
1191 	if (!isdigit(*linebuf))
1192 	    continue;		/* not the start of a diff block */
1193 
1194 	/* This line must be one of three formats:
1195 	 * {first}[,{last}]c{first}[,{last}]
1196 	 * {first}a{first}[,{last}]
1197 	 * {first}[,{last}]d{first}
1198 	 */
1199 	p = linebuf;
1200 	f1 = getdigits(&p);
1201 	if (*p == ',')
1202 	{
1203 	    ++p;
1204 	    l1 = getdigits(&p);
1205 	}
1206 	else
1207 	    l1 = f1;
1208 	if (*p != 'a' && *p != 'c' && *p != 'd')
1209 	    continue;		/* invalid diff format */
1210 	difftype = *p++;
1211 	f2 = getdigits(&p);
1212 	if (*p == ',')
1213 	{
1214 	    ++p;
1215 	    l2 = getdigits(&p);
1216 	}
1217 	else
1218 	    l2 = f2;
1219 	if (l1 < f1 || l2 < f2)
1220 	    continue;		/* invalid line range */
1221 
1222 	if (difftype == 'a')
1223 	{
1224 	    lnum_orig = f1 + 1;
1225 	    count_orig = 0;
1226 	}
1227 	else
1228 	{
1229 	    lnum_orig = f1;
1230 	    count_orig = l1 - f1 + 1;
1231 	}
1232 	if (difftype == 'd')
1233 	{
1234 	    lnum_new = f2 + 1;
1235 	    count_new = 0;
1236 	}
1237 	else
1238 	{
1239 	    lnum_new = f2;
1240 	    count_new = l2 - f2 + 1;
1241 	}
1242 
1243 	/* Go over blocks before the change, for which orig and new are equal.
1244 	 * Copy blocks from orig to new. */
1245 	while (dp != NULL
1246 		&& lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig])
1247 	{
1248 	    if (notset)
1249 		diff_copy_entry(dprev, dp, idx_orig, idx_new);
1250 	    dprev = dp;
1251 	    dp = dp->df_next;
1252 	    notset = TRUE;
1253 	}
1254 
1255 	if (dp != NULL
1256 		&& lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig]
1257 		&& lnum_orig + count_orig >= dp->df_lnum[idx_orig])
1258 	{
1259 	    /* New block overlaps with existing block(s).
1260 	     * First find last block that overlaps. */
1261 	    for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next)
1262 		if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig])
1263 		    break;
1264 
1265 	    /* If the newly found block starts before the old one, set the
1266 	     * start back a number of lines. */
1267 	    off = dp->df_lnum[idx_orig] - lnum_orig;
1268 	    if (off > 0)
1269 	    {
1270 		for (i = idx_orig; i < idx_new; ++i)
1271 		    if (curtab->tp_diffbuf[i] != NULL)
1272 			dp->df_lnum[i] -= off;
1273 		dp->df_lnum[idx_new] = lnum_new;
1274 		dp->df_count[idx_new] = count_new;
1275 	    }
1276 	    else if (notset)
1277 	    {
1278 		/* new block inside existing one, adjust new block */
1279 		dp->df_lnum[idx_new] = lnum_new + off;
1280 		dp->df_count[idx_new] = count_new - off;
1281 	    }
1282 	    else
1283 		/* second overlap of new block with existing block */
1284 		dp->df_count[idx_new] += count_new - count_orig;
1285 
1286 	    /* Adjust the size of the block to include all the lines to the
1287 	     * end of the existing block or the new diff, whatever ends last. */
1288 	    off = (lnum_orig + count_orig)
1289 			 - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]);
1290 	    if (off < 0)
1291 	    {
1292 		/* new change ends in existing block, adjust the end if not
1293 		 * done already */
1294 		if (notset)
1295 		    dp->df_count[idx_new] += -off;
1296 		off = 0;
1297 	    }
1298 	    for (i = idx_orig; i < idx_new + !notset; ++i)
1299 		if (curtab->tp_diffbuf[i] != NULL)
1300 		    dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i]
1301 						       - dp->df_lnum[i] + off;
1302 
1303 	    /* Delete the diff blocks that have been merged into one. */
1304 	    dn = dp->df_next;
1305 	    dp->df_next = dpl->df_next;
1306 	    while (dn != dp->df_next)
1307 	    {
1308 		dpl = dn->df_next;
1309 		vim_free(dn);
1310 		dn = dpl;
1311 	    }
1312 	}
1313 	else
1314 	{
1315 	    /* Allocate a new diffblock. */
1316 	    dp = diff_alloc_new(curtab, dprev, dp);
1317 	    if (dp == NULL)
1318 		return;
1319 
1320 	    dp->df_lnum[idx_orig] = lnum_orig;
1321 	    dp->df_count[idx_orig] = count_orig;
1322 	    dp->df_lnum[idx_new] = lnum_new;
1323 	    dp->df_count[idx_new] = count_new;
1324 
1325 	    /* Set values for other buffers, these must be equal to the
1326 	     * original buffer, otherwise there would have been a change
1327 	     * already. */
1328 	    for (i = idx_orig + 1; i < idx_new; ++i)
1329 		if (curtab->tp_diffbuf[i] != NULL)
1330 		    diff_copy_entry(dprev, dp, idx_orig, i);
1331 	}
1332 	notset = FALSE;		/* "*dp" has been set */
1333     }
1334 
1335     /* for remaining diff blocks orig and new are equal */
1336     while (dp != NULL)
1337     {
1338 	if (notset)
1339 	    diff_copy_entry(dprev, dp, idx_orig, idx_new);
1340 	dprev = dp;
1341 	dp = dp->df_next;
1342 	notset = TRUE;
1343     }
1344 
1345     fclose(fd);
1346 }
1347 
1348 /*
1349  * Copy an entry at "dp" from "idx_orig" to "idx_new".
1350  */
1351     static void
1352 diff_copy_entry(dprev, dp, idx_orig, idx_new)
1353     diff_T	*dprev;
1354     diff_T	*dp;
1355     int		idx_orig;
1356     int		idx_new;
1357 {
1358     long	off;
1359 
1360     if (dprev == NULL)
1361 	off = 0;
1362     else
1363 	off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig])
1364 	    - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]);
1365     dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off;
1366     dp->df_count[idx_new] = dp->df_count[idx_orig];
1367 }
1368 
1369 /*
1370  * Clear the list of diffblocks for tab page "tp".
1371  */
1372     void
1373 diff_clear(tp)
1374     tabpage_T	*tp;
1375 {
1376     diff_T	*p, *next_p;
1377 
1378     for (p = tp->tp_first_diff; p != NULL; p = next_p)
1379     {
1380 	next_p = p->df_next;
1381 	vim_free(p);
1382     }
1383     tp->tp_first_diff = NULL;
1384 }
1385 
1386 /*
1387  * Check diff status for line "lnum" in buffer "buf":
1388  * Returns 0 for nothing special
1389  * Returns -1 for a line that should be highlighted as changed.
1390  * Returns -2 for a line that should be highlighted as added/deleted.
1391  * Returns > 0 for inserting that many filler lines above it (never happens
1392  * when 'diffopt' doesn't contain "filler").
1393  * This should only be used for windows where 'diff' is set.
1394  */
1395     int
1396 diff_check(wp, lnum)
1397     win_T	*wp;
1398     linenr_T	lnum;
1399 {
1400     int		idx;		/* index in tp_diffbuf[] for this buffer */
1401     diff_T	*dp;
1402     int		maxcount;
1403     int		i;
1404     buf_T	*buf = wp->w_buffer;
1405     int		cmp;
1406 
1407     if (curtab->tp_diff_invalid)
1408 	ex_diffupdate(NULL);		/* update after a big change */
1409 
1410     if (curtab->tp_first_diff == NULL || !wp->w_p_diff)	/* no diffs at all */
1411 	return 0;
1412 
1413     /* safety check: "lnum" must be a buffer line */
1414     if (lnum < 1 || lnum > buf->b_ml.ml_line_count + 1)
1415 	return 0;
1416 
1417     idx = diff_buf_idx(buf);
1418     if (idx == DB_COUNT)
1419 	return 0;		/* no diffs for buffer "buf" */
1420 
1421 #ifdef FEAT_FOLDING
1422     /* A closed fold never has filler lines. */
1423     if (hasFoldingWin(wp, lnum, NULL, NULL, TRUE, NULL))
1424 	return 0;
1425 #endif
1426 
1427     /* search for a change that includes "lnum" in the list of diffblocks. */
1428     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1429 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1430 	    break;
1431     if (dp == NULL || lnum < dp->df_lnum[idx])
1432 	return 0;
1433 
1434     if (lnum < dp->df_lnum[idx] + dp->df_count[idx])
1435     {
1436 	int	zero = FALSE;
1437 
1438 	/* Changed or inserted line.  If the other buffers have a count of
1439 	 * zero, the lines were inserted.  If the other buffers have the same
1440 	 * count, check if the lines are identical. */
1441 	cmp = FALSE;
1442 	for (i = 0; i < DB_COUNT; ++i)
1443 	    if (i != idx && curtab->tp_diffbuf[i] != NULL)
1444 	    {
1445 		if (dp->df_count[i] == 0)
1446 		    zero = TRUE;
1447 		else
1448 		{
1449 		    if (dp->df_count[i] != dp->df_count[idx])
1450 			return -1;	    /* nr of lines changed. */
1451 		    cmp = TRUE;
1452 		}
1453 	    }
1454 	if (cmp)
1455 	{
1456 	    /* Compare all lines.  If they are equal the lines were inserted
1457 	     * in some buffers, deleted in others, but not changed. */
1458 	    for (i = 0; i < DB_COUNT; ++i)
1459 		if (i != idx && curtab->tp_diffbuf[i] != NULL && dp->df_count[i] != 0)
1460 		    if (!diff_equal_entry(dp, idx, i))
1461 			return -1;
1462 	}
1463 	/* If there is no buffer with zero lines then there is no difference
1464 	 * any longer.  Happens when making a change (or undo) that removes
1465 	 * the difference.  Can't remove the entry here, we might be halfway
1466 	 * updating the window.  Just report the text as unchanged.  Other
1467 	 * windows might still show the change though. */
1468 	if (zero == FALSE)
1469 	    return 0;
1470 	return -2;
1471     }
1472 
1473     /* If 'diffopt' doesn't contain "filler", return 0. */
1474     if (!(diff_flags & DIFF_FILLER))
1475 	return 0;
1476 
1477     /* Insert filler lines above the line just below the change.  Will return
1478      * 0 when this buf had the max count. */
1479     maxcount = 0;
1480     for (i = 0; i < DB_COUNT; ++i)
1481 	if (curtab->tp_diffbuf[i] != NULL && dp->df_count[i] > maxcount)
1482 	    maxcount = dp->df_count[i];
1483     return maxcount - dp->df_count[idx];
1484 }
1485 
1486 /*
1487  * Compare two entries in diff "*dp" and return TRUE if they are equal.
1488  */
1489     static int
1490 diff_equal_entry(dp, idx1, idx2)
1491     diff_T	*dp;
1492     int		idx1;
1493     int		idx2;
1494 {
1495     int		i;
1496     char_u	*line;
1497     int		cmp;
1498 
1499     if (dp->df_count[idx1] != dp->df_count[idx2])
1500 	return FALSE;
1501     if (diff_check_sanity(curtab, dp) == FAIL)
1502 	return FALSE;
1503     for (i = 0; i < dp->df_count[idx1]; ++i)
1504     {
1505 	line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1],
1506 					       dp->df_lnum[idx1] + i, FALSE));
1507 	if (line == NULL)
1508 	    return FALSE;
1509 	cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2],
1510 					       dp->df_lnum[idx2] + i, FALSE));
1511 	vim_free(line);
1512 	if (cmp != 0)
1513 	    return FALSE;
1514     }
1515     return TRUE;
1516 }
1517 
1518 /*
1519  * Compare strings "s1" and "s2" according to 'diffopt'.
1520  * Return non-zero when they are different.
1521  */
1522     static int
1523 diff_cmp(s1, s2)
1524     char_u	*s1;
1525     char_u	*s2;
1526 {
1527     char_u	*p1, *p2;
1528 #ifdef FEAT_MBYTE
1529     int		l;
1530 #endif
1531 
1532     if ((diff_flags & (DIFF_ICASE | DIFF_IWHITE)) == 0)
1533 	return STRCMP(s1, s2);
1534     if ((diff_flags & DIFF_ICASE) && !(diff_flags & DIFF_IWHITE))
1535 	return MB_STRICMP(s1, s2);
1536 
1537     /* Ignore white space changes and possibly ignore case. */
1538     p1 = s1;
1539     p2 = s2;
1540     while (*p1 != NUL && *p2 != NUL)
1541     {
1542 	if (vim_iswhite(*p1) && vim_iswhite(*p2))
1543 	{
1544 	    p1 = skipwhite(p1);
1545 	    p2 = skipwhite(p2);
1546 	}
1547 	else
1548 	{
1549 #ifdef FEAT_MBYTE
1550 	    l  = (*mb_ptr2len)(p1);
1551 	    if (l != (*mb_ptr2len)(p2))
1552 		break;
1553 	    if (l > 1)
1554 	    {
1555 		if (STRNCMP(p1, p2, l) != 0
1556 			&& (!enc_utf8
1557 			    || !(diff_flags & DIFF_ICASE)
1558 			    || utf_fold(utf_ptr2char(p1))
1559 					       != utf_fold(utf_ptr2char(p2))))
1560 		    break;
1561 		p1 += l;
1562 		p2 += l;
1563 	    }
1564 	    else
1565 #endif
1566 	    {
1567 		if (*p1 != *p2 && (!(diff_flags & DIFF_ICASE)
1568 				     || TOLOWER_LOC(*p1) != TOLOWER_LOC(*p2)))
1569 		    break;
1570 		++p1;
1571 		++p2;
1572 	    }
1573 	}
1574     }
1575 
1576     /* Ignore trailing white space. */
1577     p1 = skipwhite(p1);
1578     p2 = skipwhite(p2);
1579     if (*p1 != NUL || *p2 != NUL)
1580 	return 1;
1581     return 0;
1582 }
1583 
1584 /*
1585  * Return the number of filler lines above "lnum".
1586  */
1587     int
1588 diff_check_fill(wp, lnum)
1589     win_T	*wp;
1590     linenr_T	lnum;
1591 {
1592     int		n;
1593 
1594     /* be quick when there are no filler lines */
1595     if (!(diff_flags & DIFF_FILLER))
1596 	return 0;
1597     n = diff_check(wp, lnum);
1598     if (n <= 0)
1599 	return 0;
1600     return n;
1601 }
1602 
1603 /*
1604  * Set the topline of "towin" to match the position in "fromwin", so that they
1605  * show the same diff'ed lines.
1606  */
1607     void
1608 diff_set_topline(fromwin, towin)
1609     win_T	*fromwin;
1610     win_T	*towin;
1611 {
1612     buf_T	*buf = fromwin->w_buffer;
1613     linenr_T	lnum = fromwin->w_topline;
1614     int		idx;
1615     diff_T	*dp;
1616     int		i;
1617 
1618     idx = diff_buf_idx(buf);
1619     if (idx == DB_COUNT)
1620 	return;		/* safety check */
1621 
1622     if (curtab->tp_diff_invalid)
1623 	ex_diffupdate(NULL);		/* update after a big change */
1624 
1625     towin->w_topfill = 0;
1626 
1627     /* search for a change that includes "lnum" in the list of diffblocks. */
1628     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1629 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1630 	    break;
1631     if (dp == NULL)
1632     {
1633 	/* After last change, compute topline relative to end of file; no
1634 	 * filler lines. */
1635 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count
1636 					   - (buf->b_ml.ml_line_count - lnum);
1637     }
1638     else
1639     {
1640 	/* Find index for "towin". */
1641 	i = diff_buf_idx(towin->w_buffer);
1642 	if (i == DB_COUNT)
1643 	    return;		/* safety check */
1644 
1645 	towin->w_topline = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
1646 	if (lnum >= dp->df_lnum[idx])
1647 	{
1648 	    /* Inside a change: compute filler lines. */
1649 	    if (dp->df_count[i] == dp->df_count[idx])
1650 		towin->w_topfill = fromwin->w_topfill;
1651 	    else if (dp->df_count[i] > dp->df_count[idx])
1652 	    {
1653 		if (lnum == dp->df_lnum[idx] + dp->df_count[idx])
1654 		    towin->w_topline = dp->df_lnum[i] + dp->df_count[i]
1655 							 - fromwin->w_topfill;
1656 	    }
1657 	    else
1658 	    {
1659 		if (towin->w_topline >= dp->df_lnum[i] + dp->df_count[i])
1660 		{
1661 		    if (diff_flags & DIFF_FILLER)
1662 			towin->w_topfill = dp->df_lnum[idx]
1663 						   + dp->df_count[idx] - lnum;
1664 		    towin->w_topline = dp->df_lnum[i] + dp->df_count[i];
1665 		}
1666 	    }
1667 	}
1668     }
1669 
1670     /* safety check (if diff info gets outdated strange things may happen) */
1671     towin->w_botfill = FALSE;
1672     if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count)
1673     {
1674 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count;
1675 	towin->w_botfill = TRUE;
1676     }
1677     if (towin->w_topline < 1)
1678     {
1679 	towin->w_topline = 1;
1680 	towin->w_topfill = 0;
1681     }
1682 
1683     /* When w_topline changes need to recompute w_botline and cursor position */
1684     invalidate_botline_win(towin);
1685     changed_line_abv_curs_win(towin);
1686 
1687     check_topfill(towin, FALSE);
1688 #ifdef FEAT_FOLDING
1689     (void)hasFoldingWin(towin, towin->w_topline, &towin->w_topline,
1690 							    NULL, TRUE, NULL);
1691 #endif
1692 }
1693 
1694 /*
1695  * This is called when 'diffopt' is changed.
1696  */
1697     int
1698 diffopt_changed()
1699 {
1700     char_u	*p;
1701     int		diff_context_new = 6;
1702     int		diff_flags_new = 0;
1703     tabpage_T	*tp;
1704 
1705     p = p_dip;
1706     while (*p != NUL)
1707     {
1708 	if (STRNCMP(p, "filler", 6) == 0)
1709 	{
1710 	    p += 6;
1711 	    diff_flags_new |= DIFF_FILLER;
1712 	}
1713 	else if (STRNCMP(p, "context:", 8) == 0 && VIM_ISDIGIT(p[8]))
1714 	{
1715 	    p += 8;
1716 	    diff_context_new = getdigits(&p);
1717 	}
1718 	else if (STRNCMP(p, "icase", 5) == 0)
1719 	{
1720 	    p += 5;
1721 	    diff_flags_new |= DIFF_ICASE;
1722 	}
1723 	else if (STRNCMP(p, "iwhite", 6) == 0)
1724 	{
1725 	    p += 6;
1726 	    diff_flags_new |= DIFF_IWHITE;
1727 	}
1728 	if (*p != ',' && *p != NUL)
1729 	    return FAIL;
1730 	if (*p == ',')
1731 	    ++p;
1732     }
1733 
1734     /* If "icase" or "iwhite" was added or removed, need to update the diff. */
1735     if (diff_flags != diff_flags_new)
1736 	for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
1737 	    tp->tp_diff_invalid = TRUE;
1738 
1739     diff_flags = diff_flags_new;
1740     diff_context = diff_context_new;
1741 
1742     diff_redraw(TRUE);
1743 
1744     /* recompute the scroll binding with the new option value, may
1745      * remove or add filler lines */
1746     check_scrollbind((linenr_T)0, 0L);
1747 
1748     return OK;
1749 }
1750 
1751 /*
1752  * Find the difference within a changed line.
1753  * Returns TRUE if the line was added, no other buffer has it.
1754  */
1755     int
1756 diff_find_change(wp, lnum, startp, endp)
1757     win_T	*wp;
1758     linenr_T	lnum;
1759     int		*startp;	/* first char of the change */
1760     int		*endp;		/* last char of the change */
1761 {
1762     char_u	*line_org;
1763     char_u	*line_new;
1764     int		i;
1765     int		si, ei_org, ei_new;
1766     diff_T	*dp;
1767     int		idx;
1768     int		off;
1769     int		added = TRUE;
1770 
1771     /* Make a copy of the line, the next ml_get() will invalidate it. */
1772     line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, FALSE));
1773     if (line_org == NULL)
1774 	return FALSE;
1775 
1776     idx = diff_buf_idx(wp->w_buffer);
1777     if (idx == DB_COUNT)	/* cannot happen */
1778 	return FALSE;
1779 
1780     /* search for a change that includes "lnum" in the list of diffblocks. */
1781     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1782 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1783 	    break;
1784     if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL)
1785 	return FALSE;
1786 
1787     off = lnum - dp->df_lnum[idx];
1788 
1789     for (i = 0; i < DB_COUNT; ++i)
1790 	if (curtab->tp_diffbuf[i] != NULL && i != idx)
1791 	{
1792 	    /* Skip lines that are not in the other change (filler lines). */
1793 	    if (off >= dp->df_count[i])
1794 		continue;
1795 	    added = FALSE;
1796 	    line_new = ml_get_buf(curtab->tp_diffbuf[i], dp->df_lnum[i] + off, FALSE);
1797 
1798 	    /* Search for start of difference */
1799 	    for (si = 0; line_org[si] != NUL && line_org[si] == line_new[si]; )
1800 		++si;
1801 #ifdef FEAT_MBYTE
1802 	    if (has_mbyte)
1803 	    {
1804 		/* Move back to first byte of character in both lines (may
1805 		 * have "nn^" in line_org and "n^ in line_new). */
1806 		si -= (*mb_head_off)(line_org, line_org + si);
1807 		si -= (*mb_head_off)(line_new, line_new + si);
1808 	    }
1809 #endif
1810 	    if (*startp > si)
1811 		*startp = si;
1812 
1813 	    /* Search for end of difference, if any. */
1814 	    if (line_org[si] != NUL || line_new[si] != NUL)
1815 	    {
1816 		ei_org = (int)STRLEN(line_org);
1817 		ei_new = (int)STRLEN(line_new);
1818 		while (ei_org >= *startp && ei_new >= *startp
1819 			&& ei_org >= 0 && ei_new >= 0
1820 			&& line_org[ei_org] == line_new[ei_new])
1821 		{
1822 		    --ei_org;
1823 		    --ei_new;
1824 		}
1825 		if (*endp < ei_org)
1826 		    *endp = ei_org;
1827 	    }
1828 	}
1829 
1830     vim_free(line_org);
1831     return added;
1832 }
1833 
1834 #if defined(FEAT_FOLDING) || defined(PROTO)
1835 /*
1836  * Return TRUE if line "lnum" is not close to a diff block, this line should
1837  * be in a fold.
1838  * Return FALSE if there are no diff blocks at all in this window.
1839  */
1840     int
1841 diff_infold(wp, lnum)
1842     win_T	*wp;
1843     linenr_T	lnum;
1844 {
1845     int		i;
1846     int		idx = -1;
1847     int		other = FALSE;
1848     diff_T	*dp;
1849 
1850     /* Return if 'diff' isn't set. */
1851     if (!wp->w_p_diff)
1852 	return FALSE;
1853 
1854     for (i = 0; i < DB_COUNT; ++i)
1855     {
1856 	if (curtab->tp_diffbuf[i] == wp->w_buffer)
1857 	    idx = i;
1858 	else if (curtab->tp_diffbuf[i] != NULL)
1859 	    other = TRUE;
1860     }
1861 
1862     /* return here if there are no diffs in the window */
1863     if (idx == -1 || !other)
1864 	return FALSE;
1865 
1866     if (curtab->tp_diff_invalid)
1867 	ex_diffupdate(NULL);		/* update after a big change */
1868 
1869     /* Return if there are no diff blocks.  All lines will be folded. */
1870     if (curtab->tp_first_diff == NULL)
1871 	return TRUE;
1872 
1873     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
1874     {
1875 	/* If this change is below the line there can't be any further match. */
1876 	if (dp->df_lnum[idx] - diff_context > lnum)
1877 	    break;
1878 	/* If this change ends before the line we have a match. */
1879 	if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum)
1880 	    return FALSE;
1881     }
1882     return TRUE;
1883 }
1884 #endif
1885 
1886 /*
1887  * "dp" and "do" commands.
1888  */
1889     void
1890 nv_diffgetput(put)
1891     int		put;
1892 {
1893     exarg_T	ea;
1894 
1895     ea.arg = (char_u *)"";
1896     if (put)
1897 	ea.cmdidx = CMD_diffput;
1898     else
1899 	ea.cmdidx = CMD_diffget;
1900     ea.addr_count = 0;
1901     ea.line1 = curwin->w_cursor.lnum;
1902     ea.line2 = curwin->w_cursor.lnum;
1903     ex_diffgetput(&ea);
1904 }
1905 
1906 /*
1907  * ":diffget"
1908  * ":diffput"
1909  */
1910     void
1911 ex_diffgetput(eap)
1912     exarg_T	*eap;
1913 {
1914     linenr_T	lnum;
1915     int		count;
1916     linenr_T	off = 0;
1917     diff_T	*dp;
1918     diff_T	*dprev;
1919     diff_T	*dfree;
1920     int		idx_cur;
1921     int		idx_other;
1922     int		idx_from;
1923     int		idx_to;
1924     int		i;
1925     int		added;
1926     char_u	*p;
1927     aco_save_T	aco;
1928     buf_T	*buf;
1929     int		start_skip, end_skip;
1930     int		new_count;
1931     int		buf_empty;
1932 
1933     /* Find the current buffer in the list of diff buffers. */
1934     idx_cur = diff_buf_idx(curbuf);
1935     if (idx_cur == DB_COUNT)
1936     {
1937 	EMSG(_("E99: Current buffer is not in diff mode"));
1938 	return;
1939     }
1940 
1941     if (*eap->arg == NUL)
1942     {
1943 	/* No argument: Find the other buffer in the list of diff buffers. */
1944 	for (idx_other = 0; idx_other < DB_COUNT; ++idx_other)
1945 	    if (curtab->tp_diffbuf[idx_other] != curbuf
1946 		    && curtab->tp_diffbuf[idx_other] != NULL
1947 		    && (eap->cmdidx != CMD_diffput
1948 					       || curtab->tp_diffbuf[idx_other]->b_p_ma))
1949 		break;
1950 	if (idx_other == DB_COUNT)
1951 	{
1952 	    EMSG(_("E100: No other buffer in diff mode"));
1953 	    return;
1954 	}
1955 
1956 	/* Check that there isn't a third buffer in the list */
1957 	for (i = idx_other + 1; i < DB_COUNT; ++i)
1958 	    if (curtab->tp_diffbuf[i] != curbuf
1959 		    && curtab->tp_diffbuf[i] != NULL
1960 		    && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma))
1961 	    {
1962 		EMSG(_("E101: More than two buffers in diff mode, don't know which one to use"));
1963 		return;
1964 	    }
1965     }
1966     else
1967     {
1968 	/* Buffer number or pattern given.  Ignore trailing white space. */
1969 	p = eap->arg + STRLEN(eap->arg);
1970 	while (p > eap->arg && vim_iswhite(p[-1]))
1971 	    --p;
1972 	for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i)
1973 	    ;
1974 	if (eap->arg + i == p)	    /* digits only */
1975 	    i = atol((char *)eap->arg);
1976 	else
1977 	{
1978 	    i = buflist_findpat(eap->arg, p, FALSE, TRUE);
1979 	    if (i < 0)
1980 		return;		/* error message already given */
1981 	}
1982 	buf = buflist_findnr(i);
1983 	if (buf == NULL)
1984 	{
1985 	    EMSG2(_("E102: Can't find buffer \"%s\""), eap->arg);
1986 	    return;
1987 	}
1988 	idx_other = diff_buf_idx(buf);
1989 	if (idx_other == DB_COUNT)
1990 	{
1991 	    EMSG2(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg);
1992 	    return;
1993 	}
1994     }
1995 
1996     diff_busy = TRUE;
1997 
1998     /* When no range given include the line above or below the cursor. */
1999     if (eap->addr_count == 0)
2000     {
2001 	/* Make it possible that ":diffget" on the last line gets line below
2002 	 * the cursor line when there is no difference above the cursor. */
2003 	if (eap->cmdidx == CMD_diffget
2004 		&& eap->line1 == curbuf->b_ml.ml_line_count
2005 		&& diff_check(curwin, eap->line1) == 0
2006 		&& (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0))
2007 	    ++eap->line2;
2008 	else if (eap->line1 > 0)
2009 	    --eap->line1;
2010     }
2011 
2012     if (eap->cmdidx == CMD_diffget)
2013     {
2014 	idx_from = idx_other;
2015 	idx_to = idx_cur;
2016     }
2017     else
2018     {
2019 	idx_from = idx_cur;
2020 	idx_to = idx_other;
2021 	/* Need to make the other buffer the current buffer to be able to make
2022 	 * changes in it. */
2023 	/* set curwin/curbuf to buf and save a few things */
2024 	aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]);
2025     }
2026 
2027     dprev = NULL;
2028     for (dp = curtab->tp_first_diff; dp != NULL; )
2029     {
2030 	if (dp->df_lnum[idx_cur] > eap->line2 + off)
2031 	    break;	/* past the range that was specified */
2032 
2033 	dfree = NULL;
2034 	lnum = dp->df_lnum[idx_to];
2035 	count = dp->df_count[idx_to];
2036 	if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off
2037 		&& u_save(lnum - 1, lnum + count) != FAIL)
2038 	{
2039 	    /* Inside the specified range and saving for undo worked. */
2040 	    start_skip = 0;
2041 	    end_skip = 0;
2042 	    if (eap->addr_count > 0)
2043 	    {
2044 		/* A range was specified: check if lines need to be skipped. */
2045 		start_skip = eap->line1 + off - dp->df_lnum[idx_cur];
2046 		if (start_skip > 0)
2047 		{
2048 		    /* range starts below start of current diff block */
2049 		    if (start_skip > count)
2050 		    {
2051 			lnum += count;
2052 			count = 0;
2053 		    }
2054 		    else
2055 		    {
2056 			count -= start_skip;
2057 			lnum += start_skip;
2058 		    }
2059 		}
2060 		else
2061 		    start_skip = 0;
2062 
2063 		end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1
2064 							 - (eap->line2 + off);
2065 		if (end_skip > 0)
2066 		{
2067 		    /* range ends above end of current/from diff block */
2068 		    if (idx_cur == idx_from)	/* :diffput */
2069 		    {
2070 			i = dp->df_count[idx_cur] - start_skip - end_skip;
2071 			if (count > i)
2072 			    count = i;
2073 		    }
2074 		    else			/* :diffget */
2075 		    {
2076 			count -= end_skip;
2077 			end_skip = dp->df_count[idx_from] - start_skip - count;
2078 			if (end_skip < 0)
2079 			    end_skip = 0;
2080 		    }
2081 		}
2082 		else
2083 		    end_skip = 0;
2084 	    }
2085 
2086 	    buf_empty = FALSE;
2087 	    added = 0;
2088 	    for (i = 0; i < count; ++i)
2089 	    {
2090 		/* remember deleting the last line of the buffer */
2091 		buf_empty = curbuf->b_ml.ml_line_count == 1;
2092 		ml_delete(lnum, FALSE);
2093 		--added;
2094 	    }
2095 	    for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i)
2096 	    {
2097 		linenr_T nr;
2098 
2099 		nr = dp->df_lnum[idx_from] + start_skip + i;
2100 		if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count)
2101 		    break;
2102 		p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from], nr, FALSE));
2103 		if (p != NULL)
2104 		{
2105 		    ml_append(lnum + i - 1, p, 0, FALSE);
2106 		    vim_free(p);
2107 		    ++added;
2108 		    if (buf_empty && curbuf->b_ml.ml_line_count == 2)
2109 		    {
2110 			/* Added the first line into an empty buffer, need to
2111 			 * delete the dummy empty line. */
2112 			buf_empty = FALSE;
2113 			ml_delete((linenr_T)2, FALSE);
2114 		    }
2115 		}
2116 	    }
2117 	    new_count = dp->df_count[idx_to] + added;
2118 	    dp->df_count[idx_to] = new_count;
2119 
2120 	    if (start_skip == 0 && end_skip == 0)
2121 	    {
2122 		/* Check if there are any other buffers and if the diff is
2123 		 * equal in them. */
2124 		for (i = 0; i < DB_COUNT; ++i)
2125 		    if (curtab->tp_diffbuf[i] != NULL && i != idx_from && i != idx_to
2126 			    && !diff_equal_entry(dp, idx_from, i))
2127 			break;
2128 		if (i == DB_COUNT)
2129 		{
2130 		    /* delete the diff entry, the buffers are now equal here */
2131 		    dfree = dp;
2132 		    dp = dp->df_next;
2133 		    if (dprev == NULL)
2134 			curtab->tp_first_diff = dp;
2135 		    else
2136 			dprev->df_next = dp;
2137 		}
2138 	    }
2139 
2140 	    /* Adjust marks.  This will change the following entries! */
2141 	    if (added != 0)
2142 	    {
2143 		mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added);
2144 		if (curwin->w_cursor.lnum >= lnum)
2145 		{
2146 		    /* Adjust the cursor position if it's in/after the changed
2147 		     * lines. */
2148 		    if (curwin->w_cursor.lnum >= lnum + count)
2149 			curwin->w_cursor.lnum += added;
2150 		    else if (added < 0)
2151 			curwin->w_cursor.lnum = lnum;
2152 		}
2153 	    }
2154 	    changed_lines(lnum, 0, lnum + count, (long)added);
2155 
2156 	    if (dfree != NULL)
2157 	    {
2158 		/* Diff is deleted, update folds in other windows. */
2159 #ifdef FEAT_FOLDING
2160 		diff_fold_update(dfree, idx_to);
2161 #endif
2162 		vim_free(dfree);
2163 	    }
2164 	    else
2165 		/* mark_adjust() may have changed the count in a wrong way */
2166 		dp->df_count[idx_to] = new_count;
2167 
2168 	    /* When changing the current buffer, keep track of line numbers */
2169 	    if (idx_cur == idx_to)
2170 		off += added;
2171 	}
2172 
2173 	/* If before the range or not deleted, go to next diff. */
2174 	if (dfree == NULL)
2175 	{
2176 	    dprev = dp;
2177 	    dp = dp->df_next;
2178 	}
2179     }
2180 
2181     /* restore curwin/curbuf and a few other things */
2182     if (idx_other == idx_to)
2183     {
2184 	/* Syncing undo only works for the current buffer, but we change
2185 	 * another buffer.  Sync undo if the command was typed.  This isn't
2186 	 * 100% right when ":diffput" is used in a function or mapping. */
2187 	if (KeyTyped)
2188 	    u_sync();
2189 	aucmd_restbuf(&aco);
2190     }
2191 
2192     diff_busy = FALSE;
2193 
2194     /* Check that the cursor is on a valid character and update it's position.
2195      * When there were filler lines the topline has become invalid. */
2196     check_cursor();
2197     changed_line_abv_curs();
2198 
2199     /* Also need to redraw the other buffers. */
2200     diff_redraw(FALSE);
2201 }
2202 
2203 #ifdef FEAT_FOLDING
2204 /*
2205  * Update folds for all diff buffers for entry "dp".
2206  * Skip buffer with index "skip_idx".
2207  * When there are no diffs, all folds are removed.
2208  */
2209     static void
2210 diff_fold_update(dp, skip_idx)
2211     diff_T	*dp;
2212     int		skip_idx;
2213 {
2214     int		i;
2215     win_T	*wp;
2216 
2217     for (wp = firstwin; wp != NULL; wp = wp->w_next)
2218 	for (i = 0; i < DB_COUNT; ++i)
2219 	    if (curtab->tp_diffbuf[i] == wp->w_buffer && i != skip_idx)
2220 		foldUpdate(wp, dp->df_lnum[i],
2221 					    dp->df_lnum[i] + dp->df_count[i]);
2222 }
2223 #endif
2224 
2225 /*
2226  * Return TRUE if buffer "buf" is in diff-mode.
2227  */
2228     int
2229 diff_mode_buf(buf)
2230     buf_T	*buf;
2231 {
2232     tabpage_T	*tp;
2233 
2234     for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
2235 	if (diff_buf_idx_tp(buf, tp) != DB_COUNT)
2236 	    return TRUE;
2237     return FALSE;
2238 }
2239 
2240 /*
2241  * Move "count" times in direction "dir" to the next diff block.
2242  * Return FAIL if there isn't such a diff block.
2243  */
2244     int
2245 diff_move_to(dir, count)
2246     int		dir;
2247     long	count;
2248 {
2249     int		idx;
2250     linenr_T	lnum = curwin->w_cursor.lnum;
2251     diff_T	*dp;
2252 
2253     idx = diff_buf_idx(curbuf);
2254     if (idx == DB_COUNT || curtab->tp_first_diff == NULL)
2255 	return FAIL;
2256 
2257     if (curtab->tp_diff_invalid)
2258 	ex_diffupdate(NULL);		/* update after a big change */
2259 
2260     if (curtab->tp_first_diff == NULL)		/* no diffs today */
2261 	return FAIL;
2262 
2263     while (--count >= 0)
2264     {
2265 	/* Check if already before first diff. */
2266 	if (dir == BACKWARD && lnum <= curtab->tp_first_diff->df_lnum[idx])
2267 	    break;
2268 
2269 	for (dp = curtab->tp_first_diff; ; dp = dp->df_next)
2270 	{
2271 	    if (dp == NULL)
2272 		break;
2273 	    if ((dir == FORWARD && lnum < dp->df_lnum[idx])
2274 		    || (dir == BACKWARD
2275 			&& (dp->df_next == NULL
2276 			    || lnum <= dp->df_next->df_lnum[idx])))
2277 	    {
2278 		lnum = dp->df_lnum[idx];
2279 		break;
2280 	    }
2281 	}
2282     }
2283 
2284     /* don't end up past the end of the file */
2285     if (lnum > curbuf->b_ml.ml_line_count)
2286 	lnum = curbuf->b_ml.ml_line_count;
2287 
2288     /* When the cursor didn't move at all we fail. */
2289     if (lnum == curwin->w_cursor.lnum)
2290 	return FAIL;
2291 
2292     setpcmark();
2293     curwin->w_cursor.lnum = lnum;
2294     curwin->w_cursor.col = 0;
2295 
2296     return OK;
2297 }
2298 
2299 #if defined(FEAT_FOLDING) || defined(PROTO)
2300 /*
2301  * For line "lnum" in the current window find the equivalent lnum in window
2302  * "wp", compensating for inserted/deleted lines.
2303  */
2304     linenr_T
2305 diff_lnum_win(lnum, wp)
2306     linenr_T	lnum;
2307     win_T	*wp;
2308 {
2309     diff_T	*dp;
2310     int		idx;
2311     int		i;
2312     linenr_T	n;
2313 
2314     idx = diff_buf_idx(curbuf);
2315     if (idx == DB_COUNT)		/* safety check */
2316 	return (linenr_T)0;
2317 
2318     if (curtab->tp_diff_invalid)
2319 	ex_diffupdate(NULL);		/* update after a big change */
2320 
2321     /* search for a change that includes "lnum" in the list of diffblocks. */
2322     for (dp = curtab->tp_first_diff; dp != NULL; dp = dp->df_next)
2323 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
2324 	    break;
2325 
2326     /* When after the last change, compute relative to the last line number. */
2327     if (dp == NULL)
2328 	return wp->w_buffer->b_ml.ml_line_count
2329 					- (curbuf->b_ml.ml_line_count - lnum);
2330 
2331     /* Find index for "wp". */
2332     i = diff_buf_idx(wp->w_buffer);
2333     if (i == DB_COUNT)			/* safety check */
2334 	return (linenr_T)0;
2335 
2336     n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
2337     if (n > dp->df_lnum[i] + dp->df_count[i])
2338 	n = dp->df_lnum[i] + dp->df_count[i];
2339     return n;
2340 }
2341 #endif
2342 
2343 #endif	/* FEAT_DIFF */
2344