Merge branch 'vim-with-runtime' into feat/persistent-undo
[vim_extended.git] / src / undo.c
blob4ddea7ecef8705dac169a611d8a4179f2e298217
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 static 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;
337 * Common code for various ways to save text before a change.
339 static int
340 u_savecommon(top, bot, newbot)
341 linenr_T top, bot;
342 linenr_T newbot;
344 linenr_T lnum;
345 long i;
346 u_header_T *uhp;
347 u_header_T *old_curhead;
348 u_entry_T *uep;
349 u_entry_T *prev_uep;
350 long size;
352 /* When making changes is not allowed return FAIL. It's a crude way to
353 * make all change commands fail. */
354 if (!undo_allowed())
355 return FAIL;
357 #ifdef U_DEBUG
358 u_check(FALSE);
359 #endif
360 #ifdef FEAT_NETBEANS_INTG
362 * Netbeans defines areas that cannot be modified. Bail out here when
363 * trying to change text in a guarded area.
365 if (usingNetbeans)
367 if (netbeans_is_guarded(top, bot))
369 EMSG(_(e_guarded));
370 return FAIL;
372 if (curbuf->b_p_ro)
374 EMSG(_(e_nbreadonly));
375 return FAIL;
378 #endif
380 #ifdef FEAT_AUTOCMD
382 * Saving text for undo means we are going to make a change. Give a
383 * warning for a read-only file before making the change, so that the
384 * FileChangedRO event can replace the buffer with a read-write version
385 * (e.g., obtained from a source control system).
387 change_warning(0);
388 #endif
390 size = bot - top - 1;
393 * If curbuf->b_u_synced == TRUE make a new header.
395 if (curbuf->b_u_synced)
397 #ifdef FEAT_JUMPLIST
398 /* Need to create new entry in b_changelist. */
399 curbuf->b_new_change = TRUE;
400 #endif
402 if (p_ul >= 0)
405 * Make a new header entry. Do this first so that we don't mess
406 * up the undo info when out of memory.
408 uhp = (u_header_T *)U_ALLOC_LINE((unsigned)sizeof(u_header_T));
409 if (uhp == NULL)
410 goto nomem;
411 #ifdef U_DEBUG
412 uhp->uh_magic = UH_MAGIC;
413 #endif
415 else
416 uhp = NULL;
419 * If we undid more than we redid, move the entry lists before and
420 * including curbuf->b_u_curhead to an alternate branch.
422 old_curhead = curbuf->b_u_curhead;
423 if (old_curhead != NULL)
425 curbuf->b_u_newhead = old_curhead->uh_next;
426 curbuf->b_u_curhead = NULL;
430 * free headers to keep the size right
432 while (curbuf->b_u_numhead > p_ul && curbuf->b_u_oldhead != NULL)
434 u_header_T *uhfree = curbuf->b_u_oldhead;
436 if (uhfree == old_curhead)
437 /* Can't reconnect the branch, delete all of it. */
438 u_freebranch(curbuf, uhfree, &old_curhead);
439 else if (uhfree->uh_alt_next == NULL)
440 /* There is no branch, only free one header. */
441 u_freeheader(curbuf, uhfree, &old_curhead);
442 else
444 /* Free the oldest alternate branch as a whole. */
445 while (uhfree->uh_alt_next != NULL)
446 uhfree = uhfree->uh_alt_next;
447 u_freebranch(curbuf, uhfree, &old_curhead);
449 #ifdef U_DEBUG
450 u_check(TRUE);
451 #endif
454 if (uhp == NULL) /* no undo at all */
456 if (old_curhead != NULL)
457 u_freebranch(curbuf, old_curhead, NULL);
458 curbuf->b_u_synced = FALSE;
459 return OK;
462 uhp->uh_prev = NULL;
463 uhp->uh_next = curbuf->b_u_newhead;
464 uhp->uh_alt_next = old_curhead;
465 if (old_curhead != NULL)
467 uhp->uh_alt_prev = old_curhead->uh_alt_prev;
468 if (uhp->uh_alt_prev != NULL)
469 uhp->uh_alt_prev->uh_alt_next = uhp;
470 old_curhead->uh_alt_prev = uhp;
471 if (curbuf->b_u_oldhead == old_curhead)
472 curbuf->b_u_oldhead = uhp;
474 else
475 uhp->uh_alt_prev = NULL;
476 if (curbuf->b_u_newhead != NULL)
477 curbuf->b_u_newhead->uh_prev = uhp;
479 uhp->uh_seq = ++curbuf->b_u_seq_last;
480 curbuf->b_u_seq_cur = uhp->uh_seq;
481 uhp->uh_time = time(NULL);
482 curbuf->b_u_seq_time = uhp->uh_time + 1;
484 uhp->uh_walk = 0;
485 uhp->uh_entry = NULL;
486 uhp->uh_getbot_entry = NULL;
487 uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */
488 #ifdef FEAT_VIRTUALEDIT
489 if (virtual_active() && curwin->w_cursor.coladd > 0)
490 uhp->uh_cursor_vcol = getviscol();
491 else
492 uhp->uh_cursor_vcol = -1;
493 #endif
495 /* save changed and buffer empty flag for undo */
496 uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
497 ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
499 /* save named marks and Visual marks for undo */
500 mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
501 #ifdef FEAT_VISUAL
502 uhp->uh_visual = curbuf->b_visual;
503 #endif
505 curbuf->b_u_newhead = uhp;
506 if (curbuf->b_u_oldhead == NULL)
507 curbuf->b_u_oldhead = uhp;
508 ++curbuf->b_u_numhead;
510 else
512 if (p_ul < 0) /* no undo at all */
513 return OK;
516 * When saving a single line, and it has been saved just before, it
517 * doesn't make sense saving it again. Saves a lot of memory when
518 * making lots of changes inside the same line.
519 * This is only possible if the previous change didn't increase or
520 * decrease the number of lines.
521 * Check the ten last changes. More doesn't make sense and takes too
522 * long.
524 if (size == 1)
526 uep = u_get_headentry();
527 prev_uep = NULL;
528 for (i = 0; i < 10; ++i)
530 if (uep == NULL)
531 break;
533 /* If lines have been inserted/deleted we give up.
534 * Also when the line was included in a multi-line save. */
535 if ((curbuf->b_u_newhead->uh_getbot_entry != uep
536 ? (uep->ue_top + uep->ue_size + 1
537 != (uep->ue_bot == 0
538 ? curbuf->b_ml.ml_line_count + 1
539 : uep->ue_bot))
540 : uep->ue_lcount != curbuf->b_ml.ml_line_count)
541 || (uep->ue_size > 1
542 && top >= uep->ue_top
543 && top + 2 <= uep->ue_top + uep->ue_size + 1))
544 break;
546 /* If it's the same line we can skip saving it again. */
547 if (uep->ue_size == 1 && uep->ue_top == top)
549 if (i > 0)
551 /* It's not the last entry: get ue_bot for the last
552 * entry now. Following deleted/inserted lines go to
553 * the re-used entry. */
554 u_getbot();
555 curbuf->b_u_synced = FALSE;
557 /* Move the found entry to become the last entry. The
558 * order of undo/redo doesn't matter for the entries
559 * we move it over, since they don't change the line
560 * count and don't include this line. It does matter
561 * for the found entry if the line count is changed by
562 * the executed command. */
563 prev_uep->ue_next = uep->ue_next;
564 uep->ue_next = curbuf->b_u_newhead->uh_entry;
565 curbuf->b_u_newhead->uh_entry = uep;
568 /* The executed command may change the line count. */
569 if (newbot != 0)
570 uep->ue_bot = newbot;
571 else if (bot > curbuf->b_ml.ml_line_count)
572 uep->ue_bot = 0;
573 else
575 uep->ue_lcount = curbuf->b_ml.ml_line_count;
576 curbuf->b_u_newhead->uh_getbot_entry = uep;
578 return OK;
580 prev_uep = uep;
581 uep = uep->ue_next;
585 /* find line number for ue_bot for previous u_save() */
586 u_getbot();
589 #if !defined(UNIX) && !defined(DJGPP) && !defined(WIN32) && !defined(__EMX__)
591 * With Amiga and MSDOS 16 bit we can't handle big undo's, because
592 * then u_alloc_line would have to allocate a block larger than 32K
594 if (size >= 8000)
595 goto nomem;
596 #endif
599 * add lines in front of entry list
601 uep = (u_entry_T *)U_ALLOC_LINE((unsigned)sizeof(u_entry_T));
602 if (uep == NULL)
603 goto nomem;
604 #ifdef U_DEBUG
605 uep->ue_magic = UE_MAGIC;
606 #endif
608 uep->ue_size = size;
609 uep->ue_top = top;
610 if (newbot != 0)
611 uep->ue_bot = newbot;
613 * Use 0 for ue_bot if bot is below last line.
614 * Otherwise we have to compute ue_bot later.
616 else if (bot > curbuf->b_ml.ml_line_count)
617 uep->ue_bot = 0;
618 else
620 uep->ue_lcount = curbuf->b_ml.ml_line_count;
621 curbuf->b_u_newhead->uh_getbot_entry = uep;
624 if (size > 0)
626 if ((uep->ue_array = (char_u **)U_ALLOC_LINE(
627 (unsigned)(sizeof(char_u *) * size))) == NULL)
629 u_freeentry(uep, 0L);
630 goto nomem;
632 for (i = 0, lnum = top + 1; i < size; ++i)
634 fast_breakcheck();
635 if (got_int)
637 u_freeentry(uep, i);
638 return FAIL;
640 if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL)
642 u_freeentry(uep, i);
643 goto nomem;
647 else
648 uep->ue_array = NULL;
649 uep->ue_next = curbuf->b_u_newhead->uh_entry;
650 curbuf->b_u_newhead->uh_entry = uep;
651 curbuf->b_u_synced = FALSE;
652 undo_undoes = FALSE;
654 #ifdef U_DEBUG
655 u_check(FALSE);
656 #endif
657 return OK;
659 nomem:
660 msg_silent = 0; /* must display the prompt */
661 if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE)
662 == 'y')
664 undo_off = TRUE; /* will be reset when character typed */
665 return OK;
667 do_outofmem_msg((long_u)0);
668 return FAIL;
671 #ifdef FEAT_PERSISTENT_UNDO
672 static int
673 unserialize_pos(pos_T *pos, FILE *fp)
675 /* Unserialize the pos_T at the current position in fp. */
676 pos->lnum = get4c(fp);
677 pos->col = get4c(fp);
678 #ifdef FEAT_VIRTUALEDIT
679 pos->coladd = get4c(fp);
680 #endif
681 return 0;
684 #ifdef FEAT_VISUAL
685 static int
686 unserialize_visualinfo(visualinfo_T *info, FILE *fp)
688 /* Unserialize the visualinfo_T at the current position in fp. */
689 unserialize_pos(&info->vi_start, fp);
690 unserialize_pos(&info->vi_end, fp);
691 info->vi_mode = get4c(fp);
692 info->vi_curswant = get4c(fp);
693 return 0;
695 #endif
697 static char_u *
698 u_get_undofile(char_u *ffname)
700 /* Returns an allocated string of the full path of the target undofile */
701 char_u *undo_path = NULL;
702 char_u *dirp;
703 char_u dir_name[IOSIZE + 1];
704 char_u *munged_name;
705 int dir_len, undo_path_len, name_len;
706 int found_udir = FALSE;
707 int i;
708 if (ffname == NULL)
709 ffname = (char_u *) "";
711 name_len = STRLEN(ffname);
712 munged_name = alloc(name_len + 1);
713 mch_memmove(munged_name, ffname, name_len + 1);
715 for (i = 0; i < name_len; i++)
717 if (munged_name[i] == '/')
718 munged_name[i] = '_';
721 dirp = p_udir;
722 while (*dirp)
724 dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ",");
725 dir_name[dir_len] = '\0';
726 if (mch_isdir(dir_name))
728 found_udir = TRUE;
729 break;
733 if (found_udir == FALSE)
735 /* Found no created undo dirs, so create the first one in the list.*/
736 dirp = p_udir;
737 dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ",");
738 dir_name[dir_len] = '\0';
739 vim_mkdir(dir_name, 0755);
740 if (!mch_isdir(dir_name))
742 /* Couldn't create undo directory, bail */
743 vim_free(undo_path);
744 return NULL;
747 /* get_file_in_dir returns allocated memory */
748 undo_path = get_file_in_dir(munged_name, dir_name);
749 vim_free(munged_name);
750 undo_path_len = STRLEN(undo_path);
751 undo_path = vim_realloc(undo_path, sizeof(char_u) * undo_path_len + 5);
752 vim_strncpy(undo_path + undo_path_len, (char_u *) ".und", 4);
753 return undo_path;
756 void
757 u_rundo(char_u *name, int quiet)
759 /* Given a buffer name, load in the undo tree from an undo file. If quiet
760 * is 0, don't complain if there is no appropriate undo file. */
761 char_u *undo_file;
762 FILE *fp;
764 long magic, version, str_len, file_mtime;
765 char_u *line_ptr = NULL;
766 linenr_T line_lnum;
767 colnr_T line_colnr;
768 linenr_T line_count;
769 int uep_len;
770 int line_len;
771 int num_head;
772 long old_header_seq, new_header_seq, cur_header_seq, seq_last, seq_cur;
773 short old_idx = -1, new_idx = -1, cur_idx = -1;
774 long num_read_uhps = 0;
775 time_t seq_time;
776 int i, j;
777 int c;
778 short found_first_uep = 0;
779 char_u **array;
780 char_u *line;
781 u_entry_T *uep, *last_uep, *nuep;
782 u_header_T *uhp;
783 u_header_T **uhp_table = NULL;
785 if (name == NULL || STRLEN(name) == 0)
787 undo_file = u_get_undofile(curbuf->b_ffname);
789 else
791 undo_file = u_get_undofile(name);
793 if (undo_file == NULL)
795 if (!quiet)
796 EMSG(_("Error: Can't find or create an undo directory"));
797 return;
799 fp = fopen((char *)undo_file, "r");
800 if (fp == NULL)
802 if (!quiet)
803 EMSG2(_("Error: Can't open undo file %s for read"), undo_file);
804 vim_free(undo_file);
805 return;
809 /* Begin overall file information */
810 magic = get2c(fp);
811 if (magic != UF_MAGIC)
813 EMSG2(_("Error: corrupted undo file %s"), undo_file);
814 vim_free(undo_file);
815 goto error;
817 version = get2c(fp);
818 if (version != UF_VERSION)
820 EMSG2(_("Error: incompatible undo file %s"), undo_file);
821 vim_free(undo_file);
822 goto error;
824 vim_free(undo_file);
826 file_mtime = (long_u) get4c(fp);
827 if (file_mtime != curbuf->b_mtime)
829 if (p_verbose > 0 || !quiet)
831 verbose_enter();
832 give_warning((char_u *)_("Undo file mismatch"), TRUE);
833 verbose_leave();
835 goto error;
838 line_count = (linenr_T) get4c(fp);
839 if (line_count != curbuf->b_ml.ml_line_count)
841 if (p_verbose > 0 || !quiet)
843 verbose_enter();
844 give_warning((char_u *)_("Undo file linecount differs"), TRUE);
845 verbose_leave();
847 goto error;
850 /* Begin undo data for U */
851 str_len = get4c(fp);
852 if (str_len < 0)
853 goto error;
854 else if (str_len > 0)
856 if ((line_ptr = U_ALLOC_LINE(str_len)) == NULL)
858 EMSG("u_rundo: out of memory!");
859 goto error;
861 for (i = 0; i < str_len; i++)
863 line_ptr[i] = (char_u) getc(fp);
865 line_ptr[i] = '\0';
867 line_lnum = (linenr_T) get4c(fp);
868 line_colnr = (colnr_T) get4c(fp);
870 /* Begin general undo data */
871 old_header_seq = get4c(fp);
872 new_header_seq = get4c(fp);
873 cur_header_seq = get4c(fp);
874 num_head = get4c(fp);
875 seq_last = get4c(fp);
876 seq_cur = get4c(fp);
877 seq_time = get4c(fp);
878 /* uhp_table will store the freshly created undo headers we allocate
879 * until we insert them into curbuf. The table remains sorted by the
880 * sequence numbers of the headers.
882 uhp_table = (u_header_T **)U_ALLOC_LINE(num_head * sizeof(u_header_T *));
883 if (uhp_table == NULL)
885 EMSG("u_rundo: out of memory!");
886 goto error;
888 vim_memset(uhp_table, 0, num_head * sizeof(u_header_T *));
890 c = getc(fp);
891 while (c != 0x0a && c != EOF)
893 ungetc(c, fp);
895 found_first_uep = 0;
896 uhp = (u_header_T *)U_ALLOC_LINE((unsigned)sizeof(u_header_T));
897 if (uhp == NULL)
899 EMSG("u_rundo: out of memory!");
900 goto error;
902 vim_memset(uhp, 0, sizeof(u_header_T));
903 /* We're not actually trying to store pointers here. We're just storing
904 * IDs so we can swizzle them into pointers later - hence type hack */
905 uhp->uh_next = (u_header_T *)(long)get4c(fp);
906 uhp->uh_prev = (u_header_T *)(long)get4c(fp);
907 uhp->uh_alt_next = (u_header_T *)(long)get4c(fp);
908 uhp->uh_alt_prev = (u_header_T *)(long)get4c(fp);
909 uhp->uh_seq = get4c(fp);
910 if (uhp->uh_seq <= 0)
912 EMSG("u_rundo: undo file corruption detected: invalid uh_seq.");
913 U_FREE_LINE(uhp);
914 goto error;
916 uhp->uh_walk = 0;
917 unserialize_pos(&uhp->uh_cursor, fp);
918 #ifdef FEAT_VIRTUALEDIT
919 uhp->uh_cursor_vcol = get4c(fp);
920 #endif
921 uhp->uh_flags = get2c(fp);
922 for (i = 0; i < NMARKS; ++i)
924 unserialize_pos(&uhp->uh_namedm[i], fp);
926 #ifdef FEAT_VISUAL
927 unserialize_visualinfo(&uhp->uh_visual, fp);
928 #endif
929 uhp->uh_time = get4c(fp);
931 /* Unserialize uep list. The first 4 bytes is the length of the
932 * entire uep in bytes minus the length of the strings within.
933 * -1 is a sentinel value meaning no more ueps.*/
934 last_uep = NULL;
935 while ((uep_len = get4c(fp)) != -1)
937 uep = (u_entry_T *)U_ALLOC_LINE((unsigned)sizeof(u_entry_T));
938 vim_memset(uep, 0, sizeof(u_entry_T));
939 if (uep == NULL)
941 EMSG("u_rundo: out of memory!");
942 goto error;
944 uep->ue_top = get4c(fp);
945 uep->ue_bot = get4c(fp);
946 uep->ue_lcount = get4c(fp);
947 uep->ue_size = get4c(fp);
948 uep->ue_next = NULL;
949 array = (char_u **)U_ALLOC_LINE((unsigned)(sizeof(char_u *) * uep->ue_size));
950 for (i = 0; i < uep->ue_size; i++)
952 line_len = get4c(fp);
953 /* U_ALLOC_LINE provides an extra byte for the NUL terminator.*/
954 line = (char_u *)U_ALLOC_LINE((unsigned) (sizeof(char_u) * line_len));
955 if (line == NULL)
957 EMSG("u_rundo: out of memory!");
958 goto error;
960 for (j = 0; j < line_len; j++)
962 line[j] = getc(fp);
964 line[j] = '\0';
965 array[i] = line;
967 uep->ue_array = array;
968 if (found_first_uep == 0)
970 uhp->uh_entry = uep;
971 found_first_uep = 1;
973 else
975 last_uep->ue_next = uep;
977 last_uep = uep;
980 /* Insertion sort the uhp into the table by its uh_seq. This is
981 * required because, while the number of uhps is limited to
982 * num_heads, and the uh_seq order is monotonic with respect to
983 * creation time, the starting uh_seq can be > 0 if any undolevel
984 * culling was done at undofile write time, and there can be uh_seq
985 * gaps in the uhps.
987 for (i = num_read_uhps - 1; i >= -1; i--)
989 /* if i == -1, we've hit the leftmost side of the table, so insert
990 * at uhp_table[0]. */
991 if (i == -1 || uhp->uh_seq > uhp_table[i]->uh_seq)
993 /* If we've had to move from the rightmost side of the table,
994 * we have to shift everything to the right by one spot. */
995 if (i < num_read_uhps - 1)
997 memmove(uhp_table + i + 2, uhp_table + i + 1,
998 (num_read_uhps - i) * sizeof(u_header_T *));
1000 uhp_table[i + 1] = uhp;
1001 break;
1003 else if (uhp->uh_seq == uhp_table[i]->uh_seq)
1005 EMSG("u_rundo: undo file corruption detected: duplicate uh_seq.");
1006 goto error;
1009 num_read_uhps++;
1010 c = getc(fp);
1013 /* We've organized all of the uhps into a table sorted by uh_seq. Now we
1014 * iterate through the table and swizzle each sequence number we've
1015 * stored in uh_foo into a pointer corresponding to the header with that
1016 * sequence number. Then free curbuf's old undo structure, give curbuf
1017 * the updated {old,new,cur}head pointers, and then free the table. */
1018 for (i = 0; i < num_head; i++)
1020 uhp = uhp_table[i];
1021 if (uhp == NULL)
1022 continue;
1023 for (j = 0; j < num_head; j++)
1025 if (uhp_table[j] == NULL)
1026 continue;
1027 if (uhp_table[j]->uh_seq == (long)uhp->uh_next)
1028 uhp->uh_next = uhp_table[j];
1029 if (uhp_table[j]->uh_seq == (long)uhp->uh_prev)
1030 uhp->uh_prev = uhp_table[j];
1031 if (uhp_table[j]->uh_seq == (long)uhp->uh_alt_next)
1032 uhp->uh_alt_next = uhp_table[j];
1033 if (uhp_table[j]->uh_seq == (long)uhp->uh_alt_prev)
1034 uhp->uh_alt_prev = uhp_table[j];
1036 if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq)
1037 old_idx = i;
1038 if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq)
1039 new_idx = i;
1040 if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq)
1041 cur_idx = i;
1043 u_blockfree(curbuf);
1044 curbuf->b_u_oldhead = old_idx < 0 ? 0 : uhp_table[old_idx];
1045 curbuf->b_u_newhead = new_idx < 0 ? 0 : uhp_table[new_idx];
1046 curbuf->b_u_curhead = cur_idx < 0 ? 0 : uhp_table[cur_idx];
1047 curbuf->b_u_line_ptr = line_ptr;
1048 curbuf->b_u_line_lnum = line_lnum;
1049 curbuf->b_u_line_colnr = line_colnr;
1050 curbuf->b_u_numhead = num_head;
1051 curbuf->b_u_seq_last = seq_last;
1052 curbuf->b_u_seq_cur = seq_cur;
1053 curbuf->b_u_seq_time = seq_time;
1054 U_FREE_LINE(uhp_table);
1055 #ifdef U_DEBUG
1056 u_check(TRUE);
1057 #endif
1058 fclose(fp);
1059 return;
1062 error:
1063 if (fp != NULL)
1064 fclose(fp);
1065 if (line_ptr != NULL)
1066 U_FREE_LINE(line_ptr);
1067 if (uhp_table != NULL)
1069 for (i = 0; i < num_head; i++)
1071 if (uhp_table[i] != NULL)
1073 uep = uhp_table[i]->uh_entry;
1074 while (uep != NULL)
1076 nuep = uep->ue_next;
1077 u_freeentry(uep, uep->ue_size);
1078 uep = nuep;
1080 U_FREE_LINE(uhp_table[i]);
1083 U_FREE_LINE(uhp_table);
1085 return;
1088 static void
1089 serialize_uep(u_entry_T *uep, FILE *fp)
1091 /* Serialize the given u_entry_T to fp. */
1092 int i;
1093 int uep_len;
1094 int *entry_lens;
1096 if (uep->ue_size > 0)
1098 entry_lens = (int *)alloc(uep->ue_size * sizeof(int));
1101 /* Define uep_len to be the size of the entire uep minus the size of its
1102 * component strings, in bytes. The sizes of the component strings
1103 * are written before each individual string.
1104 * We have 4 entries each of 4 bytes, plus ue_size * 4 bytes
1105 * of string size information. */
1107 uep_len = uep->ue_size * 4;
1108 /* Collect sizing information for later serialization. */
1109 for (i = 0; i < uep->ue_size; i++)
1111 entry_lens[i] = (int) STRLEN(uep->ue_array[i]);
1112 uep_len += entry_lens[i];
1114 put_bytes(fp, (long_u) uep_len, 4);
1115 put_bytes(fp, (long_u) uep->ue_top, 4);
1116 put_bytes(fp, (long_u) uep->ue_bot, 4);
1117 put_bytes(fp, (long_u) uep->ue_lcount, 4);
1118 put_bytes(fp, (long_u) uep->ue_size, 4);
1119 for (i = 0; i < uep->ue_size; i++)
1121 put_bytes(fp, (long_u) entry_lens[i], 4);
1122 fprintf(fp, "%s", uep->ue_array[i]);
1124 if (uep->ue_size > 0)
1126 vim_free(entry_lens);
1130 static int lastmark = 0;
1132 static void
1133 serialize_pos(pos_T pos, FILE *fp)
1135 /* Serialize the given pos_T to fp. */
1136 put_bytes(fp, (long_u) pos.lnum, 4);
1137 put_bytes(fp, (long_u) pos.col, 4);
1138 #ifdef FEAT_VIRTUALEDIT
1139 put_bytes(fp, (long_u) pos.coladd, 4);
1140 #endif
1143 static void
1144 serialize_visualinfo(visualinfo_T info, FILE *fp)
1146 /* Serialize the given visualinfo_T to fp. */
1147 serialize_pos(info.vi_start, fp);
1148 serialize_pos(info.vi_end, fp);
1149 put_bytes(fp, (long_u) info.vi_mode, 4);
1150 put_bytes(fp, (long_u) info.vi_curswant, 4);
1153 void
1154 u_wundo(char_u *name, buf_T *buf)
1156 /* Given an optional buffer name and a buffer, write out the undo tree
1157 * to an undo file. */
1158 u_header_T *uhp;
1159 u_entry_T *uep;
1160 char_u *undo_file;
1161 int str_len, i, uep_len, mark;
1162 FILE *fp;
1164 if (name == NULL || STRLEN(name) == 0)
1166 undo_file = u_get_undofile(buf->b_ffname);
1168 else
1170 undo_file = u_get_undofile(name);
1172 if (undo_file == NULL)
1174 EMSG(_("Error: Can't find or create an undo directory"));
1175 return;
1177 fp = fopen((char *)undo_file, "w");
1178 if (fp == NULL)
1180 EMSG2(_("Error: Can't open undo file %s for write"), undo_file);
1181 vim_free(undo_file);
1182 return;
1184 vim_free(undo_file);
1186 /* Begin overall file information */
1187 put_bytes(fp, (long_u) UF_MAGIC, 2);
1188 put_bytes(fp, (long_u) UF_VERSION, 2);
1190 put_bytes(fp, (long_u) buf->b_mtime, 4);
1191 put_bytes(fp, (long_u) buf->b_ml.ml_line_count, 4);
1193 /* Begin undo data for U */
1194 str_len = buf->b_u_line_ptr != NULL ? STRLEN(buf->b_u_line_ptr) : 0;
1195 put_bytes(fp, (long_u) str_len, 4);
1196 for (i = 0; i < str_len; i++)
1198 put_bytes(fp, (long_u) buf->b_u_line_ptr[i], 1);
1201 put_bytes(fp, (long_u) buf->b_u_line_lnum, 4);
1202 put_bytes(fp, (long_u) buf->b_u_line_colnr, 4);
1204 /* Begin general undo data */
1205 uhp = buf->b_u_oldhead;
1206 put_bytes(fp, (long_u) (uhp != NULL ? uhp->uh_seq : 0), 4);
1208 uhp = buf->b_u_newhead;
1209 put_bytes(fp, (long_u) (uhp != NULL ? uhp->uh_seq : 0), 4);
1211 uhp = buf->b_u_curhead;
1212 put_bytes(fp, (long_u) (uhp != NULL ? uhp->uh_seq : 0), 4);
1214 put_bytes(fp, (long_u) buf->b_u_numhead, 4);
1215 put_bytes(fp, (long_u) buf->b_u_seq_last, 4);
1216 put_bytes(fp, (long_u) buf->b_u_seq_cur, 4);
1217 put_bytes(fp, (long_u) buf->b_u_seq_time, 4);
1219 /* Iteratively serialize UHPs and their UEPs from the top down. */
1220 mark = ++lastmark;
1221 uhp = buf->b_u_oldhead;
1222 while (uhp != NULL)
1224 /* Serialize current UHP if we haven't seen it */
1225 if (uhp->uh_walk != mark)
1227 put_bytes(fp, (long_u) ((uhp->uh_next != NULL) ? uhp->uh_next->uh_seq : 0), 4);
1228 put_bytes(fp, (long_u) ((uhp->uh_prev != NULL) ? uhp->uh_prev->uh_seq : 0), 4);
1229 put_bytes(fp, (long_u) ((uhp->uh_alt_next != NULL) ? uhp->uh_alt_next->uh_seq : 0), 4);
1230 put_bytes(fp, (long_u) ((uhp->uh_alt_prev != NULL) ? uhp->uh_alt_prev->uh_seq : 0), 4);
1231 put_bytes(fp, uhp->uh_seq, 4);
1232 serialize_pos(uhp->uh_cursor, fp);
1233 #ifdef FEAT_VIRTUALEDIT
1234 put_bytes(fp, (long_u) uhp->uh_cursor_vcol, 4);
1235 #endif
1236 put_bytes(fp, (long_u) uhp->uh_flags, 2);
1237 /* Assume NMARKS will stay the same. */
1238 for (i = 0; i < NMARKS; ++i)
1240 serialize_pos(uhp->uh_namedm[i], fp);
1242 #ifdef FEAT_VISUAL
1243 serialize_visualinfo(uhp->uh_visual, fp);
1244 #endif
1245 put_bytes(fp, (long_u) uhp->uh_time, 4);
1247 uep = uhp->uh_entry;
1248 while (uep != NULL)
1250 serialize_uep(uep, fp);
1251 uep = uep->ue_next;
1253 /* Sentinel value: no more ueps */
1254 uep_len = -1;
1255 put_bytes(fp, (long_u) uep_len, 4);
1256 uhp->uh_walk = mark;
1259 /* Now walk through the tree - algorithm from undo_time*/
1260 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != mark)
1261 uhp = uhp->uh_prev;
1262 else if (uhp->uh_alt_next != NULL && uhp->uh_alt_next->uh_walk != mark)
1263 uhp = uhp->uh_alt_next;
1264 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
1265 && uhp->uh_next->uh_walk != mark)
1266 uhp = uhp->uh_next;
1267 else if (uhp->uh_alt_prev != NULL)
1268 uhp = uhp->uh_alt_prev;
1269 else
1270 uhp = uhp->uh_next;
1272 fclose(fp);
1275 #endif /* FEAT_PERSISTENT_UNDO */
1279 * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible).
1280 * If 'cpoptions' does not contain 'u': Always undo.
1282 void
1283 u_undo(count)
1284 int count;
1287 * If we get an undo command while executing a macro, we behave like the
1288 * original vi. If this happens twice in one macro the result will not
1289 * be compatible.
1291 if (curbuf->b_u_synced == FALSE)
1293 u_sync(TRUE);
1294 count = 1;
1297 if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
1298 undo_undoes = TRUE;
1299 else
1300 undo_undoes = !undo_undoes;
1301 u_doit(count);
1305 * If 'cpoptions' contains 'u': Repeat the previous undo or redo.
1306 * If 'cpoptions' does not contain 'u': Always redo.
1308 void
1309 u_redo(count)
1310 int count;
1312 if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
1313 undo_undoes = FALSE;
1314 u_doit(count);
1318 * Undo or redo, depending on 'undo_undoes', 'count' times.
1320 static void
1321 u_doit(startcount)
1322 int startcount;
1324 int count = startcount;
1326 if (!undo_allowed())
1327 return;
1329 u_newcount = 0;
1330 u_oldcount = 0;
1331 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1332 u_oldcount = -1;
1333 while (count--)
1335 /* Do the change warning now, so that it triggers FileChangedRO when
1336 * needed. This may cause the file to be reloaded, that must happen
1337 * before we do anything, because it may change curbuf->b_u_curhead
1338 * and more. */
1339 change_warning(0);
1341 if (undo_undoes)
1343 if (curbuf->b_u_curhead == NULL) /* first undo */
1344 curbuf->b_u_curhead = curbuf->b_u_newhead;
1345 else if (p_ul > 0) /* multi level undo */
1346 /* get next undo */
1347 curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next;
1348 /* nothing to undo */
1349 if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL)
1351 /* stick curbuf->b_u_curhead at end */
1352 curbuf->b_u_curhead = curbuf->b_u_oldhead;
1353 beep_flush();
1354 if (count == startcount - 1)
1356 MSG(_("Already at oldest change"));
1357 return;
1359 break;
1362 u_undoredo(TRUE);
1364 else
1366 if (curbuf->b_u_curhead == NULL || p_ul <= 0)
1368 beep_flush(); /* nothing to redo */
1369 if (count == startcount - 1)
1371 MSG(_("Already at newest change"));
1372 return;
1374 break;
1377 u_undoredo(FALSE);
1379 /* Advance for next redo. Set "newhead" when at the end of the
1380 * redoable changes. */
1381 if (curbuf->b_u_curhead->uh_prev == NULL)
1382 curbuf->b_u_newhead = curbuf->b_u_curhead;
1383 curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev;
1386 u_undo_end(undo_undoes, FALSE);
1390 * Undo or redo over the timeline.
1391 * When "step" is negative go back in time, otherwise goes forward in time.
1392 * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as
1393 * seconds.
1394 * When "absolute" is TRUE use "step" as the sequence number to jump to.
1395 * "sec" must be FALSE then.
1397 void
1398 undo_time(step, sec, absolute)
1399 long step;
1400 int sec;
1401 int absolute;
1403 long target;
1404 long closest;
1405 long closest_start;
1406 long closest_seq = 0;
1407 long val;
1408 u_header_T *uhp;
1409 u_header_T *last;
1410 int mark;
1411 int nomark;
1412 int round;
1413 int dosec = sec;
1414 int above = FALSE;
1415 int did_undo = TRUE;
1417 /* First make sure the current undoable change is synced. */
1418 if (curbuf->b_u_synced == FALSE)
1419 u_sync(TRUE);
1421 u_newcount = 0;
1422 u_oldcount = 0;
1423 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1424 u_oldcount = -1;
1426 /* "target" is the node below which we want to be.
1427 * Init "closest" to a value we can't reach. */
1428 if (absolute)
1430 target = step;
1431 closest = -1;
1433 else
1435 /* When doing computations with time_t subtract starttime, because
1436 * time_t converted to a long may result in a wrong number. */
1437 if (sec)
1438 target = (long)(curbuf->b_u_seq_time - starttime) + step;
1439 else
1440 target = curbuf->b_u_seq_cur + step;
1441 if (step < 0)
1443 if (target < 0)
1444 target = 0;
1445 closest = -1;
1447 else
1449 if (sec)
1450 closest = (long)(time(NULL) - starttime + 1);
1451 else
1452 closest = curbuf->b_u_seq_last + 2;
1453 if (target >= closest)
1454 target = closest - 1;
1457 closest_start = closest;
1458 closest_seq = curbuf->b_u_seq_cur;
1461 * May do this twice:
1462 * 1. Search for "target", update "closest" to the best match found.
1463 * 2. If "target" not found search for "closest".
1465 * When using the closest time we use the sequence number in the second
1466 * round, because there may be several entries with the same time.
1468 for (round = 1; round <= 2; ++round)
1470 /* Find the path from the current state to where we want to go. The
1471 * desired state can be anywhere in the undo tree, need to go all over
1472 * it. We put "nomark" in uh_walk where we have been without success,
1473 * "mark" where it could possibly be. */
1474 mark = ++lastmark;
1475 nomark = ++lastmark;
1477 if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */
1478 uhp = curbuf->b_u_newhead;
1479 else
1480 uhp = curbuf->b_u_curhead;
1482 while (uhp != NULL)
1484 uhp->uh_walk = mark;
1485 val = (long)(dosec ? (uhp->uh_time - starttime) : uhp->uh_seq);
1487 if (round == 1)
1489 /* Remember the header that is closest to the target.
1490 * It must be at least in the right direction (checked with
1491 * "b_u_seq_cur"). When the timestamp is equal find the
1492 * highest/lowest sequence number. */
1493 if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur
1494 : uhp->uh_seq > curbuf->b_u_seq_cur)
1495 && ((dosec && val == closest)
1496 ? (step < 0
1497 ? uhp->uh_seq < closest_seq
1498 : uhp->uh_seq > closest_seq)
1499 : closest == closest_start
1500 || (val > target
1501 ? (closest > target
1502 ? val - target <= closest - target
1503 : val - target <= target - closest)
1504 : (closest > target
1505 ? target - val <= closest - target
1506 : target - val <= target - closest))))
1508 closest = val;
1509 closest_seq = uhp->uh_seq;
1513 /* Quit searching when we found a match. But when searching for a
1514 * time we need to continue looking for the best uh_seq. */
1515 if (target == val && !dosec)
1516 break;
1518 /* go down in the tree if we haven't been there */
1519 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != nomark
1520 && uhp->uh_prev->uh_walk != mark)
1521 uhp = uhp->uh_prev;
1523 /* go to alternate branch if we haven't been there */
1524 else if (uhp->uh_alt_next != NULL
1525 && uhp->uh_alt_next->uh_walk != nomark
1526 && uhp->uh_alt_next->uh_walk != mark)
1527 uhp = uhp->uh_alt_next;
1529 /* go up in the tree if we haven't been there and we are at the
1530 * start of alternate branches */
1531 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
1532 && uhp->uh_next->uh_walk != nomark
1533 && uhp->uh_next->uh_walk != mark)
1535 /* If still at the start we don't go through this change. */
1536 if (uhp == curbuf->b_u_curhead)
1537 uhp->uh_walk = nomark;
1538 uhp = uhp->uh_next;
1541 else
1543 /* need to backtrack; mark this node as useless */
1544 uhp->uh_walk = nomark;
1545 if (uhp->uh_alt_prev != NULL)
1546 uhp = uhp->uh_alt_prev;
1547 else
1548 uhp = uhp->uh_next;
1552 if (uhp != NULL) /* found it */
1553 break;
1555 if (absolute)
1557 EMSGN(_("Undo number %ld not found"), step);
1558 return;
1561 if (closest == closest_start)
1563 if (step < 0)
1564 MSG(_("Already at oldest change"));
1565 else
1566 MSG(_("Already at newest change"));
1567 return;
1570 target = closest_seq;
1571 dosec = FALSE;
1572 if (step < 0)
1573 above = TRUE; /* stop above the header */
1576 /* If we found it: Follow the path to go to where we want to be. */
1577 if (uhp != NULL)
1580 * First go up the tree as much as needed.
1582 while (!got_int)
1584 /* Do the change warning now, for the same reason as above. */
1585 change_warning(0);
1587 uhp = curbuf->b_u_curhead;
1588 if (uhp == NULL)
1589 uhp = curbuf->b_u_newhead;
1590 else
1591 uhp = uhp->uh_next;
1592 if (uhp == NULL || uhp->uh_walk != mark
1593 || (uhp->uh_seq == target && !above))
1594 break;
1595 curbuf->b_u_curhead = uhp;
1596 u_undoredo(TRUE);
1597 uhp->uh_walk = nomark; /* don't go back down here */
1601 * And now go down the tree (redo), branching off where needed.
1603 while (!got_int)
1605 /* Do the change warning now, for the same reason as above. */
1606 change_warning(0);
1608 uhp = curbuf->b_u_curhead;
1609 if (uhp == NULL)
1610 break;
1612 /* Go back to the first branch with a mark. */
1613 while (uhp->uh_alt_prev != NULL
1614 && uhp->uh_alt_prev->uh_walk == mark)
1615 uhp = uhp->uh_alt_prev;
1617 /* Find the last branch with a mark, that's the one. */
1618 last = uhp;
1619 while (last->uh_alt_next != NULL
1620 && last->uh_alt_next->uh_walk == mark)
1621 last = last->uh_alt_next;
1622 if (last != uhp)
1624 /* Make the used branch the first entry in the list of
1625 * alternatives to make "u" and CTRL-R take this branch. */
1626 while (uhp->uh_alt_prev != NULL)
1627 uhp = uhp->uh_alt_prev;
1628 if (last->uh_alt_next != NULL)
1629 last->uh_alt_next->uh_alt_prev = last->uh_alt_prev;
1630 last->uh_alt_prev->uh_alt_next = last->uh_alt_next;
1631 last->uh_alt_prev = NULL;
1632 last->uh_alt_next = uhp;
1633 uhp->uh_alt_prev = last;
1635 if (curbuf->b_u_oldhead == uhp)
1636 curbuf->b_u_oldhead = last;
1637 uhp = last;
1638 if (uhp->uh_next != NULL)
1639 uhp->uh_next->uh_prev = uhp;
1641 curbuf->b_u_curhead = uhp;
1643 if (uhp->uh_walk != mark)
1644 break; /* must have reached the target */
1646 /* Stop when going backwards in time and didn't find the exact
1647 * header we were looking for. */
1648 if (uhp->uh_seq == target && above)
1650 curbuf->b_u_seq_cur = target - 1;
1651 break;
1654 u_undoredo(FALSE);
1656 /* Advance "curhead" to below the header we last used. If it
1657 * becomes NULL then we need to set "newhead" to this leaf. */
1658 if (uhp->uh_prev == NULL)
1659 curbuf->b_u_newhead = uhp;
1660 curbuf->b_u_curhead = uhp->uh_prev;
1661 did_undo = FALSE;
1663 if (uhp->uh_seq == target) /* found it! */
1664 break;
1666 uhp = uhp->uh_prev;
1667 if (uhp == NULL || uhp->uh_walk != mark)
1669 /* Need to redo more but can't find it... */
1670 EMSG2(_(e_intern2), "undo_time()");
1671 break;
1675 u_undo_end(did_undo, absolute);
1679 * u_undoredo: common code for undo and redo
1681 * The lines in the file are replaced by the lines in the entry list at
1682 * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry
1683 * list for the next undo/redo.
1685 * When "undo" is TRUE we go up in the tree, when FALSE we go down.
1687 static void
1688 u_undoredo(undo)
1689 int undo;
1691 char_u **newarray = NULL;
1692 linenr_T oldsize;
1693 linenr_T newsize;
1694 linenr_T top, bot;
1695 linenr_T lnum;
1696 linenr_T newlnum = MAXLNUM;
1697 long i;
1698 u_entry_T *uep, *nuep;
1699 u_entry_T *newlist = NULL;
1700 int old_flags;
1701 int new_flags;
1702 pos_T namedm[NMARKS];
1703 #ifdef FEAT_VISUAL
1704 visualinfo_T visualinfo;
1705 #endif
1706 int empty_buffer; /* buffer became empty */
1707 u_header_T *curhead = curbuf->b_u_curhead;
1709 #ifdef FEAT_AUTOCMD
1710 /* Don't want autocommands using the undo structures here, they are
1711 * invalid till the end. */
1712 block_autocmds();
1713 #endif
1715 #ifdef U_DEBUG
1716 u_check(FALSE);
1717 #endif
1718 old_flags = curhead->uh_flags;
1719 new_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
1720 ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
1721 setpcmark();
1724 * save marks before undo/redo
1726 mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
1727 #ifdef FEAT_VISUAL
1728 visualinfo = curbuf->b_visual;
1729 #endif
1730 curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count;
1731 curbuf->b_op_start.col = 0;
1732 curbuf->b_op_end.lnum = 0;
1733 curbuf->b_op_end.col = 0;
1735 for (uep = curhead->uh_entry; uep != NULL; uep = nuep)
1737 top = uep->ue_top;
1738 bot = uep->ue_bot;
1739 if (bot == 0)
1740 bot = curbuf->b_ml.ml_line_count + 1;
1741 if (top > curbuf->b_ml.ml_line_count || top >= bot
1742 || bot > curbuf->b_ml.ml_line_count + 1)
1744 #ifdef FEAT_AUTOCMD
1745 unblock_autocmds();
1746 #endif
1747 EMSG(_("E438: u_undo: line numbers wrong"));
1748 changed(); /* don't want UNCHANGED now */
1749 return;
1752 oldsize = bot - top - 1; /* number of lines before undo */
1753 newsize = uep->ue_size; /* number of lines after undo */
1755 if (top < newlnum)
1757 /* If the saved cursor is somewhere in this undo block, move it to
1758 * the remembered position. Makes "gwap" put the cursor back
1759 * where it was. */
1760 lnum = curhead->uh_cursor.lnum;
1761 if (lnum >= top && lnum <= top + newsize + 1)
1763 curwin->w_cursor = curhead->uh_cursor;
1764 newlnum = curwin->w_cursor.lnum - 1;
1766 else
1768 /* Use the first line that actually changed. Avoids that
1769 * undoing auto-formatting puts the cursor in the previous
1770 * line. */
1771 for (i = 0; i < newsize && i < oldsize; ++i)
1772 if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0)
1773 break;
1774 if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL)
1776 newlnum = top;
1777 curwin->w_cursor.lnum = newlnum + 1;
1779 else if (i < newsize)
1781 newlnum = top + i;
1782 curwin->w_cursor.lnum = newlnum + 1;
1787 empty_buffer = FALSE;
1789 /* delete the lines between top and bot and save them in newarray */
1790 if (oldsize > 0)
1792 if ((newarray = (char_u **)U_ALLOC_LINE(
1793 (unsigned)(sizeof(char_u *) * oldsize))) == NULL)
1795 do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize));
1797 * We have messed up the entry list, repair is impossible.
1798 * we have to free the rest of the list.
1800 while (uep != NULL)
1802 nuep = uep->ue_next;
1803 u_freeentry(uep, uep->ue_size);
1804 uep = nuep;
1806 break;
1808 /* delete backwards, it goes faster in most cases */
1809 for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum)
1811 /* what can we do when we run out of memory? */
1812 if ((newarray[i] = u_save_line(lnum)) == NULL)
1813 do_outofmem_msg((long_u)0);
1814 /* remember we deleted the last line in the buffer, and a
1815 * dummy empty line will be inserted */
1816 if (curbuf->b_ml.ml_line_count == 1)
1817 empty_buffer = TRUE;
1818 ml_delete(lnum, FALSE);
1821 else
1822 newarray = NULL;
1824 /* insert the lines in u_array between top and bot */
1825 if (newsize)
1827 for (lnum = top, i = 0; i < newsize; ++i, ++lnum)
1830 * If the file is empty, there is an empty line 1 that we
1831 * should get rid of, by replacing it with the new line
1833 if (empty_buffer && lnum == 0)
1834 ml_replace((linenr_T)1, uep->ue_array[i], TRUE);
1835 else
1836 ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE);
1837 U_FREE_LINE(uep->ue_array[i]);
1839 U_FREE_LINE((char_u *)uep->ue_array);
1842 /* adjust marks */
1843 if (oldsize != newsize)
1845 mark_adjust(top + 1, top + oldsize, (long)MAXLNUM,
1846 (long)newsize - (long)oldsize);
1847 if (curbuf->b_op_start.lnum > top + oldsize)
1848 curbuf->b_op_start.lnum += newsize - oldsize;
1849 if (curbuf->b_op_end.lnum > top + oldsize)
1850 curbuf->b_op_end.lnum += newsize - oldsize;
1853 changed_lines(top + 1, 0, bot, newsize - oldsize);
1855 /* set '[ and '] mark */
1856 if (top + 1 < curbuf->b_op_start.lnum)
1857 curbuf->b_op_start.lnum = top + 1;
1858 if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum)
1859 curbuf->b_op_end.lnum = top + 1;
1860 else if (top + newsize > curbuf->b_op_end.lnum)
1861 curbuf->b_op_end.lnum = top + newsize;
1863 u_newcount += newsize;
1864 u_oldcount += oldsize;
1865 uep->ue_size = oldsize;
1866 uep->ue_array = newarray;
1867 uep->ue_bot = top + newsize + 1;
1870 * insert this entry in front of the new entry list
1872 nuep = uep->ue_next;
1873 uep->ue_next = newlist;
1874 newlist = uep;
1877 curhead->uh_entry = newlist;
1878 curhead->uh_flags = new_flags;
1879 if ((old_flags & UH_EMPTYBUF) && bufempty())
1880 curbuf->b_ml.ml_flags |= ML_EMPTY;
1881 if (old_flags & UH_CHANGED)
1882 changed();
1883 else
1884 #ifdef FEAT_NETBEANS_INTG
1885 /* per netbeans undo rules, keep it as modified */
1886 if (!isNetbeansModified(curbuf))
1887 #endif
1888 unchanged(curbuf, FALSE);
1891 * restore marks from before undo/redo
1893 for (i = 0; i < NMARKS; ++i)
1894 if (curhead->uh_namedm[i].lnum != 0)
1896 curbuf->b_namedm[i] = curhead->uh_namedm[i];
1897 curhead->uh_namedm[i] = namedm[i];
1899 #ifdef FEAT_VISUAL
1900 if (curhead->uh_visual.vi_start.lnum != 0)
1902 curbuf->b_visual = curhead->uh_visual;
1903 curhead->uh_visual = visualinfo;
1905 #endif
1908 * If the cursor is only off by one line, put it at the same position as
1909 * before starting the change (for the "o" command).
1910 * Otherwise the cursor should go to the first undone line.
1912 if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum
1913 && curwin->w_cursor.lnum > 1)
1914 --curwin->w_cursor.lnum;
1915 if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum)
1917 curwin->w_cursor.col = curhead->uh_cursor.col;
1918 #ifdef FEAT_VIRTUALEDIT
1919 if (virtual_active() && curhead->uh_cursor_vcol >= 0)
1920 coladvance((colnr_T)curhead->uh_cursor_vcol);
1921 else
1922 curwin->w_cursor.coladd = 0;
1923 #endif
1925 else if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count)
1926 beginline(BL_SOL | BL_FIX);
1927 else
1929 /* We get here with the current cursor line being past the end (eg
1930 * after adding lines at the end of the file, and then undoing it).
1931 * check_cursor() will move the cursor to the last line. Move it to
1932 * the first column here. */
1933 curwin->w_cursor.col = 0;
1934 #ifdef FEAT_VIRTUALEDIT
1935 curwin->w_cursor.coladd = 0;
1936 #endif
1939 /* Make sure the cursor is on an existing line and column. */
1940 check_cursor();
1942 /* Remember where we are for "g-" and ":earlier 10s". */
1943 curbuf->b_u_seq_cur = curhead->uh_seq;
1944 if (undo)
1945 /* We are below the previous undo. However, to make ":earlier 1s"
1946 * work we compute this as being just above the just undone change. */
1947 --curbuf->b_u_seq_cur;
1949 /* The timestamp can be the same for multiple changes, just use the one of
1950 * the undone/redone change. */
1951 curbuf->b_u_seq_time = curhead->uh_time;
1953 #ifdef FEAT_AUTOCMD
1954 unblock_autocmds();
1955 #endif
1956 #ifdef U_DEBUG
1957 u_check(FALSE);
1958 #endif
1962 * If we deleted or added lines, report the number of less/more lines.
1963 * Otherwise, report the number of changes (this may be incorrect
1964 * in some cases, but it's better than nothing).
1966 static void
1967 u_undo_end(did_undo, absolute)
1968 int did_undo; /* just did an undo */
1969 int absolute; /* used ":undo N" */
1971 char *msgstr;
1972 u_header_T *uhp;
1973 char_u msgbuf[80];
1975 #ifdef FEAT_FOLDING
1976 if ((fdo_flags & FDO_UNDO) && KeyTyped)
1977 foldOpenCursor();
1978 #endif
1980 if (global_busy /* no messages now, wait until global is finished */
1981 || !messaging()) /* 'lazyredraw' set, don't do messages now */
1982 return;
1984 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1985 --u_newcount;
1987 u_oldcount -= u_newcount;
1988 if (u_oldcount == -1)
1989 msgstr = N_("more line");
1990 else if (u_oldcount < 0)
1991 msgstr = N_("more lines");
1992 else if (u_oldcount == 1)
1993 msgstr = N_("line less");
1994 else if (u_oldcount > 1)
1995 msgstr = N_("fewer lines");
1996 else
1998 u_oldcount = u_newcount;
1999 if (u_newcount == 1)
2000 msgstr = N_("change");
2001 else
2002 msgstr = N_("changes");
2005 if (curbuf->b_u_curhead != NULL)
2007 /* For ":undo N" we prefer a "after #N" message. */
2008 if (absolute && curbuf->b_u_curhead->uh_next != NULL)
2010 uhp = curbuf->b_u_curhead->uh_next;
2011 did_undo = FALSE;
2013 else if (did_undo)
2014 uhp = curbuf->b_u_curhead;
2015 else
2016 uhp = curbuf->b_u_curhead->uh_next;
2018 else
2019 uhp = curbuf->b_u_newhead;
2021 if (uhp == NULL)
2022 *msgbuf = NUL;
2023 else
2024 u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time);
2026 smsg((char_u *)_("%ld %s; %s #%ld %s"),
2027 u_oldcount < 0 ? -u_oldcount : u_oldcount,
2028 _(msgstr),
2029 did_undo ? _("before") : _("after"),
2030 uhp == NULL ? 0L : uhp->uh_seq,
2031 msgbuf);
2035 * u_sync: stop adding to the current entry list
2037 void
2038 u_sync(force)
2039 int force; /* Also sync when no_u_sync is set. */
2041 /* Skip it when already synced or syncing is disabled. */
2042 if (curbuf->b_u_synced || (!force && no_u_sync > 0))
2043 return;
2044 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2045 if (im_is_preediting())
2046 return; /* XIM is busy, don't break an undo sequence */
2047 #endif
2048 if (p_ul < 0)
2049 curbuf->b_u_synced = TRUE; /* no entries, nothing to do */
2050 else
2052 u_getbot(); /* compute ue_bot of previous u_save */
2053 curbuf->b_u_curhead = NULL;
2059 * ":undolist": List the leafs of the undo tree
2061 void
2062 ex_undolist(eap)
2063 exarg_T *eap UNUSED;
2065 garray_T ga;
2066 u_header_T *uhp;
2067 int mark;
2068 int nomark;
2069 int changes = 1;
2070 int i;
2073 * 1: walk the tree to find all leafs, put the info in "ga".
2074 * 2: sort the lines
2075 * 3: display the list
2077 mark = ++lastmark;
2078 nomark = ++lastmark;
2079 ga_init2(&ga, (int)sizeof(char *), 20);
2081 uhp = curbuf->b_u_oldhead;
2082 while (uhp != NULL)
2084 if (uhp->uh_prev == NULL && uhp->uh_walk != nomark
2085 && uhp->uh_walk != mark)
2087 if (ga_grow(&ga, 1) == FAIL)
2088 break;
2089 vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ",
2090 uhp->uh_seq, changes);
2091 u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff),
2092 uhp->uh_time);
2093 ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff);
2096 uhp->uh_walk = mark;
2098 /* go down in the tree if we haven't been there */
2099 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != nomark
2100 && uhp->uh_prev->uh_walk != mark)
2102 uhp = uhp->uh_prev;
2103 ++changes;
2106 /* go to alternate branch if we haven't been there */
2107 else if (uhp->uh_alt_next != NULL
2108 && uhp->uh_alt_next->uh_walk != nomark
2109 && uhp->uh_alt_next->uh_walk != mark)
2110 uhp = uhp->uh_alt_next;
2112 /* go up in the tree if we haven't been there and we are at the
2113 * start of alternate branches */
2114 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
2115 && uhp->uh_next->uh_walk != nomark
2116 && uhp->uh_next->uh_walk != mark)
2118 uhp = uhp->uh_next;
2119 --changes;
2122 else
2124 /* need to backtrack; mark this node as done */
2125 uhp->uh_walk = nomark;
2126 if (uhp->uh_alt_prev != NULL)
2127 uhp = uhp->uh_alt_prev;
2128 else
2130 uhp = uhp->uh_next;
2131 --changes;
2136 if (ga.ga_len == 0)
2137 MSG(_("Nothing to undo"));
2138 else
2140 sort_strings((char_u **)ga.ga_data, ga.ga_len);
2142 msg_start();
2143 msg_puts_attr((char_u *)_("number changes time"), hl_attr(HLF_T));
2144 for (i = 0; i < ga.ga_len && !got_int; ++i)
2146 msg_putchar('\n');
2147 if (got_int)
2148 break;
2149 msg_puts(((char_u **)ga.ga_data)[i]);
2151 msg_end();
2153 ga_clear_strings(&ga);
2158 * Put the timestamp of an undo header in "buf[buflen]" in a nice format.
2160 static void
2161 u_add_time(buf, buflen, tt)
2162 char_u *buf;
2163 size_t buflen;
2164 time_t tt;
2166 #ifdef HAVE_STRFTIME
2167 struct tm *curtime;
2169 if (time(NULL) - tt >= 100)
2171 curtime = localtime(&tt);
2172 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
2174 else
2175 #endif
2176 vim_snprintf((char *)buf, buflen, _("%ld seconds ago"),
2177 (long)(time(NULL) - tt));
2181 * ":undojoin": continue adding to the last entry list
2183 void
2184 ex_undojoin(eap)
2185 exarg_T *eap UNUSED;
2187 if (curbuf->b_u_newhead == NULL)
2188 return; /* nothing changed before */
2189 if (curbuf->b_u_curhead != NULL)
2191 EMSG(_("E790: undojoin is not allowed after undo"));
2192 return;
2194 if (!curbuf->b_u_synced)
2195 return; /* already unsynced */
2196 if (p_ul < 0)
2197 return; /* no entries, nothing to do */
2198 else
2200 /* Go back to the last entry */
2201 curbuf->b_u_curhead = curbuf->b_u_newhead;
2202 curbuf->b_u_synced = FALSE; /* no entries, nothing to do */
2207 * Called after writing the file and setting b_changed to FALSE.
2208 * Now an undo means that the buffer is modified.
2210 void
2211 u_unchanged(buf)
2212 buf_T *buf;
2214 u_unch_branch(buf->b_u_oldhead);
2215 buf->b_did_warn = FALSE;
2218 static void
2219 u_unch_branch(uhp)
2220 u_header_T *uhp;
2222 u_header_T *uh;
2224 for (uh = uhp; uh != NULL; uh = uh->uh_prev)
2226 uh->uh_flags |= UH_CHANGED;
2227 if (uh->uh_alt_next != NULL)
2228 u_unch_branch(uh->uh_alt_next); /* recursive */
2233 * Get pointer to last added entry.
2234 * If it's not valid, give an error message and return NULL.
2236 static u_entry_T *
2237 u_get_headentry()
2239 if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL)
2241 EMSG(_("E439: undo list corrupt"));
2242 return NULL;
2244 return curbuf->b_u_newhead->uh_entry;
2248 * u_getbot(): compute the line number of the previous u_save
2249 * It is called only when b_u_synced is FALSE.
2251 static void
2252 u_getbot()
2254 u_entry_T *uep;
2255 linenr_T extra;
2257 uep = u_get_headentry(); /* check for corrupt undo list */
2258 if (uep == NULL)
2259 return;
2261 uep = curbuf->b_u_newhead->uh_getbot_entry;
2262 if (uep != NULL)
2265 * the new ue_bot is computed from the number of lines that has been
2266 * inserted (0 - deleted) since calling u_save. This is equal to the
2267 * old line count subtracted from the current line count.
2269 extra = curbuf->b_ml.ml_line_count - uep->ue_lcount;
2270 uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra;
2271 if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count)
2273 EMSG(_("E440: undo line missing"));
2274 uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will
2275 * get all the old lines back
2276 * without deleting the current
2277 * ones */
2280 curbuf->b_u_newhead->uh_getbot_entry = NULL;
2283 curbuf->b_u_synced = TRUE;
2287 * Free one header "uhp" and its entry list and adjust the pointers.
2289 static void
2290 u_freeheader(buf, uhp, uhpp)
2291 buf_T *buf;
2292 u_header_T *uhp;
2293 u_header_T **uhpp; /* if not NULL reset when freeing this header */
2295 u_header_T *uhap;
2297 /* When there is an alternate redo list free that branch completely,
2298 * because we can never go there. */
2299 if (uhp->uh_alt_next != NULL)
2300 u_freebranch(buf, uhp->uh_alt_next, uhpp);
2302 if (uhp->uh_alt_prev != NULL)
2303 uhp->uh_alt_prev->uh_alt_next = NULL;
2305 /* Update the links in the list to remove the header. */
2306 if (uhp->uh_next == NULL)
2307 buf->b_u_oldhead = uhp->uh_prev;
2308 else
2309 uhp->uh_next->uh_prev = uhp->uh_prev;
2311 if (uhp->uh_prev == NULL)
2312 buf->b_u_newhead = uhp->uh_next;
2313 else
2314 for (uhap = uhp->uh_prev; uhap != NULL; uhap = uhap->uh_alt_next)
2315 uhap->uh_next = uhp->uh_next;
2317 u_freeentries(buf, uhp, uhpp);
2321 * Free an alternate branch and any following alternate branches.
2323 static void
2324 u_freebranch(buf, uhp, uhpp)
2325 buf_T *buf;
2326 u_header_T *uhp;
2327 u_header_T **uhpp; /* if not NULL reset when freeing this header */
2329 u_header_T *tofree, *next;
2331 /* If this is the top branch we may need to use u_freeheader() to update
2332 * all the pointers. */
2333 if (uhp == buf->b_u_oldhead)
2335 u_freeheader(buf, uhp, uhpp);
2336 return;
2339 if (uhp->uh_alt_prev != NULL)
2340 uhp->uh_alt_prev->uh_alt_next = NULL;
2342 next = uhp;
2343 while (next != NULL)
2345 tofree = next;
2346 if (tofree->uh_alt_next != NULL)
2347 u_freebranch(buf, tofree->uh_alt_next, uhpp); /* recursive */
2348 next = tofree->uh_prev;
2349 u_freeentries(buf, tofree, uhpp);
2354 * Free all the undo entries for one header and the header itself.
2355 * This means that "uhp" is invalid when returning.
2357 static void
2358 u_freeentries(buf, uhp, uhpp)
2359 buf_T *buf;
2360 u_header_T *uhp;
2361 u_header_T **uhpp; /* if not NULL reset when freeing this header */
2363 u_entry_T *uep, *nuep;
2365 /* Check for pointers to the header that become invalid now. */
2366 if (buf->b_u_curhead == uhp)
2367 buf->b_u_curhead = NULL;
2368 if (buf->b_u_newhead == uhp)
2369 buf->b_u_newhead = NULL; /* freeing the newest entry */
2370 if (uhpp != NULL && uhp == *uhpp)
2371 *uhpp = NULL;
2373 for (uep = uhp->uh_entry; uep != NULL; uep = nuep)
2375 nuep = uep->ue_next;
2376 u_freeentry(uep, uep->ue_size);
2379 #ifdef U_DEBUG
2380 uhp->uh_magic = 0;
2381 #endif
2382 U_FREE_LINE((char_u *)uhp);
2383 --buf->b_u_numhead;
2387 * free entry 'uep' and 'n' lines in uep->ue_array[]
2389 static void
2390 u_freeentry(uep, n)
2391 u_entry_T *uep;
2392 long n;
2394 while (n > 0)
2395 U_FREE_LINE(uep->ue_array[--n]);
2396 U_FREE_LINE((char_u *)uep->ue_array);
2397 #ifdef U_DEBUG
2398 uep->ue_magic = 0;
2399 #endif
2400 U_FREE_LINE((char_u *)uep);
2404 * invalidate the undo buffer; called when storage has already been released
2406 void
2407 u_clearall(buf)
2408 buf_T *buf;
2410 buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL;
2411 buf->b_u_synced = TRUE;
2412 buf->b_u_numhead = 0;
2413 buf->b_u_line_ptr = NULL;
2414 buf->b_u_line_lnum = 0;
2418 * save the line "lnum" for the "U" command
2420 void
2421 u_saveline(lnum)
2422 linenr_T lnum;
2424 if (lnum == curbuf->b_u_line_lnum) /* line is already saved */
2425 return;
2426 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */
2427 return;
2428 u_clearline();
2429 curbuf->b_u_line_lnum = lnum;
2430 if (curwin->w_cursor.lnum == lnum)
2431 curbuf->b_u_line_colnr = curwin->w_cursor.col;
2432 else
2433 curbuf->b_u_line_colnr = 0;
2434 if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL)
2435 do_outofmem_msg((long_u)0);
2439 * clear the line saved for the "U" command
2440 * (this is used externally for crossing a line while in insert mode)
2442 void
2443 u_clearline()
2445 if (curbuf->b_u_line_ptr != NULL)
2447 U_FREE_LINE(curbuf->b_u_line_ptr);
2448 curbuf->b_u_line_ptr = NULL;
2449 curbuf->b_u_line_lnum = 0;
2454 * Implementation of the "U" command.
2455 * Differentiation from vi: "U" can be undone with the next "U".
2456 * We also allow the cursor to be in another line.
2458 void
2459 u_undoline()
2461 colnr_T t;
2462 char_u *oldp;
2464 if (undo_off)
2465 return;
2467 if (curbuf->b_u_line_ptr == NULL
2468 || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count)
2470 beep_flush();
2471 return;
2474 /* first save the line for the 'u' command */
2475 if (u_savecommon(curbuf->b_u_line_lnum - 1,
2476 curbuf->b_u_line_lnum + 1, (linenr_T)0) == FAIL)
2477 return;
2478 oldp = u_save_line(curbuf->b_u_line_lnum);
2479 if (oldp == NULL)
2481 do_outofmem_msg((long_u)0);
2482 return;
2484 ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE);
2485 changed_bytes(curbuf->b_u_line_lnum, 0);
2486 U_FREE_LINE(curbuf->b_u_line_ptr);
2487 curbuf->b_u_line_ptr = oldp;
2489 t = curbuf->b_u_line_colnr;
2490 if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum)
2491 curbuf->b_u_line_colnr = curwin->w_cursor.col;
2492 curwin->w_cursor.col = t;
2493 curwin->w_cursor.lnum = curbuf->b_u_line_lnum;
2494 check_cursor_col();
2498 * There are two implementations of the memory management for undo:
2499 * 1. Use the standard malloc()/free() functions.
2500 * This should be fast for allocating memory, but when a buffer is
2501 * abandoned every single allocated chunk must be freed, which may be slow.
2502 * 2. Allocate larger blocks of memory and keep track of chunks ourselves.
2503 * This is fast for abandoning, but the use of linked lists is slow for
2504 * finding a free chunk. Esp. when a lot of lines are changed or deleted.
2505 * A bit of profiling showed that the first method is faster, especially when
2506 * making a large number of changes, under the condition that malloc()/free()
2507 * is implemented efficiently.
2509 #ifdef U_USE_MALLOC
2511 * Version of undo memory allocation using malloc()/free()
2513 * U_FREE_LINE() and U_ALLOC_LINE() are macros that invoke vim_free() and
2514 * lalloc() directly.
2518 * Free all allocated memory blocks for the buffer 'buf'.
2520 void
2521 u_blockfree(buf)
2522 buf_T *buf;
2524 while (buf->b_u_oldhead != NULL)
2525 u_freeheader(buf, buf->b_u_oldhead, NULL);
2526 U_FREE_LINE(buf->b_u_line_ptr);
2529 #else
2531 * Storage allocation for the undo lines and blocks of the current file.
2532 * Version where Vim keeps track of the available memory.
2536 * Memory is allocated in relatively large blocks. These blocks are linked
2537 * in the allocated block list, headed by curbuf->b_block_head. They are all
2538 * freed when abandoning a file, so we don't have to free every single line.
2539 * The list is kept sorted on memory address.
2540 * block_alloc() allocates a block.
2541 * m_blockfree() frees all blocks.
2543 * The available chunks of memory are kept in free chunk lists. There is
2544 * one free list for each block of allocated memory. The list is kept sorted
2545 * on memory address.
2546 * u_alloc_line() gets a chunk from the free lists.
2547 * u_free_line() returns a chunk to the free lists.
2548 * curbuf->b_m_search points to the chunk before the chunk that was
2549 * freed/allocated the last time.
2550 * curbuf->b_mb_current points to the b_head where curbuf->b_m_search
2551 * points into the free list.
2554 * b_block_head /---> block #1 /---> block #2
2555 * mb_next ---/ mb_next ---/ mb_next ---> NULL
2556 * mb_info mb_info mb_info
2557 * | | |
2558 * V V V
2559 * NULL free chunk #1.1 free chunk #2.1
2560 * | |
2561 * V V
2562 * free chunk #1.2 NULL
2565 * NULL
2567 * When a single free chunk list would have been used, it could take a lot
2568 * of time in u_free_line() to find the correct place to insert a chunk in the
2569 * free list. The single free list would become very long when many lines are
2570 * changed (e.g. with :%s/^M$//).
2574 * this blocksize is used when allocating new lines
2576 #define MEMBLOCKSIZE 2044
2579 * The size field contains the size of the chunk, including the size field
2580 * itself.
2582 * When the chunk is not in-use it is preceded with the m_info structure.
2583 * The m_next field links it in one of the free chunk lists.
2585 * On most unix systems structures have to be longword (32 or 64 bit) aligned.
2586 * On most other systems they are short (16 bit) aligned.
2589 /* the structure definitions are now in structs.h */
2591 #ifdef ALIGN_LONG
2592 /* size of m_size */
2593 # define M_OFFSET (sizeof(long_u))
2594 #else
2595 /* size of m_size */
2596 # define M_OFFSET (sizeof(short_u))
2597 #endif
2599 static char_u *u_blockalloc __ARGS((long_u));
2602 * Allocate a block of memory and link it in the allocated block list.
2604 static char_u *
2605 u_blockalloc(size)
2606 long_u size;
2608 mblock_T *p;
2609 mblock_T *mp, *next;
2611 p = (mblock_T *)lalloc(size + sizeof(mblock_T), FALSE);
2612 if (p != NULL)
2614 /* Insert the block into the allocated block list, keeping it
2615 sorted on address. */
2616 for (mp = &curbuf->b_block_head;
2617 (next = mp->mb_next) != NULL && next < p;
2618 mp = next)
2620 p->mb_next = next; /* link in block list */
2621 p->mb_size = size;
2622 p->mb_maxsize = 0; /* nothing free yet */
2623 mp->mb_next = p;
2624 p->mb_info.m_next = NULL; /* clear free list */
2625 p->mb_info.m_size = 0;
2626 curbuf->b_mb_current = p; /* remember current block */
2627 curbuf->b_m_search = NULL;
2628 p++; /* return usable memory */
2630 return (char_u *)p;
2634 * free all allocated memory blocks for the buffer 'buf'
2636 void
2637 u_blockfree(buf)
2638 buf_T *buf;
2640 mblock_T *p, *np;
2642 for (p = buf->b_block_head.mb_next; p != NULL; p = np)
2644 np = p->mb_next;
2645 vim_free(p);
2647 buf->b_block_head.mb_next = NULL;
2648 buf->b_m_search = NULL;
2649 buf->b_mb_current = NULL;
2653 * Free a chunk of memory for the current buffer.
2654 * Insert the chunk into the correct free list, keeping it sorted on address.
2656 static void
2657 u_free_line(ptr, keep)
2658 char_u *ptr;
2659 int keep; /* don't free the block when it's empty */
2661 minfo_T *next;
2662 minfo_T *prev, *curr;
2663 minfo_T *mp;
2664 mblock_T *nextb;
2665 mblock_T *prevb;
2666 long_u maxsize;
2668 if (ptr == NULL || ptr == IObuff)
2669 return; /* illegal address can happen in out-of-memory situations */
2671 mp = (minfo_T *)(ptr - M_OFFSET);
2673 /* find block where chunk could be a part off */
2674 /* if we change curbuf->b_mb_current, curbuf->b_m_search is set to NULL */
2675 if (curbuf->b_mb_current == NULL || mp < (minfo_T *)curbuf->b_mb_current)
2677 curbuf->b_mb_current = curbuf->b_block_head.mb_next;
2678 curbuf->b_m_search = NULL;
2680 if ((nextb = curbuf->b_mb_current->mb_next) != NULL
2681 && (minfo_T *)nextb < mp)
2683 curbuf->b_mb_current = nextb;
2684 curbuf->b_m_search = NULL;
2686 while ((nextb = curbuf->b_mb_current->mb_next) != NULL
2687 && (minfo_T *)nextb < mp)
2688 curbuf->b_mb_current = nextb;
2690 curr = NULL;
2692 * If mp is smaller than curbuf->b_m_search->m_next go to the start of
2693 * the free list
2695 if (curbuf->b_m_search == NULL || mp < (curbuf->b_m_search->m_next))
2696 next = &(curbuf->b_mb_current->mb_info);
2697 else
2698 next = curbuf->b_m_search;
2700 * The following loop is executed very often.
2701 * Therefore it has been optimized at the cost of readability.
2702 * Keep it fast!
2704 #ifdef SLOW_BUT_EASY_TO_READ
2707 prev = curr;
2708 curr = next;
2709 next = next->m_next;
2711 while (mp > next && next != NULL);
2712 #else
2713 do /* first, middle, last */
2715 prev = next->m_next; /* curr, next, prev */
2716 if (prev == NULL || mp <= prev)
2718 prev = curr;
2719 curr = next;
2720 next = next->m_next;
2721 break;
2723 curr = prev->m_next; /* next, prev, curr */
2724 if (curr == NULL || mp <= curr)
2726 prev = next;
2727 curr = prev->m_next;
2728 next = curr->m_next;
2729 break;
2731 next = curr->m_next; /* prev, curr, next */
2733 while (mp > next && next != NULL);
2734 #endif
2736 /* if *mp and *next are concatenated, join them into one chunk */
2737 if ((char_u *)mp + mp->m_size == (char_u *)next)
2739 mp->m_size += next->m_size;
2740 mp->m_next = next->m_next;
2742 else
2743 mp->m_next = next;
2744 maxsize = mp->m_size;
2746 /* if *curr and *mp are concatenated, join them */
2747 if (prev != NULL && (char_u *)curr + curr->m_size == (char_u *)mp)
2749 curr->m_size += mp->m_size;
2750 maxsize = curr->m_size;
2751 curr->m_next = mp->m_next;
2752 curbuf->b_m_search = prev;
2754 else
2756 curr->m_next = mp;
2757 curbuf->b_m_search = curr; /* put curbuf->b_m_search before freed
2758 chunk */
2762 * If the block only contains free memory now, release it.
2764 if (!keep && curbuf->b_mb_current->mb_size
2765 == curbuf->b_mb_current->mb_info.m_next->m_size)
2767 /* Find the block before the current one to be able to unlink it from
2768 * the list of blocks. */
2769 prevb = &curbuf->b_block_head;
2770 for (nextb = prevb->mb_next; nextb != curbuf->b_mb_current;
2771 nextb = nextb->mb_next)
2772 prevb = nextb;
2773 prevb->mb_next = nextb->mb_next;
2774 vim_free(nextb);
2775 curbuf->b_mb_current = NULL;
2776 curbuf->b_m_search = NULL;
2778 else if (curbuf->b_mb_current->mb_maxsize < maxsize)
2779 curbuf->b_mb_current->mb_maxsize = maxsize;
2783 * Allocate and initialize a new line structure with room for at least
2784 * 'size' characters plus a terminating NUL.
2786 static char_u *
2787 u_alloc_line(size)
2788 unsigned size;
2790 minfo_T *mp, *mprev, *mp2;
2791 mblock_T *mbp;
2792 int size_align;
2795 * Add room for size field and trailing NUL byte.
2796 * Adjust for minimal size (must be able to store minfo_T
2797 * plus a trailing NUL, so the chunk can be released again)
2799 size += M_OFFSET + 1;
2800 if (size < sizeof(minfo_T) + 1)
2801 size = sizeof(minfo_T) + 1;
2804 * round size up for alignment
2806 size_align = (size + ALIGN_MASK) & ~ALIGN_MASK;
2809 * If curbuf->b_m_search is NULL (uninitialized free list) start at
2810 * curbuf->b_block_head
2812 if (curbuf->b_mb_current == NULL || curbuf->b_m_search == NULL)
2814 curbuf->b_mb_current = &curbuf->b_block_head;
2815 curbuf->b_m_search = &(curbuf->b_block_head.mb_info);
2818 /* Search for a block with enough space. */
2819 mbp = curbuf->b_mb_current;
2820 while (mbp->mb_maxsize < size_align)
2822 if (mbp->mb_next != NULL)
2823 mbp = mbp->mb_next;
2824 else
2825 mbp = &curbuf->b_block_head;
2826 if (mbp == curbuf->b_mb_current)
2828 int n = (size_align > (MEMBLOCKSIZE / 4)
2829 ? size_align : MEMBLOCKSIZE);
2831 /* Back where we started in block list: need to add a new block
2832 * with enough space. */
2833 mp = (minfo_T *)u_blockalloc((long_u)n);
2834 if (mp == NULL)
2835 return (NULL);
2836 mp->m_size = n;
2837 u_free_line((char_u *)mp + M_OFFSET, TRUE);
2838 mbp = curbuf->b_mb_current;
2839 break;
2842 if (mbp != curbuf->b_mb_current)
2843 curbuf->b_m_search = &(mbp->mb_info);
2845 /* In this block find a chunk with enough space. */
2846 mprev = curbuf->b_m_search;
2847 mp = curbuf->b_m_search->m_next;
2848 for (;;)
2850 if (mp == NULL) /* at end of the list */
2851 mp = &(mbp->mb_info); /* wrap around to begin */
2852 if (mp->m_size >= size)
2853 break;
2854 if (mp == curbuf->b_m_search)
2856 /* back where we started in free chunk list: "cannot happen" */
2857 EMSG2(_(e_intern2), "u_alloc_line()");
2858 return NULL;
2860 mprev = mp;
2861 mp = mp->m_next;
2864 /* when using the largest chunk adjust mb_maxsize */
2865 if (mp->m_size >= mbp->mb_maxsize)
2866 mbp->mb_maxsize = 0;
2868 /* if the chunk we found is large enough, split it up in two */
2869 if ((long)mp->m_size - size_align >= (long)(sizeof(minfo_T) + 1))
2871 mp2 = (minfo_T *)((char_u *)mp + size_align);
2872 mp2->m_size = mp->m_size - size_align;
2873 mp2->m_next = mp->m_next;
2874 mprev->m_next = mp2;
2875 mp->m_size = size_align;
2877 else /* remove *mp from the free list */
2879 mprev->m_next = mp->m_next;
2881 curbuf->b_m_search = mprev;
2882 curbuf->b_mb_current = mbp;
2884 /* If using the largest chunk need to find the new largest chunk */
2885 if (mbp->mb_maxsize == 0)
2886 for (mp2 = &(mbp->mb_info); mp2 != NULL; mp2 = mp2->m_next)
2887 if (mbp->mb_maxsize < mp2->m_size)
2888 mbp->mb_maxsize = mp2->m_size;
2890 mp = (minfo_T *)((char_u *)mp + M_OFFSET);
2891 *(char_u *)mp = NUL; /* set the first byte to NUL */
2893 return ((char_u *)mp);
2895 #endif
2898 * u_save_line(): allocate memory with u_alloc_line() and copy line 'lnum'
2899 * into it.
2901 static char_u *
2902 u_save_line(lnum)
2903 linenr_T lnum;
2905 char_u *src;
2906 char_u *dst;
2907 unsigned len;
2909 src = ml_get(lnum);
2910 len = (unsigned)STRLEN(src);
2911 if ((dst = U_ALLOC_LINE(len)) != NULL)
2912 mch_memmove(dst, src, (size_t)(len + 1));
2913 return (dst);
2917 * Check if the 'modified' flag is set, or 'ff' has changed (only need to
2918 * check the first character, because it can only be "dos", "unix" or "mac").
2919 * "nofile" and "scratch" type buffers are considered to always be unchanged.
2922 bufIsChanged(buf)
2923 buf_T *buf;
2925 return
2926 #ifdef FEAT_QUICKFIX
2927 !bt_dontwrite(buf) &&
2928 #endif
2929 (buf->b_changed || file_ff_differs(buf));
2933 curbufIsChanged()
2935 return
2936 #ifdef FEAT_QUICKFIX
2937 !bt_dontwrite(curbuf) &&
2938 #endif
2939 (curbuf->b_changed || file_ff_differs(curbuf));