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