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