Merge branch 'vim'
[vim_extended.git] / src / undo.c
blob0f34af81eb9f1b2aa55c70b9b2a2c110c03eda55
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 /* See below: use malloc()/free() for memory management. */
88 #define U_USE_MALLOC 1
90 static void u_unch_branch __ARGS((u_header_T *uhp));
91 static u_entry_T *u_get_headentry __ARGS((void));
92 static void u_getbot __ARGS((void));
93 static int u_savecommon __ARGS((linenr_T, linenr_T, linenr_T));
94 static void u_doit __ARGS((int count));
95 static void u_undoredo __ARGS((int undo));
96 static void u_undo_end __ARGS((int did_undo, int absolute));
97 static void u_add_time __ARGS((char_u *buf, size_t buflen, time_t tt));
98 static void u_freeheader __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp));
99 static void u_freebranch __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp));
100 static void u_freeentries __ARGS((buf_T *buf, u_header_T *uhp, u_header_T **uhpp));
101 static void u_freeentry __ARGS((u_entry_T *, long));
103 #ifdef U_USE_MALLOC
104 # define U_FREE_LINE(ptr) vim_free(ptr)
105 # define U_ALLOC_LINE(size) lalloc((long_u)((size) + 1), FALSE)
106 #else
107 static void u_free_line __ARGS((char_u *ptr, int keep));
108 static char_u *u_alloc_line __ARGS((unsigned size));
109 # define U_FREE_LINE(ptr) u_free_line((ptr), FALSE)
110 # define U_ALLOC_LINE(size) u_alloc_line(size)
111 #endif
112 static char_u *u_save_line __ARGS((linenr_T));
114 static long u_newcount, u_oldcount;
117 * When 'u' flag included in 'cpoptions', we behave like vi. Need to remember
118 * the action that "u" should do.
120 static int undo_undoes = FALSE;
122 #ifdef U_DEBUG
124 * Check the undo structures for being valid. Print a warning when something
125 * looks wrong.
127 static int seen_b_u_curhead;
128 static int seen_b_u_newhead;
129 static int header_count;
131 static void
132 u_check_tree(u_header_T *uhp,
133 u_header_T *exp_uh_next,
134 u_header_T *exp_uh_alt_prev)
136 u_entry_T *uep;
138 if (uhp == NULL)
139 return;
140 ++header_count;
141 if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1)
143 EMSG("b_u_curhead found twice (looping?)");
144 return;
146 if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1)
148 EMSG("b_u_newhead found twice (looping?)");
149 return;
152 if (uhp->uh_magic != UH_MAGIC)
153 EMSG("uh_magic wrong (may be using freed memory)");
154 else
156 /* Check pointers back are correct. */
157 if (uhp->uh_next != exp_uh_next)
159 EMSG("uh_next wrong");
160 smsg((char_u *)"expected: 0x%x, actual: 0x%x",
161 exp_uh_next, uhp->uh_next);
163 if (uhp->uh_alt_prev != exp_uh_alt_prev)
165 EMSG("uh_alt_prev wrong");
166 smsg((char_u *)"expected: 0x%x, actual: 0x%x",
167 exp_uh_alt_prev, uhp->uh_alt_prev);
170 /* Check the undo tree at this header. */
171 for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next)
173 if (uep->ue_magic != UE_MAGIC)
175 EMSG("ue_magic wrong (may be using freed memory)");
176 break;
180 /* Check the next alt tree. */
181 u_check_tree(uhp->uh_alt_next, uhp->uh_next, uhp);
183 /* Check the next header in this branch. */
184 u_check_tree(uhp->uh_prev, uhp, NULL);
188 static void
189 u_check(int newhead_may_be_NULL)
191 seen_b_u_newhead = 0;
192 seen_b_u_curhead = 0;
193 header_count = 0;
195 u_check_tree(curbuf->b_u_oldhead, NULL, NULL);
197 if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL
198 && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL))
199 EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead);
200 if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0)
201 EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead);
202 if (header_count != curbuf->b_u_numhead)
204 EMSG("b_u_numhead invalid");
205 smsg((char_u *)"expected: %ld, actual: %ld",
206 (long)header_count, (long)curbuf->b_u_numhead);
209 #endif
212 * Save the current line for both the "u" and "U" command.
213 * Returns OK or FAIL.
216 u_save_cursor()
218 return (u_save((linenr_T)(curwin->w_cursor.lnum - 1),
219 (linenr_T)(curwin->w_cursor.lnum + 1)));
223 * Save the lines between "top" and "bot" for both the "u" and "U" command.
224 * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1.
225 * Returns FAIL when lines could not be saved, OK otherwise.
228 u_save(top, bot)
229 linenr_T top, bot;
231 if (undo_off)
232 return OK;
234 if (top > curbuf->b_ml.ml_line_count ||
235 top >= bot || bot > curbuf->b_ml.ml_line_count + 1)
236 return FALSE; /* rely on caller to do error messages */
238 if (top + 2 == bot)
239 u_saveline((linenr_T)(top + 1));
241 return (u_savecommon(top, bot, (linenr_T)0));
245 * Save the line "lnum" (used by ":s" and "~" command).
246 * The line is replaced, so the new bottom line is lnum + 1.
249 u_savesub(lnum)
250 linenr_T lnum;
252 if (undo_off)
253 return OK;
255 return (u_savecommon(lnum - 1, lnum + 1, lnum + 1));
259 * A new line is inserted before line "lnum" (used by :s command).
260 * The line is inserted, so the new bottom line is lnum + 1.
263 u_inssub(lnum)
264 linenr_T lnum;
266 if (undo_off)
267 return OK;
269 return (u_savecommon(lnum - 1, lnum, lnum + 1));
273 * Save the lines "lnum" - "lnum" + nlines (used by delete command).
274 * The lines are deleted, so the new bottom line is lnum, unless the buffer
275 * becomes empty.
278 u_savedel(lnum, nlines)
279 linenr_T lnum;
280 long nlines;
282 if (undo_off)
283 return OK;
285 return (u_savecommon(lnum - 1, lnum + nlines,
286 nlines == curbuf->b_ml.ml_line_count ? 2 : lnum));
290 * Return TRUE when undo is allowed. Otherwise give an error message and
291 * return FALSE.
294 undo_allowed()
296 /* Don't allow changes when 'modifiable' is off. */
297 if (!curbuf->b_p_ma)
299 EMSG(_(e_modifiable));
300 return FALSE;
303 #ifdef HAVE_SANDBOX
304 /* In the sandbox it's not allowed to change the text. */
305 if (sandbox != 0)
307 EMSG(_(e_sandbox));
308 return FALSE;
310 #endif
312 /* Don't allow changes in the buffer while editing the cmdline. The
313 * caller of getcmdline() may get confused. */
314 if (textlock != 0)
316 EMSG(_(e_secure));
317 return FALSE;
320 return TRUE;
324 * Common code for various ways to save text before a change.
326 static int
327 u_savecommon(top, bot, newbot)
328 linenr_T top, bot;
329 linenr_T newbot;
331 linenr_T lnum;
332 long i;
333 u_header_T *uhp;
334 u_header_T *old_curhead;
335 u_entry_T *uep;
336 u_entry_T *prev_uep;
337 long size;
339 /* When making changes is not allowed return FAIL. It's a crude way to
340 * make all change commands fail. */
341 if (!undo_allowed())
342 return FAIL;
344 #ifdef U_DEBUG
345 u_check(FALSE);
346 #endif
347 #ifdef FEAT_NETBEANS_INTG
349 * Netbeans defines areas that cannot be modified. Bail out here when
350 * trying to change text in a guarded area.
352 if (usingNetbeans)
354 if (netbeans_is_guarded(top, bot))
356 EMSG(_(e_guarded));
357 return FAIL;
359 if (curbuf->b_p_ro)
361 EMSG(_(e_nbreadonly));
362 return FAIL;
365 #endif
367 #ifdef FEAT_AUTOCMD
369 * Saving text for undo means we are going to make a change. Give a
370 * warning for a read-only file before making the change, so that the
371 * FileChangedRO event can replace the buffer with a read-write version
372 * (e.g., obtained from a source control system).
374 change_warning(0);
375 #endif
377 size = bot - top - 1;
380 * If curbuf->b_u_synced == TRUE make a new header.
382 if (curbuf->b_u_synced)
384 #ifdef FEAT_JUMPLIST
385 /* Need to create new entry in b_changelist. */
386 curbuf->b_new_change = TRUE;
387 #endif
389 if (p_ul >= 0)
392 * Make a new header entry. Do this first so that we don't mess
393 * up the undo info when out of memory.
395 uhp = (u_header_T *)U_ALLOC_LINE((unsigned)sizeof(u_header_T));
396 if (uhp == NULL)
397 goto nomem;
398 #ifdef U_DEBUG
399 uhp->uh_magic = UH_MAGIC;
400 #endif
402 else
403 uhp = NULL;
406 * If we undid more than we redid, move the entry lists before and
407 * including curbuf->b_u_curhead to an alternate branch.
409 old_curhead = curbuf->b_u_curhead;
410 if (old_curhead != NULL)
412 curbuf->b_u_newhead = old_curhead->uh_next;
413 curbuf->b_u_curhead = NULL;
417 * free headers to keep the size right
419 while (curbuf->b_u_numhead > p_ul && curbuf->b_u_oldhead != NULL)
421 u_header_T *uhfree = curbuf->b_u_oldhead;
423 if (uhfree == old_curhead)
424 /* Can't reconnect the branch, delete all of it. */
425 u_freebranch(curbuf, uhfree, &old_curhead);
426 else if (uhfree->uh_alt_next == NULL)
427 /* There is no branch, only free one header. */
428 u_freeheader(curbuf, uhfree, &old_curhead);
429 else
431 /* Free the oldest alternate branch as a whole. */
432 while (uhfree->uh_alt_next != NULL)
433 uhfree = uhfree->uh_alt_next;
434 u_freebranch(curbuf, uhfree, &old_curhead);
436 #ifdef U_DEBUG
437 u_check(TRUE);
438 #endif
441 if (uhp == NULL) /* no undo at all */
443 if (old_curhead != NULL)
444 u_freebranch(curbuf, old_curhead, NULL);
445 curbuf->b_u_synced = FALSE;
446 return OK;
449 uhp->uh_prev = NULL;
450 uhp->uh_next = curbuf->b_u_newhead;
451 uhp->uh_alt_next = old_curhead;
452 if (old_curhead != NULL)
454 uhp->uh_alt_prev = old_curhead->uh_alt_prev;
455 if (uhp->uh_alt_prev != NULL)
456 uhp->uh_alt_prev->uh_alt_next = uhp;
457 old_curhead->uh_alt_prev = uhp;
458 if (curbuf->b_u_oldhead == old_curhead)
459 curbuf->b_u_oldhead = uhp;
461 else
462 uhp->uh_alt_prev = NULL;
463 if (curbuf->b_u_newhead != NULL)
464 curbuf->b_u_newhead->uh_prev = uhp;
466 uhp->uh_seq = ++curbuf->b_u_seq_last;
467 curbuf->b_u_seq_cur = uhp->uh_seq;
468 uhp->uh_time = time(NULL);
469 curbuf->b_u_seq_time = uhp->uh_time + 1;
471 uhp->uh_walk = 0;
472 uhp->uh_entry = NULL;
473 uhp->uh_getbot_entry = NULL;
474 uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */
475 #ifdef FEAT_VIRTUALEDIT
476 if (virtual_active() && curwin->w_cursor.coladd > 0)
477 uhp->uh_cursor_vcol = getviscol();
478 else
479 uhp->uh_cursor_vcol = -1;
480 #endif
482 /* save changed and buffer empty flag for undo */
483 uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
484 ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
486 /* save named marks and Visual marks for undo */
487 mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
488 #ifdef FEAT_VISUAL
489 uhp->uh_visual = curbuf->b_visual;
490 #endif
492 curbuf->b_u_newhead = uhp;
493 if (curbuf->b_u_oldhead == NULL)
494 curbuf->b_u_oldhead = uhp;
495 ++curbuf->b_u_numhead;
497 else
499 if (p_ul < 0) /* no undo at all */
500 return OK;
503 * When saving a single line, and it has been saved just before, it
504 * doesn't make sense saving it again. Saves a lot of memory when
505 * making lots of changes inside the same line.
506 * This is only possible if the previous change didn't increase or
507 * decrease the number of lines.
508 * Check the ten last changes. More doesn't make sense and takes too
509 * long.
511 if (size == 1)
513 uep = u_get_headentry();
514 prev_uep = NULL;
515 for (i = 0; i < 10; ++i)
517 if (uep == NULL)
518 break;
520 /* If lines have been inserted/deleted we give up.
521 * Also when the line was included in a multi-line save. */
522 if ((curbuf->b_u_newhead->uh_getbot_entry != uep
523 ? (uep->ue_top + uep->ue_size + 1
524 != (uep->ue_bot == 0
525 ? curbuf->b_ml.ml_line_count + 1
526 : uep->ue_bot))
527 : uep->ue_lcount != curbuf->b_ml.ml_line_count)
528 || (uep->ue_size > 1
529 && top >= uep->ue_top
530 && top + 2 <= uep->ue_top + uep->ue_size + 1))
531 break;
533 /* If it's the same line we can skip saving it again. */
534 if (uep->ue_size == 1 && uep->ue_top == top)
536 if (i > 0)
538 /* It's not the last entry: get ue_bot for the last
539 * entry now. Following deleted/inserted lines go to
540 * the re-used entry. */
541 u_getbot();
542 curbuf->b_u_synced = FALSE;
544 /* Move the found entry to become the last entry. The
545 * order of undo/redo doesn't matter for the entries
546 * we move it over, since they don't change the line
547 * count and don't include this line. It does matter
548 * for the found entry if the line count is changed by
549 * the executed command. */
550 prev_uep->ue_next = uep->ue_next;
551 uep->ue_next = curbuf->b_u_newhead->uh_entry;
552 curbuf->b_u_newhead->uh_entry = uep;
555 /* The executed command may change the line count. */
556 if (newbot != 0)
557 uep->ue_bot = newbot;
558 else if (bot > curbuf->b_ml.ml_line_count)
559 uep->ue_bot = 0;
560 else
562 uep->ue_lcount = curbuf->b_ml.ml_line_count;
563 curbuf->b_u_newhead->uh_getbot_entry = uep;
565 return OK;
567 prev_uep = uep;
568 uep = uep->ue_next;
572 /* find line number for ue_bot for previous u_save() */
573 u_getbot();
576 #if !defined(UNIX) && !defined(DJGPP) && !defined(WIN32) && !defined(__EMX__)
578 * With Amiga and MSDOS 16 bit we can't handle big undo's, because
579 * then u_alloc_line would have to allocate a block larger than 32K
581 if (size >= 8000)
582 goto nomem;
583 #endif
586 * add lines in front of entry list
588 uep = (u_entry_T *)U_ALLOC_LINE((unsigned)sizeof(u_entry_T));
589 if (uep == NULL)
590 goto nomem;
591 #ifdef U_DEBUG
592 uep->ue_magic = UE_MAGIC;
593 #endif
595 uep->ue_size = size;
596 uep->ue_top = top;
597 if (newbot != 0)
598 uep->ue_bot = newbot;
600 * Use 0 for ue_bot if bot is below last line.
601 * Otherwise we have to compute ue_bot later.
603 else if (bot > curbuf->b_ml.ml_line_count)
604 uep->ue_bot = 0;
605 else
607 uep->ue_lcount = curbuf->b_ml.ml_line_count;
608 curbuf->b_u_newhead->uh_getbot_entry = uep;
611 if (size > 0)
613 if ((uep->ue_array = (char_u **)U_ALLOC_LINE(
614 (unsigned)(sizeof(char_u *) * size))) == NULL)
616 u_freeentry(uep, 0L);
617 goto nomem;
619 for (i = 0, lnum = top + 1; i < size; ++i)
621 fast_breakcheck();
622 if (got_int)
624 u_freeentry(uep, i);
625 return FAIL;
627 if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL)
629 u_freeentry(uep, i);
630 goto nomem;
634 else
635 uep->ue_array = NULL;
636 uep->ue_next = curbuf->b_u_newhead->uh_entry;
637 curbuf->b_u_newhead->uh_entry = uep;
638 curbuf->b_u_synced = FALSE;
639 undo_undoes = FALSE;
641 #ifdef U_DEBUG
642 u_check(FALSE);
643 #endif
644 return OK;
646 nomem:
647 msg_silent = 0; /* must display the prompt */
648 if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE)
649 == 'y')
651 undo_off = TRUE; /* will be reset when character typed */
652 return OK;
654 do_outofmem_msg((long_u)0);
655 return FAIL;
659 * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible).
660 * If 'cpoptions' does not contain 'u': Always undo.
662 void
663 u_undo(count)
664 int count;
667 * If we get an undo command while executing a macro, we behave like the
668 * original vi. If this happens twice in one macro the result will not
669 * be compatible.
671 if (curbuf->b_u_synced == FALSE)
673 u_sync(TRUE);
674 count = 1;
677 if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
678 undo_undoes = TRUE;
679 else
680 undo_undoes = !undo_undoes;
681 u_doit(count);
685 * If 'cpoptions' contains 'u': Repeat the previous undo or redo.
686 * If 'cpoptions' does not contain 'u': Always redo.
688 void
689 u_redo(count)
690 int count;
692 if (vim_strchr(p_cpo, CPO_UNDO) == NULL)
693 undo_undoes = FALSE;
694 u_doit(count);
698 * Undo or redo, depending on 'undo_undoes', 'count' times.
700 static void
701 u_doit(startcount)
702 int startcount;
704 int count = startcount;
706 if (!undo_allowed())
707 return;
709 u_newcount = 0;
710 u_oldcount = 0;
711 if (curbuf->b_ml.ml_flags & ML_EMPTY)
712 u_oldcount = -1;
713 while (count--)
715 /* Do the change warning now, so that it triggers FileChangedRO when
716 * needed. This may cause the file to be reloaded, that must happen
717 * before we do anything, because it may change curbuf->b_u_curhead
718 * and more. */
719 change_warning(0);
721 if (undo_undoes)
723 if (curbuf->b_u_curhead == NULL) /* first undo */
724 curbuf->b_u_curhead = curbuf->b_u_newhead;
725 else if (p_ul > 0) /* multi level undo */
726 /* get next undo */
727 curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next;
728 /* nothing to undo */
729 if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL)
731 /* stick curbuf->b_u_curhead at end */
732 curbuf->b_u_curhead = curbuf->b_u_oldhead;
733 beep_flush();
734 if (count == startcount - 1)
736 MSG(_("Already at oldest change"));
737 return;
739 break;
742 u_undoredo(TRUE);
744 else
746 if (curbuf->b_u_curhead == NULL || p_ul <= 0)
748 beep_flush(); /* nothing to redo */
749 if (count == startcount - 1)
751 MSG(_("Already at newest change"));
752 return;
754 break;
757 u_undoredo(FALSE);
759 /* Advance for next redo. Set "newhead" when at the end of the
760 * redoable changes. */
761 if (curbuf->b_u_curhead->uh_prev == NULL)
762 curbuf->b_u_newhead = curbuf->b_u_curhead;
763 curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev;
766 u_undo_end(undo_undoes, FALSE);
769 static int lastmark = 0;
772 * Undo or redo over the timeline.
773 * When "step" is negative go back in time, otherwise goes forward in time.
774 * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as
775 * seconds.
776 * When "absolute" is TRUE use "step" as the sequence number to jump to.
777 * "sec" must be FALSE then.
779 void
780 undo_time(step, sec, absolute)
781 long step;
782 int sec;
783 int absolute;
785 long target;
786 long closest;
787 long closest_start;
788 long closest_seq = 0;
789 long val;
790 u_header_T *uhp;
791 u_header_T *last;
792 int mark;
793 int nomark;
794 int round;
795 int dosec = sec;
796 int above = FALSE;
797 int did_undo = TRUE;
799 /* First make sure the current undoable change is synced. */
800 if (curbuf->b_u_synced == FALSE)
801 u_sync(TRUE);
803 u_newcount = 0;
804 u_oldcount = 0;
805 if (curbuf->b_ml.ml_flags & ML_EMPTY)
806 u_oldcount = -1;
808 /* "target" is the node below which we want to be.
809 * Init "closest" to a value we can't reach. */
810 if (absolute)
812 target = step;
813 closest = -1;
815 else
817 /* When doing computations with time_t subtract starttime, because
818 * time_t converted to a long may result in a wrong number. */
819 if (sec)
820 target = (long)(curbuf->b_u_seq_time - starttime) + step;
821 else
822 target = curbuf->b_u_seq_cur + step;
823 if (step < 0)
825 if (target < 0)
826 target = 0;
827 closest = -1;
829 else
831 if (sec)
832 closest = (long)(time(NULL) - starttime + 1);
833 else
834 closest = curbuf->b_u_seq_last + 2;
835 if (target >= closest)
836 target = closest - 1;
839 closest_start = closest;
840 closest_seq = curbuf->b_u_seq_cur;
843 * May do this twice:
844 * 1. Search for "target", update "closest" to the best match found.
845 * 2. If "target" not found search for "closest".
847 * When using the closest time we use the sequence number in the second
848 * round, because there may be several entries with the same time.
850 for (round = 1; round <= 2; ++round)
852 /* Find the path from the current state to where we want to go. The
853 * desired state can be anywhere in the undo tree, need to go all over
854 * it. We put "nomark" in uh_walk where we have been without success,
855 * "mark" where it could possibly be. */
856 mark = ++lastmark;
857 nomark = ++lastmark;
859 if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */
860 uhp = curbuf->b_u_newhead;
861 else
862 uhp = curbuf->b_u_curhead;
864 while (uhp != NULL)
866 uhp->uh_walk = mark;
867 val = (long)(dosec ? (uhp->uh_time - starttime) : uhp->uh_seq);
869 if (round == 1)
871 /* Remember the header that is closest to the target.
872 * It must be at least in the right direction (checked with
873 * "b_u_seq_cur"). When the timestamp is equal find the
874 * highest/lowest sequence number. */
875 if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur
876 : uhp->uh_seq > curbuf->b_u_seq_cur)
877 && ((dosec && val == closest)
878 ? (step < 0
879 ? uhp->uh_seq < closest_seq
880 : uhp->uh_seq > closest_seq)
881 : closest == closest_start
882 || (val > target
883 ? (closest > target
884 ? val - target <= closest - target
885 : val - target <= target - closest)
886 : (closest > target
887 ? target - val <= closest - target
888 : target - val <= target - closest))))
890 closest = val;
891 closest_seq = uhp->uh_seq;
895 /* Quit searching when we found a match. But when searching for a
896 * time we need to continue looking for the best uh_seq. */
897 if (target == val && !dosec)
898 break;
900 /* go down in the tree if we haven't been there */
901 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != nomark
902 && uhp->uh_prev->uh_walk != mark)
903 uhp = uhp->uh_prev;
905 /* go to alternate branch if we haven't been there */
906 else if (uhp->uh_alt_next != NULL
907 && uhp->uh_alt_next->uh_walk != nomark
908 && uhp->uh_alt_next->uh_walk != mark)
909 uhp = uhp->uh_alt_next;
911 /* go up in the tree if we haven't been there and we are at the
912 * start of alternate branches */
913 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
914 && uhp->uh_next->uh_walk != nomark
915 && uhp->uh_next->uh_walk != mark)
917 /* If still at the start we don't go through this change. */
918 if (uhp == curbuf->b_u_curhead)
919 uhp->uh_walk = nomark;
920 uhp = uhp->uh_next;
923 else
925 /* need to backtrack; mark this node as useless */
926 uhp->uh_walk = nomark;
927 if (uhp->uh_alt_prev != NULL)
928 uhp = uhp->uh_alt_prev;
929 else
930 uhp = uhp->uh_next;
934 if (uhp != NULL) /* found it */
935 break;
937 if (absolute)
939 EMSGN(_("Undo number %ld not found"), step);
940 return;
943 if (closest == closest_start)
945 if (step < 0)
946 MSG(_("Already at oldest change"));
947 else
948 MSG(_("Already at newest change"));
949 return;
952 target = closest_seq;
953 dosec = FALSE;
954 if (step < 0)
955 above = TRUE; /* stop above the header */
958 /* If we found it: Follow the path to go to where we want to be. */
959 if (uhp != NULL)
962 * First go up the tree as much as needed.
964 while (!got_int)
966 /* Do the change warning now, for the same reason as above. */
967 change_warning(0);
969 uhp = curbuf->b_u_curhead;
970 if (uhp == NULL)
971 uhp = curbuf->b_u_newhead;
972 else
973 uhp = uhp->uh_next;
974 if (uhp == NULL || uhp->uh_walk != mark
975 || (uhp->uh_seq == target && !above))
976 break;
977 curbuf->b_u_curhead = uhp;
978 u_undoredo(TRUE);
979 uhp->uh_walk = nomark; /* don't go back down here */
983 * And now go down the tree (redo), branching off where needed.
985 while (!got_int)
987 /* Do the change warning now, for the same reason as above. */
988 change_warning(0);
990 uhp = curbuf->b_u_curhead;
991 if (uhp == NULL)
992 break;
994 /* Go back to the first branch with a mark. */
995 while (uhp->uh_alt_prev != NULL
996 && uhp->uh_alt_prev->uh_walk == mark)
997 uhp = uhp->uh_alt_prev;
999 /* Find the last branch with a mark, that's the one. */
1000 last = uhp;
1001 while (last->uh_alt_next != NULL
1002 && last->uh_alt_next->uh_walk == mark)
1003 last = last->uh_alt_next;
1004 if (last != uhp)
1006 /* Make the used branch the first entry in the list of
1007 * alternatives to make "u" and CTRL-R take this branch. */
1008 while (uhp->uh_alt_prev != NULL)
1009 uhp = uhp->uh_alt_prev;
1010 if (last->uh_alt_next != NULL)
1011 last->uh_alt_next->uh_alt_prev = last->uh_alt_prev;
1012 last->uh_alt_prev->uh_alt_next = last->uh_alt_next;
1013 last->uh_alt_prev = NULL;
1014 last->uh_alt_next = uhp;
1015 uhp->uh_alt_prev = last;
1017 if (curbuf->b_u_oldhead == uhp)
1018 curbuf->b_u_oldhead = last;
1019 uhp = last;
1020 if (uhp->uh_next != NULL)
1021 uhp->uh_next->uh_prev = uhp;
1023 curbuf->b_u_curhead = uhp;
1025 if (uhp->uh_walk != mark)
1026 break; /* must have reached the target */
1028 /* Stop when going backwards in time and didn't find the exact
1029 * header we were looking for. */
1030 if (uhp->uh_seq == target && above)
1032 curbuf->b_u_seq_cur = target - 1;
1033 break;
1036 u_undoredo(FALSE);
1038 /* Advance "curhead" to below the header we last used. If it
1039 * becomes NULL then we need to set "newhead" to this leaf. */
1040 if (uhp->uh_prev == NULL)
1041 curbuf->b_u_newhead = uhp;
1042 curbuf->b_u_curhead = uhp->uh_prev;
1043 did_undo = FALSE;
1045 if (uhp->uh_seq == target) /* found it! */
1046 break;
1048 uhp = uhp->uh_prev;
1049 if (uhp == NULL || uhp->uh_walk != mark)
1051 /* Need to redo more but can't find it... */
1052 EMSG2(_(e_intern2), "undo_time()");
1053 break;
1057 u_undo_end(did_undo, absolute);
1061 * u_undoredo: common code for undo and redo
1063 * The lines in the file are replaced by the lines in the entry list at
1064 * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry
1065 * list for the next undo/redo.
1067 * When "undo" is TRUE we go up in the tree, when FALSE we go down.
1069 static void
1070 u_undoredo(undo)
1071 int undo;
1073 char_u **newarray = NULL;
1074 linenr_T oldsize;
1075 linenr_T newsize;
1076 linenr_T top, bot;
1077 linenr_T lnum;
1078 linenr_T newlnum = MAXLNUM;
1079 long i;
1080 u_entry_T *uep, *nuep;
1081 u_entry_T *newlist = NULL;
1082 int old_flags;
1083 int new_flags;
1084 pos_T namedm[NMARKS];
1085 #ifdef FEAT_VISUAL
1086 visualinfo_T visualinfo;
1087 #endif
1088 int empty_buffer; /* buffer became empty */
1089 u_header_T *curhead = curbuf->b_u_curhead;
1091 #ifdef FEAT_AUTOCMD
1092 /* Don't want autocommands using the undo structures here, they are
1093 * invalid till the end. */
1094 block_autocmds();
1095 #endif
1097 #ifdef U_DEBUG
1098 u_check(FALSE);
1099 #endif
1100 old_flags = curhead->uh_flags;
1101 new_flags = (curbuf->b_changed ? UH_CHANGED : 0) +
1102 ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0);
1103 setpcmark();
1106 * save marks before undo/redo
1108 mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS);
1109 #ifdef FEAT_VISUAL
1110 visualinfo = curbuf->b_visual;
1111 #endif
1112 curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count;
1113 curbuf->b_op_start.col = 0;
1114 curbuf->b_op_end.lnum = 0;
1115 curbuf->b_op_end.col = 0;
1117 for (uep = curhead->uh_entry; uep != NULL; uep = nuep)
1119 top = uep->ue_top;
1120 bot = uep->ue_bot;
1121 if (bot == 0)
1122 bot = curbuf->b_ml.ml_line_count + 1;
1123 if (top > curbuf->b_ml.ml_line_count || top >= bot
1124 || bot > curbuf->b_ml.ml_line_count + 1)
1126 #ifdef FEAT_AUTOCMD
1127 unblock_autocmds();
1128 #endif
1129 EMSG(_("E438: u_undo: line numbers wrong"));
1130 changed(); /* don't want UNCHANGED now */
1131 return;
1134 oldsize = bot - top - 1; /* number of lines before undo */
1135 newsize = uep->ue_size; /* number of lines after undo */
1137 if (top < newlnum)
1139 /* If the saved cursor is somewhere in this undo block, move it to
1140 * the remembered position. Makes "gwap" put the cursor back
1141 * where it was. */
1142 lnum = curhead->uh_cursor.lnum;
1143 if (lnum >= top && lnum <= top + newsize + 1)
1145 curwin->w_cursor = curhead->uh_cursor;
1146 newlnum = curwin->w_cursor.lnum - 1;
1148 else
1150 /* Use the first line that actually changed. Avoids that
1151 * undoing auto-formatting puts the cursor in the previous
1152 * line. */
1153 for (i = 0; i < newsize && i < oldsize; ++i)
1154 if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0)
1155 break;
1156 if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL)
1158 newlnum = top;
1159 curwin->w_cursor.lnum = newlnum + 1;
1161 else if (i < newsize)
1163 newlnum = top + i;
1164 curwin->w_cursor.lnum = newlnum + 1;
1169 empty_buffer = FALSE;
1171 /* delete the lines between top and bot and save them in newarray */
1172 if (oldsize > 0)
1174 if ((newarray = (char_u **)U_ALLOC_LINE(
1175 (unsigned)(sizeof(char_u *) * oldsize))) == NULL)
1177 do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize));
1179 * We have messed up the entry list, repair is impossible.
1180 * we have to free the rest of the list.
1182 while (uep != NULL)
1184 nuep = uep->ue_next;
1185 u_freeentry(uep, uep->ue_size);
1186 uep = nuep;
1188 break;
1190 /* delete backwards, it goes faster in most cases */
1191 for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum)
1193 /* what can we do when we run out of memory? */
1194 if ((newarray[i] = u_save_line(lnum)) == NULL)
1195 do_outofmem_msg((long_u)0);
1196 /* remember we deleted the last line in the buffer, and a
1197 * dummy empty line will be inserted */
1198 if (curbuf->b_ml.ml_line_count == 1)
1199 empty_buffer = TRUE;
1200 ml_delete(lnum, FALSE);
1203 else
1204 newarray = NULL;
1206 /* insert the lines in u_array between top and bot */
1207 if (newsize)
1209 for (lnum = top, i = 0; i < newsize; ++i, ++lnum)
1212 * If the file is empty, there is an empty line 1 that we
1213 * should get rid of, by replacing it with the new line
1215 if (empty_buffer && lnum == 0)
1216 ml_replace((linenr_T)1, uep->ue_array[i], TRUE);
1217 else
1218 ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE);
1219 U_FREE_LINE(uep->ue_array[i]);
1221 U_FREE_LINE((char_u *)uep->ue_array);
1224 /* adjust marks */
1225 if (oldsize != newsize)
1227 mark_adjust(top + 1, top + oldsize, (long)MAXLNUM,
1228 (long)newsize - (long)oldsize);
1229 if (curbuf->b_op_start.lnum > top + oldsize)
1230 curbuf->b_op_start.lnum += newsize - oldsize;
1231 if (curbuf->b_op_end.lnum > top + oldsize)
1232 curbuf->b_op_end.lnum += newsize - oldsize;
1235 changed_lines(top + 1, 0, bot, newsize - oldsize);
1237 /* set '[ and '] mark */
1238 if (top + 1 < curbuf->b_op_start.lnum)
1239 curbuf->b_op_start.lnum = top + 1;
1240 if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum)
1241 curbuf->b_op_end.lnum = top + 1;
1242 else if (top + newsize > curbuf->b_op_end.lnum)
1243 curbuf->b_op_end.lnum = top + newsize;
1245 u_newcount += newsize;
1246 u_oldcount += oldsize;
1247 uep->ue_size = oldsize;
1248 uep->ue_array = newarray;
1249 uep->ue_bot = top + newsize + 1;
1252 * insert this entry in front of the new entry list
1254 nuep = uep->ue_next;
1255 uep->ue_next = newlist;
1256 newlist = uep;
1259 curhead->uh_entry = newlist;
1260 curhead->uh_flags = new_flags;
1261 if ((old_flags & UH_EMPTYBUF) && bufempty())
1262 curbuf->b_ml.ml_flags |= ML_EMPTY;
1263 if (old_flags & UH_CHANGED)
1264 changed();
1265 else
1266 #ifdef FEAT_NETBEANS_INTG
1267 /* per netbeans undo rules, keep it as modified */
1268 if (!isNetbeansModified(curbuf))
1269 #endif
1270 unchanged(curbuf, FALSE);
1273 * restore marks from before undo/redo
1275 for (i = 0; i < NMARKS; ++i)
1276 if (curhead->uh_namedm[i].lnum != 0)
1278 curbuf->b_namedm[i] = curhead->uh_namedm[i];
1279 curhead->uh_namedm[i] = namedm[i];
1281 #ifdef FEAT_VISUAL
1282 if (curhead->uh_visual.vi_start.lnum != 0)
1284 curbuf->b_visual = curhead->uh_visual;
1285 curhead->uh_visual = visualinfo;
1287 #endif
1290 * If the cursor is only off by one line, put it at the same position as
1291 * before starting the change (for the "o" command).
1292 * Otherwise the cursor should go to the first undone line.
1294 if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum
1295 && curwin->w_cursor.lnum > 1)
1296 --curwin->w_cursor.lnum;
1297 if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum)
1299 curwin->w_cursor.col = curhead->uh_cursor.col;
1300 #ifdef FEAT_VIRTUALEDIT
1301 if (virtual_active() && curhead->uh_cursor_vcol >= 0)
1302 coladvance((colnr_T)curhead->uh_cursor_vcol);
1303 else
1304 curwin->w_cursor.coladd = 0;
1305 #endif
1307 else if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count)
1308 beginline(BL_SOL | BL_FIX);
1309 else
1311 /* We get here with the current cursor line being past the end (eg
1312 * after adding lines at the end of the file, and then undoing it).
1313 * check_cursor() will move the cursor to the last line. Move it to
1314 * the first column here. */
1315 curwin->w_cursor.col = 0;
1316 #ifdef FEAT_VIRTUALEDIT
1317 curwin->w_cursor.coladd = 0;
1318 #endif
1321 /* Make sure the cursor is on an existing line and column. */
1322 check_cursor();
1324 /* Remember where we are for "g-" and ":earlier 10s". */
1325 curbuf->b_u_seq_cur = curhead->uh_seq;
1326 if (undo)
1327 /* We are below the previous undo. However, to make ":earlier 1s"
1328 * work we compute this as being just above the just undone change. */
1329 --curbuf->b_u_seq_cur;
1331 /* The timestamp can be the same for multiple changes, just use the one of
1332 * the undone/redone change. */
1333 curbuf->b_u_seq_time = curhead->uh_time;
1335 #ifdef FEAT_AUTOCMD
1336 unblock_autocmds();
1337 #endif
1338 #ifdef U_DEBUG
1339 u_check(FALSE);
1340 #endif
1344 * If we deleted or added lines, report the number of less/more lines.
1345 * Otherwise, report the number of changes (this may be incorrect
1346 * in some cases, but it's better than nothing).
1348 static void
1349 u_undo_end(did_undo, absolute)
1350 int did_undo; /* just did an undo */
1351 int absolute; /* used ":undo N" */
1353 char *msgstr;
1354 u_header_T *uhp;
1355 char_u msgbuf[80];
1357 #ifdef FEAT_FOLDING
1358 if ((fdo_flags & FDO_UNDO) && KeyTyped)
1359 foldOpenCursor();
1360 #endif
1362 if (global_busy /* no messages now, wait until global is finished */
1363 || !messaging()) /* 'lazyredraw' set, don't do messages now */
1364 return;
1366 if (curbuf->b_ml.ml_flags & ML_EMPTY)
1367 --u_newcount;
1369 u_oldcount -= u_newcount;
1370 if (u_oldcount == -1)
1371 msgstr = N_("more line");
1372 else if (u_oldcount < 0)
1373 msgstr = N_("more lines");
1374 else if (u_oldcount == 1)
1375 msgstr = N_("line less");
1376 else if (u_oldcount > 1)
1377 msgstr = N_("fewer lines");
1378 else
1380 u_oldcount = u_newcount;
1381 if (u_newcount == 1)
1382 msgstr = N_("change");
1383 else
1384 msgstr = N_("changes");
1387 if (curbuf->b_u_curhead != NULL)
1389 /* For ":undo N" we prefer a "after #N" message. */
1390 if (absolute && curbuf->b_u_curhead->uh_next != NULL)
1392 uhp = curbuf->b_u_curhead->uh_next;
1393 did_undo = FALSE;
1395 else if (did_undo)
1396 uhp = curbuf->b_u_curhead;
1397 else
1398 uhp = curbuf->b_u_curhead->uh_next;
1400 else
1401 uhp = curbuf->b_u_newhead;
1403 if (uhp == NULL)
1404 *msgbuf = NUL;
1405 else
1406 u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time);
1408 smsg((char_u *)_("%ld %s; %s #%ld %s"),
1409 u_oldcount < 0 ? -u_oldcount : u_oldcount,
1410 _(msgstr),
1411 did_undo ? _("before") : _("after"),
1412 uhp == NULL ? 0L : uhp->uh_seq,
1413 msgbuf);
1417 * u_sync: stop adding to the current entry list
1419 void
1420 u_sync(force)
1421 int force; /* Also sync when no_u_sync is set. */
1423 /* Skip it when already synced or syncing is disabled. */
1424 if (curbuf->b_u_synced || (!force && no_u_sync > 0))
1425 return;
1426 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
1427 if (im_is_preediting())
1428 return; /* XIM is busy, don't break an undo sequence */
1429 #endif
1430 if (p_ul < 0)
1431 curbuf->b_u_synced = TRUE; /* no entries, nothing to do */
1432 else
1434 u_getbot(); /* compute ue_bot of previous u_save */
1435 curbuf->b_u_curhead = NULL;
1440 * ":undolist": List the leafs of the undo tree
1442 void
1443 ex_undolist(eap)
1444 exarg_T *eap UNUSED;
1446 garray_T ga;
1447 u_header_T *uhp;
1448 int mark;
1449 int nomark;
1450 int changes = 1;
1451 int i;
1454 * 1: walk the tree to find all leafs, put the info in "ga".
1455 * 2: sort the lines
1456 * 3: display the list
1458 mark = ++lastmark;
1459 nomark = ++lastmark;
1460 ga_init2(&ga, (int)sizeof(char *), 20);
1462 uhp = curbuf->b_u_oldhead;
1463 while (uhp != NULL)
1465 if (uhp->uh_prev == NULL && uhp->uh_walk != nomark
1466 && uhp->uh_walk != mark)
1468 if (ga_grow(&ga, 1) == FAIL)
1469 break;
1470 vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ",
1471 uhp->uh_seq, changes);
1472 u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff),
1473 uhp->uh_time);
1474 ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff);
1477 uhp->uh_walk = mark;
1479 /* go down in the tree if we haven't been there */
1480 if (uhp->uh_prev != NULL && uhp->uh_prev->uh_walk != nomark
1481 && uhp->uh_prev->uh_walk != mark)
1483 uhp = uhp->uh_prev;
1484 ++changes;
1487 /* go to alternate branch if we haven't been there */
1488 else if (uhp->uh_alt_next != NULL
1489 && uhp->uh_alt_next->uh_walk != nomark
1490 && uhp->uh_alt_next->uh_walk != mark)
1491 uhp = uhp->uh_alt_next;
1493 /* go up in the tree if we haven't been there and we are at the
1494 * start of alternate branches */
1495 else if (uhp->uh_next != NULL && uhp->uh_alt_prev == NULL
1496 && uhp->uh_next->uh_walk != nomark
1497 && uhp->uh_next->uh_walk != mark)
1499 uhp = uhp->uh_next;
1500 --changes;
1503 else
1505 /* need to backtrack; mark this node as done */
1506 uhp->uh_walk = nomark;
1507 if (uhp->uh_alt_prev != NULL)
1508 uhp = uhp->uh_alt_prev;
1509 else
1511 uhp = uhp->uh_next;
1512 --changes;
1517 if (ga.ga_len == 0)
1518 MSG(_("Nothing to undo"));
1519 else
1521 sort_strings((char_u **)ga.ga_data, ga.ga_len);
1523 msg_start();
1524 msg_puts_attr((char_u *)_("number changes time"), hl_attr(HLF_T));
1525 for (i = 0; i < ga.ga_len && !got_int; ++i)
1527 msg_putchar('\n');
1528 if (got_int)
1529 break;
1530 msg_puts(((char_u **)ga.ga_data)[i]);
1532 msg_end();
1534 ga_clear_strings(&ga);
1539 * Put the timestamp of an undo header in "buf[buflen]" in a nice format.
1541 static void
1542 u_add_time(buf, buflen, tt)
1543 char_u *buf;
1544 size_t buflen;
1545 time_t tt;
1547 #ifdef HAVE_STRFTIME
1548 struct tm *curtime;
1550 if (time(NULL) - tt >= 100)
1552 curtime = localtime(&tt);
1553 (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime);
1555 else
1556 #endif
1557 vim_snprintf((char *)buf, buflen, _("%ld seconds ago"),
1558 (long)(time(NULL) - tt));
1562 * ":undojoin": continue adding to the last entry list
1564 void
1565 ex_undojoin(eap)
1566 exarg_T *eap UNUSED;
1568 if (curbuf->b_u_newhead == NULL)
1569 return; /* nothing changed before */
1570 if (curbuf->b_u_curhead != NULL)
1572 EMSG(_("E790: undojoin is not allowed after undo"));
1573 return;
1575 if (!curbuf->b_u_synced)
1576 return; /* already unsynced */
1577 if (p_ul < 0)
1578 return; /* no entries, nothing to do */
1579 else
1581 /* Go back to the last entry */
1582 curbuf->b_u_curhead = curbuf->b_u_newhead;
1583 curbuf->b_u_synced = FALSE; /* no entries, nothing to do */
1588 * Called after writing the file and setting b_changed to FALSE.
1589 * Now an undo means that the buffer is modified.
1591 void
1592 u_unchanged(buf)
1593 buf_T *buf;
1595 u_unch_branch(buf->b_u_oldhead);
1596 buf->b_did_warn = FALSE;
1599 static void
1600 u_unch_branch(uhp)
1601 u_header_T *uhp;
1603 u_header_T *uh;
1605 for (uh = uhp; uh != NULL; uh = uh->uh_prev)
1607 uh->uh_flags |= UH_CHANGED;
1608 if (uh->uh_alt_next != NULL)
1609 u_unch_branch(uh->uh_alt_next); /* recursive */
1614 * Get pointer to last added entry.
1615 * If it's not valid, give an error message and return NULL.
1617 static u_entry_T *
1618 u_get_headentry()
1620 if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL)
1622 EMSG(_("E439: undo list corrupt"));
1623 return NULL;
1625 return curbuf->b_u_newhead->uh_entry;
1629 * u_getbot(): compute the line number of the previous u_save
1630 * It is called only when b_u_synced is FALSE.
1632 static void
1633 u_getbot()
1635 u_entry_T *uep;
1636 linenr_T extra;
1638 uep = u_get_headentry(); /* check for corrupt undo list */
1639 if (uep == NULL)
1640 return;
1642 uep = curbuf->b_u_newhead->uh_getbot_entry;
1643 if (uep != NULL)
1646 * the new ue_bot is computed from the number of lines that has been
1647 * inserted (0 - deleted) since calling u_save. This is equal to the
1648 * old line count subtracted from the current line count.
1650 extra = curbuf->b_ml.ml_line_count - uep->ue_lcount;
1651 uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra;
1652 if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count)
1654 EMSG(_("E440: undo line missing"));
1655 uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will
1656 * get all the old lines back
1657 * without deleting the current
1658 * ones */
1661 curbuf->b_u_newhead->uh_getbot_entry = NULL;
1664 curbuf->b_u_synced = TRUE;
1668 * Free one header "uhp" and its entry list and adjust the pointers.
1670 static void
1671 u_freeheader(buf, uhp, uhpp)
1672 buf_T *buf;
1673 u_header_T *uhp;
1674 u_header_T **uhpp; /* if not NULL reset when freeing this header */
1676 u_header_T *uhap;
1678 /* When there is an alternate redo list free that branch completely,
1679 * because we can never go there. */
1680 if (uhp->uh_alt_next != NULL)
1681 u_freebranch(buf, uhp->uh_alt_next, uhpp);
1683 if (uhp->uh_alt_prev != NULL)
1684 uhp->uh_alt_prev->uh_alt_next = NULL;
1686 /* Update the links in the list to remove the header. */
1687 if (uhp->uh_next == NULL)
1688 buf->b_u_oldhead = uhp->uh_prev;
1689 else
1690 uhp->uh_next->uh_prev = uhp->uh_prev;
1692 if (uhp->uh_prev == NULL)
1693 buf->b_u_newhead = uhp->uh_next;
1694 else
1695 for (uhap = uhp->uh_prev; uhap != NULL; uhap = uhap->uh_alt_next)
1696 uhap->uh_next = uhp->uh_next;
1698 u_freeentries(buf, uhp, uhpp);
1702 * Free an alternate branch and any following alternate branches.
1704 static void
1705 u_freebranch(buf, uhp, uhpp)
1706 buf_T *buf;
1707 u_header_T *uhp;
1708 u_header_T **uhpp; /* if not NULL reset when freeing this header */
1710 u_header_T *tofree, *next;
1712 /* If this is the top branch we may need to use u_freeheader() to update
1713 * all the pointers. */
1714 if (uhp == buf->b_u_oldhead)
1716 u_freeheader(buf, uhp, uhpp);
1717 return;
1720 if (uhp->uh_alt_prev != NULL)
1721 uhp->uh_alt_prev->uh_alt_next = NULL;
1723 next = uhp;
1724 while (next != NULL)
1726 tofree = next;
1727 if (tofree->uh_alt_next != NULL)
1728 u_freebranch(buf, tofree->uh_alt_next, uhpp); /* recursive */
1729 next = tofree->uh_prev;
1730 u_freeentries(buf, tofree, uhpp);
1735 * Free all the undo entries for one header and the header itself.
1736 * This means that "uhp" is invalid when returning.
1738 static void
1739 u_freeentries(buf, uhp, uhpp)
1740 buf_T *buf;
1741 u_header_T *uhp;
1742 u_header_T **uhpp; /* if not NULL reset when freeing this header */
1744 u_entry_T *uep, *nuep;
1746 /* Check for pointers to the header that become invalid now. */
1747 if (buf->b_u_curhead == uhp)
1748 buf->b_u_curhead = NULL;
1749 if (buf->b_u_newhead == uhp)
1750 buf->b_u_newhead = NULL; /* freeing the newest entry */
1751 if (uhpp != NULL && uhp == *uhpp)
1752 *uhpp = NULL;
1754 for (uep = uhp->uh_entry; uep != NULL; uep = nuep)
1756 nuep = uep->ue_next;
1757 u_freeentry(uep, uep->ue_size);
1760 #ifdef U_DEBUG
1761 uhp->uh_magic = 0;
1762 #endif
1763 U_FREE_LINE((char_u *)uhp);
1764 --buf->b_u_numhead;
1768 * free entry 'uep' and 'n' lines in uep->ue_array[]
1770 static void
1771 u_freeentry(uep, n)
1772 u_entry_T *uep;
1773 long n;
1775 while (n > 0)
1776 U_FREE_LINE(uep->ue_array[--n]);
1777 U_FREE_LINE((char_u *)uep->ue_array);
1778 #ifdef U_DEBUG
1779 uep->ue_magic = 0;
1780 #endif
1781 U_FREE_LINE((char_u *)uep);
1785 * invalidate the undo buffer; called when storage has already been released
1787 void
1788 u_clearall(buf)
1789 buf_T *buf;
1791 buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL;
1792 buf->b_u_synced = TRUE;
1793 buf->b_u_numhead = 0;
1794 buf->b_u_line_ptr = NULL;
1795 buf->b_u_line_lnum = 0;
1799 * save the line "lnum" for the "U" command
1801 void
1802 u_saveline(lnum)
1803 linenr_T lnum;
1805 if (lnum == curbuf->b_u_line_lnum) /* line is already saved */
1806 return;
1807 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */
1808 return;
1809 u_clearline();
1810 curbuf->b_u_line_lnum = lnum;
1811 if (curwin->w_cursor.lnum == lnum)
1812 curbuf->b_u_line_colnr = curwin->w_cursor.col;
1813 else
1814 curbuf->b_u_line_colnr = 0;
1815 if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL)
1816 do_outofmem_msg((long_u)0);
1820 * clear the line saved for the "U" command
1821 * (this is used externally for crossing a line while in insert mode)
1823 void
1824 u_clearline()
1826 if (curbuf->b_u_line_ptr != NULL)
1828 U_FREE_LINE(curbuf->b_u_line_ptr);
1829 curbuf->b_u_line_ptr = NULL;
1830 curbuf->b_u_line_lnum = 0;
1835 * Implementation of the "U" command.
1836 * Differentiation from vi: "U" can be undone with the next "U".
1837 * We also allow the cursor to be in another line.
1839 void
1840 u_undoline()
1842 colnr_T t;
1843 char_u *oldp;
1845 if (undo_off)
1846 return;
1848 if (curbuf->b_u_line_ptr == NULL
1849 || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count)
1851 beep_flush();
1852 return;
1855 /* first save the line for the 'u' command */
1856 if (u_savecommon(curbuf->b_u_line_lnum - 1,
1857 curbuf->b_u_line_lnum + 1, (linenr_T)0) == FAIL)
1858 return;
1859 oldp = u_save_line(curbuf->b_u_line_lnum);
1860 if (oldp == NULL)
1862 do_outofmem_msg((long_u)0);
1863 return;
1865 ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE);
1866 changed_bytes(curbuf->b_u_line_lnum, 0);
1867 U_FREE_LINE(curbuf->b_u_line_ptr);
1868 curbuf->b_u_line_ptr = oldp;
1870 t = curbuf->b_u_line_colnr;
1871 if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum)
1872 curbuf->b_u_line_colnr = curwin->w_cursor.col;
1873 curwin->w_cursor.col = t;
1874 curwin->w_cursor.lnum = curbuf->b_u_line_lnum;
1875 check_cursor_col();
1879 * There are two implementations of the memory management for undo:
1880 * 1. Use the standard malloc()/free() functions.
1881 * This should be fast for allocating memory, but when a buffer is
1882 * abandoned every single allocated chunk must be freed, which may be slow.
1883 * 2. Allocate larger blocks of memory and keep track of chunks ourselves.
1884 * This is fast for abandoning, but the use of linked lists is slow for
1885 * finding a free chunk. Esp. when a lot of lines are changed or deleted.
1886 * A bit of profiling showed that the first method is faster, especially when
1887 * making a large number of changes, under the condition that malloc()/free()
1888 * is implemented efficiently.
1890 #ifdef U_USE_MALLOC
1892 * Version of undo memory allocation using malloc()/free()
1894 * U_FREE_LINE() and U_ALLOC_LINE() are macros that invoke vim_free() and
1895 * lalloc() directly.
1899 * Free all allocated memory blocks for the buffer 'buf'.
1901 void
1902 u_blockfree(buf)
1903 buf_T *buf;
1905 while (buf->b_u_oldhead != NULL)
1906 u_freeheader(buf, buf->b_u_oldhead, NULL);
1907 U_FREE_LINE(buf->b_u_line_ptr);
1910 #else
1912 * Storage allocation for the undo lines and blocks of the current file.
1913 * Version where Vim keeps track of the available memory.
1917 * Memory is allocated in relatively large blocks. These blocks are linked
1918 * in the allocated block list, headed by curbuf->b_block_head. They are all
1919 * freed when abandoning a file, so we don't have to free every single line.
1920 * The list is kept sorted on memory address.
1921 * block_alloc() allocates a block.
1922 * m_blockfree() frees all blocks.
1924 * The available chunks of memory are kept in free chunk lists. There is
1925 * one free list for each block of allocated memory. The list is kept sorted
1926 * on memory address.
1927 * u_alloc_line() gets a chunk from the free lists.
1928 * u_free_line() returns a chunk to the free lists.
1929 * curbuf->b_m_search points to the chunk before the chunk that was
1930 * freed/allocated the last time.
1931 * curbuf->b_mb_current points to the b_head where curbuf->b_m_search
1932 * points into the free list.
1935 * b_block_head /---> block #1 /---> block #2
1936 * mb_next ---/ mb_next ---/ mb_next ---> NULL
1937 * mb_info mb_info mb_info
1938 * | | |
1939 * V V V
1940 * NULL free chunk #1.1 free chunk #2.1
1941 * | |
1942 * V V
1943 * free chunk #1.2 NULL
1946 * NULL
1948 * When a single free chunk list would have been used, it could take a lot
1949 * of time in u_free_line() to find the correct place to insert a chunk in the
1950 * free list. The single free list would become very long when many lines are
1951 * changed (e.g. with :%s/^M$//).
1955 * this blocksize is used when allocating new lines
1957 #define MEMBLOCKSIZE 2044
1960 * The size field contains the size of the chunk, including the size field
1961 * itself.
1963 * When the chunk is not in-use it is preceded with the m_info structure.
1964 * The m_next field links it in one of the free chunk lists.
1966 * On most unix systems structures have to be longword (32 or 64 bit) aligned.
1967 * On most other systems they are short (16 bit) aligned.
1970 /* the structure definitions are now in structs.h */
1972 #ifdef ALIGN_LONG
1973 /* size of m_size */
1974 # define M_OFFSET (sizeof(long_u))
1975 #else
1976 /* size of m_size */
1977 # define M_OFFSET (sizeof(short_u))
1978 #endif
1980 static char_u *u_blockalloc __ARGS((long_u));
1983 * Allocate a block of memory and link it in the allocated block list.
1985 static char_u *
1986 u_blockalloc(size)
1987 long_u size;
1989 mblock_T *p;
1990 mblock_T *mp, *next;
1992 p = (mblock_T *)lalloc(size + sizeof(mblock_T), FALSE);
1993 if (p != NULL)
1995 /* Insert the block into the allocated block list, keeping it
1996 sorted on address. */
1997 for (mp = &curbuf->b_block_head;
1998 (next = mp->mb_next) != NULL && next < p;
1999 mp = next)
2001 p->mb_next = next; /* link in block list */
2002 p->mb_size = size;
2003 p->mb_maxsize = 0; /* nothing free yet */
2004 mp->mb_next = p;
2005 p->mb_info.m_next = NULL; /* clear free list */
2006 p->mb_info.m_size = 0;
2007 curbuf->b_mb_current = p; /* remember current block */
2008 curbuf->b_m_search = NULL;
2009 p++; /* return usable memory */
2011 return (char_u *)p;
2015 * free all allocated memory blocks for the buffer 'buf'
2017 void
2018 u_blockfree(buf)
2019 buf_T *buf;
2021 mblock_T *p, *np;
2023 for (p = buf->b_block_head.mb_next; p != NULL; p = np)
2025 np = p->mb_next;
2026 vim_free(p);
2028 buf->b_block_head.mb_next = NULL;
2029 buf->b_m_search = NULL;
2030 buf->b_mb_current = NULL;
2034 * Free a chunk of memory for the current buffer.
2035 * Insert the chunk into the correct free list, keeping it sorted on address.
2037 static void
2038 u_free_line(ptr, keep)
2039 char_u *ptr;
2040 int keep; /* don't free the block when it's empty */
2042 minfo_T *next;
2043 minfo_T *prev, *curr;
2044 minfo_T *mp;
2045 mblock_T *nextb;
2046 mblock_T *prevb;
2047 long_u maxsize;
2049 if (ptr == NULL || ptr == IObuff)
2050 return; /* illegal address can happen in out-of-memory situations */
2052 mp = (minfo_T *)(ptr - M_OFFSET);
2054 /* find block where chunk could be a part off */
2055 /* if we change curbuf->b_mb_current, curbuf->b_m_search is set to NULL */
2056 if (curbuf->b_mb_current == NULL || mp < (minfo_T *)curbuf->b_mb_current)
2058 curbuf->b_mb_current = curbuf->b_block_head.mb_next;
2059 curbuf->b_m_search = NULL;
2061 if ((nextb = curbuf->b_mb_current->mb_next) != NULL
2062 && (minfo_T *)nextb < mp)
2064 curbuf->b_mb_current = nextb;
2065 curbuf->b_m_search = NULL;
2067 while ((nextb = curbuf->b_mb_current->mb_next) != NULL
2068 && (minfo_T *)nextb < mp)
2069 curbuf->b_mb_current = nextb;
2071 curr = NULL;
2073 * If mp is smaller than curbuf->b_m_search->m_next go to the start of
2074 * the free list
2076 if (curbuf->b_m_search == NULL || mp < (curbuf->b_m_search->m_next))
2077 next = &(curbuf->b_mb_current->mb_info);
2078 else
2079 next = curbuf->b_m_search;
2081 * The following loop is executed very often.
2082 * Therefore it has been optimized at the cost of readability.
2083 * Keep it fast!
2085 #ifdef SLOW_BUT_EASY_TO_READ
2088 prev = curr;
2089 curr = next;
2090 next = next->m_next;
2092 while (mp > next && next != NULL);
2093 #else
2094 do /* first, middle, last */
2096 prev = next->m_next; /* curr, next, prev */
2097 if (prev == NULL || mp <= prev)
2099 prev = curr;
2100 curr = next;
2101 next = next->m_next;
2102 break;
2104 curr = prev->m_next; /* next, prev, curr */
2105 if (curr == NULL || mp <= curr)
2107 prev = next;
2108 curr = prev->m_next;
2109 next = curr->m_next;
2110 break;
2112 next = curr->m_next; /* prev, curr, next */
2114 while (mp > next && next != NULL);
2115 #endif
2117 /* if *mp and *next are concatenated, join them into one chunk */
2118 if ((char_u *)mp + mp->m_size == (char_u *)next)
2120 mp->m_size += next->m_size;
2121 mp->m_next = next->m_next;
2123 else
2124 mp->m_next = next;
2125 maxsize = mp->m_size;
2127 /* if *curr and *mp are concatenated, join them */
2128 if (prev != NULL && (char_u *)curr + curr->m_size == (char_u *)mp)
2130 curr->m_size += mp->m_size;
2131 maxsize = curr->m_size;
2132 curr->m_next = mp->m_next;
2133 curbuf->b_m_search = prev;
2135 else
2137 curr->m_next = mp;
2138 curbuf->b_m_search = curr; /* put curbuf->b_m_search before freed
2139 chunk */
2143 * If the block only contains free memory now, release it.
2145 if (!keep && curbuf->b_mb_current->mb_size
2146 == curbuf->b_mb_current->mb_info.m_next->m_size)
2148 /* Find the block before the current one to be able to unlink it from
2149 * the list of blocks. */
2150 prevb = &curbuf->b_block_head;
2151 for (nextb = prevb->mb_next; nextb != curbuf->b_mb_current;
2152 nextb = nextb->mb_next)
2153 prevb = nextb;
2154 prevb->mb_next = nextb->mb_next;
2155 vim_free(nextb);
2156 curbuf->b_mb_current = NULL;
2157 curbuf->b_m_search = NULL;
2159 else if (curbuf->b_mb_current->mb_maxsize < maxsize)
2160 curbuf->b_mb_current->mb_maxsize = maxsize;
2164 * Allocate and initialize a new line structure with room for at least
2165 * 'size' characters plus a terminating NUL.
2167 static char_u *
2168 u_alloc_line(size)
2169 unsigned size;
2171 minfo_T *mp, *mprev, *mp2;
2172 mblock_T *mbp;
2173 int size_align;
2176 * Add room for size field and trailing NUL byte.
2177 * Adjust for minimal size (must be able to store minfo_T
2178 * plus a trailing NUL, so the chunk can be released again)
2180 size += M_OFFSET + 1;
2181 if (size < sizeof(minfo_T) + 1)
2182 size = sizeof(minfo_T) + 1;
2185 * round size up for alignment
2187 size_align = (size + ALIGN_MASK) & ~ALIGN_MASK;
2190 * If curbuf->b_m_search is NULL (uninitialized free list) start at
2191 * curbuf->b_block_head
2193 if (curbuf->b_mb_current == NULL || curbuf->b_m_search == NULL)
2195 curbuf->b_mb_current = &curbuf->b_block_head;
2196 curbuf->b_m_search = &(curbuf->b_block_head.mb_info);
2199 /* Search for a block with enough space. */
2200 mbp = curbuf->b_mb_current;
2201 while (mbp->mb_maxsize < size_align)
2203 if (mbp->mb_next != NULL)
2204 mbp = mbp->mb_next;
2205 else
2206 mbp = &curbuf->b_block_head;
2207 if (mbp == curbuf->b_mb_current)
2209 int n = (size_align > (MEMBLOCKSIZE / 4)
2210 ? size_align : MEMBLOCKSIZE);
2212 /* Back where we started in block list: need to add a new block
2213 * with enough space. */
2214 mp = (minfo_T *)u_blockalloc((long_u)n);
2215 if (mp == NULL)
2216 return (NULL);
2217 mp->m_size = n;
2218 u_free_line((char_u *)mp + M_OFFSET, TRUE);
2219 mbp = curbuf->b_mb_current;
2220 break;
2223 if (mbp != curbuf->b_mb_current)
2224 curbuf->b_m_search = &(mbp->mb_info);
2226 /* In this block find a chunk with enough space. */
2227 mprev = curbuf->b_m_search;
2228 mp = curbuf->b_m_search->m_next;
2229 for (;;)
2231 if (mp == NULL) /* at end of the list */
2232 mp = &(mbp->mb_info); /* wrap around to begin */
2233 if (mp->m_size >= size)
2234 break;
2235 if (mp == curbuf->b_m_search)
2237 /* back where we started in free chunk list: "cannot happen" */
2238 EMSG2(_(e_intern2), "u_alloc_line()");
2239 return NULL;
2241 mprev = mp;
2242 mp = mp->m_next;
2245 /* when using the largest chunk adjust mb_maxsize */
2246 if (mp->m_size >= mbp->mb_maxsize)
2247 mbp->mb_maxsize = 0;
2249 /* if the chunk we found is large enough, split it up in two */
2250 if ((long)mp->m_size - size_align >= (long)(sizeof(minfo_T) + 1))
2252 mp2 = (minfo_T *)((char_u *)mp + size_align);
2253 mp2->m_size = mp->m_size - size_align;
2254 mp2->m_next = mp->m_next;
2255 mprev->m_next = mp2;
2256 mp->m_size = size_align;
2258 else /* remove *mp from the free list */
2260 mprev->m_next = mp->m_next;
2262 curbuf->b_m_search = mprev;
2263 curbuf->b_mb_current = mbp;
2265 /* If using the largest chunk need to find the new largest chunk */
2266 if (mbp->mb_maxsize == 0)
2267 for (mp2 = &(mbp->mb_info); mp2 != NULL; mp2 = mp2->m_next)
2268 if (mbp->mb_maxsize < mp2->m_size)
2269 mbp->mb_maxsize = mp2->m_size;
2271 mp = (minfo_T *)((char_u *)mp + M_OFFSET);
2272 *(char_u *)mp = NUL; /* set the first byte to NUL */
2274 return ((char_u *)mp);
2276 #endif
2279 * u_save_line(): allocate memory with u_alloc_line() and copy line 'lnum'
2280 * into it.
2282 static char_u *
2283 u_save_line(lnum)
2284 linenr_T lnum;
2286 char_u *src;
2287 char_u *dst;
2288 unsigned len;
2290 src = ml_get(lnum);
2291 len = (unsigned)STRLEN(src);
2292 if ((dst = U_ALLOC_LINE(len)) != NULL)
2293 mch_memmove(dst, src, (size_t)(len + 1));
2294 return (dst);
2298 * Check if the 'modified' flag is set, or 'ff' has changed (only need to
2299 * check the first character, because it can only be "dos", "unix" or "mac").
2300 * "nofile" and "scratch" type buffers are considered to always be unchanged.
2303 bufIsChanged(buf)
2304 buf_T *buf;
2306 return
2307 #ifdef FEAT_QUICKFIX
2308 !bt_dontwrite(buf) &&
2309 #endif
2310 (buf->b_changed || file_ff_differs(buf));
2314 curbufIsChanged()
2316 return
2317 #ifdef FEAT_QUICKFIX
2318 !bt_dontwrite(curbuf) &&
2319 #endif
2320 (curbuf->b_changed || file_ff_differs(curbuf));