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