blob: a2f0b4f6269b7242707fb988914bde4382a2286a [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/* for debugging */
Bram Moolenaar6f470022018-04-10 18:47:20 +020011/* #define CHECK(c, s) do { if (c) EMSG(s); } while (0) */
12#define CHECK(c, s) do { /**/ } while (0)
Bram Moolenaar071d4272004-06-13 20:20:40 +000013
14/*
15 * memline.c: Contains the functions for appending, deleting and changing the
Bram Moolenaar4770d092006-01-12 23:22:24 +000016 * text lines. The memfile functions are used to store the information in
17 * blocks of memory, backed up by a file. The structure of the information is
18 * a tree. The root of the tree is a pointer block. The leaves of the tree
19 * are data blocks. In between may be several layers of pointer blocks,
20 * forming branches.
Bram Moolenaar071d4272004-06-13 20:20:40 +000021 *
22 * Three types of blocks are used:
23 * - Block nr 0 contains information for recovery
24 * - Pointer blocks contain list of pointers to other blocks.
25 * - Data blocks contain the actual text.
26 *
27 * Block nr 0 contains the block0 structure (see below).
28 *
29 * Block nr 1 is the first pointer block. It is the root of the tree.
30 * Other pointer blocks are branches.
31 *
32 * If a line is too big to fit in a single page, the block containing that
33 * line is made big enough to hold the line. It may span several pages.
34 * Otherwise all blocks are one page.
35 *
36 * A data block that was filled when starting to edit a file and was not
37 * changed since then, can have a negative block number. This means that it
38 * has not yet been assigned a place in the file. When recovering, the lines
39 * in this data block can be read from the original file. When the block is
40 * changed (lines appended/deleted/changed) or when it is flushed it gets a
41 * positive number. Use mf_trans_del() to get the new number, before calling
42 * mf_get().
43 */
44
Bram Moolenaar071d4272004-06-13 20:20:40 +000045#include "vim.h"
46
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#ifndef UNIX /* it's in os_unix.h for Unix */
48# include <time.h>
49#endif
50
Bram Moolenaar5a6404c2006-11-01 17:12:57 +000051#if defined(SASC) || defined(__amigaos4__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000052# include <proto/dos.h> /* for Open() and Close() */
53#endif
54
55typedef struct block0 ZERO_BL; /* contents of the first block */
56typedef struct pointer_block PTR_BL; /* contents of a pointer block */
57typedef struct data_block DATA_BL; /* contents of a data block */
58typedef struct pointer_entry PTR_EN; /* block/line-count pair */
59
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020060#define DATA_ID (('d' << 8) + 'a') /* data block id */
61#define PTR_ID (('p' << 8) + 't') /* pointer block id */
62#define BLOCK0_ID0 'b' /* block 0 id 0 */
63#define BLOCK0_ID1 '0' /* block 0 id 1 */
64#define BLOCK0_ID1_C0 'c' /* block 0 id 1 'cm' 0 */
65#define BLOCK0_ID1_C1 'C' /* block 0 id 1 'cm' 1 */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020066#define BLOCK0_ID1_C2 'd' /* block 0 id 1 'cm' 2 */
67
68#if defined(FEAT_CRYPT)
69static int id1_codes[] = {
70 BLOCK0_ID1_C0, /* CRYPT_M_ZIP */
71 BLOCK0_ID1_C1, /* CRYPT_M_BF */
72 BLOCK0_ID1_C2, /* CRYPT_M_BF2 */
73};
74#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000075
76/*
77 * pointer to a block, used in a pointer block
78 */
79struct pointer_entry
80{
81 blocknr_T pe_bnum; /* block number */
82 linenr_T pe_line_count; /* number of lines in this branch */
83 linenr_T pe_old_lnum; /* lnum for this block (for recovery) */
84 int pe_page_count; /* number of pages in block pe_bnum */
85};
86
87/*
88 * A pointer block contains a list of branches in the tree.
89 */
90struct pointer_block
91{
92 short_u pb_id; /* ID for pointer block: PTR_ID */
Bram Moolenaar20a825a2010-05-31 21:27:30 +020093 short_u pb_count; /* number of pointers in this block */
Bram Moolenaar071d4272004-06-13 20:20:40 +000094 short_u pb_count_max; /* maximum value for pb_count */
95 PTR_EN pb_pointer[1]; /* list of pointers to blocks (actually longer)
96 * followed by empty space until end of page */
97};
98
99/*
100 * A data block is a leaf in the tree.
101 *
102 * The text of the lines is at the end of the block. The text of the first line
103 * in the block is put at the end, the text of the second line in front of it,
104 * etc. Thus the order of the lines is the opposite of the line number.
105 */
106struct data_block
107{
108 short_u db_id; /* ID for data block: DATA_ID */
109 unsigned db_free; /* free space available */
110 unsigned db_txt_start; /* byte where text starts */
111 unsigned db_txt_end; /* byte just after data block */
112 linenr_T db_line_count; /* number of lines in this block */
113 unsigned db_index[1]; /* index for start of line (actually bigger)
114 * followed by empty space upto db_txt_start
115 * followed by the text in the lines until
116 * end of page */
117};
118
119/*
120 * The low bits of db_index hold the actual index. The topmost bit is
121 * used for the global command to be able to mark a line.
122 * This method is not clean, but otherwise there would be at least one extra
123 * byte used for each line.
124 * The mark has to be in this place to keep it with the correct line when other
125 * lines are inserted or deleted.
126 */
127#define DB_MARKED ((unsigned)1 << ((sizeof(unsigned) * 8) - 1))
128#define DB_INDEX_MASK (~DB_MARKED)
129
130#define INDEX_SIZE (sizeof(unsigned)) /* size of one db_index entry */
131#define HEADER_SIZE (sizeof(DATA_BL) - INDEX_SIZE) /* size of data block header */
132
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000133#define B0_FNAME_SIZE_ORG 900 /* what it was in older versions */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200134#define B0_FNAME_SIZE_NOCRYPT 898 /* 2 bytes used for other things */
135#define B0_FNAME_SIZE_CRYPT 890 /* 10 bytes used for other things */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000136#define B0_UNAME_SIZE 40
137#define B0_HNAME_SIZE 40
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138/*
139 * Restrict the numbers to 32 bits, otherwise most compilers will complain.
140 * This won't detect a 64 bit machine that only swaps a byte in the top 32
141 * bits, but that is crazy anyway.
142 */
143#define B0_MAGIC_LONG 0x30313233L
144#define B0_MAGIC_INT 0x20212223L
145#define B0_MAGIC_SHORT 0x10111213L
146#define B0_MAGIC_CHAR 0x55
147
148/*
149 * Block zero holds all info about the swap file.
150 *
151 * NOTE: DEFINITION OF BLOCK 0 SHOULD NOT CHANGE! It would make all existing
152 * swap files unusable!
153 *
154 * If size of block0 changes anyway, adjust MIN_SWAP_PAGE_SIZE in vim.h!!
155 *
Bram Moolenaarbae0c162007-05-10 19:30:25 +0000156 * This block is built up of single bytes, to make it portable across
Bram Moolenaar071d4272004-06-13 20:20:40 +0000157 * different machines. b0_magic_* is used to check the byte order and size of
158 * variables, because the rest of the swap file is not portable.
159 */
160struct block0
161{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200162 char_u b0_id[2]; /* id for block 0: BLOCK0_ID0 and BLOCK0_ID1,
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200163 * BLOCK0_ID1_C0, BLOCK0_ID1_C1, etc. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164 char_u b0_version[10]; /* Vim version string */
165 char_u b0_page_size[4];/* number of bytes per page */
166 char_u b0_mtime[4]; /* last modification time of file */
167 char_u b0_ino[4]; /* inode of b0_fname */
168 char_u b0_pid[4]; /* process id of creator (or 0) */
169 char_u b0_uname[B0_UNAME_SIZE]; /* name of user (uid if no name) */
170 char_u b0_hname[B0_HNAME_SIZE]; /* host name (if it has a name) */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000171 char_u b0_fname[B0_FNAME_SIZE_ORG]; /* name of file being edited */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172 long b0_magic_long; /* check for byte order of long */
173 int b0_magic_int; /* check for byte order of int */
174 short b0_magic_short; /* check for byte order of short */
175 char_u b0_magic_char; /* check for last char */
176};
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000177
178/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000179 * Note: b0_dirty and b0_flags are put at the end of the file name. For very
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000180 * long file names in older versions of Vim they are invalid.
181 * The 'fileencoding' comes before b0_flags, with a NUL in front. But only
182 * when there is room, for very long file names it's omitted.
183 */
184#define B0_DIRTY 0x55
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200185#define b0_dirty b0_fname[B0_FNAME_SIZE_ORG - 1]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000186
187/*
188 * The b0_flags field is new in Vim 7.0.
189 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200190#define b0_flags b0_fname[B0_FNAME_SIZE_ORG - 2]
191
192/*
193 * Crypt seed goes here, 8 bytes. New in Vim 7.3.
194 * Without encryption these bytes may be used for 'fenc'.
195 */
196#define b0_seed b0_fname[B0_FNAME_SIZE_ORG - 2 - MF_SEED_LEN]
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000197
198/* The lowest two bits contain the fileformat. Zero means it's not set
199 * (compatible with Vim 6.x), otherwise it's EOL_UNIX + 1, EOL_DOS + 1 or
200 * EOL_MAC + 1. */
201#define B0_FF_MASK 3
202
203/* Swap file is in directory of edited file. Used to find the file from
204 * different mount points. */
205#define B0_SAME_DIR 4
206
207/* The 'fileencoding' is at the end of b0_fname[], with a NUL in front of it.
208 * When empty there is only the NUL. */
209#define B0_HAS_FENC 8
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210
211#define STACK_INCR 5 /* nr of entries added to ml_stack at a time */
212
213/*
214 * The line number where the first mark may be is remembered.
215 * If it is 0 there are no marks at all.
216 * (always used for the current buffer only, no buffer change possible while
217 * executing a global command).
218 */
219static linenr_T lowest_marked = 0;
220
221/*
222 * arguments for ml_find_line()
223 */
224#define ML_DELETE 0x11 /* delete line */
225#define ML_INSERT 0x12 /* insert line */
226#define ML_FIND 0x13 /* just find the line */
227#define ML_FLUSH 0x02 /* flush locked block */
228#define ML_SIMPLE(x) (x & 0x10) /* DEL, INS or FIND */
229
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200230/* argument for ml_upd_block0() */
231typedef enum {
232 UB_FNAME = 0 /* update timestamp and filename */
233 , UB_SAME_DIR /* update the B0_SAME_DIR flag */
234 , UB_CRYPT /* update crypt key */
235} upd_block0_T;
236
237#ifdef FEAT_CRYPT
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100238static void ml_set_mfp_crypt(buf_T *buf);
239static void ml_set_b0_crypt(buf_T *buf, ZERO_BL *b0p);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200240#endif
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100241static int ml_check_b0_id(ZERO_BL *b0p);
242static void ml_upd_block0(buf_T *buf, upd_block0_T what);
243static void set_b0_fname(ZERO_BL *, buf_T *buf);
244static void set_b0_dir_flag(ZERO_BL *b0p, buf_T *buf);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000245#ifdef FEAT_MBYTE
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100246static void add_b0_fenc(ZERO_BL *b0p, buf_T *buf);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000247#endif
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100248static time_t swapfile_info(char_u *);
249static int recov_file_names(char_u **, char_u *, int prepend_dot);
250static int ml_append_int(buf_T *, linenr_T, char_u *, colnr_T, int, int);
251static int ml_delete_int(buf_T *, linenr_T, int);
252static char_u *findswapname(buf_T *, char_u **, char_u *);
253static void ml_flush_line(buf_T *);
254static bhdr_T *ml_new_data(memfile_T *, int, int);
255static bhdr_T *ml_new_ptr(memfile_T *);
256static bhdr_T *ml_find_line(buf_T *, linenr_T, int);
257static int ml_add_stack(buf_T *);
258static void ml_lineadd(buf_T *, int);
259static int b0_magic_wrong(ZERO_BL *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260#ifdef CHECK_INODE
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100261static int fnamecmp_ino(char_u *, char_u *, long);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000262#endif
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100263static void long_to_char(long, char_u *);
264static long char_to_long(char_u *);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200265#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +0200266static cryptstate_T *ml_crypt_prepare(memfile_T *mfp, off_T offset, int reading);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200267#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268#ifdef FEAT_BYTEOFF
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +0100269static void ml_updatechunk(buf_T *buf, long line, long len, int updtype);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000270#endif
271
272/*
Bram Moolenaar4770d092006-01-12 23:22:24 +0000273 * Open a new memline for "buf".
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274 *
Bram Moolenaar4770d092006-01-12 23:22:24 +0000275 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276 */
277 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100278ml_open(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279{
280 memfile_T *mfp;
281 bhdr_T *hp = NULL;
282 ZERO_BL *b0p;
283 PTR_BL *pp;
284 DATA_BL *dp;
285
Bram Moolenaar4770d092006-01-12 23:22:24 +0000286 /*
287 * init fields in memline struct
288 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200289 buf->b_ml.ml_stack_size = 0; /* no stack yet */
Bram Moolenaar4770d092006-01-12 23:22:24 +0000290 buf->b_ml.ml_stack = NULL; /* no stack yet */
291 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
292 buf->b_ml.ml_locked = NULL; /* no cached block */
293 buf->b_ml.ml_line_lnum = 0; /* no cached line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294#ifdef FEAT_BYTEOFF
Bram Moolenaar4770d092006-01-12 23:22:24 +0000295 buf->b_ml.ml_chunksize = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000296#endif
297
Bram Moolenaar5803ae62014-03-23 16:04:02 +0100298 if (cmdmod.noswapfile)
299 buf->b_p_swf = FALSE;
300
Bram Moolenaar4770d092006-01-12 23:22:24 +0000301 /*
302 * When 'updatecount' is non-zero swap file may be opened later.
303 */
304 if (p_uc && buf->b_p_swf)
305 buf->b_may_swap = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306 else
Bram Moolenaar4770d092006-01-12 23:22:24 +0000307 buf->b_may_swap = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000308
Bram Moolenaar4770d092006-01-12 23:22:24 +0000309 /*
310 * Open the memfile. No swap file is created yet.
311 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000312 mfp = mf_open(NULL, 0);
313 if (mfp == NULL)
314 goto error;
315
Bram Moolenaar4770d092006-01-12 23:22:24 +0000316 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200317#ifdef FEAT_CRYPT
318 mfp->mf_buffer = buf;
319#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000320 buf->b_ml.ml_flags = ML_EMPTY;
321 buf->b_ml.ml_line_count = 1;
Bram Moolenaar592e0a22004-07-03 16:05:59 +0000322#ifdef FEAT_LINEBREAK
323 curwin->w_nrwidth_line_count = 0;
324#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325
Bram Moolenaar071d4272004-06-13 20:20:40 +0000326/*
327 * fill block0 struct and write page 0
328 */
329 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
330 goto error;
331 if (hp->bh_bnum != 0)
332 {
Bram Moolenaar95f09602016-11-10 20:01:45 +0100333 IEMSG(_("E298: Didn't get block nr 0?"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334 goto error;
335 }
336 b0p = (ZERO_BL *)(hp->bh_data);
337
338 b0p->b0_id[0] = BLOCK0_ID0;
339 b0p->b0_id[1] = BLOCK0_ID1;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 b0p->b0_magic_long = (long)B0_MAGIC_LONG;
341 b0p->b0_magic_int = (int)B0_MAGIC_INT;
342 b0p->b0_magic_short = (short)B0_MAGIC_SHORT;
343 b0p->b0_magic_char = B0_MAGIC_CHAR;
Bram Moolenaar22c10562018-05-26 17:35:27 +0200344 mch_memmove(b0p->b0_version, "VIM ", 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000345 STRNCPY(b0p->b0_version + 4, Version, 6);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 long_to_char((long)mfp->mf_page_size, b0p->b0_page_size);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000347
Bram Moolenaar76b92b22006-03-24 22:46:53 +0000348#ifdef FEAT_SPELL
349 if (!buf->b_spell)
350#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000351 {
352 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
353 b0p->b0_flags = get_fileformat(buf) + 1;
354 set_b0_fname(b0p, buf);
355 (void)get_user_name(b0p->b0_uname, B0_UNAME_SIZE);
356 b0p->b0_uname[B0_UNAME_SIZE - 1] = NUL;
357 mch_get_host_name(b0p->b0_hname, B0_HNAME_SIZE);
358 b0p->b0_hname[B0_HNAME_SIZE - 1] = NUL;
359 long_to_char(mch_get_pid(), b0p->b0_pid);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200360#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200361 ml_set_b0_crypt(buf, b0p);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200362#endif
Bram Moolenaar4770d092006-01-12 23:22:24 +0000363 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364
365 /*
366 * Always sync block number 0 to disk, so we can check the file name in
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200367 * the swap file in findswapname(). Don't do this for a help files or
368 * a spell buffer though.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369 * Only works when there's a swapfile, otherwise it's done when the file
370 * is created.
371 */
372 mf_put(mfp, hp, TRUE, FALSE);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000373 if (!buf->b_help && !B_SPELL(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374 (void)mf_sync(mfp, 0);
375
Bram Moolenaar4770d092006-01-12 23:22:24 +0000376 /*
377 * Fill in root pointer block and write page 1.
378 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 if ((hp = ml_new_ptr(mfp)) == NULL)
380 goto error;
381 if (hp->bh_bnum != 1)
382 {
Bram Moolenaar95f09602016-11-10 20:01:45 +0100383 IEMSG(_("E298: Didn't get block nr 1?"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000384 goto error;
385 }
386 pp = (PTR_BL *)(hp->bh_data);
387 pp->pb_count = 1;
388 pp->pb_pointer[0].pe_bnum = 2;
389 pp->pb_pointer[0].pe_page_count = 1;
390 pp->pb_pointer[0].pe_old_lnum = 1;
391 pp->pb_pointer[0].pe_line_count = 1; /* line count after insertion */
392 mf_put(mfp, hp, TRUE, FALSE);
393
Bram Moolenaar4770d092006-01-12 23:22:24 +0000394 /*
395 * Allocate first data block and create an empty line 1.
396 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 if ((hp = ml_new_data(mfp, FALSE, 1)) == NULL)
398 goto error;
399 if (hp->bh_bnum != 2)
400 {
Bram Moolenaar95f09602016-11-10 20:01:45 +0100401 IEMSG(_("E298: Didn't get block nr 2?"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402 goto error;
403 }
404
405 dp = (DATA_BL *)(hp->bh_data);
406 dp->db_index[0] = --dp->db_txt_start; /* at end of block */
407 dp->db_free -= 1 + INDEX_SIZE;
408 dp->db_line_count = 1;
Bram Moolenaarf05da212009-11-17 16:13:15 +0000409 *((char_u *)dp + dp->db_txt_start) = NUL; /* empty line */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410
411 return OK;
412
413error:
414 if (mfp != NULL)
415 {
416 if (hp)
417 mf_put(mfp, hp, FALSE, FALSE);
418 mf_close(mfp, TRUE); /* will also free(mfp->mf_fname) */
419 }
Bram Moolenaar4770d092006-01-12 23:22:24 +0000420 buf->b_ml.ml_mfp = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000421 return FAIL;
422}
423
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200424#if defined(FEAT_CRYPT) || defined(PROTO)
425/*
Bram Moolenaar2be79502014-08-13 21:58:28 +0200426 * Prepare encryption for "buf" for the current key and method.
427 */
428 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100429ml_set_mfp_crypt(buf_T *buf)
Bram Moolenaar2be79502014-08-13 21:58:28 +0200430{
431 if (*buf->b_p_key != NUL)
432 {
433 int method_nr = crypt_get_method_nr(buf);
434
435 if (method_nr > CRYPT_M_ZIP)
436 {
437 /* Generate a seed and store it in the memfile. */
438 sha2_seed(buf->b_ml.ml_mfp->mf_seed, MF_SEED_LEN, NULL, 0);
439 }
440 }
441}
442
443/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200444 * Prepare encryption for "buf" with block 0 "b0p".
445 */
446 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100447ml_set_b0_crypt(buf_T *buf, ZERO_BL *b0p)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200448{
449 if (*buf->b_p_key == NUL)
450 b0p->b0_id[1] = BLOCK0_ID1;
451 else
452 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200453 int method_nr = crypt_get_method_nr(buf);
454
455 b0p->b0_id[1] = id1_codes[method_nr];
456 if (method_nr > CRYPT_M_ZIP)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200457 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200458 /* Generate a seed and store it in block 0 and in the memfile. */
459 sha2_seed(&b0p->b0_seed, MF_SEED_LEN, NULL, 0);
460 mch_memmove(buf->b_ml.ml_mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
461 }
462 }
463}
464
465/*
466 * Called after the crypt key or 'cryptmethod' was changed for "buf".
467 * Will apply this to the swapfile.
468 * "old_key" is the previous key. It is equal to buf->b_p_key when
469 * 'cryptmethod' is changed.
Bram Moolenaar49771f42010-07-20 17:32:38 +0200470 * "old_cm" is the previous 'cryptmethod'. It is equal to the current
471 * 'cryptmethod' when 'key' is changed.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200472 */
473 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100474ml_set_crypt_key(
475 buf_T *buf,
476 char_u *old_key,
477 char_u *old_cm)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200478{
479 memfile_T *mfp = buf->b_ml.ml_mfp;
480 bhdr_T *hp;
481 int page_count;
482 int idx;
483 long error;
484 infoptr_T *ip;
485 PTR_BL *pp;
486 DATA_BL *dp;
487 blocknr_T bnum;
488 int top;
Bram Moolenaarbc563362015-06-09 18:35:25 +0200489 int old_method;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200490
Bram Moolenaar3832c462010-08-04 15:32:46 +0200491 if (mfp == NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200492 return; /* no memfile yet, nothing to do */
Bram Moolenaarbc563362015-06-09 18:35:25 +0200493 old_method = crypt_method_nr_from_name(old_cm);
494
495 /* First make sure the swapfile is in a consistent state, using the old
496 * key and method. */
497 {
498 char_u *new_key = buf->b_p_key;
499 char_u *new_buf_cm = buf->b_p_cm;
500
501 buf->b_p_key = old_key;
502 buf->b_p_cm = old_cm;
503 ml_preserve(buf, FALSE);
504 buf->b_p_key = new_key;
505 buf->b_p_cm = new_buf_cm;
506 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200507
508 /* Set the key, method and seed to be used for reading, these must be the
509 * old values. */
510 mfp->mf_old_key = old_key;
Bram Moolenaarbc563362015-06-09 18:35:25 +0200511 mfp->mf_old_cm = old_method;
512 if (old_method > 0 && *old_key != NUL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200513 mch_memmove(mfp->mf_old_seed, mfp->mf_seed, MF_SEED_LEN);
514
515 /* Update block 0 with the crypt flag and may set a new seed. */
516 ml_upd_block0(buf, UB_CRYPT);
517
518 if (mfp->mf_infile_count > 2)
519 {
520 /*
521 * Need to read back all data blocks from disk, decrypt them with the
522 * old key/method and mark them to be written. The algorithm is
523 * similar to what happens in ml_recover(), but we skip negative block
524 * numbers.
525 */
526 ml_flush_line(buf); /* flush buffered line */
527 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
528
529 hp = NULL;
530 bnum = 1; /* start with block 1 */
531 page_count = 1; /* which is 1 page */
532 idx = 0; /* start with first index in block 1 */
533 error = 0;
534 buf->b_ml.ml_stack_top = 0;
Bram Moolenaard23a8232018-02-10 18:45:26 +0100535 VIM_CLEAR(buf->b_ml.ml_stack);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200536 buf->b_ml.ml_stack_size = 0; /* no stack yet */
537
538 for ( ; !got_int; line_breakcheck())
539 {
540 if (hp != NULL)
541 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
542
543 /* get the block (pointer or data) */
544 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
545 {
546 if (bnum == 1)
547 break;
548 ++error;
549 }
550 else
551 {
552 pp = (PTR_BL *)(hp->bh_data);
553 if (pp->pb_id == PTR_ID) /* it is a pointer block */
554 {
555 if (pp->pb_count == 0)
556 {
557 /* empty block? */
558 ++error;
559 }
560 else if (idx < (int)pp->pb_count) /* go a block deeper */
561 {
562 if (pp->pb_pointer[idx].pe_bnum < 0)
563 {
Bram Moolenaarbc563362015-06-09 18:35:25 +0200564 /* Skip data block with negative block number.
565 * Should not happen, because of the ml_preserve()
566 * above. Get same block again for next index. */
567 ++idx;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200568 continue;
569 }
570
571 /* going one block deeper in the tree, new entry in
572 * stack */
573 if ((top = ml_add_stack(buf)) < 0)
574 {
575 ++error;
576 break; /* out of memory */
577 }
578 ip = &(buf->b_ml.ml_stack[top]);
579 ip->ip_bnum = bnum;
580 ip->ip_index = idx;
581
582 bnum = pp->pb_pointer[idx].pe_bnum;
583 page_count = pp->pb_pointer[idx].pe_page_count;
Bram Moolenaarbc563362015-06-09 18:35:25 +0200584 idx = 0;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200585 continue;
586 }
587 }
588 else /* not a pointer block */
589 {
590 dp = (DATA_BL *)(hp->bh_data);
591 if (dp->db_id != DATA_ID) /* block id wrong */
592 ++error;
593 else
594 {
595 /* It is a data block, need to write it back to disk. */
596 mf_put(mfp, hp, TRUE, FALSE);
597 hp = NULL;
598 }
599 }
600 }
601
602 if (buf->b_ml.ml_stack_top == 0) /* finished */
603 break;
604
605 /* go one block up in the tree */
606 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
607 bnum = ip->ip_bnum;
608 idx = ip->ip_index + 1; /* go to next index */
609 page_count = 1;
610 }
Bram Moolenaarbc563362015-06-09 18:35:25 +0200611 if (hp != NULL)
612 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +0100613
614 if (error > 0)
615 EMSG(_("E843: Error while updating swap file crypt"));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200616 }
617
618 mfp->mf_old_key = NULL;
619}
620#endif
621
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622/*
623 * ml_setname() is called when the file name of "buf" has been changed.
624 * It may rename the swap file.
625 */
626 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100627ml_setname(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628{
629 int success = FALSE;
630 memfile_T *mfp;
631 char_u *fname;
632 char_u *dirp;
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100633#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000634 char_u *p;
635#endif
636
637 mfp = buf->b_ml.ml_mfp;
638 if (mfp->mf_fd < 0) /* there is no swap file yet */
639 {
640 /*
641 * When 'updatecount' is 0 and 'noswapfile' there is no swap file.
642 * For help files we will make a swap file now.
643 */
Bram Moolenaar5803ae62014-03-23 16:04:02 +0100644 if (p_uc != 0 && !cmdmod.noswapfile)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645 ml_open_file(buf); /* create a swap file */
646 return;
647 }
648
649 /*
650 * Try all directories in the 'directory' option.
651 */
652 dirp = p_dir;
653 for (;;)
654 {
655 if (*dirp == NUL) /* tried all directories, fail */
656 break;
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000657 fname = findswapname(buf, &dirp, mfp->mf_fname);
658 /* alloc's fname */
Bram Moolenaarf541c362011-10-26 11:44:18 +0200659 if (dirp == NULL) /* out of memory */
660 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661 if (fname == NULL) /* no file name found for this dir */
662 continue;
663
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100664#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 /*
666 * Set full pathname for swap file now, because a ":!cd dir" may
667 * change directory without us knowing it.
668 */
669 p = FullName_save(fname, FALSE);
670 vim_free(fname);
671 fname = p;
672 if (fname == NULL)
673 continue;
674#endif
675 /* if the file name is the same we don't have to do anything */
676 if (fnamecmp(fname, mfp->mf_fname) == 0)
677 {
678 vim_free(fname);
679 success = TRUE;
680 break;
681 }
682 /* need to close the swap file before renaming */
683 if (mfp->mf_fd >= 0)
684 {
685 close(mfp->mf_fd);
686 mfp->mf_fd = -1;
687 }
688
689 /* try to rename the swap file */
690 if (vim_rename(mfp->mf_fname, fname) == 0)
691 {
692 success = TRUE;
693 vim_free(mfp->mf_fname);
694 mfp->mf_fname = fname;
695 vim_free(mfp->mf_ffname);
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100696#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 mfp->mf_ffname = NULL; /* mf_fname is full pathname already */
698#else
699 mf_set_ffname(mfp);
700#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200701 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 break;
703 }
704 vim_free(fname); /* this fname didn't work, try another */
705 }
706
707 if (mfp->mf_fd == -1) /* need to (re)open the swap file */
708 {
709 mfp->mf_fd = mch_open((char *)mfp->mf_fname, O_RDWR | O_EXTRA, 0);
710 if (mfp->mf_fd < 0)
711 {
712 /* could not (re)open the swap file, what can we do???? */
713 EMSG(_("E301: Oops, lost the swap file!!!"));
714 return;
715 }
Bram Moolenaarf05da212009-11-17 16:13:15 +0000716#ifdef HAVE_FD_CLOEXEC
717 {
718 int fdflags = fcntl(mfp->mf_fd, F_GETFD);
719 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +0100720 (void)fcntl(mfp->mf_fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +0000721 }
722#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
724 if (!success)
725 EMSG(_("E302: Could not rename swap file"));
726}
727
728/*
729 * Open a file for the memfile for all buffers that are not readonly or have
730 * been modified.
731 * Used when 'updatecount' changes from zero to non-zero.
732 */
733 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100734ml_open_files(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735{
736 buf_T *buf;
737
Bram Moolenaar29323592016-07-24 22:04:11 +0200738 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739 if (!buf->b_p_ro || buf->b_changed)
740 ml_open_file(buf);
741}
742
743/*
744 * Open a swap file for an existing memfile, if there is no swap file yet.
745 * If we are unable to find a file name, mf_fname will be NULL
746 * and the memfile will be in memory only (no recovery possible).
747 */
748 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100749ml_open_file(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750{
751 memfile_T *mfp;
752 char_u *fname;
753 char_u *dirp;
754
755 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar5803ae62014-03-23 16:04:02 +0100756 if (mfp == NULL || mfp->mf_fd >= 0 || !buf->b_p_swf || cmdmod.noswapfile)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000757 return; /* nothing to do */
758
Bram Moolenaara1956f62006-03-12 22:18:00 +0000759#ifdef FEAT_SPELL
Bram Moolenaar4770d092006-01-12 23:22:24 +0000760 /* For a spell buffer use a temp file name. */
761 if (buf->b_spell)
762 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +0200763 fname = vim_tempname('s', FALSE);
Bram Moolenaar4770d092006-01-12 23:22:24 +0000764 if (fname != NULL)
765 (void)mf_open_file(mfp, fname); /* consumes fname! */
766 buf->b_may_swap = FALSE;
767 return;
768 }
769#endif
770
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 /*
772 * Try all directories in 'directory' option.
773 */
774 dirp = p_dir;
775 for (;;)
776 {
777 if (*dirp == NUL)
778 break;
Bram Moolenaare242b832010-06-24 05:39:03 +0200779 /* There is a small chance that between choosing the swap file name
780 * and creating it, another Vim creates the file. In that case the
Bram Moolenaar071d4272004-06-13 20:20:40 +0000781 * creation will fail and we will use another directory. */
Bram Moolenaar8fc061c2004-12-29 21:03:02 +0000782 fname = findswapname(buf, &dirp, NULL); /* allocates fname */
Bram Moolenaarf541c362011-10-26 11:44:18 +0200783 if (dirp == NULL)
784 break; /* out of memory */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000785 if (fname == NULL)
786 continue;
787 if (mf_open_file(mfp, fname) == OK) /* consumes fname! */
788 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100789#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790 /*
791 * set full pathname for swap file now, because a ":!cd dir" may
792 * change directory without us knowing it.
793 */
794 mf_fullname(mfp);
795#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200796 ml_upd_block0(buf, UB_SAME_DIR);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000797
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798 /* Flush block zero, so others can read it */
799 if (mf_sync(mfp, MFS_ZERO) == OK)
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000800 {
801 /* Mark all blocks that should be in the swapfile as dirty.
802 * Needed for when the 'swapfile' option was reset, so that
803 * the swap file was deleted, and then on again. */
804 mf_set_dirty(mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805 break;
Bram Moolenaarc32840f2006-01-14 21:23:38 +0000806 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807 /* Writing block 0 failed: close the file and try another dir */
808 mf_close_file(buf, FALSE);
809 }
810 }
811
812 if (mfp->mf_fname == NULL) /* Failed! */
813 {
814 need_wait_return = TRUE; /* call wait_return later */
815 ++no_wait_return;
816 (void)EMSG2(_("E303: Unable to open swap file for \"%s\", recovery impossible"),
Bram Moolenaare1704ba2012-10-03 18:25:00 +0200817 buf_spname(buf) != NULL ? buf_spname(buf) : buf->b_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818 --no_wait_return;
819 }
820
821 /* don't try to open a swap file again */
822 buf->b_may_swap = FALSE;
823}
824
825/*
826 * If still need to create a swap file, and starting to edit a not-readonly
827 * file, or reading into an existing buffer, create a swap file now.
828 */
829 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100830check_need_swap(
831 int newfile) /* reading file into new buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832{
833 if (curbuf->b_may_swap && (!curbuf->b_p_ro || !newfile))
834 ml_open_file(curbuf);
835}
836
837/*
838 * Close memline for buffer 'buf'.
839 * If 'del_file' is TRUE, delete the swap file
840 */
841 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100842ml_close(buf_T *buf, int del_file)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843{
844 if (buf->b_ml.ml_mfp == NULL) /* not open */
845 return;
846 mf_close(buf->b_ml.ml_mfp, del_file); /* close the .swp file */
847 if (buf->b_ml.ml_line_lnum != 0 && (buf->b_ml.ml_flags & ML_LINE_DIRTY))
848 vim_free(buf->b_ml.ml_line_ptr);
849 vim_free(buf->b_ml.ml_stack);
850#ifdef FEAT_BYTEOFF
Bram Moolenaard23a8232018-02-10 18:45:26 +0100851 VIM_CLEAR(buf->b_ml.ml_chunksize);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852#endif
853 buf->b_ml.ml_mfp = NULL;
854
855 /* Reset the "recovered" flag, give the ATTENTION prompt the next time
856 * this buffer is loaded. */
857 buf->b_flags &= ~BF_RECOVERED;
858}
859
860/*
861 * Close all existing memlines and memfiles.
862 * Only used when exiting.
863 * When 'del_file' is TRUE, delete the memfiles.
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000864 * But don't delete files that were ":preserve"d when we are POSIX compatible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 */
866 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100867ml_close_all(int del_file)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000868{
869 buf_T *buf;
870
Bram Moolenaar29323592016-07-24 22:04:11 +0200871 FOR_ALL_BUFFERS(buf)
Bram Moolenaar81bf7082005-02-12 14:31:42 +0000872 ml_close(buf, del_file && ((buf->b_flags & BF_PRESERVED) == 0
873 || vim_strchr(p_cpo, CPO_PRESERVE) == NULL));
Bram Moolenaar34b466e2013-11-28 17:41:46 +0100874#ifdef FEAT_SPELL
875 spell_delete_wordlist(); /* delete the internal wordlist */
876#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000877#ifdef TEMPDIRNAMES
Bram Moolenaar34b466e2013-11-28 17:41:46 +0100878 vim_deltempdir(); /* delete created temp directory */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879#endif
880}
881
882/*
883 * Close all memfiles for not modified buffers.
884 * Only use just before exiting!
885 */
886 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100887ml_close_notmod(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000888{
889 buf_T *buf;
890
Bram Moolenaar29323592016-07-24 22:04:11 +0200891 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 if (!bufIsChanged(buf))
893 ml_close(buf, TRUE); /* close all not-modified buffers */
894}
895
896/*
897 * Update the timestamp in the .swp file.
898 * Used when the file has been written.
899 */
900 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100901ml_timestamp(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000902{
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200903 ml_upd_block0(buf, UB_FNAME);
904}
905
906/*
907 * Return FAIL when the ID of "b0p" is wrong.
908 */
909 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100910ml_check_b0_id(ZERO_BL *b0p)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200911{
912 if (b0p->b0_id[0] != BLOCK0_ID0
913 || (b0p->b0_id[1] != BLOCK0_ID1
914 && b0p->b0_id[1] != BLOCK0_ID1_C0
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200915 && b0p->b0_id[1] != BLOCK0_ID1_C1
916 && b0p->b0_id[1] != BLOCK0_ID1_C2)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200917 )
918 return FAIL;
919 return OK;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000920}
921
922/*
923 * Update the timestamp or the B0_SAME_DIR flag of the .swp file.
924 */
925 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100926ml_upd_block0(buf_T *buf, upd_block0_T what)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000927{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928 memfile_T *mfp;
929 bhdr_T *hp;
930 ZERO_BL *b0p;
931
932 mfp = buf->b_ml.ml_mfp;
Bram Moolenaar2be79502014-08-13 21:58:28 +0200933 if (mfp == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 return;
Bram Moolenaar2be79502014-08-13 21:58:28 +0200935 hp = mf_get(mfp, (blocknr_T)0, 1);
936 if (hp == NULL)
937 {
938#ifdef FEAT_CRYPT
939 /* Possibly update the seed in the memfile before there is a block0. */
940 if (what == UB_CRYPT)
941 ml_set_mfp_crypt(buf);
942#endif
943 return;
944 }
945
Bram Moolenaar071d4272004-06-13 20:20:40 +0000946 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200947 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar95f09602016-11-10 20:01:45 +0100948 IEMSG(_("E304: ml_upd_block0(): Didn't get block 0??"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000950 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200951 if (what == UB_FNAME)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000952 set_b0_fname(b0p, buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200953#ifdef FEAT_CRYPT
954 else if (what == UB_CRYPT)
955 ml_set_b0_crypt(buf, b0p);
956#endif
957 else /* what == UB_SAME_DIR */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000958 set_b0_dir_flag(b0p, buf);
959 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 mf_put(mfp, hp, TRUE, FALSE);
961}
962
963/*
964 * Write file name and timestamp into block 0 of a swap file.
965 * Also set buf->b_mtime.
966 * Don't use NameBuff[]!!!
967 */
968 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +0100969set_b0_fname(ZERO_BL *b0p, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970{
Bram Moolenaar8767f522016-07-01 17:17:39 +0200971 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000972
973 if (buf->b_ffname == NULL)
974 b0p->b0_fname[0] = NUL;
975 else
976 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100977#if defined(MSWIN) || defined(AMIGA)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000978 /* Systems that cannot translate "~user" back into a path: copy the
979 * file name unmodified. Do use slashes instead of backslashes for
980 * portability. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200981 vim_strncpy(b0p->b0_fname, buf->b_ffname, B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000982# ifdef BACKSLASH_IN_FILENAME
983 forward_slash(b0p->b0_fname);
984# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000985#else
986 size_t flen, ulen;
987 char_u uname[B0_UNAME_SIZE];
988
989 /*
990 * For a file under the home directory of the current user, we try to
991 * replace the home directory path with "~user". This helps when
992 * editing the same file on different machines over a network.
993 * First replace home dir path with "~/" with home_replace().
994 * Then insert the user name to get "~user/".
995 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200996 home_replace(NULL, buf->b_ffname, b0p->b0_fname,
997 B0_FNAME_SIZE_CRYPT, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998 if (b0p->b0_fname[0] == '~')
999 {
1000 flen = STRLEN(b0p->b0_fname);
1001 /* If there is no user name or it is too long, don't use "~/" */
1002 if (get_user_name(uname, B0_UNAME_SIZE) == FAIL
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001003 || (ulen = STRLEN(uname)) + flen > B0_FNAME_SIZE_CRYPT - 1)
1004 vim_strncpy(b0p->b0_fname, buf->b_ffname,
1005 B0_FNAME_SIZE_CRYPT - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001006 else
1007 {
1008 mch_memmove(b0p->b0_fname + ulen + 1, b0p->b0_fname + 1, flen);
1009 mch_memmove(b0p->b0_fname + 1, uname, ulen);
1010 }
1011 }
1012#endif
1013 if (mch_stat((char *)buf->b_ffname, &st) >= 0)
1014 {
1015 long_to_char((long)st.st_mtime, b0p->b0_mtime);
1016#ifdef CHECK_INODE
1017 long_to_char((long)st.st_ino, b0p->b0_ino);
1018#endif
1019 buf_store_time(buf, &st, buf->b_ffname);
1020 buf->b_mtime_read = buf->b_mtime;
1021 }
1022 else
1023 {
1024 long_to_char(0L, b0p->b0_mtime);
1025#ifdef CHECK_INODE
1026 long_to_char(0L, b0p->b0_ino);
1027#endif
1028 buf->b_mtime = 0;
1029 buf->b_mtime_read = 0;
1030 buf->b_orig_size = 0;
1031 buf->b_orig_mode = 0;
1032 }
1033 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001034
1035#ifdef FEAT_MBYTE
1036 /* Also add the 'fileencoding' if there is room. */
1037 add_b0_fenc(b0p, curbuf);
1038#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001039}
1040
1041/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001042 * Update the B0_SAME_DIR flag of the swap file. It's set if the file and the
1043 * swapfile for "buf" are in the same directory.
1044 * This is fail safe: if we are not sure the directories are equal the flag is
1045 * not set.
1046 */
1047 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01001048set_b0_dir_flag(ZERO_BL *b0p, buf_T *buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001049{
1050 if (same_directory(buf->b_ml.ml_mfp->mf_fname, buf->b_ffname))
1051 b0p->b0_flags |= B0_SAME_DIR;
1052 else
1053 b0p->b0_flags &= ~B0_SAME_DIR;
1054}
1055
1056#ifdef FEAT_MBYTE
1057/*
1058 * When there is room, add the 'fileencoding' to block zero.
1059 */
1060 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01001061add_b0_fenc(
1062 ZERO_BL *b0p,
1063 buf_T *buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001064{
1065 int n;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001066 int size = B0_FNAME_SIZE_NOCRYPT;
1067
1068# ifdef FEAT_CRYPT
1069 /* Without encryption use the same offset as in Vim 7.2 to be compatible.
1070 * With encryption it's OK to move elsewhere, the swap file is not
1071 * compatible anyway. */
1072 if (*buf->b_p_key != NUL)
1073 size = B0_FNAME_SIZE_CRYPT;
1074# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001075
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001076 n = (int)STRLEN(buf->b_p_fenc);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001077 if ((int)STRLEN(b0p->b0_fname) + n + 1 > size)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001078 b0p->b0_flags &= ~B0_HAS_FENC;
1079 else
1080 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001081 mch_memmove((char *)b0p->b0_fname + size - n,
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001082 (char *)buf->b_p_fenc, (size_t)n);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001083 *(b0p->b0_fname + size - n - 1) = NUL;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001084 b0p->b0_flags |= B0_HAS_FENC;
1085 }
1086}
1087#endif
1088
1089
1090/*
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001091 * Try to recover curbuf from the .swp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 */
1093 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01001094ml_recover(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095{
1096 buf_T *buf = NULL;
1097 memfile_T *mfp = NULL;
1098 char_u *fname;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001099 char_u *fname_used = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001100 bhdr_T *hp = NULL;
1101 ZERO_BL *b0p;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001102 int b0_ff;
1103 char_u *b0_fenc = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001104#ifdef FEAT_CRYPT
1105 int b0_cm = -1;
1106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107 PTR_BL *pp;
1108 DATA_BL *dp;
1109 infoptr_T *ip;
1110 blocknr_T bnum;
1111 int page_count;
Bram Moolenaar8767f522016-07-01 17:17:39 +02001112 stat_T org_stat, swp_stat;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 int len;
1114 int directly;
1115 linenr_T lnum;
1116 char_u *p;
1117 int i;
1118 long error;
1119 int cannot_open;
1120 linenr_T line_count;
1121 int has_error;
1122 int idx;
1123 int top;
1124 int txt_start;
Bram Moolenaar8767f522016-07-01 17:17:39 +02001125 off_T size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126 int called_from_main;
1127 int serious_error = TRUE;
1128 long mtime;
1129 int attr;
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001130 int orig_file_status = NOTDONE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001131
1132 recoverymode = TRUE;
1133 called_from_main = (curbuf->b_ml.ml_mfp == NULL);
Bram Moolenaar8820b482017-03-16 17:23:31 +01001134 attr = HL_ATTR(HLF_E);
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001135
1136 /*
Bram Moolenaaraf903e52017-12-02 15:11:22 +01001137 * If the file name ends in ".s[a-w][a-z]" we assume this is the swap file.
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001138 * Otherwise a search is done to find the swap file(s).
1139 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140 fname = curbuf->b_fname;
1141 if (fname == NULL) /* When there is no file name */
1142 fname = (char_u *)"";
1143 len = (int)STRLEN(fname);
1144 if (len >= 4 &&
Bram Moolenaare60acc12011-05-10 16:41:25 +02001145#if defined(VMS)
Bram Moolenaar79518e22017-02-17 16:31:35 +01001146 STRNICMP(fname + len - 4, "_s", 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147#else
Bram Moolenaar79518e22017-02-17 16:31:35 +01001148 STRNICMP(fname + len - 4, ".s", 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149#endif
Bram Moolenaar79518e22017-02-17 16:31:35 +01001150 == 0
Bram Moolenaaraf903e52017-12-02 15:11:22 +01001151 && vim_strchr((char_u *)"abcdefghijklmnopqrstuvw",
1152 TOLOWER_ASC(fname[len - 2])) != NULL
Bram Moolenaard0ba34a2009-11-03 12:06:23 +00001153 && ASCII_ISALPHA(fname[len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 {
1155 directly = TRUE;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001156 fname_used = vim_strsave(fname); /* make a copy for mf_open() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 }
1158 else
1159 {
1160 directly = FALSE;
1161
1162 /* count the number of matching swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001163 len = recover_names(fname, FALSE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001164 if (len == 0) /* no swap files found */
1165 {
1166 EMSG2(_("E305: No swap file found for %s"), fname);
1167 goto theend;
1168 }
1169 if (len == 1) /* one swap file found, use it */
1170 i = 1;
1171 else /* several swap files found, choose */
1172 {
1173 /* list the names of the swap files */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001174 (void)recover_names(fname, TRUE, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175 msg_putchar('\n');
1176 MSG_PUTS(_("Enter number of swap file to use (0 to quit): "));
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00001177 i = get_number(FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 if (i < 1 || i > len)
1179 goto theend;
1180 }
1181 /* get the swap file name that will be used */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001182 (void)recover_names(fname, FALSE, i, &fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001184 if (fname_used == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 goto theend; /* out of memory */
1186
1187 /* When called from main() still need to initialize storage structure */
Bram Moolenaar4770d092006-01-12 23:22:24 +00001188 if (called_from_main && ml_open(curbuf) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189 getout(1);
1190
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001191 /*
1192 * Allocate a buffer structure for the swap file that is used for recovery.
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001193 * Only the memline and crypt information in it are really used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001194 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195 buf = (buf_T *)alloc((unsigned)sizeof(buf_T));
1196 if (buf == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001197 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001199 /*
1200 * init fields in memline struct
1201 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1203 buf->b_ml.ml_stack = NULL; /* no stack yet */
1204 buf->b_ml.ml_stack_top = 0; /* nothing in the stack */
1205 buf->b_ml.ml_line_lnum = 0; /* no cached line */
1206 buf->b_ml.ml_locked = NULL; /* no locked block */
1207 buf->b_ml.ml_flags = 0;
Bram Moolenaar0fe849a2010-07-25 15:11:11 +02001208#ifdef FEAT_CRYPT
1209 buf->b_p_key = empty_option;
1210 buf->b_p_cm = empty_option;
1211#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001212
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001213 /*
1214 * open the memfile from the old swap file
1215 */
1216 p = vim_strsave(fname_used); /* save "fname_used" for the message:
1217 mf_open() will consume "fname_used"! */
1218 mfp = mf_open(fname_used, O_RDONLY);
1219 fname_used = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001220 if (mfp == NULL || mfp->mf_fd < 0)
1221 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001222 if (fname_used != NULL)
1223 EMSG2(_("E306: Cannot open %s"), fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001224 goto theend;
1225 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 buf->b_ml.ml_mfp = mfp;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001227#ifdef FEAT_CRYPT
1228 mfp->mf_buffer = buf;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001229#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230
1231 /*
1232 * The page size set in mf_open() might be different from the page size
1233 * used in the swap file, we must get it from block 0. But to read block
1234 * 0 we need a page size. Use the minimal size for block 0 here, it will
1235 * be set to the real value below.
1236 */
1237 mfp->mf_page_size = MIN_SWAP_PAGE_SIZE;
1238
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001239 /*
1240 * try to read block 0
1241 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242 if ((hp = mf_get(mfp, (blocknr_T)0, 1)) == NULL)
1243 {
1244 msg_start();
1245 MSG_PUTS_ATTR(_("Unable to read block 0 from "), attr | MSG_HIST);
1246 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001247 MSG_PUTS_ATTR(_("\nMaybe no changes were made or Vim did not update the swap file."),
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248 attr | MSG_HIST);
1249 msg_end();
1250 goto theend;
1251 }
1252 b0p = (ZERO_BL *)(hp->bh_data);
1253 if (STRNCMP(b0p->b0_version, "VIM 3.0", 7) == 0)
1254 {
1255 msg_start();
1256 msg_outtrans_attr(mfp->mf_fname, MSG_HIST);
1257 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1258 MSG_HIST);
1259 MSG_PUTS_ATTR(_("Use Vim version 3.0.\n"), MSG_HIST);
1260 msg_end();
1261 goto theend;
1262 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001263 if (ml_check_b0_id(b0p) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 {
1265 EMSG2(_("E307: %s does not look like a Vim swap file"), mfp->mf_fname);
1266 goto theend;
1267 }
1268 if (b0_magic_wrong(b0p))
1269 {
1270 msg_start();
1271 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
Bram Moolenaar48e330a2016-02-23 14:53:34 +01001272#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 if (STRNCMP(b0p->b0_hname, "PC ", 3) == 0)
1274 MSG_PUTS_ATTR(_(" cannot be used with this version of Vim.\n"),
1275 attr | MSG_HIST);
1276 else
1277#endif
1278 MSG_PUTS_ATTR(_(" cannot be used on this computer.\n"),
1279 attr | MSG_HIST);
1280 MSG_PUTS_ATTR(_("The file was created on "), attr | MSG_HIST);
Bram Moolenaare242b832010-06-24 05:39:03 +02001281 /* avoid going past the end of a corrupted hostname */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282 b0p->b0_fname[0] = NUL;
1283 MSG_PUTS_ATTR(b0p->b0_hname, attr | MSG_HIST);
1284 MSG_PUTS_ATTR(_(",\nor the file has been damaged."), attr | MSG_HIST);
1285 msg_end();
1286 goto theend;
1287 }
Bram Moolenaar1c536282007-04-26 15:21:56 +00001288
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001289#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001290 for (i = 0; i < (int)(sizeof(id1_codes) / sizeof(int)); ++i)
1291 if (id1_codes[i] == b0p->b0_id[1])
1292 b0_cm = i;
1293 if (b0_cm > 0)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001294 mch_memmove(mfp->mf_seed, &b0p->b0_seed, MF_SEED_LEN);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001295 crypt_set_cm_option(buf, b0_cm < 0 ? 0 : b0_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001296#else
1297 if (b0p->b0_id[1] != BLOCK0_ID1)
1298 {
Bram Moolenaar996343d2010-07-04 22:20:21 +02001299 EMSG2(_("E833: %s is encrypted and this version of Vim does not support encryption"), mfp->mf_fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001300 goto theend;
1301 }
1302#endif
1303
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304 /*
1305 * If we guessed the wrong page size, we have to recalculate the
1306 * highest block number in the file.
1307 */
1308 if (mfp->mf_page_size != (unsigned)char_to_long(b0p->b0_page_size))
1309 {
Bram Moolenaar1c536282007-04-26 15:21:56 +00001310 unsigned previous_page_size = mfp->mf_page_size;
1311
Bram Moolenaar071d4272004-06-13 20:20:40 +00001312 mf_new_page_size(mfp, (unsigned)char_to_long(b0p->b0_page_size));
Bram Moolenaar1c536282007-04-26 15:21:56 +00001313 if (mfp->mf_page_size < previous_page_size)
1314 {
1315 msg_start();
1316 msg_outtrans_attr(mfp->mf_fname, attr | MSG_HIST);
1317 MSG_PUTS_ATTR(_(" has been damaged (page size is smaller than minimum value).\n"),
1318 attr | MSG_HIST);
1319 msg_end();
1320 goto theend;
1321 }
Bram Moolenaar8767f522016-07-01 17:17:39 +02001322 if ((size = vim_lseek(mfp->mf_fd, (off_T)0L, SEEK_END)) <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323 mfp->mf_blocknr_max = 0; /* no file or empty file */
1324 else
1325 mfp->mf_blocknr_max = (blocknr_T)(size / mfp->mf_page_size);
1326 mfp->mf_infile_count = mfp->mf_blocknr_max;
Bram Moolenaar1c536282007-04-26 15:21:56 +00001327
1328 /* need to reallocate the memory used to store the data */
1329 p = alloc(mfp->mf_page_size);
1330 if (p == NULL)
1331 goto theend;
1332 mch_memmove(p, hp->bh_data, previous_page_size);
1333 vim_free(hp->bh_data);
1334 hp->bh_data = p;
1335 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001336 }
1337
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001338 /*
1339 * If .swp file name given directly, use name from swap file for buffer.
1340 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 if (directly)
1342 {
1343 expand_env(b0p->b0_fname, NameBuff, MAXPATHL);
1344 if (setfname(curbuf, NameBuff, NULL, TRUE) == FAIL)
1345 goto theend;
1346 }
1347
1348 home_replace(NULL, mfp->mf_fname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001349 smsg((char_u *)_("Using swap file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001350
1351 if (buf_spname(curbuf) != NULL)
Bram Moolenaare1704ba2012-10-03 18:25:00 +02001352 vim_strncpy(NameBuff, buf_spname(curbuf), MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001353 else
1354 home_replace(NULL, curbuf->b_ffname, NameBuff, MAXPATHL, TRUE);
Bram Moolenaar555b2802005-05-19 21:08:39 +00001355 smsg((char_u *)_("Original file \"%s\""), NameBuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001356 msg_putchar('\n');
1357
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001358 /*
1359 * check date of swap file and original file
1360 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361 mtime = char_to_long(b0p->b0_mtime);
1362 if (curbuf->b_ffname != NULL
1363 && mch_stat((char *)curbuf->b_ffname, &org_stat) != -1
1364 && ((mch_stat((char *)mfp->mf_fname, &swp_stat) != -1
1365 && org_stat.st_mtime > swp_stat.st_mtime)
1366 || org_stat.st_mtime != mtime))
1367 {
1368 EMSG(_("E308: Warning: Original file may have been changed"));
1369 }
1370 out_flush();
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001371
1372 /* Get the 'fileformat' and 'fileencoding' from block zero. */
1373 b0_ff = (b0p->b0_flags & B0_FF_MASK);
1374 if (b0p->b0_flags & B0_HAS_FENC)
1375 {
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001376 int fnsize = B0_FNAME_SIZE_NOCRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001377
1378#ifdef FEAT_CRYPT
1379 /* Use the same size as in add_b0_fenc(). */
1380 if (b0p->b0_id[1] != BLOCK0_ID1)
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001381 fnsize = B0_FNAME_SIZE_CRYPT;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001382#endif
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001383 for (p = b0p->b0_fname + fnsize; p > b0p->b0_fname && p[-1] != NUL; --p)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001384 ;
Bram Moolenaarf506c5b2010-06-22 06:28:58 +02001385 b0_fenc = vim_strnsave(p, (int)(b0p->b0_fname + fnsize - p));
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001386 }
1387
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 mf_put(mfp, hp, FALSE, FALSE); /* release block 0 */
1389 hp = NULL;
1390
1391 /*
1392 * Now that we are sure that the file is going to be recovered, clear the
1393 * contents of the current buffer.
1394 */
1395 while (!(curbuf->b_ml.ml_flags & ML_EMPTY))
1396 ml_delete((linenr_T)1, FALSE);
1397
1398 /*
1399 * Try reading the original file to obtain the values of 'fileformat',
1400 * 'fileencoding', etc. Ignore errors. The text itself is not used.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001401 * When the file is encrypted the user is asked to enter the key.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402 */
1403 if (curbuf->b_ffname != NULL)
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001404 orig_file_status = readfile(curbuf->b_ffname, NULL, (linenr_T)0,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001405 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001406
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001407#ifdef FEAT_CRYPT
1408 if (b0_cm >= 0)
1409 {
1410 /* Need to ask the user for the crypt key. If this fails we continue
1411 * without a key, will probably get garbage text. */
1412 if (*curbuf->b_p_key != NUL)
1413 {
1414 smsg((char_u *)_("Swap file is encrypted: \"%s\""), fname_used);
1415 MSG_PUTS(_("\nIf you entered a new crypt key but did not write the text file,"));
1416 MSG_PUTS(_("\nenter the new crypt key."));
1417 MSG_PUTS(_("\nIf you wrote the text file after changing the crypt key press enter"));
1418 MSG_PUTS(_("\nto use the same key for text file and swap file"));
1419 }
1420 else
1421 smsg((char_u *)_(need_key_msg), fname_used);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001422 buf->b_p_key = crypt_get_key(FALSE, FALSE);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001423 if (buf->b_p_key == NULL)
1424 buf->b_p_key = curbuf->b_p_key;
1425 else if (*buf->b_p_key == NUL)
1426 {
1427 vim_free(buf->b_p_key);
1428 buf->b_p_key = curbuf->b_p_key;
1429 }
1430 if (buf->b_p_key == NULL)
1431 buf->b_p_key = empty_option;
1432 }
1433#endif
1434
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001435 /* Use the 'fileformat' and 'fileencoding' as stored in the swap file. */
1436 if (b0_ff != 0)
1437 set_fileformat(b0_ff - 1, OPT_LOCAL);
1438 if (b0_fenc != NULL)
1439 {
1440 set_option_value((char_u *)"fenc", 0L, b0_fenc, OPT_LOCAL);
1441 vim_free(b0_fenc);
1442 }
1443 unchanged(curbuf, TRUE);
1444
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445 bnum = 1; /* start with block 1 */
1446 page_count = 1; /* which is 1 page */
1447 lnum = 0; /* append after line 0 in curbuf */
1448 line_count = 0;
1449 idx = 0; /* start with first index in block 1 */
1450 error = 0;
1451 buf->b_ml.ml_stack_top = 0;
1452 buf->b_ml.ml_stack = NULL;
1453 buf->b_ml.ml_stack_size = 0; /* no stack yet */
1454
1455 if (curbuf->b_ffname == NULL)
1456 cannot_open = TRUE;
1457 else
1458 cannot_open = FALSE;
1459
1460 serious_error = FALSE;
1461 for ( ; !got_int; line_breakcheck())
1462 {
1463 if (hp != NULL)
1464 mf_put(mfp, hp, FALSE, FALSE); /* release previous block */
1465
1466 /*
1467 * get block
1468 */
1469 if ((hp = mf_get(mfp, (blocknr_T)bnum, page_count)) == NULL)
1470 {
1471 if (bnum == 1)
1472 {
1473 EMSG2(_("E309: Unable to read block 1 from %s"), mfp->mf_fname);
1474 goto theend;
1475 }
1476 ++error;
1477 ml_append(lnum++, (char_u *)_("???MANY LINES MISSING"),
1478 (colnr_T)0, TRUE);
1479 }
1480 else /* there is a block */
1481 {
1482 pp = (PTR_BL *)(hp->bh_data);
1483 if (pp->pb_id == PTR_ID) /* it is a pointer block */
1484 {
1485 /* check line count when using pointer block first time */
1486 if (idx == 0 && line_count != 0)
1487 {
1488 for (i = 0; i < (int)pp->pb_count; ++i)
1489 line_count -= pp->pb_pointer[i].pe_line_count;
1490 if (line_count != 0)
1491 {
1492 ++error;
1493 ml_append(lnum++, (char_u *)_("???LINE COUNT WRONG"),
1494 (colnr_T)0, TRUE);
1495 }
1496 }
1497
1498 if (pp->pb_count == 0)
1499 {
1500 ml_append(lnum++, (char_u *)_("???EMPTY BLOCK"),
1501 (colnr_T)0, TRUE);
1502 ++error;
1503 }
1504 else if (idx < (int)pp->pb_count) /* go a block deeper */
1505 {
1506 if (pp->pb_pointer[idx].pe_bnum < 0)
1507 {
1508 /*
1509 * Data block with negative block number.
1510 * Try to read lines from the original file.
1511 * This is slow, but it works.
1512 */
1513 if (!cannot_open)
1514 {
1515 line_count = pp->pb_pointer[idx].pe_line_count;
1516 if (readfile(curbuf->b_ffname, NULL, lnum,
1517 pp->pb_pointer[idx].pe_old_lnum - 1,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01001518 line_count, NULL, 0) != OK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519 cannot_open = TRUE;
1520 else
1521 lnum += line_count;
1522 }
1523 if (cannot_open)
1524 {
1525 ++error;
1526 ml_append(lnum++, (char_u *)_("???LINES MISSING"),
1527 (colnr_T)0, TRUE);
1528 }
1529 ++idx; /* get same block again for next index */
1530 continue;
1531 }
1532
1533 /*
1534 * going one block deeper in the tree
1535 */
1536 if ((top = ml_add_stack(buf)) < 0) /* new entry in stack */
1537 {
1538 ++error;
1539 break; /* out of memory */
1540 }
1541 ip = &(buf->b_ml.ml_stack[top]);
1542 ip->ip_bnum = bnum;
1543 ip->ip_index = idx;
1544
1545 bnum = pp->pb_pointer[idx].pe_bnum;
1546 line_count = pp->pb_pointer[idx].pe_line_count;
1547 page_count = pp->pb_pointer[idx].pe_page_count;
Bram Moolenaar986a0032011-06-13 01:07:27 +02001548 idx = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 continue;
1550 }
1551 }
1552 else /* not a pointer block */
1553 {
1554 dp = (DATA_BL *)(hp->bh_data);
1555 if (dp->db_id != DATA_ID) /* block id wrong */
1556 {
1557 if (bnum == 1)
1558 {
1559 EMSG2(_("E310: Block 1 ID wrong (%s not a .swp file?)"),
1560 mfp->mf_fname);
1561 goto theend;
1562 }
1563 ++error;
1564 ml_append(lnum++, (char_u *)_("???BLOCK MISSING"),
1565 (colnr_T)0, TRUE);
1566 }
1567 else
1568 {
1569 /*
1570 * it is a data block
1571 * Append all the lines in this block
1572 */
1573 has_error = FALSE;
1574 /*
1575 * check length of block
1576 * if wrong, use length in pointer block
1577 */
1578 if (page_count * mfp->mf_page_size != dp->db_txt_end)
1579 {
1580 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may be messed up"),
1581 (colnr_T)0, TRUE);
1582 ++error;
1583 has_error = TRUE;
1584 dp->db_txt_end = page_count * mfp->mf_page_size;
1585 }
1586
1587 /* make sure there is a NUL at the end of the block */
1588 *((char_u *)dp + dp->db_txt_end - 1) = NUL;
1589
1590 /*
1591 * check number of lines in block
1592 * if wrong, use count in data block
1593 */
1594 if (line_count != dp->db_line_count)
1595 {
1596 ml_append(lnum++, (char_u *)_("??? from here until ???END lines may have been inserted/deleted"),
1597 (colnr_T)0, TRUE);
1598 ++error;
1599 has_error = TRUE;
1600 }
1601
1602 for (i = 0; i < dp->db_line_count; ++i)
1603 {
1604 txt_start = (dp->db_index[i] & DB_INDEX_MASK);
Bram Moolenaar740885b2009-11-03 14:33:17 +00001605 if (txt_start <= (int)HEADER_SIZE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606 || txt_start >= (int)dp->db_txt_end)
1607 {
1608 p = (char_u *)"???";
1609 ++error;
1610 }
1611 else
1612 p = (char_u *)dp + txt_start;
1613 ml_append(lnum++, p, (colnr_T)0, TRUE);
1614 }
1615 if (has_error)
Bram Moolenaar740885b2009-11-03 14:33:17 +00001616 ml_append(lnum++, (char_u *)_("???END"),
1617 (colnr_T)0, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 }
1619 }
1620 }
1621
1622 if (buf->b_ml.ml_stack_top == 0) /* finished */
1623 break;
1624
1625 /*
1626 * go one block up in the tree
1627 */
1628 ip = &(buf->b_ml.ml_stack[--(buf->b_ml.ml_stack_top)]);
1629 bnum = ip->ip_bnum;
1630 idx = ip->ip_index + 1; /* go to next index */
1631 page_count = 1;
1632 }
1633
1634 /*
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001635 * Compare the buffer contents with the original file. When they differ
1636 * set the 'modified' flag.
1637 * Lines 1 - lnum are the new contents.
1638 * Lines lnum + 1 to ml_line_count are the original contents.
1639 * Line ml_line_count + 1 in the dummy empty line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 */
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001641 if (orig_file_status != OK || curbuf->b_ml.ml_line_count != lnum * 2 + 1)
1642 {
1643 /* Recovering an empty file results in two lines and the first line is
1644 * empty. Don't set the modified flag then. */
1645 if (!(curbuf->b_ml.ml_line_count == 2 && *ml_get(1) == NUL))
1646 {
1647 changed_int();
Bram Moolenaar95c526e2017-02-25 14:59:34 +01001648 ++CHANGEDTICK(curbuf);
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001649 }
1650 }
1651 else
1652 {
1653 for (idx = 1; idx <= lnum; ++idx)
1654 {
1655 /* Need to copy one line, fetching the other one may flush it. */
1656 p = vim_strsave(ml_get(idx));
1657 i = STRCMP(p, ml_get(idx + lnum));
1658 vim_free(p);
1659 if (i != 0)
1660 {
1661 changed_int();
Bram Moolenaar95c526e2017-02-25 14:59:34 +01001662 ++CHANGEDTICK(curbuf);
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001663 break;
1664 }
1665 }
1666 }
1667
1668 /*
1669 * Delete the lines from the original file and the dummy line from the
1670 * empty buffer. These will now be after the last line in the buffer.
1671 */
1672 while (curbuf->b_ml.ml_line_count > lnum
1673 && !(curbuf->b_ml.ml_flags & ML_EMPTY))
1674 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 curbuf->b_flags |= BF_RECOVERED;
1676
1677 recoverymode = FALSE;
1678 if (got_int)
1679 EMSG(_("E311: Recovery Interrupted"));
1680 else if (error)
1681 {
1682 ++no_wait_return;
1683 MSG(">>>>>>>>>>>>>");
1684 EMSG(_("E312: Errors detected while recovering; look for lines starting with ???"));
1685 --no_wait_return;
1686 MSG(_("See \":help E312\" for more information."));
1687 MSG(">>>>>>>>>>>>>");
1688 }
1689 else
1690 {
Bram Moolenaarfc2d5bd2010-05-15 17:06:53 +02001691 if (curbuf->b_changed)
1692 {
1693 MSG(_("Recovery completed. You should check if everything is OK."));
1694 MSG_PUTS(_("\n(You might want to write out this file under another name\n"));
1695 MSG_PUTS(_("and run diff with the original file to check for changes)"));
1696 }
1697 else
1698 MSG(_("Recovery completed. Buffer contents equals file contents."));
1699 MSG_PUTS(_("\nYou may want to delete the .swp file now.\n\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 cmdline_row = msg_row;
1701 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001702#ifdef FEAT_CRYPT
1703 if (*buf->b_p_key != NUL && STRCMP(curbuf->b_p_key, buf->b_p_key) != 0)
1704 {
1705 MSG_PUTS(_("Using crypt key from swap file for the text file.\n"));
1706 set_option_value((char_u *)"key", 0L, buf->b_p_key, OPT_LOCAL);
1707 }
1708#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 redraw_curbuf_later(NOT_VALID);
1710
1711theend:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001712 vim_free(fname_used);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 recoverymode = FALSE;
1714 if (mfp != NULL)
1715 {
1716 if (hp != NULL)
1717 mf_put(mfp, hp, FALSE, FALSE);
1718 mf_close(mfp, FALSE); /* will also vim_free(mfp->mf_fname) */
1719 }
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001720 if (buf != NULL)
1721 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001722#ifdef FEAT_CRYPT
1723 if (buf->b_p_key != curbuf->b_p_key)
1724 free_string_option(buf->b_p_key);
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02001725 free_string_option(buf->b_p_cm);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001726#endif
Bram Moolenaardf88dda2007-01-09 13:34:50 +00001727 vim_free(buf->b_ml.ml_stack);
1728 vim_free(buf);
1729 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 if (serious_error && called_from_main)
1731 ml_close(curbuf, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 else
1733 {
1734 apply_autocmds(EVENT_BUFREADPOST, NULL, curbuf->b_fname, FALSE, curbuf);
1735 apply_autocmds(EVENT_BUFWINENTER, NULL, curbuf->b_fname, FALSE, curbuf);
1736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001737 return;
1738}
1739
1740/*
1741 * Find the names of swap files in current directory and the directory given
1742 * with the 'directory' option.
1743 *
1744 * Used to:
1745 * - list the swap files for "vim -r"
1746 * - count the number of swap files when recovering
1747 * - list the swap files when recovering
1748 * - find the name of the n'th swap file when recovering
1749 */
1750 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01001751recover_names(
1752 char_u *fname, /* base for swap file name */
1753 int list, /* when TRUE, list the swap file names */
1754 int nr, /* when non-zero, return nr'th swap file name */
1755 char_u **fname_out) /* result when "nr" > 0 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756{
1757 int num_names;
1758 char_u *(names[6]);
1759 char_u *tail;
1760 char_u *p;
1761 int num_files;
1762 int file_count = 0;
1763 char_u **files;
1764 int i;
1765 char_u *dirp;
1766 char_u *dir_name;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001767 char_u *fname_res = NULL;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001768#ifdef HAVE_READLINK
1769 char_u fname_buf[MAXPATHL];
Bram Moolenaar64354da2010-05-25 21:37:17 +02001770#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001771
Bram Moolenaar64354da2010-05-25 21:37:17 +02001772 if (fname != NULL)
1773 {
1774#ifdef HAVE_READLINK
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001775 /* Expand symlink in the file name, because the swap file is created
1776 * with the actual file instead of with the symlink. */
1777 if (resolve_symlink(fname, fname_buf) == OK)
1778 fname_res = fname_buf;
1779 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001780#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001781 fname_res = fname;
Bram Moolenaar64354da2010-05-25 21:37:17 +02001782 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783
1784 if (list)
1785 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001786 /* use msg() to start the scrolling properly */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787 msg((char_u *)_("Swap files found:"));
1788 msg_putchar('\n');
1789 }
1790
1791 /*
1792 * Do the loop for every directory in 'directory'.
1793 * First allocate some memory to put the directory name in.
1794 */
1795 dir_name = alloc((unsigned)STRLEN(p_dir) + 1);
1796 dirp = p_dir;
1797 while (dir_name != NULL && *dirp)
1798 {
1799 /*
1800 * Isolate a directory name from *dirp and put it in dir_name (we know
1801 * it is large enough, so use 31000 for length).
1802 * Advance dirp to next directory name.
1803 */
1804 (void)copy_option_part(&dirp, dir_name, 31000, ",");
1805
1806 if (dir_name[0] == '.' && dir_name[1] == NUL) /* check current dir */
1807 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001808 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 {
1810#ifdef VMS
1811 names[0] = vim_strsave((char_u *)"*_sw%");
1812#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 names[0] = vim_strsave((char_u *)"*.sw?");
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001815#if defined(UNIX) || defined(WIN3264)
1816 /* For Unix names starting with a dot are special. MS-Windows
1817 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 names[1] = vim_strsave((char_u *)".*.sw?");
1819 names[2] = vim_strsave((char_u *)".sw?");
1820 num_names = 3;
1821#else
1822# ifdef VMS
1823 names[1] = vim_strsave((char_u *)".*_sw%");
1824 num_names = 2;
1825# else
1826 num_names = 1;
1827# endif
1828#endif
1829 }
1830 else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001831 num_names = recov_file_names(names, fname_res, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 }
1833 else /* check directory dir_name */
1834 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001835 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 {
1837#ifdef VMS
1838 names[0] = concat_fnames(dir_name, (char_u *)"*_sw%", TRUE);
1839#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 names[0] = concat_fnames(dir_name, (char_u *)"*.sw?", TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841#endif
Bram Moolenaar2cc93182006-10-10 19:56:03 +00001842#if defined(UNIX) || defined(WIN3264)
1843 /* For Unix names starting with a dot are special. MS-Windows
1844 * supports this too, on some file systems. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845 names[1] = concat_fnames(dir_name, (char_u *)".*.sw?", TRUE);
1846 names[2] = concat_fnames(dir_name, (char_u *)".sw?", TRUE);
1847 num_names = 3;
1848#else
1849# ifdef VMS
1850 names[1] = concat_fnames(dir_name, (char_u *)".*_sw%", TRUE);
1851 num_names = 2;
1852# else
1853 num_names = 1;
1854# endif
1855#endif
1856 }
1857 else
1858 {
1859#if defined(UNIX) || defined(WIN3264)
Bram Moolenaarb113c3a2017-02-28 21:26:17 +01001860 int len = (int)STRLEN(dir_name);
Bram Moolenaarc525e3a2017-02-18 16:59:02 +01001861
1862 p = dir_name + len;
1863 if (after_pathsep(dir_name, p) && len > 1 && p[-1] == p[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864 {
1865 /* Ends with '//', Use Full path for swap name */
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001866 tail = make_percent_swname(dir_name, fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867 }
1868 else
1869#endif
1870 {
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001871 tail = gettail(fname_res);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 tail = concat_fnames(dir_name, tail, TRUE);
1873 }
1874 if (tail == NULL)
1875 num_names = 0;
1876 else
1877 {
1878 num_names = recov_file_names(names, tail, FALSE);
1879 vim_free(tail);
1880 }
1881 }
1882 }
1883
1884 /* check for out-of-memory */
1885 for (i = 0; i < num_names; ++i)
1886 {
1887 if (names[i] == NULL)
1888 {
1889 for (i = 0; i < num_names; ++i)
1890 vim_free(names[i]);
1891 num_names = 0;
1892 }
1893 }
1894 if (num_names == 0)
1895 num_files = 0;
1896 else if (expand_wildcards(num_names, names, &num_files, &files,
1897 EW_KEEPALL|EW_FILE|EW_SILENT) == FAIL)
1898 num_files = 0;
1899
1900 /*
1901 * When no swap file found, wildcard expansion might have failed (e.g.
1902 * not able to execute the shell).
1903 * Try finding a swap file by simply adding ".swp" to the file name.
1904 */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001905 if (*dirp == NUL && file_count + num_files == 0 && fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02001907 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 char_u *swapname;
1909
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001910 swapname = modname(fname_res,
Bram Moolenaare60acc12011-05-10 16:41:25 +02001911#if defined(VMS)
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001912 (char_u *)"_swp", FALSE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913#else
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001914 (char_u *)".swp", TRUE
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915#endif
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02001916 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 if (swapname != NULL)
1918 {
1919 if (mch_stat((char *)swapname, &st) != -1) /* It exists! */
1920 {
1921 files = (char_u **)alloc((unsigned)sizeof(char_u *));
1922 if (files != NULL)
1923 {
1924 files[0] = swapname;
1925 swapname = NULL;
1926 num_files = 1;
1927 }
1928 }
1929 vim_free(swapname);
1930 }
1931 }
1932
1933 /*
1934 * remove swapfile name of the current buffer, it must be ignored
1935 */
1936 if (curbuf->b_ml.ml_mfp != NULL
1937 && (p = curbuf->b_ml.ml_mfp->mf_fname) != NULL)
1938 {
1939 for (i = 0; i < num_files; ++i)
1940 if (fullpathcmp(p, files[i], TRUE) & FPC_SAME)
1941 {
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001942 /* Remove the name from files[i]. Move further entries
1943 * down. When the array becomes empty free it here, since
1944 * FreeWild() won't be called below. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 vim_free(files[i]);
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00001946 if (--num_files == 0)
1947 vim_free(files);
1948 else
1949 for ( ; i < num_files; ++i)
1950 files[i] = files[i + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 }
1952 }
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00001953 if (nr > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 {
1955 file_count += num_files;
1956 if (nr <= file_count)
1957 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001958 *fname_out = vim_strsave(
1959 files[nr - 1 + num_files - file_count]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 dirp = (char_u *)""; /* stop searching */
1961 }
1962 }
1963 else if (list)
1964 {
1965 if (dir_name[0] == '.' && dir_name[1] == NUL)
1966 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001967 if (fname == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 MSG_PUTS(_(" In current directory:\n"));
1969 else
1970 MSG_PUTS(_(" Using specified name:\n"));
1971 }
1972 else
1973 {
1974 MSG_PUTS(_(" In directory "));
1975 msg_home_replace(dir_name);
1976 MSG_PUTS(":\n");
1977 }
1978
1979 if (num_files)
1980 {
1981 for (i = 0; i < num_files; ++i)
1982 {
1983 /* print the swap file name */
1984 msg_outnum((long)++file_count);
1985 MSG_PUTS(". ");
1986 msg_puts(gettail(files[i]));
1987 msg_putchar('\n');
1988 (void)swapfile_info(files[i]);
1989 }
1990 }
1991 else
1992 MSG_PUTS(_(" -- none --\n"));
1993 out_flush();
1994 }
1995 else
1996 file_count += num_files;
1997
1998 for (i = 0; i < num_names; ++i)
1999 vim_free(names[i]);
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00002000 if (num_files > 0)
2001 FreeWild(num_files, files);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 }
2003 vim_free(dir_name);
2004 return file_count;
2005}
2006
Bram Moolenaarb782ba42018-08-07 21:39:28 +02002007#if defined(UNIX) || defined(WIN3264) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02002009 * Need _very_ long file names.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 * Append the full path to name with path separators made into percent
2011 * signs, to dir. An unnamed buffer is handled as "" (<currentdir>/"")
2012 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02002013 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002014make_percent_swname(char_u *dir, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015{
Bram Moolenaarb782ba42018-08-07 21:39:28 +02002016 char_u *d = NULL, *s, *f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017
Bram Moolenaarb782ba42018-08-07 21:39:28 +02002018 f = fix_fname(name != NULL ? name : (char_u *)"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019 if (f != NULL)
2020 {
2021 s = alloc((unsigned)(STRLEN(f) + 1));
2022 if (s != NULL)
2023 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002024 STRCPY(s, f);
Bram Moolenaar91acfff2017-03-12 19:22:36 +01002025 for (d = s; *d != NUL; MB_PTR_ADV(d))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002026 if (vim_ispathsep(*d))
2027 *d = '%';
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 d = concat_fnames(dir, s, TRUE);
2029 vim_free(s);
2030 }
2031 vim_free(f);
2032 }
2033 return d;
2034}
2035#endif
2036
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002037#if (defined(UNIX) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038static int process_still_running;
2039#endif
2040
2041/*
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00002042 * Give information about an existing swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 * Returns timestamp (0 when unknown).
2044 */
2045 static time_t
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002046swapfile_info(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002048 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 int fd;
2050 struct block0 b0;
2051 time_t x = (time_t)0;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002052 char *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053#ifdef UNIX
2054 char_u uname[B0_UNAME_SIZE];
2055#endif
2056
2057 /* print the swap file date */
2058 if (mch_stat((char *)fname, &st) != -1)
2059 {
2060#ifdef UNIX
2061 /* print name of owner of the file */
2062 if (mch_get_uname(st.st_uid, uname, B0_UNAME_SIZE) == OK)
2063 {
2064 MSG_PUTS(_(" owned by: "));
2065 msg_outtrans(uname);
2066 MSG_PUTS(_(" dated: "));
2067 }
2068 else
2069#endif
2070 MSG_PUTS(_(" dated: "));
2071 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00002072 p = ctime(&x); /* includes '\n' */
2073 if (p == NULL)
2074 MSG_PUTS("(invalid)\n");
2075 else
2076 MSG_PUTS(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 }
2078
2079 /*
2080 * print the original file name
2081 */
2082 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2083 if (fd >= 0)
2084 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01002085 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002086 {
2087 if (STRNCMP(b0.b0_version, "VIM 3.0", 7) == 0)
2088 {
2089 MSG_PUTS(_(" [from Vim version 3.0]"));
2090 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002091 else if (ml_check_b0_id(&b0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 {
2093 MSG_PUTS(_(" [does not look like a Vim swap file]"));
2094 }
2095 else
2096 {
2097 MSG_PUTS(_(" file name: "));
2098 if (b0.b0_fname[0] == NUL)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002099 MSG_PUTS(_("[No Name]"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100 else
2101 msg_outtrans(b0.b0_fname);
2102
2103 MSG_PUTS(_("\n modified: "));
2104 MSG_PUTS(b0.b0_dirty ? _("YES") : _("no"));
2105
2106 if (*(b0.b0_uname) != NUL)
2107 {
2108 MSG_PUTS(_("\n user name: "));
2109 msg_outtrans(b0.b0_uname);
2110 }
2111
2112 if (*(b0.b0_hname) != NUL)
2113 {
2114 if (*(b0.b0_uname) != NUL)
2115 MSG_PUTS(_(" host name: "));
2116 else
2117 MSG_PUTS(_("\n host name: "));
2118 msg_outtrans(b0.b0_hname);
2119 }
2120
2121 if (char_to_long(b0.b0_pid) != 0L)
2122 {
2123 MSG_PUTS(_("\n process ID: "));
2124 msg_outnum(char_to_long(b0.b0_pid));
Bram Moolenaara06ecab2016-07-16 14:47:36 +02002125#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 /* EMX kill() not working correctly, it seems */
2127 if (kill((pid_t)char_to_long(b0.b0_pid), 0) == 0)
2128 {
2129 MSG_PUTS(_(" (still running)"));
2130# if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2131 process_still_running = TRUE;
2132# endif
2133 }
2134#endif
2135 }
2136
2137 if (b0_magic_wrong(&b0))
2138 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01002139#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 if (STRNCMP(b0.b0_hname, "PC ", 3) == 0)
2141 MSG_PUTS(_("\n [not usable with this version of Vim]"));
2142 else
2143#endif
2144 MSG_PUTS(_("\n [not usable on this computer]"));
2145 }
2146 }
2147 }
2148 else
2149 MSG_PUTS(_(" [cannot be read]"));
2150 close(fd);
2151 }
2152 else
2153 MSG_PUTS(_(" [cannot be opened]"));
2154 msg_putchar('\n');
2155
2156 return x;
2157}
2158
2159 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002160recov_file_names(char_u **names, char_u *path, int prepend_dot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002161{
2162 int num_names;
2163
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164 /*
2165 * (Win32 and Win64) never short names, but do prepend a dot.
2166 * (Not MS-DOS or Win32 or Win64) maybe short name, maybe not: Try both.
2167 * Only use the short name if it is different.
2168 */
2169 char_u *p;
2170 int i;
2171# ifndef WIN3264
2172 int shortname = curbuf->b_shortname;
2173
2174 curbuf->b_shortname = FALSE;
2175# endif
2176
2177 num_names = 0;
2178
2179 /*
2180 * May also add the file name with a dot prepended, for swap file in same
2181 * dir as original file.
2182 */
2183 if (prepend_dot)
2184 {
2185 names[num_names] = modname(path, (char_u *)".sw?", TRUE);
2186 if (names[num_names] == NULL)
2187 goto end;
2188 ++num_names;
2189 }
2190
2191 /*
2192 * Form the normal swap file name pattern by appending ".sw?".
2193 */
2194#ifdef VMS
2195 names[num_names] = concat_fnames(path, (char_u *)"_sw%", FALSE);
2196#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 names[num_names] = concat_fnames(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198#endif
2199 if (names[num_names] == NULL)
2200 goto end;
2201 if (num_names >= 1) /* check if we have the same name twice */
2202 {
2203 p = names[num_names - 1];
2204 i = (int)STRLEN(names[num_names - 1]) - (int)STRLEN(names[num_names]);
2205 if (i > 0)
2206 p += i; /* file name has been expanded to full path */
2207
2208 if (STRCMP(p, names[num_names]) != 0)
2209 ++num_names;
2210 else
2211 vim_free(names[num_names]);
2212 }
2213 else
2214 ++num_names;
2215
2216# ifndef WIN3264
2217 /*
2218 * Also try with 'shortname' set, in case the file is on a DOS filesystem.
2219 */
2220 curbuf->b_shortname = TRUE;
2221#ifdef VMS
2222 names[num_names] = modname(path, (char_u *)"_sw%", FALSE);
2223#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002224 names[num_names] = modname(path, (char_u *)".sw?", FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225#endif
2226 if (names[num_names] == NULL)
2227 goto end;
2228
2229 /*
2230 * Remove the one from 'shortname', if it's the same as with 'noshortname'.
2231 */
2232 p = names[num_names];
2233 i = STRLEN(names[num_names]) - STRLEN(names[num_names - 1]);
2234 if (i > 0)
2235 p += i; /* file name has been expanded to full path */
2236 if (STRCMP(names[num_names - 1], p) == 0)
2237 vim_free(names[num_names]);
2238 else
2239 ++num_names;
2240# endif
2241
2242end:
2243# ifndef WIN3264
2244 curbuf->b_shortname = shortname;
2245# endif
2246
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 return num_names;
2248}
2249
2250/*
2251 * sync all memlines
2252 *
2253 * If 'check_file' is TRUE, check if original file exists and was not changed.
2254 * If 'check_char' is TRUE, stop syncing when character becomes available, but
2255 * always sync at least one block.
2256 */
2257 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002258ml_sync_all(int check_file, int check_char)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002259{
2260 buf_T *buf;
Bram Moolenaar8767f522016-07-01 17:17:39 +02002261 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002262
Bram Moolenaar29323592016-07-24 22:04:11 +02002263 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 {
2265 if (buf->b_ml.ml_mfp == NULL || buf->b_ml.ml_mfp->mf_fname == NULL)
2266 continue; /* no file */
2267
2268 ml_flush_line(buf); /* flush buffered line */
2269 /* flush locked block */
2270 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH);
2271 if (bufIsChanged(buf) && check_file && mf_need_trans(buf->b_ml.ml_mfp)
2272 && buf->b_ffname != NULL)
2273 {
2274 /*
2275 * If the original file does not exist anymore or has been changed
2276 * call ml_preserve() to get rid of all negative numbered blocks.
2277 */
2278 if (mch_stat((char *)buf->b_ffname, &st) == -1
2279 || st.st_mtime != buf->b_mtime_read
Bram Moolenaar914703b2010-05-31 21:59:46 +02002280 || st.st_size != buf->b_orig_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 {
2282 ml_preserve(buf, FALSE);
2283 did_check_timestamps = FALSE;
2284 need_check_timestamps = TRUE; /* give message later */
2285 }
2286 }
2287 if (buf->b_ml.ml_mfp->mf_dirty)
2288 {
2289 (void)mf_sync(buf->b_ml.ml_mfp, (check_char ? MFS_STOP : 0)
2290 | (bufIsChanged(buf) ? MFS_FLUSH : 0));
2291 if (check_char && ui_char_avail()) /* character available now */
2292 break;
2293 }
2294 }
2295}
2296
2297/*
2298 * sync one buffer, including negative blocks
2299 *
2300 * after this all the blocks are in the swap file
2301 *
2302 * Used for the :preserve command and when the original file has been
2303 * changed or deleted.
2304 *
2305 * when message is TRUE the success of preserving is reported
2306 */
2307 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002308ml_preserve(buf_T *buf, int message)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309{
2310 bhdr_T *hp;
2311 linenr_T lnum;
2312 memfile_T *mfp = buf->b_ml.ml_mfp;
2313 int status;
2314 int got_int_save = got_int;
2315
2316 if (mfp == NULL || mfp->mf_fname == NULL)
2317 {
2318 if (message)
2319 EMSG(_("E313: Cannot preserve, there is no swap file"));
2320 return;
2321 }
2322
2323 /* We only want to stop when interrupted here, not when interrupted
2324 * before. */
2325 got_int = FALSE;
2326
2327 ml_flush_line(buf); /* flush buffered line */
2328 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2329 status = mf_sync(mfp, MFS_ALL | MFS_FLUSH);
2330
2331 /* stack is invalid after mf_sync(.., MFS_ALL) */
2332 buf->b_ml.ml_stack_top = 0;
2333
2334 /*
2335 * Some of the data blocks may have been changed from negative to
2336 * positive block number. In that case the pointer blocks need to be
2337 * updated.
2338 *
2339 * We don't know in which pointer block the references are, so we visit
2340 * all data blocks until there are no more translations to be done (or
2341 * we hit the end of the file, which can only happen in case a write fails,
2342 * e.g. when file system if full).
2343 * ml_find_line() does the work by translating the negative block numbers
2344 * when getting the first line of each data block.
2345 */
2346 if (mf_need_trans(mfp) && !got_int)
2347 {
2348 lnum = 1;
2349 while (mf_need_trans(mfp) && lnum <= buf->b_ml.ml_line_count)
2350 {
2351 hp = ml_find_line(buf, lnum, ML_FIND);
2352 if (hp == NULL)
2353 {
2354 status = FAIL;
2355 goto theend;
2356 }
2357 CHECK(buf->b_ml.ml_locked_low != lnum, "low != lnum");
2358 lnum = buf->b_ml.ml_locked_high + 1;
2359 }
2360 (void)ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush locked block */
2361 /* sync the updated pointer blocks */
2362 if (mf_sync(mfp, MFS_ALL | MFS_FLUSH) == FAIL)
2363 status = FAIL;
2364 buf->b_ml.ml_stack_top = 0; /* stack is invalid now */
2365 }
2366theend:
2367 got_int |= got_int_save;
2368
2369 if (message)
2370 {
2371 if (status == OK)
2372 MSG(_("File preserved"));
2373 else
2374 EMSG(_("E314: Preserve failed"));
2375 }
2376}
2377
2378/*
2379 * NOTE: The pointer returned by the ml_get_*() functions only remains valid
2380 * until the next call!
2381 * line1 = ml_get(1);
2382 * line2 = ml_get(2); // line1 is now invalid!
2383 * Make a copy of the line if necessary.
2384 */
2385/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002386 * Return a pointer to a (read-only copy of a) line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387 *
2388 * On failure an error message is given and IObuff is returned (to avoid
2389 * having to check for error everywhere).
2390 */
2391 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002392ml_get(linenr_T lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002393{
2394 return ml_get_buf(curbuf, lnum, FALSE);
2395}
2396
2397/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002398 * Return pointer to position "pos".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 */
2400 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002401ml_get_pos(pos_T *pos)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402{
2403 return (ml_get_buf(curbuf, pos->lnum, FALSE) + pos->col);
2404}
2405
2406/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002407 * Return pointer to cursor line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408 */
2409 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002410ml_get_curline(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
2412 return ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE);
2413}
2414
2415/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002416 * Return pointer to cursor position.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 */
2418 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002419ml_get_cursor(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420{
2421 return (ml_get_buf(curbuf, curwin->w_cursor.lnum, FALSE) +
2422 curwin->w_cursor.col);
2423}
2424
2425/*
Bram Moolenaar2e2e13c2010-12-08 13:17:03 +01002426 * Return a pointer to a line in a specific buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002427 *
2428 * "will_change": if TRUE mark the buffer dirty (chars in the line will be
2429 * changed)
2430 */
2431 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002432ml_get_buf(
2433 buf_T *buf,
2434 linenr_T lnum,
2435 int will_change) /* line will be changed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436{
Bram Moolenaarad40f022007-02-13 03:01:39 +00002437 bhdr_T *hp;
2438 DATA_BL *dp;
2439 char_u *ptr;
2440 static int recursive = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441
2442 if (lnum > buf->b_ml.ml_line_count) /* invalid line number */
2443 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002444 if (recursive == 0)
2445 {
2446 /* Avoid giving this message for a recursive call, may happen when
2447 * the GUI redraws part of the text. */
2448 ++recursive;
Bram Moolenaar95f09602016-11-10 20:01:45 +01002449 IEMSGN(_("E315: ml_get: invalid lnum: %ld"), lnum);
Bram Moolenaarad40f022007-02-13 03:01:39 +00002450 --recursive;
2451 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452errorret:
2453 STRCPY(IObuff, "???");
2454 return IObuff;
2455 }
2456 if (lnum <= 0) /* pretend line 0 is line 1 */
2457 lnum = 1;
2458
2459 if (buf->b_ml.ml_mfp == NULL) /* there are no lines */
2460 return (char_u *)"";
2461
Bram Moolenaar37d619f2010-03-10 14:46:26 +01002462 /*
2463 * See if it is the same line as requested last time.
2464 * Otherwise may need to flush last used line.
2465 * Don't use the last used line when 'swapfile' is reset, need to load all
2466 * blocks.
2467 */
Bram Moolenaar47b8b152007-02-07 02:41:57 +00002468 if (buf->b_ml.ml_line_lnum != lnum || mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469 {
2470 ml_flush_line(buf);
2471
2472 /*
2473 * Find the data block containing the line.
2474 * This also fills the stack with the blocks from the root to the data
2475 * block and releases any locked block.
2476 */
2477 if ((hp = ml_find_line(buf, lnum, ML_FIND)) == NULL)
2478 {
Bram Moolenaarad40f022007-02-13 03:01:39 +00002479 if (recursive == 0)
2480 {
2481 /* Avoid giving this message for a recursive call, may happen
2482 * when the GUI redraws part of the text. */
2483 ++recursive;
Bram Moolenaar95f09602016-11-10 20:01:45 +01002484 IEMSGN(_("E316: ml_get: cannot find line %ld"), lnum);
Bram Moolenaarad40f022007-02-13 03:01:39 +00002485 --recursive;
2486 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002487 goto errorret;
2488 }
2489
2490 dp = (DATA_BL *)(hp->bh_data);
2491
2492 ptr = (char_u *)dp + ((dp->db_index[lnum - buf->b_ml.ml_locked_low]) & DB_INDEX_MASK);
2493 buf->b_ml.ml_line_ptr = ptr;
2494 buf->b_ml.ml_line_lnum = lnum;
2495 buf->b_ml.ml_flags &= ~ML_LINE_DIRTY;
2496 }
2497 if (will_change)
2498 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
2499
2500 return buf->b_ml.ml_line_ptr;
2501}
2502
2503/*
2504 * Check if a line that was just obtained by a call to ml_get
2505 * is in allocated memory.
2506 */
2507 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002508ml_line_alloced(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509{
2510 return (curbuf->b_ml.ml_flags & ML_LINE_DIRTY);
2511}
2512
2513/*
2514 * Append a line after lnum (may be 0 to insert a line in front of the file).
2515 * "line" does not need to be allocated, but can't be another line in a
2516 * buffer, unlocking may make it invalid.
2517 *
2518 * newfile: TRUE when starting to edit a new file, meaning that pe_old_lnum
2519 * will be set for recovery
2520 * Check: The caller of this function should probably also call
2521 * appended_lines().
2522 *
2523 * return FAIL for failure, OK otherwise
2524 */
2525 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002526ml_append(
2527 linenr_T lnum, /* append after this line (can be 0) */
2528 char_u *line, /* text of the new line */
2529 colnr_T len, /* length of new line, including NUL, or 0 */
2530 int newfile) /* flag, see above */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531{
2532 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02002533 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 return FAIL;
2535
2536 if (curbuf->b_ml.ml_line_lnum != 0)
2537 ml_flush_line(curbuf);
2538 return ml_append_int(curbuf, lnum, line, len, newfile, FALSE);
2539}
2540
Bram Moolenaar4033c552017-09-16 20:54:51 +02002541#if defined(FEAT_SPELL) || defined(FEAT_QUICKFIX) || defined(PROTO)
Bram Moolenaar4770d092006-01-12 23:22:24 +00002542/*
2543 * Like ml_append() but for an arbitrary buffer. The buffer must already have
2544 * a memline.
2545 */
2546 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002547ml_append_buf(
2548 buf_T *buf,
2549 linenr_T lnum, /* append after this line (can be 0) */
2550 char_u *line, /* text of the new line */
2551 colnr_T len, /* length of new line, including NUL, or 0 */
2552 int newfile) /* flag, see above */
Bram Moolenaar4770d092006-01-12 23:22:24 +00002553{
2554 if (buf->b_ml.ml_mfp == NULL)
2555 return FAIL;
2556
2557 if (buf->b_ml.ml_line_lnum != 0)
2558 ml_flush_line(buf);
2559 return ml_append_int(buf, lnum, line, len, newfile, FALSE);
2560}
2561#endif
2562
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01002564ml_append_int(
2565 buf_T *buf,
2566 linenr_T lnum, /* append after this line (can be 0) */
2567 char_u *line, /* text of the new line */
2568 colnr_T len, /* length of line, including NUL, or 0 */
2569 int newfile, /* flag, see above */
2570 int mark) /* mark the new line */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571{
2572 int i;
2573 int line_count; /* number of indexes in current block */
2574 int offset;
2575 int from, to;
2576 int space_needed; /* space needed for new line */
2577 int page_size;
2578 int page_count;
2579 int db_idx; /* index for lnum in data block */
2580 bhdr_T *hp;
2581 memfile_T *mfp;
2582 DATA_BL *dp;
2583 PTR_BL *pp;
2584 infoptr_T *ip;
2585
2586 /* lnum out of range */
2587 if (lnum > buf->b_ml.ml_line_count || buf->b_ml.ml_mfp == NULL)
2588 return FAIL;
2589
2590 if (lowest_marked && lowest_marked > lnum)
2591 lowest_marked = lnum + 1;
2592
2593 if (len == 0)
2594 len = (colnr_T)STRLEN(line) + 1; /* space needed for the text */
2595 space_needed = len + INDEX_SIZE; /* space needed for text + index */
2596
2597 mfp = buf->b_ml.ml_mfp;
2598 page_size = mfp->mf_page_size;
2599
2600/*
2601 * find the data block containing the previous line
2602 * This also fills the stack with the blocks from the root to the data block
2603 * This also releases any locked block.
2604 */
2605 if ((hp = ml_find_line(buf, lnum == 0 ? (linenr_T)1 : lnum,
2606 ML_INSERT)) == NULL)
2607 return FAIL;
2608
2609 buf->b_ml.ml_flags &= ~ML_EMPTY;
2610
2611 if (lnum == 0) /* got line one instead, correct db_idx */
2612 db_idx = -1; /* careful, it is negative! */
2613 else
2614 db_idx = lnum - buf->b_ml.ml_locked_low;
2615 /* get line count before the insertion */
2616 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2617
2618 dp = (DATA_BL *)(hp->bh_data);
2619
2620/*
2621 * If
2622 * - there is not enough room in the current block
2623 * - appending to the last line in the block
2624 * - not appending to the last line in the file
2625 * insert in front of the next block.
2626 */
2627 if ((int)dp->db_free < space_needed && db_idx == line_count - 1
2628 && lnum < buf->b_ml.ml_line_count)
2629 {
2630 /*
2631 * Now that the line is not going to be inserted in the block that we
2632 * expected, the line count has to be adjusted in the pointer blocks
2633 * by using ml_locked_lineadd.
2634 */
2635 --(buf->b_ml.ml_locked_lineadd);
2636 --(buf->b_ml.ml_locked_high);
2637 if ((hp = ml_find_line(buf, lnum + 1, ML_INSERT)) == NULL)
2638 return FAIL;
2639
2640 db_idx = -1; /* careful, it is negative! */
2641 /* get line count before the insertion */
2642 line_count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low;
2643 CHECK(buf->b_ml.ml_locked_low != lnum + 1, "locked_low != lnum + 1");
2644
2645 dp = (DATA_BL *)(hp->bh_data);
2646 }
2647
2648 ++buf->b_ml.ml_line_count;
2649
2650 if ((int)dp->db_free >= space_needed) /* enough room in data block */
2651 {
2652/*
2653 * Insert new line in existing data block, or in data block allocated above.
2654 */
2655 dp->db_txt_start -= len;
2656 dp->db_free -= space_needed;
2657 ++(dp->db_line_count);
2658
2659 /*
2660 * move the text of the lines that follow to the front
2661 * adjust the indexes of the lines that follow
2662 */
2663 if (line_count > db_idx + 1) /* if there are following lines */
2664 {
2665 /*
2666 * Offset is the start of the previous line.
2667 * This will become the character just after the new line.
2668 */
2669 if (db_idx < 0)
2670 offset = dp->db_txt_end;
2671 else
2672 offset = ((dp->db_index[db_idx]) & DB_INDEX_MASK);
2673 mch_memmove((char *)dp + dp->db_txt_start,
2674 (char *)dp + dp->db_txt_start + len,
2675 (size_t)(offset - (dp->db_txt_start + len)));
2676 for (i = line_count - 1; i > db_idx; --i)
2677 dp->db_index[i + 1] = dp->db_index[i] - len;
2678 dp->db_index[db_idx + 1] = offset - len;
2679 }
2680 else /* add line at the end */
2681 dp->db_index[db_idx + 1] = dp->db_txt_start;
2682
2683 /*
2684 * copy the text into the block
2685 */
2686 mch_memmove((char *)dp + dp->db_index[db_idx + 1], line, (size_t)len);
2687 if (mark)
2688 dp->db_index[db_idx + 1] |= DB_MARKED;
2689
2690 /*
2691 * Mark the block dirty.
2692 */
2693 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2694 if (!newfile)
2695 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2696 }
2697 else /* not enough space in data block */
2698 {
2699/*
2700 * If there is not enough room we have to create a new data block and copy some
2701 * lines into it.
2702 * Then we have to insert an entry in the pointer block.
2703 * If this pointer block also is full, we go up another block, and so on, up
2704 * to the root if necessary.
2705 * The line counts in the pointer blocks have already been adjusted by
2706 * ml_find_line().
2707 */
2708 long line_count_left, line_count_right;
2709 int page_count_left, page_count_right;
2710 bhdr_T *hp_left;
2711 bhdr_T *hp_right;
2712 bhdr_T *hp_new;
2713 int lines_moved;
2714 int data_moved = 0; /* init to shut up gcc */
2715 int total_moved = 0; /* init to shut up gcc */
2716 DATA_BL *dp_right, *dp_left;
2717 int stack_idx;
2718 int in_left;
2719 int lineadd;
2720 blocknr_T bnum_left, bnum_right;
2721 linenr_T lnum_left, lnum_right;
2722 int pb_idx;
2723 PTR_BL *pp_new;
2724
2725 /*
2726 * We are going to allocate a new data block. Depending on the
2727 * situation it will be put to the left or right of the existing
2728 * block. If possible we put the new line in the left block and move
2729 * the lines after it to the right block. Otherwise the new line is
2730 * also put in the right block. This method is more efficient when
2731 * inserting a lot of lines at one place.
2732 */
2733 if (db_idx < 0) /* left block is new, right block is existing */
2734 {
2735 lines_moved = 0;
2736 in_left = TRUE;
2737 /* space_needed does not change */
2738 }
2739 else /* left block is existing, right block is new */
2740 {
2741 lines_moved = line_count - db_idx - 1;
2742 if (lines_moved == 0)
2743 in_left = FALSE; /* put new line in right block */
2744 /* space_needed does not change */
2745 else
2746 {
2747 data_moved = ((dp->db_index[db_idx]) & DB_INDEX_MASK) -
2748 dp->db_txt_start;
2749 total_moved = data_moved + lines_moved * INDEX_SIZE;
2750 if ((int)dp->db_free + total_moved >= space_needed)
2751 {
2752 in_left = TRUE; /* put new line in left block */
2753 space_needed = total_moved;
2754 }
2755 else
2756 {
2757 in_left = FALSE; /* put new line in right block */
2758 space_needed += total_moved;
2759 }
2760 }
2761 }
2762
2763 page_count = ((space_needed + HEADER_SIZE) + page_size - 1) / page_size;
2764 if ((hp_new = ml_new_data(mfp, newfile, page_count)) == NULL)
2765 {
2766 /* correct line counts in pointer blocks */
2767 --(buf->b_ml.ml_locked_lineadd);
2768 --(buf->b_ml.ml_locked_high);
2769 return FAIL;
2770 }
2771 if (db_idx < 0) /* left block is new */
2772 {
2773 hp_left = hp_new;
2774 hp_right = hp;
2775 line_count_left = 0;
2776 line_count_right = line_count;
2777 }
2778 else /* right block is new */
2779 {
2780 hp_left = hp;
2781 hp_right = hp_new;
2782 line_count_left = line_count;
2783 line_count_right = 0;
2784 }
2785 dp_right = (DATA_BL *)(hp_right->bh_data);
2786 dp_left = (DATA_BL *)(hp_left->bh_data);
2787 bnum_left = hp_left->bh_bnum;
2788 bnum_right = hp_right->bh_bnum;
2789 page_count_left = hp_left->bh_page_count;
2790 page_count_right = hp_right->bh_page_count;
2791
2792 /*
2793 * May move the new line into the right/new block.
2794 */
2795 if (!in_left)
2796 {
2797 dp_right->db_txt_start -= len;
2798 dp_right->db_free -= len + INDEX_SIZE;
2799 dp_right->db_index[0] = dp_right->db_txt_start;
2800 if (mark)
2801 dp_right->db_index[0] |= DB_MARKED;
2802
2803 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2804 line, (size_t)len);
2805 ++line_count_right;
2806 }
2807 /*
2808 * may move lines from the left/old block to the right/new one.
2809 */
2810 if (lines_moved)
2811 {
2812 /*
2813 */
2814 dp_right->db_txt_start -= data_moved;
2815 dp_right->db_free -= total_moved;
2816 mch_memmove((char *)dp_right + dp_right->db_txt_start,
2817 (char *)dp_left + dp_left->db_txt_start,
2818 (size_t)data_moved);
2819 offset = dp_right->db_txt_start - dp_left->db_txt_start;
2820 dp_left->db_txt_start += data_moved;
2821 dp_left->db_free += total_moved;
2822
2823 /*
2824 * update indexes in the new block
2825 */
2826 for (to = line_count_right, from = db_idx + 1;
2827 from < line_count_left; ++from, ++to)
2828 dp_right->db_index[to] = dp->db_index[from] + offset;
2829 line_count_right += lines_moved;
2830 line_count_left -= lines_moved;
2831 }
2832
2833 /*
2834 * May move the new line into the left (old or new) block.
2835 */
2836 if (in_left)
2837 {
2838 dp_left->db_txt_start -= len;
2839 dp_left->db_free -= len + INDEX_SIZE;
2840 dp_left->db_index[line_count_left] = dp_left->db_txt_start;
2841 if (mark)
2842 dp_left->db_index[line_count_left] |= DB_MARKED;
2843 mch_memmove((char *)dp_left + dp_left->db_txt_start,
2844 line, (size_t)len);
2845 ++line_count_left;
2846 }
2847
2848 if (db_idx < 0) /* left block is new */
2849 {
2850 lnum_left = lnum + 1;
2851 lnum_right = 0;
2852 }
2853 else /* right block is new */
2854 {
2855 lnum_left = 0;
2856 if (in_left)
2857 lnum_right = lnum + 2;
2858 else
2859 lnum_right = lnum + 1;
2860 }
2861 dp_left->db_line_count = line_count_left;
2862 dp_right->db_line_count = line_count_right;
2863
2864 /*
2865 * release the two data blocks
2866 * The new one (hp_new) already has a correct blocknumber.
2867 * The old one (hp, in ml_locked) gets a positive blocknumber if
2868 * we changed it and we are not editing a new file.
2869 */
2870 if (lines_moved || in_left)
2871 buf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
2872 if (!newfile && db_idx >= 0 && in_left)
2873 buf->b_ml.ml_flags |= ML_LOCKED_POS;
2874 mf_put(mfp, hp_new, TRUE, FALSE);
2875
2876 /*
2877 * flush the old data block
2878 * set ml_locked_lineadd to 0, because the updating of the
2879 * pointer blocks is done below
2880 */
2881 lineadd = buf->b_ml.ml_locked_lineadd;
2882 buf->b_ml.ml_locked_lineadd = 0;
2883 ml_find_line(buf, (linenr_T)0, ML_FLUSH); /* flush data block */
2884
2885 /*
2886 * update pointer blocks for the new data block
2887 */
2888 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
2889 --stack_idx)
2890 {
2891 ip = &(buf->b_ml.ml_stack[stack_idx]);
2892 pb_idx = ip->ip_index;
2893 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
2894 return FAIL;
2895 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
2896 if (pp->pb_id != PTR_ID)
2897 {
Bram Moolenaar95f09602016-11-10 20:01:45 +01002898 IEMSG(_("E317: pointer block id wrong 3"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 mf_put(mfp, hp, FALSE, FALSE);
2900 return FAIL;
2901 }
2902 /*
2903 * TODO: If the pointer block is full and we are adding at the end
2904 * try to insert in front of the next block
2905 */
2906 /* block not full, add one entry */
2907 if (pp->pb_count < pp->pb_count_max)
2908 {
2909 if (pb_idx + 1 < (int)pp->pb_count)
2910 mch_memmove(&pp->pb_pointer[pb_idx + 2],
2911 &pp->pb_pointer[pb_idx + 1],
2912 (size_t)(pp->pb_count - pb_idx - 1) * sizeof(PTR_EN));
2913 ++pp->pb_count;
2914 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
2915 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
2916 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
2917 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2918 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2919 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2920
2921 if (lnum_left != 0)
2922 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
2923 if (lnum_right != 0)
2924 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2925
2926 mf_put(mfp, hp, TRUE, FALSE);
2927 buf->b_ml.ml_stack_top = stack_idx + 1; /* truncate stack */
2928
2929 if (lineadd)
2930 {
2931 --(buf->b_ml.ml_stack_top);
Bram Moolenaar6b803a72007-05-06 14:25:46 +00002932 /* fix line count for rest of blocks in the stack */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 ml_lineadd(buf, lineadd);
2934 /* fix stack itself */
2935 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
2936 lineadd;
2937 ++(buf->b_ml.ml_stack_top);
2938 }
2939
2940 /*
2941 * We are finished, break the loop here.
2942 */
2943 break;
2944 }
2945 else /* pointer block full */
2946 {
2947 /*
2948 * split the pointer block
2949 * allocate a new pointer block
2950 * move some of the pointer into the new block
2951 * prepare for updating the parent block
2952 */
2953 for (;;) /* do this twice when splitting block 1 */
2954 {
2955 hp_new = ml_new_ptr(mfp);
2956 if (hp_new == NULL) /* TODO: try to fix tree */
2957 return FAIL;
2958 pp_new = (PTR_BL *)(hp_new->bh_data);
2959
2960 if (hp->bh_bnum != 1)
2961 break;
2962
2963 /*
2964 * if block 1 becomes full the tree is given an extra level
2965 * The pointers from block 1 are moved into the new block.
2966 * block 1 is updated to point to the new block
2967 * then continue to split the new block
2968 */
2969 mch_memmove(pp_new, pp, (size_t)page_size);
2970 pp->pb_count = 1;
2971 pp->pb_pointer[0].pe_bnum = hp_new->bh_bnum;
2972 pp->pb_pointer[0].pe_line_count = buf->b_ml.ml_line_count;
2973 pp->pb_pointer[0].pe_old_lnum = 1;
2974 pp->pb_pointer[0].pe_page_count = 1;
2975 mf_put(mfp, hp, TRUE, FALSE); /* release block 1 */
2976 hp = hp_new; /* new block is to be split */
2977 pp = pp_new;
2978 CHECK(stack_idx != 0, _("stack_idx should be 0"));
2979 ip->ip_index = 0;
2980 ++stack_idx; /* do block 1 again later */
2981 }
2982 /*
2983 * move the pointers after the current one to the new block
2984 * If there are none, the new entry will be in the new block.
2985 */
2986 total_moved = pp->pb_count - pb_idx - 1;
2987 if (total_moved)
2988 {
2989 mch_memmove(&pp_new->pb_pointer[0],
2990 &pp->pb_pointer[pb_idx + 1],
2991 (size_t)(total_moved) * sizeof(PTR_EN));
2992 pp_new->pb_count = total_moved;
2993 pp->pb_count -= total_moved - 1;
2994 pp->pb_pointer[pb_idx + 1].pe_bnum = bnum_right;
2995 pp->pb_pointer[pb_idx + 1].pe_line_count = line_count_right;
2996 pp->pb_pointer[pb_idx + 1].pe_page_count = page_count_right;
2997 if (lnum_right)
2998 pp->pb_pointer[pb_idx + 1].pe_old_lnum = lnum_right;
2999 }
3000 else
3001 {
3002 pp_new->pb_count = 1;
3003 pp_new->pb_pointer[0].pe_bnum = bnum_right;
3004 pp_new->pb_pointer[0].pe_line_count = line_count_right;
3005 pp_new->pb_pointer[0].pe_page_count = page_count_right;
3006 pp_new->pb_pointer[0].pe_old_lnum = lnum_right;
3007 }
3008 pp->pb_pointer[pb_idx].pe_bnum = bnum_left;
3009 pp->pb_pointer[pb_idx].pe_line_count = line_count_left;
3010 pp->pb_pointer[pb_idx].pe_page_count = page_count_left;
3011 if (lnum_left)
3012 pp->pb_pointer[pb_idx].pe_old_lnum = lnum_left;
3013 lnum_left = 0;
3014 lnum_right = 0;
3015
3016 /*
3017 * recompute line counts
3018 */
3019 line_count_right = 0;
3020 for (i = 0; i < (int)pp_new->pb_count; ++i)
3021 line_count_right += pp_new->pb_pointer[i].pe_line_count;
3022 line_count_left = 0;
3023 for (i = 0; i < (int)pp->pb_count; ++i)
3024 line_count_left += pp->pb_pointer[i].pe_line_count;
3025
3026 bnum_left = hp->bh_bnum;
3027 bnum_right = hp_new->bh_bnum;
3028 page_count_left = 1;
3029 page_count_right = 1;
3030 mf_put(mfp, hp, TRUE, FALSE);
3031 mf_put(mfp, hp_new, TRUE, FALSE);
3032 }
3033 }
3034
3035 /*
3036 * Safety check: fallen out of for loop?
3037 */
3038 if (stack_idx < 0)
3039 {
Bram Moolenaar95f09602016-11-10 20:01:45 +01003040 IEMSG(_("E318: Updated too many blocks?"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041 buf->b_ml.ml_stack_top = 0; /* invalidate stack */
3042 }
3043 }
3044
3045#ifdef FEAT_BYTEOFF
3046 /* The line was inserted below 'lnum' */
3047 ml_updatechunk(buf, lnum + 1, (long)len, ML_CHNK_ADDLINE);
3048#endif
3049#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003050 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 {
3052 if (STRLEN(line) > 0)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003053 netbeans_inserted(buf, lnum+1, (colnr_T)0, line, (int)STRLEN(line));
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003054 netbeans_inserted(buf, lnum+1, (colnr_T)STRLEN(line),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 (char_u *)"\n", 1);
3056 }
3057#endif
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01003058#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar99ef0622016-03-06 20:22:25 +01003059 if (buf->b_write_to_channel)
3060 channel_write_new_lines(buf);
3061#endif
3062
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 return OK;
3064}
3065
3066/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00003067 * Replace line lnum, with buffering, in current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068 *
Bram Moolenaar1056d982006-03-09 22:37:52 +00003069 * If "copy" is TRUE, make a copy of the line, otherwise the line has been
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070 * copied to allocated memory already.
3071 *
3072 * Check: The caller of this function should probably also call
3073 * changed_lines(), unless update_screen(NOT_VALID) is used.
3074 *
3075 * return FAIL for failure, OK otherwise
3076 */
3077 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003078ml_replace(linenr_T lnum, char_u *line, int copy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003079{
3080 if (line == NULL) /* just checking... */
3081 return FAIL;
3082
3083 /* When starting up, we might still need to create the memfile */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02003084 if (curbuf->b_ml.ml_mfp == NULL && open_buffer(FALSE, NULL, 0) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 return FAIL;
3086
3087 if (copy && (line = vim_strsave(line)) == NULL) /* allocate memory */
3088 return FAIL;
3089#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003090 if (netbeans_active())
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 {
3092 netbeans_removed(curbuf, lnum, 0, (long)STRLEN(ml_get(lnum)));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003093 netbeans_inserted(curbuf, lnum, 0, line, (int)STRLEN(line));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094 }
3095#endif
3096 if (curbuf->b_ml.ml_line_lnum != lnum) /* other line buffered */
3097 ml_flush_line(curbuf); /* flush it */
3098 else if (curbuf->b_ml.ml_flags & ML_LINE_DIRTY) /* same line allocated */
3099 vim_free(curbuf->b_ml.ml_line_ptr); /* free it */
3100 curbuf->b_ml.ml_line_ptr = line;
3101 curbuf->b_ml.ml_line_lnum = lnum;
3102 curbuf->b_ml.ml_flags = (curbuf->b_ml.ml_flags | ML_LINE_DIRTY) & ~ML_EMPTY;
3103
3104 return OK;
3105}
3106
3107/*
Bram Moolenaar4033c552017-09-16 20:54:51 +02003108 * Delete line "lnum" in the current buffer.
3109 * When "message" is TRUE may give a "No lines in buffer" message.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 *
3111 * Check: The caller of this function should probably also call
3112 * deleted_lines() after this.
3113 *
3114 * return FAIL for failure, OK otherwise
3115 */
3116 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003117ml_delete(linenr_T lnum, int message)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118{
3119 ml_flush_line(curbuf);
3120 return ml_delete_int(curbuf, lnum, message);
3121}
3122
3123 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003124ml_delete_int(buf_T *buf, linenr_T lnum, int message)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125{
3126 bhdr_T *hp;
3127 memfile_T *mfp;
3128 DATA_BL *dp;
3129 PTR_BL *pp;
3130 infoptr_T *ip;
3131 int count; /* number of entries in block */
3132 int idx;
3133 int stack_idx;
3134 int text_start;
3135 int line_start;
3136 long line_size;
3137 int i;
3138
3139 if (lnum < 1 || lnum > buf->b_ml.ml_line_count)
3140 return FAIL;
3141
3142 if (lowest_marked && lowest_marked > lnum)
3143 lowest_marked--;
3144
3145/*
3146 * If the file becomes empty the last line is replaced by an empty line.
3147 */
3148 if (buf->b_ml.ml_line_count == 1) /* file becomes empty */
3149 {
3150 if (message
3151#ifdef FEAT_NETBEANS_INTG
3152 && !netbeansSuppressNoLines
3153#endif
3154 )
Bram Moolenaar238a5642006-02-21 22:12:05 +00003155 set_keep_msg((char_u *)_(no_lines_msg), 0);
3156
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003157 /* FEAT_BYTEOFF already handled in there, don't worry 'bout it below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 i = ml_replace((linenr_T)1, (char_u *)"", TRUE);
3159 buf->b_ml.ml_flags |= ML_EMPTY;
3160
3161 return i;
3162 }
3163
3164/*
3165 * find the data block containing the line
3166 * This also fills the stack with the blocks from the root to the data block
3167 * This also releases any locked block.
3168 */
3169 mfp = buf->b_ml.ml_mfp;
3170 if (mfp == NULL)
3171 return FAIL;
3172
3173 if ((hp = ml_find_line(buf, lnum, ML_DELETE)) == NULL)
3174 return FAIL;
3175
3176 dp = (DATA_BL *)(hp->bh_data);
3177 /* compute line count before the delete */
3178 count = (long)(buf->b_ml.ml_locked_high)
3179 - (long)(buf->b_ml.ml_locked_low) + 2;
3180 idx = lnum - buf->b_ml.ml_locked_low;
3181
3182 --buf->b_ml.ml_line_count;
3183
3184 line_start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3185 if (idx == 0) /* first line in block, text at the end */
3186 line_size = dp->db_txt_end - line_start;
3187 else
3188 line_size = ((dp->db_index[idx - 1]) & DB_INDEX_MASK) - line_start;
3189
3190#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003191 if (netbeans_active())
Bram Moolenaar35a9aaa2004-10-24 19:23:07 +00003192 netbeans_removed(buf, lnum, 0, (long)line_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193#endif
3194
3195/*
3196 * special case: If there is only one line in the data block it becomes empty.
3197 * Then we have to remove the entry, pointing to this data block, from the
3198 * pointer block. If this pointer block also becomes empty, we go up another
3199 * block, and so on, up to the root if necessary.
3200 * The line counts in the pointer blocks have already been adjusted by
3201 * ml_find_line().
3202 */
3203 if (count == 1)
3204 {
3205 mf_free(mfp, hp); /* free the data block */
3206 buf->b_ml.ml_locked = NULL;
3207
Bram Moolenaare60acc12011-05-10 16:41:25 +02003208 for (stack_idx = buf->b_ml.ml_stack_top - 1; stack_idx >= 0;
3209 --stack_idx)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 {
3211 buf->b_ml.ml_stack_top = 0; /* stack is invalid when failing */
3212 ip = &(buf->b_ml.ml_stack[stack_idx]);
3213 idx = ip->ip_index;
3214 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3215 return FAIL;
3216 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3217 if (pp->pb_id != PTR_ID)
3218 {
Bram Moolenaar95f09602016-11-10 20:01:45 +01003219 IEMSG(_("E317: pointer block id wrong 4"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220 mf_put(mfp, hp, FALSE, FALSE);
3221 return FAIL;
3222 }
3223 count = --(pp->pb_count);
3224 if (count == 0) /* the pointer block becomes empty! */
3225 mf_free(mfp, hp);
3226 else
3227 {
3228 if (count != idx) /* move entries after the deleted one */
3229 mch_memmove(&pp->pb_pointer[idx], &pp->pb_pointer[idx + 1],
3230 (size_t)(count - idx) * sizeof(PTR_EN));
3231 mf_put(mfp, hp, TRUE, FALSE);
3232
3233 buf->b_ml.ml_stack_top = stack_idx; /* truncate stack */
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003234 /* fix line count for rest of blocks in the stack */
3235 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 {
3237 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3238 buf->b_ml.ml_stack[buf->b_ml.ml_stack_top].ip_high +=
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003239 buf->b_ml.ml_locked_lineadd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003240 }
3241 ++(buf->b_ml.ml_stack_top);
3242
3243 break;
3244 }
3245 }
3246 CHECK(stack_idx < 0, _("deleted block 1?"));
3247 }
3248 else
3249 {
3250 /*
3251 * delete the text by moving the next lines forwards
3252 */
3253 text_start = dp->db_txt_start;
3254 mch_memmove((char *)dp + text_start + line_size,
3255 (char *)dp + text_start, (size_t)(line_start - text_start));
3256
3257 /*
3258 * delete the index by moving the next indexes backwards
3259 * Adjust the indexes for the text movement.
3260 */
3261 for (i = idx; i < count - 1; ++i)
3262 dp->db_index[i] = dp->db_index[i + 1] + line_size;
3263
3264 dp->db_free += line_size + INDEX_SIZE;
3265 dp->db_txt_start += line_size;
3266 --(dp->db_line_count);
3267
3268 /*
3269 * mark the block dirty and make sure it is in the file (for recovery)
3270 */
3271 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3272 }
3273
3274#ifdef FEAT_BYTEOFF
3275 ml_updatechunk(buf, lnum, line_size, ML_CHNK_DELLINE);
3276#endif
3277 return OK;
3278}
3279
3280/*
3281 * set the B_MARKED flag for line 'lnum'
3282 */
3283 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003284ml_setmarked(linenr_T lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285{
3286 bhdr_T *hp;
3287 DATA_BL *dp;
3288 /* invalid line number */
3289 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count
3290 || curbuf->b_ml.ml_mfp == NULL)
3291 return; /* give error message? */
3292
3293 if (lowest_marked == 0 || lowest_marked > lnum)
3294 lowest_marked = lnum;
3295
3296 /*
3297 * find the data block containing the line
3298 * This also fills the stack with the blocks from the root to the data block
3299 * This also releases any locked block.
3300 */
3301 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3302 return; /* give error message? */
3303
3304 dp = (DATA_BL *)(hp->bh_data);
3305 dp->db_index[lnum - curbuf->b_ml.ml_locked_low] |= DB_MARKED;
3306 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3307}
3308
3309/*
3310 * find the first line with its B_MARKED flag set
3311 */
3312 linenr_T
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003313ml_firstmarked(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003314{
3315 bhdr_T *hp;
3316 DATA_BL *dp;
3317 linenr_T lnum;
3318 int i;
3319
3320 if (curbuf->b_ml.ml_mfp == NULL)
3321 return (linenr_T) 0;
3322
3323 /*
3324 * The search starts with lowest_marked line. This is the last line where
3325 * a mark was found, adjusted by inserting/deleting lines.
3326 */
3327 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3328 {
3329 /*
3330 * Find the data block containing the line.
3331 * This also fills the stack with the blocks from the root to the data
3332 * block This also releases any locked block.
3333 */
3334 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3335 return (linenr_T)0; /* give error message? */
3336
3337 dp = (DATA_BL *)(hp->bh_data);
3338
3339 for (i = lnum - curbuf->b_ml.ml_locked_low;
3340 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3341 if ((dp->db_index[i]) & DB_MARKED)
3342 {
3343 (dp->db_index[i]) &= DB_INDEX_MASK;
3344 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3345 lowest_marked = lnum + 1;
3346 return lnum;
3347 }
3348 }
3349
3350 return (linenr_T) 0;
3351}
3352
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353/*
3354 * clear all DB_MARKED flags
3355 */
3356 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003357ml_clearmarked(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358{
3359 bhdr_T *hp;
3360 DATA_BL *dp;
3361 linenr_T lnum;
3362 int i;
3363
3364 if (curbuf->b_ml.ml_mfp == NULL) /* nothing to do */
3365 return;
3366
3367 /*
3368 * The search starts with line lowest_marked.
3369 */
3370 for (lnum = lowest_marked; lnum <= curbuf->b_ml.ml_line_count; )
3371 {
3372 /*
3373 * Find the data block containing the line.
3374 * This also fills the stack with the blocks from the root to the data
3375 * block and releases any locked block.
3376 */
3377 if ((hp = ml_find_line(curbuf, lnum, ML_FIND)) == NULL)
3378 return; /* give error message? */
3379
3380 dp = (DATA_BL *)(hp->bh_data);
3381
3382 for (i = lnum - curbuf->b_ml.ml_locked_low;
3383 lnum <= curbuf->b_ml.ml_locked_high; ++i, ++lnum)
3384 if ((dp->db_index[i]) & DB_MARKED)
3385 {
3386 (dp->db_index[i]) &= DB_INDEX_MASK;
3387 curbuf->b_ml.ml_flags |= ML_LOCKED_DIRTY;
3388 }
3389 }
3390
3391 lowest_marked = 0;
3392 return;
3393}
3394
3395/*
3396 * flush ml_line if necessary
3397 */
3398 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003399ml_flush_line(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400{
3401 bhdr_T *hp;
3402 DATA_BL *dp;
3403 linenr_T lnum;
3404 char_u *new_line;
3405 char_u *old_line;
3406 colnr_T new_len;
3407 int old_len;
3408 int extra;
3409 int idx;
3410 int start;
3411 int count;
3412 int i;
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003413 static int entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003414
3415 if (buf->b_ml.ml_line_lnum == 0 || buf->b_ml.ml_mfp == NULL)
3416 return; /* nothing to do */
3417
3418 if (buf->b_ml.ml_flags & ML_LINE_DIRTY)
3419 {
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003420 /* This code doesn't work recursively, but Netbeans may call back here
3421 * when obtaining the cursor position. */
3422 if (entered)
3423 return;
3424 entered = TRUE;
3425
Bram Moolenaar071d4272004-06-13 20:20:40 +00003426 lnum = buf->b_ml.ml_line_lnum;
3427 new_line = buf->b_ml.ml_line_ptr;
3428
3429 hp = ml_find_line(buf, lnum, ML_FIND);
3430 if (hp == NULL)
Bram Moolenaar95f09602016-11-10 20:01:45 +01003431 IEMSGN(_("E320: Cannot find line %ld"), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003432 else
3433 {
3434 dp = (DATA_BL *)(hp->bh_data);
3435 idx = lnum - buf->b_ml.ml_locked_low;
3436 start = ((dp->db_index[idx]) & DB_INDEX_MASK);
3437 old_line = (char_u *)dp + start;
3438 if (idx == 0) /* line is last in block */
3439 old_len = dp->db_txt_end - start;
3440 else /* text of previous line follows */
3441 old_len = (dp->db_index[idx - 1] & DB_INDEX_MASK) - start;
3442 new_len = (colnr_T)STRLEN(new_line) + 1;
3443 extra = new_len - old_len; /* negative if lines gets smaller */
3444
3445 /*
3446 * if new line fits in data block, replace directly
3447 */
3448 if ((int)dp->db_free >= extra)
3449 {
3450 /* if the length changes and there are following lines */
3451 count = buf->b_ml.ml_locked_high - buf->b_ml.ml_locked_low + 1;
3452 if (extra != 0 && idx < count - 1)
3453 {
3454 /* move text of following lines */
3455 mch_memmove((char *)dp + dp->db_txt_start - extra,
3456 (char *)dp + dp->db_txt_start,
3457 (size_t)(start - dp->db_txt_start));
3458
3459 /* adjust pointers of this and following lines */
3460 for (i = idx + 1; i < count; ++i)
3461 dp->db_index[i] -= extra;
3462 }
3463 dp->db_index[idx] -= extra;
3464
3465 /* adjust free space */
3466 dp->db_free -= extra;
3467 dp->db_txt_start -= extra;
3468
3469 /* copy new line into the data block */
3470 mch_memmove(old_line - extra, new_line, (size_t)new_len);
3471 buf->b_ml.ml_flags |= (ML_LOCKED_DIRTY | ML_LOCKED_POS);
3472#ifdef FEAT_BYTEOFF
3473 /* The else case is already covered by the insert and delete */
3474 ml_updatechunk(buf, lnum, (long)extra, ML_CHNK_UPDLINE);
3475#endif
3476 }
3477 else
3478 {
3479 /*
3480 * Cannot do it in one data block: Delete and append.
3481 * Append first, because ml_delete_int() cannot delete the
3482 * last line in a buffer, which causes trouble for a buffer
3483 * that has only one line.
3484 * Don't forget to copy the mark!
3485 */
3486 /* How about handling errors??? */
3487 (void)ml_append_int(buf, lnum, new_line, new_len, FALSE,
3488 (dp->db_index[idx] & DB_MARKED));
3489 (void)ml_delete_int(buf, lnum, FALSE);
3490 }
3491 }
3492 vim_free(new_line);
Bram Moolenaar0ca4b352010-02-11 18:54:43 +01003493
3494 entered = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 }
3496
3497 buf->b_ml.ml_line_lnum = 0;
3498}
3499
3500/*
3501 * create a new, empty, data block
3502 */
3503 static bhdr_T *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003504ml_new_data(memfile_T *mfp, int negative, int page_count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505{
3506 bhdr_T *hp;
3507 DATA_BL *dp;
3508
3509 if ((hp = mf_new(mfp, negative, page_count)) == NULL)
3510 return NULL;
3511
3512 dp = (DATA_BL *)(hp->bh_data);
3513 dp->db_id = DATA_ID;
3514 dp->db_txt_start = dp->db_txt_end = page_count * mfp->mf_page_size;
3515 dp->db_free = dp->db_txt_start - HEADER_SIZE;
3516 dp->db_line_count = 0;
3517
3518 return hp;
3519}
3520
3521/*
3522 * create a new, empty, pointer block
3523 */
3524 static bhdr_T *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003525ml_new_ptr(memfile_T *mfp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003526{
3527 bhdr_T *hp;
3528 PTR_BL *pp;
3529
3530 if ((hp = mf_new(mfp, FALSE, 1)) == NULL)
3531 return NULL;
3532
3533 pp = (PTR_BL *)(hp->bh_data);
3534 pp->pb_id = PTR_ID;
3535 pp->pb_count = 0;
Bram Moolenaar20a825a2010-05-31 21:27:30 +02003536 pp->pb_count_max = (short_u)((mfp->mf_page_size - sizeof(PTR_BL))
3537 / sizeof(PTR_EN) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538
3539 return hp;
3540}
3541
3542/*
3543 * lookup line 'lnum' in a memline
3544 *
3545 * action: if ML_DELETE or ML_INSERT the line count is updated while searching
3546 * if ML_FLUSH only flush a locked block
3547 * if ML_FIND just find the line
3548 *
3549 * If the block was found it is locked and put in ml_locked.
3550 * The stack is updated to lead to the locked block. The ip_high field in
3551 * the stack is updated to reflect the last line in the block AFTER the
3552 * insert or delete, also if the pointer block has not been updated yet. But
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003553 * if ml_locked != NULL ml_locked_lineadd must be added to ip_high.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 *
3555 * return: NULL for failure, pointer to block header otherwise
3556 */
3557 static bhdr_T *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003558ml_find_line(buf_T *buf, linenr_T lnum, int action)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559{
3560 DATA_BL *dp;
3561 PTR_BL *pp;
3562 infoptr_T *ip;
3563 bhdr_T *hp;
3564 memfile_T *mfp;
3565 linenr_T t;
3566 blocknr_T bnum, bnum2;
3567 int dirty;
3568 linenr_T low, high;
3569 int top;
3570 int page_count;
3571 int idx;
3572
3573 mfp = buf->b_ml.ml_mfp;
3574
3575 /*
3576 * If there is a locked block check if the wanted line is in it.
3577 * If not, flush and release the locked block.
3578 * Don't do this for ML_INSERT_SAME, because the stack need to be updated.
3579 * Don't do this for ML_FLUSH, because we want to flush the locked block.
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003580 * Don't do this when 'swapfile' is reset, we want to load all the blocks.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003581 */
3582 if (buf->b_ml.ml_locked)
3583 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003584 if (ML_SIMPLE(action)
3585 && buf->b_ml.ml_locked_low <= lnum
3586 && buf->b_ml.ml_locked_high >= lnum
3587 && !mf_dont_release)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588 {
Bram Moolenaar47b8b152007-02-07 02:41:57 +00003589 /* remember to update pointer blocks and stack later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590 if (action == ML_INSERT)
3591 {
3592 ++(buf->b_ml.ml_locked_lineadd);
3593 ++(buf->b_ml.ml_locked_high);
3594 }
3595 else if (action == ML_DELETE)
3596 {
3597 --(buf->b_ml.ml_locked_lineadd);
3598 --(buf->b_ml.ml_locked_high);
3599 }
3600 return (buf->b_ml.ml_locked);
3601 }
3602
3603 mf_put(mfp, buf->b_ml.ml_locked, buf->b_ml.ml_flags & ML_LOCKED_DIRTY,
3604 buf->b_ml.ml_flags & ML_LOCKED_POS);
3605 buf->b_ml.ml_locked = NULL;
3606
Bram Moolenaar6b803a72007-05-06 14:25:46 +00003607 /*
3608 * If lines have been added or deleted in the locked block, need to
3609 * update the line count in pointer blocks.
3610 */
3611 if (buf->b_ml.ml_locked_lineadd != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003612 ml_lineadd(buf, buf->b_ml.ml_locked_lineadd);
3613 }
3614
3615 if (action == ML_FLUSH) /* nothing else to do */
3616 return NULL;
3617
3618 bnum = 1; /* start at the root of the tree */
3619 page_count = 1;
3620 low = 1;
3621 high = buf->b_ml.ml_line_count;
3622
3623 if (action == ML_FIND) /* first try stack entries */
3624 {
3625 for (top = buf->b_ml.ml_stack_top - 1; top >= 0; --top)
3626 {
3627 ip = &(buf->b_ml.ml_stack[top]);
3628 if (ip->ip_low <= lnum && ip->ip_high >= lnum)
3629 {
3630 bnum = ip->ip_bnum;
3631 low = ip->ip_low;
3632 high = ip->ip_high;
3633 buf->b_ml.ml_stack_top = top; /* truncate stack at prev entry */
3634 break;
3635 }
3636 }
3637 if (top < 0)
3638 buf->b_ml.ml_stack_top = 0; /* not found, start at the root */
3639 }
3640 else /* ML_DELETE or ML_INSERT */
3641 buf->b_ml.ml_stack_top = 0; /* start at the root */
3642
3643/*
3644 * search downwards in the tree until a data block is found
3645 */
3646 for (;;)
3647 {
3648 if ((hp = mf_get(mfp, bnum, page_count)) == NULL)
3649 goto error_noblock;
3650
3651 /*
3652 * update high for insert/delete
3653 */
3654 if (action == ML_INSERT)
3655 ++high;
3656 else if (action == ML_DELETE)
3657 --high;
3658
3659 dp = (DATA_BL *)(hp->bh_data);
3660 if (dp->db_id == DATA_ID) /* data block */
3661 {
3662 buf->b_ml.ml_locked = hp;
3663 buf->b_ml.ml_locked_low = low;
3664 buf->b_ml.ml_locked_high = high;
3665 buf->b_ml.ml_locked_lineadd = 0;
3666 buf->b_ml.ml_flags &= ~(ML_LOCKED_DIRTY | ML_LOCKED_POS);
3667 return hp;
3668 }
3669
3670 pp = (PTR_BL *)(dp); /* must be pointer block */
3671 if (pp->pb_id != PTR_ID)
3672 {
Bram Moolenaar95f09602016-11-10 20:01:45 +01003673 IEMSG(_("E317: pointer block id wrong"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 goto error_block;
3675 }
3676
3677 if ((top = ml_add_stack(buf)) < 0) /* add new entry to stack */
3678 goto error_block;
3679 ip = &(buf->b_ml.ml_stack[top]);
3680 ip->ip_bnum = bnum;
3681 ip->ip_low = low;
3682 ip->ip_high = high;
3683 ip->ip_index = -1; /* index not known yet */
3684
3685 dirty = FALSE;
3686 for (idx = 0; idx < (int)pp->pb_count; ++idx)
3687 {
3688 t = pp->pb_pointer[idx].pe_line_count;
3689 CHECK(t == 0, _("pe_line_count is zero"));
3690 if ((low += t) > lnum)
3691 {
3692 ip->ip_index = idx;
3693 bnum = pp->pb_pointer[idx].pe_bnum;
3694 page_count = pp->pb_pointer[idx].pe_page_count;
3695 high = low - 1;
3696 low -= t;
3697
3698 /*
3699 * a negative block number may have been changed
3700 */
3701 if (bnum < 0)
3702 {
3703 bnum2 = mf_trans_del(mfp, bnum);
3704 if (bnum != bnum2)
3705 {
3706 bnum = bnum2;
3707 pp->pb_pointer[idx].pe_bnum = bnum;
3708 dirty = TRUE;
3709 }
3710 }
3711
3712 break;
3713 }
3714 }
3715 if (idx >= (int)pp->pb_count) /* past the end: something wrong! */
3716 {
3717 if (lnum > buf->b_ml.ml_line_count)
Bram Moolenaar95f09602016-11-10 20:01:45 +01003718 IEMSGN(_("E322: line number out of range: %ld past the end"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719 lnum - buf->b_ml.ml_line_count);
3720
3721 else
Bram Moolenaar95f09602016-11-10 20:01:45 +01003722 IEMSGN(_("E323: line count wrong in block %ld"), bnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 goto error_block;
3724 }
3725 if (action == ML_DELETE)
3726 {
3727 pp->pb_pointer[idx].pe_line_count--;
3728 dirty = TRUE;
3729 }
3730 else if (action == ML_INSERT)
3731 {
3732 pp->pb_pointer[idx].pe_line_count++;
3733 dirty = TRUE;
3734 }
3735 mf_put(mfp, hp, dirty, FALSE);
3736 }
3737
3738error_block:
3739 mf_put(mfp, hp, FALSE, FALSE);
3740error_noblock:
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003741 /*
3742 * If action is ML_DELETE or ML_INSERT we have to correct the tree for
3743 * the incremented/decremented line counts, because there won't be a line
3744 * inserted/deleted after all.
3745 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 if (action == ML_DELETE)
3747 ml_lineadd(buf, 1);
3748 else if (action == ML_INSERT)
3749 ml_lineadd(buf, -1);
3750 buf->b_ml.ml_stack_top = 0;
3751 return NULL;
3752}
3753
3754/*
3755 * add an entry to the info pointer stack
3756 *
3757 * return -1 for failure, number of the new entry otherwise
3758 */
3759 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003760ml_add_stack(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761{
3762 int top;
3763 infoptr_T *newstack;
3764
3765 top = buf->b_ml.ml_stack_top;
3766
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003767 /* may have to increase the stack size */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768 if (top == buf->b_ml.ml_stack_size)
3769 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003770 CHECK(top > 0, _("Stack size increases")); /* more than 5 levels??? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771
3772 newstack = (infoptr_T *)alloc((unsigned)sizeof(infoptr_T) *
3773 (buf->b_ml.ml_stack_size + STACK_INCR));
3774 if (newstack == NULL)
3775 return -1;
Bram Moolenaarfbd302f2015-08-08 18:23:46 +02003776 if (top > 0)
3777 mch_memmove(newstack, buf->b_ml.ml_stack,
Bram Moolenaar8c8de832008-06-24 22:58:06 +00003778 (size_t)top * sizeof(infoptr_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779 vim_free(buf->b_ml.ml_stack);
3780 buf->b_ml.ml_stack = newstack;
3781 buf->b_ml.ml_stack_size += STACK_INCR;
3782 }
3783
3784 buf->b_ml.ml_stack_top++;
3785 return top;
3786}
3787
3788/*
3789 * Update the pointer blocks on the stack for inserted/deleted lines.
3790 * The stack itself is also updated.
3791 *
3792 * When a insert/delete line action fails, the line is not inserted/deleted,
3793 * but the pointer blocks have already been updated. That is fixed here by
3794 * walking through the stack.
3795 *
3796 * Count is the number of lines added, negative if lines have been deleted.
3797 */
3798 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003799ml_lineadd(buf_T *buf, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800{
3801 int idx;
3802 infoptr_T *ip;
3803 PTR_BL *pp;
3804 memfile_T *mfp = buf->b_ml.ml_mfp;
3805 bhdr_T *hp;
3806
3807 for (idx = buf->b_ml.ml_stack_top - 1; idx >= 0; --idx)
3808 {
3809 ip = &(buf->b_ml.ml_stack[idx]);
3810 if ((hp = mf_get(mfp, ip->ip_bnum, 1)) == NULL)
3811 break;
3812 pp = (PTR_BL *)(hp->bh_data); /* must be pointer block */
3813 if (pp->pb_id != PTR_ID)
3814 {
3815 mf_put(mfp, hp, FALSE, FALSE);
Bram Moolenaar95f09602016-11-10 20:01:45 +01003816 IEMSG(_("E317: pointer block id wrong 2"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 break;
3818 }
3819 pp->pb_pointer[ip->ip_index].pe_line_count += count;
3820 ip->ip_high += count;
3821 mf_put(mfp, hp, TRUE, FALSE);
3822 }
3823}
3824
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003825#if defined(HAVE_READLINK) || defined(PROTO)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003826/*
3827 * Resolve a symlink in the last component of a file name.
3828 * Note that f_resolve() does it for every part of the path, we don't do that
3829 * here.
3830 * If it worked returns OK and the resolved link in "buf[MAXPATHL]".
3831 * Otherwise returns FAIL.
3832 */
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003833 int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003834resolve_symlink(char_u *fname, char_u *buf)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003835{
3836 char_u tmp[MAXPATHL];
3837 int ret;
3838 int depth = 0;
3839
3840 if (fname == NULL)
3841 return FAIL;
3842
3843 /* Put the result so far in tmp[], starting with the original name. */
3844 vim_strncpy(tmp, fname, MAXPATHL - 1);
3845
3846 for (;;)
3847 {
3848 /* Limit symlink depth to 100, catch recursive loops. */
3849 if (++depth == 100)
3850 {
3851 EMSG2(_("E773: Symlink loop for \"%s\""), fname);
3852 return FAIL;
3853 }
3854
3855 ret = readlink((char *)tmp, (char *)buf, MAXPATHL - 1);
3856 if (ret <= 0)
3857 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003858 if (errno == EINVAL || errno == ENOENT)
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003859 {
Bram Moolenaarcc984262005-12-23 22:19:46 +00003860 /* Found non-symlink or not existing file, stop here.
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00003861 * When at the first level use the unmodified name, skip the
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003862 * call to vim_FullName(). */
3863 if (depth == 1)
3864 return FAIL;
3865
3866 /* Use the resolved name in tmp[]. */
3867 break;
3868 }
3869
3870 /* There must be some error reading links, use original name. */
3871 return FAIL;
3872 }
3873 buf[ret] = NUL;
3874
3875 /*
3876 * Check whether the symlink is relative or absolute.
3877 * If it's relative, build a new path based on the directory
3878 * portion of the filename (if any) and the path the symlink
3879 * points to.
3880 */
3881 if (mch_isFullName(buf))
3882 STRCPY(tmp, buf);
3883 else
3884 {
3885 char_u *tail;
3886
3887 tail = gettail(tmp);
3888 if (STRLEN(tail) + STRLEN(buf) >= MAXPATHL)
3889 return FAIL;
3890 STRCPY(tail, buf);
3891 }
3892 }
3893
3894 /*
3895 * Try to resolve the full name of the file so that the swapfile name will
3896 * be consistent even when opening a relative symlink from different
3897 * working directories.
3898 */
3899 return vim_FullName(tmp, buf, MAXPATHL, TRUE);
3900}
3901#endif
3902
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903/*
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003904 * Make swap file name out of the file name and a directory name.
3905 * Returns pointer to allocated memory or NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003906 */
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003907 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003908makeswapname(
3909 char_u *fname,
3910 char_u *ffname UNUSED,
3911 buf_T *buf,
3912 char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913{
3914 char_u *r, *s;
Bram Moolenaar9dbe4752010-05-14 17:52:42 +02003915 char_u *fname_res = fname;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003916#ifdef HAVE_READLINK
3917 char_u fname_buf[MAXPATHL];
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003918#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919
3920#if defined(UNIX) || defined(WIN3264) /* Need _very_ long file names */
Bram Moolenaarb113c3a2017-02-28 21:26:17 +01003921 int len = (int)STRLEN(dir_name);
Bram Moolenaarc525e3a2017-02-18 16:59:02 +01003922
3923 s = dir_name + len;
3924 if (after_pathsep(dir_name, s) && len > 1 && s[-1] == s[-2])
Bram Moolenaar071d4272004-06-13 20:20:40 +00003925 { /* Ends with '//', Use Full path */
3926 r = NULL;
Bram Moolenaar04a09c12005-08-01 22:02:32 +00003927 if ((s = make_percent_swname(dir_name, fname)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 {
3929 r = modname(s, (char_u *)".swp", FALSE);
3930 vim_free(s);
3931 }
3932 return r;
3933 }
3934#endif
3935
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003936#ifdef HAVE_READLINK
3937 /* Expand symlink in the file name, so that we put the swap file with the
3938 * actual file instead of with the symlink. */
3939 if (resolve_symlink(fname, fname_buf) == OK)
3940 fname_res = fname_buf;
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003941#endif
3942
Bram Moolenaar071d4272004-06-13 20:20:40 +00003943 r = buf_modname(
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 (buf->b_p_sn || buf->b_shortname),
Bram Moolenaar900b4d72005-12-12 22:05:50 +00003945 fname_res,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946 (char_u *)
Bram Moolenaare60acc12011-05-10 16:41:25 +02003947#if defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 "_swp",
3949#else
3950 ".swp",
3951#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952 /* Prepend a '.' to the swap file name for the current directory. */
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003953 dir_name[0] == '.' && dir_name[1] == NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954 if (r == NULL) /* out of memory */
3955 return NULL;
3956
3957 s = get_file_in_dir(r, dir_name);
3958 vim_free(r);
3959 return s;
3960}
3961
3962/*
3963 * Get file name to use for swap file or backup file.
3964 * Use the name of the edited file "fname" and an entry in the 'dir' or 'bdir'
3965 * option "dname".
3966 * - If "dname" is ".", return "fname" (swap file in dir of file).
3967 * - If "dname" starts with "./", insert "dname" in "fname" (swap file
3968 * relative to dir of file).
3969 * - Otherwise, prepend "dname" to the tail of "fname" (swap file in specific
3970 * dir).
3971 *
3972 * The return value is an allocated string and can be NULL.
3973 */
3974 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01003975get_file_in_dir(
3976 char_u *fname,
3977 char_u *dname) /* don't use "dirname", it is a global for Alpha */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978{
3979 char_u *t;
3980 char_u *tail;
3981 char_u *retval;
3982 int save_char;
3983
3984 tail = gettail(fname);
3985
3986 if (dname[0] == '.' && dname[1] == NUL)
3987 retval = vim_strsave(fname);
3988 else if (dname[0] == '.' && vim_ispathsep(dname[1]))
3989 {
3990 if (tail == fname) /* no path before file name */
3991 retval = concat_fnames(dname + 2, tail, TRUE);
3992 else
3993 {
3994 save_char = *tail;
3995 *tail = NUL;
3996 t = concat_fnames(fname, dname + 2, TRUE);
3997 *tail = save_char;
3998 if (t == NULL) /* out of memory */
3999 retval = NULL;
4000 else
4001 {
4002 retval = concat_fnames(t, tail, TRUE);
4003 vim_free(t);
4004 }
4005 }
4006 }
4007 else
4008 retval = concat_fnames(dname, tail, TRUE);
4009
Bram Moolenaar69c35002013-11-04 02:54:12 +01004010#ifdef WIN3264
4011 if (retval != NULL)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01004012 for (t = gettail(retval); *t != NUL; MB_PTR_ADV(t))
Bram Moolenaar69c35002013-11-04 02:54:12 +01004013 if (*t == ':')
4014 *t = '%';
4015#endif
4016
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 return retval;
4018}
4019
Bram Moolenaar92b8b2d2016-01-29 22:36:45 +01004020static void attention_message(buf_T *buf, char_u *fname);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004021
4022/*
4023 * Print the ATTENTION message: info about an existing swap file.
4024 */
4025 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004026attention_message(
4027 buf_T *buf, /* buffer being edited */
4028 char_u *fname) /* swap file name */
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004029{
Bram Moolenaar8767f522016-07-01 17:17:39 +02004030 stat_T st;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004031 time_t x, sx;
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004032 char *p;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004033
4034 ++no_wait_return;
4035 (void)EMSG(_("E325: ATTENTION"));
4036 MSG_PUTS(_("\nFound a swap file by the name \""));
4037 msg_home_replace(fname);
4038 MSG_PUTS("\"\n");
4039 sx = swapfile_info(fname);
4040 MSG_PUTS(_("While opening file \""));
4041 msg_outtrans(buf->b_fname);
4042 MSG_PUTS("\"\n");
4043 if (mch_stat((char *)buf->b_fname, &st) != -1)
4044 {
4045 MSG_PUTS(_(" dated: "));
4046 x = st.st_mtime; /* Manx C can't do &st.st_mtime */
Bram Moolenaar31e97bf2006-10-10 14:20:13 +00004047 p = ctime(&x); /* includes '\n' */
4048 if (p == NULL)
4049 MSG_PUTS("(invalid)\n");
4050 else
4051 MSG_PUTS(p);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004052 if (sx != 0 && x > sx)
4053 MSG_PUTS(_(" NEWER than swap file!\n"));
4054 }
4055 /* Some of these messages are long to allow translation to
4056 * other languages. */
Bram Moolenaard9ea9062016-02-02 12:38:02 +01004057 MSG_PUTS(_("\n(1) Another program may be editing the same file. If this is the case,\n be careful not to end up with two different instances of the same\n file when making changes. Quit, or continue with caution.\n"));
Bram Moolenaarc41fc712011-02-15 11:57:04 +01004058 MSG_PUTS(_("(2) An edit session for this file crashed.\n"));
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004059 MSG_PUTS(_(" If this is the case, use \":recover\" or \"vim -r "));
4060 msg_outtrans(buf->b_fname);
4061 MSG_PUTS(_("\"\n to recover the changes (see \":help recovery\").\n"));
4062 MSG_PUTS(_(" If you did this already, delete the swap file \""));
4063 msg_outtrans(fname);
4064 MSG_PUTS(_("\"\n to avoid this message.\n"));
4065 cmdline_row = msg_row;
4066 --no_wait_return;
4067}
4068
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004069#if defined(FEAT_EVAL)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004070/*
4071 * Trigger the SwapExists autocommands.
4072 * Returns a value for equivalent to do_dialog() (see below):
4073 * 0: still need to ask for a choice
4074 * 1: open read-only
4075 * 2: edit anyway
4076 * 3: recover
4077 * 4: delete it
4078 * 5: quit
4079 * 6: abort
4080 */
4081 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004082do_swapexists(buf_T *buf, char_u *fname)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004083{
4084 set_vim_var_string(VV_SWAPNAME, fname, -1);
4085 set_vim_var_string(VV_SWAPCHOICE, NULL, -1);
4086
4087 /* Trigger SwapExists autocommands with <afile> set to the file being
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004088 * edited. Disallow changing directory here. */
4089 ++allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004090 apply_autocmds(EVENT_SWAPEXISTS, buf->b_fname, NULL, FALSE, NULL);
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004091 --allbuf_lock;
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004092
4093 set_vim_var_string(VV_SWAPNAME, NULL, -1);
4094
4095 switch (*get_vim_var_str(VV_SWAPCHOICE))
4096 {
4097 case 'o': return 1;
4098 case 'e': return 2;
4099 case 'r': return 3;
4100 case 'd': return 4;
4101 case 'q': return 5;
4102 case 'a': return 6;
4103 }
4104
4105 return 0;
4106}
4107#endif
4108
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109/*
4110 * Find out what name to use for the swap file for buffer 'buf'.
4111 *
4112 * Several names are tried to find one that does not exist
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004113 * Returns the name in allocated memory or NULL.
Bram Moolenaarf541c362011-10-26 11:44:18 +02004114 * When out of memory "dirp" is set to NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 *
4116 * Note: If BASENAMELEN is not correct, you will get error messages for
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004117 * not being able to open the swap or undo file
Bram Moolenaar12c22ce2009-04-22 13:58:46 +00004118 * Note: May trigger SwapExists autocmd, pointers may change!
Bram Moolenaar071d4272004-06-13 20:20:40 +00004119 */
4120 static char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004121findswapname(
4122 buf_T *buf,
4123 char_u **dirp, /* pointer to list of directories */
4124 char_u *old_fname) /* don't give warning for this file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125{
4126 char_u *fname;
4127 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 char_u *dir_name;
4129#ifdef AMIGA
4130 BPTR fh;
4131#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 int r;
Bram Moolenaar69c35002013-11-04 02:54:12 +01004133 char_u *buf_fname = buf->b_fname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004135#if !defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136# define CREATE_DUMMY_FILE
4137 FILE *dummyfd = NULL;
4138
Bram Moolenaar69c35002013-11-04 02:54:12 +01004139# ifdef WIN3264
4140 if (buf_fname != NULL && !mch_isFullName(buf_fname)
4141 && vim_strchr(gettail(buf_fname), ':'))
4142 {
4143 char_u *t;
4144
4145 buf_fname = vim_strsave(buf_fname);
4146 if (buf_fname == NULL)
4147 buf_fname = buf->b_fname;
4148 else
Bram Moolenaar91acfff2017-03-12 19:22:36 +01004149 for (t = gettail(buf_fname); *t != NUL; MB_PTR_ADV(t))
Bram Moolenaar69c35002013-11-04 02:54:12 +01004150 if (*t == ':')
4151 *t = '%';
4152 }
4153# endif
4154
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004155 /*
4156 * If we start editing a new file, e.g. "test.doc", which resides on an
4157 * MSDOS compatible filesystem, it is possible that the file
4158 * "test.doc.swp" which we create will be exactly the same file. To avoid
4159 * this problem we temporarily create "test.doc". Don't do this when the
4160 * check below for a 8.3 file name is used.
4161 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004162 if (!(buf->b_p_sn || buf->b_shortname) && buf_fname != NULL
4163 && mch_getperm(buf_fname) < 0)
4164 dummyfd = mch_fopen((char *)buf_fname, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165#endif
4166
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004167 /*
4168 * Isolate a directory name from *dirp and put it in dir_name.
4169 * First allocate some memory to put the directory name in.
4170 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004171 dir_name = alloc((unsigned)STRLEN(*dirp) + 1);
Bram Moolenaarf541c362011-10-26 11:44:18 +02004172 if (dir_name == NULL)
4173 *dirp = NULL;
4174 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 (void)copy_option_part(dirp, dir_name, 31000, ",");
4176
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004177 /*
4178 * we try different names until we find one that does not exist yet
4179 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004180 if (dir_name == NULL) /* out of memory */
4181 fname = NULL;
4182 else
Bram Moolenaar69c35002013-11-04 02:54:12 +01004183 fname = makeswapname(buf_fname, buf->b_ffname, buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004184
4185 for (;;)
4186 {
4187 if (fname == NULL) /* must be out of memory */
4188 break;
4189 if ((n = (int)STRLEN(fname)) == 0) /* safety check */
4190 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01004191 VIM_CLEAR(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004192 break;
4193 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004194#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195/*
4196 * Some systems have a MS-DOS compatible filesystem that use 8.3 character
4197 * file names. If this is the first try and the swap file name does not fit in
4198 * 8.3, detect if this is the case, set shortname and try again.
4199 */
4200 if (fname[n - 2] == 'w' && fname[n - 1] == 'p'
4201 && !(buf->b_p_sn || buf->b_shortname))
4202 {
4203 char_u *tail;
4204 char_u *fname2;
Bram Moolenaar8767f522016-07-01 17:17:39 +02004205 stat_T s1, s2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 int f1, f2;
4207 int created1 = FALSE, created2 = FALSE;
4208 int same = FALSE;
4209
4210 /*
4211 * Check if swapfile name does not fit in 8.3:
4212 * It either contains two dots, is longer than 8 chars, or starts
4213 * with a dot.
4214 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004215 tail = gettail(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004216 if ( vim_strchr(tail, '.') != NULL
4217 || STRLEN(tail) > (size_t)8
4218 || *gettail(fname) == '.')
4219 {
4220 fname2 = alloc(n + 2);
4221 if (fname2 != NULL)
4222 {
4223 STRCPY(fname2, fname);
4224 /* if fname == "xx.xx.swp", fname2 = "xx.xx.swx"
4225 * if fname == ".xx.swp", fname2 = ".xx.swpx"
4226 * if fname == "123456789.swp", fname2 = "12345678x.swp"
4227 */
4228 if (vim_strchr(tail, '.') != NULL)
4229 fname2[n - 1] = 'x';
4230 else if (*gettail(fname) == '.')
4231 {
4232 fname2[n] = 'x';
4233 fname2[n + 1] = NUL;
4234 }
4235 else
4236 fname2[n - 5] += 1;
4237 /*
4238 * may need to create the files to be able to use mch_stat()
4239 */
4240 f1 = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4241 if (f1 < 0)
4242 {
4243 f1 = mch_open_rw((char *)fname,
4244 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 created1 = TRUE;
4246 }
4247 if (f1 >= 0)
4248 {
4249 f2 = mch_open((char *)fname2, O_RDONLY | O_EXTRA, 0);
4250 if (f2 < 0)
4251 {
4252 f2 = mch_open_rw((char *)fname2,
4253 O_RDWR|O_CREAT|O_EXCL|O_EXTRA);
4254 created2 = TRUE;
4255 }
4256 if (f2 >= 0)
4257 {
4258 /*
4259 * Both files exist now. If mch_stat() returns the
4260 * same device and inode they are the same file.
4261 */
4262 if (mch_fstat(f1, &s1) != -1
4263 && mch_fstat(f2, &s2) != -1
4264 && s1.st_dev == s2.st_dev
4265 && s1.st_ino == s2.st_ino)
4266 same = TRUE;
4267 close(f2);
4268 if (created2)
4269 mch_remove(fname2);
4270 }
4271 close(f1);
4272 if (created1)
4273 mch_remove(fname);
4274 }
4275 vim_free(fname2);
4276 if (same)
4277 {
4278 buf->b_shortname = TRUE;
4279 vim_free(fname);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004280 fname = makeswapname(buf_fname, buf->b_ffname,
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004281 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282 continue; /* try again with b_shortname set */
4283 }
4284 }
4285 }
4286 }
4287#endif
4288 /*
4289 * check if the swapfile already exists
4290 */
4291 if (mch_getperm(fname) < 0) /* it does not exist */
4292 {
4293#ifdef HAVE_LSTAT
Bram Moolenaar8767f522016-07-01 17:17:39 +02004294 stat_T sb;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295
4296 /*
4297 * Extra security check: When a swap file is a symbolic link, this
4298 * is most likely a symlink attack.
4299 */
4300 if (mch_lstat((char *)fname, &sb) < 0)
4301#else
4302# ifdef AMIGA
4303 fh = Open((UBYTE *)fname, (long)MODE_NEWFILE);
4304 /*
4305 * on the Amiga mch_getperm() will return -1 when the file exists
4306 * but is being used by another program. This happens if you edit
4307 * a file twice.
4308 */
4309 if (fh != (BPTR)NULL) /* can open file, OK */
4310 {
4311 Close(fh);
4312 mch_remove(fname);
4313 break;
4314 }
4315 if (IoErr() != ERROR_OBJECT_IN_USE
4316 && IoErr() != ERROR_OBJECT_EXISTS)
4317# endif
4318#endif
4319 break;
4320 }
4321
4322 /*
4323 * A file name equal to old_fname is OK to use.
4324 */
4325 if (old_fname != NULL && fnamecmp(fname, old_fname) == 0)
4326 break;
4327
4328 /*
4329 * get here when file already exists
4330 */
4331 if (fname[n - 2] == 'w' && fname[n - 1] == 'p') /* first try */
4332 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004333 /*
4334 * on MS-DOS compatible filesystems (e.g. messydos) file.doc.swp
4335 * and file.doc are the same file. To guess if this problem is
4336 * present try if file.doc.swx exists. If it does, we set
4337 * buf->b_shortname and try file_doc.swp (dots replaced by
4338 * underscores for this file), and try again. If it doesn't we
4339 * assume that "file.doc.swp" already exists.
4340 */
4341 if (!(buf->b_p_sn || buf->b_shortname)) /* not tried yet */
4342 {
4343 fname[n - 1] = 'x';
4344 r = mch_getperm(fname); /* try "file.swx" */
4345 fname[n - 1] = 'p';
4346 if (r >= 0) /* "file.swx" seems to exist */
4347 {
4348 buf->b_shortname = TRUE;
4349 vim_free(fname);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004350 fname = makeswapname(buf_fname, buf->b_ffname,
Bram Moolenaar04a09c12005-08-01 22:02:32 +00004351 buf, dir_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004352 continue; /* try again with '.' replaced with '_' */
4353 }
4354 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004355 /*
4356 * If we get here the ".swp" file really exists.
4357 * Give an error message, unless recovering, no file name, we are
4358 * viewing a help file or when the path of the file is different
4359 * (happens when all .swp files are in one directory).
4360 */
Bram Moolenaar69c35002013-11-04 02:54:12 +01004361 if (!recoverymode && buf_fname != NULL
Bram Moolenaar8fc061c2004-12-29 21:03:02 +00004362 && !buf->b_help && !(buf->b_flags & BF_DUMMY))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363 {
4364 int fd;
4365 struct block0 b0;
4366 int differ = FALSE;
4367
4368 /*
4369 * Try to read block 0 from the swap file to get the original
4370 * file name (and inode number).
4371 */
4372 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
4373 if (fd >= 0)
4374 {
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004375 if (read_eintr(fd, &b0, sizeof(b0)) == sizeof(b0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 {
4377 /*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004378 * If the swapfile has the same directory as the
4379 * buffer don't compare the directory names, they can
4380 * have a different mountpoint.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004381 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004382 if (b0.b0_flags & B0_SAME_DIR)
4383 {
4384 if (fnamecmp(gettail(buf->b_ffname),
4385 gettail(b0.b0_fname)) != 0
4386 || !same_directory(fname, buf->b_ffname))
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004387 {
4388#ifdef CHECK_INODE
4389 /* Symlinks may point to the same file even
4390 * when the name differs, need to check the
4391 * inode too. */
4392 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
4393 if (fnamecmp_ino(buf->b_ffname, NameBuff,
4394 char_to_long(b0.b0_ino)))
4395#endif
4396 differ = TRUE;
4397 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004398 }
4399 else
4400 {
4401 /*
4402 * The name in the swap file may be
4403 * "~user/path/file". Expand it first.
4404 */
4405 expand_env(b0.b0_fname, NameBuff, MAXPATHL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004406#ifdef CHECK_INODE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004407 if (fnamecmp_ino(buf->b_ffname, NameBuff,
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004408 char_to_long(b0.b0_ino)))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004409 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410#else
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004411 if (fnamecmp(NameBuff, buf->b_ffname) != 0)
4412 differ = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004413#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415 }
4416 close(fd);
4417 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004418
4419 /* give the ATTENTION message when there is an old swap file
4420 * for the current file, and the buffer was not recovered. */
4421 if (differ == FALSE && !(curbuf->b_flags & BF_RECOVERED)
4422 && vim_strchr(p_shm, SHM_ATTENTION) == NULL)
4423 {
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004424#if defined(HAS_SWAP_EXISTS_ACTION)
4425 int choice = 0;
4426#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004427#ifdef CREATE_DUMMY_FILE
4428 int did_use_dummy = FALSE;
4429
4430 /* Avoid getting a warning for the file being created
4431 * outside of Vim, it was created at the start of this
4432 * function. Delete the file now, because Vim might exit
4433 * here if the window is closed. */
4434 if (dummyfd != NULL)
4435 {
4436 fclose(dummyfd);
4437 dummyfd = NULL;
Bram Moolenaar69c35002013-11-04 02:54:12 +01004438 mch_remove(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439 did_use_dummy = TRUE;
4440 }
4441#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004443#if (defined(UNIX) || defined(VMS)) && (defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004444 process_still_running = FALSE;
4445#endif
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004446#if defined(FEAT_EVAL)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004447 /*
4448 * If there is an SwapExists autocommand and we can handle
4449 * the response, trigger it. It may return 0 to ask the
4450 * user anyway.
4451 */
4452 if (swap_exists_action != SEA_NONE
Bram Moolenaar69c35002013-11-04 02:54:12 +01004453 && has_autocmd(EVENT_SWAPEXISTS, buf_fname, buf))
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004454 choice = do_swapexists(buf, fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004456 if (choice == 0)
4457#endif
4458 {
4459#ifdef FEAT_GUI
4460 /* If we are supposed to start the GUI but it wasn't
4461 * completely started yet, start it now. This makes
4462 * the messages displayed in the Vim window when
4463 * loading a session from the .gvimrc file. */
4464 if (gui.starting && !gui.in_use)
4465 gui_start();
4466#endif
4467 /* Show info about the existing swap file. */
4468 attention_message(buf, fname);
4469
4470 /* We don't want a 'q' typed at the more-prompt
4471 * interrupt loading a file. */
4472 got_int = FALSE;
4473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474
4475#if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004476 if (swap_exists_action != SEA_NONE && choice == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 {
4478 char_u *name;
4479
4480 name = alloc((unsigned)(STRLEN(fname)
4481 + STRLEN(_("Swap file \""))
4482 + STRLEN(_("\" already exists!")) + 5));
4483 if (name != NULL)
4484 {
4485 STRCPY(name, _("Swap file \""));
4486 home_replace(NULL, fname, name + STRLEN(name),
4487 1000, TRUE);
4488 STRCAT(name, _("\" already exists!"));
4489 }
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004490 choice = do_dialog(VIM_WARNING,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491 (char_u *)_("VIM - ATTENTION"),
4492 name == NULL
4493 ? (char_u *)_("Swap file already exists!")
4494 : name,
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004495# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496 process_still_running
4497 ? (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Quit\n&Abort") :
4498# endif
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004499 (char_u *)_("&Open Read-Only\n&Edit anyway\n&Recover\n&Delete it\n&Quit\n&Abort"), 1, NULL, FALSE);
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004500
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004501# if defined(UNIX) || defined(VMS)
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004502 if (process_still_running && choice >= 4)
4503 choice++; /* Skip missing "Delete it" button */
4504# endif
4505 vim_free(name);
4506
4507 /* pretend screen didn't scroll, need redraw anyway */
4508 msg_scrolled = 0;
4509 redraw_all_later(NOT_VALID);
4510 }
4511#endif
4512
4513#if defined(HAS_SWAP_EXISTS_ACTION)
4514 if (choice > 0)
4515 {
4516 switch (choice)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004517 {
4518 case 1:
4519 buf->b_p_ro = TRUE;
4520 break;
4521 case 2:
4522 break;
4523 case 3:
4524 swap_exists_action = SEA_RECOVER;
4525 break;
4526 case 4:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004527 mch_remove(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528 break;
4529 case 5:
4530 swap_exists_action = SEA_QUIT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 break;
4532 case 6:
Bram Moolenaard5bc83f2005-12-07 21:07:59 +00004533 swap_exists_action = SEA_QUIT;
4534 got_int = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 break;
4536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004537
4538 /* If the file was deleted this fname can be used. */
4539 if (mch_getperm(fname) < 0)
4540 break;
4541 }
4542 else
4543#endif
4544 {
4545 MSG_PUTS("\n");
Bram Moolenaar4770d092006-01-12 23:22:24 +00004546 if (msg_silent == 0)
4547 /* call wait_return() later */
4548 need_wait_return = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004549 }
4550
4551#ifdef CREATE_DUMMY_FILE
4552 /* Going to try another name, need the dummy file again. */
4553 if (did_use_dummy)
Bram Moolenaar69c35002013-11-04 02:54:12 +01004554 dummyfd = mch_fopen((char *)buf_fname, "w");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004555#endif
4556 }
4557 }
4558 }
4559
4560 /*
4561 * Change the ".swp" extension to find another file that can be used.
4562 * First decrement the last char: ".swo", ".swn", etc.
4563 * If that still isn't enough decrement the last but one char: ".svz"
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00004564 * Can happen when editing many "No Name" buffers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004565 */
4566 if (fname[n - 1] == 'a') /* ".s?a" */
4567 {
4568 if (fname[n - 2] == 'a') /* ".saa": tried enough, give up */
4569 {
4570 EMSG(_("E326: Too many swap files found"));
Bram Moolenaard23a8232018-02-10 18:45:26 +01004571 VIM_CLEAR(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572 break;
4573 }
4574 --fname[n - 2]; /* ".svz", ".suz", etc. */
4575 fname[n - 1] = 'z' + 1;
4576 }
4577 --fname[n - 1]; /* ".swo", ".swn", etc. */
4578 }
4579
4580 vim_free(dir_name);
4581#ifdef CREATE_DUMMY_FILE
4582 if (dummyfd != NULL) /* file has been created temporarily */
4583 {
4584 fclose(dummyfd);
Bram Moolenaar69c35002013-11-04 02:54:12 +01004585 mch_remove(buf_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004586 }
4587#endif
Bram Moolenaar69c35002013-11-04 02:54:12 +01004588#ifdef WIN3264
4589 if (buf_fname != buf->b_fname)
4590 vim_free(buf_fname);
4591#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004592 return fname;
4593}
4594
4595 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004596b0_magic_wrong(ZERO_BL *b0p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004597{
4598 return (b0p->b0_magic_long != (long)B0_MAGIC_LONG
4599 || b0p->b0_magic_int != (int)B0_MAGIC_INT
4600 || b0p->b0_magic_short != (short)B0_MAGIC_SHORT
4601 || b0p->b0_magic_char != B0_MAGIC_CHAR);
4602}
4603
4604#ifdef CHECK_INODE
4605/*
4606 * Compare current file name with file name from swap file.
4607 * Try to use inode numbers when possible.
4608 * Return non-zero when files are different.
4609 *
4610 * When comparing file names a few things have to be taken into consideration:
4611 * - When working over a network the full path of a file depends on the host.
4612 * We check the inode number if possible. It is not 100% reliable though,
4613 * because the device number cannot be used over a network.
4614 * - When a file does not exist yet (editing a new file) there is no inode
4615 * number.
4616 * - The file name in a swap file may not be valid on the current host. The
4617 * "~user" form is used whenever possible to avoid this.
4618 *
4619 * This is getting complicated, let's make a table:
4620 *
4621 * ino_c ino_s fname_c fname_s differ =
4622 *
4623 * both files exist -> compare inode numbers:
4624 * != 0 != 0 X X ino_c != ino_s
4625 *
4626 * inode number(s) unknown, file names available -> compare file names
4627 * == 0 X OK OK fname_c != fname_s
4628 * X == 0 OK OK fname_c != fname_s
4629 *
4630 * current file doesn't exist, file for swap file exist, file name(s) not
4631 * available -> probably different
4632 * == 0 != 0 FAIL X TRUE
4633 * == 0 != 0 X FAIL TRUE
4634 *
4635 * current file exists, inode for swap unknown, file name(s) not
4636 * available -> probably different
4637 * != 0 == 0 FAIL X TRUE
4638 * != 0 == 0 X FAIL TRUE
4639 *
4640 * current file doesn't exist, inode for swap unknown, one file name not
4641 * available -> probably different
4642 * == 0 == 0 FAIL OK TRUE
4643 * == 0 == 0 OK FAIL TRUE
4644 *
4645 * current file doesn't exist, inode for swap unknown, both file names not
Bram Moolenaar8c3169c2018-05-12 17:04:12 +02004646 * available -> compare file names
4647 * == 0 == 0 FAIL FAIL fname_c != fname_s
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648 *
4649 * Note that when the ino_t is 64 bits, only the last 32 will be used. This
4650 * can't be changed without making the block 0 incompatible with 32 bit
4651 * versions.
4652 */
4653
4654 static int
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004655fnamecmp_ino(
4656 char_u *fname_c, /* current file name */
4657 char_u *fname_s, /* file name from swap file */
4658 long ino_block0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659{
Bram Moolenaar8767f522016-07-01 17:17:39 +02004660 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004661 ino_t ino_c = 0; /* ino of current file */
4662 ino_t ino_s; /* ino of file from swap file */
4663 char_u buf_c[MAXPATHL]; /* full path of fname_c */
4664 char_u buf_s[MAXPATHL]; /* full path of fname_s */
4665 int retval_c; /* flag: buf_c valid */
4666 int retval_s; /* flag: buf_s valid */
4667
4668 if (mch_stat((char *)fname_c, &st) == 0)
4669 ino_c = (ino_t)st.st_ino;
4670
4671 /*
4672 * First we try to get the inode from the file name, because the inode in
4673 * the swap file may be outdated. If that fails (e.g. this path is not
4674 * valid on this machine), use the inode from block 0.
4675 */
4676 if (mch_stat((char *)fname_s, &st) == 0)
4677 ino_s = (ino_t)st.st_ino;
4678 else
4679 ino_s = (ino_t)ino_block0;
4680
4681 if (ino_c && ino_s)
4682 return (ino_c != ino_s);
4683
4684 /*
4685 * One of the inode numbers is unknown, try a forced vim_FullName() and
4686 * compare the file names.
4687 */
4688 retval_c = vim_FullName(fname_c, buf_c, MAXPATHL, TRUE);
4689 retval_s = vim_FullName(fname_s, buf_s, MAXPATHL, TRUE);
4690 if (retval_c == OK && retval_s == OK)
Bram Moolenaar8c3169c2018-05-12 17:04:12 +02004691 return STRCMP(buf_c, buf_s) != 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692
4693 /*
4694 * Can't compare inodes or file names, guess that the files are different,
Bram Moolenaar8c3169c2018-05-12 17:04:12 +02004695 * unless both appear not to exist at all, then compare with the file name
4696 * in the swap file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697 */
4698 if (ino_s == 0 && ino_c == 0 && retval_c == FAIL && retval_s == FAIL)
Bram Moolenaar8c3169c2018-05-12 17:04:12 +02004699 return STRCMP(fname_c, fname_s) != 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700 return TRUE;
4701}
4702#endif /* CHECK_INODE */
4703
4704/*
4705 * Move a long integer into a four byte character array.
4706 * Used for machine independency in block zero.
4707 */
4708 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004709long_to_char(long n, char_u *s)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710{
4711 s[0] = (char_u)(n & 0xff);
4712 n = (unsigned)n >> 8;
4713 s[1] = (char_u)(n & 0xff);
4714 n = (unsigned)n >> 8;
4715 s[2] = (char_u)(n & 0xff);
4716 n = (unsigned)n >> 8;
4717 s[3] = (char_u)(n & 0xff);
4718}
4719
4720 static long
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004721char_to_long(char_u *s)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004722{
4723 long retval;
4724
4725 retval = s[3];
4726 retval <<= 8;
4727 retval |= s[2];
4728 retval <<= 8;
4729 retval |= s[1];
4730 retval <<= 8;
4731 retval |= s[0];
4732
4733 return retval;
4734}
4735
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004736/*
4737 * Set the flags in the first block of the swap file:
4738 * - file is modified or not: buf->b_changed
4739 * - 'fileformat'
4740 * - 'fileencoding'
4741 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004743ml_setflags(buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744{
4745 bhdr_T *hp;
4746 ZERO_BL *b0p;
4747
4748 if (!buf->b_ml.ml_mfp)
4749 return;
4750 for (hp = buf->b_ml.ml_mfp->mf_used_last; hp != NULL; hp = hp->bh_prev)
4751 {
4752 if (hp->bh_bnum == 0)
4753 {
4754 b0p = (ZERO_BL *)(hp->bh_data);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004755 b0p->b0_dirty = buf->b_changed ? B0_DIRTY : 0;
4756 b0p->b0_flags = (b0p->b0_flags & ~B0_FF_MASK)
4757 | (get_fileformat(buf) + 1);
4758#ifdef FEAT_MBYTE
4759 add_b0_fenc(b0p, buf);
4760#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004761 hp->bh_flags |= BH_DIRTY;
4762 mf_sync(buf->b_ml.ml_mfp, MFS_ZERO);
4763 break;
4764 }
4765 }
4766}
4767
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004768#if defined(FEAT_CRYPT) || defined(PROTO)
4769/*
4770 * If "data" points to a data block encrypt the text in it and return a copy
4771 * in allocated memory. Return NULL when out of memory.
4772 * Otherwise return "data".
4773 */
4774 char_u *
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004775ml_encrypt_data(
4776 memfile_T *mfp,
4777 char_u *data,
Bram Moolenaar8767f522016-07-01 17:17:39 +02004778 off_T offset,
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004779 unsigned size)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004780{
4781 DATA_BL *dp = (DATA_BL *)data;
4782 char_u *head_end;
4783 char_u *text_start;
4784 char_u *new_data;
4785 int text_len;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004786 cryptstate_T *state;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004787
4788 if (dp->db_id != DATA_ID)
4789 return data;
4790
Bram Moolenaarbc563362015-06-09 18:35:25 +02004791 state = ml_crypt_prepare(mfp, offset, FALSE);
4792 if (state == NULL)
4793 return data;
4794
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004795 new_data = (char_u *)alloc(size);
4796 if (new_data == NULL)
4797 return NULL;
4798 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4799 text_start = (char_u *)dp + dp->db_txt_start;
4800 text_len = size - dp->db_txt_start;
4801
4802 /* Copy the header and the text. */
4803 mch_memmove(new_data, dp, head_end - (char_u *)dp);
4804
4805 /* Encrypt the text. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004806 crypt_encode(state, text_start, text_len, new_data + dp->db_txt_start);
4807 crypt_free_state(state);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004808
4809 /* Clear the gap. */
4810 if (head_end < text_start)
4811 vim_memset(new_data + (head_end - data), 0, text_start - head_end);
4812
4813 return new_data;
4814}
4815
4816/*
Bram Moolenaarbc563362015-06-09 18:35:25 +02004817 * Decrypt the text in "data" if it points to an encrypted data block.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004818 */
4819 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004820ml_decrypt_data(
4821 memfile_T *mfp,
4822 char_u *data,
Bram Moolenaar8767f522016-07-01 17:17:39 +02004823 off_T offset,
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004824 unsigned size)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004825{
4826 DATA_BL *dp = (DATA_BL *)data;
4827 char_u *head_end;
4828 char_u *text_start;
4829 int text_len;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004830 cryptstate_T *state;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004831
4832 if (dp->db_id == DATA_ID)
4833 {
4834 head_end = (char_u *)(&dp->db_index[dp->db_line_count]);
4835 text_start = (char_u *)dp + dp->db_txt_start;
4836 text_len = dp->db_txt_end - dp->db_txt_start;
4837
4838 if (head_end > text_start || dp->db_txt_start > size
4839 || dp->db_txt_end > size)
4840 return; /* data was messed up */
4841
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004842 state = ml_crypt_prepare(mfp, offset, TRUE);
Bram Moolenaarbc563362015-06-09 18:35:25 +02004843 if (state != NULL)
4844 {
4845 /* Decrypt the text in place. */
4846 crypt_decode_inplace(state, text_start, text_len);
4847 crypt_free_state(state);
4848 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004849 }
4850}
4851
4852/*
4853 * Prepare for encryption/decryption, using the key, seed and offset.
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004854 * Return an allocated cryptstate_T *.
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004855 */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004856 static cryptstate_T *
Bram Moolenaar8767f522016-07-01 17:17:39 +02004857ml_crypt_prepare(memfile_T *mfp, off_T offset, int reading)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004858{
4859 buf_T *buf = mfp->mf_buffer;
4860 char_u salt[50];
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004861 int method_nr;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004862 char_u *key;
4863 char_u *seed;
4864
4865 if (reading && mfp->mf_old_key != NULL)
4866 {
4867 /* Reading back blocks with the previous key/method/seed. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004868 method_nr = mfp->mf_old_cm;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004869 key = mfp->mf_old_key;
4870 seed = mfp->mf_old_seed;
4871 }
4872 else
4873 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004874 method_nr = crypt_get_method_nr(buf);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004875 key = buf->b_p_key;
4876 seed = mfp->mf_seed;
4877 }
Bram Moolenaarbc563362015-06-09 18:35:25 +02004878 if (*key == NUL)
4879 return NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004880
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004881 if (method_nr == CRYPT_M_ZIP)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004882 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004883 /* For PKzip: Append the offset to the key, so that we use a different
4884 * key for every block. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004885 vim_snprintf((char *)salt, sizeof(salt), "%s%ld", key, (long)offset);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004886 return crypt_create(method_nr, salt, NULL, 0, NULL, 0);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004887 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004888
4889 /* Using blowfish or better: add salt and seed. We use the byte offset
4890 * of the block for the salt. */
4891 vim_snprintf((char *)salt, sizeof(salt), "%ld", (long)offset);
4892 return crypt_create(method_nr, key, salt, (int)STRLEN(salt),
4893 seed, MF_SEED_LEN);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004894}
4895
4896#endif
4897
4898
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899#if defined(FEAT_BYTEOFF) || defined(PROTO)
4900
4901#define MLCS_MAXL 800 /* max no of lines in chunk */
4902#define MLCS_MINL 400 /* should be half of MLCS_MAXL */
4903
4904/*
Bram Moolenaar0ad014c2010-07-25 14:00:46 +02004905 * Keep information for finding byte offset of a line, updtype may be one of:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 * ML_CHNK_ADDLINE: Add len to parent chunk, possibly splitting it
4907 * Careful: ML_CHNK_ADDLINE may cause ml_find_line() to be called.
4908 * ML_CHNK_DELLINE: Subtract len from parent chunk, possibly deleting it
4909 * ML_CHNK_UPDLINE: Add len to parent chunk, as a signed entity.
4910 */
4911 static void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01004912ml_updatechunk(
4913 buf_T *buf,
4914 linenr_T line,
4915 long len,
4916 int updtype)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004917{
4918 static buf_T *ml_upd_lastbuf = NULL;
4919 static linenr_T ml_upd_lastline;
4920 static linenr_T ml_upd_lastcurline;
4921 static int ml_upd_lastcurix;
4922
4923 linenr_T curline = ml_upd_lastcurline;
4924 int curix = ml_upd_lastcurix;
4925 long size;
4926 chunksize_T *curchnk;
4927 int rest;
4928 bhdr_T *hp;
4929 DATA_BL *dp;
4930
4931 if (buf->b_ml.ml_usedchunks == -1 || len == 0)
4932 return;
4933 if (buf->b_ml.ml_chunksize == NULL)
4934 {
4935 buf->b_ml.ml_chunksize = (chunksize_T *)
4936 alloc((unsigned)sizeof(chunksize_T) * 100);
4937 if (buf->b_ml.ml_chunksize == NULL)
4938 {
4939 buf->b_ml.ml_usedchunks = -1;
4940 return;
4941 }
4942 buf->b_ml.ml_numchunks = 100;
4943 buf->b_ml.ml_usedchunks = 1;
4944 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4945 buf->b_ml.ml_chunksize[0].mlcs_totalsize = 1;
4946 }
4947
4948 if (updtype == ML_CHNK_UPDLINE && buf->b_ml.ml_line_count == 1)
4949 {
4950 /*
4951 * First line in empty buffer from ml_flush_line() -- reset
4952 */
4953 buf->b_ml.ml_usedchunks = 1;
4954 buf->b_ml.ml_chunksize[0].mlcs_numlines = 1;
4955 buf->b_ml.ml_chunksize[0].mlcs_totalsize =
4956 (long)STRLEN(buf->b_ml.ml_line_ptr) + 1;
4957 return;
4958 }
4959
4960 /*
4961 * Find chunk that our line belongs to, curline will be at start of the
4962 * chunk.
4963 */
4964 if (buf != ml_upd_lastbuf || line != ml_upd_lastline + 1
4965 || updtype != ML_CHNK_ADDLINE)
4966 {
4967 for (curline = 1, curix = 0;
4968 curix < buf->b_ml.ml_usedchunks - 1
4969 && line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4970 curix++)
4971 {
4972 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4973 }
4974 }
4975 else if (line >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines
4976 && curix < buf->b_ml.ml_usedchunks - 1)
4977 {
4978 /* Adjust cached curix & curline */
4979 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
4980 curix++;
4981 }
4982 curchnk = buf->b_ml.ml_chunksize + curix;
4983
4984 if (updtype == ML_CHNK_DELLINE)
Bram Moolenaar5a6404c2006-11-01 17:12:57 +00004985 len = -len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 curchnk->mlcs_totalsize += len;
4987 if (updtype == ML_CHNK_ADDLINE)
4988 {
4989 curchnk->mlcs_numlines++;
4990
4991 /* May resize here so we don't have to do it in both cases below */
4992 if (buf->b_ml.ml_usedchunks + 1 >= buf->b_ml.ml_numchunks)
4993 {
Bram Moolenaar9abd5c62015-02-10 18:34:01 +01004994 chunksize_T *t_chunksize = buf->b_ml.ml_chunksize;
4995
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996 buf->b_ml.ml_numchunks = buf->b_ml.ml_numchunks * 3 / 2;
4997 buf->b_ml.ml_chunksize = (chunksize_T *)
4998 vim_realloc(buf->b_ml.ml_chunksize,
4999 sizeof(chunksize_T) * buf->b_ml.ml_numchunks);
5000 if (buf->b_ml.ml_chunksize == NULL)
5001 {
5002 /* Hmmmm, Give up on offset for this buffer */
Bram Moolenaar9abd5c62015-02-10 18:34:01 +01005003 vim_free(t_chunksize);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005004 buf->b_ml.ml_usedchunks = -1;
5005 return;
5006 }
5007 }
5008
5009 if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MAXL)
5010 {
5011 int count; /* number of entries in block */
5012 int idx;
5013 int text_end;
5014 int linecnt;
5015
5016 mch_memmove(buf->b_ml.ml_chunksize + curix + 1,
5017 buf->b_ml.ml_chunksize + curix,
5018 (buf->b_ml.ml_usedchunks - curix) *
5019 sizeof(chunksize_T));
Bram Moolenaar9439cdd2009-04-22 13:39:36 +00005020 /* Compute length of first half of lines in the split chunk */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 size = 0;
5022 linecnt = 0;
5023 while (curline < buf->b_ml.ml_line_count
5024 && linecnt < MLCS_MINL)
5025 {
5026 if ((hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5027 {
5028 buf->b_ml.ml_usedchunks = -1;
5029 return;
5030 }
5031 dp = (DATA_BL *)(hp->bh_data);
5032 count = (long)(buf->b_ml.ml_locked_high) -
5033 (long)(buf->b_ml.ml_locked_low) + 1;
5034 idx = curline - buf->b_ml.ml_locked_low;
5035 curline = buf->b_ml.ml_locked_high + 1;
5036 if (idx == 0)/* first line in block, text at the end */
5037 text_end = dp->db_txt_end;
5038 else
5039 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5040 /* Compute index of last line to use in this MEMLINE */
5041 rest = count - idx;
5042 if (linecnt + rest > MLCS_MINL)
5043 {
5044 idx += MLCS_MINL - linecnt - 1;
5045 linecnt = MLCS_MINL;
5046 }
5047 else
5048 {
5049 idx = count - 1;
5050 linecnt += rest;
5051 }
5052 size += text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5053 }
5054 buf->b_ml.ml_chunksize[curix].mlcs_numlines = linecnt;
5055 buf->b_ml.ml_chunksize[curix + 1].mlcs_numlines -= linecnt;
5056 buf->b_ml.ml_chunksize[curix].mlcs_totalsize = size;
5057 buf->b_ml.ml_chunksize[curix + 1].mlcs_totalsize -= size;
5058 buf->b_ml.ml_usedchunks++;
5059 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5060 return;
5061 }
5062 else if (buf->b_ml.ml_chunksize[curix].mlcs_numlines >= MLCS_MINL
5063 && curix == buf->b_ml.ml_usedchunks - 1
5064 && buf->b_ml.ml_line_count - line <= 1)
5065 {
5066 /*
5067 * We are in the last chunk and it is cheap to crate a new one
5068 * after this. Do it now to avoid the loop above later on
5069 */
5070 curchnk = buf->b_ml.ml_chunksize + curix + 1;
5071 buf->b_ml.ml_usedchunks++;
5072 if (line == buf->b_ml.ml_line_count)
5073 {
5074 curchnk->mlcs_numlines = 0;
5075 curchnk->mlcs_totalsize = 0;
5076 }
5077 else
5078 {
5079 /*
5080 * Line is just prior to last, move count for last
5081 * This is the common case when loading a new file
5082 */
5083 hp = ml_find_line(buf, buf->b_ml.ml_line_count, ML_FIND);
5084 if (hp == NULL)
5085 {
5086 buf->b_ml.ml_usedchunks = -1;
5087 return;
5088 }
5089 dp = (DATA_BL *)(hp->bh_data);
5090 if (dp->db_line_count == 1)
5091 rest = dp->db_txt_end - dp->db_txt_start;
5092 else
5093 rest =
5094 ((dp->db_index[dp->db_line_count - 2]) & DB_INDEX_MASK)
5095 - dp->db_txt_start;
5096 curchnk->mlcs_totalsize = rest;
5097 curchnk->mlcs_numlines = 1;
5098 curchnk[-1].mlcs_totalsize -= rest;
5099 curchnk[-1].mlcs_numlines -= 1;
5100 }
5101 }
5102 }
5103 else if (updtype == ML_CHNK_DELLINE)
5104 {
5105 curchnk->mlcs_numlines--;
5106 ml_upd_lastbuf = NULL; /* Force recalc of curix & curline */
5107 if (curix < (buf->b_ml.ml_usedchunks - 1)
5108 && (curchnk->mlcs_numlines + curchnk[1].mlcs_numlines)
5109 <= MLCS_MINL)
5110 {
5111 curix++;
5112 curchnk = buf->b_ml.ml_chunksize + curix;
5113 }
5114 else if (curix == 0 && curchnk->mlcs_numlines <= 0)
5115 {
5116 buf->b_ml.ml_usedchunks--;
5117 mch_memmove(buf->b_ml.ml_chunksize, buf->b_ml.ml_chunksize + 1,
5118 buf->b_ml.ml_usedchunks * sizeof(chunksize_T));
5119 return;
5120 }
5121 else if (curix == 0 || (curchnk->mlcs_numlines > 10
5122 && (curchnk->mlcs_numlines + curchnk[-1].mlcs_numlines)
5123 > MLCS_MINL))
5124 {
5125 return;
5126 }
5127
5128 /* Collapse chunks */
5129 curchnk[-1].mlcs_numlines += curchnk->mlcs_numlines;
5130 curchnk[-1].mlcs_totalsize += curchnk->mlcs_totalsize;
5131 buf->b_ml.ml_usedchunks--;
5132 if (curix < buf->b_ml.ml_usedchunks)
5133 {
5134 mch_memmove(buf->b_ml.ml_chunksize + curix,
5135 buf->b_ml.ml_chunksize + curix + 1,
5136 (buf->b_ml.ml_usedchunks - curix) *
5137 sizeof(chunksize_T));
5138 }
5139 return;
5140 }
5141 ml_upd_lastbuf = buf;
5142 ml_upd_lastline = line;
5143 ml_upd_lastcurline = curline;
5144 ml_upd_lastcurix = curix;
5145}
5146
5147/*
5148 * Find offset for line or line with offset.
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005149 * Find line with offset if "lnum" is 0; return remaining offset in offp
5150 * Find offset of line if "lnum" > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151 * return -1 if information is not available
5152 */
5153 long
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01005154ml_find_line_or_offset(buf_T *buf, linenr_T lnum, long *offp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005155{
5156 linenr_T curline;
5157 int curix;
5158 long size;
5159 bhdr_T *hp;
5160 DATA_BL *dp;
5161 int count; /* number of entries in block */
5162 int idx;
5163 int start_idx;
5164 int text_end;
5165 long offset;
5166 int len;
5167 int ffdos = (get_fileformat(buf) == EOL_DOS);
5168 int extra = 0;
5169
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005170 /* take care of cached line first */
5171 ml_flush_line(curbuf);
5172
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 if (buf->b_ml.ml_usedchunks == -1
5174 || buf->b_ml.ml_chunksize == NULL
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005175 || lnum < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 return -1;
5177
5178 if (offp == NULL)
5179 offset = 0;
5180 else
5181 offset = *offp;
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005182 if (lnum == 0 && offset <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183 return 1; /* Not a "find offset" and offset 0 _must_ be in line 1 */
5184 /*
5185 * Find the last chunk before the one containing our line. Last chunk is
5186 * special because it will never qualify
5187 */
5188 curline = 1;
5189 curix = size = 0;
5190 while (curix < buf->b_ml.ml_usedchunks - 1
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005191 && ((lnum != 0
5192 && lnum >= curline + buf->b_ml.ml_chunksize[curix].mlcs_numlines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 || (offset != 0
5194 && offset > size + buf->b_ml.ml_chunksize[curix].mlcs_totalsize
5195 + ffdos * buf->b_ml.ml_chunksize[curix].mlcs_numlines)))
5196 {
5197 curline += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5198 size += buf->b_ml.ml_chunksize[curix].mlcs_totalsize;
5199 if (offset && ffdos)
5200 size += buf->b_ml.ml_chunksize[curix].mlcs_numlines;
5201 curix++;
5202 }
5203
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005204 while ((lnum != 0 && curline < lnum) || (offset != 0 && size < offset))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205 {
5206 if (curline > buf->b_ml.ml_line_count
5207 || (hp = ml_find_line(buf, curline, ML_FIND)) == NULL)
5208 return -1;
5209 dp = (DATA_BL *)(hp->bh_data);
5210 count = (long)(buf->b_ml.ml_locked_high) -
5211 (long)(buf->b_ml.ml_locked_low) + 1;
5212 start_idx = idx = curline - buf->b_ml.ml_locked_low;
5213 if (idx == 0)/* first line in block, text at the end */
5214 text_end = dp->db_txt_end;
5215 else
5216 text_end = ((dp->db_index[idx - 1]) & DB_INDEX_MASK);
5217 /* Compute index of last line to use in this MEMLINE */
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005218 if (lnum != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 {
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005220 if (curline + (count - idx) >= lnum)
5221 idx += lnum - curline - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 else
5223 idx = count - 1;
5224 }
5225 else
5226 {
5227 extra = 0;
5228 while (offset >= size
5229 + text_end - (int)((dp->db_index[idx]) & DB_INDEX_MASK)
5230 + ffdos)
5231 {
5232 if (ffdos)
5233 size++;
5234 if (idx == count - 1)
5235 {
5236 extra = 1;
5237 break;
5238 }
5239 idx++;
5240 }
5241 }
5242 len = text_end - ((dp->db_index[idx]) & DB_INDEX_MASK);
5243 size += len;
5244 if (offset != 0 && size >= offset)
5245 {
5246 if (size + ffdos == offset)
5247 *offp = 0;
5248 else if (idx == start_idx)
5249 *offp = offset - size + len;
5250 else
5251 *offp = offset - size + len
5252 - (text_end - ((dp->db_index[idx - 1]) & DB_INDEX_MASK));
5253 curline += idx - start_idx + extra;
5254 if (curline > buf->b_ml.ml_line_count)
5255 return -1; /* exactly one byte beyond the end */
5256 return curline;
5257 }
5258 curline = buf->b_ml.ml_locked_high + 1;
5259 }
5260
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005261 if (lnum != 0)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005262 {
5263 /* Count extra CR characters. */
5264 if (ffdos)
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00005265 size += lnum - 1;
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005266
Bram Moolenaar34d72d42015-07-17 14:18:08 +02005267 /* Don't count the last line break if 'noeol' and ('bin' or
5268 * 'nofixeol'). */
5269 if ((!buf->b_p_fixeol || buf->b_p_bin) && !buf->b_p_eol
5270 && buf->b_ml.ml_line_count == lnum)
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00005271 size -= ffdos + 1;
5272 }
5273
Bram Moolenaar071d4272004-06-13 20:20:40 +00005274 return size;
5275}
5276
5277/*
5278 * Goto byte in buffer with offset 'cnt'.
5279 */
5280 void
Bram Moolenaar52ea13d2016-01-30 18:51:09 +01005281goto_byte(long cnt)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005282{
5283 long boff = cnt;
5284 linenr_T lnum;
5285
5286 ml_flush_line(curbuf); /* cached line may be dirty */
5287 setpcmark();
5288 if (boff)
5289 --boff;
5290 lnum = ml_find_line_or_offset(curbuf, (linenr_T)0, &boff);
5291 if (lnum < 1) /* past the end */
5292 {
5293 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
5294 curwin->w_curswant = MAXCOL;
5295 coladvance((colnr_T)MAXCOL);
5296 }
5297 else
5298 {
5299 curwin->w_cursor.lnum = lnum;
5300 curwin->w_cursor.col = (colnr_T)boff;
Bram Moolenaar943d2b52005-12-02 00:50:49 +00005301# ifdef FEAT_VIRTUALEDIT
5302 curwin->w_cursor.coladd = 0;
5303# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005304 curwin->w_set_curswant = TRUE;
5305 }
5306 check_cursor();
5307
5308# ifdef FEAT_MBYTE
5309 /* Make sure the cursor is on the first byte of a multi-byte char. */
5310 if (has_mbyte)
5311 mb_adjust_cursor();
5312# endif
5313}
5314#endif