feat/persistent-undo: Fix bug in persistence with differing undolevels
[vim_extended.git] / src / undo.c
blobc4f6d6f4d3d9a8de731556d56ffb5e6b1eb61f4b
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * undo.c: multi level undo facility
13 * The saved lines are stored in a list of lists (one for each buffer):
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.
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).
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.
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.
75 * All data is allocated with U_ALLOC_LINE(), it will be freed as soon as the
76 * buffer is unloaded.
79 /* Uncomment the next line for including the u_check() function. This warns
80 * for errors in the debug information. */
81 /* #define U_DEBUG 1 */
82 #define UH_MAGIC 0x18dade /* value for uh_magic when in use */
83 #define UE_MAGIC 0xabc123 /* value for ue_magic when in use */
85 #include "vim.h"
87 #ifdef FEAT_PERSISTENT_UNDO
88 # define UF_MAGIC 0xfeac /* Quick undofile corruption check */
89 # define UF_VERSION 0 /* 2-byte undofile version number */
90 #endif
92 /* See below: use malloc()/free() for memory management. */
93 #define U_USE_MALLOC 1
95 static void u_unch_branch __ARGS((u_header_T *uhp));
96 static u_entry_T *u_get_headentry __ARGS((void));
97 static void u_getbot __ARGS((void));
98 static int u_savecommon __ARGS((linenr_T, linenr_T, linenr_T));
99 static void u_doit __ARGS((int count));
100 static void u_undoredo __ARGS((int undo));
101 static void u_undo_end __ARGS((int did_undo, int absolute));
102 static void u_add_time __ARGS((char_u *buf, size_t buflen, time_t tt));
103 static void u_freeheader __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp));
104 static void u_freebranch __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp));
105 static void u_freeentries __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp));
106 static void u_freeentry __ARGS((u_entry_T *, long));
107 #ifdef FEAT_PERSISTENT_UNDO
108 static void serialize_uep __ARGS((u_entry_T *uep, FILE *fp));
109 static void serialize_pos __ARGS((pos_T pos, FILE *fp));
110 static void serialize_visualinfo __ARGS((visualinfo_T info, FILE *fp));
111 static int unserialize_pos __ARGS((pos_T *pos, FILE *fp));
112 static int unserialize_visualinfo __ARGS((visualinfo_T *info, FILE *fp));
113 #endif
114 static char_u *u_get_undofile __ARGS((char_u *));
116 #ifdef U_USE_MALLOC
117 # define U_FREE_LINE(ptr) vim_free(ptr)
118 # define U_ALLOC_LINE(size) lalloc((long_u)((size) + 1), FALSE)
119 #else
120 static void u_free_line __ARGS((char_u *ptr, int keep));
121 static char_u *u_alloc_line __ARGS((unsigned size));
122 # define U_FREE_LINE(ptr) u_free_line((ptr), FALSE)
123 # define U_ALLOC_LINE(size) u_alloc_line(size)
124 #endif
125 static char_u *u_save_line __ARGS((linenr_T));
127 static long u_newcount, u_oldcount;
130 * When 'u' flag included in 'cpoptions', we behave like vi. Need to remember
131 * the action that "u" should do.
133 static int undo_undoes = FALSE;
135 #ifdef U_DEBUG
137 * Check the undo structures for being valid. Print a warning when something
138 * looks wrong.
140 static int seen_b_u_curhead;
141 static int seen_b_u_newhead;
142 static int header_count;
144 static void
145 u_check_tree(u_header_T *uhp,
146 u_header_T *exp_uh_next,
147 u_header_T *exp_uh_alt_prev)
149 u_entry_T *uep;
151 if (uhp == NULL)
152 return;
153 ++header_count;
154 if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1)
156 EMSG("b_u_curhead found twice (looping?)");
157 return;
159 if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1)
161 EMSG("b_u_newhead found twice (looping?)");
162 return;
165 if (uhp->uh_magic != UH_MAGIC)
166 EMSG("uh_magic wrong (may be using freed memory)");
167 else
169 /* Check pointers back are correct. */
170 if (uhp->uh_next != exp_uh_next)
172 EMSG("uh_next wrong");
173 smsg((char_u *)"expected: 0x%x, actual: 0x%x",
174 exp_uh_next, uhp->uh_next);
176 if (uhp->uh_alt_prev != exp_uh_alt_prev)
178 EMSG("uh_alt_prev wrong");
179 smsg((char_u *)"expected: 0x%x, actual: 0x%x",
180 exp_uh_alt_prev, uhp->uh_alt_prev);
183 /* Check the undo tree at this header. */
184 for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next)
186 if (uep->ue_magic != UE_MAGIC)
188 EMSG("ue_magic wrong (may be using freed memory)");
189 break;
193 /* Check the next alt tree. */
194 u_check_tree(uhp->uh_alt_next, uhp->uh_next, uhp);
196 /* Check the next header in this branch. */
197 u_check_tree(uhp->uh_prev, uhp, NULL);
201 void
202 u_check(int newhead_may_be_NULL)
204 seen_b_u_newhead = 0;
205 seen_b_u_curhead = 0;
206 header_count = 0;
208 u_check_tree(curbuf->b_u_oldhead, NULL, NULL);
210 if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL
211 && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL))
212 EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead);
213 if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0)
214 EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead);
215 if (header_count != curbuf->b_u_numhead)
217 EMSG("b_u_numhead invalid");
218 smsg((char_u *)"expected: %ld, actual: %ld",
219 (long)header_count, (long)curbuf->b_u_numhead);
222 #endif
225 * Save the current line for both the "u" and "U" command.
226 * Returns OK or FAIL.
229 u_save_cursor()
231 return (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
232 (linenr_T)(curwin->w_cursor.lnum + 1)));
236 * Save the lines between "top" and "bot" for both the "u" and "U" command.
237 * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1.
238 * Returns FAIL when lines could not be saved, OK otherwise.
241 u_save(top, bot)
242 linenr_T top, bot;
244 if (undo_off)
245 return OK;
247 if (top > curbuf->b_ml.ml_line_count ||
248 top >= bot || bot > curbuf->b_ml.ml_line_count + 1)
249 return FALSE; /* rely on caller to do error messages */
251 if (top + 2 == bot)
252 u_saveline((linenr_T)(top + 1));
254 return (u_savecommon(top, bot, (linenr_T)0));
258 * save the line "lnum" (used by ":s" and "~" command)
259 * The line is replaced, so the new bottom line is lnum + 1.
262 u_savesub(lnum)
263 linenr_T lnum;
265 if (undo_off)
266 return OK;
268 return (u_savecommon(lnum - 1, lnum + 1, lnum + 1));
272 * a new line is inserted before line "lnum" (used by :s command)
273 * The line is inserted, so the new bottom line is lnum + 1.
276 u_inssub(lnum)
277 linenr_T lnum;
279 if (undo_off)
280 return OK;
282 return (u_savecommon(lnum - 1, lnum, lnum + 1));
286 * save the lines "lnum" - "lnum" + nlines (used by delete command)
287 * The lines are deleted, so the new bottom line is lnum, unless the buffer
288 * becomes empty.
291 u_savedel(lnum, nlines)
292 linenr_T lnum;
293 long nlines;
295 if (undo_off)
296 return OK;
298 return (u_savecommon(lnum - 1, lnum + nlines,
299 nlines == curbuf->b_ml.ml_line_count ? 2 : lnum));
303 * Return TRUE when undo is allowed. Otherwise give an error message and
304 * return FALSE.
307 undo_allowed()
309 /* Don't allow changes when 'modifiable' is off. */
310 if (!curbuf->b_p_ma)
312 EMSG(_(e_modifiable));
313 return FALSE;
316 #ifdef HAVE_SANDBOX
317 /* In the sandbox it's not allowed to change the text. */
318 if (sandbox != 0)
320 EMSG(_(e_sandbox));
321 return FALSE;
323 #endif
325 /* Don't allow changes in the buffer while editing the cmdline. The
326 * caller of getcmdline() may get confused. */
327 if (textlock != 0)
329 EMSG(_(e_secure));
330 return FALSE;
333 return TRUE;
336 static int
337 u_savecommon(top, bot, newbot)
338 linenr_T top, bot;
339 linenr_T newbot;
341 linenr_T lnum;
342 long i;
343 u_header_T *uhp;
344 u_header_T *old_curhead;
345 u_entry_T *uep;
346 u_entry_T *prev_uep;
347 long size;
349 /* When making changes is not allowed return FAIL. It's a crude way to
350 * make all change commands fail. */
351 if (!undo_allowed())
352 return FAIL;
354 #ifdef U_DEBUG
355 u_check(FALSE);
356 #endif
357 #ifdef FEAT_NETBEANS_INTG
359 * Netbeans defines areas that cannot be modified. Bail out here when
360 * trying to change text in a guarded area.
362 if (usingNetbeans)
364 if (netbeans_is_guarded(top, bot))
366 EMSG(_(e_guarded));
367 return FAIL;
369 if (curbuf->b_p_ro)
371 EMSG(_(e_nbreadonly));
372 return FAIL;
375 #endif
377 #ifdef FEAT_AUTOCMD
379 * Saving text for undo means we are going to make a change. Give a
380 * warning for a read-only file before making the change, so that the
381 * FileChangedRO event can replace the buffer with a read-write version
382 * (e.g., obtained from a source control system).
384 change_warning(0);
385 #endif
387 size = bot - top - 1;
390 * if curbuf->b_u_synced == TRUE make a new header
392 if (curbuf->b_u_synced)
394 #ifdef FEAT_JUMPLIST
395 /* Need to create new entry in b_changelist. */
396 curbuf->b_new_change = TRUE;
397 #endif
399 if (p_ul >= 0)
402 * Make a new header entry. Do this first so that we don't mess
403 * up the undo info when out of memory.
405 uhp = (u_header_T *)U_ALLOC_LINE((unsigned)sizeof(u_header_T));
406 if (uhp == NULL)
407 goto nomem;
408 #ifdef U_DEBUG
409 uhp->uh_magic = UH_MAGIC;
410 #endif
412 else
413 uhp = NULL;
416 * If we undid more than we redid, move the entry lists before and
417 * including curbuf->b_u_curhead to an alternate branch.
419 old_curhead = curbuf->b_u_curhead;
420 if (old_curhead != NULL)
422 curbuf->b_u_newhead = old_curhead->uh_next;
423 curbuf->b_u_curhead = NULL;
427 * free headers to keep the size right
429 while (curbuf->b_u_numhead > p_ul && curbuf->b_u_oldhead != NULL)
431 u_header_T *uhfree = curbuf->b_u_oldhead;
433 if (uhfree == old_curhead)
434 /* Can't reconnect the branch, delete all of it. */
435 u_freebranch(curbuf, uhfree, &old_curhead);
436 else if (uhfree->uh_alt_next == NULL)
437 /* There is no branch, only free one header. */
438 u_freeheader(curbuf, uhfree, &old_curhead);
439 else
441 /* Free the oldest alternate branch as a whole. */
442 while (uhfree->uh_alt_next != NULL)
443 uhfree = uhfree->uh_alt_next;
444 u_freebranch(curbuf, uhfree, &old_curhead);
446 #ifdef U_DEBUG
447 u_check(TRUE);
448 #endif
451 if (uhp == NULL) /* no undo at all */
453 if (old_curhead != NULL)
454 u_freebranch(curbuf, old_curhead, NULL);
455 curbuf->b_u_synced = FALSE;
456 return OK;
459 uhp->uh_prev = NULL;
460 uhp->uh_next = curbuf->b_u_newhead;
461 uhp->uh_alt_next = old_curhead;
462 if (old_curhead != NULL)
464 uhp->uh_alt_prev = old_curhead->uh_alt_prev;
465 if (uhp->uh_alt_prev != NULL)
466 uhp->uh_alt_prev->uh_alt_next = uhp;
467 old_curhead->uh_alt_prev = uhp;
468 if (curbuf->b_u_oldhead == old_curhead)
469 curbuf->b_u_oldhead = uhp;
471 else
472 uhp->uh_alt_prev = NULL;
473 if (curbuf->b_u_newhead != NULL)
474 curbuf->b_u_newhead->uh_prev = uhp;
476 uhp->uh_seq = ++curbuf->b_u_seq_last;
477 curbuf->b_u_seq_cur = uhp->uh_seq;
478 uhp->uh_time = time(NULL);
479 curbuf->b_u_seq_time = uhp->uh_time + 1;
481 uhp->uh_walk = 0;
482 uhp->uh_entry = NULL;
483 uhp->uh_getbot_entry = NULL;
484 uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */
485 #ifdef FEAT_VIRTUALEDIT
486 if (virtual_active() && curwin->w_cursor.coladd > 0)
487 uhp->uh_cursor_vcol = getviscol();
488 else
489 uhp->uh_cursor_vcol = -1;
490 #endif
492 /* save changed and buffer empty flag for undo */
493 uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
494 ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
496 /* save named marks and Visual marks for undo */
497 mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
498 #ifdef FEAT_VISUAL
499 uhp->uh_visual = curbuf->b_visual;
500 #endif
502 curbuf->b_u_newhead = uhp;
503 if (curbuf->b_u_oldhead == NULL)
504 curbuf->b_u_oldhead = uhp;
505 ++curbuf->b_u_numhead;
507 else
509 if (p_ul < 0) /* no undo at all */
510 return OK;
513 * When saving a single line, and it has been saved just before, it
514 * doesn't make sense saving it again. Saves a lot of memory when
515 * making lots of changes inside the same line.
516 * This is only possible if the previous change didn't increase or
517 * decrease the number of lines.
518 * Check the ten last changes. More doesn't make sense and takes too
519 * long.
521 if (size == 1)
523 uep = u_get_headentry();
524 prev_uep = NULL;
525 for (i = 0; i < 10; ++i)
527 if (uep == NULL)
528 break;
530 /* If lines have been inserted/deleted we give up.
531 * Also when the line was included in a multi-line save. */
532 if ((curbuf->b_u_newhead->uh_getbot_entry != uep
533 ? (uep->ue_top + uep->ue_size + 1
534 != (uep->ue_bot == 0
535 ? curbuf->b_ml.ml_line_count + 1
536 : uep->ue_bot))
537 : uep->ue_lcount != curbuf->b_ml.ml_line_count)
538 || (uep->ue_size > 1
539 && top >= uep->ue_top
540 && top + 2 <= uep->ue_top + uep->ue_size + 1))
541 break;
543 /* If it's the same line we can skip saving it again. */
544 if (uep->ue_size == 1 && uep->ue_top == top)
546 if (i > 0)
548 /* It's not the last entry: get ue_bot for the last
549 * entry now. Following deleted/inserted lines go to
550 * the re-used entry. */
551 u_getbot();
552 curbuf->b_u_synced = FALSE;
554 /* Move the found entry to become the last entry. The
555 * order of undo/redo doesn't matter for the entries
556 * we move it over, since they don't change the line
557 * count and don't include this line. It does matter
558 * for the found entry if the line count is changed by
559 * the executed command. */
560 prev_uep->ue_next = uep->ue_next;
561 uep->ue_next = curbuf->b_u_newhead->uh_entry;
562 curbuf->b_u_newhead->uh_entry = uep;
565 /* The executed command may change the line count. */
566 if (newbot != 0)
567 uep->ue_bot = newbot;
568 else if (bot > curbuf->b_ml.ml_line_count)
569 uep->ue_bot = 0;
570 else
572 uep->ue_lcount = curbuf->b_ml.ml_line_count;
573 curbuf->b_u_newhead->uh_getbot_entry = uep;
575 return OK;
577 prev_uep = uep;
578 uep = uep->ue_next;
582 /* find line number for ue_bot for previous u_save() */
583 u_getbot();
586 #if !defined(UNIX) && !defined(DJGPP) && !defined(WIN32) && !defined(__EMX__)
588 * With Amiga and MSDOS 16 bit we can't handle big undo's, because
589 * then u_alloc_line would have to allocate a block larger than 32K
591 if (size >= 8000)
592 goto nomem;
593 #endif
596 * add lines in front of entry list
598 uep = (u_entry_T *)U_ALLOC_LINE((unsigned)sizeof(u_entry_T));
599 if (uep == NULL)
600 goto nomem;
601 #ifdef U_DEBUG
602 uep->ue_magic = UE_MAGIC;
603 #endif
605 uep->ue_size = size;
606 uep->ue_top = top;
607 if (newbot != 0)
608 uep->ue_bot = newbot;
610 * Use 0 for ue_bot if bot is below last line.
611 * Otherwise we have to compute ue_bot later.
613 else if (bot > curbuf->b_ml.ml_line_count)
614 uep->ue_bot = 0;
615 else
617 uep->ue_lcount = curbuf->b_ml.ml_line_count;
618 curbuf->b_u_newhead->uh_getbot_entry = uep;
621 if (size > 0)
623 if ((uep->ue_array = (char_u **)U_ALLOC_LINE(
624 (unsigned)(sizeof(char_u *) * size))) == NULL)
626 u_freeentry(uep, 0L);
627 goto nomem;
629 for (i = 0, lnum = top + 1; i < size; ++i)
631 fast_breakcheck();
632 if (got_int)
634 u_freeentry(uep, i);
635 return FAIL;
637 if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL)
639 u_freeentry(uep, i);
640 goto nomem;
644 else
645 uep->ue_array = NULL;
646 uep->ue_next = curbuf->b_u_newhead->uh_entry;
647 curbuf->b_u_newhead->uh_entry = uep;
648 curbuf->b_u_synced = FALSE;
649 undo_undoes = FALSE;
651 #ifdef U_DEBUG
652 u_check(FALSE);
653 #endif
654 return OK;
656 nomem:
657 msg_silent = 0; /* must display the prompt */
658 if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE)
659 == 'y')
661 undo_off = TRUE; /* will be reset when character typed */
662 return OK;
664 do_outofmem_msg((long_u)0);
665 return FAIL;
668 #ifdef FEAT_PERSISTENT_UNDO
669 static int
670 unserialize_pos(pos_T *pos, FILE *fp)
672 /* Unserialize the pos_T at the current position in fp. */
673 pos->lnum = get4c(fp);
674 pos->col = get4c(fp);
675 #ifdef FEAT_VIRTUALEDIT
676 pos->coladd = get4c(fp);
677 #endif
678 return 0;
681 #ifdef FEAT_VISUAL
682 static int
683 unserialize_visualinfo(visualinfo_T *info, FILE *fp)
685 /* Unserialize the visualinfo_T at the current position in fp. */
686 unserialize_pos(&info->vi_start, fp);
687 unserialize_pos(&info->vi_end, fp);
688 info->vi_mode = get4c(fp);
689 info->vi_curswant = get4c(fp);
690 return 0;
692 #endif
694 static char_u *
695 u_get_undofile(char_u *ffname)
697 /* Returns an allocated string of the full path of the target undofile */
698 char_u *undo_path = NULL;
699 char_u *dirp;
700 char_u dir_name[IOSIZE + 1];
701 char_u *munged_name;
702 int dir_len, undo_path_len, name_len;
703 int found_udir = FALSE;
704 int i;
705 if (ffname == NULL)
706 ffname = (char_u *) "";
708 name_len = STRLEN(ffname);
709 munged_name = alloc(name_len + 1);
710 mch_memmove(munged_name, ffname, name_len + 1);
712 for (i = 0; i < name_len; i++)
714 if (munged_name[i] == '/')
715 munged_name[i] = '_';
718 dirp = p_udir;
719 while (*dirp)
721 dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ",");
722 dir_name[dir_len] = '\0';
723 if (mch_isdir(dir_name))
725 found_udir = TRUE;
726 break;
730 if (found_udir == FALSE)
732 /* Found no created undo dirs, so create the first one in the list.*/
733 dirp = p_udir;
734 dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ",");
735 dir_name[dir_len] = '\0';
736 vim_mkdir(dir_name, 0755);
737 if (!mch_isdir(dir_name))
739 /* Couldn't create undo directory, bail */
740 vim_free(undo_path);
741 return NULL;
744 /* get_file_in_dir returns allocated memory */
745 undo_path = get_file_in_dir(munged_name, dir_name);
746 vim_free(munged_name);
747 undo_path_len = STRLEN(undo_path);
748 undo_path = vim_realloc(undo_path, sizeof(char_u) * undo_path_len + 5);
749 vim_strncpy(undo_path + undo_path_len, (char_u *) ".und", 4);
750 return undo_path;
753 void
754 u_rundo(char_u *name, int quiet)
756 /* Given a buffer name, load in the undo tree from an undo file. If quiet
757 * is 0, don't complain if there is no appropriate undo file. */
758 char_u *undo_file;
759 FILE *fp;
761 long magic, version, str_len, file_mtime;
762 char_u *line_ptr = NULL;
763 linenr_T line_lnum;
764 colnr_T line_colnr;
765 linenr_T line_count;
766 int uep_len;
767 int line_len;
768 int num_head;
769 long old_header_seq, new_header_seq, cur_header_seq, seq_last, seq_cur;
770 short old_idx = -1, new_idx = -1, cur_idx = -1;
771 long num_read_uhps = 0;
772 time_t seq_time;
773 int i, j;
774 int c;
775 short found_first_uep = 0;
776 char_u **array;
777 char_u *line;
778 u_entry_T *uep, *last_uep, *nuep;
779 u_header_T *uhp;
780 u_header_T **uhp_table = NULL;
782 if (name == NULL || STRLEN(name) == 0)
784 undo_file = u_get_undofile(curbuf->b_ffname);
786 else
788 undo_file = u_get_undofile(name);
790 if (undo_file == NULL)
792 if (!quiet)
793 EMSG(_("Error: Can't find or create an undo directory"));
794 return;
796 fp = fopen((char *)undo_file, "r");
797 if (fp == NULL)
799 if (!quiet)
800 EMSG2(_("Error: Can't open undo file %s for read"), undo_file);
801 vim_free(undo_file);
802 return;
806 /* Begin overall file information */
807 magic = get2c(fp);
808 if (magic != UF_MAGIC)
810 EMSG2(_("Error: corrupted undo file %s"), undo_file);
811 vim_free(undo_file);
812 goto error;
814 version = get2c(fp);
815 if (version != UF_VERSION)
817 EMSG2(_("Error: incompatible undo file %s"), undo_file);
818 vim_free(undo_file);
819 goto error;
821 vim_free(undo_file);
823 file_mtime = (long_u) get4c(fp);
824 if (file_mtime != curbuf->b_mtime)
826 if (p_verbose > 0)
828 verbose_enter();
829 give_warning((char_u *)_("Undo file mismatch"), TRUE);
830 verbose_leave();
832 goto error;
835 line_count = (linenr_T) get4c(fp);
836 if (line_count != curbuf->b_ml.ml_line_count)
838 if (p_verbose > 0)
840 verbose_enter();
841 give_warning((char_u *)_("Undo file linecount differs"), TRUE);
842 verbose_leave();
844 goto error;
847 /* Begin undo data for U */
848 str_len = get4c(fp);
849 if (str_len < 0)
850 goto error;
851 else if (str_len > 0)
853 if ((line_ptr = U_ALLOC_LINE(str_len)) == NULL)
855 EMSG("u_rundo: out of memory!");
856 goto error;
858 for (i = 0; i < str_len; i++)
860 line_ptr[i] = (char_u) getc(fp);
862 line_ptr[i] = '\0';
864 line_lnum = (linenr_T) get4c(fp);
865 line_colnr = (colnr_T) get4c(fp);
867 /* Begin general undo data */
868 old_header_seq = get4c(fp);
869 new_header_seq = get4c(fp);
870 cur_header_seq = get4c(fp);
871 num_head = get4c(fp);
872 seq_last = get4c(fp);
873 seq_cur = get4c(fp);
874 seq_time = get4c(fp);
875 /* uhp_table will store the freshly created undo headers we allocate
876 * until we insert them into curbuf. The table remains sorted by the
877 * sequence numbers of the headers.
879 uhp_table = (u_header_T **)U_ALLOC_LINE(num_head * sizeof(u_header_T *));
880 if (uhp_table == NULL)
882 EMSG("u_rundo: out of memory!");
883 goto error;
885 vim_memset(uhp_table, 0, num_head * sizeof(u_header_T *));
887 c = getc(fp);
888 while (c != 0x0a && c != EOF)
890 ungetc(c, fp);
892 found_first_uep = 0;
893 uhp = (u_header_T *)U_ALLOC_LINE((unsigned)sizeof(u_header_T));
894 if (uhp == NULL)
896 EMSG("u_rundo: out of memory!");
897 goto error;
899 vim_memset(uhp, 0, sizeof(u_header_T));
900 /* We're not actually trying to store pointers here. We're just storing
901 * IDs so we can swizzle them into pointers later - hence type hack */
902 uhp->uh_next = (u_header_T *)(long)get4c(fp);
903 uhp->uh_prev = (u_header_T *)(long)get4c(fp);
904 uhp->uh_alt_next = (u_header_T *)(long)get4c(fp);
905 uhp->uh_alt_prev = (u_header_T *)(long)get4c(fp);
906 uhp->uh_seq = get4c(fp);
907 if (uhp->uh_seq <= 0)
909 EMSG("u_rundo: undo file corruption detected: invalid uh_seq.");
910 U_FREE_LINE(uhp);
911 goto error;
913 uhp->uh_walk = 0;
914 unserialize_pos(&uhp->uh_cursor, fp);
915 #ifdef FEAT_VIRTUALEDIT
916 uhp->uh_cursor_vcol = get4c(fp);
917 #endif
918 uhp->uh_flags = get2c(fp);
919 for (i = 0; i < NMARKS; ++i)
921 unserialize_pos(&uhp->uh_namedm[i], fp);
923 #ifdef FEAT_VISUAL
924 unserialize_visualinfo(&uhp->uh_visual, fp);
925 #endif
926 uhp->uh_time = get4c(fp);
928 /* Unserialize uep list. The first 4 bytes is the length of the
929 * entire uep in bytes minus the length of the strings within.
930 * -1 is a sentinel value meaning no more ueps.*/
931 last_uep = NULL;
932 while ((uep_len = get4c(fp)) != -1)
934 uep = (u_entry_T *)U_ALLOC_LINE((unsigned)sizeof(u_entry_T));
935 vim_memset(uep, 0, sizeof(u_entry_T));
936 if (uep == NULL)
938 EMSG("u_rundo: out of memory!");
939 goto error;
941 uep->ue_top = get4c(fp);
942 uep->ue_bot = get4c(fp);
943 uep->ue_lcount = get4c(fp);
944 uep->ue_size = get4c(fp);
945 uep->ue_next = NULL;
946 array = (char_u **)U_ALLOC_LINE((unsigned)(sizeof(char_u *) * uep->ue_size));
947 for (i = 0; i < uep->ue_size; i++)
949 line_len = get4c(fp);
950 /* U_ALLOC_LINE provides an extra byte for the NUL terminator.*/
951 line = (char_u *)U_ALLOC_LINE((unsigned) (sizeof(char_u) * line_len));
952 if (line == NULL)
954 EMSG("u_rundo: out of memory!");
955 goto error;
957 for (j = 0; j < line_len; j++)
959 line[j] = getc(fp);
961 line[j] = '\0';
962 array[i] = line;
964 uep->ue_array = array;
965 if (found_first_uep == 0)
967 uhp->uh_entry = uep;
968 found_first_uep = 1;
970 else
972 last_uep->ue_next = uep;
974 last_uep = uep;
977 /* Insertion sort the uhp into the table by its uh_seq. This is
978 * required because, while the number of uhps is limited to
979 * num_heads, and the uh_seq order is monotonic with respect to
980 * creation time, the starting uh_seq can be > 0 if any undolevel
981 * culling was done at undofile write time, and there can be uh_seq
982 * gaps in the uhps.
984 for (i = num_read_uhps - 1; i >= -1; i--)
986 /* if i == -1, we've hit the leftmost side of the table, so insert
987 * at uhp_table[0]. */
988 if (i == -1 || uhp->uh_seq > uhp_table[i]->uh_seq)
990 /* If we've had to move from the rightmost side of the table,
991 * we have to shift everything to the right by one spot. */
992 if (i < num_read_uhps - 1)
994 memmove(uhp_table + i + 2, uhp_table + i + 1,
995 (num_read_uhps - i) * sizeof(u_header_T *));
997 uhp_table[i + 1] = uhp;
998 break;
1000 else if (uhp->uh_seq == uhp_table[i]->uh_seq)
1002 EMSG("u_rundo: undo file corruption detected: duplicate uh_seq.");
1003 goto error;
1006 num_read_uhps++;
1007 c = getc(fp);
1010 /* We've organized all of the uhps into a table sorted by uh_seq. Now we
1011 * iterate through the table and swizzle each sequence number we've
1012 * stored in uh_foo into a pointer corresponding to the header with that
1013 * sequence number. Then free curbuf's old undo structure, give curbuf
1014 * the updated {old,new,cur}head pointers, and then free the table. */
1015 for (i = 0; i < num_head; i++)
1017 uhp = uhp_table[i];
1018 if (uhp == NULL)
1019 continue;
1020 for (j = 0; j < num_head; j++)
1022 if (uhp_table[j] == NULL)
1023 continue;
1024 if (uhp_table[j]->uh_seq == (long)uhp->uh_next)
1025 uhp->uh_next = uhp_table[j];
1026 if (uhp_table[j]->uh_seq == (long)uhp->uh_prev)
1027 uhp->uh_prev = uhp_table[j];
1028 if (uhp_table[j]->uh_seq == (long)uhp->uh_alt_next)
1029 uhp->uh_alt_next = uhp_table[j];
1030 if (uhp_table[j]->uh_seq == (long)uhp->uh_alt_prev)
1031 uhp->uh_alt_prev = uhp_table[j];
1033 if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq)
1034 old_idx = i;
1035 if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq)
1036 new_idx = i;
1037 if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq)
1038 cur_idx = i;
1040 u_blockfree(curbuf);
1041 curbuf->b_u_oldhead = old_idx < 0 ? 0 : uhp_table[old_idx];
1042 curbuf->b_u_newhead = new_idx < 0 ? 0 : uhp_table[new_idx];
1043 curbuf->b_u_curhead = cur_idx < 0 ? 0 : uhp_table[cur_idx];
1044 curbuf->b_u_line_ptr = line_ptr;
1045 curbuf->b_u_line_lnum = line_lnum;
1046 curbuf->b_u_line_colnr = line_colnr;
1047 curbuf->b_u_numhead = num_head;
1048 curbuf->b_u_seq_last = seq_last;
1049 curbuf->b_u_seq_cur = seq_cur;
1050 curbuf->b_u_seq_time = seq_time;
1051 U_FREE_LINE(uhp_table);
1052 #ifdef U_DEBUG
1053 u_check(TRUE);
1054 #endif
1055 fclose(fp);
1056 return;
1059 error:
1060 if (fp != NULL)
1061 fclose(fp);
1062 if (line_ptr != NULL)
1063 U_FREE_LINE(line_ptr);
1064 if (uhp_table != NULL)
1066 for (i = 0; i < num_head; i++)
1068 if (uhp_table[i] != NULL)
1070 uep = uhp_table[i]->uh_entry;
1071 while (uep != NULL)
1073 nuep = uep->ue_next;
1074 u_freeentry(uep, uep->ue_size);
1075 uep = nuep;
1077 U_FREE_LINE(uhp_table[i]);
1080 U_FREE_LINE(uhp_table);
1082 return;
1085 static void
1086 serialize_uep(u_entry_T *uep, FILE *fp)
1088 /* Serialize the given u_entry_T to fp. */
1089 int i;
1090 int uep_len;
1091 int *entry_lens;
1093 if (uep->ue_size > 0)
1095 entry_lens = (int *)alloc(uep->ue_size * sizeof(int));
1098 /* Define uep_len to be the size of the entire uep minus the size of its
1099 * component strings, in bytes. The sizes of the component strings
1100 * are written before each individual string.
1101 * We have 4 entries each of 4 bytes, plus ue_size * 4 bytes
1102 * of string size information. */
1104 uep_len = uep->ue_size * 4;
1105 /* Collect sizing information for later serialization. */
1106 for (i = 0; i < uep->ue_size; i++)
1108 entry_lens[i] = (int) STRLEN(uep->ue_array[i]);
1109 uep_len += entry_lens[i];
1111 put_bytes(fp, (long_u) uep_len, 4);
1112 put_bytes(fp, (long_u) uep->ue_top, 4);
1113 put_bytes(fp, (long_u) uep->ue_bot, 4);
1114 put_bytes(fp, (long_u) uep->ue_lcount, 4);
1115 put_bytes(fp, (long_u) uep->ue_size, 4);
1116 for (i = 0; i < uep->ue_size; i++)
1118 put_bytes(fp, (long_u) entry_lens[i], 4);
1119 fprintf(fp, "%s", uep->ue_array[i]);
1121 if (uep->ue_size > 0)
1123 vim_free(entry_lens);
1127 static int lastmark = 0;
1129 static void
1130 serialize_pos(pos_T pos, FILE *fp)
1132 /* Serialize the given pos_T to fp. */
1133 put_bytes(fp, (long_u) pos.lnum, 4);
1134 put_bytes(fp, (long_u) pos.col, 4);
1135 #ifdef FEAT_VIRTUALEDIT
1136 put_bytes(fp, (long_u) pos.coladd, 4);
1137 #endif
1140 static void
1141 serialize_visualinfo(visualinfo_T info, FILE *fp)
1143 /* Serialize the given visualinfo_T to fp. */
1144 serialize_pos(info.vi_start, fp);
1145 serialize_pos(info.vi_end, fp);
1146 put_bytes(fp, (long_u) info.vi_mode, 4);
1147 put_bytes(fp, (long_u) info.vi_curswant, 4);
1150 void
1151 u_wundo(char_u *name, buf_T *buf)
1153 /* Given an optional buffer name and a buffer, write out the undo tree
1154 * to an undo file. */
1155 u_header_T *uhp;
1156 u_entry_T *uep;
1157 char_u *undo_file;
1158 int str_len, i, uep_len, mark;
1159 FILE *fp;
1161 if (name == NULL || STRLEN(name) == 0)
1163 undo_file = u_get_undofile(buf->b_ffname);
1165 else
1167 undo_file = u_get_undofile(name);
1169 if (undo_file == NULL)
1171 EMSG(_("Error: Can't find or create an undo directory"));
1172 return;
1174 fp = fopen((char *)undo_file, "w");
1175 if (fp == NULL)
1177 EMSG2(_("Error: Can't open undo file %s for write"), undo_file);
1178 vim_free(undo_file);
1179 return;
1181 vim_free(undo_file);
1183 /* Begin overall file information */
1184 put_bytes(fp, (long_u) UF_MAGIC, 2);
1185 put_bytes(fp, (long_u) UF_VERSION, 2);
1187 put_bytes(fp, (long_u) buf->b_mtime, 4);
1188 put_bytes(fp, (long_u) buf->b_ml.ml_line_count, 4);
1190 /* Begin undo data for U */
1191 str_len = buf->b_u_line_ptr != NULL ? STRLEN(buf->b_u_line_ptr) : 0;
1192 put_bytes(fp, (long_u) str_len, 4);
1193 for (i = 0; i < str_len; i++)
1195 put_bytes(fp, (long_u) buf->b_u_line_ptr[i], 1);
1198 put_bytes(fp, (long_u) buf->b_u_line_lnum, 4);
1199 put_bytes(fp, (long_u) buf->b_u_line_colnr, 4);
1201 /* Begin general undo data */
1202 uhp = buf->b_u_oldhead;
1203 put_bytes(fp, (long_u) (uhp != NULL ? uhp->uh_seq : 0), 4);
1205 uhp = buf->b_u_newhead;
1206 put_bytes(fp, (long_u) (uhp != NULL ? uhp->uh_seq : 0), 4);
1208 uhp = buf->b_u_curhead;
1209 put_bytes(fp, (long_u) (uhp != NULL ? uhp->uh_seq : 0), 4);
1211 put_bytes(fp, (long_u) buf->b_u_numhead, 4);
1212 put_bytes(fp, (long_u) buf->b_u_seq_last, 4);
1213 put_bytes(fp, (long_u) buf->b_u_seq_cur, 4);
1214 put_bytes(fp, (long_u) buf->b_u_seq_time, 4);
1216 /* Iteratively serialize UHPs and their UEPs from the top down. */
1217 mark = ++lastmark;
1218 uhp = buf->b_u_oldhead;
1219 while (uhp != NULL)
1221 /* Serialize current UHP if we haven't seen it */
1222 if (uhp->uh_walk != mark)
1224 put_bytes(fp, (long_u) ((uhp->uh_next != NULL) ? uhp->uh_next->uh_seq : 0), 4);
1225 put_bytes(fp, (long_u) ((uhp->uh_prev != NULL) ? uhp->uh_prev->uh_seq : 0), 4);
1226 put_bytes(fp, (long_u) ((uhp->uh_alt_next != NULL) ? uhp->uh_alt_next->uh_seq : 0), 4);
1227 put_bytes(fp, (long_u) ((uhp->uh_alt_prev != NULL) ? uhp->uh_alt_prev->uh_seq : 0), 4);
1228 put_bytes(fp, uhp->uh_seq, 4);
1229 serialize_pos(uhp->uh_cursor, fp);
1230 #ifdef FEAT_VIRTUALEDIT
1231 put_bytes(fp, (long_u) uhp->uh_cursor_vcol, 4);
1232 #endif
1233 put_bytes(fp, (long_u) uhp->uh_flags, 2);
1234 /* Assume NMARKS will stay the same. */
1235 for (i = 0; i < NMARKS; ++i)
1237 serialize_pos(uhp->uh_namedm[i], fp);
1239 #ifdef FEAT_VISUAL
1240 serialize_visualinfo(uhp->uh_visual, fp);
1241 #endif
1242 put_bytes(fp, (long_u) uhp->uh_time, 4);
1244 uep = uhp->uh_entry;
1245 while (uep != NULL)
1247 serialize_uep(uep, fp);
1248 uep = uep->ue_next;
1250 /* Sentinel value: no more ueps */
1251 uep_len = -1;
1252 put_bytes(fp, (long_u) uep_len, 4);
1253 uhp->uh_walk = mark;
1256 /* Now walk through the tree - algorithm from undo_time*/
1257 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != mark)
1258 uhp = uhp->uh_prev;
1259 else if (uhp->uh_alt_next != NULL && uhp->uh_alt_next->uh_walk != mark)
1260 uhp = uhp->uh_alt_next;
1261 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
1262 && uhp->uh_next->uh_walk != mark)
1263 uhp = uhp->uh_next;
1264 else if (uhp->uh_alt_prev != NULL)
1265 uhp = uhp->uh_alt_prev;
1266 else
1267 uhp = uhp->uh_next;
1269 fclose(fp);
1272 #endif /* FEAT_PERSISTENT_UNDO */
1276 * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible).
1277 * If 'cpoptions' does not contain 'u': Always undo.
1279 void
1280 u_undo(count)
1281 int count;
1284 * If we get an undo command while executing a macro, we behave like the
1285 * original vi. If this happens twice in one macro the result will not
1286 * be compatible.
1288 if (curbuf->b_u_synced == FALSE)
1290 u_sync(TRUE);
1291 count = 1;
1294 if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
1295 undo_undoes = TRUE;
1296 else
1297 undo_undoes = !undo_undoes;
1298 u_doit(count);
1302 * If 'cpoptions' contains 'u': Repeat the previous undo or redo.
1303 * If 'cpoptions' does not contain 'u': Always redo.
1305 void
1306 u_redo(count)
1307 int count;
1309 if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
1310 undo_undoes = FALSE;
1311 u_doit(count);
1315 * Undo or redo, depending on 'undo_undoes', 'count' times.
1317 static void
1318 u_doit(startcount)
1319 int startcount;
1321 int count = startcount;
1323 if (!undo_allowed())
1324 return;
1326 u_newcount = 0;
1327 u_oldcount = 0;
1328 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1329 u_oldcount = -1;
1330 while (count--)
1332 if (undo_undoes)
1334 if (curbuf->b_u_curhead == NULL) /* first undo */
1335 curbuf->b_u_curhead = curbuf->b_u_newhead;
1336 else if (p_ul > 0) /* multi level undo */
1337 /* get next undo */
1338 curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next;
1339 /* nothing to undo */
1340 if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL)
1342 /* stick curbuf->b_u_curhead at end */
1343 curbuf->b_u_curhead = curbuf->b_u_oldhead;
1344 beep_flush();
1345 if (count == startcount - 1)
1347 MSG(_("Already at oldest change"));
1348 return;
1350 break;
1353 u_undoredo(TRUE);
1355 else
1357 if (curbuf->b_u_curhead == NULL || p_ul <= 0)
1359 beep_flush(); /* nothing to redo */
1360 if (count == startcount - 1)
1362 MSG(_("Already at newest change"));
1363 return;
1365 break;
1368 u_undoredo(FALSE);
1370 /* Advance for next redo. Set "newhead" when at the end of the
1371 * redoable changes. */
1372 if (curbuf->b_u_curhead->uh_prev == NULL)
1373 curbuf->b_u_newhead = curbuf->b_u_curhead;
1374 curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev;
1377 u_undo_end(undo_undoes, FALSE);
1381 * Undo or redo over the timeline.
1382 * When "step" is negative go back in time, otherwise goes forward in time.
1383 * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as
1384 * seconds.
1385 * When "absolute" is TRUE use "step" as the sequence number to jump to.
1386 * "sec" must be FALSE then.
1388 void
1389 undo_time(step, sec, absolute)
1390 long step;
1391 int sec;
1392 int absolute;
1394 long target;
1395 long closest;
1396 long closest_start;
1397 long closest_seq = 0;
1398 long val;
1399 u_header_T *uhp;
1400 u_header_T *last;
1401 int mark;
1402 int nomark;
1403 int round;
1404 int dosec = sec;
1405 int above = FALSE;
1406 int did_undo = TRUE;
1408 /* First make sure the current undoable change is synced. */
1409 if (curbuf->b_u_synced == FALSE)
1410 u_sync(TRUE);
1412 u_newcount = 0;
1413 u_oldcount = 0;
1414 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1415 u_oldcount = -1;
1417 /* "target" is the node below which we want to be.
1418 * Init "closest" to a value we can't reach. */
1419 if (absolute)
1421 target = step;
1422 closest = -1;
1424 else
1426 /* When doing computations with time_t subtract starttime, because
1427 * time_t converted to a long may result in a wrong number. */
1428 if (sec)
1429 target = (long)(curbuf->b_u_seq_time - starttime) + step;
1430 else
1431 target = curbuf->b_u_seq_cur + step;
1432 if (step < 0)
1434 if (target < 0)
1435 target = 0;
1436 closest = -1;
1438 else
1440 if (sec)
1441 closest = (long)(time(NULL) - starttime + 1);
1442 else
1443 closest = curbuf->b_u_seq_last + 2;
1444 if (target >= closest)
1445 target = closest - 1;
1448 closest_start = closest;
1449 closest_seq = curbuf->b_u_seq_cur;
1452 * May do this twice:
1453 * 1. Search for "target", update "closest" to the best match found.
1454 * 2. If "target" not found search for "closest".
1456 * When using the closest time we use the sequence number in the second
1457 * round, because there may be several entries with the same time.
1459 for (round = 1; round <= 2; ++round)
1461 /* Find the path from the current state to where we want to go. The
1462 * desired state can be anywhere in the undo tree, need to go all over
1463 * it. We put "nomark" in uh_walk where we have been without success,
1464 * "mark" where it could possibly be. */
1465 mark = ++lastmark;
1466 nomark = ++lastmark;
1468 if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */
1469 uhp = curbuf->b_u_newhead;
1470 else
1471 uhp = curbuf->b_u_curhead;
1473 while (uhp != NULL)
1475 uhp->uh_walk = mark;
1476 val = (long)(dosec ? (uhp->uh_time - starttime) : uhp->uh_seq);
1478 if (round == 1)
1480 /* Remember the header that is closest to the target.
1481 * It must be at least in the right direction (checked with
1482 * "b_u_seq_cur"). When the timestamp is equal find the
1483 * highest/lowest sequence number. */
1484 if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur
1485 : uhp->uh_seq > curbuf->b_u_seq_cur)
1486 && ((dosec && val == closest)
1487 ? (step < 0
1488 ? uhp->uh_seq < closest_seq
1489 : uhp->uh_seq > closest_seq)
1490 : closest == closest_start
1491 || (val > target
1492 ? (closest > target
1493 ? val - target <= closest - target
1494 : val - target <= target - closest)
1495 : (closest > target
1496 ? target - val <= closest - target
1497 : target - val <= target - closest))))
1499 closest = val;
1500 closest_seq = uhp->uh_seq;
1504 /* Quit searching when we found a match. But when searching for a
1505 * time we need to continue looking for the best uh_seq. */
1506 if (target == val && !dosec)
1507 break;
1509 /* go down in the tree if we haven't been there */
1510 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != nomark
1511 && uhp->uh_prev->uh_walk != mark)
1512 uhp = uhp->uh_prev;
1514 /* go to alternate branch if we haven't been there */
1515 else if (uhp->uh_alt_next != NULL
1516 && uhp->uh_alt_next->uh_walk != nomark
1517 && uhp->uh_alt_next->uh_walk != mark)
1518 uhp = uhp->uh_alt_next;
1520 /* go up in the tree if we haven't been there and we are at the
1521 * start of alternate branches */
1522 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
1523 && uhp->uh_next->uh_walk != nomark
1524 && uhp->uh_next->uh_walk != mark)
1526 /* If still at the start we don't go through this change. */
1527 if (uhp == curbuf->b_u_curhead)
1528 uhp->uh_walk = nomark;
1529 uhp = uhp->uh_next;
1532 else
1534 /* need to backtrack; mark this node as useless */
1535 uhp->uh_walk = nomark;
1536 if (uhp->uh_alt_prev != NULL)
1537 uhp = uhp->uh_alt_prev;
1538 else
1539 uhp = uhp->uh_next;
1543 if (uhp != NULL) /* found it */
1544 break;
1546 if (absolute)
1548 EMSGN(_("Undo number %ld not found"), step);
1549 return;
1552 if (closest == closest_start)
1554 if (step < 0)
1555 MSG(_("Already at oldest change"));
1556 else
1557 MSG(_("Already at newest change"));
1558 return;
1561 target = closest_seq;
1562 dosec = FALSE;
1563 if (step < 0)
1564 above = TRUE; /* stop above the header */
1567 /* If we found it: Follow the path to go to where we want to be. */
1568 if (uhp != NULL)
1571 * First go up the tree as much as needed.
1573 for (;;)
1575 uhp = curbuf->b_u_curhead;
1576 if (uhp == NULL)
1577 uhp = curbuf->b_u_newhead;
1578 else
1579 uhp = uhp->uh_next;
1580 if (uhp == NULL || uhp->uh_walk != mark
1581 || (uhp->uh_seq == target && !above))
1582 break;
1583 curbuf->b_u_curhead = uhp;
1584 u_undoredo(TRUE);
1585 uhp->uh_walk = nomark; /* don't go back down here */
1589 * And now go down the tree (redo), branching off where needed.
1591 uhp = curbuf->b_u_curhead;
1592 while (uhp != NULL)
1594 /* Go back to the first branch with a mark. */
1595 while (uhp->uh_alt_prev != NULL
1596 && uhp->uh_alt_prev->uh_walk == mark)
1597 uhp = uhp->uh_alt_prev;
1599 /* Find the last branch with a mark, that's the one. */
1600 last = uhp;
1601 while (last->uh_alt_next != NULL
1602 && last->uh_alt_next->uh_walk == mark)
1603 last = last->uh_alt_next;
1604 if (last != uhp)
1606 /* Make the used branch the first entry in the list of
1607 * alternatives to make "u" and CTRL-R take this branch. */
1608 while (uhp->uh_alt_prev != NULL)
1609 uhp = uhp->uh_alt_prev;
1610 if (last->uh_alt_next != NULL)
1611 last->uh_alt_next->uh_alt_prev = last->uh_alt_prev;
1612 last->uh_alt_prev->uh_alt_next = last->uh_alt_next;
1613 last->uh_alt_prev = NULL;
1614 last->uh_alt_next = uhp;
1615 uhp->uh_alt_prev = last;
1617 uhp = last;
1618 if (uhp->uh_next != NULL)
1619 uhp->uh_next->uh_prev = uhp;
1621 curbuf->b_u_curhead = uhp;
1623 if (uhp->uh_walk != mark)
1624 break; /* must have reached the target */
1626 /* Stop when going backwards in time and didn't find the exact
1627 * header we were looking for. */
1628 if (uhp->uh_seq == target && above)
1630 curbuf->b_u_seq_cur = target - 1;
1631 break;
1634 u_undoredo(FALSE);
1636 /* Advance "curhead" to below the header we last used. If it
1637 * becomes NULL then we need to set "newhead" to this leaf. */
1638 if (uhp->uh_prev == NULL)
1639 curbuf->b_u_newhead = uhp;
1640 curbuf->b_u_curhead = uhp->uh_prev;
1641 did_undo = FALSE;
1643 if (uhp->uh_seq == target) /* found it! */
1644 break;
1646 uhp = uhp->uh_prev;
1647 if (uhp == NULL || uhp->uh_walk != mark)
1649 /* Need to redo more but can't find it... */
1650 EMSG2(_(e_intern2), "undo_time()");
1651 break;
1655 u_undo_end(did_undo, absolute);
1659 * u_undoredo: common code for undo and redo
1661 * The lines in the file are replaced by the lines in the entry list at
1662 * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry
1663 * list for the next undo/redo.
1665 * When "undo" is TRUE we go up in the tree, when FALSE we go down.
1667 static void
1668 u_undoredo(undo)
1669 int undo;
1671 char_u **newarray = NULL;
1672 linenr_T oldsize;
1673 linenr_T newsize;
1674 linenr_T top, bot;
1675 linenr_T lnum;
1676 linenr_T newlnum = MAXLNUM;
1677 long i;
1678 u_entry_T *uep, *nuep;
1679 u_entry_T *newlist = NULL;
1680 int old_flags;
1681 int new_flags;
1682 pos_T namedm[NMARKS];
1683 #ifdef FEAT_VISUAL
1684 visualinfo_T visualinfo;
1685 #endif
1686 int empty_buffer; /* buffer became empty */
1687 u_header_T *curhead = curbuf->b_u_curhead;
1689 #ifdef U_DEBUG
1690 u_check(FALSE);
1691 #endif
1692 old_flags = curhead->uh_flags;
1693 new_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
1694 ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
1695 setpcmark();
1698 * save marks before undo/redo
1700 mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
1701 #ifdef FEAT_VISUAL
1702 visualinfo = curbuf->b_visual;
1703 #endif
1704 curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count;
1705 curbuf->b_op_start.col = 0;
1706 curbuf->b_op_end.lnum = 0;
1707 curbuf->b_op_end.col = 0;
1709 for (uep = curhead->uh_entry; uep != NULL; uep = nuep)
1711 top = uep->ue_top;
1712 bot = uep->ue_bot;
1713 if (bot == 0)
1714 bot = curbuf->b_ml.ml_line_count + 1;
1715 if (top > curbuf->b_ml.ml_line_count || top >= bot
1716 || bot > curbuf->b_ml.ml_line_count + 1)
1718 EMSG(_("E438: u_undo: line numbers wrong"));
1719 changed(); /* don't want UNCHANGED now */
1720 return;
1723 oldsize = bot - top - 1; /* number of lines before undo */
1724 newsize = uep->ue_size; /* number of lines after undo */
1726 if (top < newlnum)
1728 /* If the saved cursor is somewhere in this undo block, move it to
1729 * the remembered position. Makes "gwap" put the cursor back
1730 * where it was. */
1731 lnum = curhead->uh_cursor.lnum;
1732 if (lnum >= top && lnum <= top + newsize + 1)
1734 curwin->w_cursor = curhead->uh_cursor;
1735 newlnum = curwin->w_cursor.lnum - 1;
1737 else
1739 /* Use the first line that actually changed. Avoids that
1740 * undoing auto-formatting puts the cursor in the previous
1741 * line. */
1742 for (i = 0; i < newsize && i < oldsize; ++i)
1743 if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0)
1744 break;
1745 if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL)
1747 newlnum = top;
1748 curwin->w_cursor.lnum = newlnum + 1;
1750 else if (i < newsize)
1752 newlnum = top + i;
1753 curwin->w_cursor.lnum = newlnum + 1;
1758 empty_buffer = FALSE;
1760 /* delete the lines between top and bot and save them in newarray */
1761 if (oldsize > 0)
1763 if ((newarray = (char_u **)U_ALLOC_LINE(
1764 (unsigned)(sizeof(char_u *) * oldsize))) == NULL)
1766 do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize));
1768 * We have messed up the entry list, repair is impossible.
1769 * we have to free the rest of the list.
1771 while (uep != NULL)
1773 nuep = uep->ue_next;
1774 u_freeentry(uep, uep->ue_size);
1775 uep = nuep;
1777 break;
1779 /* delete backwards, it goes faster in most cases */
1780 for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum)
1782 /* what can we do when we run out of memory? */
1783 if ((newarray[i] = u_save_line(lnum)) == NULL)
1784 do_outofmem_msg((long_u)0);
1785 /* remember we deleted the last line in the buffer, and a
1786 * dummy empty line will be inserted */
1787 if (curbuf->b_ml.ml_line_count == 1)
1788 empty_buffer = TRUE;
1789 ml_delete(lnum, FALSE);
1792 else
1793 newarray = NULL;
1795 /* insert the lines in u_array between top and bot */
1796 if (newsize)
1798 for (lnum = top, i = 0; i < newsize; ++i, ++lnum)
1801 * If the file is empty, there is an empty line 1 that we
1802 * should get rid of, by replacing it with the new line
1804 if (empty_buffer && lnum == 0)
1805 ml_replace((linenr_T)1, uep->ue_array[i], TRUE);
1806 else
1807 ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE);
1808 U_FREE_LINE(uep->ue_array[i]);
1810 U_FREE_LINE((char_u *)uep->ue_array);
1813 /* adjust marks */
1814 if (oldsize != newsize)
1816 mark_adjust(top + 1, top + oldsize, (long)MAXLNUM,
1817 (long)newsize - (long)oldsize);
1818 if (curbuf->b_op_start.lnum > top + oldsize)
1819 curbuf->b_op_start.lnum += newsize - oldsize;
1820 if (curbuf->b_op_end.lnum > top + oldsize)
1821 curbuf->b_op_end.lnum += newsize - oldsize;
1824 changed_lines(top + 1, 0, bot, newsize - oldsize);
1826 /* set '[ and '] mark */
1827 if (top + 1 < curbuf->b_op_start.lnum)
1828 curbuf->b_op_start.lnum = top + 1;
1829 if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum)
1830 curbuf->b_op_end.lnum = top + 1;
1831 else if (top + newsize > curbuf->b_op_end.lnum)
1832 curbuf->b_op_end.lnum = top + newsize;
1834 u_newcount += newsize;
1835 u_oldcount += oldsize;
1836 uep->ue_size = oldsize;
1837 uep->ue_array = newarray;
1838 uep->ue_bot = top + newsize + 1;
1841 * insert this entry in front of the new entry list
1843 nuep = uep->ue_next;
1844 uep->ue_next = newlist;
1845 newlist = uep;
1848 curhead->uh_entry = newlist;
1849 curhead->uh_flags = new_flags;
1850 if ((old_flags & UH_EMPTYBUF) && bufempty())
1851 curbuf->b_ml.ml_flags |= ML_EMPTY;
1852 if (old_flags & UH_CHANGED)
1853 changed();
1854 else
1855 #ifdef FEAT_NETBEANS_INTG
1856 /* per netbeans undo rules, keep it as modified */
1857 if (!isNetbeansModified(curbuf))
1858 #endif
1859 unchanged(curbuf, FALSE);
1862 * restore marks from before undo/redo
1864 for (i = 0; i < NMARKS; ++i)
1865 if (curhead->uh_namedm[i].lnum != 0)
1867 curbuf->b_namedm[i] = curhead->uh_namedm[i];
1868 curhead->uh_namedm[i] = namedm[i];
1870 #ifdef FEAT_VISUAL
1871 if (curhead->uh_visual.vi_start.lnum != 0)
1873 curbuf->b_visual = curhead->uh_visual;
1874 curhead->uh_visual = visualinfo;
1876 #endif
1879 * If the cursor is only off by one line, put it at the same position as
1880 * before starting the change (for the "o" command).
1881 * Otherwise the cursor should go to the first undone line.
1883 if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum
1884 && curwin->w_cursor.lnum > 1)
1885 --curwin->w_cursor.lnum;
1886 if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum)
1888 curwin->w_cursor.col = curhead->uh_cursor.col;
1889 #ifdef FEAT_VIRTUALEDIT
1890 if (virtual_active() && curhead->uh_cursor_vcol >= 0)
1891 coladvance((colnr_T)curhead->uh_cursor_vcol);
1892 else
1893 curwin->w_cursor.coladd = 0;
1894 #endif
1896 else if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count)
1897 beginline(BL_SOL | BL_FIX);
1898 else
1900 /* We get here with the current cursor line being past the end (eg
1901 * after adding lines at the end of the file, and then undoing it).
1902 * check_cursor() will move the cursor to the last line. Move it to
1903 * the first column here. */
1904 curwin->w_cursor.col = 0;
1905 #ifdef FEAT_VIRTUALEDIT
1906 curwin->w_cursor.coladd = 0;
1907 #endif
1910 /* Make sure the cursor is on an existing line and column. */
1911 check_cursor();
1913 /* Remember where we are for "g-" and ":earlier 10s". */
1914 curbuf->b_u_seq_cur = curhead->uh_seq;
1915 if (undo)
1916 /* We are below the previous undo. However, to make ":earlier 1s"
1917 * work we compute this as being just above the just undone change. */
1918 --curbuf->b_u_seq_cur;
1920 /* The timestamp can be the same for multiple changes, just use the one of
1921 * the undone/redone change. */
1922 curbuf->b_u_seq_time = curhead->uh_time;
1923 #ifdef U_DEBUG
1924 u_check(FALSE);
1925 #endif
1929 * If we deleted or added lines, report the number of less/more lines.
1930 * Otherwise, report the number of changes (this may be incorrect
1931 * in some cases, but it's better than nothing).
1933 static void
1934 u_undo_end(did_undo, absolute)
1935 int did_undo; /* just did an undo */
1936 int absolute; /* used ":undo N" */
1938 char *msgstr;
1939 u_header_T *uhp;
1940 char_u msgbuf[80];
1942 #ifdef FEAT_FOLDING
1943 if ((fdo_flags & FDO_UNDO) && KeyTyped)
1944 foldOpenCursor();
1945 #endif
1947 if (global_busy /* no messages now, wait until global is finished */
1948 || !messaging()) /* 'lazyredraw' set, don't do messages now */
1949 return;
1951 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1952 --u_newcount;
1954 u_oldcount -= u_newcount;
1955 if (u_oldcount == -1)
1956 msgstr = N_("more line");
1957 else if (u_oldcount < 0)
1958 msgstr = N_("more lines");
1959 else if (u_oldcount == 1)
1960 msgstr = N_("line less");
1961 else if (u_oldcount > 1)
1962 msgstr = N_("fewer lines");
1963 else
1965 u_oldcount = u_newcount;
1966 if (u_newcount == 1)
1967 msgstr = N_("change");
1968 else
1969 msgstr = N_("changes");
1972 if (curbuf->b_u_curhead != NULL)
1974 /* For ":undo N" we prefer a "after #N" message. */
1975 if (absolute && curbuf->b_u_curhead->uh_next != NULL)
1977 uhp = curbuf->b_u_curhead->uh_next;
1978 did_undo = FALSE;
1980 else if (did_undo)
1981 uhp = curbuf->b_u_curhead;
1982 else
1983 uhp = curbuf->b_u_curhead->uh_next;
1985 else
1986 uhp = curbuf->b_u_newhead;
1988 if (uhp == NULL)
1989 *msgbuf = NUL;
1990 else
1991 u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time);
1993 smsg((char_u *)_("%ld %s; %s #%ld %s"),
1994 u_oldcount < 0 ? -u_oldcount : u_oldcount,
1995 _(msgstr),
1996 did_undo ? _("before") : _("after"),
1997 uhp == NULL ? 0L : uhp->uh_seq,
1998 msgbuf);
2002 * u_sync: stop adding to the current entry list
2004 void
2005 u_sync(force)
2006 int force; /* Also sync when no_u_sync is set. */
2008 /* Skip it when already synced or syncing is disabled. */
2009 if (curbuf->b_u_synced || (!force && no_u_sync > 0))
2010 return;
2011 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2012 if (im_is_preediting())
2013 return; /* XIM is busy, don't break an undo sequence */
2014 #endif
2015 if (p_ul < 0)
2016 curbuf->b_u_synced = TRUE; /* no entries, nothing to do */
2017 else
2019 u_getbot(); /* compute ue_bot of previous u_save */
2020 curbuf->b_u_curhead = NULL;
2026 * ":undolist": List the leafs of the undo tree
2028 /*ARGSUSED*/
2029 void
2030 ex_undolist(eap)
2031 exarg_T *eap;
2033 garray_T ga;
2034 u_header_T *uhp;
2035 int mark;
2036 int nomark;
2037 int changes = 1;
2038 int i;
2041 * 1: walk the tree to find all leafs, put the info in "ga".
2042 * 2: sort the lines
2043 * 3: display the list
2045 mark = ++lastmark;
2046 nomark = ++lastmark;
2047 ga_init2(&ga, (int)sizeof(char *), 20);
2049 uhp = curbuf->b_u_oldhead;
2050 while (uhp != NULL)
2052 if (uhp->uh_prev == NULL && uhp->uh_walk != nomark
2053 && uhp->uh_walk != mark)
2055 if (ga_grow(&ga, 1) == FAIL)
2056 break;
2057 vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ",
2058 uhp->uh_seq, changes);
2059 u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff),
2060 uhp->uh_time);
2061 ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff);
2064 uhp->uh_walk = mark;
2066 /* go down in the tree if we haven't been there */
2067 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != nomark
2068 && uhp->uh_prev->uh_walk != mark)
2070 uhp = uhp->uh_prev;
2071 ++changes;
2074 /* go to alternate branch if we haven't been there */
2075 else if (uhp->uh_alt_next != NULL
2076 && uhp->uh_alt_next->uh_walk != nomark
2077 && uhp->uh_alt_next->uh_walk != mark)
2078 uhp = uhp->uh_alt_next;
2080 /* go up in the tree if we haven't been there and we are at the
2081 * start of alternate branches */
2082 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
2083 && uhp->uh_next->uh_walk != nomark
2084 && uhp->uh_next->uh_walk != mark)
2086 uhp = uhp->uh_next;
2087 --changes;
2090 else
2092 /* need to backtrack; mark this node as done */
2093 uhp->uh_walk = nomark;
2094 if (uhp->uh_alt_prev != NULL)
2095 uhp = uhp->uh_alt_prev;
2096 else
2098 uhp = uhp->uh_next;
2099 --changes;
2104 if (ga.ga_len == 0)
2105 MSG(_("Nothing to undo"));
2106 else
2108 sort_strings((char_u **)ga.ga_data, ga.ga_len);
2110 msg_start();
2111 msg_puts_attr((char_u *)_("number changes time"), hl_attr(HLF_T));
2112 for (i = 0; i < ga.ga_len && !got_int; ++i)
2114 msg_putchar('\n');
2115 if (got_int)
2116 break;
2117 msg_puts(((char_u **)ga.ga_data)[i]);
2119 msg_end();
2121 ga_clear_strings(&ga);
2126 * Put the timestamp of an undo header in "buf[buflen]" in a nice format.
2128 static void
2129 u_add_time(buf, buflen, tt)
2130 char_u *buf;
2131 size_t buflen;
2132 time_t tt;
2134 #ifdef HAVE_STRFTIME
2135 struct tm *curtime;
2137 if (time(NULL) - tt >= 100)
2139 curtime = localtime(&tt);
2140 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
2142 else
2143 #endif
2144 vim_snprintf((char *)buf, buflen, _("%ld seconds ago"),
2145 (long)(time(NULL) - tt));
2149 * ":undojoin": continue adding to the last entry list
2151 /*ARGSUSED*/
2152 void
2153 ex_undojoin(eap)
2154 exarg_T *eap;
2156 if (curbuf->b_u_newhead == NULL)
2157 return; /* nothing changed before */
2158 if (curbuf->b_u_curhead != NULL)
2160 EMSG(_("E790: undojoin is not allowed after undo"));
2161 return;
2163 if (!curbuf->b_u_synced)
2164 return; /* already unsynced */
2165 if (p_ul < 0)
2166 return; /* no entries, nothing to do */
2167 else
2169 /* Go back to the last entry */
2170 curbuf->b_u_curhead = curbuf->b_u_newhead;
2171 curbuf->b_u_synced = FALSE; /* no entries, nothing to do */
2176 * Called after writing the file and setting b_changed to FALSE.
2177 * Now an undo means that the buffer is modified.
2179 void
2180 u_unchanged(buf)
2181 buf_T *buf;
2183 u_unch_branch(buf->b_u_oldhead);
2184 buf->b_did_warn = FALSE;
2187 static void
2188 u_unch_branch(uhp)
2189 u_header_T *uhp;
2191 u_header_T *uh;
2193 for (uh = uhp; uh != NULL; uh = uh->uh_prev)
2195 uh->uh_flags |= UH_CHANGED;
2196 if (uh->uh_alt_next != NULL)
2197 u_unch_branch(uh->uh_alt_next); /* recursive */
2202 * Get pointer to last added entry.
2203 * If it's not valid, give an error message and return NULL.
2205 static u_entry_T *
2206 u_get_headentry()
2208 if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL)
2210 EMSG(_("E439: undo list corrupt"));
2211 return NULL;
2213 return curbuf->b_u_newhead->uh_entry;
2217 * u_getbot(): compute the line number of the previous u_save
2218 * It is called only when b_u_synced is FALSE.
2220 static void
2221 u_getbot()
2223 u_entry_T *uep;
2224 linenr_T extra;
2226 uep = u_get_headentry(); /* check for corrupt undo list */
2227 if (uep == NULL)
2228 return;
2230 uep = curbuf->b_u_newhead->uh_getbot_entry;
2231 if (uep != NULL)
2234 * the new ue_bot is computed from the number of lines that has been
2235 * inserted (0 - deleted) since calling u_save. This is equal to the
2236 * old line count subtracted from the current line count.
2238 extra = curbuf->b_ml.ml_line_count - uep->ue_lcount;
2239 uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra;
2240 if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count)
2242 EMSG(_("E440: undo line missing"));
2243 uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will
2244 * get all the old lines back
2245 * without deleting the current
2246 * ones */
2249 curbuf->b_u_newhead->uh_getbot_entry = NULL;
2252 curbuf->b_u_synced = TRUE;
2256 * Free one header "uhp" and its entry list and adjust the pointers.
2258 static void
2259 u_freeheader(buf, uhp, uhpp)
2260 buf_T *buf;
2261 u_header_T *uhp;
2262 u_header_T **uhpp; /* if not NULL reset when freeing this header */
2264 u_header_T *uhap;
2266 /* When there is an alternate redo list free that branch completely,
2267 * because we can never go there. */
2268 if (uhp->uh_alt_next != NULL)
2269 u_freebranch(buf, uhp->uh_alt_next, uhpp);
2271 if (uhp->uh_alt_prev != NULL)
2272 uhp->uh_alt_prev->uh_alt_next = NULL;
2274 /* Update the links in the list to remove the header. */
2275 if (uhp->uh_next == NULL)
2276 buf->b_u_oldhead = uhp->uh_prev;
2277 else
2278 uhp->uh_next->uh_prev = uhp->uh_prev;
2280 if (uhp->uh_prev == NULL)
2281 buf->b_u_newhead = uhp->uh_next;
2282 else
2283 for (uhap = uhp->uh_prev; uhap != NULL; uhap = uhap->uh_alt_next)
2284 uhap->uh_next = uhp->uh_next;
2286 u_freeentries(buf, uhp, uhpp);
2290 * Free an alternate branch and any following alternate branches.
2292 static void
2293 u_freebranch(buf, uhp, uhpp)
2294 buf_T *buf;
2295 u_header_T *uhp;
2296 u_header_T **uhpp; /* if not NULL reset when freeing this header */
2298 u_header_T *tofree, *next;
2300 /* If this is the top branch we may need to use u_freeheader() to update
2301 * all the pointers. */
2302 if (uhp == buf->b_u_oldhead)
2304 u_freeheader(buf, uhp, uhpp);
2305 return;
2308 if (uhp->uh_alt_prev != NULL)
2309 uhp->uh_alt_prev->uh_alt_next = NULL;
2311 next = uhp;
2312 while (next != NULL)
2314 tofree = next;
2315 if (tofree->uh_alt_next != NULL)
2316 u_freebranch(buf, tofree->uh_alt_next, uhpp); /* recursive */
2317 next = tofree->uh_prev;
2318 u_freeentries(buf, tofree, uhpp);
2323 * Free all the undo entries for one header and the header itself.
2324 * This means that "uhp" is invalid when returning.
2326 static void
2327 u_freeentries(buf, uhp, uhpp)
2328 buf_T *buf;
2329 u_header_T *uhp;
2330 u_header_T **uhpp; /* if not NULL reset when freeing this header */
2332 u_entry_T *uep, *nuep;
2334 /* Check for pointers to the header that become invalid now. */
2335 if (buf->b_u_curhead == uhp)
2336 buf->b_u_curhead = NULL;
2337 if (buf->b_u_newhead == uhp)
2338 buf->b_u_newhead = NULL; /* freeing the newest entry */
2339 if (uhpp != NULL && uhp == *uhpp)
2340 *uhpp = NULL;
2342 for (uep = uhp->uh_entry; uep != NULL; uep = nuep)
2344 nuep = uep->ue_next;
2345 u_freeentry(uep, uep->ue_size);
2348 #ifdef U_DEBUG
2349 uhp->uh_magic = 0;
2350 #endif
2351 U_FREE_LINE((char_u *)uhp);
2352 --buf->b_u_numhead;
2356 * free entry 'uep' and 'n' lines in uep->ue_array[]
2358 static void
2359 u_freeentry(uep, n)
2360 u_entry_T *uep;
2361 long n;
2363 while (n > 0)
2364 U_FREE_LINE(uep->ue_array[--n]);
2365 U_FREE_LINE((char_u *)uep->ue_array);
2366 #ifdef U_DEBUG
2367 uep->ue_magic = 0;
2368 #endif
2369 U_FREE_LINE((char_u *)uep);
2373 * invalidate the undo buffer; called when storage has already been released
2375 void
2376 u_clearall(buf)
2377 buf_T *buf;
2379 buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL;
2380 buf->b_u_synced = TRUE;
2381 buf->b_u_numhead = 0;
2382 buf->b_u_line_ptr = NULL;
2383 buf->b_u_line_lnum = 0;
2387 * save the line "lnum" for the "U" command
2389 void
2390 u_saveline(lnum)
2391 linenr_T lnum;
2393 if (lnum == curbuf->b_u_line_lnum) /* line is already saved */
2394 return;
2395 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */
2396 return;
2397 u_clearline();
2398 curbuf->b_u_line_lnum = lnum;
2399 if (curwin->w_cursor.lnum == lnum)
2400 curbuf->b_u_line_colnr = curwin->w_cursor.col;
2401 else
2402 curbuf->b_u_line_colnr = 0;
2403 if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL)
2404 do_outofmem_msg((long_u)0);
2408 * clear the line saved for the "U" command
2409 * (this is used externally for crossing a line while in insert mode)
2411 void
2412 u_clearline()
2414 if (curbuf->b_u_line_ptr != NULL)
2416 U_FREE_LINE(curbuf->b_u_line_ptr);
2417 curbuf->b_u_line_ptr = NULL;
2418 curbuf->b_u_line_lnum = 0;
2423 * Implementation of the "U" command.
2424 * Differentiation from vi: "U" can be undone with the next "U".
2425 * We also allow the cursor to be in another line.
2427 void
2428 u_undoline()
2430 colnr_T t;
2431 char_u *oldp;
2433 if (undo_off)
2434 return;
2436 if (curbuf->b_u_line_ptr == NULL
2437 || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count)
2439 beep_flush();
2440 return;
2443 /* first save the line for the 'u' command */
2444 if (u_savecommon(curbuf->b_u_line_lnum - 1,
2445 curbuf->b_u_line_lnum + 1, (linenr_T)0) == FAIL)
2446 return;
2447 oldp = u_save_line(curbuf->b_u_line_lnum);
2448 if (oldp == NULL)
2450 do_outofmem_msg((long_u)0);
2451 return;
2453 ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE);
2454 changed_bytes(curbuf->b_u_line_lnum, 0);
2455 U_FREE_LINE(curbuf->b_u_line_ptr);
2456 curbuf->b_u_line_ptr = oldp;
2458 t = curbuf->b_u_line_colnr;
2459 if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum)
2460 curbuf->b_u_line_colnr = curwin->w_cursor.col;
2461 curwin->w_cursor.col = t;
2462 curwin->w_cursor.lnum = curbuf->b_u_line_lnum;
2463 check_cursor_col();
2467 * There are two implementations of the memory management for undo:
2468 * 1. Use the standard malloc()/free() functions.
2469 * This should be fast for allocating memory, but when a buffer is
2470 * abandoned every single allocated chunk must be freed, which may be slow.
2471 * 2. Allocate larger blocks of memory and keep track of chunks ourselves.
2472 * This is fast for abandoning, but the use of linked lists is slow for
2473 * finding a free chunk. Esp. when a lot of lines are changed or deleted.
2474 * A bit of profiling showed that the first method is faster, especially when
2475 * making a large number of changes, under the condition that malloc()/free()
2476 * is implemented efficiently.
2478 #ifdef U_USE_MALLOC
2480 * Version of undo memory allocation using malloc()/free()
2482 * U_FREE_LINE() and U_ALLOC_LINE() are macros that invoke vim_free() and
2483 * lalloc() directly.
2487 * Free all allocated memory blocks for the buffer 'buf'.
2489 void
2490 u_blockfree(buf)
2491 buf_T *buf;
2493 while (buf->b_u_oldhead != NULL)
2494 u_freeheader(buf, buf->b_u_oldhead, NULL);
2495 U_FREE_LINE(buf->b_u_line_ptr);
2498 #else
2500 * Storage allocation for the undo lines and blocks of the current file.
2501 * Version where Vim keeps track of the available memory.
2505 * Memory is allocated in relatively large blocks. These blocks are linked
2506 * in the allocated block list, headed by curbuf->b_block_head. They are all
2507 * freed when abandoning a file, so we don't have to free every single line.
2508 * The list is kept sorted on memory address.
2509 * block_alloc() allocates a block.
2510 * m_blockfree() frees all blocks.
2512 * The available chunks of memory are kept in free chunk lists. There is
2513 * one free list for each block of allocated memory. The list is kept sorted
2514 * on memory address.
2515 * u_alloc_line() gets a chunk from the free lists.
2516 * u_free_line() returns a chunk to the free lists.
2517 * curbuf->b_m_search points to the chunk before the chunk that was
2518 * freed/allocated the last time.
2519 * curbuf->b_mb_current points to the b_head where curbuf->b_m_search
2520 * points into the free list.
2523 * b_block_head /---> block #1 /---> block #2
2524 * mb_next ---/ mb_next ---/ mb_next ---> NULL
2525 * mb_info mb_info mb_info
2526 * | | |
2527 * V V V
2528 * NULL free chunk #1.1 free chunk #2.1
2529 * | |
2530 * V V
2531 * free chunk #1.2 NULL
2534 * NULL
2536 * When a single free chunk list would have been used, it could take a lot
2537 * of time in u_free_line() to find the correct place to insert a chunk in the
2538 * free list. The single free list would become very long when many lines are
2539 * changed (e.g. with :%s/^M$//).
2543 * this blocksize is used when allocating new lines
2545 #define MEMBLOCKSIZE 2044
2548 * The size field contains the size of the chunk, including the size field
2549 * itself.
2551 * When the chunk is not in-use it is preceded with the m_info structure.
2552 * The m_next field links it in one of the free chunk lists.
2554 * On most unix systems structures have to be longword (32 or 64 bit) aligned.
2555 * On most other systems they are short (16 bit) aligned.
2558 /* the structure definitions are now in structs.h */
2560 #ifdef ALIGN_LONG
2561 /* size of m_size */
2562 # define M_OFFSET (sizeof(long_u))
2563 #else
2564 /* size of m_size */
2565 # define M_OFFSET (sizeof(short_u))
2566 #endif
2568 static char_u *u_blockalloc __ARGS((long_u));
2571 * Allocate a block of memory and link it in the allocated block list.
2573 static char_u *
2574 u_blockalloc(size)
2575 long_u size;
2577 mblock_T *p;
2578 mblock_T *mp, *next;
2580 p = (mblock_T *)lalloc(size + sizeof(mblock_T), FALSE);
2581 if (p != NULL)
2583 /* Insert the block into the allocated block list, keeping it
2584 sorted on address. */
2585 for (mp = &curbuf->b_block_head;
2586 (next = mp->mb_next) != NULL && next < p;
2587 mp = next)
2589 p->mb_next = next; /* link in block list */
2590 p->mb_size = size;
2591 p->mb_maxsize = 0; /* nothing free yet */
2592 mp->mb_next = p;
2593 p->mb_info.m_next = NULL; /* clear free list */
2594 p->mb_info.m_size = 0;
2595 curbuf->b_mb_current = p; /* remember current block */
2596 curbuf->b_m_search = NULL;
2597 p++; /* return usable memory */
2599 return (char_u *)p;
2603 * free all allocated memory blocks for the buffer 'buf'
2605 void
2606 u_blockfree(buf)
2607 buf_T *buf;
2609 mblock_T *p, *np;
2611 for (p = buf->b_block_head.mb_next; p != NULL; p = np)
2613 np = p->mb_next;
2614 vim_free(p);
2616 buf->b_block_head.mb_next = NULL;
2617 buf->b_m_search = NULL;
2618 buf->b_mb_current = NULL;
2622 * Free a chunk of memory for the current buffer.
2623 * Insert the chunk into the correct free list, keeping it sorted on address.
2625 static void
2626 u_free_line(ptr, keep)
2627 char_u *ptr;
2628 int keep; /* don't free the block when it's empty */
2630 minfo_T *next;
2631 minfo_T *prev, *curr;
2632 minfo_T *mp;
2633 mblock_T *nextb;
2634 mblock_T *prevb;
2635 long_u maxsize;
2637 if (ptr == NULL || ptr == IObuff)
2638 return; /* illegal address can happen in out-of-memory situations */
2640 mp = (minfo_T *)(ptr - M_OFFSET);
2642 /* find block where chunk could be a part off */
2643 /* if we change curbuf->b_mb_current, curbuf->b_m_search is set to NULL */
2644 if (curbuf->b_mb_current == NULL || mp < (minfo_T *)curbuf->b_mb_current)
2646 curbuf->b_mb_current = curbuf->b_block_head.mb_next;
2647 curbuf->b_m_search = NULL;
2649 if ((nextb = curbuf->b_mb_current->mb_next) != NULL
2650 && (minfo_T *)nextb < mp)
2652 curbuf->b_mb_current = nextb;
2653 curbuf->b_m_search = NULL;
2655 while ((nextb = curbuf->b_mb_current->mb_next) != NULL
2656 && (minfo_T *)nextb < mp)
2657 curbuf->b_mb_current = nextb;
2659 curr = NULL;
2661 * If mp is smaller than curbuf->b_m_search->m_next go to the start of
2662 * the free list
2664 if (curbuf->b_m_search == NULL || mp < (curbuf->b_m_search->m_next))
2665 next = &(curbuf->b_mb_current->mb_info);
2666 else
2667 next = curbuf->b_m_search;
2669 * The following loop is executed very often.
2670 * Therefore it has been optimized at the cost of readability.
2671 * Keep it fast!
2673 #ifdef SLOW_BUT_EASY_TO_READ
2676 prev = curr;
2677 curr = next;
2678 next = next->m_next;
2680 while (mp > next && next != NULL);
2681 #else
2682 do /* first, middle, last */
2684 prev = next->m_next; /* curr, next, prev */
2685 if (prev == NULL || mp <= prev)
2687 prev = curr;
2688 curr = next;
2689 next = next->m_next;
2690 break;
2692 curr = prev->m_next; /* next, prev, curr */
2693 if (curr == NULL || mp <= curr)
2695 prev = next;
2696 curr = prev->m_next;
2697 next = curr->m_next;
2698 break;
2700 next = curr->m_next; /* prev, curr, next */
2702 while (mp > next && next != NULL);
2703 #endif
2705 /* if *mp and *next are concatenated, join them into one chunk */
2706 if ((char_u *)mp + mp->m_size == (char_u *)next)
2708 mp->m_size += next->m_size;
2709 mp->m_next = next->m_next;
2711 else
2712 mp->m_next = next;
2713 maxsize = mp->m_size;
2715 /* if *curr and *mp are concatenated, join them */
2716 if (prev != NULL && (char_u *)curr + curr->m_size == (char_u *)mp)
2718 curr->m_size += mp->m_size;
2719 maxsize = curr->m_size;
2720 curr->m_next = mp->m_next;
2721 curbuf->b_m_search = prev;
2723 else
2725 curr->m_next = mp;
2726 curbuf->b_m_search = curr; /* put curbuf->b_m_search before freed
2727 chunk */
2731 * If the block only contains free memory now, release it.
2733 if (!keep && curbuf->b_mb_current->mb_size
2734 == curbuf->b_mb_current->mb_info.m_next->m_size)
2736 /* Find the block before the current one to be able to unlink it from
2737 * the list of blocks. */
2738 prevb = &curbuf->b_block_head;
2739 for (nextb = prevb->mb_next; nextb != curbuf->b_mb_current;
2740 nextb = nextb->mb_next)
2741 prevb = nextb;
2742 prevb->mb_next = nextb->mb_next;
2743 vim_free(nextb);
2744 curbuf->b_mb_current = NULL;
2745 curbuf->b_m_search = NULL;
2747 else if (curbuf->b_mb_current->mb_maxsize < maxsize)
2748 curbuf->b_mb_current->mb_maxsize = maxsize;
2752 * Allocate and initialize a new line structure with room for at least
2753 * 'size' characters plus a terminating NUL.
2755 static char_u *
2756 u_alloc_line(size)
2757 unsigned size;
2759 minfo_T *mp, *mprev, *mp2;
2760 mblock_T *mbp;
2761 int size_align;
2764 * Add room for size field and trailing NUL byte.
2765 * Adjust for minimal size (must be able to store minfo_T
2766 * plus a trailing NUL, so the chunk can be released again)
2768 size += M_OFFSET + 1;
2769 if (size < sizeof(minfo_T) + 1)
2770 size = sizeof(minfo_T) + 1;
2773 * round size up for alignment
2775 size_align = (size + ALIGN_MASK) & ~ALIGN_MASK;
2778 * If curbuf->b_m_search is NULL (uninitialized free list) start at
2779 * curbuf->b_block_head
2781 if (curbuf->b_mb_current == NULL || curbuf->b_m_search == NULL)
2783 curbuf->b_mb_current = &curbuf->b_block_head;
2784 curbuf->b_m_search = &(curbuf->b_block_head.mb_info);
2787 /* Search for a block with enough space. */
2788 mbp = curbuf->b_mb_current;
2789 while (mbp->mb_maxsize < size_align)
2791 if (mbp->mb_next != NULL)
2792 mbp = mbp->mb_next;
2793 else
2794 mbp = &curbuf->b_block_head;
2795 if (mbp == curbuf->b_mb_current)
2797 int n = (size_align > (MEMBLOCKSIZE / 4)
2798 ? size_align : MEMBLOCKSIZE);
2800 /* Back where we started in block list: need to add a new block
2801 * with enough space. */
2802 mp = (minfo_T *)u_blockalloc((long_u)n);
2803 if (mp == NULL)
2804 return (NULL);
2805 mp->m_size = n;
2806 u_free_line((char_u *)mp + M_OFFSET, TRUE);
2807 mbp = curbuf->b_mb_current;
2808 break;
2811 if (mbp != curbuf->b_mb_current)
2812 curbuf->b_m_search = &(mbp->mb_info);
2814 /* In this block find a chunk with enough space. */
2815 mprev = curbuf->b_m_search;
2816 mp = curbuf->b_m_search->m_next;
2817 for (;;)
2819 if (mp == NULL) /* at end of the list */
2820 mp = &(mbp->mb_info); /* wrap around to begin */
2821 if (mp->m_size >= size)
2822 break;
2823 if (mp == curbuf->b_m_search)
2825 /* back where we started in free chunk list: "cannot happen" */
2826 EMSG2(_(e_intern2), "u_alloc_line()");
2827 return NULL;
2829 mprev = mp;
2830 mp = mp->m_next;
2833 /* when using the largest chunk adjust mb_maxsize */
2834 if (mp->m_size >= mbp->mb_maxsize)
2835 mbp->mb_maxsize = 0;
2837 /* if the chunk we found is large enough, split it up in two */
2838 if ((long)mp->m_size - size_align >= (long)(sizeof(minfo_T) + 1))
2840 mp2 = (minfo_T *)((char_u *)mp + size_align);
2841 mp2->m_size = mp->m_size - size_align;
2842 mp2->m_next = mp->m_next;
2843 mprev->m_next = mp2;
2844 mp->m_size = size_align;
2846 else /* remove *mp from the free list */
2848 mprev->m_next = mp->m_next;
2850 curbuf->b_m_search = mprev;
2851 curbuf->b_mb_current = mbp;
2853 /* If using the largest chunk need to find the new largest chunk */
2854 if (mbp->mb_maxsize == 0)
2855 for (mp2 = &(mbp->mb_info); mp2 != NULL; mp2 = mp2->m_next)
2856 if (mbp->mb_maxsize < mp2->m_size)
2857 mbp->mb_maxsize = mp2->m_size;
2859 mp = (minfo_T *)((char_u *)mp + M_OFFSET);
2860 *(char_u *)mp = NUL; /* set the first byte to NUL */
2862 return ((char_u *)mp);
2864 #endif
2867 * u_save_line(): allocate memory with u_alloc_line() and copy line 'lnum'
2868 * into it.
2870 static char_u *
2871 u_save_line(lnum)
2872 linenr_T lnum;
2874 char_u *src;
2875 char_u *dst;
2876 unsigned len;
2878 src = ml_get(lnum);
2879 len = (unsigned)STRLEN(src);
2880 if ((dst = U_ALLOC_LINE(len)) != NULL)
2881 mch_memmove(dst, src, (size_t)(len + 1));
2882 return (dst);
2886 * Check if the 'modified' flag is set, or 'ff' has changed (only need to
2887 * check the first character, because it can only be "dos", "unix" or "mac").
2888 * "nofile" and "scratch" type buffers are considered to always be unchanged.
2891 bufIsChanged(buf)
2892 buf_T *buf;
2894 return
2895 #ifdef FEAT_QUICKFIX
2896 !bt_dontwrite(buf) &&
2897 #endif
2898 (buf->b_changed || file_ff_differs(buf));
2902 curbufIsChanged()
2904 return
2905 #ifdef FEAT_QUICKFIX
2906 !bt_dontwrite(curbuf) &&
2907 #endif
2908 (curbuf->b_changed || file_ff_differs(curbuf));