robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
143.6 KiB4306 linesraw
1// for debugging
2// #define CHECK(c, s) do { if (c) emsg(s); } while (0)
3#define CHECK(c, s) do {} while (0)
4
5// memline.c: Contains the functions for appending, deleting and changing the
6// text lines. The memfile functions are used to store the information in
7// blocks of memory, backed up by a file. The structure of the information is
8// a tree.  The root of the tree is a pointer block. The leaves of the tree
9// are data blocks. In between may be several layers of pointer blocks,
10// forming branches.
11//
12// Three types of blocks are used:
13// - Block nr 0 contains information for recovery
14// - Pointer blocks contain list of pointers to other blocks.
15// - Data blocks contain the actual text.
16//
17// Block nr 0 contains the block0 structure (see below).
18//
19// Block nr 1 is the first pointer block. It is the root of the tree.
20// Other pointer blocks are branches.
21//
22//  If a line is too big to fit in a single page, the block containing that
23//  line is made big enough to hold the line. It may span several pages.
24//  Otherwise all blocks are one page.
25//
26//  A data block that was filled when starting to edit a file and was not
27//  changed since then, can have a negative block number. This means that it
28//  has not yet been assigned a place in the file. When recovering, the lines
29//  in this data block can be read from the original file. When the block is
30//  changed (lines appended/deleted/changed) or when it is flushed it gets a
31//  positive number. Use mf_trans_del() to get the new number, before calling
32//  mf_get().
33//
34// "Mom, can we get ropes?"
35// "We have ropes at home."
36// Ropes at home:
37
38#include <assert.h>
39#include <errno.h>
40#include <fcntl.h>
41#include <inttypes.h>
42#include <stdbool.h>
43#include <stddef.h>
44#include <stdio.h>
45#include <string.h>
46#include <time.h>
47#include <uv.h>
48
49#include "auto/config.h"
50#include "klib/kvec.h"
51#include "nvim/ascii_defs.h"
52#include "nvim/autocmd.h"
53#include "nvim/autocmd_defs.h"
54#include "nvim/buffer.h"
55#include "nvim/buffer_defs.h"
56#include "nvim/change.h"
57#include "nvim/cursor.h"
58#include "nvim/dialog.h"
59#include "nvim/drawscreen.h"
60#include "nvim/eval/typval.h"
61#include "nvim/eval/vars.h"
62#include "nvim/ex_cmds_defs.h"
63#include "nvim/fileio.h"
64#include "nvim/gettext_defs.h"
65#include "nvim/globals.h"
66#include "nvim/highlight_defs.h"
67#include "nvim/input.h"
68#include "nvim/lua/executor.h"
69#include "nvim/macros_defs.h"
70#include "nvim/main.h"
71#include "nvim/map_defs.h"
72#include "nvim/mark.h"
73#include "nvim/mbyte.h"
74#include "nvim/memfile.h"
75#include "nvim/memfile_defs.h"
76#include "nvim/memline.h"
77#include "nvim/memory.h"
78#include "nvim/message.h"
79#include "nvim/option.h"
80#include "nvim/option_defs.h"
81#include "nvim/option_vars.h"
82#include "nvim/os/fs.h"
83#include "nvim/os/fs_defs.h"
84#include "nvim/os/input.h"
85#include "nvim/os/os.h"
86#include "nvim/os/os_defs.h"
87#include "nvim/os/proc.h"
88#include "nvim/os/time.h"
89#include "nvim/os/time_defs.h"
90#include "nvim/path.h"
91#include "nvim/pos_defs.h"
92#include "nvim/spell.h"
93#include "nvim/statusline.h"
94#include "nvim/strings.h"
95#include "nvim/ui.h"
96#include "nvim/undo.h"
97#include "nvim/version.h"
98#include "nvim/vim_defs.h"
99
100#ifndef UNIX            // it's in os/unix_defs.h for Unix
101# include <time.h>
102#endif
103
104enum {
105  DATA_ID = (('d' << 8) + 'a'),  // data block id
106  PTR_ID = (('p' << 8) + 't'),   // pointer block id
107  BLOCK0_ID0 = 'b',              // block 0 id 0
108  BLOCK0_ID1 = '0',              // block 0 id 1
109};
110
111// pointer to a block, used in a pointer block
112typedef struct {
113  blocknr_T pe_bnum;            // block number
114  linenr_T pe_line_count;       // number of lines in this branch
115  linenr_T pe_old_lnum;         // lnum for this block (for recovery)
116  int pe_page_count;            // number of pages in block pe_bnum
117} PointerEntry;
118
119// A pointer block contains a list of branches in the tree.
120typedef struct {
121  uint16_t pb_id;               // ID for pointer block: PTR_ID
122  uint16_t pb_count;            // number of pointers in this block
123  uint16_t pb_count_max;        // maximum value for pb_count
124  PointerEntry pb_pointer[];    // list of pointers to blocks
125                                // followed by empty space until end of page
126} PointerBlock;
127
128// Value for pb_count_max.
129#define PB_COUNT_MAX(mfp) \
130  (uint16_t)((mfp->mf_page_size - offsetof(PointerBlock, pb_pointer)) / sizeof(PointerEntry))
131
132// A data block is a leaf in the tree.
133//
134// The text of the lines is at the end of the block. The text of the first line
135// in the block is put at the end, the text of the second line in front of it,
136// etc. Thus the order of the lines is the opposite of the line number.
137typedef struct {
138  uint16_t db_id;               // ID for data block: DATA_ID
139  unsigned db_free;             // free space available
140  unsigned db_txt_start;        // byte where text starts
141  unsigned db_txt_end;          // byte just after data block
142  // linenr_T db_line_count;
143  long db_line_count;           // number of lines in this block
144  unsigned db_index[];          // index for start of line
145                                // followed by empty space up to db_txt_start
146                                // followed by the text in the lines until
147                                // end of page
148} DataBlock;
149
150// The low bits of db_index hold the actual index. The topmost bit is
151// used for the global command to be able to mark a line.
152// This method is not clean, but otherwise there would be at least one extra
153// byte used for each line.
154// The mark has to be in this place to keep it with the correct line when other
155// lines are inserted or deleted.
156#define DB_MARKED       ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
157#define DB_INDEX_MASK   (~DB_MARKED)
158
159#define INDEX_SIZE  (sizeof(unsigned))      // size of one db_index entry
160#define HEADER_SIZE (offsetof(DataBlock, db_index))  // size of data block header
161
162enum {
163  B0_FNAME_SIZE_ORG = 900,      // what it was in older versions
164  B0_FNAME_SIZE_NOCRYPT = 898,  // 2 bytes used for other things
165  B0_FNAME_SIZE_CRYPT = 890,    // 10 bytes used for other things
166  B0_UNAME_SIZE = 40,
167  B0_HNAME_SIZE = 40,
168};
169// Restrict the numbers to 32 bits, otherwise most compilers will complain.
170// This won't detect a 64 bit machine that only swaps a byte in the top 32
171// bits, but that is crazy anyway.
172enum {
173  B0_MAGIC_LONG = 0x30313233,
174  B0_MAGIC_INT = 0x20212223,
175  B0_MAGIC_SHORT = 0x10111213,
176  B0_MAGIC_CHAR = 0x55,
177};
178
179/// Block zero holds all info about the swapfile. This is the first block in the file.
180///
181/// NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing swapfiles unusable!
182///
183/// If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in memfile.h!!
184///
185/// This block is built up of single bytes, to make it portable across
186/// different machines. b0_magic_* is used to check the byte order and size of
187/// variables, because the rest of the swapfile is not portable.
188typedef struct {
189  char b0_id[2];                     ///< ID for block 0: BLOCK0_ID0 and BLOCK0_ID1.
190  char b0_version[10];               ///< Vim version string
191  char b0_page_size[4];              ///< number of bytes per page
192  char b0_mtime[4];                  ///< last modification time of file
193  char b0_ino[4];                    ///< inode of b0_fname
194  char b0_pid[4];                    ///< process id of creator (or 0)
195  char b0_uname[B0_UNAME_SIZE];      ///< name of user (uid if no name)
196  char b0_hname[B0_HNAME_SIZE];      ///< host name (if it has a name)
197  char b0_fname[B0_FNAME_SIZE_ORG];  ///< name of file being edited
198  long b0_magic_long;                ///< check for byte order of long
199  int b0_magic_int;                  ///< check for byte order of int
200  int16_t b0_magic_short;            ///< check for byte order of short
201  char b0_magic_char;                ///< check for last char
202} ZeroBlock;
203
204// Note: b0_dirty and b0_flags are put at the end of the file name.  For very
205// long file names in older versions of Vim they are invalid.
206// The 'fileencoding' comes before b0_flags, with a NUL in front.  But only
207// when there is room, for very long file names it's omitted.
208#define B0_DIRTY        0x55
209#define b0_dirty        b0_fname[B0_FNAME_SIZE_ORG - 1]
210
211// The b0_flags field is new in Vim 7.0.
212#define b0_flags        b0_fname[B0_FNAME_SIZE_ORG - 2]
213
214// The lowest two bits contain the fileformat.  Zero means it's not set
215// (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
216// EOL_MAC + 1.
217#define B0_FF_MASK      3
218
219// Swapfile is in directory of edited file.  Used to find the file from different mount points.
220#define B0_SAME_DIR     4
221
222// The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
223// When empty there is only the NUL.
224#define B0_HAS_FENC     8
225
226#define STACK_INCR      5       // nr of entries added to ml_stack at a time
227
228// The line number where the first mark may be is remembered.
229// If it is 0 there are no marks at all.
230// (always used for the current buffer only, no buffer change possible while
231// executing a global command).
232static linenr_T lowest_marked = 0;
233
234// arguments for ml_find_line()
235enum {
236  ML_DELETE = 0x11,  // delete line
237  ML_INSERT = 0x12,  // insert line
238  ML_FIND = 0x13,    // just find the line
239  ML_FLUSH = 0x02,   // flush locked block
240};
241#define ML_SIMPLE(x)    ((x) & 0x10)  // DEL, INS or FIND
242
243// argument for ml_upd_block0()
244typedef enum {
245  UB_FNAME = 0,         // update timestamp and filename
246  UB_SAME_DIR,  // update the B0_SAME_DIR flag
247} upd_block0_T;
248
249typedef enum {
250  SEA_CHOICE_NONE = 0,
251  SEA_CHOICE_READONLY = 1,
252  SEA_CHOICE_EDIT = 2,
253  SEA_CHOICE_RECOVER = 3,
254  SEA_CHOICE_DELETE = 4,
255  SEA_CHOICE_QUIT = 5,
256  SEA_CHOICE_ABORT = 6,
257} sea_choice_T;
258
259#include "memline.c.generated.h"
260
261static const char e_ml_get_invalid_lnum_nr[]
262  = N_("E315: ml_get: Invalid lnum: %" PRId64);
263static const char e_ml_get_cannot_find_line_nr_in_buffer_nr_str[]
264  = N_("E316: ml_get: Cannot find line %" PRId64 "in buffer %d %s");
265static const char e_pointer_block_id_wrong[]
266  = N_("E317: Pointer block id wrong");
267static const char e_pointer_block_id_wrong_two[]
268  = N_("E317: Pointer block id wrong 2");
269static const char e_pointer_block_id_wrong_three[]
270  = N_("E317: Pointer block id wrong 3");
271static const char e_pointer_block_id_wrong_four[]
272  = N_("E317: Pointer block id wrong 4");
273static const char e_line_number_out_of_range_nr_past_the_end[]
274  = N_("E322: Line number out of range: %" PRId64 " past the end");
275static const char e_line_count_wrong_in_block_nr[]
276  = N_("E323: Line count wrong in block %" PRId64);
277static const char e_warning_pointer_block_corrupted[]
278  = N_("E1364: Warning: Pointer block corrupted");
279
280#if __has_feature(address_sanitizer)
281# define ML_GET_ALLOC_LINES
282#endif
283
284/// Open a new memline for "buf".
285///
286/// @return  FAIL for failure, OK otherwise.
287int ml_open(buf_T *buf)
288{
289  // init fields in memline struct
290  buf->b_ml.ml_stack_size = 0;   // no stack yet
291  buf->b_ml.ml_stack = NULL;    // no stack yet
292  buf->b_ml.ml_stack_top = 0;   // nothing in the stack
293  buf->b_ml.ml_locked = NULL;   // no cached block
294  buf->b_ml.ml_line_lnum = 0;   // no cached line
295  buf->b_ml.ml_line_offset = 0;
296  buf->b_ml.ml_chunksize = NULL;
297  buf->b_ml.ml_usedchunks = 0;
298
299  if (cmdmod.cmod_flags & CMOD_NOSWAPFILE) {
300    buf->b_p_swf = false;
301  }
302
303  // When 'updatecount' is non-zero swapfile may be opened later.
304  if (!buf->terminal && p_uc && buf->b_p_swf) {
305    buf->b_may_swap = true;
306  } else {
307    buf->b_may_swap = false;
308  }
309
310  // Open the memfile.  No swapfile is created yet.
311  memfile_T *mfp = mf_open(NULL, 0);
312  if (mfp == NULL) {
313    goto error;
314  }
315
316  buf->b_ml.ml_mfp = mfp;
317  buf->b_ml.ml_flags = ML_EMPTY;
318  buf->b_ml.ml_line_count = 1;
319
320  // fill block0 struct and write page 0
321  bhdr_T *hp = mf_new(mfp, false, 1);
322  if (hp->bh_bnum != 0) {
323    iemsg(_("E298: Didn't get block nr 0?"));
324    goto error;
325  }
326  ZeroBlock *b0p = hp->bh_data;
327
328  b0p->b0_id[0] = BLOCK0_ID0;
329  b0p->b0_id[1] = BLOCK0_ID1;
330  b0p->b0_magic_long = B0_MAGIC_LONG;
331  b0p->b0_magic_int = B0_MAGIC_INT;
332  b0p->b0_magic_short = (int16_t)B0_MAGIC_SHORT;
333  b0p->b0_magic_char = B0_MAGIC_CHAR;
334  xstrlcpy(xstpcpy(b0p->b0_version, "VIM "), Versions[0], 6);
335  long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
336
337  if (!buf->b_spell) {
338    b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
339    b0p->b0_flags = (char)(get_fileformat(buf) + 1);
340    set_b0_fname(b0p, buf);
341    os_get_username(b0p->b0_uname, B0_UNAME_SIZE);
342    b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
343    os_get_hostname(b0p->b0_hname, B0_HNAME_SIZE);
344    b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
345    long_to_char((long)os_get_pid(), b0p->b0_pid);
346  }
347
348  // Always sync block number 0 to disk, so we can check the file name in
349  // the swapfile in findswapname(). Don't do this for a help files or
350  // a spell buffer though.
351  // Only works when there's a swapfile, otherwise it's done when the file
352  // is created.
353  mf_put(mfp, hp, true, false);
354  if (!buf->b_help && !buf->b_spell) {
355    mf_sync(mfp, 0);
356  }
357
358  // Fill in root pointer block and write page 1.
359  hp = ml_new_ptr(mfp);
360  assert(hp != NULL);
361  if (hp->bh_bnum != 1) {
362    iemsg(_("E298: Didn't get block nr 1?"));
363    goto error;
364  }
365  PointerBlock *pp = hp->bh_data;
366  pp->pb_count = 1;
367  pp->pb_pointer[0].pe_bnum = 2;
368  pp->pb_pointer[0].pe_page_count = 1;
369  pp->pb_pointer[0].pe_old_lnum = 1;
370  pp->pb_pointer[0].pe_line_count = 1;      // line count after insertion
371  mf_put(mfp, hp, true, false);
372
373  // Allocate first data block and create an empty line 1.
374  hp = ml_new_data(mfp, false, 1);
375  if (hp->bh_bnum != 2) {
376    iemsg(_("E298: Didn't get block nr 2?"));
377    goto error;
378  }
379
380  DataBlock *dp = hp->bh_data;
381  dp->db_index[0] = --dp->db_txt_start;         // at end of block
382  dp->db_free -= 1 + (unsigned)INDEX_SIZE;
383  dp->db_line_count = 1;
384  *((char *)dp + dp->db_txt_start) = NUL;     // empty line
385
386  return OK;
387
388error:
389  if (mfp != NULL) {
390    if (hp) {
391      mf_put(mfp, hp, false, false);
392    }
393    mf_close(mfp, true);  // will also xfree(mfp->mf_fname)
394  }
395  buf->b_ml.ml_mfp = NULL;
396  return FAIL;
397}
398
399/// ml_setname() is called when the file name of "buf" has been changed.
400/// It may rename the swapfile.
401void ml_setname(buf_T *buf)
402{
403  bool success = false;
404
405  memfile_T *mfp = buf->b_ml.ml_mfp;
406  if (mfp->mf_fd < 0) {             // there is no swapfile yet
407    // When 'updatecount' is 0 and 'noswapfile' there is no swapfile.
408    // For help files we will make a swapfile now.
409    if (p_uc != 0 && (cmdmod.cmod_flags & CMOD_NOSWAPFILE) == 0) {
410      ml_open_file(buf);  // create a swapfile
411    }
412    return;
413  }
414
415  // Try all directories in the 'directory' option.
416  char *dirp = p_dir;
417  bool found_existing_dir = false;
418  while (true) {
419    if (*dirp == NUL) {             // tried all directories, fail
420      break;
421    }
422    char *fname = findswapname(buf, &dirp, mfp->mf_fname, &found_existing_dir);
423    // autocmd may have freed mfp if findswapname creates different swapfile name
424    if (buf->b_ml.ml_mfp != mfp) {
425      xfree(fname);
426      return;
427    }
428    // alloc's fname
429    if (dirp == NULL) {             // out of memory
430      break;
431    }
432    if (fname == NULL) {            // no file name found for this dir
433      continue;
434    }
435
436    // if the file name is the same we don't have to do anything
437    if (path_equal(fname, mfp->mf_fname, kPathCmpLiteral)) {
438      xfree(fname);
439      success = true;
440      break;
441    }
442    // need to close the swapfile before renaming
443    if (mfp->mf_fd >= 0) {
444      close(mfp->mf_fd);
445      mfp->mf_fd = -1;
446    }
447
448    // try to rename the swapfile
449    if (vim_rename(mfp->mf_fname, fname) == 0) {
450      success = true;
451      mf_free_fnames(mfp);
452      mf_set_fnames(mfp, fname);
453      ml_upd_block0(buf, UB_SAME_DIR);
454      break;
455    }
456    xfree(fname);                // this fname didn't work, try another
457  }
458
459  if (mfp->mf_fd == -1) {           // need to (re)open the swapfile
460    mfp->mf_fd = os_open(mfp->mf_fname, O_RDWR, 0);
461    if (mfp->mf_fd < 0) {
462      // could not (re)open the swapfile, what can we do????
463      emsg(_("E301: Oops, lost the swap file!!!"));
464      return;
465    }
466    os_set_cloexec(mfp->mf_fd);
467  }
468  if (!success) {
469    emsg(_("E302: Could not rename swap file"));
470  }
471}
472
473/// Open a file for the memfile for all buffers that are not readonly or have
474/// been modified.
475/// Used when 'updatecount' changes from zero to non-zero.
476void ml_open_files(void)
477{
478  FOR_ALL_BUFFERS(buf) {
479    if (!buf->b_p_ro || buf->b_changed) {
480      ml_open_file(buf);
481    }
482  }
483}
484
485/// Open a swapfile for an existing memfile, if there is no swapfile yet.
486/// If we are unable to find a file name, mf_fname will be NULL
487/// and the memfile will be in memory only (no recovery possible).
488void ml_open_file(buf_T *buf)
489{
490  memfile_T *mfp = buf->b_ml.ml_mfp;
491  if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf
492      || (cmdmod.cmod_flags & CMOD_NOSWAPFILE)
493      || buf->terminal) {
494    return;  // nothing to do
495  }
496
497  // For a spell buffer use a temp file name.
498  if (buf->b_spell) {
499    char *fname = vim_tempname();
500    if (fname != NULL) {
501      mf_open_file(mfp, fname);           // consumes fname!
502    }
503    buf->b_may_swap = false;
504    return;
505  }
506
507  // Try all directories in 'directory' option.
508  char *dirp = p_dir;
509  bool found_existing_dir = false;
510  while (true) {
511    if (*dirp == NUL) {
512      break;
513    }
514    // There is a small chance that between choosing the swapfile name
515    // and creating it, another Vim creates the file.  In that case the
516    // creation will fail and we will use another directory.
517    char *fname = findswapname(buf, &dirp, NULL, &found_existing_dir);
518    // autocmd may have freed mfp, grr!
519    if (buf->b_ml.ml_mfp != mfp) {
520      xfree(fname);
521      return;
522    }
523    if (dirp == NULL) {
524      break;        // out of memory
525    }
526    if (fname == NULL) {
527      continue;
528    }
529    if (mf_open_file(mfp, fname) == OK) {       // consumes fname!
530      // don't sync yet in ml_sync_all()
531      mfp->mf_dirty = MF_DIRTY_YES_NOSYNC;
532      ml_upd_block0(buf, UB_SAME_DIR);
533
534      // Flush block zero, so others can read it
535      if (mf_sync(mfp, MFS_ZERO) == OK) {
536        // Mark all blocks that should be in the swapfile as dirty.
537        // Needed for when the 'swapfile' option was reset, so that
538        // the swapfile was deleted, and then on again.
539        mf_set_dirty(mfp);
540        break;
541      }
542      // Writing block 0 failed: close the file and try another dir
543      mf_close_file(buf, false);
544    }
545  }
546
547  if (*p_dir != NUL && mfp->mf_fname == NULL) {
548    need_wait_return = true;  // call wait_return() later
549    no_wait_return++;
550    semsg(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
551          buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname);
552    no_wait_return--;
553  }
554
555  // don't try to open a swapfile again
556  buf->b_may_swap = false;
557}
558
559/// If still need to create a swapfile, and starting to edit a not-readonly
560/// file, or reading into an existing buffer, create a swapfile now.
561///
562/// @param newfile reading file into new buffer
563void check_need_swap(bool newfile)
564{
565  int old_msg_silent = msg_silent;  // might be reset by an E325 message
566  msg_silent = 0;  // If swap dialog prompts for input, user needs to see it!
567
568  if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile)) {
569    ml_open_file(curbuf);
570  }
571
572  msg_silent = old_msg_silent;
573}
574
575/// Close memline for buffer 'buf'.
576///
577/// @param del_file  if true, delete the swapfile
578void ml_close(buf_T *buf, int del_file)
579{
580  if (buf->b_ml.ml_mfp == NULL) {               // not open
581    return;
582  }
583  mf_close(buf->b_ml.ml_mfp, del_file);       // close the .swp file
584  if (buf->b_ml.ml_line_lnum != 0
585      && (buf->b_ml.ml_flags & (ML_LINE_DIRTY | ML_ALLOCATED))) {
586    xfree(buf->b_ml.ml_line_ptr);
587  }
588  xfree(buf->b_ml.ml_stack);
589  XFREE_CLEAR(buf->b_ml.ml_chunksize);
590  buf->b_ml.ml_mfp = NULL;
591
592  // Reset the "recovered" flag, give the ATTENTION prompt the next time
593  // this buffer is loaded.
594  buf->b_flags &= ~BF_RECOVERED;
595}
596
597/// Close all existing memlines and memfiles.
598/// Only used when exiting.
599///
600/// @param del_file  if true, delete the memfiles.
601void ml_close_all(bool del_file)
602{
603  FOR_ALL_BUFFERS(buf) {
604    ml_close(buf, del_file);
605  }
606  spell_delete_wordlist();      // delete the internal wordlist
607  vim_deltempdir();             // delete created temp directory
608}
609
610/// Close all memfiles for not modified buffers.
611/// Only use just before exiting!
612void ml_close_notmod(void)
613{
614  FOR_ALL_BUFFERS(buf) {
615    if (!bufIsChanged(buf)) {
616      ml_close(buf, true);          // close all not-modified buffers
617    }
618  }
619}
620
621/// Update the timestamp in the .swp file.
622/// Used when the file has been written.
623void ml_timestamp(buf_T *buf)
624{
625  ml_upd_block0(buf, UB_FNAME);
626}
627
628/// Checks whether the IDs in b0 are valid.
629static bool ml_check_b0_id(ZeroBlock *b0p)
630  FUNC_ATTR_NONNULL_ALL
631{
632  return b0p->b0_id[0] == BLOCK0_ID0 && b0p->b0_id[1] == BLOCK0_ID1;
633}
634
635/// Checks whether all strings in b0 are valid (i.e. nul-terminated).
636static bool ml_check_b0_strings(ZeroBlock *b0p)
637  FUNC_ATTR_NONNULL_ALL
638{
639  return (memchr(b0p->b0_version, NUL, 10)
640          && memchr(b0p->b0_uname, NUL, B0_UNAME_SIZE)
641          && memchr(b0p->b0_hname, NUL, B0_HNAME_SIZE)
642          && memchr(b0p->b0_fname, NUL, B0_FNAME_SIZE_CRYPT));
643}
644
645/// Update the timestamp or the B0_SAME_DIR flag of the .swp file.
646static void ml_upd_block0(buf_T *buf, upd_block0_T what)
647{
648  bhdr_T *hp;
649
650  memfile_T *mfp = buf->b_ml.ml_mfp;
651  if (mfp == NULL || (hp = mf_get(mfp, 0, 1)) == NULL) {
652    return;
653  }
654  ZeroBlock *b0p = hp->bh_data;
655  if (ml_check_b0_id(b0p) == FAIL) {
656    iemsg(_("E304: ml_upd_block0(): Didn't get block 0??"));
657  } else {
658    if (what == UB_FNAME) {
659      set_b0_fname(b0p, buf);
660    } else {    // what == UB_SAME_DIR
661      set_b0_dir_flag(b0p, buf);
662    }
663  }
664  mf_put(mfp, hp, true, false);
665}
666
667/// Write file name and timestamp into block 0 of a swapfile.
668/// Also set buf->b_mtime.
669/// Don't use NameBuff[]!!!
670static void set_b0_fname(ZeroBlock *b0p, buf_T *buf)
671{
672  if (buf->b_ffname == NULL) {
673    b0p->b0_fname[0] = NUL;
674  } else {
675    char uname[B0_UNAME_SIZE];
676
677    // For a file under the home directory of the current user, we try to
678    // replace the home directory path with "~user". This helps when
679    // editing the same file on different machines over a network.
680    // First replace home dir path with "~/" with home_replace().
681    // Then insert the user name to get "~user/".
682    size_t flen = home_replace(NULL, buf->b_ffname, b0p->b0_fname,
683                               B0_FNAME_SIZE_CRYPT, true);
684    if (b0p->b0_fname[0] == '~') {
685      // If there is no user name or it is too long, don't use "~/"
686      int retval = os_get_username(uname, B0_UNAME_SIZE);
687      size_t ulen = strlen(uname);
688      if (retval == FAIL || ulen + flen > B0_FNAME_SIZE_CRYPT - 1) {
689        xstrlcpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT);
690      } else {
691        memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
692        memmove(b0p->b0_fname + 1, uname, ulen);
693      }
694    }
695    FileInfo file_info;
696    if (os_fileinfo(buf->b_ffname, &file_info)) {
697      long_to_char(file_info.stat.st_mtim.tv_sec, b0p->b0_mtime);
698      long_to_char((long)os_fileinfo_inode(&file_info), b0p->b0_ino);
699      buf_store_file_info(buf, &file_info);
700      buf->b_mtime_read = buf->b_mtime;
701      buf->b_mtime_read_ns = buf->b_mtime_ns;
702    } else {
703      long_to_char(0, b0p->b0_mtime);
704      long_to_char(0, b0p->b0_ino);
705      buf->b_mtime = 0;
706      buf->b_mtime_ns = 0;
707      buf->b_mtime_read = 0;
708      buf->b_mtime_read_ns = 0;
709      buf->b_orig_size = 0;
710      buf->b_orig_mode = 0;
711    }
712  }
713
714  // Also add the 'fileencoding' if there is room.
715  add_b0_fenc(b0p, curbuf);
716}
717
718/// Update the B0_SAME_DIR flag of the swapfile.  It's set if the file and the
719/// swapfile for "buf" are in the same directory.
720/// This is fail safe: if we are not sure the directories are equal the flag is
721/// not set.
722static void set_b0_dir_flag(ZeroBlock *b0p, buf_T *buf)
723{
724  if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname)) {
725    b0p->b0_flags |= B0_SAME_DIR;
726  } else {
727    b0p->b0_flags = (char)(b0p->b0_flags & ~B0_SAME_DIR);
728  }
729}
730
731/// When there is room, add the 'fileencoding' to block zero.
732static void add_b0_fenc(ZeroBlock *b0p, buf_T *buf)
733{
734  const int size = B0_FNAME_SIZE_NOCRYPT;
735
736  int n = (int)strlen(buf->b_p_fenc);
737  if ((int)strlen(b0p->b0_fname) + n + 1 > size) {
738    b0p->b0_flags = (char)(b0p->b0_flags & ~B0_HAS_FENC);
739  } else {
740    memmove(b0p->b0_fname + size - n,
741            buf->b_p_fenc, (size_t)n);
742    *(b0p->b0_fname + size - n - 1) = NUL;
743    b0p->b0_flags |= B0_HAS_FENC;
744  }
745}
746
747/// Returns the PID of the process that owns the swapfile, if it is running.
748///
749/// @param b0p swapfile data
750/// @param swap_fname Name of the swapfile. If it's from before a reboot, the result is 0.
751///
752/// @return PID, or 0 if process is not running or the swapfile is from before a reboot.
753static int swapfile_proc_running(const ZeroBlock *b0p, const char *swap_fname)
754{
755  FileInfo st;
756  double uptime;
757  // If the system rebooted after when the swapfile was written then the
758  // process can't be running now.
759  if (os_fileinfo(swap_fname, &st)
760      && uv_uptime(&uptime) == 0
761      && (Timestamp)st.stat.st_mtim.tv_sec < os_time() - (Timestamp)uptime) {
762    return 0;
763  }
764  int pid = (int)char_to_long(b0p->b0_pid);
765  return os_proc_running(pid) ? pid : 0;
766}
767
768/// Try to recover curbuf from the .swp file.
769///
770/// @param checkext  if true, check the extension and detect whether it is a swapfile.
771void ml_recover(bool checkext)
772{
773  buf_T *buf = NULL;
774  memfile_T *mfp = NULL;
775  char *fname_used = NULL;
776  bhdr_T *hp = NULL;
777  char *b0_fenc = NULL;
778  infoptr_T *ip;
779  bool directly;
780  bool serious_error = true;
781  int orig_file_status = NOTDONE;
782
783  recoverymode = true;
784  int called_from_main = (curbuf->b_ml.ml_mfp == NULL);
785
786  // If the file name ends in ".s[a-w][a-z]" we assume this is the swapfile.
787  // Otherwise a search is done to find the swapfile(s).
788  char *fname = curbuf->b_fname;
789  if (fname == NULL) {              // When there is no file name
790    fname = "";
791  }
792  int len = (int)strlen(fname);
793  if (checkext && len >= 4
794      && STRNICMP(fname + len - 4, ".s", 2) == 0
795      && vim_strchr("abcdefghijklmnopqrstuvw", TOLOWER_ASC((uint8_t)fname[len - 2])) != NULL
796      && ASCII_ISALPHA(fname[len - 1])) {
797    directly = true;
798    fname_used = xstrdup(fname);     // make a copy for mf_open()
799  } else {
800    directly = false;
801
802    // Enumerate matching swapfiles into items_tv.
803    typval_T items_tv;
804    tv_list_alloc_ret(&items_tv, 0);
805    recover_names(fname, true, items_tv.vval.v_list);
806    int n_swaps = tv_list_len(items_tv.vval.v_list);
807
808    if (n_swaps == 0) {
809      tv_clear(&items_tv);
810      semsg(_("E305: No swap file found for %s"), fname);
811      goto theend;
812    }
813    if (n_swaps > 1) {
814      // Several swapfiles found: prompt (async) via vim.ui.select().
815      typval_T lua_args[] = { items_tv, { .v_type = VAR_UNKNOWN } };
816      nlua_call_typval("vim._core.swapfile", "select_swap", lua_args, NULL);
817      tv_clear(&items_tv);
818      goto theend;
819    }
820    // One swapfile: use it directly.
821    fname_used = xstrdup(tv_list_first(items_tv.vval.v_list)->li_tv.vval.v_string);
822    tv_clear(&items_tv);
823  }
824  if (fname_used == NULL) {
825    goto theend;  // user chose invalid number.
826  }
827  // When called from main() still need to initialize storage structure
828  if (called_from_main && ml_open(curbuf) == FAIL) {
829    getout(1);
830  }
831
832  // Allocate a buffer structure for the swapfile that is used for recovery.
833  // Only the memline in it is really used.
834  buf = xmalloc(sizeof(buf_T));
835
836  // init fields in memline struct
837  buf->b_ml.ml_stack_size = 0;          // no stack yet
838  buf->b_ml.ml_stack = NULL;            // no stack yet
839  buf->b_ml.ml_stack_top = 0;           // nothing in the stack
840  buf->b_ml.ml_line_lnum = 0;           // no cached line
841  buf->b_ml.ml_line_offset = 0;
842  buf->b_ml.ml_locked = NULL;           // no locked block
843  buf->b_ml.ml_flags = 0;
844
845  // open the memfile from the old swapfile
846  char *p = xstrdup(fname_used);  // save "fname_used" for the message:
847  // mf_open() will consume "fname_used"!
848  mfp = mf_open(fname_used, O_RDONLY);
849  fname_used = p;
850  if (mfp == NULL || mfp->mf_fd < 0) {
851    semsg(_("E306: Cannot open %s"), fname_used);
852    goto theend;
853  }
854  buf->b_ml.ml_mfp = mfp;
855
856  // The page size set in mf_open() might be different from the page size
857  // used in the swapfile, we must get it from block 0.  But to read block
858  // 0 we need a page size.  Use the minimal size for block 0 here, it will
859  // be set to the real value below.
860  mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
861
862  int hl_id = HLF_E;
863  msg_ext_set_kind("emsg");
864  // try to read block 0
865  if ((hp = mf_get(mfp, 0, 1)) == NULL) {
866    msg_start();
867    msg_puts_hl(_("Unable to read block 0 from "), hl_id, true);
868    msg_outtrans(mfp->mf_fname, hl_id, true);
869    msg_puts_hl(_("\nMaybe no changes were made or Nvim did not update the swap file."), hl_id,
870                true);
871    msg_end();
872    goto theend;
873  }
874  ZeroBlock *b0p = hp->bh_data;
875  if (strncmp(b0p->b0_version, "VIM 3.0", 7) == 0) {
876    msg_start();
877    msg_outtrans(mfp->mf_fname, 0, true);
878    msg_puts_hl(_(" cannot be used with this version of Nvim.\n"), 0, true);
879    msg_puts_hl(_("Use Vim version 3.0.\n"), 0, true);
880    msg_end();
881    goto theend;
882  }
883  if (ml_check_b0_id(b0p) == FAIL) {
884    semsg(_("E307: %s does not look like a Nvim swap file"), mfp->mf_fname);
885    goto theend;
886  }
887  if (b0_magic_wrong(b0p)) {
888    msg_start();
889    msg_outtrans(mfp->mf_fname, hl_id, true);
890    msg_puts_hl(_(" cannot be used on this computer.\n"), hl_id, true);
891    msg_puts_hl(_("The file was created on "), hl_id, true);
892    // avoid going past the end of a corrupted hostname
893    b0p->b0_fname[0] = NUL;
894    msg_puts_hl(b0p->b0_hname, hl_id, true);
895    msg_puts_hl(_(",\nor the file has been damaged."), hl_id, true);
896    msg_end();
897    goto theend;
898  }
899
900  // If we guessed the wrong page size, we have to recalculate the
901  // highest block number in the file.
902  if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size)) {
903    unsigned previous_page_size = mfp->mf_page_size;
904
905    mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
906    if (mfp->mf_page_size < previous_page_size) {
907      msg_start();
908      msg_outtrans(mfp->mf_fname, hl_id, true);
909      msg_puts_hl(_(" has been damaged (page size is smaller than minimum value).\n"), hl_id, true);
910      msg_end();
911      goto theend;
912    }
913    off_T size = vim_lseek(mfp->mf_fd, 0, SEEK_END);
914    // 0 means no file or empty file
915    mfp->mf_blocknr_max = size <= 0 ? 0 : size / mfp->mf_page_size;
916    mfp->mf_infile_count = mfp->mf_blocknr_max;
917
918    // need to reallocate the memory used to store the data
919    p = xmalloc(mfp->mf_page_size);
920    memmove(p, hp->bh_data, previous_page_size);
921    xfree(hp->bh_data);
922    hp->bh_data = p;
923    b0p = hp->bh_data;
924  }
925
926  // If .swp file name given directly, use name from swapfile for buffer.
927  if (directly) {
928    TO_SLASH(b0p->b0_fname);
929    expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
930    if (setfname(curbuf, NameBuff, NULL, true) == FAIL) {
931      goto theend;
932    }
933  }
934
935  msg_ext_set_kind("wmsg");
936  msg_ext_skip_flush = true;
937  home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, true);
938  smsg(0, _("Using swap file \"%s\""), NameBuff);
939
940  if (buf_spname(curbuf) != NULL) {
941    xstrlcpy(NameBuff, buf_spname(curbuf), MAXPATHL);
942  } else {
943    home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, true);
944  }
945  msg_putchar('\n');
946  smsg(0, _("Original file \"%s\""), NameBuff);
947  msg_putchar('\n');
948  msg_ext_skip_flush = false;
949
950  // check date of swapfile and original file
951  FileInfo org_file_info;
952  FileInfo swp_file_info;
953  int mtime = (int)char_to_long(b0p->b0_mtime);
954  if (curbuf->b_ffname != NULL
955      && os_fileinfo(curbuf->b_ffname, &org_file_info)
956      && ((os_fileinfo(mfp->mf_fname, &swp_file_info)
957           && org_file_info.stat.st_mtim.tv_sec
958           > swp_file_info.stat.st_mtim.tv_sec)
959          || org_file_info.stat.st_mtim.tv_sec != mtime)) {
960    emsg(_("E308: Warning: Original file may have been changed"));
961  }
962  ui_flush();
963
964  // Get the 'fileformat' and 'fileencoding' from block zero.
965  int b0_ff = (b0p->b0_flags & B0_FF_MASK);
966  if (b0p->b0_flags & B0_HAS_FENC) {
967    int fnsize = B0_FNAME_SIZE_NOCRYPT;
968
969    for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; p--) {}
970    b0_fenc = xstrnsave(p, (size_t)(b0p->b0_fname + fnsize - p));
971  }
972
973  mf_put(mfp, hp, false, false);        // release block 0
974  hp = NULL;
975
976  // Now that we are sure that the file is going to be recovered, clear the
977  // contents of the current buffer.
978  while (!(curbuf->b_ml.ml_flags & ML_EMPTY)) {
979    ml_delete(1);
980  }
981
982  // Try reading the original file to obtain the values of 'fileformat',
983  // 'fileencoding', etc.  Ignore errors.  The text itself is not used.
984  if (curbuf->b_ffname != NULL) {
985    orig_file_status = readfile(curbuf->b_ffname, NULL, 0,
986                                0, MAXLNUM, NULL, READ_NEW, false);
987  }
988
989  // Use the 'fileformat' and 'fileencoding' as stored in the swapfile.
990  if (b0_ff != 0) {
991    set_fileformat(b0_ff - 1, OPT_LOCAL);
992  }
993  if (b0_fenc != NULL) {
994    set_option_value_give_err(kOptFileencoding, CSTR_AS_OBJ(b0_fenc), OPT_LOCAL);
995    xfree(b0_fenc);
996  }
997  unchanged(curbuf, true, true);
998
999  blocknr_T bnum = 1;       // start with block 1
1000  unsigned page_count = 1;  // which is 1 page
1001  linenr_T lnum = 0;        // append after line 0 in curbuf
1002  linenr_T line_count = 0;
1003  int idx = 0;              // start with first index in block 1
1004  int error = 0;
1005  buf->b_ml.ml_stack_top = 0;
1006  buf->b_ml.ml_stack = NULL;
1007  buf->b_ml.ml_stack_size = 0;
1008
1009  bool cannot_open = (curbuf->b_ffname == NULL);
1010
1011  serious_error = false;
1012  for (; !got_int; line_breakcheck()) {
1013    if (hp != NULL) {
1014      mf_put(mfp, hp, false, false);            // release previous block
1015    }
1016    // get block
1017    if ((hp = mf_get(mfp, bnum, page_count)) == NULL) {
1018      if (bnum == 1) {
1019        semsg(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1020        goto theend;
1021      }
1022      error++;
1023      ml_append(lnum++, _("???MANY LINES MISSING"), 0, true);
1024    } else {          // there is a block
1025      PointerBlock *pp = hp->bh_data;
1026      if (pp->pb_id == PTR_ID) {                // it is a pointer block
1027        bool ptr_block_error = false;
1028        if (pp->pb_count_max != PB_COUNT_MAX(mfp)) {
1029          ptr_block_error = true;
1030          pp->pb_count_max = PB_COUNT_MAX(mfp);
1031        }
1032        if (pp->pb_count > pp->pb_count_max) {
1033          ptr_block_error = true;
1034          pp->pb_count = pp->pb_count_max;
1035        }
1036        if (ptr_block_error) {
1037          emsg(_(e_warning_pointer_block_corrupted));
1038        }
1039
1040        // check line count when using pointer block first time
1041        if (idx == 0 && line_count != 0) {
1042          for (int i = 0; i < (int)pp->pb_count; i++) {
1043            line_count -= pp->pb_pointer[i].pe_line_count;
1044          }
1045          if (line_count != 0) {
1046            error++;
1047            ml_append(lnum++, _("???LINE COUNT WRONG"), 0, true);
1048          }
1049        }
1050
1051        if (pp->pb_count == 0) {
1052          ml_append(lnum++, _("???EMPTY BLOCK"), 0, true);
1053          error++;
1054        } else if (idx < (int)pp->pb_count) {         // go a block deeper
1055          if (pp->pb_pointer[idx].pe_bnum < 0) {
1056            // Data block with negative block number.
1057            // Try to read lines from the original file.
1058            // This is slow, but it works.
1059            if (!cannot_open) {
1060              line_count = pp->pb_pointer[idx].pe_line_count;
1061              linenr_T pe_old_lnum = pp->pb_pointer[idx].pe_old_lnum;
1062              // Validate pe_line_count and pe_old_lnum from the
1063              // untrusted swap file before passing to readfile().
1064              if (line_count <= 0 || pe_old_lnum < 1
1065                  || readfile(curbuf->b_ffname, NULL, lnum, pe_old_lnum - 1,
1066                              line_count, NULL, 0, false) != OK) {
1067                cannot_open = true;
1068              } else {
1069                lnum += line_count;
1070              }
1071            }
1072            if (cannot_open) {
1073              error++;
1074              ml_append(lnum++, _("???LINES MISSING"), 0, true);
1075            }
1076            idx++;                  // get same block again for next index
1077            continue;
1078          }
1079
1080          // going one block deeper in the tree
1081          int top = ml_add_stack(buf);  // new entry in stack
1082          ip = &(buf->b_ml.ml_stack[top]);
1083          ip->ip_bnum = bnum;
1084          ip->ip_index = idx;
1085
1086          bnum = pp->pb_pointer[idx].pe_bnum;
1087          line_count = pp->pb_pointer[idx].pe_line_count;
1088          page_count = (unsigned)pp->pb_pointer[idx].pe_page_count;
1089          // Validate pe_bnum and pe_page_count from the untrusted
1090          // swap file before passing to mf_get(), which uses
1091          // page_count to calculate allocation size.  A bogus value
1092          // (e.g. 0x40000000) would cause a multi-GB allocation.
1093          // pe_page_count must be >= 1 and bnum + page_count must
1094          // not exceed the number of pages in the swap file.
1095          if (page_count < 1 || bnum + page_count > mfp->mf_blocknr_max + 1) {
1096            error++;
1097            ml_append(lnum++, _("???ILLEGAL BLOCK NUMBER"), (colnr_T)0, true);
1098            // Skip this entry and pop back up the stack to keep
1099            // recovering whatever else we can.
1100            idx = ip->ip_index + 1;
1101            bnum = ip->ip_bnum;
1102            page_count = 1;
1103            buf->b_ml.ml_stack_top--;
1104            continue;
1105          }
1106          idx = 0;
1107          continue;
1108        }
1109      } else {            // not a pointer block
1110        DataBlock *dp = hp->bh_data;
1111        if (dp->db_id != DATA_ID) {             // block id wrong
1112          if (bnum == 1) {
1113            semsg(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1114                  mfp->mf_fname);
1115            goto theend;
1116          }
1117          error++;
1118          ml_append(lnum++, _("???BLOCK MISSING"), 0, true);
1119        } else {
1120          // It is a data block.
1121          // Append all the lines in this block.
1122          bool has_error = false;
1123
1124          // Verify the cached block's actual size matches the
1125          // pointer entry's pe_page_count.  mf_get() cache hits
1126          // return the original block without resizing, so a
1127          // crafted swap file referencing the same block twice
1128          // with different pe_page_count values would cause an
1129          // OOB write below.
1130          if (hp->bh_page_count != page_count) {
1131            error++;
1132            ml_append(lnum++, _("??? BLOCK PAGE COUNT MISMATCH"), 0, true);
1133            page_count = hp->bh_page_count;
1134          }
1135
1136          // Check the length of the block.
1137          // If wrong, use the length given in the pointer block.
1138          if (page_count * mfp->mf_page_size != dp->db_txt_end) {
1139            ml_append(lnum++,
1140                      _("??? from here until ???END lines" " may be messed up"),
1141                      0, true);
1142            error++;
1143            has_error = true;
1144            dp->db_txt_end = page_count * mfp->mf_page_size;
1145          }
1146
1147          if (dp->db_txt_start < HEADER_SIZE || dp->db_txt_start > dp->db_txt_end) {
1148            ml_append(lnum++, _("??? block header corrupted"), 0, true);
1149            error++;
1150            has_error = true;
1151            dp->db_txt_start = dp->db_txt_end;
1152          }
1153          // Make sure there is a NUL at the end of the block so we
1154          // don't go over the end when copying text.
1155          *((char *)dp + dp->db_txt_end - 1) = NUL;
1156
1157          // Check the number of lines in the block.
1158          // If wrong, use the count in the data block.
1159          if (line_count != dp->db_line_count) {
1160            ml_append(lnum++,
1161                      _("??? from here until ???END lines"
1162                        " may have been inserted/deleted"),
1163                      0, true);
1164            error++;
1165            has_error = true;
1166          }
1167
1168          bool did_questions = false;
1169          for (int i = 0; i < dp->db_line_count; i++) {
1170            if ((char *)&(dp->db_index[i]) >= (char *)dp + dp->db_txt_start) {
1171              // line count must be wrong
1172              error++;
1173              ml_append(lnum++, _("??? lines may be missing"), 0, true);
1174              break;
1175            }
1176
1177            int txt_start = (dp->db_index[i] & DB_INDEX_MASK);
1178            if (txt_start <= (int)HEADER_SIZE
1179                || txt_start >= (int)dp->db_txt_end) {
1180              error++;
1181              // avoid lots of lines with "???"
1182              if (did_questions) {
1183                continue;
1184              }
1185              did_questions = true;
1186              p = "???";
1187            } else {
1188              did_questions = false;
1189              p = (char *)dp + txt_start;
1190            }
1191            ml_append(lnum++, p, 0, true);
1192          }
1193          if (has_error) {
1194            ml_append(lnum++, _("???END"), 0, true);
1195          }
1196        }
1197      }
1198    }
1199
1200    if (buf->b_ml.ml_stack_top == 0) {          // finished
1201      break;
1202    }
1203
1204    // go one block up in the tree
1205    ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1206    bnum = ip->ip_bnum;
1207    idx = ip->ip_index + 1;         // go to next index
1208    page_count = 1;
1209  }
1210
1211  // Compare the buffer contents with the original file.  When they differ
1212  // set the 'modified' flag.
1213  // Lines 1 - lnum are the new contents.
1214  // Lines lnum + 1 to ml_line_count are the original contents.
1215  // Line ml_line_count + 1 in the dummy empty line.
1216  if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1) {
1217    // Recovering an empty file results in two lines and the first line is
1218    // empty.  Don't set the modified flag then.
1219    if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL)) {
1220      changed_internal(curbuf);
1221      buf_inc_changedtick(curbuf);
1222    }
1223  } else {
1224    for (idx = 1; idx <= lnum; idx++) {
1225      // Need to copy one line, fetching the other one may flush it.
1226      p = xstrnsave(ml_get(idx), (size_t)ml_get_len(idx));
1227      int i = strcmp(p, ml_get(idx + lnum));
1228      xfree(p);
1229      if (i != 0) {
1230        changed_internal(curbuf);
1231        buf_inc_changedtick(curbuf);
1232        break;
1233      }
1234    }
1235  }
1236
1237  // Delete the lines from the original file and the dummy line from the
1238  // empty buffer.  These will now be after the last line in the buffer.
1239  while (curbuf->b_ml.ml_line_count > lnum
1240         && !(curbuf->b_ml.ml_flags & ML_EMPTY)) {
1241    ml_delete(curbuf->b_ml.ml_line_count);
1242  }
1243  curbuf->b_flags |= BF_RECOVERED;
1244  check_cursor(curwin);
1245
1246  msg_ext_skip_flush = !got_int;
1247  recoverymode = false;
1248  if (got_int) {
1249    emsg(_("E311: Recovery Interrupted"));
1250  } else if (error) {
1251    no_wait_return++;
1252    msg_ext_set_kind("emsg");
1253    msg(">>>>>>>>>>>>>\n", 0);
1254    emsg(_("E312: Errors detected while recovering; look for lines starting with ???"));
1255    no_wait_return--;
1256    msg_putchar('\n');
1257    msg(_("See \":help E312\" for more information."), 0);
1258    msg("\n>>>>>>>>>>>>>", 0);
1259  } else {
1260    msg_ext_set_kind("wmsg");
1261    if (curbuf->b_changed) {
1262      msg(_("Recovery completed. You should check if everything is OK."), 0);
1263      msg_puts(_("\n(You might want to write out this file under another name\n"));
1264      msg_puts(_("and run diff with the original file to check for changes)"));
1265    } else {
1266      msg(_("Recovery completed. Buffer contents equals file contents."), 0);
1267    }
1268    msg_puts(_("\nYou may want to delete the .swp file now."));
1269    if (swapfile_proc_running(b0p, fname_used)) {
1270      // Warn there could be an active Vim on the same file, the user may
1271      // want to kill it.
1272      msg_puts(_("\nNote: process STILL RUNNING: "));
1273      msg_outnum((int)char_to_long(b0p->b0_pid));
1274    }
1275    if (!ui_has(kUIMessages)) {
1276      msg_puts("\n\n");
1277    }
1278    cmdline_row = msg_row;
1279  }
1280  redraw_curbuf_later(UPD_NOT_VALID);
1281
1282theend:
1283  msg_ext_skip_flush = false;
1284  xfree(fname_used);
1285  recoverymode = false;
1286  if (mfp != NULL) {
1287    if (hp != NULL) {
1288      mf_put(mfp, hp, false, false);
1289    }
1290    mf_close(mfp, false);           // will also xfree(mfp->mf_fname)
1291  }
1292  if (buf != NULL) {  // may be NULL if swapfile not found.
1293    xfree(buf->b_ml.ml_stack);
1294    xfree(buf);
1295  }
1296  if (serious_error && called_from_main) {
1297    ml_close(curbuf, true);
1298  } else {
1299    apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, false, curbuf);
1300    apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, false, curbuf);
1301  }
1302}
1303
1304/// Enumerate swapfiles for `fname` (or for the global swap dir if `fname` is NULL),
1305/// appending each found path to `ret_list`.
1306///
1307/// Used by `:recover` (`ml_recover()`), `nvim -r`, and `swapfilelist()`.
1308///
1309/// @param fname  base for swapfile name, or NULL to list every swapfile in 'directory'.
1310/// @param skip_curbuf  exclude the current buffer's own active swapfile (used by `:recover`,
1311///                     not by `swapfilelist()`).
1312/// @param ret_list  receives the paths.
1313void recover_names(char *fname, bool skip_curbuf, list_T *ret_list)
1314  FUNC_ATTR_NONNULL_ARG(3)
1315{
1316  int num_names;
1317  char *(names[6]);
1318  char *tail;
1319  char *p;
1320  char **files;
1321  char *fname_res = NULL;
1322#ifdef HAVE_READLINK
1323  char fname_buf[MAXPATHL];
1324#endif
1325
1326  if (fname != NULL) {
1327#ifdef HAVE_READLINK
1328    // Expand symlink in the file name, because the swapfile is created
1329    // with the actual file instead of with the symlink.
1330    fname_res = (resolve_symlink(fname, fname_buf) == OK) ? fname_buf : fname;
1331#else
1332    fname_res = fname;
1333#endif
1334  }
1335
1336  // Do the loop for every directory in 'directory'.
1337  // First allocate some memory to put the directory name in.
1338  String dir_name;
1339  dir_name.data = xmalloc(strlen(p_dir) + 1);
1340  char *dirp = p_dir;
1341  while (*dirp) {
1342    // Isolate a directory name from *dirp and put it in dir_name (we know
1343    // it is large enough, so use 31000 for length).
1344    // Advance dirp to next directory name.
1345    dir_name.size = copy_option_part(&dirp, dir_name.data, 31000, ",");
1346
1347    if (dir_name.data[0] == '.' && dir_name.data[1] == NUL) {     // check current dir
1348      if (fname == NULL) {
1349        names[0] = xmemdupz(S_LEN("*.sw?"));
1350        // For Unix names starting with a dot are special.  MS-Windows
1351        // supports this too, on some file systems.
1352        names[1] = xmemdupz(S_LEN(".*.sw?"));
1353        names[2] = xmemdupz(S_LEN(".sw?"));
1354        num_names = 3;
1355      } else {
1356        num_names = recov_file_names(names, fname_res, true);
1357      }
1358    } else {                      // check directory dir_name
1359      if (fname == NULL) {
1360        names[0] = concat_fnames(dir_name, STATIC_CSTR_AS_STRING("*.sw?"), true).data;
1361        // For Unix names starting with a dot are special.  MS-Windows
1362        // supports this too, on some file systems.
1363        names[1] = concat_fnames(dir_name, STATIC_CSTR_AS_STRING(".*.sw?"), true).data;
1364        names[2] = concat_fnames(dir_name, STATIC_CSTR_AS_STRING(".sw?"), true).data;
1365        num_names = 3;
1366      } else {
1367        p = dir_name.data + dir_name.size;
1368        if (after_pathsep(dir_name.data, p) && dir_name.size > 1 && p[-1] == p[-2]) {
1369          // Ends with '//', Use Full path for swap name
1370          tail = make_percent_swname(dir_name.data, p, fname_res);
1371        } else {
1372          tail = path_tail(fname_res);
1373          tail = concat_fnames(dir_name, cstr_as_string(tail), true).data;
1374        }
1375        num_names = recov_file_names(names, tail, false);
1376        xfree(tail);
1377      }
1378    }
1379
1380    int num_files;
1381    if (num_names == 0) {
1382      num_files = 0;
1383    } else if (expand_wildcards(num_names, names, &num_files, &files,
1384                                EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL) {
1385      num_files = 0;
1386    }
1387
1388    // When no swapfile found, wildcard expansion might have failed (e.g.
1389    // not able to execute the shell).
1390    // Try finding a swapfile by simply adding ".swp" to the file name.
1391    if (*dirp == NUL && tv_list_len(ret_list) + num_files == 0 && fname != NULL) {
1392      char *swapname = modname(fname_res, ".swp", true);
1393      if (swapname != NULL) {
1394        if (os_path_exists(swapname)) {
1395          files = xmalloc(sizeof(char *));
1396          files[0] = swapname;
1397          swapname = NULL;
1398          num_files = 1;
1399        }
1400        xfree(swapname);
1401      }
1402    }
1403
1404    // Remove swapfile name of the current buffer, it must be ignored.
1405    if (skip_curbuf
1406        && curbuf->b_ml.ml_mfp != NULL
1407        && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL) {
1408      for (int i = 0; i < num_files; i++) {
1409        // Do not expand wildcards, on Windows would try to expand
1410        // "%tmp%" in "%tmp%file"
1411        if (path_equal(p, files[i], kPathCmpFull)) {
1412          // Remove the name from files[i].  Move further entries
1413          // down.  When the array becomes empty free it here, since
1414          // FreeWild() won't be called below.
1415          xfree(files[i]);
1416          if (--num_files == 0) {
1417            xfree(files);
1418          } else {
1419            for (; i < num_files; i++) {
1420              files[i] = files[i + 1];
1421            }
1422          }
1423        }
1424      }
1425    }
1426    for (int i = 0; i < num_files; i++) {
1427      // `files[i]` is already a full path (from `expand_wildcards`).
1428      tv_list_append_allocated_string(ret_list, xstrdup(files[i]));
1429    }
1430
1431    for (int i = 0; i < num_names; i++) {
1432      xfree(names[i]);
1433    }
1434    if (num_files > 0) {
1435      FreeWild(num_files, files);
1436    }
1437  }
1438  xfree(dir_name.data);
1439}
1440
1441/// Append the full path to name with path separators made into percent
1442/// signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
1443/// signs, to "dir". An unnamed buffer is handled as "" (<currentdir>/"")
1444/// The last character in "dir" must be an extra slash or backslash, it is
1445/// removed.
1446char *make_percent_swname(char *dir, char *dir_end, const char *name)
1447  FUNC_ATTR_NONNULL_ARG(1, 2)
1448{
1449  String fixed_fname;
1450  char *fname = fix_fname(name != NULL ? name : "");
1451  if (fname == NULL) {
1452    return NULL;
1453  }
1454
1455  FileInfo file_info;
1456  if (!os_fileinfo2(fname, &file_info)) {
1457    xfree(fname);
1458    return NULL;
1459  }
1460  fixed_fname.data = fname + file_info.root_off;
1461  if (file_info.type == kPathDeviceUNC) {
1462    assert(file_info.root_off >= 2);
1463    fixed_fname.data -= 2;
1464    fixed_fname.data[0] = '/';  // Fixup //?/UNC/server/ path: "C/server/..." -> "//server/..."
1465  }
1466  char *p;
1467  for (p = fixed_fname.data; *p != NUL; MB_PTR_ADV(p)) {
1468    if (vim_ispathsep(*p)) {
1469      *p = '%';
1470    }
1471  }
1472  fixed_fname.size = (size_t)(p - fixed_fname.data);
1473
1474  // remove one trailing slash
1475  p = &dir_end[-1];
1476  *p = NUL;
1477  String d = concat_fnames(cbuf_as_string(dir, (size_t)(p - dir)), fixed_fname, true);
1478  xfree(fname);
1479
1480  return d.data;
1481}
1482
1483// PID of swapfile owner, or zero if not running.
1484static int proc_running;
1485
1486/// For Vimscript "swapinfo()".
1487///
1488/// @return  information found in swapfile "fname" in dictionary "d".
1489void swapfile_dict(const char *fname, dict_T *d)
1490{
1491  int fd;
1492  ZeroBlock b0;
1493
1494  if ((fd = os_open(fname, O_RDONLY, 0)) >= 0) {
1495    if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) {
1496      if (ml_check_b0_id(&b0) == FAIL) {
1497        tv_dict_add_str_len(d, S_LEN("error"), S_LEN("Not a swap file"));
1498      } else if (b0_magic_wrong(&b0)) {
1499        tv_dict_add_str_len(d, S_LEN("error"), S_LEN("Magic number mismatch"));
1500      } else {
1501        // We have swap information.
1502        tv_dict_add_str_len(d, S_LEN("version"), b0.b0_version, 10);
1503        tv_dict_add_str_len(d, S_LEN("user"), b0.b0_uname,
1504                            B0_UNAME_SIZE);
1505        tv_dict_add_str_len(d, S_LEN("host"), b0.b0_hname,
1506                            B0_HNAME_SIZE);
1507        tv_dict_add_str_len(d, S_LEN("fname"), b0.b0_fname,
1508                            B0_FNAME_SIZE_ORG);
1509
1510        tv_dict_add_nr(d, S_LEN("pid"), swapfile_proc_running(&b0, fname));
1511        tv_dict_add_nr(d, S_LEN("mtime"), char_to_long(b0.b0_mtime));
1512        tv_dict_add_nr(d, S_LEN("dirty"), b0.b0_dirty ? 1 : 0);
1513        tv_dict_add_nr(d, S_LEN("inode"), char_to_long(b0.b0_ino));
1514      }
1515    } else {
1516      tv_dict_add_str_len(d, S_LEN("error"), S_LEN("Cannot read file"));
1517    }
1518    close(fd);
1519  } else {
1520    tv_dict_add_str_len(d, S_LEN("error"), S_LEN("Cannot open file"));
1521  }
1522}
1523
1524/// Loads info from swapfile `fname`, and displays it to the user.
1525///
1526/// @return  timestamp (0 when unknown).
1527static time_t swapfile_info(char *fname, StringBuilder *msg)
1528{
1529  assert(fname != NULL);
1530  ZeroBlock b0;
1531  time_t x = (time_t)0;
1532#ifdef UNIX
1533  char uname[B0_UNAME_SIZE];
1534#endif
1535
1536  // print the swapfile date
1537  FileInfo file_info;
1538  if (os_fileinfo(fname, &file_info)) {
1539#ifdef UNIX
1540    // print name of owner of the file
1541    if (os_get_uname((uv_uid_t)file_info.stat.st_uid, uname, B0_UNAME_SIZE) == OK) {
1542      kv_printf(*msg, "%s%s", _("          owned by: "), uname);
1543      kv_printf(*msg, _("   dated: "));
1544    } else {
1545      kv_printf(*msg, _("             dated: "));
1546    }
1547#else
1548    kv_printf(*msg, _("             dated: "));
1549#endif
1550    x = file_info.stat.st_mtim.tv_sec;
1551    char ctime_buf[100];  // hopefully enough for every language
1552    kv_printf(*msg, "%s", os_ctime_r(&x, ctime_buf, sizeof(ctime_buf), true));
1553  }
1554
1555  // print the original file name
1556  int fd = os_open(fname, O_RDONLY, 0);
1557  if (fd >= 0) {
1558    if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) {
1559      if (strncmp(b0.b0_version, "VIM 3.0", 7) == 0) {
1560        kv_printf(*msg, _("         [from Vim version 3.0]"));
1561      } else if (ml_check_b0_id(&b0) == FAIL) {
1562        kv_printf(*msg, _("         [does not look like a Nvim swap file]"));
1563      } else if (!ml_check_b0_strings(&b0)) {
1564        kv_printf(*msg, _("         [garbled strings (not nul terminated)]"));
1565      } else {
1566        kv_printf(*msg, _("         file name: "));
1567        if (b0.b0_fname[0] == NUL) {
1568          kv_printf(*msg, _("[No Name]"));
1569        } else {
1570          kv_printf(*msg, "%s", b0.b0_fname);
1571        }
1572
1573        kv_printf(*msg, _("\n          modified: "));
1574        kv_printf(*msg, b0.b0_dirty ? _("YES") : _("no"));
1575
1576        if (*(b0.b0_uname) != NUL) {
1577          kv_printf(*msg, _("\n         user name: "));
1578          kv_printf(*msg, "%s", b0.b0_uname);
1579        }
1580
1581        if (*(b0.b0_hname) != NUL) {
1582          if (*(b0.b0_uname) != NUL) {
1583            kv_printf(*msg, _("   host name: "));
1584          } else {
1585            kv_printf(*msg, _("\n         host name: "));
1586          }
1587          kv_printf(*msg, "%s", b0.b0_hname);
1588        }
1589
1590        if (char_to_long(b0.b0_pid) != 0) {
1591          kv_printf(*msg, _("\n        process ID: "));
1592          kv_printf(*msg, "%d", (int)char_to_long(b0.b0_pid));
1593          if ((proc_running = swapfile_proc_running(&b0, fname))) {
1594            kv_printf(*msg, _(" (STILL RUNNING)"));
1595          }
1596        }
1597
1598        if (b0_magic_wrong(&b0)) {
1599          kv_printf(*msg, _("\n         [not usable on this computer]"));
1600        }
1601      }
1602    } else {
1603      kv_printf(*msg, _("         [cannot be read]"));
1604    }
1605    close(fd);
1606  } else {
1607    kv_printf(*msg, _("         [cannot be opened]"));
1608  }
1609  kv_printf(*msg, "\n");
1610
1611  return x;
1612}
1613
1614/// @return  true if the swapfile looks OK and there are no changes, thus it can be safely deleted.
1615static bool swapfile_unchanged(char *fname)
1616{
1617  ZeroBlock b0;
1618
1619  // Swapfile must exist.
1620  if (!os_path_exists(fname)) {
1621    return false;
1622  }
1623
1624  // must be able to read the first block
1625  int fd = os_open(fname, O_RDONLY, 0);
1626  if (fd < 0) {
1627    return false;
1628  }
1629  if (read_eintr(fd, &b0, sizeof(b0)) != sizeof(b0)) {
1630    close(fd);
1631    return false;
1632  }
1633
1634  bool ret = true;
1635
1636  // the ID and magic number must be correct
1637  if (ml_check_b0_id(&b0) == FAIL || b0_magic_wrong(&b0)) {
1638    ret = false;
1639  }
1640
1641  // must be unchanged
1642  if (b0.b0_dirty) {
1643    ret = false;
1644  }
1645
1646  // Host name must be known and must equal the current host name, otherwise
1647  // comparing pid is meaningless.
1648  if (*(b0.b0_hname) == NUL) {
1649    ret = false;
1650  } else {
1651    char hostname[B0_HNAME_SIZE];
1652    os_get_hostname(hostname, B0_HNAME_SIZE);
1653    hostname[B0_HNAME_SIZE - 1] = NUL;
1654    b0.b0_hname[B0_HNAME_SIZE - 1] = NUL;  // in case of corruption
1655    if (STRICMP(b0.b0_hname, hostname) != 0) {
1656      ret = false;
1657    }
1658  }
1659
1660  // process must be known and not running.
1661  if (char_to_long(b0.b0_pid) == 0 || swapfile_proc_running(&b0, fname)) {
1662    ret = false;
1663  }
1664
1665  // We do not check the user, it should be irrelevant for whether the swap
1666  // file is still useful.
1667
1668  close(fd);
1669  return ret;
1670}
1671
1672static int recov_file_names(char **names, char *path, bool prepend_dot)
1673  FUNC_ATTR_NONNULL_ALL
1674{
1675  int num_names = 0;
1676
1677  // May also add the file name with a dot prepended, for swapfile in same
1678  // dir as original file.
1679  if (prepend_dot) {
1680    names[num_names] = modname(path, ".sw?", true);
1681    if (names[num_names] == NULL) {
1682      return num_names;
1683    }
1684    num_names++;
1685  }
1686
1687  // Form the normal swapfile name pattern by appending ".sw?".
1688  names[num_names] = concat_fnames(cstr_as_string(path),
1689                                   STATIC_CSTR_AS_STRING(".sw?"), false).data;
1690  if (num_names >= 1) {     // check if we have the same name twice
1691    char *p = names[num_names - 1];
1692    int i = (int)strlen(names[num_names - 1]) - (int)strlen(names[num_names]);
1693    if (i > 0) {
1694      p += i;               // file name has been expanded to full path
1695    }
1696    if (strcmp(p, names[num_names]) != 0) {
1697      num_names++;
1698    } else {
1699      xfree(names[num_names]);
1700    }
1701  } else {
1702    num_names++;
1703  }
1704
1705  return num_names;
1706}
1707
1708/// sync all memlines
1709///
1710/// @param check_file  if true, check if original file exists and was not changed.
1711/// @param check_char  if true, stop syncing when character becomes available, but
1712///
1713/// always sync at least one block.
1714void ml_sync_all(int check_file, int check_char, bool do_fsync)
1715{
1716  FOR_ALL_BUFFERS(buf) {
1717    if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL) {
1718      continue;                             // no file
1719    }
1720    ml_flush_line(buf, false);              // flush buffered line
1721                                            // flush locked block
1722    ml_find_line(buf, 0, ML_FLUSH);
1723    if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
1724        && buf->b_ffname != NULL) {
1725      // If the original file does not exist anymore or has been changed
1726      // call ml_preserve() to get rid of all negative numbered blocks.
1727      FileInfo file_info;
1728      if (!os_fileinfo(buf->b_ffname, &file_info)
1729          || file_info.stat.st_mtim.tv_sec != buf->b_mtime_read
1730          || file_info.stat.st_mtim.tv_nsec != buf->b_mtime_read_ns
1731          || os_fileinfo_size(&file_info) != buf->b_orig_size) {
1732        ml_preserve(buf, false, do_fsync);
1733        did_check_timestamps = false;
1734        need_check_timestamps = true;           // give message later
1735      }
1736    }
1737    if (buf->b_ml.ml_mfp->mf_dirty == MF_DIRTY_YES) {
1738      mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
1739              | (do_fsync && bufIsChanged(buf) ? MFS_FLUSH : 0));
1740      if (check_char && os_char_avail()) {      // character available now
1741        break;
1742      }
1743    }
1744  }
1745}
1746
1747/// sync one buffer, including negative blocks
1748///
1749/// after this all the blocks are in the swapfile
1750///
1751/// Used for the :preserve command and when the original file has been
1752/// changed or deleted.
1753///
1754/// @param message  if true, the success of preserving is reported.
1755void ml_preserve(buf_T *buf, bool message, bool do_fsync)
1756{
1757  memfile_T *mfp = buf->b_ml.ml_mfp;
1758  int got_int_save = got_int;
1759
1760  if (mfp == NULL || mfp->mf_fname == NULL) {
1761    if (message) {
1762      emsg(_("E313: Cannot preserve, there is no swap file"));
1763    }
1764    return;
1765  }
1766
1767  // We only want to stop when interrupted here, not when interrupted
1768  // before.
1769  got_int = false;
1770
1771  ml_flush_line(buf, false);        // flush buffered line
1772  ml_find_line(buf, 0, ML_FLUSH);   // flush locked block
1773  int status = mf_sync(mfp, MFS_ALL | (do_fsync ? MFS_FLUSH : 0));
1774
1775  // stack is invalid after mf_sync(.., MFS_ALL)
1776  buf->b_ml.ml_stack_top = 0;
1777
1778  // Some of the data blocks may have been changed from negative to
1779  // positive block number. In that case the pointer blocks need to be
1780  // updated.
1781  //
1782  // We don't know in which pointer block the references are, so we visit
1783  // all data blocks until there are no more translations to be done (or
1784  // we hit the end of the file, which can only happen in case a write fails,
1785  // e.g. when file system if full).
1786  // ml_find_line() does the work by translating the negative block numbers
1787  // when getting the first line of each data block.
1788  if (mf_need_trans(mfp) && !got_int) {
1789    linenr_T lnum = 1;
1790    while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count) {
1791      bhdr_T *hp = ml_find_line(buf, lnum, ML_FIND);
1792      if (hp == NULL) {
1793        status = FAIL;
1794        goto theend;
1795      }
1796      CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
1797      lnum = buf->b_ml.ml_locked_high + 1;
1798    }
1799    ml_find_line(buf, 0, ML_FLUSH);  // flush locked block
1800    // sync the updated pointer blocks
1801    if (mf_sync(mfp, MFS_ALL | (do_fsync ? MFS_FLUSH : 0)) == FAIL) {
1802      status = FAIL;
1803    }
1804    buf->b_ml.ml_stack_top = 0;  // stack is invalid now
1805  }
1806theend:
1807  got_int |= got_int_save;
1808
1809  if (message) {
1810    if (status == OK) {
1811      msg(_("File preserved"), 0);
1812    } else {
1813      emsg(_("E314: Preserve failed"));
1814    }
1815  }
1816}
1817
1818// NOTE: The pointer returned by the ml_get_*() functions only remains valid
1819// until the next call!
1820//  line1 = ml_get(1);
1821//  line2 = ml_get(2);  // line1 is now invalid!
1822// Make a copy of the line if necessary.
1823
1824/// @return  a pointer to a (read-only copy of a) line in curbuf.
1825///
1826/// On failure an error message is given and IObuff is returned (to avoid
1827/// having to check for error everywhere).
1828char *ml_get(linenr_T lnum)
1829  FUNC_ATTR_NONNULL_RET
1830{
1831  return ml_get_buf_impl(curbuf, lnum, false);
1832}
1833
1834/// @return  a pointer to a (read-only copy of a) line.
1835///
1836/// This is the same as ml_get(), but taking in the buffer
1837/// as an argument.
1838char *ml_get_buf(buf_T *buf, linenr_T lnum)
1839  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
1840{
1841  return ml_get_buf_impl(buf, lnum, false);
1842}
1843
1844/// Like `ml_get_buf`, but allow the line to be mutated in place.
1845///
1846/// This is very limited. Generally ml_replace_buf()
1847/// should be used to modify a line.
1848///
1849/// @return a pointer to a line in the buffer
1850char *ml_get_buf_mut(buf_T *buf, linenr_T lnum)
1851  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
1852{
1853  return ml_get_buf_impl(buf, lnum, true);
1854}
1855
1856/// @return  pointer to position "pos".
1857char *ml_get_pos(const pos_T *pos)
1858  FUNC_ATTR_NONNULL_ALL
1859{
1860  return ml_get_buf(curbuf, pos->lnum) + pos->col;
1861}
1862
1863/// @return  length (excluding the NUL) of the given line.
1864colnr_T ml_get_len(linenr_T lnum)
1865{
1866  return ml_get_buf_len(curbuf, lnum);
1867}
1868
1869/// @return  length (excluding the NUL) of the text after position "pos".
1870colnr_T ml_get_pos_len(pos_T *pos)
1871{
1872  return ml_get_buf_len(curbuf, pos->lnum) - pos->col;
1873}
1874
1875/// @return  length (excluding the NUL) of the given line in the given buffer.
1876colnr_T ml_get_buf_len(buf_T *buf, linenr_T lnum)
1877{
1878  const char *line = ml_get_buf(buf, lnum);
1879
1880  if (*line == NUL) {
1881    return 0;
1882  }
1883
1884  assert(buf->b_ml.ml_line_textlen > 0);
1885  return buf->b_ml.ml_line_textlen - 1;
1886}
1887
1888/// Gets the charwise NL-joined text of range [start, end), 1-based lnum, 0-based col, end col
1889/// exclusive, as an allocated String ("" if empty). Line range must be valid (start <= end); cols
1890/// clamp to line-length.
1891String ml_region_text(buf_T *buf, pos_T start, pos_T end)
1892  FUNC_ATTR_NONNULL_ALL
1893{
1894  StringBuilder sb = KV_INITIAL_VALUE;
1895  for (linenr_T lnum = start.lnum; lnum <= end.lnum; lnum++) {
1896    char *line = ml_get_buf(buf, lnum);
1897    colnr_T len = ml_get_buf_len(buf, lnum);
1898    colnr_T from = lnum == start.lnum ? MIN(start.col, len) : 0;
1899    colnr_T to = lnum == end.lnum ? MIN(end.col, len) : len;
1900    kv_concat_len(sb, line + from, (size_t)(to - from));
1901    if (lnum < end.lnum) {
1902      kv_push(sb, NL);
1903    }
1904  }
1905  kv_push(sb, NUL);
1906  return cbuf_as_string(sb.items, kv_size(sb) - 1);
1907}
1908
1909/// @return  codepoint at pos. pos must be either valid or have col set to MAXCOL!
1910int gchar_pos(pos_T *pos)
1911  FUNC_ATTR_NONNULL_ARG(1)
1912{
1913  // When searching columns is sometimes put at the end of a line.
1914  if (pos->col == MAXCOL || pos->col > ml_get_len(pos->lnum)) {
1915    return NUL;
1916  }
1917  return utf_ptr2char(ml_get_pos(pos));
1918}
1919
1920/// @param will_change  true mark the buffer dirty (chars in the line will be changed)
1921///
1922/// @return  a pointer to a line in a specific buffer
1923static char *ml_get_buf_impl(buf_T *buf, linenr_T lnum, bool will_change)
1924  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
1925{
1926  static int recursive = 0;
1927  static char questions[4];
1928
1929  if (buf->b_ml.ml_mfp == NULL) {       // there are no lines
1930    buf->b_ml.ml_line_textlen = 1;
1931    return "";
1932  }
1933
1934  if (lnum > buf->b_ml.ml_line_count) {  // invalid line number
1935    if (recursive == 0) {
1936      // Avoid giving this message for a recursive call, may happen when
1937      // the GUI redraws part of the text.
1938      recursive++;
1939      siemsg(_(e_ml_get_invalid_lnum_nr), (int64_t)lnum);
1940      recursive--;
1941    }
1942    ml_flush_line(buf, false);
1943errorret:
1944    STRCPY(questions, "???");
1945    buf->b_ml.ml_line_textlen = 4;
1946    buf->b_ml.ml_line_lnum = lnum;
1947    return questions;
1948  }
1949  lnum = MAX(lnum, 1);  // pretend line 0 is line 1
1950
1951  // See if it is the same line as requested last time.
1952  // Otherwise may need to flush last used line.
1953  // Don't use the last used line when 'swapfile' is reset, need to load all
1954  // blocks.
1955  if (buf->b_ml.ml_line_lnum != lnum) {
1956    ml_flush_line(buf, false);
1957
1958    // Find the data block containing the line.
1959    // This also fills the stack with the blocks from the root to the data
1960    // block and releases any locked block.
1961    bhdr_T *hp;
1962    if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL) {
1963      if (recursive == 0) {
1964        // Avoid giving this message for a recursive call, may happen
1965        // when the GUI redraws part of the text.
1966        recursive++;
1967        get_trans_bufname(buf);
1968        shorten_dir(NameBuff);
1969        siemsg(_(e_ml_get_cannot_find_line_nr_in_buffer_nr_str),
1970               (int64_t)lnum, buf->b_fnum, NameBuff);
1971        recursive--;
1972      }
1973      goto errorret;
1974    }
1975
1976    DataBlock *dp = hp->bh_data;
1977
1978    int idx = lnum - buf->b_ml.ml_locked_low;
1979    unsigned start = (dp->db_index[idx] & DB_INDEX_MASK);
1980    // The text ends where the previous line starts.  The first line ends
1981    // at the end of the block.
1982    unsigned end = idx == 0 ? dp->db_txt_end : (dp->db_index[idx - 1] & DB_INDEX_MASK);
1983
1984    buf->b_ml.ml_line_ptr = (char *)dp + start;
1985    buf->b_ml.ml_line_textlen = (colnr_T)(end - start);
1986    buf->b_ml.ml_line_lnum = lnum;
1987    buf->b_ml.ml_flags &= ~(ML_LINE_DIRTY | ML_ALLOCATED);
1988  }
1989  if (will_change) {
1990    buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
1991#ifdef ML_GET_ALLOC_LINES
1992    if (buf->b_ml.ml_flags & ML_ALLOCATED) {
1993      // can't make the change in the data block
1994      buf->b_ml.ml_flags |= ML_LINE_DIRTY;
1995    }
1996#endif
1997    ml_add_deleted_len_buf(buf, buf->b_ml.ml_line_ptr, -1);
1998  }
1999
2000#ifdef ML_GET_ALLOC_LINES
2001  if ((buf->b_ml.ml_flags & (ML_LINE_DIRTY | ML_ALLOCATED)) == 0) {
2002    // make sure the text is in allocated memory
2003    buf->b_ml.ml_line_ptr = xmemdup(buf->b_ml.ml_line_ptr,
2004                                    (size_t)buf->b_ml.ml_line_textlen);
2005    buf->b_ml.ml_flags |= ML_ALLOCATED;
2006    if (will_change) {
2007      // can't make the change in the data block
2008      buf->b_ml.ml_flags |= ML_LINE_DIRTY;
2009    }
2010  }
2011#endif
2012  return buf->b_ml.ml_line_ptr;
2013}
2014
2015/// Check if a line that was just obtained by a call to ml_get
2016/// is in allocated memory.
2017/// This ignores ML_ALLOCATED to get the same behavior as without ML_GET_ALLOC_LINES.
2018int ml_line_alloced(void)
2019{
2020  return curbuf->b_ml.ml_flags & ML_LINE_DIRTY;
2021}
2022
2023/// @param lnum  append after this line (can be 0)
2024/// @param line_arg  text of the new line
2025/// @param len_arg  length of line, including NUL, or 0
2026/// @param flags  ML_APPEND_ flags
2027///
2028/// @return  FAIL for failure, OK otherwise
2029static int ml_append_int(buf_T *buf, linenr_T lnum, char *line_arg, colnr_T len_arg, int flags)
2030  FUNC_ATTR_NONNULL_ARG(1)
2031{
2032  char *line = line_arg;
2033  colnr_T len = len_arg;
2034
2035  if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL) {
2036    return FAIL;  // lnum out of range
2037  }
2038
2039  if (lowest_marked && lowest_marked > lnum) {
2040    lowest_marked = lnum + 1;
2041  }
2042
2043  if (len == 0) {
2044    len = (colnr_T)strlen(line) + 1;            // space needed for the text
2045  }
2046  int64_t space_needed = len + (int64_t)INDEX_SIZE;  // space needed for text + index
2047
2048  memfile_T *mfp = buf->b_ml.ml_mfp;
2049  int64_t page_size = mfp->mf_page_size;
2050
2051  // find the data block containing the previous line
2052  // This also fills the stack with the blocks from the root to the data block
2053  // This also releases any locked block.
2054  int ret = FAIL;
2055  bhdr_T *hp;
2056  if ((hp = ml_find_line(buf, lnum == 0 ? 1 : lnum,
2057                         ML_INSERT)) == NULL) {
2058    goto theend;
2059  }
2060
2061  buf->b_ml.ml_flags &= ~ML_EMPTY;
2062
2063  int db_idx;                   // index for lnum in data block
2064  if (lnum == 0) {              // got line one instead, correct db_idx
2065    db_idx = -1;                // careful, it is negative!
2066  } else {
2067    db_idx = lnum - buf->b_ml.ml_locked_low;
2068  }
2069  // get line count (number of indexes in current block) before the insertion
2070  int line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2071
2072  DataBlock *dp = hp->bh_data;
2073
2074  // If
2075  // - there is not enough room in the current block
2076  // - appending to the last line in the block
2077  // - not appending to the last line in the file
2078  // insert in front of the next block.
2079  if ((int64_t)dp->db_free < space_needed && db_idx == line_count - 1
2080      && lnum < buf->b_ml.ml_line_count) {
2081    // Now that the line is not going to be inserted in the block that we
2082    // expected, the line count has to be adjusted in the pointer blocks
2083    // by using ml_locked_lineadd.
2084    (buf->b_ml.ml_locked_lineadd)--;
2085    (buf->b_ml.ml_locked_high)--;
2086    if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL) {
2087      goto theend;
2088    }
2089
2090    db_idx = -1;                    // careful, it is negative!
2091    // get line count before the insertion
2092    line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2093    CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2094
2095    dp = hp->bh_data;
2096  }
2097
2098  if (buf->b_prev_line_count == 0) {
2099    buf->b_prev_line_count = buf->b_ml.ml_line_count;
2100  }
2101  buf->b_ml.ml_line_count++;
2102
2103  if ((int64_t)dp->db_free >= space_needed) {  // enough room in data block
2104    // Insert the new line in an existing data block, or in the data block
2105    // allocated above.
2106    dp->db_txt_start -= (unsigned)len;
2107    dp->db_free -= (unsigned)space_needed;
2108    dp->db_line_count++;
2109
2110    // move the text of the lines that follow to the front
2111    // adjust the indexes of the lines that follow
2112    if (line_count > db_idx + 1) {          // if there are following lines
2113      // Offset is the start of the previous line.
2114      // This will become the character just after the new line.
2115      int offset = db_idx < 0 ? (int)dp->db_txt_end
2116                              : (int)((dp->db_index[db_idx]) & DB_INDEX_MASK);
2117      memmove((char *)dp + dp->db_txt_start,
2118              (char *)dp + dp->db_txt_start + len,
2119              (size_t)offset - (dp->db_txt_start + (size_t)len));
2120      for (int i = line_count - 1; i > db_idx; i--) {
2121        dp->db_index[i + 1] = dp->db_index[i] - (unsigned)len;
2122      }
2123      dp->db_index[db_idx + 1] = (unsigned)(offset - len);
2124    } else {
2125      // add line at the end (which is the start of the text)
2126      dp->db_index[db_idx + 1] = dp->db_txt_start;
2127    }
2128
2129    // copy the text into the block
2130    memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2131    if (flags & ML_APPEND_MARK) {
2132      dp->db_index[db_idx + 1] |= DB_MARKED;
2133    }
2134
2135    // Mark the block dirty.
2136    buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2137    if (!(flags & ML_APPEND_NEW)) {
2138      buf->b_ml.ml_flags |= ML_LOCKED_POS;
2139    }
2140  } else {        // not enough space in data block
2141    int line_count_left, line_count_right;
2142    int page_count_left, page_count_right;
2143    bhdr_T *hp_left;
2144    bhdr_T *hp_right;
2145    bhdr_T *hp_new;
2146    int lines_moved;
2147    int data_moved = 0;                     // init to shut up gcc
2148    int total_moved = 0;                    // init to shut up gcc
2149    int stack_idx;
2150    bool in_left;
2151    linenr_T lnum_left, lnum_right;
2152    PointerBlock *pp_new;
2153
2154    // There is not enough room, we have to create a new data block and
2155    // copy some lines into it.
2156    // Then we have to insert an entry in the pointer block.
2157    // If this pointer block also is full, we go up another block, and so
2158    // on, up to the root if necessary.
2159    // The line counts in the pointer blocks have already been adjusted by
2160    // ml_find_line().
2161    //
2162    // We are going to allocate a new data block. Depending on the
2163    // situation it will be put to the left or right of the existing
2164    // block.  If possible we put the new line in the left block and move
2165    // the lines after it to the right block. Otherwise the new line is
2166    // also put in the right block. This method is more efficient when
2167    // inserting a lot of lines at one place.
2168    if (db_idx < 0) {           // left block is new, right block is existing
2169      lines_moved = 0;
2170      in_left = true;
2171      // space_needed does not change
2172    } else {                  // left block is existing, right block is new
2173      lines_moved = line_count - db_idx - 1;
2174      if (lines_moved == 0) {
2175        in_left = false;                // put new line in right block
2176                                        // space_needed does not change
2177      } else {
2178        data_moved = (int)(((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2179                           dp->db_txt_start);
2180        total_moved = data_moved + lines_moved * (int)INDEX_SIZE;
2181        if ((int64_t)dp->db_free + total_moved >= space_needed) {
2182          in_left = true;               // put new line in left block
2183          space_needed = total_moved;
2184        } else {
2185          in_left = false;                  // put new line in right block
2186          space_needed += total_moved;
2187        }
2188      }
2189    }
2190
2191    int64_t page_count = ((space_needed + (int64_t)HEADER_SIZE) + page_size - 1) / page_size;
2192    hp_new = ml_new_data(mfp, flags & ML_APPEND_NEW, page_count);
2193    if (db_idx < 0) {           // left block is new
2194      hp_left = hp_new;
2195      hp_right = hp;
2196      line_count_left = 0;
2197      line_count_right = line_count;
2198    } else {                  // right block is new
2199      hp_left = hp;
2200      hp_right = hp_new;
2201      line_count_left = line_count;
2202      line_count_right = 0;
2203    }
2204    DataBlock *dp_right = hp_right->bh_data;
2205    DataBlock *dp_left = hp_left->bh_data;
2206    blocknr_T bnum_left = hp_left->bh_bnum;
2207    blocknr_T bnum_right = hp_right->bh_bnum;
2208    page_count_left = (int)hp_left->bh_page_count;
2209    page_count_right = (int)hp_right->bh_page_count;
2210
2211    // May move the new line into the right/new block.
2212    if (!in_left) {
2213      dp_right->db_txt_start -= (unsigned)len;
2214      dp_right->db_free -= (unsigned)len + (unsigned)INDEX_SIZE;
2215      dp_right->db_index[0] = dp_right->db_txt_start;
2216      if (flags & ML_APPEND_MARK) {
2217        dp_right->db_index[0] |= DB_MARKED;
2218      }
2219
2220      memmove((char *)dp_right + dp_right->db_txt_start,
2221              line, (size_t)len);
2222      line_count_right++;
2223    }
2224    // may move lines from the left/old block to the right/new one.
2225    if (lines_moved) {
2226      dp_right->db_txt_start -= (unsigned)data_moved;
2227      dp_right->db_free -= (unsigned)total_moved;
2228      memmove((char *)dp_right + dp_right->db_txt_start,
2229              (char *)dp_left + dp_left->db_txt_start,
2230              (size_t)data_moved);
2231      int offset = (int)(dp_right->db_txt_start - dp_left->db_txt_start);
2232      dp_left->db_txt_start += (unsigned)data_moved;
2233      dp_left->db_free += (unsigned)total_moved;
2234
2235      // update indexes in the new block
2236      for (int to = line_count_right, from = db_idx + 1;
2237           from < line_count_left; from++, to++) {
2238        dp_right->db_index[to] = dp->db_index[from] + (unsigned)offset;
2239      }
2240      line_count_right += lines_moved;
2241      line_count_left -= lines_moved;
2242    }
2243
2244    // May move the new line into the left (old or new) block.
2245    if (in_left) {
2246      dp_left->db_txt_start -= (unsigned)len;
2247      dp_left->db_free -= (unsigned)len + (unsigned)INDEX_SIZE;
2248      dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2249      if (flags & ML_APPEND_MARK) {
2250        dp_left->db_index[line_count_left] |= DB_MARKED;
2251      }
2252      memmove((char *)dp_left + dp_left->db_txt_start,
2253              line, (size_t)len);
2254      line_count_left++;
2255    }
2256
2257    if (db_idx < 0) {           // left block is new
2258      lnum_left = lnum + 1;
2259      lnum_right = 0;
2260    } else {                  // right block is new
2261      lnum_left = 0;
2262      if (in_left) {
2263        lnum_right = lnum + 2;
2264      } else {
2265        lnum_right = lnum + 1;
2266      }
2267    }
2268    dp_left->db_line_count = line_count_left;
2269    dp_right->db_line_count = line_count_right;
2270
2271    // release the two data blocks
2272    // The new one (hp_new) already has a correct blocknumber.
2273    // The old one (hp, in ml_locked) gets a positive blocknumber if
2274    // we changed it and we are not editing a new file.
2275    if (lines_moved || in_left) {
2276      buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2277    }
2278    if (!(flags & ML_APPEND_NEW) && db_idx >= 0 && in_left) {
2279      buf->b_ml.ml_flags |= ML_LOCKED_POS;
2280    }
2281    mf_put(mfp, hp_new, true, false);
2282
2283    // flush the old data block
2284    // set ml_locked_lineadd to 0, because the updating of the
2285    // pointer blocks is done below
2286    int lineadd = buf->b_ml.ml_locked_lineadd;
2287    buf->b_ml.ml_locked_lineadd = 0;
2288    ml_find_line(buf, 0, ML_FLUSH);  // flush data block
2289
2290    // update pointer blocks for the new data block
2291    for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; stack_idx--) {
2292      infoptr_T *ip = &(buf->b_ml.ml_stack[stack_idx]);
2293      int pb_idx = ip->ip_index;
2294      if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL) {
2295        goto theend;
2296      }
2297      PointerBlock *pp = hp->bh_data;         // must be pointer block
2298      if (pp->pb_id != PTR_ID) {
2299        iemsg(_(e_pointer_block_id_wrong_three));
2300        mf_put(mfp, hp, false, false);
2301        goto theend;
2302      }
2303      // TODO(vim): If the pointer block is full and we are adding at the end
2304      // try to insert in front of the next block
2305      // block not full, add one entry
2306      if (pp->pb_count < pp->pb_count_max) {
2307        if (pb_idx + 1 < (int)pp->pb_count) {
2308          memmove(&pp->pb_pointer[pb_idx + 2],
2309                  &pp->pb_pointer[pb_idx + 1],
2310                  (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PointerEntry));
2311        }
2312        pp->pb_count++;
2313        pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2314        pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2315        pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2316        pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2317        pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2318        pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2319
2320        if (lnum_left != 0) {
2321          pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2322        }
2323        if (lnum_right != 0) {
2324          pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2325        }
2326
2327        mf_put(mfp, hp, true, false);
2328        buf->b_ml.ml_stack_top = stack_idx + 1;             // truncate stack
2329
2330        if (lineadd) {
2331          (buf->b_ml.ml_stack_top)--;
2332          // fix line count for rest of blocks in the stack
2333          ml_lineadd(buf, lineadd);
2334          // fix stack itself
2335          buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high += lineadd;
2336          (buf->b_ml.ml_stack_top)++;
2337        }
2338
2339        // We are finished, break the loop here.
2340        break;
2341      }
2342      // pointer block full
2343      //
2344      // split the pointer block
2345      // allocate a new pointer block
2346      // move some of the pointer into the new block
2347      // prepare for updating the parent block
2348      while (true) {          // do this twice when splitting block 1
2349        hp_new = ml_new_ptr(mfp);
2350        if (hp_new == NULL) {             // TODO(vim): try to fix tree
2351          goto theend;
2352        }
2353        pp_new = hp_new->bh_data;
2354
2355        if (hp->bh_bnum != 1) {
2356          break;
2357        }
2358
2359        // if block 1 becomes full the tree is given an extra level
2360        // The pointers from block 1 are moved into the new block.
2361        // block 1 is updated to point to the new block
2362        // then continue to split the new block
2363        memmove(pp_new, pp, (size_t)page_size);
2364        pp->pb_count = 1;
2365        pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2366        pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2367        pp->pb_pointer[0].pe_old_lnum = 1;
2368        pp->pb_pointer[0].pe_page_count = 1;
2369        mf_put(mfp, hp, true, false);             // release block 1
2370        hp = hp_new;                          // new block is to be split
2371        pp = pp_new;
2372        CHECK(stack_idx != 0, _("stack_idx should be 0"));
2373        ip->ip_index = 0;
2374        stack_idx++;                  // do block 1 again later
2375      }
2376      // move the pointers after the current one to the new block
2377      // If there are none, the new entry will be in the new block.
2378      total_moved = pp->pb_count - pb_idx - 1;
2379      if (total_moved) {
2380        memmove(&pp_new->pb_pointer[0],
2381                &pp->pb_pointer[pb_idx + 1],
2382                (size_t)total_moved * sizeof(PointerEntry));
2383        pp_new->pb_count = (uint16_t)total_moved;
2384        pp->pb_count = (uint16_t)(pp->pb_count - (total_moved - 1));
2385        pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2386        pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2387        pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2388        if (lnum_right) {
2389          pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2390        }
2391      } else {
2392        pp_new->pb_count = 1;
2393        pp_new->pb_pointer[0].pe_bnum = bnum_right;
2394        pp_new->pb_pointer[0].pe_line_count = line_count_right;
2395        pp_new->pb_pointer[0].pe_page_count = page_count_right;
2396        pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
2397      }
2398      pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2399      pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2400      pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2401      if (lnum_left) {
2402        pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2403      }
2404      lnum_left = 0;
2405      lnum_right = 0;
2406
2407      // recompute line counts
2408      line_count_right = 0;
2409      for (int i = 0; i < (int)pp_new->pb_count; i++) {
2410        line_count_right += pp_new->pb_pointer[i].pe_line_count;
2411      }
2412      line_count_left = 0;
2413      for (int i = 0; i < (int)pp->pb_count; i++) {
2414        line_count_left += pp->pb_pointer[i].pe_line_count;
2415      }
2416
2417      bnum_left = hp->bh_bnum;
2418      bnum_right = hp_new->bh_bnum;
2419      page_count_left = 1;
2420      page_count_right = 1;
2421      mf_put(mfp, hp, true, false);
2422      mf_put(mfp, hp_new, true, false);
2423    }
2424
2425    // Safety check: fallen out of for loop?
2426    if (stack_idx < 0) {
2427      iemsg(_("E318: Updated too many blocks?"));
2428      buf->b_ml.ml_stack_top = 0;       // invalidate stack
2429    }
2430  }
2431
2432  // The line was inserted below 'lnum'
2433  ml_updatechunk(buf, lnum + 1, len, ML_CHNK_ADDLINE);
2434  ret = OK;
2435
2436theend:
2437  return ret;
2438}
2439
2440/// Flush any pending change and call ml_append_int()
2441///
2442/// @param buf
2443/// @param lnum  append after this line (can be 0)
2444/// @param line  text of the new line
2445/// @param len  length of line, including NUL, or 0
2446/// @param flags  ML_APPEND_ flags
2447///
2448/// @return  FAIL for failure, OK otherwise
2449static int ml_append_flush(buf_T *buf, linenr_T lnum, char *line, colnr_T len, int flags)
2450  FUNC_ATTR_NONNULL_ARG(1)
2451{
2452  if (lnum > buf->b_ml.ml_line_count) {
2453    return FAIL;  // lnum out of range
2454  }
2455  if (buf->b_ml.ml_line_lnum != 0) {
2456    // This may also invoke ml_append_int().
2457    ml_flush_line(buf, false);
2458  }
2459
2460  return ml_append_int(buf, lnum, line, len, flags);
2461}
2462
2463/// Append a line after lnum (may be 0 to insert a line in front of the file).
2464/// "line" does not need to be allocated, but can't be another line in a
2465/// buffer, unlocking may make it invalid.
2466///
2467/// "newfile": true when starting to edit a new file, meaning that pe_old_lnum
2468///              will be set for recovery
2469/// Check: The caller of this function should probably also call
2470/// appended_lines().
2471///
2472/// @param lnum  append after this line (can be 0)
2473/// @param line  text of the new line
2474/// @param len  length of new line, including NUL, or 0
2475/// @param newfile  flag, see above
2476///
2477/// @return  FAIL for failure, OK otherwise
2478int ml_append(linenr_T lnum, char *line, colnr_T len, bool newfile)
2479{
2480  return ml_append_flags(lnum, line, len, newfile ? ML_APPEND_NEW : 0);
2481}
2482
2483/// @param lnum  append after this line (can be 0)
2484/// @param line  text of the new line
2485/// @param len  length of new line, including nul, or 0
2486/// @param flags  ML_APPEND_ values
2487///
2488/// @return  FAIL for failure, OK otherwise
2489int ml_append_flags(linenr_T lnum, char *line, colnr_T len, int flags)
2490{
2491  // When starting up, we might still need to create the memfile
2492  if (curbuf->b_ml.ml_mfp == NULL && open_buffer(false, NULL, 0) == FAIL) {
2493    return FAIL;
2494  }
2495
2496  return ml_append_flush(curbuf, lnum, line, len, flags);
2497}
2498
2499/// Like ml_append() but for an arbitrary buffer.  The buffer must already have
2500/// a memline.
2501///
2502/// @param lnum  append after this line (can be 0)
2503/// @param line  text of the new line
2504/// @param len  length of new line, including NUL, or 0
2505/// @param newfile  flag, see above
2506int ml_append_buf(buf_T *buf, linenr_T lnum, char *line, colnr_T len, bool newfile)
2507  FUNC_ATTR_NONNULL_ARG(1)
2508{
2509  if (buf->b_ml.ml_mfp == NULL) {
2510    return FAIL;
2511  }
2512
2513  return ml_append_flush(buf, lnum, line, len, newfile ? ML_APPEND_NEW : 0);
2514}
2515
2516void ml_add_deleted_len(char *ptr, ssize_t len)
2517{
2518  ml_add_deleted_len_buf(curbuf, ptr, len);
2519}
2520
2521void ml_add_deleted_len_buf(buf_T *buf, char *ptr, ssize_t len)
2522{
2523  if (inhibit_delete_count) {
2524    return;
2525  }
2526  ssize_t maxlen = (ssize_t)strlen(ptr);
2527  if (len == -1 || len > maxlen) {
2528    len = maxlen;
2529  }
2530  buf->deleted_bytes += (size_t)len + 1;
2531  buf->deleted_bytes2 += (size_t)len + 1;
2532  if (buf->update_need_codepoints) {
2533    mb_utflen(ptr, (size_t)len, &buf->deleted_codepoints,
2534              &buf->deleted_codeunits);
2535    buf->deleted_codepoints++;  // NL char
2536    buf->deleted_codeunits++;
2537  }
2538}
2539
2540/// Replace line "lnum", with buffering, in current buffer.
2541int ml_replace(linenr_T lnum, char *line, bool copy)
2542{
2543  return ml_replace_buf(curbuf, lnum, line, copy, false);
2544}
2545
2546/// Replace a line for the current buffer.  Like ml_replace() with:
2547/// "len" is the length of the text, excluding NUL.
2548int ml_replace_len(linenr_T lnum, char *line, size_t len, bool copy)
2549{
2550  return ml_replace_buf_len(curbuf, lnum, line, len, copy, false);
2551}
2552
2553int ml_replace_buf(buf_T *buf, linenr_T lnum, char *line, bool copy, bool noalloc)
2554  FUNC_ATTR_NONNULL_ARG(1)
2555{
2556  size_t len = line != NULL ? strlen(line) : (size_t)-1;
2557  return ml_replace_buf_len(buf, lnum, line, len, copy, noalloc);
2558}
2559
2560/// Replace line "lnum", with buffering.
2561///
2562/// @param copy  if true, make a copy of the line, otherwise the line has been
2563///              copied to allocated memory already.
2564///              if false, the "line" may be freed to add text properties!
2565/// @param len_arg  length of the text, excluding NUL
2566///
2567/// Do not use it after calling ml_replace().
2568///
2569/// Check: The caller of this function should probably also call
2570/// changed_lines(), unless update_screen(UPD_NOT_VALID) is used.
2571///
2572/// @return  FAIL for failure, OK otherwise
2573int ml_replace_buf_len(buf_T *buf, linenr_T lnum, char *line_arg, size_t len_arg, bool copy,
2574                       bool noalloc)
2575  FUNC_ATTR_NONNULL_ARG(1)
2576{
2577  char *line = line_arg;
2578
2579  if (line == NULL) {           // just checking...
2580    return FAIL;
2581  }
2582
2583  // When starting up, we might still need to create the memfile
2584  if (buf->b_ml.ml_mfp == NULL && open_buffer(false, NULL, 0) == FAIL) {
2585    return FAIL;
2586  }
2587
2588  if (copy) {
2589    assert(!noalloc);
2590    line = xmemdupz(line, len_arg);
2591  }
2592
2593  if (buf->b_ml.ml_line_lnum != lnum) {
2594    // another line is buffered, flush it
2595    ml_flush_line(buf, false);
2596  }
2597
2598  if (kv_size(buf->update_callbacks)) {
2599    ml_add_deleted_len_buf(buf, ml_get_buf(buf, lnum), -1);
2600  }
2601
2602  if (buf->b_ml.ml_flags & (ML_LINE_DIRTY | ML_ALLOCATED)) {
2603    xfree(buf->b_ml.ml_line_ptr);  // free allocated line
2604  }
2605
2606  buf->b_ml.ml_line_ptr = line;
2607  buf->b_ml.ml_line_textlen = (colnr_T)len_arg + 1;
2608  buf->b_ml.ml_line_lnum = lnum;
2609  buf->b_ml.ml_flags = (buf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
2610  if (noalloc) {
2611    // TODO(bfredl): this is a bit of a hack. but replacing lines in a loop is really common,
2612    // and allocating a separate scratch buffer for each line which is immediately freed adds
2613    // a lot of noise. A more general refactor could be to use a _fixed_ scratch buffer for
2614    // all lines up to $REASONABLE_SIZE .
2615    ml_flush_line(buf, true);
2616  }
2617
2618  return OK;
2619}
2620
2621/// Delete line `lnum` in buffer
2622///
2623/// @note The caller of this function should probably also call changed_lines() after this.
2624///
2625/// @param message  Show "--No lines in buffer--" message.
2626///
2627/// @return  FAIL for failure, OK otherwise
2628int ml_delete_buf(buf_T *buf, linenr_T lnum, bool message)
2629  FUNC_ATTR_NONNULL_ALL
2630{
2631  ml_flush_line(buf, false);
2632  return ml_delete_int(buf, lnum, message ? ML_DEL_MESSAGE : 0);
2633}
2634
2635/// Delete line `lnum` in the current buffer.
2636///
2637/// @param flags  ML_DEL_MESSAGE may give a "No lines in buffer" message.
2638///               ML_DEL_UNDO this is called from undo.
2639///
2640/// @return  FAIL for failure, OK otherwise
2641static int ml_delete_int(buf_T *buf, linenr_T lnum, int flags)
2642  FUNC_ATTR_NONNULL_ALL
2643{
2644  if (lowest_marked && lowest_marked > lnum) {
2645    lowest_marked--;
2646  }
2647
2648  // If the file becomes empty the last line is replaced by an empty line.
2649  if (buf->b_ml.ml_line_count == 1) {       // file becomes empty
2650    if (flags & ML_DEL_MESSAGE) {
2651      set_keep_msg(_(no_lines_msg), 0);
2652    }
2653
2654    int i = ml_replace_buf(buf, 1, "", true, false);
2655    buf->b_ml.ml_flags |= ML_EMPTY;
2656
2657    return i;
2658  }
2659
2660  // Find the data block containing the line.
2661  // This also fills the stack with the blocks from the root to the data block.
2662  // This also releases any locked block.
2663  memfile_T *mfp = buf->b_ml.ml_mfp;
2664  if (mfp == NULL) {
2665    return FAIL;
2666  }
2667
2668  bhdr_T *hp;
2669  if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL) {
2670    return FAIL;
2671  }
2672
2673  DataBlock *dp = hp->bh_data;
2674  // compute line count (number of entries in block) before the delete
2675  int count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 2;
2676  int idx = lnum - buf->b_ml.ml_locked_low;
2677
2678  if (buf->b_prev_line_count == 0) {
2679    buf->b_prev_line_count = buf->b_ml.ml_line_count;
2680  }
2681  buf->b_ml.ml_line_count--;
2682
2683  int line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
2684  int line_size;
2685  if (idx == 0) {               // first line in block, text at the end
2686    line_size = (int)(dp->db_txt_end - (unsigned)line_start);
2687  } else {
2688    line_size = (int)(((dp->db_index[idx - 1]) & DB_INDEX_MASK) - (unsigned)line_start);
2689  }
2690
2691  // Line should always have an NL char internally (represented as NUL),
2692  // even if 'noeol' is set.
2693  assert(line_size >= 1);
2694  ml_add_deleted_len_buf(buf, (char *)dp + line_start, line_size - 1);
2695
2696  // special case: If there is only one line in the data block it becomes empty.
2697  // Then we have to remove the entry, pointing to this data block, from the
2698  // pointer block. If this pointer block also becomes empty, we go up another
2699  // block, and so on, up to the root if necessary.
2700  // The line counts in the pointer blocks have already been adjusted by
2701  // ml_find_line().
2702  int ret = FAIL;
2703  if (count == 1) {
2704    mf_free(mfp, hp);           // free the data block
2705    buf->b_ml.ml_locked = NULL;
2706
2707    for (int stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0; stack_idx--) {
2708      buf->b_ml.ml_stack_top = 0;           // stack is invalid when failing
2709      infoptr_T *ip = &(buf->b_ml.ml_stack[stack_idx]);
2710      idx = ip->ip_index;
2711      if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL) {
2712        goto theend;
2713      }
2714      PointerBlock *pp = hp->bh_data;         // must be pointer block
2715      if (pp->pb_id != PTR_ID) {
2716        iemsg(_(e_pointer_block_id_wrong_four));
2717        mf_put(mfp, hp, false, false);
2718        goto theend;
2719      }
2720      count = --(pp->pb_count);
2721      if (count == 0) {             // the pointer block becomes empty!
2722        mf_free(mfp, hp);
2723      } else {
2724        if (count != idx) {             // move entries after the deleted one
2725          memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
2726                  (size_t)(count - idx) * sizeof(PointerEntry));
2727        }
2728        mf_put(mfp, hp, true, false);
2729
2730        buf->b_ml.ml_stack_top = stack_idx;             // truncate stack
2731        // fix line count for rest of blocks in the stack
2732        if (buf->b_ml.ml_locked_lineadd != 0) {
2733          ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
2734          buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2735            buf->b_ml.ml_locked_lineadd;
2736        }
2737        (buf->b_ml.ml_stack_top)++;
2738
2739        break;
2740      }
2741    }
2742    CHECK(stack_idx < 0, _("deleted block 1?"));
2743  } else {
2744    // delete the text by moving the next lines forwards
2745    int text_start = (int)dp->db_txt_start;
2746    memmove((char *)dp + text_start + line_size,
2747            (char *)dp + text_start, (size_t)(line_start - text_start));
2748
2749    // delete the index by moving the next indexes backwards
2750    // Adjust the indexes for the text movement.
2751    for (int i = idx; i < count - 1; i++) {
2752      dp->db_index[i] = dp->db_index[i + 1] + (unsigned)line_size;
2753    }
2754
2755    dp->db_free += (unsigned)line_size + (unsigned)INDEX_SIZE;
2756    dp->db_txt_start += (unsigned)line_size;
2757    dp->db_line_count--;
2758
2759    // mark the block dirty and make sure it is in the file (for recovery)
2760    buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2761  }
2762
2763  ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
2764  ret = OK;
2765
2766theend:
2767  return ret;
2768}
2769
2770/// Delete line "lnum" in the current buffer.
2771///
2772/// @note The caller of this function should probably also call
2773/// deleted_lines() after this.
2774///
2775/// @return  FAIL for failure, OK otherwise
2776int ml_delete(linenr_T lnum)
2777{
2778  return ml_delete_flags(lnum, 0);
2779}
2780
2781/// Like ml_delete() but using flags (see ml_delete_int()).
2782///
2783/// @return  FAIL for failure, OK otherwise
2784int ml_delete_flags(linenr_T lnum, int flags)
2785{
2786  ml_flush_line(curbuf, false);
2787  if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) {
2788    return FAIL;
2789  }
2790
2791  return ml_delete_int(curbuf, lnum, flags);
2792}
2793
2794/// set the DB_MARKED flag for line 'lnum'
2795void ml_setmarked(linenr_T lnum)
2796{
2797  // invalid line number
2798  if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
2799      || curbuf->b_ml.ml_mfp == NULL) {
2800    return;                         // give error message?
2801  }
2802  if (lowest_marked == 0 || lowest_marked > lnum) {
2803    lowest_marked = lnum;
2804  }
2805
2806  // find the data block containing the line
2807  // This also fills the stack with the blocks from the root to the data block
2808  // This also releases any locked block.
2809  bhdr_T *hp;
2810  if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) {
2811    return;                 // give error message?
2812  }
2813  DataBlock *dp = hp->bh_data;
2814  dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
2815  curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2816}
2817
2818/// find the first line with its DB_MARKED flag set
2819linenr_T ml_firstmarked(void)
2820{
2821  if (curbuf->b_ml.ml_mfp == NULL) {
2822    return 0;
2823  }
2824
2825  // The search starts with lowest_marked line. This is the last line where
2826  // a mark was found, adjusted by inserting/deleting lines.
2827  for (linenr_T lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count;) {
2828    // Find the data block containing the line.
2829    // This also fills the stack with the blocks from the root to the data
2830    // block This also releases any locked block.
2831    bhdr_T *hp;
2832    if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) {
2833      return 0;                   // give error message?
2834    }
2835    DataBlock *dp = hp->bh_data;
2836
2837    for (int i = lnum - curbuf->b_ml.ml_locked_low;
2838         lnum <= curbuf->b_ml.ml_locked_high; i++, lnum++) {
2839      if ((dp->db_index[i]) & DB_MARKED) {
2840        (dp->db_index[i]) &= DB_INDEX_MASK;
2841        curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2842        lowest_marked = lnum + 1;
2843        return lnum;
2844      }
2845    }
2846  }
2847
2848  return 0;
2849}
2850
2851/// clear all DB_MARKED flags
2852void ml_clearmarked(void)
2853{
2854  if (curbuf->b_ml.ml_mfp == NULL) {        // nothing to do
2855    return;
2856  }
2857
2858  // The search starts with line lowest_marked.
2859  for (linenr_T lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count;) {
2860    // Find the data block containing the line.
2861    // This also fills the stack with the blocks from the root to the data
2862    // block and releases any locked block.
2863    bhdr_T *hp;
2864    if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL) {
2865      return;                   // give error message?
2866    }
2867    DataBlock *dp = hp->bh_data;
2868
2869    for (int i = lnum - curbuf->b_ml.ml_locked_low;
2870         lnum <= curbuf->b_ml.ml_locked_high; i++, lnum++) {
2871      if ((dp->db_index[i]) & DB_MARKED) {
2872        (dp->db_index[i]) &= DB_INDEX_MASK;
2873        curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2874      }
2875    }
2876  }
2877
2878  lowest_marked = 0;
2879}
2880
2881size_t ml_flush_deleted_bytes(buf_T *buf, size_t *codepoints, size_t *codeunits)
2882{
2883  size_t ret = buf->deleted_bytes;
2884  *codepoints = buf->deleted_codepoints;
2885  *codeunits = buf->deleted_codeunits;
2886  buf->deleted_bytes = 0;
2887  buf->deleted_codepoints = 0;
2888  buf->deleted_codeunits = 0;
2889  return ret;
2890}
2891
2892/// flush ml_line if necessary
2893static void ml_flush_line(buf_T *buf, bool noalloc)
2894{
2895  static bool entered = false;
2896
2897  if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL) {
2898    return;             // nothing to do
2899  }
2900  if (buf->b_ml.ml_flags & ML_LINE_DIRTY) {
2901    // This code doesn't work recursively.
2902    if (entered) {
2903      return;
2904    }
2905    entered = true;
2906
2907    buf->flush_count++;
2908
2909    linenr_T lnum = buf->b_ml.ml_line_lnum;
2910    char *new_line = buf->b_ml.ml_line_ptr;
2911
2912    bhdr_T *hp = ml_find_line(buf, lnum, ML_FIND);
2913    if (hp == NULL) {
2914      siemsg(_("E320: Cannot find line %" PRId64), (int64_t)lnum);
2915    } else {
2916      DataBlock *dp = hp->bh_data;
2917      int idx = lnum - buf->b_ml.ml_locked_low;
2918      int start = ((dp->db_index[idx]) & DB_INDEX_MASK);
2919      char *old_line = (char *)dp + start;
2920      int old_len;
2921      if (idx == 0) {           // line is last in block
2922        old_len = (int)dp->db_txt_end - start;
2923      } else {  // text of previous line follows
2924        old_len = (int)(dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
2925      }
2926      colnr_T new_len = buf->b_ml.ml_line_textlen;
2927      int extra = new_len - old_len;            // negative if lines gets smaller
2928
2929      // if new line fits in data block, replace directly
2930      if ((int)dp->db_free >= extra) {
2931        // if the length changes and there are following lines
2932        int count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
2933        if (extra != 0 && idx < count - 1) {
2934          // move text of following lines
2935          memmove((char *)dp + dp->db_txt_start - extra,
2936                  (char *)dp + dp->db_txt_start,
2937                  (size_t)(start - (int)dp->db_txt_start));
2938
2939          // adjust pointers of this and following lines
2940          for (int i = idx + 1; i < count; i++) {
2941            dp->db_index[i] -= (unsigned)extra;
2942          }
2943        }
2944        dp->db_index[idx] -= (unsigned)extra;
2945
2946        // adjust free space
2947        dp->db_free -= (unsigned)extra;
2948        dp->db_txt_start -= (unsigned)extra;
2949
2950        // copy new line into the data block
2951        memmove(old_line - extra, new_line, (size_t)new_len);
2952        buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2953        // The else case is already covered by the insert and delete
2954        if (extra != 0) {
2955          ml_updatechunk(buf, lnum, extra, ML_CHNK_UPDLINE);
2956        }
2957      } else {
2958        // Cannot do it in one data block: Delete and append.
2959        // Append first, because ml_delete_int() cannot delete the
2960        // last line in a buffer, which causes trouble for a buffer
2961        // that has only one line.
2962        // Don't forget to copy the mark!
2963        // How about handling errors???
2964        (void)ml_append_int(buf, lnum, new_line, new_len,
2965                            (dp->db_index[idx] & DB_MARKED) ? ML_APPEND_MARK : 0);
2966        (void)ml_delete_int(buf, lnum, 0);
2967      }
2968    }
2969    if (!noalloc) {
2970      xfree(new_line);
2971    }
2972
2973    entered = false;
2974  } else if (buf->b_ml.ml_flags & ML_ALLOCATED) {
2975    assert(!noalloc);  // caller must set ML_LINE_DIRTY with noalloc, handled above
2976    xfree(buf->b_ml.ml_line_ptr);
2977  }
2978
2979  buf->b_ml.ml_flags &= ~(ML_LINE_DIRTY | ML_ALLOCATED);
2980  buf->b_ml.ml_line_lnum = 0;
2981  buf->b_ml.ml_line_offset = 0;
2982}
2983
2984/// create a new, empty, data block
2985static bhdr_T *ml_new_data(memfile_T *mfp, bool negative, int64_t page_count)
2986{
2987  assert(page_count >= 0);
2988  bhdr_T *hp = mf_new(mfp, negative, (unsigned)page_count);
2989  DataBlock *dp = hp->bh_data;
2990  dp->db_id = DATA_ID;
2991  dp->db_txt_start = dp->db_txt_end = (unsigned)page_count * mfp->mf_page_size;
2992  dp->db_free = dp->db_txt_start - (unsigned)HEADER_SIZE;
2993  dp->db_line_count = 0;
2994
2995  return hp;
2996}
2997
2998/// create a new, empty, pointer block
2999static bhdr_T *ml_new_ptr(memfile_T *mfp)
3000{
3001  bhdr_T *hp = mf_new(mfp, false, 1);
3002  PointerBlock *pp = hp->bh_data;
3003  pp->pb_id = PTR_ID;
3004  pp->pb_count = 0;
3005  pp->pb_count_max = PB_COUNT_MAX(mfp);
3006
3007  return hp;
3008}
3009
3010/// Lookup line 'lnum' in a memline.
3011///
3012/// @param action: if ML_DELETE or ML_INSERT the line count is updated while searching
3013///                if ML_FLUSH only flush a locked block
3014///                if ML_FIND just find the line
3015///
3016/// If the block was found it is locked and put in ml_locked.
3017/// The stack is updated to lead to the locked block. The ip_high field in
3018/// the stack is updated to reflect the last line in the block AFTER the
3019/// insert or delete, also if the pointer block has not been updated yet. But
3020/// if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
3021///
3022/// @return  NULL for failure, pointer to block header otherwise
3023static bhdr_T *ml_find_line(buf_T *buf, linenr_T lnum, int action)
3024{
3025  bhdr_T *hp;
3026  int top;
3027
3028  memfile_T *mfp = buf->b_ml.ml_mfp;
3029
3030  // If there is a locked block check if the wanted line is in it.
3031  // If not, flush and release the locked block.
3032  // Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3033  // Don't do this for ML_FLUSH, because we want to flush the locked block.
3034  // Don't do this when 'swapfile' is reset, we want to load all the blocks.
3035  if (buf->b_ml.ml_locked) {
3036    if (ML_SIMPLE(action)
3037        && buf->b_ml.ml_locked_low <= lnum
3038        && buf->b_ml.ml_locked_high >= lnum) {
3039      // remember to update pointer blocks and stack later
3040      if (action == ML_INSERT) {
3041        (buf->b_ml.ml_locked_lineadd)++;
3042        (buf->b_ml.ml_locked_high)++;
3043      } else if (action == ML_DELETE) {
3044        (buf->b_ml.ml_locked_lineadd)--;
3045        (buf->b_ml.ml_locked_high)--;
3046      }
3047      return buf->b_ml.ml_locked;
3048    }
3049
3050    mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3051           buf->b_ml.ml_flags & ML_LOCKED_POS);
3052    buf->b_ml.ml_locked = NULL;
3053
3054    // If lines have been added or deleted in the locked block, need to
3055    // update the line count in pointer blocks.
3056    if (buf->b_ml.ml_locked_lineadd != 0) {
3057      ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3058    }
3059  }
3060
3061  if (action == ML_FLUSH) {         // nothing else to do
3062    return NULL;
3063  }
3064
3065  blocknr_T bnum = 1;                         // start at the root of the tree
3066  blocknr_T bnum2;
3067  int page_count = 1;
3068  linenr_T low = 1;
3069  linenr_T high = buf->b_ml.ml_line_count;
3070
3071  if (action == ML_FIND) {      // first try stack entries
3072    for (top = buf->b_ml.ml_stack_top - 1; top >= 0; top--) {
3073      infoptr_T *ip = &(buf->b_ml.ml_stack[top]);
3074      if (ip->ip_low <= lnum && ip->ip_high >= lnum) {
3075        bnum = ip->ip_bnum;
3076        low = ip->ip_low;
3077        high = ip->ip_high;
3078        buf->b_ml.ml_stack_top = top;           // truncate stack at prev entry
3079        break;
3080      }
3081    }
3082    if (top < 0) {
3083      buf->b_ml.ml_stack_top = 0;               // not found, start at the root
3084    }
3085  } else {  // ML_DELETE or ML_INSERT
3086    buf->b_ml.ml_stack_top = 0;         // start at the root
3087  }
3088  // search downwards in the tree until a data block is found
3089  while (true) {
3090    if ((hp = mf_get(mfp, bnum, (unsigned)page_count)) == NULL) {
3091      goto error_noblock;
3092    }
3093
3094    // update high for insert/delete
3095    if (action == ML_INSERT) {
3096      high++;
3097    } else if (action == ML_DELETE) {
3098      high--;
3099    }
3100
3101    DataBlock *dp = hp->bh_data;
3102    if (dp->db_id == DATA_ID) {         // data block
3103      buf->b_ml.ml_locked = hp;
3104      buf->b_ml.ml_locked_low = low;
3105      buf->b_ml.ml_locked_high = high;
3106      buf->b_ml.ml_locked_lineadd = 0;
3107      buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3108      return hp;
3109    }
3110
3111    PointerBlock *pp = (PointerBlock *)dp;                // must be pointer block
3112    if (pp->pb_id != PTR_ID) {
3113      iemsg(_(e_pointer_block_id_wrong));
3114      goto error_block;
3115    }
3116
3117    top = ml_add_stack(buf);  // add new entry to stack
3118    infoptr_T *ip = &(buf->b_ml.ml_stack[top]);
3119    ip->ip_bnum = bnum;
3120    ip->ip_low = low;
3121    ip->ip_high = high;
3122    ip->ip_index = -1;                  // index not known yet
3123
3124    bool dirty = false;
3125    int idx;
3126    for (idx = 0; idx < (int)pp->pb_count; idx++) {
3127      linenr_T t = pp->pb_pointer[idx].pe_line_count;
3128      CHECK(t == 0, _("pe_line_count is zero"));
3129      if ((low += t) > lnum) {
3130        ip->ip_index = idx;
3131        bnum = pp->pb_pointer[idx].pe_bnum;
3132        page_count = pp->pb_pointer[idx].pe_page_count;
3133        high = low - 1;
3134        low -= t;
3135
3136        // a negative block number may have been changed
3137        if (bnum < 0) {
3138          bnum2 = mf_trans_del(mfp, bnum);
3139          if (bnum != bnum2) {
3140            bnum = bnum2;
3141            pp->pb_pointer[idx].pe_bnum = bnum;
3142            dirty = true;
3143          }
3144        }
3145
3146        break;
3147      }
3148    }
3149    if (idx >= (int)pp->pb_count) {         // past the end: something wrong!
3150      if (lnum > buf->b_ml.ml_line_count) {
3151        siemsg(_(e_line_number_out_of_range_nr_past_the_end),
3152               (int64_t)lnum - buf->b_ml.ml_line_count);
3153      } else {
3154        siemsg(_(e_line_count_wrong_in_block_nr), bnum);
3155      }
3156      goto error_block;
3157    }
3158    if (action == ML_DELETE) {
3159      pp->pb_pointer[idx].pe_line_count--;
3160      dirty = true;
3161    } else if (action == ML_INSERT) {
3162      pp->pb_pointer[idx].pe_line_count++;
3163      dirty = true;
3164    }
3165    mf_put(mfp, hp, dirty, false);
3166  }
3167
3168error_block:
3169  mf_put(mfp, hp, false, false);
3170error_noblock:
3171  // If action is ML_DELETE or ML_INSERT we have to correct the tree for
3172  // the incremented/decremented line counts, because there won't be a line
3173  // inserted/deleted after all.
3174  if (action == ML_DELETE) {
3175    ml_lineadd(buf, 1);
3176  } else if (action == ML_INSERT) {
3177    ml_lineadd(buf, -1);
3178  }
3179  buf->b_ml.ml_stack_top = 0;
3180  return NULL;
3181}
3182
3183/// add an entry to the info pointer stack
3184///
3185/// @return  number of the new entry
3186static int ml_add_stack(buf_T *buf)
3187{
3188  int top = buf->b_ml.ml_stack_top;
3189
3190  // may have to increase the stack size
3191  if (top == buf->b_ml.ml_stack_size) {
3192    CHECK(top > 0, _("Stack size increases"));     // more than 5 levels???
3193
3194    buf->b_ml.ml_stack_size += STACK_INCR;
3195    size_t new_size = sizeof(infoptr_T) * (size_t)buf->b_ml.ml_stack_size;
3196    buf->b_ml.ml_stack = xrealloc(buf->b_ml.ml_stack, new_size);
3197  }
3198
3199  buf->b_ml.ml_stack_top++;
3200  return top;
3201}
3202
3203/// Update the pointer blocks on the stack for inserted/deleted lines.
3204/// The stack itself is also updated.
3205///
3206/// When an insert/delete line action fails, the line is not inserted/deleted,
3207/// but the pointer blocks have already been updated. That is fixed here by
3208/// walking through the stack.
3209///
3210/// Count is the number of lines added, negative if lines have been deleted.
3211static void ml_lineadd(buf_T *buf, int count)
3212{
3213  memfile_T *mfp = buf->b_ml.ml_mfp;
3214
3215  for (int idx = buf->b_ml.ml_stack_top - 1; idx >= 0; idx--) {
3216    infoptr_T *ip = &(buf->b_ml.ml_stack[idx]);
3217    bhdr_T *hp;
3218    if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL) {
3219      break;
3220    }
3221    PointerBlock *pp = hp->bh_data;       // must be pointer block
3222    if (pp->pb_id != PTR_ID) {
3223      mf_put(mfp, hp, false, false);
3224      iemsg(_(e_pointer_block_id_wrong_two));
3225      break;
3226    }
3227    pp->pb_pointer[ip->ip_index].pe_line_count += count;
3228    ip->ip_high += count;
3229    mf_put(mfp, hp, true, false);
3230  }
3231}
3232
3233#ifdef HAVE_READLINK
3234
3235/// Resolve a symlink in the last component of a file name.
3236/// Note that f_resolve() does it for every part of the path, we don't do that
3237/// here.
3238///
3239/// @return  OK if it worked and the resolved link in "buf[MAXPATHL]",
3240///          FAIL otherwise
3241int resolve_symlink(const char *fname, char *buf)
3242{
3243  char tmp[MAXPATHL];
3244  int depth = 0;
3245
3246  if (fname == NULL) {
3247    return FAIL;
3248  }
3249
3250  // Put the result so far in tmp[], starting with the original name.
3251  xstrlcpy(tmp, fname, MAXPATHL);
3252
3253  while (true) {
3254    // Limit symlink depth to 100, catch recursive loops.
3255    if (++depth == 100) {
3256      semsg(_("E773: Symlink loop for \"%s\""), fname);
3257      return FAIL;
3258    }
3259
3260    int ret = (int)readlink(tmp, buf, MAXPATHL - 1);
3261    if (ret <= 0) {
3262      if (errno == EINVAL || errno == ENOENT) {
3263        // Found non-symlink or not existing file, stop here.
3264        // When at the first level use the unmodified name, skip the
3265        // call to vim_FullName().
3266        if (depth == 1) {
3267          return FAIL;
3268        }
3269
3270        // Use the resolved name in tmp[].
3271        break;
3272      }
3273
3274      // There must be some error reading links, use original name.
3275      return FAIL;
3276    }
3277    buf[ret] = NUL;
3278
3279    // Check whether the symlink is relative or absolute.
3280    // If it's relative, build a new path based on the directory
3281    // portion of the filename (if any) and the path the symlink
3282    // points to.
3283    if (path_is_absolute(buf)) {
3284      STRCPY(tmp, buf);
3285    } else {
3286      char *tail = path_tail(tmp);
3287      if (strlen(tail) + strlen(buf) >= MAXPATHL) {
3288        return FAIL;
3289      }
3290      STRCPY(tail, buf);
3291    }
3292  }
3293
3294  // Try to resolve the full name of the file so that the swapfile name will
3295  // be consistent even when opening a relative symlink from different
3296  // working directories.
3297  return vim_FullName(tmp, buf, MAXPATHL, true);
3298}
3299#endif
3300
3301/// Make swapfile name out of the file name and a directory name.
3302///
3303/// @return  pointer to allocated memory or NULL.
3304char *makeswapname(char *fname, char *ffname, buf_T *buf, char *dir_name)
3305{
3306  char *fname_res = fname;
3307#ifdef HAVE_READLINK
3308  char fname_buf[MAXPATHL];
3309
3310  // Expand symlink in the file name, so that we put the swapfile with the
3311  // actual file instead of with the symlink.
3312  if (resolve_symlink(fname, fname_buf) == OK) {
3313    fname_res = fname_buf;
3314  }
3315#endif
3316  int len = (int)strlen(dir_name);
3317
3318  char *s = dir_name + len;
3319  if (after_pathsep(dir_name, s) && len > 1 && s[-1] == s[-2]) {
3320    // Ends with '//', Use Full path
3321    char *r = NULL;
3322    s = make_percent_swname(dir_name, s, fname_res);
3323    if (s != NULL) {
3324      r = modname(s, ".swp", false);
3325      xfree(s);
3326    }
3327    return r;
3328  }
3329
3330  // Prepend a '.' to the swapfile name for the current directory.
3331  char *r = modname(fname_res, ".swp",
3332                    dir_name[0] == '.' && dir_name[1] == NUL);
3333  if (r == NULL) {          // out of memory
3334    return NULL;
3335  }
3336
3337  s = get_file_in_dir(r, dir_name);
3338  xfree(r);
3339  return s;
3340}
3341
3342/// Get file name to use for swapfile or backup file.
3343/// Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir' option "dname".
3344/// - If "dname" is ".", return "fname" (swapfile in dir of file).
3345/// - If "dname" starts with "./", insert "dname" in "fname" (swapfile relative to dir of file).
3346/// - Otherwise, prepend "dname" to the tail of "fname" (swapfile in specific dir).
3347///
3348/// The return value is an allocated string and can be NULL.
3349///
3350/// @param dname  don't use "dirname", it is a global for Alpha
3351char *get_file_in_dir(char *fname, char *dname)
3352{
3353  String retval;
3354  String tail = cstr_as_string(path_tail(fname));
3355
3356  if (dname[0] == '.' && dname[1] == NUL) {
3357    retval = cbuf_to_string(fname, (size_t)(tail.data - fname) + tail.size);
3358  } else {
3359    size_t dname_len = strlen(dname);
3360    if (dname[0] == '.' && vim_ispathsep(dname[1])) {
3361      if (tail.data == fname) {  // no path before file name
3362        retval = concat_fnames(cbuf_as_string(dname + 2, dname_len - 2), tail, true);
3363      } else {
3364        const char save_char = *tail.data;
3365        *tail.data = NUL;
3366        String tmp = concat_fnames(cbuf_as_string(fname, (size_t)(tail.data - fname)),
3367                                   cbuf_as_string(dname + 2, dname_len - 2), true);
3368        *tail.data = save_char;
3369        retval = concat_fnames(tmp, tail, true);
3370        xfree(tmp.data);
3371      }
3372    } else {
3373      retval = concat_fnames(cbuf_as_string(dname, dname_len), tail, true);
3374    }
3375  }
3376
3377  return retval.data;
3378}
3379
3380/// Build the ATTENTION message: info about an existing swapfile.
3381///
3382/// @param buf  buffer being edited
3383/// @param fname  swapfile name
3384/// @param fhname  swapfile name, home replaced
3385/// @param msg  string buffer, emitted as either a regular or confirm message
3386static void attention_message(buf_T *buf, char *fname, char *fhname, StringBuilder *msg)
3387{
3388  assert(buf->b_fname != NULL);
3389
3390  emsg(_("E325: ATTENTION"));
3391  kv_printf(*msg, _("Found a swap file by the name \""));
3392  kv_printf(*msg, "%s\"\n", fhname);
3393  const time_t swap_mtime = swapfile_info(fname, msg);
3394  kv_printf(*msg, (_("While opening file \"")));
3395  kv_printf(*msg, "%s\"\n", buf->b_fname);
3396  FileInfo file_info;
3397  if (!os_fileinfo(buf->b_fname, &file_info)) {
3398    kv_printf(*msg, _("      CANNOT BE FOUND"));
3399  } else {
3400    kv_printf(*msg, _("             dated: "));
3401    time_t x = file_info.stat.st_mtim.tv_sec;
3402    char ctime_buf[50];
3403    kv_printf(*msg, "%s", os_ctime_r(&x, ctime_buf, sizeof(ctime_buf), true));
3404    if (swap_mtime != 0 && x > swap_mtime) {
3405      kv_printf(*msg, _("      NEWER than swap file!\n"));
3406    }
3407  }
3408  // Some of these messages are long to allow translation to
3409  // other languages.
3410  kv_printf(*msg, _("\n(1) Another program may be editing the same file.  If this is"
3411                    " the case,\n    be careful not to end up with two different"
3412                    " instances of the same\n    file when making changes."
3413                    "  Quit, or continue with caution.\n"));
3414  kv_printf(*msg, _("(2) An edit session for this file crashed.\n"));
3415  kv_printf(*msg, _("    If this is the case, use \":recover\" or \"nvim -r "));
3416  kv_printf(*msg, "%s", buf->b_fname);
3417  kv_printf(*msg, (_("\"\n    to recover the changes (see \":help recovery\").\n")));
3418  kv_printf(*msg, _("    If you did this already, delete the swap file \""));
3419  kv_printf(*msg, "%s", fname);
3420  kv_printf(*msg, _("\"\n    to avoid this message.\n"));
3421}
3422
3423/// Trigger the SwapExists autocommands.
3424///
3425/// @return  a value for equivalent to do_dialog().
3426static sea_choice_T do_swapexists(buf_T *buf, char *fname)
3427{
3428  set_vim_var_string(VV_SWAPNAME, fname, -1);
3429  set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
3430
3431  // Trigger SwapExists autocommands with <afile> set to the file being
3432  // edited.  Disallow changing directory here.
3433  allbuf_lock++;
3434  apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, false, NULL);
3435  allbuf_lock--;
3436
3437  set_vim_var_string(VV_SWAPNAME, NULL, -1);
3438
3439  switch (*get_vim_var_str(VV_SWAPCHOICE)) {
3440  case 'o':
3441    return SEA_CHOICE_READONLY;
3442  case 'e':
3443    return SEA_CHOICE_EDIT;
3444  case 'r':
3445    return SEA_CHOICE_RECOVER;
3446  case 'd':
3447    return SEA_CHOICE_DELETE;
3448  case 'q':
3449    return SEA_CHOICE_QUIT;
3450  case 'a':
3451    return SEA_CHOICE_ABORT;
3452  }
3453
3454  return SEA_CHOICE_NONE;
3455}
3456
3457/// Find out what name to use for the swapfile for buffer 'buf'.
3458///
3459/// Several names are tried to find one that does not exist. Last directory in
3460/// option is automatically created.
3461///
3462/// @note If BASENAMELEN is not correct, you will get error messages for
3463///   not being able to open the swap or undo file.
3464/// @note May trigger SwapExists autocmd, pointers may change!
3465///
3466/// @param[in]  buf  Buffer for which swapfile names needs to be found.
3467/// @param[in,out]  dirp  Pointer to a list of directories. When out of memory,
3468///                       is set to NULL. Is advanced to the next directory in
3469///                       the list otherwise.
3470/// @param[in]  old_fname  Allowed existing swapfile name. Except for this
3471///                        case, name of the non-existing file is used.
3472/// @param[in,out]  found_existing_dir  If points to true, then new directory
3473///                                     for swapfile is not created. At first
3474///                                     findswapname() call this argument must
3475///                                     point to false. This parameter may only
3476///                                     be set to true by this function, it is
3477///                                     never set to false.
3478///
3479/// @return [allocated] Name of the swapfile.
3480static char *findswapname(buf_T *buf, char **dirp, char *old_fname, bool *found_existing_dir)
3481  FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1, 2, 4)
3482{
3483  char *buf_fname = buf->b_fname;
3484
3485  // Isolate a directory name from *dirp and put it in dir_name.
3486  // First allocate some memory to put the directory name in.
3487  const size_t dir_len = strlen(*dirp) + 1;
3488  char *dir_name = xmalloc(dir_len);
3489  copy_option_part(dirp, dir_name, dir_len, ",");
3490
3491  // We try different swapfile names until we find one that does not exist yet.
3492  char *fname = makeswapname(buf_fname, buf->b_ffname, buf, dir_name);
3493
3494  while (true) {
3495    size_t n;
3496    if (fname == NULL) {        // must be out of memory
3497      break;
3498    }
3499    if ((n = strlen(fname)) == 0) {        // safety check
3500      XFREE_CLEAR(fname);
3501      break;
3502    }
3503    // check if the swapfile already exists
3504    // Extra security check: When a swapfile is a symbolic link, this
3505    // is most likely a symlink attack.
3506    FileInfo file_info;
3507    bool file_or_link_found = os_fileinfo_link(fname, &file_info);
3508    if (!file_or_link_found) {
3509      break;
3510    }
3511
3512    // A file name equal to old_fname is OK to use.
3513    if (old_fname != NULL && path_equal(fname, old_fname, kPathCmpLiteral)) {
3514      break;
3515    }
3516
3517    // get here when file already exists
3518    if (fname[n - 2] == 'w' && fname[n - 1] == 'p') {   // first try
3519      // If we get here the ".swp" file really exists.
3520      // Give an error message, unless recovering, no file name, we are
3521      // viewing a help file or when the path of the file is different
3522      // (happens when all .swp files are in one directory).
3523      if (!recoverymode && buf_fname != NULL && !buf->b_help && !(buf->b_flags & BF_DUMMY)) {
3524        int fd;
3525        ZeroBlock b0;
3526        bool differ = false;
3527
3528        // Try to read block 0 from the swapfile to get the original file name (and inode number).
3529        fd = os_open(fname, O_RDONLY, 0);
3530        if (fd >= 0) {
3531          if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0)) {
3532            TO_SLASH(b0.b0_fname);
3533            proc_running = swapfile_proc_running(&b0, fname);
3534
3535            // If the swapfile has the same directory as the
3536            // buffer don't compare the directory names, they can
3537            // have a different mountpoint.
3538            if (b0.b0_flags & B0_SAME_DIR) {
3539              if (!path_equal(path_tail(buf->b_ffname), path_tail(b0.b0_fname), kPathCmpLiteral)
3540                  || !same_directory(fname, buf->b_ffname)) {
3541                // Symlinks may point to the same file even
3542                // when the name differs, need to check the
3543                // inode too.
3544                expand_env(b0.b0_fname, NameBuff, MAXPATHL);
3545                if (fnamecmp_ino(buf->b_ffname, NameBuff,
3546                                 char_to_long(b0.b0_ino))) {
3547                  differ = true;
3548                }
3549              }
3550            } else {
3551              // The name in the swapfile may be "~user/path/file".  Expand it first.
3552              expand_env(b0.b0_fname, NameBuff, MAXPATHL);
3553              if (fnamecmp_ino(buf->b_ffname, NameBuff,
3554                               char_to_long(b0.b0_ino))) {
3555                differ = true;
3556              }
3557            }
3558          }
3559          close(fd);
3560        }
3561
3562        // Show the ATTENTION message when:
3563        //  - there is an old swapfile for the current file
3564        //  - the buffer was not recovered
3565        if (!differ && !(curbuf->b_flags & BF_RECOVERED)
3566            && vim_strchr(p_shm, kShmAttention) == NULL) {
3567          sea_choice_T choice = SEA_CHOICE_NONE;
3568
3569          // It's safe to delete the swapfile if all these are true:
3570          // - the edited file exists
3571          // - the swapfile has no changes and looks OK
3572          if (os_path_exists(buf->b_fname) && swapfile_unchanged(fname)) {
3573            choice = SEA_CHOICE_DELETE;
3574            if (p_verbose > 0) {
3575              verb_msg(_("Found a swap file that is not useful, deleting it"));
3576            }
3577          }
3578
3579          // If there is a SwapExists autocommand and we can handle the
3580          // response, trigger it.  It may return 0 to ask the user anyway.
3581          if (choice == SEA_CHOICE_NONE
3582              && swap_exists_action != SEA_NONE
3583              && has_autocmd(EVENT_SWAPEXISTS, buf_fname, buf)) {
3584            choice = do_swapexists(buf, fname);
3585          }
3586
3587          if (choice == SEA_CHOICE_NONE && swap_exists_action == SEA_READONLY) {
3588            // always open readonly.
3589            choice = SEA_CHOICE_READONLY;
3590          }
3591
3592          proc_running = 0;  // Set by attention_message..swapfile_info.
3593          if (choice == SEA_CHOICE_NONE) {
3594            no_wait_return++;
3595            // Show info about the existing swapfile.
3596            StringBuilder msg = KV_INITIAL_VALUE;
3597            kv_resize(msg, IOSIZE);
3598            char *fhname = home_replace_save(NULL, fname);
3599            attention_message(buf, fname, fhname, &msg);
3600
3601            // We don't want a 'q' typed at the more-prompt
3602            // interrupt loading a file.
3603            got_int = false;
3604
3605            // If vimrc has "simalt ~x" we don't want it to
3606            // interfere with the prompt here.
3607            flush_buffers(FLUSH_TYPEAHEAD);
3608
3609            if (swap_exists_action != SEA_NONE) {
3610              kv_printf(msg, _("Swap file \""));
3611              kv_printf(msg, "%s", fhname);
3612              kv_printf(msg, _("\" already exists!"));
3613              char *run_but = _("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort");
3614              char *but = _("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort");
3615              choice = (sea_choice_T)do_dialog(VIM_WARNING, _("VIM - ATTENTION"), msg.items,
3616                                               proc_running ? run_but : but, 1, NULL, false);
3617
3618              // compensate for missing "Delete it" button
3619              choice += proc_running && choice >= 4;
3620              // pretend screen didn't scroll, need redraw anyway
3621              msg_reset_scroll();
3622            } else {
3623              bool need_clear = false;
3624              msg_ext_set_kind("wmsg");
3625              msg_multiline(cbuf_as_string(msg.items, msg.size), 0, false, false, &need_clear);
3626            }
3627            no_wait_return--;
3628            kv_destroy(msg);
3629            xfree(fhname);
3630          }
3631
3632          switch (choice) {
3633          case SEA_CHOICE_READONLY:  // "Open Read-Only"
3634            buf->b_p_ro = true;
3635            break;
3636          case SEA_CHOICE_EDIT:  // "Edit anyway"
3637            break;
3638          case SEA_CHOICE_RECOVER:  // "Recover"
3639            swap_exists_action = SEA_RECOVER;
3640            break;
3641          case SEA_CHOICE_DELETE:  // "Delete it"
3642            os_remove(fname);
3643            break;
3644          case SEA_CHOICE_QUIT:  // "Quit"
3645            swap_exists_action = SEA_QUIT;
3646            break;
3647          case SEA_CHOICE_ABORT:  // "Abort"
3648            swap_exists_action = SEA_QUIT;
3649            got_int = true;
3650            break;
3651          case SEA_CHOICE_NONE:
3652            msg_puts("\n");
3653            if (msg_silent == 0) {
3654              // call wait_return() later
3655              need_wait_return = true;
3656            }
3657            break;
3658          }
3659
3660          // If the swapfile was deleted this `fname` can be used.
3661          if (choice != SEA_CHOICE_NONE && !os_path_exists(fname)) {
3662            break;
3663          }
3664        }
3665      }
3666    }
3667
3668    // Permute the ".swp" extension to find a unique swapfile name.
3669    // First decrement the last char: ".swo", ".swn", etc.
3670    // If that still isn't enough decrement the last but one char: ".svz"
3671    // Can happen when many Nvim instances are editing the same file (including "No Name" buffers).
3672    if (fname[n - 1] == 'a') {          // ".s?a"
3673      if (fname[n - 2] == 'a') {        // ".saa": tried enough, give up
3674        emsg(_("E326: Too many swap files found"));
3675        XFREE_CLEAR(fname);
3676        break;
3677      }
3678      fname[n - 2]--;                   // ".svz", ".suz", etc.
3679      fname[n - 1] = 'z' + 1;
3680    }
3681    fname[n - 1]--;                     // ".swo", ".swn", etc.
3682  }
3683
3684  if (os_isdir(dir_name)) {
3685    *found_existing_dir = true;
3686  } else if (!*found_existing_dir && **dirp == NUL) {
3687    int ret;
3688    char *failed_dir;
3689    if ((ret = os_mkdir_recurse(dir_name, 0755, &failed_dir, NULL)) != 0) {
3690      semsg(_("E303: Unable to create directory \"%s\" for swap file, "
3691              "recovery impossible: %s"),
3692            failed_dir, os_strerror(ret));
3693      xfree(failed_dir);
3694    }
3695  }
3696
3697  xfree(dir_name);
3698  return fname;
3699}
3700
3701static int b0_magic_wrong(ZeroBlock *b0p)
3702{
3703  return b0p->b0_magic_long != B0_MAGIC_LONG
3704         || b0p->b0_magic_int != B0_MAGIC_INT
3705         || b0p->b0_magic_short != (int16_t)B0_MAGIC_SHORT
3706         || b0p->b0_magic_char != B0_MAGIC_CHAR;
3707}
3708
3709/// Compare current file name with file name from swapfile.
3710/// Try to use inode numbers when possible.
3711/// Return non-zero when files are different.
3712///
3713/// When comparing file names a few things have to be taken into consideration:
3714/// - When working over a network the full path of a file depends on the host.
3715///   We check the inode number if possible.  It is not 100% reliable though,
3716///   because the device number cannot be used over a network.
3717/// - When a file does not exist yet (editing a new file) there is no inode
3718///   number.
3719/// - The file name in a swapfile may not be valid on the current host.  The
3720///   "~user" form is used whenever possible to avoid this.
3721///
3722/// This is getting complicated, let's make a table:
3723///
3724///              ino_c  ino_s  fname_c  fname_s  differ =
3725///
3726/// both files exist -> compare inode numbers:
3727///              != 0   != 0     X        X      ino_c != ino_s
3728///
3729/// inode number(s) unknown, file names available -> compare file names
3730///              == 0    X       OK       OK     fname_c != fname_s
3731///               X     == 0     OK       OK     fname_c != fname_s
3732///
3733/// current file doesn't exist, file for swapfile exist, file name(s) not
3734/// available -> probably different
3735///              == 0   != 0    FAIL      X      true
3736///              == 0   != 0     X       FAIL    true
3737///
3738/// current file exists, inode for swap unknown, file name(s) not
3739/// available -> probably different
3740///              != 0   == 0    FAIL      X      true
3741///              != 0   == 0     X       FAIL    true
3742///
3743/// current file doesn't exist, inode for swap unknown, one file name not
3744/// available -> probably different
3745///              == 0   == 0    FAIL      OK     true
3746///              == 0   == 0     OK      FAIL    true
3747///
3748/// current file doesn't exist, inode for swap unknown, both file names not
3749/// available -> compare file names
3750///              == 0   == 0    FAIL     FAIL    fname_c != fname_s
3751///
3752/// Only the last 32 bits of the inode will be used. This can't be changed
3753/// without making the block 0 incompatible with 32 bit versions.
3754///
3755/// @param fname_c  current file name
3756/// @param fname_s  file name from swapfile
3757static bool fnamecmp_ino(char *fname_c, char *fname_s, long ino_block0)
3758{
3759  uint64_t ino_c = 0;               // ino of current file
3760  uint64_t ino_s;                   // ino of file from swapfile
3761  char buf_c[MAXPATHL];             // full path of fname_c
3762  char buf_s[MAXPATHL];             // full path of fname_s
3763  int retval_c;                     // flag: buf_c valid
3764  int retval_s;                     // flag: buf_s valid
3765
3766  FileInfo file_info;
3767  if (os_fileinfo(fname_c, &file_info)) {
3768    ino_c = os_fileinfo_inode(&file_info);
3769  }
3770
3771  // First we try to get the inode from the file name, because the inode in
3772  // the swapfile may be outdated.  If that fails (e.g. this path is not
3773  // valid on this machine), use the inode from block 0.
3774  if (os_fileinfo(fname_s, &file_info)) {
3775    ino_s = os_fileinfo_inode(&file_info);
3776  } else {
3777    ino_s = (uint64_t)ino_block0;
3778  }
3779
3780  if (ino_c && ino_s) {
3781    return ino_c != ino_s;
3782  }
3783
3784  // One of the inode numbers is unknown, try a forced vim_FullName() and
3785  // compare the file names.
3786  retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, true);
3787  retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, true);
3788  if (retval_c == OK && retval_s == OK) {
3789    return strcmp(buf_c, buf_s) != 0;
3790  }
3791
3792  // Can't compare inodes or file names, guess that the files are different,
3793  // unless both appear not to exist at all, then compare with the file name
3794  // in the swapfile.
3795  if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL) {
3796    return strcmp(fname_c, fname_s) != 0;
3797  }
3798  return true;
3799}
3800
3801/// Move a long integer into a four byte character array.
3802/// Used for machine independency in block zero.
3803static void long_to_char(long n, char *s_in)
3804{
3805  uint8_t *s = (uint8_t *)s_in;
3806  s[0] = (uint8_t)(n & 0xff);
3807  n = (unsigned)n >> 8;
3808  s[1] = (uint8_t)(n & 0xff);
3809  n = (unsigned)n >> 8;
3810  s[2] = (uint8_t)(n & 0xff);
3811  n = (unsigned)n >> 8;
3812  s[3] = (uint8_t)(n & 0xff);
3813}
3814
3815static long char_to_long(const char *s_in)
3816{
3817  const uint8_t *s = (uint8_t *)s_in;
3818
3819  long retval = s[3];
3820  retval <<= 8;
3821  retval |= s[2];
3822  retval <<= 8;
3823  retval |= s[1];
3824  retval <<= 8;
3825  retval |= s[0];
3826
3827  return retval;
3828}
3829
3830/// Set the flags in the first block of the swapfile:
3831/// - file is modified or not: buf->b_changed
3832/// - 'fileformat'
3833/// - 'fileencoding'
3834void ml_setflags(buf_T *buf)
3835{
3836  if (!buf->b_ml.ml_mfp) {
3837    return;
3838  }
3839  bhdr_T *hp = pmap_get(int64_t)(&buf->b_ml.ml_mfp->mf_hash, 0);
3840  if (hp) {
3841    ZeroBlock *b0p = hp->bh_data;
3842    b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
3843    b0p->b0_flags = (char)((b0p->b0_flags & ~B0_FF_MASK) | (uint8_t)(get_fileformat(buf) + 1));
3844    add_b0_fenc(b0p, buf);
3845    hp->bh_flags |= BH_DIRTY;
3846    mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
3847  }
3848}
3849
3850enum {
3851  MLCS_MAXL = 800,  // max no of lines in chunk
3852  MLCS_MINL = 400,  // should be half of MLCS_MAXL
3853};
3854
3855/// Keep information for finding byte offset of a line
3856///
3857/// @param updtype  may be one of:
3858///                 ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
3859///                         Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
3860///                 ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
3861///                 ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
3862static void ml_updatechunk(buf_T *buf, linenr_T line, int len, int updtype)
3863{
3864  static buf_T *ml_upd_lastbuf = NULL;
3865  static linenr_T ml_upd_lastcurline;
3866  static int ml_upd_lastcurix;
3867
3868  linenr_T curline = ml_upd_lastcurline;
3869  int curix = ml_upd_lastcurix;
3870  bhdr_T *hp;
3871
3872  if (buf->b_ml.ml_usedchunks == -1 || len == 0) {
3873    return;
3874  }
3875  if (buf->b_ml.ml_chunksize == NULL) {
3876    buf->b_ml.ml_chunksize = xmalloc(sizeof(chunksize_T) * 100);
3877    buf->b_ml.ml_numchunks = 100;
3878    buf->b_ml.ml_usedchunks = 1;
3879    buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
3880    buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
3881    ml_upd_lastbuf = NULL;          // invalidate resume cache
3882  }
3883
3884  if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1) {
3885    // First line in empty buffer from ml_flush_line() -- reset
3886    buf->b_ml.ml_usedchunks = 1;
3887    buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
3888    buf->b_ml.ml_chunksize[0].mlcs_totalsize = buf->b_ml.ml_line_textlen;
3889    ml_upd_lastbuf = NULL;          // invalidate resume cache
3890    return;
3891  }
3892
3893  // Find chunk that our line belongs to, curline will be at start of the
3894  // chunk.
3895  // The scan resumes at the cached chunk while ml_upd_lastbuf is set: the
3896  // chunks have not moved since the last call.
3897  if (buf != ml_upd_lastbuf || line < curline) {
3898    curline = 1;
3899    curix = 0;
3900  }
3901  for (; curix < buf->b_ml.ml_usedchunks - 1
3902       && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
3903       curix++) {
3904    curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
3905  }
3906  chunksize_T *curchnk = buf->b_ml.ml_chunksize + curix;
3907
3908  if (updtype == ML_CHNK_DELLINE) {
3909    len = -len;
3910  }
3911  curchnk->mlcs_totalsize += len;
3912  if (updtype == ML_CHNK_ADDLINE) {
3913    int rest;
3914    DataBlock *dp;
3915    curchnk->mlcs_numlines++;
3916
3917    // May resize here so we don't have to do it in both cases below
3918    if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks) {
3919      buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
3920      buf->b_ml.ml_chunksize = xrealloc(buf->b_ml.ml_chunksize,
3921                                        sizeof(chunksize_T) * (size_t)buf->b_ml.ml_numchunks);
3922    }
3923
3924    if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL) {
3925      int end_idx;
3926      int text_end;
3927
3928      memmove(buf->b_ml.ml_chunksize + curix + 1,
3929              buf->b_ml.ml_chunksize + curix,
3930              (size_t)(buf->b_ml.ml_usedchunks - curix) * sizeof(chunksize_T));
3931      // Compute length of first half of lines in the split chunk
3932      int size = 0;
3933      int linecnt = 0;
3934      while (curline < buf->b_ml.ml_line_count
3935             && linecnt < MLCS_MINL) {
3936        if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL) {
3937          buf->b_ml.ml_usedchunks = -1;
3938          return;
3939        }
3940        dp = hp->bh_data;
3941        int count
3942          = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;  // number of entries in block
3943        int idx = curline - buf->b_ml.ml_locked_low;
3944        curline = buf->b_ml.ml_locked_high + 1;
3945        // compute index of last line to use in this MEMLINE
3946        rest = count - idx;
3947        if (linecnt + rest > MLCS_MINL) {
3948          end_idx = idx + MLCS_MINL - linecnt - 1;
3949          linecnt = MLCS_MINL;
3950        } else {
3951          end_idx = count - 1;
3952          linecnt += rest;
3953        }
3954        if (idx == 0) {  // first line in block, text at the end
3955          text_end = (int)dp->db_txt_end;
3956        } else {
3957          text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
3958        }
3959        size += text_end - (int)((dp->db_index[end_idx]) & DB_INDEX_MASK);
3960      }
3961      buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
3962      buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
3963      buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
3964      buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
3965      buf->b_ml.ml_usedchunks++;
3966      ml_upd_lastbuf = NULL;         // Force recalc of curix & curline
3967      return;
3968    } else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
3969               && curix == buf->b_ml.ml_usedchunks - 1
3970               && buf->b_ml.ml_line_count - line <= 1) {
3971      // We are in the last chunk and it is cheap to create a new one
3972      // after this. Do it now to avoid the loop above later on
3973      curchnk = buf->b_ml.ml_chunksize + curix + 1;
3974      buf->b_ml.ml_usedchunks++;
3975      if (line == buf->b_ml.ml_line_count) {
3976        curchnk->mlcs_numlines = 0;
3977        curchnk->mlcs_totalsize = 0;
3978      } else {
3979        // Line is just prior to last, move count for last
3980        // This is the common case  when loading a new file
3981        hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
3982        if (hp == NULL) {
3983          buf->b_ml.ml_usedchunks = -1;
3984          return;
3985        }
3986        dp = hp->bh_data;
3987        if (dp->db_line_count == 1) {
3988          rest = (int)(dp->db_txt_end - dp->db_txt_start);
3989        } else {
3990          rest = (int)((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
3991                 - (int)dp->db_txt_start;
3992        }
3993        curchnk->mlcs_totalsize = rest;
3994        curchnk->mlcs_numlines = 1;
3995        curchnk[-1].mlcs_totalsize -= rest;
3996        curchnk[-1].mlcs_numlines -= 1;
3997      }
3998    }
3999  } else if (updtype == ML_CHNK_DELLINE) {
4000    curchnk->mlcs_numlines--;
4001    if (curix < (buf->b_ml.ml_usedchunks - 1)
4002        && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
4003        <= MLCS_MINL) {
4004      curix++;
4005      curchnk = buf->b_ml.ml_chunksize + curix;
4006    } else if (curix == 0 && curchnk->mlcs_numlines <= 0) {
4007      ml_upd_lastbuf = NULL;   // Force recalc of curix & curline
4008      buf->b_ml.ml_usedchunks--;
4009      memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
4010              (size_t)buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
4011      return;
4012    } else if (curix == 0 || (curchnk->mlcs_numlines > 10
4013                              && (curchnk->mlcs_numlines +
4014                                  curchnk[-1].mlcs_numlines)
4015                              > MLCS_MINL)) {
4016      // The chunks are left as they are, the cached position stays valid.
4017      ml_upd_lastbuf = buf;
4018      ml_upd_lastcurline = curline;
4019      ml_upd_lastcurix = curix;
4020      return;
4021    }
4022
4023    // Collapse chunks
4024    ml_upd_lastbuf = NULL;   // Force recalc of curix & curline
4025    curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
4026    curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
4027    buf->b_ml.ml_usedchunks--;
4028    if (curix < buf->b_ml.ml_usedchunks) {
4029      memmove(buf->b_ml.ml_chunksize + curix,
4030              buf->b_ml.ml_chunksize + curix + 1,
4031              (size_t)(buf->b_ml.ml_usedchunks - curix) * sizeof(chunksize_T));
4032    }
4033    return;
4034  }
4035  ml_upd_lastbuf = buf;
4036  ml_upd_lastcurline = curline;
4037  ml_upd_lastcurix = curix;
4038}
4039
4040/// Find offset for line or line with offset.
4041///
4042/// @param buf buffer to use
4043/// @param lnum if > 0, find offset of lnum, return offset
4044///             if == 0, return line with offset *offp
4045/// @param offp offset to use to find line, store remaining column offset
4046///             Should be NULL when getting offset of line
4047/// @param no_ff ignore 'fileformat' option, always use one byte for NL.
4048///
4049/// @return  -1 if information is not available
4050int ml_find_line_or_offset(buf_T *buf, linenr_T lnum, int *offp, bool no_ff)
4051{
4052  bhdr_T *hp;
4053  int text_end;
4054  int offset;
4055  int ffdos = !no_ff && (get_fileformat(buf) == EOL_DOS);
4056  int extra = 0;
4057
4058  // take care of cached line first. Only needed if the cached line is before
4059  // the requested line. Additionally cache the value for the cached line.
4060  // This is used by the extmark code which needs the byte offset of the edited
4061  // line. So when doing multiple small edits on the same line the value is
4062  // only calculated once.
4063  //
4064  // NB: caching doesn't work with 'fileformat'. This is not a problem for
4065  // bytetracking, as bytetracking ignores 'fileformat' option. But calling
4066  // line2byte() will invalidate the cache for the time being (this function
4067  // was never cached to start with anyway).
4068  bool can_cache = (lnum != 0 && !ffdos && buf->b_ml.ml_line_lnum == lnum);
4069  if (lnum == 0 || buf->b_ml.ml_line_lnum < lnum || !no_ff) {
4070    ml_flush_line(curbuf, false);
4071  } else if (can_cache && buf->b_ml.ml_line_offset > 0) {
4072    return (int)buf->b_ml.ml_line_offset;
4073  }
4074
4075  if (buf->b_ml.ml_usedchunks == -1
4076      || buf->b_ml.ml_chunksize == NULL
4077      || lnum < 0) {
4078    // memline is currently empty. Although if it is loaded,
4079    // it behaves like there is one empty line.
4080    if (no_ff && buf->b_ml.ml_mfp && (lnum == 1 || lnum == 2)) {
4081      return lnum - 1;
4082    }
4083    return -1;
4084  }
4085
4086  if (offp == NULL) {
4087    offset = 0;
4088  } else {
4089    offset = *offp;
4090  }
4091  if (lnum == 0 && offset <= 0) {
4092    return 1;       // Not a "find offset" and offset 0 _must_ be in line 1
4093  }
4094  // Find the last chunk before the one containing our line. Last chunk is
4095  // special because it will never qualify.
4096  linenr_T curline = 1;
4097  int curix = 0;
4098  int size = 0;
4099  while (curix < buf->b_ml.ml_usedchunks - 1
4100         && ((lnum != 0
4101              && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
4102             || (offset != 0
4103                 && offset > size +
4104                 buf->b_ml.ml_chunksize[curix].mlcs_totalsize
4105                 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines))) {
4106    curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4107    size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
4108    if (offset && ffdos) {
4109      size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4110    }
4111    curix++;
4112  }
4113
4114  while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset)) {
4115    if (curline > buf->b_ml.ml_line_count
4116        || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL) {
4117      return -1;
4118    }
4119    DataBlock *dp = hp->bh_data;
4120    int count
4121      = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;  // number of entries in block
4122    int idx;
4123    int start_idx = idx = curline - buf->b_ml.ml_locked_low;
4124    if (idx == 0) {  // first line in block, text at the end
4125      text_end = (int)dp->db_txt_end;
4126    } else {
4127      text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
4128    }
4129    // Compute index of last line to use in this MEMLINE
4130    if (lnum != 0) {
4131      if (curline + (count - idx) >= lnum) {
4132        idx += lnum - curline - 1;
4133      } else {
4134        idx = count - 1;
4135      }
4136    } else {
4137      extra = 0;
4138      while (true) {
4139        if (!(offset >= size
4140              + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
4141              + ffdos)) {
4142          break;
4143        }
4144        if (ffdos) {
4145          size++;
4146        }
4147        if (idx == count - 1) {
4148          extra = 1;
4149          break;
4150        }
4151        idx++;
4152      }
4153    }
4154    int len = text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK);
4155    size += len;
4156    if (offset != 0 && size >= offset) {
4157      if (size + ffdos == offset) {
4158        *offp = 0;
4159      } else if (idx == start_idx) {
4160        *offp = offset - size + len;
4161      } else {
4162        *offp = offset - size + len
4163                - (text_end - (int)((dp->db_index[idx - 1]) & DB_INDEX_MASK));
4164      }
4165      curline += idx - start_idx + extra;
4166      if (curline > buf->b_ml.ml_line_count) {
4167        return -1;              // exactly one byte beyond the end
4168      }
4169      return curline;
4170    }
4171    curline = buf->b_ml.ml_locked_high + 1;
4172  }
4173
4174  if (lnum != 0) {
4175    // Count extra CR characters.
4176    if (ffdos) {
4177      size += lnum - 1;
4178    }
4179
4180    // Don't count the last line break if 'noeol' and ('bin' or
4181    // 'nofixeol').
4182    if ((!buf->b_p_fixeol || buf->b_p_bin) && !buf->b_p_eol
4183        && lnum > buf->b_ml.ml_line_count) {
4184      size -= ffdos + 1;
4185    }
4186  }
4187
4188  if (can_cache && size > 0) {
4189    buf->b_ml.ml_line_offset = (size_t)size;
4190  }
4191
4192  return size;
4193}
4194
4195/// Goto byte in buffer with offset 'cnt'.
4196void goto_byte(int cnt)
4197{
4198  int boff = cnt;
4199
4200  ml_flush_line(curbuf, false);  // cached line may be dirty
4201  setpcmark();
4202  if (boff) {
4203    boff--;
4204  }
4205  linenr_T lnum = (linenr_T)ml_find_line_or_offset(curbuf, 0, &boff, false);
4206  if (lnum < 1) {         // past the end
4207    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
4208    curwin->w_curswant = MAXCOL;
4209    coladvance(curwin, MAXCOL);
4210  } else {
4211    curwin->w_cursor.lnum = lnum;
4212    curwin->w_cursor.col = (colnr_T)boff;
4213    curwin->w_cursor.coladd = 0;
4214    curwin->w_set_curswant = true;
4215  }
4216  check_cursor(curwin);
4217
4218  // Make sure the cursor is on the first byte of a multi-byte char.
4219  mb_adjust_cursor();
4220}
4221
4222/// Increment the line pointer "lp" crossing line boundaries as necessary.
4223///
4224/// @return   1 when going to the next line.
4225///           2 when moving forward onto a NUL at the end of the line).
4226///          -1 when at the end of file.
4227///           0 otherwise.
4228int inc(pos_T *lp)
4229{
4230  // when searching position may be set to end of a line
4231  if (lp->col != MAXCOL) {
4232    const char *const p = ml_get_pos(lp);
4233    if (*p != NUL) {  // still within line, move to next char (may be NUL)
4234      const int l = utfc_ptr2len(p);
4235
4236      lp->col += l;
4237      return ((p[l] != NUL) ? 0 : 2);
4238    }
4239  }
4240  if (lp->lnum != curbuf->b_ml.ml_line_count) {     // there is a next line
4241    lp->col = 0;
4242    lp->lnum++;
4243    lp->coladd = 0;
4244    return 1;
4245  }
4246  return -1;
4247}
4248
4249/// Same as inc(), but skip NUL at the end of non-empty lines.
4250int incl(pos_T *lp)
4251{
4252  int r;
4253
4254  if ((r = inc(lp)) >= 1 && lp->col) {
4255    r = inc(lp);
4256  }
4257  return r;
4258}
4259
4260/// Decrements position `lp` by one character (multibyte-aware), crossing line boundaries as
4261/// necessary. Resets `lp.coladd`. Uses curbuf.
4262///
4263/// @return   1 when crossing to the previous line.
4264///          -1 when at the start of the file.
4265///           0 otherwise.
4266int dec(pos_T *lp)
4267{
4268  lp->coladd = 0;
4269  if (lp->col == MAXCOL) {
4270    // past end of line
4271    char *p = ml_get(lp->lnum);
4272    lp->col = ml_get_len(lp->lnum);
4273    lp->col -= utf_head_off(p, p + lp->col);
4274    return 0;
4275  }
4276
4277  if (lp->col > 0) {
4278    // still within line
4279    lp->col--;
4280    char *p = ml_get(lp->lnum);
4281    lp->col -= utf_head_off(p, p + lp->col);
4282    return 0;
4283  }
4284  if (lp->lnum > 1) {
4285    // there is a prior line
4286    lp->lnum--;
4287    char *p = ml_get(lp->lnum);
4288    lp->col = ml_get_len(lp->lnum);
4289    lp->col -= utf_head_off(p, p + lp->col);
4290    return 1;
4291  }
4292
4293  // at start of file
4294  return -1;
4295}
4296
4297/// Same as dec(), but skip NUL at the end of non-empty lines.
4298int decl(pos_T *lp)
4299{
4300  int r;
4301
4302  if ((r = dec(lp)) == 1 && lp->col) {
4303    r = dec(lp);
4304  }
4305  return r;
4306}