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