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