robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

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