xref: /vim-8.2.3635/src/undo.c (revision c024b466)
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  * undo.c: multi level undo facility
12  *
13  * The saved lines are stored in a list of lists (one for each buffer):
14  *
15  * b_u_oldhead------------------------------------------------+
16  *							      |
17  *							      V
18  *		  +--------------+    +--------------+	  +--------------+
19  * b_u_newhead--->| u_header	 |    | u_header     |	  | u_header	 |
20  *		  |	uh_next------>|     uh_next------>|	uh_next---->NULL
21  *	   NULL<--------uh_prev  |<---------uh_prev  |<---------uh_prev  |
22  *		  |	uh_entry |    |     uh_entry |	  |	uh_entry |
23  *		  +--------|-----+    +--------|-----+	  +--------|-----+
24  *			   |		       |		   |
25  *			   V		       V		   V
26  *		  +--------------+    +--------------+	  +--------------+
27  *		  | u_entry	 |    | u_entry      |	  | u_entry	 |
28  *		  |	ue_next  |    |     ue_next  |	  |	ue_next  |
29  *		  +--------|-----+    +--------|-----+	  +--------|-----+
30  *			   |		       |		   |
31  *			   V		       V		   V
32  *		  +--------------+	      NULL		  NULL
33  *		  | u_entry	 |
34  *		  |	ue_next  |
35  *		  +--------|-----+
36  *			   |
37  *			   V
38  *			  etc.
39  *
40  * Each u_entry list contains the information for one undo or redo.
41  * curbuf->b_u_curhead points to the header of the last undo (the next redo),
42  * or is NULL if nothing has been undone (end of the branch).
43  *
44  * For keeping alternate undo/redo branches the uh_alt field is used.  Thus at
45  * each point in the list a branch may appear for an alternate to redo.  The
46  * uh_seq field is numbered sequentially to be able to find a newer or older
47  * branch.
48  *
49  *		   +---------------+	+---------------+
50  * b_u_oldhead --->| u_header	   |	| u_header	|
51  *		   |   uh_alt_next ---->|   uh_alt_next ----> NULL
52  *	   NULL <----- uh_alt_prev |<------ uh_alt_prev |
53  *		   |   uh_prev	   |	|   uh_prev	|
54  *		   +-----|---------+	+-----|---------+
55  *			 |		      |
56  *			 V		      V
57  *		   +---------------+	+---------------+
58  *		   | u_header	   |	| u_header	|
59  *		   |   uh_alt_next |	|   uh_alt_next |
60  * b_u_newhead --->|   uh_alt_prev |	|   uh_alt_prev |
61  *		   |   uh_prev	   |	|   uh_prev	|
62  *		   +-----|---------+	+-----|---------+
63  *			 |		      |
64  *			 V		      V
65  *		       NULL		+---------------+    +---------------+
66  *					| u_header	|    | u_header      |
67  *					|   uh_alt_next ---->|	 uh_alt_next |
68  *					|   uh_alt_prev |<------ uh_alt_prev |
69  *					|   uh_prev	|    |	 uh_prev     |
70  *					+-----|---------+    +-----|---------+
71  *					      |			   |
72  *					     etc.		  etc.
73  *
74  *
75  * All data is allocated and will all be freed when the buffer is unloaded.
76  */
77 
78 /* Uncomment the next line for including the u_check() function.  This warns
79  * for errors in the debug information. */
80 /* #define U_DEBUG 1 */
81 #define UH_MAGIC 0x18dade	/* value for uh_magic when in use */
82 #define UE_MAGIC 0xabc123	/* value for ue_magic when in use */
83 
84 /* Size of buffer used for encryption. */
85 #define CRYPT_BUF_SIZE 8192
86 
87 #include "vim.h"
88 
89 /* Structure passed around between functions.
90  * Avoids passing cryptstate_T when encryption not available. */
91 typedef struct {
92     buf_T	*bi_buf;
93     FILE	*bi_fp;
94 #ifdef FEAT_CRYPT
95     cryptstate_T *bi_state;
96     char_u	*bi_buffer; /* CRYPT_BUF_SIZE, NULL when not buffering */
97     size_t	bi_used;    /* bytes written to/read from bi_buffer */
98     size_t	bi_avail;   /* bytes available in bi_buffer */
99 #endif
100 } bufinfo_T;
101 
102 
103 static void u_unch_branch(u_header_T *uhp);
104 static u_entry_T *u_get_headentry(void);
105 static void u_getbot(void);
106 static void u_doit(int count);
107 static void u_undoredo(int undo);
108 static void u_undo_end(int did_undo, int absolute);
109 static void u_add_time(char_u *buf, size_t buflen, time_t tt);
110 static void u_freeheader(buf_T *buf, u_header_T *uhp, u_header_T **uhpp);
111 static void u_freebranch(buf_T *buf, u_header_T *uhp, u_header_T **uhpp);
112 static void u_freeentries(buf_T *buf, u_header_T *uhp, u_header_T **uhpp);
113 static void u_freeentry(u_entry_T *, long);
114 #ifdef FEAT_PERSISTENT_UNDO
115 # ifdef FEAT_CRYPT
116 static int undo_flush(bufinfo_T *bi);
117 # endif
118 static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size);
119 static int serialize_uep(bufinfo_T *bi, u_entry_T *uep);
120 static u_entry_T *unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name);
121 static void serialize_pos(bufinfo_T *bi, pos_T pos);
122 static void unserialize_pos(bufinfo_T *bi, pos_T *pos);
123 static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info);
124 static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info);
125 #endif
126 
127 #define U_ALLOC_LINE(size) lalloc(size, FALSE)
128 
129 /* used in undo_end() to report number of added and deleted lines */
130 static long	u_newcount, u_oldcount;
131 
132 /*
133  * When 'u' flag included in 'cpoptions', we behave like vi.  Need to remember
134  * the action that "u" should do.
135  */
136 static int	undo_undoes = FALSE;
137 
138 static int	lastmark = 0;
139 
140 #if defined(U_DEBUG) || defined(PROTO)
141 /*
142  * Check the undo structures for being valid.  Print a warning when something
143  * looks wrong.
144  */
145 static int seen_b_u_curhead;
146 static int seen_b_u_newhead;
147 static int header_count;
148 
149     static void
150 u_check_tree(u_header_T *uhp,
151 	u_header_T *exp_uh_next,
152 	u_header_T *exp_uh_alt_prev)
153 {
154     u_entry_T *uep;
155 
156     if (uhp == NULL)
157 	return;
158     ++header_count;
159     if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1)
160     {
161 	emsg("b_u_curhead found twice (looping?)");
162 	return;
163     }
164     if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1)
165     {
166 	emsg("b_u_newhead found twice (looping?)");
167 	return;
168     }
169 
170     if (uhp->uh_magic != UH_MAGIC)
171 	emsg("uh_magic wrong (may be using freed memory)");
172     else
173     {
174 	/* Check pointers back are correct. */
175 	if (uhp->uh_next.ptr != exp_uh_next)
176 	{
177 	    emsg("uh_next wrong");
178 	    smsg("expected: 0x%x, actual: 0x%x",
179 					       exp_uh_next, uhp->uh_next.ptr);
180 	}
181 	if (uhp->uh_alt_prev.ptr != exp_uh_alt_prev)
182 	{
183 	    emsg("uh_alt_prev wrong");
184 	    smsg("expected: 0x%x, actual: 0x%x",
185 				       exp_uh_alt_prev, uhp->uh_alt_prev.ptr);
186 	}
187 
188 	/* Check the undo tree at this header. */
189 	for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next)
190 	{
191 	    if (uep->ue_magic != UE_MAGIC)
192 	    {
193 		emsg("ue_magic wrong (may be using freed memory)");
194 		break;
195 	    }
196 	}
197 
198 	/* Check the next alt tree. */
199 	u_check_tree(uhp->uh_alt_next.ptr, uhp->uh_next.ptr, uhp);
200 
201 	/* Check the next header in this branch. */
202 	u_check_tree(uhp->uh_prev.ptr, uhp, NULL);
203     }
204 }
205 
206     static void
207 u_check(int newhead_may_be_NULL)
208 {
209     seen_b_u_newhead = 0;
210     seen_b_u_curhead = 0;
211     header_count = 0;
212 
213     u_check_tree(curbuf->b_u_oldhead, NULL, NULL);
214 
215     if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL
216 	    && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL))
217 	semsg("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead);
218     if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0)
219 	semsg("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead);
220     if (header_count != curbuf->b_u_numhead)
221     {
222 	emsg("b_u_numhead invalid");
223 	smsg("expected: %ld, actual: %ld",
224 			       (long)header_count, (long)curbuf->b_u_numhead);
225     }
226 }
227 #endif
228 
229 /*
230  * Save the current line for both the "u" and "U" command.
231  * Careful: may trigger autocommands that reload the buffer.
232  * Returns OK or FAIL.
233  */
234     int
235 u_save_cursor(void)
236 {
237     return (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
238 				      (linenr_T)(curwin->w_cursor.lnum + 1)));
239 }
240 
241 /*
242  * Save the lines between "top" and "bot" for both the "u" and "U" command.
243  * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1.
244  * Careful: may trigger autocommands that reload the buffer.
245  * Returns FAIL when lines could not be saved, OK otherwise.
246  */
247     int
248 u_save(linenr_T top, linenr_T bot)
249 {
250     if (undo_off)
251 	return OK;
252 
253     if (top >= bot || bot > curbuf->b_ml.ml_line_count + 1)
254 	return FAIL;	// rely on caller to give an error message
255 
256     if (top + 2 == bot)
257 	u_saveline((linenr_T)(top + 1));
258 
259     return (u_savecommon(top, bot, (linenr_T)0, FALSE));
260 }
261 
262 /*
263  * Save the line "lnum" (used by ":s" and "~" command).
264  * The line is replaced, so the new bottom line is lnum + 1.
265  * Careful: may trigger autocommands that reload the buffer.
266  * Returns FAIL when lines could not be saved, OK otherwise.
267  */
268     int
269 u_savesub(linenr_T lnum)
270 {
271     if (undo_off)
272 	return OK;
273 
274     return (u_savecommon(lnum - 1, lnum + 1, lnum + 1, FALSE));
275 }
276 
277 /*
278  * A new line is inserted before line "lnum" (used by :s command).
279  * The line is inserted, so the new bottom line is lnum + 1.
280  * Careful: may trigger autocommands that reload the buffer.
281  * Returns FAIL when lines could not be saved, OK otherwise.
282  */
283     int
284 u_inssub(linenr_T lnum)
285 {
286     if (undo_off)
287 	return OK;
288 
289     return (u_savecommon(lnum - 1, lnum, lnum + 1, FALSE));
290 }
291 
292 /*
293  * Save the lines "lnum" - "lnum" + nlines (used by delete command).
294  * The lines are deleted, so the new bottom line is lnum, unless the buffer
295  * becomes empty.
296  * Careful: may trigger autocommands that reload the buffer.
297  * Returns FAIL when lines could not be saved, OK otherwise.
298  */
299     int
300 u_savedel(linenr_T lnum, long nlines)
301 {
302     if (undo_off)
303 	return OK;
304 
305     return (u_savecommon(lnum - 1, lnum + nlines,
306 		     nlines == curbuf->b_ml.ml_line_count ? 2 : lnum, FALSE));
307 }
308 
309 /*
310  * Return TRUE when undo is allowed.  Otherwise give an error message and
311  * return FALSE.
312  */
313     int
314 undo_allowed(void)
315 {
316     /* Don't allow changes when 'modifiable' is off.  */
317     if (!curbuf->b_p_ma)
318     {
319 	emsg(_(e_modifiable));
320 	return FALSE;
321     }
322 
323 #ifdef HAVE_SANDBOX
324     /* In the sandbox it's not allowed to change the text. */
325     if (sandbox != 0)
326     {
327 	emsg(_(e_sandbox));
328 	return FALSE;
329     }
330 #endif
331 
332     /* Don't allow changes in the buffer while editing the cmdline.  The
333      * caller of getcmdline() may get confused. */
334     if (textlock != 0)
335     {
336 	emsg(_(e_secure));
337 	return FALSE;
338     }
339 
340     return TRUE;
341 }
342 
343 /*
344  * Get the undolevle value for the current buffer.
345  */
346     static long
347 get_undolevel(void)
348 {
349     if (curbuf->b_p_ul == NO_LOCAL_UNDOLEVEL)
350 	return p_ul;
351     return curbuf->b_p_ul;
352 }
353 
354 /*
355  * u_save_line(): save an allocated copy of line "lnum" into "ul".
356  * Returns FAIL when out of memory.
357  */
358     static int
359 u_save_line(undoline_T *ul, linenr_T lnum)
360 {
361     char_u *line = ml_get(lnum);
362 
363     if (curbuf->b_ml.ml_line_len == 0)
364     {
365 	ul->ul_len = 1;
366 	ul->ul_line = vim_strsave((char_u *)"");
367     }
368     else
369     {
370 	// This uses the length in the memline, thus text properties are
371 	// included.
372 	ul->ul_len = curbuf->b_ml.ml_line_len;
373 	ul->ul_line = vim_memsave(line, ul->ul_len);
374     }
375     return ul->ul_line == NULL ? FAIL : OK;
376 }
377 
378 /*
379  * Common code for various ways to save text before a change.
380  * "top" is the line above the first changed line.
381  * "bot" is the line below the last changed line.
382  * "newbot" is the new bottom line.  Use zero when not known.
383  * "reload" is TRUE when saving for a buffer reload.
384  * Careful: may trigger autocommands that reload the buffer.
385  * Returns FAIL when lines could not be saved, OK otherwise.
386  */
387     int
388 u_savecommon(
389     linenr_T	top,
390     linenr_T	bot,
391     linenr_T	newbot,
392     int		reload)
393 {
394     linenr_T	lnum;
395     long	i;
396     u_header_T	*uhp;
397     u_header_T	*old_curhead;
398     u_entry_T	*uep;
399     u_entry_T	*prev_uep;
400     long	size;
401 
402     if (!reload)
403     {
404 	/* When making changes is not allowed return FAIL.  It's a crude way
405 	 * to make all change commands fail. */
406 	if (!undo_allowed())
407 	    return FAIL;
408 
409 #ifdef FEAT_NETBEANS_INTG
410 	/*
411 	 * Netbeans defines areas that cannot be modified.  Bail out here when
412 	 * trying to change text in a guarded area.
413 	 */
414 	if (netbeans_active())
415 	{
416 	    if (netbeans_is_guarded(top, bot))
417 	    {
418 		emsg(_(e_guarded));
419 		return FAIL;
420 	    }
421 	    if (curbuf->b_p_ro)
422 	    {
423 		emsg(_(e_nbreadonly));
424 		return FAIL;
425 	    }
426 	}
427 #endif
428 #ifdef FEAT_TERMINAL
429 	/* A change in a terminal buffer removes the highlighting. */
430 	term_change_in_curbuf();
431 #endif
432 
433 	/*
434 	 * Saving text for undo means we are going to make a change.  Give a
435 	 * warning for a read-only file before making the change, so that the
436 	 * FileChangedRO event can replace the buffer with a read-write version
437 	 * (e.g., obtained from a source control system).
438 	 */
439 	change_warning(0);
440 	if (bot > curbuf->b_ml.ml_line_count + 1)
441 	{
442 	    /* This happens when the FileChangedRO autocommand changes the
443 	     * file in a way it becomes shorter. */
444 	    emsg(_("E881: Line count changed unexpectedly"));
445 	    return FAIL;
446 	}
447     }
448 
449 #ifdef U_DEBUG
450     u_check(FALSE);
451 #endif
452 
453     size = bot - top - 1;
454 
455     /*
456      * If curbuf->b_u_synced == TRUE make a new header.
457      */
458     if (curbuf->b_u_synced)
459     {
460 #ifdef FEAT_JUMPLIST
461 	/* Need to create new entry in b_changelist. */
462 	curbuf->b_new_change = TRUE;
463 #endif
464 
465 	if (get_undolevel() >= 0)
466 	{
467 	    /*
468 	     * Make a new header entry.  Do this first so that we don't mess
469 	     * up the undo info when out of memory.
470 	     */
471 	    uhp = U_ALLOC_LINE(sizeof(u_header_T));
472 	    if (uhp == NULL)
473 		goto nomem;
474 #ifdef U_DEBUG
475 	    uhp->uh_magic = UH_MAGIC;
476 #endif
477 	}
478 	else
479 	    uhp = NULL;
480 
481 	/*
482 	 * If we undid more than we redid, move the entry lists before and
483 	 * including curbuf->b_u_curhead to an alternate branch.
484 	 */
485 	old_curhead = curbuf->b_u_curhead;
486 	if (old_curhead != NULL)
487 	{
488 	    curbuf->b_u_newhead = old_curhead->uh_next.ptr;
489 	    curbuf->b_u_curhead = NULL;
490 	}
491 
492 	/*
493 	 * free headers to keep the size right
494 	 */
495 	while (curbuf->b_u_numhead > get_undolevel()
496 					       && curbuf->b_u_oldhead != NULL)
497 	{
498 	    u_header_T	    *uhfree = curbuf->b_u_oldhead;
499 
500 	    if (uhfree == old_curhead)
501 		/* Can't reconnect the branch, delete all of it. */
502 		u_freebranch(curbuf, uhfree, &old_curhead);
503 	    else if (uhfree->uh_alt_next.ptr == NULL)
504 		/* There is no branch, only free one header. */
505 		u_freeheader(curbuf, uhfree, &old_curhead);
506 	    else
507 	    {
508 		/* Free the oldest alternate branch as a whole. */
509 		while (uhfree->uh_alt_next.ptr != NULL)
510 		    uhfree = uhfree->uh_alt_next.ptr;
511 		u_freebranch(curbuf, uhfree, &old_curhead);
512 	    }
513 #ifdef U_DEBUG
514 	    u_check(TRUE);
515 #endif
516 	}
517 
518 	if (uhp == NULL)		/* no undo at all */
519 	{
520 	    if (old_curhead != NULL)
521 		u_freebranch(curbuf, old_curhead, NULL);
522 	    curbuf->b_u_synced = FALSE;
523 	    return OK;
524 	}
525 
526 	uhp->uh_prev.ptr = NULL;
527 	uhp->uh_next.ptr = curbuf->b_u_newhead;
528 	uhp->uh_alt_next.ptr = old_curhead;
529 	if (old_curhead != NULL)
530 	{
531 	    uhp->uh_alt_prev.ptr = old_curhead->uh_alt_prev.ptr;
532 	    if (uhp->uh_alt_prev.ptr != NULL)
533 		uhp->uh_alt_prev.ptr->uh_alt_next.ptr = uhp;
534 	    old_curhead->uh_alt_prev.ptr = uhp;
535 	    if (curbuf->b_u_oldhead == old_curhead)
536 		curbuf->b_u_oldhead = uhp;
537 	}
538 	else
539 	    uhp->uh_alt_prev.ptr = NULL;
540 	if (curbuf->b_u_newhead != NULL)
541 	    curbuf->b_u_newhead->uh_prev.ptr = uhp;
542 
543 	uhp->uh_seq = ++curbuf->b_u_seq_last;
544 	curbuf->b_u_seq_cur = uhp->uh_seq;
545 	uhp->uh_time = vim_time();
546 	uhp->uh_save_nr = 0;
547 	curbuf->b_u_time_cur = uhp->uh_time + 1;
548 
549 	uhp->uh_walk = 0;
550 	uhp->uh_entry = NULL;
551 	uhp->uh_getbot_entry = NULL;
552 	uhp->uh_cursor = curwin->w_cursor;	/* save cursor pos. for undo */
553 	if (virtual_active() && curwin->w_cursor.coladd > 0)
554 	    uhp->uh_cursor_vcol = getviscol();
555 	else
556 	    uhp->uh_cursor_vcol = -1;
557 
558 	/* save changed and buffer empty flag for undo */
559 	uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
560 		       ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
561 
562 	/* save named marks and Visual marks for undo */
563 	mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
564 	uhp->uh_visual = curbuf->b_visual;
565 
566 	curbuf->b_u_newhead = uhp;
567 	if (curbuf->b_u_oldhead == NULL)
568 	    curbuf->b_u_oldhead = uhp;
569 	++curbuf->b_u_numhead;
570     }
571     else
572     {
573 	if (get_undolevel() < 0)	/* no undo at all */
574 	    return OK;
575 
576 	/*
577 	 * When saving a single line, and it has been saved just before, it
578 	 * doesn't make sense saving it again.  Saves a lot of memory when
579 	 * making lots of changes inside the same line.
580 	 * This is only possible if the previous change didn't increase or
581 	 * decrease the number of lines.
582 	 * Check the ten last changes.  More doesn't make sense and takes too
583 	 * long.
584 	 */
585 	if (size == 1)
586 	{
587 	    uep = u_get_headentry();
588 	    prev_uep = NULL;
589 	    for (i = 0; i < 10; ++i)
590 	    {
591 		if (uep == NULL)
592 		    break;
593 
594 		/* If lines have been inserted/deleted we give up.
595 		 * Also when the line was included in a multi-line save. */
596 		if ((curbuf->b_u_newhead->uh_getbot_entry != uep
597 			    ? (uep->ue_top + uep->ue_size + 1
598 				!= (uep->ue_bot == 0
599 				    ? curbuf->b_ml.ml_line_count + 1
600 				    : uep->ue_bot))
601 			    : uep->ue_lcount != curbuf->b_ml.ml_line_count)
602 			|| (uep->ue_size > 1
603 			    && top >= uep->ue_top
604 			    && top + 2 <= uep->ue_top + uep->ue_size + 1))
605 		    break;
606 
607 		/* If it's the same line we can skip saving it again. */
608 		if (uep->ue_size == 1 && uep->ue_top == top)
609 		{
610 		    if (i > 0)
611 		    {
612 			/* It's not the last entry: get ue_bot for the last
613 			 * entry now.  Following deleted/inserted lines go to
614 			 * the re-used entry. */
615 			u_getbot();
616 			curbuf->b_u_synced = FALSE;
617 
618 			/* Move the found entry to become the last entry.  The
619 			 * order of undo/redo doesn't matter for the entries
620 			 * we move it over, since they don't change the line
621 			 * count and don't include this line.  It does matter
622 			 * for the found entry if the line count is changed by
623 			 * the executed command. */
624 			prev_uep->ue_next = uep->ue_next;
625 			uep->ue_next = curbuf->b_u_newhead->uh_entry;
626 			curbuf->b_u_newhead->uh_entry = uep;
627 		    }
628 
629 		    /* The executed command may change the line count. */
630 		    if (newbot != 0)
631 			uep->ue_bot = newbot;
632 		    else if (bot > curbuf->b_ml.ml_line_count)
633 			uep->ue_bot = 0;
634 		    else
635 		    {
636 			uep->ue_lcount = curbuf->b_ml.ml_line_count;
637 			curbuf->b_u_newhead->uh_getbot_entry = uep;
638 		    }
639 		    return OK;
640 		}
641 		prev_uep = uep;
642 		uep = uep->ue_next;
643 	    }
644 	}
645 
646 	/* find line number for ue_bot for previous u_save() */
647 	u_getbot();
648     }
649 
650 #if !defined(UNIX) && !defined(MSWIN)
651 	/*
652 	 * With Amiga we can't handle big undo's, because
653 	 * then u_alloc_line would have to allocate a block larger than 32K
654 	 */
655     if (size >= 8000)
656 	goto nomem;
657 #endif
658 
659     /*
660      * add lines in front of entry list
661      */
662     uep = U_ALLOC_LINE(sizeof(u_entry_T));
663     if (uep == NULL)
664 	goto nomem;
665     vim_memset(uep, 0, sizeof(u_entry_T));
666 #ifdef U_DEBUG
667     uep->ue_magic = UE_MAGIC;
668 #endif
669 
670     uep->ue_size = size;
671     uep->ue_top = top;
672     if (newbot != 0)
673 	uep->ue_bot = newbot;
674     /*
675      * Use 0 for ue_bot if bot is below last line.
676      * Otherwise we have to compute ue_bot later.
677      */
678     else if (bot > curbuf->b_ml.ml_line_count)
679 	uep->ue_bot = 0;
680     else
681     {
682 	uep->ue_lcount = curbuf->b_ml.ml_line_count;
683 	curbuf->b_u_newhead->uh_getbot_entry = uep;
684     }
685 
686     if (size > 0)
687     {
688 	if ((uep->ue_array = U_ALLOC_LINE(sizeof(undoline_T) * size)) == NULL)
689 	{
690 	    u_freeentry(uep, 0L);
691 	    goto nomem;
692 	}
693 	for (i = 0, lnum = top + 1; i < size; ++i)
694 	{
695 	    fast_breakcheck();
696 	    if (got_int)
697 	    {
698 		u_freeentry(uep, i);
699 		return FAIL;
700 	    }
701 	    if (u_save_line(&uep->ue_array[i], lnum++) == FAIL)
702 	    {
703 		u_freeentry(uep, i);
704 		goto nomem;
705 	    }
706 	}
707     }
708     else
709 	uep->ue_array = NULL;
710     uep->ue_next = curbuf->b_u_newhead->uh_entry;
711     curbuf->b_u_newhead->uh_entry = uep;
712     curbuf->b_u_synced = FALSE;
713     undo_undoes = FALSE;
714 
715 #ifdef U_DEBUG
716     u_check(FALSE);
717 #endif
718     return OK;
719 
720 nomem:
721     msg_silent = 0;	/* must display the prompt */
722     if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE)
723 								       == 'y')
724     {
725 	undo_off = TRUE;	    /* will be reset when character typed */
726 	return OK;
727     }
728     do_outofmem_msg((long_u)0);
729     return FAIL;
730 }
731 
732 #if defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
733 
734 # define UF_START_MAGIC	    "Vim\237UnDo\345"  /* magic at start of undofile */
735 # define UF_START_MAGIC_LEN	9
736 # define UF_HEADER_MAGIC	0x5fd0	/* magic at start of header */
737 # define UF_HEADER_END_MAGIC	0xe7aa	/* magic after last header */
738 # define UF_ENTRY_MAGIC		0xf518	/* magic at start of entry */
739 # define UF_ENTRY_END_MAGIC	0x3581	/* magic after last entry */
740 # define UF_VERSION		2	/* 2-byte undofile version number */
741 # define UF_VERSION_CRYPT	0x8002	/* idem, encrypted */
742 
743 /* extra fields for header */
744 # define UF_LAST_SAVE_NR	1
745 
746 /* extra fields for uhp */
747 # define UHP_SAVE_NR		1
748 
749 static char_u e_not_open[] = N_("E828: Cannot open undo file for writing: %s");
750 
751 /*
752  * Compute the hash for the current buffer text into hash[UNDO_HASH_SIZE].
753  */
754     void
755 u_compute_hash(char_u *hash)
756 {
757     context_sha256_T	ctx;
758     linenr_T		lnum;
759     char_u		*p;
760 
761     sha256_start(&ctx);
762     for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
763     {
764 	p = ml_get(lnum);
765 	sha256_update(&ctx, p, (UINT32_T)(STRLEN(p) + 1));
766     }
767     sha256_finish(&ctx, hash);
768 }
769 
770 /*
771  * Return an allocated string of the full path of the target undofile.
772  * When "reading" is TRUE find the file to read, go over all directories in
773  * 'undodir'.
774  * When "reading" is FALSE use the first name where the directory exists.
775  * Returns NULL when there is no place to write or no file to read.
776  */
777     char_u *
778 u_get_undo_file_name(char_u *buf_ffname, int reading)
779 {
780     char_u	*dirp;
781     char_u	dir_name[IOSIZE + 1];
782     char_u	*munged_name = NULL;
783     char_u	*undo_file_name = NULL;
784     int		dir_len;
785     char_u	*p;
786     stat_T	st;
787     char_u	*ffname = buf_ffname;
788 #ifdef HAVE_READLINK
789     char_u	fname_buf[MAXPATHL];
790 #endif
791 
792     if (ffname == NULL)
793 	return NULL;
794 
795 #ifdef HAVE_READLINK
796     /* Expand symlink in the file name, so that we put the undo file with the
797      * actual file instead of with the symlink. */
798     if (resolve_symlink(ffname, fname_buf) == OK)
799 	ffname = fname_buf;
800 #endif
801 
802     /* Loop over 'undodir'.  When reading find the first file that exists.
803      * When not reading use the first directory that exists or ".". */
804     dirp = p_udir;
805     while (*dirp != NUL)
806     {
807 	dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ",");
808 	if (dir_len == 1 && dir_name[0] == '.')
809 	{
810 	    /* Use same directory as the ffname,
811 	     * "dir/name" -> "dir/.name.un~" */
812 	    undo_file_name = vim_strnsave(ffname, (int)(STRLEN(ffname) + 5));
813 	    if (undo_file_name == NULL)
814 		break;
815 	    p = gettail(undo_file_name);
816 #ifdef VMS
817 	    /* VMS can not handle more than one dot in the filenames
818 	     * use "dir/name" -> "dir/_un_name" - add _un_
819 	     * at the beginning to keep the extension */
820 	    mch_memmove(p + 4,  p, STRLEN(p) + 1);
821 	    mch_memmove(p, "_un_", 4);
822 
823 #else
824 	    /* Use same directory as the ffname,
825 	     * "dir/name" -> "dir/.name.un~" */
826 	    mch_memmove(p + 1, p, STRLEN(p) + 1);
827 	    *p = '.';
828 	    STRCAT(p, ".un~");
829 #endif
830 	}
831 	else
832 	{
833 	    dir_name[dir_len] = NUL;
834 	    if (mch_isdir(dir_name))
835 	    {
836 		if (munged_name == NULL)
837 		{
838 		    munged_name = vim_strsave(ffname);
839 		    if (munged_name == NULL)
840 			return NULL;
841 		    for (p = munged_name; *p != NUL; MB_PTR_ADV(p))
842 			if (vim_ispathsep(*p))
843 			    *p = '%';
844 		}
845 		undo_file_name = concat_fnames(dir_name, munged_name, TRUE);
846 	    }
847 	}
848 
849 	/* When reading check if the file exists. */
850 	if (undo_file_name != NULL && (!reading
851 			       || mch_stat((char *)undo_file_name, &st) >= 0))
852 	    break;
853 	VIM_CLEAR(undo_file_name);
854     }
855 
856     vim_free(munged_name);
857     return undo_file_name;
858 }
859 
860     static void
861 corruption_error(char *mesg, char_u *file_name)
862 {
863     semsg(_("E825: Corrupted undo file (%s): %s"), mesg, file_name);
864 }
865 
866     static void
867 u_free_uhp(u_header_T *uhp)
868 {
869     u_entry_T	*nuep;
870     u_entry_T	*uep;
871 
872     uep = uhp->uh_entry;
873     while (uep != NULL)
874     {
875 	nuep = uep->ue_next;
876 	u_freeentry(uep, uep->ue_size);
877 	uep = nuep;
878     }
879     vim_free(uhp);
880 }
881 
882 /*
883  * Write a sequence of bytes to the undo file.
884  * Buffers and encrypts as needed.
885  * Returns OK or FAIL.
886  */
887     static int
888 undo_write(bufinfo_T *bi, char_u *ptr, size_t len)
889 {
890 #ifdef FEAT_CRYPT
891     if (bi->bi_buffer != NULL)
892     {
893 	size_t	len_todo = len;
894 	char_u  *p = ptr;
895 
896 	while (bi->bi_used + len_todo >= CRYPT_BUF_SIZE)
897 	{
898 	    size_t	n = CRYPT_BUF_SIZE - bi->bi_used;
899 
900 	    mch_memmove(bi->bi_buffer + bi->bi_used, p, n);
901 	    len_todo -= n;
902 	    p += n;
903 	    bi->bi_used = CRYPT_BUF_SIZE;
904 	    if (undo_flush(bi) == FAIL)
905 		return FAIL;
906 	}
907 	if (len_todo > 0)
908 	{
909 	    mch_memmove(bi->bi_buffer + bi->bi_used, p, len_todo);
910 	    bi->bi_used += len_todo;
911 	}
912 	return OK;
913     }
914 #endif
915     if (fwrite(ptr, len, (size_t)1, bi->bi_fp) != 1)
916 	return FAIL;
917     return OK;
918 }
919 
920 #ifdef FEAT_CRYPT
921     static int
922 undo_flush(bufinfo_T *bi)
923 {
924     if (bi->bi_buffer != NULL && bi->bi_state != NULL && bi->bi_used > 0)
925     {
926 	crypt_encode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_used);
927 	if (fwrite(bi->bi_buffer, bi->bi_used, (size_t)1, bi->bi_fp) != 1)
928 	    return FAIL;
929 	bi->bi_used = 0;
930     }
931     return OK;
932 }
933 #endif
934 
935 /*
936  * Write "ptr[len]" and crypt the bytes when needed.
937  * Returns OK or FAIL.
938  */
939     static int
940 fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len)
941 {
942 #ifdef FEAT_CRYPT
943     char_u  *copy;
944     char_u  small_buf[100];
945     size_t  i;
946 
947     if (bi->bi_state != NULL && bi->bi_buffer == NULL)
948     {
949 	/* crypting every piece of text separately */
950 	if (len < 100)
951 	    copy = small_buf;  /* no malloc()/free() for short strings */
952 	else
953 	{
954 	    copy = lalloc(len, FALSE);
955 	    if (copy == NULL)
956 		return 0;
957 	}
958 	crypt_encode(bi->bi_state, ptr, len, copy);
959 	i = fwrite(copy, len, (size_t)1, bi->bi_fp);
960 	if (copy != small_buf)
961 	    vim_free(copy);
962 	return i == 1 ? OK : FAIL;
963     }
964 #endif
965     return undo_write(bi, ptr, len);
966 }
967 
968 /*
969  * Write a number, MSB first, in "len" bytes.
970  * Must match with undo_read_?c() functions.
971  * Returns OK or FAIL.
972  */
973     static int
974 undo_write_bytes(bufinfo_T *bi, long_u nr, int len)
975 {
976     char_u  buf[8];
977     int	    i;
978     int	    bufi = 0;
979 
980     for (i = len - 1; i >= 0; --i)
981 	buf[bufi++] = (char_u)(nr >> (i * 8));
982     return undo_write(bi, buf, (size_t)len);
983 }
984 
985 /*
986  * Write the pointer to an undo header.  Instead of writing the pointer itself
987  * we use the sequence number of the header.  This is converted back to
988  * pointers when reading. */
989     static void
990 put_header_ptr(bufinfo_T *bi, u_header_T *uhp)
991 {
992     undo_write_bytes(bi, (long_u)(uhp != NULL ? uhp->uh_seq : 0), 4);
993 }
994 
995     static int
996 undo_read_4c(bufinfo_T *bi)
997 {
998 #ifdef FEAT_CRYPT
999     if (bi->bi_buffer != NULL)
1000     {
1001 	char_u  buf[4];
1002 	int	n;
1003 
1004 	undo_read(bi, buf, (size_t)4);
1005 	n = ((unsigned)buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
1006 	return n;
1007     }
1008 #endif
1009     return get4c(bi->bi_fp);
1010 }
1011 
1012     static int
1013 undo_read_2c(bufinfo_T *bi)
1014 {
1015 #ifdef FEAT_CRYPT
1016     if (bi->bi_buffer != NULL)
1017     {
1018 	char_u  buf[2];
1019 	int	n;
1020 
1021 	undo_read(bi, buf, (size_t)2);
1022 	n = (buf[0] << 8) + buf[1];
1023 	return n;
1024     }
1025 #endif
1026     return get2c(bi->bi_fp);
1027 }
1028 
1029     static int
1030 undo_read_byte(bufinfo_T *bi)
1031 {
1032 #ifdef FEAT_CRYPT
1033     if (bi->bi_buffer != NULL)
1034     {
1035 	char_u  buf[1];
1036 
1037 	undo_read(bi, buf, (size_t)1);
1038 	return buf[0];
1039     }
1040 #endif
1041     return getc(bi->bi_fp);
1042 }
1043 
1044     static time_t
1045 undo_read_time(bufinfo_T *bi)
1046 {
1047 #ifdef FEAT_CRYPT
1048     if (bi->bi_buffer != NULL)
1049     {
1050 	char_u  buf[8];
1051 	time_t	n = 0;
1052 	int	i;
1053 
1054 	undo_read(bi, buf, (size_t)8);
1055 	for (i = 0; i < 8; ++i)
1056 	    n = (n << 8) + buf[i];
1057 	return n;
1058     }
1059 #endif
1060     return get8ctime(bi->bi_fp);
1061 }
1062 
1063 /*
1064  * Read "buffer[size]" from the undo file.
1065  * Return OK or FAIL.
1066  */
1067     static int
1068 undo_read(bufinfo_T *bi, char_u *buffer, size_t size)
1069 {
1070     int retval = OK;
1071 
1072 #ifdef FEAT_CRYPT
1073     if (bi->bi_buffer != NULL)
1074     {
1075 	int	size_todo = (int)size;
1076 	char_u	*p = buffer;
1077 
1078 	while (size_todo > 0)
1079 	{
1080 	    size_t n;
1081 
1082 	    if (bi->bi_used >= bi->bi_avail)
1083 	    {
1084 		n = fread(bi->bi_buffer, 1, (size_t)CRYPT_BUF_SIZE, bi->bi_fp);
1085 		if (n == 0)
1086 		{
1087 		    retval = FAIL;
1088 		    break;
1089 		}
1090 		bi->bi_avail = n;
1091 		bi->bi_used = 0;
1092 		crypt_decode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_avail);
1093 	    }
1094 	    n = size_todo;
1095 	    if (n > bi->bi_avail - bi->bi_used)
1096 		n = bi->bi_avail - bi->bi_used;
1097 	    mch_memmove(p, bi->bi_buffer + bi->bi_used, n);
1098 	    bi->bi_used += n;
1099 	    size_todo -= (int)n;
1100 	    p += n;
1101 	}
1102     }
1103     else
1104 #endif
1105     if (fread(buffer, (size_t)size, 1, bi->bi_fp) != 1)
1106 	retval = FAIL;
1107 
1108     if (retval == FAIL)
1109 	/* Error may be checked for only later.  Fill with zeros,
1110 	 * so that the reader won't use garbage. */
1111 	vim_memset(buffer, 0, size);
1112     return retval;
1113 }
1114 
1115 /*
1116  * Read a string of length "len" from "bi->bi_fd".
1117  * "len" can be zero to allocate an empty line.
1118  * Decrypt the bytes if needed.
1119  * Append a NUL.
1120  * Returns a pointer to allocated memory or NULL for failure.
1121  */
1122     static char_u *
1123 read_string_decrypt(bufinfo_T *bi, int len)
1124 {
1125     char_u  *ptr = alloc(len + 1);
1126 
1127     if (ptr != NULL)
1128     {
1129 	if (len > 0 && undo_read(bi, ptr, len) == FAIL)
1130 	{
1131 	    vim_free(ptr);
1132 	    return NULL;
1133 	}
1134 	// In case there are text properties there already is a NUL, but
1135 	// checking for that is more expensive than just adding a dummy byte.
1136 	ptr[len] = NUL;
1137 #ifdef FEAT_CRYPT
1138 	if (bi->bi_state != NULL && bi->bi_buffer == NULL)
1139 	    crypt_decode_inplace(bi->bi_state, ptr, len);
1140 #endif
1141     }
1142     return ptr;
1143 }
1144 
1145 /*
1146  * Writes the (not encrypted) header and initializes encryption if needed.
1147  */
1148     static int
1149 serialize_header(bufinfo_T *bi, char_u *hash)
1150 {
1151     long	len;
1152     buf_T	*buf = bi->bi_buf;
1153     FILE	*fp = bi->bi_fp;
1154     char_u	time_buf[8];
1155 
1156     /* Start writing, first the magic marker and undo info version. */
1157     if (fwrite(UF_START_MAGIC, (size_t)UF_START_MAGIC_LEN, (size_t)1, fp) != 1)
1158 	return FAIL;
1159 
1160     /* If the buffer is encrypted then all text bytes following will be
1161      * encrypted.  Numbers and other info is not crypted. */
1162 #ifdef FEAT_CRYPT
1163     if (*buf->b_p_key != NUL)
1164     {
1165 	char_u *header;
1166 	int    header_len;
1167 
1168 	undo_write_bytes(bi, (long_u)UF_VERSION_CRYPT, 2);
1169 	bi->bi_state = crypt_create_for_writing(crypt_get_method_nr(buf),
1170 					  buf->b_p_key, &header, &header_len);
1171 	if (bi->bi_state == NULL)
1172 	    return FAIL;
1173 	len = (long)fwrite(header, (size_t)header_len, (size_t)1, fp);
1174 	vim_free(header);
1175 	if (len != 1)
1176 	{
1177 	    crypt_free_state(bi->bi_state);
1178 	    bi->bi_state = NULL;
1179 	    return FAIL;
1180 	}
1181 
1182 	if (crypt_whole_undofile(crypt_get_method_nr(buf)))
1183 	{
1184 	    bi->bi_buffer = alloc(CRYPT_BUF_SIZE);
1185 	    if (bi->bi_buffer == NULL)
1186 	    {
1187 		crypt_free_state(bi->bi_state);
1188 		bi->bi_state = NULL;
1189 		return FAIL;
1190 	    }
1191 	    bi->bi_used = 0;
1192 	}
1193     }
1194     else
1195 #endif
1196 	undo_write_bytes(bi, (long_u)UF_VERSION, 2);
1197 
1198 
1199     /* Write a hash of the buffer text, so that we can verify it is still the
1200      * same when reading the buffer text. */
1201     if (undo_write(bi, hash, (size_t)UNDO_HASH_SIZE) == FAIL)
1202 	return FAIL;
1203 
1204     /* buffer-specific data */
1205     undo_write_bytes(bi, (long_u)buf->b_ml.ml_line_count, 4);
1206     len = buf->b_u_line_ptr.ul_line == NULL
1207 				? 0L : (long)STRLEN(buf->b_u_line_ptr.ul_line);
1208     undo_write_bytes(bi, (long_u)len, 4);
1209     if (len > 0 && fwrite_crypt(bi, buf->b_u_line_ptr.ul_line, (size_t)len)
1210 								       == FAIL)
1211 	return FAIL;
1212     undo_write_bytes(bi, (long_u)buf->b_u_line_lnum, 4);
1213     undo_write_bytes(bi, (long_u)buf->b_u_line_colnr, 4);
1214 
1215     /* Undo structures header data */
1216     put_header_ptr(bi, buf->b_u_oldhead);
1217     put_header_ptr(bi, buf->b_u_newhead);
1218     put_header_ptr(bi, buf->b_u_curhead);
1219 
1220     undo_write_bytes(bi, (long_u)buf->b_u_numhead, 4);
1221     undo_write_bytes(bi, (long_u)buf->b_u_seq_last, 4);
1222     undo_write_bytes(bi, (long_u)buf->b_u_seq_cur, 4);
1223     time_to_bytes(buf->b_u_time_cur, time_buf);
1224     undo_write(bi, time_buf, 8);
1225 
1226     /* Optional fields. */
1227     undo_write_bytes(bi, 4, 1);
1228     undo_write_bytes(bi, UF_LAST_SAVE_NR, 1);
1229     undo_write_bytes(bi, (long_u)buf->b_u_save_nr_last, 4);
1230 
1231     undo_write_bytes(bi, 0, 1);  /* end marker */
1232 
1233     return OK;
1234 }
1235 
1236     static int
1237 serialize_uhp(bufinfo_T *bi, u_header_T *uhp)
1238 {
1239     int		i;
1240     u_entry_T	*uep;
1241     char_u	time_buf[8];
1242 
1243     if (undo_write_bytes(bi, (long_u)UF_HEADER_MAGIC, 2) == FAIL)
1244 	return FAIL;
1245 
1246     put_header_ptr(bi, uhp->uh_next.ptr);
1247     put_header_ptr(bi, uhp->uh_prev.ptr);
1248     put_header_ptr(bi, uhp->uh_alt_next.ptr);
1249     put_header_ptr(bi, uhp->uh_alt_prev.ptr);
1250     undo_write_bytes(bi, uhp->uh_seq, 4);
1251     serialize_pos(bi, uhp->uh_cursor);
1252     undo_write_bytes(bi, (long_u)uhp->uh_cursor_vcol, 4);
1253     undo_write_bytes(bi, (long_u)uhp->uh_flags, 2);
1254     /* Assume NMARKS will stay the same. */
1255     for (i = 0; i < NMARKS; ++i)
1256 	serialize_pos(bi, uhp->uh_namedm[i]);
1257     serialize_visualinfo(bi, &uhp->uh_visual);
1258     time_to_bytes(uhp->uh_time, time_buf);
1259     undo_write(bi, time_buf, 8);
1260 
1261     /* Optional fields. */
1262     undo_write_bytes(bi, 4, 1);
1263     undo_write_bytes(bi, UHP_SAVE_NR, 1);
1264     undo_write_bytes(bi, (long_u)uhp->uh_save_nr, 4);
1265 
1266     undo_write_bytes(bi, 0, 1);  /* end marker */
1267 
1268     /* Write all the entries. */
1269     for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next)
1270     {
1271 	undo_write_bytes(bi, (long_u)UF_ENTRY_MAGIC, 2);
1272 	if (serialize_uep(bi, uep) == FAIL)
1273 	    return FAIL;
1274     }
1275     undo_write_bytes(bi, (long_u)UF_ENTRY_END_MAGIC, 2);
1276     return OK;
1277 }
1278 
1279     static u_header_T *
1280 unserialize_uhp(bufinfo_T *bi, char_u *file_name)
1281 {
1282     u_header_T	*uhp;
1283     int		i;
1284     u_entry_T	*uep, *last_uep;
1285     int		c;
1286     int		error;
1287 
1288     uhp = U_ALLOC_LINE(sizeof(u_header_T));
1289     if (uhp == NULL)
1290 	return NULL;
1291     vim_memset(uhp, 0, sizeof(u_header_T));
1292 #ifdef U_DEBUG
1293     uhp->uh_magic = UH_MAGIC;
1294 #endif
1295     uhp->uh_next.seq = undo_read_4c(bi);
1296     uhp->uh_prev.seq = undo_read_4c(bi);
1297     uhp->uh_alt_next.seq = undo_read_4c(bi);
1298     uhp->uh_alt_prev.seq = undo_read_4c(bi);
1299     uhp->uh_seq = undo_read_4c(bi);
1300     if (uhp->uh_seq <= 0)
1301     {
1302 	corruption_error("uh_seq", file_name);
1303 	vim_free(uhp);
1304 	return NULL;
1305     }
1306     unserialize_pos(bi, &uhp->uh_cursor);
1307     uhp->uh_cursor_vcol = undo_read_4c(bi);
1308     uhp->uh_flags = undo_read_2c(bi);
1309     for (i = 0; i < NMARKS; ++i)
1310 	unserialize_pos(bi, &uhp->uh_namedm[i]);
1311     unserialize_visualinfo(bi, &uhp->uh_visual);
1312     uhp->uh_time = undo_read_time(bi);
1313 
1314     /* Optional fields. */
1315     for (;;)
1316     {
1317 	int len = undo_read_byte(bi);
1318 	int what;
1319 
1320 	if (len == 0)
1321 	    break;
1322 	what = undo_read_byte(bi);
1323 	switch (what)
1324 	{
1325 	    case UHP_SAVE_NR:
1326 		uhp->uh_save_nr = undo_read_4c(bi);
1327 		break;
1328 	    default:
1329 		/* field not supported, skip */
1330 		while (--len >= 0)
1331 		    (void)undo_read_byte(bi);
1332 	}
1333     }
1334 
1335     /* Unserialize the uep list. */
1336     last_uep = NULL;
1337     while ((c = undo_read_2c(bi)) == UF_ENTRY_MAGIC)
1338     {
1339 	error = FALSE;
1340 	uep = unserialize_uep(bi, &error, file_name);
1341 	if (last_uep == NULL)
1342 	    uhp->uh_entry = uep;
1343 	else
1344 	    last_uep->ue_next = uep;
1345 	last_uep = uep;
1346 	if (uep == NULL || error)
1347 	{
1348 	    u_free_uhp(uhp);
1349 	    return NULL;
1350 	}
1351     }
1352     if (c != UF_ENTRY_END_MAGIC)
1353     {
1354 	corruption_error("entry end", file_name);
1355 	u_free_uhp(uhp);
1356 	return NULL;
1357     }
1358 
1359     return uhp;
1360 }
1361 
1362 /*
1363  * Serialize "uep".
1364  */
1365     static int
1366 serialize_uep(
1367     bufinfo_T	*bi,
1368     u_entry_T	*uep)
1369 {
1370     int		i;
1371     size_t	len;
1372 
1373     undo_write_bytes(bi, (long_u)uep->ue_top, 4);
1374     undo_write_bytes(bi, (long_u)uep->ue_bot, 4);
1375     undo_write_bytes(bi, (long_u)uep->ue_lcount, 4);
1376     undo_write_bytes(bi, (long_u)uep->ue_size, 4);
1377     for (i = 0; i < uep->ue_size; ++i)
1378     {
1379 	// Text is written without the text properties, since we cannot restore
1380 	// the text property types.
1381 	len = STRLEN(uep->ue_array[i].ul_line);
1382 	if (undo_write_bytes(bi, (long_u)len, 4) == FAIL)
1383 	    return FAIL;
1384 	if (len > 0 && fwrite_crypt(bi, uep->ue_array[i].ul_line, len) == FAIL)
1385 	    return FAIL;
1386     }
1387     return OK;
1388 }
1389 
1390     static u_entry_T *
1391 unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name)
1392 {
1393     int		i;
1394     u_entry_T	*uep;
1395     undoline_T	*array = NULL;
1396     char_u	*line;
1397     int		line_len;
1398 
1399     uep = U_ALLOC_LINE(sizeof(u_entry_T));
1400     if (uep == NULL)
1401 	return NULL;
1402     vim_memset(uep, 0, sizeof(u_entry_T));
1403 #ifdef U_DEBUG
1404     uep->ue_magic = UE_MAGIC;
1405 #endif
1406     uep->ue_top = undo_read_4c(bi);
1407     uep->ue_bot = undo_read_4c(bi);
1408     uep->ue_lcount = undo_read_4c(bi);
1409     uep->ue_size = undo_read_4c(bi);
1410     if (uep->ue_size > 0)
1411     {
1412 	if (uep->ue_size < LONG_MAX / (int)sizeof(char_u *))
1413 	    array = U_ALLOC_LINE(sizeof(undoline_T) * uep->ue_size);
1414 	if (array == NULL)
1415 	{
1416 	    *error = TRUE;
1417 	    return uep;
1418 	}
1419 	vim_memset(array, 0, sizeof(undoline_T) * uep->ue_size);
1420     }
1421     uep->ue_array = array;
1422 
1423     for (i = 0; i < uep->ue_size; ++i)
1424     {
1425 	line_len = undo_read_4c(bi);
1426 	if (line_len >= 0)
1427 	    line = read_string_decrypt(bi, line_len);
1428 	else
1429 	{
1430 	    line = NULL;
1431 	    corruption_error("line length", file_name);
1432 	}
1433 	if (line == NULL)
1434 	{
1435 	    *error = TRUE;
1436 	    return uep;
1437 	}
1438 	array[i].ul_line = line;
1439 	array[i].ul_len = line_len + 1;
1440     }
1441     return uep;
1442 }
1443 
1444 /*
1445  * Serialize "pos".
1446  */
1447     static void
1448 serialize_pos(bufinfo_T *bi, pos_T pos)
1449 {
1450     undo_write_bytes(bi, (long_u)pos.lnum, 4);
1451     undo_write_bytes(bi, (long_u)pos.col, 4);
1452     undo_write_bytes(bi, (long_u)pos.coladd, 4);
1453 }
1454 
1455 /*
1456  * Unserialize the pos_T at the current position.
1457  */
1458     static void
1459 unserialize_pos(bufinfo_T *bi, pos_T *pos)
1460 {
1461     pos->lnum = undo_read_4c(bi);
1462     if (pos->lnum < 0)
1463 	pos->lnum = 0;
1464     pos->col = undo_read_4c(bi);
1465     if (pos->col < 0)
1466 	pos->col = 0;
1467     pos->coladd = undo_read_4c(bi);
1468     if (pos->coladd < 0)
1469 	pos->coladd = 0;
1470 }
1471 
1472 /*
1473  * Serialize "info".
1474  */
1475     static void
1476 serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info)
1477 {
1478     serialize_pos(bi, info->vi_start);
1479     serialize_pos(bi, info->vi_end);
1480     undo_write_bytes(bi, (long_u)info->vi_mode, 4);
1481     undo_write_bytes(bi, (long_u)info->vi_curswant, 4);
1482 }
1483 
1484 /*
1485  * Unserialize the visualinfo_T at the current position.
1486  */
1487     static void
1488 unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info)
1489 {
1490     unserialize_pos(bi, &info->vi_start);
1491     unserialize_pos(bi, &info->vi_end);
1492     info->vi_mode = undo_read_4c(bi);
1493     info->vi_curswant = undo_read_4c(bi);
1494 }
1495 
1496 /*
1497  * Write the undo tree in an undo file.
1498  * When "name" is not NULL, use it as the name of the undo file.
1499  * Otherwise use buf->b_ffname to generate the undo file name.
1500  * "buf" must never be null, buf->b_ffname is used to obtain the original file
1501  * permissions.
1502  * "forceit" is TRUE for ":wundo!", FALSE otherwise.
1503  * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text.
1504  */
1505     void
1506 u_write_undo(
1507     char_u	*name,
1508     int		forceit,
1509     buf_T	*buf,
1510     char_u	*hash)
1511 {
1512     u_header_T	*uhp;
1513     char_u	*file_name;
1514     int		mark;
1515 #ifdef U_DEBUG
1516     int		headers_written = 0;
1517 #endif
1518     int		fd;
1519     FILE	*fp = NULL;
1520     int		perm;
1521     int		write_ok = FALSE;
1522 #ifdef UNIX
1523     int		st_old_valid = FALSE;
1524     stat_T	st_old;
1525     stat_T	st_new;
1526 #endif
1527     bufinfo_T	bi;
1528 
1529     vim_memset(&bi, 0, sizeof(bi));
1530 
1531     if (name == NULL)
1532     {
1533 	file_name = u_get_undo_file_name(buf->b_ffname, FALSE);
1534 	if (file_name == NULL)
1535 	{
1536 	    if (p_verbose > 0)
1537 	    {
1538 		verbose_enter();
1539 		smsg(
1540 		   _("Cannot write undo file in any directory in 'undodir'"));
1541 		verbose_leave();
1542 	    }
1543 	    return;
1544 	}
1545     }
1546     else
1547 	file_name = name;
1548 
1549     /*
1550      * Decide about the permission to use for the undo file.  If the buffer
1551      * has a name use the permission of the original file.  Otherwise only
1552      * allow the user to access the undo file.
1553      */
1554     perm = 0600;
1555     if (buf->b_ffname != NULL)
1556     {
1557 #ifdef UNIX
1558 	if (mch_stat((char *)buf->b_ffname, &st_old) >= 0)
1559 	{
1560 	    perm = st_old.st_mode;
1561 	    st_old_valid = TRUE;
1562 	}
1563 #else
1564 	perm = mch_getperm(buf->b_ffname);
1565 	if (perm < 0)
1566 	    perm = 0600;
1567 #endif
1568     }
1569 
1570     /* strip any s-bit and executable bit */
1571     perm = perm & 0666;
1572 
1573     /* If the undo file already exists, verify that it actually is an undo
1574      * file, and delete it. */
1575     if (mch_getperm(file_name) >= 0)
1576     {
1577 	if (name == NULL || !forceit)
1578 	{
1579 	    /* Check we can read it and it's an undo file. */
1580 	    fd = mch_open((char *)file_name, O_RDONLY|O_EXTRA, 0);
1581 	    if (fd < 0)
1582 	    {
1583 		if (name != NULL || p_verbose > 0)
1584 		{
1585 		    if (name == NULL)
1586 			verbose_enter();
1587 		    smsg(
1588 		      _("Will not overwrite with undo file, cannot read: %s"),
1589 								   file_name);
1590 		    if (name == NULL)
1591 			verbose_leave();
1592 		}
1593 		goto theend;
1594 	    }
1595 	    else
1596 	    {
1597 		char_u	mbuf[UF_START_MAGIC_LEN];
1598 		int	len;
1599 
1600 		len = read_eintr(fd, mbuf, UF_START_MAGIC_LEN);
1601 		close(fd);
1602 		if (len < UF_START_MAGIC_LEN
1603 		      || memcmp(mbuf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0)
1604 		{
1605 		    if (name != NULL || p_verbose > 0)
1606 		    {
1607 			if (name == NULL)
1608 			    verbose_enter();
1609 			smsg(
1610 			_("Will not overwrite, this is not an undo file: %s"),
1611 								   file_name);
1612 			if (name == NULL)
1613 			    verbose_leave();
1614 		    }
1615 		    goto theend;
1616 		}
1617 	    }
1618 	}
1619 	mch_remove(file_name);
1620     }
1621 
1622     /* If there is no undo information at all, quit here after deleting any
1623      * existing undo file. */
1624     if (buf->b_u_numhead == 0 && buf->b_u_line_ptr.ul_line == NULL)
1625     {
1626 	if (p_verbose > 0)
1627 	    verb_msg(_("Skipping undo file write, nothing to undo"));
1628 	goto theend;
1629     }
1630 
1631     fd = mch_open((char *)file_name,
1632 			    O_CREAT|O_EXTRA|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
1633     if (fd < 0)
1634     {
1635 	semsg(_(e_not_open), file_name);
1636 	goto theend;
1637     }
1638     (void)mch_setperm(file_name, perm);
1639     if (p_verbose > 0)
1640     {
1641 	verbose_enter();
1642 	smsg(_("Writing undo file: %s"), file_name);
1643 	verbose_leave();
1644     }
1645 
1646 #ifdef U_DEBUG
1647     /* Check there is no problem in undo info before writing. */
1648     u_check(FALSE);
1649 #endif
1650 
1651 #ifdef UNIX
1652     /*
1653      * Try to set the group of the undo file same as the original file. If
1654      * this fails, set the protection bits for the group same as the
1655      * protection bits for others.
1656      */
1657     if (st_old_valid
1658 	    && mch_stat((char *)file_name, &st_new) >= 0
1659 	    && st_new.st_gid != st_old.st_gid
1660 # ifdef HAVE_FCHOWN  /* sequent-ptx lacks fchown() */
1661 	    && fchown(fd, (uid_t)-1, st_old.st_gid) != 0
1662 # endif
1663        )
1664 	mch_setperm(file_name, (perm & 0707) | ((perm & 07) << 3));
1665 # if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1666     if (buf->b_ffname != NULL)
1667 	mch_copy_sec(buf->b_ffname, file_name);
1668 # endif
1669 #endif
1670 
1671     fp = fdopen(fd, "w");
1672     if (fp == NULL)
1673     {
1674 	semsg(_(e_not_open), file_name);
1675 	close(fd);
1676 	mch_remove(file_name);
1677 	goto theend;
1678     }
1679 
1680     /* Undo must be synced. */
1681     u_sync(TRUE);
1682 
1683     /*
1684      * Write the header.  Initializes encryption, if enabled.
1685      */
1686     bi.bi_buf = buf;
1687     bi.bi_fp = fp;
1688     if (serialize_header(&bi, hash) == FAIL)
1689 	goto write_error;
1690 
1691     /*
1692      * Iteratively serialize UHPs and their UEPs from the top down.
1693      */
1694     mark = ++lastmark;
1695     uhp = buf->b_u_oldhead;
1696     while (uhp != NULL)
1697     {
1698 	/* Serialize current UHP if we haven't seen it */
1699 	if (uhp->uh_walk != mark)
1700 	{
1701 	    uhp->uh_walk = mark;
1702 #ifdef U_DEBUG
1703 	    ++headers_written;
1704 #endif
1705 	    if (serialize_uhp(&bi, uhp) == FAIL)
1706 		goto write_error;
1707 	}
1708 
1709 	/* Now walk through the tree - algorithm from undo_time(). */
1710 	if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != mark)
1711 	    uhp = uhp->uh_prev.ptr;
1712 	else if (uhp->uh_alt_next.ptr != NULL
1713 				     && uhp->uh_alt_next.ptr->uh_walk != mark)
1714 	    uhp = uhp->uh_alt_next.ptr;
1715 	else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL
1716 					 && uhp->uh_next.ptr->uh_walk != mark)
1717 	    uhp = uhp->uh_next.ptr;
1718 	else if (uhp->uh_alt_prev.ptr != NULL)
1719 	    uhp = uhp->uh_alt_prev.ptr;
1720 	else
1721 	    uhp = uhp->uh_next.ptr;
1722     }
1723 
1724     if (undo_write_bytes(&bi, (long_u)UF_HEADER_END_MAGIC, 2) == OK)
1725 	write_ok = TRUE;
1726 #ifdef U_DEBUG
1727     if (headers_written != buf->b_u_numhead)
1728     {
1729 	semsg("Written %ld headers, ...", headers_written);
1730 	semsg("... but numhead is %ld", buf->b_u_numhead);
1731     }
1732 #endif
1733 
1734 #ifdef FEAT_CRYPT
1735     if (bi.bi_state != NULL && undo_flush(&bi) == FAIL)
1736 	write_ok = FALSE;
1737 #endif
1738 
1739 write_error:
1740     fclose(fp);
1741     if (!write_ok)
1742 	semsg(_("E829: write error in undo file: %s"), file_name);
1743 
1744 #if defined(MSWIN)
1745     /* Copy file attributes; for systems where this can only be done after
1746      * closing the file. */
1747     if (buf->b_ffname != NULL)
1748 	(void)mch_copy_file_attribute(buf->b_ffname, file_name);
1749 #endif
1750 #ifdef HAVE_ACL
1751     if (buf->b_ffname != NULL)
1752     {
1753 	vim_acl_T	    acl;
1754 
1755 	/* For systems that support ACL: get the ACL from the original file. */
1756 	acl = mch_get_acl(buf->b_ffname);
1757 	mch_set_acl(file_name, acl);
1758 	mch_free_acl(acl);
1759     }
1760 #endif
1761 
1762 theend:
1763 #ifdef FEAT_CRYPT
1764     if (bi.bi_state != NULL)
1765 	crypt_free_state(bi.bi_state);
1766     vim_free(bi.bi_buffer);
1767 #endif
1768     if (file_name != name)
1769 	vim_free(file_name);
1770 }
1771 
1772 /*
1773  * Load the undo tree from an undo file.
1774  * If "name" is not NULL use it as the undo file name.  This also means being
1775  * a bit more verbose.
1776  * Otherwise use curbuf->b_ffname to generate the undo file name.
1777  * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text.
1778  */
1779     void
1780 u_read_undo(char_u *name, char_u *hash, char_u *orig_name)
1781 {
1782     char_u	*file_name;
1783     FILE	*fp;
1784     long	version, str_len;
1785     undoline_T	line_ptr;
1786     linenr_T	line_lnum;
1787     colnr_T	line_colnr;
1788     linenr_T	line_count;
1789     long	num_head = 0;
1790     long	old_header_seq, new_header_seq, cur_header_seq;
1791     long	seq_last, seq_cur;
1792     long	last_save_nr = 0;
1793     short	old_idx = -1, new_idx = -1, cur_idx = -1;
1794     long	num_read_uhps = 0;
1795     time_t	seq_time;
1796     int		i, j;
1797     int		c;
1798     u_header_T	*uhp;
1799     u_header_T	**uhp_table = NULL;
1800     char_u	read_hash[UNDO_HASH_SIZE];
1801     char_u	magic_buf[UF_START_MAGIC_LEN];
1802 #ifdef U_DEBUG
1803     int		*uhp_table_used;
1804 #endif
1805 #ifdef UNIX
1806     stat_T	st_orig;
1807     stat_T	st_undo;
1808 #endif
1809     bufinfo_T	bi;
1810 
1811     vim_memset(&bi, 0, sizeof(bi));
1812     line_ptr.ul_len = 0;
1813     line_ptr.ul_line = NULL;
1814 
1815     if (name == NULL)
1816     {
1817 	file_name = u_get_undo_file_name(curbuf->b_ffname, TRUE);
1818 	if (file_name == NULL)
1819 	    return;
1820 
1821 #ifdef UNIX
1822 	/* For safety we only read an undo file if the owner is equal to the
1823 	 * owner of the text file or equal to the current user. */
1824 	if (mch_stat((char *)orig_name, &st_orig) >= 0
1825 		&& mch_stat((char *)file_name, &st_undo) >= 0
1826 		&& st_orig.st_uid != st_undo.st_uid
1827 		&& st_undo.st_uid != getuid())
1828 	{
1829 	    if (p_verbose > 0)
1830 	    {
1831 		verbose_enter();
1832 		smsg(_("Not reading undo file, owner differs: %s"),
1833 								   file_name);
1834 		verbose_leave();
1835 	    }
1836 	    return;
1837 	}
1838 #endif
1839     }
1840     else
1841 	file_name = name;
1842 
1843     if (p_verbose > 0)
1844     {
1845 	verbose_enter();
1846 	smsg(_("Reading undo file: %s"), file_name);
1847 	verbose_leave();
1848     }
1849 
1850     fp = mch_fopen((char *)file_name, "r");
1851     if (fp == NULL)
1852     {
1853 	if (name != NULL || p_verbose > 0)
1854 	    semsg(_("E822: Cannot open undo file for reading: %s"), file_name);
1855 	goto error;
1856     }
1857     bi.bi_buf = curbuf;
1858     bi.bi_fp = fp;
1859 
1860     /*
1861      * Read the undo file header.
1862      */
1863     if (fread(magic_buf, UF_START_MAGIC_LEN, 1, fp) != 1
1864 		|| memcmp(magic_buf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0)
1865     {
1866 	semsg(_("E823: Not an undo file: %s"), file_name);
1867 	goto error;
1868     }
1869     version = get2c(fp);
1870     if (version == UF_VERSION_CRYPT)
1871     {
1872 #ifdef FEAT_CRYPT
1873 	if (*curbuf->b_p_key == NUL)
1874 	{
1875 	    semsg(_("E832: Non-encrypted file has encrypted undo file: %s"),
1876 								   file_name);
1877 	    goto error;
1878 	}
1879 	bi.bi_state = crypt_create_from_file(fp, curbuf->b_p_key);
1880 	if (bi.bi_state == NULL)
1881 	{
1882 	    semsg(_("E826: Undo file decryption failed: %s"), file_name);
1883 	    goto error;
1884 	}
1885 	if (crypt_whole_undofile(bi.bi_state->method_nr))
1886 	{
1887 	    bi.bi_buffer = alloc(CRYPT_BUF_SIZE);
1888 	    if (bi.bi_buffer == NULL)
1889 	    {
1890 		crypt_free_state(bi.bi_state);
1891 		bi.bi_state = NULL;
1892 		goto error;
1893 	    }
1894 	    bi.bi_avail = 0;
1895 	    bi.bi_used = 0;
1896 	}
1897 #else
1898 	semsg(_("E827: Undo file is encrypted: %s"), file_name);
1899 	goto error;
1900 #endif
1901     }
1902     else if (version != UF_VERSION)
1903     {
1904 	semsg(_("E824: Incompatible undo file: %s"), file_name);
1905 	goto error;
1906     }
1907 
1908     if (undo_read(&bi, read_hash, (size_t)UNDO_HASH_SIZE) == FAIL)
1909     {
1910 	corruption_error("hash", file_name);
1911 	goto error;
1912     }
1913     line_count = (linenr_T)undo_read_4c(&bi);
1914     if (memcmp(hash, read_hash, UNDO_HASH_SIZE) != 0
1915 				  || line_count != curbuf->b_ml.ml_line_count)
1916     {
1917 	if (p_verbose > 0 || name != NULL)
1918 	{
1919 	    if (name == NULL)
1920 		verbose_enter();
1921 	    give_warning((char_u *)
1922 		      _("File contents changed, cannot use undo info"), TRUE);
1923 	    if (name == NULL)
1924 		verbose_leave();
1925 	}
1926 	goto error;
1927     }
1928 
1929     /* Read undo data for "U" command. */
1930     str_len = undo_read_4c(&bi);
1931     if (str_len < 0)
1932 	goto error;
1933     if (str_len > 0)
1934     {
1935 	line_ptr.ul_line = read_string_decrypt(&bi, str_len);
1936 	line_ptr.ul_len = str_len + 1;
1937     }
1938     line_lnum = (linenr_T)undo_read_4c(&bi);
1939     line_colnr = (colnr_T)undo_read_4c(&bi);
1940     if (line_lnum < 0 || line_colnr < 0)
1941     {
1942 	corruption_error("line lnum/col", file_name);
1943 	goto error;
1944     }
1945 
1946     /* Begin general undo data */
1947     old_header_seq = undo_read_4c(&bi);
1948     new_header_seq = undo_read_4c(&bi);
1949     cur_header_seq = undo_read_4c(&bi);
1950     num_head = undo_read_4c(&bi);
1951     seq_last = undo_read_4c(&bi);
1952     seq_cur = undo_read_4c(&bi);
1953     seq_time = undo_read_time(&bi);
1954 
1955     /* Optional header fields. */
1956     for (;;)
1957     {
1958 	int len = undo_read_byte(&bi);
1959 	int what;
1960 
1961 	if (len == 0 || len == EOF)
1962 	    break;
1963 	what = undo_read_byte(&bi);
1964 	switch (what)
1965 	{
1966 	    case UF_LAST_SAVE_NR:
1967 		last_save_nr = undo_read_4c(&bi);
1968 		break;
1969 	    default:
1970 		/* field not supported, skip */
1971 		while (--len >= 0)
1972 		    (void)undo_read_byte(&bi);
1973 	}
1974     }
1975 
1976     /* uhp_table will store the freshly created undo headers we allocate
1977      * until we insert them into curbuf. The table remains sorted by the
1978      * sequence numbers of the headers.
1979      * When there are no headers uhp_table is NULL. */
1980     if (num_head > 0)
1981     {
1982 	if (num_head < LONG_MAX / (long)sizeof(u_header_T *))
1983 	    uhp_table = U_ALLOC_LINE(num_head * sizeof(u_header_T *));
1984 	if (uhp_table == NULL)
1985 	    goto error;
1986     }
1987 
1988     while ((c = undo_read_2c(&bi)) == UF_HEADER_MAGIC)
1989     {
1990 	if (num_read_uhps >= num_head)
1991 	{
1992 	    corruption_error("num_head too small", file_name);
1993 	    goto error;
1994 	}
1995 
1996 	uhp = unserialize_uhp(&bi, file_name);
1997 	if (uhp == NULL)
1998 	    goto error;
1999 	uhp_table[num_read_uhps++] = uhp;
2000     }
2001 
2002     if (num_read_uhps != num_head)
2003     {
2004 	corruption_error("num_head", file_name);
2005 	goto error;
2006     }
2007     if (c != UF_HEADER_END_MAGIC)
2008     {
2009 	corruption_error("end marker", file_name);
2010 	goto error;
2011     }
2012 
2013 #ifdef U_DEBUG
2014     uhp_table_used = alloc_clear(sizeof(int) * num_head + 1);
2015 # define SET_FLAG(j) ++uhp_table_used[j]
2016 #else
2017 # define SET_FLAG(j)
2018 #endif
2019 
2020     /* We have put all of the headers into a table. Now we iterate through the
2021      * table and swizzle each sequence number we have stored in uh_*_seq into
2022      * a pointer corresponding to the header with that sequence number. */
2023     for (i = 0; i < num_head; i++)
2024     {
2025 	uhp = uhp_table[i];
2026 	if (uhp == NULL)
2027 	    continue;
2028 	for (j = 0; j < num_head; j++)
2029 	    if (uhp_table[j] != NULL && i != j
2030 			      && uhp_table[i]->uh_seq == uhp_table[j]->uh_seq)
2031 	    {
2032 		corruption_error("duplicate uh_seq", file_name);
2033 		goto error;
2034 	    }
2035 	for (j = 0; j < num_head; j++)
2036 	    if (uhp_table[j] != NULL
2037 				  && uhp_table[j]->uh_seq == uhp->uh_next.seq)
2038 	    {
2039 		uhp->uh_next.ptr = uhp_table[j];
2040 		SET_FLAG(j);
2041 		break;
2042 	    }
2043 	for (j = 0; j < num_head; j++)
2044 	    if (uhp_table[j] != NULL
2045 				  && uhp_table[j]->uh_seq == uhp->uh_prev.seq)
2046 	    {
2047 		uhp->uh_prev.ptr = uhp_table[j];
2048 		SET_FLAG(j);
2049 		break;
2050 	    }
2051 	for (j = 0; j < num_head; j++)
2052 	    if (uhp_table[j] != NULL
2053 			      && uhp_table[j]->uh_seq == uhp->uh_alt_next.seq)
2054 	    {
2055 		uhp->uh_alt_next.ptr = uhp_table[j];
2056 		SET_FLAG(j);
2057 		break;
2058 	    }
2059 	for (j = 0; j < num_head; j++)
2060 	    if (uhp_table[j] != NULL
2061 			      && uhp_table[j]->uh_seq == uhp->uh_alt_prev.seq)
2062 	    {
2063 		uhp->uh_alt_prev.ptr = uhp_table[j];
2064 		SET_FLAG(j);
2065 		break;
2066 	    }
2067 	if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq)
2068 	{
2069 	    old_idx = i;
2070 	    SET_FLAG(i);
2071 	}
2072 	if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq)
2073 	{
2074 	    new_idx = i;
2075 	    SET_FLAG(i);
2076 	}
2077 	if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq)
2078 	{
2079 	    cur_idx = i;
2080 	    SET_FLAG(i);
2081 	}
2082     }
2083 
2084     /* Now that we have read the undo info successfully, free the current undo
2085      * info and use the info from the file. */
2086     u_blockfree(curbuf);
2087     curbuf->b_u_oldhead = old_idx < 0 ? NULL : uhp_table[old_idx];
2088     curbuf->b_u_newhead = new_idx < 0 ? NULL : uhp_table[new_idx];
2089     curbuf->b_u_curhead = cur_idx < 0 ? NULL : uhp_table[cur_idx];
2090     curbuf->b_u_line_ptr = line_ptr;
2091     curbuf->b_u_line_lnum = line_lnum;
2092     curbuf->b_u_line_colnr = line_colnr;
2093     curbuf->b_u_numhead = num_head;
2094     curbuf->b_u_seq_last = seq_last;
2095     curbuf->b_u_seq_cur = seq_cur;
2096     curbuf->b_u_time_cur = seq_time;
2097     curbuf->b_u_save_nr_last = last_save_nr;
2098     curbuf->b_u_save_nr_cur = last_save_nr;
2099 
2100     curbuf->b_u_synced = TRUE;
2101     vim_free(uhp_table);
2102 
2103 #ifdef U_DEBUG
2104     for (i = 0; i < num_head; ++i)
2105 	if (uhp_table_used[i] == 0)
2106 	    semsg("uhp_table entry %ld not used, leaking memory", i);
2107     vim_free(uhp_table_used);
2108     u_check(TRUE);
2109 #endif
2110 
2111     if (name != NULL)
2112 	smsg(_("Finished reading undo file %s"), file_name);
2113     goto theend;
2114 
2115 error:
2116     vim_free(line_ptr.ul_line);
2117     if (uhp_table != NULL)
2118     {
2119 	for (i = 0; i < num_read_uhps; i++)
2120 	    if (uhp_table[i] != NULL)
2121 		u_free_uhp(uhp_table[i]);
2122 	vim_free(uhp_table);
2123     }
2124 
2125 theend:
2126 #ifdef FEAT_CRYPT
2127     if (bi.bi_state != NULL)
2128 	crypt_free_state(bi.bi_state);
2129     vim_free(bi.bi_buffer);
2130 #endif
2131     if (fp != NULL)
2132 	fclose(fp);
2133     if (file_name != name)
2134 	vim_free(file_name);
2135     return;
2136 }
2137 
2138 #endif /* FEAT_PERSISTENT_UNDO */
2139 
2140 
2141 /*
2142  * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible).
2143  * If 'cpoptions' does not contain 'u': Always undo.
2144  */
2145     void
2146 u_undo(int count)
2147 {
2148     /*
2149      * If we get an undo command while executing a macro, we behave like the
2150      * original vi. If this happens twice in one macro the result will not
2151      * be compatible.
2152      */
2153     if (curbuf->b_u_synced == FALSE)
2154     {
2155 	u_sync(TRUE);
2156 	count = 1;
2157     }
2158 
2159     if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
2160 	undo_undoes = TRUE;
2161     else
2162 	undo_undoes = !undo_undoes;
2163     u_doit(count);
2164 }
2165 
2166 /*
2167  * If 'cpoptions' contains 'u': Repeat the previous undo or redo.
2168  * If 'cpoptions' does not contain 'u': Always redo.
2169  */
2170     void
2171 u_redo(int count)
2172 {
2173     if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
2174 	undo_undoes = FALSE;
2175     u_doit(count);
2176 }
2177 
2178 /*
2179  * Undo or redo, depending on 'undo_undoes', 'count' times.
2180  */
2181     static void
2182 u_doit(int startcount)
2183 {
2184     int count = startcount;
2185 
2186     if (!undo_allowed())
2187 	return;
2188 
2189     u_newcount = 0;
2190     u_oldcount = 0;
2191     if (curbuf->b_ml.ml_flags & ML_EMPTY)
2192 	u_oldcount = -1;
2193     while (count--)
2194     {
2195 	/* Do the change warning now, so that it triggers FileChangedRO when
2196 	 * needed.  This may cause the file to be reloaded, that must happen
2197 	 * before we do anything, because it may change curbuf->b_u_curhead
2198 	 * and more. */
2199 	change_warning(0);
2200 
2201 	if (undo_undoes)
2202 	{
2203 	    if (curbuf->b_u_curhead == NULL)		/* first undo */
2204 		curbuf->b_u_curhead = curbuf->b_u_newhead;
2205 	    else if (get_undolevel() > 0)		/* multi level undo */
2206 		/* get next undo */
2207 		curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next.ptr;
2208 	    /* nothing to undo */
2209 	    if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL)
2210 	    {
2211 		/* stick curbuf->b_u_curhead at end */
2212 		curbuf->b_u_curhead = curbuf->b_u_oldhead;
2213 		beep_flush();
2214 		if (count == startcount - 1)
2215 		{
2216 		    msg(_("Already at oldest change"));
2217 		    return;
2218 		}
2219 		break;
2220 	    }
2221 
2222 	    u_undoredo(TRUE);
2223 	}
2224 	else
2225 	{
2226 	    if (curbuf->b_u_curhead == NULL || get_undolevel() <= 0)
2227 	    {
2228 		beep_flush();	/* nothing to redo */
2229 		if (count == startcount - 1)
2230 		{
2231 		    msg(_("Already at newest change"));
2232 		    return;
2233 		}
2234 		break;
2235 	    }
2236 
2237 	    u_undoredo(FALSE);
2238 
2239 	    /* Advance for next redo.  Set "newhead" when at the end of the
2240 	     * redoable changes. */
2241 	    if (curbuf->b_u_curhead->uh_prev.ptr == NULL)
2242 		curbuf->b_u_newhead = curbuf->b_u_curhead;
2243 	    curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev.ptr;
2244 	}
2245     }
2246     u_undo_end(undo_undoes, FALSE);
2247 }
2248 
2249 /*
2250  * Undo or redo over the timeline.
2251  * When "step" is negative go back in time, otherwise goes forward in time.
2252  * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as
2253  * seconds.
2254  * When "file" is TRUE use "step" as a number of file writes.
2255  * When "absolute" is TRUE use "step" as the sequence number to jump to.
2256  * "sec" must be FALSE then.
2257  */
2258     void
2259 undo_time(
2260     long	step,
2261     int		sec,
2262     int		file,
2263     int		absolute)
2264 {
2265     long	    target;
2266     long	    closest;
2267     long	    closest_start;
2268     long	    closest_seq = 0;
2269     long	    val;
2270     u_header_T	    *uhp = NULL;
2271     u_header_T	    *last;
2272     int		    mark;
2273     int		    nomark = 0;  // shut up compiler
2274     int		    round;
2275     int		    dosec = sec;
2276     int		    dofile = file;
2277     int		    above = FALSE;
2278     int		    did_undo = TRUE;
2279 
2280     /* First make sure the current undoable change is synced. */
2281     if (curbuf->b_u_synced == FALSE)
2282 	u_sync(TRUE);
2283 
2284     u_newcount = 0;
2285     u_oldcount = 0;
2286     if (curbuf->b_ml.ml_flags & ML_EMPTY)
2287 	u_oldcount = -1;
2288 
2289     /* "target" is the node below which we want to be.
2290      * Init "closest" to a value we can't reach. */
2291     if (absolute)
2292     {
2293 	target = step;
2294 	closest = -1;
2295     }
2296     else
2297     {
2298 	if (dosec)
2299 	    target = (long)(curbuf->b_u_time_cur) + step;
2300 	else if (dofile)
2301 	{
2302 	    if (step < 0)
2303 	    {
2304 		/* Going back to a previous write. If there were changes after
2305 		 * the last write, count that as moving one file-write, so
2306 		 * that ":earlier 1f" undoes all changes since the last save. */
2307 		uhp = curbuf->b_u_curhead;
2308 		if (uhp != NULL)
2309 		    uhp = uhp->uh_next.ptr;
2310 		else
2311 		    uhp = curbuf->b_u_newhead;
2312 		if (uhp != NULL && uhp->uh_save_nr != 0)
2313 		    /* "uh_save_nr" was set in the last block, that means
2314 		     * there were no changes since the last write */
2315 		    target = curbuf->b_u_save_nr_cur + step;
2316 		else
2317 		    /* count the changes since the last write as one step */
2318 		    target = curbuf->b_u_save_nr_cur + step + 1;
2319 		if (target <= 0)
2320 		    /* Go to before first write: before the oldest change. Use
2321 		     * the sequence number for that. */
2322 		    dofile = FALSE;
2323 	    }
2324 	    else
2325 	    {
2326 		/* Moving forward to a newer write. */
2327 		target = curbuf->b_u_save_nr_cur + step;
2328 		if (target > curbuf->b_u_save_nr_last)
2329 		{
2330 		    /* Go to after last write: after the latest change. Use
2331 		     * the sequence number for that. */
2332 		    target = curbuf->b_u_seq_last + 1;
2333 		    dofile = FALSE;
2334 		}
2335 	    }
2336 	}
2337 	else
2338 	    target = curbuf->b_u_seq_cur + step;
2339 	if (step < 0)
2340 	{
2341 	    if (target < 0)
2342 		target = 0;
2343 	    closest = -1;
2344 	}
2345 	else
2346 	{
2347 	    if (dosec)
2348 		closest = (long)(vim_time() + 1);
2349 	    else if (dofile)
2350 		closest = curbuf->b_u_save_nr_last + 2;
2351 	    else
2352 		closest = curbuf->b_u_seq_last + 2;
2353 	    if (target >= closest)
2354 		target = closest - 1;
2355 	}
2356     }
2357     closest_start = closest;
2358     closest_seq = curbuf->b_u_seq_cur;
2359 
2360     /* When "target" is 0; Back to origin. */
2361     if (target == 0)
2362     {
2363 	mark = lastmark;  /* avoid that GCC complains */
2364 	goto target_zero;
2365     }
2366 
2367     /*
2368      * May do this twice:
2369      * 1. Search for "target", update "closest" to the best match found.
2370      * 2. If "target" not found search for "closest".
2371      *
2372      * When using the closest time we use the sequence number in the second
2373      * round, because there may be several entries with the same time.
2374      */
2375     for (round = 1; round <= 2; ++round)
2376     {
2377 	/* Find the path from the current state to where we want to go.  The
2378 	 * desired state can be anywhere in the undo tree, need to go all over
2379 	 * it.  We put "nomark" in uh_walk where we have been without success,
2380 	 * "mark" where it could possibly be. */
2381 	mark = ++lastmark;
2382 	nomark = ++lastmark;
2383 
2384 	if (curbuf->b_u_curhead == NULL)	/* at leaf of the tree */
2385 	    uhp = curbuf->b_u_newhead;
2386 	else
2387 	    uhp = curbuf->b_u_curhead;
2388 
2389 	while (uhp != NULL)
2390 	{
2391 	    uhp->uh_walk = mark;
2392 	    if (dosec)
2393 		val = (long)(uhp->uh_time);
2394 	    else if (dofile)
2395 		val = uhp->uh_save_nr;
2396 	    else
2397 		val = uhp->uh_seq;
2398 
2399 	    if (round == 1 && !(dofile && val == 0))
2400 	    {
2401 		/* Remember the header that is closest to the target.
2402 		 * It must be at least in the right direction (checked with
2403 		 * "b_u_seq_cur").  When the timestamp is equal find the
2404 		 * highest/lowest sequence number. */
2405 		if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur
2406 			      : uhp->uh_seq > curbuf->b_u_seq_cur)
2407 			&& ((dosec && val == closest)
2408 			    ? (step < 0
2409 				? uhp->uh_seq < closest_seq
2410 				: uhp->uh_seq > closest_seq)
2411 			    : closest == closest_start
2412 				|| (val > target
2413 				    ? (closest > target
2414 					? val - target <= closest - target
2415 					: val - target <= target - closest)
2416 				    : (closest > target
2417 					? target - val <= closest - target
2418 					: target - val <= target - closest))))
2419 		{
2420 		    closest = val;
2421 		    closest_seq = uhp->uh_seq;
2422 		}
2423 	    }
2424 
2425 	    /* Quit searching when we found a match.  But when searching for a
2426 	     * time we need to continue looking for the best uh_seq. */
2427 	    if (target == val && !dosec)
2428 	    {
2429 		target = uhp->uh_seq;
2430 		break;
2431 	    }
2432 
2433 	    /* go down in the tree if we haven't been there */
2434 	    if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark
2435 					 && uhp->uh_prev.ptr->uh_walk != mark)
2436 		uhp = uhp->uh_prev.ptr;
2437 
2438 	    /* go to alternate branch if we haven't been there */
2439 	    else if (uhp->uh_alt_next.ptr != NULL
2440 		    && uhp->uh_alt_next.ptr->uh_walk != nomark
2441 		    && uhp->uh_alt_next.ptr->uh_walk != mark)
2442 		uhp = uhp->uh_alt_next.ptr;
2443 
2444 	    /* go up in the tree if we haven't been there and we are at the
2445 	     * start of alternate branches */
2446 	    else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL
2447 		    && uhp->uh_next.ptr->uh_walk != nomark
2448 		    && uhp->uh_next.ptr->uh_walk != mark)
2449 	    {
2450 		/* If still at the start we don't go through this change. */
2451 		if (uhp == curbuf->b_u_curhead)
2452 		    uhp->uh_walk = nomark;
2453 		uhp = uhp->uh_next.ptr;
2454 	    }
2455 
2456 	    else
2457 	    {
2458 		/* need to backtrack; mark this node as useless */
2459 		uhp->uh_walk = nomark;
2460 		if (uhp->uh_alt_prev.ptr != NULL)
2461 		    uhp = uhp->uh_alt_prev.ptr;
2462 		else
2463 		    uhp = uhp->uh_next.ptr;
2464 	    }
2465 	}
2466 
2467 	if (uhp != NULL)    /* found it */
2468 	    break;
2469 
2470 	if (absolute)
2471 	{
2472 	    semsg(_("E830: Undo number %ld not found"), step);
2473 	    return;
2474 	}
2475 
2476 	if (closest == closest_start)
2477 	{
2478 	    if (step < 0)
2479 		msg(_("Already at oldest change"));
2480 	    else
2481 		msg(_("Already at newest change"));
2482 	    return;
2483 	}
2484 
2485 	target = closest_seq;
2486 	dosec = FALSE;
2487 	dofile = FALSE;
2488 	if (step < 0)
2489 	    above = TRUE;	/* stop above the header */
2490     }
2491 
2492 target_zero:
2493     /* If we found it: Follow the path to go to where we want to be. */
2494     if (uhp != NULL || target == 0)
2495     {
2496 	/*
2497 	 * First go up the tree as much as needed.
2498 	 */
2499 	while (!got_int)
2500 	{
2501 	    /* Do the change warning now, for the same reason as above. */
2502 	    change_warning(0);
2503 
2504 	    uhp = curbuf->b_u_curhead;
2505 	    if (uhp == NULL)
2506 		uhp = curbuf->b_u_newhead;
2507 	    else
2508 		uhp = uhp->uh_next.ptr;
2509 	    if (uhp == NULL || (target > 0 && uhp->uh_walk != mark)
2510 					 || (uhp->uh_seq == target && !above))
2511 		break;
2512 	    curbuf->b_u_curhead = uhp;
2513 	    u_undoredo(TRUE);
2514 	    if (target > 0)
2515 		uhp->uh_walk = nomark;	/* don't go back down here */
2516 	}
2517 
2518 	/* When back to origin, redo is not needed. */
2519 	if (target > 0)
2520 	{
2521 	    /*
2522 	     * And now go down the tree (redo), branching off where needed.
2523 	     */
2524 	    while (!got_int)
2525 	    {
2526 		/* Do the change warning now, for the same reason as above. */
2527 		change_warning(0);
2528 
2529 		uhp = curbuf->b_u_curhead;
2530 		if (uhp == NULL)
2531 		    break;
2532 
2533 		/* Go back to the first branch with a mark. */
2534 		while (uhp->uh_alt_prev.ptr != NULL
2535 				     && uhp->uh_alt_prev.ptr->uh_walk == mark)
2536 		    uhp = uhp->uh_alt_prev.ptr;
2537 
2538 		/* Find the last branch with a mark, that's the one. */
2539 		last = uhp;
2540 		while (last->uh_alt_next.ptr != NULL
2541 				    && last->uh_alt_next.ptr->uh_walk == mark)
2542 		    last = last->uh_alt_next.ptr;
2543 		if (last != uhp)
2544 		{
2545 		    /* Make the used branch the first entry in the list of
2546 		     * alternatives to make "u" and CTRL-R take this branch. */
2547 		    while (uhp->uh_alt_prev.ptr != NULL)
2548 			uhp = uhp->uh_alt_prev.ptr;
2549 		    if (last->uh_alt_next.ptr != NULL)
2550 			last->uh_alt_next.ptr->uh_alt_prev.ptr =
2551 							last->uh_alt_prev.ptr;
2552 		    last->uh_alt_prev.ptr->uh_alt_next.ptr =
2553 							last->uh_alt_next.ptr;
2554 		    last->uh_alt_prev.ptr = NULL;
2555 		    last->uh_alt_next.ptr = uhp;
2556 		    uhp->uh_alt_prev.ptr = last;
2557 
2558 		    if (curbuf->b_u_oldhead == uhp)
2559 			curbuf->b_u_oldhead = last;
2560 		    uhp = last;
2561 		    if (uhp->uh_next.ptr != NULL)
2562 			uhp->uh_next.ptr->uh_prev.ptr = uhp;
2563 		}
2564 		curbuf->b_u_curhead = uhp;
2565 
2566 		if (uhp->uh_walk != mark)
2567 		    break;	    /* must have reached the target */
2568 
2569 		/* Stop when going backwards in time and didn't find the exact
2570 		 * header we were looking for. */
2571 		if (uhp->uh_seq == target && above)
2572 		{
2573 		    curbuf->b_u_seq_cur = target - 1;
2574 		    break;
2575 		}
2576 
2577 		u_undoredo(FALSE);
2578 
2579 		/* Advance "curhead" to below the header we last used.  If it
2580 		 * becomes NULL then we need to set "newhead" to this leaf. */
2581 		if (uhp->uh_prev.ptr == NULL)
2582 		    curbuf->b_u_newhead = uhp;
2583 		curbuf->b_u_curhead = uhp->uh_prev.ptr;
2584 		did_undo = FALSE;
2585 
2586 		if (uhp->uh_seq == target)	/* found it! */
2587 		    break;
2588 
2589 		uhp = uhp->uh_prev.ptr;
2590 		if (uhp == NULL || uhp->uh_walk != mark)
2591 		{
2592 		    /* Need to redo more but can't find it... */
2593 		    internal_error("undo_time()");
2594 		    break;
2595 		}
2596 	    }
2597 	}
2598     }
2599     u_undo_end(did_undo, absolute);
2600 }
2601 
2602 /*
2603  * u_undoredo: common code for undo and redo
2604  *
2605  * The lines in the file are replaced by the lines in the entry list at
2606  * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry
2607  * list for the next undo/redo.
2608  *
2609  * When "undo" is TRUE we go up in the tree, when FALSE we go down.
2610  */
2611     static void
2612 u_undoredo(int undo)
2613 {
2614     undoline_T	*newarray = NULL;
2615     linenr_T	oldsize;
2616     linenr_T	newsize;
2617     linenr_T	top, bot;
2618     linenr_T	lnum;
2619     linenr_T	newlnum = MAXLNUM;
2620     long	i;
2621     u_entry_T	*uep, *nuep;
2622     u_entry_T	*newlist = NULL;
2623     int		old_flags;
2624     int		new_flags;
2625     pos_T	namedm[NMARKS];
2626     visualinfo_T visualinfo;
2627     int		empty_buffer;		    /* buffer became empty */
2628     u_header_T	*curhead = curbuf->b_u_curhead;
2629 
2630     /* Don't want autocommands using the undo structures here, they are
2631      * invalid till the end. */
2632     block_autocmds();
2633 
2634 #ifdef U_DEBUG
2635     u_check(FALSE);
2636 #endif
2637     old_flags = curhead->uh_flags;
2638     new_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
2639 	       ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
2640     setpcmark();
2641 
2642     /*
2643      * save marks before undo/redo
2644      */
2645     mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
2646     visualinfo = curbuf->b_visual;
2647     curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count;
2648     curbuf->b_op_start.col = 0;
2649     curbuf->b_op_end.lnum = 0;
2650     curbuf->b_op_end.col = 0;
2651 
2652     for (uep = curhead->uh_entry; uep != NULL; uep = nuep)
2653     {
2654 	top = uep->ue_top;
2655 	bot = uep->ue_bot;
2656 	if (bot == 0)
2657 	    bot = curbuf->b_ml.ml_line_count + 1;
2658 	if (top > curbuf->b_ml.ml_line_count || top >= bot
2659 				      || bot > curbuf->b_ml.ml_line_count + 1)
2660 	{
2661 	    unblock_autocmds();
2662 	    iemsg(_("E438: u_undo: line numbers wrong"));
2663 	    changed();		/* don't want UNCHANGED now */
2664 	    return;
2665 	}
2666 
2667 	oldsize = bot - top - 1;    /* number of lines before undo */
2668 	newsize = uep->ue_size;	    /* number of lines after undo */
2669 
2670 	if (top < newlnum)
2671 	{
2672 	    /* If the saved cursor is somewhere in this undo block, move it to
2673 	     * the remembered position.  Makes "gwap" put the cursor back
2674 	     * where it was. */
2675 	    lnum = curhead->uh_cursor.lnum;
2676 	    if (lnum >= top && lnum <= top + newsize + 1)
2677 	    {
2678 		curwin->w_cursor = curhead->uh_cursor;
2679 		newlnum = curwin->w_cursor.lnum - 1;
2680 	    }
2681 	    else
2682 	    {
2683 		/* Use the first line that actually changed.  Avoids that
2684 		 * undoing auto-formatting puts the cursor in the previous
2685 		 * line. */
2686 		for (i = 0; i < newsize && i < oldsize; ++i)
2687 		{
2688 		    char_u *p = ml_get(top + 1 + i);
2689 
2690 		    if (curbuf->b_ml.ml_line_len != uep->ue_array[i].ul_len
2691 			    || memcmp(uep->ue_array[i].ul_line, p,
2692 						curbuf->b_ml.ml_line_len) != 0)
2693 			break;
2694 		}
2695 		if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL)
2696 		{
2697 		    newlnum = top;
2698 		    curwin->w_cursor.lnum = newlnum + 1;
2699 		}
2700 		else if (i < newsize)
2701 		{
2702 		    newlnum = top + i;
2703 		    curwin->w_cursor.lnum = newlnum + 1;
2704 		}
2705 	    }
2706 	}
2707 
2708 	empty_buffer = FALSE;
2709 
2710 	/* delete the lines between top and bot and save them in newarray */
2711 	if (oldsize > 0)
2712 	{
2713 	    if ((newarray = U_ALLOC_LINE(sizeof(undoline_T) * oldsize)) == NULL)
2714 	    {
2715 		do_outofmem_msg((long_u)(sizeof(undoline_T) * oldsize));
2716 		/*
2717 		 * We have messed up the entry list, repair is impossible.
2718 		 * we have to free the rest of the list.
2719 		 */
2720 		while (uep != NULL)
2721 		{
2722 		    nuep = uep->ue_next;
2723 		    u_freeentry(uep, uep->ue_size);
2724 		    uep = nuep;
2725 		}
2726 		break;
2727 	    }
2728 	    /* delete backwards, it goes faster in most cases */
2729 	    for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum)
2730 	    {
2731 		/* what can we do when we run out of memory? */
2732 		if (u_save_line(&newarray[i], lnum) == FAIL)
2733 		    do_outofmem_msg((long_u)0);
2734 		/* remember we deleted the last line in the buffer, and a
2735 		 * dummy empty line will be inserted */
2736 		if (curbuf->b_ml.ml_line_count == 1)
2737 		    empty_buffer = TRUE;
2738 		ml_delete(lnum, FALSE);
2739 	    }
2740 	}
2741 	else
2742 	    newarray = NULL;
2743 
2744 	/* insert the lines in u_array between top and bot */
2745 	if (newsize)
2746 	{
2747 	    for (lnum = top, i = 0; i < newsize; ++i, ++lnum)
2748 	    {
2749 		// If the file is empty, there is an empty line 1 that we
2750 		// should get rid of, by replacing it with the new line.
2751 		if (empty_buffer && lnum == 0)
2752 		    ml_replace_len((linenr_T)1, uep->ue_array[i].ul_line,
2753 					  uep->ue_array[i].ul_len, TRUE, TRUE);
2754 		else
2755 		    ml_append(lnum, uep->ue_array[i].ul_line,
2756 				      (colnr_T)uep->ue_array[i].ul_len, FALSE);
2757 		vim_free(uep->ue_array[i].ul_line);
2758 	    }
2759 	    vim_free((char_u *)uep->ue_array);
2760 	}
2761 
2762 	/* adjust marks */
2763 	if (oldsize != newsize)
2764 	{
2765 	    mark_adjust(top + 1, top + oldsize, (long)MAXLNUM,
2766 					       (long)newsize - (long)oldsize);
2767 	    if (curbuf->b_op_start.lnum > top + oldsize)
2768 		curbuf->b_op_start.lnum += newsize - oldsize;
2769 	    if (curbuf->b_op_end.lnum > top + oldsize)
2770 		curbuf->b_op_end.lnum += newsize - oldsize;
2771 	}
2772 
2773 	changed_lines(top + 1, 0, bot, newsize - oldsize);
2774 
2775 	/* set '[ and '] mark */
2776 	if (top + 1 < curbuf->b_op_start.lnum)
2777 	    curbuf->b_op_start.lnum = top + 1;
2778 	if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum)
2779 	    curbuf->b_op_end.lnum = top + 1;
2780 	else if (top + newsize > curbuf->b_op_end.lnum)
2781 	    curbuf->b_op_end.lnum = top + newsize;
2782 
2783 	u_newcount += newsize;
2784 	u_oldcount += oldsize;
2785 	uep->ue_size = oldsize;
2786 	uep->ue_array = newarray;
2787 	uep->ue_bot = top + newsize + 1;
2788 
2789 	/*
2790 	 * insert this entry in front of the new entry list
2791 	 */
2792 	nuep = uep->ue_next;
2793 	uep->ue_next = newlist;
2794 	newlist = uep;
2795     }
2796 
2797     curhead->uh_entry = newlist;
2798     curhead->uh_flags = new_flags;
2799     if ((old_flags & UH_EMPTYBUF) && BUFEMPTY())
2800 	curbuf->b_ml.ml_flags |= ML_EMPTY;
2801     if (old_flags & UH_CHANGED)
2802 	changed();
2803     else
2804 #ifdef FEAT_NETBEANS_INTG
2805 	/* per netbeans undo rules, keep it as modified */
2806 	if (!isNetbeansModified(curbuf))
2807 #endif
2808 	unchanged(curbuf, FALSE, TRUE);
2809 
2810     /*
2811      * restore marks from before undo/redo
2812      */
2813     for (i = 0; i < NMARKS; ++i)
2814     {
2815 	if (curhead->uh_namedm[i].lnum != 0)
2816 	    curbuf->b_namedm[i] = curhead->uh_namedm[i];
2817 	if (namedm[i].lnum != 0)
2818 	    curhead->uh_namedm[i] = namedm[i];
2819 	else
2820 	    curhead->uh_namedm[i].lnum = 0;
2821     }
2822     if (curhead->uh_visual.vi_start.lnum != 0)
2823     {
2824 	curbuf->b_visual = curhead->uh_visual;
2825 	curhead->uh_visual = visualinfo;
2826     }
2827 
2828     /*
2829      * If the cursor is only off by one line, put it at the same position as
2830      * before starting the change (for the "o" command).
2831      * Otherwise the cursor should go to the first undone line.
2832      */
2833     if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum
2834 						 && curwin->w_cursor.lnum > 1)
2835 	--curwin->w_cursor.lnum;
2836     if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count)
2837     {
2838 	if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum)
2839 	{
2840 	    curwin->w_cursor.col = curhead->uh_cursor.col;
2841 	    if (virtual_active() && curhead->uh_cursor_vcol >= 0)
2842 		coladvance((colnr_T)curhead->uh_cursor_vcol);
2843 	    else
2844 		curwin->w_cursor.coladd = 0;
2845 	}
2846 	else
2847 	    beginline(BL_SOL | BL_FIX);
2848     }
2849     else
2850     {
2851 	/* We get here with the current cursor line being past the end (eg
2852 	 * after adding lines at the end of the file, and then undoing it).
2853 	 * check_cursor() will move the cursor to the last line.  Move it to
2854 	 * the first column here. */
2855 	curwin->w_cursor.col = 0;
2856 	curwin->w_cursor.coladd = 0;
2857     }
2858 
2859     /* Make sure the cursor is on an existing line and column. */
2860     check_cursor();
2861 
2862     /* Remember where we are for "g-" and ":earlier 10s". */
2863     curbuf->b_u_seq_cur = curhead->uh_seq;
2864     if (undo)
2865     {
2866 	/* We are below the previous undo.  However, to make ":earlier 1s"
2867 	 * work we compute this as being just above the just undone change. */
2868 	if (curhead->uh_next.ptr != NULL)
2869 	    curbuf->b_u_seq_cur = curhead->uh_next.ptr->uh_seq;
2870 	else
2871 	    curbuf->b_u_seq_cur = 0;
2872     }
2873 
2874     /* Remember where we are for ":earlier 1f" and ":later 1f". */
2875     if (curhead->uh_save_nr != 0)
2876     {
2877 	if (undo)
2878 	    curbuf->b_u_save_nr_cur = curhead->uh_save_nr - 1;
2879 	else
2880 	    curbuf->b_u_save_nr_cur = curhead->uh_save_nr;
2881     }
2882 
2883     /* The timestamp can be the same for multiple changes, just use the one of
2884      * the undone/redone change. */
2885     curbuf->b_u_time_cur = curhead->uh_time;
2886 
2887     unblock_autocmds();
2888 #ifdef U_DEBUG
2889     u_check(FALSE);
2890 #endif
2891 }
2892 
2893 /*
2894  * If we deleted or added lines, report the number of less/more lines.
2895  * Otherwise, report the number of changes (this may be incorrect
2896  * in some cases, but it's better than nothing).
2897  */
2898     static void
2899 u_undo_end(
2900     int		did_undo,	/* just did an undo */
2901     int		absolute)	/* used ":undo N" */
2902 {
2903     char	*msgstr;
2904     u_header_T	*uhp;
2905     char_u	msgbuf[80];
2906 
2907 #ifdef FEAT_FOLDING
2908     if ((fdo_flags & FDO_UNDO) && KeyTyped)
2909 	foldOpenCursor();
2910 #endif
2911 
2912     if (global_busy	    /* no messages now, wait until global is finished */
2913 	    || !messaging())  /* 'lazyredraw' set, don't do messages now */
2914 	return;
2915 
2916     if (curbuf->b_ml.ml_flags & ML_EMPTY)
2917 	--u_newcount;
2918 
2919     u_oldcount -= u_newcount;
2920     if (u_oldcount == -1)
2921 	msgstr = N_("more line");
2922     else if (u_oldcount < 0)
2923 	msgstr = N_("more lines");
2924     else if (u_oldcount == 1)
2925 	msgstr = N_("line less");
2926     else if (u_oldcount > 1)
2927 	msgstr = N_("fewer lines");
2928     else
2929     {
2930 	u_oldcount = u_newcount;
2931 	if (u_newcount == 1)
2932 	    msgstr = N_("change");
2933 	else
2934 	    msgstr = N_("changes");
2935     }
2936 
2937     if (curbuf->b_u_curhead != NULL)
2938     {
2939 	/* For ":undo N" we prefer a "after #N" message. */
2940 	if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL)
2941 	{
2942 	    uhp = curbuf->b_u_curhead->uh_next.ptr;
2943 	    did_undo = FALSE;
2944 	}
2945 	else if (did_undo)
2946 	    uhp = curbuf->b_u_curhead;
2947 	else
2948 	    uhp = curbuf->b_u_curhead->uh_next.ptr;
2949     }
2950     else
2951 	uhp = curbuf->b_u_newhead;
2952 
2953     if (uhp == NULL)
2954 	*msgbuf = NUL;
2955     else
2956 	u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time);
2957 
2958 #ifdef FEAT_CONCEAL
2959     {
2960 	win_T	*wp;
2961 
2962 	FOR_ALL_WINDOWS(wp)
2963 	{
2964 	    if (wp->w_buffer == curbuf && wp->w_p_cole > 0)
2965 		redraw_win_later(wp, NOT_VALID);
2966 	}
2967     }
2968 #endif
2969 
2970     smsg_attr_keep(0, _("%ld %s; %s #%ld  %s"),
2971 	    u_oldcount < 0 ? -u_oldcount : u_oldcount,
2972 	    _(msgstr),
2973 	    did_undo ? _("before") : _("after"),
2974 	    uhp == NULL ? 0L : uhp->uh_seq,
2975 	    msgbuf);
2976 }
2977 
2978 /*
2979  * u_sync: stop adding to the current entry list
2980  */
2981     void
2982 u_sync(
2983     int	    force)	/* Also sync when no_u_sync is set. */
2984 {
2985     /* Skip it when already synced or syncing is disabled. */
2986     if (curbuf->b_u_synced || (!force && no_u_sync > 0))
2987 	return;
2988 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2989     if (p_imst == IM_ON_THE_SPOT && im_is_preediting())
2990 	return;		    /* XIM is busy, don't break an undo sequence */
2991 #endif
2992     if (get_undolevel() < 0)
2993 	curbuf->b_u_synced = TRUE;  /* no entries, nothing to do */
2994     else
2995     {
2996 	u_getbot();		    /* compute ue_bot of previous u_save */
2997 	curbuf->b_u_curhead = NULL;
2998     }
2999 }
3000 
3001 /*
3002  * ":undolist": List the leafs of the undo tree
3003  */
3004     void
3005 ex_undolist(exarg_T *eap UNUSED)
3006 {
3007     garray_T	ga;
3008     u_header_T	*uhp;
3009     int		mark;
3010     int		nomark;
3011     int		changes = 1;
3012     int		i;
3013 
3014     /*
3015      * 1: walk the tree to find all leafs, put the info in "ga".
3016      * 2: sort the lines
3017      * 3: display the list
3018      */
3019     mark = ++lastmark;
3020     nomark = ++lastmark;
3021     ga_init2(&ga, (int)sizeof(char *), 20);
3022 
3023     uhp = curbuf->b_u_oldhead;
3024     while (uhp != NULL)
3025     {
3026 	if (uhp->uh_prev.ptr == NULL && uhp->uh_walk != nomark
3027 						      && uhp->uh_walk != mark)
3028 	{
3029 	    if (ga_grow(&ga, 1) == FAIL)
3030 		break;
3031 	    vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7d  ",
3032 							uhp->uh_seq, changes);
3033 	    u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff),
3034 								uhp->uh_time);
3035 	    if (uhp->uh_save_nr > 0)
3036 	    {
3037 		while (STRLEN(IObuff) < 33)
3038 		    STRCAT(IObuff, " ");
3039 		vim_snprintf_add((char *)IObuff, IOSIZE,
3040 						   "  %3ld", uhp->uh_save_nr);
3041 	    }
3042 	    ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff);
3043 	}
3044 
3045 	uhp->uh_walk = mark;
3046 
3047 	/* go down in the tree if we haven't been there */
3048 	if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark
3049 					 && uhp->uh_prev.ptr->uh_walk != mark)
3050 	{
3051 	    uhp = uhp->uh_prev.ptr;
3052 	    ++changes;
3053 	}
3054 
3055 	/* go to alternate branch if we haven't been there */
3056 	else if (uhp->uh_alt_next.ptr != NULL
3057 		&& uhp->uh_alt_next.ptr->uh_walk != nomark
3058 		&& uhp->uh_alt_next.ptr->uh_walk != mark)
3059 	    uhp = uhp->uh_alt_next.ptr;
3060 
3061 	/* go up in the tree if we haven't been there and we are at the
3062 	 * start of alternate branches */
3063 	else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL
3064 		&& uhp->uh_next.ptr->uh_walk != nomark
3065 		&& uhp->uh_next.ptr->uh_walk != mark)
3066 	{
3067 	    uhp = uhp->uh_next.ptr;
3068 	    --changes;
3069 	}
3070 
3071 	else
3072 	{
3073 	    /* need to backtrack; mark this node as done */
3074 	    uhp->uh_walk = nomark;
3075 	    if (uhp->uh_alt_prev.ptr != NULL)
3076 		uhp = uhp->uh_alt_prev.ptr;
3077 	    else
3078 	    {
3079 		uhp = uhp->uh_next.ptr;
3080 		--changes;
3081 	    }
3082 	}
3083     }
3084 
3085     if (ga.ga_len == 0)
3086 	msg(_("Nothing to undo"));
3087     else
3088     {
3089 	sort_strings((char_u **)ga.ga_data, ga.ga_len);
3090 
3091 	msg_start();
3092 	msg_puts_attr(_("number changes  when               saved"),
3093 							      HL_ATTR(HLF_T));
3094 	for (i = 0; i < ga.ga_len && !got_int; ++i)
3095 	{
3096 	    msg_putchar('\n');
3097 	    if (got_int)
3098 		break;
3099 	    msg_puts(((char **)ga.ga_data)[i]);
3100 	}
3101 	msg_end();
3102 
3103 	ga_clear_strings(&ga);
3104     }
3105 }
3106 
3107 /*
3108  * Put the timestamp of an undo header in "buf[buflen]" in a nice format.
3109  */
3110     static void
3111 u_add_time(char_u *buf, size_t buflen, time_t tt)
3112 {
3113 #ifdef HAVE_STRFTIME
3114 # ifdef HAVE_LOCALTIME_R
3115     struct tm	tmval;
3116 # endif
3117     struct tm	*curtime;
3118 
3119     if (vim_time() - tt >= 100)
3120     {
3121 # ifdef HAVE_LOCALTIME_R
3122 	curtime = localtime_r(&tt, &tmval);
3123 # else
3124 	curtime = localtime(&tt);
3125 # endif
3126 	if (vim_time() - tt < (60L * 60L * 12L))
3127 	    /* within 12 hours */
3128 	    (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
3129 	else
3130 	    /* longer ago */
3131 	    (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime);
3132     }
3133     else
3134 #endif
3135     {
3136 	long seconds = (long)(vim_time() - tt);
3137 
3138 	vim_snprintf((char *)buf, buflen,
3139 		NGETTEXT("%ld second ago", "%ld seconds ago", seconds),
3140 		seconds);
3141     }
3142 }
3143 
3144 /*
3145  * ":undojoin": continue adding to the last entry list
3146  */
3147     void
3148 ex_undojoin(exarg_T *eap UNUSED)
3149 {
3150     if (curbuf->b_u_newhead == NULL)
3151 	return;		    /* nothing changed before */
3152     if (curbuf->b_u_curhead != NULL)
3153     {
3154 	emsg(_("E790: undojoin is not allowed after undo"));
3155 	return;
3156     }
3157     if (!curbuf->b_u_synced)
3158 	return;		    /* already unsynced */
3159     if (get_undolevel() < 0)
3160 	return;		    /* no entries, nothing to do */
3161     else
3162 	/* Append next change to the last entry */
3163 	curbuf->b_u_synced = FALSE;
3164 }
3165 
3166 /*
3167  * Called after writing or reloading the file and setting b_changed to FALSE.
3168  * Now an undo means that the buffer is modified.
3169  */
3170     void
3171 u_unchanged(buf_T *buf)
3172 {
3173     u_unch_branch(buf->b_u_oldhead);
3174     buf->b_did_warn = FALSE;
3175 }
3176 
3177 /*
3178  * After reloading a buffer which was saved for 'undoreload': Find the first
3179  * line that was changed and set the cursor there.
3180  */
3181     void
3182 u_find_first_changed(void)
3183 {
3184     u_header_T	*uhp = curbuf->b_u_newhead;
3185     u_entry_T   *uep;
3186     linenr_T	lnum;
3187 
3188     if (curbuf->b_u_curhead != NULL || uhp == NULL)
3189 	return;  /* undid something in an autocmd? */
3190 
3191     /* Check that the last undo block was for the whole file. */
3192     uep = uhp->uh_entry;
3193     if (uep->ue_top != 0 || uep->ue_bot != 0)
3194 	return;
3195 
3196     for (lnum = 1; lnum < curbuf->b_ml.ml_line_count
3197 					      && lnum <= uep->ue_size; ++lnum)
3198     {
3199 	char_u *p = ml_get_buf(curbuf, lnum, FALSE);
3200 
3201 	if (uep->ue_array[lnum - 1].ul_len != curbuf->b_ml.ml_line_len
3202 		|| memcmp(p, uep->ue_array[lnum - 1].ul_line, uep->ue_array[lnum - 1].ul_len) != 0)
3203 	{
3204 	    CLEAR_POS(&(uhp->uh_cursor));
3205 	    uhp->uh_cursor.lnum = lnum;
3206 	    return;
3207 	}
3208     }
3209     if (curbuf->b_ml.ml_line_count != uep->ue_size)
3210     {
3211 	/* lines added or deleted at the end, put the cursor there */
3212 	CLEAR_POS(&(uhp->uh_cursor));
3213 	uhp->uh_cursor.lnum = lnum;
3214     }
3215 }
3216 
3217 /*
3218  * Increase the write count, store it in the last undo header, what would be
3219  * used for "u".
3220  */
3221     void
3222 u_update_save_nr(buf_T *buf)
3223 {
3224     u_header_T	*uhp;
3225 
3226     ++buf->b_u_save_nr_last;
3227     buf->b_u_save_nr_cur = buf->b_u_save_nr_last;
3228     uhp = buf->b_u_curhead;
3229     if (uhp != NULL)
3230 	uhp = uhp->uh_next.ptr;
3231     else
3232 	uhp = buf->b_u_newhead;
3233     if (uhp != NULL)
3234 	uhp->uh_save_nr = buf->b_u_save_nr_last;
3235 }
3236 
3237     static void
3238 u_unch_branch(u_header_T *uhp)
3239 {
3240     u_header_T	*uh;
3241 
3242     for (uh = uhp; uh != NULL; uh = uh->uh_prev.ptr)
3243     {
3244 	uh->uh_flags |= UH_CHANGED;
3245 	if (uh->uh_alt_next.ptr != NULL)
3246 	    u_unch_branch(uh->uh_alt_next.ptr);	    /* recursive */
3247     }
3248 }
3249 
3250 /*
3251  * Get pointer to last added entry.
3252  * If it's not valid, give an error message and return NULL.
3253  */
3254     static u_entry_T *
3255 u_get_headentry(void)
3256 {
3257     if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL)
3258     {
3259 	iemsg(_("E439: undo list corrupt"));
3260 	return NULL;
3261     }
3262     return curbuf->b_u_newhead->uh_entry;
3263 }
3264 
3265 /*
3266  * u_getbot(): compute the line number of the previous u_save
3267  *		It is called only when b_u_synced is FALSE.
3268  */
3269     static void
3270 u_getbot(void)
3271 {
3272     u_entry_T	*uep;
3273     linenr_T	extra;
3274 
3275     uep = u_get_headentry();	/* check for corrupt undo list */
3276     if (uep == NULL)
3277 	return;
3278 
3279     uep = curbuf->b_u_newhead->uh_getbot_entry;
3280     if (uep != NULL)
3281     {
3282 	/*
3283 	 * the new ue_bot is computed from the number of lines that has been
3284 	 * inserted (0 - deleted) since calling u_save. This is equal to the
3285 	 * old line count subtracted from the current line count.
3286 	 */
3287 	extra = curbuf->b_ml.ml_line_count - uep->ue_lcount;
3288 	uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra;
3289 	if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count)
3290 	{
3291 	    iemsg(_("E440: undo line missing"));
3292 	    uep->ue_bot = uep->ue_top + 1;  /* assume all lines deleted, will
3293 					     * get all the old lines back
3294 					     * without deleting the current
3295 					     * ones */
3296 	}
3297 
3298 	curbuf->b_u_newhead->uh_getbot_entry = NULL;
3299     }
3300 
3301     curbuf->b_u_synced = TRUE;
3302 }
3303 
3304 /*
3305  * Free one header "uhp" and its entry list and adjust the pointers.
3306  */
3307     static void
3308 u_freeheader(
3309     buf_T	    *buf,
3310     u_header_T	    *uhp,
3311     u_header_T	    **uhpp)	/* if not NULL reset when freeing this header */
3312 {
3313     u_header_T	    *uhap;
3314 
3315     /* When there is an alternate redo list free that branch completely,
3316      * because we can never go there. */
3317     if (uhp->uh_alt_next.ptr != NULL)
3318 	u_freebranch(buf, uhp->uh_alt_next.ptr, uhpp);
3319 
3320     if (uhp->uh_alt_prev.ptr != NULL)
3321 	uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL;
3322 
3323     /* Update the links in the list to remove the header. */
3324     if (uhp->uh_next.ptr == NULL)
3325 	buf->b_u_oldhead = uhp->uh_prev.ptr;
3326     else
3327 	uhp->uh_next.ptr->uh_prev.ptr = uhp->uh_prev.ptr;
3328 
3329     if (uhp->uh_prev.ptr == NULL)
3330 	buf->b_u_newhead = uhp->uh_next.ptr;
3331     else
3332 	for (uhap = uhp->uh_prev.ptr; uhap != NULL;
3333 						 uhap = uhap->uh_alt_next.ptr)
3334 	    uhap->uh_next.ptr = uhp->uh_next.ptr;
3335 
3336     u_freeentries(buf, uhp, uhpp);
3337 }
3338 
3339 /*
3340  * Free an alternate branch and any following alternate branches.
3341  */
3342     static void
3343 u_freebranch(
3344     buf_T	    *buf,
3345     u_header_T	    *uhp,
3346     u_header_T	    **uhpp)	/* if not NULL reset when freeing this header */
3347 {
3348     u_header_T	    *tofree, *next;
3349 
3350     /* If this is the top branch we may need to use u_freeheader() to update
3351      * all the pointers. */
3352     if (uhp == buf->b_u_oldhead)
3353     {
3354 	while (buf->b_u_oldhead != NULL)
3355 	    u_freeheader(buf, buf->b_u_oldhead, uhpp);
3356 	return;
3357     }
3358 
3359     if (uhp->uh_alt_prev.ptr != NULL)
3360 	uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL;
3361 
3362     next = uhp;
3363     while (next != NULL)
3364     {
3365 	tofree = next;
3366 	if (tofree->uh_alt_next.ptr != NULL)
3367 	    u_freebranch(buf, tofree->uh_alt_next.ptr, uhpp);   /* recursive */
3368 	next = tofree->uh_prev.ptr;
3369 	u_freeentries(buf, tofree, uhpp);
3370     }
3371 }
3372 
3373 /*
3374  * Free all the undo entries for one header and the header itself.
3375  * This means that "uhp" is invalid when returning.
3376  */
3377     static void
3378 u_freeentries(
3379     buf_T	    *buf,
3380     u_header_T	    *uhp,
3381     u_header_T	    **uhpp)	/* if not NULL reset when freeing this header */
3382 {
3383     u_entry_T	    *uep, *nuep;
3384 
3385     /* Check for pointers to the header that become invalid now. */
3386     if (buf->b_u_curhead == uhp)
3387 	buf->b_u_curhead = NULL;
3388     if (buf->b_u_newhead == uhp)
3389 	buf->b_u_newhead = NULL;  /* freeing the newest entry */
3390     if (uhpp != NULL && uhp == *uhpp)
3391 	*uhpp = NULL;
3392 
3393     for (uep = uhp->uh_entry; uep != NULL; uep = nuep)
3394     {
3395 	nuep = uep->ue_next;
3396 	u_freeentry(uep, uep->ue_size);
3397     }
3398 
3399 #ifdef U_DEBUG
3400     uhp->uh_magic = 0;
3401 #endif
3402     vim_free((char_u *)uhp);
3403     --buf->b_u_numhead;
3404 }
3405 
3406 /*
3407  * free entry 'uep' and 'n' lines in uep->ue_array[]
3408  */
3409     static void
3410 u_freeentry(u_entry_T *uep, long n)
3411 {
3412     while (n > 0)
3413 	vim_free(uep->ue_array[--n].ul_line);
3414     vim_free((char_u *)uep->ue_array);
3415 #ifdef U_DEBUG
3416     uep->ue_magic = 0;
3417 #endif
3418     vim_free((char_u *)uep);
3419 }
3420 
3421 /*
3422  * invalidate the undo buffer; called when storage has already been released
3423  */
3424     void
3425 u_clearall(buf_T *buf)
3426 {
3427     buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL;
3428     buf->b_u_synced = TRUE;
3429     buf->b_u_numhead = 0;
3430     buf->b_u_line_ptr.ul_line = NULL;
3431     buf->b_u_line_ptr.ul_len = 0;
3432     buf->b_u_line_lnum = 0;
3433 }
3434 
3435 /*
3436  * Save the line "lnum" for the "U" command.
3437  */
3438     void
3439 u_saveline(linenr_T lnum)
3440 {
3441     if (lnum == curbuf->b_u_line_lnum)	    /* line is already saved */
3442 	return;
3443     if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */
3444 	return;
3445     u_clearline();
3446     curbuf->b_u_line_lnum = lnum;
3447     if (curwin->w_cursor.lnum == lnum)
3448 	curbuf->b_u_line_colnr = curwin->w_cursor.col;
3449     else
3450 	curbuf->b_u_line_colnr = 0;
3451     if (u_save_line(&curbuf->b_u_line_ptr, lnum) == FAIL)
3452 	do_outofmem_msg((long_u)0);
3453 }
3454 
3455 /*
3456  * clear the line saved for the "U" command
3457  * (this is used externally for crossing a line while in insert mode)
3458  */
3459     void
3460 u_clearline(void)
3461 {
3462     if (curbuf->b_u_line_ptr.ul_line != NULL)
3463     {
3464 	VIM_CLEAR(curbuf->b_u_line_ptr.ul_line);
3465 	curbuf->b_u_line_ptr.ul_len = 0;
3466 	curbuf->b_u_line_lnum = 0;
3467     }
3468 }
3469 
3470 /*
3471  * Implementation of the "U" command.
3472  * Differentiation from vi: "U" can be undone with the next "U".
3473  * We also allow the cursor to be in another line.
3474  * Careful: may trigger autocommands that reload the buffer.
3475  */
3476     void
3477 u_undoline(void)
3478 {
3479     colnr_T	t;
3480     undoline_T  oldp;
3481 
3482     if (undo_off)
3483 	return;
3484 
3485     if (curbuf->b_u_line_ptr.ul_line == NULL
3486 			|| curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count)
3487     {
3488 	beep_flush();
3489 	return;
3490     }
3491 
3492     // first save the line for the 'u' command
3493     if (u_savecommon(curbuf->b_u_line_lnum - 1,
3494 		       curbuf->b_u_line_lnum + 1, (linenr_T)0, FALSE) == FAIL)
3495 	return;
3496     if (u_save_line(&oldp, curbuf->b_u_line_lnum) == FAIL)
3497     {
3498 	do_outofmem_msg((long_u)0);
3499 	return;
3500     }
3501     ml_replace_len(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr.ul_line, curbuf->b_u_line_ptr.ul_len, TRUE, FALSE);
3502     changed_bytes(curbuf->b_u_line_lnum, 0);
3503     curbuf->b_u_line_ptr = oldp;
3504 
3505     t = curbuf->b_u_line_colnr;
3506     if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum)
3507 	curbuf->b_u_line_colnr = curwin->w_cursor.col;
3508     curwin->w_cursor.col = t;
3509     curwin->w_cursor.lnum = curbuf->b_u_line_lnum;
3510     check_cursor_col();
3511 }
3512 
3513 /*
3514  * Free all allocated memory blocks for the buffer 'buf'.
3515  */
3516     void
3517 u_blockfree(buf_T *buf)
3518 {
3519     while (buf->b_u_oldhead != NULL)
3520 	u_freeheader(buf, buf->b_u_oldhead, NULL);
3521     vim_free(buf->b_u_line_ptr.ul_line);
3522 }
3523 
3524 /*
3525  * Check if the 'modified' flag is set, or 'ff' has changed (only need to
3526  * check the first character, because it can only be "dos", "unix" or "mac").
3527  * "nofile" and "scratch" type buffers are considered to always be unchanged.
3528  * Also considers a buffer changed when a terminal window contains a running
3529  * job.
3530  */
3531     int
3532 bufIsChanged(buf_T *buf)
3533 {
3534 #ifdef FEAT_TERMINAL
3535     if (term_job_running(buf->b_term))
3536 	return TRUE;
3537 #endif
3538     return bufIsChangedNotTerm(buf);
3539 }
3540 
3541 /*
3542  * Return TRUE if any buffer has changes.  Also buffers that are not written.
3543  */
3544     int
3545 anyBufIsChanged(void)
3546 {
3547     buf_T *buf;
3548 
3549     FOR_ALL_BUFFERS(buf)
3550 	if (bufIsChanged(buf))
3551 	    return TRUE;
3552     return FALSE;
3553 }
3554 
3555 /*
3556  * Like bufIsChanged() but ignoring a terminal window.
3557  */
3558     int
3559 bufIsChangedNotTerm(buf_T *buf)
3560 {
3561     // In a "prompt" buffer we do respect 'modified', so that we can control
3562     // closing the window by setting or resetting that option.
3563     return (!bt_dontwrite(buf) || bt_prompt(buf))
3564 	&& (buf->b_changed || file_ff_differs(buf, TRUE));
3565 }
3566 
3567     int
3568 curbufIsChanged(void)
3569 {
3570     return bufIsChanged(curbuf);
3571 }
3572 
3573 #if defined(FEAT_EVAL) || defined(PROTO)
3574 /*
3575  * For undotree(): Append the list of undo blocks at "first_uhp" to "list".
3576  * Recursive.
3577  */
3578     void
3579 u_eval_tree(u_header_T *first_uhp, list_T *list)
3580 {
3581     u_header_T  *uhp = first_uhp;
3582     dict_T	*dict;
3583 
3584     while (uhp != NULL)
3585     {
3586 	dict = dict_alloc();
3587 	if (dict == NULL)
3588 	    return;
3589 	dict_add_number(dict, "seq", uhp->uh_seq);
3590 	dict_add_number(dict, "time", (long)uhp->uh_time);
3591 	if (uhp == curbuf->b_u_newhead)
3592 	    dict_add_number(dict, "newhead", 1);
3593 	if (uhp == curbuf->b_u_curhead)
3594 	    dict_add_number(dict, "curhead", 1);
3595 	if (uhp->uh_save_nr > 0)
3596 	    dict_add_number(dict, "save", uhp->uh_save_nr);
3597 
3598 	if (uhp->uh_alt_next.ptr != NULL)
3599 	{
3600 	    list_T	*alt_list = list_alloc();
3601 
3602 	    if (alt_list != NULL)
3603 	    {
3604 		/* Recursive call to add alternate undo tree. */
3605 		u_eval_tree(uhp->uh_alt_next.ptr, alt_list);
3606 		dict_add_list(dict, "alt", alt_list);
3607 	    }
3608 	}
3609 
3610 	list_append_dict(list, dict);
3611 	uhp = uhp->uh_prev.ptr;
3612     }
3613 }
3614 #endif
3615