xref: /vim-8.2.3635/src/diff.c (revision f573c6e1)
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  * There are three ways to diff:
14  * - Shell out to an external diff program, using files.
15  * - Use the compiled-in xdiff library.
16  * - Let 'diffexpr' do the work, using files.
17  */
18 
19 #include "vim.h"
20 #include "xdiff/xdiff.h"
21 
22 #if defined(FEAT_DIFF) || defined(PROTO)
23 
24 static int diff_busy = FALSE;	    // using diff structs, don't change them
25 static int diff_need_update = FALSE; // ex_diffupdate needs to be called
26 
27 // flags obtained from the 'diffopt' option
28 #define DIFF_FILLER	0x001	// display filler lines
29 #define DIFF_IBLANK	0x002	// ignore empty lines
30 #define DIFF_ICASE	0x004	// ignore case
31 #define DIFF_IWHITE	0x008	// ignore change in white space
32 #define DIFF_IWHITEALL	0x010	// ignore all white space changes
33 #define DIFF_IWHITEEOL	0x020	// ignore change in white space at EOL
34 #define DIFF_HORIZONTAL	0x040	// horizontal splits
35 #define DIFF_VERTICAL	0x080	// vertical splits
36 #define DIFF_HIDDEN_OFF	0x100	// diffoff when hidden
37 #define DIFF_INTERNAL	0x200	// use internal xdiff algorithm
38 #define DIFF_CLOSE_OFF	0x400	// diffoff when closing window
39 #define DIFF_FOLLOWWRAP	0x800	// follow the wrap option
40 #define ALL_WHITE_DIFF (DIFF_IWHITE | DIFF_IWHITEALL | DIFF_IWHITEEOL)
41 static int	diff_flags = DIFF_INTERNAL | DIFF_FILLER | DIFF_CLOSE_OFF;
42 
43 static long diff_algorithm = 0;
44 
45 #define LBUFLEN 50		// length of line in diff file
46 
47 static int diff_a_works = MAYBE; // TRUE when "diff -a" works, FALSE when it
48 				 // doesn't work, MAYBE when not checked yet
49 #if defined(MSWIN)
50 static int diff_bin_works = MAYBE; // TRUE when "diff --binary" works, FALSE
51 				   // when it doesn't work, MAYBE when not
52 				   // checked yet
53 #endif
54 
55 // used for diff input
56 typedef struct {
57     char_u	*din_fname;  // used for external diff
58     mmfile_t	din_mmfile;  // used for internal diff
59 } diffin_T;
60 
61 // used for diff result
62 typedef struct {
63     char_u	*dout_fname;  // used for external diff
64     garray_T	dout_ga;      // used for internal diff
65 } diffout_T;
66 
67 // two diff inputs and one result
68 typedef struct {
69     diffin_T	dio_orig;     // original file input
70     diffin_T	dio_new;      // new file input
71     diffout_T	dio_diff;     // diff result
72     int		dio_internal; // using internal diff
73 } diffio_T;
74 
75 static int diff_buf_idx(buf_T *buf);
76 static int diff_buf_idx_tp(buf_T *buf, tabpage_T *tp);
77 static void diff_mark_adjust_tp(tabpage_T *tp, int idx, linenr_T line1, linenr_T line2, long amount, long amount_after);
78 static void diff_check_unchanged(tabpage_T *tp, diff_T *dp);
79 static int diff_check_sanity(tabpage_T *tp, diff_T *dp);
80 static int check_external_diff(diffio_T *diffio);
81 static int diff_file(diffio_T *diffio);
82 static int diff_equal_entry(diff_T *dp, int idx1, int idx2);
83 static int diff_cmp(char_u *s1, char_u *s2);
84 #ifdef FEAT_FOLDING
85 static void diff_fold_update(diff_T *dp, int skip_idx);
86 #endif
87 static void diff_read(int idx_orig, int idx_new, diffout_T *fname);
88 static void diff_copy_entry(diff_T *dprev, diff_T *dp, int idx_orig, int idx_new);
89 static diff_T *diff_alloc_new(tabpage_T *tp, diff_T *dprev, diff_T *dp);
90 static int parse_diff_ed(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new);
91 static int parse_diff_unified(char_u *line, linenr_T *lnum_orig, long *count_orig, linenr_T *lnum_new, long *count_new);
92 static int xdiff_out(void *priv, mmbuffer_t *mb, int nbuf);
93 
94 #define FOR_ALL_DIFFBLOCKS_IN_TAB(tp, dp) \
95     for ((dp) = (tp)->tp_first_diff; (dp) != NULL; (dp) = (dp)->df_next)
96 
97 /*
98  * Called when deleting or unloading a buffer: No longer make a diff with it.
99  */
100     void
101 diff_buf_delete(buf_T *buf)
102 {
103     int		i;
104     tabpage_T	*tp;
105 
106     FOR_ALL_TABPAGES(tp)
107     {
108 	i = diff_buf_idx_tp(buf, tp);
109 	if (i != DB_COUNT)
110 	{
111 	    tp->tp_diffbuf[i] = NULL;
112 	    tp->tp_diff_invalid = TRUE;
113 	    if (tp == curtab)
114 		diff_redraw(TRUE);
115 	}
116     }
117 }
118 
119 /*
120  * Check if the current buffer should be added to or removed from the list of
121  * diff buffers.
122  */
123     void
124 diff_buf_adjust(win_T *win)
125 {
126     win_T	*wp;
127     int		i;
128 
129     if (!win->w_p_diff)
130     {
131 	// When there is no window showing a diff for this buffer, remove
132 	// it from the diffs.
133 	FOR_ALL_WINDOWS(wp)
134 	    if (wp->w_buffer == win->w_buffer && wp->w_p_diff)
135 		break;
136 	if (wp == NULL)
137 	{
138 	    i = diff_buf_idx(win->w_buffer);
139 	    if (i != DB_COUNT)
140 	    {
141 		curtab->tp_diffbuf[i] = NULL;
142 		curtab->tp_diff_invalid = TRUE;
143 		diff_redraw(TRUE);
144 	    }
145 	}
146     }
147     else
148 	diff_buf_add(win->w_buffer);
149 }
150 
151 /*
152  * Add a buffer to make diffs for.
153  * Call this when a new buffer is being edited in the current window where
154  * 'diff' is set.
155  * Marks the current buffer as being part of the diff and requiring updating.
156  * This must be done before any autocmd, because a command may use info
157  * about the screen contents.
158  */
159     void
160 diff_buf_add(buf_T *buf)
161 {
162     int		i;
163 
164     if (diff_buf_idx(buf) != DB_COUNT)
165 	return;		// It's already there.
166 
167     for (i = 0; i < DB_COUNT; ++i)
168 	if (curtab->tp_diffbuf[i] == NULL)
169 	{
170 	    curtab->tp_diffbuf[i] = buf;
171 	    curtab->tp_diff_invalid = TRUE;
172 	    diff_redraw(TRUE);
173 	    return;
174 	}
175 
176     semsg(_("E96: Cannot diff more than %d buffers"), DB_COUNT);
177 }
178 
179 /*
180  * Remove all buffers to make diffs for.
181  */
182     static void
183 diff_buf_clear(void)
184 {
185     int		i;
186 
187     for (i = 0; i < DB_COUNT; ++i)
188 	if (curtab->tp_diffbuf[i] != NULL)
189 	{
190 	    curtab->tp_diffbuf[i] = NULL;
191 	    curtab->tp_diff_invalid = TRUE;
192 	    diff_redraw(TRUE);
193 	}
194 }
195 
196 /*
197  * Find buffer "buf" in the list of diff buffers for the current tab page.
198  * Return its index or DB_COUNT if not found.
199  */
200     static int
201 diff_buf_idx(buf_T *buf)
202 {
203     int		idx;
204 
205     for (idx = 0; idx < DB_COUNT; ++idx)
206 	if (curtab->tp_diffbuf[idx] == buf)
207 	    break;
208     return idx;
209 }
210 
211 /*
212  * Find buffer "buf" in the list of diff buffers for tab page "tp".
213  * Return its index or DB_COUNT if not found.
214  */
215     static int
216 diff_buf_idx_tp(buf_T *buf, tabpage_T *tp)
217 {
218     int		idx;
219 
220     for (idx = 0; idx < DB_COUNT; ++idx)
221 	if (tp->tp_diffbuf[idx] == buf)
222 	    break;
223     return idx;
224 }
225 
226 /*
227  * Mark the diff info involving buffer "buf" as invalid, it will be updated
228  * when info is requested.
229  */
230     void
231 diff_invalidate(buf_T *buf)
232 {
233     tabpage_T	*tp;
234     int		i;
235 
236     FOR_ALL_TABPAGES(tp)
237     {
238 	i = diff_buf_idx_tp(buf, tp);
239 	if (i != DB_COUNT)
240 	{
241 	    tp->tp_diff_invalid = TRUE;
242 	    if (tp == curtab)
243 		diff_redraw(TRUE);
244 	}
245     }
246 }
247 
248 /*
249  * Called by mark_adjust(): update line numbers in "curbuf".
250  */
251     void
252 diff_mark_adjust(
253     linenr_T	line1,
254     linenr_T	line2,
255     long	amount,
256     long	amount_after)
257 {
258     int		idx;
259     tabpage_T	*tp;
260 
261     // Handle all tab pages that use the current buffer in a diff.
262     FOR_ALL_TABPAGES(tp)
263     {
264 	idx = diff_buf_idx_tp(curbuf, tp);
265 	if (idx != DB_COUNT)
266 	    diff_mark_adjust_tp(tp, idx, line1, line2, amount, amount_after);
267     }
268 }
269 
270 /*
271  * Update line numbers in tab page "tp" for "curbuf" with index "idx".
272  * This attempts to update the changes as much as possible:
273  * When inserting/deleting lines outside of existing change blocks, create a
274  * new change block and update the line numbers in following blocks.
275  * When inserting/deleting lines in existing change blocks, update them.
276  */
277     static void
278 diff_mark_adjust_tp(
279     tabpage_T	*tp,
280     int		idx,
281     linenr_T	line1,
282     linenr_T	line2,
283     long	amount,
284     long	amount_after)
285 {
286     diff_T	*dp;
287     diff_T	*dprev;
288     diff_T	*dnext;
289     int		i;
290     int		inserted, deleted;
291     int		n, off;
292     linenr_T	last;
293     linenr_T	lnum_deleted = line1;	// lnum of remaining deletion
294     int		check_unchanged;
295 
296     if (diff_internal())
297     {
298 	// Will update diffs before redrawing.  Set _invalid to update the
299 	// diffs themselves, set _update to also update folds properly just
300 	// before redrawing.
301 	// Do update marks here, it is needed for :%diffput.
302 	tp->tp_diff_invalid = TRUE;
303 	tp->tp_diff_update = TRUE;
304     }
305 
306     if (line2 == MAXLNUM)
307     {
308 	// mark_adjust(99, MAXLNUM, 9, 0): insert lines
309 	inserted = amount;
310 	deleted = 0;
311     }
312     else if (amount_after > 0)
313     {
314 	// mark_adjust(99, 98, MAXLNUM, 9): a change that inserts lines
315 	inserted = amount_after;
316 	deleted = 0;
317     }
318     else
319     {
320 	// mark_adjust(98, 99, MAXLNUM, -2): delete lines
321 	inserted = 0;
322 	deleted = -amount_after;
323     }
324 
325     dprev = NULL;
326     dp = tp->tp_first_diff;
327     for (;;)
328     {
329 	// If the change is after the previous diff block and before the next
330 	// diff block, thus not touching an existing change, create a new diff
331 	// block.  Don't do this when ex_diffgetput() is busy.
332 	if ((dp == NULL || dp->df_lnum[idx] - 1 > line2
333 		    || (line2 == MAXLNUM && dp->df_lnum[idx] > line1))
334 		&& (dprev == NULL
335 		    || dprev->df_lnum[idx] + dprev->df_count[idx] < line1)
336 		&& !diff_busy)
337 	{
338 	    dnext = diff_alloc_new(tp, dprev, dp);
339 	    if (dnext == NULL)
340 		return;
341 
342 	    dnext->df_lnum[idx] = line1;
343 	    dnext->df_count[idx] = inserted;
344 	    for (i = 0; i < DB_COUNT; ++i)
345 		if (tp->tp_diffbuf[i] != NULL && i != idx)
346 		{
347 		    if (dprev == NULL)
348 			dnext->df_lnum[i] = line1;
349 		    else
350 			dnext->df_lnum[i] = line1
351 			    + (dprev->df_lnum[i] + dprev->df_count[i])
352 			    - (dprev->df_lnum[idx] + dprev->df_count[idx]);
353 		    dnext->df_count[i] = deleted;
354 		}
355 	}
356 
357 	// if at end of the list, quit
358 	if (dp == NULL)
359 	    break;
360 
361 	/*
362 	 * Check for these situations:
363 	 *	  1  2	3
364 	 *	  1  2	3
365 	 * line1     2	3  4  5
366 	 *	     2	3  4  5
367 	 *	     2	3  4  5
368 	 * line2     2	3  4  5
369 	 *		3     5  6
370 	 *		3     5  6
371 	 */
372 	// compute last line of this change
373 	last = dp->df_lnum[idx] + dp->df_count[idx] - 1;
374 
375 	// 1. change completely above line1: nothing to do
376 	if (last >= line1 - 1)
377 	{
378 	    // 6. change below line2: only adjust for amount_after; also when
379 	    // "deleted" became zero when deleted all lines between two diffs
380 	    if (dp->df_lnum[idx] - (deleted + inserted != 0) > line2)
381 	    {
382 		if (amount_after == 0)
383 		    break;	// nothing left to change
384 		dp->df_lnum[idx] += amount_after;
385 	    }
386 	    else
387 	    {
388 		check_unchanged = FALSE;
389 
390 		// 2. 3. 4. 5.: inserted/deleted lines touching this diff.
391 		if (deleted > 0)
392 		{
393 		    if (dp->df_lnum[idx] >= line1)
394 		    {
395 			off = dp->df_lnum[idx] - lnum_deleted;
396 			if (last <= line2)
397 			{
398 			    // 4. delete all lines of diff
399 			    if (dp->df_next != NULL
400 				    && dp->df_next->df_lnum[idx] - 1 <= line2)
401 			    {
402 				// delete continues in next diff, only do
403 				// lines until that one
404 				n = dp->df_next->df_lnum[idx] - lnum_deleted;
405 				deleted -= n;
406 				n -= dp->df_count[idx];
407 				lnum_deleted = dp->df_next->df_lnum[idx];
408 			    }
409 			    else
410 				n = deleted - dp->df_count[idx];
411 			    dp->df_count[idx] = 0;
412 			}
413 			else
414 			{
415 			    // 5. delete lines at or just before top of diff
416 			    n = off;
417 			    dp->df_count[idx] -= line2 - dp->df_lnum[idx] + 1;
418 			    check_unchanged = TRUE;
419 			}
420 			dp->df_lnum[idx] = line1;
421 		    }
422 		    else
423 		    {
424 			off = 0;
425 			if (last < line2)
426 			{
427 			    // 2. delete at end of diff
428 			    dp->df_count[idx] -= last - lnum_deleted + 1;
429 			    if (dp->df_next != NULL
430 				    && dp->df_next->df_lnum[idx] - 1 <= line2)
431 			    {
432 				// delete continues in next diff, only do
433 				// lines until that one
434 				n = dp->df_next->df_lnum[idx] - 1 - last;
435 				deleted -= dp->df_next->df_lnum[idx]
436 							       - lnum_deleted;
437 				lnum_deleted = dp->df_next->df_lnum[idx];
438 			    }
439 			    else
440 				n = line2 - last;
441 			    check_unchanged = TRUE;
442 			}
443 			else
444 			{
445 			    // 3. delete lines inside the diff
446 			    n = 0;
447 			    dp->df_count[idx] -= deleted;
448 			}
449 		    }
450 
451 		    for (i = 0; i < DB_COUNT; ++i)
452 			if (tp->tp_diffbuf[i] != NULL && i != idx)
453 			{
454 			    dp->df_lnum[i] -= off;
455 			    dp->df_count[i] += n;
456 			}
457 		}
458 		else
459 		{
460 		    if (dp->df_lnum[idx] <= line1)
461 		    {
462 			// inserted lines somewhere in this diff
463 			dp->df_count[idx] += inserted;
464 			check_unchanged = TRUE;
465 		    }
466 		    else
467 			// inserted lines somewhere above this diff
468 			dp->df_lnum[idx] += inserted;
469 		}
470 
471 		if (check_unchanged)
472 		    // Check if inserted lines are equal, may reduce the
473 		    // size of the diff.  TODO: also check for equal lines
474 		    // in the middle and perhaps split the block.
475 		    diff_check_unchanged(tp, dp);
476 	    }
477 	}
478 
479 	// check if this block touches the previous one, may merge them.
480 	if (dprev != NULL && dprev->df_lnum[idx] + dprev->df_count[idx]
481 							  == dp->df_lnum[idx])
482 	{
483 	    for (i = 0; i < DB_COUNT; ++i)
484 		if (tp->tp_diffbuf[i] != NULL)
485 		    dprev->df_count[i] += dp->df_count[i];
486 	    dprev->df_next = dp->df_next;
487 	    vim_free(dp);
488 	    dp = dprev->df_next;
489 	}
490 	else
491 	{
492 	    // Advance to next entry.
493 	    dprev = dp;
494 	    dp = dp->df_next;
495 	}
496     }
497 
498     dprev = NULL;
499     dp = tp->tp_first_diff;
500     while (dp != NULL)
501     {
502 	// All counts are zero, remove this entry.
503 	for (i = 0; i < DB_COUNT; ++i)
504 	    if (tp->tp_diffbuf[i] != NULL && dp->df_count[i] != 0)
505 		break;
506 	if (i == DB_COUNT)
507 	{
508 	    dnext = dp->df_next;
509 	    vim_free(dp);
510 	    dp = dnext;
511 	    if (dprev == NULL)
512 		tp->tp_first_diff = dnext;
513 	    else
514 		dprev->df_next = dnext;
515 	}
516 	else
517 	{
518 	    // Advance to next entry.
519 	    dprev = dp;
520 	    dp = dp->df_next;
521 	}
522 
523     }
524 
525     if (tp == curtab)
526     {
527 	// Don't redraw right away, this updates the diffs, which can be slow.
528 	need_diff_redraw = TRUE;
529 
530 	// Need to recompute the scroll binding, may remove or add filler
531 	// lines (e.g., when adding lines above w_topline). But it's slow when
532 	// making many changes, postpone until redrawing.
533 	diff_need_scrollbind = TRUE;
534     }
535 }
536 
537 /*
538  * Allocate a new diff block and link it between "dprev" and "dp".
539  */
540     static diff_T *
541 diff_alloc_new(tabpage_T *tp, diff_T *dprev, diff_T *dp)
542 {
543     diff_T	*dnew;
544 
545     dnew = ALLOC_ONE(diff_T);
546     if (dnew != NULL)
547     {
548 	dnew->df_next = dp;
549 	if (dprev == NULL)
550 	    tp->tp_first_diff = dnew;
551 	else
552 	    dprev->df_next = dnew;
553     }
554     return dnew;
555 }
556 
557 /*
558  * Check if the diff block "dp" can be made smaller for lines at the start and
559  * end that are equal.  Called after inserting lines.
560  * This may result in a change where all buffers have zero lines, the caller
561  * must take care of removing it.
562  */
563     static void
564 diff_check_unchanged(tabpage_T *tp, diff_T *dp)
565 {
566     int		i_org;
567     int		i_new;
568     int		off_org, off_new;
569     char_u	*line_org;
570     int		dir = FORWARD;
571 
572     // Find the first buffers, use it as the original, compare the other
573     // buffer lines against this one.
574     for (i_org = 0; i_org < DB_COUNT; ++i_org)
575 	if (tp->tp_diffbuf[i_org] != NULL)
576 	    break;
577     if (i_org == DB_COUNT)	// safety check
578 	return;
579 
580     if (diff_check_sanity(tp, dp) == FAIL)
581 	return;
582 
583     // First check lines at the top, then at the bottom.
584     off_org = 0;
585     off_new = 0;
586     for (;;)
587     {
588 	// Repeat until a line is found which is different or the number of
589 	// lines has become zero.
590 	while (dp->df_count[i_org] > 0)
591 	{
592 	    // Copy the line, the next ml_get() will invalidate it.
593 	    if (dir == BACKWARD)
594 		off_org = dp->df_count[i_org] - 1;
595 	    line_org = vim_strsave(ml_get_buf(tp->tp_diffbuf[i_org],
596 					dp->df_lnum[i_org] + off_org, FALSE));
597 	    if (line_org == NULL)
598 		return;
599 	    for (i_new = i_org + 1; i_new < DB_COUNT; ++i_new)
600 	    {
601 		if (tp->tp_diffbuf[i_new] == NULL)
602 		    continue;
603 		if (dir == BACKWARD)
604 		    off_new = dp->df_count[i_new] - 1;
605 		// if other buffer doesn't have this line, it was inserted
606 		if (off_new < 0 || off_new >= dp->df_count[i_new])
607 		    break;
608 		if (diff_cmp(line_org, ml_get_buf(tp->tp_diffbuf[i_new],
609 				   dp->df_lnum[i_new] + off_new, FALSE)) != 0)
610 		    break;
611 	    }
612 	    vim_free(line_org);
613 
614 	    // Stop when a line isn't equal in all diff buffers.
615 	    if (i_new != DB_COUNT)
616 		break;
617 
618 	    // Line matched in all buffers, remove it from the diff.
619 	    for (i_new = i_org; i_new < DB_COUNT; ++i_new)
620 		if (tp->tp_diffbuf[i_new] != NULL)
621 		{
622 		    if (dir == FORWARD)
623 			++dp->df_lnum[i_new];
624 		    --dp->df_count[i_new];
625 		}
626 	}
627 	if (dir == BACKWARD)
628 	    break;
629 	dir = BACKWARD;
630     }
631 }
632 
633 /*
634  * Check if a diff block doesn't contain invalid line numbers.
635  * This can happen when the diff program returns invalid results.
636  */
637     static int
638 diff_check_sanity(tabpage_T *tp, diff_T *dp)
639 {
640     int		i;
641 
642     for (i = 0; i < DB_COUNT; ++i)
643 	if (tp->tp_diffbuf[i] != NULL)
644 	    if (dp->df_lnum[i] + dp->df_count[i] - 1
645 				      > tp->tp_diffbuf[i]->b_ml.ml_line_count)
646 		return FAIL;
647     return OK;
648 }
649 
650 /*
651  * Mark all diff buffers in the current tab page for redraw.
652  */
653     void
654 diff_redraw(
655     int		dofold)	    // also recompute the folds
656 {
657     win_T	*wp;
658     int		n;
659 
660     need_diff_redraw = FALSE;
661     FOR_ALL_WINDOWS(wp)
662 	if (wp->w_p_diff)
663 	{
664 	    redraw_win_later(wp, SOME_VALID);
665 #ifdef FEAT_FOLDING
666 	    if (dofold && foldmethodIsDiff(wp))
667 		foldUpdateAll(wp);
668 #endif
669 	    // A change may have made filler lines invalid, need to take care
670 	    // of that for other windows.
671 	    n = diff_check(wp, wp->w_topline);
672 	    if ((wp != curwin && wp->w_topfill > 0) || n > 0)
673 	    {
674 		if (wp->w_topfill > n)
675 		    wp->w_topfill = (n < 0 ? 0 : n);
676 		else if (n > 0 && n > wp->w_topfill)
677 		    wp->w_topfill = n;
678 		check_topfill(wp, FALSE);
679 	    }
680 	}
681 }
682 
683     static void
684 clear_diffin(diffin_T *din)
685 {
686     if (din->din_fname == NULL)
687     {
688 	vim_free(din->din_mmfile.ptr);
689 	din->din_mmfile.ptr = NULL;
690     }
691     else
692 	mch_remove(din->din_fname);
693 }
694 
695     static void
696 clear_diffout(diffout_T *dout)
697 {
698     if (dout->dout_fname == NULL)
699 	ga_clear_strings(&dout->dout_ga);
700     else
701 	mch_remove(dout->dout_fname);
702 }
703 
704 /*
705  * Write buffer "buf" to a memory buffer.
706  * Return FAIL for failure.
707  */
708     static int
709 diff_write_buffer(buf_T *buf, diffin_T *din)
710 {
711     linenr_T	lnum;
712     char_u	*s;
713     long	len = 0;
714     char_u	*ptr;
715 
716     // xdiff requires one big block of memory with all the text.
717     for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum)
718 	len += (long)STRLEN(ml_get_buf(buf, lnum, FALSE)) + 1;
719     ptr = alloc(len);
720     if (ptr == NULL)
721     {
722 	// Allocating memory failed.  This can happen, because we try to read
723 	// the whole buffer text into memory.  Set the failed flag, the diff
724 	// will be retried with external diff.  The flag is never reset.
725 	buf->b_diff_failed = TRUE;
726 	if (p_verbose > 0)
727 	{
728 	    verbose_enter();
729 	    smsg(_("Not enough memory to use internal diff for buffer \"%s\""),
730 								 buf->b_fname);
731 	    verbose_leave();
732 	}
733 	return FAIL;
734     }
735     din->din_mmfile.ptr = (char *)ptr;
736     din->din_mmfile.size = len;
737 
738     len = 0;
739     for (lnum = 1; lnum <= buf->b_ml.ml_line_count; ++lnum)
740     {
741 	for (s = ml_get_buf(buf, lnum, FALSE); *s != NUL; )
742 	{
743 	    if (diff_flags & DIFF_ICASE)
744 	    {
745 		int c;
746 		int	orig_len;
747 		char_u	cbuf[MB_MAXBYTES + 1];
748 
749 		// xdiff doesn't support ignoring case, fold-case the text.
750 		c = PTR2CHAR(s);
751 		c = MB_CASEFOLD(c);
752 		orig_len = mb_ptr2len(s);
753 		if (mb_char2bytes(c, cbuf) != orig_len)
754 		    // TODO: handle byte length difference
755 		    mch_memmove(ptr + len, s, orig_len);
756 		else
757 		    mch_memmove(ptr + len, cbuf, orig_len);
758 
759 		s += orig_len;
760 		len += orig_len;
761 	    }
762 	    else
763 		ptr[len++] = *s++;
764 	}
765 	ptr[len++] = NL;
766     }
767     return OK;
768 }
769 
770 /*
771  * Write buffer "buf" to file or memory buffer.
772  * Return FAIL for failure.
773  */
774     static int
775 diff_write(buf_T *buf, diffin_T *din)
776 {
777     int		r;
778     char_u	*save_ff;
779     int		save_cmod_flags;
780 
781     if (din->din_fname == NULL)
782 	return diff_write_buffer(buf, din);
783 
784     // Always use 'fileformat' set to "unix".
785     save_ff = buf->b_p_ff;
786     buf->b_p_ff = vim_strsave((char_u *)FF_UNIX);
787     save_cmod_flags = cmdmod.cmod_flags;
788     // Writing the buffer is an implementation detail of performing the diff,
789     // so it shouldn't update the '[ and '] marks.
790     cmdmod.cmod_flags |= CMOD_LOCKMARKS;
791     r = buf_write(buf, din->din_fname, NULL,
792 			(linenr_T)1, buf->b_ml.ml_line_count,
793 			NULL, FALSE, FALSE, FALSE, TRUE);
794     cmdmod.cmod_flags = save_cmod_flags;
795     free_string_option(buf->b_p_ff);
796     buf->b_p_ff = save_ff;
797     return r;
798 }
799 
800 /*
801  * Update the diffs for all buffers involved.
802  */
803     static void
804 diff_try_update(
805 	diffio_T    *dio,
806 	int	    idx_orig,
807 	exarg_T	    *eap)	// "eap" can be NULL
808 {
809     buf_T	*buf;
810     int		idx_new;
811 
812     if (dio->dio_internal)
813     {
814 	ga_init2(&dio->dio_diff.dout_ga, sizeof(char *), 1000);
815     }
816     else
817     {
818 	// We need three temp file names.
819 	dio->dio_orig.din_fname = vim_tempname('o', TRUE);
820 	dio->dio_new.din_fname = vim_tempname('n', TRUE);
821 	dio->dio_diff.dout_fname = vim_tempname('d', TRUE);
822 	if (dio->dio_orig.din_fname == NULL
823 		|| dio->dio_new.din_fname == NULL
824 		|| dio->dio_diff.dout_fname == NULL)
825 	    goto theend;
826     }
827 
828     // Check external diff is actually working.
829     if (!dio->dio_internal && check_external_diff(dio) == FAIL)
830 	goto theend;
831 
832     // :diffupdate!
833     if (eap != NULL && eap->forceit)
834 	for (idx_new = idx_orig; idx_new < DB_COUNT; ++idx_new)
835 	{
836 	    buf = curtab->tp_diffbuf[idx_new];
837 	    if (buf_valid(buf))
838 		buf_check_timestamp(buf, FALSE);
839 	}
840 
841     // Write the first buffer to a tempfile or mmfile_t.
842     buf = curtab->tp_diffbuf[idx_orig];
843     if (diff_write(buf, &dio->dio_orig) == FAIL)
844 	goto theend;
845 
846     // Make a difference between the first buffer and every other.
847     for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new)
848     {
849 	buf = curtab->tp_diffbuf[idx_new];
850 	if (buf == NULL || buf->b_ml.ml_mfp == NULL)
851 	    continue; // skip buffer that isn't loaded
852 
853 	// Write the other buffer and diff with the first one.
854 	if (diff_write(buf, &dio->dio_new) == FAIL)
855 	    continue;
856 	if (diff_file(dio) == FAIL)
857 	    continue;
858 
859 	// Read the diff output and add each entry to the diff list.
860 	diff_read(idx_orig, idx_new, &dio->dio_diff);
861 
862 	clear_diffin(&dio->dio_new);
863 	clear_diffout(&dio->dio_diff);
864     }
865     clear_diffin(&dio->dio_orig);
866 
867 theend:
868     vim_free(dio->dio_orig.din_fname);
869     vim_free(dio->dio_new.din_fname);
870     vim_free(dio->dio_diff.dout_fname);
871 }
872 
873 /*
874  * Return TRUE if the options are set to use the internal diff library.
875  * Note that if the internal diff failed for one of the buffers, the external
876  * diff will be used anyway.
877  */
878     int
879 diff_internal(void)
880 {
881     return (diff_flags & DIFF_INTERNAL) != 0
882 #ifdef FEAT_EVAL
883 	&& *p_dex == NUL
884 #endif
885 	;
886 }
887 
888 /*
889  * Return TRUE if the internal diff failed for one of the diff buffers.
890  */
891     static int
892 diff_internal_failed(void)
893 {
894     int idx;
895 
896     // Only need to do something when there is another buffer.
897     for (idx = 0; idx < DB_COUNT; ++idx)
898 	if (curtab->tp_diffbuf[idx] != NULL
899 		&& curtab->tp_diffbuf[idx]->b_diff_failed)
900 	    return TRUE;
901     return FALSE;
902 }
903 
904 /*
905  * Completely update the diffs for the buffers involved.
906  * When using the external "diff" command the buffers are written to a file,
907  * also for unmodified buffers (the file could have been produced by
908  * autocommands, e.g. the netrw plugin).
909  */
910     void
911 ex_diffupdate(exarg_T *eap)	// "eap" can be NULL
912 {
913     int		idx_orig;
914     int		idx_new;
915     diffio_T	diffio;
916     int		had_diffs = curtab->tp_first_diff != NULL;
917 
918     if (diff_busy)
919     {
920 	diff_need_update = TRUE;
921 	return;
922     }
923 
924     // Delete all diffblocks.
925     diff_clear(curtab);
926     curtab->tp_diff_invalid = FALSE;
927 
928     // Use the first buffer as the original text.
929     for (idx_orig = 0; idx_orig < DB_COUNT; ++idx_orig)
930 	if (curtab->tp_diffbuf[idx_orig] != NULL)
931 	    break;
932     if (idx_orig == DB_COUNT)
933 	goto theend;
934 
935     // Only need to do something when there is another buffer.
936     for (idx_new = idx_orig + 1; idx_new < DB_COUNT; ++idx_new)
937 	if (curtab->tp_diffbuf[idx_new] != NULL)
938 	    break;
939     if (idx_new == DB_COUNT)
940 	goto theend;
941 
942     // Only use the internal method if it did not fail for one of the buffers.
943     CLEAR_FIELD(diffio);
944     diffio.dio_internal = diff_internal() && !diff_internal_failed();
945 
946     diff_try_update(&diffio, idx_orig, eap);
947     if (diffio.dio_internal && diff_internal_failed())
948     {
949 	// Internal diff failed, use external diff instead.
950 	CLEAR_FIELD(diffio);
951 	diff_try_update(&diffio, idx_orig, eap);
952     }
953 
954     // force updating cursor position on screen
955     curwin->w_valid_cursor.lnum = 0;
956 
957 theend:
958     // A redraw is needed if there were diffs and they were cleared, or there
959     // are diffs now, which means they got updated.
960     if (had_diffs || curtab->tp_first_diff != NULL)
961     {
962 	diff_redraw(TRUE);
963 	apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf);
964     }
965 }
966 
967 /*
968  * Do a quick test if "diff" really works.  Otherwise it looks like there
969  * are no differences.  Can't use the return value, it's non-zero when
970  * there are differences.
971  */
972     static int
973 check_external_diff(diffio_T *diffio)
974 {
975     FILE	*fd;
976     int		ok;
977     int		io_error = FALSE;
978 
979     // May try twice, first with "-a" and then without.
980     for (;;)
981     {
982 	ok = FALSE;
983 	fd = mch_fopen((char *)diffio->dio_orig.din_fname, "w");
984 	if (fd == NULL)
985 	    io_error = TRUE;
986 	else
987 	{
988 	    if (fwrite("line1\n", (size_t)6, (size_t)1, fd) != 1)
989 		io_error = TRUE;
990 	    fclose(fd);
991 	    fd = mch_fopen((char *)diffio->dio_new.din_fname, "w");
992 	    if (fd == NULL)
993 		io_error = TRUE;
994 	    else
995 	    {
996 		if (fwrite("line2\n", (size_t)6, (size_t)1, fd) != 1)
997 		    io_error = TRUE;
998 		fclose(fd);
999 		fd = NULL;
1000 		if (diff_file(diffio) == OK)
1001 		    fd = mch_fopen((char *)diffio->dio_diff.dout_fname, "r");
1002 		if (fd == NULL)
1003 		    io_error = TRUE;
1004 		else
1005 		{
1006 		    char_u	linebuf[LBUFLEN];
1007 
1008 		    for (;;)
1009 		    {
1010 			// For normal diff there must be a line that contains
1011 			// "1c1".  For unified diff "@@ -1 +1 @@".
1012 			if (vim_fgets(linebuf, LBUFLEN, fd))
1013 			    break;
1014 			if (STRNCMP(linebuf, "1c1", 3) == 0
1015 				|| STRNCMP(linebuf, "@@ -1 +1 @@", 11) == 0)
1016 			    ok = TRUE;
1017 		    }
1018 		    fclose(fd);
1019 		}
1020 		mch_remove(diffio->dio_diff.dout_fname);
1021 		mch_remove(diffio->dio_new.din_fname);
1022 	    }
1023 	    mch_remove(diffio->dio_orig.din_fname);
1024 	}
1025 
1026 #ifdef FEAT_EVAL
1027 	// When using 'diffexpr' break here.
1028 	if (*p_dex != NUL)
1029 	    break;
1030 #endif
1031 
1032 #if defined(MSWIN)
1033 	// If the "-a" argument works, also check if "--binary" works.
1034 	if (ok && diff_a_works == MAYBE && diff_bin_works == MAYBE)
1035 	{
1036 	    diff_a_works = TRUE;
1037 	    diff_bin_works = TRUE;
1038 	    continue;
1039 	}
1040 	if (!ok && diff_a_works == TRUE && diff_bin_works == TRUE)
1041 	{
1042 	    // Tried --binary, but it failed. "-a" works though.
1043 	    diff_bin_works = FALSE;
1044 	    ok = TRUE;
1045 	}
1046 #endif
1047 
1048 	// If we checked if "-a" works already, break here.
1049 	if (diff_a_works != MAYBE)
1050 	    break;
1051 	diff_a_works = ok;
1052 
1053 	// If "-a" works break here, otherwise retry without "-a".
1054 	if (ok)
1055 	    break;
1056     }
1057     if (!ok)
1058     {
1059 	if (io_error)
1060 	    emsg(_("E810: Cannot read or write temp files"));
1061 	emsg(_("E97: Cannot create diffs"));
1062 	diff_a_works = MAYBE;
1063 #if defined(MSWIN)
1064 	diff_bin_works = MAYBE;
1065 #endif
1066 	return FAIL;
1067     }
1068     return OK;
1069 }
1070 
1071 /*
1072  * Invoke the xdiff function.
1073  */
1074     static int
1075 diff_file_internal(diffio_T *diffio)
1076 {
1077     xpparam_t	    param;
1078     xdemitconf_t    emit_cfg;
1079     xdemitcb_t	    emit_cb;
1080 
1081     CLEAR_FIELD(param);
1082     CLEAR_FIELD(emit_cfg);
1083     CLEAR_FIELD(emit_cb);
1084 
1085     param.flags = diff_algorithm;
1086 
1087     if (diff_flags & DIFF_IWHITE)
1088 	param.flags |= XDF_IGNORE_WHITESPACE_CHANGE;
1089     if (diff_flags & DIFF_IWHITEALL)
1090 	param.flags |= XDF_IGNORE_WHITESPACE;
1091     if (diff_flags & DIFF_IWHITEEOL)
1092 	param.flags |= XDF_IGNORE_WHITESPACE_AT_EOL;
1093     if (diff_flags & DIFF_IBLANK)
1094 	param.flags |= XDF_IGNORE_BLANK_LINES;
1095 
1096     emit_cfg.ctxlen = 0; // don't need any diff_context here
1097     emit_cb.priv = &diffio->dio_diff;
1098     emit_cb.outf = xdiff_out;
1099     if (xdl_diff(&diffio->dio_orig.din_mmfile,
1100 		&diffio->dio_new.din_mmfile,
1101 		&param, &emit_cfg, &emit_cb) < 0)
1102     {
1103 	emsg(_("E960: Problem creating the internal diff"));
1104 	return FAIL;
1105     }
1106     return OK;
1107 }
1108 
1109 /*
1110  * Make a diff between files "tmp_orig" and "tmp_new", results in "tmp_diff".
1111  * return OK or FAIL;
1112  */
1113     static int
1114 diff_file(diffio_T *dio)
1115 {
1116     char_u	*cmd;
1117     size_t	len;
1118     char_u	*tmp_orig = dio->dio_orig.din_fname;
1119     char_u	*tmp_new = dio->dio_new.din_fname;
1120     char_u	*tmp_diff = dio->dio_diff.dout_fname;
1121 
1122 #ifdef FEAT_EVAL
1123     if (*p_dex != NUL)
1124     {
1125 	// Use 'diffexpr' to generate the diff file.
1126 	eval_diff(tmp_orig, tmp_new, tmp_diff);
1127 	return OK;
1128     }
1129     else
1130 #endif
1131     // Use xdiff for generating the diff.
1132     if (dio->dio_internal)
1133     {
1134 	return diff_file_internal(dio);
1135     }
1136     else
1137     {
1138 	len = STRLEN(tmp_orig) + STRLEN(tmp_new)
1139 				      + STRLEN(tmp_diff) + STRLEN(p_srr) + 27;
1140 	cmd = alloc(len);
1141 	if (cmd == NULL)
1142 	    return FAIL;
1143 
1144 	// We don't want $DIFF_OPTIONS to get in the way.
1145 	if (getenv("DIFF_OPTIONS"))
1146 	    vim_setenv((char_u *)"DIFF_OPTIONS", (char_u *)"");
1147 
1148 	// Build the diff command and execute it.  Always use -a, binary
1149 	// differences are of no use.  Ignore errors, diff returns
1150 	// non-zero when differences have been found.
1151 	vim_snprintf((char *)cmd, len, "diff %s%s%s%s%s%s%s%s %s",
1152 		diff_a_works == FALSE ? "" : "-a ",
1153 #if defined(MSWIN)
1154 		diff_bin_works == TRUE ? "--binary " : "",
1155 #else
1156 		"",
1157 #endif
1158 		(diff_flags & DIFF_IWHITE) ? "-b " : "",
1159 		(diff_flags & DIFF_IWHITEALL) ? "-w " : "",
1160 		(diff_flags & DIFF_IWHITEEOL) ? "-Z " : "",
1161 		(diff_flags & DIFF_IBLANK) ? "-B " : "",
1162 		(diff_flags & DIFF_ICASE) ? "-i " : "",
1163 		tmp_orig, tmp_new);
1164 	append_redir(cmd, (int)len, p_srr, tmp_diff);
1165 	block_autocmds();	// avoid ShellCmdPost stuff
1166 	(void)call_shell(cmd, SHELL_FILTER|SHELL_SILENT|SHELL_DOOUT);
1167 	unblock_autocmds();
1168 	vim_free(cmd);
1169 	return OK;
1170     }
1171 }
1172 
1173 /*
1174  * Create a new version of a file from the current buffer and a diff file.
1175  * The buffer is written to a file, also for unmodified buffers (the file
1176  * could have been produced by autocommands, e.g. the netrw plugin).
1177  */
1178     void
1179 ex_diffpatch(exarg_T *eap)
1180 {
1181     char_u	*tmp_orig;	// name of original temp file
1182     char_u	*tmp_new;	// name of patched temp file
1183     char_u	*buf = NULL;
1184     size_t	buflen;
1185     win_T	*old_curwin = curwin;
1186     char_u	*newname = NULL;	// name of patched file buffer
1187 #ifdef UNIX
1188     char_u	dirbuf[MAXPATHL];
1189     char_u	*fullname = NULL;
1190 #endif
1191 #ifdef FEAT_BROWSE
1192     char_u	*browseFile = NULL;
1193     int		save_cmod_flags = cmdmod.cmod_flags;
1194 #endif
1195     stat_T	st;
1196     char_u	*esc_name = NULL;
1197 
1198 #ifdef FEAT_BROWSE
1199     if (cmdmod.cmod_flags & CMOD_BROWSE)
1200     {
1201 	browseFile = do_browse(0, (char_u *)_("Patch file"),
1202 			 eap->arg, NULL, NULL,
1203 			 (char_u *)_(BROWSE_FILTER_ALL_FILES), NULL);
1204 	if (browseFile == NULL)
1205 	    return;		// operation cancelled
1206 	eap->arg = browseFile;
1207 	cmdmod.cmod_flags &= ~CMOD_BROWSE; // don't let do_ecmd() browse again
1208     }
1209 #endif
1210 
1211     // We need two temp file names.
1212     tmp_orig = vim_tempname('o', FALSE);
1213     tmp_new = vim_tempname('n', FALSE);
1214     if (tmp_orig == NULL || tmp_new == NULL)
1215 	goto theend;
1216 
1217     // Write the current buffer to "tmp_orig".
1218     if (buf_write(curbuf, tmp_orig, NULL,
1219 		(linenr_T)1, curbuf->b_ml.ml_line_count,
1220 				     NULL, FALSE, FALSE, FALSE, TRUE) == FAIL)
1221 	goto theend;
1222 
1223 #ifdef UNIX
1224     // Get the absolute path of the patchfile, changing directory below.
1225     fullname = FullName_save(eap->arg, FALSE);
1226 #endif
1227     esc_name = vim_strsave_shellescape(
1228 # ifdef UNIX
1229 		    fullname != NULL ? fullname :
1230 # endif
1231 		    eap->arg, TRUE, TRUE);
1232     if (esc_name == NULL)
1233 	goto theend;
1234     buflen = STRLEN(tmp_orig) + STRLEN(esc_name) + STRLEN(tmp_new) + 16;
1235     buf = alloc(buflen);
1236     if (buf == NULL)
1237 	goto theend;
1238 
1239 #ifdef UNIX
1240     // Temporarily chdir to /tmp, to avoid patching files in the current
1241     // directory when the patch file contains more than one patch.  When we
1242     // have our own temp dir use that instead, it will be cleaned up when we
1243     // exit (any .rej files created).  Don't change directory if we can't
1244     // return to the current.
1245     if (mch_dirname(dirbuf, MAXPATHL) != OK || mch_chdir((char *)dirbuf) != 0)
1246 	dirbuf[0] = NUL;
1247     else
1248     {
1249 # ifdef TEMPDIRNAMES
1250 	if (vim_tempdir != NULL)
1251 	    vim_ignored = mch_chdir((char *)vim_tempdir);
1252 	else
1253 # endif
1254 	    vim_ignored = mch_chdir("/tmp");
1255 	shorten_fnames(TRUE);
1256     }
1257 #endif
1258 
1259 #ifdef FEAT_EVAL
1260     if (*p_pex != NUL)
1261 	// Use 'patchexpr' to generate the new file.
1262 	eval_patch(tmp_orig,
1263 # ifdef UNIX
1264 		fullname != NULL ? fullname :
1265 # endif
1266 		eap->arg, tmp_new);
1267     else
1268 #endif
1269     {
1270 	// Build the patch command and execute it.  Ignore errors.  Switch to
1271 	// cooked mode to allow the user to respond to prompts.
1272 	vim_snprintf((char *)buf, buflen, "patch -o %s %s < %s",
1273 						  tmp_new, tmp_orig, esc_name);
1274 	block_autocmds();	// Avoid ShellCmdPost stuff
1275 	(void)call_shell(buf, SHELL_FILTER | SHELL_COOKED);
1276 	unblock_autocmds();
1277     }
1278 
1279 #ifdef UNIX
1280     if (dirbuf[0] != NUL)
1281     {
1282 	if (mch_chdir((char *)dirbuf) != 0)
1283 	    emsg(_(e_prev_dir));
1284 	shorten_fnames(TRUE);
1285     }
1286 #endif
1287 
1288     // patch probably has written over the screen
1289     redraw_later(CLEAR);
1290 
1291     // Delete any .orig or .rej file created.
1292     STRCPY(buf, tmp_new);
1293     STRCAT(buf, ".orig");
1294     mch_remove(buf);
1295     STRCPY(buf, tmp_new);
1296     STRCAT(buf, ".rej");
1297     mch_remove(buf);
1298 
1299     // Only continue if the output file was created.
1300     if (mch_stat((char *)tmp_new, &st) < 0 || st.st_size == 0)
1301 	emsg(_("E816: Cannot read patch output"));
1302     else
1303     {
1304 	if (curbuf->b_fname != NULL)
1305 	{
1306 	    newname = vim_strnsave(curbuf->b_fname,
1307 						  STRLEN(curbuf->b_fname) + 4);
1308 	    if (newname != NULL)
1309 		STRCAT(newname, ".new");
1310 	}
1311 
1312 #ifdef FEAT_GUI
1313 	need_mouse_correct = TRUE;
1314 #endif
1315 	// don't use a new tab page, each tab page has its own diffs
1316 	cmdmod.cmod_tab = 0;
1317 
1318 	if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL)
1319 	{
1320 	    // Pretend it was a ":split fname" command
1321 	    eap->cmdidx = CMD_split;
1322 	    eap->arg = tmp_new;
1323 	    do_exedit(eap, old_curwin);
1324 
1325 	    // check that split worked and editing tmp_new
1326 	    if (curwin != old_curwin && win_valid(old_curwin))
1327 	    {
1328 		// Set 'diff', 'scrollbind' on and 'wrap' off.
1329 		diff_win_options(curwin, TRUE);
1330 		diff_win_options(old_curwin, TRUE);
1331 
1332 		if (newname != NULL)
1333 		{
1334 		    // do a ":file filename.new" on the patched buffer
1335 		    eap->arg = newname;
1336 		    ex_file(eap);
1337 
1338 		    // Do filetype detection with the new name.
1339 		    if (au_has_group((char_u *)"filetypedetect"))
1340 			do_cmdline_cmd((char_u *)":doau filetypedetect BufRead");
1341 		}
1342 	    }
1343 	}
1344     }
1345 
1346 theend:
1347     if (tmp_orig != NULL)
1348 	mch_remove(tmp_orig);
1349     vim_free(tmp_orig);
1350     if (tmp_new != NULL)
1351 	mch_remove(tmp_new);
1352     vim_free(tmp_new);
1353     vim_free(newname);
1354     vim_free(buf);
1355 #ifdef UNIX
1356     vim_free(fullname);
1357 #endif
1358     vim_free(esc_name);
1359 #ifdef FEAT_BROWSE
1360     vim_free(browseFile);
1361     cmdmod.cmod_flags = save_cmod_flags;
1362 #endif
1363 }
1364 
1365 /*
1366  * Split the window and edit another file, setting options to show the diffs.
1367  */
1368     void
1369 ex_diffsplit(exarg_T *eap)
1370 {
1371     win_T	*old_curwin = curwin;
1372     bufref_T	old_curbuf;
1373 
1374     set_bufref(&old_curbuf, curbuf);
1375 #ifdef FEAT_GUI
1376     need_mouse_correct = TRUE;
1377 #endif
1378     // Need to compute w_fraction when no redraw happened yet.
1379     validate_cursor();
1380     set_fraction(curwin);
1381 
1382     // don't use a new tab page, each tab page has its own diffs
1383     cmdmod.cmod_tab = 0;
1384 
1385     if (win_split(0, (diff_flags & DIFF_VERTICAL) ? WSP_VERT : 0) != FAIL)
1386     {
1387 	// Pretend it was a ":split fname" command
1388 	eap->cmdidx = CMD_split;
1389 	curwin->w_p_diff = TRUE;
1390 	do_exedit(eap, old_curwin);
1391 
1392 	if (curwin != old_curwin)		// split must have worked
1393 	{
1394 	    // Set 'diff', 'scrollbind' on and 'wrap' off.
1395 	    diff_win_options(curwin, TRUE);
1396 	    if (win_valid(old_curwin))
1397 	    {
1398 		diff_win_options(old_curwin, TRUE);
1399 
1400 		if (bufref_valid(&old_curbuf))
1401 		    // Move the cursor position to that of the old window.
1402 		    curwin->w_cursor.lnum = diff_get_corresponding_line(
1403 			    old_curbuf.br_buf, old_curwin->w_cursor.lnum);
1404 	    }
1405 	    // Now that lines are folded scroll to show the cursor at the same
1406 	    // relative position.
1407 	    scroll_to_fraction(curwin, curwin->w_height);
1408 	}
1409     }
1410 }
1411 
1412 /*
1413  * Set options to show diffs for the current window.
1414  */
1415     void
1416 ex_diffthis(exarg_T *eap UNUSED)
1417 {
1418     // Set 'diff', 'scrollbind' on and 'wrap' off.
1419     diff_win_options(curwin, TRUE);
1420 }
1421 
1422     static void
1423 set_diff_option(win_T *wp, int value)
1424 {
1425     win_T *old_curwin = curwin;
1426 
1427     curwin = wp;
1428     curbuf = curwin->w_buffer;
1429     ++curbuf_lock;
1430     set_option_value((char_u *)"diff", (long)value, NULL, OPT_LOCAL);
1431     --curbuf_lock;
1432     curwin = old_curwin;
1433     curbuf = curwin->w_buffer;
1434 }
1435 
1436 /*
1437  * Set options in window "wp" for diff mode.
1438  */
1439     void
1440 diff_win_options(
1441     win_T	*wp,
1442     int		addbuf)		// Add buffer to diff.
1443 {
1444 # ifdef FEAT_FOLDING
1445     win_T *old_curwin = curwin;
1446 
1447     // close the manually opened folds
1448     curwin = wp;
1449     newFoldLevel();
1450     curwin = old_curwin;
1451 # endif
1452 
1453     // Use 'scrollbind' and 'cursorbind' when available
1454     if (!wp->w_p_diff)
1455 	wp->w_p_scb_save = wp->w_p_scb;
1456     wp->w_p_scb = TRUE;
1457     if (!wp->w_p_diff)
1458 	wp->w_p_crb_save = wp->w_p_crb;
1459     wp->w_p_crb = TRUE;
1460     if (!(diff_flags & DIFF_FOLLOWWRAP))
1461     {
1462         if (!wp->w_p_diff)
1463 	    wp->w_p_wrap_save = wp->w_p_wrap;
1464         wp->w_p_wrap = FALSE;
1465     }
1466 # ifdef FEAT_FOLDING
1467     if (!wp->w_p_diff)
1468     {
1469 	if (wp->w_p_diff_saved)
1470 	    free_string_option(wp->w_p_fdm_save);
1471 	wp->w_p_fdm_save = vim_strsave(wp->w_p_fdm);
1472     }
1473     set_string_option_direct_in_win(wp, (char_u *)"fdm", -1, (char_u *)"diff",
1474 						       OPT_LOCAL|OPT_FREE, 0);
1475     if (!wp->w_p_diff)
1476     {
1477 	wp->w_p_fdc_save = wp->w_p_fdc;
1478 	wp->w_p_fen_save = wp->w_p_fen;
1479 	wp->w_p_fdl_save = wp->w_p_fdl;
1480     }
1481     wp->w_p_fdc = diff_foldcolumn;
1482     wp->w_p_fen = TRUE;
1483     wp->w_p_fdl = 0;
1484     foldUpdateAll(wp);
1485     // make sure topline is not halfway a fold
1486     changed_window_setting_win(wp);
1487 # endif
1488     if (vim_strchr(p_sbo, 'h') == NULL)
1489 	do_cmdline_cmd((char_u *)"set sbo+=hor");
1490     // Save the current values, to be restored in ex_diffoff().
1491     wp->w_p_diff_saved = TRUE;
1492 
1493     set_diff_option(wp, TRUE);
1494 
1495     if (addbuf)
1496 	diff_buf_add(wp->w_buffer);
1497     redraw_win_later(wp, NOT_VALID);
1498 }
1499 
1500 /*
1501  * Set options not to show diffs.  For the current window or all windows.
1502  * Only in the current tab page.
1503  */
1504     void
1505 ex_diffoff(exarg_T *eap)
1506 {
1507     win_T	*wp;
1508     int		diffwin = FALSE;
1509 
1510     FOR_ALL_WINDOWS(wp)
1511     {
1512 	if (eap->forceit ? wp->w_p_diff : wp == curwin)
1513 	{
1514 	    // Set 'diff' off. If option values were saved in
1515 	    // diff_win_options(), restore the ones whose settings seem to have
1516 	    // been left over from diff mode.
1517 	    set_diff_option(wp, FALSE);
1518 
1519 	    if (wp->w_p_diff_saved)
1520 	    {
1521 
1522 		if (wp->w_p_scb)
1523 		    wp->w_p_scb = wp->w_p_scb_save;
1524 		if (wp->w_p_crb)
1525 		    wp->w_p_crb = wp->w_p_crb_save;
1526 		if (!(diff_flags & DIFF_FOLLOWWRAP))
1527 		{
1528 		    if (!wp->w_p_wrap)
1529 		        wp->w_p_wrap = wp->w_p_wrap_save;
1530 		}
1531 #ifdef FEAT_FOLDING
1532 		free_string_option(wp->w_p_fdm);
1533 		wp->w_p_fdm = vim_strsave(
1534 		    *wp->w_p_fdm_save ? wp->w_p_fdm_save : (char_u*)"manual");
1535 
1536 		if (wp->w_p_fdc == diff_foldcolumn)
1537 		    wp->w_p_fdc = wp->w_p_fdc_save;
1538 		if (wp->w_p_fdl == 0)
1539 		    wp->w_p_fdl = wp->w_p_fdl_save;
1540 
1541 		// Only restore 'foldenable' when 'foldmethod' is not
1542 		// "manual", otherwise we continue to show the diff folds.
1543 		if (wp->w_p_fen)
1544 		    wp->w_p_fen = foldmethodIsManual(wp) ? FALSE
1545 							 : wp->w_p_fen_save;
1546 
1547 		foldUpdateAll(wp);
1548 #endif
1549 	    }
1550 	    // remove filler lines
1551 	    wp->w_topfill = 0;
1552 
1553 	    // make sure topline is not halfway a fold and cursor is
1554 	    // invalidated
1555 	    changed_window_setting_win(wp);
1556 
1557 	    // Note: 'sbo' is not restored, it's a global option.
1558 	    diff_buf_adjust(wp);
1559 	}
1560 	diffwin |= wp->w_p_diff;
1561     }
1562 
1563     // Also remove hidden buffers from the list.
1564     if (eap->forceit)
1565 	diff_buf_clear();
1566 
1567     if (!diffwin)
1568     {
1569 	diff_need_update = FALSE;
1570 	curtab->tp_diff_invalid = FALSE;
1571 	curtab->tp_diff_update = FALSE;
1572 	diff_clear(curtab);
1573     }
1574 
1575     // Remove "hor" from from 'scrollopt' if there are no diff windows left.
1576     if (!diffwin && vim_strchr(p_sbo, 'h') != NULL)
1577 	do_cmdline_cmd((char_u *)"set sbo-=hor");
1578 }
1579 
1580 /*
1581  * Read the diff output and add each entry to the diff list.
1582  */
1583     static void
1584 diff_read(
1585     int		idx_orig,	// idx of original file
1586     int		idx_new,	// idx of new file
1587     diffout_T	*dout)		// diff output
1588 {
1589     FILE	*fd = NULL;
1590     int		line_idx = 0;
1591     diff_T	*dprev = NULL;
1592     diff_T	*dp = curtab->tp_first_diff;
1593     diff_T	*dn, *dpl;
1594     char_u	linebuf[LBUFLEN];   // only need to hold the diff line
1595     char_u	*line;
1596     long	off;
1597     int		i;
1598     linenr_T	lnum_orig, lnum_new;
1599     long	count_orig, count_new;
1600     int		notset = TRUE;	    // block "*dp" not set yet
1601     enum {
1602 	DIFF_ED,
1603 	DIFF_UNIFIED,
1604 	DIFF_NONE
1605     } diffstyle = DIFF_NONE;
1606 
1607     if (dout->dout_fname == NULL)
1608     {
1609 	diffstyle = DIFF_UNIFIED;
1610     }
1611     else
1612     {
1613 	fd = mch_fopen((char *)dout->dout_fname, "r");
1614 	if (fd == NULL)
1615 	{
1616 	    emsg(_("E98: Cannot read diff output"));
1617 	    return;
1618 	}
1619     }
1620 
1621     for (;;)
1622     {
1623 	if (fd == NULL)
1624 	{
1625 	    if (line_idx >= dout->dout_ga.ga_len)
1626 		break;	    // did last line
1627 	    line = ((char_u **)dout->dout_ga.ga_data)[line_idx++];
1628 	}
1629 	else
1630 	{
1631 	    if (vim_fgets(linebuf, LBUFLEN, fd))
1632 		break;		// end of file
1633 	    line = linebuf;
1634 	}
1635 
1636 	if (diffstyle == DIFF_NONE)
1637 	{
1638 	    // Determine diff style.
1639 	    // ed like diff looks like this:
1640 	    // {first}[,{last}]c{first}[,{last}]
1641 	    // {first}a{first}[,{last}]
1642 	    // {first}[,{last}]d{first}
1643 	    //
1644 	    // unified diff looks like this:
1645 	    // --- file1       2018-03-20 13:23:35.783153140 +0100
1646 	    // +++ file2       2018-03-20 13:23:41.183156066 +0100
1647 	    // @@ -1,3 +1,5 @@
1648 	    if (isdigit(*line))
1649 		diffstyle = DIFF_ED;
1650 	    else if ((STRNCMP(line, "@@ ", 3) == 0))
1651 	       diffstyle = DIFF_UNIFIED;
1652 	    else if ((STRNCMP(line, "--- ", 4) == 0)
1653 		    && (vim_fgets(linebuf, LBUFLEN, fd) == 0)
1654 		    && (STRNCMP(line, "+++ ", 4) == 0)
1655 		    && (vim_fgets(linebuf, LBUFLEN, fd) == 0)
1656 		    && (STRNCMP(line, "@@ ", 3) == 0))
1657 		diffstyle = DIFF_UNIFIED;
1658 	    else
1659 		// Format not recognized yet, skip over this line.  Cygwin diff
1660 		// may put a warning at the start of the file.
1661 		continue;
1662 	}
1663 
1664 	if (diffstyle == DIFF_ED)
1665 	{
1666 	    if (!isdigit(*line))
1667 		continue;	// not the start of a diff block
1668 	    if (parse_diff_ed(line, &lnum_orig, &count_orig,
1669 						&lnum_new, &count_new) == FAIL)
1670 		continue;
1671 	}
1672 	else if (diffstyle == DIFF_UNIFIED)
1673 	{
1674 	    if (STRNCMP(line, "@@ ", 3)  != 0)
1675 		continue;	// not the start of a diff block
1676 	    if (parse_diff_unified(line, &lnum_orig, &count_orig,
1677 						&lnum_new, &count_new) == FAIL)
1678 		continue;
1679 	}
1680 	else
1681 	{
1682 	    emsg(_("E959: Invalid diff format."));
1683 	    break;
1684 	}
1685 
1686 	// Go over blocks before the change, for which orig and new are equal.
1687 	// Copy blocks from orig to new.
1688 	while (dp != NULL
1689 		&& lnum_orig > dp->df_lnum[idx_orig] + dp->df_count[idx_orig])
1690 	{
1691 	    if (notset)
1692 		diff_copy_entry(dprev, dp, idx_orig, idx_new);
1693 	    dprev = dp;
1694 	    dp = dp->df_next;
1695 	    notset = TRUE;
1696 	}
1697 
1698 	if (dp != NULL
1699 		&& lnum_orig <= dp->df_lnum[idx_orig] + dp->df_count[idx_orig]
1700 		&& lnum_orig + count_orig >= dp->df_lnum[idx_orig])
1701 	{
1702 	    // New block overlaps with existing block(s).
1703 	    // First find last block that overlaps.
1704 	    for (dpl = dp; dpl->df_next != NULL; dpl = dpl->df_next)
1705 		if (lnum_orig + count_orig < dpl->df_next->df_lnum[idx_orig])
1706 		    break;
1707 
1708 	    // If the newly found block starts before the old one, set the
1709 	    // start back a number of lines.
1710 	    off = dp->df_lnum[idx_orig] - lnum_orig;
1711 	    if (off > 0)
1712 	    {
1713 		for (i = idx_orig; i < idx_new; ++i)
1714 		    if (curtab->tp_diffbuf[i] != NULL)
1715 			dp->df_lnum[i] -= off;
1716 		dp->df_lnum[idx_new] = lnum_new;
1717 		dp->df_count[idx_new] = count_new;
1718 	    }
1719 	    else if (notset)
1720 	    {
1721 		// new block inside existing one, adjust new block
1722 		dp->df_lnum[idx_new] = lnum_new + off;
1723 		dp->df_count[idx_new] = count_new - off;
1724 	    }
1725 	    else
1726 		// second overlap of new block with existing block
1727 		dp->df_count[idx_new] += count_new - count_orig
1728 		    + dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]
1729 		    - (dp->df_lnum[idx_orig] + dp->df_count[idx_orig]);
1730 
1731 	    // Adjust the size of the block to include all the lines to the
1732 	    // end of the existing block or the new diff, whatever ends last.
1733 	    off = (lnum_orig + count_orig)
1734 			 - (dpl->df_lnum[idx_orig] + dpl->df_count[idx_orig]);
1735 	    if (off < 0)
1736 	    {
1737 		// new change ends in existing block, adjust the end if not
1738 		// done already
1739 		if (notset)
1740 		    dp->df_count[idx_new] += -off;
1741 		off = 0;
1742 	    }
1743 	    for (i = idx_orig; i < idx_new; ++i)
1744 		if (curtab->tp_diffbuf[i] != NULL)
1745 		    dp->df_count[i] = dpl->df_lnum[i] + dpl->df_count[i]
1746 						       - dp->df_lnum[i] + off;
1747 
1748 	    // Delete the diff blocks that have been merged into one.
1749 	    dn = dp->df_next;
1750 	    dp->df_next = dpl->df_next;
1751 	    while (dn != dp->df_next)
1752 	    {
1753 		dpl = dn->df_next;
1754 		vim_free(dn);
1755 		dn = dpl;
1756 	    }
1757 	}
1758 	else
1759 	{
1760 	    // Allocate a new diffblock.
1761 	    dp = diff_alloc_new(curtab, dprev, dp);
1762 	    if (dp == NULL)
1763 		goto done;
1764 
1765 	    dp->df_lnum[idx_orig] = lnum_orig;
1766 	    dp->df_count[idx_orig] = count_orig;
1767 	    dp->df_lnum[idx_new] = lnum_new;
1768 	    dp->df_count[idx_new] = count_new;
1769 
1770 	    // Set values for other buffers, these must be equal to the
1771 	    // original buffer, otherwise there would have been a change
1772 	    // already.
1773 	    for (i = idx_orig + 1; i < idx_new; ++i)
1774 		if (curtab->tp_diffbuf[i] != NULL)
1775 		    diff_copy_entry(dprev, dp, idx_orig, i);
1776 	}
1777 	notset = FALSE;		// "*dp" has been set
1778     }
1779 
1780     // for remaining diff blocks orig and new are equal
1781     while (dp != NULL)
1782     {
1783 	if (notset)
1784 	    diff_copy_entry(dprev, dp, idx_orig, idx_new);
1785 	dprev = dp;
1786 	dp = dp->df_next;
1787 	notset = TRUE;
1788     }
1789 
1790 done:
1791     if (fd != NULL)
1792 	fclose(fd);
1793 }
1794 
1795 /*
1796  * Copy an entry at "dp" from "idx_orig" to "idx_new".
1797  */
1798     static void
1799 diff_copy_entry(
1800     diff_T	*dprev,
1801     diff_T	*dp,
1802     int		idx_orig,
1803     int		idx_new)
1804 {
1805     long	off;
1806 
1807     if (dprev == NULL)
1808 	off = 0;
1809     else
1810 	off = (dprev->df_lnum[idx_orig] + dprev->df_count[idx_orig])
1811 	    - (dprev->df_lnum[idx_new] + dprev->df_count[idx_new]);
1812     dp->df_lnum[idx_new] = dp->df_lnum[idx_orig] - off;
1813     dp->df_count[idx_new] = dp->df_count[idx_orig];
1814 }
1815 
1816 /*
1817  * Clear the list of diffblocks for tab page "tp".
1818  */
1819     void
1820 diff_clear(tabpage_T *tp)
1821 {
1822     diff_T	*p, *next_p;
1823 
1824     for (p = tp->tp_first_diff; p != NULL; p = next_p)
1825     {
1826 	next_p = p->df_next;
1827 	vim_free(p);
1828     }
1829     tp->tp_first_diff = NULL;
1830 }
1831 
1832 /*
1833  * Check diff status for line "lnum" in buffer "buf":
1834  * Returns 0 for nothing special
1835  * Returns -1 for a line that should be highlighted as changed.
1836  * Returns -2 for a line that should be highlighted as added/deleted.
1837  * Returns > 0 for inserting that many filler lines above it (never happens
1838  * when 'diffopt' doesn't contain "filler").
1839  * This should only be used for windows where 'diff' is set.
1840  */
1841     int
1842 diff_check(win_T *wp, linenr_T lnum)
1843 {
1844     int		idx;		// index in tp_diffbuf[] for this buffer
1845     diff_T	*dp;
1846     int		maxcount;
1847     int		i;
1848     buf_T	*buf = wp->w_buffer;
1849     int		cmp;
1850 
1851     if (curtab->tp_diff_invalid)
1852 	ex_diffupdate(NULL);		// update after a big change
1853 
1854     if (curtab->tp_first_diff == NULL || !wp->w_p_diff)	// no diffs at all
1855 	return 0;
1856 
1857     // safety check: "lnum" must be a buffer line
1858     if (lnum < 1 || lnum > buf->b_ml.ml_line_count + 1)
1859 	return 0;
1860 
1861     idx = diff_buf_idx(buf);
1862     if (idx == DB_COUNT)
1863 	return 0;		// no diffs for buffer "buf"
1864 
1865 #ifdef FEAT_FOLDING
1866     // A closed fold never has filler lines.
1867     if (hasFoldingWin(wp, lnum, NULL, NULL, TRUE, NULL))
1868 	return 0;
1869 #endif
1870 
1871     // search for a change that includes "lnum" in the list of diffblocks.
1872     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
1873 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
1874 	    break;
1875     if (dp == NULL || lnum < dp->df_lnum[idx])
1876 	return 0;
1877 
1878     if (lnum < dp->df_lnum[idx] + dp->df_count[idx])
1879     {
1880 	int	zero = FALSE;
1881 
1882 	// Changed or inserted line.  If the other buffers have a count of
1883 	// zero, the lines were inserted.  If the other buffers have the same
1884 	// count, check if the lines are identical.
1885 	cmp = FALSE;
1886 	for (i = 0; i < DB_COUNT; ++i)
1887 	    if (i != idx && curtab->tp_diffbuf[i] != NULL)
1888 	    {
1889 		if (dp->df_count[i] == 0)
1890 		    zero = TRUE;
1891 		else
1892 		{
1893 		    if (dp->df_count[i] != dp->df_count[idx])
1894 			return -1;	    // nr of lines changed.
1895 		    cmp = TRUE;
1896 		}
1897 	    }
1898 	if (cmp)
1899 	{
1900 	    // Compare all lines.  If they are equal the lines were inserted
1901 	    // in some buffers, deleted in others, but not changed.
1902 	    for (i = 0; i < DB_COUNT; ++i)
1903 		if (i != idx && curtab->tp_diffbuf[i] != NULL
1904 						      && dp->df_count[i] != 0)
1905 		    if (!diff_equal_entry(dp, idx, i))
1906 			return -1;
1907 	}
1908 	// If there is no buffer with zero lines then there is no difference
1909 	// any longer.  Happens when making a change (or undo) that removes
1910 	// the difference.  Can't remove the entry here, we might be halfway
1911 	// updating the window.  Just report the text as unchanged.  Other
1912 	// windows might still show the change though.
1913 	if (zero == FALSE)
1914 	    return 0;
1915 	return -2;
1916     }
1917 
1918     // If 'diffopt' doesn't contain "filler", return 0.
1919     if (!(diff_flags & DIFF_FILLER))
1920 	return 0;
1921 
1922     // Insert filler lines above the line just below the change.  Will return
1923     // 0 when this buf had the max count.
1924     maxcount = 0;
1925     for (i = 0; i < DB_COUNT; ++i)
1926 	if (curtab->tp_diffbuf[i] != NULL && dp->df_count[i] > maxcount)
1927 	    maxcount = dp->df_count[i];
1928     return maxcount - dp->df_count[idx];
1929 }
1930 
1931 /*
1932  * Compare two entries in diff "*dp" and return TRUE if they are equal.
1933  */
1934     static int
1935 diff_equal_entry(diff_T *dp, int idx1, int idx2)
1936 {
1937     int		i;
1938     char_u	*line;
1939     int		cmp;
1940 
1941     if (dp->df_count[idx1] != dp->df_count[idx2])
1942 	return FALSE;
1943     if (diff_check_sanity(curtab, dp) == FAIL)
1944 	return FALSE;
1945     for (i = 0; i < dp->df_count[idx1]; ++i)
1946     {
1947 	line = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx1],
1948 					       dp->df_lnum[idx1] + i, FALSE));
1949 	if (line == NULL)
1950 	    return FALSE;
1951 	cmp = diff_cmp(line, ml_get_buf(curtab->tp_diffbuf[idx2],
1952 					       dp->df_lnum[idx2] + i, FALSE));
1953 	vim_free(line);
1954 	if (cmp != 0)
1955 	    return FALSE;
1956     }
1957     return TRUE;
1958 }
1959 
1960 /*
1961  * Compare the characters at "p1" and "p2".  If they are equal (possibly
1962  * ignoring case) return TRUE and set "len" to the number of bytes.
1963  */
1964     static int
1965 diff_equal_char(char_u *p1, char_u *p2, int *len)
1966 {
1967     int l  = (*mb_ptr2len)(p1);
1968 
1969     if (l != (*mb_ptr2len)(p2))
1970 	return FALSE;
1971     if (l > 1)
1972     {
1973 	if (STRNCMP(p1, p2, l) != 0
1974 		&& (!enc_utf8
1975 		    || !(diff_flags & DIFF_ICASE)
1976 		    || utf_fold(utf_ptr2char(p1))
1977 						!= utf_fold(utf_ptr2char(p2))))
1978 	    return FALSE;
1979 	*len = l;
1980     }
1981     else
1982     {
1983 	if ((*p1 != *p2)
1984 		&& (!(diff_flags & DIFF_ICASE)
1985 		    || TOLOWER_LOC(*p1) != TOLOWER_LOC(*p2)))
1986 	    return FALSE;
1987 	*len = 1;
1988     }
1989     return TRUE;
1990 }
1991 
1992 /*
1993  * Compare strings "s1" and "s2" according to 'diffopt'.
1994  * Return non-zero when they are different.
1995  */
1996     static int
1997 diff_cmp(char_u *s1, char_u *s2)
1998 {
1999     char_u	*p1, *p2;
2000     int		l;
2001 
2002     if ((diff_flags & DIFF_IBLANK)
2003 	    && (*skipwhite(s1) == NUL || *skipwhite(s2) == NUL))
2004 	return 0;
2005 
2006     if ((diff_flags & (DIFF_ICASE | ALL_WHITE_DIFF)) == 0)
2007 	return STRCMP(s1, s2);
2008     if ((diff_flags & DIFF_ICASE) && !(diff_flags & ALL_WHITE_DIFF))
2009 	return MB_STRICMP(s1, s2);
2010 
2011     p1 = s1;
2012     p2 = s2;
2013 
2014     // Ignore white space changes and possibly ignore case.
2015     while (*p1 != NUL && *p2 != NUL)
2016     {
2017 	if (((diff_flags & DIFF_IWHITE)
2018 		    && VIM_ISWHITE(*p1) && VIM_ISWHITE(*p2))
2019 		|| ((diff_flags & DIFF_IWHITEALL)
2020 		    && (VIM_ISWHITE(*p1) || VIM_ISWHITE(*p2))))
2021 	{
2022 	    p1 = skipwhite(p1);
2023 	    p2 = skipwhite(p2);
2024 	}
2025 	else
2026 	{
2027 	    if (!diff_equal_char(p1, p2, &l))
2028 		break;
2029 	    p1 += l;
2030 	    p2 += l;
2031 	}
2032     }
2033 
2034     // Ignore trailing white space.
2035     p1 = skipwhite(p1);
2036     p2 = skipwhite(p2);
2037     if (*p1 != NUL || *p2 != NUL)
2038 	return 1;
2039     return 0;
2040 }
2041 
2042 /*
2043  * Return the number of filler lines above "lnum".
2044  */
2045     int
2046 diff_check_fill(win_T *wp, linenr_T lnum)
2047 {
2048     int		n;
2049 
2050     // be quick when there are no filler lines
2051     if (!(diff_flags & DIFF_FILLER))
2052 	return 0;
2053     n = diff_check(wp, lnum);
2054     if (n <= 0)
2055 	return 0;
2056     return n;
2057 }
2058 
2059 /*
2060  * Set the topline of "towin" to match the position in "fromwin", so that they
2061  * show the same diff'ed lines.
2062  */
2063     void
2064 diff_set_topline(win_T *fromwin, win_T *towin)
2065 {
2066     buf_T	*frombuf = fromwin->w_buffer;
2067     linenr_T	lnum = fromwin->w_topline;
2068     int		fromidx;
2069     int		toidx;
2070     diff_T	*dp;
2071     int		max_count;
2072     int		i;
2073 
2074     fromidx = diff_buf_idx(frombuf);
2075     if (fromidx == DB_COUNT)
2076 	return;		// safety check
2077 
2078     if (curtab->tp_diff_invalid)
2079 	ex_diffupdate(NULL);		// update after a big change
2080 
2081     towin->w_topfill = 0;
2082 
2083     // search for a change that includes "lnum" in the list of diffblocks.
2084     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
2085 	if (lnum <= dp->df_lnum[fromidx] + dp->df_count[fromidx])
2086 	    break;
2087     if (dp == NULL)
2088     {
2089 	// After last change, compute topline relative to end of file; no
2090 	// filler lines.
2091 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count
2092 				       - (frombuf->b_ml.ml_line_count - lnum);
2093     }
2094     else
2095     {
2096 	// Find index for "towin".
2097 	toidx = diff_buf_idx(towin->w_buffer);
2098 	if (toidx == DB_COUNT)
2099 	    return;		// safety check
2100 
2101 	towin->w_topline = lnum + (dp->df_lnum[toidx] - dp->df_lnum[fromidx]);
2102 	if (lnum >= dp->df_lnum[fromidx])
2103 	{
2104 	    // Inside a change: compute filler lines. With three or more
2105 	    // buffers we need to know the largest count.
2106 	    max_count = 0;
2107 	    for (i = 0; i < DB_COUNT; ++i)
2108 		if (curtab->tp_diffbuf[i] != NULL
2109 					       && max_count < dp->df_count[i])
2110 		    max_count = dp->df_count[i];
2111 
2112 	    if (dp->df_count[toidx] == dp->df_count[fromidx])
2113 	    {
2114 		// same number of lines: use same filler count
2115 		towin->w_topfill = fromwin->w_topfill;
2116 	    }
2117 	    else if (dp->df_count[toidx] > dp->df_count[fromidx])
2118 	    {
2119 		if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx])
2120 		{
2121 		    // more lines in towin and fromwin doesn't show diff
2122 		    // lines, only filler lines
2123 		    if (max_count - fromwin->w_topfill >= dp->df_count[toidx])
2124 		    {
2125 			// towin also only shows filler lines
2126 			towin->w_topline = dp->df_lnum[toidx]
2127 						       + dp->df_count[toidx];
2128 			towin->w_topfill = fromwin->w_topfill;
2129 		    }
2130 		    else
2131 			// towin still has some diff lines to show
2132 			towin->w_topline = dp->df_lnum[toidx]
2133 					     + max_count - fromwin->w_topfill;
2134 		}
2135 	    }
2136 	    else if (towin->w_topline >= dp->df_lnum[toidx]
2137 							+ dp->df_count[toidx])
2138 	    {
2139 		// less lines in towin and no diff lines to show: compute
2140 		// filler lines
2141 		towin->w_topline = dp->df_lnum[toidx] + dp->df_count[toidx];
2142 		if (diff_flags & DIFF_FILLER)
2143 		{
2144 		    if (lnum == dp->df_lnum[fromidx] + dp->df_count[fromidx])
2145 			// fromwin is also out of diff lines
2146 			towin->w_topfill = fromwin->w_topfill;
2147 		    else
2148 			// fromwin has some diff lines
2149 			towin->w_topfill = dp->df_lnum[fromidx]
2150 							   + max_count - lnum;
2151 		}
2152 	    }
2153 	}
2154     }
2155 
2156     // safety check (if diff info gets outdated strange things may happen)
2157     towin->w_botfill = FALSE;
2158     if (towin->w_topline > towin->w_buffer->b_ml.ml_line_count)
2159     {
2160 	towin->w_topline = towin->w_buffer->b_ml.ml_line_count;
2161 	towin->w_botfill = TRUE;
2162     }
2163     if (towin->w_topline < 1)
2164     {
2165 	towin->w_topline = 1;
2166 	towin->w_topfill = 0;
2167     }
2168 
2169     // When w_topline changes need to recompute w_botline and cursor position
2170     invalidate_botline_win(towin);
2171     changed_line_abv_curs_win(towin);
2172 
2173     check_topfill(towin, FALSE);
2174 #ifdef FEAT_FOLDING
2175     (void)hasFoldingWin(towin, towin->w_topline, &towin->w_topline,
2176 							    NULL, TRUE, NULL);
2177 #endif
2178 }
2179 
2180 /*
2181  * This is called when 'diffopt' is changed.
2182  */
2183     int
2184 diffopt_changed(void)
2185 {
2186     char_u	*p;
2187     int		diff_context_new = 6;
2188     int		diff_flags_new = 0;
2189     int		diff_foldcolumn_new = 2;
2190     long	diff_algorithm_new = 0;
2191     long	diff_indent_heuristic = 0;
2192     tabpage_T	*tp;
2193 
2194     p = p_dip;
2195     while (*p != NUL)
2196     {
2197 	if (STRNCMP(p, "filler", 6) == 0)
2198 	{
2199 	    p += 6;
2200 	    diff_flags_new |= DIFF_FILLER;
2201 	}
2202 	else if (STRNCMP(p, "context:", 8) == 0 && VIM_ISDIGIT(p[8]))
2203 	{
2204 	    p += 8;
2205 	    diff_context_new = getdigits(&p);
2206 	}
2207 	else if (STRNCMP(p, "iblank", 6) == 0)
2208 	{
2209 	    p += 6;
2210 	    diff_flags_new |= DIFF_IBLANK;
2211 	}
2212 	else if (STRNCMP(p, "icase", 5) == 0)
2213 	{
2214 	    p += 5;
2215 	    diff_flags_new |= DIFF_ICASE;
2216 	}
2217 	else if (STRNCMP(p, "iwhiteall", 9) == 0)
2218 	{
2219 	    p += 9;
2220 	    diff_flags_new |= DIFF_IWHITEALL;
2221 	}
2222 	else if (STRNCMP(p, "iwhiteeol", 9) == 0)
2223 	{
2224 	    p += 9;
2225 	    diff_flags_new |= DIFF_IWHITEEOL;
2226 	}
2227 	else if (STRNCMP(p, "iwhite", 6) == 0)
2228 	{
2229 	    p += 6;
2230 	    diff_flags_new |= DIFF_IWHITE;
2231 	}
2232 	else if (STRNCMP(p, "horizontal", 10) == 0)
2233 	{
2234 	    p += 10;
2235 	    diff_flags_new |= DIFF_HORIZONTAL;
2236 	}
2237 	else if (STRNCMP(p, "vertical", 8) == 0)
2238 	{
2239 	    p += 8;
2240 	    diff_flags_new |= DIFF_VERTICAL;
2241 	}
2242 	else if (STRNCMP(p, "foldcolumn:", 11) == 0 && VIM_ISDIGIT(p[11]))
2243 	{
2244 	    p += 11;
2245 	    diff_foldcolumn_new = getdigits(&p);
2246 	}
2247 	else if (STRNCMP(p, "hiddenoff", 9) == 0)
2248 	{
2249 	    p += 9;
2250 	    diff_flags_new |= DIFF_HIDDEN_OFF;
2251 	}
2252 	else if (STRNCMP(p, "closeoff", 8) == 0)
2253 	{
2254 	    p += 8;
2255 	    diff_flags_new |= DIFF_CLOSE_OFF;
2256 	}
2257 	else if (STRNCMP(p, "followwrap", 10) == 0)
2258 	{
2259 	    p += 10;
2260 	    diff_flags_new |= DIFF_FOLLOWWRAP;
2261 	}
2262 	else if (STRNCMP(p, "indent-heuristic", 16) == 0)
2263 	{
2264 	    p += 16;
2265 	    diff_indent_heuristic = XDF_INDENT_HEURISTIC;
2266 	}
2267 	else if (STRNCMP(p, "internal", 8) == 0)
2268 	{
2269 	    p += 8;
2270 	    diff_flags_new |= DIFF_INTERNAL;
2271 	}
2272 	else if (STRNCMP(p, "algorithm:", 10) == 0)
2273 	{
2274 	    p += 10;
2275 	    if (STRNCMP(p, "myers", 5) == 0)
2276 	    {
2277 		p += 5;
2278 		diff_algorithm_new = 0;
2279 	    }
2280 	    else if (STRNCMP(p, "minimal", 7) == 0)
2281 	    {
2282 		p += 7;
2283 		diff_algorithm_new = XDF_NEED_MINIMAL;
2284 	    }
2285 	    else if (STRNCMP(p, "patience", 8) == 0)
2286 	    {
2287 		p += 8;
2288 		diff_algorithm_new = XDF_PATIENCE_DIFF;
2289 	    }
2290 	    else if (STRNCMP(p, "histogram", 9) == 0)
2291 	    {
2292 		p += 9;
2293 		diff_algorithm_new = XDF_HISTOGRAM_DIFF;
2294 	    }
2295 	    else
2296 		return FAIL;
2297 	}
2298 
2299 	if (*p != ',' && *p != NUL)
2300 	    return FAIL;
2301 	if (*p == ',')
2302 	    ++p;
2303     }
2304 
2305     diff_algorithm_new |= diff_indent_heuristic;
2306 
2307     // Can't have both "horizontal" and "vertical".
2308     if ((diff_flags_new & DIFF_HORIZONTAL) && (diff_flags_new & DIFF_VERTICAL))
2309 	return FAIL;
2310 
2311     // If flags were added or removed, or the algorithm was changed, need to
2312     // update the diff.
2313     if (diff_flags != diff_flags_new || diff_algorithm != diff_algorithm_new)
2314 	FOR_ALL_TABPAGES(tp)
2315 	    tp->tp_diff_invalid = TRUE;
2316 
2317     diff_flags = diff_flags_new;
2318     diff_context = diff_context_new == 0 ? 1 : diff_context_new;
2319     diff_foldcolumn = diff_foldcolumn_new;
2320     diff_algorithm = diff_algorithm_new;
2321 
2322     diff_redraw(TRUE);
2323 
2324     // recompute the scroll binding with the new option value, may
2325     // remove or add filler lines
2326     check_scrollbind((linenr_T)0, 0L);
2327 
2328     return OK;
2329 }
2330 
2331 /*
2332  * Return TRUE if 'diffopt' contains "horizontal".
2333  */
2334     int
2335 diffopt_horizontal(void)
2336 {
2337     return (diff_flags & DIFF_HORIZONTAL) != 0;
2338 }
2339 
2340 /*
2341  * Return TRUE if 'diffopt' contains "hiddenoff".
2342  */
2343     int
2344 diffopt_hiddenoff(void)
2345 {
2346     return (diff_flags & DIFF_HIDDEN_OFF) != 0;
2347 }
2348 
2349 /*
2350  * Return TRUE if 'diffopt' contains "closeoff".
2351  */
2352     int
2353 diffopt_closeoff(void)
2354 {
2355     return (diff_flags & DIFF_CLOSE_OFF) != 0;
2356 }
2357 
2358 /*
2359  * Find the difference within a changed line.
2360  * Returns TRUE if the line was added, no other buffer has it.
2361  */
2362     int
2363 diff_find_change(
2364     win_T	*wp,
2365     linenr_T	lnum,
2366     int		*startp,	// first char of the change
2367     int		*endp)		// last char of the change
2368 {
2369     char_u	*line_org;
2370     char_u	*line_new;
2371     int		i;
2372     int		si_org, si_new;
2373     int		ei_org, ei_new;
2374     diff_T	*dp;
2375     int		idx;
2376     int		off;
2377     int		added = TRUE;
2378     char_u	*p1, *p2;
2379     int		l;
2380 
2381     // Make a copy of the line, the next ml_get() will invalidate it.
2382     line_org = vim_strsave(ml_get_buf(wp->w_buffer, lnum, FALSE));
2383     if (line_org == NULL)
2384 	return FALSE;
2385 
2386     idx = diff_buf_idx(wp->w_buffer);
2387     if (idx == DB_COUNT)	// cannot happen
2388     {
2389 	vim_free(line_org);
2390 	return FALSE;
2391     }
2392 
2393     // search for a change that includes "lnum" in the list of diffblocks.
2394     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
2395 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
2396 	    break;
2397     if (dp == NULL || diff_check_sanity(curtab, dp) == FAIL)
2398     {
2399 	vim_free(line_org);
2400 	return FALSE;
2401     }
2402 
2403     off = lnum - dp->df_lnum[idx];
2404 
2405     for (i = 0; i < DB_COUNT; ++i)
2406 	if (curtab->tp_diffbuf[i] != NULL && i != idx)
2407 	{
2408 	    // Skip lines that are not in the other change (filler lines).
2409 	    if (off >= dp->df_count[i])
2410 		continue;
2411 	    added = FALSE;
2412 	    line_new = ml_get_buf(curtab->tp_diffbuf[i],
2413 						 dp->df_lnum[i] + off, FALSE);
2414 
2415 	    // Search for start of difference
2416 	    si_org = si_new = 0;
2417 	    while (line_org[si_org] != NUL)
2418 	    {
2419 		if (((diff_flags & DIFF_IWHITE)
2420 			    && VIM_ISWHITE(line_org[si_org])
2421 					      && VIM_ISWHITE(line_new[si_new]))
2422 			|| ((diff_flags & DIFF_IWHITEALL)
2423 			    && (VIM_ISWHITE(line_org[si_org])
2424 					    || VIM_ISWHITE(line_new[si_new]))))
2425 		{
2426 		    si_org = (int)(skipwhite(line_org + si_org) - line_org);
2427 		    si_new = (int)(skipwhite(line_new + si_new) - line_new);
2428 		}
2429 		else
2430 		{
2431 		    if (!diff_equal_char(line_org + si_org, line_new + si_new,
2432 									   &l))
2433 			break;
2434 		    si_org += l;
2435 		    si_new += l;
2436 		}
2437 	    }
2438 	    if (has_mbyte)
2439 	    {
2440 		// Move back to first byte of character in both lines (may
2441 		// have "nn^" in line_org and "n^ in line_new).
2442 		si_org -= (*mb_head_off)(line_org, line_org + si_org);
2443 		si_new -= (*mb_head_off)(line_new, line_new + si_new);
2444 	    }
2445 	    if (*startp > si_org)
2446 		*startp = si_org;
2447 
2448 	    // Search for end of difference, if any.
2449 	    if (line_org[si_org] != NUL || line_new[si_new] != NUL)
2450 	    {
2451 		ei_org = (int)STRLEN(line_org);
2452 		ei_new = (int)STRLEN(line_new);
2453 		while (ei_org >= *startp && ei_new >= si_new
2454 						&& ei_org >= 0 && ei_new >= 0)
2455 		{
2456 		    if (((diff_flags & DIFF_IWHITE)
2457 				&& VIM_ISWHITE(line_org[ei_org])
2458 					      && VIM_ISWHITE(line_new[ei_new]))
2459 			    || ((diff_flags & DIFF_IWHITEALL)
2460 				&& (VIM_ISWHITE(line_org[ei_org])
2461 					    || VIM_ISWHITE(line_new[ei_new]))))
2462 		    {
2463 			while (ei_org >= *startp
2464 					     && VIM_ISWHITE(line_org[ei_org]))
2465 			    --ei_org;
2466 			while (ei_new >= si_new
2467 					     && VIM_ISWHITE(line_new[ei_new]))
2468 			    --ei_new;
2469 		    }
2470 		    else
2471 		    {
2472 			p1 = line_org + ei_org;
2473 			p2 = line_new + ei_new;
2474 			p1 -= (*mb_head_off)(line_org, p1);
2475 			p2 -= (*mb_head_off)(line_new, p2);
2476 			if (!diff_equal_char(p1, p2, &l))
2477 			    break;
2478 			ei_org -= l;
2479 			ei_new -= l;
2480 		    }
2481 		}
2482 		if (*endp < ei_org)
2483 		    *endp = ei_org;
2484 	    }
2485 	}
2486 
2487     vim_free(line_org);
2488     return added;
2489 }
2490 
2491 #if defined(FEAT_FOLDING) || defined(PROTO)
2492 /*
2493  * Return TRUE if line "lnum" is not close to a diff block, this line should
2494  * be in a fold.
2495  * Return FALSE if there are no diff blocks at all in this window.
2496  */
2497     int
2498 diff_infold(win_T *wp, linenr_T lnum)
2499 {
2500     int		i;
2501     int		idx = -1;
2502     int		other = FALSE;
2503     diff_T	*dp;
2504 
2505     // Return if 'diff' isn't set.
2506     if (!wp->w_p_diff)
2507 	return FALSE;
2508 
2509     for (i = 0; i < DB_COUNT; ++i)
2510     {
2511 	if (curtab->tp_diffbuf[i] == wp->w_buffer)
2512 	    idx = i;
2513 	else if (curtab->tp_diffbuf[i] != NULL)
2514 	    other = TRUE;
2515     }
2516 
2517     // return here if there are no diffs in the window
2518     if (idx == -1 || !other)
2519 	return FALSE;
2520 
2521     if (curtab->tp_diff_invalid)
2522 	ex_diffupdate(NULL);		// update after a big change
2523 
2524     // Return if there are no diff blocks.  All lines will be folded.
2525     if (curtab->tp_first_diff == NULL)
2526 	return TRUE;
2527 
2528     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
2529     {
2530 	// If this change is below the line there can't be any further match.
2531 	if (dp->df_lnum[idx] - diff_context > lnum)
2532 	    break;
2533 	// If this change ends before the line we have a match.
2534 	if (dp->df_lnum[idx] + dp->df_count[idx] + diff_context > lnum)
2535 	    return FALSE;
2536     }
2537     return TRUE;
2538 }
2539 #endif
2540 
2541 /*
2542  * "dp" and "do" commands.
2543  */
2544     void
2545 nv_diffgetput(int put, long count)
2546 {
2547     exarg_T	ea;
2548     char_u	buf[30];
2549 
2550 #ifdef FEAT_JOB_CHANNEL
2551     if (bt_prompt(curbuf))
2552     {
2553 	vim_beep(BO_OPER);
2554 	return;
2555     }
2556 #endif
2557     if (count == 0)
2558 	ea.arg = (char_u *)"";
2559     else
2560     {
2561 	vim_snprintf((char *)buf, 30, "%ld", count);
2562 	ea.arg = buf;
2563     }
2564     if (put)
2565 	ea.cmdidx = CMD_diffput;
2566     else
2567 	ea.cmdidx = CMD_diffget;
2568     ea.addr_count = 0;
2569     ea.line1 = curwin->w_cursor.lnum;
2570     ea.line2 = curwin->w_cursor.lnum;
2571     ex_diffgetput(&ea);
2572 }
2573 
2574 /*
2575  * ":diffget"
2576  * ":diffput"
2577  */
2578     void
2579 ex_diffgetput(exarg_T *eap)
2580 {
2581     linenr_T	lnum;
2582     int		count;
2583     linenr_T	off = 0;
2584     diff_T	*dp;
2585     diff_T	*dprev;
2586     diff_T	*dfree;
2587     int		idx_cur;
2588     int		idx_other;
2589     int		idx_from;
2590     int		idx_to;
2591     int		i;
2592     int		added;
2593     char_u	*p;
2594     aco_save_T	aco;
2595     buf_T	*buf;
2596     int		start_skip, end_skip;
2597     int		new_count;
2598     int		buf_empty;
2599     int		found_not_ma = FALSE;
2600 
2601     // Find the current buffer in the list of diff buffers.
2602     idx_cur = diff_buf_idx(curbuf);
2603     if (idx_cur == DB_COUNT)
2604     {
2605 	emsg(_("E99: Current buffer is not in diff mode"));
2606 	return;
2607     }
2608 
2609     if (*eap->arg == NUL)
2610     {
2611 	// No argument: Find the other buffer in the list of diff buffers.
2612 	for (idx_other = 0; idx_other < DB_COUNT; ++idx_other)
2613 	    if (curtab->tp_diffbuf[idx_other] != curbuf
2614 		    && curtab->tp_diffbuf[idx_other] != NULL)
2615 	    {
2616 		if (eap->cmdidx != CMD_diffput
2617 				     || curtab->tp_diffbuf[idx_other]->b_p_ma)
2618 		    break;
2619 		found_not_ma = TRUE;
2620 	    }
2621 	if (idx_other == DB_COUNT)
2622 	{
2623 	    if (found_not_ma)
2624 		emsg(_("E793: No other buffer in diff mode is modifiable"));
2625 	    else
2626 		emsg(_("E100: No other buffer in diff mode"));
2627 	    return;
2628 	}
2629 
2630 	// Check that there isn't a third buffer in the list
2631 	for (i = idx_other + 1; i < DB_COUNT; ++i)
2632 	    if (curtab->tp_diffbuf[i] != curbuf
2633 		    && curtab->tp_diffbuf[i] != NULL
2634 		    && (eap->cmdidx != CMD_diffput || curtab->tp_diffbuf[i]->b_p_ma))
2635 	    {
2636 		emsg(_("E101: More than two buffers in diff mode, don't know which one to use"));
2637 		return;
2638 	    }
2639     }
2640     else
2641     {
2642 	// Buffer number or pattern given.  Ignore trailing white space.
2643 	p = eap->arg + STRLEN(eap->arg);
2644 	while (p > eap->arg && VIM_ISWHITE(p[-1]))
2645 	    --p;
2646 	for (i = 0; vim_isdigit(eap->arg[i]) && eap->arg + i < p; ++i)
2647 	    ;
2648 	if (eap->arg + i == p)	    // digits only
2649 	    i = atol((char *)eap->arg);
2650 	else
2651 	{
2652 	    i = buflist_findpat(eap->arg, p, FALSE, TRUE, FALSE);
2653 	    if (i < 0)
2654 		return;		// error message already given
2655 	}
2656 	buf = buflist_findnr(i);
2657 	if (buf == NULL)
2658 	{
2659 	    semsg(_("E102: Can't find buffer \"%s\""), eap->arg);
2660 	    return;
2661 	}
2662 	if (buf == curbuf)
2663 	    return;		// nothing to do
2664 	idx_other = diff_buf_idx(buf);
2665 	if (idx_other == DB_COUNT)
2666 	{
2667 	    semsg(_("E103: Buffer \"%s\" is not in diff mode"), eap->arg);
2668 	    return;
2669 	}
2670     }
2671 
2672     diff_busy = TRUE;
2673 
2674     // When no range given include the line above or below the cursor.
2675     if (eap->addr_count == 0)
2676     {
2677 	// Make it possible that ":diffget" on the last line gets line below
2678 	// the cursor line when there is no difference above the cursor.
2679 	if (eap->cmdidx == CMD_diffget
2680 		&& eap->line1 == curbuf->b_ml.ml_line_count
2681 		&& diff_check(curwin, eap->line1) == 0
2682 		&& (eap->line1 == 1 || diff_check(curwin, eap->line1 - 1) == 0))
2683 	    ++eap->line2;
2684 	else if (eap->line1 > 0)
2685 	    --eap->line1;
2686     }
2687 
2688     if (eap->cmdidx == CMD_diffget)
2689     {
2690 	idx_from = idx_other;
2691 	idx_to = idx_cur;
2692     }
2693     else
2694     {
2695 	idx_from = idx_cur;
2696 	idx_to = idx_other;
2697 	// Need to make the other buffer the current buffer to be able to make
2698 	// changes in it.
2699 	// set curwin/curbuf to buf and save a few things
2700 	aucmd_prepbuf(&aco, curtab->tp_diffbuf[idx_other]);
2701     }
2702 
2703     // May give the warning for a changed buffer here, which can trigger the
2704     // FileChangedRO autocommand, which may do nasty things and mess
2705     // everything up.
2706     if (!curbuf->b_changed)
2707     {
2708 	change_warning(0);
2709 	if (diff_buf_idx(curbuf) != idx_to)
2710 	{
2711 	    emsg(_("E787: Buffer changed unexpectedly"));
2712 	    goto theend;
2713 	}
2714     }
2715 
2716     dprev = NULL;
2717     for (dp = curtab->tp_first_diff; dp != NULL; )
2718     {
2719 	if (dp->df_lnum[idx_cur] > eap->line2 + off)
2720 	    break;	// past the range that was specified
2721 
2722 	dfree = NULL;
2723 	lnum = dp->df_lnum[idx_to];
2724 	count = dp->df_count[idx_to];
2725 	if (dp->df_lnum[idx_cur] + dp->df_count[idx_cur] > eap->line1 + off
2726 		&& u_save(lnum - 1, lnum + count) != FAIL)
2727 	{
2728 	    // Inside the specified range and saving for undo worked.
2729 	    start_skip = 0;
2730 	    end_skip = 0;
2731 	    if (eap->addr_count > 0)
2732 	    {
2733 		// A range was specified: check if lines need to be skipped.
2734 		start_skip = eap->line1 + off - dp->df_lnum[idx_cur];
2735 		if (start_skip > 0)
2736 		{
2737 		    // range starts below start of current diff block
2738 		    if (start_skip > count)
2739 		    {
2740 			lnum += count;
2741 			count = 0;
2742 		    }
2743 		    else
2744 		    {
2745 			count -= start_skip;
2746 			lnum += start_skip;
2747 		    }
2748 		}
2749 		else
2750 		    start_skip = 0;
2751 
2752 		end_skip = dp->df_lnum[idx_cur] + dp->df_count[idx_cur] - 1
2753 							 - (eap->line2 + off);
2754 		if (end_skip > 0)
2755 		{
2756 		    // range ends above end of current/from diff block
2757 		    if (idx_cur == idx_from)	// :diffput
2758 		    {
2759 			i = dp->df_count[idx_cur] - start_skip - end_skip;
2760 			if (count > i)
2761 			    count = i;
2762 		    }
2763 		    else			// :diffget
2764 		    {
2765 			count -= end_skip;
2766 			end_skip = dp->df_count[idx_from] - start_skip - count;
2767 			if (end_skip < 0)
2768 			    end_skip = 0;
2769 		    }
2770 		}
2771 		else
2772 		    end_skip = 0;
2773 	    }
2774 
2775 	    buf_empty = BUFEMPTY();
2776 	    added = 0;
2777 	    for (i = 0; i < count; ++i)
2778 	    {
2779 		// remember deleting the last line of the buffer
2780 		buf_empty = curbuf->b_ml.ml_line_count == 1;
2781 		ml_delete(lnum);
2782 		--added;
2783 	    }
2784 	    for (i = 0; i < dp->df_count[idx_from] - start_skip - end_skip; ++i)
2785 	    {
2786 		linenr_T nr;
2787 
2788 		nr = dp->df_lnum[idx_from] + start_skip + i;
2789 		if (nr > curtab->tp_diffbuf[idx_from]->b_ml.ml_line_count)
2790 		    break;
2791 		p = vim_strsave(ml_get_buf(curtab->tp_diffbuf[idx_from],
2792 								  nr, FALSE));
2793 		if (p != NULL)
2794 		{
2795 		    ml_append(lnum + i - 1, p, 0, FALSE);
2796 		    vim_free(p);
2797 		    ++added;
2798 		    if (buf_empty && curbuf->b_ml.ml_line_count == 2)
2799 		    {
2800 			// Added the first line into an empty buffer, need to
2801 			// delete the dummy empty line.
2802 			buf_empty = FALSE;
2803 			ml_delete((linenr_T)2);
2804 		    }
2805 		}
2806 	    }
2807 	    new_count = dp->df_count[idx_to] + added;
2808 	    dp->df_count[idx_to] = new_count;
2809 
2810 	    if (start_skip == 0 && end_skip == 0)
2811 	    {
2812 		// Check if there are any other buffers and if the diff is
2813 		// equal in them.
2814 		for (i = 0; i < DB_COUNT; ++i)
2815 		    if (curtab->tp_diffbuf[i] != NULL && i != idx_from
2816 								&& i != idx_to
2817 			    && !diff_equal_entry(dp, idx_from, i))
2818 			break;
2819 		if (i == DB_COUNT)
2820 		{
2821 		    // delete the diff entry, the buffers are now equal here
2822 		    dfree = dp;
2823 		    dp = dp->df_next;
2824 		    if (dprev == NULL)
2825 			curtab->tp_first_diff = dp;
2826 		    else
2827 			dprev->df_next = dp;
2828 		}
2829 	    }
2830 
2831 	    // Adjust marks.  This will change the following entries!
2832 	    if (added != 0)
2833 	    {
2834 		mark_adjust(lnum, lnum + count - 1, (long)MAXLNUM, (long)added);
2835 		if (curwin->w_cursor.lnum >= lnum)
2836 		{
2837 		    // Adjust the cursor position if it's in/after the changed
2838 		    // lines.
2839 		    if (curwin->w_cursor.lnum >= lnum + count)
2840 			curwin->w_cursor.lnum += added;
2841 		    else if (added < 0)
2842 			curwin->w_cursor.lnum = lnum;
2843 		}
2844 	    }
2845 	    changed_lines(lnum, 0, lnum + count, (long)added);
2846 
2847 	    if (dfree != NULL)
2848 	    {
2849 		// Diff is deleted, update folds in other windows.
2850 #ifdef FEAT_FOLDING
2851 		diff_fold_update(dfree, idx_to);
2852 #endif
2853 		vim_free(dfree);
2854 	    }
2855 	    else
2856 		// mark_adjust() may have changed the count in a wrong way
2857 		dp->df_count[idx_to] = new_count;
2858 
2859 	    // When changing the current buffer, keep track of line numbers
2860 	    if (idx_cur == idx_to)
2861 		off += added;
2862 	}
2863 
2864 	// If before the range or not deleted, go to next diff.
2865 	if (dfree == NULL)
2866 	{
2867 	    dprev = dp;
2868 	    dp = dp->df_next;
2869 	}
2870     }
2871 
2872     // restore curwin/curbuf and a few other things
2873     if (eap->cmdidx != CMD_diffget)
2874     {
2875 	// Syncing undo only works for the current buffer, but we change
2876 	// another buffer.  Sync undo if the command was typed.  This isn't
2877 	// 100% right when ":diffput" is used in a function or mapping.
2878 	if (KeyTyped)
2879 	    u_sync(FALSE);
2880 	aucmd_restbuf(&aco);
2881     }
2882 
2883 theend:
2884     diff_busy = FALSE;
2885     if (diff_need_update)
2886 	ex_diffupdate(NULL);
2887 
2888     // Check that the cursor is on a valid character and update its
2889     // position.  When there were filler lines the topline has become
2890     // invalid.
2891     check_cursor();
2892     changed_line_abv_curs();
2893 
2894     if (diff_need_update)
2895 	// redraw already done by ex_diffupdate()
2896 	diff_need_update = FALSE;
2897     else
2898     {
2899 	// Also need to redraw the other buffers.
2900 	diff_redraw(FALSE);
2901 	apply_autocmds(EVENT_DIFFUPDATED, NULL, NULL, FALSE, curbuf);
2902     }
2903 }
2904 
2905 #ifdef FEAT_FOLDING
2906 /*
2907  * Update folds for all diff buffers for entry "dp".
2908  * Skip buffer with index "skip_idx".
2909  * When there are no diffs, all folds are removed.
2910  */
2911     static void
2912 diff_fold_update(diff_T *dp, int skip_idx)
2913 {
2914     int		i;
2915     win_T	*wp;
2916 
2917     FOR_ALL_WINDOWS(wp)
2918 	for (i = 0; i < DB_COUNT; ++i)
2919 	    if (curtab->tp_diffbuf[i] == wp->w_buffer && i != skip_idx)
2920 		foldUpdate(wp, dp->df_lnum[i],
2921 					    dp->df_lnum[i] + dp->df_count[i]);
2922 }
2923 #endif
2924 
2925 /*
2926  * Return TRUE if buffer "buf" is in diff-mode.
2927  */
2928     int
2929 diff_mode_buf(buf_T *buf)
2930 {
2931     tabpage_T	*tp;
2932 
2933     FOR_ALL_TABPAGES(tp)
2934 	if (diff_buf_idx_tp(buf, tp) != DB_COUNT)
2935 	    return TRUE;
2936     return FALSE;
2937 }
2938 
2939 /*
2940  * Move "count" times in direction "dir" to the next diff block.
2941  * Return FAIL if there isn't such a diff block.
2942  */
2943     int
2944 diff_move_to(int dir, long count)
2945 {
2946     int		idx;
2947     linenr_T	lnum = curwin->w_cursor.lnum;
2948     diff_T	*dp;
2949 
2950     idx = diff_buf_idx(curbuf);
2951     if (idx == DB_COUNT || curtab->tp_first_diff == NULL)
2952 	return FAIL;
2953 
2954     if (curtab->tp_diff_invalid)
2955 	ex_diffupdate(NULL);		// update after a big change
2956 
2957     if (curtab->tp_first_diff == NULL)		// no diffs today
2958 	return FAIL;
2959 
2960     while (--count >= 0)
2961     {
2962 	// Check if already before first diff.
2963 	if (dir == BACKWARD && lnum <= curtab->tp_first_diff->df_lnum[idx])
2964 	    break;
2965 
2966 	for (dp = curtab->tp_first_diff; ; dp = dp->df_next)
2967 	{
2968 	    if (dp == NULL)
2969 		break;
2970 	    if ((dir == FORWARD && lnum < dp->df_lnum[idx])
2971 		    || (dir == BACKWARD
2972 			&& (dp->df_next == NULL
2973 			    || lnum <= dp->df_next->df_lnum[idx])))
2974 	    {
2975 		lnum = dp->df_lnum[idx];
2976 		break;
2977 	    }
2978 	}
2979     }
2980 
2981     // don't end up past the end of the file
2982     if (lnum > curbuf->b_ml.ml_line_count)
2983 	lnum = curbuf->b_ml.ml_line_count;
2984 
2985     // When the cursor didn't move at all we fail.
2986     if (lnum == curwin->w_cursor.lnum)
2987 	return FAIL;
2988 
2989     setpcmark();
2990     curwin->w_cursor.lnum = lnum;
2991     curwin->w_cursor.col = 0;
2992 
2993     return OK;
2994 }
2995 
2996 /*
2997  * Return the line number in the current window that is closest to "lnum1" in
2998  * "buf1" in diff mode.
2999  */
3000     static linenr_T
3001 diff_get_corresponding_line_int(
3002     buf_T	*buf1,
3003     linenr_T	lnum1)
3004 {
3005     int		idx1;
3006     int		idx2;
3007     diff_T	*dp;
3008     int		baseline = 0;
3009 
3010     idx1 = diff_buf_idx(buf1);
3011     idx2 = diff_buf_idx(curbuf);
3012     if (idx1 == DB_COUNT || idx2 == DB_COUNT || curtab->tp_first_diff == NULL)
3013 	return lnum1;
3014 
3015     if (curtab->tp_diff_invalid)
3016 	ex_diffupdate(NULL);		// update after a big change
3017 
3018     if (curtab->tp_first_diff == NULL)		// no diffs today
3019 	return lnum1;
3020 
3021     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
3022     {
3023 	if (dp->df_lnum[idx1] > lnum1)
3024 	    return lnum1 - baseline;
3025 	if ((dp->df_lnum[idx1] + dp->df_count[idx1]) > lnum1)
3026 	{
3027 	    // Inside the diffblock
3028 	    baseline = lnum1 - dp->df_lnum[idx1];
3029 	    if (baseline > dp->df_count[idx2])
3030 		baseline = dp->df_count[idx2];
3031 
3032 	    return dp->df_lnum[idx2] + baseline;
3033 	}
3034 	if (    (dp->df_lnum[idx1] == lnum1)
3035 	     && (dp->df_count[idx1] == 0)
3036 	     && (dp->df_lnum[idx2] <= curwin->w_cursor.lnum)
3037 	     && ((dp->df_lnum[idx2] + dp->df_count[idx2])
3038 						      > curwin->w_cursor.lnum))
3039 	    /*
3040 	     * Special case: if the cursor is just after a zero-count
3041 	     * block (i.e. all filler) and the target cursor is already
3042 	     * inside the corresponding block, leave the target cursor
3043 	     * unmoved. This makes repeated CTRL-W W operations work
3044 	     * as expected.
3045 	     */
3046 	    return curwin->w_cursor.lnum;
3047 	baseline = (dp->df_lnum[idx1] + dp->df_count[idx1])
3048 				   - (dp->df_lnum[idx2] + dp->df_count[idx2]);
3049     }
3050 
3051     // If we get here then the cursor is after the last diff
3052     return lnum1 - baseline;
3053 }
3054 
3055 /*
3056  * Return the line number in the current window that is closest to "lnum1" in
3057  * "buf1" in diff mode.  Checks the line number to be valid.
3058  */
3059     linenr_T
3060 diff_get_corresponding_line(buf_T *buf1, linenr_T lnum1)
3061 {
3062     linenr_T lnum = diff_get_corresponding_line_int(buf1, lnum1);
3063 
3064     // don't end up past the end of the file
3065     if (lnum > curbuf->b_ml.ml_line_count)
3066 	return curbuf->b_ml.ml_line_count;
3067     return lnum;
3068 }
3069 
3070 /*
3071  * For line "lnum" in the current window find the equivalent lnum in window
3072  * "wp", compensating for inserted/deleted lines.
3073  */
3074     linenr_T
3075 diff_lnum_win(linenr_T lnum, win_T *wp)
3076 {
3077     diff_T	*dp;
3078     int		idx;
3079     int		i;
3080     linenr_T	n;
3081 
3082     idx = diff_buf_idx(curbuf);
3083     if (idx == DB_COUNT)		// safety check
3084 	return (linenr_T)0;
3085 
3086     if (curtab->tp_diff_invalid)
3087 	ex_diffupdate(NULL);		// update after a big change
3088 
3089     // search for a change that includes "lnum" in the list of diffblocks.
3090     FOR_ALL_DIFFBLOCKS_IN_TAB(curtab, dp)
3091 	if (lnum <= dp->df_lnum[idx] + dp->df_count[idx])
3092 	    break;
3093 
3094     // When after the last change, compute relative to the last line number.
3095     if (dp == NULL)
3096 	return wp->w_buffer->b_ml.ml_line_count
3097 					- (curbuf->b_ml.ml_line_count - lnum);
3098 
3099     // Find index for "wp".
3100     i = diff_buf_idx(wp->w_buffer);
3101     if (i == DB_COUNT)			// safety check
3102 	return (linenr_T)0;
3103 
3104     n = lnum + (dp->df_lnum[i] - dp->df_lnum[idx]);
3105     if (n > dp->df_lnum[i] + dp->df_count[i])
3106 	n = dp->df_lnum[i] + dp->df_count[i];
3107     return n;
3108 }
3109 
3110 /*
3111  * Handle an ED style diff line.
3112  * Return FAIL if the line does not contain diff info.
3113  */
3114     static int
3115 parse_diff_ed(
3116 	char_u	    *line,
3117 	linenr_T    *lnum_orig,
3118 	long	    *count_orig,
3119 	linenr_T    *lnum_new,
3120 	long	    *count_new)
3121 {
3122     char_u *p;
3123     long    f1, l1, f2, l2;
3124     int	    difftype;
3125 
3126     // The line must be one of three formats:
3127     // change: {first}[,{last}]c{first}[,{last}]
3128     // append: {first}a{first}[,{last}]
3129     // delete: {first}[,{last}]d{first}
3130     p = line;
3131     f1 = getdigits(&p);
3132     if (*p == ',')
3133     {
3134 	++p;
3135 	l1 = getdigits(&p);
3136     }
3137     else
3138 	l1 = f1;
3139     if (*p != 'a' && *p != 'c' && *p != 'd')
3140 	return FAIL;		// invalid diff format
3141     difftype = *p++;
3142     f2 = getdigits(&p);
3143     if (*p == ',')
3144     {
3145 	++p;
3146 	l2 = getdigits(&p);
3147     }
3148     else
3149 	l2 = f2;
3150     if (l1 < f1 || l2 < f2)
3151 	return FAIL;
3152 
3153     if (difftype == 'a')
3154     {
3155 	*lnum_orig = f1 + 1;
3156 	*count_orig = 0;
3157     }
3158     else
3159     {
3160 	*lnum_orig = f1;
3161 	*count_orig = l1 - f1 + 1;
3162     }
3163     if (difftype == 'd')
3164     {
3165 	*lnum_new = f2 + 1;
3166 	*count_new = 0;
3167     }
3168     else
3169     {
3170 	*lnum_new = f2;
3171 	*count_new = l2 - f2 + 1;
3172     }
3173     return OK;
3174 }
3175 
3176 /*
3177  * Parses unified diff with zero(!) context lines.
3178  * Return FAIL if there is no diff information in "line".
3179  */
3180     static int
3181 parse_diff_unified(
3182 	char_u	    *line,
3183 	linenr_T    *lnum_orig,
3184 	long	    *count_orig,
3185 	linenr_T    *lnum_new,
3186 	long	    *count_new)
3187 {
3188     char_u *p;
3189     long    oldline, oldcount, newline, newcount;
3190 
3191     // Parse unified diff hunk header:
3192     // @@ -oldline,oldcount +newline,newcount @@
3193     p = line;
3194     if (*p++ == '@' && *p++ == '@' && *p++ == ' ' && *p++ == '-')
3195     {
3196 	oldline = getdigits(&p);
3197 	if (*p == ',')
3198 	{
3199 	    ++p;
3200 	    oldcount = getdigits(&p);
3201 	}
3202 	else
3203 	    oldcount = 1;
3204 	if (*p++ == ' ' && *p++ == '+')
3205 	{
3206 	    newline = getdigits(&p);
3207 	    if (*p == ',')
3208 	    {
3209 		++p;
3210 		newcount = getdigits(&p);
3211 	    }
3212 	    else
3213 		newcount = 1;
3214 	}
3215 	else
3216 	    return FAIL;	// invalid diff format
3217 
3218 	if (oldcount == 0)
3219 	    oldline += 1;
3220 	if (newcount == 0)
3221 	    newline += 1;
3222 	if (newline == 0)
3223 	    newline = 1;
3224 
3225 	*lnum_orig = oldline;
3226 	*count_orig = oldcount;
3227 	*lnum_new = newline;
3228 	*count_new = newcount;
3229 
3230 	return OK;
3231     }
3232 
3233     return FAIL;
3234 }
3235 
3236 /*
3237  * Callback function for the xdl_diff() function.
3238  * Stores the diff output in a grow array.
3239  */
3240     static int
3241 xdiff_out(void *priv, mmbuffer_t *mb, int nbuf)
3242 {
3243     diffout_T	*dout = (diffout_T *)priv;
3244     char_u	*p;
3245 
3246     // The header line always comes by itself, text lines in at least two
3247     // parts.  We drop the text part.
3248     if (nbuf > 1)
3249 	return 0;
3250 
3251     // sanity check
3252     if (STRNCMP(mb[0].ptr, "@@ ", 3)  != 0)
3253 	return 0;
3254 
3255     if (ga_grow(&dout->dout_ga, 1) == FAIL)
3256 	return -1;
3257     p = vim_strnsave((char_u *)mb[0].ptr, mb[0].size);
3258     if (p == NULL)
3259 	return -1;
3260     ((char_u **)dout->dout_ga.ga_data)[dout->dout_ga.ga_len++] = p;
3261     return 0;
3262 }
3263 
3264 #endif	// FEAT_DIFF
3265 
3266 #if defined(FEAT_EVAL) || defined(PROTO)
3267 
3268 /*
3269  * "diff_filler()" function
3270  */
3271     void
3272 f_diff_filler(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
3273 {
3274 #ifdef FEAT_DIFF
3275     rettv->vval.v_number = diff_check_fill(curwin, tv_get_lnum(argvars));
3276 #endif
3277 }
3278 
3279 /*
3280  * "diff_hlID()" function
3281  */
3282     void
3283 f_diff_hlID(typval_T *argvars UNUSED, typval_T *rettv UNUSED)
3284 {
3285 #ifdef FEAT_DIFF
3286     linenr_T		lnum = tv_get_lnum(argvars);
3287     static linenr_T	prev_lnum = 0;
3288     static varnumber_T	changedtick = 0;
3289     static int		fnum = 0;
3290     static int		change_start = 0;
3291     static int		change_end = 0;
3292     static hlf_T	hlID = (hlf_T)0;
3293     int			filler_lines;
3294     int			col;
3295 
3296     if (lnum < 0)	// ignore type error in {lnum} arg
3297 	lnum = 0;
3298     if (lnum != prev_lnum
3299 	    || changedtick != CHANGEDTICK(curbuf)
3300 	    || fnum != curbuf->b_fnum)
3301     {
3302 	// New line, buffer, change: need to get the values.
3303 	filler_lines = diff_check(curwin, lnum);
3304 	if (filler_lines < 0)
3305 	{
3306 	    if (filler_lines == -1)
3307 	    {
3308 		change_start = MAXCOL;
3309 		change_end = -1;
3310 		if (diff_find_change(curwin, lnum, &change_start, &change_end))
3311 		    hlID = HLF_ADD;	// added line
3312 		else
3313 		    hlID = HLF_CHD;	// changed line
3314 	    }
3315 	    else
3316 		hlID = HLF_ADD;	// added line
3317 	}
3318 	else
3319 	    hlID = (hlf_T)0;
3320 	prev_lnum = lnum;
3321 	changedtick = CHANGEDTICK(curbuf);
3322 	fnum = curbuf->b_fnum;
3323     }
3324 
3325     if (hlID == HLF_CHD || hlID == HLF_TXD)
3326     {
3327 	col = tv_get_number(&argvars[1]) - 1; // ignore type error in {col}
3328 	if (col >= change_start && col <= change_end)
3329 	    hlID = HLF_TXD;			// changed text
3330 	else
3331 	    hlID = HLF_CHD;			// changed line
3332     }
3333     rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
3334 #endif
3335 }
3336 
3337 #endif
3338