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